Merge mozilla-central into Places.
authorShawn Wilsher <me@shawnwilsher.com>
Tue, 07 Dec 2010 15:06:32 -0800
changeset 59383 ca7bfd15abfd47e4d4fdb541ed1a5abe349ffb80
parent 59382 f0110c8264c8d12112628b188be75df9aefa27a9 (current diff)
parent 58800 d2f3fcf3b1db251d1e5863ed2b8bb3d3fb15bfcf (diff)
child 59384 e88c33f1fc0bc4a88f19b5a9ea8c0d5e4bdecf24
push id1
push usershaver@mozilla.com
push dateTue, 04 Jan 2011 17:58:04 +0000
milestone2.0b8pre
Merge mozilla-central into Places.
browser/base/content/browser.js
content/base/public/nsContentUtils.h
content/base/src/nsContentUtils.cpp
extensions/access-builtin/Makefile.in
extensions/access-builtin/README
extensions/access-builtin/accessproxy/Makefile.in
extensions/access-builtin/accessproxy/nsAccessProxy.cpp
extensions/access-builtin/accessproxy/nsAccessProxy.h
extensions/access-builtin/accessproxy/nsAccessProxyRegistration.cpp
extensions/access-builtin/accessproxy/nsIAccessProxy.idl
extensions/access-builtin/makefiles.sh
extensions/metrics/Makefile.in
extensions/metrics/build/Makefile.in
extensions/metrics/build/nsMetricsModule.cpp
extensions/metrics/content/prefs.xul
extensions/metrics/install.rdf
extensions/metrics/jar.mn
extensions/metrics/locale/en-US/prefs.dtd
extensions/metrics/makefiles.sh
extensions/metrics/metrics.js
extensions/metrics/public/Makefile.in
extensions/metrics/public/nsIMetricsCollector.idl
extensions/metrics/public/nsIMetricsService.idl
extensions/metrics/public/nsMetricsModule.h
extensions/metrics/skin/prefs.css
extensions/metrics/src/Makefile.in
extensions/metrics/src/nsAutoCompleteCollector.cpp
extensions/metrics/src/nsAutoCompleteCollector.h
extensions/metrics/src/nsLoadCollector.cpp
extensions/metrics/src/nsLoadCollector.h
extensions/metrics/src/nsMetricsConfig.cpp
extensions/metrics/src/nsMetricsConfig.h
extensions/metrics/src/nsMetricsEventItem.cpp
extensions/metrics/src/nsMetricsEventItem.h
extensions/metrics/src/nsMetricsService.cpp
extensions/metrics/src/nsMetricsService.h
extensions/metrics/src/nsProfileCollector.cpp
extensions/metrics/src/nsProfileCollector.h
extensions/metrics/src/nsPtrHashKey.h
extensions/metrics/src/nsStringUtils.cpp
extensions/metrics/src/nsStringUtils.h
extensions/metrics/src/nsUICommandCollector.cpp
extensions/metrics/src/nsUICommandCollector.h
extensions/metrics/src/nsWindowCollector.cpp
extensions/metrics/src/nsWindowCollector.h
extensions/metrics/src/nssstubs.c
extensions/metrics/test/Makefile.in
extensions/metrics/test/TestCommon.h
extensions/metrics/test/TestMetricsConfig.cpp
extensions/metrics/test/TestUICommandCollector.cpp
extensions/metrics/test/data/test_config.xml
extensions/metrics/test/unit/head_content.js
extensions/metrics/test/unit/test_event_item.js
services/sync/tests/unit/test_bookmark_predecessor.js
--- a/browser/base/content/browser-tabPreviews.js
+++ b/browser/base/content/browser-tabPreviews.js
@@ -559,16 +559,24 @@ var ctrlTab = {
     tabContainer[toggleEventListener]("TabClose", this, false);
 
     document[toggleEventListener]("keypress", this, false);
     gBrowser.mTabBox.handleCtrlTab = !enable;
 
     // If we're not running, hide the "Show All Tabs" menu item,
     // as Shift+Ctrl+Tab will be handled by the tab bar.
     document.getElementById("menu_showAllTabs").hidden = !enable;
+
+    // Also disable the <key> to ensure Shift+Ctrl+Tab never triggers
+    // Show All Tabs.
+    var key_showAllTabs = document.getElementById("key_showAllTabs");
+    if (enable)
+      key_showAllTabs.removeAttribute("disabled");
+    else
+      key_showAllTabs.setAttribute("disabled", "true");
   }
 };
 
 
 /**
  * All Tabs panel
  */
 var allTabs = {
@@ -623,22 +631,23 @@ var allTabs = {
     this._initiated = false;
   },
 
   prefName: "browser.allTabs.previews",
   readPref: function allTabs_readPref() {
     var allTabsButton = document.getElementById("alltabs-button");
     if (!allTabsButton)
       return;
-    if (gPrefService.getBoolPref(this.prefName)) {
-      allTabsButton.removeAttribute("type");
+
+    if (gPrefService.getBoolPref(this.prefName)) {
+      allTabsButton.removeAttribute("type");
       allTabsButton.setAttribute("command", "Browser:ShowAllTabs");
-    } else {
-      allTabsButton.setAttribute("type", "menu");
-      allTabsButton.removeAttribute("command");
+    } else {
+      allTabsButton.setAttribute("type", "menu");
+      allTabsButton.removeAttribute("command");
       allTabsButton.removeAttribute("oncommand");
     }
   },
   observe: function (aSubject, aTopic, aPrefName) {
     this.readPref();
   },
 
   pick: function allTabs_pick(aPreview) {
--- a/browser/base/content/browser.css
+++ b/browser/base/content/browser.css
@@ -95,16 +95,20 @@ toolbar[printpreview="true"] {
   -moz-binding: url("chrome://global/content/bindings/general.xml#windowdragbox");
 }
 %endif
 
 toolbarpaletteitem[place="palette"] > toolbaritem > hbox[type="places"] {
   display: none;
 }
 
+#main-window[disablechrome] #navigator-toolbox[tabsontop="true"] > toolbar:not(#toolbar-menubar):not(#TabsToolbar) {
+  visibility: collapse;
+}
+
 #wrapper-urlbar-container #urlbar-container > #urlbar > toolbarbutton,
 #urlbar-container:not([combined]) > #urlbar > toolbarbutton,
 #urlbar-container[combined] + #reload-button + #stop-button,
 #urlbar-container[combined] + #reload-button,
 toolbar:not([mode="icons"]) > #urlbar-container > #urlbar > toolbarbutton,
 toolbar[mode="icons"] > #urlbar-container > #urlbar > #urlbar-reload-button:not([displaystop]) + #urlbar-stop-button,
 toolbar[mode="icons"] > #urlbar-container > #urlbar > #urlbar-reload-button[displaystop],
 toolbar[mode="icons"] > #reload-button:not([displaystop]) + #stop-button,
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -3894,16 +3894,17 @@ var XULBrowserWindow = {
   // Stored Status, Link and Loading values
   status: "",
   defaultStatus: "",
   jsStatus: "",
   jsDefaultStatus: "",
   startTime: 0,
   statusText: "",
   isBusy: false,
+  inContentWhitelist: ["about:addons"],
 
   QueryInterface: function (aIID) {
     if (aIID.equals(Ci.nsIWebProgressListener) ||
         aIID.equals(Ci.nsIWebProgressListener2) ||
         aIID.equals(Ci.nsISupportsWeakReference) ||
         aIID.equals(Ci.nsIXULBrowserWindow) ||
         aIID.equals(Ci.nsISupports))
       return this;
@@ -4132,16 +4133,26 @@ var XULBrowserWindow = {
             document.getElementById("aHTMLTooltip").hidePopup();
             document.tooltipNode = null;
             break;
           }
         }
       }
     }
 
+    // Show or hide browser chrome based on the whitelist
+    var disableChrome = this.inContentWhitelist.some(function(aSpec) {
+      return aSpec == location;
+    });
+
+    if (disableChrome)
+      document.documentElement.setAttribute("disablechrome", "true");
+    else
+      document.documentElement.removeAttribute("disablechrome");
+
     // This code here does not compare uris exactly when determining
     // whether or not the message should be hidden since the message
     // may be prematurely hidden when an install is invoked by a click
     // on a link that looks like this:
     //
     // <a href="#" onclick="return install();">Install Foo</a>
     //
     // - which fires a onLocationChange message to uri + '#'...
@@ -7287,17 +7298,17 @@ var gIdentityHandler = {
     var urlString = value + "\n" + content.document.title;
     var htmlString = "<a href=\"" + value + "\">" + value + "</a>";
 
     var dt = event.dataTransfer;
     dt.setData("text/x-moz-url", urlString);
     dt.setData("text/uri-list", value);
     dt.setData("text/plain", value);
     dt.setData("text/html", htmlString);
-    dt.setDragImage(event.currentTarget, 0, 0);
+    dt.addElement(event.currentTarget);
   }
 };
 
 let DownloadMonitorPanel = {
   //////////////////////////////////////////////////////////////////////////////
   //// DownloadMonitorPanel Member Variables
 
   _panel: null,
--- a/browser/base/content/test/Makefile.in
+++ b/browser/base/content/test/Makefile.in
@@ -161,16 +161,17 @@ endif
                  browser_bug595507.js \
                  browser_bug596687.js \
                  browser_bug597218.js \
                  browser_bug598923.js \
                  browser_bug599325.js \
                  browser_bug609700.js \
                  browser_contextSearchTabPosition.js \
                  browser_ctrlTab.js \
+                 browser_disablechrome.js \
                  browser_discovery.js \
                  browser_duplicateIDs.js \
                  browser_gestureSupport.js \
                  browser_getshortcutoruri.js \
                  browser_hide_removing.js \
                  browser_inspector_initialization.js \
                  browser_inspector_treeSelection.js \
                  browser_inspector_highlighter.js \
@@ -202,16 +203,17 @@ endif
                  browser_tabs_owner.js \
                  browser_visibleFindSelection.js \
                  browser_visibleTabs.js \
                  browser_visibleTabs_contextMenu.js \
                  browser_visibleTabs_bookmarkAllPages.js \
                  browser_visibleTabs_bookmarkAllTabs.js \
                  browser_visibleTabs_tabPreview.js \
                  bug592338.html \
+                 disablechrome.html \
                  discovery.html \
                  domplate_test.js \
                  moz.png \
                  test_bug435035.html \
                  test_bug462673.html \
                  page_style_sample.html \
                  feed_tab.html \
                  plugin_unknown.html \
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/browser_disablechrome.js
@@ -0,0 +1,141 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+// Tests that the disablechrome attribute gets propogated to the main UI
+
+const HTTPSRC = "http://example.com/browser/browser/base/content/test/";
+
+function is_element_hidden(aElement) {
+  var style = window.getComputedStyle(document.getElementById("nav-bar"), "");
+  if (style.visibility != "visible" || style.display == "none")
+    return true;
+
+  if (aElement.ownerDocument != aElement.parentNode)
+    return is_element_hidden(aElement.parentNode);
+
+  return false;
+}
+
+function is_chrome_hidden() {
+  is(document.documentElement.getAttribute("disablechrome"), "true", "Attribute should be set");
+  if (TabsOnTop.enabled)
+    ok(is_element_hidden(document.getElementById("nav-bar")), "Toolbar should be hidden");
+  else
+    ok(!is_element_hidden(document.getElementById("nav-bar")), "Toolbar should not be hidden");
+}
+
+function is_chrome_visible() {
+  isnot(document.getElementById("main-window").getAttribute("disablechrome"), "true", "Attribute should not be set");
+  ok(!is_element_hidden(document.getElementById("nav-bar")), "Toolbar should not be hidden");
+}
+
+function load_page(aURL, aCallback) {
+  gNewBrowser.addEventListener("pageshow", function() {
+    // Filter out about:blank loads
+    if (gNewBrowser.currentURI.spec != aURL)
+      return;
+
+    gNewBrowser.removeEventListener("pageshow", arguments.callee, false);
+    executeSoon(aCallback);
+  }, false);
+  gNewBrowser.loadURI(aURL);
+}
+
+var gOldTab;
+var gNewTab;
+var gNewBrowser;
+
+function test() {
+  var gOldTabsOnTop = TabsOnTop.enabled;
+  registerCleanupFunction(function() {
+    TabsOnTop.enabled = gOldTabsOnTop;
+  });
+
+  waitForExplicitFinish();
+
+  gOldTab = gBrowser.selectedTab;
+  gNewTab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
+  gNewBrowser = gBrowser.selectedBrowser;
+
+  info("Tabs on top");
+  TabsOnTop.enabled = true;
+
+  run_http_test_1();
+}
+
+function end_test() {
+  gBrowser.removeTab(gNewTab);
+  finish();
+}
+
+function test_url(aURL, aCanHide, aNextTest) {
+  is_chrome_visible();
+
+  info("Page load");
+  load_page(aURL, function() {
+    if (aCanHide)
+      is_chrome_hidden();
+    else
+      is_chrome_visible();
+
+    info("Switch away");
+    gBrowser.selectedTab = gOldTab;
+    is_chrome_visible();
+
+    info("Switch back");
+    gBrowser.selectedTab = gNewTab;
+    if (aCanHide)
+      is_chrome_hidden();
+    else
+      is_chrome_visible();
+
+    gBrowser.removeTab(gNewTab);
+    gNewTab = gBrowser.selectedTab = gBrowser.addTab("about:blank");
+    gNewBrowser = gBrowser.selectedBrowser;
+
+    gBrowser.selectedTab = gOldTab;
+
+    info("Background load");
+    load_page(aURL, function() {
+      is_chrome_visible();
+
+      info("Switch back");
+      gBrowser.selectedTab = gNewTab;
+      if (aCanHide)
+        is_chrome_hidden();
+      else
+        is_chrome_visible();
+
+      load_page("about:blank", aNextTest);
+    });
+  });
+}
+
+// Should never hide the chrome
+function run_http_test_1() {
+  info("HTTP tests");
+  test_url(HTTPSRC + "disablechrome.html", false, run_chrome_about_test);
+}
+
+// Should hide the chrome
+function run_chrome_about_test() {
+  info("Chrome about: tests");
+  test_url("about:addons", true, function() {
+    info("Tabs on bottom");
+    TabsOnTop.enabled = false;
+    run_http_test_2();
+  });
+}
+
+// Should never hide the chrome
+function run_http_test_2() {
+  info("HTTP tests");
+  test_url(HTTPSRC + "disablechrome.html", false, run_chrome_about_test_2);
+}
+
+// Should not hide the chrome
+function run_chrome_about_test_2() {
+  info("Chrome about: tests");
+  test_url("about:addons", true, end_test);
+}
--- a/browser/base/content/test/browser_overflowScroll.js
+++ b/browser/base/content/test/browser_overflowScroll.js
@@ -10,16 +10,17 @@ function right(ele)          rect(ele).r
 function isLeft(ele, msg)    is(left(ele), left(scrollbox), msg);
 function isRight(ele, msg)   is(right(ele), right(scrollbox), msg);
 function elementFromPoint(x) tabstrip._elementFromPoint(x);
 function nextLeftElement()   elementFromPoint(left(scrollbox) - 1);
 function nextRightElement()  elementFromPoint(right(scrollbox) + 1);
 function firstScrollable()   tabs[gBrowser._numPinnedTabs];
 
 function test() {
+  requestLongerTimeout(2);
   waitForExplicitFinish();
 
   // If the previous (or more) test finished with cleaning up the tabs,
   // there may be some pending animations. That can cause a failure of
   // this tests, so, we should test this in another stack.
   setTimeout(doTest, 0);
 }
 
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/disablechrome.html
@@ -0,0 +1,4 @@
+<html>
+<body>
+</body>
+</html>
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -988,20 +988,20 @@
           ]]>
         </body>
       </method>
 
     </implementation>
   </binding>
 
   <binding id="geolocation-notification" extends="chrome://global/content/bindings/notification.xml#popup-notification">
-    <content>
+    <content align="start">
       <xul:image class="popup-notification-icon"
                  xbl:inherits="popupid"/>
-      <xul:vbox>
+      <xul:vbox flex="1">
         <xul:description class="popup-notification-description"
                          xbl:inherits="xbl:text=label"/>
         <xul:spacer flex="1"/>
         <xul:hbox pack="end">
           <xul:label anonid="learnmore" class="text-link geolocation-text-link"/>
           <xul:spacer flex="1"/>
           <xul:button anonid="button"
                       class="popup-notification-menubutton"
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle.js
+++ b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle.js
@@ -42,16 +42,17 @@ function test() {
   // initialization
   gPrefService.setBoolPref("browser.privatebrowsing.keep_current_session", true);
   let pb = Cc["@mozilla.org/privatebrowsing;1"].
            getService(Ci.nsIPrivateBrowsingService);
 
   const testPageURL = "http://mochi.test:8888/browser/" +
     "browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle_page.html";
   waitForExplicitFinish();
+  requestLongerTimeout(2);
 
   // initialization of expected titles
   let test_title = "Test title";
   let app_name = document.documentElement.getAttribute("title");
   const isOSX = ("nsILocalFileMac" in Ci);
   let page_with_title;
   let page_without_title;
   let about_pb_title;
--- a/browser/components/sessionstore/src/nsSessionStore.js
+++ b/browser/components/sessionstore/src/nsSessionStore.js
@@ -1454,16 +1454,25 @@ SessionStoreService.prototype = {
       return tabData;
     else if (browser.__SS_data && browser.__SS_data._tabStillLoading) {
       // use the data to be restored when the tab hasn't been completely loaded
       tabData = browser.__SS_data;
       if (aTab.pinned)
         tabData.pinned = true;
       else
         delete tabData.pinned;
+      tabData.hidden = aTab.hidden;
+
+      // If __SS_extdata is set then we'll use that since it might be newer.
+      if (aTab.__SS_extdata)
+        tabData.extData = aTab.__SS_extdata;
+      // If it exists but is empty then a key was likely deleted. In that case just
+      // delete extData.
+      if (tabData.extData && !Object.keys(tabData.extData).length)
+        delete tabData.extData;
       return tabData;
     }
     
     var history = null;
     try {
       history = browser.sessionHistory;
     }
     catch (ex) { } // this could happen if we catch a tab during (de)initialization
--- a/browser/components/sessionstore/test/browser/Makefile.in
+++ b/browser/components/sessionstore/test/browser/Makefile.in
@@ -118,16 +118,17 @@ include $(topsrcdir)/config/rules.mk
 	browser_579879.js \
 	browser_580512.js \
 	browser_581593.js \
 	browser_586147.js \
 	browser_586068-cascaded_restore.js \
 	browser_589246.js \
 	browser_590268.js \
 	browser_600545.js \
+	browser_607016.js \
 	$(NULL)
 
 ifneq ($(OS_ARCH),Darwin)
 _BROWSER_TEST_FILES += \
 	browser_597071.js \
 	$(NULL)
 endif
 
new file mode 100644
--- /dev/null
+++ b/browser/components/sessionstore/test/browser/browser_607016.js
@@ -0,0 +1,156 @@
+/* ***** 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 sessionstore test code.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ * Paul O’Shannessy <paul@oshannessy.com>
+ *
+ * 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 ***** */
+
+const TAB_STATE_NEEDS_RESTORE = 1;
+const TAB_STATE_RESTORING = 2;
+
+Cu.import("resource://gre/modules/Services.jsm");
+let ss = Cc["@mozilla.org/browser/sessionstore;1"].
+         getService(Ci.nsISessionStore);
+
+let stateBackup = ss.getBrowserState();
+
+function cleanup() {
+  // Reset the pref
+  try {
+    Services.prefs.clearUserPref("browser.sessionstore.max_concurrent_tabs");
+  } catch (e) {}
+  ss.setBrowserState(stateBackup);
+  executeSoon(finish);
+}
+
+function test() {
+  /** Bug 607016 - If a tab is never restored, attributes (eg. hidden) aren't updated correctly **/
+  waitForExplicitFinish();
+
+  // Set the pref to 0 so we know exactly how many tabs should be restoring at
+  // any given time. This guarantees that a finishing load won't start another.
+  Services.prefs.setIntPref("browser.sessionstore.max_concurrent_tabs", 0);
+
+  // We have our own progress listener for this test, which we'll attach before our state is set
+  let progressListener = {
+    onStateChange: function (aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) {
+      if (aBrowser.__SS_restoreState == TAB_STATE_RESTORING &&
+          aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
+          aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK &&
+          aStateFlags & Ci.nsIWebProgressListener.STATE_IS_WINDOW)
+        progressCallback(aBrowser);
+    }
+  }
+
+  let state = { windows: [{ tabs: [
+    { entries: [{ url: "http://example.org#1" }], extData: { "uniq": r() } },
+    { entries: [{ url: "http://example.org#2" }], extData: { "uniq": r() } }, // overwriting
+    { entries: [{ url: "http://example.org#3" }], extData: { "uniq": r() } }, // hiding
+    { entries: [{ url: "http://example.org#4" }], extData: { "uniq": r() } }, // adding
+    { entries: [{ url: "http://example.org#5" }], extData: { "uniq": r() } }, // deleting
+    { entries: [{ url: "http://example.org#6" }] } // creating
+  ], selected: 1 }] };
+
+  function progressCallback(aBrowser) {
+    // We'll remove the progress listener after the first one because we aren't
+    // loading any other tabs
+    window.gBrowser.removeTabsProgressListener(progressListener);
+
+    let curState = JSON.parse(ss.getBrowserState());
+    for (let i = 0; i < curState.windows[0].tabs.length; i++) {
+      if (state.windows[0].tabs[i].extData) {
+        is(curState.windows[0].tabs[i].extData["uniq"],
+           state.windows[0].tabs[i].extData["uniq"],
+           "sanity check that tab has correct extData");
+      }
+      else
+        ok(!("extData" in curState.windows[0].tabs[i]),
+           "sanity check that tab doesn't have extData");
+    }
+
+    // Now we'll set a new unique value on 1 of the tabs
+    let newUniq = r();
+    ss.setTabValue(gBrowser.tabs[1], "uniq", newUniq);
+    gBrowser.removeTab(gBrowser.tabs[1]);
+    let closedTabData = (JSON.parse(ss.getClosedTabData(window)))[0];
+    is(closedTabData.state.extData.uniq, newUniq,
+       "(overwriting) new data is stored in extData");
+
+    // hide the next tab before closing it
+    gBrowser.hideTab(gBrowser.tabs[1]);
+    gBrowser.removeTab(gBrowser.tabs[1]);
+    closedTabData = (JSON.parse(ss.getClosedTabData(window)))[0];
+    ok(closedTabData.state.hidden, "(hiding) tab data has hidden == true");
+
+    // set data that's not in a conflicting key
+    let stillUniq = r();
+    ss.setTabValue(gBrowser.tabs[1], "stillUniq", stillUniq);
+    gBrowser.removeTab(gBrowser.tabs[1]);
+    closedTabData = (JSON.parse(ss.getClosedTabData(window)))[0];
+    is(closedTabData.state.extData.stillUniq, stillUniq,
+       "(adding) new data is stored in extData");
+
+    // remove the uniq value and make sure it's not there in the closed data
+    ss.deleteTabValue(gBrowser.tabs[1], "uniq");
+    gBrowser.removeTab(gBrowser.tabs[1]);
+    closedTabData = (JSON.parse(ss.getClosedTabData(window)))[0];
+    // Since Panorama might have put data in, first check if there is extData.
+    // If there is explicitly check that "uniq" isn't in it. Otherwise, we're ok
+    if ("extData" in closedTabData.state) {
+      ok(!("uniq" in closedTabData.state.extData),
+         "(deleting) uniq not in existing extData");
+    }
+    else {
+      ok(true, "(deleting) no data is stored in extData");
+    }
+
+    // set unique data on the tab that never had any set, make sure that's saved
+    let newUniq2 = r();
+    ss.setTabValue(gBrowser.tabs[1], "uniq", newUniq2);
+    gBrowser.removeTab(gBrowser.tabs[1]);
+    closedTabData = (JSON.parse(ss.getClosedTabData(window)))[0];
+    is(closedTabData.state.extData.uniq, newUniq2,
+       "(creating) new data is stored in extData where there was none");
+
+    cleanup();
+  }
+
+  window.gBrowser.addTabsProgressListener(progressListener);
+  ss.setBrowserState(JSON.stringify(state));
+}
+
+// Helper function to create a random value
+function r() {
+  return "" + Date.now() + Math.random();
+}
+
--- a/browser/installer/windows/nsis/installer.nsi
+++ b/browser/installer/windows/nsis/installer.nsi
@@ -223,16 +223,18 @@ Section "-InstallStartCleanup"
     Sleep 5000
     ${DeleteFile} "$INSTDIR\${FileMainEXE}"
     ClearErrors
   ${EndIf}
 
   ; Remove the updates directory for Vista and above
   ${CleanUpdatesDir} "Mozilla\Firefox"
 
+  ${RemoveDeprecatedFiles}
+
   ${InstallStartCleanupCommon}
 SectionEnd
 
 Section "-Application" APP_IDX
   ${StartUninstallLog}
 
   SetDetailsPrint both
   DetailPrint $(STATUS_INSTALL_APP)
--- a/browser/installer/windows/nsis/shared.nsh
+++ b/browser/installer/windows/nsis/shared.nsh
@@ -86,20 +86,17 @@
 
   ; Win7 taskbar and start menu link maintenance
   ${UpdateShortcutAppModelIDs} "$INSTDIR\${FileMainEXE}" "${AppUserModelID}" $0
 
   ; Remove files that may be left behind by the application in the
   ; VirtualStore directory.
   ${CleanVirtualStore}
 
-  ; Remove talkback if it is present (remove after bug 386760 is fixed)
-  ${If} ${FileExists} "$INSTDIR\extensions\talkback@mozilla.org\"
-    RmDir /r "$INSTDIR\extensions\talkback@mozilla.org\"
-  ${EndIf}
+  ${RemoveDeprecatedFiles}
 !macroend
 !define PostUpdate "!insertmacro PostUpdate"
 
 !macro SetAsDefaultAppGlobal
   ${RemoveDeprecatedKeys}
 
   SetShellVarContext all      ; Set SHCTX to all users (e.g. HKLM)
   ${SetHandlers}
@@ -500,16 +497,126 @@
   StrCpy $0 "Software\Microsoft\Windows\Shell\Associations\UrlAssociations\gopher"
   ReadRegStr $2 HKCU "$0\UserChoice" "Progid"
   ${If} "$2" == "FirefoxURL"
     DeleteRegKey HKCU "$0"
   ${EndIf}
 !macroend
 !define RemoveDeprecatedKeys "!insertmacro RemoveDeprecatedKeys"
 
+; Removes various directories and files for reasons noted below.
+!macro RemoveDeprecatedFiles
+  ; Remove talkback if it is present (remove after bug 386760 is fixed)
+  ${If} ${FileExists} "$INSTDIR\extensions\talkback@mozilla.org\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\talkback@mozilla.org\"
+  ${EndIf}
+
+  ; Remove the Java Console extension (bug 597235)
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0012-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0012-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0013-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0013-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0014-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0014-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0015-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0015-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0016-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0016-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0017-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0017-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0018-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0018-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0019-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0019-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0020-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0020-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0021-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0021-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0022-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0015-0000-0022-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0000-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0000-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0001-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0001-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0002-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0002-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0003-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0003-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0004-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0004-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0005-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0005-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0006-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0006-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0007-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0007-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0010-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0010-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0011-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0011-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0012-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0012-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0013-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0013-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0014-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0014-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0015-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0015-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0016-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0016-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0017-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0017-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0018-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0018-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0019-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0019-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0020-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0020-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0021-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0021-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0023-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0016-0000-0023-ABCDEFFEDCBA}\"
+  ${EndIf}
+  ${If} ${FileExists} "$INSTDIR\extensions\{CAFEEFAC-0017-0000-0000-ABCDEFFEDCBA}\"
+    RmDir /r /REBOOTOK "$INSTDIR\extensions\{CAFEEFAC-0017-0000-0000-ABCDEFFEDCBA}\"
+  ${EndIf}
+!macroend
+!define RemoveDeprecatedFiles "!insertmacro RemoveDeprecatedFiles"
+
 ; Creates the shortcuts log ini file with the appropriate entries if it doesn't
 ; already exist.
 !macro CreateShortcutsLog
   ${GetShortcutsLogPath} $0
   ${Unless} ${FileExists} "$0"
     ; Default to ${BrandFullName} for the Start Menu Folder
     StrCpy $TmpVal "${BrandFullName}"
     ; Prior to Firefox 3.1 the Start Menu directory was written to the registry and
--- a/browser/locales/shipped-locales
+++ b/browser/locales/shipped-locales
@@ -38,16 +38,17 @@ ja-JP-mac osx
 kn
 ko
 ku
 lg
 lt
 lv
 mk
 ml
+mr
 nb-NO
 nl
 nn-NO
 nso
 or
 pa-IN
 pl
 pt-BR
--- a/browser/themes/gnomestripe/browser/browser.css
+++ b/browser/themes/gnomestripe/browser/browser.css
@@ -1705,17 +1705,18 @@ toolbar[mode="text"] toolbarbutton.chevr
 }
 
 .allTabs-preview-label {
   -moz-transform: translate(0, 2px);
 }
 
 /* Application menu toolbar button */
 
-#appmenu-toolbar-button > .toolbarbutton-text {
+#appmenu-toolbar-button > .toolbarbutton-text,
+#appmenu-toolbar-button > .toolbarbutton-menu-dropmarker {
   margin-top: -2px !important;
   margin-bottom: -2px !important;
 }
 #appmenuSecondaryPane {
   -moz-border-start: 1px solid ThreeDShadow;
 }
 #appmenuSecondaryPane-spacer {
   min-height: 1em;
index 87d2405a394e38c4a6e9b21638beae47bf0a63ae..78f36581631f5a7ad49eac9fae3f029e914c7c49
GIT binary patch
literal 2115
zc$@)42)y@+P)<h;3K|Lk000e1NJLTq002+`000mO1^@s6fl2tm00009a7bBm000ic
z000ic0Tn1pfB*mh2XskIMF-jp0}eG0kR&B5000N#Nkl<ZSi{YjYfzNe8OJv>O~23?
zKh)7g+j?2<E5dRUqd`j*QCMz5%%~d*%SBXNAZ()50J|uHnYaiuCRGy3=um<Z45g?6
z#UP+Vi?oe{Q@66nRS;OYEsDf{&-2Q=F3YaM#1A<$|Jn1N^E`*$-+9jSoEL$>OtXDI
z#@RdTbj`*SXW<n0v0CtoR#Q_0Q&m@2V`OCHfM6Caz((+9fbAPr?9)mj6j*tPgjNd{
zF8qGM!nbNYoNRt2p>bQ%8&<6Urr_t^ocA2mI!5fhxjgg(l~|qz0{SX|lao&|`SgVv
z8yj)y(xo5U+S}si`u9IdPH5V(Q#wXcB<*dUtzTznr&O;W$Kc=~r-6Y1^!N9pudffi
zeZA=J?nZNSlho9&X!QmMrVJ*{EJd~s0t?Z%L?lbX68~`F@(}5-MbXIwaNWzk_|>ad
zIcQIxP8d{IR|mabkBb*CKDm4MZp6#{6<ZxjnLw(j_#4{p--ouf6<Td8+S=N<F@BzG
zEv-{jRD?&59-+6l7rhT2aKO5{y3o<lf&1<4xOeX!$i~#~>?)s(R#oN@N=q>tkuCXH
z1nBt31cJ82K^m`SeI4u1<LAu5q~l7^Zr*6%H1XsyE?>S(@HkQb6#$VFDMIFUdngnN
zNTt$gN=r-U=Dv(|<RHEbpiZabBJW}ULl$*?9LS#T9&~heavNd}V4=r)&9mZS{9C2M
zw{dZts83^-#>vOx4`O)_o_{(9*CZu@45G0WF(0bEQq_=r{x#e`K057KRaI4CV&Vy&
zJRUdb*|Q(f&33;{tHrHbw_XX56z^|?z%@d%qB(h>9rtN&jgpcQUxG8p08$jv5vJoy
z5PNzapsTZs0n~B;&!0c<YwY`#o401Nun-rbqQJLnN+p^P9pXfNzL5>tl8?n7#Ez}j
zU6BbEfo0sYEU94SuKidlc|V&S?O2v0ryXmGFp9c{`g%@x?%cs#3X9S4L`vv$#ci=h
zte-Vvn4&icA@da?YNOC%1lBh+gkGz;is9j5jOoWPIy#Esp<z6th#aI`_>h6@Ms4ji
zR90RLHTFH_vPLtJmxo(PNvJt^&;X12rq5(Uw&Y_GAS)oCJV=ljtb)yXMX=kkD|hM`
z%ctfHg{7jR0*}Y_7#kVk^mu$6b15t@;MsFZW(xND&5RAGs`?IpR?21oY;5}1raPL}
z_RgMOFp!*WWo0EwO3oqw%X}O^ejKTvd;+<AA4@TfEUi?xpE*;!gZDq_<fR!ud>EvE
z#Kz)EN(xLHjnN!$M?MyFAd5WMyeA__ph#p#79RVvAeN`<oMIIOv%uJg9SMxF9j~pe
z<#hY@ZOo;xaPXKu3~@kmussrk>>*jT`1vLf{K@B{4WOKAx&a4Mm0xJPAENp8UF7EG
zAtxsXSy@>~O-)52i<pRr2m}NKz|+$cXU`Pl``S9h#KfKD{ZBZ0Xj;6z!K>WG1*IV&
z26)t`F=HF@F$<8vOQWj`gTz5(&sr)b3})JtW?X6V^Ybyvj?T!?5U266F&GNV%^RF3
zM_MW@3J#t<l7dNgkO$d8;<=dH1X_cSU~?N_ZDae3zhAymeZRXOwe^k2JbDzVX=zAI
zOhlAShOn?O`1$$aUGH~cYi9?gG6RLhe?eCEr?tZ6!e7!FpV^5umf%@}NIo;*`S|<K
zbBvVZ<f&5xPG=n!DWA>#ORZL8WO!&AK)$e0ZscWLSWE$O;7F`cBuH%G&j8XU&>DOM
zo7({Ibv|z8mER4VDf${Yd7s1A*B5`-umQjK@!_<7{d#z_AME9|8cUZgMYJpyrRC?D
zZQg*Zi<>L0k!`(F)57e^#bT6(hQ5Ht`liohL$>5I4MJo>f^*=uZO!kbp8ypMmIv3(
z_5yq0zyTPmkX0$Zu-srdiI?#;haeaOq^R3B1#eG)Ew;EXLV0;P^lUT6^)p3t<hyFs
z>acIiD^OS8fMcJjv2(|E$f7=gbmw-w7aoT2ty>YwqQ`%WAJ(o}jpSqnXG=b=Vz+Qw
z<M1+(=D!U5DUrwk>znX!RInpYqCVfqhHS~l0AQCw;hdS1qf5`u#y@}f0a0>!+E0C(
z;S0;S{)On77tI?3OfbN+LHrgQY<63ObLY-+sevy}#-cg$b#ZZtA|Nd-Eprn2h{a+V
zt&#pad(Hm>15vqlE%MnhB~hQoERB<o0bb7O)4J^3T>SOI1>_eOYhTCfAYWMOSWz+P
z`gKk;PV>e93EXaff@h6go2{|Q^=(jY9bo`R&4}i>JFAnE>;n7V6!8hW<B)c`2EjQU
zDE?0ma;vYvFHs8nfFQWa)JSD_*nNBVaJFS-WnjM1w8o*uHk!6=+b|cA5BKGx6BBj2
zQ&I}{?%!W_y{QSw>FMiU2S7t%F_Jj|JV1gL=O;uAyYtb#Z==gw;BqVF)!~_<Ir5!9
zf4+xABKeBxn~>n3>bAa7yi6e>!PSAxmR02f^5s&{+siX<L`Dyd9y^BFh-}G+`|{HG
z_$BoD>B*DLDN3bU@S2)wVKD{412BCT<`w$RZ*k<v5e&1pifL<1iRPx<={0i^(=sLx
zM@NSgSLYR~6(W(!d8M<;)zw|)=H{+)cN41|MWPh4nX+9p<tzAT!BPjN3?|JiMYhxb
tnZS;+j%nWO0%%%T%;~4DA@~`z{{!2OzG!jLq6Yu~002ovPDHLkV1gnV6fOV&
--- a/browser/themes/winstripe/browser/browser-aero.css
+++ b/browser/themes/winstripe/browser/browser-aero.css
@@ -2,73 +2,65 @@
 %include browser.css
 %undef WINSTRIPE_AERO
 
 %define customToolbarColor hsl(214,44%,87%)
 %define glassToolbarBorderColor rgba(10%,10%,10%,.4)
 %define glassActiveBorderColor rgb(37, 44, 51)
 %define glassInactiveBorderColor rgb(102, 102, 102)
 
-@media all and (-moz-windows-default-theme) {
-  #navigator-toolbox > toolbar:not(:-moz-lwtheme) {
-    background-color: @customToolbarColor@;
-  }
-
-  .tabbrowser-tab[selected="true"]:not(:-moz-lwtheme) {
-    background-image: -moz-linear-gradient(white, @toolbarHighlight@ 30%),
-                      -moz-linear-gradient(@customToolbarColor@, @customToolbarColor@);
-  }
-
-  /* App menu button */
-
+@media not all and (-moz-windows-classic) {
   #main-window[sizemode="normal"] > #titlebar > #titlebar-content > #appmenu-button-container {
     margin-top: 1px;
   }
 
   #appmenu-button {
-    border: 2px solid;
-    border-top: none;
+    border-width: 2px;
     -moz-border-left-colors: rgba(255,255,255,.5) rgba(83,42,6,.9);
     -moz-border-bottom-colors: rgba(255,255,255,.5) rgba(83,42,6,.9);
     -moz-border-right-colors: rgba(255,255,255,.5) rgba(83,42,6,.9);
-    margin-bottom: -1px; /* compensate white outer border */
+    margin-bottom: 1px; /* compensate white outer border */
     box-shadow: 0 1px 0 rgba(255,255,255,.25) inset,
                 0 0 2px 1px rgba(255,255,255,.25) inset;
   }
 
   #main-window[privatebrowsingmode=temporary] #appmenu-button {
     -moz-border-left-colors: rgba(255,255,255,.5) rgba(43,8,65,.9);
     -moz-border-bottom-colors: rgba(255,255,255,.5) rgba(43,8,65,.9);
     -moz-border-right-colors: rgba(255,255,255,.5) rgba(43,8,65,.9);
   }
 
   #appmenu-popup {
     margin-top: -1px;
     -moz-margin-start: 1px;
   }
+}
+
+@media all and (-moz-windows-default-theme) {
+  #navigator-toolbox > toolbar:not(:-moz-lwtheme) {
+    background-color: @customToolbarColor@;
+  }
+
+  .tabbrowser-tab[selected="true"]:not(:-moz-lwtheme) {
+    background-image: -moz-linear-gradient(white, @toolbarHighlight@ 30%),
+                      -moz-linear-gradient(@customToolbarColor@, @customToolbarColor@);
+  }
 
   #sidebar-splitter {
     border: 0;
     -moz-border-end: 1px solid #A9B7C9;
     min-width: 0;
     width: 3px;
     background-color: transparent;
     -moz-margin-start: -3px;
     position: relative;
     z-index: 10;
   }
 }
 
-@media not all and (-moz-windows-compositor) {
-  /* aero basic, which is a default windows theme */
-  #appmenu-button:-moz-system-metric(windows-theme-aero) {
-    margin-bottom: 1px;
-  }
-}
-
 @media all and (-moz-windows-compositor) {
   /* these should be hidden w/glass enabled. windows draws it's own buttons. */
   .titlebar-button {
     display: none;
   }
 
   #main-window[sizemode="maximized"] #titlebar-buttonbox {
     -moz-margin-end: 2px;
@@ -96,16 +88,20 @@
   #main-window[sizemode="normal"] > #titlebar > #titlebar-content > #appmenu-button-container:-moz-lwtheme {
     margin-top: -1px;
   }
 
   #main-window[sizemode="normal"] #titlebar-buttonbox:-moz-lwtheme {
     margin-top: -2px;
   }
 
+  #appmenu-button {
+    margin-bottom: -1px; /* compensate white outer border */
+  }
+
   #main-window:not(:-moz-lwtheme)[inFullscreen="true"] {
     -moz-appearance: none;
     background-color: #556;
   }
 
   #toolbar-menubar:not(:-moz-lwtheme),
   #TabsToolbar[tabsontop="true"]:not(:-moz-lwtheme),
   #navigator-toolbox[tabsontop="false"] > #nav-bar:not(:-moz-lwtheme),
--- a/browser/themes/winstripe/browser/browser.css
+++ b/browser/themes/winstripe/browser/browser.css
@@ -208,16 +208,17 @@
   #appmenu-popup {
     -moz-appearance: none;
     background: white;
     border: 1px solid ThreeDShadow;
   }
   #appmenuPrimaryPane {
     background-color: rgba(255,255,255,0.5);
     padding: 2px;
+    -moz-border-end: none;
   }
   #appmenuSecondaryPane {
     background-color: #f1f5fb;
     box-shadow: 1px 0 2px rgb(204,214,234) inset;
     -moz-padding-start: 3px;
     -moz-padding-end: 2px;
     padding-top: 2px;
     padding-bottom: 2px;
--- a/content/base/src/nsContentSink.cpp
+++ b/content/base/src/nsContentSink.cpp
@@ -847,25 +847,16 @@ nsContentSink::ProcessMETATag(nsIContent
     nsAutoString result;
     aContent->GetAttr(kNameSpaceID_None, nsGkAtoms::content, result);
     if (!result.IsEmpty()) {
       ToLowerCase(result);
       mDocument->SetHeaderData(nsGkAtoms::handheldFriendly, result);
     }
   }
 
-  /* Look for the viewport meta tag. If we find it, process it and put the
-   * data into the document header. */
-  if (aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::name,
-                            nsGkAtoms::viewport, eIgnoreCase)) {
-    nsAutoString value;
-    aContent->GetAttr(kNameSpaceID_None, nsGkAtoms::content, value);
-    rv = nsContentUtils::ProcessViewportInfo(mDocument, value);
-  }
-
   return rv;
 }
 
 
 void
 nsContentSink::PrefetchHref(const nsAString &aHref,
                             nsIContent *aSource,
                             PRBool aExplicit)
--- a/content/base/src/nsScriptLoader.cpp
+++ b/content/base/src/nsScriptLoader.cpp
@@ -555,23 +555,34 @@ nsScriptLoader::ProcessScriptElement(nsI
     }
     nsTArray<PreloadInfo>::index_type i =
       mPreloads.IndexOf(scriptURI.get(), 0, PreloadURIComparator());
     if (i != nsTArray<PreloadInfo>::NoIndex) {
       // preloaded
       // note that a script-inserted script can steal a preload!
       request = mPreloads[i].mRequest;
       request->mElement = aElement;
-      // XXX what if the charset attribute of the element and the charset
-      // of the preload don't match?
+      nsString preloadCharset(mPreloads[i].mCharset);
       mPreloads.RemoveElementAt(i);
-      rv = CheckContentPolicy(mDocument, aElement, request->mURI, type);
-      NS_ENSURE_SUCCESS(rv, rv);
-    } else {
-      // not preloaded
+
+      // Double-check that the charset the preload used is the same as
+      // the charset we have now.
+      nsAutoString elementCharset;
+      aElement->GetScriptCharset(elementCharset);
+      if (elementCharset.Equals(preloadCharset)) {
+        rv = CheckContentPolicy(mDocument, aElement, request->mURI, type);
+        NS_ENSURE_SUCCESS(rv, rv);
+      } else {
+        // Drop the preload
+        request = nsnull;
+      }
+    }
+
+    if (!request) {
+      // no usable preload
       request = new nsScriptLoadRequest(aElement, version);
       NS_ENSURE_TRUE(request, NS_ERROR_OUT_OF_MEMORY);
       request->mURI = scriptURI;
       request->mIsInline = PR_FALSE;
       request->mLoading = PR_TRUE;
       rv = StartLoad(request, type);
       NS_ENSURE_SUCCESS(rv, rv);
     }
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -420,16 +420,19 @@ include $(topsrcdir)/config/rules.mk
 		test_x-frame-options.html \
 		file_x-frame-options_main.html \
 		file_x-frame-options_page.sjs \
 		test_createHTMLDocument.html \
 		test_bug564047.html \
 		test_bug567350.html \
 		test_bug574596.html \
 		test_bug578096.html \
+		test_bug597345.html \
+		script-1_bug597345.sjs \
+		script-2_bug597345.js \
 		test_bug598877.html \
 		test_bug599588.html \
 		test_bug600466.html \
 		test_bug600468.html \
 		test_bug600471.html \
 		test_bug601803.html \
 		file_bug601803a.html \
 		file_bug601803b.html \
--- a/content/base/test/chrome/file_bug549682.xul
+++ b/content/base/test/chrome/file_bug549682.xul
@@ -7,27 +7,29 @@ https://bugzilla.mozilla.org/show_bug.cg
 -->
 <window title="Mozilla Bug 549682"
   xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
   onload="run()">
   <label value="Mozilla Bug 549682"/>
   <!-- test code goes here -->
   <script type="application/javascript"><![CDATA[
   var didRunAsync = false;
+  var didRunLocal = false;
   var global = Components.classes["@mozilla.org/globalmessagemanager;1"].getService(Components.interfaces.nsIChromeFrameMessageManager);
   var globalListenerCallCount = 0;
   function globalListener(m) {
     ++globalListenerCallCount;
     if (m.name == "sync") {
       global.removeMessageListener("async", globalListener);
       global.removeMessageListener("sync", globalListener);
       global.removeMessageListener("global-sync", globalListener);
       // Note, the result depends on what other windows are open.
       opener.wrappedJSObject.ok(globalListenerCallCount >= 4,
                                 "Global listener should have been called at least 4 times!");
+      opener.wrappedJSObject.ok(didRunLocal, "Local message received.");
 
       opener.setTimeout("done()", 0);
       var i = document.getElementById("ifr");
       i.parentNode.removeChild(i); // This is a crash test!
       window.close();
     }
   }
 
@@ -38,22 +40,32 @@ https://bugzilla.mozilla.org/show_bug.cg
   }
 
   function syncL(m) {
     opener.wrappedJSObject.is(m.name, "sync", "Wrong message!");
     opener.wrappedJSObject.is(m.json.data, 1234, "Wrong data!");
     opener.wrappedJSObject.ok(didRunAsync, "Should have run async!");
   }
 
+  function localL(m) {
+    opener.wrappedJSObject.is(m.name, "lasync", "Wrong message!");
+    opener.wrappedJSObject.is(m.json.data, 2345, "Wrong data!");
+    didRunLocal = true;
+  }
+
   function loadScript() {
     // Async should be processed first!
     messageManager.loadFrameScript("data:,sendAsyncMessage('async', { data: 1234 }); sendSyncMessage('sync', { data: 1234 });", false);
   }
 
   function run() {
+    var localmm = document.getElementById('ifr').messageManager;
+    localmm.addMessageListener("lasync", localL);
+    localmm.loadFrameScript("data:,sendAsyncMessage('lasync', { data: 2345 })", false);
+
     messageManager.addMessageListener("async", asyncL);
     messageManager.addMessageListener("sync", syncL);
     global.addMessageListener("async", globalListener);
     global.addMessageListener("sync", globalListener);
     global.addMessageListener("global-sync", globalListener);
     global.loadFrameScript("data:,sendSyncMessage('global-sync', { data: 1234 });", true);
 
     var oldValue = globalListenerCallCount;
new file mode 100644
--- /dev/null
+++ b/content/base/test/script-1_bug597345.sjs
@@ -0,0 +1,13 @@
+function handleRequest(request, response)
+{
+  response.setHeader("Cache-Control", "no-cache", false);
+  response.setHeader("Content-Type", "text/javascript", false);
+  // The "stray" open comment at the end of the write is important!
+  response.write("document.write(\"<script charset='utf-8' src='script-2_bug597345.js'></script><!--\")");
+  response.processAsync();
+  var timer = Components.classes["@mozilla.org/timer;1"]
+    .createInstance(Components.interfaces.nsITimer);
+  timer.initWithCallback(function() {
+      response.finish();
+    }, 200, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
+}
new file mode 100644
--- /dev/null
+++ b/content/base/test/script-2_bug597345.js
@@ -0,0 +1,1 @@
+document.write("Räksmörgås");
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_bug597345.html
@@ -0,0 +1,28 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=597345
+-->
+<head>
+  <title>Test for Bug 597345</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=597345">Mozilla Bug 597345</a>
+<pre id="test">
+  <!-- We want no spaces inside span id="target".  The 'stray' close comment at
+       the end of that span needs to be there! -->
+  <span id="target"><script
+    src="script-1_bug597345.sjs"></script><script
+    charset="ISO-5559-1" src="script-2_bug597345.js"></script>--></span>
+<script type="application/javascript">
+
+/** Test for Bug 597345 **/
+is($("target").textContent, "R\u00e4ksm\u00f6rg\u00e5s",
+   "script-2 should be decoded as UTF-8");
+</script>
+</pre>
+</body>
+</html>
--- a/content/canvas/src/CustomQS_WebGL.h
+++ b/content/canvas/src/CustomQS_WebGL.h
@@ -106,38 +106,44 @@ nsIDOMWebGLRenderingContext_BufferData(J
     int32 size;
     int32 usage;
 
     if (!JS_ValueToECMAInt32(cx, argv[0], &target))
         return JS_FALSE;
     if (!JS_ValueToECMAInt32(cx, argv[2], &usage))
         return JS_FALSE;
 
-    if (!JSVAL_IS_PRIMITIVE(argv[1])) {
+    JSBool nullobject = JSVAL_IS_NULL(argv[1]);
+
+    if (!nullobject) {
+        if (!JSVAL_IS_PRIMITIVE(argv[1])) {
 
-        JSObject *arg2 = JSVAL_TO_OBJECT(argv[1]);
-        if (js_IsArrayBuffer(arg2)) {
-            wb = js::ArrayBuffer::fromJSObject(arg2);
-        } else if (js_IsTypedArray(arg2)) {
-            wa = js::TypedArray::fromJSObject(arg2);
+            JSObject *arg2 = JSVAL_TO_OBJECT(argv[1]);
+            if (js_IsArrayBuffer(arg2)) {
+                wb = js::ArrayBuffer::fromJSObject(arg2);
+            } else if (js_IsTypedArray(arg2)) {
+                wa = js::TypedArray::fromJSObject(arg2);
+            }
         }
-    }
 
-    if (!wa && !wb &&
-        !JS_ValueToECMAInt32(cx, argv[1], &size))
-    {
-        return JS_FALSE;
+        if (!wa && !wb &&
+            !JS_ValueToECMAInt32(cx, argv[1], &size))
+        {
+            return JS_FALSE;
+        }
     }
 
     nsresult rv;
 
     if (wa)
         rv = self->BufferData_array(target, wa, usage);
     else if (wb)
         rv = self->BufferData_buf(target, wb, usage);
+    else if (nullobject)
+        rv = self->BufferData_null();
     else
         rv = self->BufferData_size(target, size, usage);
 
     if (NS_FAILED(rv))
         return xpc_qsThrowMethodFailed(cx, rv, vp);
 
     *vp = JSVAL_VOID;
     return JS_TRUE;
@@ -177,32 +183,38 @@ nsIDOMWebGLRenderingContext_BufferSubDat
     if (!JS_ValueToECMAInt32(cx, argv[1], &offset))
         return JS_FALSE;
 
     if (!JSVAL_IS_OBJECT(argv[2])) {
         xpc_qsThrowBadArg(cx, NS_ERROR_FAILURE, vp, 2);
         return JS_FALSE;
     }
 
-    JSObject *arg3 = JSVAL_TO_OBJECT(argv[2]);
-    if (js_IsArrayBuffer(arg3)) {
-        wb = js::ArrayBuffer::fromJSObject(arg3);
-    } else if (js_IsTypedArray(arg3)) {
-        wa = js::TypedArray::fromJSObject(arg3);
-    } else {
-        xpc_qsThrowBadArg(cx, NS_ERROR_FAILURE, vp, 2);
-        return JS_FALSE;
+    JSBool nullobject = JSVAL_IS_NULL(argv[2]);
+
+    if (!nullobject) {
+        JSObject *arg3 = JSVAL_TO_OBJECT(argv[2]);
+        if (js_IsArrayBuffer(arg3)) {
+            wb = js::ArrayBuffer::fromJSObject(arg3);
+        } else if (js_IsTypedArray(arg3)) {
+            wa = js::TypedArray::fromJSObject(arg3);
+        } else {
+            xpc_qsThrowBadArg(cx, NS_ERROR_FAILURE, vp, 2);
+            return JS_FALSE;
+        }
     }
 
     nsresult rv;
 
     if (wa) {
         rv = self->BufferSubData_array(target, offset, wa);
     } else if (wb) {
         rv = self->BufferSubData_buf(target, offset, wb);
+    } else if (nullobject) {
+        rv = self->BufferSubData_null();
     } else {
         xpc_qsThrowBadArg(cx, NS_ERROR_FAILURE, vp, 2);
         return JS_FALSE;
     }
 
     if (NS_FAILED(rv))
         return xpc_qsThrowMethodFailed(cx, rv, vp);
 
--- a/content/canvas/src/WebGLContext.cpp
+++ b/content/canvas/src/WebGLContext.cpp
@@ -94,16 +94,17 @@ WebGLContext::WebGLContext()
     mResetLayer = PR_TRUE;
     mVerbose = PR_FALSE;
     mOptionsFrozen = PR_FALSE;
 
     mActiveTexture = 0;
     mSynthesizedGLError = LOCAL_GL_NO_ERROR;
     mPixelStoreFlipY = PR_FALSE;
     mPixelStorePremultiplyAlpha = PR_FALSE;
+    mPixelStoreColorspaceConversion = BROWSER_DEFAULT_WEBGL;
 
     mShaderValidation = PR_TRUE;
 
     mMapBuffers.Init();
     mMapTextures.Init();
     mMapPrograms.Init();
     mMapShaders.Init();
     mMapFramebuffers.Init();
--- a/content/canvas/src/WebGLContext.h
+++ b/content/canvas/src/WebGLContext.h
@@ -417,19 +417,20 @@ protected:
     PRInt32 mGLMaxVaryingVectors;
     PRInt32 mGLMaxFragmentUniformVectors;
     PRInt32 mGLMaxVertexUniformVectors;
 
     PRBool SafeToCreateCanvas3DContext(nsHTMLCanvasElement *canvasElement);
     PRBool InitAndValidateGL();
     PRBool ValidateBuffers(PRUint32 count);
     PRBool ValidateCapabilityEnum(WebGLenum cap, const char *info);
-    PRBool ValidateBlendEquationEnum(WebGLuint cap, const char *info);
-    PRBool ValidateBlendFuncDstEnum(WebGLuint mode, const char *info);
-    PRBool ValidateBlendFuncSrcEnum(WebGLuint mode, const char *info);
+    PRBool ValidateBlendEquationEnum(WebGLenum cap, const char *info);
+    PRBool ValidateBlendFuncDstEnum(WebGLenum mode, const char *info);
+    PRBool ValidateBlendFuncSrcEnum(WebGLenum mode, const char *info);
+    PRBool ValidateBlendFuncEnumsCompatibility(WebGLenum sfactor, WebGLenum dfactor, const char *info);
     PRBool ValidateTextureTargetEnum(WebGLenum target, const char *info);
     PRBool ValidateComparisonEnum(WebGLenum target, const char *info);
     PRBool ValidateStencilOpEnum(WebGLenum action, const char *info);
     PRBool ValidateFaceEnum(WebGLenum face, const char *info);
     PRBool ValidateBufferUsageEnum(WebGLenum target, const char *info);
     PRBool ValidateTexFormatAndType(WebGLenum format, WebGLenum type,
                                       PRUint32 *texelSize, const char *info);
     PRBool ValidateDrawModeEnum(WebGLenum mode, const char *info);
@@ -520,27 +521,30 @@ protected:
     nsRefPtrHashtable<nsUint32HashKey, WebGLTexture> mMapTextures;
     nsRefPtrHashtable<nsUint32HashKey, WebGLBuffer> mMapBuffers;
     nsRefPtrHashtable<nsUint32HashKey, WebGLProgram> mMapPrograms;
     nsRefPtrHashtable<nsUint32HashKey, WebGLShader> mMapShaders;
     nsRefPtrHashtable<nsUint32HashKey, WebGLFramebuffer> mMapFramebuffers;
     nsRefPtrHashtable<nsUint32HashKey, WebGLRenderbuffer> mMapRenderbuffers;
 
     // PixelStore parameters
-    PRUint32 mPixelStorePackAlignment, mPixelStoreUnpackAlignment;
+    PRUint32 mPixelStorePackAlignment, mPixelStoreUnpackAlignment, mPixelStoreColorspaceConversion;
     PRBool mPixelStoreFlipY, mPixelStorePremultiplyAlpha;
 
     FakeBlackStatus mFakeBlackStatus;
 
     WebGLuint mBlackTexture2D, mBlackTextureCubeMap;
     PRBool mBlackTexturesAreInitialized;
 
     WebGLfloat mVertexAttrib0Vector[4];
     nsAutoArrayPtr<WebGLfloat> mFakeVertexAttrib0Array;
 
+    WebGLint mStencilRef;
+    WebGLuint mStencilValueMask, mStencilWriteMask;
+
 public:
     // console logging helpers
     static void LogMessage(const char *fmt, ...);
     static void LogMessage(const char *fmt, va_list ap);
     void LogMessageIfVerbose(const char *fmt, ...);
     void LogMessageIfVerbose(const char *fmt, va_list ap);
 
     friend class WebGLTexture;
@@ -745,17 +749,18 @@ public:
         mMinFilter(LOCAL_GL_NEAREST_MIPMAP_LINEAR),
         mMagFilter(LOCAL_GL_LINEAR),
         mWrapS(LOCAL_GL_REPEAT),
         mWrapT(LOCAL_GL_REPEAT),
         mFacesCount(0),
         mMaxLevelWithCustomImages(0),
         mHaveGeneratedMipmap(PR_FALSE),
         mFakeBlackStatus(DoNotNeedFakeBlack)
-    {}
+    {
+    }
 
     void Delete() {
         if (mDeleted)
             return;
         ZeroOwners();
         mDeleted = PR_TRUE;
     }
 
@@ -794,29 +799,33 @@ protected:
             return is_pot_assuming_nonnegative(mWidth) &&
                    is_pot_assuming_nonnegative(mHeight); // negative sizes should never happen (caught in texImage2D...)
         }
         WebGLsizei mWidth, mHeight;
         WebGLenum mFormat, mType;
         PRBool mIsDefined;
     };
 
+public:
+
     ImageInfo& ImageInfoAt(size_t level, size_t face) {
 #ifdef DEBUG
         if (face >= mFacesCount)
             NS_ERROR("wrong face index, must be 0 for TEXTURE_2D and at most 5 for cube maps");
 #endif
         // no need to check level as a wrong value would be caught by ElementAt().
         return mImageInfos.ElementAt(level * mFacesCount + face);
     }
 
     const ImageInfo& ImageInfoAt(size_t level, size_t face) const {
         return const_cast<WebGLTexture*>(this)->ImageInfoAt(level, face);
     }
 
+protected:
+
     WebGLenum mTarget;
     WebGLenum mMinFilter, mMagFilter, mWrapS, mWrapT;
 
     size_t mFacesCount, mMaxLevelWithCustomImages;
     nsTArray<ImageInfo> mImageInfos;
 
     PRBool mHaveGeneratedMipmap;
     FakeBlackStatus mFakeBlackStatus;
@@ -1023,42 +1032,27 @@ public:
         // handle this case first, it's the generic case
         if (mFakeBlackStatus == DoNotNeedFakeBlack)
             return PR_FALSE;
 
         if (mFakeBlackStatus == DontKnowIfNeedFakeBlack) {
             // Determine if the texture needs to be faked as a black texture.
             // See 3.8.2 Shader Execution in the OpenGL ES 2.0.24 spec.
 
-            // First detect undefined images. These are typically not-yet-loaded textures.
-            // The generic fake-black-texture messages have been confusing in this case, see bug 594310.
-            // So generate a special message for that.
-
-            PRBool areAllLevel0ImagesDefined = PR_TRUE;
             for (size_t face = 0; face < mFacesCount; ++face) {
-                    areAllLevel0ImagesDefined &= ImageInfoAt(0, face).mIsDefined;
+                if (!ImageInfoAt(0, face).mIsDefined) {
+                    // In case of undefined texture image, we don't print any message because this is a very common
+                    // and often legitimate case, for example when doing asynchronous texture loading.
+                    // An extreme case of this is the photowall google demo.
+                    // Exiting early here allows us to avoid making noise on valid webgl code.
+                    mFakeBlackStatus = DoNeedFakeBlack;
+                    return PR_TRUE;
+                }
             }
 
-            if (!areAllLevel0ImagesDefined) {
-                if (mTarget == LOCAL_GL_TEXTURE_2D) {
-                    mContext->LogMessageIfVerbose(
-                        "We are currently drawing stuff, but some 2D texture has not yet been "
-                        "uploaded any image at level 0. Until it's uploaded, this texture will look black.");
-                } else {
-                    mContext->LogMessageIfVerbose(
-                        "We are currently drawing stuff, but some cube map texture has not yet been "
-                        "uploaded any image at level 0, for at least one of its six faces. "
-                        "Until it's uploaded, this texture will look black.");
-                }
-                mFakeBlackStatus = DoNeedFakeBlack;
-                return PR_TRUE;
-            }
-
-            // ok, done with the stupid special cases above. Now actually implementing the cases defined in section 3.8.2.
-
             const char *msg_rendering_as_black
                 = "A texture is going to be rendered as if it were black, as per the OpenGL ES 2.0.24 spec section 3.8.2, "
                   "because it";
 
             if (mTarget == LOCAL_GL_TEXTURE_2D)
             {
                 if (DoesMinFilterRequireMipmap())
                 {
@@ -1347,47 +1341,118 @@ protected:
     PRBool mDeleted;
     PRBool mInitialized;
 
     friend class WebGLFramebuffer;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(WebGLRenderbuffer, WEBGLRENDERBUFFER_PRIVATE_IID)
 
+class WebGLFramebufferAttachment
+{
+    nsRefPtr<WebGLTexture> mTexturePtr;
+    nsRefPtr<WebGLRenderbuffer> mRenderbufferPtr;
+    WebGLenum mAttachmentPoint;
+
+public:
+    WebGLFramebufferAttachment(WebGLenum aAttachmentPoint)
+        : mAttachmentPoint(aAttachmentPoint)
+    {}
+
+    PRBool IsNull() const {
+        return !mTexturePtr && !mRenderbufferPtr;
+    }
+
+    PRBool HasAlpha() const {
+        WebGLenum format = 0;
+        if (mTexturePtr)
+            format = mTexturePtr->ImageInfoAt(0,0).mFormat;
+        if (mRenderbufferPtr)
+            format = mRenderbufferPtr->InternalFormat();
+        return format == LOCAL_GL_RGBA ||
+               format == LOCAL_GL_LUMINANCE_ALPHA ||
+               format == LOCAL_GL_ALPHA ||
+               format == LOCAL_GL_RGBA4 ||
+               format == LOCAL_GL_RGB5_A1;
+    }
+
+    void SetTexture(WebGLTexture *tex) {
+        mTexturePtr = tex;
+        mRenderbufferPtr = nsnull;
+    }
+    void SetRenderbuffer(WebGLRenderbuffer *rb) {
+        mTexturePtr = nsnull;
+        mRenderbufferPtr = rb;
+    }
+    WebGLTexture *Texture() const {
+        return mTexturePtr.get();
+    }
+    WebGLRenderbuffer *Renderbuffer() const {
+        return mRenderbufferPtr.get();
+    }
+
+    PRBool IsIncompatibleWithAttachmentPoint() const
+    {
+        // textures can only be color textures in WebGL
+        if (mTexturePtr)
+            return mAttachmentPoint != LOCAL_GL_COLOR_ATTACHMENT0;
+
+        if (mRenderbufferPtr) {
+            WebGLenum format = mRenderbufferPtr->InternalFormat();
+            switch (mAttachmentPoint) {
+                case LOCAL_GL_COLOR_ATTACHMENT0:
+                    return format != LOCAL_GL_RGB565 &&
+                           format != LOCAL_GL_RGB5_A1 &&
+                           format != LOCAL_GL_RGBA4;
+                case LOCAL_GL_DEPTH_ATTACHMENT:
+                    return format != LOCAL_GL_DEPTH_COMPONENT16;
+                case LOCAL_GL_STENCIL_ATTACHMENT:
+                    return format != LOCAL_GL_STENCIL_INDEX8;
+                case LOCAL_GL_DEPTH_STENCIL_ATTACHMENT:
+                    return format != LOCAL_GL_DEPTH_STENCIL;
+            }
+        }
+
+        return PR_FALSE; // no attachment at all, so no incompatibility
+    }
+
+    PRBool HasUninitializedRenderbuffer() const {
+        return mRenderbufferPtr && !mRenderbufferPtr->Initialized();
+    }
+};
+
 #define WEBGLFRAMEBUFFER_PRIVATE_IID \
     {0x0052a16f, 0x4bc9, 0x4a55, {0x9d, 0xa3, 0x54, 0x95, 0xaa, 0x4e, 0x80, 0xb9}}
 class WebGLFramebuffer :
     public nsIWebGLFramebuffer,
     public WebGLZeroingObject,
     public WebGLRectangleObject,
     public WebGLContextBoundObject
 {
 public:
     NS_DECLARE_STATIC_IID_ACCESSOR(WEBGLFRAMEBUFFER_PRIVATE_IID)
 
     WebGLFramebuffer(WebGLContext *context, WebGLuint name) :
         WebGLContextBoundObject(context),
         mName(name), mDeleted(PR_FALSE),
-        mColorAttachment0HasAlpha(PR_FALSE),
-        mHasDepthAttachment(PR_FALSE),
-        mHasStencilAttachment(PR_FALSE),
-        mHasDepthStencilAttachment(PR_FALSE)
+        mColorAttachment(LOCAL_GL_COLOR_ATTACHMENT0),
+        mDepthAttachment(LOCAL_GL_DEPTH_ATTACHMENT),
+        mStencilAttachment(LOCAL_GL_STENCIL_ATTACHMENT),
+        mDepthStencilAttachment(LOCAL_GL_DEPTH_STENCIL_ATTACHMENT)
     { }
 
     void Delete() {
         if (mDeleted)
             return;
         ZeroOwners();
         mDeleted = PR_TRUE;
     }
     PRBool Deleted() { return mDeleted; }
     WebGLuint GLName() { return mName; }
 
-    PRBool ColorAttachment0HasAlpha() { return mColorAttachment0HasAlpha; }
-
     nsresult FramebufferRenderbuffer(WebGLenum target,
                                      WebGLenum attachment,
                                      WebGLenum rbtarget,
                                      nsIWebGLRenderbuffer *rbobj)
     {
         WebGLuint renderbuffername;
         PRBool isNull;
         WebGLRenderbuffer *wrb;
@@ -1399,69 +1464,36 @@ public:
         }
 
         if (target != LOCAL_GL_FRAMEBUFFER)
             return mContext->ErrorInvalidEnumInfo("framebufferRenderbuffer: target", target);
 
         if (rbtarget != LOCAL_GL_RENDERBUFFER)
             return mContext->ErrorInvalidEnumInfo("framebufferRenderbuffer: renderbuffer target:", rbtarget);
 
-        const char *badAttachmentFormatMsg =
-            "framebufferRenderbuffer: this renderbuffer does not have a suitable format for this attachment point";
-
         switch (attachment) {
         case LOCAL_GL_DEPTH_ATTACHMENT:
-            if (!isNull) {
-                if (wrb->mInternalFormat != LOCAL_GL_DEPTH_COMPONENT16)
-                    return mContext->ErrorInvalidOperation(badAttachmentFormatMsg);
-            }
-            mDepthOrStencilRenderbufferAttachment = wrb;
-            mHasDepthAttachment = !isNull;
+            mDepthAttachment.SetRenderbuffer(wrb);
             break;
         case LOCAL_GL_STENCIL_ATTACHMENT:
-            if (!isNull) {
-                if (wrb->mInternalFormat != LOCAL_GL_STENCIL_INDEX8)
-                    return mContext->ErrorInvalidOperation(badAttachmentFormatMsg);
-            }
-            mDepthOrStencilRenderbufferAttachment = wrb;
-            mHasStencilAttachment = !isNull;
+            mStencilAttachment.SetRenderbuffer(wrb);
             break;
         case LOCAL_GL_DEPTH_STENCIL_ATTACHMENT:
-            if (!isNull) {
-                if (wrb->mInternalFormat != LOCAL_GL_DEPTH_STENCIL)
-                    return mContext->ErrorInvalidOperation(badAttachmentFormatMsg);
-            }
-            mDepthOrStencilRenderbufferAttachment = wrb;
-            mHasDepthStencilAttachment = !isNull;
+            mDepthStencilAttachment.SetRenderbuffer(wrb);
             break;
         default:
             // finish checking that the 'attachment' parameter is among the allowed values
-            if ((attachment < LOCAL_GL_COLOR_ATTACHMENT0 ||
-                 attachment >= LOCAL_GL_COLOR_ATTACHMENT0 + mContext->mMaxFramebufferColorAttachments))
-            {
+            if (attachment != LOCAL_GL_COLOR_ATTACHMENT0)
                 return mContext->ErrorInvalidEnumInfo("framebufferRenderbuffer: attachment", attachment);
-            }
             if (!isNull) {
-                if (wrb->mInternalFormat != LOCAL_GL_RGBA4 &&
-                    wrb->mInternalFormat != LOCAL_GL_RGB565 &&
-                    wrb->mInternalFormat != LOCAL_GL_RGB5_A1)
-                {
-                    return mContext->ErrorInvalidOperation(badAttachmentFormatMsg);
-                }
-
                 // ReadPixels needs alpha and size information, but only
                 // for COLOR_ATTACHMENT0
-                if (attachment == LOCAL_GL_COLOR_ATTACHMENT0) {
-                    setDimensions(wrb);
-                    mColorAttachment0HasAlpha = InternalFormatHasAlpha(wrb->mInternalFormat);
-                } else {
-                    mColorAttachment0HasAlpha = PR_FALSE;
-                }
+                setDimensions(wrb);
             }
-            mColorRenderbufferAttachment = wrb;
+            mColorAttachment.SetRenderbuffer(wrb);
             break;
         }
 
         mContext->MakeContextCurrent();
         mContext->gl->fFramebufferRenderbuffer(target, attachment, rbtarget, renderbuffername);
 
         return NS_OK;
     }
@@ -1490,104 +1522,100 @@ public:
             textarget > LOCAL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z))
             return mContext->ErrorInvalidEnumInfo("framebufferTexture2D: invalid texture target", textarget);
 
         if (!isNull && level > 0)
             return mContext->ErrorInvalidValue("framebufferTexture2D: level must be 0");
 
         switch (attachment) {
         case LOCAL_GL_DEPTH_ATTACHMENT:
+            mDepthAttachment.SetTexture(wtex);
+            break;
         case LOCAL_GL_STENCIL_ATTACHMENT:
+            mStencilAttachment.SetTexture(wtex);
+            break;
         case LOCAL_GL_DEPTH_STENCIL_ATTACHMENT:
-            return mContext->ErrorInvalidOperation("framebufferTexture2D: depth and stencil attachments can "
-                          "only be renderbuffers, not textures, as there is no suitable texture format.");
+            mDepthStencilAttachment.SetTexture(wtex);
             break;
         default:
-            if ((attachment < LOCAL_GL_COLOR_ATTACHMENT0 ||
-                 attachment >= LOCAL_GL_COLOR_ATTACHMENT0 + mContext->mMaxFramebufferColorAttachments))
-            {
+            if (attachment != LOCAL_GL_COLOR_ATTACHMENT0)
                 return mContext->ErrorInvalidEnumInfo("framebufferTexture2D: attachment", attachment);
-            }
 
             // keep data for readPixels, function only uses COLOR_ATTACHMENT0
-            if (attachment == LOCAL_GL_COLOR_ATTACHMENT0) {
-                setDimensions(wtex);
+            setDimensions(wtex);
 
-                if (wtex) {
-                    const WebGLTexture::ImageInfo& ia = wtex->ImageInfoAt
-                        (level, textarget == LOCAL_GL_TEXTURE_2D
-                         ? 0
-                         : textarget - LOCAL_GL_TEXTURE_CUBE_MAP_POSITIVE_X);
-                    mColorAttachment0HasAlpha = InternalFormatHasAlpha(ia.mFormat);
-                } else {
-                    mColorAttachment0HasAlpha = PR_FALSE;
-                }
-            }
-
-            // nothing else to do for color buffers. all textures have a color-renderable format.
+            mColorAttachment.SetTexture(wtex);
             break;
         }
 
         mContext->MakeContextCurrent();
         mContext->gl->fFramebufferTexture2D(target, attachment, textarget, texturename, level);
 
         return NS_OK;
     }
 
-    // implement inline, as it's performance critical (called by draw-functions).
-    // the generic case for which we're optimizing is the case where there's nothing to initialize.
-    inline PRBool CheckAndInitializeRenderbuffers()
+    PRBool CheckAndInitializeRenderbuffers()
     {
-        if (HasConflictingAttachments()) {
+        if (HasBadAttachments()) {
             mContext->SynthesizeGLError(LOCAL_GL_INVALID_FRAMEBUFFER_OPERATION);
             return PR_FALSE;
         }
 
-        if ((mColorRenderbufferAttachment          && !mColorRenderbufferAttachment->Initialized()) ||
-            (mDepthOrStencilRenderbufferAttachment && !mDepthOrStencilRenderbufferAttachment->Initialized()))
+        if (mColorAttachment.HasUninitializedRenderbuffer() ||
+            mDepthAttachment.HasUninitializedRenderbuffer() ||
+            mStencilAttachment.HasUninitializedRenderbuffer() ||
+            mDepthStencilAttachment.HasUninitializedRenderbuffer())
         {
             InitializeRenderbuffers();
         }
 
         return PR_TRUE;
     }
 
+    PRBool HasBadAttachments() const {
+        if (mColorAttachment.IsIncompatibleWithAttachmentPoint() ||
+            mDepthAttachment.IsIncompatibleWithAttachmentPoint() ||
+            mStencilAttachment.IsIncompatibleWithAttachmentPoint() ||
+            mDepthStencilAttachment.IsIncompatibleWithAttachmentPoint())
+        {
+            // some attachment is incompatible with its attachment point
+            return PR_TRUE;
+        }
+        else if (int(mDepthAttachment.IsNull()) +
+                 int(mStencilAttachment.IsNull()) +
+                 int(mDepthStencilAttachment.IsNull()) <= 1)
+        {
+            // has at least two among Depth, Stencil, DepthStencil
+            return PR_TRUE;
+        }
+        else return PR_FALSE;
+    }
+
+    const WebGLFramebufferAttachment ColorAttachment() const {
+        return mColorAttachment;
+    }
+
     NS_DECL_ISUPPORTS
     NS_DECL_NSIWEBGLFRAMEBUFFER
 
-    PRBool HasConflictingAttachments() const {
-        return int(mHasDepthAttachment) +
-               int(mHasStencilAttachment) +
-               int(mHasDepthStencilAttachment) > 1;
-    }
-
-    static PRBool InternalFormatHasAlpha(WebGLenum aInternalFormat) {
-        return
-            aInternalFormat == LOCAL_GL_RGBA ||
-            aInternalFormat == LOCAL_GL_ALPHA ||
-            aInternalFormat == LOCAL_GL_RGBA4 ||
-            aInternalFormat == LOCAL_GL_RGB5_A1;
-    }
-
 protected:
 
     // protected because WebGLContext should only call InitializeRenderbuffers
     void InitializeRenderbuffers()
     {
         mContext->MakeContextCurrent();
 
         if (mContext->gl->fCheckFramebufferStatus(LOCAL_GL_FRAMEBUFFER) != LOCAL_GL_FRAMEBUFFER_COMPLETE)
             return;
 
-        PRBool initializeColorBuffer = mColorRenderbufferAttachment &&
-                                       !mColorRenderbufferAttachment->Initialized();
-        PRBool initializeDepthOrStencilBuffer = mDepthOrStencilRenderbufferAttachment &&
-                                                !mDepthOrStencilRenderbufferAttachment->Initialized();
-        PRBool initializeDepthBuffer = initializeDepthOrStencilBuffer && HasDepthBuffer();
-        PRBool initializeStencilBuffer = initializeDepthOrStencilBuffer && HasStencilBuffer();
+        PRBool initializeColorBuffer = mColorAttachment.HasUninitializedRenderbuffer();
+        PRBool initializeDepthBuffer = mDepthAttachment.HasUninitializedRenderbuffer() ||
+                                       mDepthStencilAttachment.HasUninitializedRenderbuffer();
+        PRBool initializeStencilBuffer = mStencilAttachment.HasUninitializedRenderbuffer() ||
+                                         mDepthStencilAttachment.HasUninitializedRenderbuffer();
 
         realGLboolean savedColorMask[] = {0}, savedDepthMask = 0;
         GLuint savedStencilMask = 0;
         GLfloat savedColorClearValue[] = {0.f}, savedDepthClearValue = 0.f;
         GLint savedStencilClearValue = 0;
         GLuint clearBits = 0;
 
         realGLboolean wasScissorTestEnabled = mContext->gl->fIsEnabled(LOCAL_GL_SCISSOR_TEST);
@@ -1629,66 +1657,60 @@ protected:
             mContext->gl->fColorMask(savedColorMask[0],
                                      savedColorMask[1],
                                      savedColorMask[2],
                                      savedColorMask[3]);
             mContext->gl->fClearColor(savedColorClearValue[0],
                                       savedColorClearValue[1],
                                       savedColorClearValue[2],
                                       savedColorClearValue[3]);
-            mColorRenderbufferAttachment->SetInitialized(PR_TRUE);
+            mColorAttachment.Renderbuffer()->SetInitialized(PR_TRUE);
         }
 
         if (initializeDepthBuffer) {
             mContext->gl->fDepthMask(savedDepthMask);
             mContext->gl->fClearDepth(savedDepthClearValue);
-            mDepthOrStencilRenderbufferAttachment->SetInitialized(PR_TRUE);
+            if (mDepthAttachment.Renderbuffer())
+                mDepthAttachment.Renderbuffer()->SetInitialized(PR_TRUE);
         }
 
         if (initializeStencilBuffer) {
             mContext->gl->fStencilMask(savedStencilMask);
             mContext->gl->fClearStencil(savedStencilClearValue);
-            mDepthOrStencilRenderbufferAttachment->SetInitialized(PR_TRUE);
+            if (mStencilAttachment.Renderbuffer())
+                mStencilAttachment.Renderbuffer()->SetInitialized(PR_TRUE);
+        }
+
+        if (initializeDepthBuffer && initializeStencilBuffer) {
+            if (mDepthStencilAttachment.Renderbuffer())
+                mDepthStencilAttachment.Renderbuffer()->SetInitialized(PR_TRUE);
         }
 
         mContext->gl->PopViewportRect();
 
         if (wasDitherEnabled)
             mContext->gl->fEnable(LOCAL_GL_DITHER);
         else
             mContext->gl->fDisable(LOCAL_GL_DITHER);
 
         if (wasScissorTestEnabled)
             mContext->gl->fEnable(LOCAL_GL_DITHER);
         else
             mContext->gl->fDisable(LOCAL_GL_SCISSOR_TEST);
     }
 
-    PRBool HasDepthBuffer() const {
-        return mHasDepthAttachment || mHasDepthStencilAttachment;
-    }
-
-    PRBool HasStencilBuffer() const {
-        return mHasStencilAttachment || mHasDepthStencilAttachment;
-    }
-
     WebGLuint mName;
     PRPackedBool mDeleted;
-    PRPackedBool mColorAttachment0HasAlpha;
 
     // we only store pointers to attached renderbuffers, not to attached textures, because
     // we will only need to initialize renderbuffers. Textures are already initialized.
-    nsRefPtr<WebGLRenderbuffer> mColorRenderbufferAttachment;
-    nsRefPtr<WebGLRenderbuffer> mDepthOrStencilRenderbufferAttachment;
-
-    // these boolean values keep track of all attachments: renderbuffers and textures.
-    // thus they are not at all redundant with the above member pointers.
-    PRBool mHasDepthAttachment;
-    PRBool mHasStencilAttachment;
-    PRBool mHasDepthStencilAttachment;
+    WebGLFramebufferAttachment mColorAttachment,
+                               mDepthAttachment,
+                               mStencilAttachment,
+                               mDepthStencilAttachment;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(WebGLFramebuffer, WEBGLFRAMEBUFFER_PRIVATE_IID)
 
 #define WEBGLUNIFORMLOCATION_PRIVATE_IID \
     {0x01a8a614, 0xb109, 0x42f1, {0xb4, 0x40, 0x8d, 0x8b, 0x87, 0x0b, 0x43, 0xa7}}
 class WebGLUniformLocation :
     public nsIWebGLUniformLocation,
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -319,45 +319,61 @@ NS_IMETHODIMP WebGLContext::BlendEquatio
 }
 
 NS_IMETHODIMP WebGLContext::BlendFunc(WebGLenum sfactor, WebGLenum dfactor)
 {
     if (!ValidateBlendFuncSrcEnum(sfactor, "blendFunc: sfactor") ||
         !ValidateBlendFuncDstEnum(dfactor, "blendFunc: dfactor"))
         return NS_OK;
 
+    if (!ValidateBlendFuncEnumsCompatibility(sfactor, dfactor, "blendFuncSeparate: srcRGB and dstRGB"))
+        return NS_OK;
+
     MakeContextCurrent();
     gl->fBlendFunc(sfactor, dfactor);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::BlendFuncSeparate(WebGLenum srcRGB, WebGLenum dstRGB,
                                 WebGLenum srcAlpha, WebGLenum dstAlpha)
 {
     if (!ValidateBlendFuncSrcEnum(srcRGB, "blendFuncSeparate: srcRGB") ||
         !ValidateBlendFuncSrcEnum(srcAlpha, "blendFuncSeparate: srcAlpha") ||
         !ValidateBlendFuncDstEnum(dstRGB, "blendFuncSeparate: dstRGB") ||
         !ValidateBlendFuncDstEnum(dstAlpha, "blendFuncSeparate: dstAlpha"))
         return NS_OK;
 
+    // note that we only check compatibity for the RGB enums, no need to for the Alpha enums, see
+    // "Section 6.8 forgetting to mention alpha factors?" thread on the public_webgl mailing list
+    if (!ValidateBlendFuncEnumsCompatibility(srcRGB, dstRGB, "blendFuncSeparate: srcRGB and dstRGB"))
+        return NS_OK;
+
     MakeContextCurrent();
     gl->fBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::BufferData(PRInt32 dummy)
 {
     // this should never be called
     LogMessageIfVerbose("BufferData");
     return NS_ERROR_FAILURE;
 }
 
 NS_IMETHODIMP
+WebGLContext::BufferData_null()
+{
+    // see http://www.khronos.org/bugzilla/show_bug.cgi?id=386
+    return ErrorInvalidValue("bufferData: null object passed");
+}
+
+
+NS_IMETHODIMP
 WebGLContext::BufferData_size(WebGLenum target, WebGLsizei size, WebGLenum usage)
 {
     WebGLBuffer *boundBuffer = NULL;
 
     if (target == LOCAL_GL_ARRAY_BUFFER) {
         boundBuffer = mBoundArrayBuffer;
     } else if (target == LOCAL_GL_ELEMENT_ARRAY_BUFFER) {
         boundBuffer = mBoundElementArrayBuffer;
@@ -444,16 +460,22 @@ WebGLContext::BufferData_array(WebGLenum
 
 NS_IMETHODIMP
 WebGLContext::BufferSubData(PRInt32 dummy)
 {
     return NS_ERROR_FAILURE;
 }
 
 NS_IMETHODIMP
+WebGLContext::BufferSubData_null()
+{
+    return NS_OK; // see http://www.khronos.org/bugzilla/show_bug.cgi?id=386
+}
+
+NS_IMETHODIMP
 WebGLContext::BufferSubData_buf(GLenum target, WebGLsizei byteOffset, js::ArrayBuffer *wb)
 {
     WebGLBuffer *boundBuffer = NULL;
 
     if (target == LOCAL_GL_ARRAY_BUFFER) {
         boundBuffer = mBoundArrayBuffer;
     } else if (target == LOCAL_GL_ELEMENT_ARRAY_BUFFER) {
         boundBuffer = mBoundElementArrayBuffer;
@@ -518,17 +540,17 @@ NS_IMETHODIMP
 WebGLContext::CheckFramebufferStatus(WebGLenum target, WebGLenum *retval)
 {
     *retval = 0;
 
     MakeContextCurrent();
     if (target != LOCAL_GL_FRAMEBUFFER)
         return ErrorInvalidEnum("checkFramebufferStatus: target must be FRAMEBUFFER");
 
-    if (mBoundFramebuffer && mBoundFramebuffer->HasConflictingAttachments())
+    if (mBoundFramebuffer && mBoundFramebuffer->HasBadAttachments())
         *retval = LOCAL_GL_FRAMEBUFFER_UNSUPPORTED;
     else
         *retval = gl->fCheckFramebufferStatus(target);
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -576,21 +598,22 @@ WebGLContext::CopyTexImage2D(WebGLenum t
         case LOCAL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
         case LOCAL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
         case LOCAL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
             break;
         default:
             return ErrorInvalidEnumInfo("copyTexImage2D: target", target);
     }
 
+
     switch (internalformat) {
         case LOCAL_GL_RGB:
+        case LOCAL_GL_LUMINANCE:
         case LOCAL_GL_RGBA:
         case LOCAL_GL_ALPHA:
-        case LOCAL_GL_LUMINANCE:
         case LOCAL_GL_LUMINANCE_ALPHA:
             break;
         default:
             return ErrorInvalidEnumInfo("CopyTexImage2D: internal format", internalformat);
     }
 
     if (border != 0)
         return ErrorInvalidValue("copyTexImage2D: border must be 0");
@@ -599,19 +622,32 @@ WebGLContext::CopyTexImage2D(WebGLenum t
         return ErrorInvalidValue("copyTexImage2D: level may not be negative");
 
     if (level >= 1) {
         if (!(is_pot_assuming_nonnegative(width) &&
               is_pot_assuming_nonnegative(height)))
             return ErrorInvalidValue("copyTexImage2D: with level > 0, width and height must be powers of two");
     }
 
+    PRBool texFormatRequiresAlpha = internalformat == LOCAL_GL_RGBA ||
+                                    internalformat == LOCAL_GL_ALPHA ||
+                                    internalformat == LOCAL_GL_LUMINANCE_ALPHA;
+    PRBool fboFormatHasAlpha = mBoundFramebuffer ? mBoundFramebuffer->ColorAttachment().HasAlpha()
+                                                 : PRBool(gl->ActualFormat().alpha > 0);
+    if (texFormatRequiresAlpha && !fboFormatHasAlpha)
+        return ErrorInvalidOperation("copyTexImage2D: texture format requires an alpha channel "
+                                     "but the framebuffer doesn't have one");
+
     if (!CanvasUtils::CheckSaneSubrectSize(x,y,width, height, mWidth, mHeight))
         return ErrorInvalidOperation("CopyTexImage2D: copied rectangle out of bounds");
 
+
+    if (mBoundFramebuffer && !mBoundFramebuffer->CheckAndInitializeRenderbuffers())
+        return NS_OK;
+
     WebGLTexture *tex = activeBoundTextureForTarget(target);
     if (!tex)
         return ErrorInvalidOperation("copyTexImage2D: no texture bound to this target");
 
     tex->SetImageInfo(target, level, width, height);
 
     MakeContextCurrent();
 
@@ -638,19 +674,37 @@ WebGLContext::CopyTexSubImage2D(WebGLenu
         case LOCAL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
         case LOCAL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
         case LOCAL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
             break;
         default:
             return ErrorInvalidEnumInfo("CopyTexSubImage2D: target", target);
     }
 
+    WebGLTexture *tex = activeBoundTextureForTarget(target);
+    if (!tex)
+        return ErrorInvalidOperation("copyTexSubImage2D: no texture bound to this target");
+
+    WebGLenum format = tex->ImageInfoAt(0,0).mFormat;
+    PRBool texFormatRequiresAlpha = format == LOCAL_GL_RGBA ||
+                                    format == LOCAL_GL_ALPHA ||
+                                    format == LOCAL_GL_LUMINANCE_ALPHA;
+    PRBool fboFormatHasAlpha = mBoundFramebuffer ? mBoundFramebuffer->ColorAttachment().HasAlpha()
+                                                 : PRBool(gl->ActualFormat().alpha > 0);
+
+    if (texFormatRequiresAlpha && !fboFormatHasAlpha)
+        return ErrorInvalidOperation("copyTexSubImage2D: texture format requires an alpha channel "
+                                     "but the framebuffer doesn't have one");
+
     if (!CanvasUtils::CheckSaneSubrectSize(x,y,width, height, mWidth, mHeight))
         return ErrorInvalidOperation("CopyTexSubImage2D: copied rectangle out of bounds");
 
+    if (mBoundFramebuffer && !mBoundFramebuffer->CheckAndInitializeRenderbuffers())
+        return NS_OK;
+
     MakeContextCurrent();
 
     gl->fCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
 
     return NS_OK;
 }
 
 
@@ -870,17 +924,26 @@ WebGLContext::DepthFunc(WebGLenum func)
 
     MakeContextCurrent();
     gl->fDepthFunc(func);
     return NS_OK;
 }
 
 GL_SAME_METHOD_1(DepthMask, DepthMask, WebGLboolean)
 
-GL_SAME_METHOD_2(DepthRange, DepthRange, WebGLfloat, WebGLfloat)
+NS_IMETHODIMP
+WebGLContext::DepthRange(WebGLfloat zNear, WebGLfloat zFar)
+{
+    if (zNear > zFar)
+        return ErrorInvalidOperation("depthRange: the near value is greater than the far value!");
+
+    MakeContextCurrent();
+    gl->fDepthRange(zNear, zFar);
+    return NS_OK;
+}
 
 NS_IMETHODIMP
 WebGLContext::DisableVertexAttribArray(WebGLuint index)
 {
     if (index > mAttribBuffers.Length())
         return ErrorInvalidValue("DisableVertexAttribArray: index out of range");
 
     MakeContextCurrent();
@@ -1463,24 +1526,25 @@ WebGLContext::GetParameter(PRUint32 pnam
         case LOCAL_GL_MAX_CUBE_MAP_TEXTURE_SIZE:
         case LOCAL_GL_SAMPLE_BUFFERS:
         case LOCAL_GL_SAMPLES:
         case LOCAL_GL_MAX_VERTEX_ATTRIBS:
         case LOCAL_GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
         case LOCAL_GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
         case LOCAL_GL_MAX_TEXTURE_IMAGE_UNITS:
         case LOCAL_GL_MAX_FRAGMENT_UNIFORM_COMPONENTS:
+        case LOCAL_GL_MAX_FRAGMENT_UNIFORM_VECTORS:
+        case LOCAL_GL_MAX_VERTEX_UNIFORM_VECTORS:
         case LOCAL_GL_MAX_RENDERBUFFER_SIZE:
         case LOCAL_GL_RED_BITS:
         case LOCAL_GL_GREEN_BITS:
         case LOCAL_GL_BLUE_BITS:
         case LOCAL_GL_ALPHA_BITS:
         case LOCAL_GL_DEPTH_BITS:
         case LOCAL_GL_STENCIL_BITS:
-        case UNPACK_COLORSPACE_CONVERSION_WEBGL:
         {
             GLint i = 0;
             gl->fGetIntegerv(pname, &i);
             wrval->SetAsInt32(i);
         }
             break;
 
         case LOCAL_GL_MAX_VARYING_VECTORS:
@@ -1555,16 +1619,21 @@ WebGLContext::GetParameter(PRUint32 pnam
 // bool, WebGL-specific
         case UNPACK_FLIP_Y_WEBGL:
             wrval->SetAsBool(mPixelStoreFlipY);
             break;
         case UNPACK_PREMULTIPLY_ALPHA_WEBGL:
             wrval->SetAsBool(mPixelStorePremultiplyAlpha);
             break;
 
+// uint, WebGL-specific
+        case UNPACK_COLORSPACE_CONVERSION_WEBGL:
+            wrval->SetAsUint32(mPixelStoreColorspaceConversion);
+            break;
+
         //
         // Complex values
         //
         case LOCAL_GL_DEPTH_RANGE: // 2 floats
         case LOCAL_GL_ALIASED_POINT_SIZE_RANGE: // 2 floats
         case LOCAL_GL_ALIASED_LINE_WIDTH_RANGE: // 2 floats
         {
             GLfloat fv[2] = { 0 };
@@ -1789,30 +1858,39 @@ WebGLContext::GetRenderbufferParameter(W
     if (target != LOCAL_GL_RENDERBUFFER)
         return ErrorInvalidEnumInfo("GetRenderbufferParameter: target", target);
 
     MakeContextCurrent();
 
     switch (pname) {
         case LOCAL_GL_RENDERBUFFER_WIDTH:
         case LOCAL_GL_RENDERBUFFER_HEIGHT:
-        case LOCAL_GL_RENDERBUFFER_INTERNAL_FORMAT:
         case LOCAL_GL_RENDERBUFFER_RED_SIZE:
         case LOCAL_GL_RENDERBUFFER_GREEN_SIZE:
         case LOCAL_GL_RENDERBUFFER_BLUE_SIZE:
         case LOCAL_GL_RENDERBUFFER_ALPHA_SIZE:
         case LOCAL_GL_RENDERBUFFER_DEPTH_SIZE:
         case LOCAL_GL_RENDERBUFFER_STENCIL_SIZE:
         {
             GLint i = 0;
             gl->fGetRenderbufferParameteriv(target, pname, &i);
             wrval->SetAsInt32(i);
         }
             break;
-
+        case LOCAL_GL_RENDERBUFFER_INTERNAL_FORMAT:
+        {
+            GLint i = 0;
+            gl->fGetRenderbufferParameteriv(target, pname, &i);
+            if (i == LOCAL_GL_DEPTH24_STENCIL8)
+            {
+                i = LOCAL_GL_DEPTH_STENCIL;
+            }
+            wrval->SetAsInt32(i);
+        }
+            break;
         default:
             return ErrorInvalidEnumInfo("GetRenderbufferParameter: parameter", pname);
     }
 
     *retval = wrval.forget().get();
 
     return NS_OK;
 }
@@ -2017,21 +2095,23 @@ nsresult WebGLContext::TexParameter_base
                     pnameAndParamAreIncompatible = PR_TRUE;
             }
             break;
         default:
             return ErrorInvalidEnumInfo("texParameter: pname", pname);
     }
 
     if (pnameAndParamAreIncompatible) {
+        // note that currently all params are enums, and the tex-input-validation test wants INVALID_ENUM errors
+        // even for texParameterf. why not.
         if (intParamPtr)
             return ErrorInvalidEnum("texParameteri: pname %x and param %x (decimal %d) are mutually incompatible",
                                     pname, intParam, intParam);
         else
-            return ErrorInvalidValue("texParameterf: pname %x and floating-point param %e are mutually incompatible",
+            return ErrorInvalidEnum("texParameterf: pname %x and floating-point param %e are mutually incompatible",
                                     pname, floatParam);
     }
 
     MakeContextCurrent();
     if (intParamPtr)
         gl->fTexParameteri(target, pname, intParam);
     else
         gl->fTexParameterf(target, pname, floatParam);
@@ -2422,16 +2502,22 @@ WebGLContext::PixelStorei(WebGLenum pnam
 {
     switch (pname) {
         case UNPACK_FLIP_Y_WEBGL:
             mPixelStoreFlipY = (param != 0);
             break;
         case UNPACK_PREMULTIPLY_ALPHA_WEBGL:
             mPixelStorePremultiplyAlpha = (param != 0);
             break;
+        case UNPACK_COLORSPACE_CONVERSION_WEBGL:
+            if (param == LOCAL_GL_NONE || param == BROWSER_DEFAULT_WEBGL)
+                mPixelStoreColorspaceConversion = param;
+            else
+                return ErrorInvalidEnumInfo("pixelStorei: colorspace conversion parameter", param);
+            break;
         case LOCAL_GL_PACK_ALIGNMENT:
         case LOCAL_GL_UNPACK_ALIGNMENT:
             if (param != 1 &&
                 param != 2 &&
                 param != 4 &&
                 param != 8)
                 return ErrorInvalidValue("PixelStorei: invalid pack/unpack alignment value");
             if (pname == LOCAL_GL_PACK_ALIGNMENT)
@@ -2585,17 +2671,17 @@ WebGLContext::ReadPixels_base(WebGLint x
     }
 
     // if we're reading alpha, we may need to do fixup
     if (format == LOCAL_GL_ALPHA ||
         format == LOCAL_GL_RGBA)
     {
         PRBool needAlphaFixup;
         if (mBoundFramebuffer) {
-            needAlphaFixup = !mBoundFramebuffer->ColorAttachment0HasAlpha();
+            needAlphaFixup = !mBoundFramebuffer->ColorAttachment().HasAlpha();
         } else {
             needAlphaFixup = gl->ActualFormat().alpha == 0;
         }
 
         if (needAlphaFixup) {
             if (format == LOCAL_GL_ALPHA && type == LOCAL_GL_UNSIGNED_BYTE) {
                 // this is easy; it's an 0xff memset per row
                 PRUint8 *row = (PRUint8*)data;
@@ -2676,18 +2762,18 @@ WebGLContext::RenderbufferStorage(WebGLe
         // 16-bit RGBA formats are not supported on desktop GL
         if (!gl->IsGLES2()) internalformatForGL = LOCAL_GL_RGBA8;
         break;
     case LOCAL_GL_RGB565:
         // the RGB565 format is not supported on desktop GL
         if (!gl->IsGLES2()) internalformatForGL = LOCAL_GL_RGB8;
         break;
     case LOCAL_GL_DEPTH_COMPONENT16:
+        break;
     case LOCAL_GL_STENCIL_INDEX8:
-        // nothing to do for these ones
         break;
     case LOCAL_GL_DEPTH_STENCIL:
         // this one is available in newer OpenGL (at least since 3.1); will probably become available
         // in OpenGL ES 3 (at least it will have some DEPTH_STENCIL) and is the same value that
         // is otherwise provided by EXT_packed_depth_stencil and OES_packed_depth_stencil extensions
         // which means it's supported on most GL and GL ES systems already.
         //
         // So we just use it hoping that it's available (perhaps as an extension) and if it's not available,
@@ -2721,41 +2807,64 @@ WebGLContext::Scissor(WebGLint x, WebGLi
 }
 
 NS_IMETHODIMP
 WebGLContext::StencilFunc(WebGLenum func, WebGLint ref, WebGLuint mask)
 {
     if (!ValidateComparisonEnum(func, "stencilFunc: func"))
         return NS_OK;
 
+    mStencilRef = ref;
+    mStencilValueMask = mask;
+
     MakeContextCurrent();
     gl->fStencilFunc(func, ref, mask);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::StencilFuncSeparate(WebGLenum face, WebGLenum func, WebGLint ref, WebGLuint mask)
 {
     if (!ValidateFaceEnum(face, "stencilFuncSeparate: face") ||
         !ValidateComparisonEnum(func, "stencilFuncSeparate: func"))
         return NS_OK;
 
+    if (face != LOCAL_GL_FRONT_AND_BACK && (ref != mStencilRef || mask != mStencilValueMask))
+        return ErrorInvalidOperation("stencilFuncSeparate: WebGL doesn't currently allow specifying "
+                                     "different values for front and back.");
+
+    mStencilRef = ref;
+    mStencilValueMask = mask;
+
     MakeContextCurrent();
     gl->fStencilFuncSeparate(face, func, ref, mask);
     return NS_OK;
 }
 
-GL_SAME_METHOD_1(StencilMask, StencilMask, WebGLuint)
+NS_IMETHODIMP
+WebGLContext::StencilMask(WebGLuint mask)
+{
+    mStencilWriteMask = mask;
+
+    MakeContextCurrent();
+    gl->fStencilMask(mask);
+    return NS_OK;
+}
 
 NS_IMETHODIMP
 WebGLContext::StencilMaskSeparate(WebGLenum face, WebGLuint mask)
 {
     if (!ValidateFaceEnum(face, "stencilMaskSeparate: face"))
         return NS_OK;
 
+    if (face != LOCAL_GL_FRONT_AND_BACK && mask != mStencilWriteMask)
+        return ErrorInvalidOperation("stencilMaskSeparate: WebGL doesn't currently allow specifying "
+                                     "different values for front and back.");
+    mStencilWriteMask = mask;
+
     MakeContextCurrent();
     gl->fStencilMaskSeparate(face, mask);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::StencilOp(WebGLenum sfail, WebGLenum dpfail, WebGLenum dppass)
 {
--- a/content/canvas/src/WebGLContextUtils.cpp
+++ b/content/canvas/src/WebGLContextUtils.cpp
@@ -225,34 +225,36 @@ WebGLContext::LogMessage(const char *fmt
     JSContext* ccx = nsnull;
     if (stack && NS_SUCCEEDED(stack->Peek(&ccx)) && ccx)
         JS_ReportWarning(ccx, "WebGL: %s", buf);
 }
 
 void
 WebGLContext::LogMessageIfVerbose(const char *fmt, ...)
 {
-    if (!mVerbose)
-        return;
-
     va_list ap;
     va_start(ap, fmt);
 
-    LogMessage(fmt, ap);
+    LogMessageIfVerbose(fmt, ap);
 
     va_end(ap);
 }
 
 void
 WebGLContext::LogMessageIfVerbose(const char *fmt, va_list ap)
 {
-    if (!mVerbose)
-        return;
+    static PRBool firstTime = PR_TRUE;
 
-    LogMessage(fmt, ap);
+    if (mVerbose)
+        LogMessage(fmt, ap);
+    else if (firstTime)
+        LogMessage("There are WebGL warnings or messages in this page, but they are hidden. To see them, "
+                   "go to about:config, set the webgl.verbose preference, and reload this page.");
+
+    firstTime = PR_FALSE;
 }
 
 nsresult
 WebGLContext::SynthesizeGLError(WebGLenum err)
 {
     // If there is already a pending error, don't overwrite it;
     // but if there isn't, then we need to check for a gl error
     // that may have occurred before this one and use that code
--- a/content/canvas/src/WebGLContextValidate.cpp
+++ b/content/canvas/src/WebGLContextValidate.cpp
@@ -199,16 +199,35 @@ PRBool WebGLContext::ValidateBlendFuncDs
 PRBool WebGLContext::ValidateBlendFuncSrcEnum(WebGLenum factor, const char *info)
 {
     if (factor == LOCAL_GL_SRC_ALPHA_SATURATE)
         return PR_TRUE;
     else
         return ValidateBlendFuncDstEnum(factor, info);
 }
 
+PRBool WebGLContext::ValidateBlendFuncEnumsCompatibility(WebGLenum sfactor, WebGLenum dfactor, const char *info)
+{
+    PRBool sfactorIsConstantColor = sfactor == LOCAL_GL_CONSTANT_COLOR ||
+                                    sfactor == LOCAL_GL_ONE_MINUS_CONSTANT_COLOR;
+    PRBool sfactorIsConstantAlpha = sfactor == LOCAL_GL_CONSTANT_ALPHA ||
+                                    sfactor == LOCAL_GL_ONE_MINUS_CONSTANT_ALPHA;
+    PRBool dfactorIsConstantColor = dfactor == LOCAL_GL_CONSTANT_COLOR ||
+                                    dfactor == LOCAL_GL_ONE_MINUS_CONSTANT_COLOR;
+    PRBool dfactorIsConstantAlpha = dfactor == LOCAL_GL_CONSTANT_ALPHA ||
+                                    dfactor == LOCAL_GL_ONE_MINUS_CONSTANT_ALPHA;
+    if ( (sfactorIsConstantColor && dfactorIsConstantAlpha) ||
+         (dfactorIsConstantColor && sfactorIsConstantAlpha) ) {
+        ErrorInvalidOperation("%s are mutually incompatible, see section 6.8 in the WebGL 1.0 spec", info);
+        return PR_FALSE;
+    } else {
+        return PR_TRUE;
+    }
+}
+
 PRBool WebGLContext::ValidateTextureTargetEnum(WebGLenum target, const char *info)
 {
     switch (target) {
         case LOCAL_GL_TEXTURE_2D:
         case LOCAL_GL_TEXTURE_CUBE_MAP:
             return PR_TRUE;
         default:
             ErrorInvalidEnumInfo(info, target);
@@ -459,16 +478,20 @@ WebGLContext::InitAndValidateGL()
             //   http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=261472
             gl->fEnable(LOCAL_GL_POINT_SPRITE);
         }
     }
 
     gl->fGetIntegerv(LOCAL_GL_PACK_ALIGNMENT,   (GLint*) &mPixelStorePackAlignment);
     gl->fGetIntegerv(LOCAL_GL_UNPACK_ALIGNMENT, (GLint*) &mPixelStoreUnpackAlignment);
 
+    gl->fGetIntegerv(LOCAL_GL_STENCIL_WRITEMASK, (GLint*) &mStencilWriteMask);
+    gl->fGetIntegerv(LOCAL_GL_STENCIL_VALUE_MASK, (GLint*) &mStencilValueMask);
+    gl->fGetIntegerv(LOCAL_GL_STENCIL_REF, (GLint*) &mStencilRef);
+
     // Check the shader validator pref
     nsCOMPtr<nsIPrefBranch> prefService = do_GetService(NS_PREFSERVICE_CONTRACTID);
     NS_ENSURE_TRUE(prefService != nsnull, NS_ERROR_FAILURE);
 
     prefService->GetBoolPref("webgl.shader_validator", &mShaderValidation);
 
 #if defined(USE_ANGLE)
     // initialize shader translator
--- a/content/html/content/src/nsHTMLMetaElement.cpp
+++ b/content/html/content/src/nsHTMLMetaElement.cpp
@@ -116,16 +116,23 @@ nsresult
 nsHTMLMetaElement::BindToTree(nsIDocument* aDocument, nsIContent* aParent,
                               nsIContent* aBindingParent,
                               PRBool aCompileEventHandlers)
 {
   nsresult rv = nsGenericHTMLElement::BindToTree(aDocument, aParent,
                                                  aBindingParent,
                                                  aCompileEventHandlers);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (aDocument &&
+      AttrValueIs(kNameSpaceID_None, nsGkAtoms::name, nsGkAtoms::viewport, eIgnoreCase)) {
+    nsAutoString content;
+    rv = GetContent(content);
+    NS_ENSURE_SUCCESS(rv, rv);
+    nsContentUtils::ProcessViewportInfo(aDocument, content);  
+  }
   CreateAndDispatchEvent(aDocument, NS_LITERAL_STRING("DOMMetaAdded"));
   return rv;
 }
 
 void
 nsHTMLMetaElement::UnbindFromTree(PRBool aDeep, PRBool aNullParent)
 {
   nsCOMPtr<nsIDocument> oldDoc = GetCurrentDoc();
--- a/content/html/document/src/nsHTMLDocument.cpp
+++ b/content/html/document/src/nsHTMLDocument.cpp
@@ -129,17 +129,18 @@
 
 #include "nsIPrompt.h"
 //AHMED 12-2
 #include "nsBidiUtils.h"
 
 #include "nsIEditingSession.h"
 #include "nsIEditor.h"
 #include "nsNodeInfoManager.h"
-#include "nsIEditor.h"
+#include "nsIPlaintextEditor.h"
+#include "nsIHTMLEditor.h"
 #include "nsIEditorDocShell.h"
 #include "nsIEditorStyleSheets.h"
 #include "nsIInlineSpellChecker.h"
 #include "nsRange.h"
 #include "mozAutoDocUpdate.h"
 #include "nsCCUncollectableMarker.h"
 #include "nsHtml5Module.h"
 #include "prprf.h"
@@ -3259,16 +3260,32 @@ nsHTMLDocument::EditingStateChanged()
   nsIDocShell *docshell = window->GetDocShell();
   if (!docshell)
     return NS_ERROR_FAILURE;
 
   nsresult rv;
   nsCOMPtr<nsIEditingSession> editSession = do_GetInterface(docshell, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
+  nsCOMPtr<nsIEditor> existingEditor;
+  editSession->GetEditorForWindow(window, getter_AddRefs(existingEditor));
+  if (existingEditor) {
+    // We might already have an editor if it was set up for mail, let's see
+    // if this is actually the case.
+    nsCOMPtr<nsIHTMLEditor> htmlEditor = do_QueryInterface(existingEditor);
+    NS_ABORT_IF_FALSE(htmlEditor, "If we have an editor, it must be an HTML editor");
+    PRUint32 flags = 0;
+    existingEditor->GetFlags(&flags);
+    if (flags & nsIPlaintextEditor::eEditorMailMask) {
+      // We already have a mail editor, then we should not attempt to create
+      // another one.
+      return NS_OK;
+    }
+  }
+
   if (!HasPresShell(window)) {
     // We should not make the window editable or setup its editor.
     // It's probably style=display:none.
     return NS_OK;
   }
 
   PRBool makeWindowEditable = mEditingState == eOff;
   PRBool updateState;
--- a/content/xul/templates/src/nsXULTemplateBuilder.cpp
+++ b/content/xul/templates/src/nsXULTemplateBuilder.cpp
@@ -1171,17 +1171,16 @@ nsXULTemplateBuilder::ContentRemoved(nsI
         // clear the template state when removing content so that template
         // content will be regenerated again if the content is reinserted
         nsXULElement *xulcontent = nsXULElement::FromContent(mRoot);
         if (xulcontent)
             xulcontent->ClearTemplateGenerated();
 
         mDB = nsnull;
         mCompDB = nsnull;
-        mRoot = nsnull;
         mDataSource = nsnull;
     }
 }
 
 void
 nsXULTemplateBuilder::NodeWillBeDestroyed(const nsINode* aNode)
 {
     // The call to RemoveObserver could release the last reference to
@@ -1190,17 +1189,16 @@ nsXULTemplateBuilder::NodeWillBeDestroye
 
     // Break circular references
     if (mQueryProcessor)
         mQueryProcessor->Done();
 
     mDataSource = nsnull;
     mDB = nsnull;
     mCompDB = nsnull;
-    mRoot = nsnull;
 
     nsContentUtils::AddScriptRunner(
         NS_NewRunnableMethod(this, &nsXULTemplateBuilder::UninitTrue));
 }
 
 
 
 
--- a/content/xul/templates/src/nsXULTemplateBuilder.h
+++ b/content/xul/templates/src/nsXULTemplateBuilder.h
@@ -159,18 +159,21 @@ public:
       if (doc) {
         PRBool shouldDelay;
         LoadDataSources(doc, &shouldDelay);
         if (!shouldDelay) {
           Rebuild();
         }
       }
     }
-    void UninitFalse() { Uninit(PR_FALSE); }
-    void UninitTrue() { Uninit(PR_TRUE); }
+
+    // mRoot should not be cleared until after Uninit is finished so that
+    // generated content can be removed during uninitialization.
+    void UninitFalse() { Uninit(PR_FALSE); mRoot = nsnull; }
+    void UninitTrue() { Uninit(PR_TRUE); mRoot = nsnull; }
 
     /**
      * Find the <template> tag that applies for this builder
      */
     nsresult
     GetTemplateRoot(nsIContent** aResult);
 
     /**
--- a/content/xul/templates/tests/chrome/Makefile.in
+++ b/content/xul/templates/tests/chrome/Makefile.in
@@ -253,12 +253,13 @@ include $(topsrcdir)/config/rules.mk
 		test_tmpl_xmlquerywithsort.xul \
 		test_tmpl_xmlquerywithsortotherfield.xul \
 		test_tmpl_xmlquerywithmultiplequeries.xul \
 		test_tmpl_xmlquerywithothertypes.xul \
 		test_tmpl_xmlquerywithinlinedata.xul \
 		test_tmpl_xmlquerywithinlinedatawithmultiplequeries.xul \
 		test_tmpl_invalidqp.xul \
 		test_tmpl_errors.xul \
+		test_tmpl_regenerate.xul \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/chrome/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/content/xul/templates/tests/chrome/test_tmpl_regenerate.xul
@@ -0,0 +1,51 @@
+<?xml version="1.0"?>
+<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
+<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
+
+<!--
+  Regenerate template by removing and appending elements
+-->
+
+<window title="XUL Template Tests" width="500" height="600"
+        onload="test_regenerate()"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+  <script type="application/javascript"
+          src="chrome://mochikit/content/MochiKit/packed.js"></script>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+
+  <body xmlns="http://www.w3.org/1999/xhtml" style="height: 300px; overflow: auto;"/>
+
+<script>
+<![CDATA[
+SimpleTest.waitForExplicitFinish();
+
+function test_regenerate()
+{
+  var container = document.getElementById("container");
+  var node = container.firstChild;
+
+  if (node.childNodes.length != 2) {
+    setTimeout(test_regenerate, 50);
+    return;
+  }
+
+  container.removeChild(node);
+  is(node.childNodes.length, 1, "childNodes after removeChild");
+  container.appendChild(node);
+  is(node.childNodes.length, 2, "childNodes after appendChild");
+  SimpleTest.finish();
+}
+
+]]>
+</script>
+
+<vbox id="container">
+<vbox xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="root" datasources="animals.rdf" ref="http://www.some-fictitious-zoo.com/birds">
+<template zoo:name="Barn Owl" xmlns:zoo="http://www.some-fictitious-zoo.com/rdf#">
+<label uri="rdf:*" value="rdf:http://www.some-fictitious-zoo.com/rdf#name"/>
+</template>
+</vbox>
+</vbox>
+
+</window>
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -4696,24 +4696,33 @@ nsDOMClassInfo::PostCreatePrototype(JSCo
   // document.body.foopy() needs to ensure that looking up foopy on
   // document.body's prototype will find the right function.
   JSObject *global = ::JS_GetGlobalForObject(cx, proto);
 
   // Only do this if the global object is a window.
   // XXX Is there a better way to check this?
   nsISupports *globalNative = XPConnect()->GetNativeOfWrapper(cx, global);
   nsCOMPtr<nsPIDOMWindow> piwin = do_QueryInterface(globalNative);
-  if(!piwin) {
+  if (!piwin) {
     return NS_OK;
   }
 
   nsGlobalWindow *win = nsGlobalWindow::FromSupports(globalNative);
   if (win->IsClosedOrClosing()) {
     return NS_OK;
   }
+
+  // If the window is in a different compartment than the global object, then
+  // it's likely that global is a sandbox object whose prototype is a window.
+  // Don't do anything in this case.
+  if (win->FastGetGlobalJSObject() &&
+      global->compartment() != win->FastGetGlobalJSObject()->compartment()) {
+    return NS_OK;
+  }
+
   if (win->IsOuterWindow()) {
     // XXXjst: Do security checks here when we remove the security
     // checks on the inner window.
 
     win = win->GetCurrentInnerWindowInternal();
 
     if (!win || !(global = win->GetGlobalJSObject()) ||
         win->IsClosedOrClosing()) {
@@ -4941,17 +4950,17 @@ nsWindowSH::PreCreate(nsISupports *nativ
 
   nsGlobalWindow *win = nsGlobalWindow::FromSupports(nativeObj);
   if (win->IsOuterWindow()) {
     if (!win->EnsureInnerWindow()) {
       return NS_ERROR_FAILURE;
     }
 
     *parentObj = win->GetCurrentInnerWindowInternal()->FastGetGlobalJSObject();
-    return win->IsChromeWindow() ? NS_OK : NS_SUCCESS_NEEDS_XOW;
+    return NS_OK;
   }
 
   JSObject *winObj = win->FastGetGlobalJSObject();
   if (!winObj) {
     NS_ASSERTION(win->GetOuterWindowInternal()->IsCreatingInnerWindow(),
                  "should have a JS object by this point");
     return NS_OK;
   }
--- a/dom/interfaces/canvas/nsIDOMWebGLRenderingContext.idl
+++ b/dom/interfaces/canvas/nsIDOMWebGLRenderingContext.idl
@@ -574,20 +574,22 @@ interface nsIDOMWebGLRenderingContext : 
   void blendFunc(in WebGLenum sfactor, in WebGLenum dfactor);
   void blendFuncSeparate(in WebGLenum srcRGB, in WebGLenum dstRGB, in WebGLenum srcAlpha, in WebGLenum dstAlpha);
 
   // Modified: void glBufferData(WebGLenum target, long size, const void* data, WebGLenum usage);
   void bufferData([optional] in long dummy);
   [noscript] void bufferData_size(in WebGLenum target, in WebGLsizei size, in WebGLenum usage);
   [noscript] void bufferData_buf(in WebGLenum target, in WebGLArrayBufferPtr data, in WebGLenum usage);
   [noscript] void bufferData_array(in WebGLenum target, in WebGLArrayPtr data, in WebGLenum usage);
+  [noscript] void bufferData_null();
 
   void bufferSubData([optional] in long dummy);
   [noscript] void bufferSubData_buf(in WebGLenum target, in long offset, in WebGLArrayBufferPtr data);
   [noscript] void bufferSubData_array(in WebGLenum target, in long offset, in WebGLArrayPtr data);
+  [noscript] void bufferSubData_null();
 
   WebGLenum checkFramebufferStatus(in WebGLenum target);
   void clear(in WebGLbitfield mask);
   void clearColor(in WebGLclampf red, in WebGLclampf green, in WebGLclampf blue, in WebGLclampf alpha);
   void clearDepth(in WebGLclampf depth);
   void clearStencil(in WebGLint s);
   void colorMask(in WebGLboolean red, in WebGLboolean green, in WebGLboolean blue, in WebGLboolean alpha);
   void compileShader([optional] in nsIWebGLShader shader);
--- a/dom/plugins/PluginInstanceChild.cpp
+++ b/dom/plugins/PluginInstanceChild.cpp
@@ -107,20 +107,18 @@ static const TCHAR kPluginIgnoreSubclass
 
 template<>
 struct RunnableMethodTraits<PluginInstanceChild>
 {
     static void RetainCallee(PluginInstanceChild* obj) { }
     static void ReleaseCallee(PluginInstanceChild* obj) { }
 };
 
-PluginInstanceChild::PluginInstanceChild(const NPPluginFuncs* aPluginIface,
-                                         const nsCString& aMimeType)
+PluginInstanceChild::PluginInstanceChild(const NPPluginFuncs* aPluginIface)
     : mPluginIface(aPluginIface)
-    , mQuirks(0)
     , mCachedWindowActor(nsnull)
     , mCachedElementActor(nsnull)
 #if defined(OS_WIN)
     , mPluginWindowHWND(0)
     , mPluginWndProc(0)
     , mPluginParentHWND(0)
     , mCachedWinlessPluginHWND(0)
     , mWinlessPopupSurrogateHWND(0)
@@ -141,45 +139,43 @@ PluginInstanceChild::PluginInstanceChild
     , mAccumulatedInvalidRect(0,0,0,0)
     , mIsTransparent(false)
     , mSurfaceType(gfxASurface::SurfaceTypeMax)
     , mCurrentInvalidateTask(nsnull)
     , mCurrentAsyncSetWindowTask(nsnull)
     , mPendingPluginCall(false)
     , mDoAlphaExtraction(false)
     , mSurfaceDifferenceRect(0,0,0,0)
-#ifdef MOZ_X11
-    , mFlash10Quirks(false)
-#endif
 #if (MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6)
     , mMaemoImageRendering(PR_FALSE)
 #endif
 {
     memset(&mWindow, 0, sizeof(mWindow));
     mData.ndata = (void*) this;
     mData.pdata = nsnull;
 #if defined(MOZ_X11) && defined(XP_UNIX) && !defined(XP_MACOSX)
     mWindow.ws_info = &mWsInfo;
     memset(&mWsInfo, 0, sizeof(mWsInfo));
     mWsInfo.display = DefaultXDisplay();
 #endif // MOZ_X11 && XP_UNIX && !XP_MACOSX
 #if defined(OS_WIN)
     memset(&mAlphaExtract, 0, sizeof(mAlphaExtract));
 #endif // OS_WIN
-    InitQuirksModes(aMimeType);
 #if defined(OS_WIN)
     InitPopupMenuHook();
 #endif // OS_WIN
 #ifdef MOZ_X11
     const char *description = NULL;
     mPluginIface->getvalue(GetNPP(), NPPVpluginDescriptionString,
                            &description);
     if (description) {
         NS_NAMED_LITERAL_CSTRING(flash10Head, "Shockwave Flash 10.");
-        mFlash10Quirks = StringBeginsWith(nsDependentCString(description), flash10Head);
+        if (StringBeginsWith(nsDependentCString(description), flash10Head)) {
+          PluginModuleChild::current()->AddQuirk(PluginModuleChild::QUIRK_FLASH_EXPOSE_COORD_TRANSLATION);
+        }
     }
 #endif
 }
 
 PluginInstanceChild::~PluginInstanceChild()
 {
 #if defined(OS_WIN)
   DestroyPluginWindow();
@@ -189,38 +185,20 @@ PluginInstanceChild::~PluginInstanceChil
         ::CGColorSpaceRelease(mShColorSpace);
     }
     if (mShContext) {
         ::CGContextRelease(mShContext);
     }
 #endif
 }
 
-void
-PluginInstanceChild::InitQuirksModes(const nsCString& aMimeType)
+int
+PluginInstanceChild::GetQuirks()
 {
-    // application/x-silverlight
-    // application/x-silverlight-2
-    NS_NAMED_LITERAL_CSTRING(silverlight, "application/x-silverlight");
-    if (FindInReadable(silverlight, aMimeType)) {
-        mQuirks |= QUIRK_SILVERLIGHT_DEFAULT_TRANSPARENT;
-#ifdef OS_WIN
-        mQuirks |= QUIRK_WINLESS_TRACKPOPUP_HOOK;
-#endif
-    }
-
-#ifdef OS_WIN
-    // application/x-shockwave-flash
-    NS_NAMED_LITERAL_CSTRING(flash, "application/x-shockwave-flash");
-    if (FindInReadable(flash, aMimeType)) {
-        mQuirks |= QUIRK_WINLESS_TRACKPOPUP_HOOK;
-        mQuirks |= QUIRK_FLASH_THROTTLE_WMUSER_EVENTS; 
-        mQuirks |= QUIRK_FLASH_HOOK_SETLONGPTR;
-    }
-#endif
+    return PluginModuleChild::current()->GetQuirks();
 }
 
 NPError
 PluginInstanceChild::InternalGetNPObjectForValue(NPNVariable aValue,
                                                  NPObject** aObject)
 {
     PluginScriptableObjectChild* actor;
     NPError result = NPERR_NO_ERROR;
@@ -955,19 +933,19 @@ PluginInstanceChild::AnswerNPP_SetWindow
               RemoveProp(mPluginWindowHWND, kPluginIgnoreSubclassProperty);
               HookSetWindowLongPtr();
           }
       }
       break;
 
       case NPWindowTypeDrawable:
           mWindow.type = aWindow.type;
-          if (mQuirks & QUIRK_WINLESS_TRACKPOPUP_HOOK)
+          if (GetQuirks() & PluginModuleChild::QUIRK_WINLESS_TRACKPOPUP_HOOK)
               CreateWinlessPopupSurrogate();
-          if (mQuirks & QUIRK_FLASH_THROTTLE_WMUSER_EVENTS)
+          if (GetQuirks() & PluginModuleChild::QUIRK_FLASH_THROTTLE_WMUSER_EVENTS)
               SetupFlashMsgThrottle();
           return SharedSurfaceSetWindow(aWindow);
       break;
 
       default:
           NS_NOTREACHED("Bad plugin window type.");
           return false;
       break;
@@ -1188,17 +1166,17 @@ PluginInstanceChild::PluginWindowProc(HW
             break;
         }
     }
 
     if (message == WM_KILLFOCUS)
       self->CallPluginFocusChange(false);
 
     if (message == WM_USER+1 &&
-        (self->mQuirks & PluginInstanceChild::QUIRK_FLASH_THROTTLE_WMUSER_EVENTS)) {
+        (self->GetQuirks() & PluginModuleChild::QUIRK_FLASH_THROTTLE_WMUSER_EVENTS)) {
         self->FlashThrottleMessage(hWnd, message, wParam, lParam, true);
         return 0;
     }
 
     // Make sure capture is released by the child on mouse events. Fixes a
     // problem with flash full screen mode mouse input. Appears to be
     // caused by a bug in flash, since we are not setting the capture
     // on the window. (In non-oopp land, we would set and release via
@@ -1356,17 +1334,17 @@ void
 PluginInstanceChild::HookSetWindowLongPtr()
 {
 #ifdef _WIN64
     // XXX WindowsDllInterceptor doesn't support hooks
     // in 64-bit builds, disabling this code for now.
     return;
 #endif
 
-    if (!(GetQuirks() & QUIRK_FLASH_HOOK_SETLONGPTR))
+    if (!(GetQuirks() & PluginModuleChild::QUIRK_FLASH_HOOK_SETLONGPTR))
         return;
 
     sUser32Intercept.Init("user32.dll");
 #ifdef _WIN64
     sUser32Intercept.AddHook("SetWindowLongPtrA", SetWindowLongPtrAHook,
                              (void**) &sUser32SetWindowLongAHookStub);
     sUser32Intercept.AddHook("SetWindowLongPtrW", SetWindowLongPtrWHook,
                              (void**) &sUser32SetWindowLongWHookStub);
@@ -1439,17 +1417,17 @@ PluginInstanceChild::TrackPopupHookProc(
   }
 
   return res;
 }
 
 void
 PluginInstanceChild::InitPopupMenuHook()
 {
-    if (!(mQuirks & QUIRK_WINLESS_TRACKPOPUP_HOOK) ||
+    if (!(GetQuirks() & PluginModuleChild::QUIRK_WINLESS_TRACKPOPUP_HOOK) ||
         sUser32TrackPopupMenuStub)
         return;
 
     // Note, once WindowsDllInterceptor is initialized for a module,
     // it remains initialized for that particular module for it's
     // lifetime. Additional instances are needed if other modules need
     // to be hooked.
     sUser32Intercept.Init("user32.dll");
@@ -1539,17 +1517,17 @@ PluginInstanceChild::WinlessHandleEvent(
 
     // Events that might generate nested event dispatch loops need
     // special handling during delivery.
     int16_t handled;
 
     // TrackPopupMenu will fail if the parent window is not associated with
     // our ui thread. So we hook TrackPopupMenu so we can hand in a surrogate
     // parent created in the child process.
-    if ((mQuirks & QUIRK_WINLESS_TRACKPOPUP_HOOK) && // XXX turn on by default?
+    if ((GetQuirks() & PluginModuleChild::QUIRK_WINLESS_TRACKPOPUP_HOOK) && // XXX turn on by default?
           (event.event == WM_RBUTTONDOWN || // flash
            event.event == WM_RBUTTONUP)) {  // silverlight
       sWinlessPopupSurrogateHWND = mWinlessPopupSurrogateHWND;
     }
 
     handled = mPluginIface->event(&mData, reinterpret_cast<void*>(&event));
 
     sWinlessPopupSurrogateHWND = NULL;
@@ -2223,27 +2201,27 @@ PluginInstanceChild::DoAsyncSetWindow(co
 
     mWindow.x = aWindow.x;
     mWindow.y = aWindow.y;
     mWindow.width = aWindow.width;
     mWindow.height = aWindow.height;
     mWindow.clipRect = aWindow.clipRect;
     mWindow.type = aWindow.type;
 
-    if (mQuirks & QUIRK_SILVERLIGHT_DEFAULT_TRANSPARENT)
+    if (GetQuirks() & PluginModuleChild::QUIRK_SILVERLIGHT_DEFAULT_TRANSPARENT)
         mIsTransparent = true;
 
     mLayersRendering = true;
     mSurfaceType = aSurfaceType;
     UpdateWindowAttributes(true);
 
 #ifdef XP_WIN
-    if (mQuirks & QUIRK_WINLESS_TRACKPOPUP_HOOK)
+    if (GetQuirks() & PluginModuleChild::QUIRK_WINLESS_TRACKPOPUP_HOOK)
         CreateWinlessPopupSurrogate();
-    if (mQuirks & QUIRK_FLASH_THROTTLE_WMUSER_EVENTS)
+    if (GetQuirks() & PluginModuleChild::QUIRK_FLASH_THROTTLE_WMUSER_EVENTS)
         SetupFlashMsgThrottle();
 #endif
 
     if (!mAccumulatedInvalidRect.IsEmpty()) {
         AsyncShowPluginFrame();
     }
 }
 
@@ -2615,17 +2593,17 @@ void
 PluginInstanceChild::PaintRectToSurface(const nsIntRect& aRect,
                                         gfxASurface* aSurface,
                                         const gfxRGBA& aColor)
 {
     // Render using temporary X surface, with copy to image surface
     nsIntRect plPaintRect(aRect);
     nsRefPtr<gfxASurface> renderSurface = aSurface;
 #ifdef MOZ_X11
-    if (mIsTransparent && mFlash10Quirks) {
+    if (mIsTransparent && (GetQuirks() & PluginModuleChild::QUIRK_FLASH_EXPOSE_COORD_TRANSLATION)) {
         // Work around a bug in Flash up to 10.1 d51 at least, where expose event
         // top left coordinates within the plugin-rect and not at the drawable
         // origin are misinterpreted.  (We can move the top left coordinate
         // provided it is within the clipRect.), see bug 574583
         plPaintRect.SetRect(0, 0, aRect.XMost(), aRect.YMost());
     }
     if (renderSurface->GetType() != gfxASurface::SurfaceTypeXlib) {
         // On X11 we can paint to non Xlib surface only with HelperSurface
@@ -2985,33 +2963,29 @@ PluginInstanceChild::AnswerNPP_Destroy(N
         if (static_cast<BrowserStreamChild*>(streams[i])->InstanceDying())
             ++i;
         else
             streams.RemoveElementAt(i);
     }
     for (PRUint32 i = 0; i < streams.Length(); ++i)
         static_cast<BrowserStreamChild*>(streams[i])->FinishDelivery();
 
-    {
-        MutexAutoLock lock(mAsyncCallMutex);
-        for (PRUint32 i = 0; i < mPendingAsyncCalls.Length(); ++i)
-            mPendingAsyncCalls[i]->Cancel();
-        mPendingAsyncCalls.TruncateLength(0);
-    }
-
     mTimers.Clear();
     if (mCurrentInvalidateTask) {
         mCurrentInvalidateTask->Cancel();
         mCurrentInvalidateTask = nsnull;
     }
     if (mCurrentAsyncSetWindowTask) {
         mCurrentAsyncSetWindowTask->Cancel();
         mCurrentAsyncSetWindowTask = nsnull;
     }
 
+    // NPP_Destroy() should be a synchronization point for plugin threads
+    // calling NPN_AsyncCall: after this function returns, they are no longer
+    // allowed to make async calls on this instance.
     PluginModuleChild::current()->NPP_Destroy(this);
     mData.ndata = 0;
 
     mDeletingHash = new nsTHashtable<DeletingObjectEntry>;
     mDeletingHash->Init();
     PluginModuleChild::current()->FindNPObjectsForInstance(this);
 
     mDeletingHash->EnumerateEntries(InvalidateObject, NULL);
@@ -3023,10 +2997,17 @@ PluginInstanceChild::AnswerNPP_Destroy(N
     mCachedElementActor = nsnull;
 
 #if defined(OS_WIN)
     SharedSurfaceRelease();
     DestroyWinlessPopupSurrogate();
     UnhookWinlessFlashThrottle();
 #endif
 
+    // Pending async calls are discarded, not delivered. This matches the
+    // in-process behavior.
+    for (PRUint32 i = 0; i < mPendingAsyncCalls.Length(); ++i)
+        mPendingAsyncCalls[i]->Cancel();
+
+    mPendingAsyncCalls.Clear();
+
     return true;
 }
--- a/dom/plugins/PluginInstanceChild.h
+++ b/dom/plugins/PluginInstanceChild.h
@@ -178,17 +178,17 @@ protected:
 
     virtual bool
     AnswerSetPluginFocus();
 
     virtual bool
     AnswerUpdateWindow();
 
 public:
-    PluginInstanceChild(const NPPluginFuncs* aPluginIface, const nsCString& aMimeType);
+    PluginInstanceChild(const NPPluginFuncs* aPluginIface);
 
     virtual ~PluginInstanceChild();
 
     bool Initialize();
 
     NPP GetNPP()
     {
         return &mData;
@@ -209,40 +209,21 @@ public:
 
     void InvalidateRect(NPRect* aInvalidRect);
 
     uint32_t ScheduleTimer(uint32_t interval, bool repeat, TimerFunc func);
     void UnscheduleTimer(uint32_t id);
 
     void AsyncCall(PluginThreadCallback aFunc, void* aUserData);
 
-    int GetQuirks() { return mQuirks; }
-
-    // Quirks mode support for various plugin mime types
-    enum PluginQuirks {
-        // Silverlight assumes it is transparent in windowless mode. This quirk
-        // matches the logic in nsNPAPIPluginInstance::SetWindowless.
-        QUIRK_SILVERLIGHT_DEFAULT_TRANSPARENT           = 1 << 0,
-        // Win32: Hook TrackPopupMenu api so that we can swap out parent
-        // hwnds. The api will fail with parents not associated with our
-        // child ui thread. See WinlessHandleEvent for details.
-        QUIRK_WINLESS_TRACKPOPUP_HOOK                   = 1 << 1,
-        // Win32: Throttle flash WM_USER+1 heart beat messages to prevent
-        // flooding chromium's dispatch loop, which can cause ipc traffic
-        // processing lag.
-        QUIRK_FLASH_THROTTLE_WMUSER_EVENTS              = 1 << 2,
-        // Win32: Catch resets on our subclass by hooking SetWindowLong.
-        QUIRK_FLASH_HOOK_SETLONGPTR                     = 1 << 3,
-    };
+    int GetQuirks();
 
 private:
     friend class PluginModuleChild;
 
-    void InitQuirksModes(const nsCString& aMimeType);
-
     NPError
     InternalGetNPObjectForValue(NPNVariable aValue,
                                 NPObject** aObject);
 
 #if defined(OS_WIN)
     static bool RegisterWindowClass();
     bool CreatePluginWindow();
     void DestroyPluginWindow();
@@ -329,17 +310,16 @@ private:
         bool                 mWindowed;
     };
 
 #endif
 
     const NPPluginFuncs* mPluginIface;
     NPP_t mData;
     NPWindow mWindow;
-    int mQuirks;
 
     // Cached scriptable actors to avoid IPC churn
     PluginScriptableObjectChild* mCachedWindowActor;
     PluginScriptableObjectChild* mCachedElementActor;
 
 #if defined(MOZ_X11) && defined(XP_UNIX) && !defined(XP_MACOSX)
     NPSetWindowCallbackStruct mWsInfo;
 #elif defined(OS_WIN)
@@ -518,20 +498,16 @@ private:
     // supports NPPVpluginTransparentAlphaBool (which is not part of NPAPI yet)
     bool mDoAlphaExtraction;
 
     // Cached rectangle rendered to previous surface(mBackSurface)
     // Used for reading back to current surface and syncing data,
     // in plugin coordinates.
     nsIntRect mSurfaceDifferenceRect;
 
-#ifdef MOZ_X11
-    // Used with windowless flash plugin only, see bug 574583
-    bool                  mFlash10Quirks;
-#endif
 #if (MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6)
     // Maemo5 Flash does not remember WindowlessLocal state
     // we should listen for NPP values negotiation and remember it
     PRPackedBool          mMaemoImageRendering;
 #endif
 };
 
 } // namespace plugins
--- a/dom/plugins/PluginModuleChild.cpp
+++ b/dom/plugins/PluginModuleChild.cpp
@@ -65,48 +65,56 @@
 #include "mozilla/plugins/BrowserStreamChild.h"
 #include "mozilla/plugins/PluginStreamChild.h"
 #include "PluginIdentifierChild.h"
 
 #include "nsNPAPIPlugin.h"
 
 #ifdef XP_WIN
 #include "COMMessageFilter.h"
+#include "nsWindowsDllInterceptor.h"
 #endif
 
 #ifdef OS_MACOSX
 #include "PluginInterposeOSX.h"
 #include "PluginUtilsOSX.h"
 #endif
 
 using namespace mozilla::plugins;
 
 #if defined(XP_WIN)
 const PRUnichar * kFlashFullscreenClass = L"ShockwaveFlashFullScreen";
+const PRUnichar * kMozillaWindowClass = L"MozillaWindowClass";
 #endif
 
 namespace {
 PluginModuleChild* gInstance = nsnull;
 }
 
 #ifdef MOZ_WIDGET_QT
 typedef void (*_gtk_init_fn)(int argc, char **argv);
 static _gtk_init_fn s_gtk_init = nsnull;
 static PRLibrary *sGtkLib = nsnull;
 #endif
 
 #ifdef XP_WIN
 // Used with fix for flash fullscreen window loosing focus.
 static bool gDelayFlashFocusReplyUntilEval = false;
+// Used to fix GetWindowInfo problems with internal flash settings dialogs
+static WindowsDllInterceptor sUser32Intercept;
+typedef BOOL (WINAPI *GetWindowInfoPtr)(HWND hwnd, PWINDOWINFO pwi);
+static GetWindowInfoPtr sGetWindowInfoPtrStub = NULL;
+static HWND sBrowserHwnd = NULL;
 #endif
 
 PluginModuleChild::PluginModuleChild() :
     mLibrary(0),
     mShutdownFunc(0),
-    mInitializeFunc(0)
+    mInitializeFunc(0),
+    mQuirks(QUIRKS_NOT_INITIALIZED)
 #if defined(OS_WIN) || defined(OS_MACOSX)
   , mGetEntryPointsFunc(0)
 #elif defined(MOZ_WIDGET_GTK2)
   , mNestedLoopTimerId(0)
 #elif defined(MOZ_WIDGET_QT)
   , mNestedLoopTimerObject(0)
 #endif
 #ifdef OS_WIN
@@ -1704,35 +1712,103 @@ PluginModuleChild::AllocPPluginIdentifie
 
 bool
 PluginModuleChild::DeallocPPluginIdentifier(PPluginIdentifierChild* aActor)
 {
     delete aActor;
     return true;
 }
 
+#if defined(XP_WIN)
+BOOL WINAPI
+PMCGetWindowInfoHook(HWND hWnd, PWINDOWINFO pwi)
+{
+  if (!pwi)
+      return FALSE;
+
+  if (!sGetWindowInfoPtrStub) {
+     NS_ASSERTION(FALSE, "Something is horribly wrong in PMCGetWindowInfoHook!");
+     return FALSE;
+  }
+
+  if (!sBrowserHwnd) {
+      PRUnichar szClass[20];
+      if (GetClassNameW(hWnd, szClass, NS_ARRAY_LENGTH(szClass)) && 
+          !wcscmp(szClass, kMozillaWindowClass)) {
+          sBrowserHwnd = hWnd;
+      }
+  }
+  // Oddity: flash does strange rect comparisons for mouse input destined for
+  // it's internal settings window. Post removing sub widgets for tabs, touch
+  // this up so they get the rect they expect.
+  // XXX potentially tie this to a specific major version?
+  BOOL result = sGetWindowInfoPtrStub(hWnd, pwi);
+  if (sBrowserHwnd && sBrowserHwnd == hWnd)
+      pwi->rcWindow = pwi->rcClient;
+  return result;
+}
+#endif
+
 PPluginInstanceChild*
 PluginModuleChild::AllocPPluginInstance(const nsCString& aMimeType,
                                         const uint16_t& aMode,
                                         const InfallibleTArray<nsCString>& aNames,
                                         const InfallibleTArray<nsCString>& aValues,
                                         NPError* rv)
 {
     PLUGIN_LOG_DEBUG_METHOD;
     AssertPluginThread();
 
+    InitQuirksModes(aMimeType);
+
+#ifdef XP_WIN
+    if (mQuirks & QUIRK_FLASH_HOOK_GETWINDOINFO) {
+        sUser32Intercept.Init("user32.dll");
+        sUser32Intercept.AddHook("GetWindowInfo", PMCGetWindowInfoHook,
+                                 (void**) &sGetWindowInfoPtrStub);
+    }
+#endif
+
     nsAutoPtr<PluginInstanceChild> childInstance(
-        new PluginInstanceChild(&mFunctions, aMimeType));
+        new PluginInstanceChild(&mFunctions));
     if (!childInstance->Initialize()) {
         *rv = NPERR_GENERIC_ERROR;
         return 0;
     }
     return childInstance.forget();
 }
 
+void
+PluginModuleChild::InitQuirksModes(const nsCString& aMimeType)
+{
+    if (mQuirks != QUIRKS_NOT_INITIALIZED)
+      return;
+    mQuirks = 0;
+    // application/x-silverlight
+    // application/x-silverlight-2
+    NS_NAMED_LITERAL_CSTRING(silverlight, "application/x-silverlight");
+    if (FindInReadable(silverlight, aMimeType)) {
+        mQuirks |= QUIRK_SILVERLIGHT_DEFAULT_TRANSPARENT;
+#ifdef OS_WIN
+        mQuirks |= QUIRK_WINLESS_TRACKPOPUP_HOOK;
+#endif
+    }
+
+#ifdef OS_WIN
+    // application/x-shockwave-flash
+    NS_NAMED_LITERAL_CSTRING(flash, "application/x-shockwave-flash");
+    if (FindInReadable(flash, aMimeType)) {
+        mQuirks |= QUIRK_WINLESS_TRACKPOPUP_HOOK;
+        mQuirks |= QUIRK_FLASH_THROTTLE_WMUSER_EVENTS; 
+        mQuirks |= QUIRK_FLASH_HOOK_SETLONGPTR;
+        mQuirks |= QUIRK_FLASH_HOOK_GETWINDOINFO;
+    }
+#endif
+}
+
 bool
 PluginModuleChild::AnswerPPluginInstanceConstructor(PPluginInstanceChild* aActor,
                                                     const nsCString& aMimeType,
                                                     const uint16_t& aMode,
                                                     const InfallibleTArray<nsCString>& aNames,
                                                     const InfallibleTArray<nsCString>& aValues,
                                                     NPError* rv)
 {
--- a/dom/plugins/PluginModuleChild.h
+++ b/dom/plugins/PluginModuleChild.h
@@ -200,17 +200,51 @@ public:
         SendPluginShowWindow(window_id, modal, r.origin.x, r.origin.y, r.size.width, r.size.height);
     }
 
     void PluginHideWindow(uint32_t window_id) {
         SendPluginHideWindow(window_id);
     }
 #endif
 
+    // Quirks mode support for various plugin mime types
+    enum PluginQuirks {
+        QUIRKS_NOT_INITIALIZED                          = 0,
+        // Silverlight assumes it is transparent in windowless mode. This quirk
+        // matches the logic in nsNPAPIPluginInstance::SetWindowless.
+        QUIRK_SILVERLIGHT_DEFAULT_TRANSPARENT           = 1 << 0,
+        // Win32: Hook TrackPopupMenu api so that we can swap out parent
+        // hwnds. The api will fail with parents not associated with our
+        // child ui thread. See WinlessHandleEvent for details.
+        QUIRK_WINLESS_TRACKPOPUP_HOOK                   = 1 << 1,
+        // Win32: Throttle flash WM_USER+1 heart beat messages to prevent
+        // flooding chromium's dispatch loop, which can cause ipc traffic
+        // processing lag.
+        QUIRK_FLASH_THROTTLE_WMUSER_EVENTS              = 1 << 2,
+        // Win32: Catch resets on our subclass by hooking SetWindowLong.
+        QUIRK_FLASH_HOOK_SETLONGPTR                     = 1 << 3,
+        // X11: Work around a bug in Flash up to 10.1 d51 at least, where
+        // expose event top left coordinates within the plugin-rect and
+        // not at the drawable origin are misinterpreted.
+        QUIRK_FLASH_EXPOSE_COORD_TRANSLATION            = 1 << 4,
+        // Win32: Catch get window info calls on the browser and tweak the
+        // results so mouse input works when flash is displaying it's settings
+        // window.
+        QUIRK_FLASH_HOOK_GETWINDOINFO                   = 1 << 5,
+    };
+
+    int GetQuirks() { return mQuirks; }
+    void AddQuirk(PluginQuirks quirk) {
+      if (mQuirks == QUIRKS_NOT_INITIALIZED)
+        mQuirks = 0;
+      mQuirks |= quirk;
+    }
+
 private:
+    void InitQuirksModes(const nsCString& aMimeType);
     bool InitGraphics();
 #if defined(MOZ_WIDGET_GTK2)
     static gboolean DetectNestedEventLoop(gpointer data);
     static gboolean ProcessBrowserEvents(gpointer data);
 
     NS_OVERRIDE
     virtual void EnteredCxxStack();
     NS_OVERRIDE
@@ -221,16 +255,17 @@ private:
     virtual void EnteredCxxStack();
     NS_OVERRIDE
     virtual void ExitedCxxStack();
 #endif
 
     std::string mPluginFilename;
     PRLibrary* mLibrary;
     nsCString mUserAgent;
+    int mQuirks;
 
     // we get this from the plugin
     NP_PLUGINSHUTDOWN mShutdownFunc;
 #ifdef OS_LINUX
     NP_PLUGINUNIXINIT mInitializeFunc;
 #elif defined(OS_WIN) || defined(OS_MACOSX)
     NP_PLUGININIT mInitializeFunc;
     NP_GETENTRYPOINTS mGetEntryPointsFunc;
--- a/dom/tests/mochitest/localstorage/frameMasterNotEqual.html
+++ b/dom/tests/mochitest/localstorage/frameMasterNotEqual.html
@@ -2,36 +2,86 @@
 <head>
 <title>frame for localStorage test</title>
 
 <script type="text/javascript" src="interOriginFrame.js"></script>
 <script type="text/javascript">
 
 var currentStep = 1;
 
+var __observer = {
+  QueryInterface: function(iid)
+  {
+    if (iid.equals(nsIObserver) ||
+        iid.equals(nsISupports))
+      return this;
+
+    throw Components.results.NS_ERROR_NO_INTERFACE;
+  },
+  
+  observe: function(subject, topic, data)
+  {
+    ok(true, "Observed: " + topic);
+  }    
+}
+
+netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+var obsSvc = Components.classes["@mozilla.org/observer-service;1"]
+              .getService(Components.interfaces.nsIObserverService);
+              
+function setupTestObserver()
+{
+  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+  
+  obsSvc.addObserver(__observer, "domstorage-flush-timer", false);
+  obsSvc.addObserver(__observer, "cookie-changed", false);
+  obsSvc.addObserver(__observer, "offline-app-removed", false);
+  obsSvc.addObserver(__observer, "private-browsing", false);
+  obsSvc.addObserver(__observer, "perm-changed", false);
+}
+
+function releaseTestObserver()
+{
+  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+  
+  obsSvc.removeObserver(__observer, "domstorage-flush-timer");
+  obsSvc.removeObserver(__observer, "cookie-changed");
+  obsSvc.removeObserver(__observer, "offline-app-removed");
+  obsSvc.removeObserver(__observer, "private-browsing");
+  obsSvc.removeObserver(__observer, "perm-changed");
+}
+
 function doStep()
 {
   switch (currentStep)
   {
     case 1:
+      setupTestObserver();
       localStorage.setItem("X", "1");
       is(localStorage.getItem("X"), "1", "X is 1 in the master");
       break;
 
     case 3:
       is(localStorage.getItem("X"), "1", "X remains 1 in the master");
+      is(localStorage.getItem("X"), "1", "X remains 1 in the master");
+      is(localStorage.length, 1, "One item in the master");
+      is(localStorage.getItem("X"), "1", "X remains 1 in the master");
+      is(localStorage.length, 1, "One item in the master");
+      is(localStorage.getItem("X"), "1", "X remains 1 in the master");
+
       localStorage.removeItem("X");
       is(localStorage.getItem("X"), null, "X was removed from the master");
       break;
 
     case 5:
       is(localStorage.getItem("Y"), null, "Y null in the master");
       break;
 
     case 7:
+      releaseTestObserver();
       return finishTest();
   }
 
   // Increase by two to distinguish each test step order
   // in both master doStep and slave doStep functions.
   ++currentStep;
   ++currentStep;
 
--- a/editor/libeditor/html/tests/Makefile.in
+++ b/editor/libeditor/html/tests/Makefile.in
@@ -83,16 +83,17 @@ include $(topsrcdir)/config/rules.mk
 		data/cfhtml-firefox.txt \
 		data/cfhtml-ie.txt \
 		data/cfhtml-ooo.txt \
 		$(NULL)
 
 _CHROME_TEST_FILES = \
 		test_bug490879.xul \
 		test_bug607584.xul \
+		test_bug616590.xul \
 		green.png \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
 	(cd $(srcdir) && tar $(TAR_CREATE_FLAGS) - browserscope 2> /dev/null) | (cd $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir) && tar -xf -)
 
 libs:: $(_DATA_FILES)
new file mode 100644
--- /dev/null
+++ b/editor/libeditor/html/tests/test_bug616590.xul
@@ -0,0 +1,106 @@
+<?xml version="1.0"?>
+<?xml-stylesheet href="chrome://global/skin"
+                 type="text/css"?>
+<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
+                 type="text/css"?>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=616590
+-->
+<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+        title="Mozilla Bug 616590" onload="runTest();">
+  <script type="application/javascript"
+          src="chrome://mochikit/content/MochiKit/packed.js"/>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
+
+  <body xmlns="http://www.w3.org/1999/xhtml">
+  <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=616590"
+     target="_blank">Mozilla Bug 616590</a>
+  <p/>
+  <editor xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+          id="editor"
+          type="content"
+          editortype="htmlmail"
+          style="width: 400px; height: 100px;"/>
+  <p/>
+  <pre id="test">
+  </pre>
+  </body>
+  <script class="testbody" type="application/javascript">
+  <![CDATA[
+
+  SimpleTest.waitForExplicitFinish();
+
+  function EditorContentListener(aEditor)
+  {
+    this.init(aEditor);
+  }
+
+  EditorContentListener.prototype = {
+    init : function(aEditor)
+    {
+      this.mEditor = aEditor;
+    },
+
+    QueryInterface : function(aIID)
+    {
+      if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
+          aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
+          aIID.equals(Components.interfaces.nsISupports))
+        return this;
+      throw Components.results.NS_NOINTERFACE;
+    },
+
+    onStateChange : function(aWebProgress, aRequest, aStateFlags, aStatus)
+    {
+      if (aStateFlags & Components.interfaces.nsIWebProgressListener.STATE_STOP)
+      {
+        var editor = this.mEditor.getEditor(this.mEditor.contentWindow);
+        if (editor) {
+          editor.QueryInterface(Components.interfaces.nsIEditorMailSupport);
+          editor.insertAsCitedQuotation("<html><body><div contenteditable>foo</div></body></html>", "", true);
+          document.documentElement.clientWidth;
+          progress.removeProgressListener(this);
+          SimpleTest.finish();
+        }
+      }
+    },
+
+
+    onProgressChange : function(aWebProgress, aRequest,
+                                aCurSelfProgress, aMaxSelfProgress,
+                                aCurTotalProgress, aMaxTotalProgress)
+    {
+    },
+
+    onLocationChange : function(aWebProgress, aRequest, aLocation)
+    {
+    },
+
+    onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage)
+    {
+    },
+
+    onSecurityChange : function(aWebProgress, aRequest, aState)
+    {
+    },
+
+    mEditor: null
+  };
+
+  var progress;
+
+  function runTest() {
+    var editorElement = document.getElementById("editor");
+    editorElement.makeEditable("htmlmail", true);
+    var docShell = editorElement.boxObject.QueryInterface(Components.interfaces.nsIEditorBoxObject).docShell;
+    progress = docShell.QueryInterface(Components.interfaces.nsIInterfaceRequestor).getInterface(Components.interfaces.nsIWebProgress);
+    var progressListener = new EditorContentListener(editorElement);
+    progress.addProgressListener(progressListener, Components.interfaces.nsIWebProgress.NOTIFY_ALL);
+    editorElement.setAttribute("src", "data:text/html,");
+  }
+]]>
+</script>
+</window>
deleted file mode 100644
--- a/extensions/access-builtin/Makefile.in
+++ /dev/null
@@ -1,47 +0,0 @@
-# ***** 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 mozilla.org Code.
-#
-# The Initial Developer of the Original Code is
-# Aaron Leventhal.
-# Portions created by the Initial Developer are Copyright (C) 2001
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# 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 *****
-
-DEPTH		= ../..
-topsrcdir	= @top_srcdir@
-srcdir		= @srcdir@
-VPATH		= @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-DIRS		= accessproxy
-
-include $(topsrcdir)/config/rules.mk
-
deleted file mode 100644
--- a/extensions/access-builtin/README
+++ /dev/null
@@ -1,58 +0,0 @@
-# ***** 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 mozilla.org Code.
-#
-# The Initial Developer of the Original Code is
-# Aaron Leventhal.
-# Portions created by the Initial Developer are Copyright (C) 2001
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# 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 is the access-builtin module
-
-This module creates a preference in Mozilla for browsing with text-to-speech, and eventually
-with a brailled display.
-
-See http://access-mozilla.sourceforge.net
-
-On UNIX or Linux, enable this as part of the build with
-./configure --with-extensions=default,accessibility
-
-On Windows you will need to manually perform the make in this directory.
-
-Mac builds are not enabled yet.
-
-To use, you must add these lines to prefs.js in your profile directory.
-user_pref("accessibility.browsewithcaret", true);
-user_pref("accessibility.usetexttospeech", "ViaVoice");
-
-The actual text-to-speech conversion is temporarily broken.
-However, the debug console window will tell you what would be spoken.
-
-Normally, you would need to get the free download of IBM ViaVoice.
deleted file mode 100644
--- a/extensions/access-builtin/accessproxy/Makefile.in
+++ /dev/null
@@ -1,71 +0,0 @@
-#!gmake
-# ***** 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 mozilla.org Code.
-#
-# The Initial Developer of the Original Code is
-# Aaron Leventhal.
-# Portions created by the Initial Developer are Copyright (C) 2001
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# 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 *****
-
-DEPTH = ../../..
-topsrcdir = @top_srcdir@
-srcdir = @srcdir@
-VPATH = @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-MODULE = accessproxy
-XPIDL_MODULE = accessproxy
-LIBRARY_NAME = accessproxy
-SHORT_LIBNAME = accproxy
-MOZILLA_INTERNAL_API = 1
-
-EXPORT_LIBRARY = 1
-IS_COMPONENT = 1
-MODULE_NAME	= nsAccessProxy
-
-# Don't install. At the moment we only want to build this extension
-# for inclusion in 3rd party assistive technology installers, 
-# not as part of our own installation
-NO_INSTALL = 1
-NO_DIST_INSTALL = 1
-
-CPPSRCS =   \
-  nsAccessProxy.cpp	   \
-  nsAccessProxyRegistration.cpp \
-  $(NULL)
-
-XPIDLSRCS	= nsIAccessProxy.idl
-
-include $(topsrcdir)/config/rules.mk
-
-EXTRA_DSO_LDOPTS += $(MOZ_COMPONENT_LIBS)
-
deleted file mode 100644
--- a/extensions/access-builtin/accessproxy/nsAccessProxy.cpp
+++ /dev/null
@@ -1,297 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- *
- * ***** 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 mozilla.org Code.
- *
- * The Initial Developer of the Original Code is
- * Aaron Leventhal.
- * Portions created by the Initial Developer are Copyright (C) 2001
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * 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 ***** */
-
-#include "nsCOMPtr.h"
-#include "nsMemory.h"
-#include "nsIServiceManager.h"
-#include "nsIObserverService.h"
-#include "nsIGenericFactory.h"
-#include "nsIWebProgress.h"
-#include "nsCURILoader.h"
-#include "nsIDocShell.h"
-#include "nsIDOMWindow.h"
-#include "nsIDOMWindowInternal.h"
-#include "nsIDOMEventTarget.h"
-#include "nsIDOMNSEvent.h"
-#include "nsIPrefBranch.h"
-#include "nsIPrefService.h"
-
-#include "nsIRegistry.h"
-#include "nsString.h"
-
-#include "nsIDOMNode.h"
-#include "nsIPresShell.h"
-#include "nsIDOMDocument.h"
-#include "nsIDocument.h"
-#include "nsISelection.h"
-#include "nsISelectionController.h"
-#include "nsCaret.h"
-
-// Header for this class
-#include "nsAccessProxy.h"
-
-// #define NS_DEBUG_ACCESS_BUILTIN 1
-
-
-////////////////////////////////////////////////////////////////////////
-
-
-NS_IMPL_ISUPPORTS4(nsAccessProxy, nsIObserver, nsISupportsWeakReference, nsIWebProgressListener, nsIDOMEventListener)
-
-nsAccessProxy* nsAccessProxy::mInstance = nsnull;
-
-nsAccessProxy::nsAccessProxy()
-{
-}
-
-nsAccessProxy::~nsAccessProxy()
-{
-}
-
-nsAccessProxy *nsAccessProxy::GetInstance()
-{
-  if (mInstance == nsnull) {
-    mInstance = new nsAccessProxy();
-    // Will be released in the module destructor
-    NS_IF_ADDREF(mInstance);
-  }
-
-  NS_IF_ADDREF(mInstance);
-  return mInstance;
-}
-
-void nsAccessProxy::ReleaseInstance()
-{
-  NS_IF_RELEASE(nsAccessProxy::mInstance);
-}
-
-
-NS_IMETHODIMP nsAccessProxy::HandleEvent(nsIDOMEvent* aEvent)
-{
-  nsresult rv;
-
-  //////// Get Type of Event into a string called eventName ///////
-  nsAutoString eventNameStr;
-  rv=aEvent->GetType(eventNameStr);
-  if (NS_FAILED(rv))
-    return rv;
-  // Print event name and styles debugging messages
-  #ifdef NS_DEBUG_ACCESS_BUILTIN
-  printf("\n==== %s event occurred ====\n",NS_ConvertUTF16toUTF8(eventNameStr).get());
-  #endif
-
-  ////////// Get Target Node - place in document where event was fired ////////////
-  nsCOMPtr<nsIDOMEventTarget> targetNode;
-
-  nsCOMPtr<nsIDOMNSEvent> nsevent(do_QueryInterface(aEvent));
-
-  if (nsevent) {
-    rv = nsevent->GetOriginalTarget(getter_AddRefs(targetNode));
-
-    if (NS_FAILED(rv))
-      return rv;
-  }
-
-  if (!targetNode)
-    return NS_ERROR_NULL_POINTER;
-  nsCOMPtr<nsIDOMNode> domNode = do_QueryInterface(targetNode);
-  if (!domNode)
-    return NS_OK;
-
-  // get the Document and PresShell
-  nsCOMPtr<nsIDOMDocument> domDoc;
-  nsIPresShell *presShell = nsnull;
-  nsCOMPtr<nsIDocument> doc;
-  domNode->GetOwnerDocument(getter_AddRefs(domDoc));
-  if (domDoc) {
-    doc = do_QueryInterface(domDoc);
-    if (doc) {
-      presShell = doc->GetShell();
-    }
-  }
-  //return  NS_OK;
-  /*
-  if (presShell && eventNameStr.EqualsLiteral("click")) {
-    nsCOMPtr<nsISelection> domSelection;
-    presShell->FrameSelection()->GetSelection(nsISelectionController::SELECTION_NORMAL,
-                            getter_AddRefs(domSelection));
-    if (!domSelection)
-      return NS_OK;
-    nsCOMPtr<nsIDOMNode> focusDomNode;
-    domSelection->GetAnchorNode(getter_AddRefs(focusDomNode));
-    if (focusDomNode) domNode=focusDomNode;
-    // first, tell the caret which selection to use
-    nsRefPtr<nsCaret> caret;
-    presShell->GetCaret(getter_AddRefs(caret));
-    if (!caret) return NS_OK;
-    caret->SetCaretDOMSelection(domSelection);
-    // tell the pres shell to enable the caret, rather than settings its visibility directly.
-    // this way the presShell's idea of caret visibility is maintained.
-    nsCOMPtr<nsISelectionController> selCon = do_QueryInterface(presShell);
-    if (!selCon) return NS_ERROR_NO_INTERFACE;
-    selCon->SetCaretEnabled(PR_TRUE);
-    caret->SetCaretVisible(PR_TRUE);
-  }
-  */
-
-  return NS_OK;
-}
-
-
-// This method gets called on application startup
-NS_IMETHODIMP nsAccessProxy::Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData) 
-{
-  static PRBool accessProxyInstalled;
-
-  nsresult rv = NS_OK;
-  nsDependentCString aTopicString(aTopic);
-
-  if (accessProxyInstalled && aTopicString.EqualsLiteral(NS_XPCOM_SHUTDOWN_OBSERVER_ID))
-    return Release();
-
-  if (!accessProxyInstalled && aTopicString.EqualsLiteral(APPSTARTUP_CATEGORY)) {
-    accessProxyInstalled = PR_TRUE; // Set to TRUE even for failure cases - we don't want to try more than once
-    nsCOMPtr<nsIWebProgress> progress(do_GetService(NS_DOCUMENTLOADER_SERVICE_CONTRACTID));
-    rv = NS_ERROR_FAILURE;
-    if (progress) {
-      rv = progress->AddProgressListener(static_cast<nsIWebProgressListener*>(this),
-                                         nsIWebProgress::NOTIFY_STATE_DOCUMENT);
-      if (NS_SUCCEEDED(rv))
-        AddRef();
-    }
-     // install xpcom shutdown observer
-    if (NS_SUCCEEDED(rv)) {
-      nsCOMPtr<nsIObserverService> observerService(do_GetService("@mozilla.org/observer-service;1", &rv));
-      if (NS_SUCCEEDED(rv)) 
-        rv = observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, PR_TRUE);
-    }
-  }
-  return rv;
-}
-
-
-NS_IMETHODIMP nsAccessProxy::OnStateChange(nsIWebProgress *aWebProgress,
-  nsIRequest *aRequest, PRUint32 aStateFlags, nsresult aStatus)
-{
-/* PRUint32 aStateFlags ...
- *
- * ===== What has happened =====	
- * STATE_START, STATE_REDIRECTING, STATE_TRANSFERRING,
- * STATE_NEGOTIATING, STATE_STOP
-
- * ===== Where did it occur? =====
- * STATE_IS_REQUEST, STATE_IS_DOCUMENT, STATE_IS_NETWORK, STATE_IS_WINDOW
-
- * ===== Security info =====
- * STATE_IS_INSECURE, STATE_IS_BROKEN, STATE_IS_SECURE, STATE_SECURE_HIGH
- * STATE_SECURE_MED, STATE_SECURE_LOW
- *
- */
-
-  if ((aStateFlags & (STATE_STOP|STATE_START)) && (aStateFlags & STATE_IS_DOCUMENT)) {
-    // Test for built in text to speech or braille display usage preference
-    // If so, attach event handlers to window. If not, don't.
-    nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID));
-    nsXPIDLCString textToSpeechEngine, brailleDisplayEngine;
-    if (prefBranch) {
-      prefBranch->GetCharPref("accessibility.usetexttospeech", getter_Copies(textToSpeechEngine));
-      prefBranch->GetCharPref("accessibility.usebrailledisplay", getter_Copies(brailleDisplayEngine));
-    }
-
-    if ((textToSpeechEngine && *textToSpeechEngine) || (brailleDisplayEngine && *brailleDisplayEngine)) {  
-      // Yes, prefs say we will need handlers for this 
-      nsCOMPtr<nsIDOMWindow> domWindow;
-      aWebProgress->GetDOMWindow(getter_AddRefs(domWindow));
-
-      if (domWindow) {
-        nsCOMPtr<nsIDOMEventTarget> eventTarget = do_QueryInterface(domWindow);
-        nsCOMPtr<nsIDOMWindowInternal> windowInternal = do_QueryInterface(domWindow);
-        nsCOMPtr<nsIDOMWindowInternal> opener;
-        if (windowInternal)
-          windowInternal->GetOpener(getter_AddRefs(opener));
-        if (eventTarget && opener) {
-          eventTarget->AddEventListener(NS_LITERAL_STRING("keyup"), this, PR_FALSE);
-          eventTarget->AddEventListener(NS_LITERAL_STRING("keypress"), this, PR_FALSE);
-          eventTarget->AddEventListener(NS_LITERAL_STRING("focus"), this, PR_FALSE);
-          eventTarget->AddEventListener(NS_LITERAL_STRING("load"), this, PR_FALSE);
-          eventTarget->AddEventListener(NS_LITERAL_STRING("click"), this, PR_FALSE); // for debugging
-        }
-      }
-    }
-  }
-
-  return NS_OK;
-}
-
-/* void onProgressChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in long aCurSelfProgress, in long aMaxSelfProgress, in long aCurTotalProgress, in long aMaxTotalProgress); */
-NS_IMETHODIMP nsAccessProxy::OnProgressChange(nsIWebProgress *aWebProgress,
-  nsIRequest *aRequest, PRInt32 aCurSelfProgress, PRInt32 aMaxSelfProgress,
-  PRInt32 aCurTotalProgress, PRInt32 aMaxTotalProgress)
-{
-  // We can use this to report the percentage done
-  NS_NOTREACHED("notification excluded in AddProgressListener(...)");
-  return NS_OK;
-}
-
-/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location); */
-NS_IMETHODIMP nsAccessProxy::OnLocationChange(nsIWebProgress *aWebProgress,
-  nsIRequest *aRequest, nsIURI *location)
-{
-  // Load has been verified, it will occur, about to commence
-  NS_NOTREACHED("notification excluded in AddProgressListener(...)");
-  return NS_OK;
-}
-
-/* void onStatusChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); */
-NS_IMETHODIMP nsAccessProxy::OnStatusChange(nsIWebProgress *aWebProgress,
-  nsIRequest *aRequest, nsresult aStatus, const PRUnichar *aMessage)
-{
-  // Status bar has changed
-  NS_NOTREACHED("notification excluded in AddProgressListener(...)");
-  return NS_OK;
-}
-
-/* void onSecurityChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in unsigned long state); */
-NS_IMETHODIMP nsAccessProxy::OnSecurityChange(nsIWebProgress *aWebProgress,
-  nsIRequest *aRequest, PRUint32 state)
-{
-  // Security setting has changed
-  NS_NOTREACHED("notification excluded in AddProgressListener(...)");
-  return NS_OK;
-}
-
deleted file mode 100644
--- a/extensions/access-builtin/accessproxy/nsAccessProxy.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
- *
- * ***** 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 mozilla.org Code.
- *
- * The Initial Developer of the Original Code is
- * Aaron Leventhal.
- * Portions created by the Initial Developer are Copyright (C) 2001
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * 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 file is the header of an implementation
- * nsAccessProxy of the nsIAccessProxy interface.
- */
-
-#include "nsIAccessProxy.h"
-#include "nsIDOMEventListener.h"
-#include "nsIWebProgressListener.h"
-#include "nsWeakReference.h"
-#include "nsIObserver.h"
-#include "nsIAppStartupNotifier.h"
-
-
-/**
- * AccessProxy is an implementation of the nsIAccessProxy interface.  In XPCOM,
- * there can be more than one implementation of an given interface.  Class
- * IDs (CIDs) uniquely identify a particular implementation of an interface.
- * Interface IDs (IIDs) uniquely identify an interface.
- *
- * The CID is also a unique number that looks just like an IID
- * and uniquely identifies an implementation
- * {7CB5B7A0-07D7-11d3-BDE2-000064657374}
- */
-
-
-class nsAccessProxy : public nsIDOMEventListener,
-                      public nsIObserver,
-                      public nsIWebProgressListener,
-                      public nsSupportsWeakReference
-{
-public:
-  nsAccessProxy();
-  virtual ~nsAccessProxy();
-
-  NS_DEFINE_STATIC_CID_ACCESSOR(NS_ACCESSPROXY_CID);
-
-  NS_DECL_ISUPPORTS  // This macro expands into declaration of nsISupports interface
-  NS_DECL_NSIOBSERVER
-  NS_DECL_NSIWEBPROGRESSLISTENER
-
-  //NS_DECL_NSIACCESSPROXY
-  NS_IMETHOD HandleEvent(nsIDOMEvent *event);  
-
-  static nsAccessProxy *GetInstance();
-  static void ReleaseInstance(void);
-
-private:
-  static nsAccessProxy *mInstance;
-};
deleted file mode 100644
--- a/extensions/access-builtin/accessproxy/nsAccessProxyRegistration.cpp
+++ /dev/null
@@ -1,93 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
- * 
- * ***** 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 mozilla.org Code.
- *
- * The Initial Developer of the Original Code is
- * Aaron Leventhal.
- * Portions created by the Initial Developer are Copyright (C) 2001
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * 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 ***** */
-
-#include "nsIGenericFactory.h"
-#include "nsAccessProxy.h"
-#include "nsIServiceManager.h"
-#include "nsIRegistry.h"
-#include "prprf.h"
-#include "nsCRT.h"
-#include "nsICategoryManager.h"
-
-////////////////////////////////////////////////////////////////////////
-// Define a table of CIDs implemented by this module along with other
-// information like the function to create an instance, contractid, and
-// class name.
-//
-// The Registration and Unregistration proc are optional in the structure.
-//
-
-
-// This function is called at component registration time
-static NS_METHOD nsAccessProxyRegistrationProc(nsIComponentManager *aCompMgr,
-  nsIFile *aPath, const char *registryLocation, const char *componentType,
-  const nsModuleComponentInfo *info)
-{
-  // This function performs the extra step of installing us as
-  // an application component. This makes sure that we're
-  // initialized on application startup.
-
-  nsresult rv;
-  nsCOMPtr<nsICategoryManager> categoryManager(do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv));
-  if (NS_SUCCEEDED(rv)) 
-    rv = categoryManager->AddCategoryEntry(APPSTARTUP_CATEGORY, "Access Proxy", 
-      "service," NS_ACCESSPROXY_CONTRACTID, PR_TRUE, PR_TRUE, nsnull);
-  return rv;
-}
-
-
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsAccessProxy,nsAccessProxy::GetInstance)
-
-static void AccessProxyModuleDtor(nsIModule* self)
-{
-    nsAccessProxy::ReleaseInstance();
-}
-
-static const nsModuleComponentInfo components[] =
-{
-  { "AccessProxy Component", NS_ACCESSPROXY_CID, NS_ACCESSPROXY_CONTRACTID,
-    nsAccessProxyConstructor, nsAccessProxyRegistrationProc,
-    nsnull  // Unregistration proc
-  }
-};
-
-NS_IMPL_NSGETMODULE_WITH_DTOR(nsAccessProxy, components, AccessProxyModuleDtor)
-
-
-
-
deleted file mode 100644
--- a/extensions/access-builtin/accessproxy/nsIAccessProxy.idl
+++ /dev/null
@@ -1,64 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
- * ***** 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 mozilla.org Code.
- *
- * The Initial Developer of the Original Code is
- * Aaron Leventhal.
- * Portions created by the Initial Developer are Copyright (C) 2001
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * 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 ***** */
-
-/**
- * A accessproxy of XPConnect. This file contains a accessproxy interface.
- *
- */
-
-#include "nsISupports.idl"
-#include "domstubs.idl"
-
-%{ C++
-  #include "nsIDOMEvent.h"
-
-  #define NS_ACCESSPROXY_CID \
-    { 0x5500c0d7, 0xdcc3, 0x4786, { 0xb4, 0x2f, 0xc2, 0x74, 0xb8, 0xc0, 0x7f, 0x72 } }
-
-  #define NS_ACCESSPROXY_CONTRACTID "@mozilla.org/accessproxy;1"
-%}
-
-interface nsIDOMEvent;
-
-[uuid(27B1B140-2939-432a-9B59-3A4C6B11B6C3)]
-interface nsIAccessProxy : nsISupports
-{
-  void handleEvent(in nsIDOMEvent event);
-};
-
-
-
deleted file mode 100755
--- a/extensions/access-builtin/makefiles.sh
+++ /dev/null
@@ -1,42 +0,0 @@
-#! /bin/sh
-# ***** 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 Mozilla Build System
-#
-# The Initial Developer of the Original Code is
-# Ben Turner <mozilla@songbirdnest.com>
-#
-# Portions created by the Initial Developer are Copyright (C) 2007
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# 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 *****
-
-add_makefiles "
-  extensions/access-builtin/Makefile
-  extensions/access-builtin/accessproxy/Makefile
-"
deleted file mode 100644
--- a/extensions/metrics/Makefile.in
+++ /dev/null
@@ -1,70 +0,0 @@
-# vim:set ts=8 sw=8 sts=8 noet:
-# ***** 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 the Metrics extension.
-#
-# The Initial Developer of the Original Code is Google Inc.
-# Portions created by the Initial Developer are Copyright (C) 2006
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Darin Fisher <darin@meer.net>
-#
-# 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 *****
-
-DEPTH		= ../..
-topsrcdir	= @top_srcdir@
-srcdir		= @srcdir@
-VPATH		= @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-METRICS_VERSION = 2a3
-XPI_NAME		= metrics
-USE_EXTENSION_MANIFEST	= 1
-NO_JAR_AUTO_REG		= 1
-INSTALL_EXTENSION_ID	= metrics@mozilla.org
-XPI_PKGNAME		= metrics-$(METRICS_VERSION)
-
-DIRS		= public src build
-
-ifdef ENABLE_TESTS
-DIRS += test
-endif
-
-PREF_JS_EXPORTS = $(srcdir)/metrics.js
-
-DIST_FILES = install.rdf
-
-# We should really pull FIREFOX_VERSION from browser/config/version.txt but we
-# can't be assured that we've even pulled those files. So we hardcode them.
-
-XULAPP_DEFINES = \
-        -DFIREFOX_VERSION=$(FIREFOX_VERSION) \
-        -DEXTENSION_VERSION=$(METRICS_VERSION) \
-        $(NULL)
-
-include $(topsrcdir)/config/rules.mk
deleted file mode 100644
--- a/extensions/metrics/build/Makefile.in
+++ /dev/null
@@ -1,78 +0,0 @@
-# vim:set ts=8 sw=8 sts=8 noet:
-# ***** 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 the Metrics extension.
-#
-# The Initial Developer of the Original Code is Google Inc.
-# Portions created by the Initial Developer are Copyright (C) 2006
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Brian Ryner <bryner@brianryner.com>
-#
-# 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 *****
-
-DEPTH		= ../../..
-topsrcdir	= @top_srcdir@
-srcdir		= @srcdir@
-VPATH		= @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-MODULE		= metrics
-IS_COMPONENT	= 1
-LIBRARY_NAME	= metrics
-SHORT_LIBNAME	= metrics
-
-XPI_NAME	= metrics
-
-
-CPPSRCS		= \
-		nsMetricsModule.cpp \
-		$(NULL)
-
-SHARED_LIBRARY_LIBS = \
-		../src/$(LIB_PREFIX)metrics_s.$(LIB_SUFFIX) \
-		$(NULL)
-
-EXTRA_DSO_LDOPTS = $(XPCOM_GLUE_LDOPTS) \
-		   $(NSPR_LIBS) \
-		   $(BZ2_LIBS) \
-		   $(NULL)
-
-LOCAL_INCLUDES	= \
-		-I$(srcdir)/../src \
-		-I$(DIST)/public/nss \
-		-I$(DIST)/private/nss \
-		$(NULL)
-
-include $(topsrcdir)/config/rules.mk
-
-ifeq ($(OS_ARCH)_$(GNU_CC), WINNT_)
-  LDFLAGS += -NODEFAULTLIB:MSVCRT
-endif
-
-CXXFLAGS += $(BZ2_CFLAGS)
deleted file mode 100644
--- a/extensions/metrics/build/nsMetricsModule.cpp
+++ /dev/null
@@ -1,134 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Darin Fisher <darin@meer.net>
- *
- * 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 ***** */
-
-#include "nsMetricsModule.h"
-#include "nsMetricsService.h"
-#include "nsLoadCollector.h"
-#include "nsWindowCollector.h"
-#include "nsProfileCollector.h"
-#include "nsUICommandCollector.h"
-#include "nsAutoCompleteCollector.h"
-#include "nsIGenericFactory.h"
-#include "nsICategoryManager.h"
-#include "nsServiceManagerUtils.h"
-#include "nsCOMPtr.h"
-#include "nsXPCOMCID.h"
-#include "nsIClassInfoImpl.h"
-
-NS_DECL_CLASSINFO(nsMetricsService)
-
-#define COLLECTOR_CONTRACTID(type) \
-  "@mozilla.org/extensions/metrics/collector;1?name=" type ":" NS_METRICS_NAMESPACE
-
-static NS_METHOD
-nsMetricsServiceRegisterSelf(nsIComponentManager *compMgr,
-                             nsIFile *path,
-                             const char *loaderStr,
-                             const char *type,
-                             const nsModuleComponentInfo *info)
-{
-  nsCOMPtr<nsICategoryManager> cat =
-      do_GetService(NS_CATEGORYMANAGER_CONTRACTID);
-  NS_ENSURE_STATE(cat);
-
-  cat->AddCategoryEntry("app-startup",
-                        NS_METRICSSERVICE_CLASSNAME,
-                        "service," NS_METRICSSERVICE_CONTRACTID,
-                        PR_TRUE, PR_TRUE, nsnull);
-  return NS_OK;
-}
-
-NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsLoadCollector, Init)
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsWindowCollector)
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsProfileCollector)
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsUICommandCollector)
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsAutoCompleteCollector)
-
-static const nsModuleComponentInfo components[] = {
-  {
-    NS_METRICSSERVICE_CLASSNAME,
-    NS_METRICSSERVICE_CID,
-    NS_METRICSSERVICE_CONTRACTID,
-    nsMetricsService::Create,
-    nsMetricsServiceRegisterSelf,
-    NULL,
-    NULL,
-    NS_CI_INTERFACE_GETTER_NAME(nsMetricsService),
-    NULL,
-    &NS_CLASSINFO_NAME(nsMetricsService),
-    nsIClassInfo::MAIN_THREAD_ONLY | nsIClassInfo::SINGLETON
-  },
-  {
-    NS_METRICSSERVICE_CLASSNAME,
-    NS_METRICSSERVICE_CID,
-    NS_ABOUT_MODULE_CONTRACTID_PREFIX "metrics",
-    nsMetricsService::Create
-  },
-  {
-    NS_LOADCOLLECTOR_CLASSNAME,
-    NS_LOADCOLLECTOR_CID,
-    COLLECTOR_CONTRACTID("document"),
-    nsLoadCollectorConstructor
-  },
-  {
-    NS_WINDOWCOLLECTOR_CLASSNAME,
-    NS_WINDOWCOLLECTOR_CID,
-    COLLECTOR_CONTRACTID("window"),
-    nsWindowCollectorConstructor
-  },
-  {
-    NS_PROFILECOLLECTOR_CLASSNAME,
-    NS_PROFILECOLLECTOR_CID,
-    COLLECTOR_CONTRACTID("profile"),
-    nsProfileCollectorConstructor
-  },
-  {
-    NS_UICOMMANDCOLLECTOR_CLASSNAME,
-    NS_UICOMMANDCOLLECTOR_CID,
-    COLLECTOR_CONTRACTID("uielement"),
-    nsUICommandCollectorConstructor
-  },
-  {
-    NS_AUTOCOMPLETECOLLECTOR_CLASSNAME,
-    NS_AUTOCOMPLETECOLLECTOR_CID,
-    COLLECTOR_CONTRACTID("autocomplete"),
-    nsAutoCompleteCollectorConstructor
-  }
-};
-
-NS_IMPL_NSGETMODULE(metrics, components)
deleted file mode 100644
--- a/extensions/metrics/content/prefs.xul
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0"?>
-
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-<?xml-stylesheet href="chrome://metrics/skin/prefs.css" type="text/css"?>
-
-<!DOCTYPE prefwindow SYSTEM "chrome://metrics/locale/prefs.dtd">
-
-<prefwindow
-    id="metrics-options-window"
-    type="prefwindow"
-    windowtype="Metrics:Preferences"
-    title="&prefs.title;"
-    width="400" height="160"
-    xmlns:html="http://www.w3.org/1999/xhtml"
-    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
-
-  <prefpane id="metricsPrefsPanel" flex="1">
-    <preferences id="metrics-prefs">
-      <preference id="metrics-pref-upload-enable" name="extensions.mozilla.metrics.upload.enable" type="bool" instantApply="true"/>
-    </preferences>
-    <vbox class="prefs" flex="1">
-      <description class="msg">&prefs.label.msg;</description>
-      <checkbox id="metrics-enable-checkbox" checked="true" label="&prefs.checkbox.enable;" preference="metrics-pref-upload-enable" 
-                persist="checked" class="cb" />
-    </vbox>
-    <spacer flex="1" />
-  </prefpane>
-</prefwindow>
deleted file mode 100644
--- a/extensions/metrics/install.rdf
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0"?>
-
-#filter substitution
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
-     xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-  <Description about="urn:mozilla:install-manifest">
-    <em:id>metrics@mozilla.org</em:id>
-    <em:version>@EXTENSION_VERSION@</em:version>
-
-    <em:targetApplication>
-      <!-- Firefox -->
-      <Description>
-        <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
-        <em:minVersion>3.0a1</em:minVersion>
-        <em:maxVersion>@FIREFOX_VERSION@</em:maxVersion> 
-      </Description>
-    </em:targetApplication>
-
-    <!-- front-end metadata -->
-    <em:name>Spectator</em:name>
-    <em:description>Collects anonymous usage statistics from the browser</em:description>
-    <em:creator>mozilla.org</em:creator>
-    <em:optionsURL>chrome://metrics/content/prefs.xul</em:optionsURL>
-
-    <em:file>
-      <Description about="urn:mozilla:extension:file:metrics.jar">
-        <em:package>content/</em:package>
-        <em:skin>skin/</em:skin>
-        <em:locale>locale/en-US/</em:locale>
-      </Description>
-    </em:file>
-  </Description>
-</RDF>
deleted file mode 100644
--- a/extensions/metrics/jar.mn
+++ /dev/null
@@ -1,7 +0,0 @@
-metrics.jar:
-% content metrics %content/
-% skin    metrics classic/1.0 %skin/
-% locale  metrics en-US %locale/en-US/
-  content/prefs.xul               (content/prefs.xul)
-  skin/prefs.css                  (skin/prefs.css)
-  locale/en-US/prefs.dtd          (locale/en-US/prefs.dtd)
deleted file mode 100644
--- a/extensions/metrics/locale/en-US/prefs.dtd
+++ /dev/null
@@ -1,7 +0,0 @@
-<!ENTITY prefs.title           "Spectator Preferences">
-
-<!ENTITY prefs.label.msg       "Help us make Firefox better by sending anonymous usage statistics.">
-<!ENTITY prefs.checkbox.enable "Enable Spectator">
-
-<!ENTITY prefs.button.close    "Close">
-
deleted file mode 100755
--- a/extensions/metrics/makefiles.sh
+++ /dev/null
@@ -1,45 +0,0 @@
-#! /bin/sh
-# ***** 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 Mozilla Build System
-#
-# The Initial Developer of the Original Code is
-# Ben Turner <mozilla@songbirdnest.com>
-#
-# Portions created by the Initial Developer are Copyright (C) 2007
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# 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 *****
-
-add_makefiles "
-  extensions/metrics/Makefile
-  extensions/metrics/build/Makefile
-  extensions/metrics/public/Makefile
-  extensions/metrics/src/Makefile
-  extensions/metrics/test/Makefile
-"
deleted file mode 100644
--- a/extensions/metrics/metrics.js
+++ /dev/null
@@ -1,3 +0,0 @@
-pref("extensions.mozilla.metrics.upload.enable", false);
-pref("extensions.mozilla.metrics.upload.uri", "");
-pref("extensions.mozilla.metrics.event-count", 0);
deleted file mode 100644
--- a/extensions/metrics/public/Makefile.in
+++ /dev/null
@@ -1,57 +0,0 @@
-# vim:set ts=8 sw=8 sts=8 noet:
-# ***** 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 the Metrics extension.
-#
-# The Initial Developer of the Original Code is Google Inc.
-# Portions created by the Initial Developer are Copyright (C) 2006
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Darin Fisher <darin@meer.net>
-#
-# 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 *****
-
-DEPTH		= ../../..
-topsrcdir	= @top_srcdir@
-srcdir		= @srcdir@
-VPATH		= @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-MODULE		= metrics
-XPI_NAME	= metrics
-
-XPIDLSRCS	= \
-		nsIMetricsService.idl \
-		nsIMetricsCollector.idl \
-		$(NULL)
-
-EXPORTS		= \
-		nsMetricsModule.h \
-		$(NULL)
-
-include $(topsrcdir)/config/rules.mk
deleted file mode 100644
--- a/extensions/metrics/public/nsIMetricsCollector.idl
+++ /dev/null
@@ -1,73 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Brian Ryner <bryner@brianryner.com>
- *
- * 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 ***** */
-
-#include "nsISupports.idl"
-
-/**
- * The nsIMetricsCollector interface is implemented by any object that collects
- * data on behalf of the MetricsService.  When the configuration file reequests
- * collector "foo" in namespace "http://www.mozilla.org/metrics",
- * the contract id
- * "@mozilla.org/extensions/metrics/collector;1?name=http://www.mozilla.org/metrics:foo"
- * is instantiated (using getSerivce).  The collector is responsible for
- * calling nsIMetricsService::logEvent() when it has something to log.
- */
-[scriptable, uuid(be965c17-848a-43d1-a9f6-b3f1c1bd8faa)]
-interface nsIMetricsCollector : nsISupports
-{
-  /**
-   * Notification that this collector should be enabled.  The collector
-   * should register itself for observer and event notifications as
-   * necessary.
-   */
-  void onAttach();
-
-  /**
-   * Notification that this collector is no longer enabled.  The collector
-   * should unregister itself from observer and event notifications so that
-   * the object can be freed.
-   */
-  void onDetach();
-
-  /**
-   * Notification that the MetricsService is starting a new event log.
-   * This happens after any onDetach() notifications that result from parsing
-   * the new configuration.
-   */
-  void onNewLog();
-};
deleted file mode 100644
--- a/extensions/metrics/public/nsIMetricsService.idl
+++ /dev/null
@@ -1,214 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Darin Fisher <darin@meer.net>
- *
- * 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 ***** */
-
-#include "nsISupports.idl"
-
-interface nsIPropertyBag;
-interface nsIDOMWindow;
-
-/**
- * This file defines the interfaces for the Metrics Service.
- *
- * This service allows arbitrary types of events to be logged and uploaded
- * to a server, based on server-configured collection parameters.
- * The nsIMetricsService API provides an abstraction for the underlying XML
- * data format.
- * 
- * For more information about the data format and the built-in
- * event collectors, see http://wiki.mozilla.org/Browser_Metrics.
- */
-
-
-/**
- * nsIMetricsEventItem represents a particular node of data to record
- * in an event.  Each item has a namespaced item name, a list of properties
- * (key/value pairs), and an ordered list of child items.  The child items
- * need not be unique; an item may be repeated.
- */
-[scriptable, uuid(62f4528f-5c59-4e86-a7ee-f34b67d7d65f)]
-interface nsIMetricsEventItem : nsISupports
-{
-  /**
-   * The namespace for this item, which must be a valid XML namespace URI.
-   */
-  readonly attribute DOMString itemNamespace;
-
-  /**
-   * The name of this item, which must be a valid XML tag name.
-   */
-  readonly attribute DOMString itemName;
-
-  /**
-   * A PropertyBag containing the key/value pairs to be included in the item.
-   * JavaScript callers can simply set this to an object containing the
-   * key/value pairs as object properties.
-   */
-  attribute nsIPropertyBag properties;
-
-  /**
-   * Returns the child event item at the given index.
-   */
-  nsIMetricsEventItem childAt(in long index);
-
-  /**
-   * Returns the first occurrence of the given item in the child list,
-   * or -1 if the item is not in the child list.
-   */
-  long indexOf(in nsIMetricsEventItem item);
-
-  /**
-   * Appends a child event item to this item.
-   */
-  void appendChild(in nsIMetricsEventItem item);
-
-  /**
-   * Inserts a child event item at a given index, moving later items
-   * up by one position.
-   *  @param item   The new item to insert 
-   *  @param index  The position in the array.  If the index is equal to
-   *                childCount, the new item will be appended.
-   *                The index may not be greater than childCount.
-   */
-  void insertChildAt(in nsIMetricsEventItem item, in long index);
-
-  /**
-   * Removes a child event item at the given index, moving all items
-   * stored at a higher position down one.
-   */
-  void removeChildAt(in long index);
-
-  /**
-   * Replaces a child event item at the given index.
-   *  @param newItem  The new item
-   *  @param index    The position of the item to be replaced
-   */
-  void replaceChildAt(in nsIMetricsEventItem newItem, in long index);
-
-  /**
-   * Clears all of the child items.
-   */
-  void clearChildren();
-
-  /**
-   * The number of child event items
-   */
-  readonly attribute long childCount;
-};
-
-[scriptable, uuid(0aad28fd-3478-4090-9730-0fff8c7683b5)]
-interface nsIMetricsService : nsISupports
-{
-  /**
-   * Creates a new EventItem object to hold event data.
-   * The event will not be logged until logEvent() is called.
-   *  @param itemNamespace   The new item's namespace
-   *  @param itemName        The new item's name
-   *
-   * @returns a new MetricsEventItem instance
-   */
-  nsIMetricsEventItem createEventItem(in DOMString itemNamespace,
-                                      in DOMString itemName);
-
-  /**
-   * Logs an event using the given EventItem.  The event is recorded with a
-   * timestamp generated at the time at which this method is called, and a
-   * session id for this instance of the application.  The keys "time" and
-   * "sessionid" are reserved for this data.
-   *
-   * @param item
-   *        The item to log.  This item and its entire tree of child items
-   *        will be logged as part of the event.
-   */
-  void logEvent(in nsIMetricsEventItem item);
-
-  /**
-   * Constructs and logs an EventItem, using the given namespace, event name,
-   * and event properties. This is a more convenient version of logEvent() for
-   * the case where there are no child EventItems.
-   *
-   * @see nsIMetricsEventItem
-   */
-  void logSimpleEvent(in DOMString eventNS, in DOMString event,
-                      in nsIPropertyBag eventValues);
-
-  /**
-   * Flush data to disk.
-   */
-  void flush();
-
-  /**
-   * Initiate the upload of the current event log.  This causes the current
-   * event log to be truncated once the upload completes.
-   */
-  void upload();
-
-  /**
-   * Suspend log collection.  LogEvent calls will be silently ignored while log
-   * collection is suspended.  For each call to suspend, resume must be called
-   * to re-enable log collection.
-   */
-  void suspend();
-
-  /**
-   * Resume log collection.  Call this method once per call to suspend to
-   * re-enable log collection.
-   */
-  void resume();
-
-  /**
-   * Gets a numeric window id corresponding to the given DOMWindow.
-   * The id remains constant for as long as the window exists.
-   */
-  unsigned long getWindowID(in nsIDOMWindow window);
-};
-
-%{C++
-/**
-  * Observer notifications
-  */
-
-/**
- * These work like NS[_CHROME]_WEBNAVIGATION_DESTROY, except that the
- * MetricsService is guaranteed to still know about the window which is being
- * destroyed (via getWindowID).  Collectors should use these notifications
- * instead of the docshell-provided ones.
- */
-#define NS_METRICS_WEBNAVIGATION_DESTROY "metrics-webnavigation-destroy"
-#define NS_METRICS_CHROME_WEBNAVIGATION_DESTROY \
-  "metrics-chrome-webnavigation-destroy"
-%}
deleted file mode 100644
--- a/extensions/metrics/public/nsMetricsModule.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Darin Fisher <darin@meer.net>
- *
- * 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 ***** */
-
-#ifndef nsMetricsModule_h__
-#define nsMetricsModule_h__
-
-#define NS_METRICSSERVICE_CLASSNAME "nsMetricsService"
-#define NS_METRICSSERVICE_CID                      \
-{ /* 45f190da-8e83-4389-8b42-6939417c3297 */       \
-  0x45f190da,                                      \
-  0x8e83,                                          \
-  0x4389,                                          \
-  {0x8b, 0x42, 0x69, 0x39, 0x41, 0x7c, 0x32, 0x97} \
-}
-#define NS_METRICSSERVICE_CONTRACTID "@mozilla.org/extensions/metrics/service;1"
-
-#endif  // nsMetricsModule_h__
deleted file mode 100644
--- a/extensions/metrics/skin/prefs.css
+++ /dev/null
@@ -1,18 +0,0 @@
-.prefs
-{
-  background     : white;
-  margin         : 5px 5px 0px 5px;
-  border         : 1px inset ThreeDFace;
-}
-
-.msg
-{
-  margin-left    : 4px;
-  margin-bottom  : 10px;
-}
-
-.cb
-{
-  margin-left    : 20px;
-}
-
deleted file mode 100644
--- a/extensions/metrics/src/Makefile.in
+++ /dev/null
@@ -1,91 +0,0 @@
-# vim:set ts=8 sw=8 sts=8 noet:
-# ***** 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 the Metrics extension.
-#
-# The Initial Developer of the Original Code is Google Inc.
-# Portions created by the Initial Developer are Copyright (C) 2006
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Darin Fisher <darin@meer.net>
-#
-# 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 *****
-
-DEPTH		= ../../..
-topsrcdir	= @top_srcdir@
-srcdir		= @srcdir@
-VPATH		= @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-MODULE		= metrics
-LIBRARY_NAME	= metrics_s
-SHORT_LIBNAME	= metrics_s
-
-XPI_NAME	= metrics
-
-
-CSRCS		= \
-		md5.c \
-		nssstubs.c \
-		$(NULL)
-
-CPPSRCS		= \
-		nsLoadCollector.cpp \
-		nsMetricsConfig.cpp \
-		nsMetricsEventItem.cpp \
-		nsMetricsService.cpp \
-		nsProfileCollector.cpp \
-		nsWindowCollector.cpp \
-		nsUICommandCollector.cpp \
-		nsAutoCompleteCollector.cpp \
-		nsStringUtils.cpp \
-		$(NULL)
-
-# Create a static library to link into the component library and unit tests
-FORCE_STATIC_LIB = 1
-
-# md5.c requires NSS headers
-LOCAL_INCLUDES = -I$(topsrcdir)/security/nss/lib/freebl
-
-# Link against the static CRT
-ifeq ($(OS_ARCH)_$(GNU_CC), WINNT_)
-USE_STATIC_LIBS = 1
-EXTRA_DSO_LDOPTS += -NODEFAULTLIB:MSVCRT \
-		    -NODEFAULTLIB:MSVCRTD \
-		    $(NULL)
-endif
-
-# Enable logging in release builds
-ifneq (,$(findstring -DMOZ_LOGGING=1, $(ACDEFINES)))
-DEFINES += -DFORCE_PR_LOG
-endif
-
-include $(topsrcdir)/config/rules.mk
-
-export:: $(topsrcdir)/security/nss/lib/freebl/md5.c
-	$(INSTALL) $^ .
deleted file mode 100644
--- a/extensions/metrics/src/nsAutoCompleteCollector.cpp
+++ /dev/null
@@ -1,219 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Brian Ryner <bryner@brianryner.com>
- *
- * 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 ***** */
-
-#include "nsAutoCompleteCollector.h"
-#include "nsMetricsService.h"
-
-#include "nsIObserverService.h"
-#include "nsIAutoCompleteController.h"
-#include "nsIAutoCompleteInput.h"
-#include "nsIAutoCompletePopup.h"
-#include "nsIDOMElement.h"
-#include "nsServiceManagerUtils.h"
-
-static const char kAutoCompleteTopic[] = "autocomplete-will-enter-text";
-
-nsAutoCompleteCollector::nsAutoCompleteCollector()
-{
-}
-
-nsAutoCompleteCollector::~nsAutoCompleteCollector()
-{
-}
-
-NS_IMPL_ISUPPORTS2(nsAutoCompleteCollector, nsIMetricsCollector, nsIObserver)
-
-NS_IMETHODIMP
-nsAutoCompleteCollector::OnAttach()
-{
-  nsCOMPtr<nsIObserverService> obsSvc =
-    do_GetService("@mozilla.org/observer-service;1");
-  NS_ENSURE_STATE(obsSvc);
-
-  nsresult rv = obsSvc->AddObserver(this, kAutoCompleteTopic, PR_FALSE);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsAutoCompleteCollector::OnDetach()
-{
-  nsCOMPtr<nsIObserverService> obsSvc =
-    do_GetService("@mozilla.org/observer-service;1");
-  NS_ENSURE_STATE(obsSvc);
-
-  nsresult rv = obsSvc->RemoveObserver(this, kAutoCompleteTopic);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsAutoCompleteCollector::OnNewLog()
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsAutoCompleteCollector::Observe(nsISupports *subject,
-                                 const char *topic,
-                                 const PRUnichar *data)
-{
-  if (strcmp(topic, kAutoCompleteTopic) != 0) {
-    MS_LOG(("Unexpected observer notification received: %s", topic));
-    return NS_ERROR_UNEXPECTED;
-  }
-
-  nsCOMPtr<nsIAutoCompleteInput> input = do_QueryInterface(subject);
-  if (!input) {
-    MS_LOG(("subject isn't an AutoCompleteInput"));
-    return NS_OK;
-  }
-
-  nsCOMPtr<nsIAutoCompletePopup> popup;
-  input->GetPopup(getter_AddRefs(popup));
-  if (!popup) {
-    MS_LOG(("AutoCompleteInput has no popup"));
-    return NS_OK;
-  }
-
-  PRBool open;
-  nsresult rv = popup->GetPopupOpen(&open);
-  NS_ENSURE_SUCCESS(rv, rv);
-  if (!open) {
-    MS_LOG(("AutoComplete popup is closed, not logging"));
-    return NS_OK;
-  }
-
-  PRInt32 selectedIndex;
-  rv = popup->GetSelectedIndex(&selectedIndex);
-  NS_ENSURE_SUCCESS(rv, rv);
-  if (selectedIndex == -1) {
-    MS_LOG(("popup has no selected index, not logging"));
-    return NS_OK;
-  }
-
-  nsString textValue;
-  rv = input->GetTextValue(textValue);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIAutoCompleteController> controller;
-  input->GetController(getter_AddRefs(controller));
-  NS_ENSURE_STATE(controller);
-
-  nsString completion;
-  rv = controller->GetValueAt(selectedIndex, completion);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIDOMElement> element = do_QueryInterface(subject);
-  if (!element) {
-    MS_LOG(("subject isn't a DOMElement"));
-    return NS_OK;
-  }
-
-  nsString id;
-  element->GetAttribute(NS_LITERAL_STRING("id"), id);
-  if (id.IsEmpty()) {
-    MS_LOG(("Warning: skipping logging because of empty target ID"));
-    return NS_OK;
-  }
-
-  // Fill a property bag for the <uielement> item
-  nsCOMPtr<nsIWritablePropertyBag2> properties;
-  nsMetricsUtils::NewPropertyBag(getter_AddRefs(properties));
-  NS_ENSURE_STATE(properties);
-
-  PRInt32 window = nsMetricsUtils::FindWindowForNode(element);
-  rv = properties->SetPropertyAsUint32(NS_LITERAL_STRING("window"), window);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = properties->SetPropertyAsAString(NS_LITERAL_STRING("action"),
-                                        NS_LITERAL_STRING("autocomplete"));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsMetricsService *ms = nsMetricsService::get();
-  NS_ENSURE_STATE(ms);
-
-  nsCString hashedId;
-  rv = ms->HashUTF16(id, hashedId);
-  NS_ENSURE_SUCCESS(rv, rv);
- 
-  rv = properties->SetPropertyAsACString(NS_LITERAL_STRING("targetidhash"),
-                                        hashedId);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIMetricsEventItem> item;
-  ms->CreateEventItem(NS_LITERAL_STRING("uielement"), getter_AddRefs(item));
-  NS_ENSURE_STATE(item);
-  item->SetProperties(properties);
-
-  // Now fill in the properties for the <autocomplete> child item
-  nsMetricsUtils::NewPropertyBag(getter_AddRefs(properties));
-  NS_ENSURE_STATE(properties);
-
-  rv = properties->SetPropertyAsUint32(NS_LITERAL_STRING("typedlength"),
-                                      textValue.Length());
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = properties->SetPropertyAsInt32(NS_LITERAL_STRING("selectedindex"),
-                                      selectedIndex);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = properties->SetPropertyAsInt32(NS_LITERAL_STRING("completedlength"),
-                                      completion.Length());
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = nsMetricsUtils::AddChildItem(item, NS_LITERAL_STRING("autocomplete"),
-                                    properties);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = ms->LogEvent(item);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  MS_LOG(("Logged autocomplete event:\n"
-          "  window id: %d\n"
-          "  target %s (hash=%s)\n"
-          "  typedlength: %d\n"
-          "  selectedindex: %d\n"
-          "  completedlength: %d",
-          window, NS_ConvertUTF16toUTF8(id).get(), hashedId.get(),
-          textValue.Length(), selectedIndex, completion.Length()));
-
-  return NS_OK;
-}
deleted file mode 100644
--- a/extensions/metrics/src/nsAutoCompleteCollector.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Brian Ryner <bryner@brianryner.com>
- *
- * 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 ***** */
-
-// nsAutoCompleteCollector listens for autocomplete events using the
-// observer service notification "autocomplete-text-entered".  The
-// AutoCompleteInput is examined to determine the autocomplete index,
-// and the length of typed and completed text.  The text itself is not logged.
-// This data, along with the hashed id of the AutoCompleteInput, is logged
-// to the MetricsService in a <uielement action="autocomplete"> event.
-
-#ifndef nsAutoCompleteCollector_h_
-#define nsAutoCompleteCollector_h_
-
-#include "nsIMetricsCollector.h"
-#include "nsIObserver.h"
-
-class nsAutoCompleteCollector : public nsIMetricsCollector,
-                                public nsIObserver
-{
- public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIMETRICSCOLLECTOR
-  NS_DECL_NSIOBSERVER
-
-  nsAutoCompleteCollector();
-
- private:
-  ~nsAutoCompleteCollector();
-};
-
-#define NS_AUTOCOMPLETECOLLECTOR_CLASSNAME "AutoComplete Collector"
-#define NS_AUTOCOMPLETECOLLECTOR_CID \
-{ 0x62cb877d, 0x5c8a, 0x44ca, {0xab, 0xcd, 0x1c, 0xaa, 0x76, 0x7c, 0xf4, 0xd4}}
-
-#endif  // nsAutoCompleteCollector_h_
deleted file mode 100644
--- a/extensions/metrics/src/nsLoadCollector.cpp
+++ /dev/null
@@ -1,547 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Brian Ryner <bryner@brianryner.com>
- *
- * 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 ***** */
-
-#include "nsLoadCollector.h"
-#include "nsMetricsService.h"
-#include "nsCOMPtr.h"
-#include "nsCURILoader.h"
-#include "nsIServiceManager.h"
-#include "nsIWebProgress.h"
-#include "nsIDocShell.h"
-#include "nsIDocShellTreeItem.h"
-#include "nsIChannel.h"
-#include "nsIDOMWindow.h"
-#include "nsIInterfaceRequestorUtils.h"
-#include "nsServiceManagerUtils.h"
-#include "nsIURI.h"
-#include "nsIDOMDocument.h"
-
-// Hack around internal string usage in nsIDocument.h on the branch
-#include "nsIDocument.h"
-
-// This is needed to gain access to the LOAD_ defines in this file.
-#define MOZILLA_INTERNAL_API
-#include "nsDocShellLoadTypes.h"
-#undef MOZILLA_INTERNAL_API
-
-//-----------------------------------------------------------------------------
-
-#if defined(__linux)
-#include <sys/types.h>
-#include <unistd.h>
-#include <stdio.h>
-static FILE *sProcFP;
-static void GetMemUsage_Shutdown() {
-  if (sProcFP) {
-    fclose(sProcFP);
-    sProcFP = NULL;
-  }
-}
-#elif defined(XP_WIN)
-#include <windows.h>
-#if _MSC_VER > 1200
-#include <psapi.h>
-#else
-typedef struct _PROCESS_MEMORY_COUNTERS {
-  DWORD cb;
-  DWORD PageFaultCount;
-  SIZE_T PeakWorkingSetSize;
-  SIZE_T WorkingSetSize;
-  SIZE_T QuotaPeakPagedPoolUsage;
-  SIZE_T QuotaPagedPoolUsage;
-  SIZE_T QuotaPeakNonPagedPoolUsage;
-  SIZE_T QuotaNonPagedPoolUsage;
-  SIZE_T PagefileUsage;
-  SIZE_T PeakPagefileUsage;
-} PROCESS_MEMORY_COUNTERS;
-typedef PROCESS_MEMORY_COUNTERS *PPROCESS_MEMORY_COUNTERS;
-#endif
-typedef BOOL (WINAPI * GETPROCESSMEMORYINFO_FUNC)(
-    HANDLE process, PPROCESS_MEMORY_COUNTERS counters, DWORD cb);
-static HMODULE sPSModule;
-static HANDLE sProcess;
-static GETPROCESSMEMORYINFO_FUNC sGetMemInfo;
-static void GetMemUsage_Shutdown() {
-  if (sProcess) {
-    CloseHandle(sProcess);
-    sProcess = NULL;
-  }
-  if (sPSModule) {
-    FreeLibrary(sPSModule);
-    sPSModule = NULL;
-  }
-  sGetMemInfo = NULL;
-}
-#elif defined(XP_MACOSX)
-#include <mach/mach.h>
-#include <mach/task.h>
-static void GetMemUsage_Shutdown() {
-}
-#endif
-
-struct MemUsage {
-  PRInt64 total;
-  PRInt64 resident;
-};
-
-// This method should be incorporated into NSPR
-static PRBool GetMemUsage(MemUsage *result)
-{
-  PRBool setResult = PR_FALSE;
-#if defined(__linux)
-  // Read /proc/<pid>/statm, and look at the first and second fields, which
-  // report the program size and the number of resident pages for this process,
-  // respectively.
- 
-  char buf[256];
-  if (!sProcFP) {
-    pid_t pid = getpid();
-    snprintf(buf, sizeof(buf), "/proc/%d/statm", pid);
-    sProcFP = fopen(buf, "rb");
-  }
-  if (sProcFP) {
-    int vmsize, vmrss;
-
-    int count = fscanf(sProcFP, "%d %d", &vmsize, &vmrss);
-    rewind(sProcFP);
-
-    if (count == 2) {
-      static int ps = getpagesize();
-      result->total = PRInt64(vmsize) * ps;
-      result->resident = PRInt64(vmrss) * ps;
-      setResult = PR_TRUE;
-    }
-  }
-#elif defined(XP_WIN)
-  // Use GetProcessMemoryInfo, which only works on WinNT and later.
-
-  if (!sGetMemInfo) {
-    sPSModule = LoadLibrary("psapi.dll");
-    if (sPSModule) {
-      sGetMemInfo = (GETPROCESSMEMORYINFO_FUNC)
-          GetProcAddress(sPSModule, "GetProcessMemoryInfo");
-      if (sGetMemInfo)
-        sProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
-                               FALSE, GetCurrentProcessId());
-      // Don't leave ourselves partially initialized.
-      if (!sProcess)
-        GetMemUsage_Shutdown();
-    }
-  }
-  if (sGetMemInfo) {
-    PROCESS_MEMORY_COUNTERS pmc;
-    if (sGetMemInfo(sProcess, &pmc, sizeof(pmc))) {
-      result->total = PRInt64(pmc.PagefileUsage);
-      result->resident = PRInt64(pmc.WorkingSetSize);
-      setResult = PR_TRUE;
-    }
-  }
-#elif defined(XP_MACOSX)
-  // Use task_info
-
-  task_basic_info_data_t ti;
-  mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;
-  kern_return_t error = task_info(mach_task_self(), TASK_BASIC_INFO,
-                                  (task_info_t) &ti, &count);
-  if (error == KERN_SUCCESS) {
-    result->total = PRInt64(ti.virtual_size);
-    result->resident = PRInt64(ti.resident_size);
-    setResult = PR_TRUE;
-  }
-#endif
-  return setResult;
-}
-
-//-----------------------------------------------------------------------------
-
-nsLoadCollector::nsLoadCollector()
-    : mNextDocID(0)
-{
-  mDocumentMap.Init(16);
-}
-
-nsLoadCollector::~nsLoadCollector()
-{
-  GetMemUsage_Shutdown();
-}
-
-NS_IMPL_ISUPPORTS5(nsLoadCollector, nsIMetricsCollector,
-                   nsIWebProgressListener, nsISupportsWeakReference,
-                   nsIDocumentObserver, nsIMutationObserver)
-
-NS_IMETHODIMP
-nsLoadCollector::OnStateChange(nsIWebProgress *webProgress,
-                               nsIRequest *request,
-                               PRUint32 flags,
-                               nsresult status)
-{
-  NS_ASSERTION(flags & STATE_IS_DOCUMENT,
-               "incorrect state change notification");
-
-#ifdef PR_LOGGING
-  if (MS_LOG_ENABLED()) {
-    nsCString name;
-    request->GetName(name);
-
-    MS_LOG(("LoadCollector: progress = %p, request = %p [%s], flags = %x, status = %x",
-            webProgress, request, name.get(), flags, status));
-  }
-#endif
-
-  nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
-  if (!channel) {
-    // We don't care about non-channel requests
-    return NS_OK;
-  }
-
-  nsresult rv;
-  if (flags & STATE_START) {
-    RequestEntry entry;
-    NS_ASSERTION(!mRequestMap.Get(request, &entry), "duplicate STATE_START");
-
-    nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(webProgress);
-    nsCOMPtr<nsIDOMWindow> window = do_GetInterface(docShell);
-    if (!window) {
-      // We don't really care about windowless loads
-      return NS_OK;
-    }
-
-    rv = nsMetricsUtils::NewPropertyBag(getter_AddRefs(entry.properties));
-    NS_ENSURE_SUCCESS(rv, rv);
-    nsIWritablePropertyBag2 *props = entry.properties;
-
-    rv = props->SetPropertyAsUint32(NS_LITERAL_STRING("window"),
-                                    nsMetricsService::GetWindowID(window));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    if (flags & STATE_RESTORING) {
-      rv = props->SetPropertyAsBool(NS_LITERAL_STRING("bfCacheHit"), PR_TRUE);
-      NS_ENSURE_SUCCESS(rv, rv);
-    }
-
-    nsString origin;
-    PRUint32 loadType;
-    docShell->GetLoadType(&loadType);
-
-    switch (loadType) {
-    case LOAD_NORMAL:
-    case LOAD_NORMAL_REPLACE:
-    case LOAD_BYPASS_HISTORY:
-      origin = NS_LITERAL_STRING("typed");
-      break;
-    case LOAD_NORMAL_EXTERNAL:
-      origin = NS_LITERAL_STRING("external");
-      break;
-    case LOAD_HISTORY:
-      origin = NS_LITERAL_STRING("session-history");
-      break;
-    case LOAD_RELOAD_NORMAL:
-    case LOAD_RELOAD_BYPASS_CACHE:
-    case LOAD_RELOAD_BYPASS_PROXY:
-    case LOAD_RELOAD_BYPASS_PROXY_AND_CACHE:
-    case LOAD_RELOAD_CHARSET_CHANGE:
-      origin = NS_LITERAL_STRING("reload");
-      break;
-    case LOAD_LINK:
-      origin = NS_LITERAL_STRING("link");
-      break;
-    case LOAD_REFRESH:
-      origin = NS_LITERAL_STRING("refresh");
-      break;
-    default:
-      break;
-    }
-    if (!origin.IsEmpty()) {
-      rv = props->SetPropertyAsAString(NS_LITERAL_STRING("origin"), origin);
-      NS_ENSURE_SUCCESS(rv, rv);
-    }
-    entry.startTime = PR_Now();
-    NS_ENSURE_TRUE(mRequestMap.Put(request, entry), NS_ERROR_OUT_OF_MEMORY);
-  } else if (flags & STATE_STOP) {
-    RequestEntry entry;
-    if (mRequestMap.Get(request, &entry)) {
-      mRequestMap.Remove(request);
-
-      // Log a <document action="load"> event
-      nsIWritablePropertyBag2 *props = entry.properties;
-      rv = props->SetPropertyAsACString(NS_LITERAL_STRING("action"),
-                                        NS_LITERAL_CSTRING("load"));
-      NS_ENSURE_SUCCESS(rv, rv);
-      
-      // Compute the load time now that we have the end time.
-      PRInt64 loadTime = (PR_Now() - entry.startTime) / PR_USEC_PER_MSEC;
-      rv = props->SetPropertyAsUint64(NS_LITERAL_STRING("loadtime"), loadTime);
-      NS_ENSURE_SUCCESS(rv, rv);
-
-      MemUsage mu;
-      if (GetMemUsage(&mu)) {
-        rv = props->SetPropertyAsUint64(NS_LITERAL_STRING("memtotal"), mu.total);
-        NS_ENSURE_SUCCESS(rv, rv);
-        rv = props->SetPropertyAsUint64(NS_LITERAL_STRING("memresident"), mu.resident);
-        NS_ENSURE_SUCCESS(rv, rv);
-      }
-
-      // Look up the document id, or assign a new one
-      nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(webProgress);
-      nsCOMPtr<nsIDOMWindow> window = do_GetInterface(docShell);
-      if (!window) {
-        MS_LOG(("Couldn't get window"));
-        return NS_ERROR_UNEXPECTED;
-      }
-
-      nsCOMPtr<nsIDOMDocument> domDoc;
-      window->GetDocument(getter_AddRefs(domDoc));
-      nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc);
-      if (!doc) {
-        MS_LOG(("Couldn't get document"));
-        return NS_ERROR_UNEXPECTED;
-      }
-
-      nsCOMPtr<nsIDocShellTreeItem> item = do_QueryInterface(docShell);
-      NS_ENSURE_STATE(item);
-      PRBool subframe = nsMetricsUtils::IsSubframe(item);
-      if (subframe) {
-        rv = props->SetPropertyAsBool(NS_LITERAL_STRING("subframe"), PR_TRUE);
-        NS_ENSURE_SUCCESS(rv, rv);
-      }
-
-      nsMetricsService *ms = nsMetricsService::get();
-      DocumentEntry docEntry;
-      if (!mDocumentMap.Get(doc, &docEntry)) {
-        docEntry.docID = mNextDocID++;
-        docEntry.subframe = subframe;
-
-        if (!ms->WindowMap().Get(window, &docEntry.windowID)) {
-          MS_LOG(("Window not in the window map"));
-          return NS_ERROR_UNEXPECTED;
-        }
-
-        NS_ENSURE_TRUE(mDocumentMap.Put(doc, docEntry),
-                       NS_ERROR_OUT_OF_MEMORY);
-      }
-      doc->AddObserver(this);  // set up to log the document destroy
-
-      rv = props->SetPropertyAsUint32(NS_LITERAL_STRING("docid"),
-                                      docEntry.docID);
-      NS_ENSURE_SUCCESS(rv, rv);
-
-      // If this was a load of a chrome document, hash the URL of the document
-      // so it can be identified.
-
-      nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
-      if (channel) {
-        nsCOMPtr<nsIURI> uri;
-        channel->GetURI(getter_AddRefs(uri));
-        if (uri) {
-          PRBool isChrome = PR_FALSE;
-          uri->SchemeIs("chrome", &isChrome);
-          if (isChrome) {
-            nsCString spec;
-            uri->GetSpec(spec);
-
-            nsCString hashedSpec;
-            rv = ms->HashUTF8(spec, hashedSpec);
-            NS_ENSURE_SUCCESS(rv, rv);
-
-            rv = props->SetPropertyAsACString(NS_LITERAL_STRING("urlhash"),
-                                              hashedSpec);
-            NS_ENSURE_SUCCESS(rv, rv);
-          }
-        }
-      }
-
-      rv = ms->LogEvent(NS_LITERAL_STRING("document"), props);
-      NS_ENSURE_SUCCESS(rv, rv);
-    } else {
-      NS_WARNING("STATE_STOP without STATE_START");
-    }
-  }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsLoadCollector::OnProgressChange(nsIWebProgress *webProgress,
-                                  nsIRequest *request,
-                                  PRInt32 curSelfProgress,
-                                  PRInt32 maxSelfProgress,
-                                  PRInt32 curTotalProgress,
-                                  PRInt32 maxTotalProgress)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsLoadCollector::OnLocationChange(nsIWebProgress *webProgress,
-                                  nsIRequest *request, nsIURI *location)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsLoadCollector::OnStatusChange(nsIWebProgress *webProgress,
-                                nsIRequest *request,
-                                nsresult status, const PRUnichar *messaage)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsLoadCollector::OnSecurityChange(nsIWebProgress *webProgress,
-                                  nsIRequest *request, PRUint32 state)
-{
-  return NS_OK;
-}
-
-nsresult
-nsLoadCollector::Init()
-{
-  NS_ENSURE_TRUE(mRequestMap.Init(32), NS_ERROR_OUT_OF_MEMORY);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsLoadCollector::OnAttach()
-{
-  // Attach the LoadCollector as a global web progress listener
-  nsCOMPtr<nsIWebProgress> progress =
-    do_GetService(NS_DOCUMENTLOADER_SERVICE_CONTRACTID);
-  NS_ENSURE_STATE(progress);
-  
-  nsresult rv = progress->AddProgressListener(
-      this, nsIWebProgress::NOTIFY_STATE_DOCUMENT);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-/* static */ PLDHashOperator
-nsLoadCollector::RemoveDocumentFromMap(const nsIDocument *document,
-                                       DocumentEntry &entry, void *userData)
-{
-  nsIDocument *mutable_doc = const_cast<nsIDocument*>(document);
-  mutable_doc->RemoveObserver(static_cast<nsLoadCollector*>(userData));
-  return PL_DHASH_REMOVE;
-}
-
-NS_IMETHODIMP
-nsLoadCollector::OnDetach()
-{
-  // Clear the request and document maps so we start fresh
-  // next time we're attached
-  mRequestMap.Clear();
-  mDocumentMap.Enumerate(RemoveDocumentFromMap, this);
-
-  // Remove the progress listener
-  nsCOMPtr<nsIWebProgress> progress =
-    do_GetService(NS_DOCUMENTLOADER_SERVICE_CONTRACTID);
-  NS_ENSURE_STATE(progress);
-  
-  nsresult rv = progress->RemoveProgressListener(this);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsLoadCollector::OnNewLog()
-{
-  return NS_OK;
-}
-
-NS_IMPL_NSIDOCUMENTOBSERVER_LOAD_STUB(nsLoadCollector)
-NS_IMPL_NSIDOCUMENTOBSERVER_STATE_STUB(nsLoadCollector)
-NS_IMPL_NSIDOCUMENTOBSERVER_CONTENT(nsLoadCollector)
-NS_IMPL_NSIDOCUMENTOBSERVER_STYLE_STUB(nsLoadCollector)
-
-void
-nsLoadCollector::BeginUpdate(nsIDocument *document, nsUpdateType updateType)
-{
-}
-
-void
-nsLoadCollector::EndUpdate(nsIDocument *document, nsUpdateType updateType)
-{
-}
-
-void
-nsLoadCollector::NodeWillBeDestroyed(const nsINode *node)
-{
-  const nsIDocument* document = static_cast<const nsIDocument*>(node);
-  // Look up the document to get its id.
-  DocumentEntry entry;
-  if (!mDocumentMap.Get(document, &entry)) {
-    MS_LOG(("Document not in map!"));
-    return;
-  }
-
-  mDocumentMap.Remove(document);
-
-  nsCOMPtr<nsIWritablePropertyBag2> props;
-  nsMetricsUtils::NewPropertyBag(getter_AddRefs(props));
-  if (!props) {
-    return;
-  }
-
-  props->SetPropertyAsACString(NS_LITERAL_STRING("action"),
-                               NS_LITERAL_CSTRING("destroy"));
-  props->SetPropertyAsUint32(NS_LITERAL_STRING("docid"), entry.docID);
-  props->SetPropertyAsUint32(NS_LITERAL_STRING("window"), entry.windowID);
-  if (entry.subframe) {
-    props->SetPropertyAsBool(NS_LITERAL_STRING("subframe"), PR_TRUE);
-  }
-
-  MemUsage mu;
-  if (GetMemUsage(&mu)) {
-    props->SetPropertyAsUint64(NS_LITERAL_STRING("memtotal"), mu.total);
-    props->SetPropertyAsUint64(NS_LITERAL_STRING("memresident"), mu.resident);
-  }
-
-  nsMetricsService *ms = nsMetricsService::get();
-  if (ms) {
-    ms->LogEvent(NS_LITERAL_STRING("document"), props);
-#ifdef PR_LOGGING
-    nsIURI *uri = document->GetDocumentURI();
-    if (uri) {
-      nsCString spec;
-      uri->GetSpec(spec);
-      MS_LOG(("LoadCollector: Logged document destroy for %s\n", spec.get()));
-    }
-#endif
-  }
-}
deleted file mode 100644
--- a/extensions/metrics/src/nsLoadCollector.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Brian Ryner <bryner@brianryner.com>
- *
- * 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 ***** */
-
-#ifndef nsLoadCollector_h_
-#define nsLoadCollector_h_
-
-// This file defines the load collector class, which monitors requests using
-// the document loader service and records the events into the metrics service.
-//
-// The load collector logs <document action="load"/> events.
-// This event has the following attributes:
-//
-// origin: The action which initiated the load (string).  Possible values are:
-//         "typed": The user typed or pasted the URI into the location bar.
-//         "link": The user followed a link to the URI.
-//         "reload": The user reloaded the URI.
-//         "refresh": A meta-refresh caused the URI to be loaded.
-//         "session-history": The user used back/forward to load the URI.
-//         "global-history": The user selected the URI from global history.
-//         "bookmark": The user selected the URI from bookmarks.
-//         "external": An external application passed in the URI to load.
-//         "other": Any origin not listed above.
-//
-// bfCacheHit: The document presentation was restored from the
-//             session history cache (boolean).
-//
-// window: The id of the window where the document loaded (uint16).
-// loadtime: The elapsed time for the load, in milliseconds (uint32).
-
-#include "nsIMetricsCollector.h"
-#include "nsIWebProgressListener.h"
-#include "nsIWritablePropertyBag2.h"
-#include "nsWeakReference.h"
-#include "nsDataHashtable.h"
-#include "nsAutoPtr.h"
-#include "nsIDocumentObserver.h"
-#include "nsPtrHashKey.h"
-
-class nsIDocument;
-
-class nsLoadCollector : public nsIMetricsCollector,
-                        public nsIWebProgressListener,
-                        public nsIDocumentObserver,
-                        public nsSupportsWeakReference
-{
- public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIMETRICSCOLLECTOR
-  NS_DECL_NSIWEBPROGRESSLISTENER
-  NS_DECL_NSIDOCUMENTOBSERVER
-
-  nsLoadCollector();
-  nsresult Init();
-
- private:
-  struct RequestEntry {
-    nsCOMPtr<nsIWritablePropertyBag2> properties;
-    PRTime startTime;
-  };
-
-  struct DocumentEntry {
-    PRUint32 docID;
-    PRUint32 windowID;
-    PRBool subframe;
-  };
-
-  ~nsLoadCollector();
-
-  // Callback for removing a document observer and map entry
-  static PLDHashOperator
-  RemoveDocumentFromMap(const nsIDocument *document,
-                        DocumentEntry &entry, void *userData);
-
-  // Hash table mapping nsIRequest objects to their event properties.
-  nsDataHashtable<nsISupportsHashKey, RequestEntry> mRequestMap;
-
-  // Documents we're currently listening to, and their associated ids
-  nsDataHashtable< nsPtrHashKey<nsIDocument>, DocumentEntry > mDocumentMap;
-
-  // The next document id we'll assign
-  PRUint32 mNextDocID;
-};
-
-#define NS_LOADCOLLECTOR_CLASSNAME "Load Collector"
-#define NS_LOADCOLLECTOR_CID \
-{ 0xa97357a0, 0xa2f3, 0x4b1f, {0x93, 0xd3, 0x36, 0xdc, 0xb7, 0xee, 0x24, 0x63}}
-
-#endif // nsLoadCollector_h_
deleted file mode 100644
--- a/extensions/metrics/src/nsMetricsConfig.cpp
+++ /dev/null
@@ -1,428 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Darin Fisher <darin@meer.net>
- *
- * 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 ***** */
-
-#include "nsMetricsService.h"
-#include "nsStringUtils.h"
-#include "nsIDOMDocument.h"
-#include "nsIDOMParser.h"
-#include "nsIDOMElement.h"
-#include "nsIDOM3Node.h"
-#include "nsIFileStreams.h"
-#include "nsILocalFile.h"
-#include "nsComponentManagerUtils.h"
-#include "nsNetCID.h"
-#include "prprf.h"
-#include "nsTArray.h"
-#include "nsIDOMSerializer.h"
-
-#define NS_DEFAULT_UPLOAD_INTERVAL_SEC 60 * 5
-
-//-----------------------------------------------------------------------------
-
-static const nsString
-MakeKey(const nsAString &eventNS, const nsAString &eventName)
-{
-  // Since eventName must be a valid XML NCName, we can use ':' to separate
-  // eventName from eventNS when formulating our hash key.
-  NS_ASSERTION(FindChar(eventName, ':') == -1, "Not a valid NCName");
-
-  nsString key;
-  key.Append(eventName);
-  key.Append(':');
-  key.Append(eventNS);
-  return key;
-}
-
-static void
-SplitKey(const nsString &key, nsString &eventNS, nsString &eventName)
-{
-  PRInt32 colon = FindChar(key, ':');
-  if (colon == -1) {
-    NS_ERROR("keys from MakeKey should always have a colon");
-    return;
-  }
-
-  eventName = Substring(key, 0, colon);
-  eventNS = Substring(key, colon + 1, key.Length() - colon - 1);
-}
-
-// This method leaves the result value unchanged if a parsing error occurs.
-static void
-ReadIntegerAttr(nsIDOMElement *elem, const nsAString &attrName, PRInt32 *result)
-{
-  nsString attrValue;
-  elem->GetAttribute(attrName, attrValue);
-
-  NS_ConvertUTF16toUTF8 attrValueUtf8(attrValue);
-  PR_sscanf(attrValueUtf8.get(), "%ld", result);
-}
-
-//-----------------------------------------------------------------------------
-
-nsMetricsConfig::nsMetricsConfig()
-{
-}
-
-PRBool
-nsMetricsConfig::Init()
-{
-  if (!mEventSet.Init() || !mNSURIToPrefixMap.Init()) {
-    return PR_FALSE;
-  }
-  Reset();
-  return PR_TRUE;
-}
-
-void
-nsMetricsConfig::Reset()
-{
-  // By default, we have no event limit, but all collectors are disabled
-  // until we're told by the server to enable them.
-  NS_ASSERTION(mEventSet.IsInitialized(), "nsMetricsConfig::Init not called");
-
-  mEventSet.Clear();
-  mNSURIToPrefixMap.Clear();
-  mEventLimit = PR_INT32_MAX;
-  mUploadInterval = NS_DEFAULT_UPLOAD_INTERVAL_SEC;
-  mHasConfig = PR_FALSE;
-}
-
-nsresult
-nsMetricsConfig::Load(nsIFile *file)
-{
-  // The given file references a XML file with the following structure:
-  //
-  // <response xmlns="http://www.mozilla.org/metrics">
-  //   <config xmlns:foo="http://foo.com/metrics">
-  //     <collectors>
-  //       <collector type="ui"/>
-  //       <collector type="document"/>
-  //       <collector type="window"/>
-  //       <collector type="foo:mystat"/>
-  //     </collectors>
-  //     <limit events="200"/>
-  //     <upload interval="600"/>
-  //   </config>
-  // </response>
-
-  NS_ASSERTION(mEventSet.IsInitialized(), "nsMetricsConfig::Init not called");
-
-  PRInt64 fileSize;
-  nsresult rv = file->GetFileSize(&fileSize);
-  NS_ENSURE_SUCCESS(rv, rv);
-  NS_ENSURE_STATE(fileSize <= PR_INT32_MAX);
-
-  nsCOMPtr<nsIFileInputStream> stream =
-      do_CreateInstance(NS_LOCALFILEINPUTSTREAM_CONTRACTID);
-  NS_ENSURE_STATE(stream);
-  rv = stream->Init(file, -1, -1, 0);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIDOMParser> parser = do_CreateInstance(NS_DOMPARSER_CONTRACTID);
-  NS_ENSURE_STATE(parser);
-
-  nsCOMPtr<nsIDOMDocument> doc;
-  parser->ParseFromStream(stream, nsnull, PRInt32(fileSize), "application/xml",
-                          getter_AddRefs(doc));
-  NS_ENSURE_STATE(doc);
-
-  // Now, walk the DOM.  Most elements are optional, but we check the root
-  // element to make sure it's a valid response document.
-  nsCOMPtr<nsIDOMElement> elem;
-  doc->GetDocumentElement(getter_AddRefs(elem));
-  NS_ENSURE_STATE(elem);
-
-  nsString nameSpace;
-  elem->GetNamespaceURI(nameSpace);
-  if (!nameSpace.Equals(NS_LITERAL_STRING(NS_METRICS_NAMESPACE))) {
-    // We have a root element, but it's the wrong namespace
-    return NS_ERROR_FAILURE;
-  }
-
-  nsString tag;
-  elem->GetLocalName(tag);
-  if (!tag.Equals(NS_LITERAL_STRING("response"))) {
-    // The root tag isn't what we're expecting
-    return NS_ERROR_FAILURE;
-  }
-
-  // At this point, we can clear our old configuration.
-  Reset();
-
-  ForEachChildElement(elem, &nsMetricsConfig::ProcessToplevelElement);
-  return NS_OK;
-}
-
-nsresult
-nsMetricsConfig::Save(nsILocalFile *file)
-{
-  nsCOMPtr<nsIDOMDocument> doc =
-    do_CreateInstance("@mozilla.org/xml/xml-document;1");
-  NS_ENSURE_STATE(doc);
-
-  nsCOMPtr<nsIDOMElement> response;
-  nsMetricsUtils::CreateElement(doc, NS_LITERAL_STRING("response"),
-                                getter_AddRefs(response));
-  NS_ENSURE_STATE(response);
-
-  nsCOMPtr<nsIDOMElement> config;
-  nsMetricsUtils::CreateElement(doc, NS_LITERAL_STRING("config"),
-                                getter_AddRefs(config));
-  NS_ENSURE_STATE(config);
-
-  nsCOMPtr<nsIDOMElement> collectors;
-  nsMetricsUtils::CreateElement(doc, NS_LITERAL_STRING("collectors"),
-                                getter_AddRefs(collectors));
-  NS_ENSURE_STATE(collectors);
-
-  nsTArray<nsString> events;
-  GetEvents(events);
-
-  nsCOMPtr<nsIDOMNode> nodeOut;
-  nsresult rv;
-
-  for (PRUint32 i = 0; i < events.Length(); ++i) {
-    nsString eventNS, eventName;
-    SplitKey(events[i], eventNS, eventName);
-
-    nsString prefix;
-    if (!eventNS.Equals(NS_LITERAL_STRING(NS_METRICS_NAMESPACE))) {
-      if (!mNSURIToPrefixMap.Get(eventNS, &prefix)) {
-        MS_LOG(("uri %s not in prefix map",
-                NS_ConvertUTF16toUTF8(eventNS).get()));
-        continue;
-      }
-
-      // Declare the namespace prefix on the root element
-      nsString attrName(NS_LITERAL_STRING("xmlns:"));
-      attrName.Append(prefix);
-      response->SetAttribute(attrName, eventNS);
-    }
-
-    nsCOMPtr<nsIDOMElement> collector;
-    nsMetricsUtils::CreateElement(doc, NS_LITERAL_STRING("collector"),
-                                  getter_AddRefs(collector));
-    NS_ENSURE_STATE(collector);
-
-    nsString shortName;
-    if (!prefix.IsEmpty()) {
-      shortName = prefix;
-      shortName.Append(':');
-    }
-    shortName.Append(eventName);
-
-    collector->SetAttribute(NS_LITERAL_STRING("type"), eventName);
-    collectors->AppendChild(collector, getter_AddRefs(nodeOut));
-  }
-  config->AppendChild(collectors, getter_AddRefs(nodeOut));
-
-  if (mEventLimit != PR_INT32_MAX) {
-    nsCOMPtr<nsIDOMElement> limit;
-    nsMetricsUtils::CreateElement(doc, NS_LITERAL_STRING("limit"),
-                                  getter_AddRefs(limit));
-    NS_ENSURE_STATE(limit);
-
-    nsString limitStr;
-    AppendInt(limitStr, mEventLimit);
-    limit->SetAttribute(NS_LITERAL_STRING("events"), limitStr);
-    config->AppendChild(limit, getter_AddRefs(nodeOut));
-  }
-
-  nsCOMPtr<nsIDOMElement> upload;
-  nsMetricsUtils::CreateElement(doc, NS_LITERAL_STRING("upload"),
-                                getter_AddRefs(upload));
-  NS_ENSURE_STATE(upload);
-
-  nsString intervalStr;
-  AppendInt(intervalStr, mUploadInterval);
-  upload->SetAttribute(NS_LITERAL_STRING("interval"), intervalStr);
-  config->AppendChild(upload, getter_AddRefs(nodeOut));
-
-  response->AppendChild(config, getter_AddRefs(nodeOut));
-
-  nsCOMPtr<nsIDOMSerializer> ds =
-    do_CreateInstance(NS_XMLSERIALIZER_CONTRACTID);
-  NS_ENSURE_STATE(ds);
-
-  nsString docText;
-  rv = ds->SerializeToString(response, docText);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  NS_ConvertUTF16toUTF8 utf8Doc(docText);
-  PRInt32 num = utf8Doc.Length();
-
-  PRFileDesc *fd;
-  rv = file->OpenNSPRFileDesc(
-      PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 0600, &fd);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  PRBool success = (PR_Write(fd, utf8Doc.get(), num) == num);
-  PR_Close(fd);
-
-  return success ? NS_OK : NS_ERROR_FAILURE;
-}
-
-void
-nsMetricsConfig::ForEachChildElement(nsIDOMElement *elem,
-                                     ForEachChildElementCallback callback)
-{
-  nsCOMPtr<nsIDOMNode> node, next;
-  elem->GetFirstChild(getter_AddRefs(node));
-  while (node) {
-    nsCOMPtr<nsIDOMElement> childElem = do_QueryInterface(node);
-    if (childElem) {
-      // Skip elements that are not in our namespace
-      nsString namespaceURI;
-      childElem->GetNamespaceURI(namespaceURI);
-      if (namespaceURI.Equals(NS_LITERAL_STRING(NS_METRICS_NAMESPACE)))
-        (this->*callback)(childElem);
-    }
-    node->GetNextSibling(getter_AddRefs(next));
-    node.swap(next);
-  }
-}
-
-void
-nsMetricsConfig::ProcessToplevelElement(nsIDOMElement *elem)
-{
-  // Process a top-level element
-
-  nsString name;
-  elem->GetLocalName(name);
-  if (name.Equals(NS_LITERAL_STRING("config"))) {
-    mHasConfig = PR_TRUE;
-    ForEachChildElement(elem, &nsMetricsConfig::ProcessConfigChild);
-  }
-}
-
-void
-nsMetricsConfig::ProcessConfigChild(nsIDOMElement *elem)
-{
-  // Process a config element child
-
-  nsString name;
-  elem->GetLocalName(name);
-  if (name.Equals(NS_LITERAL_STRING("collectors"))) {
-    // Enumerate <collector> elements
-    ForEachChildElement(elem, &nsMetricsConfig::ProcessCollectorElement);
-  } else if (name.Equals(NS_LITERAL_STRING("limit"))) {
-    ReadIntegerAttr(elem, NS_LITERAL_STRING("events"), &mEventLimit);
-  } else if (name.Equals(NS_LITERAL_STRING("upload"))) {
-    ReadIntegerAttr(elem, NS_LITERAL_STRING("interval"), &mUploadInterval);
-  }
-}
-
-void
-nsMetricsConfig::ProcessCollectorElement(nsIDOMElement *elem)
-{
-  // Make sure we are dealing with a <collector> element.
-  nsString localName;
-  elem->GetLocalName(localName);
-  if (!localName.Equals(NS_LITERAL_STRING("collector")))
-    return;
-
-  nsString type;
-  elem->GetAttribute(NS_LITERAL_STRING("type"), type);
-  if (type.IsEmpty())
-    return;
-
-  // Get the namespace URI specified by any prefix of |type|.
-  nsCOMPtr<nsIDOM3Node> node = do_QueryInterface(elem);
-  if (!node)
-    return;
-
-  // Check to see if this type references a specific namespace.
-  PRInt32 colon = FindChar(type, ':');
-
-  nsString namespaceURI;
-  if (colon == -1) {
-    node->LookupNamespaceURI(EmptyString(), namespaceURI);
-    // value is the EventName
-  } else {
-    // value is NamespacePrefix + ":" + EventName
-    nsString prefix(StringHead(type, colon));
-    node->LookupNamespaceURI(prefix, namespaceURI);
-    type.Cut(0, colon + 1);
-
-    // Add this namespace -> prefix mapping to our lookup table
-    mNSURIToPrefixMap.Put(namespaceURI, prefix);
-  }
-
-  mEventSet.PutEntry(MakeKey(namespaceURI, type));
-}
-
-PRBool
-nsMetricsConfig::IsEventEnabled(const nsAString &eventNS,
-                                const nsAString &eventName) const
-{
-  NS_ASSERTION(mEventSet.IsInitialized(), "nsMetricsConfig::Init not called");
-  return mEventSet.GetEntry(MakeKey(eventNS, eventName)) != nsnull;
-}
-
-void
-nsMetricsConfig::SetEventEnabled(const nsAString &eventNS,
-                                 const nsAString &eventName, PRBool enabled)
-{
-  NS_ASSERTION(mEventSet.IsInitialized(), "nsMetricsConfig::Init not called");
-  nsString key = MakeKey(eventNS, eventName);
-  if (enabled) {
-    mEventSet.PutEntry(key);
-  } else {
-    mEventSet.RemoveEntry(key);
-  }
-}
-
-void
-nsMetricsConfig::ClearEvents()
-{
-  NS_ASSERTION(mEventSet.IsInitialized(), "nsMetricsConfig::Init not called");
-  mEventSet.Clear();
-}
-
-/* static */ PLDHashOperator
-nsMetricsConfig::CopyKey(nsStringHashKey *entry, void *userData)
-{
-  static_cast<nsTArray<nsString> *>(userData)->
-    AppendElement(entry->GetKey());
-  return PL_DHASH_NEXT;
-}
-
-void
-nsMetricsConfig::GetEvents(nsTArray<nsString> &events) {
-  mEventSet.EnumerateEntries(CopyKey, &events);
-}
deleted file mode 100644
--- a/extensions/metrics/src/nsMetricsConfig.h
+++ /dev/null
@@ -1,164 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Darin Fisher <darin@meer.net>
- *
- * 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 ***** */
-
-#ifndef nsMetricsConfig_h__
-#define nsMetricsConfig_h__
-
-#include "nsDataHashtable.h"
-#include "nsHashKeys.h"
-
-class nsIDOMElement;
-class nsIFile;
-class nsILocalFile;
-template<class E> class nsTArray;
-
-class nsMetricsConfig
-{
-public:
-  nsMetricsConfig();
-  ~nsMetricsConfig() {}
-
-  /**
-   * This method must be called before using an instance of this class.
-   */
-  PRBool Init();
-
-  /**
-   * Restore the default configuration.
-   */
-  void Reset();
-
-  /**
-   * Load the metrics configuration from disk.
-   */
-  nsresult Load(nsIFile *file);
-
-  /**
-   * Writes the current metrics configuration to disk.
-   */
-  nsresult Save(nsILocalFile *file);
-
-  /**
-   * Call this method to determine if the given event type is enabled for
-   * collection.
-   */
-  PRBool IsEventEnabled(const nsAString &eventNS,
-                        const nsAString &eventName) const;
-
-  /**
-   * Sets a particular event to be enabled or disabled.
-   */
-  void SetEventEnabled(const nsAString &eventNS,
-                       const nsAString &eventName, PRBool enabled);
-
-  /**
-   * Call this method to get a list of all events that are enabled.
-   * The event names are prefixed with the namespace, separated by a colon.
-   */
-  void GetEvents(nsTArray<nsString> &events);
-
-  /**
-   * Clears the set of events in this config.
-   */
-  void ClearEvents();
-
-  /**
-   * Get the limit on the number of events that should be collected.
-   */
-  PRInt32 EventLimit() const {
-    NS_ASSERTION(mEventSet.IsInitialized(),
-                 "nsMetricsConfig::Init not called");
-    return mEventLimit;
-  }
-
-  /**
-   * Sets the event limit.
-   */
-  void SetEventLimit(PRInt32 limit) {
-    NS_ASSERTION(mEventSet.IsInitialized(),
-                 "nsMetricsConfig::Init not called");
-    mEventLimit = limit;
-  }
-
-  /**
-   * Get the upload interval (measured in seconds).
-   */
-  PRInt32 UploadInterval() const {
-    NS_ASSERTION(mEventSet.IsInitialized(),
-                 "nsMetricsConfig::Init not called");
-    return mUploadInterval;
-  }
-
-  /**
-   * Set the upload interval (measured in seconds).
-   */
-  void SetUploadInterval(PRInt32 uploadInterval) {
-    NS_ASSERTION(mEventSet.IsInitialized(),
-                 "nsMetricsConfig::Init not called");
-    mUploadInterval = uploadInterval;
-  }
-
-  /**
-   * Returns true if there was a <config> present in the response.
-   */
-  PRBool HasConfig() const {
-    NS_ASSERTION(mEventSet.IsInitialized(),
-                 "nsMetricsConfig::Init not called");
-    return mHasConfig;
-  }
-
-private:
-  typedef void (nsMetricsConfig::*ForEachChildElementCallback)(nsIDOMElement *);
-
-  // Run a callback method for each child element of the given element.
-  void ForEachChildElement(nsIDOMElement *elem, ForEachChildElementCallback cb);
-
-  void ProcessToplevelElement(nsIDOMElement *elem);
-  void ProcessConfigChild(nsIDOMElement *elem);
-  void ProcessCollectorElement(nsIDOMElement *elem);
-
-  static PLDHashOperator CopyKey(nsStringHashKey *key, void *userData);
-
-  nsTHashtable<nsStringHashKey> mEventSet;
-  nsDataHashtable<nsStringHashKey,nsString> mNSURIToPrefixMap;
-  PRInt32 mEventLimit;
-  PRInt32 mUploadInterval;
-  PRBool mHasConfig;
-};
-
-#endif  // nsMetricsConfig_h__
deleted file mode 100644
--- a/extensions/metrics/src/nsMetricsEventItem.cpp
+++ /dev/null
@@ -1,153 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Brian Ryner <bryner@brianryner.com>
- *
- * 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 ***** */
-
-#include "nsMetricsEventItem.h"
-#include "nsIPropertyBag.h"
-
-nsMetricsEventItem::nsMetricsEventItem(const nsAString &itemNamespace,
-                                       const nsAString &itemName)
-    : mNamespace(itemNamespace), mName(itemName)
-{
-}
-
-nsMetricsEventItem::~nsMetricsEventItem()
-{
-}
-
-NS_IMPL_ISUPPORTS1(nsMetricsEventItem, nsIMetricsEventItem)
-
-NS_IMETHODIMP
-nsMetricsEventItem::GetItemNamespace(nsAString &result)
-{
-  result = mNamespace;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsEventItem::GetItemName(nsAString &result)
-{
-  result = mName;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsEventItem::GetProperties(nsIPropertyBag **aProperties)
-{
-  NS_IF_ADDREF(*aProperties = mProperties);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsEventItem::SetProperties(nsIPropertyBag *aProperties)
-{
-  // This do_QueryInterface() shouldn't be necessary, but is needed to avoid
-  // assertions from nsCOMPtr when an nsIWritablePropertyBag2 is passed in.
-  mProperties = do_QueryInterface(aProperties);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsEventItem::ChildAt(PRInt32 index, nsIMetricsEventItem **result)
-{
-  NS_ENSURE_ARG_RANGE(index, 0, PRInt32(mChildren.Length()) - 1);
-
-  NS_ADDREF(*result = mChildren[index]);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsEventItem::IndexOf(nsIMetricsEventItem *item, PRInt32 *result)
-{
-  *result = PRInt32(mChildren.IndexOf(item));  // NoIndex mapped to -1
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsEventItem::AppendChild(nsIMetricsEventItem *item)
-{
-  NS_ENSURE_ARG_POINTER(item);
-
-  NS_ENSURE_TRUE(mChildren.AppendElement(item), NS_ERROR_OUT_OF_MEMORY);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsEventItem::InsertChildAt(nsIMetricsEventItem *item, PRInt32 index)
-{
-  NS_ENSURE_ARG_POINTER(item);
-
-  // allow appending
-  NS_ENSURE_ARG_RANGE(index, 0, PRInt32(mChildren.Length()));
-
-  NS_ENSURE_TRUE(mChildren.InsertElementAt(index, item),
-                 NS_ERROR_OUT_OF_MEMORY);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsEventItem::RemoveChildAt(PRInt32 index)
-{
-  NS_ENSURE_ARG_RANGE(index, 0, PRInt32(mChildren.Length()) - 1);
-
-  mChildren.RemoveElementAt(index);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsEventItem::ReplaceChildAt(nsIMetricsEventItem *newItem, PRInt32 index)
-{
-  NS_ENSURE_ARG_POINTER(newItem);
-  NS_ENSURE_ARG_RANGE(index, 0, PRInt32(mChildren.Length()) - 1);
-
-  mChildren.ReplaceElementsAt(index, 1, newItem);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsEventItem::ClearChildren()
-{
-  mChildren.Clear();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsEventItem::GetChildCount(PRInt32 *childCount)
-{
-  *childCount = PRInt32(mChildren.Length());
-  return NS_OK;
-}
deleted file mode 100644
--- a/extensions/metrics/src/nsMetricsEventItem.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Brian Ryner <bryner@brianryner.com>
- *
- * 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 ***** */
-
-#ifndef nsMetricsEventItem_h__
-#define nsMetricsEventItem_h__
-
-#include "nsIMetricsService.h"
-#include "nsTArray.h"
-#include "nsCOMPtr.h"
-#include "nsStringAPI.h"
-
-class nsIPropertyBag;
-
-// nsMetricsEventItem implements a single event item that can store properties.
-
-class nsMetricsEventItem : public nsIMetricsEventItem
-{
- public:
-  nsMetricsEventItem(const nsAString &itemNamespace,
-                     const nsAString &itemName);
-
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIMETRICSEVENTITEM
-
- private:
-  ~nsMetricsEventItem();
-
-  nsString mNamespace;
-  nsString mName;
-  nsCOMPtr<nsIPropertyBag> mProperties;
-  nsTArray< nsCOMPtr<nsIMetricsEventItem> > mChildren;
-};
-
-#endif  // nsMetricsEventItem_h__
deleted file mode 100644
--- a/extensions/metrics/src/nsMetricsService.cpp
+++ /dev/null
@@ -1,1691 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Darin Fisher <darin@meer.net>
- *
- * 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 ***** */
-
-#include "nsMetricsService.h"
-#include "nsMetricsEventItem.h"
-#include "nsIMetricsCollector.h"
-#include "nsStringUtils.h"
-#include "nsXPCOM.h"
-#include "nsServiceManagerUtils.h"
-#include "nsComponentManagerUtils.h"
-#include "nsIFile.h"
-#include "nsDirectoryServiceUtils.h"
-#include "nsAppDirectoryServiceDefs.h"
-#include "nsNetCID.h"
-#include "nsIObserverService.h"
-#include "nsIUploadChannel.h"
-#include "nsIPrefService.h"
-#include "nsIPrefBranch2.h"
-#include "nsIObserver.h"
-#include "nsILocalFile.h"
-#include "nsIPropertyBag.h"
-#include "nsIProperty.h"
-#include "nsIVariant.h"
-#include "nsIDOMElement.h"
-#include "nsIDOMDocument.h"
-#include "nsIDOMSerializer.h"
-#include "nsIVariant.h"
-#include "blapi.h"
-#include "plbase64.h"
-#include "nsISimpleEnumerator.h"
-#include "nsIInputStreamChannel.h"
-#include "nsIFileStreams.h"
-#include "nsIBufferedStreams.h"
-#include "nsIHttpChannel.h"
-#include "nsIHttpProtocolHandler.h"
-#include "nsIIOService.h"
-#include "nsMultiplexInputStream.h"
-#include "prtime.h"
-#include "prmem.h"
-#include "prprf.h"
-#include "prrng.h"
-#include "bzlib.h"
-#include "nsIClassInfoImpl.h"
-#include "nsIDocShellTreeItem.h"
-#include "nsDocShellCID.h"
-#include "nsMemory.h"
-#include "nsIInterfaceRequestor.h"
-#include "nsIInterfaceRequestorUtils.h"
-#include "nsIX509Cert.h"
-#include "nsAutoPtr.h"
-#include "nsIDOMWindow.h"
-#include "nsIDOMDocumentView.h"
-#include "nsIDOMAbstractView.h"
-
-// We need to suppress inclusion of nsString.h
-#define nsString_h___
-#include "nsIStringStream.h"
-#undef nsString_h___
-
-// Make our MIME type inform the server of possible compression.
-#ifdef NS_METRICS_SEND_UNCOMPRESSED_DATA
-#define NS_METRICS_MIME_TYPE "application/vnd.mozilla.metrics"
-#else
-#define NS_METRICS_MIME_TYPE "application/vnd.mozilla.metrics.bz2"
-#endif
-
-// Flush the event log whenever its size exceeds this number of events.
-#define NS_EVENTLOG_FLUSH_POINT 64
-
-#define NS_SECONDS_PER_DAY (60 * 60 * 24)
-
-nsMetricsService* nsMetricsService::sMetricsService = nsnull;
-#ifdef PR_LOGGING
-PRLogModuleInfo *gMetricsLog;
-#endif
-
-static const char kQuitApplicationTopic[] = "quit-application";
-static const char kUploadTimePref[] = "extensions.mozilla.metrics.upload.next-time";
-static const char kPingTimePref[] = "extensions.mozilla.metrics.upload.next-ping";
-static const char kEventCountPref[] = "extensions.mozilla.metrics.event-count";
-static const char kEnablePref[] = "extensions.mozilla.metrics.upload.enable";
-
-const PRUint32 nsMetricsService::kMaxRetries = 3;
-const PRUint32 nsMetricsService::kMetricsVersion = 2;
-
-//-----------------------------------------------------------------------------
-
-#ifndef NS_METRICS_SEND_UNCOMPRESSED_DATA
-
-// Compress data read from |src|, and write to |outFd|.
-static nsresult
-CompressBZ2(nsIInputStream *src, PRFileDesc *outFd)
-{
-  // compress the data chunk-by-chunk
-
-  char inbuf[4096], outbuf[4096];
-  bz_stream strm;
-  int ret = BZ_OK;
-
-  memset(&strm, 0, sizeof(strm));
-
-  if (BZ2_bzCompressInit(&strm, 9 /*max blocksize*/, 0, 0) != BZ_OK)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  nsresult rv = NS_OK;
-  int action = BZ_RUN;
-  for (;;) {
-    PRUint32 bytesRead = 0;
-    if (action == BZ_RUN && strm.avail_in == 0) {
-      // fill inbuf
-      rv = src->Read(inbuf, sizeof(inbuf), &bytesRead);
-      if (NS_FAILED(rv))
-        break;
-      strm.next_in = inbuf;
-      strm.avail_in = (int) bytesRead;
-    }
-
-    strm.next_out = outbuf;
-    strm.avail_out = sizeof(outbuf);
-
-    ret = BZ2_bzCompress(&strm, action);
-    if (action == BZ_RUN) {
-      if (ret != BZ_RUN_OK) {
-        MS_LOG(("BZ2_bzCompress/RUN failed: %d", ret));
-        rv = NS_ERROR_UNEXPECTED;
-        break;
-      }
-
-      if (bytesRead < sizeof(inbuf)) {
-        // We're done now, tell libbz2 to finish
-        action = BZ_FINISH;
-      }
-    } else if (ret != BZ_FINISH_OK && ret != BZ_STREAM_END) {
-      MS_LOG(("BZ2_bzCompress/FINISH failed: %d", ret));
-      rv = NS_ERROR_UNEXPECTED;
-      break;
-    }
-
-    if (strm.avail_out < sizeof(outbuf)) {
-      PRInt32 n = sizeof(outbuf) - strm.avail_out;
-      if (PR_Write(outFd, outbuf, n) != n) {
-        MS_LOG(("Failed to write compressed file"));
-        rv = NS_ERROR_UNEXPECTED;
-        break;
-      }
-    }
-
-    if (ret == BZ_STREAM_END)
-      break;
-  }
-
-  BZ2_bzCompressEnd(&strm);
-  return rv;
-}
-
-#endif // !defined(NS_METRICS_SEND_UNCOMPRESSED_DATA)
-
-//-----------------------------------------------------------------------------
-
-nsMetricsService::nsMetricsService()  
-    : mMD5Context(nsnull),
-      mEventCount(0),
-      mSuspendCount(0),
-      mUploading(PR_FALSE),
-      mNextWindowID(0),
-      mRetryCount(0)
-{
-  NS_ASSERTION(!sMetricsService, ">1 MetricsService object created");
-  sMetricsService = this;
-}
-
-/* static */ PLDHashOperator
-nsMetricsService::DetachCollector(const nsAString &key,
-                                  nsIMetricsCollector *value, void *userData)
-{
-  value->OnDetach();
-  return PL_DHASH_NEXT;
-}
-
-nsMetricsService::~nsMetricsService()
-{
-  NS_ASSERTION(sMetricsService == this, ">1 MetricsService object created");
-
-  mCollectorMap.EnumerateRead(DetachCollector, nsnull);
-  MD5_DestroyContext(mMD5Context, PR_TRUE);
-
-  sMetricsService = nsnull;
-}
-
-NS_IMPL_ISUPPORTS6_CI(nsMetricsService, nsIMetricsService, nsIAboutModule,
-                      nsIStreamListener, nsIRequestObserver, nsIObserver,
-                      nsITimerCallback)
-
-NS_IMETHODIMP
-nsMetricsService::CreateEventItem(const nsAString &itemNamespace,
-                                  const nsAString &itemName,
-                                  nsIMetricsEventItem **result)
-{
-  *result = nsnull;
-
-  nsMetricsEventItem *item = new nsMetricsEventItem(itemNamespace, itemName);
-  NS_ENSURE_TRUE(item, NS_ERROR_OUT_OF_MEMORY);
-
-  NS_ADDREF(*result = item);
-  return NS_OK;
-}
-
-nsresult
-nsMetricsService::BuildEventItem(nsIMetricsEventItem *item,
-                                 nsIDOMElement **itemElement)
-{
-  *itemElement = nsnull;
-
-  nsString itemNS, itemName;
-  item->GetItemNamespace(itemNS);
-  item->GetItemName(itemName);
-
-  nsCOMPtr<nsIDOMElement> element;
-  nsresult rv = mDocument->CreateElementNS(itemNS, itemName,
-                                           getter_AddRefs(element));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // Attach the given properties as attributes.
-  nsCOMPtr<nsIPropertyBag> properties;
-  item->GetProperties(getter_AddRefs(properties));
-  if (properties) {
-    nsCOMPtr<nsISimpleEnumerator> enumerator;
-    rv = properties->GetEnumerator(getter_AddRefs(enumerator));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    nsCOMPtr<nsISupports> propertySupports;
-    while (NS_SUCCEEDED(
-               enumerator->GetNext(getter_AddRefs(propertySupports)))) {
-      nsCOMPtr<nsIProperty> property = do_QueryInterface(propertySupports);
-      if (!property) {
-        NS_WARNING("PropertyBag enumerator has non-nsIProperty elements");
-        continue;
-      }
-
-      nsString name;
-      rv = property->GetName(name);
-      if (NS_FAILED(rv)) {
-        NS_WARNING("Failed to get property name");
-        continue;
-      }
-
-      nsCOMPtr<nsIVariant> value;
-      rv = property->GetValue(getter_AddRefs(value));
-      if (NS_FAILED(rv) || !value) {
-        NS_WARNING("Failed to get property value");
-        continue;
-      }
-
-      // If the type is boolean, we want to use the strings "true" and "false",
-      // rather than "1" and "0" which is what nsVariant generates on its own.
-      PRUint16 dataType;
-      value->GetDataType(&dataType);
-
-      nsString valueString;
-      if (dataType == nsIDataType::VTYPE_BOOL) {
-        PRBool valueBool;
-        rv = value->GetAsBool(&valueBool);
-        if (NS_FAILED(rv)) {
-          NS_WARNING("Variant has bool type but couldn't get bool value");
-          continue;
-        }
-        valueString = valueBool ? NS_LITERAL_STRING("true")
-                      : NS_LITERAL_STRING("false");
-      } else {
-        rv = value->GetAsDOMString(valueString);
-        if (NS_FAILED(rv)) {
-          NS_WARNING("Failed to convert property value to string");
-          continue;
-        }
-      }
-
-      rv = element->SetAttribute(name, valueString);
-      if (NS_FAILED(rv)) {
-        NS_WARNING("Failed to set attribute value");
-      }
-      continue;
-    }
-  }
-
-  // Now recursively build the child event items
-  PRInt32 childCount = 0;
-  item->GetChildCount(&childCount);
-  for (PRInt32 i = 0; i < childCount; ++i) {
-    nsCOMPtr<nsIMetricsEventItem> childItem;
-    item->ChildAt(i, getter_AddRefs(childItem));
-    NS_ASSERTION(childItem, "The child list cannot contain null items");
-
-    nsCOMPtr<nsIDOMElement> childElement;
-    rv = BuildEventItem(childItem, getter_AddRefs(childElement));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    nsCOMPtr<nsIDOMNode> nodeReturn;
-    rv = element->AppendChild(childElement, getter_AddRefs(nodeReturn));
-    NS_ENSURE_SUCCESS(rv, rv);
-  }
-
-  element.swap(*itemElement);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsService::LogEvent(nsIMetricsEventItem *item)
-{
-  NS_ENSURE_ARG_POINTER(item);
-
-  if (mSuspendCount != 0)  // Ignore events while suspended
-    return NS_OK;
-
-  // Restrict the number of events logged
-  if (mEventCount >= mConfig.EventLimit())
-    return NS_OK;
-
-  // Restrict the types of events logged
-  nsString eventNS, eventName;
-  item->GetItemNamespace(eventNS);
-  item->GetItemName(eventName);
-
-  if (!mConfig.IsEventEnabled(eventNS, eventName))
-    return NS_OK;
-
-  // Create a DOM element for the event and append it to our document.
-  nsCOMPtr<nsIDOMElement> eventElement;
-  nsresult rv = BuildEventItem(item, getter_AddRefs(eventElement));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // Add the event timestamp
-  nsString timeString;
-  AppendInt(timeString, PR_Now() / PR_USEC_PER_SEC);
-  rv = eventElement->SetAttribute(NS_LITERAL_STRING("time"), timeString);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // Add the session id
-  rv = eventElement->SetAttribute(NS_LITERAL_STRING("session"), mSessionID);
-  NS_ENSURE_SUCCESS(rv, rv);
-  
-  nsCOMPtr<nsIDOMNode> outChild;
-  rv = mRoot->AppendChild(eventElement, getter_AddRefs(outChild));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // Flush event log to disk if it has grown too large
-  if ((++mEventCount % NS_EVENTLOG_FLUSH_POINT) == 0)
-    Flush();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsService::LogSimpleEvent(const nsAString &eventNS,
-                                 const nsAString &eventName,
-                                 nsIPropertyBag *eventProperties)
-{
-  NS_ENSURE_ARG_POINTER(eventProperties);
-
-  nsCOMPtr<nsIMetricsEventItem> item;
-  nsresult rv = CreateEventItem(eventNS, eventName, getter_AddRefs(item));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  item->SetProperties(eventProperties);
-  return LogEvent(item);
-}
-
-NS_IMETHODIMP
-nsMetricsService::Flush()
-{
-  nsresult rv;
-
-  PRFileDesc *fd;
-  rv = OpenDataFile(PR_WRONLY | PR_APPEND | PR_CREATE_FILE, &fd);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // Serialize our document, then strip off the root start and end tags,
-  // and write it out.
-
-  nsCOMPtr<nsIDOMSerializer> ds =
-    do_CreateInstance(NS_XMLSERIALIZER_CONTRACTID);
-  NS_ENSURE_TRUE(ds, NS_ERROR_UNEXPECTED);
-
-  nsString docText;
-  rv = ds->SerializeToString(mRoot, docText);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // The first '>' will be the end of the root start tag.
-  docText.Cut(0, FindChar(docText, '>') + 1);
-
-  // The last '<' will be the beginning of the root end tag.
-  PRInt32 start = RFindChar(docText, '<');
-  docText.Cut(start, docText.Length() - start);
-
-  NS_ConvertUTF16toUTF8 utf8Doc(docText);
-  PRInt32 num = utf8Doc.Length();
-  PRBool succeeded = ( PR_Write(fd, utf8Doc.get(), num) == num );
-
-  PR_Close(fd);
-  NS_ENSURE_STATE(succeeded);
-
-  // Write current event count to prefs
-  NS_ENSURE_STATE(PersistEventCount());
-
-  // Create a new mRoot
-  rv = CreateRoot();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsService::Upload()
-{
-  if (mUploading) {
-    // Ignore new uploads issued while uploading.
-    MS_LOG(("Upload already in progress, aborting"));
-    return NS_OK;
-  }
-
-  // If we don't have anything to upload, then don't upload, unless
-  // the time given by the next-ping pref has passed.
-  if (mEventCount == 0) {
-    nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
-    NS_ENSURE_STATE(prefs);
-
-    PRInt32 pingTime_sec;
-    if (NS_SUCCEEDED(prefs->GetIntPref(kPingTimePref, &pingTime_sec))) {
-      PRInt32 now_sec = PRInt32(PR_Now() / PR_USEC_PER_SEC);
-      if (now_sec < pingTime_sec) {
-        // No need to upload yet, just reset our timer
-        MS_LOG(("Suppressing upload while idle"));
-        InitUploadTimer(PR_FALSE);
-        return NS_OK;
-      }
-    }
-  }
-
-  // XXX Download filtering rules and apply them.
-
-  nsresult rv = Flush();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = UploadData();
-  if (NS_SUCCEEDED(rv))
-    mUploading = PR_TRUE;
-
-  // We keep the original data file until we know we've uploaded
-  // successfully, or get a 4xx (bad request) response from the server.
-
-  // Reset event count and persist.
-  mEventCount = 0;
-  NS_ENSURE_STATE(PersistEventCount());
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsService::Suspend()
-{
-  mSuspendCount++;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsService::Resume()
-{
-  if (mSuspendCount > 0)
-    mSuspendCount--;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsService::NewChannel(nsIURI *uri, nsIChannel **result)
-{
-  nsresult rv = Flush();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsILocalFile> dataFile;
-  GetDataFile(&dataFile);
-  NS_ENSURE_STATE(dataFile);
-
-  nsCOMPtr<nsIInputStreamChannel> streamChannel =
-      do_CreateInstance(NS_INPUTSTREAMCHANNEL_CONTRACTID);
-  NS_ENSURE_STATE(streamChannel);
-
-  rv = streamChannel->SetURI(uri);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIChannel> channel = do_QueryInterface(streamChannel, &rv);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  PRBool val;
-  if (NS_SUCCEEDED(dataFile->Exists(&val)) && val) {
-    nsCOMPtr<nsIInputStream> stream;
-    OpenCompleteXMLStream(dataFile, getter_AddRefs(stream));
-    NS_ENSURE_STATE(stream);
-
-    rv  = streamChannel->SetContentStream(stream);
-    rv |= channel->SetContentType(NS_LITERAL_CSTRING("text/xml"));
-  } else {
-    nsCOMPtr<nsIStringInputStream> errorStream =
-        do_CreateInstance("@mozilla.org/io/string-input-stream;1");
-    NS_ENSURE_STATE(errorStream);
-
-    rv = errorStream->SetData("no metrics data", -1);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    rv  = streamChannel->SetContentStream(errorStream);
-    rv |= channel->SetContentType(NS_LITERAL_CSTRING("text/plain"));
-  }
-
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
-
-  NS_ADDREF(*result = channel);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsService::GetURIFlags(nsIURI *aURI, PRUint32 *result)
-{
-    *result = 0;
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsService::OnStartRequest(nsIRequest *request, nsISupports *context)
-{
-  NS_ENSURE_STATE(!mConfigOutputStream);
-
-  nsCOMPtr<nsIFile> file;
-  GetConfigTempFile(getter_AddRefs(file));
-
-  nsCOMPtr<nsIFileOutputStream> out =
-      do_CreateInstance(NS_LOCALFILEOUTPUTSTREAM_CONTRACTID);
-  NS_ENSURE_STATE(out);
-
-  nsresult rv = out->Init(file, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, -1,
-                          0);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  mConfigOutputStream = out;
-  return NS_OK;
-}
-
-PRBool
-nsMetricsService::LoadNewConfig(nsIFile *newConfig, nsIFile *oldConfig)
-{
-  // Try to load the new config
-  PRBool exists = PR_FALSE;
-  newConfig->Exists(&exists);
-  if (exists && NS_SUCCEEDED(mConfig.Load(newConfig))) {
-    MS_LOG(("Successfully loaded new config"));
-
-    // Replace the old config file with the new one
-    oldConfig->Remove(PR_FALSE);
-
-    nsString filename;
-    oldConfig->GetLeafName(filename);
-
-    nsCOMPtr<nsIFile> directory;
-    oldConfig->GetParent(getter_AddRefs(directory));
-
-    newConfig->MoveTo(directory, filename);
-    return PR_TRUE;
-  }
-
-  MS_LOG(("Couldn't load new config"));
-
-  // We want to disable collection until the next upload interval,
-  // but we don't want to reset the upload interval to the default
-  // if the server had supplied one.  So, write out a new config
-  // that just has the collectors disabled.
-  mConfig.ClearEvents();
-
-  nsCOMPtr<nsILocalFile> lf = do_QueryInterface(oldConfig);
-  nsresult rv = mConfig.Save(lf);
-  if (NS_FAILED(rv)) {
-    MS_LOG(("failed to save config: %d", rv));
-  }
-
-  return PR_FALSE;
-}
-
-void
-nsMetricsService::RemoveDataFile()
-{
-  nsCOMPtr<nsILocalFile> dataFile;
-  GetDataFile(&dataFile);
-  if (!dataFile) {
-    MS_LOG(("Couldn't get data file to remove"));
-    return;
-  }
-
-  nsresult rv = dataFile->Remove(PR_FALSE);
-  if (NS_SUCCEEDED(rv)) {
-    MS_LOG(("Removed data file"));
-  } else {
-    MS_LOG(("Couldn't remove data file: %d", rv));
-  }
-}
-
-PRInt32
-nsMetricsService::GetRandomUploadInterval()
-{
-  static const int kSecondsPerHour = 60 * 60;
-  mRetryCount = 0;
-
-  PRInt32 interval_sec = kSecondsPerHour * 12;
-  PRUint32 random = 0;
-  if (nsMetricsUtils::GetRandomNoise(&random, sizeof(random))) {
-    interval_sec += (random % (24 * kSecondsPerHour));
-  }
-  // If we couldn't get any random bytes, just use the default of
-  // 12 hours.
-
-  return interval_sec;
-}
-
-NS_IMETHODIMP
-nsMetricsService::OnStopRequest(nsIRequest *request, nsISupports *context,
-                                nsresult status)
-{
-  MS_LOG(("OnStopRequest status = %x", status));
-
-  // Close the output stream for the download
-  if (mConfigOutputStream) {
-    mConfigOutputStream->Close();
-    mConfigOutputStream = 0;
-  }
-
-  // There are several possible outcomes of our upload request:
-  // 1. The server returns 200 OK
-  //    We consider the upload a success and delete the old data file.
-  //
-  // 2. The server returns a 4xx error
-  //    There was a problem with the uploaded data, so we delete the data file.
-  //
-  // 3. The server returns a 5xx error
-  //    There was a transient server-side problem.  We keep the data file.
-  //
-  // In any of these cases, we parse the server response.  If it contains
-  // a <config>, then it replaces our current config file.  If not, we reset
-  // to the default configuration, but preserve the upload interval.
-  // Currently we don't properly handle a 3xx response, it's treated like
-  // a 4xx error (delete the data file).
-  //
-  // 4. A network error occurs (NS_FAILED(status) is true)
-  //    We keep the old data and the old config.
-  //
-  // In any of the error cases, we increment the retry count and schedule
-  // a retry for the next upload interval.  To start off, the retry is at
-  // the upload interval specified by our config.  If we fail kMaxRetries
-  // times, we'll delete the data file and defer trying again until a randomly
-  // selected time 12-36 hours from the last attempt.  When the 12-36 hour
-  // deferred upload is attempted, we reset the state and will again retry up
-  // to kMaxRetriesTimes at the default upload interval.
-  //
-  // Any time an upload is successful, the retry count is reset to 0.
-
-  nsCOMPtr<nsIFile> configTempFile;  // the response we just downloaded
-  GetConfigTempFile(getter_AddRefs(configTempFile));
-  NS_ENSURE_STATE(configTempFile);
-
-  nsCOMPtr<nsIFile> configFile;  // our old config
-  GetConfigFile(getter_AddRefs(configFile));
-  NS_ENSURE_STATE(configFile);
-
-  PRBool success = PR_FALSE, replacedConfig = PR_FALSE;
-  if (NS_SUCCEEDED(status)) {
-    // If the request succeeded (200), we remove the old data file
-    PRUint32 responseCode = 500;
-    nsCOMPtr<nsIHttpChannel> channel = do_QueryInterface(request);
-    if (channel) {
-      channel->GetResponseStatus(&responseCode);
-    }
-    MS_LOG(("Server response: %u", responseCode));
-
-    if (responseCode == 200) {
-      success = PR_TRUE;
-      RemoveDataFile();
-    } else if (responseCode < 500) {
-      // This was a request error, so delete the data file
-      RemoveDataFile();
-    }
-
-    replacedConfig = LoadNewConfig(configTempFile, configFile);
-  } else {
-    MS_LOG(("Request failed"));
-  }
-
-  // Clean up the temp file if we didn't rename it
-  if (!replacedConfig) {
-    configTempFile->Remove(PR_FALSE);
-  }
-
-  // Handle success or failure of the request
-  if (success) {
-    mRetryCount = 0;
-
-    // Clear the next-upload-time pref, in case it was set somehow.
-    FlushClearPref(kUploadTimePref);
-    MS_LOG(("Uploaded successfully and reset retry count"));
-
-    // Set the minimum next-ping time to a random time 12-36 hours from now.
-    // This is the time at which we'll upload to get a new config, even
-    // if we have no data.
-    PRInt32 interval_sec = GetRandomUploadInterval();
-    MS_LOG(("Next ping no later than %d seconds from now", interval_sec));
-    FlushIntPref(kPingTimePref, (PR_Now() / PR_USEC_PER_SEC) + interval_sec);
-  } else if (++mRetryCount >= kMaxRetries) {
-    RemoveDataFile();
-
-    PRInt32 interval_sec = GetRandomUploadInterval();
-    MS_LOG(("Reached max retry count, deferring upload for %d seconds",
-            interval_sec));
-    FlushIntPref(kUploadTimePref, (PR_Now() / PR_USEC_PER_SEC) + interval_sec);
-
-    // We'll initialize a timer for this interval below by calling
-    // InitUploadTimer().
-  }
-
-  // Restart the upload timer for our next upload
-  InitUploadTimer(PR_FALSE);
-  EnableCollectors();
-
-  mUploading = PR_FALSE;
-  return NS_OK;
-}
-
-struct DisabledCollectorsClosure
-{
-  DisabledCollectorsClosure(const nsTArray<nsString> &enabled)
-      : enabledCollectors(enabled) { }
-
-  // Collectors which are enabled in the new config
-  const nsTArray<nsString> &enabledCollectors;
-
-  // Collector instances which should no longer be enabled
-  nsTArray< nsCOMPtr<nsIMetricsCollector> > disabledCollectors;
-};
-
-/* static */ PLDHashOperator
-nsMetricsService::PruneDisabledCollectors(const nsAString &key,
-                                          nsCOMPtr<nsIMetricsCollector> &value,
-                                          void *userData)
-{
-  DisabledCollectorsClosure *dc =
-    static_cast<DisabledCollectorsClosure *>(userData);
-
-  // The frozen string API doesn't expose operator==, so we can't use
-  // IndexOf() here.
-  for (PRUint32 i = 0; i < dc->enabledCollectors.Length(); ++i) {
-    if (dc->enabledCollectors[i].Equals(key)) {
-      // The collector is enabled, continue
-      return PL_DHASH_NEXT;
-    }
-  }
-
-  // We didn't find the collector |key| in the list of enabled collectors,
-  // so move it from the hash table to the disabledCollectors list.
-  MS_LOG(("Disabling collector %s", NS_ConvertUTF16toUTF8(key).get()));
-  dc->disabledCollectors.AppendElement(value);
-  return PL_DHASH_REMOVE;
-}
-
-/* static */ PLDHashOperator
-nsMetricsService::NotifyNewLog(const nsAString &key,
-                               nsIMetricsCollector *value, void *userData)
-{
-  value->OnNewLog();
-  return PL_DHASH_NEXT;
-}
-
-void
-nsMetricsService::EnableCollectors()
-{
-  // Start and stop collectors based on the current config.
-  nsTArray<nsString> enabledCollectors;
-  mConfig.GetEvents(enabledCollectors);
-
-  // We need to find two sets of collectors:
-  //  (1) collectors which are running but not in |collectors|.
-  //      We'll call onDetach() on them and let them be released.
-  //  (2) collectors which are in |collectors| but not running.
-  //      We need to instantiate these collectors.
-
-  DisabledCollectorsClosure dc(enabledCollectors);
-  mCollectorMap.Enumerate(PruneDisabledCollectors, &dc);
-
-  // Notify this set of collectors that they're going away, and release them.
-  PRUint32 i;
-  for (i = 0; i < dc.disabledCollectors.Length(); ++i) {
-    dc.disabledCollectors[i]->OnDetach();
-  }
-  dc.disabledCollectors.Clear();
-
-  // Now instantiate any newly-enabled collectors.
-  for (i = 0; i < enabledCollectors.Length(); ++i) {
-    const nsString &name = enabledCollectors[i];
-    if (!mCollectorMap.GetWeak(name)) {
-      nsCString contractID("@mozilla.org/extensions/metrics/collector;1?name=");
-      contractID.Append(NS_ConvertUTF16toUTF8(name));
-
-      nsCOMPtr<nsIMetricsCollector> coll = do_GetService(contractID.get());
-      if (coll) {
-        MS_LOG(("Created collector %s", contractID.get()));
-        mCollectorMap.Put(name, coll);
-        coll->OnAttach();
-      } else {
-        MS_LOG(("Couldn't instantiate collector %s", contractID.get()));
-      }
-    }
-  }
-
-  // Finally, notify all collectors that we've restarted the log.
-  mCollectorMap.EnumerateRead(NotifyNewLog, nsnull);
-}
-
-// Copied from nsStreamUtils.cpp:
-static NS_METHOD
-CopySegmentToStream(nsIInputStream *inStr,
-                    void *closure,
-                    const char *buffer,
-                    PRUint32 offset,
-                    PRUint32 count,
-                    PRUint32 *countWritten)
-{
-  nsIOutputStream *outStr = static_cast<nsIOutputStream *>(closure);
-  *countWritten = 0;
-  while (count) {
-    PRUint32 n;
-    nsresult rv = outStr->Write(buffer, count, &n);
-    if (NS_FAILED(rv))
-      return rv;
-    buffer += n;
-    count -= n;
-    *countWritten += n;
-  }
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsService::OnDataAvailable(nsIRequest *request, nsISupports *context,
-                                  nsIInputStream *stream, PRUint32 offset,
-                                  PRUint32 count)
-{
-  PRUint32 n;
-  return stream->ReadSegments(CopySegmentToStream, mConfigOutputStream,
-                              count, &n);
-}
-
-NS_IMETHODIMP
-nsMetricsService::Observe(nsISupports *subject, const char *topic,
-                          const PRUnichar *data)
-{
-  if (strcmp(topic, kQuitApplicationTopic) == 0) {
-    Flush();
-
-    // We don't detach the collectors here, to allow them to log events
-    // as we're shutting down.  The collectors will be detached and released
-    // when the MetricsService goes away.
-  } else if (strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0) {
-    mUploadTimer->Cancel();
-  } else if (strcmp(topic, "profile-after-change") == 0) {
-    nsresult rv = ProfileStartup();
-    NS_ENSURE_SUCCESS(rv, rv);
-  } else if (strcmp(topic, NS_WEBNAVIGATION_DESTROY) == 0 ||
-             strcmp(topic, NS_CHROME_WEBNAVIGATION_DESTROY) == 0) {
-
-    // Dispatch our notification before removing the window from the map.
-    nsCOMPtr<nsIObserverService> obsSvc =
-      do_GetService("@mozilla.org/observer-service;1");
-    NS_ENSURE_STATE(obsSvc);
-
-    const char *newTopic;
-    if (strcmp(topic, NS_WEBNAVIGATION_DESTROY) == 0) {
-      newTopic = NS_METRICS_WEBNAVIGATION_DESTROY;
-    } else {
-      newTopic = NS_METRICS_CHROME_WEBNAVIGATION_DESTROY;
-    }
-
-    obsSvc->NotifyObservers(subject, newTopic, data);
-
-    // Remove the window from our map.
-    nsCOMPtr<nsIDOMWindow> window = do_GetInterface(subject);
-    if (window) {
-      MS_LOG(("Removing window from map: %p", window.get()));
-      mWindowMap.Remove(window);
-    } else {
-      MS_LOG(("Couldn't get window to remove from map"));
-    }
-  } else if (strcmp(topic, NS_HTTP_ON_MODIFY_REQUEST_TOPIC) == 0) {
-    // Check whether this channel if one of ours.  If it is, clear the cookies.
-    nsCOMPtr<nsIPropertyBag2> props = do_QueryInterface(subject);
-    if (props) {
-      PRBool isMetrics = PR_FALSE;
-      props->GetPropertyAsBool(
-          NS_LITERAL_STRING("moz-metrics-request"), &isMetrics);
-      if (isMetrics) {
-        nsCOMPtr<nsIHttpChannel> channel = do_QueryInterface(subject);
-        if (channel) {
-          channel->SetRequestHeader(NS_LITERAL_CSTRING("Cookie"),
-                                    EmptyCString(), PR_FALSE);
-        }
-      }
-    }
-  } else if (strcmp(topic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID) == 0) {
-    // The only pref we care about changing is the .enable pref
-    if (NS_ConvertUTF8toUTF16(kEnablePref).Equals(nsDependentString(data))) {
-      if (CollectionEnabled()) {
-        StartCollection();
-      } else {
-        StopCollection();
-      }
-    }
-  }
-  
-  return NS_OK;
-}
-
-nsresult
-nsMetricsService::ProfileStartup()
-{
-  nsCOMPtr<nsIPrefBranch2> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
-  NS_ENSURE_STATE(prefs);
-  prefs->AddObserver(kEnablePref, this, PR_FALSE);
-
-  return CollectionEnabled() ? StartCollection() : StopCollection();
-}
-
-nsresult
-nsMetricsService::StartCollection()
-{
-  // Initialize configuration by reading our old config file if one exists.
-  nsCOMPtr<nsIFile> file;
-  GetConfigFile(getter_AddRefs(file));
-
-  PRBool loaded = PR_FALSE;
-  if (file) {
-    PRBool exists;
-    if (NS_SUCCEEDED(file->Exists(&exists)) && exists) {
-      loaded = NS_SUCCEEDED(mConfig.Load(file));
-    }
-  }
-  
-  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
-  NS_ENSURE_STATE(prefs);
-  prefs->GetIntPref("extensions.mozilla.metrics.event-count", &mEventCount);
-
-  // Update the session id pref for the new session
-  static const char kSessionIDPref[] = "extensions.mozilla.metrics.last-session-id";
-  PRInt32 sessionID = -1;
-  prefs->GetIntPref(kSessionIDPref, &sessionID);
-  mSessionID.Cut(0, PR_UINT32_MAX);
-  AppendInt(mSessionID, ++sessionID);
-  nsresult rv = FlushIntPref(kSessionIDPref, sessionID);
-  NS_ENSURE_SUCCESS(rv, rv);
-  
-  // Start up the collectors
-  EnableCollectors();
-
-  // If we didn't load a config file, we should upload as soon as possible.
-  InitUploadTimer(!loaded);
-
-  return NS_OK;
-}
-
-nsresult
-nsMetricsService::StopCollection()
-{
-  // Clear out prefs and files associated with metrics collection
-  MS_LOG(("Clearing metrics state"));
-  FlushClearPref(kUploadTimePref);
-  FlushClearPref(kPingTimePref);
-  FlushClearPref(kEventCountPref);
-
-  nsCOMPtr<nsIFile> configFile;
-  GetConfigFile(getter_AddRefs(configFile));
-  if (configFile) {
-    configFile->Remove(PR_FALSE);
-  }
-
-  nsCOMPtr<nsILocalFile> dataFile;
-  GetDataFile(&dataFile);
-  if (dataFile) {
-    dataFile->Remove(PR_FALSE);
-  }
-
-  // Clear our current config and make sure all collectors are disabled
-  mConfig.Reset();
-  EnableCollectors();
-  CreateRoot();  // clear any unflushed events
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMetricsService::Notify(nsITimer *timer)
-{
-  // OK, we are ready to upload!
-  MS_LOG(("Timer fired, uploading metrics log"));
-
-  // Clear the next-upload-time pref
-  FlushClearPref(kUploadTimePref);
-
-  Upload();
-  return NS_OK;
-}
-
-/*static*/ nsMetricsService *
-nsMetricsService::get()
-{
-  if (!sMetricsService) {
-    nsCOMPtr<nsIMetricsService> ms =
-      do_GetService(NS_METRICSSERVICE_CONTRACTID);
-    if (!sMetricsService)
-      NS_WARNING("failed to initialize metrics service");
-  }
-  return sMetricsService;
-}
-
-/*static*/ NS_METHOD
-nsMetricsService::Create(nsISupports *outer, const nsIID &iid, void **result)
-{
-  NS_ENSURE_TRUE(!outer, NS_ERROR_NO_AGGREGATION);
-
-  nsRefPtr<nsMetricsService> ms;
-  if (!sMetricsService) {
-    ms = new nsMetricsService();
-    if (!ms)
-      return NS_ERROR_OUT_OF_MEMORY;
-    NS_ASSERTION(sMetricsService, "should be non-null");
-
-    nsresult rv = ms->Init();
-    if (NS_FAILED(rv))
-      return rv;
-  }
-  return sMetricsService->QueryInterface(iid, result);
-}
-
-nsresult
-nsMetricsService::Init()
-{
-  // Anything that requires reading profile prefs must be initialized
-  // later, once the profile-after-change notification has happened.
-  // We can create objects and register for notifications now.
-  
-#ifdef PR_LOGGING
-  gMetricsLog = PR_NewLogModule("nsMetricsService");
-#endif
-
-  MS_LOG(("nsMetricsService::Init"));
-
-  // Set up our hashtables
-  NS_ENSURE_TRUE(mWindowMap.Init(32), NS_ERROR_OUT_OF_MEMORY);
-  NS_ENSURE_TRUE(mCollectorMap.Init(16), NS_ERROR_OUT_OF_MEMORY);
-
-  mUploadTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
-  NS_ENSURE_TRUE(mUploadTimer, NS_ERROR_OUT_OF_MEMORY);
-
-  mMD5Context = MD5_NewContext();
-  NS_ENSURE_TRUE(mMD5Context, NS_ERROR_FAILURE);
-
-  NS_ENSURE_STATE(mConfig.Init());
-
-  // Create an XML document to serve as the owner document for elements.
-  mDocument = do_CreateInstance("@mozilla.org/xml/xml-document;1");
-  NS_ENSURE_TRUE(mDocument, NS_ERROR_FAILURE);
-
-  // Create a root log element.
-  nsresult rv = CreateRoot();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIObserverService> obsSvc =
-      do_GetService("@mozilla.org/observer-service;1", &rv);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // The rest of startup will happen on profile-after-change
-  rv = obsSvc->AddObserver(this, "profile-after-change", PR_FALSE);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // Listen for quit-application so we can properly flush our data to disk
-  rv = obsSvc->AddObserver(this, kQuitApplicationTopic, PR_FALSE);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // We wait to cancel our timer until xpcom-shutdown, to catch cases
-  // where quit-application is never called.
-  rv = obsSvc->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, PR_FALSE);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // Listen for window destruction so that we can remove the windows
-  // from our window id map.
-  rv = obsSvc->AddObserver(this, NS_WEBNAVIGATION_DESTROY, PR_FALSE);
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = obsSvc->AddObserver(this, NS_CHROME_WEBNAVIGATION_DESTROY, PR_FALSE);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // Listen for http-on-modify-request so that we can clear out cookies
-  // from our requests.
-  rv = obsSvc->AddObserver(this, NS_HTTP_ON_MODIFY_REQUEST_TOPIC, PR_FALSE);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-nsresult
-nsMetricsService::CreateRoot()
-{
-  nsresult rv;
-  nsCOMPtr<nsIDOMElement> root;
-  rv = nsMetricsUtils::CreateElement(mDocument, NS_LITERAL_STRING("log"),
-                                     getter_AddRefs(root));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  mRoot = root;
-  return NS_OK;
-}
-
-nsresult
-nsMetricsService::GetDataFile(nsCOMPtr<nsILocalFile> *result)
-{
-  nsCOMPtr<nsIFile> file;
-  nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
-                                       getter_AddRefs(file));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = file->AppendNative(NS_LITERAL_CSTRING("metrics.xml"));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  *result = do_QueryInterface(file, &rv);
-  return rv;
-}
-
-nsresult
-nsMetricsService::OpenDataFile(PRUint32 flags, PRFileDesc **fd)
-{
-  nsCOMPtr<nsILocalFile> dataFile;
-  nsresult rv = GetDataFile(&dataFile);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return dataFile->OpenNSPRFileDesc(flags, 0600, fd);
-}
-
-nsresult
-nsMetricsService::UploadData()
-{
-  // TODO: Prepare a data stream for upload that is prefixed with a PROFILE
-  //       event.
- 
-  if (!CollectionEnabled()) {
-    MS_LOG(("Upload disabled"));
-    return NS_ERROR_ABORT;
-  }
- 
-  nsCString spec;
-  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
-  if (prefs) {
-    prefs->GetCharPref("extensions.mozilla.metrics.upload.uri", getter_Copies(spec));
-  }
-  if (spec.IsEmpty()) {
-    MS_LOG(("Upload URI not set"));
-    return NS_ERROR_ABORT;
-  }
-
-  nsCOMPtr<nsILocalFile> file;
-  nsresult rv = GetDataFileForUpload(&file);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // NOTE: nsIUploadChannel requires a buffered stream to upload...
-
-  nsCOMPtr<nsIFileInputStream> fileStream =
-      do_CreateInstance(NS_LOCALFILEINPUTSTREAM_CONTRACTID);
-  NS_ENSURE_STATE(fileStream);
-
-  rv = fileStream->Init(file, -1, -1, nsIFileInputStream::DELETE_ON_CLOSE);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  PRUint32 streamLen;
-  rv = fileStream->Available(&streamLen);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  if (streamLen == 0)
-    return NS_ERROR_ABORT;
-
-  nsCOMPtr<nsIBufferedInputStream> uploadStream =
-      do_CreateInstance(NS_BUFFEREDINPUTSTREAM_CONTRACTID);
-  NS_ENSURE_STATE(uploadStream);
-
-  rv = uploadStream->Init(fileStream, 4096);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIIOService> ios = do_GetService(NS_IOSERVICE_CONTRACTID);
-  NS_ENSURE_STATE(ios);
-
-  nsCOMPtr<nsIChannel> channel;
-  ios->NewChannel(spec, nsnull, nsnull, getter_AddRefs(channel));
-  NS_ENSURE_STATE(channel); 
-
-  // Tag the channel so that we know it's one of ours.
-  nsCOMPtr<nsIWritablePropertyBag2> props = do_QueryInterface(channel);
-  NS_ENSURE_STATE(props);
-  props->SetPropertyAsBool(NS_LITERAL_STRING("moz-metrics-request"), PR_TRUE);
-
-  nsCOMPtr<nsIUploadChannel> uploadChannel = do_QueryInterface(channel);
-  NS_ENSURE_STATE(uploadChannel); 
-
-  NS_NAMED_LITERAL_CSTRING(binaryType, NS_METRICS_MIME_TYPE);
-  rv = uploadChannel->SetUploadStream(uploadStream, binaryType, -1);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(channel);
-  NS_ENSURE_STATE(httpChannel);
-  rv = httpChannel->SetRequestMethod(NS_LITERAL_CSTRING("POST"));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = channel->AsyncOpen(this, nsnull);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-nsresult
-nsMetricsService::GetDataFileForUpload(nsCOMPtr<nsILocalFile> *result)
-{
-  nsCOMPtr<nsILocalFile> input;
-  nsresult rv = GetDataFile(&input);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIInputStream> src;
-  rv = OpenCompleteXMLStream(input, getter_AddRefs(src));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIFile> temp;
-  rv = input->Clone(getter_AddRefs(temp));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCString leafName;
-  rv = temp->GetNativeLeafName(leafName);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  leafName.Append(".bz2");
-  rv = temp->SetNativeLeafName(leafName);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsILocalFile> ltemp = do_QueryInterface(temp, &rv);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  PRFileDesc *destFd = NULL;
-  rv = ltemp->OpenNSPRFileDesc(PR_WRONLY | PR_TRUNCATE | PR_CREATE_FILE, 0600,
-                               &destFd);
-
-  // Copy file using bzip2 compression:
-
-  if (NS_SUCCEEDED(rv)) {
-#ifdef NS_METRICS_SEND_UNCOMPRESSED_DATA
-    char buf[4096];
-    PRUint32 n;
-
-    while (NS_SUCCEEDED(rv = src->Read(buf, sizeof(buf), &n)) && n) {
-      if (PR_Write(destFd, buf, n) != n) {
-        NS_WARNING("failed to write data");
-        rv = NS_ERROR_UNEXPECTED;
-        break;
-      }
-    }
-#else
-    rv = CompressBZ2(src, destFd);
-#endif
-  }
-
-  if (destFd)
-    PR_Close(destFd);
-
-  if (NS_SUCCEEDED(rv)) {
-    *result = nsnull;
-    ltemp.swap(*result);
-  }
-
-  return rv;
-}
-
-nsresult
-nsMetricsService::OpenCompleteXMLStream(nsILocalFile *dataFile,
-                                       nsIInputStream **result)
-{
-  // Construct a full XML document using the header, file contents, and
-  // footer.  We need to generate a client id now if one doesn't exist.
-  static const char kClientIDPref[] = "extensions.mozilla.metrics.client-id";
-
-  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
-  NS_ENSURE_STATE(prefs);
-  
-  nsCString clientID;
-  nsresult rv = prefs->GetCharPref(kClientIDPref, getter_Copies(clientID));
-  if (NS_FAILED(rv) || clientID.IsEmpty()) {
-    rv = GenerateClientID(clientID);
-    NS_ENSURE_SUCCESS(rv, rv);
-    
-    rv = FlushCharPref(kClientIDPref, clientID.get());
-    NS_ENSURE_SUCCESS(rv, rv);
-  }
-
-  static const char METRICS_XML_HEAD[] =
-      "<?xml version=\"1.0\"?>\n"
-      "<log xmlns=\"" NS_METRICS_NAMESPACE "\" "
-           "version=\"%d\" clientid=\"%s\">\n";
-  static const char METRICS_XML_TAIL[] = "</log>";
-
-  nsCOMPtr<nsIFileInputStream> fileStream =
-      do_CreateInstance(NS_LOCALFILEINPUTSTREAM_CONTRACTID);
-  NS_ENSURE_STATE(fileStream);
-
-  rv = fileStream->Init(dataFile, -1, -1, 0);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIMultiplexInputStream> miStream =
-    do_CreateInstance(NS_MULTIPLEXINPUTSTREAM_CONTRACTID);
-  NS_ENSURE_STATE(miStream);
-
-  nsCOMPtr<nsIStringInputStream> stringStream =
-      do_CreateInstance("@mozilla.org/io/string-input-stream;1");
-  NS_ENSURE_STATE(stringStream);
-
-  char *head = PR_smprintf(METRICS_XML_HEAD, kMetricsVersion, clientID.get());
-  rv = stringStream->SetData(head, -1);
-  PR_smprintf_free(head);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = miStream->AppendStream(stringStream);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = miStream->AppendStream(fileStream);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  stringStream = do_CreateInstance("@mozilla.org/io/string-input-stream;1");
-  NS_ENSURE_STATE(stringStream);
-
-  rv = stringStream->SetData(METRICS_XML_TAIL, sizeof(METRICS_XML_TAIL)-1);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = miStream->AppendStream(stringStream);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  NS_ADDREF(*result = miStream);
-  return NS_OK;
-}
-
-void
-nsMetricsService::InitUploadTimer(PRBool immediate)
-{
-  // Check whether we've set a delayed upload time due to previous errors.
-  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
-  if (!prefs) {
-    NS_WARNING("couldn't get prefs service");
-    return;
-  }
-
-  PRUint32 delay_sec;
-
-  PRInt32 uploadTime_sec;
-  if (NS_SUCCEEDED(prefs->GetIntPref(kUploadTimePref, &uploadTime_sec))) {
-    // Set a timer for when we should upload.  If the time to upload has
-    // passed, we'll set a timer for 0ms.
-    PRInt32 now_sec = PRInt32(PR_Now() / PR_USEC_PER_SEC);
-    if (now_sec >= uploadTime_sec) {
-      delay_sec = 0;
-    } else {
-      delay_sec = (uploadTime_sec - now_sec);
-    }
-  } else if (immediate) {
-    delay_sec = 0;
-  } else {
-    delay_sec = mConfig.UploadInterval();
-  }
-
-  nsresult rv = mUploadTimer->InitWithCallback(this,
-                                               delay_sec * PR_MSEC_PER_SEC,
-                                               nsITimer::TYPE_ONE_SHOT);
-  if (NS_SUCCEEDED(rv)) {
-    MS_LOG(("Initialized upload timer for %d sec", delay_sec));
-  } else {
-    MS_LOG(("Failed to initialize upload timer"));
-  }
-}
-
-void
-nsMetricsService::GetConfigFile(nsIFile **result)
-{
-  nsCOMPtr<nsIFile> file;
-  NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file));
-  if (file)
-    file->AppendNative(NS_LITERAL_CSTRING("metrics-config.xml"));
-
-  *result = nsnull;
-  file.swap(*result);
-}
-
-void
-nsMetricsService::GetConfigTempFile(nsIFile **result)
-{
-  nsCOMPtr<nsIFile> file;
-  NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file));
-  if (file)
-    file->AppendNative(NS_LITERAL_CSTRING("metrics-config.tmp"));
-
-  *result = nsnull;
-  file.swap(*result);
-}
-
-nsresult
-nsMetricsService::GenerateClientID(nsCString &clientID)
-{
-  // Feed some data into the hasher...
-
-  struct {
-    PRTime  a;
-    PRUint8 b[32];
-  } input;
-
-  input.a = PR_Now();
-  nsMetricsUtils::GetRandomNoise(input.b, sizeof(input.b));
-
-  return HashBytes(
-      reinterpret_cast<const PRUint8 *>(&input), sizeof(input), clientID);
-}
-
-nsresult
-nsMetricsService::HashBytes(const PRUint8 *bytes, PRUint32 length,
-                            nsACString &result)
-{
-  unsigned char buf[HASH_LENGTH_MAX];
-  unsigned int resultLength = 0;
-
-  MD5_Begin(mMD5Context);
-  MD5_Update(mMD5Context, bytes, length);
-  MD5_End(mMD5Context, buf, &resultLength, sizeof(buf));
-
-  // Base64-encode the result.  The maximum result length is calculated
-  // as described in plbase64.h.
-  char *resultBuffer;
-  if (NS_CStringGetMutableData(
-          result, ((resultLength + 2) / 3) * 4, &resultBuffer) == 0) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
-  PL_Base64Encode(reinterpret_cast<char*>(buf), resultLength, resultBuffer);
-
-  // Size the string to its null-terminated length
-  result.SetLength(strlen(resultBuffer));
-  return NS_OK;
-}
-
-PRBool
-nsMetricsService::PersistEventCount()
-{
-  return NS_SUCCEEDED(FlushIntPref(kEventCountPref, mEventCount));
-}
-
-/* static */ PRUint32
-nsMetricsService::GetWindowID(nsIDOMWindow *window)
-{
-  if (!sMetricsService) {
-    NS_NOTREACHED("metrics service not created");
-    return PR_UINT32_MAX;
-  }
-
-  return sMetricsService->GetWindowIDInternal(window);
-}
-
-NS_IMETHODIMP
-nsMetricsService::GetWindowID(nsIDOMWindow *window, PRUint32 *id)
-{
-  *id = GetWindowIDInternal(window);
-  return NS_OK;
-}
-
-PRUint32
-nsMetricsService::GetWindowIDInternal(nsIDOMWindow *window)
-{
-  PRUint32 id;
-  if (!mWindowMap.Get(window, &id)) {
-    id = mNextWindowID++;
-    MS_LOG(("Adding window %p to map with id %d", window, id));
-    mWindowMap.Put(window, id);
-  }
-
-  return id;
-}
-
-nsresult
-nsMetricsService::HashUTF8(const nsCString &str, nsCString &hashed)
-{
-  if (str.IsEmpty()) {
-    return NS_ERROR_INVALID_ARG;
-  }
-
-  return HashBytes(
-      reinterpret_cast<const PRUint8 *>(str.get()), str.Length(), hashed);
-}
-
-/* static */ nsresult
-nsMetricsService::FlushIntPref(const char *prefName, PRInt32 prefValue)
-{
-  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
-  NS_ENSURE_STATE(prefs);
-
-  nsresult rv = prefs->SetIntPref(prefName, prefValue);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIPrefService> prefService = do_QueryInterface(prefs);
-  NS_ENSURE_STATE(prefService);
-
-  rv = prefService->SavePrefFile(nsnull);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-/* static */ nsresult
-nsMetricsService::FlushCharPref(const char *prefName, const char *prefValue)
-{
-  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
-  NS_ENSURE_STATE(prefs);
-
-  nsresult rv = prefs->SetCharPref(prefName, prefValue);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIPrefService> prefService = do_QueryInterface(prefs);
-  NS_ENSURE_STATE(prefService);
-
-  rv = prefService->SavePrefFile(nsnull);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-/* static */ nsresult
-nsMetricsService::FlushClearPref(const char *prefName)
-{
-  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
-  NS_ENSURE_STATE(prefs);
-
-  nsresult rv = prefs->ClearUserPref(prefName);
-  if (NS_FAILED(rv)) {
-    // There was no user-set value for this pref.
-    // It's not an error, and we don't need to flush.
-    return NS_OK;
-  }
-
-  nsCOMPtr<nsIPrefService> prefService = do_QueryInterface(prefs);
-  NS_ENSURE_STATE(prefService);
-
-  rv = prefService->SavePrefFile(nsnull);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-/* static */ PRBool
-nsMetricsService::CollectionEnabled()
-{
-  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
-  NS_ENSURE_TRUE(prefs, PR_FALSE);
-
-  PRBool enabled = PR_FALSE;
-  prefs->GetBoolPref(kEnablePref, &enabled);
-  return enabled;
-}
-
-/* static */ nsresult
-nsMetricsUtils::NewPropertyBag(nsIWritablePropertyBag2 **result)
-{
-  return CallCreateInstance("@mozilla.org/hash-property-bag;1", result);
-}
-
-/* static */ nsresult
-nsMetricsUtils::AddChildItem(nsIMetricsEventItem *parent,
-                             const nsAString &childName,
-                             nsIPropertyBag *childProperties)
-{
-  nsCOMPtr<nsIMetricsEventItem> item;
-  nsMetricsService::get()->CreateEventItem(childName, getter_AddRefs(item));
-  NS_ENSURE_STATE(item);
-
-  item->SetProperties(childProperties);
-
-  nsresult rv = parent->AppendChild(item);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-/* static */ PRBool
-nsMetricsUtils::GetRandomNoise(void *buf, PRSize size)
-{
-  PRSize nbytes = 0;
-  while (nbytes < size) {
-    PRSize n = PR_GetRandomNoise(
-        static_cast<char *>(buf) + nbytes, size - nbytes);
-    if (n == 0) {
-      MS_LOG(("Couldn't get any random bytes"));
-      return PR_FALSE;
-    }
-    nbytes += n;
-  }
-  return PR_TRUE;
-}
-
-/* static */ nsresult
-nsMetricsUtils::CreateElement(nsIDOMDocument *ownerDoc,
-                              const nsAString &tag, nsIDOMElement **element)
-{
-  return ownerDoc->CreateElementNS(NS_LITERAL_STRING(NS_METRICS_NAMESPACE),
-                                   tag, element);
-}
-
-
-/* static */ PRBool
-nsMetricsUtils::IsSubframe(nsIDocShellTreeItem* docShell)
-{
-  // Consider the docshell to be a subframe if it's is content, not chrome,
-  // and has a parent docshell which is also content.
-  if (!docShell) {
-    return PR_FALSE;
-  }
-
-  PRInt32 itemType;
-  docShell->GetItemType(&itemType);
-  if (itemType != nsIDocShellTreeItem::typeContent) {
-    return PR_FALSE;
-  }
-
-  nsCOMPtr<nsIDocShellTreeItem> parent;
-  docShell->GetSameTypeParent(getter_AddRefs(parent));
-  return (parent != nsnull);
-}
-
-
-/* static */ PRUint32
-nsMetricsUtils::FindWindowForNode(nsIDOMNode *node)
-{
-  nsCOMPtr<nsIDOMDocument> ownerDoc;
-  node->GetOwnerDocument(getter_AddRefs(ownerDoc));
-  NS_ENSURE_STATE(ownerDoc);
-
-  nsCOMPtr<nsIDOMDocumentView> docView = do_QueryInterface(ownerDoc);
-  NS_ENSURE_STATE(docView);
-
-  nsCOMPtr<nsIDOMAbstractView> absView;
-  docView->GetDefaultView(getter_AddRefs(absView));
-  NS_ENSURE_STATE(absView);
-
-  nsCOMPtr<nsIDOMWindow> window = do_QueryInterface(absView);
-  NS_ENSURE_STATE(window);
-
-  return nsMetricsService::GetWindowID(window);
-}
deleted file mode 100644
--- a/extensions/metrics/src/nsMetricsService.h
+++ /dev/null
@@ -1,325 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Darin Fisher <darin@meer.net>
- *
- * 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 ***** */
-
-#ifndef nsMetricsService_h__
-#define nsMetricsService_h__
-
-#include "nsIMetricsService.h"
-#include "nsMetricsModule.h"
-#include "nsMetricsConfig.h"
-#include "nsIAboutModule.h"
-#include "nsIStreamListener.h"
-#include "nsIOutputStream.h"
-#include "nsIObserver.h"
-#include "nsITimer.h"
-#include "nsCOMPtr.h"
-#include "prio.h"
-#include "prlog.h"
-#include "nsIWritablePropertyBag2.h"
-#include "nsDataHashtable.h"
-#include "nsInterfaceHashtable.h"
-#include "nsPtrHashKey.h"
-#include "blapit.h"
-
-class nsILocalFile;
-class nsIDOMWindow;
-class nsIDOMDocument;
-class nsIDOMNode;
-class nsIMetricsCollector;
-class nsIDocShellTreeItem;
-
-#ifdef PR_LOGGING
-// Shared log for the metrics service and collectors.
-// (NSPR_LOG_MODULES=nsMetricsService:5)
-extern PRLogModuleInfo *gMetricsLog;
-#endif
-#define MS_LOG(args) PR_LOG(gMetricsLog, PR_LOG_DEBUG, args)
-#define MS_LOG_ENABLED() PR_LOG_TEST(gMetricsLog, PR_LOG_DEBUG)
-
-// This is the namespace for the built-in metrics events.
-#define NS_METRICS_NAMESPACE "http://www.mozilla.org/metrics"
-
-// This class manages the metrics datastore.  It is responsible for persisting
-// the data when the browser closes and for uploading it to the metrics server
-// periodically.
-
-class nsMetricsService : public nsIMetricsService
-                       , public nsIAboutModule
-                       , public nsIStreamListener
-                       , public nsIObserver
-                       , public nsITimerCallback
-{
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIMETRICSSERVICE
-  NS_DECL_NSIABOUTMODULE
-  NS_DECL_NSIREQUESTOBSERVER
-  NS_DECL_NSISTREAMLISTENER
-  NS_DECL_NSIOBSERVER
-  NS_DECL_NSITIMERCALLBACK
-  
-  // Get the metrics service singleton.  This method will call do_GetService if
-  // necessary to fetch the metrics service.  It relies on the service manager
-  // to keep the singleton instance alive.  This method may return null!
-  static nsMetricsService* get();
-
-  // Create the metrics service singleton, called only by the XPCOM factory for
-  // this class.
-  static NS_METHOD Create(nsISupports *outer, const nsIID &iid, void **result);
-
-  // Helper function for logging events in the default namespace
-  nsresult LogEvent(const nsAString &eventName,
-                    nsIWritablePropertyBag2 *eventProperties)
-  {
-    nsCOMPtr<nsIPropertyBag> bag = do_QueryInterface(eventProperties);
-    NS_ENSURE_STATE(bag);
-    return LogSimpleEvent(NS_LITERAL_STRING(NS_METRICS_NAMESPACE), eventName,
-                          bag);
-  }
-
-  // Creates an EventItem in the default metrics namespace.
-  nsresult CreateEventItem(const nsAString &name, nsIMetricsEventItem **item)
-  {
-    return CreateEventItem(NS_LITERAL_STRING(NS_METRICS_NAMESPACE),
-                           name, item);
-  }
-
-  // More convenient non-scriptable version of GetWindowID().
-  static PRUint32 GetWindowID(nsIDOMWindow *window);
-
-  // VC6 needs this to be public :-(
-  nsresult Init();
-
-  // Returns the window id map (readonly)
-  const nsDataHashtable< nsPtrHashKey<nsIDOMWindow>, PRUint32 >&
-  WindowMap() const
-  {
-    return mWindowMap;
-  }
-
-  // Creates a one-way hash of the given string.
-  nsresult HashUTF8(const nsCString &str, nsCString &hashed);
-
-  // Convenience method for hashing UTF-16 strings.
-  // The string is converted to UTF-8, then HashUTF8() is called.
-  nsresult HashUTF16(const nsString &str, nsCString &hashed) {
-    return HashUTF8(NS_ConvertUTF16toUTF8(str), hashed);
-  }
-
-private:
-  nsMetricsService();
-  ~nsMetricsService();
-
-  // Post-profile-initialization startup code
-  nsresult ProfileStartup();
-
-  // Reads the config, starts a new session, and turns on collectors
-  nsresult StartCollection();
-
-  // Stops collectors and removes all metrics-related prefs and files
-  nsresult StopCollection();
-
-  // Starts and stops collectors based on the current configuration
-  void EnableCollectors();
-  
-  // Creates a new root element to hold event nodes
-  nsresult CreateRoot();
-
-  nsresult UploadData();
-  nsresult GetDataFile(nsCOMPtr<nsILocalFile> *result);
-  nsresult OpenDataFile(PRUint32 flags, PRFileDesc **result);
-  nsresult GetDataFileForUpload(nsCOMPtr<nsILocalFile> *result);
-
-  // This method returns an input stream containing the complete XML for the
-  // data to upload.
-  nsresult OpenCompleteXMLStream(nsILocalFile *dataFile,
-                                 nsIInputStream **result);
-
-  // Initialize our timer for the next upload.
-  // If immediate is true, the timer will be fired as soon as possible,
-  // which is at the deferred-upload time if one exists, or immediately
-  // if not.
-  void InitUploadTimer(PRBool immediate);
-
-  // A reference to the local file containing our current configuration
-  void GetConfigFile(nsIFile **result);
-
-  // A reference to the local file where we'll download the server response.
-  // We don't replace the real config file until we know the new one is valid.
-  void GetConfigTempFile(nsIFile **result);
-
-  // Generate a new random client id string
-  nsresult GenerateClientID(nsCString &clientID);
-
-  // Check if a built-in event is enabled
-  PRBool IsEventEnabled(const nsAString &event) const
-  {
-    return mConfig.IsEventEnabled(NS_LITERAL_STRING(NS_METRICS_NAMESPACE),
-                                  event);
-  }
-
-  // Builds up a DOMElement tree from the given item and its children
-  nsresult BuildEventItem(nsIMetricsEventItem *item,
-                          nsIDOMElement **itemElement);
-
-  // Called to persist mEventCount.  Returns "true" if succeeded.
-  PRBool PersistEventCount();
-
-  // Hashes a byte buffer of the given length
-  nsresult HashBytes(const PRUint8 *bytes, PRUint32 length,
-                     nsACString &result);
-
-  // Does the real work of GetWindowID().
-  PRUint32 GetWindowIDInternal(nsIDOMWindow *window);
-
-  // Tries to load a new config.  If successful, the old config file is
-  // replaced with the new one.  If the new config couldn't be loaded,
-  // a config file is written which disables collection and preserves the
-  // upload interval from the old config.  Returns true if the new config
-  // file was loaded successfully.
-  PRBool LoadNewConfig(nsIFile *newConfig, nsIFile *oldConfig);
-
-  // Removes the existing data file (metrics.xml)
-  void RemoveDataFile();
-
-  // Generates a random interval, in seconds, between 12 and 36 hours.
-  PRInt32 GetRandomUploadInterval();
-
-  static PLDHashOperator
-  PruneDisabledCollectors(const nsAString &key,
-                          nsCOMPtr<nsIMetricsCollector> &value,
-                          void *userData);
-
-  static PLDHashOperator
-  DetachCollector(const nsAString &key,
-                  nsIMetricsCollector *value, void *userData);
-
-  static PLDHashOperator
-  NotifyNewLog(const nsAString &key,
-               nsIMetricsCollector *value, void *userData);
-
-  // Helpers to set a pref and then flush the pref file to disk.
-  static nsresult FlushIntPref(const char *prefName, PRInt32 prefValue);
-  static nsresult FlushCharPref(const char *prefName, const char *prefValue);
-  static nsresult FlushClearPref(const char *prefName);
-
-  // Returns true if the pref to enable collection is set to true
-  static PRBool CollectionEnabled();
-
-private:
-  class BadCertListener;
-
-  // Pointer to the metrics service singleton
-  static nsMetricsService* sMetricsService;
-
-  nsMetricsConfig mConfig;
-
-  // This output stream is non-null when we are downloading the config file.
-  nsCOMPtr<nsIOutputStream> mConfigOutputStream;
-
-  // XML document containing events to be flushed.
-  nsCOMPtr<nsIDOMDocument> mDocument;
-
-  // Root element of the XML document
-  nsCOMPtr<nsIDOMNode> mRoot;
-
-  // MD5 hashing object for collectors to use
-  MD5Context *mMD5Context;
-
-  // Window to incrementing-id map.  The keys are nsIDOMWindow*.
-  nsDataHashtable< nsPtrHashKey<nsIDOMWindow>, PRUint32 > mWindowMap;
-
-  // All of the active observers, keyed by name.
-  nsInterfaceHashtable<nsStringHashKey, nsIMetricsCollector> mCollectorMap;
-
-  // Timer object used for uploads
-  nsCOMPtr<nsITimer> mUploadTimer;
-
-  // The max number of times we'll retry the upload before stopping
-  // for several hours.
-  static const PRUint32 kMaxRetries;
-
-  // This is the logging format version that is sent with each upload.
-  // The version should be incremented whenver a change is made that
-  // affects the log output, including but not limited to:
-  //  - adding or removing a collector
-  //  - adding or removing a property
-  //  - changing the meaning or interpretation of a property value
-  static const PRUint32 kMetricsVersion;
-
-  PRInt32 mEventCount;
-  PRInt32 mSuspendCount;
-  PRBool mUploading;
-  nsString mSessionID;
-  // the next window id to hand out
-  PRUint32 mNextWindowID;
-
-  // The number of times we've tried to upload
-  PRUint32 mRetryCount;
-};
-
-class nsMetricsUtils
-{
-public:
-  // Creates a new nsIWritablePropertyBag2 instance.
-  static nsresult NewPropertyBag(nsIWritablePropertyBag2 **result);
-
-  // Creates a new item with the given properties, and appends it to the parent
-  static nsresult AddChildItem(nsIMetricsEventItem *parent,
-                               const nsAString &childName,
-                               nsIPropertyBag *childProperties);
-
-  // Loops until the given number of random bytes have been returned
-  // from the OS.  Returns true on success, or false if no random
-  // bytes are available
-  static PRBool GetRandomNoise(void *buf, PRSize size);
-
-  // Creates a new element in the metrics namespace, using the given
-  // ownerDocument and tag.
-  static nsresult CreateElement(nsIDOMDocument *ownerDoc,
-                                const nsAString &tag, nsIDOMElement **element);
-
-  // Returns true if the docshell should be considered a subframe.
-  static PRBool IsSubframe(nsIDocShellTreeItem *docShell);
-
-  // Finds the window id for the DOMWindow containing |node|.
-  // Returns 0 if the window could not be found.
-  static PRUint32 FindWindowForNode(nsIDOMNode *node);
-};
-
-#endif  // nsMetricsService_h__
deleted file mode 100644
--- a/extensions/metrics/src/nsProfileCollector.cpp
+++ /dev/null
@@ -1,832 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* ***** 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 the Metrics extension.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Brian Ryner <bryner@brianryner.com>
- *
- * 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 ***** */
-
-#include "nsProfileCollector.h"
-#include "nsMetricsService.h"
-#include "prsystem.h"
-#include "nsIXULAppInfo.h"
-#include "nsXULAppAPI.h"
-#include "nsIServiceManager.h"
-#include "nsComponentManagerUtils.h"
-#include "nsIExtensionManager.h"
-#include "nsIRDFDataSource.h"
-#include "nsIRDFService.h"
-#include "rdf.h"
-#include "nsIDOMPlugin.h"
-#include "nsAppDirectoryServiceDefs.h"
-#include "nsIScreenManager.h"
-#include "nsILocalFile.h"
-#include "nsDirectoryServiceUtils.h"
-#include "nsAutoPtr.h"
-#include "nsTArray.h"
-#include "nsINavBookmarksService.h"
-#include "nsINavHistoryService.h"
-#include "nsILivemarkService.h"
-#include "nsILocaleService.h"
-#include "nsToolkitCompsCID.h"
-#include "nsXPCOMCIDInternal.h"
-
-// We need to suppress inclusion of nsString.h
-#define nsString_h___
-#include "nsIPluginHost.h"
-#undef nsString_h___
-
-// Logs data on all installed plugins.
-class nsProfileCollector::PluginEnumerator
-{
- public:
-  PluginEnumerator() : mMetricsService(nsnull) {}
-  nsresult Init();
-
-  // Creates a MetricsEventItem for each installed plugin, and appends them
-  // to pluginsItem.
-  nsresult LogPlugins(nsIMetricsEventItem *pluginsItem);
-
- private:
-  // Creates and returns a MetricsEventItem for a single plugin, or
-  // NULL on failure.
-  already_AddRefed<nsIMetricsEventItem> CreatePluginItem(nsIDOMPlugin *plugin);
-
-  nsRefPtr<nsMetricsService> mMetricsService;
-};
-
-// Logs data on all installed extensions
-class nsProfileCollector::ExtensionEnumerator
-{
- public:
-  ExtensionEnumerator() : mMetricsService(nsnull) {}
-  nsresult Init();
-
-  // Creates a MetricsEventItem for each installed extension, and appends them
-  // to extensionsItem.
-  nsresult LogExtensions(nsIMetricsEventItem *extensionsItem);
-
- private:
-  // Creates and returns a MetricsEventItem for a single extension,
-  // or NULL on failure.
-  already_AddRefed<nsIMetricsEventItem> CreateExtensionItem(
-      nsIUpdateItem *extension);
-
-  nsRefPtr<nsMetricsService> mMetricsService;
-  nsCOMPtr<nsIRDFService> mRDFService;
-  nsCOMPtr<nsIExtensionManager> mExtensionManager;
-  nsCOMPtr<nsIRDFDataSource> mExtensionsDS;
-  nsCOMPtr<nsIRDFResource> mDisabledResource;
-};
-
-// Counts the number of bookmark items and folders in a container
-class nsProfileCollector::BookmarkCounter
-{
- public:
-  BookmarkCounter() {}
-  nsresult Init();
-
-  // These values correspond to indices of |count| for CountChildren().
-  enum BookmarkType {
-    ITEM,
-    FOLDER,
-    LIVEMARK,
-    SEPARATOR,
-    kLastBookmarkType
-  };
-
-  // Fills in |count| with the number of children of each BookmarkType.
-  // If |deep| is true, then the count will include children of all subfolders.
-  void CountChildren(PRInt64 root, PRBool deep, nsTArray<PRInt32> &count);
-
- private:
-  void CountRecursive(nsINavHistoryContainerResultNode *root, PRBool deep,
-                      nsTArray<PRInt32> &count);
-
-  nsCOMPtr<nsILivemarkService> mLivemarkService;
-};
-
-nsProfileCollector::nsProfileCollector()
-    : mLoggedProfile(PR_FALSE)
-{
-}
-
-nsProfileCollector::~nsProfileCollector()
-{
-}
-
-NS_IMPL_ISUPPORTS1(nsProfileCollector, nsIMetricsCollector)
-
-NS_IMETHODIMP
-nsProfileCollector::OnAttach()
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsProfileCollector::OnDetach()
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsProfileCollector::OnNewLog()
-{
-  if (mLoggedProfile) {
-    return NS_OK;
-  }
-
-  nsMetricsService *ms = nsMetricsService::get();
-
-  nsCOMPtr<nsIMetricsEventItem> profileItem;
-  ms->CreateEventItem(NS_LITERAL_STRING("profile"),
-                      getter_AddRefs(profileItem));
-  NS_ENSURE_STATE(profileItem);
-
-  LogCPU(profileItem);
-  LogMemory(profileItem);
-  LogOS(profileItem);
-  LogInstall(profileItem);
-  LogExtensions(profileItem);
-  LogPlugins(profileItem);
-  LogDisplay(profileItem);
-  LogBookmarks(profileItem);
-
-  nsresult rv = ms->LogEvent(profileItem);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  mLoggedProfile = PR_TRUE;
-  return NS_OK;
-}
-
-nsresult
-nsProfileCollector::LogCPU(nsIMetricsEventItem *profile)
-{
-  nsCOMPtr<nsIWritablePropertyBag2> properties;
-  nsMetricsUtils::NewPropertyBag(getter_AddRefs(properties));
-  NS_ENSURE_STATE(properties);
-
-  char buf[SYS_INFO_BUFFER_LENGTH];
-  if (PR_GetSystemInfo(PR_SI_ARCHITECTURE, buf, sizeof(buf)) != PR_SUCCESS) {
-    MS_LOG(("Failed to get architecture"));
-    return NS_ERROR_FAILURE;
-  }
-
-  properties->SetPropertyAsACString(NS_LITERAL_STRING("arch"),
-                                    nsDependentCString(buf));
-  MS_LOG(("Logged CPU arch=%s", buf));
-
-  nsresult rv = nsMetricsUtils::AddChildItem(
-      profile, NS_LITERAL_STRING("cpu"), properties);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-nsresult
-nsProfileCollector::LogMemory(nsIMetricsEventItem *profile)
-{
-  nsCOMPtr<nsIWritablePropertyBag2> properties;
-  nsMetricsUtils::NewPropertyBag(getter_AddRefs(properties));
-  NS_ENSURE_STATE(properties);
-
-  static PRUint64 size = PR_GetPhysicalMemorySize();
-  if (size == 0) {
-    MS_LOG(("Failed to get physical memory size"));
-    return NS_ERROR_FAILURE;
-  }
-
-  PRUint64 sizeMB = size >> 20;
-  properties->SetPropertyAsUint64(NS_LITERAL_STRING("mb"), sizeMB);
-  MS_LOG(("Logged memory mb=%ull", sizeMB));
-
-  nsresult rv = nsMetricsUtils::AddChildItem(
-      profile, NS_LITERAL_STRING("memory"), properties);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-nsresult
-nsProfileCollector::LogOS(nsIMetricsEventItem *profile)
-{
-  nsCOMPtr<nsIWritablePropertyBag2> properties;
-  nsMetricsUtils::NewPropertyBag(getter_AddRefs(properties));
-  NS_ENSURE_STATE(properties);
-
-  char buf[SYS_INFO_BUFFER_LENGTH];
-  if (PR_GetSystemInfo(PR_SI_SYSNAME, buf, sizeof(buf)) != PR_SUCCESS) {
-    MS_LOG(("Failed to get OS name"));
-    return NS_ERROR_FAILURE;
-  }
-
-  properties->SetPropertyAsACString(NS_LITERAL_STRING("name"),
-                                    nsDependentCString(buf));
-  MS_LOG(("Logged os name=%s", buf));
-
-  if (PR_GetSystemInfo(PR_SI_RELEASE, buf, sizeof(buf)) != PR_SUCCESS) {
-    MS_LOG(("Failed to get OS version"));
-    return NS_ERROR_FAILURE;
-  }
-
-  properties->SetPropertyAsACString(NS_LITERAL_STRING("version"),
-                                    nsDependentCString(buf));
-  MS_LOG(("Logged os version=%s", buf));
-
-  nsresult rv = nsMetricsUtils::AddChildItem(
-      profile, NS_LITERAL_STRING("os"), properties);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-nsresult
-nsProfileCollector::LogInstall(nsIMetricsEventItem *profile)
-{
-  nsCOMPtr<nsIWritablePropertyBag2> properties;
-  nsMetricsUtils::NewPropertyBag(getter_AddRefs(properties));
-  NS_ENSURE_STATE(properties);
-
-  nsCOMPtr<nsIXULAppInfo> appInfo =
-    do_GetService(XULAPPINFO_SERVICE_CONTRACTID);
-  NS_ENSURE_STATE(appInfo);
-
-  nsCString buildID;
-  appInfo->GetAppBuildID(buildID);
-  properties->SetPropertyAsACString(NS_LITERAL_STRING("buildid"), buildID);
-  MS_LOG(("Logged install buildid=%s", buildID.get()));
-
-  nsCOMPtr<nsIExtensionManager> em = do_GetService("@mozilla.org/extensions/manager;1");
-  NS_ENSURE_STATE(em);
-
-  nsCOMPtr<nsIUpdateItem> item;
-  nsresult rv = em->GetItemForID(NS_LITERAL_STRING("metrics@mozilla.org"), getter_AddRefs(item));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // get the metrics extension version
-  nsAutoString extversion;
-  rv = item->GetVersion(extversion);
-  NS_ENSURE_SUCCESS(rv, rv);
-  properties->SetPropertyAsAString(NS_LITERAL_STRING("extversion"), extversion);
-  
-  MS_LOG(("Logged install extversion=%s", NS_ConvertUTF16toUTF8(extversion).get()));
-
-  // get the application version
-  nsCString appversion;
-  appInfo->GetVersion(appversion);
-  properties->SetPropertyAsACString(NS_LITERAL_STRING("appversion"), appversion);
-
-  MS_LOG(("Logged install appversion=%s", appversion.get()));
-
-  // get the application locale
-  nsCOMPtr<nsILocaleService> ls = do_GetService(NS_LOCALESERVICE_CONTRACTID);
-  NS_ENSURE_STATE(ls);
-
-  nsCOMPtr<nsILocale> locale(nsnull);
-  rv = ls->GetApplicationLocale(getter_AddRefs(locale));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsAutoString l;
-  rv = locale->GetCategory(NS_LITERAL_STRING("NSILOCALE_CTYPE"), l);
-  NS_ENSURE_SUCCESS(rv, rv);
-  properties->SetPropertyAsAString(NS_LITERAL_STRING("locale"), l);
-
-  MS_LOG(("Logged install locale=%s", NS_ConvertUTF16toUTF8(l).get()));
-
-  // The file defaults/pref/channel-prefs.js is exlucded from any
-  // security update, so we can use its creation time as an indicator
-  // of when this installation was performed.
-
-  nsCOMPtr<nsIFile> prefsDirectory;
-  NS_GetSpecialDirectory(NS_APP_PREF_DEFAULTS_50_DIR,
-                         getter_AddRefs(prefsDirectory));
-
-  nsCOMPtr<nsILocalFile> channelPrefs = do_QueryInterface(prefsDirectory);
-  NS_ENSURE_STATE(channelPrefs);
-
-  rv = channelPrefs->Append(NS_LITERAL_STRING("channel-prefs.js"));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCString nativePath;
-  channelPrefs->GetNativePath(nativePath);
-  PRFileInfo64 fileInfo;
-  if (PR_GetFileInfo64(nativePath.get(), &fileInfo) == PR_SUCCESS) {
-    // Convert the time to seconds since the epoch
-    PRInt64 installTime = fileInfo.creationTime / PR_USEC_PER_SEC;
-
-    static const int kSecondsPerDay = 60 * 60 * 24;
-
-    // Round down to the nearest full day
-    installTime = ((installTime / kSecondsPerDay) * kSecondsPerDay);
-    properties->SetPropertyAsInt64(NS_LITERAL_STRING("installdate"),
-                                   installTime);
-    MS_LOG(("Logged install installdate=%lld", installTime));
-  }
-
-  // TODO: log default= based on default-browser selection
-  properties->SetPropertyAsBool(NS_LITERAL_STRING("default"), PR_TRUE);
-
-  rv = nsMetricsUtils::AddChildItem(profile,
-                                    NS_LITERAL_STRING("install"), properties);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-nsresult
-nsProfileCollector::LogExtensions(nsIMetricsEventItem *profile)
-{
-  nsCOMPtr<nsIMetricsEventItem> extensions;
-  nsMetricsService::get()->CreateEventItem(NS_LITERAL_STRING("extensions"),
-                                           getter_AddRefs(extensions));
-  NS_ENSURE_STATE(extensions);
-
-  ExtensionEnumerator enumerator;
-  nsresult rv = enumerator.Init();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = enumerator.LogExtensions(extensions);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = profile->AppendChild(extensions);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-nsresult
-nsProfileCollector::LogPlugins(nsIMetricsEventItem *profile)
-{
-  nsCOMPtr<nsIMetricsEventItem> plugins;
-  nsMetricsService::get()->CreateEventItem(NS_LITERAL_STRING("plugins"),
-                                           getter_AddRefs(plugins));
-  NS_ENSURE_STATE(plugins);
-
-  PluginEnumerator enumerator;
-  nsresult rv = enumerator.Init();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = enumerator.LogPlugins(plugins);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = profile->AppendChild(plugins);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-nsresult
-nsProfileCollector::LogDisplay(nsIMetricsEventItem *profile)
-{
-  nsCOMPtr<nsIWritablePropertyBag2> properties;
-  nsMetricsUtils::NewPropertyBag(getter_AddRefs(properties));
-  NS_ENSURE_STATE(properties);
-
-  nsCOMPtr<nsIScreenManager> screenManager =
-    do_GetService("@mozilla.org/gfx/screenmanager;1");
-  NS_ENSURE_STATE(screenManager);
-
-  nsCOMPtr<nsIScreen> primaryScreen;
-  screenManager->GetPrimaryScreen(getter_AddRefs(primaryScreen));
-  NS_ENSURE_STATE(primaryScreen);
-
-  PRInt32 left, top, width, height;
-  nsresult rv = primaryScreen->GetRect(&left, &top, &width, &height);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  properties->SetPropertyAsInt32(NS_LITERAL_STRING("xsize"), width);
-  properties->SetPropertyAsInt32(NS_LITERAL_STRING("ysize"), height);
-  MS_LOG(("Logged display xsize=%d ysize=%d", width, height));
-
-  PRUint32 numScreens = 0;
-  if (NS_SUCCEEDED(screenManager->GetNumberOfScreens(&numScreens))) {
-    properties->SetPropertyAsUint32(NS_LITERAL_STRING("screens"), numScreens);
-    MS_LOG(("Logged display screens=%d", numScreens));
-  } else {
-    MS_LOG(("Could not get number of screens"));
-  }
-
-  rv = nsMetricsUtils::AddChildItem(profile,
-                                    NS_LITERAL_STRING("display"), properties);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-nsresult
-nsProfileCollector::LogBookmarks(nsIMetricsEventItem *profile)
-{
-  nsresult rv;
-
-  nsMetricsService *ms = nsMetricsService::get();
-  NS_ENSURE_STATE(ms);
-
-  nsCOMPtr<nsIMetricsEventItem> bookmarksItem;
-  ms->CreateEventItem(NS_LITERAL_STRING("bookmarks"),
-                      getter_AddRefs(bookmarksItem));
-  NS_ENSURE_STATE(bookmarksItem);
-
-  nsCOMPtr<nsINavBookmarksService> bmSvc =
-    do_GetService(NS_NAVBOOKMARKSSERVICE_CONTRACTID);
-  NS_ENSURE_STATE(bmSvc);
-
-  PRInt64 root = 0;
-  rv = bmSvc->GetPlacesRoot(&root);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  BookmarkCounter counter;
-  rv = counter.Init();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  LogBookmarkLocation(bookmarksItem, NS_LITERAL_CSTRING("full-tree"),
-                      &counter, root, PR_TRUE);
-
-  rv = bmSvc->GetBookmarksMenuFolder(&root);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  LogBookmarkLocation(bookmarksItem, NS_LITERAL_CSTRING("root"),
-                      &counter, root, PR_FALSE);
-
-  rv = bmSvc->GetToolbarFolder(&root);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  LogBookmarkLocation(bookmarksItem, NS_LITERAL_CSTRING("toolbar"),
-                  &counter, root, PR_FALSE);
-
-  rv = profile->AppendChild(bookmarksItem);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-void
-nsProfileCollector::LogBookmarkLocation(nsIMetricsEventItem *bookmarksItem,
-                                        const nsACString &location,
-                                        BookmarkCounter *counter,
-                                        PRInt64 root,
-                                        PRBool deep)
-{
-  nsTArray<PRInt32> count;
-  counter->CountChildren(root, deep, count);
-
-  nsCOMPtr<nsIWritablePropertyBag2> props;
-  nsMetricsUtils::NewPropertyBag(getter_AddRefs(props));
-  if (!props) {
-    return;
-  }
-
-  props->SetPropertyAsACString(NS_LITERAL_STRING("name"), location);
-  props->SetPropertyAsInt32(NS_LITERAL_STRING("itemcount"),
-                            count[BookmarkCounter::ITEM]);
-  props->SetPropertyAsInt32(NS_LITERAL_STRING("foldercount"),
-                            count[BookmarkCounter::FOLDER]);