Merge mozilla-central to tracemonkey.
authorRobert Sayre <sayrer@gmail.com>
Wed, 31 Mar 2010 12:47:53 -0700
changeset 40420 c03d8f9f6b5641a192a0fbe705c5ac6f34b474f1
parent 40416 427b42ddeb2e7f4091cd16ca7821b4a2d5f80a97 (current diff)
parent 40070 c6e18218ed8e9ea8ccb548b9b3a156867610058b (diff)
child 40421 b2f90065b52d225f8823fb33492c680945fd5cb7
push id12610
push userrsayre@mozilla.com
push dateMon, 05 Apr 2010 17:26:41 +0000
treeherdermozilla-central@1942c0b4e101 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone1.9.3a4pre
Merge mozilla-central to tracemonkey.
config/insure.mk
configure.in
content/base/src/nsContentUtils.cpp
dom/base/nsDOMClassInfo.cpp
js/src/config/insure.mk
js/src/configure.in
js/src/xpconnect/idl/nsIXPConnect.idl
js/src/xpconnect/src/nsXPConnect.cpp
js/src/xpconnect/src/xpcwrappednative.cpp
--- a/accessible/src/base/nsCaretAccessible.cpp
+++ b/accessible/src/base/nsCaretAccessible.cpp
@@ -317,18 +317,17 @@ nsCaretAccessible::GetCaretRect(nsIWidge
   nsCOMPtr<nsIDOMNode> lastNodeWithCaret;
   lastAccessNode->GetDOMNode(getter_AddRefs(lastNodeWithCaret));
   NS_ENSURE_TRUE(lastNodeWithCaret, caretRect);
 
   nsCOMPtr<nsIPresShell> presShell =
     nsCoreUtils::GetPresShellFor(lastNodeWithCaret);
   NS_ENSURE_TRUE(presShell, caretRect);
 
-  nsRefPtr<nsCaret> caret;
-  presShell->GetCaret(getter_AddRefs(caret));
+  nsRefPtr<nsCaret> caret = presShell->GetCaret();
   NS_ENSURE_TRUE(caret, caretRect);
 
   nsCOMPtr<nsISelection> caretSelection(do_QueryReferent(mLastUsedSelection));
   NS_ENSURE_TRUE(caretSelection, caretRect);
   
   PRBool isVisible;
   caret->GetCaretVisible(&isVisible);
   if (!isVisible) {
--- a/accessible/tests/mochitest/tree/test_tabbrowser.xul
+++ b/accessible/tests/mochitest/tree/test_tabbrowser.xul
@@ -59,19 +59,16 @@
     }
 
     function testAccTree()
     {
       var tabsAccTree = {
         role: ROLE_PAGETABLIST,
         children: [
           {
-            role: ROLE_MENUPOPUP
-          },
-          {
             role: ROLE_PAGETAB,
             children: [
               {
                 role: ROLE_PUSHBUTTON
               }
             ]
           },
           {
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -7620,8 +7620,28 @@ function switchToTabHavingURI(aURI) {
     if (browserWin.closed || browserWin == window)
       continue;
     if (switchIfURIInWindow(browserWin))
       return true;
   }
   // No opened tab has that url.
   return false;
 }
+
+var TabContextMenu = {
+  contextTab: null,
+  updateContextMenu: function updateContextMenu(aPopupMenu) {
+    this.contextTab = document.popupNode.localName == "tab" ?
+                      document.popupNode : gBrowser.selectedTab;
+    var disabled = gBrowser.tabs.length == 1;
+    var menuItems = aPopupMenu.getElementsByAttribute("tbattr", "tabbrowser-multiple");
+    for (var i = 0; i < menuItems.length; i++)
+      menuItems[i].disabled = disabled;
+
+    // Session store
+    // XXXzeniko should't we just disable this item as we disable
+    // the tabbrowser-multiple items above - for consistency?
+    document.getElementById("context_undoCloseTab").hidden =
+      Cc["@mozilla.org/browser/sessionstore;1"].
+      getService(Ci.nsISessionStore).
+      getClosedTabCount(window) == 0;
+  }
+}
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -105,16 +105,54 @@
      rely on the new Drag and Drop API these dependencies should be removed. -->
 <script type="application/javascript" src="chrome://global/content/nsDragAndDrop.js"/>
 
 # All sets except for popupsets (commands, keys, stringbundles and broadcasters) *must* go into the 
 # browser-sets.inc file for sharing with hiddenWindow.xul.
 #include browser-sets.inc
 
   <popupset id="mainPopupSet">
+    <menupopup id="tabContextMenu"
+               onpopupshowing="if (event.target == this) TabContextMenu.updateContextMenu(this);"
+               onpopuphidden="if (event.target == this) TabContextMenu.contextTab = null;">
+      <menuitem id="context_newTab" label="&newTab.label;" accesskey="&newTab.accesskey;"
+                command="cmd_newNavigatorTab"/>
+      <menuseparator/>
+      <menuitem id="context_reloadTab" label="&reloadTab.label;" accesskey="&reloadTab.accesskey;"
+                oncommand="gBrowser.reloadTab(TabContextMenu.contextTab);"/>
+      <menuitem id="context_reloadAllTabs" label="&reloadAllTabs.label;" accesskey="&reloadAllTabs.accesskey;"
+                tbattr="tabbrowser-multiple"
+                oncommand="gBrowser.reloadAllTabs();"/>
+      <menuitem id="context_closeOtherTabs" label="&closeOtherTabs.label;" accesskey="&closeOtherTabs.accesskey;"
+                tbattr="tabbrowser-multiple"
+                oncommand="gBrowser.removeAllTabsBut(TabContextMenu.contextTab);"/>
+      <menuseparator/>
+      <menuitem id="context_openTabInWindow" label="&openTabInNewWindow.label;"
+                accesskey="&openTabInNewWindow.accesskey;"
+                tbattr="tabbrowser-multiple"
+                oncommand="gBrowser.replaceTabWithWindow(TabContextMenu.contextTab);"/>
+      <menuseparator/>
+      <menuitem id="context_bookmarkTab"
+                label="&bookmarkThisTab.label;"
+                accesskey="&bookmarkThisTab.accesskey;"
+                oncommand="BookmarkThisTab(TabContextMenu.contextTab);"/>
+      <menuitem id="context_bookmarkAllTabs"
+                label="&bookmarkAllTabs.label;"
+                accesskey="&bookmarkAllTabs.accesskey;"
+                command="Browser:BookmarkAllTabs"/>
+      <menuitem id="context_undoCloseTab"
+                label="&undoCloseTab.label;"
+                accesskey="&undoCloseTab.accesskey;"
+                command="History:UndoCloseTab"/>
+      <menuseparator/>
+      <menuitem id="context_closeTab" label="&closeTab.label;" accesskey="&closeTab.accesskey;"
+                tbattr="tabbrowser-multiple"
+                oncommand="gBrowser.removeTab(TabContextMenu.contextTab);"/>
+    </menupopup>
+
     <menupopup id="backForwardMenu"
                onpopupshowing="return FillHistoryMenu(event.target);"
                oncommand="gotoHistoryIndex(event);"
                onclick="checkForMiddleClick(this, event);"/>
     <tooltip id="aHTMLTooltip" onpopupshowing="return FillInHTMLTooltip(document.tooltipNode);"/>
 
     <!-- for search and content formfill/pw manager -->
     <panel type="autocomplete" id="PopupAutoComplete" noautofocus="true" hidden="true"/>
@@ -516,17 +554,19 @@
                tooltip="bhTooltip" popupsinherittooltip="true"/>
       </toolbaritem>
     </toolbar>
 
     <toolbar id="TabsToolbar"
              fullscreentoolbar="true"
              ordinal="100"
              collapsed="true">
-      <tabs id="tabbrowser-tabs" class="tabbrowser-tabs"
+      <tabs id="tabbrowser-tabs"
+            class="tabbrowser-tabs"
+            context="tabContextMenu"
             tabbrowser="content"
             flex="1"
             setfocus="false"
             tooltip="tabbrowser-tab-tooltip">
         <tab class="tabbrowser-tab" selected="true"/>
       </tabs>
     </toolbar>
 
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -2295,17 +2295,17 @@
         </body>
       </method>
       <method name="getStripVisibility">
         <body>
           return this.tabContainer.visible;
         </body>
       </method>
       <property name="mContextTab" readonly="true"
-                onget="return this.tabContainer._contextTab;"/>
+                onget="return TabContextMenu.contextTab;"/>
       <property name="mPrefs" readonly="true"
                 onget="return Services.prefs;"/>
       <property name="mTabContainer" readonly="true"
                 onget="return this.tabContainer;"/>
       <property name="mTabs" readonly="true"
                 onget="return this.tabs;"/>
       <!--
         - Compatibility hack: several extensions depend on this property to
@@ -2417,57 +2417,20 @@
   </binding>
 
   <binding id="tabbrowser-tabs"
            extends="chrome://global/content/bindings/tabbox.xml#tabs">
     <resources>
       <stylesheet src="chrome://browser/content/tabbrowser.css"/>
     </resources>
 
-    <content context="_child">
+    <content>
       <xul:hbox align="start">
         <xul:image class="tab-drop-indicator" anonid="tab-drop-indicator" collapsed="true"/>
       </xul:hbox>
-      <xul:menupopup anonid="tabContextMenu"
-                     onpopupshowing="if (event.target == this) this.parentNode._updateContextMenu(this);"
-                     onpopuphidden="if (event.target == this) this.parentNode._contextTab = null;">
-        <xul:menuitem id="context_newTab" label="&newTab.label;" accesskey="&newTab.accesskey;"
-                      command="cmd_newNavigatorTab"/>
-        <xul:menuseparator/>
-        <xul:menuitem id="context_reloadTab" label="&reloadTab.label;" accesskey="&reloadTab.accesskey;"
-                      oncommand="this.parentNode.parentNode._contextMenuAction('reloadTab');"/>
-        <xul:menuitem id="context_reloadAllTabs" label="&reloadAllTabs.label;" accesskey="&reloadAllTabs.accesskey;"
-                      tbattr="tabbrowser-multiple"
-                      oncommand="this.parentNode.parentNode._contextMenuAction('reloadAllTabs');"/>
-        <xul:menuitem id="context_closeOtherTabs" label="&closeOtherTabs.label;" accesskey="&closeOtherTabs.accesskey;"
-                      tbattr="tabbrowser-multiple"
-                      oncommand="this.parentNode.parentNode._contextMenuAction('removeAllTabsBut');"/>
-        <xul:menuseparator/>
-        <xul:menuitem id="context_openTabInWindow" label="&openTabInNewWindow.label;"
-                      accesskey="&openTabInNewWindow.accesskey;"
-                      tbattr="tabbrowser-multiple"
-                      oncommand="this.parentNode.parentNode._contextMenuAction('replaceTabWithWindow');"/>
-        <xul:menuseparator/>
-        <xul:menuitem id="context_bookmarkTab"
-                      label="&bookmarkThisTab.label;"
-                      accesskey="&bookmarkThisTab.accesskey;"
-                      oncommand="this.parentNode.parentNode._contextMenuAction('BookmarkThisTab', window);"/>
-        <xul:menuitem id="context_bookmarkAllTabs"
-                      label="&bookmarkAllTabs.label;"
-                      accesskey="&bookmarkAllTabs.accesskey;"
-                      command="Browser:BookmarkAllTabs"/>
-        <xul:menuitem id="context_undoCloseTab"
-                      label="&undoCloseTab.label;"
-                      accesskey="&undoCloseTab.accesskey;"
-                      command="History:UndoCloseTab"/>
-        <xul:menuseparator/>
-        <xul:menuitem id="context_closeTab" label="&closeTab.label;" accesskey="&closeTab.accesskey;"
-                      tbattr="tabbrowser-multiple"
-                      oncommand="this.parentNode.parentNode._contextMenuAction('removeTab');"/>
-      </xul:menupopup>
       <xul:arrowscrollbox anonid="arrowscrollbox" orient="horizontal" flex="1"
                           style="min-width: 1px;"
 #ifndef XP_MACOSX
                           clicktoscroll="true"
 #endif
                           class="tabbrowser-arrowscrollbox">
 # This is a hack to circumvent bug 472020, otherwise the tabs show up on the
 # right of the newtab button.
@@ -2533,17 +2496,17 @@
         document.getElementById(this.getAttribute("tabbrowser"));
       </field>
 
       <field name="tabbox" readonly="true">
         this.tabbrowser.mTabBox;
       </field>
 
       <field name="contextMenu" readonly="true">
-        document.getAnonymousElementByAttribute(this, "anonid", "tabContextMenu");
+        document.getElementById(this.getAttribute("context"));
       </field>
 
       <field name="mTabstripWidth">0</field>
 
       <field name="mTabstrip">
         document.getAnonymousElementByAttribute(this, "anonid", "arrowscrollbox");
       </field>
 
@@ -2720,45 +2683,16 @@
             this._animateElement.setAttribute("notifybgtab", "true");
             setTimeout(function (ele) {
               ele.removeAttribute("notifybgtab");
             }, 150, this._animateElement);
           }
         ]]></body>
       </method>
 
-      <field name="_contextTab">null</field>
-      <method name="_updateContextMenu">
-        <parameter name="aPopupMenu"/>
-        <body><![CDATA[
-          this._contextTab = document.popupNode.localName == "tab" ?
-                             document.popupNode : this.selectedItem;
-          var disabled = this.childNodes.length == 1;
-          var menuItems = aPopupMenu.getElementsByAttribute("tbattr", "tabbrowser-multiple");
-          for (var i = 0; i < menuItems.length; i++)
-            menuItems[i].disabled = disabled;
-
-          // Session store
-          // XXXzeniko should't we just disable this item as we disable
-          // the tabbrowser-multiple items above - for consistency?
-          document.getElementById("context_undoCloseTab").hidden =
-            Cc["@mozilla.org/browser/sessionstore;1"].
-            getService(Ci.nsISessionStore).
-            getClosedTabCount(window) == 0;
-        ]]></body>
-      </method>
-
-      <method name="_contextMenuAction">
-        <parameter name="aMethod"/>
-        <parameter name="aContext"/>
-        <body><![CDATA[
-          (aContext || this.tabbrowser)[aMethod](this._contextTab);
-        ]]></body>
-      </method>
-
       <method name="_getDragTargetTab">
         <parameter name="event"/>
         <body><![CDATA[
           return event.target.localName == "tab" ? event.target : null;
         ]]></body>
       </method>
 
       <method name="_getDropIndex">
--- a/browser/confvars.sh
+++ b/browser/confvars.sh
@@ -37,17 +37,16 @@
 # ***** END LICENSE BLOCK *****
 
 MOZ_APP_NAME=firefox
 MOZ_UPDATER=1
 MOZ_PHOENIX=1
 
 MOZ_ENABLE_LIBXUL=1
 MOZ_STATIC_BUILD_UNSUPPORTED=1
-MOZ_PLACES=1
 # always enabled for form history
 MOZ_MORKREADER=1
 MOZ_SAFE_BROWSING=1
 MOZ_APP_VERSION=$FIREFOX_VERSION
 MOZ_EXTENSIONS_DEFAULT=" gnomevfs reporter"
 # MOZ_APP_DISPLAYNAME will be set by branding/configure.sh
 MOZ_BRANDING_DIRECTORY=browser/branding/nightly
 MOZ_OFFICIAL_BRANDING_DIRECTORY=other-licenses/branding/firefox
--- a/browser/locales/en-US/chrome/browser/browser.dtd
+++ b/browser/locales/en-US/chrome/browser/browser.dtd
@@ -6,16 +6,36 @@
 <!-- LOCALIZATION NOTE (mainWindow.titlemodifier) : DONT_TRANSLATE -->
 <!ENTITY mainWindow.titlemodifier "&brandFullName;">
 <!-- LOCALIZATION NOTE (mainWindow.titlemodifiermenuseparator): DONT_TRANSLATE -->
 <!ENTITY mainWindow.titlemodifiermenuseparator " - ">
 <!-- LOCALIZATION NOTE (mainWindow.titlePrivateBrowsingSuffix): This will be appended to the window's title
                                                                 inside the private browsing mode -->
 <!ENTITY mainWindow.titlePrivateBrowsingSuffix "(Private Browsing)">
 
+<!-- Tab context menu -->
+<!ENTITY  newTab.label                       "New Tab">
+<!ENTITY  newTab.accesskey                   "N">
+<!ENTITY  reloadTab.label                    "Reload Tab">
+<!ENTITY  reloadTab.accesskey                "R">
+<!ENTITY  reloadAllTabs.label                "Reload All Tabs">
+<!ENTITY  reloadAllTabs.accesskey            "A">
+<!ENTITY  closeOtherTabs.label               "Close Other Tabs">
+<!ENTITY  closeOtherTabs.accesskey           "o">
+<!ENTITY  openTabInNewWindow.label           "Open in a New Window">
+<!ENTITY  openTabInNewWindow.accesskey       "W">
+<!ENTITY  bookmarkThisTab.label              "Bookmark This Tab">
+<!ENTITY  bookmarkThisTab.accesskey          "B">
+<!ENTITY  bookmarkAllTabs.label              "Bookmark All Tabs…">
+<!ENTITY  bookmarkAllTabs.accesskey          "T">
+<!ENTITY  undoCloseTab.label                 "Undo Close Tab">
+<!ENTITY  undoCloseTab.accesskey             "U">
+<!ENTITY  closeTab.label                     "Close Tab">
+<!ENTITY  closeTab.accesskey                 "c">
+
 <!ENTITY tabCmd.label "New Tab">
 <!ENTITY tabCmd.accesskey "T">
 <!ENTITY tabCmd.commandkey "t">
 <!ENTITY openLocationCmd.label "Open Location…">
 <!ENTITY openLocationCmd.accesskey "L">
 <!ENTITY openFileCmd.label "Open File…">
 <!ENTITY openFileCmd.accesskey "O">
 <!ENTITY openFileCmd.commandkey "o">
--- a/browser/locales/en-US/chrome/browser/tabbrowser.dtd
+++ b/browser/locales/en-US/chrome/browser/tabbrowser.dtd
@@ -1,20 +1,3 @@
-<!ENTITY  newTab.label           "New Tab">
-<!ENTITY  newTab.accesskey       "N">
 <!ENTITY  closeTab.label         "Close Tab">
-<!ENTITY  closeTab.accesskey         "c">
-<!ENTITY  closeOtherTabs.accesskey  "o">
-<!ENTITY  closeOtherTabs.label   "Close Other Tabs">
-<!ENTITY  reloadAllTabs.label    "Reload All Tabs">
-<!ENTITY  reloadAllTabs.accesskey         "A">
-<!ENTITY  reloadTab.label        "Reload Tab">
-<!ENTITY  reloadTab.accesskey         "r">
-<!ENTITY  openTabInNewWindow.label    "Open in a New Window">
-<!ENTITY  openTabInNewWindow.accesskey "W">
 <!ENTITY  listAllTabs.label      "List all tabs">
-<!ENTITY  bookmarkAllTabs.label       "Bookmark All Tabs…">
-<!ENTITY  bookmarkAllTabs.accesskey   "T">
-<!ENTITY  bookmarkThisTab.label       "Bookmark This Tab">
-<!ENTITY  bookmarkThisTab.accesskey   "B">
-<!ENTITY  undoCloseTab.label          "Undo Close Tab">
-<!ENTITY  undoCloseTab.accesskey      "U">
 <!ENTITY  newTabButton.tooltip        "Open a new tab">
--- a/browser/themes/winstripe/browser/browser.css
+++ b/browser/themes/winstripe/browser/browser.css
@@ -253,17 +253,17 @@ toolbar[iconsize="small"][mode="icons"] 
 .toolbarbutton-menubutton-button[disabled="true"],
 .toolbarbutton-menubutton-dropmarker[disabled="true"],
 .toolbarbutton-1[disabled="true"] {
   opacity: .8;
 }
 
 .toolbarbutton-menubutton-button[disabled="true"] > .toolbarbutton-icon,
 .toolbarbutton-1[disabled="true"] > .toolbarbutton-icon {
-  opacity: .6;
+  opacity: .5;
 }
 
 .toolbarbutton-menubutton-button:not([disabled="true"]):not(:active):hover,
 toolbarbutton[type="menu-button"]:not([open="true"]):not(:active):hover > .toolbarbutton-menubutton-dropmarker:not([disabled="true"]),
 .toolbarbutton-1:not([disabled="true"]):not([checked="true"]):not(:active):hover {
   background-color: hsla(190,60%,70%,.5);
   border-color: hsla(190,50%,65%,.8) hsla(190,50%,50%,.8) hsla(190,50%,40%,.8);
   -moz-box-shadow: 0 0 0 1px rgba(255,255,255,.3) inset,
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -257,21 +257,16 @@ MOZ_GCONF_CFLAGS = @MOZ_GCONF_CFLAGS@
 MOZ_GCONF_LIBS = @MOZ_GCONF_LIBS@
 
 MOZ_ENABLE_GNOME_COMPONENT = @MOZ_ENABLE_GNOME_COMPONENT@
 
 MOZ_ENABLE_GIO = @MOZ_ENABLE_GIO@
 MOZ_GIO_CFLAGS = @MOZ_GIO_CFLAGS@
 MOZ_GIO_LIBS = @MOZ_GIO_LIBS@
 
-MOZ_INSURE = @MOZ_INSURE@
-MOZ_INSURIFYING = @MOZ_INSURIFYING@
-MOZ_INSURE_DIRS = @MOZ_INSURE_DIRS@
-MOZ_INSURE_EXCLUDE_DIRS = @MOZ_INSURE_EXCLUDE_DIRS@
-
 MOZ_NATIVE_NSPR = @MOZ_NATIVE_NSPR@
 MOZ_NATIVE_NSS = @MOZ_NATIVE_NSS@
 
 BUILD_CTYPES = @BUILD_CTYPES@
 
 COMPILE_ENVIRONMENT = @COMPILE_ENVIRONMENT@
 CROSS_COMPILE   = @CROSS_COMPILE@
 
--- a/config/config.mk
+++ b/config/config.mk
@@ -51,21 +51,16 @@ EXIT_ON_ERROR = set -e; # Shell loops co
 
 ifndef topsrcdir
 topsrcdir	= $(DEPTH)
 endif
 
 ifndef INCLUDED_AUTOCONF_MK
 include $(DEPTH)/config/autoconf.mk
 endif
-ifndef INCLUDED_INSURE_MK
-ifdef MOZ_INSURIFYING
-include $(topsrcdir)/config/insure.mk
-endif
-endif
 
 COMMA = ,
 
 # Sanity check some variables
 CHECK_VARS := \
  XPI_NAME \
  LIBRARY_NAME \
  MODULE \
deleted file mode 100644
--- a/config/insure.mk
+++ /dev/null
@@ -1,53 +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
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either of 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 *****
-
-INCLUDED_INSURE_MK = 1
-
-INSURE_MATCH_SCRIPT=$(topsrcdir)/build/autoconf/match-dir.sh
-
-INSURE_EXCLUDE=$(shell $(INSURE_MATCH_SCRIPT) $(MOZ_INSURE_EXCLUDE_DIRS))
-
-INSURE_INCLUDE=$(shell $(INSURE_MATCH_SCRIPT) $(MOZ_INSURE_DIRS))
-
-ifeq ($(INSURE_EXCLUDE),0)
-
-ifeq ($(INSURE_INCLUDE),1)
-CC		:= $(MOZ_INSURE)
-CXX		:= $(MOZ_INSURE)
-endif # INSURE_INCLUDE == 1
-
-endif # INSURE_EXCLUDE == 0
--- a/configure.in
+++ b/configure.in
@@ -4722,17 +4722,17 @@ MOZ_NO_ACTIVEX_SUPPORT=1
 MOZ_NO_INSPECTOR_APIS=
 MOZ_NO_FAST_LOAD=
 MOZ_OGG=1
 MOZ_SYDNEYAUDIO=
 MOZ_WAVE=1
 MOZ_MEDIA=
 MOZ_PANGO=1
 MOZ_PERMISSIONS=1
-MOZ_PLACES=
+MOZ_PLACES=1
 MOZ_PLAINTEXT_EDITOR_ONLY=
 MOZ_PLUGINS=1
 MOZ_PREF_EXTENSIONS=1
 MOZ_PROFILELOCKING=1
 MOZ_PSM=1
 MOZ_RDF=1
 MOZ_REFLOW_PERF=
 MOZ_SAFE_BROWSING=
@@ -6302,33 +6302,26 @@ AC_SUBST(MOZ_DISABLE_PARENTAL_CONTROLS)
 dnl ========================================================
 dnl =
 dnl = Module specific options
 dnl =
 dnl ========================================================
 MOZ_ARG_HEADER(Individual module options)
 
 dnl ========================================================
-dnl = Enable places (new history/bookmarks)
-dnl ========================================================
-MOZ_ARG_ENABLE_BOOL(places,
-[  --enable-places        Enable 'places' bookmark/history implementation],
-    MOZ_PLACES=1,
-    MOZ_PLACES= )
+dnl = Places, no configure argument
+dnl ========================================================
 if test -n "$MOZ_PLACES"; then
     AC_DEFINE(MOZ_PLACES)
     if test -z "$MOZ_MAIL_NEWS"; then
       MOZ_MORK=
     fi
     MOZ_MORKREADER=1
-else
-  if test "$MOZ_BUILD_APP" = "browser"; then
-    AC_MSG_ERROR([Cannot build Firefox with --disable-places.])
-  fi
-fi
+fi
+
 
 dnl ========================================================
 dnl = Disable feed handling components
 dnl ========================================================
 MOZ_ARG_DISABLE_BOOL(feeds,
 [  --disable-feeds        Disable feed handling and processing components],
     MOZ_FEEDS=,
     MOZ_FEEDS=1 )
@@ -6459,31 +6452,16 @@ else
     if test "x$ac_cv_sqlite_enable_fts3" = "xno"; then
         AC_MSG_ERROR([System SQLite library is not compiled with SQLITE_ENABLE_FTS3.])
     fi
 fi
 
 AC_SUBST(MOZ_NATIVE_SQLITE)
 
 dnl ========================================================
-dnl = Enable help viewer (off by default)
-dnl ========================================================
-MOZ_ARG_ENABLE_BOOL(help-viewer,
-[  --enable-help-viewer        Enable help viewer],
-    MOZ_HELP_VIEWER=1,
-    MOZ_HELP_VIEWER= )
-if test -n "$MOZ_HELP_VIEWER"; then
-     AC_DEFINE(MOZ_HELP_VIEWER)
-fi
-AC_SUBST(MOZ_HELP_VIEWER)
-if test "$MOZ_BUILD_APP" = "browser" -a -n "$MOZ_HELP_VIEWER"; then
-    AC_MSG_ERROR([Cannot build Firefox with --enable-help-viewer.])
-fi
-
-dnl ========================================================
 dnl = Enable safe browsing (anti-phishing)
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(safe-browsing,
 [  --enable-safe-browsing        Enable safe browsing (anti-phishing) implementation],
     MOZ_SAFE_BROWSING=1,
     MOZ_SAFE_BROWSING= )
 if test -n "$MOZ_SAFE_BROWSING"; then
     AC_DEFINE(MOZ_SAFE_BROWSING)
@@ -7168,37 +7146,16 @@ MOZ_ARG_ENABLE_BOOL(codesighs,
 if test -n "$_ENABLE_CODESIGHS"; then
     if test -d $srcdir/tools/codesighs; then 
         MOZ_MAPINFO=1
     else
         AC_MSG_ERROR([Codesighs directory $srcdir/tools/codesighs required.])
     fi
 fi
 
-MOZ_ARG_ENABLE_BOOL(insure,
-[  --enable-insure         Enable insure++ instrumentation (linux only)],
-    _ENABLE_INSURE=1,
-    _ENABLE_INSURE= )
-if test -n "$_ENABLE_INSURE"; then
-    MOZ_INSURE="insure"
-    MOZ_INSURIFYING=1
-    MOZ_INSURE_DIRS="."
-    MOZ_INSURE_EXCLUDE_DIRS="config"
-fi
-
-MOZ_ARG_WITH_STRING(insure-dirs,
-[  --with-insure-dirs=DIRS
-                          Dirs to instrument with insure ],
-    MOZ_INSURE_DIRS=$withval )
-
-MOZ_ARG_WITH_STRING(insure-exclude-dirs,
-[  --with-insure-exclude-dirs=DIRS
-                          Dirs to not instrument with insure ],
-    MOZ_INSURE_EXCLUDE_DIRS="config $withval" )
-
 dnl ========================================================
 dnl = Support for Quantify (Windows)
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(quantify,
 [  --enable-quantify      Enable Quantify support (Windows only) ],
     MOZ_QUANTIFY=1,
     MOZ_QUANTIFY= )
 
@@ -8249,29 +8206,26 @@ AC_SUBST(MOZ_LOG_REFCNT)
 AC_SUBST(MOZ_LEAKY)
 AC_SUBST(MOZ_JPROF)
 AC_SUBST(MOZ_SHARK)
 AC_SUBST(MOZ_CALLGRIND)
 AC_SUBST(MOZ_VTUNE)
 AC_SUBST(MOZ_XPCTOOLS)
 AC_SUBST(MOZ_JSLOADER)
 AC_SUBST(MOZ_USE_NATIVE_UCONV)
-AC_SUBST(MOZ_INSURE)
-AC_SUBST(MOZ_INSURE_DIRS)
-AC_SUBST(MOZ_INSURE_EXCLUDE_DIRS)
 AC_SUBST(MOZ_QUANTIFY)
-AC_SUBST(MOZ_INSURIFYING)
 AC_SUBST(LIBICONV)
 AC_SUBST(MOZ_PLACES)
 AC_SUBST(MOZ_PLACES_BOOKMARKS)
 AC_SUBST(MOZ_STORAGE)
 AC_SUBST(MOZ_TOOLKIT_SEARCH)
 AC_SUBST(MOZ_FEEDS)
 AC_SUBST(NS_PRINTING)
 AC_SUBST(MOZ_WEBGL)
+AC_SUBST(MOZ_HELP_VIEWER)
 
 AC_SUBST(MOZ_JAVAXPCOM)
 AC_SUBST(JAVA_INCLUDE_PATH)
 AC_SUBST(JAVA)
 AC_SUBST(JAVAC)
 AC_SUBST(JAR)
 
 AC_SUBST(MOZ_PROFILELOCKING)
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -1300,17 +1300,17 @@ nsContentUtils::ReparentContentWrappersI
   JSObject *newScopeObj = aNewScope->GetGlobalJSObject();
 
   if (!newScopeObj || !oldScopeObj) {
     // We can't really do anything without the JSObjects.
 
     return NS_ERROR_NOT_AVAILABLE;
   }
 
-  return sXPConnect->ReparentScopeAwareWrappers(cx, oldScopeObj, newScopeObj);
+  return sXPConnect->MoveWrappers(cx, oldScopeObj, newScopeObj);
 }
 
 nsIDocShell *
 nsContentUtils::GetDocShellFromCaller()
 {
   JSContext *cx = nsnull;
   sThreadJSContextStack->Peek(&cx);
 
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -2913,25 +2913,27 @@ nsGenericElement::doPreHandleEvent(nsICo
     nsCOMPtr<nsIContent> content(do_QueryInterface(aVisitor.mEvent->target));
     if (content && content->GetBindingParent() == parent) {
       aVisitor.mEventTargetAtParent = parent;
     }
   }
 
   // check for an anonymous parent
   // XXX XBL2/sXBL issue
-  nsIDocument* ownerDoc = aContent->GetOwnerDoc();
-  if (ownerDoc) {
-    nsIContent* insertionParent = ownerDoc->BindingManager()->
-      GetInsertionParent(aContent);
-    NS_ASSERTION(!(aVisitor.mEventTargetAtParent && insertionParent &&
-                   aVisitor.mEventTargetAtParent != insertionParent),
-                 "Retargeting and having insertion parent!");
-    if (insertionParent) {
-      parent = insertionParent;
+  if (aContent->HasFlag(NODE_MAY_BE_IN_BINDING_MNGR)) {
+    nsIDocument* ownerDoc = aContent->GetOwnerDoc();
+    if (ownerDoc) {
+      nsIContent* insertionParent = ownerDoc->BindingManager()->
+        GetInsertionParent(aContent);
+      NS_ASSERTION(!(aVisitor.mEventTargetAtParent && insertionParent &&
+                     aVisitor.mEventTargetAtParent != insertionParent),
+                   "Retargeting and having insertion parent!");
+      if (insertionParent) {
+        parent = insertionParent;
+      }
     }
   }
 
   if (parent) {
     aVisitor.mParentTarget = parent;
   } else {
     aVisitor.mParentTarget = aContent->GetCurrentDoc();
   }
--- a/content/base/src/nsImageLoadingContent.cpp
+++ b/content/base/src/nsImageLoadingContent.cpp
@@ -302,19 +302,17 @@ nsImageLoadingContent::OnStopDecode(imgI
     // returns false
     if (!shell->DidInitialReflow())
       doRequestDecode = PR_TRUE;
 
     // Figure out if painting is suppressed. Note that it's possible for painting
     // to be suppressed for reasons other than the initial paint delay (for
     // example - being in the bfcache), but we probably aren't loading images in
     // those situations.
-    PRBool isSuppressed = PR_FALSE;
-    nsresult rv = shell->IsPaintingSuppressed(&isSuppressed);
-    if (NS_SUCCEEDED(rv) && isSuppressed)
+    if (shell->IsPaintingSuppressed())
       doRequestDecode = PR_TRUE;
 
     // If we're requesting a decode, do it
     if (doRequestDecode)
       aRequest->RequestDecode();
   }
 
   // XXXldb What's the difference between when OnStopDecode and OnStopRequest
--- a/content/base/test/file_bug416317.xhtml
+++ b/content/base/test/file_bug416317.xhtml
@@ -709,16 +709,21 @@
       t( "Child escaped Class", "form > .foo\\:bar", ["foo:bar"] );
       t( "Child escaped Class", "form > .test\\.foo\\[5\\]bar", ["test.foo[5]bar"] );
 
       t( "Comma Support", "a.blog, p", ['firstp','ap','mark','sndp','en','sap','simon','first'] );
       t( "Comma Support", "a.blog , p", ['firstp','ap','mark','sndp','en','sap','simon','first'] );
       t( "Comma Support", "a.blog ,p", ['firstp','ap','mark','sndp','en','sap','simon','first'] );
       t( "Comma Support", "a.blog,p", ['firstp','ap','mark','sndp','en','sap','simon','first'] );
 
+      t( "Outer Whitespace", " a.blog,p", ['firstp','ap','mark','sndp','en','sap','simon','first'] );
+      t( "Outer Whitespace", "a.blog,p ", ['firstp','ap','mark','sndp','en','sap','simon','first'] );
+      t( "Outer Whitespace", " p,a.blog", ['firstp','ap','mark','sndp','en','sap','simon','first'] );
+      t( "Outer Whitespace", "p,a.blog ", ['firstp','ap','mark','sndp','en','sap','simon','first'] );
+
       t( "Child", "p > a", ["simon1","google","groups","mark","yahoo","simon"] );
       t( "Child", "p> a", ["simon1","google","groups","mark","yahoo","simon"] );
       t( "Child", "p >a", ["simon1","google","groups","mark","yahoo","simon"] );
       t( "Child", "p>a", ["simon1","google","groups","mark","yahoo","simon"] );
       t( "Child w/ Class", "p > a.blog", ["mark","simon"] );
       t( "All Children", "code > *", ["anchor1","anchor2"] );
       t( "All Grandchildren", "p > * > *", ["anchor1","anchor2"] );
       t( "Adjacent", "a + a", ["groups"] );
--- a/content/events/src/nsContentEventHandler.cpp
+++ b/content/events/src/nsContentEventHandler.cpp
@@ -130,20 +130,18 @@ nsContentEventHandler::Init(nsQueryConte
 
   aEvent->mReply.mContentsRoot = mRootContent.get();
 
   PRBool isCollapsed;
   rv = mSelection->GetIsCollapsed(&isCollapsed);
   NS_ENSURE_SUCCESS(rv, NS_ERROR_NOT_AVAILABLE);
   aEvent->mReply.mHasSelection = !isCollapsed;
 
-  nsRefPtr<nsCaret> caret;
-  rv = mPresShell->GetCaret(getter_AddRefs(caret));
-  NS_ENSURE_SUCCESS(rv, rv);
-  NS_ASSERTION(caret, "GetCaret succeeded, but the result is null");
+  nsRefPtr<nsCaret> caret = mPresShell->GetCaret();
+  NS_ASSERTION(caret, "GetCaret returned null");
 
   nsRect r;
   nsIFrame* frame = caret->GetGeometry(mSelection, &r);
   NS_ENSURE_TRUE(frame, NS_ERROR_FAILURE);
 
   aEvent->mReply.mFocusedWidget = frame->GetWindow();
 
   return NS_OK;
@@ -658,20 +656,18 @@ nsContentEventHandler::OnQueryEditorRect
 
 nsresult
 nsContentEventHandler::OnQueryCaretRect(nsQueryContentEvent* aEvent)
 {
   nsresult rv = Init(aEvent);
   if (NS_FAILED(rv))
     return rv;
 
-  nsRefPtr<nsCaret> caret;
-  rv = mPresShell->GetCaret(getter_AddRefs(caret));
-  NS_ENSURE_SUCCESS(rv, rv);
-  NS_ASSERTION(caret, "GetCaret succeeded, but the result is null");
+  nsRefPtr<nsCaret> caret = mPresShell->GetCaret();
+  NS_ASSERTION(caret, "GetCaret returned null");
 
   // When the selection is collapsed and the queried offset is current caret
   // position, we should return the "real" caret rect.
   PRBool selectionIsCollapsed;
   rv = mSelection->GetIsCollapsed(&selectionIsCollapsed);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (selectionIsCollapsed) {
--- a/content/events/src/nsDOMEvent.cpp
+++ b/content/events/src/nsDOMEvent.cpp
@@ -254,22 +254,21 @@ NS_METHOD nsDOMEvent::GetType(nsAString&
     mCachedType = aType;
     return NS_OK;
   }
   
   return NS_ERROR_FAILURE;
 }
 
 static nsresult
-GetDOMEventTarget(nsISupports* aTarget,
+GetDOMEventTarget(nsPIDOMEventTarget* aTarget,
                   nsIDOMEventTarget** aDOMTarget)
 {
-  nsCOMPtr<nsPIDOMEventTarget> piTarget = do_QueryInterface(aTarget);
-  nsISupports* realTarget =
-    piTarget ? piTarget->GetTargetForDOMEvent() : aTarget;
+  nsPIDOMEventTarget* realTarget =
+    aTarget ? aTarget->GetTargetForDOMEvent() : aTarget;
   if (realTarget) {
     return CallQueryInterface(realTarget, aDOMTarget);
   }
 
   *aDOMTarget = nsnull;
   return NS_OK;
 }
 
@@ -1061,17 +1060,17 @@ NS_METHOD nsDOMEvent::SetTarget(nsIDOMEv
   {
     nsCOMPtr<nsPIDOMWindow> win = do_QueryInterface(aTarget);
 
     NS_ASSERTION(!win || !win->IsInnerWindow(),
                  "Uh, inner window set as event target!");
   }
 #endif
 
-  mEvent->target = aTarget;
+  mEvent->target = do_QueryInterface(aTarget);
   return NS_OK;
 }
 
 NS_IMETHODIMP_(PRBool)
 nsDOMEvent::IsDispatchStopped()
 {
   return !!(mEvent->flags & NS_EVENT_FLAG_STOP_DISPATCH);
 }
--- a/content/events/src/nsEventDispatcher.cpp
+++ b/content/events/src/nsEventDispatcher.cpp
@@ -91,17 +91,17 @@ public:
   }
 
   PRBool IsValid()
   {
     NS_WARN_IF_FALSE(!!(mTarget), "Event target is not valid!");
     return !!(mTarget);
   }
 
-  nsISupports* GetNewTarget()
+  nsPIDOMEventTarget* GetNewTarget()
   {
     return mNewTarget;
   }
 
   void SetNewTarget(nsPIDOMEventTarget* aNewTarget)
   {
     mNewTarget = aNewTarget;
   }
@@ -275,17 +275,17 @@ nsEventTargetChainItem::PostHandleEvent(
 nsresult
 nsEventTargetChainItem::HandleEventTargetChain(nsEventChainPostVisitor& aVisitor, PRUint32 aFlags,
                                                nsDispatchingCallback* aCallback,
                                                PRBool aMayHaveNewListenerManagers,
                                                nsCxPusher* aPusher)
 {
   PRUint32 createdELMs = nsEventListenerManager::sCreatedCount;
   // Save the target so that it can be restored later.
-  nsCOMPtr<nsISupports> firstTarget = aVisitor.mEvent->target;
+  nsCOMPtr<nsPIDOMEventTarget> firstTarget = aVisitor.mEvent->target;
 
   // Capture
   nsEventTargetChainItem* item = this;
   aVisitor.mEvent->flags |= NS_EVENT_FLAG_CAPTURE;
   aVisitor.mEvent->flags &= ~NS_EVENT_FLAG_BUBBLE;
   while (item->mChild) {
     if ((!(aVisitor.mEvent->flags & NS_EVENT_FLAG_NO_CONTENT_DISPATCH) ||
          item->ForceContentDispatch()) &&
@@ -295,17 +295,17 @@ nsEventTargetChainItem::HandleEventTarge
                         createdELMs != nsEventListenerManager::sCreatedCount,
                         aPusher);
     }
 
     if (item->GetNewTarget()) {
       // item is at anonymous boundary. Need to retarget for the child items.
       nsEventTargetChainItem* nextTarget = item->mChild;
       while (nextTarget) {
-        nsISupports* newTarget = nextTarget->GetNewTarget();
+        nsPIDOMEventTarget* newTarget = nextTarget->GetNewTarget();
         if (newTarget) {
           aVisitor.mEvent->target = newTarget;
           break;
         }
         nextTarget = nextTarget->mChild;
       }
     }
 
@@ -328,17 +328,17 @@ nsEventTargetChainItem::HandleEventTarge
   if (aFlags & NS_EVENT_FLAG_SYSTEM_EVENT) {
     item->PostHandleEvent(aVisitor);
   }
 
   // Bubble
   aVisitor.mEvent->flags &= ~NS_EVENT_FLAG_CAPTURE;
   item = item->mParent;
   while (item) {
-    nsISupports* newTarget = item->GetNewTarget();
+    nsPIDOMEventTarget* newTarget = item->GetNewTarget();
     if (newTarget) {
       // Item is at anonymous boundary. Need to retarget for the current item
       // and for parent items.
       aVisitor.mEvent->target = newTarget;
     }
 
     if (!(aVisitor.mEvent->flags & NS_EVENT_FLAG_CANT_BUBBLE) || newTarget) {
       if ((!(aVisitor.mEvent->flags & NS_EVENT_FLAG_NO_CONTENT_DISPATCH) ||
@@ -449,16 +449,17 @@ nsEventDispatcher::Dispatch(nsISupports*
                             nsEventStatus* aEventStatus,
                             nsDispatchingCallback* aCallback,
                             nsCOMArray<nsPIDOMEventTarget>* aTargets)
 {
   NS_ASSERTION(aEvent, "Trying to dispatch without nsEvent!");
   NS_ENSURE_TRUE(!NS_IS_EVENT_IN_DISPATCH(aEvent),
                  NS_ERROR_ILLEGAL_VALUE);
   NS_ASSERTION(!aTargets || !aEvent->message, "Wrong parameters!");
+  nsCOMPtr<nsPIDOMEventTarget> target = do_QueryInterface(aTarget);
 
   if (aEvent->flags & NS_EVENT_FLAG_ONLY_CHROME_DISPATCH) {
     nsCOMPtr<nsINode> node = do_QueryInterface(aTarget);
     if (!node) {
       nsCOMPtr<nsPIDOMWindow> win = do_QueryInterface(aTarget);
       if (win) {
         node = do_QueryInterface(win->GetExtantDocument());
       }
@@ -466,23 +467,22 @@ nsEventDispatcher::Dispatch(nsISupports*
 
     NS_ENSURE_STATE(node);
     nsIDocument* doc = node->GetOwnerDoc();
     if (!nsContentUtils::IsChromeDoc(doc)) {
       nsPIDOMWindow* win = doc ? doc->GetInnerWindow() : nsnull;
       // If we can't dispatch the event to chrome, do nothing.
       NS_ENSURE_TRUE(win && win->GetChromeEventHandler(), NS_OK);
       // Set the target to be the original dispatch target,
-      aEvent->target = aTarget;
+      aEvent->target = target;
       // but use chrome event handler for event target chain.
-      aTarget = win->GetChromeEventHandler();
+      target = do_QueryInterface(win->GetChromeEventHandler());
     }
   }
 
-  nsCOMPtr<nsPIDOMEventTarget> target = do_QueryInterface(aTarget);
 #ifdef DEBUG
   if (!nsContentUtils::IsSafeToRunScript()) {
     nsresult rv = NS_ERROR_FAILURE;
     if (target->GetContextForEventHandlers(&rv) ||
         NS_FAILED(rv)) {
       nsCOMPtr<nsINode> node = do_QueryInterface(target);
       if (node && nsContentUtils::IsChromeDoc(node->GetOwnerDoc())) {
         NS_WARNING("Fix the caller!");
@@ -527,19 +527,17 @@ nsEventDispatcher::Dispatch(nsISupports*
     // GetTargetForEventTargetChain().
     aEvent->target = targetEtci->CurrentTarget();
   } else {
     // XXX But if the target is already set, use that. This is a hack
     //     for the 'load', 'beforeunload' and 'unload' events,
     //     which are dispatched to |window| but have document as their target.
     //
     // Make sure that the event target points to the right object.
-    nsCOMPtr<nsPIDOMEventTarget> t = do_QueryInterface(aEvent->target);
-    NS_ENSURE_STATE(t);
-    aEvent->target = t->GetTargetForEventTargetChain();
+    aEvent->target = aEvent->target->GetTargetForEventTargetChain();
     NS_ENSURE_STATE(aEvent->target);
   }
   aEvent->originalTarget = aEvent->target;
   nsCOMPtr<nsIContent> content = do_QueryInterface(aEvent->originalTarget);
   PRBool isInAnon = (content && content->IsInAnonymousSubtree());
 
   NS_MARK_EVENT_DISPATCH_STARTED(aEvent);
 
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -3899,18 +3899,17 @@ nsEventStateManager::GetEventTarget(nsIF
   if (mCurrentTargetContent) {
     mCurrentTarget = mPresContext->GetPrimaryFrameFor(mCurrentTargetContent);
     if (mCurrentTarget) {
       *aFrame = mCurrentTarget;
       return NS_OK;
     }
   }
 
-  nsIFrame* frame = nsnull;
-  shell->GetEventTargetFrame(&frame);
+  nsIFrame* frame = shell->GetEventTargetFrame();
   *aFrame = mCurrentTarget = frame;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsEventStateManager::GetEventTargetContent(nsEvent* aEvent,
                                            nsIContent** aContent)
 {
@@ -3926,17 +3925,17 @@ nsEventStateManager::GetEventTargetConte
     NS_IF_ADDREF(*aContent);
     return NS_OK;
   }
 
   *aContent = nsnull;
 
   nsIPresShell *presShell = mPresContext->GetPresShell();
   if (presShell) {
-    presShell->GetEventTargetContent(aEvent, aContent);
+    *aContent = presShell->GetEventTargetContent(aEvent).get();
   }
 
   // Some events here may set mCurrentTarget but not set the corresponding
   // event target in the PresShell.
   if (!*aContent && mCurrentTarget) {
     mCurrentTarget->GetContentForEvent(mPresContext, aEvent, aContent);
   }
 
--- a/content/html/document/src/nsHTMLContentSink.cpp
+++ b/content/html/document/src/nsHTMLContentSink.cpp
@@ -174,16 +174,17 @@ public:
 
   NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW
 
   nsresult Init(nsIDocument* aDoc, nsIURI* aURI, nsISupports* aContainer,
                 nsIChannel* aChannel);
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(HTMLContentSink, nsContentSink)
 
   // nsIContentSink
   NS_IMETHOD WillParse(void);
   NS_IMETHOD WillBuildModel(nsDTDMode aDTDMode);
   NS_IMETHOD DidBuildModel(PRBool aTerminated);
   NS_IMETHOD WillInterrupt(void);
   NS_IMETHOD WillResume(void);
   NS_IMETHOD SetParser(nsIParser* aParser);
@@ -227,25 +228,25 @@ protected:
 #ifdef NS_DEBUG
   void SinkTraceNode(PRUint32 aBit,
                      const char* aMsg,
                      const nsHTMLTag aTag,
                      PRInt32 aStackPos,
                      void* aThis);
 #endif
 
-  nsIHTMLDocument* mHTMLDocument;
+  nsCOMPtr<nsIHTMLDocument> mHTMLDocument;
 
   // The maximum length of a text run
   PRInt32 mMaxTextRun;
 
-  nsGenericHTMLElement* mRoot;
-  nsGenericHTMLElement* mBody;
+  nsRefPtr<nsGenericHTMLElement> mRoot;
+  nsRefPtr<nsGenericHTMLElement> mBody;
   nsRefPtr<nsGenericHTMLElement> mFrameset;
-  nsGenericHTMLElement* mHead;
+  nsRefPtr<nsGenericHTMLElement> mHead;
 
   nsRefPtr<nsGenericHTMLElement> mCurrentForm;
 
   nsAutoTArray<SinkContext*, 8> mContextStack;
   SinkContext* mCurrentContext;
   SinkContext* mHeadContext;
   PRInt32 mNumOpenIFRAMES;
 
@@ -1521,22 +1522,16 @@ HTMLContentSink::HTMLContentSink()
   if (!gSinkLogModuleInfo) {
     gSinkLogModuleInfo = PR_NewLogModule("htmlcontentsink");
   }
 #endif
 }
 
 HTMLContentSink::~HTMLContentSink()
 {
-  NS_IF_RELEASE(mHead);
-  NS_IF_RELEASE(mBody);
-  NS_IF_RELEASE(mRoot);
-
-  NS_IF_RELEASE(mHTMLDocument);
-
   if (mNotificationTimer) {
     mNotificationTimer->Cancel();
   }
 
   PRInt32 numContexts = mContextStack.Length();
 
   if (mCurrentContext == mHeadContext && numContexts > 0) {
     // Pop off the second html context if it's not done earlier
@@ -1564,28 +1559,55 @@ HTMLContentSink::~HTMLContentSink()
 
   delete mHeadContext;
 
   for (i = 0; PRUint32(i) < NS_ARRAY_LENGTH(mNodeInfoCache); ++i) {
     NS_IF_RELEASE(mNodeInfoCache[i]);
   }
 }
 
+NS_IMPL_CYCLE_COLLECTION_CLASS(HTMLContentSink)
+
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(HTMLContentSink, nsContentSink)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mHTMLDocument)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mRoot)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mBody)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mFrameset)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mHead)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCurrentForm)
+  for (PRUint32 i = 0; i < NS_ARRAY_LENGTH(tmp->mNodeInfoCache); ++i) {
+    NS_IF_RELEASE(tmp->mNodeInfoCache[i]);
+  }
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(HTMLContentSink,
+                                                  nsContentSink)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mHTMLDocument)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mRoot)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mBody)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mFrameset)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mHead)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mCurrentForm)
+  for (PRUint32 i = 0; i < NS_ARRAY_LENGTH(tmp->mNodeInfoCache); ++i) {
+    NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mNodeInfoCache[i]");
+    cb.NoteXPCOMChild(tmp->mNodeInfoCache[i]);
+  }
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION_INHERITED(HTMLContentSink)
+  NS_INTERFACE_TABLE_BEGIN
+    NS_INTERFACE_TABLE_ENTRY(HTMLContentSink, nsIContentSink)
+    NS_INTERFACE_TABLE_ENTRY(HTMLContentSink, nsIHTMLContentSink)
 #if DEBUG
-NS_IMPL_ISUPPORTS_INHERITED3(HTMLContentSink,
-                             nsContentSink,
-                             nsIContentSink,
-                             nsIHTMLContentSink,
-                             nsIDebugDumpContent)
-#else
-NS_IMPL_ISUPPORTS_INHERITED2(HTMLContentSink,
-                             nsContentSink,
-                             nsIContentSink,
-                             nsIHTMLContentSink)
+    NS_INTERFACE_TABLE_ENTRY(HTMLContentSink, nsIDebugDumpContent)
 #endif
+  NS_INTERFACE_TABLE_END
+NS_INTERFACE_TABLE_TAIL_INHERITING(nsContentSink)
+
+NS_IMPL_ADDREF_INHERITED(HTMLContentSink, nsContentSink)
+NS_IMPL_RELEASE_INHERITED(HTMLContentSink, nsContentSink)
 
 static PRBool
 IsScriptEnabled(nsIDocument *aDoc, nsIDocShell *aContainer)
 {
   NS_ENSURE_TRUE(aDoc && aContainer, PR_TRUE);
 
   nsCOMPtr<nsIScriptGlobalObject> globalObject = aDoc->GetScriptGlobalObject();
 
@@ -1621,17 +1643,17 @@ HTMLContentSink::Init(nsIDocument* aDoc,
   
   nsresult rv = nsContentSink::Init(aDoc, aURI, aContainer, aChannel);
   if (NS_FAILED(rv)) {
     return rv;
   }
 
   aDoc->AddObserver(this);
   mIsDocumentObserver = PR_TRUE;
-  CallQueryInterface(aDoc, &mHTMLDocument);
+  mHTMLDocument = do_QueryInterface(aDoc);
 
   mObservers = nsnull;
   nsIParserService* service = nsContentUtils::GetParserService();
   if (!service) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   service->GetTopicObservers(NS_LITERAL_STRING("text/html"),
@@ -1665,40 +1687,38 @@ HTMLContentSink::Init(nsIDocument* aDoc,
 
   // Make root part
   nsIContent *doc_root = mDocument->GetRootContent();
 
   if (doc_root) {
     // If the document already has a root we'll use it. This will
     // happen when we do document.open()/.write()/.close()...
 
-    NS_ADDREF(mRoot = static_cast<nsGenericHTMLElement*>(doc_root));
+    mRoot = static_cast<nsGenericHTMLElement*>(doc_root);
   } else {
     mRoot = NS_NewHTMLHtmlElement(nodeInfo);
     if (!mRoot) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
-    NS_ADDREF(mRoot);
 
     NS_ASSERTION(mDocument->GetChildCount() == 0,
                  "Document should have no kids here!");
     rv = mDocument->AppendChildTo(mRoot, PR_FALSE);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // Make head part
   nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::head,
                                            nsnull, kNameSpaceID_XHTML);
   NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
 
   mHead = NS_NewHTMLHeadElement(nodeInfo);
   if (NS_FAILED(rv)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
-  NS_ADDREF(mHead);
 
   mRoot->AppendChildTo(mHead, PR_FALSE);
 
   mCurrentContext = new SinkContext(this);
   NS_ENSURE_TRUE(mCurrentContext, NS_ERROR_OUT_OF_MEMORY);
   mCurrentContext->Begin(eHTMLTag_html, mRoot, 0, -1);
   mContextStack.AppendElement(mCurrentContext);
 
@@ -1964,18 +1984,16 @@ HTMLContentSink::OpenBody(const nsIParse
   nsresult rv = mCurrentContext->OpenContainer(aNode);
 
   if (NS_FAILED(rv)) {
     return rv;
   }
 
   mBody = mCurrentContext->mStack[mCurrentContext->mStackPos - 1].mContent;
 
-  NS_ADDREF(mBody);
-
   if (mCurrentContext->mStackPos > 1) {
     PRInt32 parentIndex    = mCurrentContext->mStackPos - 2;
     nsGenericHTMLElement *parent = mCurrentContext->mStack[parentIndex].mContent;
     PRInt32 numFlushed     = mCurrentContext->mStack[parentIndex].mNumFlushed;
     PRInt32 childCount = parent->GetChildCount();
     NS_ASSERTION(numFlushed < childCount, "Already notified on the body?");
     
     PRInt32 insertionPoint =
--- a/content/xul/content/src/nsXULPopupListener.cpp
+++ b/content/xul/content/src/nsXULPopupListener.cpp
@@ -270,17 +270,17 @@ nsXULPopupListener::FireFocusOnTargetCon
 
     // Get nsIDOMElement for targetNode
     nsIPresShell *shell = doc->GetPrimaryShell();
     if (!shell)
       return NS_ERROR_FAILURE;
 
     // strong reference to keep this from going away between events
     // XXXbz between what events?  We don't use this local at all!
-    nsCOMPtr<nsPresContext> context = shell->GetPresContext();
+    nsRefPtr<nsPresContext> context = shell->GetPresContext();
  
     nsCOMPtr<nsIContent> content = do_QueryInterface(aTargetNode);
     nsIFrame* targetFrame = content->GetPrimaryFrame();
     if (!targetFrame) return NS_ERROR_FAILURE;
 
     const nsStyleUserInterface* ui = targetFrame->GetStyleUserInterface();
     PRBool suppressBlur = (ui->mUserFocus == NS_STYLE_USER_FOCUS_IGNORE);
 
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -10367,18 +10367,17 @@ nsEventListenerThisTranslator::Translate
   *aIIDOfResult = nsnull;
 
   nsCOMPtr<nsIDOMEvent> event(do_QueryInterface(aInitialThis));
   NS_ENSURE_TRUE(event, NS_ERROR_UNEXPECTED);
 
   nsCOMPtr<nsIDOMEventTarget> target;
   event->GetCurrentTarget(getter_AddRefs(target));
 
-  *_retval = target;
-  NS_IF_ADDREF(*_retval);
+  *_retval = target.forget().get();
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMConstructorSH::Call(nsIXPConnectWrappedNative *wrapper, JSContext *cx,
                          JSObject *obj, PRUint32 argc, jsval *argv, jsval *vp,
                          PRBool *_retval)
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -727,17 +727,18 @@ nsDOMWindowUtils::DisableNonTestMouseEve
   }
 
   NS_ENSURE_TRUE(mWindow, NS_ERROR_FAILURE);
   nsIDocShell *docShell = mWindow->GetDocShell();
   NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);
   nsCOMPtr<nsIPresShell> presShell;
   docShell->GetPresShell(getter_AddRefs(presShell));
   NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
-  return presShell->DisableNonTestMouseEvents(aDisable);
+  presShell->DisableNonTestMouseEvents(aDisable);
+  return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMWindowUtils::SuppressEventHandling(PRBool aSuppress)
 {
   if (!IsUniversalXPConnectCapable()) {
     return NS_ERROR_DOM_SECURITY_ERR;
   }
--- a/dom/base/nsFocusManager.cpp
+++ b/dom/base/nsFocusManager.cpp
@@ -1894,18 +1894,17 @@ nsFocusManager::MoveCaretToFocus(nsIPres
 nsresult
 nsFocusManager::SetCaretVisible(nsIPresShell* aPresShell,
                                 PRBool aVisible,
                                 nsIContent* aContent)
 {
   // When browsing with caret, make sure caret is visible after new focus
   // Return early if there is no caret. This can happen for the testcase
   // for bug 308025 where a window is closed in a blur handler.
-  nsRefPtr<nsCaret> caret;
-  aPresShell->GetCaret(getter_AddRefs(caret));
+  nsRefPtr<nsCaret> caret = aPresShell->GetCaret();
   if (!caret)
     return NS_OK;
 
   PRBool caretVisible = PR_FALSE;
   caret->GetCaretVisible(&caretVisible);
   if (!aVisible && !caretVisible)
     return NS_OK;
 
@@ -2049,18 +2048,17 @@ nsFocusManager::GetSelectionLocation(nsI
             if (nsnull == newCaretFrame)
               break;
             newCaretContent = newCaretFrame->GetContent();            
           } while (!newCaretContent || newCaretContent == startContent);
 
           if (newCaretFrame && newCaretContent) {
             // If the caret is exactly at the same position of the new frame,
             // then we can use the newCaretFrame and newCaretContent for our position
-            nsRefPtr<nsCaret> caret;
-            aPresShell->GetCaret(getter_AddRefs(caret));
+            nsRefPtr<nsCaret> caret = aPresShell->GetCaret();
             nsRect caretRect;
             nsIFrame *frame = caret->GetGeometry(domSelection, &caretRect);
             if (frame) {
               nsPoint caretWindowOffset;
               nsIWidget *window = frame->GetWindowOffset(caretWindowOffset);
               caretRect.MoveBy(caretWindowOffset);
               nsPoint newCaretOffset;
               nsIWidget *newCaretWindow = newCaretFrame->GetWindowOffset(newCaretOffset);
--- a/dom/interfaces/canvas/nsIDOMCanvasRenderingContext2D.idl
+++ b/dom/interfaces/canvas/nsIDOMCanvasRenderingContext2D.idl
@@ -56,17 +56,17 @@ interface nsIDOMCanvasPattern : nsISuppo
 };
 
 [scriptable, uuid(2d01715c-ec7d-424a-ab85-e0fd70c8665c)]
 interface nsIDOMTextMetrics : nsISupports
 {
   readonly attribute float width;
 };
 
-[scriptable, uuid(72635fb6-0c1c-47d7-bf69-49388d5980fc)]
+[scriptable, uuid(b8dc64ac-1278-4f1c-9ba3-3fd2940d4c30)]
 interface nsIDOMCanvasRenderingContext2D : nsISupports
 {
   // back-reference to the canvas element for which
   // this context was created
   readonly attribute nsIDOMHTMLCanvasElement canvas;
 
   // state
   void save();
--- a/editor/libeditor/base/nsEditor.cpp
+++ b/editor/libeditor/base/nsEditor.cpp
@@ -1976,20 +1976,19 @@ nsEditor::QueryComposition(nsTextEventRe
   nsCOMPtr<nsISelection> selection;
   nsCOMPtr<nsISelectionController> selcon = do_QueryReferent(mSelConWeak);
   if (selcon)
     selcon->GetSelection(nsISelectionController::SELECTION_NORMAL, getter_AddRefs(selection));
 
   if (!mPresShellWeak) return NS_ERROR_NOT_INITIALIZED;
   nsCOMPtr<nsIPresShell> ps = do_QueryReferent(mPresShellWeak);
   if (!ps) return NS_ERROR_NOT_INITIALIZED;
-  nsRefPtr<nsCaret> caretP; 
-  result = ps->GetCaret(getter_AddRefs(caretP));
-  
-  if (NS_SUCCEEDED(result) && caretP) {
+  nsRefPtr<nsCaret> caretP = ps->GetCaret();
+
+  if (caretP) {
     if (aReply) {
       caretP->SetCaretDOMSelection(selection);
 
       // XXX_kin: BEGIN HACK! HACK! HACK!
       // XXX_kin:
       // XXX_kin: This is lame! The IME stuff needs caret coordinates
       // XXX_kin: synchronously, but the editor could be using async
       // XXX_kin: updates (reflows and paints) for performance reasons.
@@ -4358,20 +4357,20 @@ nsresult nsEditor::EndUpdateViewBatch()
     // notifications should've happened so the caret should have enough info
     // to draw at the correct position.
 
     nsRefPtr<nsCaret> caret;
     nsCOMPtr<nsIPresShell> presShell;
     GetPresShell(getter_AddRefs(presShell));
 
     if (presShell)
-      presShell->GetCaret(getter_AddRefs(caret));
+      caret = presShell->GetCaret();
 
     StCaretHider caretHider(caret);
-        
+
     PRUint32 flags = 0;
 
     GetFlags(&flags);
 
     // Turn view updating back on.
     if (mViewManager)
     {
       PRUint32 updateFlag = NS_VMREFRESH_IMMEDIATE;
--- a/editor/libeditor/base/nsEditorEventListener.cpp
+++ b/editor/libeditor/base/nsEditorEventListener.cpp
@@ -865,18 +865,17 @@ nsEditorEventListener::Focus(nsIDOMEvent
       if (selCon && (targetIsEditableDoc || editableRoot))
       {
         nsCOMPtr<nsISelection> selection;
         selCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                              getter_AddRefs(selection));
 
         nsCOMPtr<nsIPresShell> presShell = GetPresShell();
         if (presShell) {
-          nsRefPtr<nsCaret> caret;
-          presShell->GetCaret(getter_AddRefs(caret));
+          nsRefPtr<nsCaret> caret = presShell->GetCaret();
           if (caret) {
             caret->SetIgnoreUserModify(PR_FALSE);
             if (selection) {
               caret->SetCaretDOMSelection(selection);
             }
           }
         }
 
@@ -937,18 +936,17 @@ nsEditorEventListener::Blur(nsIDOMEvent*
         nsCOMPtr<nsISelectionPrivate> selectionPrivate =
           do_QueryInterface(selection);
         if (selectionPrivate) {
           selectionPrivate->SetAncestorLimiter(nsnull);
         }
 
         nsCOMPtr<nsIPresShell> presShell = GetPresShell();
         if (presShell) {
-          nsRefPtr<nsCaret> caret;
-          presShell->GetCaret(getter_AddRefs(caret));
+          nsRefPtr<nsCaret> caret = presShell->GetCaret();
           if (caret) {
             caret->SetIgnoreUserModify(PR_TRUE);
           }
         }
 
         selCon->SetCaretEnabled(PR_FALSE);
 
         PRUint32 flags;
--- a/editor/libeditor/text/nsPlaintextEditor.cpp
+++ b/editor/libeditor/text/nsPlaintextEditor.cpp
@@ -1571,18 +1571,17 @@ nsPlaintextEditor::SetCompositionString(
   nsCOMPtr<nsIPresShell> ps = do_QueryReferent(mPresShellWeak);
   if (!ps) 
     return NS_ERROR_NOT_INITIALIZED;
 
   nsCOMPtr<nsISelection> selection;
   nsresult result = GetSelection(getter_AddRefs(selection));
   if (NS_FAILED(result)) return result;
 
-  nsRefPtr<nsCaret> caretP;
-  ps->GetCaret(getter_AddRefs(caretP));
+  nsRefPtr<nsCaret> caretP = ps->GetCaret();
 
   // We should return caret position if it is possible. Because this event
   // dispatcher always expects to be returned the correct caret position.
   // But in following cases, we don't need to process the composition string,
   // so, we only need to return the caret position.
 
   // aCompositionString.IsEmpty() && !mIMETextNode:
   //   Workaround for Windows IME bug 23558: We get every IME event twice.
--- a/gfx/public/nsITheme.h
+++ b/gfx/public/nsITheme.h
@@ -54,17 +54,18 @@ class nsIRenderingContext;
 class nsIDeviceContext;
 class nsIFrame;
 class nsIContent;
 class nsIAtom;
 
 // IID for the nsITheme interface
 // {887e8902-db6b-41b4-8481-a80f49c5a93a}
  #define NS_ITHEME_IID     \
-{ 0x23db7c13, 0x873d, 0x4fb5, { 0xaf, 0x29, 0xc1, 0xe9, 0xed, 0x91, 0x23, 0xf9 } }
+{ 0x887e8902, 0xdb6b, 0x41b4, { 0x84, 0x81, 0xa8, 0x0f, 0x49, 0xc5, 0xa9, 0x3a } }
+
 // {D930E29B-6909-44e5-AB4B-AF10D6923705}
 #define NS_THEMERENDERER_CID \
 { 0xd930e29b, 0x6909, 0x44e5, { 0xab, 0x4b, 0xaf, 0x10, 0xd6, 0x92, 0x37, 0x5 } }
 
 enum nsTransparencyMode {
   eTransparencyOpaque = 0,  // Fully opaque
   eTransparencyTransparent, // Parts of the window may be transparent
   eTransparencyGlass        // Transparent parts of the window have Vista AeroGlass effect applied
@@ -133,28 +134,17 @@ public:
    * widget.
    */
   NS_IMETHOD GetMinimumWidgetSize(nsIRenderingContext* aContext,
                                   nsIFrame* aFrame,
                                   PRUint8 aWidgetType,
                                   nsIntSize* aResult,
                                   PRBool* aIsOverridable)=0;
 
-
-  typedef enum {
-    eOpaque = 0,
-    eTransparent,
-    eUnknownTransparency
-  } Transparency;
-
-  /**
-   * Returns what we know about the transparency of the widget.
-   */
-  virtual Transparency GetWidgetTransparency(nsIFrame* aFrame, PRUint8 aWidgetType)
-  { return eUnknownTransparency; }
+  virtual nsTransparencyMode GetWidgetTransparency(PRUint8 aWidgetType)=0;
 
   NS_IMETHOD WidgetStateChanged(nsIFrame* aFrame, PRUint8 aWidgetType, 
                                 nsIAtom* aAttribute, PRBool* aShouldRepaint)=0;
 
   NS_IMETHOD ThemeChanged()=0;
 
   /**
    * Can the nsITheme implementation handle this widget?
--- a/gfx/thebes/src/gfxDWriteFonts.cpp
+++ b/gfx/thebes/src/gfxDWriteFonts.cpp
@@ -176,21 +176,33 @@ gfxDWriteFont::ComputeMetrics()
         ((gfxFloat)fontMetrics.underlineThickness /
                    fontMetrics.designUnitsPerEm) * mAdjustedSize;
     mMetrics.strikeoutOffset = 
         ((gfxFloat)fontMetrics.strikethroughPosition /
                    fontMetrics.designUnitsPerEm) * mAdjustedSize;
     mMetrics.strikeoutSize = 
         ((gfxFloat)fontMetrics.strikethroughThickness /
                    fontMetrics.designUnitsPerEm) * mAdjustedSize;
-    mMetrics.subscriptOffset = 0;
+    mMetrics.superscriptOffset = 0;
     mMetrics.subscriptOffset = 0;
 
     SanitizeMetrics(&mMetrics, PR_FALSE);
- }
+
+#if 0
+    printf("Font: %p (%s) size: %f\n", this,
+           NS_ConvertUTF16toUTF8(GetName()).get(), mStyle.size);
+    printf("    emHeight: %f emAscent: %f emDescent: %f\n", mMetrics.emHeight, mMetrics.emAscent, mMetrics.emDescent);
+    printf("    maxAscent: %f maxDescent: %f maxAdvance: %f\n", mMetrics.maxAscent, mMetrics.maxDescent, mMetrics.maxAdvance);
+    printf("    internalLeading: %f externalLeading: %f\n", mMetrics.internalLeading, mMetrics.externalLeading);
+    printf("    spaceWidth: %f aveCharWidth: %f xHeight: %f\n", mMetrics.spaceWidth, mMetrics.aveCharWidth, mMetrics.xHeight);
+    printf("    uOff: %f uSize: %f stOff: %f stSize: %f supOff: %f subOff: %f\n",
+           mMetrics.underlineOffset, mMetrics.underlineSize, mMetrics.strikeoutOffset, mMetrics.strikeoutSize,
+           mMetrics.superscriptOffset, mMetrics.subscriptOffset);
+#endif
+}
 
 PRUint32
 gfxDWriteFont::GetSpaceGlyph()
 {
     UINT32 ucs = L' ';
     UINT16 glyph;
     HRESULT hr;
     hr = mFontFace->GetGlyphIndicesA(&ucs, 1, &glyph);
--- a/gfx/thebes/src/gfxFont.cpp
+++ b/gfx/thebes/src/gfxFont.cpp
@@ -1270,22 +1270,22 @@ gfxFont::SanitizeMetrics(gfxFont::Metric
     if (mStyle.size == 0) {
         memset(aMetrics, 0, sizeof(gfxFont::Metrics));
         return;
     }
 
     // MS (P)Gothic and MS (P)Mincho are not having suitable values in their super script offset.
     // If the values are not suitable, we should use x-height instead of them.
     // See https://bugzilla.mozilla.org/show_bug.cgi?id=353632
-    if (aMetrics->superscriptOffset == 0 ||
+    if (aMetrics->superscriptOffset <= 0 ||
         aMetrics->superscriptOffset >= aMetrics->maxAscent) {
         aMetrics->superscriptOffset = aMetrics->xHeight;
     }
     // And also checking the case of sub script offset. The old gfx for win has checked this too.
-    if (aMetrics->subscriptOffset == 0 ||
+    if (aMetrics->subscriptOffset <= 0 ||
         aMetrics->subscriptOffset >= aMetrics->maxAscent) {
         aMetrics->subscriptOffset = aMetrics->xHeight;
     }
 
     aMetrics->underlineSize = PR_MAX(1.0, aMetrics->underlineSize);
     aMetrics->strikeoutSize = PR_MAX(1.0, aMetrics->strikeoutSize);
 
     aMetrics->underlineOffset = PR_MIN(aMetrics->underlineOffset, -1.0);
--- a/gfx/thebes/src/gfxGDIFont.cpp
+++ b/gfx/thebes/src/gfxGDIFont.cpp
@@ -300,16 +300,28 @@ gfxGDIFont::InitMetrics()
                                      GGI_MARK_NONEXISTING_GLYPHS);
         if (ret != GDI_ERROR && glyph != 0xFFFF) {
             mSpaceGlyph = glyph;
         }
     }
 
     SanitizeMetrics(&mMetrics, GetFontEntry()->mIsBadUnderlineFont);
     mIsValid = PR_TRUE;
+
+#if 0
+    printf("Font: %p (%s) size: %f\n", this,
+           NS_ConvertUTF16toUTF8(GetName()).get(), mStyle.size);
+    printf("    emHeight: %f emAscent: %f emDescent: %f\n", mMetrics.emHeight, mMetrics.emAscent, mMetrics.emDescent);
+    printf("    maxAscent: %f maxDescent: %f maxAdvance: %f\n", mMetrics.maxAscent, mMetrics.maxDescent, mMetrics.maxAdvance);
+    printf("    internalLeading: %f externalLeading: %f\n", mMetrics.internalLeading, mMetrics.externalLeading);
+    printf("    spaceWidth: %f aveCharWidth: %f xHeight: %f\n", mMetrics.spaceWidth, mMetrics.aveCharWidth, mMetrics.xHeight);
+    printf("    uOff: %f uSize: %f stOff: %f stSize: %f supOff: %f subOff: %f\n",
+           mMetrics.underlineOffset, mMetrics.underlineSize, mMetrics.strikeoutOffset, mMetrics.strikeoutSize,
+           mMetrics.superscriptOffset, mMetrics.subscriptOffset);
+#endif
 }
 
 void
 gfxGDIFont::FillLogFont(gfxFloat aSize)
 {
     GDIFontEntry *fe = static_cast<GDIFontEntry*>(GetFontEntry());
 
     PRUint16 weight = mNeedsBold ? 700 : fe->Weight();
--- a/js/src/config/autoconf.mk.in
+++ b/js/src/config/autoconf.mk.in
@@ -121,21 +121,16 @@ MOZ_TIMELINE=@MOZ_TIMELINE@
 ENABLE_STRIP	= @ENABLE_STRIP@
 PKG_SKIP_STRIP	= @PKG_SKIP_STRIP@
 
 MOZ_POST_DSO_LIB_COMMAND = @MOZ_POST_DSO_LIB_COMMAND@
 MOZ_POST_PROGRAM_COMMAND = @MOZ_POST_PROGRAM_COMMAND@
 
 MOZ_BUILD_ROOT             = @MOZ_BUILD_ROOT@
 
-MOZ_INSURE = @MOZ_INSURE@
-MOZ_INSURIFYING = @MOZ_INSURIFYING@
-MOZ_INSURE_DIRS = @MOZ_INSURE_DIRS@
-MOZ_INSURE_EXCLUDE_DIRS = @MOZ_INSURE_EXCLUDE_DIRS@
-
 MOZ_NATIVE_NSPR = @MOZ_NATIVE_NSPR@
 
 CROSS_COMPILE   = @CROSS_COMPILE@
 
 OS_CPPFLAGS	= @CPPFLAGS@
 OS_CFLAGS	= $(OS_CPPFLAGS) @CFLAGS@
 OS_CXXFLAGS	= $(OS_CPPFLAGS) @CXXFLAGS@
 OS_LDFLAGS	= @LDFLAGS@
--- a/js/src/config/config.mk
+++ b/js/src/config/config.mk
@@ -51,21 +51,16 @@ EXIT_ON_ERROR = set -e; # Shell loops co
 
 ifndef topsrcdir
 topsrcdir	= $(DEPTH)
 endif
 
 ifndef INCLUDED_AUTOCONF_MK
 include $(DEPTH)/config/autoconf.mk
 endif
-ifndef INCLUDED_INSURE_MK
-ifdef MOZ_INSURIFYING
-include $(topsrcdir)/config/insure.mk
-endif
-endif
 
 COMMA = ,
 
 # Sanity check some variables
 CHECK_VARS := \
  XPI_NAME \
  LIBRARY_NAME \
  MODULE \
deleted file mode 100644
--- a/js/src/config/insure.mk
+++ /dev/null
@@ -1,53 +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
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either of 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 *****
-
-INCLUDED_INSURE_MK = 1
-
-INSURE_MATCH_SCRIPT=$(topsrcdir)/build/autoconf/match-dir.sh
-
-INSURE_EXCLUDE=$(shell $(INSURE_MATCH_SCRIPT) $(MOZ_INSURE_EXCLUDE_DIRS))
-
-INSURE_INCLUDE=$(shell $(INSURE_MATCH_SCRIPT) $(MOZ_INSURE_DIRS))
-
-ifeq ($(INSURE_EXCLUDE),0)
-
-ifeq ($(INSURE_INCLUDE),1)
-CC		:= $(MOZ_INSURE)
-CXX		:= $(MOZ_INSURE)
-endif # INSURE_INCLUDE == 1
-
-endif # INSURE_EXCLUDE == 0
--- a/js/src/configure.in
+++ b/js/src/configure.in
@@ -4361,37 +4361,16 @@ dnl ====================================
 MOZ_ARG_ENABLE_BOOL(timeline,
 [  --enable-timeline       Enable timeline services ],
     MOZ_TIMELINE=1,
     MOZ_TIMELINE= )
 if test -n "$MOZ_TIMELINE"; then
     AC_DEFINE(MOZ_TIMELINE)
 fi
 
-MOZ_ARG_ENABLE_BOOL(insure,
-[  --enable-insure         Enable insure++ instrumentation (linux only)],
-    _ENABLE_INSURE=1,
-    _ENABLE_INSURE= )
-if test -n "$_ENABLE_INSURE"; then
-    MOZ_INSURE="insure"
-    MOZ_INSURIFYING=1
-    MOZ_INSURE_DIRS="."
-    MOZ_INSURE_EXCLUDE_DIRS="config"
-fi
-
-MOZ_ARG_WITH_STRING(insure-dirs,
-[  --with-insure-dirs=DIRS
-                          Dirs to instrument with insure ],
-    MOZ_INSURE_DIRS=$withval )
-
-MOZ_ARG_WITH_STRING(insure-exclude-dirs,
-[  --with-insure-exclude-dirs=DIRS
-                          Dirs to not instrument with insure ],
-    MOZ_INSURE_EXCLUDE_DIRS="config $withval" )
-
 dnl ========================================================
 dnl = Support for Quantify (Windows)
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(quantify,
 [  --enable-quantify      Enable Quantify support (Windows only) ],
     MOZ_QUANTIFY=1,
     MOZ_QUANTIFY= )
 
@@ -4891,21 +4870,17 @@ AC_SUBST(MOZ_DEBUG_LDFLAGS)
 AC_SUBST(WARNINGS_AS_ERRORS)
 AC_SUBST(MOZ_LEAKY)
 AC_SUBST(MOZ_JPROF)
 AC_SUBST(MOZ_SHARK)
 AC_SUBST(MOZ_CALLGRIND)
 AC_SUBST(MOZ_VTUNE)
 AC_SUBST(MOZ_XPCTOOLS)
 AC_SUBST(MOZ_JSLOADER)
-AC_SUBST(MOZ_INSURE)
-AC_SUBST(MOZ_INSURE_DIRS)
-AC_SUBST(MOZ_INSURE_EXCLUDE_DIRS)
 AC_SUBST(MOZ_QUANTIFY)
-AC_SUBST(MOZ_INSURIFYING)
 AC_SUBST(LIBICONV)
 
 AC_SUBST(BUILD_STATIC_LIBS)
 AC_SUBST(ENABLE_TESTS)
 
 AC_SUBST(ENABLE_STRIP)
 AC_SUBST(PKG_SKIP_STRIP)
 AC_SUBST(INCREMENTAL_LINKER)
--- a/js/src/xpconnect/idl/nsIXPConnect.idl
+++ b/js/src/xpconnect/idl/nsIXPConnect.idl
@@ -647,19 +647,19 @@ interface nsIXPConnect : nsISupports
                               in nsIXPCFunctionThisTranslator aTranslator);
 
     nsIXPConnectJSObjectHolder
     reparentWrappedNativeIfFound(in JSContextPtr aJSContext,
                                  in JSObjectPtr  aScope,
                                  in JSObjectPtr  aNewParent,
                                  in nsISupports  aCOMObj);
     void
-    reparentScopeAwareWrappers(in JSContextPtr aJSContext,
-                               in JSObjectPtr  aOldScope,
-                               in JSObjectPtr  aNewScope);
+    moveWrappers(in JSContextPtr aJSContext,
+                 in JSObjectPtr  aOldScope,
+                 in JSObjectPtr  aNewScope);
 
     void clearAllWrappedNativeSecurityPolicies();
 
     nsIXPConnectJSObjectHolder
     getWrappedNativePrototype(in JSContextPtr aJSContext,
                               in JSObjectPtr  aScope,
                               in nsIClassInfo aClassInfo);
 
--- a/js/src/xpconnect/src/nsXPConnect.cpp
+++ b/js/src/xpconnect/src/nsXPConnect.cpp
@@ -1576,21 +1576,21 @@ MoveableWrapperFinder(JSDHashTable *tabl
 {
     // Every element counts.
     nsTArray<nsRefPtr<XPCWrappedNative> > *array =
         static_cast<nsTArray<nsRefPtr<XPCWrappedNative> > *>(arg);
     array->AppendElement(((Native2WrappedNativeMap::Entry*)hdr)->value);
     return JS_DHASH_NEXT;
 }
 
-/* void reparentScopeAwareWrappers(in JSContextPtr aJSContext, in JSObjectPtr  aOldScope, in JSObjectPtr  aNewScope); */
+/* void moveWrappers(in JSContextPtr aJSContext, in JSObjectPtr  aOldScope, in JSObjectPtr  aNewScope); */
 NS_IMETHODIMP
-nsXPConnect::ReparentScopeAwareWrappers(JSContext *aJSContext,
-                                        JSObject *aOldScope,
-                                        JSObject *aNewScope)
+nsXPConnect::MoveWrappers(JSContext *aJSContext,
+                          JSObject *aOldScope,
+                          JSObject *aNewScope)
 {
     XPCCallContext ccx(NATIVE_CALLER, aJSContext);
     if(!ccx.IsValid())
         return UnexpectedFailure(NS_ERROR_FAILURE);
 
     XPCWrappedNativeScope *oldScope =
         XPCWrappedNativeScope::FindInJSObjectScope(ccx, aOldScope);
     if(!oldScope)
@@ -1648,34 +1648,39 @@ nsXPConnect::ReparentScopeAwareWrappers(
             continue;
 
         JSObject *newParent = aOldScope;
         rv = sciWrapper.GetCallback()->PreCreate(identity, ccx, aOldScope,
                                                  &newParent);
         if(NS_FAILED(rv))
             return rv;
 
-        if(newParent != aOldScope)
+        if(newParent == aOldScope)
         {
-            // The wrapper returned a new parent. If the new parent is in
-            // a different scope, then we need to reparent it, otherwise,
-            // the old scope is fine.
-
-            XPCWrappedNativeScope *betterScope =
-                XPCWrappedNativeScope::FindInJSObjectScope(ccx, newParent);
-            if(betterScope == oldScope)
-                continue;
-
-            NS_ASSERTION(betterScope == newScope, "Weird scope returned");
+            // The old scope still works for this wrapper. We have to assume
+            // that the wrapper will continue to return the old scope from
+            // PreCreate, so don't move it.
+            continue;
+        }
+
+        // The wrapper returned a new parent. If the new parent is in
+        // a different scope, then we need to reparent it, otherwise,
+        // the old scope is fine.
+
+        XPCWrappedNativeScope *betterScope =
+            XPCWrappedNativeScope::FindInJSObjectScope(ccx, newParent);
+        if(betterScope == oldScope)
+        {
+            // The wrapper asked for a different object, but that object
+            // was in the same scope. We assume here that the new parent
+            // simply hasn't been reparented yet.
+            newParent = nsnull;
         }
         else
-        {
-            // The old scope still works for this wrapper.
-            continue;
-        }
+            NS_ASSERTION(betterScope == newScope, "Weird scope returned");
 
         // Now, reparent the wrapper, since we know that it wants to be
         // reparented.
 
         nsRefPtr<XPCWrappedNative> junk;
         rv = XPCWrappedNative::ReparentWrapperIfFound(ccx, oldScope,
                                                       newScope, newParent,
                                                       wrapper->GetIdentityObject(),
--- a/js/src/xpconnect/src/xpcwrappednative.cpp
+++ b/js/src/xpconnect/src/xpcwrappednative.cpp
@@ -1451,18 +1451,21 @@ XPCWrappedNative::ReparentWrapperIfFound
     nsRefPtr<XPCWrappedNative> wrapper;
     JSObject *flat;
     nsWrapperCache* cache = nsnull;
     CallQueryInterface(aCOMObj, &cache);
     if(cache)
     {
         flat = cache->GetWrapper();
         if(flat && !IS_SLIM_WRAPPER_OBJECT(flat))
+        {
             wrapper = static_cast<XPCWrappedNative*>(xpc_GetJSPrivate(flat));
-        
+            NS_ASSERTION(wrapper->GetScope() == aOldScope,
+                         "Incorrect scope passed");
+        }
     }
     else
     {
         rv = XPCWrappedNative::GetUsedOnly(ccx, aCOMObj, aOldScope, iface,
                                            getter_AddRefs(wrapper));
         if(NS_FAILED(rv))
             return rv;
 
@@ -1596,20 +1599,18 @@ XPCWrappedNative::ReparentWrapperIfFound
                 NS_ERROR("JS_SetPrototype failed");
                 return NS_ERROR_FAILURE;
             }
         }
     }
 
     // Now we can just fix up the parent and return the wrapper
 
-    if(!JS_SetParent(ccx, flat, aNewParent))
-    {
+    if(aNewParent && !JS_SetParent(ccx, flat, aNewParent))
         return NS_ERROR_FAILURE;
-    }
 
     *aWrapper = nsnull;
     wrapper.swap(*aWrapper);
 
     return NS_OK;
 }
 
 #define IS_TEAROFF_CLASS(clazz)                                               \
--- a/layout/base/nsCSSFrameConstructor.cpp
+++ b/layout/base/nsCSSFrameConstructor.cpp
@@ -7218,19 +7218,17 @@ DoApplyRenderingChangeToTree(nsIFrame* a
 }
 
 static void
 ApplyRenderingChangeToTree(nsPresContext* aPresContext,
                            nsIFrame* aFrame,
                            nsChangeHint aChange)
 {
   nsIPresShell *shell = aPresContext->PresShell();
-  PRBool isPaintingSuppressed = PR_FALSE;
-  shell->IsPaintingSuppressed(&isPaintingSuppressed);
-  if (isPaintingSuppressed) {
+  if (shell->IsPaintingSuppressed()) {
     // Don't allow synchronous rendering changes when painting is turned off.
     aChange = NS_SubtractHint(aChange, nsChangeHint_RepaintFrame);
     if (!aChange) {
       return;
     }
   }
 
   // If the frame's background is propagated to an ancestor, walk up to
@@ -10734,19 +10732,17 @@ nsCSSFrameConstructor::ReframeContaining
   if (gNoisyContentUpdates) {
     printf("nsCSSFrameConstructor::ReframeContainingBlock frame=%p\n",
            static_cast<void*>(aFrame));
   }
 #endif
 
   // XXXbz how exactly would we get here while isReflowing anyway?  Should this
   // whole test be ifdef DEBUG?
-  PRBool isReflowing;
-  mPresShell->IsReflowLocked(&isReflowing);
-  if(isReflowing) {
+  if (mPresShell->IsReflowLocked()) {
     // don't ReframeContainingBlock, this will result in a crash
     // if we remove a tree that's in reflow - see bug 121368 for testcase
     NS_ERROR("Atemptted to nsCSSFrameConstructor::ReframeContainingBlock during a Reflow!!!");
     return NS_OK;
   }
 
   // Get the first "normal" ancestor of the target frame.
   nsIFrame* containingBlock = GetIBContainingBlockFor(aFrame);
--- a/layout/base/nsCaret.cpp
+++ b/layout/base/nsCaret.cpp
@@ -1000,19 +1000,17 @@ void nsCaret::DrawCaret(PRBool aInvalida
   // Do we need to draw the caret at all?
   if (!MustDrawCaret(PR_FALSE))
     return;
   
   // Can we draw the caret now?
   nsCOMPtr<nsIPresShell> presShell = do_QueryReferent(mPresShell);
   NS_ENSURE_TRUE(presShell, /**/);
   {
-    PRBool isPaintingSuppressed;
-    presShell->IsPaintingSuppressed(&isPaintingSuppressed);
-    if (isPaintingSuppressed)
+    if (presShell->IsPaintingSuppressed())
     {
       if (!mDrawn)
         mPendingDraw = PR_TRUE;
 
       // PresShell::UnsuppressAndInvalidate() will call CheckCaretDrawingState()
       // to get us drawn.
       return;
     }
--- a/layout/base/nsDisplayList.cpp
+++ b/layout/base/nsDisplayList.cpp
@@ -77,19 +77,17 @@ nsDisplayListBuilder::nsDisplayListBuild
       mPaintAllFrames(PR_FALSE),
       mAccurateVisibleRegions(PR_FALSE),
       mInTransform(PR_FALSE),
       mSyncDecodeImages(PR_FALSE) {
   PL_InitArenaPool(&mPool, "displayListArena", 1024, sizeof(void*)-1);
 
   nsPresContext* pc = aReferenceFrame->PresContext();
   nsIPresShell *shell = pc->PresShell();
-  PRBool suppressed;
-  shell->IsPaintingSuppressed(&suppressed);
-  mIsBackgroundOnly = suppressed;
+  mIsBackgroundOnly = shell->IsPaintingSuppressed();
   if (pc->IsRenderingOnlySelection()) {
     nsCOMPtr<nsISelectionController> selcon(do_QueryInterface(shell));
     if (selcon) {
       selcon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                            getter_AddRefs(mBoundingSelection));
     }
   }
 
@@ -177,18 +175,17 @@ PRBool
 nsDisplayListBuilder::IsMovingFrame(nsIFrame* aFrame)
 {
   return mMovingFrame &&
      nsLayoutUtils::IsAncestorFrameCrossDoc(mMovingFrame, aFrame, mReferenceFrame);
 }
 
 nsCaret *
 nsDisplayListBuilder::GetCaret() {
-  nsRefPtr<nsCaret> caret;
-  CurrentPresShellState()->mPresShell->GetCaret(getter_AddRefs(caret));
+  nsRefPtr<nsCaret> caret = CurrentPresShellState()->mPresShell->GetCaret();
   return caret;
 }
 
 void
 nsDisplayListBuilder::EnterPresShell(nsIFrame* aReferenceFrame,
                                      const nsRect& aDirtyRect) {
   PresShellState* state = mPresShellStates.AppendElement();
   if (!state)
@@ -197,18 +194,17 @@ nsDisplayListBuilder::EnterPresShell(nsI
   state->mCaretFrame = nsnull;
   state->mFirstFrameMarkedForDisplay = mFramesMarkedForDisplay.Length();
 
   state->mPresShell->UpdateCanvasBackground();
 
   if (!mBuildCaret)
     return;
 
-  nsRefPtr<nsCaret> caret;
-  state->mPresShell->GetCaret(getter_AddRefs(caret));
+  nsRefPtr<nsCaret> caret = state->mPresShell->GetCaret();
   state->mCaretFrame = caret->GetCaretFrame();
 
   if (state->mCaretFrame) {
     // Check if the dirty rect intersects with the caret's dirty rect.
     nsRect caretRect =
       caret->GetCaretRect() + state->mCaretFrame->GetOffsetTo(aReferenceFrame);
     if (caretRect.Intersects(aDirtyRect)) {
       // Okay, our rects intersect, let's mark the frame and all of its ancestors.
@@ -1068,17 +1064,17 @@ static PRBool RoundedRectContainsRect(co
 
   return PR_FALSE;
 }
 
 PRBool
 nsDisplayBackground::IsOpaque(nsDisplayListBuilder* aBuilder) {
   // theme background overrides any other background
   if (mIsThemed)
-    return mThemeTransparency == nsITheme::eOpaque;
+    return PR_FALSE;
 
   const nsStyleBackground* bg;
 
   if (!nsCSSRendering::FindBackground(mFrame->PresContext(), mFrame, &bg))
     return PR_FALSE;
 
   const nsStyleBackground::Layer& bottomLayer = bg->BottomLayer();
 
--- a/layout/base/nsDisplayList.h
+++ b/layout/base/nsDisplayList.h
@@ -1300,17 +1300,17 @@ private:
 };
 
 /**
  * The standard display item to paint the CSS background of a frame.
  */
 class nsDisplayBackground : public nsDisplayItem {
 public:
   nsDisplayBackground(nsIFrame* aFrame) : nsDisplayItem(aFrame) {
-    mIsThemed = mFrame->IsThemed(&mThemeTransparency);
+    mIsThemed = mFrame->IsThemed();
     MOZ_COUNT_CTOR(nsDisplayBackground);
   }
 #ifdef NS_BUILD_REFCNT_LOGGING
   virtual ~nsDisplayBackground() {
     MOZ_COUNT_DTOR(nsDisplayBackground);
   }
 #endif
 
@@ -1320,17 +1320,16 @@ public:
   virtual PRBool IsVaryingRelativeToMovingFrame(nsDisplayListBuilder* aBuilder);
   virtual PRBool IsUniform(nsDisplayListBuilder* aBuilder);
   virtual nsRect GetBounds(nsDisplayListBuilder* aBuilder);
   virtual void Paint(nsDisplayListBuilder* aBuilder, nsIRenderingContext* aCtx);
   NS_DISPLAY_DECL_NAME("Background")
 private:
     /* Used to cache mFrame->IsThemed() since it isn't a cheap call */
     PRPackedBool mIsThemed;
-    nsITheme::Transparency mThemeTransparency;
 };
 
 /**
  * The standard display item to paint the outer CSS box-shadows of a frame.
  */
 class nsDisplayBoxShadowOuter : public nsDisplayItem {
 public:
   nsDisplayBoxShadowOuter(nsIFrame* aFrame) : nsDisplayItem(aFrame) {
--- a/layout/base/nsFrameManager.h
+++ b/layout/base/nsFrameManager.h
@@ -87,28 +87,16 @@ public:
   /*
    * After Destroy is called, it is an error to call any FrameManager methods.
    * Destroy should be called when the frame tree managed by the frame
    * manager is no longer being displayed.
    */
   NS_HIDDEN_(void) Destroy();
 
   /*
-   * Gets and sets the root frame (typically the viewport). The lifetime of the
-   * root frame is controlled by the frame manager. When the frame manager is
-   * destroyed, it destroys the entire frame hierarchy.
-   */
-  NS_HIDDEN_(nsIFrame*) GetRootFrame() { return mRootFrame; }
-  NS_HIDDEN_(void)      SetRootFrame(nsIFrame* aRootFrame)
-  {
-    NS_ASSERTION(!mRootFrame, "already have a root frame");
-    mRootFrame = aRootFrame;
-  }
-
-  /*
    * Get the canvas frame, searching from the root frame down.
    * The canvas frame may or may not exist, so this may return null.
    */
   NS_HIDDEN_(nsIFrame*) GetCanvasFrame();
 
   // Placeholder frame functions
   NS_HIDDEN_(nsPlaceholderFrame*) GetPlaceholderFrameFor(nsIFrame* aFrame);
   NS_HIDDEN_(nsresult)
--- a/layout/base/nsFrameManagerBase.h
+++ b/layout/base/nsFrameManagerBase.h
@@ -65,16 +65,28 @@ class nsIAtom;
 class nsStyleChangeList;
 class nsILayoutHistoryState;
 
 class nsFrameManagerBase
 {
 public:
   PRBool IsDestroyingFrames() { return mIsDestroyingFrames; }
 
+  /*
+   * Gets and sets the root frame (typically the viewport). The lifetime of the
+   * root frame is controlled by the frame manager. When the frame manager is
+   * destroyed, it destroys the entire frame hierarchy.
+   */
+  NS_HIDDEN_(nsIFrame*) GetRootFrame() const { return mRootFrame; }
+  NS_HIDDEN_(void)      SetRootFrame(nsIFrame* aRootFrame)
+  {
+    NS_ASSERTION(!mRootFrame, "already have a root frame");
+    mRootFrame = aRootFrame;
+  }
+
 protected:
   class UndisplayedMap;
 
   // weak link, because the pres shell owns us
   nsIPresShell*                   mPresShell;
   // the pres shell owns the style set
   nsStyleSet*                     mStyleSet;
   nsIFrame*                       mRootFrame;
--- a/layout/base/nsIPresShell.h
+++ b/layout/base/nsIPresShell.h
@@ -122,18 +122,18 @@ typedef struct CapturingContentInfo {
   nsIContent* mContent;
 
   CapturingContentInfo() :
     mAllowed(PR_FALSE), mRetargetToElement(PR_FALSE), mPreventDrag(PR_FALSE),
     mContent(nsnull) { }
 } CapturingContentInfo;
 
 #define NS_IPRESSHELL_IID     \
-{ 0x94c34e88, 0x2da3, 0x49d4, \
-  { 0xa5, 0x35, 0x51, 0xa4, 0x16, 0x92, 0xa5, 0x79 } }
+{ 0x6736ae7e, 0x25f9, 0x4594, \
+  { 0xb5, 0x26, 0x49, 0x39, 0x17, 0x63, 0x2f, 0x94 } }
 
 // Constants for ScrollContentIntoView() function
 #define NS_PRESSHELL_SCROLL_TOP      0
 #define NS_PRESSHELL_SCROLL_BOTTOM   100
 #define NS_PRESSHELL_SCROLL_LEFT     0
 #define NS_PRESSHELL_SCROLL_RIGHT    100
 #define NS_PRESSHELL_SCROLL_CENTER   50
 #define NS_PRESSHELL_SCROLL_ANYWHERE -1
@@ -230,42 +230,39 @@ public:
    * The allocations cannot be for more than 4044 bytes.
    */
   virtual void PushStackMemory() = 0;
   virtual void PopStackMemory() = 0;
   virtual void* AllocateStackMemory(size_t aSize) = 0;
 
   nsIDocument* GetDocument() const { return mDocument; }
 
-  nsPresContext* GetPresContext() { return mPresContext; }
+  nsPresContext* GetPresContext() const { return mPresContext; }
 
-  nsIViewManager* GetViewManager() { return mViewManager; }
+  nsIViewManager* GetViewManager() const { return mViewManager; }
 
 #ifdef _IMPL_NS_LAYOUT
-  nsStyleSet*  StyleSet() { return mStyleSet; }
+  nsStyleSet* StyleSet() const { return mStyleSet; }
 
-  nsCSSFrameConstructor* FrameConstructor()
-  {
-    return mFrameConstructor;
-  }
+  nsCSSFrameConstructor* FrameConstructor() const { return mFrameConstructor; }
 
   nsFrameManager* FrameManager() const {
     return reinterpret_cast<nsFrameManager*>
                            (&const_cast<nsIPresShell*>(this)->mFrameManager);
   }
 
 #endif
 
   /* Enable/disable author style level. Disabling author style disables the entire
    * author level of the cascade, including the HTML preshint level.
    */
   // XXX these could easily be inlined, but there is a circular #include
   // problem with nsStyleSet.
   NS_HIDDEN_(void) SetAuthorStyleDisabled(PRBool aDisabled);
-  NS_HIDDEN_(PRBool) GetAuthorStyleDisabled();
+  NS_HIDDEN_(PRBool) GetAuthorStyleDisabled() const;
 
   /*
    * Called when stylesheets are added/removed/enabled/disabled to rebuild
    * all style data for a given pres shell without necessarily reconstructing
    * all of the frames.  This will not reconstruct style synchronously; if
    * you need to do that, call FlushPendingNotifications to flush out style
    * reresolves.
    * // XXXbz why do we have this on the interface anyway?  The only consumer
@@ -296,17 +293,17 @@ public:
    * nsIFrame sel.
    */
   already_AddRefed<nsFrameSelection> FrameSelection();
 
   /**
    * ConstFrameSelection returns an object which methods are safe to use for
    * example in nsIFrame code.
    */
-  const nsFrameSelection* ConstFrameSelection() { return mSelection; }
+  const nsFrameSelection* ConstFrameSelection() const { return mSelection; }
 
   // Make shell be a document observer.  If called after Destroy() has
   // been called on the shell, this will be ignored.
   virtual NS_HIDDEN_(void) BeginObservingDocument() = 0;
 
   // Make shell stop being a document observer
   virtual NS_HIDDEN_(void) EndObservingDocument() = 0;
 
@@ -336,20 +333,25 @@ public:
 
   /**
    * Reflow the frame model with a reflow reason of eReflowReason_StyleChange
    */
   virtual NS_HIDDEN_(void) StyleChangeReflow() = 0;
 
   /**
    * This calls through to the frame manager to get the root frame.
-   * Callers inside of gklayout should use FrameManager()->GetRootFrame()
-   * instead, as it's more efficient.
    */
-  virtual NS_HIDDEN_(nsIFrame*) GetRootFrame() const;
+  virtual NS_HIDDEN_(nsIFrame*) GetRootFrameExternal() const;
+  nsIFrame* GetRootFrame() const {
+#ifdef _IMPL_NS_LAYOUT
+    return mFrameManager.GetRootFrame();
+#else
+    return GetRootFrameExternal();
+#endif
+  }
 
   /*
    * Get root scroll frame from FrameManager()->GetRootFrame().
    */
   nsIFrame* GetRootScrollFrame() const;
 
   /*
    * The same as GetRootScrollFrame, but returns an nsIScrollableFrame
@@ -423,74 +425,74 @@ public:
    */
   virtual NS_HIDDEN_(void) FrameNeedsToContinueReflow(nsIFrame *aFrame) = 0;
 
   virtual NS_HIDDEN_(void) CancelAllPendingReflows() = 0;
 
   /**
    * Recreates the frames for a node
    */
-  NS_IMETHOD RecreateFramesFor(nsIContent* aContent) = 0;
+  virtual NS_HIDDEN_(nsresult) RecreateFramesFor(nsIContent* aContent) = 0;
 
   void PostRecreateFramesFor(nsIContent* aContent);
   void RestyleForAnimation(nsIContent* aContent);
 
   /**
    * Determine if it is safe to flush all pending notifications
    * @param aIsSafeToFlush PR_TRUE if it is safe, PR_FALSE otherwise.
    * 
    */
-  virtual NS_HIDDEN_(PRBool) IsSafeToFlush() = 0;
+  virtual NS_HIDDEN_(PRBool) IsSafeToFlush() const = 0;
 
   /**
    * Flush pending notifications of the type specified.  This method
    * will not affect the content model; it'll just affect style and
    * frames. Callers that actually want up-to-date presentation (other
    * than the document itself) should probably be calling
    * nsIDocument::FlushPendingNotifications.
    *
    * @param aType the type of notifications to flush
    */
   virtual NS_HIDDEN_(void) FlushPendingNotifications(mozFlushType aType) = 0;
 
   /**
    * Callbacks will be called even if reflow itself fails for
    * some reason.
    */
-  NS_IMETHOD PostReflowCallback(nsIReflowCallback* aCallback) = 0;
-  NS_IMETHOD CancelReflowCallback(nsIReflowCallback* aCallback) = 0;
+  virtual NS_HIDDEN_(nsresult) PostReflowCallback(nsIReflowCallback* aCallback) = 0;
+  virtual NS_HIDDEN_(void) CancelReflowCallback(nsIReflowCallback* aCallback) = 0;
 
-  NS_IMETHOD ClearFrameRefs(nsIFrame* aFrame) = 0;
+  virtual NS_HIDDEN_(void) ClearFrameRefs(nsIFrame* aFrame) = 0;
 
   /**
    * Given a frame, create a rendering context suitable for use with
    * the frame.
    */
-  NS_IMETHOD CreateRenderingContext(nsIFrame *aFrame,
-                                    nsIRenderingContext** aContext) = 0;
+  virtual NS_HIDDEN_(nsresult) CreateRenderingContext(nsIFrame *aFrame,
+                                                      nsIRenderingContext** aContext) = 0;
 
   /**
    * Informs the pres shell that the document is now at the anchor with
    * the given name.  If |aScroll| is true, scrolls the view of the
    * document so that the anchor with the specified name is displayed at
    * the top of the window.  If |aAnchorName| is empty, then this informs
    * the pres shell that there is no current target, and |aScroll| must
    * be false.
    */
-  NS_IMETHOD GoToAnchor(const nsAString& aAnchorName, PRBool aScroll) = 0;
+  virtual NS_HIDDEN_(nsresult) GoToAnchor(const nsAString& aAnchorName, PRBool aScroll) = 0;
 
   /**
    * Tells the presshell to scroll again to the last anchor scrolled to by
    * GoToAnchor, if any. This scroll only happens if the scroll
    * position has not changed since the last GoToAnchor. This is called
    * by nsDocumentViewer::LoadComplete. This clears the last anchor
    * scrolled to by GoToAnchor (we don't want to keep it alive if it's
    * removed from the DOM), so don't call this more than once.
    */
-  NS_IMETHOD ScrollToAnchor() = 0;
+  virtual NS_HIDDEN_(nsresult) ScrollToAnchor() = 0;
 
   /**
    * Scrolls the view of the document so that the primary frame of the content
    * is displayed in the window. Layout is flushed before scrolling.
    *
    * @param aContent  The content object of which primary frame should be
    *                  scrolled into view.
    * @param aVPercent How to align the frame vertically. A value of 0
@@ -511,19 +513,19 @@ public:
    *                  edge is aligned with the right edge of the visible area.
    *                  For values in between, the point "aVPercent" across the frame
    *                  is placed at the point "aVPercent" across the visible area.
    *                  A value of 50 (NS_PRESSHELL_SCROLL_CENTER) centers the frame
    *                  horizontally . A value of NS_PRESSHELL_SCROLL_ANYWHERE means move
    *                  the frame the minimum amount necessary in order for the entire
    *                  frame to be visible horizontally (if possible)
    */
-  NS_IMETHOD ScrollContentIntoView(nsIContent* aContent,
-                                   PRIntn      aVPercent,
-                                   PRIntn      aHPercent) = 0;
+  virtual NS_HIDDEN_(nsresult) ScrollContentIntoView(nsIContent* aContent,
+                                                     PRIntn      aVPercent,
+                                                     PRIntn      aHPercent) = 0;
 
   enum {
     SCROLL_FIRST_ANCESTOR_ONLY = 0x01,
     SCROLL_OVERFLOW_HIDDEN = 0x02
   };
   /**
    * Scrolls the view of the document so that the given area of a frame
    * is visible, if possible. Layout is not flushed before scrolling.
@@ -556,48 +558,48 @@ public:
    * @return nsRectVisibility_kVisible if the rect is visible
    *         nsRectVisibility_kAboveViewport
    *         nsRectVisibility_kBelowViewport 
    *         nsRectVisibility_kLeftOfViewport 
    *         nsRectVisibility_kRightOfViewport rectangle is outside the viewport
    *         in the specified direction 
    */
   virtual nsRectVisibility GetRectVisibility(nsIFrame *aFrame,
-                                             const nsRect &aRect, 
-                                             nscoord aMinTwips) = 0;
+                                             const nsRect &aRect,
+                                             nscoord aMinTwips) const = 0;
 
   /**
    * Suppress notification of the frame manager that frames are
    * being destroyed.
    */
-  NS_IMETHOD SetIgnoreFrameDestruction(PRBool aIgnore) = 0;
+  virtual NS_HIDDEN_(void) SetIgnoreFrameDestruction(PRBool aIgnore) = 0;
 
   /**
    * Notification sent by a frame informing the pres shell that it is about to
    * be destroyed.
    * This allows any outstanding references to the frame to be cleaned up
    */
-  NS_IMETHOD NotifyDestroyingFrame(nsIFrame* aFrame) = 0;
+  virtual NS_HIDDEN_(void) NotifyDestroyingFrame(nsIFrame* aFrame) = 0;
 
   /**
    * Get link location.
    */
-  NS_IMETHOD GetLinkLocation(nsIDOMNode* aNode, nsAString& aLocation) = 0;
+  virtual NS_HIDDEN_(nsresult) GetLinkLocation(nsIDOMNode* aNode, nsAString& aLocation) const = 0;
 
   /**
    * Get the caret, if it exists. AddRefs it.
    */
-  NS_IMETHOD GetCaret(nsCaret **aOutCaret) = 0;
+  virtual NS_HIDDEN_(already_AddRefed<nsCaret>) GetCaret() const = 0;
 
   /**
    * Invalidate the caret's current position if it's outside of its frame's
    * boundaries. This function is useful if you're batching selection
    * notifications and might remove the caret's frame out from under it.
    */
-  NS_IMETHOD_(void) MaybeInvalidateCaretPosition() = 0;
+  virtual NS_HIDDEN_(void) MaybeInvalidateCaretPosition() = 0;
 
   /**
    * Set the current caret to a new caret. To undo this, call RestoreCaret.
    */
   virtual void SetCaret(nsCaret *aNewCaret) = 0;
 
   /**
    * Restore the caret to the original caret that this pres shell was created
@@ -615,83 +617,83 @@ public:
    */
   NS_IMETHOD SetSelectionFlags(PRInt16 aInEnable) = 0;
 
   /** 
     * Gets the current state of non text selection effects
     * @return   current state of non text selection,
     *           as set by SetDisplayNonTextSelection
     */
-  virtual NS_HIDDEN_(PRInt16) GetSelectionFlags() = 0;
+  PRInt16 GetSelectionFlags() const { return mSelectionFlags; }
 
   virtual nsISelection* GetCurrentSelection(SelectionType aType) = 0;
 
   /**
     * Interface to dispatch events via the presshell
     * @note The caller must have a strong reference to the PresShell.
     */
-  NS_IMETHOD HandleEventWithTarget(nsEvent* aEvent,
-                                   nsIFrame* aFrame,
-                                   nsIContent* aContent,
-                                   nsEventStatus* aStatus) = 0;
+  virtual NS_HIDDEN_(nsresult) HandleEventWithTarget(nsEvent* aEvent,
+                                                     nsIFrame* aFrame,
+                                                     nsIContent* aContent,
+                                                     nsEventStatus* aStatus) = 0;
 
   /**
    * Dispatch event to content only (NOT full processing)
    * @note The caller must have a strong reference to the PresShell.
    */
-  NS_IMETHOD HandleDOMEventWithTarget(nsIContent* aTargetContent,
-                                      nsEvent* aEvent,
-                                      nsEventStatus* aStatus) = 0;
+  virtual NS_HIDDEN_(nsresult) HandleDOMEventWithTarget(nsIContent* aTargetContent,
+                                                        nsEvent* aEvent,
+                                                        nsEventStatus* aStatus) = 0;
 
   /**
    * Dispatch event to content only (NOT full processing)
    * @note The caller must have a strong reference to the PresShell.
    */
-  NS_IMETHOD HandleDOMEventWithTarget(nsIContent* aTargetContent,
-                                      nsIDOMEvent* aEvent,
-                                      nsEventStatus* aStatus) = 0;
+  virtual NS_HIDDEN_(nsresult) HandleDOMEventWithTarget(nsIContent* aTargetContent,
+                                                        nsIDOMEvent* aEvent,
+                                                        nsEventStatus* aStatus) = 0;
 
   /**
     * Gets the current target event frame from the PresShell
     */
-  NS_IMETHOD GetEventTargetFrame(nsIFrame** aFrame) = 0;
+  virtual NS_HIDDEN_(nsIFrame*) GetEventTargetFrame() = 0;
 
   /**
     * Gets the current target event frame from the PresShell
     */
-  NS_IMETHOD GetEventTargetContent(nsEvent* aEvent, nsIContent** aContent) = 0;
+  virtual NS_HIDDEN_(already_AddRefed<nsIContent>) GetEventTargetContent(nsEvent* aEvent) = 0;
 
   /**
    * Get and set the history state for the current document 
    */
 
-  NS_IMETHOD CaptureHistoryState(nsILayoutHistoryState** aLayoutHistoryState, PRBool aLeavingPage = PR_FALSE) = 0;
+  virtual NS_HIDDEN_(nsresult) CaptureHistoryState(nsILayoutHistoryState** aLayoutHistoryState, PRBool aLeavingPage = PR_FALSE) = 0;
 
   /**
    * Determine if reflow is currently locked
-   * @param aIsReflowLocked returns PR_TRUE if reflow is locked, PR_FALSE otherwise
+   * returns PR_TRUE if reflow is locked, PR_FALSE otherwise
    */
-  NS_IMETHOD IsReflowLocked(PRBool* aIsLocked) = 0;  
+  PRBool IsReflowLocked() const { return mIsReflowing; }
 
   /**
    * Called to find out if painting is suppressed for this presshell.  If it is suppressd,
    * we don't allow the painting of any layer but the background, and we don't
    * recur into our children.
    */
-  NS_IMETHOD IsPaintingSuppressed(PRBool* aResult)=0;
+  PRBool IsPaintingSuppressed() const { return mPaintingSuppressed; }
 
   /**
    * Unsuppress painting.
    */
-  NS_IMETHOD UnsuppressPainting() = 0;
+  virtual NS_HIDDEN_(void) UnsuppressPainting() = 0;
 
   /**
    * Called to disable nsITheme support in a specific presshell.
    */
-  NS_IMETHOD DisableThemeSupport() = 0;
+  virtual NS_HIDDEN_(void) DisableThemeSupport() = 0;
 
   /**
    * Indicates whether theme support is enabled.
    */
   virtual PRBool IsThemeSupportEnabled() = 0;
 
   /**
    * Get the set of agent style sheets for this presentation
@@ -742,24 +744,24 @@ public:
   /**
    * Get the flags associated with the VerifyReflow debug tool
    */
   static PRInt32 GetVerifyReflowFlags();
 
   virtual nsIFrame* GetAbsoluteContainingBlock(nsIFrame* aFrame);
 
 #ifdef MOZ_REFLOW_PERF
-  NS_IMETHOD DumpReflows() = 0;
-  NS_IMETHOD CountReflows(const char * aName, nsIFrame * aFrame) = 0;
-  NS_IMETHOD PaintCount(const char * aName, 
-                        nsIRenderingContext* aRenderingContext, 
-                        nsPresContext * aPresContext, 
-                        nsIFrame * aFrame,
-                        PRUint32 aColor) = 0;
-  NS_IMETHOD SetPaintFrameCount(PRBool aOn) = 0;
+  virtual NS_HIDDEN_(void) DumpReflows() = 0;
+  virtual NS_HIDDEN_(void) CountReflows(const char * aName, nsIFrame * aFrame) = 0;
+  virtual NS_HIDDEN_(void) PaintCount(const char * aName,
+                                      nsIRenderingContext* aRenderingContext,
+                                      nsPresContext * aPresContext,
+                                      nsIFrame * aFrame,
+                                      PRUint32 aColor) = 0;
+  virtual NS_HIDDEN_(void) SetPaintFrameCount(PRBool aOn) = 0;
   virtual PRBool IsPaintingFrameCounts() = 0;
 #endif
 
 #ifdef DEBUG
   // Debugging hooks
   virtual void ListStyleContexts(nsIFrame *aRootFrame, FILE *out,
                                  PRInt32 aIndent = 0) = 0;
 
@@ -827,19 +829,19 @@ public:
    * transform.
    */
   enum {
     RENDER_IS_UNTRUSTED = 0x01,
     RENDER_IGNORE_VIEWPORT_SCROLLING = 0x02,
     RENDER_CARET = 0x04,
     RENDER_USE_WIDGET_LAYERS = 0x08
   };
-  NS_IMETHOD RenderDocument(const nsRect& aRect, PRUint32 aFlags,
-                            nscolor aBackgroundColor,
-                            gfxContext* aRenderedContext) = 0;
+  virtual NS_HIDDEN_(nsresult) RenderDocument(const nsRect& aRect, PRUint32 aFlags,
+                                              nscolor aBackgroundColor,
+                                              gfxContext* aRenderedContext) = 0;
 
   /**
    * Renders a node aNode to a surface and returns it. The aRegion may be used
    * to clip the rendering. This region is measured in device pixels from the
    * edge of the presshell area. The aPoint, aScreenRect and aSurface
    * arguments function in a similar manner as RenderSelection.
    */
   virtual already_AddRefed<gfxASurface> RenderNode(nsIDOMNode* aNode,
@@ -896,17 +898,17 @@ public:
 
   /**
    * Stop or restart non synthetic test mouse event handling on *all*
    * presShells.
    *
    * @param aDisable If true, disable all non synthetic test mouse
    * events on all presShells.  Otherwise, enable them.
    */
-  NS_IMETHOD DisableNonTestMouseEvents(PRBool aDisable) = 0;
+  virtual NS_HIDDEN_(void) DisableNonTestMouseEvents(PRBool aDisable) = 0;
 
   /**
    * Record the background color of the most recently drawn canvas. This color
    * is composited on top of the user's default background color and then used
    * to draw the background color of the canvas. See PresShell::Paint,
    * PresShell::PaintDefaultBackground, and nsDocShell::SetupNewViewer;
    * bug 488242, bug 476557 and other bugs mentioned there.
    */
@@ -1006,19 +1008,23 @@ protected:
   nsFrameSelection*         mSelection;
   nsFrameManagerBase        mFrameManager;  // [OWNS]
   nsWeakPtr                 mForwardingContainer;
 
 #ifdef NS_DEBUG
   nsIFrame*                 mDrawEventTargetFrame;
 #endif
 
+  PRInt16                   mSelectionFlags;
+
   PRPackedBool              mStylesHaveChanged;
   PRPackedBool              mDidInitialReflow;
   PRPackedBool              mIsDestroying;
+  PRPackedBool              mIsReflowing;
+  PRPackedBool              mPaintingSuppressed;  // For all documents we initially lock down painting.
 
 #ifdef ACCESSIBILITY
   /**
    * Call this when there have been significant changes in the rendering for
    * a content subtree, so the matching accessibility subtree can be invalidated
    */
   void InvalidateAccessibleSubtree(nsIContent *aContent);
 #endif
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -3239,21 +3239,19 @@ nsLayoutUtils::HasNonZeroCornerOnSide(co
 nsLayoutUtils::GetFrameTransparency(nsIFrame* aBackgroundFrame,
                                     nsIFrame* aCSSRootFrame) {
   if (aCSSRootFrame->GetStyleContext()->GetStyleDisplay()->mOpacity < 1.0f)
     return eTransparencyTransparent;
 
   if (HasNonZeroCorner(aCSSRootFrame->GetStyleContext()->GetStyleBorder()->mBorderRadius))
     return eTransparencyTransparent;
 
-  nsITheme::Transparency transparency;
+  nsTransparencyMode transparency;
   if (aCSSRootFrame->IsThemed(&transparency))
-    return transparency == nsITheme::eTransparent
-         ? eTransparencyTransparent
-         : eTransparencyOpaque;
+    return transparency;
 
   if (aCSSRootFrame->GetStyleDisplay()->mAppearance == NS_THEME_WIN_GLASS)
     return eTransparencyGlass;
 
   // We need an uninitialized window to be treated as opaque because
   // doing otherwise breaks window display effects on some platforms,
   // specifically Vista. (bug 450322)
   if (aBackgroundFrame->GetType() == nsGkAtoms::viewportFrame &&
--- a/layout/base/nsPresContext.cpp
+++ b/layout/base/nsPresContext.cpp
@@ -1618,17 +1618,17 @@ nsPresContext::EnsureVisible()
 {
   nsCOMPtr<nsIDocShell> docShell(do_QueryReferent(mContainer));
   if (docShell) {
     nsCOMPtr<nsIContentViewer> cv;
     docShell->GetContentViewer(getter_AddRefs(cv));
     // Make sure this is the content viewer we belong with
     nsCOMPtr<nsIDocumentViewer> docV(do_QueryInterface(cv));
     if (docV) {
-      nsCOMPtr<nsPresContext> currentPresContext;
+      nsRefPtr<nsPresContext> currentPresContext;
       docV->GetPresContext(getter_AddRefs(currentPresContext));
       if (currentPresContext == this) {
         // OK, this is us.  We want to call Show() on the content viewer.
         cv->Show();
         return PR_TRUE;
       }
     }
   }
@@ -1841,19 +1841,17 @@ nsPresContext::GetUserFontSetInternal()
     // @font-face rules, then we will call StyleChangeReflow in
     // FlushUserFontSet.  If we're in the middle of reflow,
     // that's a bad thing to do, and the caller was responsible for
     // flushing first.  If we're not (e.g., in frame construction), it's
     // ok.
 #ifdef DEBUG
     {
       PRBool inReflow;
-      NS_ASSERTION(!userFontSetGottenBefore ||
-                   (NS_SUCCEEDED(mShell->IsReflowLocked(&inReflow)) &&
-                    !inReflow),
+      NS_ASSERTION(!userFontSetGottenBefore || !mShell->IsReflowLocked(),
                    "FlushUserFontSet should have been called first");
     }
 #endif
     FlushUserFontSet();
   }
 
   return mUserFontSet;
 }
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -697,85 +697,83 @@ public:
   virtual NS_HIDDEN_(nsIPageSequenceFrame*) GetPageSequenceFrame() const;
   virtual NS_HIDDEN_(nsIFrame*) GetRealPrimaryFrameFor(nsIContent* aContent) const;
 
   virtual NS_HIDDEN_(nsIFrame*) GetPlaceholderFrameFor(nsIFrame* aFrame) const;
   virtual NS_HIDDEN_(void) FrameNeedsReflow(nsIFrame *aFrame, IntrinsicDirty aIntrinsicDirty,
                                             nsFrameState aBitToAdd);
   virtual NS_HIDDEN_(void) FrameNeedsToContinueReflow(nsIFrame *aFrame);
   virtual NS_HIDDEN_(void) CancelAllPendingReflows();
-  virtual NS_HIDDEN_(PRBool) IsSafeToFlush();
+  virtual NS_HIDDEN_(PRBool) IsSafeToFlush() const;
   virtual NS_HIDDEN_(void) FlushPendingNotifications(mozFlushType aType);
 
   /**
    * Recreates the frames for a node
    */
-  NS_IMETHOD RecreateFramesFor(nsIContent* aContent);
+  virtual NS_HIDDEN_(nsresult) RecreateFramesFor(nsIContent* aContent);
 
   /**
    * Post a callback that should be handled after reflow has finished.
    */
-  NS_IMETHOD PostReflowCallback(nsIReflowCallback* aCallback);
-  NS_IMETHOD CancelReflowCallback(nsIReflowCallback* aCallback);
-
-  NS_IMETHOD ClearFrameRefs(nsIFrame* aFrame);
-  NS_IMETHOD CreateRenderingContext(nsIFrame *aFrame,
-                                    nsIRenderingContext** aContext);
-  NS_IMETHOD GoToAnchor(const nsAString& aAnchorName, PRBool aScroll);
-  NS_IMETHOD ScrollToAnchor();
-
-  NS_IMETHOD ScrollContentIntoView(nsIContent* aContent,
-                                   PRIntn      aVPercent,
-                                   PRIntn      aHPercent);
+  virtual NS_HIDDEN_(nsresult) PostReflowCallback(nsIReflowCallback* aCallback);
+  virtual NS_HIDDEN_(void) CancelReflowCallback(nsIReflowCallback* aCallback);
+
+  virtual NS_HIDDEN_(void) ClearFrameRefs(nsIFrame* aFrame);
+  virtual NS_HIDDEN_(nsresult) CreateRenderingContext(nsIFrame *aFrame,
+                                                      nsIRenderingContext** aContext);
+  virtual NS_HIDDEN_(nsresult) GoToAnchor(const nsAString& aAnchorName, PRBool aScroll);
+  virtual NS_HIDDEN_(nsresult) ScrollToAnchor();
+
+  virtual NS_HIDDEN_(nsresult) ScrollContentIntoView(nsIContent* aContent,
+                                                     PRIntn      aVPercent,
+                                                     PRIntn      aHPercent);
   virtual PRBool ScrollFrameRectIntoView(nsIFrame*     aFrame,
                                          const nsRect& aRect,
                                          PRIntn        aVPercent,
                                          PRIntn        aHPercent,
                                          PRUint32      aFlags);
   virtual nsRectVisibility GetRectVisibility(nsIFrame *aFrame,
-                                             const nsRect &aRect, 
-                                             nscoord aMinTwips);
-
-  NS_IMETHOD SetIgnoreFrameDestruction(PRBool aIgnore);
-  NS_IMETHOD NotifyDestroyingFrame(nsIFrame* aFrame);
-
-  NS_IMETHOD GetLinkLocation(nsIDOMNode* aNode, nsAString& aLocationString);
-
-  NS_IMETHOD CaptureHistoryState(nsILayoutHistoryState** aLayoutHistoryState, PRBool aLeavingPage);
-
-  NS_IMETHOD IsPaintingSuppressed(PRBool* aResult);
-  NS_IMETHOD UnsuppressPainting();
-  
-  NS_IMETHOD DisableThemeSupport();
+                                             const nsRect &aRect,
+                                             nscoord aMinTwips) const;
+
+  virtual NS_HIDDEN_(void) SetIgnoreFrameDestruction(PRBool aIgnore);
+  virtual NS_HIDDEN_(void) NotifyDestroyingFrame(nsIFrame* aFrame);
+
+  virtual NS_HIDDEN_(nsresult) GetLinkLocation(nsIDOMNode* aNode, nsAString& aLocationString) const;
+
+  virtual NS_HIDDEN_(nsresult) CaptureHistoryState(nsILayoutHistoryState** aLayoutHistoryState, PRBool aLeavingPage);
+
+  virtual NS_HIDDEN_(void) UnsuppressPainting();
+
+  virtual NS_HIDDEN_(void) DisableThemeSupport();
   virtual PRBool IsThemeSupportEnabled();
 
   virtual nsresult GetAgentStyleSheets(nsCOMArray<nsIStyleSheet>& aSheets);
   virtual nsresult SetAgentStyleSheets(const nsCOMArray<nsIStyleSheet>& aSheets);
 
   virtual nsresult AddOverrideStyleSheet(nsIStyleSheet *aSheet);
   virtual nsresult RemoveOverrideStyleSheet(nsIStyleSheet *aSheet);
 
-  NS_IMETHOD HandleEventWithTarget(nsEvent* aEvent, nsIFrame* aFrame,
-                                   nsIContent* aContent,
-                                   nsEventStatus* aStatus);
-  NS_IMETHOD GetEventTargetFrame(nsIFrame** aFrame);
-  NS_IMETHOD GetEventTargetContent(nsEvent* aEvent, nsIContent** aContent);
-
-  NS_IMETHOD IsReflowLocked(PRBool* aIsLocked);  
+  virtual NS_HIDDEN_(nsresult) HandleEventWithTarget(nsEvent* aEvent, nsIFrame* aFrame,
+                                                     nsIContent* aContent,
+                                                     nsEventStatus* aStatus);
+  virtual NS_HIDDEN_(nsIFrame*) GetEventTargetFrame();
+  virtual NS_HIDDEN_(already_AddRefed<nsIContent>) GetEventTargetContent(nsEvent* aEvent);
+
 
   virtual nsresult ReconstructFrames(void);
   virtual void Freeze();
   virtual void Thaw();
   virtual void FireOrClearDelayedEvents(PRBool aFireEvents);
 
   virtual nsIFrame* GetFrameForPoint(nsIFrame* aFrame, nsPoint aPt);
 
-  NS_IMETHOD RenderDocument(const nsRect& aRect, PRUint32 aFlags,
-                            nscolor aBackgroundColor,
-                            gfxContext* aThebesContext);
+  virtual NS_HIDDEN_(nsresult) RenderDocument(const nsRect& aRect, PRUint32 aFlags,
+                                              nscolor aBackgroundColor,
+                                              gfxContext* aThebesContext);
 
   virtual already_AddRefed<gfxASurface> RenderNode(nsIDOMNode* aNode,
                                                    nsIRegion* aRegion,
                                                    nsIntPoint& aPoint,
                                                    nsIntRect* aScreenRect);
 
   virtual already_AddRefed<gfxASurface> RenderSelection(nsISelection* aSelection,
                                                         nsIntPoint& aPoint,
@@ -792,43 +790,42 @@ public:
                                          nsIView*      aMovingView,
                                          nsPoint       aDelta,
                                          const nsRect& aUpdateRect,
                                          nsRegion*     aBlitRegion,
                                          nsRegion*     aRepaintRegion);
   NS_IMETHOD HandleEvent(nsIView*        aView,
                          nsGUIEvent*     aEvent,
                          nsEventStatus*  aEventStatus);
-  NS_IMETHOD HandleDOMEventWithTarget(nsIContent* aTargetContent,
-                                      nsEvent* aEvent,
-                                      nsEventStatus* aStatus);
-  NS_IMETHOD HandleDOMEventWithTarget(nsIContent* aTargetContent,
-                                      nsIDOMEvent* aEvent,
-                                      nsEventStatus* aStatus);
+  virtual NS_HIDDEN_(nsresult) HandleDOMEventWithTarget(nsIContent* aTargetContent,
+                                                        nsEvent* aEvent,
+                                                        nsEventStatus* aStatus);
+  virtual NS_HIDDEN_(nsresult) HandleDOMEventWithTarget(nsIContent* aTargetContent,
+                                                        nsIDOMEvent* aEvent,
+                                                        nsEventStatus* aStatus);
   NS_IMETHOD ResizeReflow(nsIView *aView, nscoord aWidth, nscoord aHeight);
   NS_IMETHOD_(PRBool) IsVisible();
   NS_IMETHOD_(void) WillPaint();
   NS_IMETHOD_(void) DispatchSynthMouseMove(nsGUIEvent *aEvent,
                                            PRBool aFlushOnHoverChange);
   NS_IMETHOD_(void) ClearMouseCapture(nsIView* aView);
 
   // caret handling
-  NS_IMETHOD GetCaret(nsCaret **aOutCaret);
-  NS_IMETHOD_(void) MaybeInvalidateCaretPosition();
+  virtual NS_HIDDEN_(already_AddRefed<nsCaret>) GetCaret() const;
+  virtual NS_HIDDEN_(void) MaybeInvalidateCaretPosition();
   NS_IMETHOD SetCaretEnabled(PRBool aInEnable);
   NS_IMETHOD SetCaretReadOnly(PRBool aReadOnly);
   NS_IMETHOD GetCaretEnabled(PRBool *aOutEnabled);
   NS_IMETHOD SetCaretVisibilityDuringSelection(PRBool aVisibility);
   NS_IMETHOD GetCaretVisible(PRBool *_retval);
   virtual void SetCaret(nsCaret *aNewCaret);
   virtual void RestoreCaret();
 
   NS_IMETHOD SetSelectionFlags(PRInt16 aInEnable);
   NS_IMETHOD GetSelectionFlags(PRInt16 *aOutEnable);
-  virtual NS_HIDDEN_(PRInt16) GetSelectionFlags();
 
   // nsISelectionController
 
   NS_IMETHOD CharacterMove(PRBool aForward, PRBool aExtend);
   NS_IMETHOD CharacterExtendForDelete();
   NS_IMETHOD WordMove(PRBool aForward, PRBool aExtend);
   NS_IMETHOD WordExtendForDelete(PRBool aForward);
   NS_IMETHOD LineMove(PRBool aForward, PRBool aExtend);
@@ -882,37 +879,40 @@ public:
   NS_DECL_NSIMUTATIONOBSERVER_CONTENTREMOVED
 
   NS_DECL_NSIOBSERVER
 
   // nsARefreshObserver
   virtual void WillRefresh(mozilla::TimeStamp aTime);
 
 #ifdef MOZ_REFLOW_PERF
-  NS_IMETHOD DumpReflows();
-  NS_IMETHOD CountReflows(const char * aName, nsIFrame * aFrame);
-  NS_IMETHOD PaintCount(const char * aName, nsIRenderingContext* aRenderingContext, nsPresContext* aPresContext, nsIFrame * aFrame, PRUint32 aColor);
-
-  NS_IMETHOD SetPaintFrameCount(PRBool aOn);
+  virtual NS_HIDDEN_(void) DumpReflows();
+  virtual NS_HIDDEN_(void) CountReflows(const char * aName, nsIFrame * aFrame);
+  virtual NS_HIDDEN_(void) PaintCount(const char * aName,
+                                      nsIRenderingContext* aRenderingContext,
+                                      nsPresContext* aPresContext,
+                                      nsIFrame * aFrame,
+                                      PRUint32 aColor);
+  virtual NS_HIDDEN_(void) SetPaintFrameCount(PRBool aOn);
   virtual PRBool IsPaintingFrameCounts();
 #endif
 
 #ifdef DEBUG
   virtual void ListStyleContexts(nsIFrame *aRootFrame, FILE *out,
                                  PRInt32 aIndent = 0);
 
   virtual void ListStyleSheets(FILE *out, PRInt32 aIndent = 0);
   virtual void VerifyStyleTree();
 #endif
 
 #ifdef PR_LOGGING
   static PRLogModuleInfo* gLog;
 #endif
 
-  NS_IMETHOD DisableNonTestMouseEvents(PRBool aDisable);
+  virtual NS_HIDDEN_(void) DisableNonTestMouseEvents(PRBool aDisable);
 
   virtual void UpdateCanvasBackground();
 
   virtual nsresult AddCanvasBackgroundColorItem(nsDisplayListBuilder& aBuilder,
                                                 nsDisplayList& aList,
                                                 nsIFrame* aFrame,
                                                 nsRect* aBounds,
                                                 nscolor aBackstopColor,
@@ -1041,17 +1041,16 @@ protected:
                                               // maintain a ref, may be null
 #ifdef DEBUG
   PRUint32                  mUpdateCount;
 #endif
   // reflow roots that need to be reflowed, as both a queue and a hashtable
   nsTArray<nsIFrame*> mDirtyRoots;
 
   PRPackedBool mDocumentLoading;
-  PRPackedBool mIsReflowing;
 
   PRPackedBool mIgnoreFrameDestruction;
   PRPackedBool mHaveShutDown;
 
   // This is used to protect ourselves from triggering reflow while in the
   // middle of frame construction and the like... it really shouldn't be
   // needed, one hopes, but it is for now.
   PRUint32  mChangeNestCount;
@@ -1060,17 +1059,16 @@ protected:
   nsCOMPtr<nsIContent> mCurrentEventContent;
   nsTArray<nsIFrame*> mCurrentEventFrameStack;
   nsCOMArray<nsIContent> mCurrentEventContentStack;
 
   nsCOMPtr<nsIContent>          mLastAnchorScrolledTo;
   nscoord                       mLastAnchorScrollPositionY;
   nsRefPtr<nsCaret>             mCaret;
   nsRefPtr<nsCaret>             mOriginalCaret;
-  PRInt16                       mSelectionFlags;
   nsPresArena                   mFrameArena;
   StackArena                    mStackArena;
   nsCOMPtr<nsIDragService>      mDragService;
   
 #ifdef DEBUG
   // The reflow root under which we're currently reflowing.  Null when
   // not in reflow.
   nsIFrame* mCurrentReflowRoot;
@@ -1183,17 +1181,16 @@ protected:
   nsCallbackEventRequest* mFirstCallbackEventRequest;
   nsCallbackEventRequest* mLastCallbackEventRequest;
 
   PRPackedBool      mSuppressInterruptibleReflows;
 
   PRPackedBool      mIsThemeSupportDisabled;  // Whether or not form controls should use nsITheme in this shell.
 
   PRPackedBool      mIsDocumentGone;      // We've been disconnected from the document.
-  PRPackedBool      mPaintingSuppressed;  // For all documents we initially lock down painting.
                                           // We will refuse to paint the document until either
                                           // (a) our timer fires or (b) all frames are constructed.
   PRPackedBool      mShouldUnsuppressPainting;  // Indicates that it is safe to unlock painting once all pending
                                                 // reflows have been processed.
   PRPackedBool      mReflowScheduled; // If true, we have a reflow scheduled.
                                       // Guaranteed to be false if
                                       // mReflowContinueTimer is non-null.
   nsCOMPtr<nsITimer> mPaintSuppressionTimer; // This timer controls painting suppression.  Until it fires
@@ -1490,25 +1487,26 @@ nsIPresShell::FrameSelection()
 }
 
 //----------------------------------------------------------------------
 
 nsresult
 NS_NewPresShell(nsIPresShell** aInstancePtrResult)
 {
   NS_PRECONDITION(nsnull != aInstancePtrResult, "null ptr");
-  if (nsnull == aInstancePtrResult) {
+
+  if (!aInstancePtrResult)
     return NS_ERROR_NULL_POINTER;
-  }
-  PresShell* it = new PresShell();
-  if (nsnull == it) {
+
+  *aInstancePtrResult = new PresShell();
+  if (!*aInstancePtrResult)
     return NS_ERROR_OUT_OF_MEMORY;
-  }
-  return it->QueryInterface(NS_GET_IID(nsIPresShell),
-                            (void **) aInstancePtrResult);
+
+  NS_ADDREF(*aInstancePtrResult);
+  return NS_OK;
 }
 
 PresShell::PresShell()
 {
   mSelection = nsnull;
 #ifdef MOZ_REFLOW_PERF
   mReflowCountMgr = new ReflowCountMgr();
   mReflowCountMgr->SetPresContext(mPresContext);
@@ -1946,17 +1944,17 @@ nsIPresShell::SetAuthorStyleDisabled(PRB
 {
   if (aStyleDisabled != mStyleSet->GetAuthorStyleDisabled()) {
     mStyleSet->SetAuthorStyleDisabled(aStyleDisabled);
     ReconstructStyleData();
   }
 }
 
 PRBool
-nsIPresShell::GetAuthorStyleDisabled()
+nsIPresShell::GetAuthorStyleDisabled() const
 {
   return mStyleSet->GetAuthorStyleDisabled();
 }
 
 nsresult
 PresShell::SetPreferenceStyleRules(PRBool aForceReflow)
 {
   if (!mDocument) {
@@ -2724,24 +2722,23 @@ PresShell::FireResizeEvent()
   if (window) {
     nsCOMPtr<nsIPresShell> kungFuDeathGrip(this);
     mInResize = PR_TRUE;
     nsEventDispatcher::Dispatch(window, mPresContext, &event, nsnull, &status);
     mInResize = PR_FALSE;
   }
 }
 
-NS_IMETHODIMP
+void
 PresShell::SetIgnoreFrameDestruction(PRBool aIgnore)
 {
   mIgnoreFrameDestruction = aIgnore;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
+}
+
+void
 PresShell::NotifyDestroyingFrame(nsIFrame* aFrame)
 {
   if (!mIgnoreFrameDestruction) {
     mPresContext->StopImagesFor(aFrame);
 
     mFrameConstructor->NotifyDestroyingFrame(aFrame);
 
     for (PRInt32 idx = mDirtyRoots.Length(); idx; ) {
@@ -2756,50 +2753,45 @@ PresShell::NotifyDestroyingFrame(nsIFram
 
     // Remove frame properties
     mPresContext->PropertyTable()->DeleteAllFor(aFrame);
 
     if (aFrame == mCurrentEventFrame) {
       mCurrentEventContent = aFrame->GetContent();
       mCurrentEventFrame = nsnull;
     }
-  
+
   #ifdef NS_DEBUG
     if (aFrame == mDrawEventTargetFrame) {
       mDrawEventTargetFrame = nsnull;
     }
   #endif
-  
+
     for (unsigned int i=0; i < mCurrentEventFrameStack.Length(); i++) {
       if (aFrame == mCurrentEventFrameStack.ElementAt(i)) {
         //One of our stack frames was deleted.  Get its content so that when we
         //pop it we can still get its new frame from its content
         nsIContent *currentEventContent = aFrame->GetContent();
         mCurrentEventContentStack.ReplaceObjectAt(currentEventContent, i);
         mCurrentEventFrameStack[i] = nsnull;
       }
     }
   
     mFramesToDirty.RemoveEntry(aFrame);
   }
-
-  return NS_OK;
-}
-
-// note that this can return a null caret, but NS_OK
-NS_IMETHODIMP PresShell::GetCaret(nsCaret **outCaret)
-{
-  NS_ENSURE_ARG_POINTER(outCaret);
-  
-  *outCaret = mCaret;
-  NS_IF_ADDREF(*outCaret);
-  return NS_OK;
-}
-
-NS_IMETHODIMP_(void) PresShell::MaybeInvalidateCaretPosition()
+}
+
+already_AddRefed<nsCaret> PresShell::GetCaret() const
+{
+  nsCaret* caret = mCaret;
+  NS_IF_ADDREF(caret);
+  return caret;
+}
+
+void PresShell::MaybeInvalidateCaretPosition()
 {
   if (mCaret) {
     mCaret->InvalidateOutsideCaret();
   }
 }
 
 void PresShell::SetCaret(nsCaret *aNewCaret)
 {
@@ -2870,21 +2862,16 @@ NS_IMETHODIMP PresShell::SetSelectionFla
 NS_IMETHODIMP PresShell::GetSelectionFlags(PRInt16 *aOutEnable)
 {
   if (!aOutEnable)
     return NS_ERROR_INVALID_ARG;
   *aOutEnable = mSelectionFlags;
   return NS_OK;
 }
 
-PRInt16 PresShell::GetSelectionFlags()
-{
-  return mSelectionFlags;
-}
-
 //implementation of nsISelectionController
 
 NS_IMETHODIMP 
 PresShell::CharacterMove(PRBool aForward, PRBool aExtend)
 {
   return mSelection->CharacterMove(aForward, aExtend);  
 }
 
@@ -3081,17 +3068,17 @@ PresShell::StyleChangeReflow()
   // reflow; it's safe to just ignore the request in that case
   if (!rootFrame)
     return;
 
   FrameNeedsReflow(rootFrame, eStyleChange, NS_FRAME_IS_DIRTY);
 }
 
 nsIFrame*
-nsIPresShell::GetRootFrame() const
+nsIPresShell::GetRootFrameExternal() const
 {
   return FrameManager()->GetRootFrame();
 }
 
 nsIFrame*
 nsIPresShell::GetRootScrollFrame() const
 {
   nsIFrame* rootFrame = FrameManager()->GetRootFrame();
@@ -3464,17 +3451,17 @@ void nsIPresShell::InvalidateAccessibleS
     if (accService) {
       accService->InvalidateSubtreeFor(this, aContent,
                                        nsIAccessibilityService::FRAME_SIGNIFICANT_CHANGE);
     }
   }
 }
 #endif
 
-NS_IMETHODIMP
+nsresult
 PresShell::RecreateFramesFor(nsIContent* aContent)
 {
   NS_ENSURE_TRUE(mPresContext, NS_ERROR_FAILURE);
   if (!mDidInitialReflow) {
     // Nothing to do here.  In fact, if we proceed and aContent is the
     // root we will crash.
     return NS_OK;
   }
@@ -3515,35 +3502,33 @@ nsIPresShell::PostRecreateFramesFor(nsIC
 
 void
 nsIPresShell::RestyleForAnimation(nsIContent* aContent)
 {
   FrameConstructor()->PostAnimationRestyleEvent(aContent, eReStyle_Self,
                                                 NS_STYLE_HINT_NONE);
 }
 
-NS_IMETHODIMP
+void
 PresShell::ClearFrameRefs(nsIFrame* aFrame)
 {
   mPresContext->EventStateManager()->ClearFrameRefs(aFrame);
 
   nsWeakFrame* weakFrame = mWeakFrames;
   while (weakFrame) {
     nsWeakFrame* prev = weakFrame->GetPreviousWeakFrame();
     if (weakFrame->GetFrame() == aFrame) {
       // This removes weakFrame from mWeakFrames.
       weakFrame->Clear(this);
     }
     weakFrame = prev;
   }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
+}
+
+nsresult
 PresShell::CreateRenderingContext(nsIFrame *aFrame,
                                   nsIRenderingContext** aResult)
 {
   NS_PRECONDITION(nsnull != aResult, "null ptr");
   if (nsnull == aResult) {
     return NS_ERROR_NULL_POINTER;
   }
 
@@ -3579,17 +3564,17 @@ PresShell::CreateRenderingContext(nsIFra
 
   if (NS_SUCCEEDED(rv)) {
     result->Translate(offset.x, offset.y);
   }
 
   return rv;
 }
 
-NS_IMETHODIMP
+nsresult
 PresShell::GoToAnchor(const nsAString& aAnchorName, PRBool aScroll)
 {
   if (!mDocument) {
     return NS_ERROR_FAILURE;
   }
   
   // Hold a reference to the ESM in case event dispatch tears us down.
   nsCOMPtr<nsIEventStateManager> esm = mPresContext->EventStateManager();
@@ -3839,17 +3824,17 @@ PresShell::GoToAnchor(const nsAString& a
     if (accService)
       accService->NotifyOfAnchorJumpTo(anchorTarget);
   }
 #endif
 
   return rv;
 }
 
-NS_IMETHODIMP
+nsresult
 PresShell::ScrollToAnchor()
 {
   if (!mLastAnchorScrolledTo)
     return NS_OK;
 
   nsIScrollableFrame* rootScroll = GetRootScrollFrameAsScrollable();
   if (!rootScroll ||
       mLastAnchorScrollPositionY != rootScroll->GetScrollPosition().y)
@@ -4031,17 +4016,17 @@ static void ScrollToShowRect(nsIScrollab
       scrollPt.x =
         NSToCoordRound(frameAlignX - visibleRect.width * (aHPercent / 100.0f));
     }
   }
 
   aScrollFrame->ScrollTo(scrollPt, nsIScrollableFrame::INSTANT);
 }
 
-NS_IMETHODIMP
+nsresult
 PresShell::ScrollContentIntoView(nsIContent* aContent,
                                  PRIntn      aVPercent,
                                  PRIntn      aHPercent)
 {
   nsCOMPtr<nsIContent> content = aContent; // Keep content alive while flushing.
   NS_ENSURE_TRUE(content, NS_ERROR_NULL_POINTER);
   nsCOMPtr<nsIDocument> currentDoc = content->GetCurrentDoc();
   NS_ENSURE_STATE(currentDoc);
@@ -4165,18 +4150,18 @@ PresShell::ScrollFrameRectIntoView(nsIFr
     container = container->GetParent();
   } while (container);
 
   return didScroll;
 }
 
 nsRectVisibility
 PresShell::GetRectVisibility(nsIFrame* aFrame,
-                             const nsRect &aRect, 
-                             nscoord aMinTwips)
+                             const nsRect &aRect,
+                             nscoord aMinTwips) const
 {
   nsIFrame* rootFrame = FrameManager()->GetRootFrame();
   NS_ASSERTION(rootFrame,
                "How can someone have a frame for this presshell when there's no root?");
   nsIScrollableFrame* sf = GetRootScrollFrameAsScrollable();
   nsRect scrollPortRect;
   if (sf) {
     scrollPortRect = sf->GetScrollPortRect();
@@ -4202,17 +4187,17 @@ PresShell::GetRectVisibility(nsIFrame* a
     return nsRectVisibility_kLeftOfViewport;
   if (r.x >= insetRect.XMost())
     return nsRectVisibility_kRightOfViewport;
 
   return nsRectVisibility_kVisible;
 }
 
 // GetLinkLocation: copy link location to clipboard
-NS_IMETHODIMP PresShell::GetLinkLocation(nsIDOMNode* aNode, nsAString& aLocationString)
+nsresult PresShell::GetLinkLocation(nsIDOMNode* aNode, nsAString& aLocationString) const
 {
 #ifdef DEBUG_dr
   printf("dr :: PresShell::GetLinkLocation\n");
 #endif
 
   NS_ENSURE_ARG_POINTER(aNode);
   nsresult rv;
   nsAutoString anchorText;
@@ -4338,17 +4323,17 @@ PresShell::ClearMouseCapture(nsIView* aV
   }
 
   // disable mouse capture until the next mousedown as a dialog has opened
   // or a drag has started. Otherwise, someone could start capture during
   // the modal dialog or drag.
   gCaptureInfo.mAllowed = PR_FALSE;
 }
 
-NS_IMETHODIMP
+nsresult
 PresShell::CaptureHistoryState(nsILayoutHistoryState** aState, PRBool aLeavingPage)
 {
   nsresult rv = NS_OK;
 
   NS_PRECONDITION(nsnull != aState, "null state pointer");
 
   // We actually have to mess with the docshell here, since we want to
   // store the state back in it.
@@ -4396,23 +4381,16 @@ PresShell::CaptureHistoryState(nsILayout
     }
   }
 
   FrameManager()->CaptureFrameState(rootFrame, historyState);  
  
   return NS_OK;
 }
 
-NS_IMETHODIMP
-PresShell::IsPaintingSuppressed(PRBool* aResult)
-{
-  *aResult = mPaintingSuppressed;
-  return NS_OK;
-}
-
 void
 PresShell::UnsuppressAndInvalidate()
 {
   if (!mPresContext->EnsureVisible() || mHaveShutDown) {
     // No point; we're about to be torn down anyway.
     return;
   }
   
@@ -4437,54 +4415,52 @@ PresShell::UnsuppressAndInvalidate()
   nsPIDOMWindow *win = mDocument->GetWindow();
   if (win)
     win->SetReadyForFocus();
 
   if (!mHaveShutDown && mViewManager)
     mViewManager->SynthesizeMouseMove(PR_FALSE);
 }
 
-NS_IMETHODIMP
+void
 PresShell::UnsuppressPainting()
 {
   if (mPaintSuppressionTimer) {
     mPaintSuppressionTimer->Cancel();
     mPaintSuppressionTimer = nsnull;
   }
 
   if (mIsDocumentGone || !mPaintingSuppressed)
-    return NS_OK;
+    return;
 
   // If we have reflows pending, just wait until we process
   // the reflows and get all the frames where we want them
   // before actually unlocking the painting.  Otherwise
   // go ahead and unlock now.
   if (mDirtyRoots.Length() > 0)
     mShouldUnsuppressPainting = PR_TRUE;
   else
     UnsuppressAndInvalidate();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
+}
+
+void
 PresShell::DisableThemeSupport()
 {
   // Doesn't have to be dynamic.  Just set the bool.
   mIsThemeSupportDisabled = PR_TRUE;
-  return NS_OK;
 }
 
 PRBool 
 PresShell::IsThemeSupportEnabled()
 {
   return !mIsThemeSupportDisabled;
 }
 
 // Post a request to handle an arbitrary callback after reflow has finished.
-NS_IMETHODIMP
+nsresult
 PresShell::PostReflowCallback(nsIReflowCallback* aCallback)
 {
   void* result = AllocateMisc(sizeof(nsCallbackEventRequest));
   if (NS_UNLIKELY(!result)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
   nsCallbackEventRequest* request = (nsCallbackEventRequest*)result;
 
@@ -4496,17 +4472,17 @@ PresShell::PostReflowCallback(nsIReflowC
   } else {
     mFirstCallbackEventRequest = request;
     mLastCallbackEventRequest = request;
   }
  
   return NS_OK;
 }
 
-NS_IMETHODIMP
+void
 PresShell::CancelReflowCallback(nsIReflowCallback* aCallback)
 {
    nsCallbackEventRequest* before = nsnull;
    nsCallbackEventRequest* node = mFirstCallbackEventRequest;
    while(node)
    {
       nsIReflowCallback* callback = node->callback;
 
@@ -4527,18 +4503,16 @@ PresShell::CancelReflowCallback(nsIReflo
         }
 
         FreeMisc(sizeof(nsCallbackEventRequest), toFree);
       } else {
         before = node;
         node = node->next;
       }
    }
-
-   return NS_OK;
 }
 
 void
 PresShell::CancelPostedReflowCallbacks()
 {
   while (mFirstCallbackEventRequest) {
     nsCallbackEventRequest* node = mFirstCallbackEventRequest;
     mFirstCallbackEventRequest = node->next;
@@ -4575,17 +4549,17 @@ PresShell::HandlePostedReflowCallbacks(P
 
    mozFlushType flushType =
      aInterruptible ? Flush_InterruptibleLayout : Flush_Layout;
    if (shouldFlush)
      FlushPendingNotifications(flushType);
 }
 
 PRBool
-PresShell::IsSafeToFlush()
+PresShell::IsSafeToFlush() const
 {
   // Not safe if we are reflowing or in the middle of frame construction
   PRBool isSafeToFlush = !mIsReflowing &&
                          !mChangeNestCount;
 
   if (isSafeToFlush) {
     // Not safe if we are painting
     nsIViewManager* viewManager = GetViewManager();
@@ -4703,23 +4677,16 @@ PresShell::FlushPendingNotifications(moz
       // from possibly flushing out reflows due to invalidates being processed
       // at the end of this view batch.
       updateFlags = NS_VMREFRESH_DEFERRED;
     }
     batch.EndUpdateViewBatch(updateFlags);
   }
 }
 
-NS_IMETHODIMP
-PresShell::IsReflowLocked(PRBool* aIsReflowLocked) 
-{
-  *aIsReflowLocked = mIsReflowing;
-  return NS_OK;
-}
-
 void
 PresShell::CharacterDataChanged(nsIDocument *aDocument,
                                 nsIContent*  aContent,
                                 CharacterDataChangeInfo* aInfo)
 {
   NS_PRECONDITION(!mIsDocumentGone, "Unexpected CharacterDataChanged");
   NS_PRECONDITION(aDocument == mDocument, "Unexpected aDocument");
 
@@ -5115,17 +5082,17 @@ PrepareContext(const nsRect& aRect, nsco
     aThebesContext->SetOperator(gfxContext::OPERATOR_SOURCE);
     aThebesContext->Paint();
   }
 
   aThebesContext->SetOperator(gfxContext::OPERATOR_OVER);
   return needsGroup;
 }
 
-NS_IMETHODIMP
+nsresult
 PresShell::RenderDocument(const nsRect& aRect, PRUint32 aFlags,
                           nscolor aBackgroundColor,
                           gfxContext* aThebesContext)
 {
   NS_ENSURE_TRUE(!(aFlags & RENDER_IS_UNTRUSTED), NS_ERROR_NOT_IMPLEMENTED);
 
   // we want the window to be composited as a single image using
   // whatever operator was set; set OPERATOR_OVER here, which is
@@ -5760,38 +5727,39 @@ PresShell::GetCurrentEventFrame()
     if (mCurrentEventContent->GetDocument()) {
       mCurrentEventFrame = mCurrentEventContent->GetPrimaryFrame();
     }
   }
 
   return mCurrentEventFrame;
 }
 
-NS_IMETHODIMP
-PresShell::GetEventTargetFrame(nsIFrame** aFrame)
-{
-  *aFrame = GetCurrentEventFrame();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-PresShell::GetEventTargetContent(nsEvent* aEvent, nsIContent** aContent)
-{
+nsIFrame*
+PresShell::GetEventTargetFrame()
+{
+  return GetCurrentEventFrame();
+}
+
+already_AddRefed<nsIContent>
+PresShell::GetEventTargetContent(nsEvent* aEvent)
+{
+  nsIContent* content = nsnull;
+
   if (mCurrentEventContent) {
-    *aContent = mCurrentEventContent;
-    NS_IF_ADDREF(*aContent);
+    content = mCurrentEventContent;
+    NS_IF_ADDREF(content);
   } else {
     nsIFrame* currentEventFrame = GetCurrentEventFrame();
     if (currentEventFrame) {
-      currentEventFrame->GetContentForEvent(mPresContext, aEvent, aContent);
+      currentEventFrame->GetContentForEvent(mPresContext, aEvent, &content);
     } else {
-      *aContent = nsnull;
-    }
-  }
-  return NS_OK;
+      content = nsnull;
+    }
+  }
+  return content;
 }
 
 void
 PresShell::PushCurrentEventInfo(nsIFrame* aFrame, nsIContent* aContent)
 {
   if (mCurrentEventFrame || mCurrentEventContent) {
     mCurrentEventFrameStack.InsertElementAt(0, mCurrentEventFrame);
     mCurrentEventContentStack.InsertObjectAt(mCurrentEventContent, 0);
@@ -5868,21 +5836,20 @@ nsresult PresShell::RetargetEventToParen
   parentPresShell->GetViewManager()->GetRootView(parentRootView);
   
   sDontRetargetEvents = PR_TRUE;
   nsresult rv = parentViewObserver->HandleEvent(parentRootView, aEvent, aEventStatus);
   sDontRetargetEvents = PR_FALSE;
   return rv;
 }
 
-NS_IMETHODIMP
+void
 PresShell::DisableNonTestMouseEvents(PRBool aDisable)
 {
   sDisableNonTestMouseEvents = aDisable;
-  return NS_OK;
 }
 
 already_AddRefed<nsPIDOMWindow>
 PresShell::GetFocusedDOMWindowInOurWindow()
 {
   nsCOMPtr<nsPIDOMWindow> window =
     do_QueryInterface(mDocument->GetWindow());
   NS_ENSURE_TRUE(window, nsnull);
@@ -6313,26 +6280,24 @@ PresShell::HandlePositionedEvent(nsIView
 
 #ifdef NS_DEBUG
   ShowEventTargetDebug();
 #endif
   PopCurrentEventInfo();
   return rv;
 }
 
-NS_IMETHODIMP
+nsresult
 PresShell::HandleEventWithTarget(nsEvent* aEvent, nsIFrame* aFrame,
                                  nsIContent* aContent, nsEventStatus* aStatus)
 {
-  nsresult ret;
-
   PushCurrentEventInfo(aFrame, aContent);
-  ret = HandleEventInternal(aEvent, nsnull, aStatus);
+  nsresult rv = HandleEventInternal(aEvent, nsnull, aStatus);
   PopCurrentEventInfo();
-  return NS_OK;
+  return rv;
 }
 
 static inline PRBool
 IsSynthesizedMouseEvent(nsEvent* aEvent)
 {
   return aEvent->eventStructType == NS_MOUSE_EVENT &&
          static_cast<nsMouseEvent*>(aEvent)->reason != nsMouseEvent::eReal;
 }
@@ -6494,54 +6459,58 @@ PresShell::HandleEventInternal(nsEvent* 
       SetCapturingContent(nsnull, 0);
     }
   }
   return rv;
 }
 
 // Dispatch event to content only (NOT full processing)
 // See also HandleEventWithTarget which does full event processing.
-NS_IMETHODIMP
+nsresult
 PresShell::HandleDOMEventWithTarget(nsIContent* aTargetContent, nsEvent* aEvent,
                                     nsEventStatus* aStatus)
 {
+  nsresult rv = NS_OK;
+
   PushCurrentEventInfo(nsnull, aTargetContent);
 
   // Bug 41013: Check if the event should be dispatched to content.
   // It's possible that we are in the middle of destroying the window
   // and the js context is out of date. This check detects the case
   // that caused a crash in bug 41013, but there may be a better way
   // to handle this situation!
   nsCOMPtr<nsISupports> container = mPresContext->GetContainer();
   if (container) {
 
     // Dispatch event to content
-    nsEventDispatcher::Dispatch(aTargetContent, mPresContext, aEvent, nsnull,
-                                aStatus);
+    rv = nsEventDispatcher::Dispatch(aTargetContent, mPresContext, aEvent, nsnull,
+                                     aStatus);
   }
 
   PopCurrentEventInfo();
-  return NS_OK;
+  return rv;
 }
 
 // See the method above.
-NS_IMETHODIMP
+nsresult
 PresShell::HandleDOMEventWithTarget(nsIContent* aTargetContent,
                                     nsIDOMEvent* aEvent,
                                     nsEventStatus* aStatus)
 {
+  nsresult rv = NS_OK;
+
   PushCurrentEventInfo(nsnull, aTargetContent);
   nsCOMPtr<nsISupports> container = mPresContext->GetContainer();
   if (container) {
-    nsEventDispatcher::DispatchDOMEvent(aTargetContent, nsnull, aEvent,
-                                        mPresContext, aStatus);
+    rv = nsEventDispatcher::DispatchDOMEvent(aTargetContent, nsnull, aEvent,
+                                             mPresContext, aStatus);
   }
 
   PopCurrentEventInfo();
-  return NS_OK;
+  return rv;
 }
 
 PRBool
 PresShell::AdjustContextMenuKeyEvent(nsMouseEvent* aEvent)
 {
 #ifdef MOZ_XUL
   // if a menu is open, open the context menu relative to the active item on the menu. 
   nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
@@ -6630,19 +6599,17 @@ PresShell::AdjustContextMenuKeyEvent(nsM
 //    relative to.  The returned point is in device pixels realtive to the
 //    widget passed in.
 PRBool
 PresShell::PrepareToUseCaretPosition(nsIWidget* aEventWidget, nsIntPoint& aTargetPt)
 {
   nsresult rv;
 
   // check caret visibility
-  nsRefPtr<nsCaret> caret;
-  rv = GetCaret(getter_AddRefs(caret));
-  NS_ENSURE_SUCCESS(rv, PR_FALSE);
+  nsRefPtr<nsCaret> caret = GetCaret();
   NS_ENSURE_TRUE(caret, PR_FALSE);
 
   PRBool caretVisible = PR_FALSE;
   rv = caret->GetCaretVisible(&caretVisible);
   if (NS_FAILED(rv) || ! caretVisible)
     return PR_FALSE;
 
   // caret selection, this is a temporary weak reference, so no refcounting is 
@@ -7857,18 +7824,17 @@ DumpToPNG(nsIPresShell* shell, nsAString
     gfxPlatform::GetPlatform()->
     CreateOffscreenSurface(gfxIntSize(width, height),
       gfxASurface::ImageFormatARGB32);
   NS_ENSURE_TRUE(surface, NS_ERROR_OUT_OF_MEMORY);
 
   nsRefPtr<gfxContext> context = new gfxContext(surface);
   NS_ENSURE_TRUE(context, NS_ERROR_OUT_OF_MEMORY);
 
-  nsresult rv = shell->RenderDocument(r, 0, NS_RGB(255, 255, 0), context);
-  NS_ENSURE_SUCCESS(rv, rv);
+  shell->RenderDocument(r, 0, NS_RGB(255, 255, 0), context);
 
   imgContext->DrawSurface(surface, gfxSize(width, height));
 
   nsCOMPtr<imgIEncoder> encoder = do_CreateInstance("@mozilla.org/image/encoder;2?type=image/png");
   NS_ENSURE_TRUE(encoder, NS_ERROR_FAILURE);
   encoder->InitFromData(imgSurface->Data(), imgSurface->Stride() * height,
                         width, height, imgSurface->Stride(),
                         imgIEncoder::INPUT_FORMAT_HOSTARGB, EmptyString());
@@ -8042,68 +8008,67 @@ PresShell::VerifyStyleTree()
 
 //=============================================================
 //=============================================================
 //-- Debug Reflow Counts
 //=============================================================
 //=============================================================
 #ifdef MOZ_REFLOW_PERF
 //-------------------------------------------------------------
-NS_IMETHODIMP
+void
 PresShell::DumpReflows()
 {
   if (mReflowCountMgr) {
     nsCAutoString uriStr;
     if (mDocument) {
       nsIURI *uri = mDocument->GetDocumentURI();
       if (uri) {
         uri->GetPath(uriStr);
       }
     }
     mReflowCountMgr->DisplayTotals(uriStr.get());
     mReflowCountMgr->DisplayHTMLTotals(uriStr.get());
     mReflowCountMgr->DisplayDiffsInTotals("Differences");
   }
-  return NS_OK;
 }
 
 //-------------------------------------------------------------
-NS_IMETHODIMP
+void
 PresShell::CountReflows(const char * aName, nsIFrame * aFrame)
 {
   if (mReflowCountMgr) {
     mReflowCountMgr->Add(aName, aFrame);
   }
-
-  return NS_OK;
 }
 
 //-------------------------------------------------------------
-NS_IMETHODIMP
-PresShell::PaintCount(const char * aName, nsIRenderingContext* aRenderingContext, nsPresContext* aPresContext, nsIFrame * aFrame, PRUint32 aColor)
+void
+PresShell::PaintCount(const char * aName,
+                      nsIRenderingContext* aRenderingContext,
+                      nsPresContext* aPresContext,
+                      nsIFrame * aFrame,
+                      PRUint32 aColor)
 {
   if (mReflowCountMgr) {
     mReflowCountMgr->PaintCount(aName, aRenderingContext, aPresContext, aFrame, aColor);
   }
-  return NS_OK;
 }
 
 //-------------------------------------------------------------
-NS_IMETHODIMP
+void
 PresShell::SetPaintFrameCount(PRBool aPaintFrameCounts)
-{ 
+{
   if (mReflowCountMgr) {
     mReflowCountMgr->SetPaintFrameCounts(aPaintFrameCounts);
   }
-  return NS_OK; 
 }
 
 PRBool
 PresShell::IsPaintingFrameCounts()
-{ 
+{
   if (mReflowCountMgr)
     return mReflowCountMgr->IsPaintingFrameCounts();
   return PR_FALSE;
 }
 
 //------------------------------------------------------------------
 //-- Reflow Counter Classes Impls
 //------------------------------------------------------------------
--- a/layout/forms/nsTextControlFrame.cpp
+++ b/layout/forms/nsTextControlFrame.cpp
@@ -684,19 +684,18 @@ nsTextInputSelectionImpl::SetCaretEnable
 NS_IMETHODIMP
 nsTextInputSelectionImpl::SetCaretReadOnly(PRBool aReadOnly)
 {
   if (!mPresShellWeak) return NS_ERROR_NOT_INITIALIZED;
   nsresult result;
   nsCOMPtr<nsIPresShell> shell = do_QueryReferent(mPresShellWeak, &result);
   if (shell)
   {
-    nsRefPtr<nsCaret> caret;
-    if (NS_SUCCEEDED(shell->GetCaret(getter_AddRefs(caret))))
-    {
+    nsRefPtr<nsCaret> caret = shell->GetCaret();
+    if (caret) {
       nsISelection* domSel = mFrameSelection->
         GetSelection(nsISelectionController::SELECTION_NORMAL);
       if (domSel)
         caret->SetCaretReadOnly(aReadOnly);
       return NS_OK;
     }
   }
   return NS_ERROR_FAILURE;
@@ -711,19 +710,18 @@ nsTextInputSelectionImpl::GetCaretEnable
 NS_IMETHODIMP
 nsTextInputSelectionImpl::GetCaretVisible(PRBool *_retval)
 {
   if (!mPresShellWeak) return NS_ERROR_NOT_INITIALIZED;
   nsresult result;
   nsCOMPtr<nsIPresShell> shell = do_QueryReferent(mPresShellWeak, &result);
   if (shell)
   {
-    nsRefPtr<nsCaret> caret;
-    if (NS_SUCCEEDED(shell->GetCaret(getter_AddRefs(caret))))
-    {
+    nsRefPtr<nsCaret> caret = shell->GetCaret();
+    if (caret) {
       nsISelection* domSel = mFrameSelection->
         GetSelection(nsISelectionController::SELECTION_NORMAL);
       if (domSel)
         return caret->GetCaretVisible(_retval);
     }
   }
   return NS_ERROR_FAILURE;
 }
@@ -731,19 +729,18 @@ nsTextInputSelectionImpl::GetCaretVisibl
 NS_IMETHODIMP
 nsTextInputSelectionImpl::SetCaretVisibilityDuringSelection(PRBool aVisibility)
 {
   if (!mPresShellWeak) return NS_ERROR_NOT_INITIALIZED;
   nsresult result;
   nsCOMPtr<nsIPresShell> shell = do_QueryReferent(mPresShellWeak, &result);
   if (shell)
   {
-    nsRefPtr<nsCaret> caret;
-    if (NS_SUCCEEDED(shell->GetCaret(getter_AddRefs(caret))))
-    {
+    nsRefPtr<nsCaret> caret = shell->GetCaret();
+    if (caret) {
       nsISelection* domSel = mFrameSelection->
         GetSelection(nsISelectionController::SELECTION_NORMAL);
       if (domSel)
         caret->SetVisibilityDuringSelection(aVisibility);
       return NS_OK;
     }
   }
   return NS_ERROR_FAILURE;
@@ -1644,19 +1641,19 @@ nsTextControlFrame::CreateAnonymousConte
 
   // Get the caret and make it a selection listener.
 
   nsRefPtr<nsISelection> domSelection;
   if (NS_SUCCEEDED(mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                                          getter_AddRefs(domSelection))) &&
       domSelection) {
     nsCOMPtr<nsISelectionPrivate> selPriv(do_QueryInterface(domSelection));
-    nsRefPtr<nsCaret> caret;
+    nsRefPtr<nsCaret> caret = shell->GetCaret();
     nsCOMPtr<nsISelectionListener> listener;
-    if (NS_SUCCEEDED(shell->GetCaret(getter_AddRefs(caret))) && caret) {
+    if (caret) {
       listener = do_QueryInterface(caret);
       if (listener) {
         selPriv->AddSelectionListener(listener);
       }
     }
 
     selPriv->AddSelectionListener(static_cast<nsISelectionListener*>
                                              (mTextListener));
@@ -1878,18 +1875,17 @@ void nsTextControlFrame::SetFocus(PRBool
   // tell the caret to use our selection
 
   nsCOMPtr<nsISelection> ourSel;
   mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL, 
     getter_AddRefs(ourSel));
   if (!ourSel) return;
 
   nsIPresShell* presShell = PresContext()->GetPresShell();
-  nsRefPtr<nsCaret> caret;
-  presShell->GetCaret(getter_AddRefs(caret));
+  nsRefPtr<nsCaret> caret = presShell->GetCaret();
   if (!caret) return;
   caret->SetCaretDOMSelection(ourSel);
 
   // mutual-exclusion: the selection is either controlled by the
   // document or by the text input/area. Clear any selection in the
   // document since the focus is now on our independent selection.
 
   nsCOMPtr<nsISelectionController> selCon(do_QueryInterface(presShell));
--- a/layout/generic/nsFrame.cpp
+++ b/layout/generic/nsFrame.cpp
@@ -3671,22 +3671,20 @@ nsIFrame::InvalidateWithFlags(const nsRe
   if (aDamageRect.IsEmpty()) {
     return;
   }
 
   // Don't allow invalidates to do anything when
   // painting is suppressed.
   nsIPresShell *shell = PresContext()->GetPresShell();
   if (shell) {
-    PRBool suppressed = PR_FALSE;
-    shell->IsPaintingSuppressed(&suppressed);
-    if (suppressed)
+    if (shell->IsPaintingSuppressed())
       return;
   }
-  
+
   InvalidateInternal(aDamageRect, 0, 0, nsnull, aFlags);
 }
 
 /**
  * Helper function that funnels an InvalidateInternal request up to the
  * parent.  This function is used so that if MOZ_SVG is not defined, we still
  * have unified control paths in the InvalidateInternal chain.
  *
--- a/layout/generic/nsIFrame.h
+++ b/layout/generic/nsIFrame.h
@@ -972,29 +972,29 @@ public:
    * painted on top of the rest of the display list items.
    *
    * @param aDirtyRect is the dirty rectangle that we're repainting.
    */
   nsresult DisplayCaret(nsDisplayListBuilder*       aBuilder,
                         const nsRect&               aDirtyRect,
                         nsDisplayList*              aList);
 
-  PRBool IsThemed(nsITheme::Transparency* aTransparencyState = nsnull) {
-    return IsThemed(GetStyleDisplay(), aTransparencyState);
+  PRBool IsThemed(nsTransparencyMode* aTransparencyMode = nsnull) {
+    return IsThemed(GetStyleDisplay(), aTransparencyMode);
   }
   PRBool IsThemed(const nsStyleDisplay* aDisp,
-                  nsITheme::Transparency* aTransparencyState = nsnull) {
+                  nsTransparencyMode* aTransparencyMode = nsnull) {
     if (!aDisp->mAppearance)
       return PR_FALSE;
     nsPresContext* pc = PresContext();
     nsITheme *theme = pc->GetTheme();
     if(!theme || !theme->ThemeSupportsWidget(pc, this, aDisp->mAppearance))
       return PR_FALSE;
-    if (aTransparencyState) {
-      *aTransparencyState = theme->GetWidgetTransparency(this, aDisp->mAppearance);
+    if (aTransparencyMode) {
+      *aTransparencyMode = theme->GetWidgetTransparency(aDisp->mAppearance);
     }
     return PR_TRUE;
   }
   
   /**
    * Builds a display list for the content represented by this frame,
    * treating this frame as the root of a stacking context.
    * @param aDirtyRect content outside this rectangle can be ignored; the
--- a/layout/generic/nsObjectFrame.cpp
+++ b/layout/generic/nsObjectFrame.cpp
@@ -3744,17 +3744,17 @@ void nsPluginInstanceOwner::ScrollPositi
         mInstance->HandleEvent(&scrollEvent, &eventHandled);
       }
       pluginWidget->EndDrawPlugin();
     }
   }
 #endif
 }
 
-/*=============== nsIFocusListener ======================*/
+/*=============== nsIDOMFocusListener ======================*/
 nsresult nsPluginInstanceOwner::Focus(nsIDOMEvent * aFocusEvent)
 {
   mContentFocused = PR_TRUE;
   return DispatchFocusToPlugin(aFocusEvent);
 }
 
 nsresult nsPluginInstanceOwner::Blur(nsIDOMEvent * aFocusEvent)
 {
--- a/layout/generic/nsSelection.cpp
+++ b/layout/generic/nsSelection.cpp
@@ -783,25 +783,22 @@ nsFrameSelection::FetchDesiredX(nscoord 
     return NS_ERROR_FAILURE;
   }
   if (mDesiredXSet)
   {
     aDesiredX = mDesiredX;
     return NS_OK;
   }
 
-  nsRefPtr<nsCaret> caret;
-  nsresult result = mShell->GetCaret(getter_AddRefs(caret));
-  if (NS_FAILED(result))
-    return result;
+  nsRefPtr<nsCaret> caret = mShell->GetCaret();
   if (!caret)
     return NS_ERROR_NULL_POINTER;
 
   PRInt8 index = GetIndexFromSelectionType(nsISelectionController::SELECTION_NORMAL);
-  result = caret->SetCaretDOMSelection(mDomSelections[index]);
+  nsresult result = caret->SetCaretDOMSelection(mDomSelections[index]);
   if (NS_FAILED(result))
     return result;
 
   nsRect coord;
   nsIFrame* caretFrame = caret->GetGeometry(mDomSelections[index], &coord);
   if (!caretFrame)
     return NS_ERROR_FAILURE;
   nsPoint viewOffset(0, 0);
@@ -2081,34 +2078,30 @@ nsFrameSelection::GetFrameForNodeOffset(
 void
 nsFrameSelection::CommonPageMove(PRBool aForward,
                                  PRBool aExtend,
                                  nsIScrollableFrame* aScrollableFrame)
 {
   // expected behavior for PageMove is to scroll AND move the caret
   // and remain relative position of the caret in view. see Bug 4302.
 
-  nsresult result;
   //get the frame from the scrollable view
 
   nsIFrame* scrolledFrame = aScrollableFrame->GetScrolledFrame();
   if (!scrolledFrame)
     return;
 
   // find out where the caret is.
   // we should know mDesiredX value of nsFrameSelection, but I havent seen that behavior in other windows applications yet.
   nsISelection* domSel = GetSelection(nsISelectionController::SELECTION_NORMAL);
   if (!domSel) 
     return;
-  
-  nsRefPtr<nsCaret> caret;
-  result = mShell->GetCaret(getter_AddRefs(caret));
-  if (NS_FAILED(result)) 
-    return;
-  
+
+  nsRefPtr<nsCaret> caret = mShell->GetCaret();
+
   nsRect caretPos;
   nsIFrame* caretFrame = caret->GetGeometry(domSel, &caretPos);
   if (!caretFrame) 
     return;
   
   //need to adjust caret jump by percentage scroll
   nsSize scrollDelta = aScrollableFrame->GetPageScrollAmount();
 
@@ -4190,19 +4183,18 @@ nsTypedSelection::GetPrimaryFrameForFocu
   PRInt32 frameOffset = 0;
   *aReturnFrame = 0;
   if (!aOffsetUsed)
     aOffsetUsed = &frameOffset;
     
   nsFrameSelection::HINT hint = mFrameSelection->GetHint();
 
   if (aVisual) {
-    nsRefPtr<nsCaret> caret;
-    nsresult result = presShell->GetCaret(getter_AddRefs(caret));
-    if (NS_FAILED(result) || !caret)
+    nsRefPtr<nsCaret> caret = presShell->GetCaret();
+    if (!caret)
       return NS_ERROR_FAILURE;
     
     PRUint8 caretBidiLevel = mFrameSelection->GetCaretBidiLevel();
 
     return caret->GetCaretFrameForNodeOffset(content, GetFocusOffset(),
       hint, caretBidiLevel, aReturnFrame, aOffsetUsed);
   }
   
@@ -5553,18 +5545,17 @@ nsTypedSelection::ScrollIntoView(Selecti
   //
   // Shut the caret off before scrolling to avoid
   // leaving caret turds on the screen!
   //
   nsCOMPtr<nsIPresShell> presShell;
   result = GetPresShell(getter_AddRefs(presShell));
   if (NS_FAILED(result) || !presShell)
     return result;
-  nsRefPtr<nsCaret> caret;
-  presShell->GetCaret(getter_AddRefs(caret));
+  nsRefPtr<nsCaret> caret = presShell->GetCaret();
   if (caret)
   {
     // Now that text frame character offsets are always valid (though not
     // necessarily correct), the worst that will happen if we don't flush here
     // is that some callers might scroll to the wrong place.  Those should
     // either manually flush if they're in a safe position for it or use the
     // async version of this method.
     if (aDoFlush) {
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-parsing/pseudo-elements-1-ref.html
@@ -0,0 +1,22 @@
+<!doctype html><style>
+  div { color: green; float: left }
+</style><div
+><div>T</div
+><div>h</div
+><div>e</div
+><div>r</div
+><div>e</div
+><div>s</div
+><div>h</div
+><div>o</div
+><div>u</div
+><div>l</div
+><div>d</div
+><div>b</div
+><div>e</div
+><div>n</div
+><div>o</div
+><div>r</div
+><div>e</div
+><div>d</div
+></div>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-parsing/pseudo-elements-1.html
@@ -0,0 +1,36 @@
+<!doctype html><style>
+  div { float: left }
+  /* Pseudo elements can appear only at the end of the selector. */
+  .good { color: red }
+  .bad { color: green }
+  #good1::first-letter { color: green }
+  #good2::first-letter, #good3 { color: green }
+  #good4, #good5::first-letter { color: green }
+  div > #good6::first-letter, #good7 { color:green }
+  div #good7 > ::first-letter, #good8 { color:green }
+
+  #bad1::first-letter *, #bad2 { color: red }
+  #bad4, #bad3::first-letter * { color: red }
+  div::first-line #bad5, #bad6 { color: red }
+  #bad7, div::first-line #bad8 { color: red }
+  #bad9, div ::first-line>#bad10 { color:red }
+</style><div
+><div class="good" id="good1">T</div
+><div class="good" id="good2">h</div
+><div class="good" id="good3">e</div
+><div class="good" id="good4">r</div
+><div class="good" id="good5">e</div
+><div class="good" id="good6">s</div
+><div class="good" id="good7">h</div
+><div class="good" id="good8">o</div
+><div class="bad"  id="bad1" >u</div
+><div class="bad"  id="bad2" >l</div
+><div class="bad"  id="bad3" >d</div
+><div class="bad"  id="bad4" >b</div
+><div class="bad"  id="bad5" >e</div
+><div class="bad"  id="bad6" >n</div
+><div class="bad"  id="bad7" >o</div
+><div class="bad"  id="bad8" >r</div
+><div class="bad"  id="bad9" >e</div
+><div class="bad"  id="bad10">d</div
+></div>
--- a/layout/reftests/css-parsing/reftest.list
+++ b/layout/reftests/css-parsing/reftest.list
@@ -1,1 +1,2 @@
 == invalid-url-handling.xhtml invalid-url-handling-ref.xhtml
+== pseudo-elements-1.html pseudo-elements-1-ref.html
--- a/layout/reftests/first-letter/399941-8-ref.html
+++ b/layout/reftests/first-letter/399941-8-ref.html
@@ -1,17 +1,16 @@
 <!DOCTYPE html>
 <html>
  <head>
   <meta http-equiv="content-type" content="text/html; charset=utf-8">
   <title>Test case for bug 399941.html</title>
   <style type="text/css">
    span.fake-first-letter {
      color: lime;
-     background-color: olive;
    }
   </style>
  </head>
  <body>
  <!-- Test SMP characters -->
   <p><span class="fake-first-letter">&#x10900;</span>&#x10901;&#x10909; is Phoenician</p>
  </body>
 </html>
--- a/layout/reftests/first-letter/399941-8.html
+++ b/layout/reftests/first-letter/399941-8.html
@@ -1,17 +1,16 @@
 <!DOCTYPE html>
 <html>
  <head>
   <meta http-equiv="content-type" content="text/html; charset=utf-8">
   <title>Test case for bug 399941.html</title>
   <style type="text/css">
    p:first-letter {
      color: lime;
-     background-color: olive;
    }
   </style>
  </head>
  <body>
  <!-- Test SMP characters -->
   <p>&#x10900;&#x10901;&#x10909; is Phoenician</p>
  </body>
 </html>
--- a/layout/reftests/first-letter/399941-9-ref.html
+++ b/layout/reftests/first-letter/399941-9-ref.html
@@ -1,17 +1,16 @@
 <!DOCTYPE html>
 <html>
  <head>
   <meta http-equiv="content-type" content="text/html; charset=utf-8">
   <title>Test case for bug 399941.html</title>
   <style type="text/css">
    span.fake-first-letter {
      color: lime;
-     background-color: olive;
    }
   </style>
  </head>
  <body>
  <!-- Test SMP characters and punctuation -->
   <p><span class="fake-first-letter">&#x12470;&#x12000;&#x12470;</span>&#x12041; is cuneiform with punctuation</p>
  </body>
 </html>
--- a/layout/reftests/first-letter/399941-9.html
+++ b/layout/reftests/first-letter/399941-9.html
@@ -1,17 +1,16 @@
 <!DOCTYPE html>
 <html>
  <head>
   <meta http-equiv="content-type" content="text/html; charset=utf-8">
   <title>Test case for bug 399941.html</title>
   <style type="text/css">
    p:first-letter {
      color: lime;
-     background-color: olive;
    }
   </style>
  </head>
  <body>
  <!-- Test SMP characters and punctuation -->
   <p>&#x12470;&#x12000;&#x12470;&#x12041; is cuneiform with punctuation</p>
  </body>
 </html>
--- a/layout/reftests/svg/reftest.list
+++ b/layout/reftests/svg/reftest.list
@@ -139,16 +139,17 @@ random-if(MOZ_WIDGET_TOOLKIT=="gtk2") ==
 == switch-01.svg pass.svg
 == text-gradient-01.svg text-gradient-01-ref.svg
 == text-in-link-01.svg text-in-link-01-ref.svg
 == text-in-link-02.svg text-in-link-02-ref.svg
 # For bug 546813: sanity-check using HTML text, then test SVG behavior. Fails on Linux tryserver due to lack of CJK fonts.
 != text-language-00.xhtml text-language-00-ref.xhtml
 random-if(MOZ_WIDGET_TOOLKIT=="gtk2") != text-language-01.xhtml text-language-01-ref.xhtml
 == text-layout-01.svg text-layout-01-ref.svg
+== text-layout-02.svg text-layout-02-ref.svg
 == text-scale-01.svg text-scale-01-ref.svg
 == text-style-01a.svg text-style-01-ref.svg
 == text-style-01b.svg text-style-01-ref.svg
 == text-style-01c.svg text-style-01-ref.svg
 == text-style-01d.svg text-style-01-ref.svg
 == text-style-01e.svg text-style-01-ref.svg
 == thin-stroke-01.svg pass.svg
 == userSpaceOnUse-and-pattern-01.svg userSpaceOnUse-and-pattern-01-ref.svg
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/text-layout-02-ref.svg
@@ -0,0 +1,21 @@
+<!--
+     Any copyright is dedicated to the Public Domain.
+     http://creativecommons.org/licenses/publicdomain/
+-->
+<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     font-family="monospace" font-size="20" xml:space="preserve">
+
+  <title>Reference to check that a single rotate value works for text</title>
+
+  <!-- From https://bugzilla.mozilla.org/show_bug.cgi?id=521636 -->
+
+  <defs>
+    <path id="h1" d="M 30,150 h 100"/>
+  </defs>
+
+  <text x="20" y="20" rotate="90,90,90,90,90">TEST1</text>
+
+  <text><textPath xlink:href="#h1"><tspan rotate="90,90">TE</tspan>ST4</textPath></text>
+
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/text-layout-02.svg
@@ -0,0 +1,21 @@
+<!--
+     Any copyright is dedicated to the Public Domain.
+     http://creativecommons.org/licenses/publicdomain/
+-->
+<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     font-family="monospace" font-size="20" xml:space="preserve">
+
+  <title>Testcase to check that a single rotate value works for text</title>
+
+  <!-- From https://bugzilla.mozilla.org/show_bug.cgi?id=521636 -->
+
+  <defs>
+    <path id="h1" d="M 30,150 h 100"/>
+  </defs>
+
+  <text x="20" y="20" rotate="90">TEST1</text>
+
+  <text><textPath xlink:href="#h1"><tspan rotate="90">TE</tspan>ST4</textPath></text>
+
+</svg>
--- a/layout/style/nsCSSParser.cpp
+++ b/layout/style/nsCSSParser.cpp
@@ -339,18 +339,16 @@ protected:
   PRBool ParsePageRule(RuleAppendFunc aAppendFunc, void* aProcessData);
 
   enum nsSelectorParsingStatus {
     // we have parsed a selector and we saw a token that cannot be
     // part of a selector:
     eSelectorParsingStatus_Done,
     // we should continue parsing the selector:
     eSelectorParsingStatus_Continue,
-    // same as "Done" but we did not find a selector:
-    eSelectorParsingStatus_Empty,
     // we saw an unexpected token or token value,
     // or we saw end-of-file with an unfinished selector:
     eSelectorParsingStatus_Error
   };
   nsSelectorParsingStatus ParseIDSelector(PRInt32&       aDataMask,
                                           nsCSSSelector& aSelector);
 
   nsSelectorParsingStatus ParseClassSelector(PRInt32&       aDataMask,
@@ -380,26 +378,23 @@ protected:
 
   nsSelectorParsingStatus ParsePseudoClassWithNthPairArg(nsCSSSelector& aSelector,
                                                          nsIAtom*       aPseudo,
                                                          nsCSSPseudoClasses::Type aType);
 
   nsSelectorParsingStatus ParseNegatedSimpleSelector(PRInt32&       aDataMask,
                                                      nsCSSSelector& aSelector);
 
-  nsSelectorParsingStatus ParseSelector(nsCSSSelector& aSelectorResult,
-                                        nsIAtom** aPseudoElement,
-                                        nsPseudoClassList** aPseudoElementArgs,
-                                        nsCSSPseudoElements::Type* aPseudoElementType);
-
   // If aTerminateAtBrace is true, the selector list is done when we
   // hit a '{'.  Otherwise, it's done when we hit EOF.
   PRBool ParseSelectorList(nsCSSSelectorList*& aListHead,
                            PRBool aTerminateAtBrace);
   PRBool ParseSelectorGroup(nsCSSSelectorList*& aListHead);
+  PRBool ParseSelector(nsCSSSelectorList* aList, PRUnichar aPrevCombinator);
+
   nsCSSDeclaration* ParseDeclarationBlock(PRBool aCheckForBraces);
   PRBool ParseDeclaration(nsCSSDeclaration* aDeclaration,
                           PRBool aCheckForBraces,
                           PRBool aMustCallValueAppended,
                           PRBool* aChanged);
   // After a parse error parsing |aPropID|, clear the data in
   // |mTempData|.
   void ClearTempData(nsCSSProperty aPropID);
@@ -2515,140 +2510,59 @@ static PRBool IsUniversalSelector(const 
                 (aSelector.mAttrList == nsnull) &&
                 (aSelector.mNegations == nsnull) &&
                 (aSelector.mPseudoClassList == nsnull));
 }
 
 PRBool
 CSSParserImpl::ParseSelectorGroup(nsCSSSelectorList*& aList)
 {
-  nsAutoPtr<nsCSSSelectorList> list;
-  PRUnichar     combinator = PRUnichar(0);
-  PRInt32       weight = 0;
-  PRBool        havePseudoElement = PR_FALSE;
-  PRBool        done = PR_FALSE;
-  while (!done) {
-    nsAutoPtr<nsCSSSelector> newSelector(new nsCSSSelector());
-    if (!newSelector) {
-      mScanner.SetLowLevelError(NS_ERROR_OUT_OF_MEMORY);
+  PRUnichar combinator = 0;
+  nsAutoPtr<nsCSSSelectorList> list(new nsCSSSelectorList());
+
+  for (;;) {
+    if (!ParseSelector(list, combinator)) {
       return PR_FALSE;
     }
-    nsCOMPtr<nsIAtom> pseudoElement;
-    nsAutoPtr<nsPseudoClassList> pseudoElementArgs;
-    nsCSSPseudoElements::Type pseudoElementType =
-      nsCSSPseudoElements::ePseudo_NotPseudoElement;
-    nsSelectorParsingStatus parsingStatus =
-      ParseSelector(*newSelector, getter_AddRefs(pseudoElement),
-                    getter_Transfers(pseudoElementArgs),
-                    &pseudoElementType);
-    if (parsingStatus == eSelectorParsingStatus_Empty) {
-      if (!list) {
-        REPORT_UNEXPECTED(PESelectorGroupNoSelector);
-      }
-      break;
-    }
-    if (parsingStatus == eSelectorParsingStatus_Error) {
-      list = nsnull;
-      break;
-    }
-    if (pseudoElementType == nsCSSPseudoElements::ePseudo_AnonBox &&
-        (list || !IsUniversalSelector(*newSelector))) {
-      REPORT_UNEXPECTED(PEAnonBoxNotAlone);
-      list = nsnull;
-      break;
-    }
-    if (nsnull == list) {
-      list = new nsCSSSelectorList();
-      if (nsnull == list) {
-        mScanner.SetLowLevelError(NS_ERROR_OUT_OF_MEMORY);
-        return PR_FALSE;
-      }
-    }
-
-    list->AddSelector(newSelector);
-    nsCSSSelector* listSel = list->mSelectors;
-
-    // We got a pseudo-element (or anonymous box).  We actually
-    // represent pseudo-elements as a child of the rest of the selector.
-    if (pseudoElement) {
-      if (pseudoElementType != nsCSSPseudoElements::ePseudo_AnonBox) {
-        // We need to put the pseudo-element on a new selector that's a
-        // child of the current one.
-        listSel->mOperator = PRUnichar('>');
-        nsAutoPtr<nsCSSSelector> empty(new nsCSSSelector());
-        if (!empty) {
-          mScanner.SetLowLevelError(NS_ERROR_OUT_OF_MEMORY);
-          return PR_FALSE;
-        }
-        list->AddSelector(empty);
-        // Save the weight of the non-pseudo-element part of this selector now
-        weight += listSel->CalcWeight();
-        listSel = list->mSelectors; // use the new one for the pseudo
-      }
-      NS_ASSERTION(!listSel->mLowercaseTag &&
-                   !listSel->mCasedTag &&
-                   !listSel->mPseudoClassList,
-                   "already initialized");
-      listSel->mLowercaseTag.swap(pseudoElement);
-      listSel->mPseudoClassList = pseudoElementArgs.forget();
-      listSel->SetPseudoType(pseudoElementType);
-      havePseudoElement = PR_TRUE;
+
+    // Look for a combinator.
+    if (!GetToken(PR_FALSE)) {
+      break; // EOF ok here
     }
 
     combinator = PRUnichar(0);
-    if (!GetToken(PR_FALSE)) {
-      break;
-    }
-
-    // Assume we are done unless we find a combinator here.
-    done = PR_TRUE;
-    if (eCSSToken_WhiteSpace == mToken.mType) {
+    if (mToken.mType == eCSSToken_WhiteSpace) {
       if (!GetToken(PR_TRUE)) {
-        break;
-      }
-      done = PR_FALSE;
-    }
-
-    if (eCSSToken_Symbol == mToken.mType &&
-        ('+' == mToken.mSymbol ||
-         '>' == mToken.mSymbol ||
-         '~' == mToken.mSymbol)) {
-      done = PR_FALSE;
-      combinator = mToken.mSymbol;
-      list->mSelectors->SetOperator(combinator);
-    }
-    else {
-      if (eCSSToken_Symbol == mToken.mType &&
-          ('{' == mToken.mSymbol ||
-           ',' == mToken.mSymbol)) {
-        // End of this selector group
-        done = PR_TRUE;
-      }
-      UngetToken(); // give it back to selector if we're not done, or make sure
-                    // we see it as the end of the selector if we are.
-    }
-
-    if (havePseudoElement) {
-      break;
-    }
-    else {
-      weight += listSel->CalcWeight();
-    }
-  }
-
-  if (PRUnichar(0) != combinator) { // no dangling combinators
-    list = nsnull;
-    // This should report the problematic combinator
-    REPORT_UNEXPECTED(PESelectorGroupExtraCombinator);
-  }
+        break; // EOF ok here
+      }
+      combinator = PRUnichar(' ');
+    }
+
+    if (mToken.mType != eCSSToken_Symbol) {
+      UngetToken(); // not a combinator
+    } else {
+      PRUnichar symbol = mToken.mSymbol;
+      if (symbol == '+' || symbol == '>' || symbol == '~') {
+        combinator = mToken.mSymbol;
+      } else {
+        UngetToken(); // not a combinator
+        if (symbol == ',' || symbol == '{') {
+          break; // end of selector group
+        }
+      }
+    }
+
+    if (!combinator) {
+      REPORT_UNEXPECTED_TOKEN(PESelectorListExtra);
+      return PR_FALSE;
+    }
+  }
+
   aList = list.forget();
-  if (aList) {
-    aList->mWeight = weight;
-  }
-  return PRBool(nsnull != aList);
+  return PR_TRUE;
 }
 
 #define SEL_MASK_NSPACE   0x01
 #define SEL_MASK_ELEM     0x02
 #define SEL_MASK_ID       0x04
 #define SEL_MASK_CLASS    0x08
 #define SEL_MASK_ATTRIB   0x10
 #define SEL_MASK_PCLASS   0x20
@@ -3214,27 +3128,27 @@ CSSParserImpl::ParsePseudoSelector(PRInt
         // item in the list to the pseudoclass list.  They will be pulled
         // from the list later along with the pseudo-element.
         if (!ParseTreePseudoElement(aPseudoElementArgs)) {
           return eSelectorParsingStatus_Error;
         }
       }
 #endif
 
-      // ensure selector ends here, must be followed by EOF, space, '{' or ','
-      if (GetToken(PR_FALSE)) { // premature eof is ok (here!)
-        if ((eCSSToken_WhiteSpace == mToken.mType) ||
-            (mToken.IsSymbol('{') || mToken.IsSymbol(','))) {
-          UngetToken();
-          return eSelectorParsingStatus_Done;
-        }
-        REPORT_UNEXPECTED_TOKEN(PEPseudoSelTrailing);
+      // the next *non*whitespace token must be '{' or ',' or EOF
+      if (!GetToken(PR_TRUE)) { // premature eof is ok (here!)
+        return eSelectorParsingStatus_Done;
+      }
+      if ((mToken.IsSymbol('{') || mToken.IsSymbol(','))) {
         UngetToken();
-        return eSelectorParsingStatus_Error;
-      }
+        return eSelectorParsingStatus_Done;
+      }
+      REPORT_UNEXPECTED_TOKEN(PEPseudoSelTrailing);
+      UngetToken();
+      return eSelectorParsingStatus_Error;
     }
     else {  // multiple pseudo elements, not legal
       REPORT_UNEXPECTED_TOKEN(PEPseudoSelMultiplePE);
       UngetToken();
       return eSelectorParsingStatus_Error;
     }
   }
 #ifdef DEBUG
@@ -3488,64 +3402,109 @@ CSSParserImpl::ParsePseudoClassWithNthPa
   return eSelectorParsingStatus_Continue;
 }
 
 
 /**
  * This is the format for selectors:
  * operator? [[namespace |]? element_name]? [ ID | class | attrib | pseudo ]*
  */
-CSSParserImpl::nsSelectorParsingStatus
-CSSParserImpl::ParseSelector(nsCSSSelector& aSelector,
-                             nsIAtom** aPseudoElement,
-                             nsPseudoClassList** aPseudoElementArgs,
-                             nsCSSPseudoElements::Type* aPseudoElementType)
+PRBool
+CSSParserImpl::ParseSelector(nsCSSSelectorList* aList,
+                             PRUnichar aPrevCombinator)
 {
   if (! GetToken(PR_TRUE)) {
     REPORT_UNEXPECTED_EOF(PESelectorEOF);
-    return eSelectorParsingStatus_Error;
-  }
+    return PR_FALSE;
+  }
+
+  nsCSSSelector* selector = aList->AddSelector(aPrevCombinator);
+  nsCOMPtr<nsIAtom> pseudoElement;
+  nsAutoPtr<nsPseudoClassList> pseudoElementArgs;
+  nsCSSPseudoElements::Type pseudoElementType =
+    nsCSSPseudoElements::ePseudo_NotPseudoElement;
 
   PRInt32 dataMask = 0;
   nsSelectorParsingStatus parsingStatus =
-    ParseTypeOrUniversalSelector(dataMask, aSelector, PR_FALSE);
-  if (parsingStatus != eSelectorParsingStatus_Continue) {
-    return parsingStatus;
-  }
-
-  for (;;) {
+    ParseTypeOrUniversalSelector(dataMask, *selector, PR_FALSE);
+
+  while (parsingStatus == eSelectorParsingStatus_Continue) {
     if (eCSSToken_ID == mToken.mType) { // #id
-      parsingStatus = ParseIDSelector(dataMask, aSelector);
+      parsingStatus = ParseIDSelector(dataMask, *selector);
     }
     else if (mToken.IsSymbol('.')) {    // .class
-      parsingStatus = ParseClassSelector(dataMask, aSelector);
+      parsingStatus = ParseClassSelector(dataMask, *selector);
     }
     else if (mToken.IsSymbol(':')) {    // :pseudo
-      parsingStatus = ParsePseudoSelector(dataMask, aSelector, PR_FALSE,
-                                          aPseudoElement, aPseudoElementArgs,
-                                          aPseudoElementType);
+      parsingStatus = ParsePseudoSelector(dataMask, *selector, PR_FALSE,
+                                          getter_AddRefs(pseudoElement),
+                                          getter_Transfers(pseudoElementArgs),
+                                          &pseudoElementType);
     }
     else if (mToken.IsSymbol('[')) {    // [attribute
-      parsingStatus = ParseAttributeSelector(dataMask, aSelector);
+      parsingStatus = ParseAttributeSelector(dataMask, *selector);
     }
     else {  // not a selector token, we're done
       parsingStatus = eSelectorParsingStatus_Done;
+      UngetToken();
       break;
     }
 
     if (parsingStatus != eSelectorParsingStatus_Continue) {
-      return parsingStatus;
+      break;
     }
 
     if (! GetToken(PR_FALSE)) { // premature eof is ok (here!)
-      return eSelectorParsingStatus_Done;
-    }
-  }
-  UngetToken();
-  return dataMask ? parsingStatus : eSelectorParsingStatus_Empty;
+      parsingStatus = eSelectorParsingStatus_Done;
+      break;
+    }
+  }
+
+  if (parsingStatus == eSelectorParsingStatus_Error) {
+    return PR_FALSE;
+  }
+
+  if (!dataMask) {
+    if (selector->mNext) {
+      REPORT_UNEXPECTED(PESelectorGroupExtraCombinator);
+    } else {
+      REPORT_UNEXPECTED(PESelectorGroupNoSelector);
+    }
+    return PR_FALSE;
+  }
+
+  if (pseudoElementType == nsCSSPseudoElements::ePseudo_AnonBox) {
+    // We got an anonymous box pseudo-element; it must be the only
+    // thing in this selector group.
+    if (selector->mNext || !IsUniversalSelector(*selector)) {
+      REPORT_UNEXPECTED(PEAnonBoxNotAlone);
+      return PR_FALSE;
+    }
+
+    // Rewrite the current selector as this pseudo-element.
+    // It does not contribute to selector weight.
+    selector->mLowercaseTag.swap(pseudoElement);
+    selector->mPseudoClassList = pseudoElementArgs.forget();
+    selector->SetPseudoType(pseudoElementType);
+    return PR_TRUE;
+  }
+
+  aList->mWeight += selector->CalcWeight();
+
+  // Pseudo-elements other than anonymous boxes are represented as
+  // direct children ('>' combinator) of the rest of the selector.
+  if (pseudoElement) {
+    selector = aList->AddSelector('>');
+
+    selector->mLowercaseTag.swap(pseudoElement);
+    selector->mPseudoClassList = pseudoElementArgs.forget();
+    selector->SetPseudoType(pseudoElementType);
+  }
+
+  return PR_TRUE;
 }
 
 nsCSSDeclaration*
 CSSParserImpl::ParseDeclarationBlock(PRBool aCheckForBraces)
 {
   if (aCheckForBraces) {
     if (!ExpectSymbol('{', PR_TRUE)) {
       REPORT_UNEXPECTED_TOKEN(PEBadDeclBlockStart);
--- a/layout/style/nsCSSRuleProcessor.cpp
+++ b/layout/style/nsCSSRuleProcessor.cpp
@@ -2035,28 +2035,33 @@ static PRBool SelectorMatches(RuleProces
     }
   }
   return result;
 }
 
 #undef STATE_CHECK
 
 // Right now, there are four operators:
-//   PRUnichar(0), the descendant combinator, is greedy
+//   ' ', the descendant combinator, is greedy
 //   '~', the indirect adjacent sibling combinator, is greedy
 //   '+' and '>', the direct adjacent sibling and child combinators, are not
-#define NS_IS_GREEDY_OPERATOR(ch) (ch == PRUnichar(0) || ch == PRUnichar('~'))
+#define NS_IS_GREEDY_OPERATOR(ch) \
+  ((ch) == PRUnichar(' ') || (ch) == PRUnichar('~'))
 
 static PRBool SelectorMatchesTree(RuleProcessorData& aPrevData,
                                   nsCSSSelector* aSelector,
                                   PRBool aForStyling) 
 {
   nsCSSSelector* selector = aSelector;
   RuleProcessorData* prevdata = &aPrevData;
   while (selector) { // check compound selectors
+    NS_ASSERTION(!selector->mNext ||
+                 selector->mNext->mOperator != PRUnichar(0),
+                 "compound selector without combinator");
+
     // If we don't already have a RuleProcessorData for the next
     // appropriate content (whether parent or previous sibling), create
     // one.
 
     // for adjacent sibling combinators, the content to test against the
     // selector is the previous sibling *element*
     RuleProcessorData* data;
     if (PRUnichar('+') == selector->mOperator ||
@@ -2107,17 +2112,17 @@ static PRBool SelectorMatchesTree(RulePr
       // descendant or general sibling combinator and the next
       // combinator is different, but we can make an exception for
       // sibling, then parent, since a sibling's parent is always the
       // same.
       if (NS_IS_GREEDY_OPERATOR(selector->mOperator) &&
           selector->mNext &&
           selector->mNext->mOperator != selector->mOperator &&
           !(selector->mOperator == '~' &&
-            (selector->mNext->mOperator == PRUnichar(0) ||
+            (selector->mNext->mOperator == PRUnichar(' ') ||
              selector->mNext->mOperator == PRUnichar('>')))) {
 
         // pretend the selector didn't match, and step through content
         // while testing the same selector
 
         // This approach is slightly strange in that when it recurs
         // it tests from the top of the content tree, down.  This
         // doesn't matter much for performance since most selectors
--- a/layout/style/nsCSSStyleRule.cpp
+++ b/layout/style/nsCSSStyleRule.cpp
@@ -508,31 +508,37 @@ nsCSSSelector::ToString(nsAString& aStri
    aString.Truncate();
 
   // selectors are linked from right-to-left, so the next selector in
   // the linked list actually precedes this one in the resulting string
   nsAutoTArray<const nsCSSSelector*, 8> stack;
   for (const nsCSSSelector *s = this; s; s = s->mNext) {
     stack.AppendElement(s);
   }
-   
+
   while (!stack.IsEmpty()) {
     PRUint32 index = stack.Length() - 1;
     const nsCSSSelector *s = stack.ElementAt(index);
     stack.RemoveElementAt(index);
 
     s->AppendToStringWithoutCombinators(aString, aSheet);
 
     // Append the combinator, if needed.
     if (!stack.IsEmpty()) {
       const nsCSSSelector *next = stack.ElementAt(index - 1);
-      if (!next->IsPseudoElement()) {
+      PRUnichar oper = s->mOperator;
+      if (next->IsPseudoElement()) {
+        NS_ASSERTION(oper == PRUnichar('>'),
+                     "improperly chained pseudo element");
+      } else {
+        NS_ASSERTION(oper != PRUnichar(0),
+                     "compound selector without combinator");
+
         aString.Append(PRUnichar(' '));
-        PRUnichar oper = s->mOperator;
-        if (oper != PRUnichar(0)) {
+        if (oper != PRUnichar(' ')) {
           aString.Append(oper);
           aString.Append(PRUnichar(' '));
         }
       }
     }
   }
 }
 
@@ -798,23 +804,31 @@ nsCSSSelectorList::nsCSSSelectorList(voi
 
 nsCSSSelectorList::~nsCSSSelectorList()
 {
   MOZ_COUNT_DTOR(nsCSSSelectorList);
   delete mSelectors;
   NS_CSS_DELETE_LIST_MEMBER(nsCSSSelectorList, this, mNext);
 }
 
-void nsCSSSelectorList::AddSelector(nsAutoPtr<nsCSSSelector>& aSelector)
-{ // prepend to list
-  nsCSSSelector* newSel = aSelector.forget();
-  if (newSel) {
-    newSel->mNext = mSelectors;
-    mSelectors = newSel;
+nsCSSSelector*
+nsCSSSelectorList::AddSelector(PRUnichar aOperator)
+{
+  nsCSSSelector* newSel = new nsCSSSelector();
+
+  if (mSelectors) {
+    NS_ASSERTION(aOperator != PRUnichar(0), "chaining without combinator");
+    mSelectors->SetOperator(aOperator);
+  } else {
+    NS_ASSERTION(aOperator == PRUnichar(0), "combinator without chaining");
   }
+
+  newSel->mNext = mSelectors;
+  mSelectors = newSel;
+  return newSel;
 }
 
 void
 nsCSSSelectorList::ToString(nsAString& aResult, nsICSSStyleSheet* aSheet)
 {
   aResult.Truncate();
   nsCSSSelectorList *p = this;
   for (;;) {
--- a/layout/style/nsICSSStyleRule.h
+++ b/layout/style/nsICSSStyleRule.h
@@ -244,23 +244,25 @@ private:
  * items (where each |nsCSSSelectorList| object's |mSelectors| has
  * an |mNext| for the P or H1).  We represent them as linked lists.
  */
 struct nsCSSSelectorList {
   nsCSSSelectorList(void);
   ~nsCSSSelectorList(void);
 
   /**
-   * Push the selector pointed to by |aSelector| on to the beginning of
-   * |mSelectors|, setting its |mNext| to the current value of |mSelectors|.
-   * This nulls out aSelector.
-   *
+   * Create a new selector and push it onto the beginning of |mSelectors|,
+   * setting its |mNext| to the current value of |mSelectors|.  If there is an
+   * earlier selector, set its |mOperator| to |aOperator|; else |aOperator|
+   * must be PRUnichar(0).
+   * Returns the new selector.
+   * The list owns the new selector.
    * The caller is responsible for updating |mWeight|.
    */
-  void AddSelector(nsAutoPtr<nsCSSSelector>& aSelector);
+  nsCSSSelector* AddSelector(PRUnichar aOperator);
 
   /**
    * Should be used only on the first in the list
    */
   void ToString(nsAString& aResult, nsICSSStyleSheet* aSheet);
 
   /**
    * Do a deep clone.  Should be used only on the first in the list.
--- a/layout/svg/base/src/nsSVGForeignObjectFrame.cpp
+++ b/layout/svg/base/src/nsSVGForeignObjectFrame.cpp
@@ -395,19 +395,17 @@ nsSVGForeignObjectFrame::NotifySVGChange
   if (reflow) {
     // If we're called while the PresShell is handling reflow events then we
     // must have been called as a result of the NotifyViewportChange() call in
     // our nsSVGOuterSVGFrame's Reflow() method. We must not call RequestReflow
     // at this point (i.e. during reflow) because it could confuse the
     // PresShell and prevent it from reflowing us properly in future. Besides
     // that, nsSVGOuterSVGFrame::DidReflow will take care of reflowing us
     // synchronously, so there's no need.
-    PRBool reflowing;
-    PresContext()->PresShell()->IsReflowLocked(&reflowing);
-    if (!reflowing) {
+    if (!PresContext()->PresShell()->IsReflowLocked()) {
       UpdateGraphic(); // update mRect before requesting reflow
       RequestReflow(nsIPresShell::eResize);
     }
   }
 }
 
 NS_IMETHODIMP
 nsSVGForeignObjectFrame::NotifyRedrawSuspended()
--- a/layout/svg/base/src/nsSVGGlyphFrame.cpp
+++ b/layout/svg/base/src/nsSVGGlyphFrame.cpp
@@ -713,16 +713,20 @@ nsSVGGlyphFrame::GetCharacterPositions(n
   NS_ASSERTION(strLength > 0, "no text");
 
   const gfxFloat radPerDeg = M_PI / 180.0;
 
   nsCOMPtr<nsIDOMSVGLengthList> dxList = GetDx();
   nsCOMPtr<nsIDOMSVGLengthList> dyList = GetDy();
   nsCOMPtr<nsIDOMSVGNumberList> rotateList = GetRotate();
 
+  PRBool rotateAllGlyphs = (GetNumberOfNumberListItems(rotateList) == 1);
+  gfxFloat overallGlyphRotation =
+    rotateAllGlyphs ? GetNumberListValue(rotateList, 0) * radPerDeg : 0.0;
+
   gfxPoint pos = mPosition;
 
   nsSVGTextPathFrame *textPath = FindTextPathParent();
 
   if (textPath) {
     nsRefPtr<gfxFlattenedPath> data = textPath->GetFlattenedPath();
 
     // textPath frame, but invalid target
@@ -753,17 +757,18 @@ nsSVGGlyphFrame::GetCharacterPositions(n
 
         // add y (normal)
         // add rotation
         // move point back along tangent
         gfxPoint pt = data->FindPoint(gfxPoint(pos.x + halfAdvance, pos.y),
                                       &(cp[i].angle));
         cp[i].pos =
           pt - gfxPoint(cos(cp[i].angle), sin(cp[i].angle)) * halfAdvance;
-        cp[i].angle += GetNumberListValue(rotateList, i) * radPerDeg;
+        cp[i].angle += rotateAllGlyphs ? overallGlyphRotation :
+          GetNumberListValue(rotateList, i) * radPerDeg;
       }
       pos.x += 2 * halfAdvance;
     }
     return PR_TRUE;
   }
 
   nsCOMPtr<nsIDOMSVGLengthList> xList = GetX();
   nsCOMPtr<nsIDOMSVGLengthList> yList = GetY();
@@ -801,17 +806,18 @@ nsSVGGlyphFrame::GetCharacterPositions(n
     }
     if (yListCount > 1 && i < yListCount) {
       pos.y = GetLengthListValue(yList, i);
     }
     pos.x += GetLengthListValue(dxList, i);
     pos.y += GetLengthListValue(dyList, i);
     cp[i].pos = pos;
     pos.x += advance;
-    cp[i].angle = GetNumberListValue(rotateList, i) * radPerDeg;
+    cp[i].angle = rotateAllGlyphs ? overallGlyphRotation :
+      GetNumberListValue(rotateList, i) * radPerDeg;
   }
   return PR_TRUE;
 }
 
 float
 nsSVGGlyphFrame::GetSubStringAdvance(PRUint32 aCharnum, 
                                      PRUint32 aFragmentChars,
                                      float aMetricsScale)
--- a/layout/xul/base/src/nsXULPopupManager.cpp
+++ b/layout/xul/base/src/nsXULPopupManager.cpp
@@ -547,18 +547,17 @@ CheckCaretDrawingState() {
     focusedDoc = do_QueryInterface(domDoc);
     if (!focusedDoc)
       return;
 
     nsIPresShell* presShell = focusedDoc->GetPrimaryShell();
     if (!presShell)
       return;
 
-    nsRefPtr<nsCaret> caret;
-    presShell->GetCaret(getter_AddRefs(caret));
+    nsRefPtr<nsCaret> caret = presShell->GetCaret();
     if (!caret)
       return;
     caret->CheckCaretDrawingState();
   }
 }
 
 void
 nsXULPopupManager::ShowPopupCallback(nsIContent* aPopup,
--- a/layout/xul/base/src/tree/src/nsTreeBodyFrame.cpp
+++ b/layout/xul/base/src/tree/src/nsTreeBodyFrame.cpp
@@ -365,19 +365,17 @@ nsTreeBodyFrame::EnsureBoxObject()
     }
   }
 }
 
 void
 nsTreeBodyFrame::EnsureView()
 {
   if (!mView) {
-    PRBool isInReflow;
-    PresContext()->PresShell()->IsReflowLocked(&isInReflow);
-    if (isInReflow) {
+    if (PresContext()->PresShell()->IsReflowLocked()) {
       if (!mReflowCallbackPosted) {
         mReflowCallbackPosted = PR_TRUE;
         PresContext()->PresShell()->PostReflowCallback(this);
       }
       return;
     }
     nsCOMPtr<nsIBoxObject> box = do_QueryInterface(mTreeBoxObject);
     if (box) {
@@ -527,19 +525,17 @@ nsTreeBodyFrame::SetView(nsITreeView * a
     }
 
     // View, meet the tree.
     nsWeakFrame weakFrame(this);
     mView->SetTree(mTreeBoxObject);
     NS_ENSURE_STATE(weakFrame.IsAlive());
     mView->GetRowCount(&mRowCount);
  
-    PRBool isInReflow;
-    PresContext()->PresShell()->IsReflowLocked(&isInReflow);
-    if (!isInReflow) {
+    if (!PresContext()->PresShell()->IsReflowLocked()) {
       // The scrollbar will need to be updated.
       FullScrollbarsUpdate(PR_FALSE);
     } else if (!mReflowCallbackPosted) {
       mReflowCallbackPosted = PR_TRUE;
       PresContext()->PresShell()->PostReflowCallback(this);
     }
   }
  
--- a/toolkit/mozapps/installer/package-name.mk
+++ b/toolkit/mozapps/installer/package-name.mk
@@ -53,18 +53,22 @@ MOZ_PKG_PLATFORM := $(TARGET_OS)-$(TARGE
 ifeq ($(OS_ARCH),WINNT)
 ifeq ($(TARGET_CPU),x86_64)
 MOZ_PKG_PLATFORM := win64-$(TARGET_CPU)
 else
 MOZ_PKG_PLATFORM := win32
 endif
 endif
 ifeq ($(OS_ARCH),Darwin)
+ifeq ($(TARGET_CPU),x86_64)
+MOZ_PKG_PLATFORM := mac64
+else
 MOZ_PKG_PLATFORM := mac
 endif
+endif
 ifeq ($(TARGET_OS),linux-gnu)
 MOZ_PKG_PLATFORM := linux-$(TARGET_CPU)
 endif
 ifeq ($(OS_ARCH),OS2)
 MOZ_PKG_PLATFORM := os2
 endif
 ifeq ($(OS_ARCH),BeOS)
 ifeq (,$(filter-out 6.%, $(OS_RELEASE)))
--- a/widget/public/nsGUIEvent.h
+++ b/widget/public/nsGUIEvent.h
@@ -46,16 +46,17 @@
 #include "nsRect.h"
 #include "nsRegion.h"
 #include "nsEvent.h"
 #include "nsStringGlue.h"
 #include "nsCOMPtr.h"
 #include "nsIAtom.h"
 #include "nsIDOMKeyEvent.h"
 #include "nsIDOMDataTransfer.h"
+#include "nsPIDOMEventTarget.h"
 #include "nsWeakPtr.h"
 #include "nsIWidget.h"
 #include "nsTArray.h"
 #include "nsTraceRefcnt.h"
 #include "nsITransferable.h"
 #include "nsIVariant.h"
 
 class nsIRenderingContext;
@@ -519,21 +520,19 @@ public:
   // to the time the message was created
   PRUint32    time;
   // Flags to hold event flow stage and capture/bubble cancellation
   // status. This is used also to indicate whether the event is trusted.
   PRUint32    flags;
   // Additional type info for user defined events
   nsCOMPtr<nsIAtom>     userType;
   // Event targets, needed by DOM Events
-  // Using nsISupports, not nsIDOMEventTarget because in some cases
-  // nsIDOMEventTarget is implemented as a tearoff.
-  nsCOMPtr<nsISupports> target;
-  nsCOMPtr<nsISupports> currentTarget;
-  nsCOMPtr<nsISupports> originalTarget;
+  nsCOMPtr<nsPIDOMEventTarget> target;
+  nsCOMPtr<nsPIDOMEventTarget> currentTarget;
+  nsCOMPtr<nsPIDOMEventTarget> originalTarget;
 };
 
 /**
  * General graphic user interface event
  */
 
 class nsGUIEvent : public nsEvent
 {
--- a/widget/src/cocoa/nsIdleServiceX.h
+++ b/widget/src/cocoa/nsIdleServiceX.h
@@ -39,15 +39,12 @@
 
 #include "nsIdleService.h"
 
 class nsIdleServiceX : public nsIdleService
 {
 public:
   NS_DECL_ISUPPORTS
 
-  bool PollIdleTime(PRUint32* aIdleTime);
-
-protected:
-    bool UsePollMode();
+  NS_IMETHOD GetIdleTime(PRUint32* idleTime);
 };
 
 #endif // nsIdleServiceX_h_
--- a/widget/src/cocoa/nsIdleServiceX.mm
+++ b/widget/src/cocoa/nsIdleServiceX.mm
@@ -34,50 +34,50 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsIdleServiceX.h"
 #include "nsObjCExceptions.h"
 #include "nsIServiceManager.h"
 #import <Foundation/Foundation.h>
 
-NS_IMPL_ISUPPORTS2(nsIdleServiceX, nsIIdleService, nsIdleService)
+NS_IMPL_ISUPPORTS1(nsIdleServiceX, nsIIdleService)
 
-bool
-nsIdleServiceX::PollIdleTime(PRUint32 *aIdleTime)
+NS_IMETHODIMP
+nsIdleServiceX::GetIdleTime(PRUint32 *aTimeDiff)
 {
-  NS_OBJC_BEGIN_TRY_ABORT_BLOCK_RETURN;
+  NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT;
 
   kern_return_t rval;
   mach_port_t masterPort;
 
   rval = IOMasterPort(kIOMasterPortDefault, &masterPort);
   if (rval != KERN_SUCCESS)
-    return false;
+    return NS_ERROR_FAILURE;
 
   io_iterator_t hidItr;
   rval = IOServiceGetMatchingServices(masterPort,
                                       IOServiceMatching("IOHIDSystem"),
                                       &hidItr);
 
   if (rval != KERN_SUCCESS)
-    return false;
+    return NS_ERROR_FAILURE;
   NS_ASSERTION(hidItr, "Our iterator is null, but it ought not to be!");
 
   io_registry_entry_t entry = IOIteratorNext(hidItr);
   NS_ASSERTION(entry, "Our IO Registry Entry is null, but it shouldn't be!");
 
   IOObjectRelease(hidItr);
 
   NSMutableDictionary *hidProps;
   rval = IORegistryEntryCreateCFProperties(entry,
                                            (CFMutableDictionaryRef*)&hidProps,
                                            kCFAllocatorDefault, 0);
   if (rval != KERN_SUCCESS)
-    return false;
+    return NS_ERROR_FAILURE;
   NS_ASSERTION(hidProps, "HIDProperties is null, but no error was returned.");
   [hidProps autorelease];
 
   id idleObj = [hidProps objectForKey:@"HIDIdleTime"];
   NS_ASSERTION([idleObj isKindOfClass: [NSData class]] ||
                [idleObj isKindOfClass: [NSNumber class]],
                "What we got for the idle object is not what we expect!");
 
@@ -87,23 +87,16 @@ nsIdleServiceX::PollIdleTime(PRUint32 *a
   else
     time = [idleObj unsignedLongLongValue];
 
   IOObjectRelease(entry);
 
   // convert to ms from ns
   time /= 1000000;
   if (time > PR_UINT32_MAX) // Overflow will occur
-    return false;
+    return NS_ERROR_CANNOT_CONVERT_DATA;
 
-  *aIdleTime = static_cast<PRUint32>(time);
+  *aTimeDiff = static_cast<PRUint32>(time);
 
-  return true;
+  return NS_OK;
 
-  NS_OBJC_END_TRY_ABORT_BLOCK_RETURN(false);
+  NS_OBJC_END_TRY_ABORT_BLOCK_NSRESULT;
 }
-
-bool
-nsIdleServiceX::UsePollMode()
-{
-  return true;
-}
-
--- a/widget/src/cocoa/nsNativeThemeCocoa.h
+++ b/widget/src/cocoa/nsNativeThemeCocoa.h
@@ -85,17 +85,17 @@ public:
                                   nsIntSize* aResult, PRBool* aIsOverridable);
   NS_IMETHOD WidgetStateChanged(nsIFrame* aFrame, PRUint8 aWidgetType, 
                                 nsIAtom* aAttribute, PRBool* aShouldRepaint);
   NS_IMETHOD ThemeChanged();
   PRBool ThemeSupportsWidget(nsPresContext* aPresContext, nsIFrame* aFrame, PRUint8 aWidgetType);
   PRBool WidgetIsContainer(PRUint8 aWidgetType);
   PRBool ThemeDrawsFocusForWidget(nsPresContext* aPresContext, nsIFrame* aFrame, PRUint8 aWidgetType);
   PRBool ThemeNeedsComboboxDropmarker();
-  virtual Transparency GetWidgetTransparency(nsIFrame* aFrame, PRUint8 aWidgetType);
+  virtual nsTransparencyMode GetWidgetTransparency(PRUint8 aWidgetType);
 
 protected:  
 
   nsresult GetSystemColor(PRUint8 aWidgetType, nsILookAndFeel::nsColorID& aColorID);
   nsresult GetSystemFont(PRUint8 aWidgetType, nsSystemFontID& aFont);
   nsIntMargin RTLAwareMargin(const nsIntMargin& aMargin, nsIFrame* aFrame);
 
   // HITheme drawing routines
--- a/widget/src/cocoa/nsNativeThemeCocoa.mm
+++ b/widget/src/cocoa/nsNativeThemeCocoa.mm
@@ -2464,17 +2464,17 @@ nsNativeThemeCocoa::ThemeDrawsFocusForWi
 }
 
 PRBool
 nsNativeThemeCocoa::ThemeNeedsComboboxDropmarker()
 {
   return PR_FALSE;
 }
 
-nsITheme::Transparency
-nsNativeThemeCocoa::GetWidgetTransparency(nsIFrame* aFrame, PRUint8 aWidgetType)
+nsTransparencyMode
+nsNativeThemeCocoa::GetWidgetTransparency(PRUint8 aWidgetType)
 {
   if (aWidgetType == NS_THEME_MENUPOPUP ||
       aWidgetType == NS_THEME_TOOLTIP)
-    return eTransparent;
+    return eTransparencyTransparent;
 
-  return eUnknownTransparency;
+  return eTransparencyOpaque;
 }
--- a/widget/src/gtk2/nsIdleServiceGTK.cpp
+++ b/widget/src/gtk2/nsIdleServiceGTK.cpp
@@ -57,17 +57,18 @@ typedef XScreenSaverInfo* (*_XScreenSave
 typedef void (*_XScreenSaverQueryInfo_fn)(Display* dpy, Drawable drw,
                                           XScreenSaverInfo *info);
 
 static PRBool sInitialized = PR_FALSE;
 static _XScreenSaverQueryExtension_fn _XSSQueryExtension = nsnull;
 static _XScreenSaverAllocInfo_fn _XSSAllocInfo = nsnull;
 static _XScreenSaverQueryInfo_fn _XSSQueryInfo = nsnull;
 
-NS_IMPL_ISUPPORTS2(nsIdleServiceGTK, nsIdleService, nsIIdleService)
+
+NS_IMPL_ISUPPORTS1(nsIdleServiceGTK, nsIIdleService)
 
 static void Initialize()
 {
     // This will leak - See comments in ~nsIdleServiceGTK().
     PRLibrary* xsslib = PR_LoadLibrary("libXss.so.1");
     if (!xsslib) // ouch.
     {
 #ifdef PR_LOGGING
@@ -116,58 +117,62 @@ nsIdleServiceGTK::~nsIdleServiceGTK()
 #if 0
     if (xsslib) {
         PR_UnloadLibrary(xsslib);
         xsslib = nsnull;
     }
 #endif
 }
 
-bool
-nsIdleServiceGTK::PollIdleTime(PRUint32 *aIdleTime)
+NS_IMETHODIMP
+nsIdleServiceGTK::GetIdleTime(PRUint32 *aTimeDiff)
 {
     if (!sInitialized) {
-        // For some reason, we could not find xscreensaver.  This this might be
-        // because we are on a mobile platforms (e.g. Maemo/OSSO).  In this
-        // case, let the base class handle it
-        return false;
+        // For some reason, we could not find xscreensaver.  This this might be because
+        // we are on a mobile platforms (e.g. Maemo/OSSO).  In this case, fall back to
+        // using gLastInputEventTime which is 
+
+        // The last user input event time in microseconds. If there are any pending
+        // native toolkit input events it returns the current time. The value is
+        // compatible with PR_IntervalToMicroseconds(PR_IntervalNow()).
+        // DEFINED IN widget/src/gtk2/nsWindow.cpp
+        extern PRUint32 gLastInputEventTime;
+
+        PRUint32 nowTime = PR_IntervalToMicroseconds(PR_IntervalNow());
+        *aTimeDiff = (nowTime - gLastInputEventTime) / 1000;
+        return NS_OK;
     }
 
+
     // Ask xscreensaver about idle time:
-    *aIdleTime = 0;
+    *aTimeDiff = 0;
 
     // We might not have a display (cf. in xpcshell)
     Display *dplay = GDK_DISPLAY();
     if (!dplay) {
 #ifdef PR_LOGGING
         PR_LOG(sIdleLog, PR_LOG_WARNING, ("No display found!\n"));
 #endif
-        return false;
+        return NS_ERROR_FAILURE;
     }
 
     if (!_XSSQueryExtension || !_XSSAllocInfo || !_XSSQueryInfo) {
-        return false;
+        return NS_ERROR_FAILURE;
     }
 
     int event_base, error_base;
     if (_XSSQueryExtension(dplay, &event_base, &error_base))
     {
         if (!mXssInfo)
             mXssInfo = _XSSAllocInfo();
         if (!mXssInfo)
-            return false;
+            return NS_ERROR_OUT_OF_MEMORY;
         _XSSQueryInfo(dplay, GDK_ROOT_WINDOW(), mXssInfo);
-        *aIdleTime = mXssInfo->idle;
-        return true;
+        *aTimeDiff = mXssInfo->idle;
+        return NS_OK;
     }
     // If we get here, we couldn't get to XScreenSaver:
 #ifdef PR_LOGGING
     PR_LOG(sIdleLog, PR_LOG_WARNING, ("XSSQueryExtension returned false!\n"));
 #endif
-    return false;
+    return NS_ERROR_FAILURE;
 }
 
-bool
-nsIdleServiceGTK::UsePollMode()
-{
-    return sInitialized;
-}
-
--- a/widget/src/gtk2/nsIdleServiceGTK.h
+++ b/widget/src/gtk2/nsIdleServiceGTK.h
@@ -56,19 +56,15 @@ typedef struct {
 } XScreenSaverInfo;
 
 class nsIdleServiceGTK : public nsIdleService
 {
 public:
     NS_DECL_ISUPPORTS
     nsIdleServiceGTK();
 
-    bool PollIdleTime(PRUint32* aIdleTime);
-
+    NS_IMETHOD GetIdleTime(PRUint32* idleTime);
 private:
     ~nsIdleServiceGTK();
     XScreenSaverInfo* mXssInfo;
-
-protected:
-    bool UsePollMode();
 };
 
 #endif // nsIdleServiceGTK_h__
--- a/widget/src/gtk2/nsNativeThemeGTK.cpp
+++ b/widget/src/gtk2/nsNativeThemeGTK.cpp
@@ -1336,8 +1336,14 @@ nsNativeThemeGTK::ThemeDrawsFocusForWidg
   return PR_FALSE;
 }
 
 PRBool
 nsNativeThemeGTK::ThemeNeedsComboboxDropmarker()
 {
   return PR_FALSE;
 }
+
+nsTransparencyMode
+nsNativeThemeGTK::GetWidgetTransparency(PRUint8 aWidgetType)
+{
+  return eTransparencyOpaque;
+}
--- a/widget/src/gtk2/nsNativeThemeGTK.h
+++ b/widget/src/gtk2/nsNativeThemeGTK.h
@@ -87,16 +87,18 @@ public:
 
   NS_IMETHOD_(PRBool) WidgetIsContainer(PRUint8 aWidgetType);
   
   NS_IMETHOD_(PRBool) ThemeDrawsFocusForWidget(nsPresContext* aPresContext,
                                                nsIFrame* aFrame, PRUint8 aWidgetType);
 
   PRBool ThemeNeedsComboboxDropmarker();
 
+  virtual nsTransparencyMode GetWidgetTransparency(PRUint8 aWidgetType);
+
   nsNativeThemeGTK();
   virtual ~nsNativeThemeGTK();
 
 private:
   PRBool GetGtkWidgetAndState(PRUint8 aWidgetType, nsIFrame* aFrame,
                               GtkThemeWidgetType& aGtkWidgetType,
                               GtkWidgetState* aState, gint* aWidgetFlags);
 
--- a/widget/src/gtk2/nsWindow.cpp
+++ b/widget/src/gtk2/nsWindow.cpp
@@ -261,23 +261,24 @@ static PRBool gdk_keyboard_get_modmap_ma
                                             PRUint32* aCapsLockMask,
                                             PRUint32* aNumLockMask,
                                             PRUint32* aScrollLockMask);
 #endif /* MOZ_X11 */
 
 /* initialization static functions */
 static nsresult    initialize_prefs        (void);
 
-static void
-UpdateLastInputEventTime()
-{
-  nsCOMPtr<nsIdleService> idleService = do_GetService("@mozilla.org/widget/idleservice;1");
-  if (idleService) {
-    idleService->ResetIdleTimeOut();
-  }
+PRUint32        gLastInputEventTime = 0;
+
+static void UpdateLastInputEventTime() {
+  gLastInputEventTime = PR_IntervalToMicroseconds(PR_IntervalNow());
+  nsCOMPtr<nsIIdleService> idleService = do_GetService("@mozilla.org/widget/idleservice;1");
+  nsIdleService* is = static_cast<nsIdleService*>(idleService.get());
+  if (is)
+    is->IdleTimeWasModified();
 }
 
 // this is the last window that had a drag event happen on it.
 nsWindow *nsWindow::mLastDragMotionWindow = NULL;
 PRBool nsWindow::sIsDraggingOutOf = PR_FALSE;
 
 // This is the time of the last button press event.  The drag service
 // uses it as the time to start drags.
@@ -455,16 +456,19 @@ nsWindow::nsWindow()
     if (gUseBufferPixmap) {
         if (gBufferPixmapMaxSize.width == 0) {
             gBufferPixmapMaxSize.width = gdk_screen_width();
             gBufferPixmapMaxSize.height = gdk_screen_height();
         }
 
         gBufferPixmapUsageCount++;
     }
+
+    // Set gLastInputEventTime to some valid number
+    gLastInputEventTime = PR_IntervalToMicroseconds(PR_IntervalNow());
 }
 
 nsWindow::~nsWindow()
 {
     LOG(("nsWindow::~nsWindow() [%p]\n", (void *)this));
     if (mLastDragMotionWindow == this) {
         mLastDragMotionWindow = NULL;
     }
--- a/widget/src/os2/nsIdleServiceOS2.cpp
+++ b/widget/src/os2/nsIdleServiceOS2.cpp
@@ -37,17 +37,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsIdleServiceOS2.h"
 
 // prototype for funtion imported from DSSaver
 static int (*_System DSSaver_GetInactivityTime)(ULONG *, ULONG *);
 #define SSCORE_NOERROR 0 // as in the DSSaver header files
 
-NS_IMPL_ISUPPORTS2(nsIdleServiceOS2, nsIIdleService, nsIdleService)
+NS_IMPL_ISUPPORTS1(nsIdleServiceOS2, nsIIdleService)
 
 nsIdleServiceOS2::nsIdleServiceOS2()
   : mHMod(NULLHANDLE), mInitialized(PR_FALSE)
 {
   const char error[256] = "";
   if (DosLoadModule(error, 256, "SSCORE", &mHMod) == NO_ERROR) {
     if (DosQueryProcAddr(mHMod, 0, "SSCore_GetInactivityTime",
                          (PFN*)&DSSaver_GetInactivityTime) == NO_ERROR) {
@@ -58,31 +58,24 @@ nsIdleServiceOS2::nsIdleServiceOS2()
 
 nsIdleServiceOS2::~nsIdleServiceOS2()
 {
   if (mHMod != NULLHANDLE) {
     DosFreeModule(mHMod);
   }
 }
 
-bool
-nsIdleServiceOS2::PollIdleTime(PRUint32 *aIdleTime)
+NS_IMETHODIMP
+nsIdleServiceOS2::GetIdleTime(PRUint32 *aIdleTime)
 {
   if (!mInitialized)
-    return false;
+    return NS_ERROR_NOT_INITIALIZED;
 
   ULONG mouse, keyboard;
   if (DSSaver_GetInactivityTime(&mouse, &keyboard) != SSCORE_NOERROR) {
-    return false;
+    return NS_ERROR_FAILURE;
   }
 
   // we are only interested in activity in general, so take the minimum
   // of both timers
   *aIdleTime = PR_MIN(mouse, keyboard);
-  return true;
+  return NS_OK;
 }
-
-bool
-nsIdleServiceOS2::UsePollMode()
-{
-  return mInitialized;
-}
-
--- a/widget/src/os2/nsIdleServiceOS2.h
+++ b/widget/src/os2/nsIdleServiceOS2.h
@@ -48,19 +48,16 @@ class nsIdleServiceOS2 : public nsIdleSe
 {
 public:
   NS_DECL_ISUPPORTS
 
   nsIdleServiceOS2();
   ~nsIdleServiceOS2();
 
   // ask the DSSaver DLL (sscore.dll) for the time of the last activity
-  bool PollIdleTime(PRUint32 *aIdleTime);
+  NS_IMETHOD GetIdleTime(PRUint32 *aIdleTime);
 
 private:
   HMODULE mHMod; // module handle for screensaver DLL
   PRBool mInitialized; // fully initialized (function found in screensaver DLL?)
-
-protected:
-  bool UsePollMode();
 };
 
 #endif // nsIdleServiceOS2_h__
--- a/widget/src/qt/nsIdleServiceQt.cpp
+++ b/widget/src/qt/nsIdleServiceQt.cpp
@@ -53,17 +53,17 @@ typedef void (*_XScreenSaverQueryInfo_fn
                                           XScreenSaverInfo *info);
 
 static PRBool sInitialized = PR_FALSE;
 static _XScreenSaverQueryExtension_fn _XSSQueryExtension = nsnull;
 static _XScreenSaverAllocInfo_fn _XSSAllocInfo = nsnull;
 static _XScreenSaverQueryInfo_fn _XSSQueryInfo = nsnull;
 
 
-NS_IMPL_ISUPPORTS2(nsIdleServiceQt, nsIIdleService, nsIdleService)
+NS_IMPL_ISUPPORTS1(nsIdleServiceQt, nsIIdleService)
 
 nsIdleServiceQt::nsIdleServiceQt()
     : mXssInfo(nsnull)
 {
 }
 
 static void Initialize()
 {
@@ -94,47 +94,41 @@ nsIdleServiceQt::~nsIdleServiceQt()
 #if 0
     if (xsslib) {
         PR_UnloadLibrary(xsslib);
         xsslib = nsnull;
     }
 #endif
 }
 
-bool
-nsIdleServiceQt::PollIdleTime(PRUint32 *aIdleTime)
+NS_IMETHODIMP
+nsIdleServiceQt::GetIdleTime(PRUint32 *aTimeDiff)
 {
     // Ask xscreensaver about idle time:
-    *aIdleTime = 0;
+    *aTimeDiff = 0;
 
     // We might not have a display (cf. in xpcshell)
     Display *dplay = QX11Info::display();
     if (!dplay) {
-        return false;
+        return NS_ERROR_FAILURE;
     }
 
     if (!sInitialized) {
         Initialize();
     }
     if (!_XSSQueryExtension || !_XSSAllocInfo || !_XSSQueryInfo) {
-        return false;
+        return NS_ERROR_FAILURE;
     }
 
     int event_base, error_base;
     if (_XSSQueryExtension(dplay, &event_base, &error_base)) {
         if (!mXssInfo)
             mXssInfo = _XSSAllocInfo();
         if (!mXssInfo)
-            return false;
+            return NS_ERROR_OUT_OF_MEMORY;
 
         _XSSQueryInfo(dplay, QX11Info::appRootWindow(), mXssInfo);
-        *aIdleTime = mXssInfo->idle;
-        return true;
+        *aTimeDiff = mXssInfo->idle;
+        return NS_OK;
     }
 
-    return false;
+    return NS_ERROR_FAILURE;
 }
-bool
-nsIdleServiceQt::UsePollMode()
-{
-    return true;
-}
-
--- a/widget/src/qt/nsIdleServiceQt.h
+++ b/widget/src/qt/nsIdleServiceQt.h
@@ -54,19 +54,15 @@ typedef struct {
 } XScreenSaverInfo;
 
 class nsIdleServiceQt : public nsIdleService
 {
 public:
     NS_DECL_ISUPPORTS
     nsIdleServiceQt();
 
-    bool PollIdleTime(PRUint32* aIdleTime);
-
+    NS_IMETHOD GetIdleTime(PRUint32* idleTime);
 private:
     ~nsIdleServiceQt();
     XScreenSaverInfo* mXssInfo;
-
-protected:
-    bool UsePollMode();
 };
 
 #endif // nsIdleServiceQt_h__
--- a/widget/src/qt/nsNativeThemeQt.cpp
+++ b/widget/src/qt/nsNativeThemeQt.cpp
@@ -622,16 +622,22 @@ nsNativeThemeQt::ThemeDrawsFocusForWidge
 }
 
 PRBool
 nsNativeThemeQt::ThemeNeedsComboboxDropmarker()
 {
     return PR_TRUE;
 }
 
+nsTransparencyMode
+nsNativeThemeQt::GetWidgetTransparency(PRUint8 aWidgetType)
+{
+  return eTransparencyOpaque;
+}
+
 void
 nsNativeThemeQt::InitButtonStyle(PRUint8 aWidgetType,
                                  nsIFrame* aFrame,
                                  QRect rect,
                                  QStyleOptionButton &opt)
 {
     PRInt32 eventState = GetContentState(aFrame, aWidgetType);
 
--- a/widget/src/qt/nsNativeThemeQt.h
+++ b/widget/src/qt/nsNativeThemeQt.h
@@ -94,16 +94,18 @@ public:
                                               PRUint8 aWidgetType,
                                               nsIntMargin* aResult);
 
   NS_IMETHOD_(PRBool) ThemeDrawsFocusForWidget(nsPresContext* aPresContext,
                                                nsIFrame* aFrame, PRUint8 aWidgetType);
 
   PRBool ThemeNeedsComboboxDropmarker();
 
+  virtual nsTransparencyMode GetWidgetTransparency(PRUint8 aWidgetType);
+
   nsNativeThemeQt();
   virtual ~nsNativeThemeQt();
 
 private:
 
   inline nsresult DrawWidgetBackground(QPainter *qPainter,
                                        nsIRenderingContext* aContext,
                                        nsIFrame* aFrame,
--- a/widget/src/qt/nsWindow.cpp
+++ b/widget/src/qt/nsWindow.cpp
@@ -66,17 +66,16 @@
 
 #include "prlink.h"
 
 #include "nsWindow.h"
 #include "mozqwidget.h"
 
 #include "nsToolkit.h"
 #include "nsIDeviceContext.h"
-#include "nsIdleService.h"
 #include "nsIRenderingContext.h"
 #include "nsIRegion.h"
 #include "nsIRollupListener.h"
 #include "nsIMenuRollup.h"
 #include "nsWidgetsCID.h"
 #include "nsQtKeyUtils.h"
 
 #include "nsIPrefService.h"
@@ -1261,19 +1260,16 @@ nsWindow::InitButtonEvent(nsMouseEvent &
     aMoveEvent.isAlt           = ((aEvent->modifiers() & Qt::AltModifier) != 0);
     aMoveEvent.isMeta          = ((aEvent->modifiers() & Qt::MetaModifier) != 0);
     aMoveEvent.clickCount      = aClickCount;
 }
 
 nsEventStatus
 nsWindow::OnButtonPressEvent(QGraphicsSceneMouseEvent *aEvent)
 {
-    // The user has done something.
-    UserActivity();
-
     QPointF pos = aEvent->pos();
 
     // we check against the widgets geometry, so use parent coordinates
     // for the check
     if (mWidget)
         pos = mWidget->mapToParent(pos);
 
     PRBool rolledUp = check_for_rollup( pos.x(), pos.y(), PR_FALSE);
@@ -1311,19 +1307,16 @@ nsWindow::OnButtonPressEvent(QGraphicsSc
     }
 
     return status;
 }
 
 nsEventStatus
 nsWindow::OnButtonReleaseEvent(QGraphicsSceneMouseEvent *aEvent)
 {
-    // The user has done something.
-    UserActivity();
-
     PRUint16 domButton;
 
     switch (aEvent->button()) {
     case Qt::MidButton:
         domButton = nsMouseEvent::eMiddleButton;
         break;
     case Qt::RightButton:
         domButton = nsMouseEvent::eRightButton;
@@ -1411,19 +1404,16 @@ nsWindow::DispatchCommandEvent(nsIAtom* 
     return PR_TRUE;
 }
 
 nsEventStatus
 nsWindow::OnKeyPressEvent(QKeyEvent *aEvent)
 {
     LOGFOCUS(("OnKeyPressEvent [%p]\n", (void *)this));
 
-    // The user has done something.
-    UserActivity();
-
     PRBool setNoDefault = PR_FALSE;
 
     // before we dispatch a key, check if it's the context menu key.
     // If so, send a context menu key event instead.
     if (isContextMenuKeyEvent(aEvent)) {
         nsMouseEvent contextMenuEvent(PR_TRUE, NS_CONTEXTMENU, this,
                                       nsMouseEvent::eReal,
                                       nsMouseEvent::eContextMenuKey);
@@ -1469,19 +1459,16 @@ nsWindow::OnKeyPressEvent(QKeyEvent *aEv
     return DispatchEvent(&event);
 }
 
 nsEventStatus
 nsWindow::OnKeyReleaseEvent(QKeyEvent *aEvent)
 {
     LOGFOCUS(("OnKeyReleaseEvent [%p]\n", (void *)this));
 
-    // The user has done something.
-    UserActivity();
-
     if (isContextMenuKeyEvent(aEvent)) {
         // er, what do we do here? DoDefault or NoDefault?
         return nsEventStatus_eConsumeDoDefault;
     }
 
     PRUint32 domCharCode = 0;
     PRUint32 domKeyCode = QtKeyCodeToDOMKeyCode(aEvent->key());
 
@@ -2519,20 +2506,8 @@ nsWindow::GetIMEEnabled(PRUint32* aState
 {
     NS_ENSURE_ARG_POINTER(aState);
     NS_ENSURE_TRUE(mWidget, NS_ERROR_FAILURE);
 
     *aState = mWidget->isVKBOpen() ? IME_STATUS_ENABLED : IME_STATUS_DISABLED;
     return NS_OK;
 }
 
-void
-nsWindow::UserActivity()
-{
-  if (!mIdleService) {
-    mIdleService = do_GetService("@mozilla.org/widget/idleservice;1");
-  }
-
-  if (mIdleService) {
-    mIdleService->ResetIdleTimeOut();
-  }
-}
-
--- a/widget/src/qt/nsWindow.h
+++ b/widget/src/qt/nsWindow.h
@@ -95,18 +95,16 @@ extern PRLogModuleInfo *gWidgetDrawLog;
 #endif
 
 #endif /* MOZ_LOGGING */
 
 class QEvent;
 
 class MozQWidget;
 
-class nsIdleService;
-
 class nsWindow : public nsBaseWidget,
                  public nsSupportsWeakReference
 {
 public:
     nsWindow();
     virtual ~nsWindow();
 
     nsEventStatus DoPaint( QPainter* aPainter, const QStyleOptionGraphicsItem * aOption );
@@ -319,17 +317,16 @@ private:
     MozQWidget*        mWidget;
 
     PRUint32           mIsVisible : 1,
                        mActivatePending : 1;
     PRInt32            mSizeState;
     PluginType         mPluginType;
 
     nsRefPtr<gfxASurface> mThebesSurface;
-    nsCOMPtr<nsIdleService> mIdleService;
 
     PRBool       mIsTransparent;
  
     // all of our DND stuff
     // this is the last window that had a drag event happen on it.
     void   InitDragEvent         (nsMouseEvent &aEvent);
 
     // this is everything we need to be able to fire motion events
@@ -361,20 +358,16 @@ private:
 
     void ClearKeyDownFlag(PRUint32 aKeyCode) {
         PRUint32 mask;
         PRUint32* flag = GetFlagWord32(aKeyCode, &mask);
         *flag &= ~mask;
     }
     PRInt32 mQCursor;
 
-    // Call this function when the users activity is the direct cause of an
-    // event (like a keypress or mouse click).
-    void UserActivity();
-
     // Remember dirty area caused by ::Scroll
     QRegion mDirtyScrollArea;
 
 #if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 0))
     double mTouchPointDistance;
     double mLastPinchDistance;
     PRBool mMouseEventsDisabled;
 #endif
--- a/widget/src/windows/nsIdleServiceWin.cpp
+++ b/widget/src/windows/nsIdleServiceWin.cpp
@@ -36,38 +36,40 @@
  * 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 "nsIdleServiceWin.h"
 #include <windows.h>
 
-NS_IMPL_ISUPPORTS2(nsIdleServiceWin, nsIIdleService, nsIdleService)
 
-bool
-nsIdleServiceWin::PollIdleTime(PRUint32 *aIdleTime)
+#ifdef WINCE
+// The last user input event time in microseconds. If there are any pending
+// native toolkit input events it returns the current time. The value is
+// compatible with PR_IntervalToMicroseconds(PR_IntervalNow()).
+// DEFINED IN widget/src/windows/nsWindow.cpp
+extern PRUint32 gLastInputEventTime;
+#endif
+
+
+NS_IMPL_ISUPPORTS1(nsIdleServiceWin, nsIIdleService)
+
+NS_IMETHODIMP
+nsIdleServiceWin::GetIdleTime(PRUint32 *aTimeDiff)
 {
 #ifndef WINCE
     LASTINPUTINFO inputInfo;
     inputInfo.cbSize = sizeof(inputInfo);
     if (!::GetLastInputInfo(&inputInfo))
-        return false;
-
-    *aIdleTime = SAFE_COMPARE_EVEN_WITH_WRAPPING(GetTickCount(), inputInfo.dwTime);
-
-    return true;
-#else
-    // On WinCE we don't pull the idle time from the system.
-    return false;
-#endif
-}
+        return NS_ERROR_FAILURE;
 
-bool
-nsIdleServiceWin::UsePollMode()
-{
-#ifndef WINCE
-    return true;
+    *aTimeDiff = SAFE_COMPARE_EVEN_WITH_WRAPPING(GetTickCount(), inputInfo.dwTime);
 #else
-    // On WinCE we don't pull the idle time from the system.
-    return false;
+    // NOTE: nowTime is not necessarily equivalent to GetTickCount() return value
+    //       we need to compare apples to apples - hence the nowTime variable
+    PRUint32 nowTime = PR_IntervalToMicroseconds(PR_IntervalNow());
+
+    *aTimeDiff = SAFE_COMPARE_EVEN_WITH_WRAPPING(nowTime, gLastInputEventTime) / 1000;
 #endif
+
+    return NS_OK;
 }
--- a/widget/src/windows/nsIdleServiceWin.h
+++ b/widget/src/windows/nsIdleServiceWin.h
@@ -17,17 +17,17 @@
  * The Original Code is mozilla.org code.
  *
  * The Initial Developer of the Original Code is
  * Gijs Kruitbosch <gijskruitbosch@gmail.com>.
  * Portions created by the Initial Developer are Copyright (C) 2007
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
- *  Gijs Kruitbosch <gijskruitbosch@gmail.com>
+ *  Gijs Kruitbosch <gijskruitbosch@gmail.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
@@ -52,15 +52,12 @@
 #endif
 
 
 class nsIdleServiceWin : public nsIdleService
 {
 public:
     NS_DECL_ISUPPORTS
 
-    bool PollIdleTime(PRUint32* aIdleTime);
-
-protected:
-    bool UsePollMode();
+    NS_IMETHOD GetIdleTime(PRUint32* idleTime);
 };
 
 #endif // nsIdleServiceWin_h__
--- a/widget/src/windows/nsNativeThemeWin.cpp
+++ b/widget/src/windows/nsNativeThemeWin.cpp
@@ -1771,32 +1771,20 @@ nsNativeThemeWin::ThemeDrawsFocusForWidg
 }
 
 PRBool
 nsNativeThemeWin::ThemeNeedsComboboxDropmarker()
 {
   return PR_TRUE;
 }
 
-nsITheme::Transparency
-nsNativeThemeWin::GetWidgetTransparency(nsIFrame* aFrame, PRUint8 aWidgetType)
+nsTransparencyMode
+nsNativeThemeWin::GetWidgetTransparency(PRUint8 aWidgetType)
 {
-  HANDLE theme = GetTheme(aWidgetType);
-  // For the classic theme we don't really have a way of knowing
-  if (!theme)
-    return eUnknownTransparency;
-
-  PRInt32 part, state;
-  nsresult rv = GetThemePartAndState(aFrame, aWidgetType, part, state);
-  // Fail conservatively
-  NS_ENSURE_SUCCESS(rv, eUnknownTransparency);
-
-  if (nsUXThemeData::isThemeBackgroundPartiallyTransparent(theme, part, state))
-    return eTransparent;
-  return eOpaque;
+  return eTransparencyOpaque;
 }
 
 /* Windows 9x/NT/2000/Classic XP Theme Support */
 
 PRBool 
 nsNativeThemeWin::ClassicThemeSupportsWidget(nsPresContext* aPresContext,
                                       nsIFrame* aFrame,
                                       PRUint8 aWidgetType)
--- a/widget/src/windows/nsNativeThemeWin.h
+++ b/widget/src/windows/nsNativeThemeWin.h
@@ -73,17 +73,17 @@ public:
                                    PRUint8 aWidgetType,
                                    nsRect* aOverflowRect);
 
   NS_IMETHOD GetMinimumWidgetSize(nsIRenderingContext* aContext, nsIFrame* aFrame,
                                   PRUint8 aWidgetType,
                                   nsIntSize* aResult,
                                   PRBool* aIsOverridable);
 
-  virtual Transparency GetWidgetTransparency(nsIFrame* aFrame, PRUint8 aWidgetType);
+  virtual nsTransparencyMode GetWidgetTransparency(PRUint8 aWidgetType);
 
   NS_IMETHOD WidgetStateChanged(nsIFrame* aFrame, PRUint8 aWidgetType, 
                                 nsIAtom* aAttribute, PRBool* aShouldRepaint);
 
   NS_IMETHOD ThemeChanged();
 
   PRBool ThemeSupportsWidget(nsPresContext* aPresContext, 
                              nsIFrame* aFrame,
--- a/widget/src/windows/nsUXThemeData.cpp
+++ b/widget/src/windows/nsUXThemeData.cpp
@@ -78,17 +78,16 @@ nsUXThemeData::GetThemeContentRectPtr ns
 nsUXThemeData::GetThemeBackgroundRegionPtr nsUXThemeData::getThemeBackgroundRegion = NULL;
 nsUXThemeData::GetThemePartSizePtr nsUXThemeData::getThemePartSize = NULL;
 nsUXThemeData::GetThemeSysFontPtr nsUXThemeData::getThemeSysFont = NULL;
 nsUXThemeData::GetThemeColorPtr nsUXThemeData::getThemeColor = NULL;
 nsUXThemeData::GetThemeMarginsPtr nsUXThemeData::getThemeMargins = NULL;
 nsUXThemeData::IsAppThemedPtr nsUXThemeData::isAppThemed = NULL;
 nsUXThemeData::GetCurrentThemeNamePtr nsUXThemeData::getCurrentThemeName = NULL;
 nsUXThemeData::GetThemeSysColorPtr nsUXThemeData::getThemeSysColor = NULL;
-nsUXThemeData::IsThemeBackgroundPartiallyTransparentPtr nsUXThemeData::isThemeBackgroundPartiallyTransparent = NULL;
 
 #if MOZ_WINSDK_TARGETVER >= MOZ_NTDDI_LONGHORN
 nsUXThemeData::DwmExtendFrameIntoClientAreaProc nsUXThemeData::dwmExtendFrameIntoClientAreaPtr = NULL;
 nsUXThemeData::DwmIsCompositionEnabledProc nsUXThemeData::dwmIsCompositionEnabledPtr = NULL;
 nsUXThemeData::DwmSetIconicThumbnailProc nsUXThemeData::dwmSetIconicThumbnailPtr = NULL;
 nsUXThemeData::DwmSetIconicLivePreviewBitmapProc nsUXThemeData::dwmSetIconicLivePreviewBitmapPtr = NULL;
 nsUXThemeData::DwmSetWindowAttributeProc nsUXThemeData::dwmSetWindowAttributePtr = NULL;
 nsUXThemeData::DwmInvalidateIconicBitmapsProc nsUXThemeData::dwmInvalidateIconicBitmapsPtr = NULL;
@@ -120,17 +119,16 @@ nsUXThemeData::Initialize()
     getThemeBackgroundRegion = (GetThemeBackgroundRegionPtr)GetProcAddress(sThemeDLL, "GetThemeBackgroundRegion");
     getThemePartSize = (GetThemePartSizePtr)GetProcAddress(sThemeDLL, "GetThemePartSize");
     getThemeSysFont = (GetThemeSysFontPtr)GetProcAddress(sThemeDLL, "GetThemeSysFont");
     getThemeColor = (GetThemeColorPtr)GetProcAddress(sThemeDLL, "GetThemeColor");
     getThemeMargins = (GetThemeMarginsPtr)GetProcAddress(sThemeDLL, "GetThemeMargins");
     isAppThemed = (IsAppThemedPtr)GetProcAddress(sThemeDLL, "IsAppThemed");
     getCurrentThemeName = (GetCurrentThemeNamePtr)GetProcAddress(sThemeDLL, "GetCurrentThemeName");
     getThemeSysColor = (GetThemeSysColorPtr)GetProcAddress(sThemeDLL, "GetThemeSysColor");
-    isThemeBackgroundPartiallyTransparent = (IsThemeBackgroundPartiallyTransparentPtr)GetProcAddress(sThemeDLL, "IsThemeBackgroundPartiallyTransparent");
   }
 #if MOZ_WINSDK_TARGETVER >= MOZ_NTDDI_LONGHORN
    sDwmDLL = ::LoadLibraryW(kDwmLibraryName);
    if(sDwmDLL) {
      dwmExtendFrameIntoClientAreaPtr = (DwmExtendFrameIntoClientAreaProc)::GetProcAddress(sDwmDLL, "DwmExtendFrameIntoClientArea");
      dwmIsCompositionEnabledPtr = (DwmIsCompositionEnabledProc)::GetProcAddress(sDwmDLL, "DwmIsCompositionEnabled");
      dwmSetIconicThumbnailPtr = (DwmSetIconicThumbnailProc)::GetProcAddress(sDwmDLL, "DwmSetIconicThumbnail");
      dwmSetIconicLivePreviewBitmapPtr = (DwmSetIconicLivePreviewBitmapProc)::GetProcAddress(sDwmDLL, "DwmSetIconicLivePreviewBitmap");
--- a/widget/src/windows/nsUXThemeData.h
+++ b/widget/src/windows/nsUXThemeData.h
@@ -148,32 +148,30 @@ public:
   typedef HRESULT (WINAPI*GetThemeMarginsPtr)(HANDLE hTheme, HDC hdc, int iPartId,
                                            int iStateid, int iPropId,
                                            LPRECT prc, MARGINS *pMargins);
   typedef BOOL (WINAPI*IsAppThemedPtr)(VOID);
   typedef HRESULT (WINAPI*GetCurrentThemeNamePtr)(LPWSTR pszThemeFileName, int dwMaxNameChars,
                                                   LPWSTR pszColorBuff, int cchMaxColorChars,
                                                   LPWSTR pszSizeBuff, int cchMaxSizeChars);
   typedef COLORREF (WINAPI*GetThemeSysColorPtr)(HANDLE hTheme, int iColorID);
-  typedef BOOL (WINAPI*IsThemeBackgroundPartiallyTransparentPtr)(HANDLE hTheme, int iPartId, int iStateId);
 
   static OpenThemeDataPtr openTheme;
   static CloseThemeDataPtr closeTheme;
   static DrawThemeBackgroundPtr drawThemeBG;
   static DrawThemeEdgePtr drawThemeEdge;
   static GetThemeContentRectPtr getThemeContentRect;
   static GetThemeBackgroundRegionPtr getThemeBackgroundRegion;
   static GetThemePartSizePtr getThemePartSize;
   static GetThemeSysFontPtr getThemeSysFont;
   static GetThemeColorPtr getThemeColor;
   static GetThemeMarginsPtr getThemeMargins;
   static IsAppThemedPtr isAppThemed;
   static GetCurrentThemeNamePtr getCurrentThemeName;
   static GetThemeSysColorPtr getThemeSysColor;
-  static IsThemeBackgroundPartiallyTransparentPtr isThemeBackgroundPartiallyTransparent;
 
 #if MOZ_WINSDK_TARGETVER >= MOZ_NTDDI_LONGHORN
   // dwmapi.dll function typedefs and declarations
   typedef HRESULT (WINAPI*DwmExtendFrameIntoClientAreaProc)(HWND hWnd, const MARGINS *pMarInset);
   typedef HRESULT (WINAPI*DwmIsCompositionEnabledProc)(BOOL *pfEnabled);
   typedef HRESULT (WINAPI*DwmSetIconicThumbnailProc)(HWND hWnd, HBITMAP hBitmap, DWORD dwSITFlags);
   typedef HRESULT (WINAPI*DwmSetIconicLivePreviewBitmapProc)(HWND hWnd, HBITMAP hBitmap, POINT *pptClient, DWORD dwSITFlags);
   typedef HRESULT (WINAPI*DwmSetWindowAttributeProc)(HWND hWnd, DWORD dwAttribute, LPCVOID pvAttribute, DWORD cbAttribute);
--- a/widget/src/windows/nsWindow.cpp
+++ b/widget/src/windows/nsWindow.cpp
@@ -135,16 +135,17 @@
 #include "nsIRegion.h"
 #include "nsIServiceManager.h"
 #include "nsIClipboard.h"
 #include "nsIMM32Handler.h"
 #include "nsILocalFile.h"
 #include "nsIFontMetrics.h"
 #include "nsIFontEnumerator.h"
 #include "nsIDeviceContext.h"
+#include "nsIdleService.h"
 #include "nsGUIEvent.h"
 #include "nsFont.h"
 #include "nsRect.h"
 #include "nsThreadUtils.h"
 #include "nsNativeCharsetUtils.h"
 #include "nsWidgetAtoms.h"
 #include "nsUnicharUtils.h"
 #include "nsCRT.h"
@@ -310,16 +311,34 @@ const int WM_HTCNAV = 0x0400 + 200;
 typedef int (__stdcall * HTCApiNavOpen)(HANDLE, int);
 typedef int (__stdcall * HTCApiNavSetMode)(HANDLE, unsigned int);
 
 HTCApiNavOpen    gHTCApiNavOpen = nsnull;
 HTCApiNavSetMode gHTCApiNavSetMode = nsnull;
 static PRBool    gCheckForHTCApi = PR_FALSE;
 #endif
 
+// The last user input event time in microseconds. If
+// there are any pending native toolkit input events
+// it returns the current time. The value is compatible
+// with PR_IntervalToMicroseconds(PR_IntervalNow()).
+#if !defined(WINCE)
+static PRUint32 gLastInputEventTime               = 0;
+#else
+PRUint32        gLastInputEventTime               = 0;
+#endif
+
+static void UpdateLastInputEventTime() {
+  gLastInputEventTime = PR_IntervalToMicroseconds(PR_IntervalNow());
+  nsCOMPtr<nsIIdleService> idleService = do_GetService("@mozilla.org/widget/idleservice;1");
+  nsIdleService* is = static_cast<nsIdleService*>(idleService.get());
+  if (is)
+    is->IdleTimeWasModified();
+}
+
 // Global user preference for disabling native theme. Used
 // in NativeWindowTheme.
 PRBool          gDisableNativeTheme               = PR_FALSE;
 
 // Global used in Show window enumerations.
 static PRBool   gWindowsVisible                   = PR_FALSE;
 
 static NS_DEFINE_CID(kCClipboardCID, NS_CLIPBOARD_CID);
@@ -417,17 +436,18 @@ nsWindow::nsWindow() : nsBaseWidget()
   InitHeapDump();
 #endif
 
 #if !defined(WINCE)
   InitTrackPointHack();
 #endif
   } // !sInstanceCount
 
-  mIdleService = nsnull;
+  // Set gLastInputEventTime to some valid number
+  gLastInputEventTime = PR_IntervalToMicroseconds(PR_IntervalNow());
 
   sInstanceCount++;
 }
 
 nsWindow::~nsWindow()
 {
   mInDtor = PR_TRUE;
 
@@ -3201,18 +3221,16 @@ PRBool nsWindow::DispatchWindowEvent(nsG
 }
 
 PRBool nsWindow::DispatchKeyEvent(PRUint32 aEventType, WORD aCharCode,
                    const nsTArray<nsAlternativeCharCode>* aAlternativeCharCodes,
                    UINT aVirtualCharCode, const MSG *aMsg,
                    const nsModifierKeyState &aModKeyState,
                    PRUint32 aFlags)
 {
-  UserActivity();
-
   nsKeyEvent event(PR_TRUE, aEventType, this);
   nsIntPoint point(0, 0);
 
   InitEvent(event, &point); // this add ref's event.widget
 
   event.flags |= aFlags;
   event.charCode = aCharCode;
   if (aAlternativeCharCodes)
@@ -3316,16 +3334,18 @@ BOOL CALLBACK nsWindow::DispatchStarvedP
 void nsWindow::DispatchPendingEvents()
 {
   if (mPainting) {
     NS_WARNING("We were asked to dispatch pending events during painting, "
                "denying since that's unsafe.");
     return;
   }
 
+  UpdateLastInputEventTime();
+
   // We need to ensure that reflow events do not get starved.
   // At the same time, we don't want to recurse through here
   // as that would prevent us from dispatching starved paints.
   static int recursionBlocker = 0;
   if (recursionBlocker++ == 0) {
     NS_ProcessPendingEvents(nsnull, PR_MillisecondsToInterval(100));
     --recursionBlocker;
   }
@@ -3374,18 +3394,16 @@ void nsWindow::RemoveMessageAndDispatchP
 
 // Deal with all sort of mouse event
 PRBool nsWindow::DispatchMouseEvent(PRUint32 aEventType, WPARAM wParam,
                                     LPARAM lParam, PRBool aIsContextMenuKey,
                                     PRInt16 aButton)
 {
   PRBool result = PR_FALSE;
 
-  UserActivity();
-
   if (!mEventCallback) {
     return result;
   }
 
   nsIntPoint eventPoint;
   eventPoint.x = GET_X_LPARAM(lParam);
   eventPoint.y = GET_Y_LPARAM(lParam);
 
@@ -5389,29 +5407,16 @@ void nsWindow::OnWindowPosChanging(LPWIN
     NS_IF_RELEASE(event.mActualBelow);
   }
   // prevent rude external programs from making hidden window visible
   if (mWindowType == eWindowType_invisible)
     info->flags &= ~SWP_SHOWWINDOW;
 }
 #endif
 
-void nsWindow::UserActivity()
-{
-  // Check if we have the idle service, if not we try to get it.
-  if (!mIdleService) {
-    mIdleService = do_GetService("@mozilla.org/widget/idleservice;1");
-  }
-
-  // Check that we now have the idle service.
-  if (mIdleService) {
-    mIdleService->ResetIdleTimeOut();
-  }
-}
-
 // Gesture event processing. Handles WM_GESTURE events.
 #if !defined(WINCE)
 PRBool nsWindow::OnGesture(WPARAM wParam, LPARAM lParam)
 {
   // Treatment for pan events which translate into scroll events:
   if (mGesture.IsPanEvent(lParam)) {
     nsMouseScrollEvent event(PR_TRUE, NS_MOUSE_PIXEL_SCROLL, this);
 
--- a/widget/src/windows/nsWindow.h
+++ b/widget/src/windows/nsWindow.h
@@ -46,17 +46,16 @@
 #define Window_h__
 
 /*
  * nsWindow - Native window management and event handling.
  */
 
 #include "nsBaseWidget.h"
 #include "nsdefs.h"
-#include "nsIdleService.h"
 #include "nsToolkit.h"
 #include "nsString.h"
 #include "nsTArray.h"
 #include "gfxWindowsSurface.h"
 #include "nsWindowDbg.h"
 #include "cairo.h"
 #ifdef CAIRO_HAS_D2D_SURFACE
 #include "gfxD2DSurface.h"
@@ -354,22 +353,16 @@ protected:
   PRBool                  OnMouseWheel(UINT msg, WPARAM wParam, LPARAM lParam, 
                                        PRBool& result, PRBool& getWheelInfo,
                                        LRESULT *aRetValue);
 #if !defined(WINCE)
   void                    OnWindowPosChanging(LPWINDOWPOS& info);
 #endif // !defined(WINCE)
 
   /**
-   * Function that registers when the user has been active (used for detecting
-   * when the user is idle).
-   */
-  void                    UserActivity();
-
-  /**
    * Methods for derived classes 
    */
   virtual PRInt32         GetHeight(PRInt32 aProposedHeight);
   virtual LPCWSTR         WindowClass();
   virtual LPCWSTR         WindowPopupClass();
   virtual DWORD           WindowStyle();
   virtual DWORD           WindowExStyle();
 
@@ -462,18 +455,16 @@ protected:
   static PRBool         sJustGotDeactivate;
   static PRBool         sJustGotActivate;
   static int            sTrimOnMinimize;
   static PRBool         sTrackPointHack;
 #ifdef MOZ_IPC
   static PRUint32       sOOPPPluginFocusEvent;
 #endif
 
-  nsCOMPtr<nsIdleService> mIdleService;
-
   // Hook Data Memebers for Dropdowns. sProcessHook Tells the
   // hook methods whether they should be processing the hook
   // messages.
   static HHOOK          sMsgFilterHook;
   static HHOOK          sCallProcHook;
   static HHOOK          sCallMouseHook;
   static PRPackedBool   sProcessHook;
   static UINT           sRollupMsgId;
--- a/widget/src/xpwidgets/nsIdleService.cpp
+++ b/widget/src/xpwidgets/nsIdleService.cpp
@@ -1,10 +1,10 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:expandtab:shiftwidth=2:tabstop=2:
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* vim:expandtab:shiftwidth=4:tabstop=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/
@@ -19,17 +19,16 @@
  * The Initial Developer of the Original Code is
  * Gijs Kruitbosch <gijskruitbosch@gmail.com>.
  * Portions created by the Initial Developer are Copyright (C) 2007
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
  *  Gijs Kruitbosch <gijskruitbosch@gmail.com>
  *  Edward Lee <edward.lee@engineering.uiuc.edu>
- *  Mike Kristoffersen <moz@mikek.dk>
  *
  * 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
@@ -43,372 +42,206 @@
 #include "nsIdleService.h"
 #include "nsString.h"
 #include "nsIObserverService.h"
 #include "nsIPrefBranch.h"
 #include "nsIPrefService.h"
 #include "nsIServiceManager.h"
 #include "nsDebug.h"
 #include "nsCOMArray.h"
-#include "prinrval.h"
 
 // observer topics used:
 #define OBSERVER_TOPIC_IDLE "idle"
 #define OBSERVER_TOPIC_BACK "back"
 #define OBSERVER_TOPIC_IDLE_DAILY "idle-daily"
-// interval in seconds between internal idle time requests.
-#define MIN_IDLE_POLL_INTERVAL 5
-#define MAX_IDLE_POLL_INTERVAL 300 /* 5 min */
-// Pref for last time (seconds since epoch) daily notification was sent.
+// interval in milliseconds between internal idle time requests
+#define MIN_IDLE_POLL_INTERVAL 5000
+#define MAX_IDLE_POLL_INTERVAL 300000
+// Pref for last time (seconds since epoch) daily notification was sent
 #define PREF_LAST_DAILY "idle.lastDailyNotification"
 
 // Use this to find previously added observers in our array:
 class IdleListenerComparator
 {
 public:
-  PRBool Equals(IdleListener a, IdleListener b) const
-  {
-    return (a.observer == b.observer) &&
-           (a.reqIdleTime == b.reqIdleTime);
-  }
+    PRBool Equals(IdleListener a, IdleListener b) const
+    {
+        return (a.observer == b.observer) &&
+               (a.reqIdleTime == b.reqIdleTime);
+    }
 };
 
-NS_IMPL_ISUPPORTS1(nsIdleServiceDaily, nsIObserver)
-
-NS_IMETHODIMP
-nsIdleServiceDaily::Observe(nsISupports *,
-                            const char *,
-                            const PRUnichar *)
-{
-  // Notify anyone who cares.
-  nsCOMPtr<nsIObserverService> observerService =
-    do_GetService("@mozilla.org/observer-service;1");
-
-  observerService->NotifyObservers(nsnull,
-                                   OBSERVER_TOPIC_IDLE_DAILY,
-                                   nsnull);
-  // Remove from idle timeout.
-  mIdleService->RemoveIdleObserver(this, MAX_IDLE_POLL_INTERVAL);
-
-  // Start timer for next search in 1 day.
-  if (mTimer) {
-    mTimer->InitWithFuncCallback(DailyCallback, this, 24*60*60*1000,
-                                                       nsITimer::TYPE_ONE_SHOT);
-  }
-
-  return NS_OK;
-}
-
-void
-nsIdleServiceDaily::Init(nsIdleService *aIdleService)
+nsIdleService::nsIdleService()
 {
-  nsresult rv;
-  mTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
-
-  mIdleService = aIdleService;
-
-  // Wait for the user to become idle, so we can do todays idle tasks.
-  DailyCallback(0, this);
-}
-
-void
-nsIdleServiceDaily::Shutdown()
-{
-  if (mTimer) {
-    mTimer->Cancel();
-    mTimer = nsnull;
-  }
-  if (mIdleService) {
-    mIdleService->RemoveIdleObserver(this, MAX_IDLE_POLL_INTERVAL);
-    mIdleService = nsnull;
-  }
-}
-
-void
-nsIdleServiceDaily::DailyCallback(nsITimer* aTimer, void* aClosure)
-{
-  nsIdleServiceDaily* me = static_cast<nsIdleServiceDaily*>(aClosure);
-
-  // The one thing we do every day is to start waiting for the user to "have
-  // a significant idle time".
-  me->mIdleService->AddIdleObserver(me, MAX_IDLE_POLL_INTERVAL);
-}
-
-nsIdleService::nsIdleService() : mLastIdleReset(0), mLastHandledActivity(0)
-{
-  mDailyIdle = new nsIdleServiceDaily;
-  if (mDailyIdle) {
-    mDailyIdle->Init(this);
-  }
+    // Immediately create a timer to handle the daily notification
+    mTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
+    StartTimer(MAX_IDLE_POLL_INTERVAL);
 }
 
 nsIdleService::~nsIdleService()
 {
-  StopTimer();
-  mDailyIdle->Shutdown();
+    StopTimer();
 }
 
 NS_IMETHODIMP
 nsIdleService::AddIdleObserver(nsIObserver* aObserver, PRUint32 aIdleTime)
 {
-  NS_ENSURE_ARG_POINTER(aObserver);
-  NS_ENSURE_ARG(aIdleTime);
+    NS_ENSURE_ARG_POINTER(aObserver);
+    NS_ENSURE_ARG(aIdleTime);
 
-  // Put the time + observer in a struct we can keep:
-  IdleListener listener(aObserver, aIdleTime);
+    // Put the time + observer in a struct we can keep:
+    IdleListener listener(aObserver, aIdleTime * 1000);
 
-  if (!mArrayListeners.AppendElement(listener)) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
+    if (!mArrayListeners.AppendElement(listener))
+        return NS_ERROR_OUT_OF_MEMORY;
 
-  // Create our timer callback if it's not there already.
-  if (!mTimer) {
-    nsresult rv;
-    mTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
-    NS_ENSURE_SUCCESS(rv, rv);
-  }
+    // Create our timer callback if it's not there already
+    if (!mTimer) {
+        nsresult rv;
+        mTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
+        NS_ENSURE_SUCCESS(rv, rv);
+    }
 
-  // Make sure our observer goes into 'idle' immediately if applicable.
-  CheckAwayState(false);
+    // Make sure our observer goes into 'idle' immediately if applicable.
+    CheckAwayState();
 
-  return NS_OK;
+    return NS_OK;
 }
 
 NS_IMETHODIMP
 nsIdleService::RemoveIdleObserver(nsIObserver* aObserver, PRUint32 aTime)
 {
-  NS_ENSURE_ARG_POINTER(aObserver);
-  NS_ENSURE_ARG(aTime);
-  IdleListener listener(aObserver, aTime);
-
-  // Find the entry and remove it:
-  IdleListenerComparator c;
-  if (mArrayListeners.RemoveElement(listener, c)) {
-    if (mArrayListeners.IsEmpty()) {
-      StopTimer();
-    }
-    return NS_OK;
-  }
-
-  // If we get here, we haven't removed anything:
-  return NS_ERROR_FAILURE;
-}
-
-void
-nsIdleService::ResetIdleTimeOut()
-{
-  mLastIdleReset = PR_IntervalToSeconds(PR_IntervalNow());
-  // A zero in mLastIdleReset indicates that this function has never been
-  // called.
-  if (!mLastIdleReset) mLastIdleReset = 1;
-
-  // Now check if this changes anything
-  CheckAwayState(true);
-}
-
-NS_IMETHODIMP
-nsIdleService::GetIdleTime(PRUint32* idleTime)
-{
-  // Check sanity of in parameter.
-  if (!idleTime) {
-    return NS_ERROR_NULL_POINTER;
-  }
-
-  // Polled idle time in ms
-  PRUint32 polledIdleTimeMS;
-  bool polledIdleTimeIsValid;
-
-  polledIdleTimeIsValid = PollIdleTime(&polledIdleTimeMS);
+    NS_ENSURE_ARG_POINTER(aObserver);
+    NS_ENSURE_ARG(aTime);
+    IdleListener listener(aObserver, aTime * 1000);
 
-  // If we don't have any valid data, then we are not in idle - pr. definition.
-  if (!polledIdleTimeIsValid && 0 == mLastIdleReset) {
-    *idleTime = 0;
-    return NS_OK;
-  }
-
-  // If we never got a reset, just return the pulled time.
-  if (0 == mLastIdleReset) {
-    *idleTime = polledIdleTimeMS;
-    return NS_OK;
-  }
-
-  // timeSinceReset is in seconds.
-  PRUint32 timeSinceReset =
-    PR_IntervalToSeconds(PR_IntervalNow()) - mLastIdleReset;
+    // Find the entry and remove it:
+    IdleListenerComparator c;
+    if (mArrayListeners.RemoveElement(listener, c)) {
+        if (mArrayListeners.IsEmpty()) {
+            StopTimer();
+        }
+        return NS_OK;
+    }
 
-  // If we did't get pulled data, return the time since last idle reset.
-  if (!polledIdleTimeIsValid) {
-    // We need to convert to ms before returning the time.
-    *idleTime = timeSinceReset * 1000;
-    return NS_OK;
-  }
-
-  // Otherwise return the shortest time detected (in ms).
-  *idleTime = NS_MIN(timeSinceReset * 1000, polledIdleTimeMS);
-
-  return NS_OK;
-}
-
-
-bool
-nsIdleService::PollIdleTime(PRUint32* /*aIdleTime*/)
-{
-  // Default behavior is not to have the ability to poll an idle time.
-  return false;
-}
-
-bool
-nsIdleService::UsePollMode()
-{
-  PRUint32 dummy;
-  return PollIdleTime(&dummy);
+    // If we get here, we haven't removed anything:
+    return NS_ERROR_FAILURE;
 }
 
 void
 nsIdleService::IdleTimerCallback(nsITimer* aTimer, void* aClosure)
 {
-  static_cast<nsIdleService*>(aClosure)->CheckAwayState(false);
+    static_cast<nsIdleService*>(aClosure)->CheckAwayState();
 }
 
 void
-nsIdleService::CheckAwayState(bool aNoTimeReset)
+nsIdleService::CheckAwayState()
 {
-  /**
-   * Find our last detected idle time (it's important this happens before the
-   * call below to GetIdleTime, as we use the two values to detect if there
-   * has been user activity since the last time we were here).
-   */
-  PRUint32 curTime = PR_Now() / PR_USEC_PER_SEC;
-  PRUint32 lastTime = curTime - mLastHandledActivity;
+    // Get the idle time.
+    PRUint32 idleTime;
+    if (NS_FAILED(GetIdleTime(&idleTime)))
+        return;
+
+    // Dynamically figure out what's the best time to poll again
+    PRUint32 nextPoll = MAX_IDLE_POLL_INTERVAL;
 
-  // Get the idle time (in seconds).
-  PRUint32 idleTime;
-  if (NS_FAILED(GetIdleTime(&idleTime))) {
-    return;
-  }
+    nsAutoString timeStr;
+    timeStr.AppendInt(idleTime);
 
-  // GetIdleTime returns the time in ms, internally we only calculate in s.
-  idleTime /= 1000;
+    // Change state first, and save observers that need notification, so
+    // removing things will always work without upsetting notifications.
+    nsCOMArray<nsIObserver> idleListeners;
+    nsCOMArray<nsIObserver> hereListeners;
+    for (PRUint32 i = 0; i < mArrayListeners.Length(); i++) {
+        IdleListener& curListener = mArrayListeners.ElementAt(i);
+
+        // Assume the next best poll time is the time left before idle
+        PRUint32 curPoll = curListener.reqIdleTime - idleTime;
 
-  // We need a text string to send with any state change events.
-  nsAutoString timeStr;
-  timeStr.AppendInt(idleTime);
-
-  // Set the time for last user activity.
-  mLastHandledActivity = curTime - idleTime;
+        // For listeners that haven't gone idle yet:
+        if (!curListener.isIdle) {
+            // User has been idle longer than the listener expects
+            if (idleTime >= curListener.reqIdleTime) {
+                curListener.isIdle = PR_TRUE;
+                idleListeners.AppendObject(curListener.observer);
 
-  /**
-   * Now, if the idle time, is less than what we expect, it means the
-   * user was active since last time that we checked.
-   */
-  nsCOMArray<nsIObserver> notifyList;
+                // We'll need to poll frequently to notice if the user is back
+                curPoll = MIN_IDLE_POLL_INTERVAL;
+            }
+        }
+        // For listeners that are waiting for the user to come back:
+        else {
+            // Short idle time means the user is back
+            if (idleTime < curListener.reqIdleTime) {
+                curListener.isIdle = PR_FALSE;
+                hereListeners.AppendObject(curListener.observer);
+            }
+            // Keep polling frequently to detect if the user comes back
+            else {
+                curPoll = MIN_IDLE_POLL_INTERVAL;
+            }
+        }
 
-  if (lastTime > idleTime) {
-    // Loop trough all listeners, and find any that have detected idle.
-    for (PRUint32 i = 0; i < mArrayListeners.Length(); i++) {
-      IdleListener& curListener = mArrayListeners.ElementAt(i);
-
-      if (curListener.isIdle) {
-        notifyList.AppendObject(curListener.observer);
-        curListener.isIdle = false;
-      }
+        // Take the shortest poll time needed for each listener
+        nextPoll = PR_MIN(nextPoll, curPoll);
     }
 
-    // Send the "non-idle" events.
-    for (PRInt32 i = 0; i < notifyList.Count(); i++) {
-      notifyList[i]->Observe(this, OBSERVER_TOPIC_BACK, timeStr.get());
+    // Notify listeners gone idle:
+    for (PRInt32 i = 0; i < idleListeners.Count(); i++) {
+        idleListeners[i]->Observe(this, OBSERVER_TOPIC_IDLE, timeStr.get());
     }
-  }
-
-  /**
-   * Now we need to check for listeners that have expired, and while we are
-   * looping through all the elements, we will also calculate when, if ever
-   * the next one will need to be notified.
-   */
-
-  // Clean up the list, so it's ready for the next iteration.
-  notifyList.Clear();
 
-  // Bail out if we don't need to calculate new times.
-  if (aNoTimeReset) {
-    return;
-  }
-  /**
-   * Placet to store the wait time to the next notification, note that
-   * PR_UINT32_MAX means no-one are listening (or that they have such a big
-   * delay that it doesn't matter).
-   */
-  PRUint32 nextWaitTime = PR_UINT32_MAX;
-
-  /**
-   * Place to remember if there are any listeners that are in the idle state,
-   * if there are, we need to poll frequently in a polling environment to detect
-   * when the user becomes active again.
-   */
-  bool anyOneIdle = false;
-
-  for (PRUint32 i = 0; i < mArrayListeners.Length(); i++) {
-    IdleListener& curListener = mArrayListeners.ElementAt(i);
-
-    // We are only interested in items, that are not in the idle state.
-    if (!curListener.isIdle) {
-      // If they have an idle time smaller than the actual idle time.
-      if (curListener.reqIdleTime <= idleTime) {
-        // then add the listener to the list of listeners that should be
-        // notified.
-        notifyList.AppendObject(curListener.observer);
-        // This listener is now idle.
-        curListener.isIdle = true;
-      } else {
-        // If it hasn't expired yet, then we should note the time when it should
-        // expire.
-        nextWaitTime = PR_MIN(nextWaitTime, curListener.reqIdleTime);
-      }
+    // Notify listeners that came back:
+    for (PRInt32 i = 0; i < hereListeners.Count(); i++) {
+        hereListeners[i]->Observe(this, OBSERVER_TOPIC_BACK, timeStr.get());
     }
 
-    // Remember if anyone becomes idle (it's safe to do this as a binary compare
-    // as we are or'ing).
-    anyOneIdle |= curListener.isIdle;
-  }
+    // The user has been idle for a while, so try sending the daily idle
+    if (idleTime >= MAX_IDLE_POLL_INTERVAL) {
+        nsCOMPtr<nsIPrefBranch> pref = do_GetService(NS_PREFSERVICE_CONTRACTID);
+        if (pref) {
+            // Get the current number of seconds since epoch
+            PRUint32 nowSec = PR_Now() / PR_USEC_PER_SEC;
 
-  // In order to find when the next idle event should time out, we need to
-  // subtract the time we should wait, from the time that has already passed.
-  nextWaitTime -= idleTime;
+            // Get the last notification time; default to 0 for the first time
+            PRInt32 lastDaily = 0;
+            pref->GetIntPref(PREF_LAST_DAILY, &lastDaily);
 
-  // Notify all listeners that just timed out.
-  for (PRInt32 i = 0; i < notifyList.Count(); i++) {
-    notifyList[i]->Observe(this, OBSERVER_TOPIC_IDLE, timeStr.get());
-  }
+            // Has it been a day (24*60*60 seconds) since the last notification
+            if (nowSec - lastDaily > 86400) {
+                nsCOMPtr<nsIObserverService> observerService =
+                    do_GetService("@mozilla.org/observer-service;1");
+                observerService->NotifyObservers(nsnull,
+                                                 OBSERVER_TOPIC_IDLE_DAILY,
+                                                 nsnull);
 
-  // If we are in poll mode, we need to poll for activity if anyone are idle,
-  // otherwise we can wait polling until they would expire.
-  if (UsePollMode() &&
-      anyOneIdle &&
-      nextWaitTime > MIN_IDLE_POLL_INTERVAL) {
-    nextWaitTime = MIN_IDLE_POLL_INTERVAL;
-  }
+                pref->SetIntPref(PREF_LAST_DAILY, nowSec);
+            }
+        }
+    }
 
-  // Start the timer if there is anything to wait for.
-  if (PR_UINT32_MAX != nextWaitTime) {
-    StartTimer(nextWaitTime);
-  }
+    // Restart the timer with the dynamically optimized poll time
+    StartTimer(nextPoll);
 }
 
 void
 nsIdleService::StartTimer(PRUint32 aDelay)
 {
-  if (mTimer) {
-    StopTimer();
-    if (aDelay) {
-      mTimer->InitWithFuncCallback(IdleTimerCallback, this, aDelay*1000,
-                                   nsITimer::TYPE_ONE_SHOT);
+    if (mTimer) {
+        StopTimer();
+        mTimer->InitWithFuncCallback(IdleTimerCallback, this, aDelay,
+                                     nsITimer::TYPE_ONE_SHOT);
     }
-  }
 }
 
 void
 nsIdleService::StopTimer()
 {
-  if (mTimer) {
-    mTimer->Cancel();
-  }
+    if (mTimer) {
+        mTimer->Cancel();
+    }
 }
 
+void
+nsIdleService::IdleTimeWasModified()
+{
+    StartTimer(0);
+}
--- a/widget/src/xpwidgets/nsIdleService.h
+++ b/widget/src/xpwidgets/nsIdleService.h
@@ -1,10 +1,10 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:expandtab:shiftwidth=2:tabstop=2:
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* vim:expandtab:shiftwidth=4:tabstop=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/
@@ -17,18 +17,17 @@
  * The Original Code is mozilla.org code.
  *
  * The Initial Developer of the Original Code is
  * Gijs Kruitbosch <gijskruitbosch@gmail.com>.
  * Portions created by the Initial Developer are Copyright (C) 2007
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
- *  Gijs Kruitbosch <gijskruitbosch@gmail.com>
- *  Mike Kristoffersen <moz@mikek.dk>
+ *  Gijs Kruitbosch <gijskruitbosch@gmail.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
@@ -42,175 +41,48 @@
 #ifndef nsIdleService_h__
 #define nsIdleService_h__
 
 #include "nsIIdleService.h"
 #include "nsCOMPtr.h"
 #include "nsITimer.h"
 #include "nsTArray.h"
 #include "nsIObserver.h"
-#include "nsIIdleService.h"
 
-/**
- * Class we can use to store an observer with its associated idle time
- * requirement and whether or not the observer thinks it's "idle".
- */
+// Class we can use to store an observer with its associated idle time
+// requirement and whether or not the observer thinks it's "idle".
 class IdleListener {
 public:
-  nsCOMPtr<nsIObserver> observer;
-  PRUint32 reqIdleTime;
-  bool isIdle;
-
-  IdleListener(nsIObserver* obs, PRUint32 reqIT, bool aIsIdle = false) :
-    observer(obs), reqIdleTime(reqIT), isIdle(aIsIdle) {}
-  ~IdleListener() {}
-};
-
-// This one will be declared later.
-class nsIdleService;
-
-/**
- * Class to handle the daily idle timer.
- */
-class nsIdleServiceDaily : public nsIObserver
-{
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIOBSERVER
+    nsCOMPtr<nsIObserver> observer;
+    PRUint32 reqIdleTime;
+    PRBool isIdle;
 
-  /**
-   * Function to call to tell the daily idle service that the idle service
-   * is ready.
-   *
-   * @param aIdleService
-   *        Pointer to the idle service.
-   */
-  void Init(nsIdleService *aIdleService);
-
-  /**
-   * This function will make this class release its allocated resources (its
-   * idle timer and/or its normal timer).
-   */
-  void Shutdown();
-
-private:
-  /**
-   * @note This is a normal pointer, or the idle service could keep it self
-   * alive.
-   */
-  nsIdleService *mIdleService;
-
-  /**
-   * Place to hold the timer used by this class to determine when a day has
-   * passed, after that it will wait for idle time to be detected.
-   */
-  nsCOMPtr<nsITimer> mTimer;
-
-  /**
-   * Function that is called back once a day.
-   */
-  static void DailyCallback(nsITimer* aTimer, void* aClosure);
+    IdleListener(nsIObserver* obs, PRUint32 reqIT, PRBool aIsIdle = PR_FALSE) :
+        observer(obs), reqIdleTime(reqIT), isIdle(aIsIdle) {}
+    ~IdleListener() {}
 };
 
 class nsIdleService : public nsIIdleService
 {
 public:
-  nsIdleService();
+    nsIdleService();
 
-  // Implement nsIIdleService methods.
-  NS_IMETHOD AddIdleObserver(nsIObserver* aObserver, PRUint32 aIdleTime);
-  NS_IMETHOD RemoveIdleObserver(nsIObserver* aObserver, PRUint32 aIdleTime);
-  NS_IMETHOD GetIdleTime(PRUint32* idleTime);
+    // Implement nsIIdleService methods, but not the idleTime getter,
+    // which is platform-dependent.
+    NS_IMETHOD AddIdleObserver(nsIObserver* aObserver, PRUint32 aIdleTime);
+    NS_IMETHOD RemoveIdleObserver(nsIObserver* aObserver, PRUint32 aIdleTime);
 
-  void ResetIdleTimeOut();
+    static void IdleTimerCallback(nsITimer* aTimer, void* aClosure);
+    
+    void IdleTimeWasModified();
 
 protected:
-  ~nsIdleService();
-
-  /**
-   * If there is a platform specific function to poll the system idel time
-   * then that must be returned in this function, and the function MUST return
-   * true, otherwise then the function should be left unimplemented or made
-   * to return false (this can also be used for systems where it depends on
-   * the configuration of the system if the idle time can be determined)
-   *
-   * @param aIdleTime
-   *        The idle time in ms.
-   *
-   * @return true if the idle time could be polled, false otherwise.
-   *
-   * @note The time returned by this function can be different than the one
-   *       returned by GetIdleTime, as that is corrected by any calls to
-   *       ResetIdleTimeOut(), unless you overwrite that function too...
-   */
-  virtual bool PollIdleTime(PRUint32* aIdleTime);
-
-  /**
-   * Function that determines if we are in poll mode or not.
-   *
-   * @return true if polling is supported, false otherwise.
-   */
-  virtual bool UsePollMode();
-
-  /**
-   * Send expired events and start timers.
-   *
-   * @param aNoTimeReset
-   *        If true new times will not be calculated.
-   */
-  void CheckAwayState(bool aNoTimeReset);
+    void CheckAwayState();
+    ~nsIdleService();
 
 private:
-  /**
-   * Start the internal timer, restart it if it is allready running.
-   *
-   * @param aDelay
-   *        The time in seconds that should pass before the next timeout.
-   */
-
-  void StartTimer(PRUint32 aDelay);
-
-  /**
-   * Stop the internal timer, it is safe to call this function, even when
-   * there are no timers running.
-   */
-  void StopTimer();
-
-  /**
-   * mTimer holds the internal timer used by this class to detect when to poll
-   * for idle time, when to check if idle timers should expire etc.
-   */
-  nsCOMPtr<nsITimer> mTimer;
-
-  /**
-   * Array of listeners that wants to be notified about idle time.
-   */
-  nsTArray<IdleListener> mArrayListeners;
-
-  /**
-   * Object keeping track of the daily idle thingy.
-   */
-  nsCOMPtr<nsIdleServiceDaily> mDailyIdle;
-
-  /**
-   * Contains the time of the last idle reset or 0 if there haven't been a
-   * reset.
-   * <p>
-   * Time is kept in seconds since the epoch at midnight, January 1, 1970 UTC.
-   */
-  PRUint32 mLastIdleReset;
-
-  /**
-   * The time since the last handled activity (which might be different than
-   * mLastIdleReset, since the activity that reset the idle timer could just
-   * have happend, and not handled yet).
-   * <p>
-   * Time is kept in seconds since the epoch at midnight, January 1, 1970 UTC.
-   */
-  PRUint32 mLastHandledActivity;
-
-  /**
-   * Callback function that is called when the internal timer expires.
-   */
-  static void IdleTimerCallback(nsITimer* aTimer, void* aClosure);
+    void StartTimer(PRUint32 aDelay);
+    void StopTimer();
+    nsCOMPtr<nsITimer> mTimer;
+    nsTArray<IdleListener> mArrayListeners;
 };
 
 #endif // nsIdleService_h__
--- a/widget/tests/test_bug343416.xul
+++ b/widget/tests/test_bug343416.xul
@@ -93,27 +93,25 @@ try
     idleService = Components.classes[nsIISCID].getService(nsIIdleService);
 }
 catch (ex)
 {}
 
 ok(idleService, "nsIIdleService should exist and be implemented on all tier 1 platforms.");
 
 var idleTime = null;
-var gotIdleTime = false;
 try
 {
     idleTime = idleService.idleTime;
-    gotIdleTime = true;
 }
 catch (ex)
 {}
 
-ok (gotIdleTime, "Getting the idle time should not fail " +
-                 "in normal circumstances on any tier 1 platform.");
+ok (idleTime, "Getting the idle time should not fail " +
+              "in normal circumstances on any tier 1 platform.");
 
 // Now we set up a timeout to sanity-test the idleTime after 5 seconds
 setTimeout(testIdleTime, 5000);
 var startTimeStamp = Date.now();
 
 // Now we add the listener:
 var newIdleSeconds = Math.floor(idleTime / 1000) + 6;
 var addedObserver = false;
@@ -146,38 +144,31 @@ try
 }
 catch (ex)
 {}
 
 ok(removedObserver, "The nsIIdleService should allow us to remove the observer just once.");
 
 function testIdleTime()
 {
-    var gotIdleTime = false
     try
     {
         var newIdleTime = idleService.idleTime;
-    gotIdleTime = true
     }
     catch (ex)
     {}
-    ok(gotIdleTime, "Getting the idle time should not fail " +
+    ok(newIdleTime, "Getting the idle time should not fail " +
                     "in normal circumstances on any tier 1 platform.");
     // Get the time difference, remove the approx. 5 seconds that we've waited,
     // should be very close to 0 left.
     var timeDiff = Math.abs((newIdleTime - idleTime) -
                             (Date.now() - startTimeStamp));
-
-    var timePassed = Date.now() - startTimeStamp;
-    var idleTimeDiff = newIdleTime - idleTime;
-    // 1 second leniency.
-    ok(timeDiff < 1000, "The idle time should have increased by roughly the " +
-                        "amount of time it took for the timeout to fire. " +
-                        "You didn't touch the mouse or keyboard during the" +
-                        "test did you?");
+    // 0.5 second leniency.
+    ok(timeDiff < 500, "The idle time should have increased by roughly the " +
+                       "amount of time it took for the timeout to fire.");
     finishedTimeoutOK = true;
 }
 
 // make sure we still exit when the listener and/or setTimeout don't fire:
 var testBailout = setTimeout(finishThisTest, 12000);
 var finishedTimeoutOK = false, finishedListenerOK = false;
 function finishThisTest()
 {