Merge mozilla-central to build-system.
authorMitchell Field <mitchell.field@live.com.au>
Sat, 16 Apr 2011 00:27:18 +1000
changeset 68302 62dcc1af0d1b12c02487dd5c8263fde95b8efb3f
parent 68301 9387b78736542a213584405d6a5c67fd9d3a1650 (current diff)
parent 68182 40035327893360561bcaed071ac5f6eab83edac4 (diff)
child 68303 c5c1cac00a06b9030cafd3caa2f0ea0a9949e39c
push id19579
push usermitchell.field@live.com.au
push dateTue, 19 Apr 2011 14:40:50 +0000
treeherdermozilla-central@2b974a79020f [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone6.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge mozilla-central to build-system.
accessible/tests/mochitest/tree/test_colorpicker.xul
accessible/tests/mochitest/tree/test_menu.xul
build/util.py
configure.in
dom/interfaces/core/nsIDOMDOMConfiguration.idl
gfx/src/nsIFontMetrics.h
gfx/src/nsIRenderingContext.h
gfx/src/nsIThebesFontMetrics.h
gfx/src/nsThebesFontMetrics.cpp
gfx/src/nsThebesFontMetrics.h
gfx/src/nsThebesRenderingContext.cpp
gfx/src/nsThebesRenderingContext.h
js/src/configure.in
mobile/installer/wince/Makefile.in
mobile/installer/wince/Setup.cpp
mobile/installer/wince/Setup.def
xpcom/typelib/xpt/tools/xpt_dump.c
xpcom/typelib/xpt/tools/xpt_link.c
--- a/accessible/src/base/nsAccessibilityAtomList.h
+++ b/accessible/src/base/nsAccessibilityAtomList.h
@@ -59,17 +59,16 @@
 ACCESSIBILITY_ATOM(button, "button")
 ACCESSIBILITY_ATOM(checkbox, "checkbox")
 ACCESSIBILITY_ATOM(col, "col")
 ACCESSIBILITY_ATOM(_empty, "")
 ACCESSIBILITY_ATOM(_false, "false")
 ACCESSIBILITY_ATOM(image, "image")
 ACCESSIBILITY_ATOM(menu, "menu")
 ACCESSIBILITY_ATOM(menuButton, "menu-button")
-ACCESSIBILITY_ATOM(menugenerated, "menugenerated")
 ACCESSIBILITY_ATOM(multiple, "multiple")
 ACCESSIBILITY_ATOM(open, "open")
 ACCESSIBILITY_ATOM(password, "password")
 ACCESSIBILITY_ATOM(radio, "radio")
 ACCESSIBILITY_ATOM(reset, "reset")
 ACCESSIBILITY_ATOM(row, "row")
 ACCESSIBILITY_ATOM(submit, "submit")
 ACCESSIBILITY_ATOM(_true, "true")
--- a/accessible/src/base/nsCoreUtils.cpp
+++ b/accessible/src/base/nsCoreUtils.cpp
@@ -756,57 +756,16 @@ nsCoreUtils::IsColumnHidden(nsITreeColum
 {
   nsCOMPtr<nsIDOMElement> element;
   aColumn->GetElement(getter_AddRefs(element));
   nsCOMPtr<nsIContent> content = do_QueryInterface(element);
   return content->AttrValueIs(kNameSpaceID_None, nsAccessibilityAtoms::hidden,
                               nsAccessibilityAtoms::_true, eCaseMatters);
 }
 
-void
-nsCoreUtils::GeneratePopupTree(nsIContent *aContent, PRBool aIsAnon)
-{
-  // Set menugenerated="true" on the menupopup node to generate the sub-menu
-  // items if they have not been generated.
-
-  nsCOMPtr<nsIDOMNodeList> list;
-  if (aIsAnon) {    
-    nsIDocument* document = aContent->GetCurrentDoc();
-    if (document)
-      document->GetXBLChildNodesFor(aContent, getter_AddRefs(list));
-
-  } else {
-    list = aContent->GetChildNodesList();
-  }
-
-  PRUint32 length = 0;
-  if (!list || NS_FAILED(list->GetLength(&length)))
-    return;
-
-  for (PRUint32 idx = 0; idx < length; idx++) {
-    nsCOMPtr<nsIDOMNode> childNode;
-    list->Item(idx, getter_AddRefs(childNode));
-    nsCOMPtr<nsIContent> child(do_QueryInterface(childNode));
-
-    PRBool isPopup = child->NodeInfo()->Equals(nsAccessibilityAtoms::menupopup,
-                                               kNameSpaceID_XUL) ||
-                     child->NodeInfo()->Equals(nsAccessibilityAtoms::panel,
-                                               kNameSpaceID_XUL);
-    if (isPopup && !child->AttrValueIs(kNameSpaceID_None,
-                                       nsAccessibilityAtoms::menugenerated,
-                                       nsAccessibilityAtoms::_true,
-                                       eCaseMatters)) {
-
-      child->SetAttr(kNameSpaceID_None, nsAccessibilityAtoms::menugenerated,
-                     NS_LITERAL_STRING("true"), PR_TRUE);
-      return;
-    }
-  }
-}
-
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessibleDOMStringList
 ////////////////////////////////////////////////////////////////////////////////
 
 NS_IMPL_ISUPPORTS1(nsAccessibleDOMStringList, nsIDOMDOMStringList)
 
 NS_IMETHODIMP
--- a/accessible/src/base/nsCoreUtils.h
+++ b/accessible/src/base/nsCoreUtils.h
@@ -362,26 +362,16 @@ public:
   /**
    * Return true if the given node is table header element.
    */
   static PRBool IsHTMLTableHeader(nsIContent *aContent)
   {
     return aContent->NodeInfo()->Equals(nsAccessibilityAtoms::th) ||
       aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::scope);
   }
-
-  /**
-   * Generates frames for popup subtree.
-   *
-   * @param aContent [in] DOM node containing the menupopup element as a child
-   * @param aIsAnon  [in] specifies whether popup should be searched inside of
-   *                  anonymous or explicit content
-   */
-  static void GeneratePopupTree(nsIContent *aContent,
-                                PRBool aIsAnon = PR_FALSE);
 };
 
 
 /**
  * nsIDOMDOMStringList implementation.
  */
 class nsAccessibleDOMStringList : public nsIDOMDOMStringList
 {
--- a/accessible/src/base/nsTextAttrs.cpp
+++ b/accessible/src/base/nsTextAttrs.cpp
@@ -39,17 +39,17 @@
 #include "nsTextAttrs.h"
 
 #include "nsAccUtils.h"
 #include "nsCoreUtils.h"
 #include "nsHyperTextAccessibleWrap.h"
 
 #include "gfxFont.h"
 #include "gfxUserFontSet.h"
-#include "nsIThebesFontMetrics.h"
+#include "nsFontMetrics.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // Constants and structures
 
 /**
  * Item of the gCSSTextAttrsMap map.
  */
 struct nsCSSTextAttrMapItem
@@ -527,23 +527,22 @@ nsFontWeightTextAttr::GetFontWeight(nsIF
 {
   // nsFont::width isn't suitable here because it's necessary to expose real
   // value of font weight (used font might not have some font weight values).
   nsStyleFont* styleFont =
     (nsStyleFont*)(aFrame->GetStyleDataExternal(eStyleStruct_Font));
 
   gfxUserFontSet *fs = aFrame->PresContext()->GetUserFontSet();
 
-  nsCOMPtr<nsIFontMetrics> fm;
+  nsRefPtr<nsFontMetrics> fm;
   aFrame->PresContext()->DeviceContext()->
     GetMetricsFor(styleFont->mFont, aFrame->GetStyleVisibility()->mLanguage,
                   fs, *getter_AddRefs(fm));
 
-  nsCOMPtr<nsIThebesFontMetrics> tfm = do_QueryInterface(fm);
-  gfxFontGroup *fontGroup = tfm->GetThebesFontGroup();
+  gfxFontGroup *fontGroup = fm->GetThebesFontGroup();
   gfxFont *font = fontGroup->GetFontAt(0);
 
   // When there doesn't exist a bold font in the family and so the rendering of
   // a non-bold font face is changed so that the user sees what looks like a
   // bold font, i.e. synthetic bolding is used. IsSyntheticBold method is only
   // needed on Mac, but it is "safe" to use on all platforms.  (For non-Mac
   // platforms it always return false.)
   if (font->IsSyntheticBold())
--- a/accessible/src/html/nsHTMLFormControlAccessible.cpp
+++ b/accessible/src/html/nsHTMLFormControlAccessible.cpp
@@ -417,16 +417,19 @@ nsHTMLTextFieldAccessible::GetNameIntern
   // text inputs and textareas might have useful placeholder text
   mContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::placeholder, aName);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP nsHTMLTextFieldAccessible::GetValue(nsAString& _retval)
 {
+  if (IsDefunct())
+    return NS_ERROR_FAILURE;
+
   if (NativeState() & states::PROTECTED)    // Don't return password text!
     return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIDOMHTMLTextAreaElement> textArea(do_QueryInterface(mContent));
   if (textArea) {
     return textArea->GetValue(_retval);
   }
   
--- a/accessible/src/html/nsHyperTextAccessible.cpp
+++ b/accessible/src/html/nsHyperTextAccessible.cpp
@@ -53,17 +53,16 @@
 #include "nsPIDOMWindow.h"        
 #include "nsIDOMDocumentView.h"
 #include "nsIDOMRange.h"
 #include "nsIDOMNSRange.h"
 #include "nsIDOMWindowInternal.h"
 #include "nsIDOMXULDocument.h"
 #include "nsIEditingSession.h"
 #include "nsIEditor.h"
-#include "nsIFontMetrics.h"
 #include "nsIFrame.h"
 #include "nsFrameSelection.h"
 #include "nsILineIterator.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIPlaintextEditor.h"
 #include "nsIScrollableFrame.h"
 #include "nsISelection2.h"
 #include "nsISelectionPrivate.h"
--- a/accessible/src/msaa/nsTextAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsTextAccessibleWrap.cpp
@@ -31,29 +31,24 @@
  * 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 ***** */
 
-// NOTE: alphabetically ordered
 #include "nsTextAccessibleWrap.h"
 #include "ISimpleDOMText_i.c"
 
 #include "nsCoreUtils.h"
 #include "nsDocAccessible.h"
-
-#include "nsIThebesFontMetrics.h"
 #include "nsIFrame.h"
+#include "nsFontMetrics.h"
 #include "nsPresContext.h"
-#include "nsIPresShell.h"
-#include "nsIRenderingContext.h"
-#include "nsIComponentManager.h"
 
 #include "gfxFont.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsTextAccessibleWrap Accessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsTextAccessibleWrap::
@@ -255,26 +250,24 @@ STDMETHODIMP nsTextAccessibleWrap::get_f
 __try {
   *aFontFamily = NULL;
 
   nsIFrame* frame = GetFrame();
   if (!frame) {
     return E_FAIL;
   }
 
-  nsCOMPtr<nsIFontMetrics> fm;
+  nsRefPtr<nsFontMetrics> fm;
   frame->PresContext()->DeviceContext()->
     GetMetricsFor(frame->GetStyleFont()->mFont,
                   frame->GetStyleVisibility()->mLanguage,
                   frame->PresContext()->GetUserFontSet(),
                   *getter_AddRefs(fm));
 
-  nsCOMPtr<nsIThebesFontMetrics> tfm = do_QueryInterface(fm);
-  const nsString& name = tfm->GetThebesFontGroup()->GetFontAt(0)->GetName();
-
+  const nsString& name = fm->GetThebesFontGroup()->GetFontAt(0)->GetName();
   if (name.IsEmpty())
     return S_FALSE;
 
   *aFontFamily = ::SysAllocStringLen(name.get(), name.Length());
   if (!*aFontFamily)
     return E_OUTOFMEMORY;
 
 } __except(FilterA11yExceptions(::GetExceptionCode(),
--- a/accessible/src/msaa/nsTextAccessibleWrap.h
+++ b/accessible/src/msaa/nsTextAccessibleWrap.h
@@ -39,17 +39,17 @@
 #ifndef _nsTextAccessibleWrap_H_
 #define _nsTextAccessibleWrap_H_
 
 #include "nsTextAccessible.h"
 #include "ISimpleDOMText.h"
 #include "nsRect.h"
 
 class nsIFrame;
-class nsIRenderingContext;
+class nsRenderingContext;
 
 class nsTextAccessibleWrap : public nsTextAccessible, 
                              public ISimpleDOMText
 {
 public:
   nsTextAccessibleWrap(nsIContent *aContent, nsIWeakReference *aShell);
   virtual ~nsTextAccessibleWrap() {}
 
--- a/accessible/src/xul/nsXULColorPickerAccessible.cpp
+++ b/accessible/src/xul/nsXULColorPickerAccessible.cpp
@@ -112,29 +112,16 @@ nsXULColorPickerTileAccessible::NativeSt
 
 nsXULColorPickerAccessible::
   nsXULColorPickerAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsXULColorPickerTileAccessible(aContent, aShell)
 {
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsXULColorPickerAccessible: nsAccessNode
-
-PRBool
-nsXULColorPickerAccessible::Init()
-{
-  if (!nsXULColorPickerTileAccessible::Init())
-    return PR_FALSE;
-
-  nsCoreUtils::GeneratePopupTree(mContent, PR_TRUE);
-  return PR_TRUE;
-}
-
-////////////////////////////////////////////////////////////////////////////////
 // nsXULColorPickerAccessible: nsAccessible
 
 PRUint64
 nsXULColorPickerAccessible::NativeState()
 {
   // Possible states: focused, focusable, unavailable(disabled).
 
   // get focus and disable status from base class
--- a/accessible/src/xul/nsXULColorPickerAccessible.h
+++ b/accessible/src/xul/nsXULColorPickerAccessible.h
@@ -63,19 +63,16 @@ public:
 /**
  * Used for colorpicker button (xul:colorpicker@type="button").
  */
 class nsXULColorPickerAccessible : public nsXULColorPickerTileAccessible
 {
 public:
   nsXULColorPickerAccessible(nsIContent *aContent, nsIWeakReference *aShell);
 
-  // nsAccessNode
-  virtual PRBool Init();
-
   // nsAccessible
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
 
 protected:
 
   // nsAccessible
   virtual void CacheChildren();
--- a/accessible/src/xul/nsXULComboboxAccessible.cpp
+++ b/accessible/src/xul/nsXULComboboxAccessible.cpp
@@ -52,26 +52,16 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULComboboxAccessible::
   nsXULComboboxAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
 }
 
-PRBool
-nsXULComboboxAccessible::Init()
-{
-  if (!nsAccessibleWrap::Init())
-    return PR_FALSE;
-
-  nsCoreUtils::GeneratePopupTree(mContent);
-  return PR_TRUE;
-}
-
 PRUint32
 nsXULComboboxAccessible::NativeRole()
 {
   if (mContent->AttrValueIs(kNameSpaceID_None, nsAccessibilityAtoms::type,
                             nsAccessibilityAtoms::autocomplete, eIgnoreCase))
     return nsIAccessibleRole::ROLE_AUTOCOMPLETE;
   return nsIAccessibleRole::ROLE_COMBOBOX;
 }
--- a/accessible/src/xul/nsXULComboboxAccessible.h
+++ b/accessible/src/xul/nsXULComboboxAccessible.h
@@ -55,18 +55,15 @@ public:
 
   // nsIAccessible
   NS_IMETHOD GetValue(nsAString& aValue);
   NS_IMETHOD GetDescription(nsAString& aDescription);
   NS_IMETHOD DoAction(PRUint8 aIndex);
   NS_IMETHOD GetNumActions(PRUint8 *aNumActions);
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
 
-  // nsAccessNode
-  virtual PRBool Init();
-
   // nsAccessible
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
   virtual PRBool GetAllowsAnonChildAccessibles();
 };
 
 #endif
--- a/accessible/src/xul/nsXULFormControlAccessible.cpp
+++ b/accessible/src/xul/nsXULFormControlAccessible.cpp
@@ -105,31 +105,16 @@ nsXULButtonAccessible::DoAction(PRUint8 
   if (aIndex != 0)
     return NS_ERROR_INVALID_ARG;
 
   DoCommand();
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsXULButtonAccessible: nsAccessNode
-
-PRBool
-nsXULButtonAccessible::Init()
-{
-  if (!nsAccessibleWrap::Init())
-    return PR_FALSE;
-
-  if (ContainsMenu())
-    nsCoreUtils::GeneratePopupTree(mContent);
-
-  return PR_TRUE;
-}
-
-////////////////////////////////////////////////////////////////////////////////
 // nsXULButtonAccessible: nsAccessible
 
 PRUint32
 nsXULButtonAccessible::NativeRole()
 {
   return nsIAccessibleRole::ROLE_PUSHBUTTON;
 }
 
--- a/accessible/src/xul/nsXULFormControlAccessible.h
+++ b/accessible/src/xul/nsXULFormControlAccessible.h
@@ -61,19 +61,16 @@ public:
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIAccessible
   NS_IMETHOD GetNumActions(PRUint8 *_retval);
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
   NS_IMETHOD DoAction(PRUint8 index);
 
-  // nsAccessNode
-  virtual PRBool Init();
-
   // nsAccessible
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
 
 protected:
 
   // nsAccessible
   virtual void CacheChildren();
--- a/accessible/src/xul/nsXULMenuAccessible.cpp
+++ b/accessible/src/xul/nsXULMenuAccessible.cpp
@@ -275,26 +275,16 @@ nsXULSelectableAccessible::SelectAll()
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULMenuitemAccessible::
   nsXULMenuitemAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
 }
 
-PRBool
-nsXULMenuitemAccessible::Init()
-{
-  if (!nsAccessibleWrap::Init())
-    return PR_FALSE;
-
-  nsCoreUtils::GeneratePopupTree(mContent);
-  return PR_TRUE;
-}
-
 PRUint64
 nsXULMenuitemAccessible::NativeState()
 {
   PRUint64 state = nsAccessible::NativeState();
 
   // Focused?
   if (mContent->HasAttr(kNameSpaceID_None,
                         nsAccessibilityAtoms::_moz_menuactive))
--- a/accessible/src/xul/nsXULMenuAccessible.h
+++ b/accessible/src/xul/nsXULMenuAccessible.h
@@ -84,19 +84,16 @@ public:
   // nsIAccessible
   NS_IMETHOD GetDescription(nsAString& aDescription);
   NS_IMETHOD GetKeyboardShortcut(nsAString& _retval);
   NS_IMETHOD GetDefaultKeyBinding(nsAString& aKeyBinding);
   NS_IMETHOD DoAction(PRUint8 index);
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
   NS_IMETHOD GetNumActions(PRUint8 *_retval);
 
-  // nsAccessNode
-  virtual PRBool Init();
-
   // nsAccessible
   virtual nsresult GetNameInternal(nsAString& aName);
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
   virtual PRInt32 GetLevelInternal();
   virtual void GetPositionAndSizeInternal(PRInt32 *aPosInSet,
                                           PRInt32 *aSetSize);
 
--- a/accessible/tests/mochitest/actions/test_general.xul
+++ b/accessible/tests/mochitest/actions/test_general.xul
@@ -24,17 +24,22 @@
   <script type="application/javascript">
   <![CDATA[
     function doTest()
     {
       var actionsArray = [
         {
           ID: "menu",
           actionName: "click",
-          events: CLICK_EVENTS
+          events: CLICK_EVENTS,
+          // Wait for focus event, it guarantees us the submenu tree is created,
+          // that's necessary for next test.
+          eventSeq: [
+            new invokerChecker(EVENT_FOCUS, getNode("menu"))
+          ]
         },
         {
           ID: "submenu",
           actionName: "click",
           events: CLICK_EVENTS
         },
         {
           ID: "menuitem",
--- a/accessible/tests/mochitest/tree/Makefile.in
+++ b/accessible/tests/mochitest/tree/Makefile.in
@@ -46,31 +46,29 @@ include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES =\
 		dockids.html \
 	$(warning test_applicationacc.xul temporarily disabled, see bug 561508) \
 		test_aria_globals.html \
 		test_aria_imgmap.html \
 		test_button.xul \
-		test_colorpicker.xul \
 		test_combobox.xul \
 		test_cssoverflow.html \
 		test_dochierarchy.html \
 		test_dockids.html \
 		test_filectrl.html \
 		test_formctrl.html \
 		test_formctrl.xul \
 		test_gencontent.html \
 		test_groupbox.xul \
 		test_iframe.html \
 		test_img.html \
 		test_list.html \
 		test_media.html \
-		test_menu.xul \
 		test_select.html \
 		test_tabbox.xul \
 		test_tabbrowser.xul \
 		test_table.html \
 		test_tree.xul \
 		test_txtcntr.html \
 		test_txtctrl.html \
 		test_txtctrl.xul \
--- a/accessible/tests/mochitest/tree/test_button.xul
+++ b/accessible/tests/mochitest/tree/test_button.xul
@@ -19,132 +19,34 @@
   <script type="application/javascript">
   <![CDATA[
     ////////////////////////////////////////////////////////////////////////////
     // Test
 
     function doTest()
     {
       //////////////////////////////////////////////////////////////////////////
-      // button1
+      // button
 
       var accTree = {
         role: ROLE_PUSHBUTTON,
         name: "hello",
         children: [ ]
       };
       testAccessibleTree("button1", accTree);
 
       //////////////////////////////////////////////////////////////////////////
-      // button2
-
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button2", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button3
-
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          },
-          {
-            role: ROLE_PUSHBUTTON,
-            children: [
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button3", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button4
+      // toolbarbutton
 
       var accTree = {
         role: ROLE_PUSHBUTTON,
         name: "hello",
         children: [ ]
       };
-      testAccessibleTree("button4", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button5
-
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button5", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button6
-
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          },
-          {
-            role: ROLE_PUSHBUTTON,
-            children: [
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button6", accTree);
+      testAccessibleTree("button2", accTree);
 
       SimpleTest.finish()
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   ]]>
   </script>
@@ -160,39 +62,14 @@
       <div id="content" style="display: none">
       </div>
       <pre id="test">
       </pre>
     </body>
 
     <vbox flex="1">
       <button id="button1" label="hello"/>
-      <button id="button2" type="menu" label="hello">
-        <menupopup>
-          <menuitem label="menuitem"/>
-          <menuitem label="menuitem"/>
-        </menupopup>
-      </button>
-      <button id="button3" type="menu-button" label="hello">
-        <menupopup>
-          <menuitem label="menuitem"/>
-          <menuitem label="menuitem"/>
-        </menupopup>
-      </button>
-
-      <toolbarbutton id="button4" label="hello"/>
-      <toolbarbutton id="button5" type="menu" label="hello">
-        <menupopup>
-          <menuitem label="menuitem"/>
-          <menuitem label="menuitem"/>
-        </menupopup>
-      </toolbarbutton>
-      <toolbarbutton id="button6" type="menu-button" label="hello">
-        <menupopup>
-          <menuitem label="menuitem"/>
-          <menuitem label="menuitem"/>
-        </menupopup>
-      </toolbarbutton>
+      <toolbarbutton id="button2" label="hello"/>
     </vbox>
   </hbox>
 
 </window>
 
deleted file mode 100644
--- a/accessible/tests/mochitest/tree/test_menu.xul
+++ /dev/null
@@ -1,86 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
-                 type="text/css"?>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
-        title="Accessible XUL menu hierarchy tests">
-
-  <script type="application/javascript" 
-          src="chrome://mochikit/content/MochiKit/packed.js" />
-  <script type="application/javascript"
-          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
-
-  <script type="application/javascript"
-          src="../common.js" />
-  <script type="application/javascript"
-          src="../role.js" />
-
-  <script type="application/javascript">
-  <![CDATA[
-    ////////////////////////////////////////////////////////////////////////////
-    // Test
-
-    function doTest()
-    {
-      if (LINUX || SOLARIS) {
-        // XXX: bug 527646
-
-        todo(false, "Failure on Linux and Solaris.");
-        SimpleTest.finish();
-        return;
-      }
-
-      var accTree = {
-        role: ROLE_PARENT_MENUITEM,
-        name: "menu",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("menu", accTree);
-
-      SimpleTest.finish();
-    }
-
-    SimpleTest.waitForExplicitFinish();
-    addA11yLoadEvent(doTest);
-  ]]>
-  </script>
-
-  <hbox flex="1" style="overflow: auto;">
-    <body xmlns="http://www.w3.org/1999/xhtml">
-      <a target="_blank"
-         href="https://bugzilla.mozilla.org/show_bug.cgi?id=249292"
-         title="Ensure accessible children for toolbarbutton types 'menu' and 'menu-button'">
-        Mozilla Bug 249292
-      </a><br/>
-      <p id="display"></p>
-      <div id="content" style="display: none">
-      </div>
-      <pre id="test">
-      </pre>
-    </body>
-
-    <vbox flex="1">
-      <menu id="menu" label="menu">
-        <menupopup>
-          <menuitem label="menuitem"/>
-          <menuitem label="menuitem"/>
-        </menupopup>
-      </menu>
-    </vbox>
-  </hbox>
-
-</window>
-
--- a/accessible/tests/mochitest/treeupdate/Makefile.in
+++ b/accessible/tests/mochitest/treeupdate/Makefile.in
@@ -42,21 +42,24 @@ srcdir		= @srcdir@
 VPATH		= @srcdir@
 relativesrcdir  = accessible/treeupdate
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES =\
 		test_ariadialog.html \
+		test_colorpicker.xul \
+		test_contextmenu.xul \
 		test_doc.html \
 		test_gencontent.html \
 		test_list_editabledoc.html \
 		test_list.html \
 		test_menu.xul \
+		test_menubutton.xul \
 		test_recreation.html \
 		test_select.html \
 		test_textleaf.html \
 		test_visibility.html \
 		test_whitespace.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
rename from accessible/tests/mochitest/tree/test_colorpicker.xul
rename to accessible/tests/mochitest/treeupdate/test_colorpicker.xul
--- a/accessible/tests/mochitest/tree/test_colorpicker.xul
+++ b/accessible/tests/mochitest/treeupdate/test_colorpicker.xul
@@ -10,60 +10,137 @@
           src="chrome://mochikit/content/MochiKit/packed.js" />
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
 
   <script type="application/javascript"
           src="../common.js" />
   <script type="application/javascript"
           src="../role.js" />
+  <script type="application/javascript"
+          src="../events.js" />
 
   <script type="application/javascript">
   <![CDATA[
     ////////////////////////////////////////////////////////////////////////////
     // Test
 
+    function openColorpicker(aColorpickerID)
+    {
+      this.node = getNode(aColorpickerID);
+
+      this.eventSeq = [];
+
+      var it = new colorButtonIterator(this.node);
+      for (var btnNode = it.next(); btnNode = it.next(); btnNode)
+        this.eventSeq.push(new invokerChecker(EVENT_SHOW, btnNode));
+
+      var popupNode = getPopupNode(this.node);
+      this.eventSeq.push(new invokerChecker(EVENT_REORDER, popupNode));
+
+      this.invoke = function openColorpicker_invoke()
+      {
+        var tree =
+          { BUTTONDROPDOWNGRID: [
+            { ALERT: [ ] }
+          ] };
+        testAccessibleTree(this.node, tree);
+
+        this.node.showPopup();
+      }
+
+      this.finalCheck = function openColorpicker_finalCheck()
+      {
+        var tree =
+          { BUTTONDROPDOWNGRID: [
+            { ALERT: [ ] }
+          ] };
+
+        var colorButtons = tree.BUTTONDROPDOWNGRID[0].ALERT;
+        var it = new colorButtonIterator(this.node);
+        while (it.next()) {
+          var obj = { PUSHBUTTON: [ ] };
+          colorButtons.push(obj);
+        }
+
+        testAccessibleTree(this.node, tree);
+      }
+
+      this.getID = function openColorpicker_getID()
+      {
+        return "open colorpicker " + prettyName(aColorpickerID);
+      }
+    }
+
+    function getPopupNode(aColorpickerNode)
+    {
+      return aColorpickerNode.mPicker.parentNode;
+    }
+
+    function colorButtonIterator(aColorpickerNode)
+    {
+      this.container = aColorpickerNode.mPicker.mBox;
+      this.group = this.container.firstChild;
+      this.item = null;
+
+      this.next = function colorButtonIterator_next()
+      {
+        if (!this.group)
+          return null;
+
+        if (!this.item) {
+          this.item = this.group.firstChild;
+          return this.item;
+        }
+
+        if (this.item.nextSibling) {
+          this.item = this.item.nextSibling;
+          return this.item;
+        }
+
+        if (this.group.nextSibling) {
+          this.group = this.group.nextSibling;
+          this.item = this.group.firstChild;
+          return this.item;
+        }
+
+        this.group = null;
+        this.item = null;
+        return null;
+      }
+    }
+
+    //gA11yEventDumpToConsole = true; // debug stuff
+
+    var gQueue = null;
     function doTest()
     {
-      //////////////////////////////////////////////////////////////////////////
-      // button1
-
-      var accTree = {
-        role: ROLE_BUTTONDROPDOWNGRID,
-        children: [
-          {
-            role: ROLE_ALERT,
-            children: [ ]
-          }
-        ]
-      };
-
-      var colorButtons = accTree.children[0].children;
-      for (var idx = 0; idx < 70; idx++) {
-        var obj = { role: ROLE_PUSHBUTTON };
-        colorButtons.push(obj);
-      }
-
-      testAccessibleTree("colorpicker", accTree);
-
-      SimpleTest.finish()
+      gQueue = new eventQueue();
+      gQueue.push(new openColorpicker("colorpicker"));
+      gQueue.invoke(); // Will call SimpleTest.finish()
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   ]]>
   </script>
 
   <hbox flex="1" style="overflow: auto;">
     <body xmlns="http://www.w3.org/1999/xhtml">
       <a target="_blank"
          href="https://bugzilla.mozilla.org/show_bug.cgi?id=249292"
          title="Ensure accessible children for toolbarbutton types 'menu' and 'menu-button'">
         Mozilla Bug 249292
-      </a><br/>
+      </a>
+      <a target="_blank"
+         href="https://bugzilla.mozilla.org/show_bug.cgi?id=630486"
+         title="Don't force accessible creation for popup children.">
+        Mozilla Bug 630486
+      </a>
+      <br/>
       <p id="display"></p>
       <div id="content" style="display: none">
       </div>
       <pre id="test">
       </pre>
     </body>
 
     <vbox flex="1">
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/treeupdate/test_contextmenu.xul
@@ -0,0 +1,321 @@
+<?xml version="1.0"?>
+<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
+<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
+                 type="text/css"?>
+
+<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+        title="menu tree and events">
+
+  <script type="application/javascript" 
+          src="chrome://mochikit/content/MochiKit/packed.js" />
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
+
+  <script type="application/javascript"
+          src="../common.js" />
+  <script type="application/javascript"
+          src="../events.js" />
+  <script type="application/javascript"
+          src="../role.js" />
+
+  <script type="application/javascript">
+  <![CDATA[
+
+    function openMenu(aID, aTree)
+    {
+      this.eventSeq = [
+        new invokerChecker(EVENT_MENUPOPUP_START, getNode(aID))
+      ];
+
+      this.invoke = function openMenu_invoke()
+      {
+        var button = getNode("button");
+        getNode(aID).openPopup(button, "after_start", 0, 0, true, false);
+      }
+
+      this.finalCheck = function openMenu_finalCheck(aEvent)
+      {
+        testAccessibleTree(aID, aTree);
+      }
+
+      this.getID = function openMenu_getID()
+      {
+        return "open menu " + prettyName(aID);
+      }
+    }
+
+    function selectNextMenuItem(aID)
+    {
+      this.eventSeq = [
+        new invokerChecker(EVENT_FOCUS, getNode(aID))
+      ];
+
+      this.invoke = function selectMenuItem_invoke()
+      {
+        synthesizeKey("VK_DOWN", { });
+      }
+
+      this.getID = function selectMenuItem_getID()
+      {
+        return "select menuitem " + prettyName(aID);
+      }
+    }
+    
+    function openSubMenu(aSubMenuID, aItemID, aMenuID, aTree)
+    {
+      this.eventSeq = [
+        new invokerChecker(EVENT_FOCUS, getNode(aItemID)),
+      ];
+
+      this.invoke = function openSubMenu_invoke()
+      {
+        synthesizeKey("VK_ENTER", { });
+      }
+
+      this.finalCheck = function openSubMenu_finalCheck(aEvent)
+      {
+        testAccessibleTree(aMenuID, aTree);
+      }
+
+      this.getID = function openSubMenu_getID()
+      {
+        return "open submenu " + prettyName(aSubMenuID) + " focusing item " + prettyName(aItemID);
+      }
+    }
+
+    function closeSubMenu(aSubMenuID, aItemID)
+    {
+      this.eventSeq = [
+        new invokerChecker(EVENT_FOCUS, getNode(aItemID)),
+      ];
+
+      this.invoke = function closeSubMenu_invoke()
+      {
+        synthesizeKey("VK_ESCAPE", { });
+      }
+
+      this.getID = function closeSubMenu_getID()
+      {
+        return "close submenu " + prettyName(aSubMenuID) + " focusing item " + prettyName(aItemID);
+      }
+    }
+
+    function closeMenu(aID)
+    {
+      this.eventSeq = [
+        new invokerChecker(EVENT_MENUPOPUP_END, getNode(aID))
+      ];
+
+      this.invoke = function closeMenu_invoke()
+      {
+        synthesizeKey("VK_ESCAPE", { });
+      }
+
+      this.getID = function closeMenu_getID()
+      {
+        return "close menu " + prettyName(aID);
+      }
+    }
+
+    //gA11yEventDumpID = "eventdump";
+    //gA11yEventDumpToConsole = true;
+
+    var gQueue = null;
+    var gContextTree = {};
+
+    // Linux and Windows menu trees discrepancy: bug 527646.
+
+    /**
+     * Return the context menu tree before submenus were open.
+     */
+    function getMenuTree1()
+    {
+      if (LINUX || SOLARIS) {
+        var tree = {
+          role: ROLE_MENUPOPUP,
+          children: [
+            {
+              name: "item0",
+              role: ROLE_MENUITEM,
+              children: []
+            },
+            {
+              name: "item1",
+              role: ROLE_MENUITEM,
+              children: []
+            },
+            {
+              name: "item2",
+              role: ROLE_PARENT_MENUITEM,
+              children: [ ]
+            }
+          ]
+        };
+        return tree;
+      }
+
+      // Windows
+      var tree = {
+        role: ROLE_MENUPOPUP,
+        children: [
+          {
+            name: "item0",
+            role: ROLE_MENUITEM,
+            children: []
+          },
+          {
+            name: "item1",
+            role: ROLE_MENUITEM,
+            children: []
+          },
+          {
+            name: "item2",
+            role: ROLE_PARENT_MENUITEM,
+            children: [
+              {
+                name: "item2",
+                role: ROLE_MENUPOPUP,
+                children: [ ]
+              }
+            ]
+          }
+        ]
+      };
+      return tree;
+    }
+
+    /**
+     * Return context menu tree when submenu was open.
+     */
+    function getMenuTree2()
+    {
+      var tree = getMenuTree1();
+      if (LINUX || SOLARIS) {
+        var submenuTree =
+        {
+          name: "item2.0",
+          role: ROLE_PARENT_MENUITEM,
+          children: [ ]
+        };
+        tree.children[2].children.push(submenuTree);
+        return tree;
+      }
+
+      // Windows
+      var submenuTree =
+      {
+        name: "item2.0",
+        role: ROLE_PARENT_MENUITEM,
+        children: [
+          {
+            name: "item2.0",
+            role: ROLE_MENUPOPUP,
+            children: [ ]
+          }
+        ]
+      };
+
+      tree.children[2].children[0].children.push(submenuTree);
+      return tree;
+    }
+
+    /**
+     * Return context menu tree when subsub menu was open.
+     */
+    function getMenuTree3()
+    {
+      var tree = getMenuTree2();
+      var subsubmenuTree =
+      {
+        name: "item2.0.0",
+        role: ROLE_MENUITEM,
+        children: []
+      };
+
+      if (LINUX || SOLARIS)
+        tree.children[2].children[0].\(subsubmenuTree);
+      else
+        tree.children[2].children[0].children[0].children[0].children.push(subsubmenuTree);
+
+      return tree;
+    }
+
+
+    function doTests()
+    {
+      gQueue = new eventQueue();
+
+      // Check initial empty tree
+      testAccessibleTree("context", { MENUPOPUP: [] });
+
+      // Open context menu and check that menu item accesibles are created.
+      gQueue.push(new openMenu("context", getMenuTree1()));
+
+      // Select items and check focus event on them.
+      gQueue.push(new selectNextMenuItem("item0"));
+      gQueue.push(new selectNextMenuItem("item1"));
+      gQueue.push(new selectNextMenuItem("item2"));
+
+      // Open sub menu and check menu accessible tree and focus event.
+      gQueue.push(new openSubMenu("submenu2", "item2.0",
+                                  "context", getMenuTree2()));
+      gQueue.push(new openSubMenu("submenu2.0", "item2.0.0",
+                                  "context", getMenuTree3()));
+
+      // Close submenus and check that focus goes to parent.
+      gQueue.push(new closeSubMenu("submenu2.0", "item2.0"));
+      gQueue.push(new closeSubMenu("submenu2", "item2"));
+
+      gQueue.push(new closeMenu("context"));
+
+      gQueue.invoke(); // Will call SimpleTest.finish();
+    }
+
+    SimpleTest.waitForExplicitFinish();
+    addA11yLoadEvent(doTests);
+  ]]>
+  </script>
+
+  <hbox flex="1" style="overflow: auto;">
+  <body xmlns="http://www.w3.org/1999/xhtml">
+    <a target="_blank"
+       href="https://bugzilla.mozilla.org/show_bug.cgi?id=630194"
+       title="Update accessible tree when opening the menu popup">
+      Mozilla Bug 630194
+    </a>
+    <a target="_blank"
+       href="https://bugzilla.mozilla.org/show_bug.cgi?id=630486"
+       title="Don't force accessible creation for popup children.">
+      Mozilla Bug 630486
+    </a>
+  <p id="display"></p>
+    <div id="content" style="display: none">
+    </div>
+    <pre id="test">
+    </pre>
+  </body>
+
+    <vbox flex="1">
+
+      <menupopup id="context">
+        <menuitem id="item0" label="item0"/>
+        <menuitem id="item1" label="item1"/>
+        <menu id="item2" label="item2">
+          <menupopup id="submenu2">
+            <menu id="item2.0" label="item2.0">
+              <menupopup id="submenu2.0">
+                <menuitem id="item2.0.0" label="item2.0.0"/>
+              </menupopup>
+            </menu>
+          </menupopup>
+        </menu>
+      </menupopup>
+
+      <button context="context" id="button">btn</button>
+
+      <vbox id="eventdump" role="log"/>
+    </vbox>
+  </hbox>
+</window>
--- a/accessible/tests/mochitest/treeupdate/test_menu.xul
+++ b/accessible/tests/mochitest/treeupdate/test_menu.xul
@@ -1,277 +1,130 @@
 <?xml version="1.0"?>
 <?xml-stylesheet href="chrome://global/skin" type="text/css"?>
 <?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
                  type="text/css"?>
 
 <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
-        title="menu tree and events">
+        title="Accessible XUL menu hierarchy tests">
 
   <script type="application/javascript" 
           src="chrome://mochikit/content/MochiKit/packed.js" />
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
-  <script type="application/javascript"
-          src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
 
   <script type="application/javascript"
           src="../common.js" />
   <script type="application/javascript"
-          src="../events.js" />
+          src="../role.js" />
   <script type="application/javascript"
-          src="../role.js" />
+          src="../events.js" />
 
   <script type="application/javascript">
   <![CDATA[
-    function openMenu(aID, aTree)
+    ////////////////////////////////////////////////////////////////////////////
+    // Invokers
+
+    function openMenu(aID)
     {
+      this.menuNode = getNode(aID),
+
       this.eventSeq = [
-        new invokerChecker(EVENT_MENUPOPUP_START, getNode(aID))
+        new invokerChecker(EVENT_FOCUS, this.menuNode)
       ];
 
       this.invoke = function openMenu_invoke()
       {
-        var button = getNode("button");
-        getNode(aID).openPopup(button, "after_start", 0, 0, true, false);
+        var tree;
+        if (LINUX || SOLARIS) {
+          tree =
+            { PARENT_MENUITEM: [ ] };
+
+        } else {
+          tree =
+            { PARENT_MENUITEM: [
+              { MENUPOPUP: [ ] }
+            ] };
+        }
+        testAccessibleTree(aID, tree);
+
+        // Show menu.
+        this.menuNode.open = true;
       }
 
-      this.finalCheck = function openMenu_finalCheck(aEvent)
+      this.finalCheck = function openMenu_finalCheck()
       {
-        testAccessibleTree(aID, aTree);
+        var tree;
+        if (LINUX || SOLARIS) {
+          tree =
+            { PARENT_MENUITEM: [
+              { MENUITEM: [ ] },
+              { MENUITEM: [ ] }
+            ] };
+
+        } else {
+          tree =
+            { PARENT_MENUITEM: [
+              { MENUPOPUP: [
+                { MENUITEM: [ ] },
+                { MENUITEM: [ ] }
+              ] }
+            ] };
+        }
+        testAccessibleTree(aID, tree);
       }
 
       this.getID = function openMenu_getID()
       {
         return "open menu " + prettyName(aID);
       }
     }
 
-    function selectNextMenuItem(aID)
-    {
-      this.eventSeq = [
-        new invokerChecker(EVENT_FOCUS, getNode(aID))
-      ];
-
-      this.invoke = function selectMenuItem_invoke()
-      {
-        synthesizeKey("VK_DOWN", { });
-      }
-
-      this.getID = function selectMenuItem_getID()
-      {
-        return "select menuitem " + prettyName(aID);
-      }
-    }
-    
-    function openSubMenu(aSubMenuID, aItemID)
-    {
-      this.eventSeq = [
-        new invokerChecker(EVENT_FOCUS, getNode(aItemID)),
-      ];
-
-      this.invoke = function openSubMenu_invoke()
-      {
-        synthesizeKey("VK_ENTER", { });
-      }
-
-      this.finalCheck = function openSubMenu_finalCheck(aEvent)
-      {
-        getAccessible(aItemID);
-      }
-
-      this.getID = function openSubMenu_getID()
-      {
-        return "open submenu " + prettyName(aSubMenuID) + " focusing item " + prettyName(aItemID);
-      }
-    }
-
-    function closeSubMenu(aSubMenuID, aItemID)
-    {
-      this.eventSeq = [
-        new invokerChecker(EVENT_FOCUS, getNode(aItemID)),
-      ];
-
-      this.invoke = function closeSubMenu_invoke()
-      {
-        synthesizeKey("VK_ESCAPE", { });
-      }
-
-      this.getID = function closeSubMenu_getID()
-      {
-        return "close submenu " + prettyName(aSubMenuID) + " focusing item " + prettyName(aItemID);
-      }
-    }
-
-    function closeMenu(aID)
-    {
-      this.eventSeq = [
-        new invokerChecker(EVENT_MENUPOPUP_END, getNode(aID))
-      ];
-
-      this.invoke = function closeMenu_invoke()
-      {
-        synthesizeKey("VK_ESCAPE", { });
-      }
-
-      this.getID = function closeMenu_getID()
-      {
-        return "close menu " + prettyName(aID);
-      }
-    }
-
-    //gA11yEventDumpID = "eventdump";
-    //gA11yEventDumpToConsole = true;
+    ////////////////////////////////////////////////////////////////////////////
+    // Test
 
     var gQueue = null;
-    var gContextTree = {};
-
-    // bug 527646
-    if (LINUX || SOLARIS) {
-      gContextTree = {
-        role: ROLE_MENUPOPUP,
-        children: [
-          {
-            name: "item0",
-            role: ROLE_MENUITEM,
-            children: []
-          },
-          {
-            name: "item1",
-            role: ROLE_MENUITEM,
-            children: []
-          },
-          {
-            name: "item2",
-            role: ROLE_PARENT_MENUITEM,
-            children: [
-              {
-                name: "item2.0",
-                role: ROLE_PARENT_MENUITEM,
-                children: [
-                  { 
-                    name: "item2.0.0",
-                    role: ROLE_MENUITEM,
-                    children: []
-                  }
-                ]
-              }
-            ]
-          }
-        ]
-      };
-    } else {
-      gContextTree = {
-        role: ROLE_MENUPOPUP,
-        children: [
-          {
-            name: "item0",
-            role: ROLE_MENUITEM,
-            children: []
-          },
-          {
-            name: "item1",
-            role: ROLE_MENUITEM,
-            children: []
-          },
-          {
-            name: "item2",
-            role: ROLE_PARENT_MENUITEM,
-            children: [
-              {
-                name: "item2",
-                role: ROLE_MENUPOPUP,
-                children: [
-                  {
-                    name: "item2.0",
-                    role: ROLE_PARENT_MENUITEM,
-                    children: [
-                      { 
-                        name: "item2.0",
-                        role: ROLE_MENUPOPUP,
-                        children: [
-                          { 
-                            name: "item2.0.0",
-                            role: ROLE_MENUITEM,
-                            children: []
-                          }
-                        ]
-                      }
-                    ]
-                  }
-                ]
-              }
-            ]
-          }
-        ]
-      };
-    }
-
-
-    function doTests()
+    function doTest()
     {
       gQueue = new eventQueue();
-
-      // Check initial empty tree
-      testAccessibleTree("context", { MENUPOPUP: [] });
-
-      // Open context menu and check that menu item accesibles are created.
-      gQueue.push(new openMenu("context", gContextTree));
-
-      // Select items and check focus event on them.
-      gQueue.push(new selectNextMenuItem("item0"));
-      gQueue.push(new selectNextMenuItem("item1"));
-      gQueue.push(new selectNextMenuItem("item2"));
-
-      // Open sub menu and check menu item accessibles and focus event.
-      gQueue.push(new openSubMenu("submenu2", "item2.0"));
-      gQueue.push(new openSubMenu("submenu2.0", "item2.0.0"));
-
-      // Close submenus and check that focus goes to parent.
-      gQueue.push(new closeSubMenu("submenu2.0", "item2.0"));
-      gQueue.push(new closeSubMenu("submenu2", "item2"));
-
-      gQueue.push(new closeMenu("context"));
-
+      gQueue.push(new openMenu("menu"));
       gQueue.invoke(); // Will call SimpleTest.finish();
     }
 
     SimpleTest.waitForExplicitFinish();
-    addA11yLoadEvent(doTests);
+    addA11yLoadEvent(doTest);
   ]]>
   </script>
 
   <hbox flex="1" style="overflow: auto;">
-  <body xmlns="http://www.w3.org/1999/xhtml">
-    <a target="_blank"
-       href="https://bugzilla.mozilla.org/show_bug.cgi?id=630194"
-       title="Update accessible tree when opening the menu popup">
-      Mozilla Bug 630194
-    </a>
-  <p id="display"></p>
-    <div id="content" style="display: none">
-    </div>
-    <pre id="test">
-    </pre>
-  </body>
+    <body xmlns="http://www.w3.org/1999/xhtml">
+      <a target="_blank"
+         href="https://bugzilla.mozilla.org/show_bug.cgi?id=249292"
+         title="Ensure accessible children for toolbarbutton types 'menu' and 'menu-button'">
+        Mozilla Bug 249292
+      </a>
+      <a target="_blank"
+         href="https://bugzilla.mozilla.org/show_bug.cgi?id=630486"
+         title="Don't force accessible creation for popup children.">
+        Mozilla Bug 630486
+      </a>
+      <br/>
+      <p id="display"></p>
+      <div id="content" style="display: none">
+      </div>
+      <pre id="test">
+      </pre>
+    </body>
 
     <vbox flex="1">
-
-      <menupopup id="context">
-        <menuitem id="item0" label="item0"/>
-        <menuitem id="item1" label="item1"/>
-        <menu id="item2" label="item2">
-          <menupopup id="submenu2">
-            <menu id="item2.0" label="item2.0">
-              <menupopup id="submenu2.0">
-                <menuitem id="item2.0.0" label="item2.0.0"/>
-              </menupopup>
-            </menu>
+      <menubar>
+        <menu id="menu" label="menu">
+          <menupopup>
+            <menuitem label="menuitem"/>
+            <menuitem label="menuitem"/>
           </menupopup>
         </menu>
-      </menupopup>
-
-      <button context="context" id="button">btn</button>
-
-      <vbox id="eventdump" role="log"/>
+      </menubar>
     </vbox>
   </hbox>
+
 </window>
+
copy from accessible/tests/mochitest/tree/test_button.xul
copy to accessible/tests/mochitest/treeupdate/test_menubutton.xul
--- a/accessible/tests/mochitest/tree/test_button.xul
+++ b/accessible/tests/mochitest/treeupdate/test_menubutton.xul
@@ -10,187 +10,168 @@
           src="chrome://mochikit/content/MochiKit/packed.js" />
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
 
   <script type="application/javascript"
           src="../common.js" />
   <script type="application/javascript"
           src="../role.js" />
+  <script type="application/javascript"
+          src="../events.js" />
 
   <script type="application/javascript">
   <![CDATA[
+
     ////////////////////////////////////////////////////////////////////////////
-    // Test
+    // Invokers
+
+    function openMenu(aButtonID)
+    {
+      this.buttonNode = getNode(aButtonID);
+      this.menupoupNode = this.buttonNode.firstChild;
+
+      this.eventSeq = [
+        new invokerChecker(EVENT_REORDER, this.menupoupNode)
+      ];
+
+      this.invoke = function openMenu_invoke()
+      {
+        var tree =
+          { PUSHBUTTON: [
+            { MENUPOPUP: [ ] }
+          ] };
+        testAccessibleTree(this.buttonNode, tree);
+
+        this.buttonNode.open = true;
+      }
+
+      this.finalCheck = function openMenu_finalCheck()
+      {
+        var tree =
+          { PUSHBUTTON: [
+            { MENUPOPUP: [
+              { MENUITEM: [ ] },
+              { MENUITEM: [ ] }
+            ] }
+          ] };
+        testAccessibleTree(this.buttonNode, tree);
+      }
+
+      this.getID = function openMenu_getID()
+      {
+        return "open menu for button " + prettyName(aButtonID);
+      }
+    }
+
+    function openMenuButton(aButtonID)
+    {
+      this.buttonNode = getNode(aButtonID);
+      this.menupoupNode = this.buttonNode.firstChild;
+
+      this.eventSeq = [
+        new invokerChecker(EVENT_REORDER, this.menupoupNode)
+      ];
+
+      this.invoke = function openMenu_invoke()
+      {
+        var tree =
+          { PUSHBUTTON: [
+            { MENUPOPUP: [ ] },
+            { PUSHBUTTON: [ ] }
+          ] };
+        testAccessibleTree(this.buttonNode, tree);
+
+        this.buttonNode.open = true;
+      }
+
+      this.finalCheck = function openMenu_finalCheck()
+      {
+        var tree =
+          { PUSHBUTTON: [
+            { MENUPOPUP: [
+              { MENUITEM: [ ] },
+              { MENUITEM: [ ] }
+            ] },
+            { PUSHBUTTON: [ ] }
+          ] };
+        testAccessibleTree(this.buttonNode, tree);
+      }
+
+      this.getID = function openMenu_getID()
+      {
+        return "open menu for menu button " + prettyName(aButtonID);
+      }
+    }
+
+    ////////////////////////////////////////////////////////////////////////////
+    // Do test
+
+    gA11yEventDumpToConsole = true; // debug stuff
+
+    var gQueue = null;
 
     function doTest()
     {
-      //////////////////////////////////////////////////////////////////////////
-      // button1
-
-      var accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [ ]
-      };
-      testAccessibleTree("button1", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button2
-
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button2", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button3
-
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          },
-          {
-            role: ROLE_PUSHBUTTON,
-            children: [
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button3", accTree);
+      gQueue = new eventQueue();
 
-      //////////////////////////////////////////////////////////////////////////
-      // button4
-
-      var accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [ ]
-      };
-      testAccessibleTree("button4", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button5
+      gQueue.push(new openMenu("button1"));
+      gQueue.push(new openMenuButton("button2"));
+      gQueue.push(new openMenu("button3"));
+      gQueue.push(new openMenuButton("button4"));
 
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button5", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button6
-
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          },
-          {
-            role: ROLE_PUSHBUTTON,
-            children: [
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button6", accTree);
-
-      SimpleTest.finish()
+      gQueue.invoke(); // SimpleTest.finish()
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   ]]>
   </script>
 
   <hbox flex="1" style="overflow: auto;">
     <body xmlns="http://www.w3.org/1999/xhtml">
       <a target="_blank"
          href="https://bugzilla.mozilla.org/show_bug.cgi?id=249292"
          title="Ensure accessible children for toolbarbutton types 'menu' and 'menu-button'">
         Mozilla Bug 249292
-      </a><br/>
+      </a>
+      <a target="_blank"
+         href="https://bugzilla.mozilla.org/show_bug.cgi?id=630486"
+         title="Don't force accessible creation for popup children.">
+        Mozilla Bug 630486
+      </a>
+      <br/>
       <p id="display"></p>
       <div id="content" style="display: none">
       </div>
       <pre id="test">
       </pre>
     </body>
 
     <vbox flex="1">
-      <button id="button1" label="hello"/>
-      <button id="button2" type="menu" label="hello">
+      <button id="button1" type="menu" label="hello">
         <menupopup>
           <menuitem label="menuitem"/>
           <menuitem label="menuitem"/>
         </menupopup>
       </button>
-      <button id="button3" type="menu-button" label="hello">
+      <button id="button2" type="menu-button" label="hello">
         <menupopup>
           <menuitem label="menuitem"/>
           <menuitem label="menuitem"/>
         </menupopup>
       </button>
 
-      <toolbarbutton id="button4" label="hello"/>
-      <toolbarbutton id="button5" type="menu" label="hello">
+      <toolbarbutton id="button3" type="menu" label="hello">
         <menupopup>
           <menuitem label="menuitem"/>
           <menuitem label="menuitem"/>
         </menupopup>
       </toolbarbutton>
-      <toolbarbutton id="button6" type="menu-button" label="hello">
+      <toolbarbutton id="button4" type="menu-button" label="hello">
         <menupopup>
           <menuitem label="menuitem"/>
           <menuitem label="menuitem"/>
         </menupopup>
       </toolbarbutton>
     </vbox>
   </hbox>
 
--- a/browser/base/content/browser-tabview.js
+++ b/browser/base/content/browser-tabview.js
@@ -33,16 +33,17 @@
 # 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 *****
 
 let TabView = {
   _deck: null,
+  _iframe: null,
   _window: null,
   _firstUseExperienced: false,
   _browserKeyHandlerInitialized: false,
   VISIBILITY_IDENTIFIER: "tabview-visibility",
 
   // ----------
   get windowTitle() {
     delete this.windowTitle;
@@ -130,27 +131,27 @@ let TabView = {
     if (this._window) {
       if (typeof callback == "function")
         callback();
     } else {
       // ___ find the deck
       this._deck = document.getElementById("tab-view-deck");
 
       // ___ create the frame
-      let iframe = document.createElement("iframe");
-      iframe.id = "tab-view";
-      iframe.setAttribute("transparent", "true");
-      iframe.flex = 1;
+      this._iframe = document.createElement("iframe");
+      this._iframe.id = "tab-view";
+      this._iframe.setAttribute("transparent", "true");
+      this._iframe.flex = 1;
 
       if (typeof callback == "function")
         window.addEventListener("tabviewframeinitialized", callback, false);
 
-      iframe.setAttribute("src", "chrome://browser/content/tabview.html");
-      this._deck.appendChild(iframe);
-      this._window = iframe.contentWindow;
+      this._iframe.setAttribute("src", "chrome://browser/content/tabview.html");
+      this._deck.appendChild(this._iframe);
+      this._window = this._iframe.contentWindow;
 
       if (this._tabShowEventListener) {
         gBrowser.tabContainer.removeEventListener(
           "TabShow", this._tabShowEventListener, true);
         this._tabShowEventListener = null;
       }
 
       this._setBrowserKeyHandlers();
@@ -158,18 +159,18 @@ let TabView = {
   },
 
   // ----------
   getContentWindow: function TabView_getContentWindow() {
     return this._window;
   },
 
   // ----------
-  isVisible: function() {
-    return (this._deck ? this._deck.selectedIndex == 1 : false);
+  isVisible: function TabView_isVisible() {
+    return (this._deck ? this._deck.selectedPanel == this._iframe : false);
   },
 
   // ----------
   show: function() {
     if (this.isVisible())
       return;
 
     let self = this;
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -458,17 +458,17 @@
         <toolbarbutton class="titlebar-button" id="titlebar-close" command="cmd_closeWindow"/>
       </hbox>
     </hbox>
   </hbox>
 </vbox>
 #endif
 
 <deck flex="1" id="tab-view-deck">
-<vbox flex="1">
+<vbox flex="1" id="browser-panel">
 
   <toolbox id="navigator-toolbox"
            defaultmode="icons" mode="icons"
 #ifdef WINCE
            defaulticonsize="small" iconsize="small"
 #else
            iconsize="large"
 #endif
--- a/browser/base/content/tabview/groupitems.js
+++ b/browser/base/content/tabview/groupitems.js
@@ -1783,17 +1783,22 @@ GroupItem.prototype = Utils.extend(new I
   // ----------
   // Function: setResizable
   // Sets whether the groupItem is resizable and updates the UI accordingly.
   setResizable: function GroupItem_setResizable(value, immediately) {
     var self = this;
 
     this.resizeOptions.minWidth = GroupItems.minGroupWidth;
     this.resizeOptions.minHeight = GroupItems.minGroupHeight;
-    this.resizeOptions.start = function () self._unfreezeItemSize();
+
+    let start = this.resizeOptions.start;
+    this.resizeOptions.start = function (event) {
+      start.call(self, event);
+      self._unfreezeItemSize();
+    }
 
     if (value) {
       immediately ? this.$resizer.show() : this.$resizer.fadeIn();
       this.resizable(true);
     } else {
       immediately ? this.$resizer.hide() : this.$resizer.fadeOut();
       this.resizable(false);
     }
--- a/browser/base/content/tabview/tabview.js
+++ b/browser/base/content/tabview/tabview.js
@@ -28,16 +28,17 @@ XPCOMUtils.defineLazyGetter(this, "gNetU
   Cu.import("resource://gre/modules/NetUtil.jsm", obj);
   return obj.NetUtil;
 });
 
 var gWindow = window.parent;
 var gBrowser = gWindow.gBrowser;
 var gTabView = gWindow.TabView;
 var gTabViewDeck = gWindow.document.getElementById("tab-view-deck");
+var gBrowserPanel = gWindow.document.getElementById("browser-panel");
 var gTabViewFrame = gWindow.document.getElementById("tab-view");
 
 # NB: Certain files need to evaluate before others
 
 #include iq.js
 #include storage.js
 #include items.js
 #include groupitems.js
--- a/browser/base/content/tabview/ui.js
+++ b/browser/base/content/tabview/ui.js
@@ -411,17 +411,17 @@ let UI = {
   getActiveOrphanTab: function UI_getActiveOrphanTab() {
     return (this._activeTab && !this._activeTab.parent) ? this._activeTab : null;
   },
 
   // ----------
   // Function: isTabViewVisible
   // Returns true if the TabView UI is currently shown.
   isTabViewVisible: function UI_isTabViewVisible() {
-    return gTabViewDeck.selectedIndex == 1;
+    return gTabViewDeck.selectedPanel == gTabViewFrame;
   },
 
   // ---------
   // Function: _initPageDirection
   // Initializes the page base direction
   _initPageDirection: function UI__initPageDirection() {
     let chromeReg = Cc["@mozilla.org/chrome/chrome-registry;1"].
                     getService(Ci.nsIXULChromeRegistry);
@@ -450,17 +450,17 @@ let UI = {
       groupItem.reorderTabItemsBasedOnTabOrder();
     });
     this._reorderTabItemsOnShow = [];
 
 #ifdef XP_WIN
     // Restore the full height when showing TabView
     gTabViewFrame.style.marginTop = "";
 #endif
-    gTabViewDeck.selectedIndex = 1;
+    gTabViewDeck.selectedPanel = gTabViewFrame;
     gWindow.TabsInTitlebar.allowedBy("tabview-open", false);
     gTabViewFrame.contentWindow.focus();
 
     gBrowser.updateTitlebar();
 #ifdef XP_MACOSX
     this.setTitlebarColors(true);
 #endif
     let event = document.createEvent("Events");
@@ -532,17 +532,17 @@ let UI = {
     this._reorderTabsOnHide = [];
 
 #ifdef XP_WIN
     // Push the top of TabView frame to behind the tabbrowser, so glass can show
     // XXX bug 586679: avoid shrinking the iframe and squishing iframe contents
     // as well as avoiding the flash of black as we animate out
     gTabViewFrame.style.marginTop = gBrowser.boxObject.y + "px";
 #endif
-    gTabViewDeck.selectedIndex = 0;
+    gTabViewDeck.selectedPanel = gBrowserPanel;
     gWindow.TabsInTitlebar.allowedBy("tabview-open", true);
     gBrowser.contentWindow.focus();
 
     gBrowser.updateTitlebar();
 #ifdef XP_MACOSX
     this.setTitlebarColors(false);
 #endif
     Storage.saveVisibilityData(gWindow, "false");
--- a/browser/base/content/test/tabview/browser_tabview_bug595436.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug595436.js
@@ -1,67 +1,54 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 function test() {
-  waitForExplicitFinish();
-  
-  window.addEventListener('tabviewshown', onTabViewWindowLoaded, false);
-  TabView.toggle();
-}
+  let cw, search, searchButton;
+
+  let assertSearchIsEnabled = function () {
+    isnot(search.style.display, "none", "search is enabled");
+  }
 
-function onTabViewWindowLoaded() {
-  window.removeEventListener('tabviewshown', onTabViewWindowLoaded, false);
-  
-  let contentWindow = document.getElementById('tab-view').contentWindow;
-  let search = contentWindow.document.getElementById('search');
-  let searchButton = contentWindow.document.getElementById('searchbutton');
-  
-  let isSearchEnabled = function () {
-    return 'none' != search.style.display;
+  let assertSearchIsDisabled = function () {
+    is(search.style.display, "none", "search is disabled");
   }
-  
-  let assertSearchIsEnabled = function () {
-    ok(isSearchEnabled(), 'search is enabled');
-  }
-  
-  let assertSearchIsDisabled = function () {
-    ok(!isSearchEnabled(), 'search is disabled');
-  }
-  
+
   let testSearchInitiatedByKeyPress = function () {
-    EventUtils.synthesizeKey('a', {});
+    EventUtils.synthesizeKey("a", {}, cw);
     assertSearchIsEnabled();
-    
-    EventUtils.synthesizeKey('VK_BACK_SPACE', {});
+
+    EventUtils.synthesizeKey("VK_BACK_SPACE", {}, cw);
     assertSearchIsDisabled();
   }
-  
+
   let testSearchInitiatedByMouseClick = function () {
-    EventUtils.sendMouseEvent({type: 'mousedown'}, searchButton, contentWindow);
+    EventUtils.sendMouseEvent({type: "mousedown"}, searchButton, cw);
     assertSearchIsEnabled();
-    
-    EventUtils.synthesizeKey('a', {});
-    EventUtils.synthesizeKey('VK_BACK_SPACE', {});
-    EventUtils.synthesizeKey('VK_BACK_SPACE', {});
+
+    EventUtils.synthesizeKey("a", {}, cw);
+    EventUtils.synthesizeKey("VK_BACK_SPACE", {}, cw);
+    EventUtils.synthesizeKey("VK_BACK_SPACE", {}, cw);
     assertSearchIsEnabled();
-    
-    EventUtils.synthesizeKey('VK_ESCAPE', {});
+
+    EventUtils.synthesizeKey("VK_ESCAPE", {}, cw);
     assertSearchIsDisabled();
   }
-  
-  let finishTest = function () {
-    let onTabViewHidden = function () {
-      window.removeEventListener('tabviewhidden', onTabViewHidden, false);
+
+  waitForExplicitFinish();
+
+  newWindowWithTabView(function (win) {
+    registerCleanupFunction(function () win.close());
+
+    cw = win.TabView.getContentWindow();
+    search = cw.document.getElementById("search");
+    searchButton = cw.document.getElementById("searchbutton");
+
+    SimpleTest.waitForFocus(function () {
+      assertSearchIsDisabled();
+
+      testSearchInitiatedByKeyPress();
+      testSearchInitiatedByMouseClick();
+
       finish();
-    }
-    
-    window.addEventListener('tabviewhidden', onTabViewHidden, false);
-    TabView.hide();
-  }
-  
-  assertSearchIsDisabled();
-  
-  testSearchInitiatedByKeyPress();
-  testSearchInitiatedByMouseClick();
-  
-  finishTest();
+    }, cw);
+  });
 }
--- a/browser/base/content/test/tabview/browser_tabview_bug602432.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug602432.js
@@ -1,72 +1,45 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 function test() {
-  waitForExplicitFinish();
-  newWindowWithTabView(onTabViewWindowLoaded);
-}
-
-let contentWindow = null;
-
-function onTabViewWindowLoaded(win) {
-  ok(win.TabView.isVisible(), "Tab View is visible");
-
-  contentWindow = win.TabView.getContentWindow();
-
-  // Preparation
-  //
-  let numTabs = 10;
-  let groupItem = createGroupItemWithBlankTabs(win, 150, 150, 100,
-    numTabs, false);
-
-  // Ensure that group is stacked
-  ok(groupItem.isStacked(), "Group item is stacked");
+  let checkUpdateTimes = function (groupItem) {
+    let children = groupItem.getChildren();
+    let earliestUpdateTime = children.shift()._testLastTabUpdateTime;
 
-  // Force updates to be deferred
-  contentWindow.TabItems.pausePainting();
-  let children = groupItem.getChildren();
-  is(children.length, numTabs, "Correct number of tabitems created");
-   
-  let leftToUpdate = numTabs;
-  let testFunc = function(tabItem) {
-    tabItem.removeSubscriber(tabItem, "updated");
-    if (--leftToUpdate>0)
-      return;
-    // Now that everything is updated, compare update times.
-    // All tabs in the group should have updated AFTER the first one.
-    let earliest = children[0]._lastTabUpdateTime;
-    for (let c=1; c<children.length; ++c)
-      ok(earliest <= children[c]._lastTabUpdateTime,
-        "Stacked group item update ("+children[c]._lastTabUpdateTime+") > first item ("+earliest+")");
-    shutDown(win, groupItem);
-  };
-
-  for (let c=0; c<children.length; ++c) {
-    let tabItem = children[c];
-    tabItem.addSubscriber(tabItem, "updated", testFunc);
-    contentWindow.TabItems.update(tabItem.tab);
+    children.forEach(function (tabItem) {
+      let updateTime = tabItem._testLastTabUpdateTime;
+      ok(earliestUpdateTime <= updateTime, "Stacked group item update (" +
+         updateTime + ") > first item (" + earliestUpdateTime + ")");
+    });
   }
 
-  // Let the update queue start again
-  contentWindow.TabItems.resumePainting();
-}
+  waitForExplicitFinish();
+
+  newWindowWithTabView(function (win) {
+    registerCleanupFunction(function () win.close());
+
+    let numTabsToUpdate = 10;
+    let groupItem = createGroupItemWithBlankTabs(win, 150, 150, 100, numTabsToUpdate, false);
+    ok(groupItem.isStacked(), "groupItem is stacked");
+
+    let cw = win.TabView.getContentWindow();
+    cw.TabItems.pausePainting();
 
-function shutDown(win, groupItem) {
-  // Shut down
-  let groupItemCount = contentWindow.GroupItems.groupItems.length;
-  closeGroupItem(groupItem, function() {
-    // check the number of groups.
-    is(contentWindow.GroupItems.groupItems.length, --groupItemCount,
-       "The number of groups is decreased by 1");
-    let onTabViewHidden = function() {
-      win.removeEventListener("tabviewhidden", onTabViewHidden, false);
-      // assert that we're no longer in tab view
-      ok(!TabView.isVisible(), "Tab View is hidden");
-      win.close();
-      ok(win.closed, "new window is closed");
-      finish();
-    };
-    win.addEventListener("tabviewhidden", onTabViewHidden, false);
-    win.TabView.toggle();
+    groupItem.getChildren().forEach(function (tabItem) {
+      tabItem.addSubscriber(tabItem, "updated", function () {
+        tabItem.removeSubscriber(tabItem, "updated");
+        tabItem._testLastTabUpdateTime = tabItem._lastTabUpdateTime;
+
+        if (--numTabsToUpdate)
+          return;
+
+        checkUpdateTimes(groupItem);
+        finish();
+      });
+
+      cw.TabItems.update(tabItem.tab);
+    });
+
+    cw.TabItems.resumePainting();
   });
 }
--- a/browser/base/content/test/tabview/browser_tabview_bug626791.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug626791.js
@@ -15,20 +15,16 @@ function test() {
           prefix + ": panorama button should be in the toolbar");
   }
 
   let assertToolbarButtonNotExists = function () {
     is(getToolbar().currentSet.indexOf("tabview-button"), -1,
        prefix + ": panorama button should not be in the toolbar");
   }
 
-  let assertNumberOfGroups = function (num) {
-    is(cw.GroupItems.groupItems.length, num, prefix + ': there are ' + num + ' groups');
-  }
-
   let assertNumberOfTabs = function (num) {
     is(win.gBrowser.tabs.length, num, prefix + ': there are ' + num + ' tabs');
   }
 
   let removeToolbarButton = function () {
     let toolbar = getToolbar();
     let currentSet = toolbar.currentSet.split(",");
     let buttonId = "tabview-button";
@@ -86,17 +82,17 @@ function test() {
     EventUtils.synthesizeMouse(body, width - 10, height - 10, {}, cw);
     EventUtils.synthesizeMouse(body, width - 10, height - 10, {}, cw);
 
     whenTabViewIsHidden(function () {
       assertNumberOfTabs(2);
       assertToolbarButtonExists();
 
       next();
-    });
+    }, win);
   }
 
   let testDragToCreateOrphan = function (tab) {
     if (!tab) {
       let tab = win.gBrowser.loadOneTab('about:blank', {inBackground: true});
       afterAllTabsLoaded(function () testDragToCreateOrphan(tab), win);
       return;
     }
@@ -119,60 +115,65 @@ function test() {
     assertToolbarButtonExists();
     next();
   }
 
   let testReAddingAfterRemoval = function () {
     prefix = 're-adding-after-removal';
     assertToolbarButtonNotExists();
 
-    TabView.firstUseExperienced = true;
+    win.TabView.firstUseExperienced = true;
+    assertToolbarButtonExists();
     removeToolbarButton();
+    assertToolbarButtonNotExists();
+
+    win.close();
 
-    TabView.firstUseExperienced = true;
-    TabView._addToolbarButton();
-
-    assertToolbarButtonNotExists();
-    next();
+    newWindowWithTabView(function (newWin) {
+      win = newWin;
+      win.TabView.firstUseExperienced = true;
+      assertToolbarButtonNotExists();
+      next();
+    });
   }
 
   let tests = [testNameGroup, testDragToCreateGroup, testCreateOrphan,
                testDragToCreateOrphan, testReAddingAfterRemoval];
 
   let next = function () {
     let test = tests.shift();
 
-    if (win)
-      win.close();
-
     if (!test) {
       finish();
       return;
     }
 
-    newWindowWithTabView(
-      function (newWin) {
-        cw = win.TabView.getContentWindow();
-        let groupItem = cw.GroupItems.groupItems[0];
-        groupItem.setSize(200, 200, true);
-        groupItem.setUserSize();
+    if (win)
+      win.close();
+
+    TabView.firstUseExperienced = false;
 
+    let onLoad = function (newWin) {
+      win = newWin;
+      removeToolbarButton();
+    }
+
+    let onShow = function () {
+      cw = win.TabView.getContentWindow();
+
+      let groupItem = cw.GroupItems.groupItems[0];
+      groupItem.setSize(200, 200, true);
+      groupItem.setUserSize();
+
+      SimpleTest.waitForFocus(function () {
         assertToolbarButtonNotExists();
         test();
-      },
-      function(newWin) {
-        win = newWin;
-        removeToolbarButton();
-        TabView.firstUseExperienced = false;
-        TabView.init();
-      }
-    );
+      }, cw);
+    }
+
+    newWindowWithTabView(onShow, onLoad);
   }
 
   waitForExplicitFinish();
-
-  registerCleanupFunction(function () {
-    if (win && !win.closed)
-      win.close();
-  });
+  registerCleanupFunction(function () win && win.close());
 
   next();
 }
--- a/browser/base/content/test/tabview/browser_tabview_rtl.js
+++ b/browser/base/content/test/tabview/browser_tabview_rtl.js
@@ -1,61 +1,46 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
-let tabViewShownCount = 0;
-
 // ----------
 function test() {
   waitForExplicitFinish();
 
   // verify initial state
   ok(!TabView.isVisible(), "Tab View starts hidden");
 
-  // use the Tab View button to launch it for the first time
-  window.addEventListener("tabviewshown", onTabViewLoadedAndShown("ltr"), false);
-  toggleTabView();
-}
-
-function toggleTabView() {
-  let tabViewCommand = document.getElementById("Browser:ToggleTabView");
-  tabViewCommand.doCommand();
+  showTabView(onTabViewLoadedAndShown("ltr"));
 }
 
 // ----------
 function onTabViewLoadedAndShown(dir) {
   return function() {
-    window.removeEventListener("tabviewshown", arguments.callee, false);
     ok(TabView.isVisible(), "Tab View is visible.");
 
     let contentWindow = document.getElementById("tab-view").contentWindow;
     let contentDocument = contentWindow.document;
     is(contentDocument.documentElement.getAttribute("dir"), dir,
        "The direction should be set to " + dir.toUpperCase());
 
     // kick off the series
-    window.addEventListener("tabviewhidden", onTabViewHidden(dir), false);
-    TabView.toggle();
+    hideTabView(onTabViewHidden(dir));
   };
 }
 
 // ---------- 
 function onTabViewHidden(dir) {
   return function() {
-    window.removeEventListener("tabviewhidden", arguments.callee, false);
     ok(!TabView.isVisible(), "Tab View is hidden.");
 
     if (dir == "ltr") {
       // Switch to RTL mode
       Services.prefs.setCharPref("intl.uidirection.en-US", "rtl");
 
-      // use the Tab View button to launch it for the second time
-      window.addEventListener("tabviewshown", onTabViewLoadedAndShown("rtl"), false);
-      toggleTabView();
+      showTabView(onTabViewLoadedAndShown("rtl"));
     } else {
       // Switch to LTR mode
       Services.prefs.clearUserPref("intl.uidirection.en-US");
 
       finish();
     }
   };
 }
-
--- a/browser/components/feeds/content/subscribe.xml
+++ b/browser/components/feeds/content/subscribe.xml
@@ -44,17 +44,17 @@
           xmlns="http://www.mozilla.org/xbl"
           xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
   <binding id="feedreaderUI">
     <content>
       <xul:vbox>
         <xul:hbox align="center">
           <xul:description anonid="subscribeUsingDescription" class="subscribeUsingDescription"/>
           <xul:menulist anonid="handlersMenuList" class="handlersMenuList" aria-labelledby="subscribeUsingDescription">
-            <xul:menupopup menugenerated="true" anonid="handlersMenuPopup" class="handlersMenuPopup">
+            <xul:menupopup anonid="handlersMenuPopup" class="handlersMenuPopup">
               <xul:menuitem anonid="liveBookmarksMenuItem" label="&feedLiveBookmarks;" class="menuitem-iconic liveBookmarksMenuItem" image="chrome://browser/skin/page-livemarks.png" selected="true"/>
               <xul:menuseparator/>
             </xul:menupopup>
           </xul:menulist>
         </xul:hbox>
         <xul:hbox>
           <xul:checkbox anonid="alwaysUse" class="alwaysUse" checked="false"/>
         </xul:hbox>
--- a/browser/components/sessionstore/test/browser/head.js
+++ b/browser/components/sessionstore/test/browser/head.js
@@ -94,11 +94,12 @@ function waitForBrowserState(aState, aSe
 function waitForSaveState(aSaveStateCallback) {
   let topic = "sessionstore-state-write";
   Services.obs.addObserver(function() {
     Services.obs.removeObserver(arguments.callee, topic, false);
     executeSoon(aSaveStateCallback);
   }, topic, false);
 };
 
+var gUniqueCounter = 0;
 function r() {
-  return Date.now() + Math.random();
+  return Date.now() + "-" + (++gUniqueCounter);
 }
--- a/build/automation.py.in
+++ b/build/automation.py.in
@@ -629,20 +629,17 @@ user_pref("camino.use_system_proxy_setti
       STILL_ACTIVE = 259
       PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
       pHandle = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid)
       if not pHandle:
         return False
       pExitCode = ctypes.wintypes.DWORD()
       ctypes.windll.kernel32.GetExitCodeProcess(pHandle, ctypes.byref(pExitCode))
       ctypes.windll.kernel32.CloseHandle(pHandle)
-      if (pExitCode.value == STILL_ACTIVE):
-        return True
-      else:
-        return False
+      return pExitCode.value == STILL_ACTIVE
 
     def killPid(self, pid):
       PROCESS_TERMINATE = 0x0001
       pHandle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, 0, pid)
       if not pHandle:
         return
       success = ctypes.windll.kernel32.TerminateProcess(pHandle, 1)
       ctypes.windll.kernel32.CloseHandle(pHandle)
@@ -663,20 +660,17 @@ user_pref("camino.use_system_proxy_setti
       try:
         # kill(pid, 0) checks for a valid PID without actually sending a signal
         # The method throws OSError if the PID is invalid, which we catch below.
         os.kill(pid, 0)
 
         # Wait on it to see if it's a zombie. This can throw OSError.ECHILD if
         # the process terminates before we get to this point.
         wpid, wstatus = os.waitpid(pid, os.WNOHANG)
-        if wpid == 0:
-          return True
-
-        return False
+        return wpid == 0
       except OSError, err:
         # Catch the errors we might expect from os.kill/os.waitpid, 
         # and re-raise any others
         if err.errno == errno.ESRCH or err.errno == errno.ECHILD:
           return False
         raise
 
     def killPid(self, pid):
@@ -912,54 +906,40 @@ user_pref("camino.use_system_proxy_setti
     if os.path.exists(processLog):
       os.unlink(processLog)
 
     if self.IS_TEST_BUILD and runSSLTunnel:
       ssltunnelProcess.kill()
 
     return status
 
-  """ 
-   Copies an "installed" extension into the extensions directory of the given profile
-   extensionSource - the source location of the extension files.  This can be either 
+  """
+   Copies an extension into the extensions directory of the given profile.
+   extensionSource - the source location of the extension files.  This can be either
                      a directory or a path to an xpi file.
    profileDir      - the profile directory we are copying into.  We will create the
-                     "extensions" directory there if it doesn't exist
+                     "extensions" directory there if it doesn't exist.
    extensionID     - the id of the extension to be used as the containing directory for the
-                     extension, i.e.
+                     extension, if extensionSource is a directory, i.e.
                  this is the name of the folder in the <profileDir>/extensions/<extensionID>
   """
-  def installExtension(self, extensionSource, profileDir, extensionID):
-    if (not os.path.exists(extensionSource)):
-      self.log.info("INFO | automation.py | Cannot install extension no source at: %s", extensionSource) 
-      return
-      
-    if (not os.path.exists(profileDir)):
-      self.log.info("INFO | automation.py | Cannot install extension invalid profileDir at: %s", profileDir)
+  def installExtension(self, extensionSource, profileDir, extensionID = None):
+    if not os.path.isdir(profileDir):
+      self.log.info("INFO | automation.py | Cannot install extension, invalid profileDir at: %s", profileDir)
       return
 
-    # See if we have an XPI or a directory
-    if (os.path.isfile(extensionSource)):
-      tmpd = tempfile.mkdtemp()
-      extrootdir = self.extractZip(extensionSource, tmpd)
-    else:
-      extrootdir = extensionSource 
     extnsdir = os.path.join(profileDir, "extensions")
-    extnshome = os.path.join(extnsdir, extensionID)
-
-    # Now we copy the extension source into the extnshome
-    shutil.copytree(extrootdir, extnshome)
 
-  def extractZip(self, filename, dest):
-    z = zipfile.ZipFile(filename, 'r')
-    for n in z.namelist():
-      fullpath = os.path.join(dest, n)
-      parentdir = os.path.dirname(fullpath)
-      if not os.path.isdir(parentdir):
-        os.makedirs(parentdir)
-      if (not n.endswith(os.sep)):
-        data = z.read(n)
-        f = open(fullpath, 'w')
-        f.write(data)
-        f.close()
-    z.close()
-    return dest
+    if os.path.isfile(extensionSource):
+      # Copy extension xpi directly.
+      # "destination file is created or overwritten".
+      shutil.copy2(extensionSource, extnsdir)
+    elif os.path.isdir(extensionSource):
+      if extensionID == None:
+        self.log.info("INFO | automation.py | Cannot install extension, missing extensionID")
+        return
 
+      # Copy extension tree into its own directory.
+      # "destination directory must not already exist".
+      shutil.copytree(extensionSource, os.path.join(extnsdir, extensionID))
+    else:
+      self.log.info("INFO | automation.py | Cannot install extension, invalid extensionSource at: %s", extensionSource)
+      return
new file mode 100644
--- /dev/null
+++ b/build/stdc++compat.cpp
@@ -0,0 +1,114 @@
+/* ***** 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 a hack to avoid dependencies on recent libstdc++.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Mike Hommey <mh@glandium.org>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include <ostream>
+#include <istream>
+#ifdef DEBUG
+#include <string>
+#endif
+
+namespace std {
+#if (__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)
+    /* Instantiate these templates to avoid GLIBCXX_3.4.9 symbol versions */
+    template ostream& ostream::_M_insert(double);
+    template ostream& ostream::_M_insert(long);
+    template ostream& ostream::_M_insert(unsigned long);
+    template ostream& __ostream_insert(ostream&, const char*, streamsize);
+    template istream& istream::_M_extract(double&);
+#endif
+#ifdef DEBUG
+#if (__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)
+    /* Instantiate these templates to avoid GLIBCXX_3.4.14 symbol versions
+     * in debug builds */
+    template char *basic_string<char, char_traits<char>, allocator<char> >::_S_construct_aux_2(size_type, char, allocator<char> const&);
+    template wchar_t *basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> >::_S_construct_aux_2(size_type, wchar_t, allocator<wchar_t> const&);
+#endif
+#endif
+}
+
+namespace std __attribute__((visibility("default"))) {
+
+#if (__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)
+    /* Hack to avoid GLIBCXX_3.4.14 symbol versions */
+    struct _List_node_base
+    {
+        void hook(_List_node_base * const __position) throw ();
+
+        void unhook() throw ();
+
+        void transfer(_List_node_base * const __first,
+                      _List_node_base * const __last) throw();
+
+        void _M_hook(_List_node_base * const __position) throw ();
+
+        void _M_unhook() throw ();
+
+        void _M_transfer(_List_node_base * const __first,
+                         _List_node_base * const __last) throw();
+    };
+
+    /* The functions actually have the same implementation */
+    void
+    _List_node_base::_M_hook(_List_node_base * const __position) throw ()
+    {
+        hook(__position);
+    }
+
+    void
+    _List_node_base::_M_unhook() throw ()
+    {
+        unhook();
+    }
+
+    void
+    _List_node_base::_M_transfer(_List_node_base * const __first,
+                                 _List_node_base * const __last) throw ()
+    {
+        transfer(__first, __last);
+    }
+#endif
+
+#if (__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)
+    /* Hack to avoid GLIBCXX_3.4.11 symbol versions
+       An inline definition of ctype<char>::_M_widen_init() used to be in
+       locale_facets.h before GCC 4.4, but moved out of headers in more
+       recent versions.
+       It is actually safe to make it do nothing. */
+    void ctype<char>::_M_widen_init() const {}
+#endif
+
+}
--- a/build/unix/elfhack/Makefile.in
+++ b/build/unix/elfhack/Makefile.in
@@ -43,19 +43,22 @@ VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 INTERNAL_TOOLS = 1
 
 HOST_PROGRAM = elfhack
 NO_DIST_INSTALL = 1
 
+VPATH += $(topsrcdir)/build
+
 HOST_CPPSRCS = \
   elf.cpp \
   elfhack.cpp \
+  $(STDCXX_COMPAT) \
   $(NULL)
 
 OS_CXXFLAGS := $(filter-out -fno-exceptions,$(OS_CXXFLAGS)) -fexceptions
 
 ifneq (,$(filter %86,$(TARGET_CPU)))
 CPU := x86
 else
 ifneq (,$(filter arm%,$(TARGET_CPU)))
--- a/build/upload.py
+++ b/build/upload.py
@@ -52,18 +52,17 @@
 #
 # All files to be uploaded should be passed as commandline arguments to this
 # script. The script takes one other parameter, --base-path, which you can use
 # to indicate that files should be uploaded including their paths relative
 # to the base path.
 
 import sys, os
 from optparse import OptionParser
-from subprocess import Popen, PIPE
-from util import check_call
+from subprocess import PIPE, Popen, check_call
 
 def RequireEnvironmentVariable(v):
     """Return the value of the environment variable named v, or print
     an error and exit if it's unset (or empty)."""
     if not v in os.environ or os.environ[v] == "":
         print "Error: required environment variable %s not set" % v
         sys.exit(1)
     return os.environ[v]
deleted file mode 100644
--- a/build/util.py
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/usr/bin/python
-#
-# ***** 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
-# The Mozilla Foundation
-# Portions created by the Initial Developer are Copyright (C) 2008
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#  Ted Mielczarek <ted.mielczarek@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
-# 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 *****
-
-try:
-    from subprocess import check_call
-except ImportError:
-    import subprocess
-    def check_call(*popenargs, **kwargs):
-        retcode = subprocess.call(*popenargs, **kwargs)
-        if retcode:
-            cmd = kwargs.get("args")
-            if cmd is None:
-                cmd = popenargs[0]
-                raise Exception("Command '%s' returned non-zero exit status %i" % (cmd, retcode))
--- a/client.py
+++ b/client.py
@@ -10,17 +10,17 @@ LIBFFI_DIRS = (('js/ctypes/libffi', 'lib
 CVSROOT_MOZILLA = ':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot'
 CVSROOT_LIBFFI = ':pserver:anoncvs@sources.redhat.com:/cvs/libffi'
 
 import os
 import sys
 import datetime
 import shutil
 from optparse import OptionParser
-from build.util import check_call
+from subprocess import check_call
 
 topsrcdir = os.path.dirname(__file__)
 if topsrcdir == '':
     topsrcdir = '.'
 
 def check_call_noisy(cmd, *args, **kwargs):
     print "Executing command:", cmd
     check_call(cmd, *args, **kwargs)
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -112,16 +112,17 @@ MOZ_CALLGRIND   = @MOZ_CALLGRIND@
 MOZ_VTUNE       = @MOZ_VTUNE@
 MOZ_TRACE_JSCALLS = @MOZ_TRACE_JSCALLS@
 MOZ_TRACEVIS    = @MOZ_TRACEVIS@
 DEHYDRA_PATH    = @DEHYDRA_PATH@
 
 NS_TRACE_MALLOC = @NS_TRACE_MALLOC@
 USE_ELF_DYNSTR_GC = @USE_ELF_DYNSTR_GC@
 USE_ELF_HACK = @USE_ELF_HACK@
+STDCXX_COMPAT = @STDCXX_COMPAT@
 INCREMENTAL_LINKER = @INCREMENTAL_LINKER@
 MACOSX_DEPLOYMENT_TARGET = @MACOSX_DEPLOYMENT_TARGET@
 MOZ_MAIL_NEWS	= @MOZ_MAIL_NEWS@
 BUILD_STATIC_LIBS = @BUILD_STATIC_LIBS@
 MOZ_ENABLE_LIBXUL = @MOZ_ENABLE_LIBXUL@
 ENABLE_TESTS	= @ENABLE_TESTS@
 IBMBIDI = @IBMBIDI@
 MOZ_UNIVERSALCHARDET = @MOZ_UNIVERSALCHARDET@
--- a/config/config.mk
+++ b/config/config.mk
@@ -337,16 +337,21 @@ NO_PROFILE_GUIDED_OPTIMIZE = 1
 endif
 
 # Don't build SIMPLE_PROGRAMS with PGO, since they don't need it anyway,
 # and we don't have the same build logic to re-link them in the second pass.
 ifdef SIMPLE_PROGRAMS
 NO_PROFILE_GUIDED_OPTIMIZE = 1
 endif
 
+# No sense in profiling unit tests
+ifdef CPP_UNIT_TESTS
+NO_PROFILE_GUIDED_OPTIMIZE = 1
+endif
+
 # Enable profile-based feedback
 ifndef NO_PROFILE_GUIDED_OPTIMIZE
 ifdef MOZ_PROFILE_GENERATE
 OS_CFLAGS += $(PROFILE_GEN_CFLAGS)
 OS_CXXFLAGS += $(PROFILE_GEN_CFLAGS)
 OS_LDFLAGS += $(PROFILE_GEN_LDFLAGS)
 ifeq (WINNT,$(OS_ARCH))
 AR_FLAGS += -LTCG
@@ -437,21 +442,20 @@ MY_RULES	:= $(DEPTH)/config/myrules.mk
 # Default command macros; can be overridden in <arch>.mk.
 #
 CCC = $(CXX)
 NFSPWD = $(CONFIG_TOOLS)/nfspwd
 PURIFY = purify $(PURIFYOPTIONS)
 QUANTIFY = quantify $(QUANTIFYOPTIONS)
 ifdef CROSS_COMPILE
 XPIDL_COMPILE = $(LIBXUL_DIST)/host/bin/host_xpidl$(HOST_BIN_SUFFIX)
-XPIDL_LINK = $(LIBXUL_DIST)/host/bin/host_xpt_link$(HOST_BIN_SUFFIX)
 else
 XPIDL_COMPILE = $(LIBXUL_DIST)/bin/xpidl$(BIN_SUFFIX)
-XPIDL_LINK = $(LIBXUL_DIST)/bin/xpt_link$(BIN_SUFFIX)
 endif
+XPIDL_LINK = $(PYTHON) $(SDK_BIN_DIR)/xpt.py link
 
 # Java macros
 JAVA_GEN_DIR  = _javagen
 JAVA_DIST_DIR = $(DEPTH)/$(JAVA_GEN_DIR)
 JAVA_IFACES_PKG_NAME = org/mozilla/interfaces
 
 INCLUDES = \
   $(LOCAL_INCLUDES) \
@@ -840,8 +844,12 @@ CREATE_PRECOMPLETE_CMD = $(PYTHON) $(cal
 EXPAND_LIBS = $(PYTHON) -I$(DEPTH)/config $(topsrcdir)/config/expandlibs.py
 EXPAND_LIBS_EXEC = $(PYTHON) $(topsrcdir)/config/pythonpath.py -I$(DEPTH)/config $(topsrcdir)/config/expandlibs_exec.py
 EXPAND_LIBS_GEN = $(PYTHON) $(topsrcdir)/config/pythonpath.py -I$(DEPTH)/config $(topsrcdir)/config/expandlibs_gen.py
 EXPAND_AR = $(EXPAND_LIBS_EXEC) --extract -- $(AR)
 EXPAND_CC = $(EXPAND_LIBS_EXEC) --uselist -- $(CC)
 EXPAND_CCC = $(EXPAND_LIBS_EXEC) --uselist -- $(CCC)
 EXPAND_LD = $(EXPAND_LIBS_EXEC) --uselist -- $(LD)
 EXPAND_MKSHLIB = $(EXPAND_LIBS_EXEC) --uselist -- $(MKSHLIB)
+
+ifdef STDCXX_COMPAT
+CHECK_STDCXX = objdump -p $(1) | grep -e 'GLIBCXX_3\.4\.\(9\|[1-9][0-9]\)' && echo "Error: We don't want these libstdc++ symbol versions to be used" && exit 1 || exit 0
+endif
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -356,16 +356,21 @@ ifeq (86,$(findstring 86,$(OS_TEST)))
 OS_LDFLAGS += -M $(topsrcdir)/config/solaris_ia32.map
 endif # x86
 endif # Solaris Sun Studio C++
 
 ifeq (,$(filter-out WINNT WINCE,$(HOST_OS_ARCH)))
 HOST_PDBFILE=$(basename $(@F)).pdb
 endif
 
+# Don't build SIMPLE_PROGRAMS during the MOZ_PROFILE_GENERATE pass
+ifdef MOZ_PROFILE_GENERATE
+SIMPLE_PROGRAMS :=
+endif
+
 ifndef TARGETS
 TARGETS			= $(LIBRARY) $(SHARED_LIBRARY) $(PROGRAM) $(SIMPLE_PROGRAMS) $(HOST_LIBRARY) $(HOST_PROGRAM) $(HOST_SIMPLE_PROGRAMS) $(JAVA_LIBRARY)
 endif
 
 ifndef OBJS
 _OBJS			= \
 	$(JRI_STUB_CFILES) \
 	$(addsuffix .$(OBJ_SUFFIX), $(JMC_GEN)) \
@@ -982,16 +987,17 @@ endif	# MSVC with manifest tool
 ifdef MOZ_PROFILE_GENERATE
 # touch it a few seconds into the future to work around FAT's
 # 2-second granularity
 	touch -t `date +%Y%m%d%H%M.%S -d "now+5seconds"` pgo.relink
 endif
 else # !WINNT || GNU_CC
 ifeq ($(CPP_PROG_LINK),1)
 	$(EXPAND_CCC) -o $@ $(CXXFLAGS) $(WRAP_MALLOC_CFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(WRAP_MALLOC_LIB) $(EXE_DEF_FILE)
+	$(call CHECK_STDCXX,$@)
 else # ! CPP_PROG_LINK
 	$(EXPAND_CC) -o $@ $(CFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(EXE_DEF_FILE)
 endif # CPP_PROG_LINK
 endif # WINNT && !GNU_CC
 endif # WINCE
 
 ifdef ENABLE_STRIP
 	$(STRIP) $@
@@ -1047,16 +1053,17 @@ ifdef MSMANIFEST_TOOL
 	@if test -f $@.manifest; then \
 		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
 		rm -f $@.manifest; \
 	fi
 endif	# MSVC with manifest tool
 else
 ifeq ($(CPP_PROG_LINK),1)
 	$(EXPAND_CCC) $(WRAP_MALLOC_CFLAGS) $(CXXFLAGS) -o $@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(WRAP_MALLOC_LIB) $(BIN_FLAGS)
+	$(call CHECK_STDCXX,$@)
 else
 	$(EXPAND_CC) $(WRAP_MALLOC_CFLAGS) $(CFLAGS) $(OUTOPTION)$@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(WRAP_MALLOC_LIB) $(BIN_FLAGS)
 endif # CPP_PROG_LINK
 endif # WINNT && !GNU_CC
 endif # WINCE
 
 ifdef ENABLE_STRIP
 	$(STRIP) $@
@@ -1167,16 +1174,17 @@ ifdef DTRACE_LIB_DEPENDENT
 ifndef XP_MACOSX
 	dtrace -G -C -s $(MOZILLA_DTRACE_SRC) -o  $(DTRACE_PROBE_OBJ) $(shell $(EXPAND_LIBS) $(MOZILLA_PROBE_LIBS))
 endif
 	$(EXPAND_MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(DTRACE_PROBE_OBJ) $(MOZILLA_PROBE_LIBS) $(RESFILE) $(LDFLAGS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
 	@$(RM) $(DTRACE_PROBE_OBJ)
 else # ! DTRACE_LIB_DEPENDENT
 	$(EXPAND_MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(DTRACE_PROBE_OBJ) $(LOBJS) $(SUB_SHLOBJS) $(RESFILE) $(LDFLAGS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
 endif # DTRACE_LIB_DEPENDENT
+	$(call CHECK_STDCXX,$@)
 
 ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
 ifdef MSMANIFEST_TOOL
 ifdef EMBED_MANIFEST_AT
 	@if test -f $@.manifest; then \
 		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;$(EMBED_MANIFEST_AT); \
 		rm -f $@.manifest; \
 	fi
@@ -1565,17 +1573,17 @@ ifndef NO_GEN_XPT
 # generate intermediate .xpt files into $(XPIDL_GEN_DIR), then link
 # into $(XPIDL_MODULE).xpt and export it to $(FINAL_TARGET)/components.
 $(XPIDL_GEN_DIR)/%.xpt: %.idl $(XPIDL_COMPILE) $(XPIDL_GEN_DIR)/.done
 	$(REPORT_BUILD)
 	$(ELOG) $(XPIDL_COMPILE) -m typelib -w $(XPIDL_FLAGS) -e $@ -d $(MDDEPDIR)/$*.pp $(_VPATH_SRCS)
 
 # no need to link together if XPIDLSRCS contains only XPIDL_MODULE
 ifneq ($(XPIDL_MODULE).idl,$(strip $(XPIDLSRCS)))
-$(XPIDL_GEN_DIR)/$(XPIDL_MODULE).xpt: $(patsubst %.idl,$(XPIDL_GEN_DIR)/%.xpt,$(XPIDLSRCS)) $(GLOBAL_DEPS) $(XPIDL_LINK)
+$(XPIDL_GEN_DIR)/$(XPIDL_MODULE).xpt: $(patsubst %.idl,$(XPIDL_GEN_DIR)/%.xpt,$(XPIDLSRCS)) $(GLOBAL_DEPS)
 	$(XPIDL_LINK) $(XPIDL_GEN_DIR)/$(XPIDL_MODULE).xpt $(patsubst %.idl,$(XPIDL_GEN_DIR)/%.xpt,$(XPIDLSRCS))
 endif # XPIDL_MODULE.xpt != XPIDLSRCS
 
 libs:: $(XPIDL_GEN_DIR)/$(XPIDL_MODULE).xpt
 ifndef NO_DIST_INSTALL
 	$(INSTALL) $(IFLAGS1) $(XPIDL_GEN_DIR)/$(XPIDL_MODULE).xpt $(FINAL_TARGET)/components
 ifndef NO_INTERFACES_MANIFEST
 	@$(PYTHON) $(MOZILLA_DIR)/config/buildlist.py $(FINAL_TARGET)/components/interfaces.manifest "interfaces $(XPIDL_MODULE).xpt"
@@ -1696,17 +1704,17 @@ ifneq (,$(SDK_LIBRARY))
 
 ifndef NO_DIST_INSTALL
 libs:: $(SDK_LIBRARY) $(SDK_LIB_DIR)
 	$(INSTALL) $(IFLAGS2) $^
 endif
 
 endif # SDK_LIBRARY
 
-ifneq (,$(SDK_BINARY))
+ifneq (,$(strip $(SDK_BINARY)))
 $(SDK_BIN_DIR)::
 	$(NSINSTALL) -D $@
 
 ifndef NO_DIST_INSTALL
 libs:: $(SDK_BINARY) $(SDK_BIN_DIR)
 	$(INSTALL) $(IFLAGS2) $^
 endif
 
--- a/configure.in
+++ b/configure.in
@@ -3584,46 +3584,49 @@ fi # $no_x
 
 AC_SUBST(XCFLAGS)
 AC_SUBST(XLDFLAGS)
 AC_SUBST(XLIBS)
 AC_SUBST(XEXT_LIBS)
 AC_SUBST(XT_LIBS)
 AC_SUBST(XSS_LIBS)
 
-AC_MSG_CHECKING(for ARM SIMD support in compiler)
-# We try to link so that this also fails when
-# building with LTO.
-AC_TRY_LINK([],
-               [asm("uqadd8 r1, r1, r2");],
-               result="yes", result="no")
-AC_MSG_RESULT("$result")
-if test "$result" = "yes"; then
-    AC_DEFINE(HAVE_ARM_SIMD)
-    HAVE_ARM_SIMD=1
-fi
+if test "$CPU_ARCH" = "arm"; then
+  AC_MSG_CHECKING(for ARM SIMD support in compiler)
+  # We try to link so that this also fails when
+  # building with LTO.
+  AC_TRY_LINK([],
+                 [asm("uqadd8 r1, r1, r2");],
+                 result="yes", result="no")
+  AC_MSG_RESULT("$result")
+  if test "$result" = "yes"; then
+      AC_DEFINE(HAVE_ARM_SIMD)
+      HAVE_ARM_SIMD=1
+  fi
+
+  AC_MSG_CHECKING(for ARM NEON support in compiler)
+  _SAVE_CFLAGS="$CFLAGS"
+  if test "$GNU_CC"; then
+    # gcc needs -mfpu=neon to recognize NEON instructions
+    CFLAGS="$CFLAGS -mfpu=neon -mfloat-abi=softfp"
+  fi
+  # We try to link so that this also fails when
+  # building with LTO.
+  AC_TRY_LINK([],
+                 [asm("vadd.i8 d0, d0, d0");],
+                 result="yes", result="no")
+  AC_MSG_RESULT("$result")
+  if test "$result" = "yes"; then
+      AC_DEFINE(HAVE_ARM_NEON)
+      HAVE_ARM_NEON=1
+  fi
+  CFLAGS="$_SAVE_CFLAGS"
+fi # CPU_ARCH = arm
+
 AC_SUBST(HAVE_ARM_SIMD)
-
-AC_MSG_CHECKING(for ARM NEON support in compiler)
-_SAVE_CFLAGS="$CFLAGS"
-if test "$GNU_CC"; then
-  # gcc needs -mfpu=neon to recognize NEON instructions
-  CFLAGS="$CFLAGS -mfpu=neon -mfloat-abi=softfp"
-fi
-# We try to link so that this also fails when
-# building with LTO.
-AC_TRY_LINK([],
-               [asm("vadd.i8 d0, d0, d0");],
-               result="yes", result="no")
-AC_MSG_RESULT("$result")
-if test "$result" = "yes"; then
-    AC_DEFINE(HAVE_ARM_NEON)
-    HAVE_ARM_NEON=1
-fi
-CFLAGS="$_SAVE_CFLAGS"
 AC_SUBST(HAVE_ARM_NEON)
 
 dnl ========================================================
 dnl = pthread support
 dnl = Start by checking whether the system support pthreads
 dnl ========================================================
 case "$target_os" in
 darwin*)
@@ -6430,17 +6433,17 @@ if test -n "$LIBJPEG_TURBO_X86_ASM" -o -
     if test -z "$LIBJPEG_TURBO_AS" ; then
         AC_MSG_ERROR([yasm is required to build with libjpeg-turbo's optimized JPEG decoding routines, but you do not appear to have yasm installed.  Either install it or configure with --disable-libjpeg-turbo to use the pure C JPEG decoder.  See https://developer.mozilla.org/en/YASM for more details.])
     fi
 
     dnl Check that we have the right yasm version.  We require 1.0.1 or newer
     dnl on Linux and 1.1 or newer everywhere else.
     if test "$OS_ARCH" = "Linux" ; then
         if test "$_YASM_MAJOR_VERSION" -lt "1" -o \( "$_YASM_MAJOR_VERSION" -eq "1" -a "$_YASM_MINOR_VERSION" -eq "0" -a "$_YASM_RELEASE" -lt "1" \) ; then
-            AC_MSG_ERROR([yasm 1.0.1 or greater is required to build with libjpeg-turbo's optimized JPEG decoding routines, but you appear to have version $_YASM_MAJOR_VERSION.$_YASM_MINOR_VERSION.$_YASM_MINOR_VERSION.  Upgrade to the newest version or configure with --disable-libjpeg-turbo to use the pure C JPEG decoder.  See https://developer.mozilla.org/en/YASM for more details.])
+            AC_MSG_ERROR([yasm 1.0.1 or greater is required to build with libjpeg-turbo's optimized JPEG decoding routines, but you appear to have version $_YASM_MAJOR_VERSION.$_YASM_MINOR_VERSION.$_YASM_RELEASE.  Upgrade to the newest version or configure with --disable-libjpeg-turbo to use the pure C JPEG decoder.  See https://developer.mozilla.org/en/YASM for more details.])
         fi
     else
         if test "$_YASM_MAJOR_VERSION" -lt "1" -o \( "$_YASM_MAJOR_VERSION" -eq "1" -a "$_YASM_MINOR_VERSION" -lt "1" \) ; then
             AC_MSG_ERROR([yasm 1.1 or greater is required to build with libjpeg-turbo's optimized JPEG decoding routines, but you appear to have version $_YASM_MAJOR_VERSION.$_YASM_MINOR_VERSION.  Upgrade to the newest version or configure with --disable-libjpeg-turbo to use the pure C JPEG decoder.  See https://developer.mozilla.org/en/YASM for more details.])
         fi
     fi
 fi
 
@@ -7709,16 +7712,38 @@ if test "$USE_ELF_HACK" = 1; then
         ;;
     *)
         USE_ELF_HACK=
         ;;
     esac
 fi
 
 dnl ========================================================
+dnl = libstdc++ compatibility hacks
+dnl ========================================================
+
+STDCXX_COMPAT=stdc++compat.cpp
+MOZ_ARG_DISABLE_BOOL(stdcxx-compat,
+[  --disable-stdcxx-compat Disable libstdc++ compatibility],
+    STDCXX_COMPAT=)
+
+# Disable on platforms where it doesn't make sense
+if test -n "$STDCXX_COMPAT"; then
+    case "${OS_TARGET}" in
+    Linux)
+        ;;
+    *)
+        STDCXX_COMPAT=
+        ;;
+    esac
+fi
+
+AC_SUBST(STDCXX_COMPAT)
+
+dnl ========================================================
 dnl = 
 dnl = Profiling and Instrumenting
 dnl = 
 dnl ========================================================
 MOZ_ARG_HEADER(Profiling and Instrumenting)
 
 dnl ========================================================
 dnl = Enable timeline service, which provides lightweight
--- a/content/base/public/nsDOMFile.h
+++ b/content/base/public/nsDOMFile.h
@@ -39,32 +39,34 @@
 #ifndef nsDOMFile_h__
 #define nsDOMFile_h__
 
 #include "nsICharsetDetectionObserver.h"
 #include "nsIDOMFile.h"
 #include "nsIDOMFileList.h"
 #include "nsIDOMFileError.h"
 #include "nsIInputStream.h"
+#include "nsIJSNativeInitializer.h"
 #include "nsCOMArray.h"
 #include "nsCOMPtr.h"
 #include "mozilla/AutoRestore.h"
 #include "nsString.h"
 #include "nsIXMLHttpRequest.h"
 #include "prmem.h"
 #include "nsAutoPtr.h"
 
 class nsIFile;
 class nsIInputStream;
 class nsIClassInfo;
 
 class nsDOMFile : public nsIDOMFile,
                   public nsIDOMBlob_MOZILLA_2_0_BRANCH,
                   public nsIXHRSendable,
-                  public nsICharsetDetectionObserver
+                  public nsICharsetDetectionObserver,
+                  public nsIJSNativeInitializer
 {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIDOMBLOB
   NS_DECL_NSIDOMFILE
   NS_DECL_NSIDOMBLOB_MOZILLA_2_0_BRANCH
   NS_DECL_NSIXHRSENDABLE
 
@@ -93,16 +95,27 @@ public:
     mContentType.SetIsVoid(PR_FALSE);
   }
 
   virtual ~nsDOMFile() {}
 
   // from nsICharsetDetectionObserver
   NS_IMETHOD Notify(const char *aCharset, nsDetectionConfident aConf);
 
+  // nsIJSNativeInitializer
+  NS_IMETHOD Initialize(nsISupports* aOwner,
+                        JSContext* aCx,
+                        JSObject* aObj,
+                        PRUint32 aArgc,
+                        jsval* aArgv);
+
+  // DOMClassInfo constructor (for File("foo"))
+  static nsresult
+  NewFile(nsISupports* *aNewObject);
+
 protected:
   nsCOMPtr<nsIFile> mFile;
 
   // start and length in 
   PRUint64 mStart;
   PRUint64 mLength;
 
   nsString mContentType;
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -4705,31 +4705,32 @@ nsContentUtils::RemoveScriptBlocker()
     sScriptBlockerCountWhereRunnersPrevented = 0;
   }
   if (sScriptBlockerCount) {
     return;
   }
 
   PRUint32 firstBlocker = sRunnersCountAtFirstBlocker;
   PRUint32 lastBlocker = (PRUint32)sBlockedScriptRunners->Count();
+  PRUint32 originalFirstBlocker = firstBlocker;
+  PRUint32 blockersCount = lastBlocker - firstBlocker;
   sRunnersCountAtFirstBlocker = 0;
   NS_ASSERTION(firstBlocker <= lastBlocker,
                "bad sRunnersCountAtFirstBlocker");
 
   while (firstBlocker < lastBlocker) {
     nsCOMPtr<nsIRunnable> runnable = (*sBlockedScriptRunners)[firstBlocker];
-    sBlockedScriptRunners->RemoveObjectAt(firstBlocker);
-    --lastBlocker;
+    ++firstBlocker;
 
     runnable->Run();
-    NS_ASSERTION(lastBlocker == (PRUint32)sBlockedScriptRunners->Count() &&
-                 sRunnersCountAtFirstBlocker == 0,
+    NS_ASSERTION(sRunnersCountAtFirstBlocker == 0,
                  "Bad count");
     NS_ASSERTION(!sScriptBlockerCount, "This is really bad");
   }
+  sBlockedScriptRunners->RemoveObjectsAt(originalFirstBlocker, blockersCount);
 }
 
 /* static */
 PRBool
 nsContentUtils::AddScriptRunner(nsIRunnable* aRunnable)
 {
   if (!aRunnable) {
     return PR_FALSE;
--- a/content/base/src/nsDOMDocumentType.cpp
+++ b/content/base/src/nsDOMDocumentType.cpp
@@ -53,70 +53,56 @@
 #include "nsIDOMDocument.h"
 #include "xpcpublic.h"
 
 nsresult
 NS_NewDOMDocumentType(nsIDOMDocumentType** aDocType,
                       nsNodeInfoManager *aNodeInfoManager,
                       nsIPrincipal *aPrincipal,
                       nsIAtom *aName,
-                      nsIDOMNamedNodeMap *aEntities,
-                      nsIDOMNamedNodeMap *aNotations,
                       const nsAString& aPublicId,
                       const nsAString& aSystemId,
                       const nsAString& aInternalSubset)
 {
   NS_PRECONDITION(aNodeInfoManager || aPrincipal,
                   "Must have a principal if no nodeinfo manager.");
   NS_ENSURE_ARG_POINTER(aDocType);
   NS_ENSURE_ARG_POINTER(aName);
 
-  nsresult rv;
-
   nsRefPtr<nsNodeInfoManager> nimgr;
   if (aNodeInfoManager) {
     nimgr = aNodeInfoManager;
   }
   else {
     nimgr = new nsNodeInfoManager();
-    NS_ENSURE_TRUE(nimgr, NS_ERROR_OUT_OF_MEMORY);
-    
-    rv = nimgr->Init(nsnull);
+    nsresult rv = nimgr->Init(nsnull);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nimgr->SetDocumentPrincipal(aPrincipal);
   }
 
   nsCOMPtr<nsINodeInfo> ni;
   ni = nimgr->GetNodeInfo(nsGkAtoms::documentTypeNodeName, nsnull,
                           kNameSpaceID_None);
   NS_ENSURE_TRUE(ni, NS_ERROR_OUT_OF_MEMORY);
 
-  *aDocType = new nsDOMDocumentType(ni.forget(), aName, aEntities, aNotations,
-                                    aPublicId, aSystemId, aInternalSubset);
-  if (!*aDocType) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
+  *aDocType = new nsDOMDocumentType(ni.forget(), aName, aPublicId, aSystemId,
+                                    aInternalSubset);
   NS_ADDREF(*aDocType);
 
   return NS_OK;
 }
 
 nsDOMDocumentType::nsDOMDocumentType(already_AddRefed<nsINodeInfo> aNodeInfo,
                                      nsIAtom *aName,
-                                     nsIDOMNamedNodeMap *aEntities,
-                                     nsIDOMNamedNodeMap *aNotations,
                                      const nsAString& aPublicId,
                                      const nsAString& aSystemId,
                                      const nsAString& aInternalSubset) :
   nsGenericDOMDataNode(aNodeInfo),
   mName(aName),
-  mEntities(aEntities),
-  mNotations(aNotations),
   mPublicId(aPublicId),
   mSystemId(aSystemId),
   mInternalSubset(aInternalSubset)
 {
 }
 
 nsDOMDocumentType::~nsDOMDocumentType()
 {
@@ -153,40 +139,16 @@ nsDOMDocumentType::GetText()
 
 NS_IMETHODIMP    
 nsDOMDocumentType::GetName(nsAString& aName)
 {
   mName->ToString(aName);
   return NS_OK;
 }
 
-NS_IMETHODIMP    
-nsDOMDocumentType::GetEntities(nsIDOMNamedNodeMap** aEntities)
-{
-  NS_ENSURE_ARG_POINTER(aEntities);
-
-  *aEntities = mEntities;
-
-  NS_IF_ADDREF(*aEntities);
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP    
-nsDOMDocumentType::GetNotations(nsIDOMNamedNodeMap** aNotations)
-{
-  NS_ENSURE_ARG_POINTER(aNotations);
-
-  *aNotations = mNotations;
-
-  NS_IF_ADDREF(*aNotations);
-
-  return NS_OK;
-}
-
 NS_IMETHODIMP
 nsDOMDocumentType::GetPublicId(nsAString& aPublicId)
 {
   aPublicId = mPublicId;
 
   return NS_OK;
 }
 
@@ -233,18 +195,18 @@ nsDOMDocumentType::GetNodeType(PRUint16*
 
   return NS_OK;
 }
 
 nsGenericDOMDataNode*
 nsDOMDocumentType::CloneDataNode(nsINodeInfo *aNodeInfo, PRBool aCloneText) const
 {
   nsCOMPtr<nsINodeInfo> ni = aNodeInfo;
-  return new nsDOMDocumentType(ni.forget(), mName, mEntities, mNotations,
-                               mPublicId, mSystemId, mInternalSubset);
+  return new nsDOMDocumentType(ni.forget(), mName, mPublicId, mSystemId,
+                               mInternalSubset);
 }
 
 nsresult
 nsDOMDocumentType::BindToTree(nsIDocument *aDocument, nsIContent *aParent,
                               nsIContent *aBindingParent,
                               PRBool aCompileEventHandlers)
 {
   if (!HasSameOwnerDoc(NODE_FROM(aParent, aDocument))) {
--- a/content/base/src/nsDOMDocumentType.h
+++ b/content/base/src/nsDOMDocumentType.h
@@ -34,18 +34,18 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Implementation of DOM Core's nsIDOMDocumentType node.
  */
 
-#ifndef nsDOMDocumentType_h___
-#define nsDOMDocumentType_h___
+#ifndef nsDOMDocumentType_h
+#define nsDOMDocumentType_h
 
 #include "nsCOMPtr.h"
 #include "nsIDOMDocumentType.h"
 #include "nsIContent.h"
 #include "nsGenericDOMDataNode.h"
 #include "nsString.h"
 
 // XXX DocumentType is currently implemented by inheriting the generic
@@ -54,18 +54,16 @@
 // this restricts what should be done for character data.
 
 class nsDOMDocumentType : public nsGenericDOMDataNode,
                           public nsIDOMDocumentType
 {
 public:
   nsDOMDocumentType(already_AddRefed<nsINodeInfo> aNodeInfo,
                     nsIAtom *aName,
-                    nsIDOMNamedNodeMap *aEntities,
-                    nsIDOMNamedNodeMap *aNotations,
                     const nsAString& aPublicId,
                     const nsAString& aSystemId,
                     const nsAString& aInternalSubset);
 
   virtual ~nsDOMDocumentType();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
@@ -81,27 +79,23 @@ public:
   virtual const nsTextFragment* GetText();
   virtual nsresult BindToTree(nsIDocument *aDocument, nsIContent *aParent,
                               nsIContent *aBindingParent,
                               PRBool aCompileEventHandlers);
 
   virtual nsXPCClassInfo* GetClassInfo();
 protected:
   nsCOMPtr<nsIAtom> mName;
-  nsCOMPtr<nsIDOMNamedNodeMap> mEntities;
-  nsCOMPtr<nsIDOMNamedNodeMap> mNotations;
   nsString mPublicId;
   nsString mSystemId;
   nsString mInternalSubset;
 };
 
 nsresult
 NS_NewDOMDocumentType(nsIDOMDocumentType** aDocType,
                       nsNodeInfoManager *aOwnerDoc,
                       nsIPrincipal *aPrincipal,
                       nsIAtom *aName,
-                      nsIDOMNamedNodeMap *aEntities,
-                      nsIDOMNamedNodeMap *aNotations,
                       const nsAString& aPublicId,
                       const nsAString& aSystemId,
                       const nsAString& aInternalSubset);
 
-#endif // nsDOMDocument_h___
+#endif // nsDOMDocumentType_h
--- a/content/base/src/nsDOMFile.cpp
+++ b/content/base/src/nsDOMFile.cpp
@@ -59,16 +59,17 @@
 #include "nsIUnicharInputStream.h"
 #include "nsIUnicodeDecoder.h"
 #include "nsNetCID.h"
 #include "nsNetUtil.h"
 #include "nsIUUIDGenerator.h"
 #include "nsFileDataProtocolHandler.h"
 #include "nsStringStream.h"
 #include "CheckedInt.h"
+#include "nsJSUtils.h"
 
 #include "plbase64.h"
 #include "prmem.h"
 
 using namespace mozilla;
 
 // XXXkhuey the input stream that we pass out of a DOMFile
 // can outlive the actual DOMFile object.  Thus, we must
@@ -138,16 +139,17 @@ DOMCI_DATA(Blob, nsDOMFile)
 
 NS_INTERFACE_MAP_BEGIN(nsDOMFile)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMFile)
   NS_INTERFACE_MAP_ENTRY(nsIDOMBlob)
   NS_INTERFACE_MAP_ENTRY(nsIDOMBlob_MOZILLA_2_0_BRANCH)
   NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIDOMFile, mIsFullFile)
   NS_INTERFACE_MAP_ENTRY(nsIXHRSendable)
   NS_INTERFACE_MAP_ENTRY(nsICharsetDetectionObserver)
+  NS_INTERFACE_MAP_ENTRY(nsIJSNativeInitializer)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO_CONDITIONAL(File, mIsFullFile)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO_CONDITIONAL(Blob, !mIsFullFile)
 NS_INTERFACE_MAP_END
 
 NS_IMPL_ADDREF(nsDOMFile)
 NS_IMPL_RELEASE(nsDOMFile)
 
 static nsresult
@@ -159,16 +161,24 @@ DOMFileResult(nsresult rv)
 
   if (NS_ERROR_GET_MODULE(rv) == NS_ERROR_MODULE_FILES) {
     return NS_ERROR_DOM_FILE_NOT_READABLE_ERR;
   }
 
   return rv;
 }
 
+/* static */ nsresult
+nsDOMFile::NewFile(nsISupports* *aNewObject)
+{
+  nsCOMPtr<nsISupports> file = do_QueryObject(new nsDOMFile(nsnull));
+  file.forget(aNewObject);
+  return NS_OK;
+}
+
 NS_IMETHODIMP
 nsDOMFile::GetFileName(nsAString &aFileName)
 {
   return GetName(aFileName);
 }
 
 NS_IMETHODIMP
 nsDOMFile::GetFileSize(PRUint64 *aFileSize)
@@ -606,16 +616,58 @@ nsDOMFile::GetSendInfo(nsIInputStream** 
 NS_IMETHODIMP
 nsDOMFile::Notify(const char* aCharset, nsDetectionConfident aConf)
 {
   mCharset.Assign(aCharset);
 
   return NS_OK;
 }
 
+NS_IMETHODIMP
+nsDOMFile::Initialize(nsISupports* aOwner,
+                      JSContext* aCx,
+                      JSObject* aObj,
+                      PRUint32 aArgc,
+                      jsval* aArgv)
+{
+  if (!nsContentUtils::IsCallerChrome()) {
+    return NS_ERROR_DOM_SECURITY_ERR; // Real short trip
+  }
+
+  NS_ENSURE_TRUE(aArgc > 0, NS_ERROR_UNEXPECTED);
+
+  // We expect to get a path to represent as a File object
+  if (!JSVAL_IS_STRING(aArgv[0]))
+    return NS_ERROR_UNEXPECTED;
+
+  JSString* str = JS_ValueToString(aCx, aArgv[0]);
+  NS_ENSURE_TRUE(str, NS_ERROR_XPC_BAD_CONVERT_JS);
+
+  nsDependentJSString xpcomStr;
+  if (!xpcomStr.init(aCx, str)) {
+    return NS_ERROR_XPC_BAD_CONVERT_JS;
+  }
+
+  nsCOMPtr<nsILocalFile> localFile;
+  nsresult rv = NS_NewLocalFile(xpcomStr,
+                                PR_FALSE, getter_AddRefs(localFile));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  nsCOMPtr<nsIFile> file = do_QueryInterface(localFile, &rv);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  PRBool exists;
+  rv = file->Exists(&exists);
+  NS_ENSURE_SUCCESS(rv, rv);
+  NS_ENSURE_TRUE(exists, NS_ERROR_FILE_NOT_FOUND);
+
+  mFile = file;
+  return NS_OK;
+}
+
 nsresult
 nsDOMFile::ConvertStream(nsIInputStream *aStream,
                          const char *aCharset,
                          nsAString &aResult)
 {
   aResult.Truncate();
 
   nsCOMPtr<nsIConverterInputStream> converterStream =
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -1436,18 +1436,18 @@ nsDOMImplementation::CreateDocumentType(
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIAtom> name = do_GetAtom(aQualifiedName);
   NS_ENSURE_TRUE(name, NS_ERROR_OUT_OF_MEMORY);
 
   // Indicate that there is no internal subset (not just an empty one)
   nsAutoString voidString;
   voidString.SetIsVoid(PR_TRUE);
-  return NS_NewDOMDocumentType(aReturn, nsnull, mPrincipal, name, nsnull,
-                               nsnull, aPublicId, aSystemId, voidString);
+  return NS_NewDOMDocumentType(aReturn, nsnull, mPrincipal, name, aPublicId,
+                               aSystemId, voidString);
 }
 
 NS_IMETHODIMP
 nsDOMImplementation::CreateDocument(const nsAString& aNamespaceURI,
                                     const nsAString& aQualifiedName,
                                     nsIDOMDocumentType* aDoctype,
                                     nsIDOMDocument** aReturn)
 {
@@ -1502,18 +1502,16 @@ nsDOMImplementation::CreateHTMLDocument(
   nsCOMPtr<nsIDOMDocumentType> doctype;
   // Indicate that there is no internal subset (not just an empty one)
   nsAutoString voidString;
   voidString.SetIsVoid(true);
   nsresult rv = NS_NewDOMDocumentType(getter_AddRefs(doctype),
                                       NULL, // aNodeInfoManager
                                       mPrincipal, // aPrincipal
                                       nsGkAtoms::html, // aName
-                                      NULL, // aEntities
-                                      NULL, // aNotations
                                       EmptyString(), // aPublicId
                                       EmptyString(), // aSystemId
                                       voidString); // aInternalSubset
   NS_ENSURE_SUCCESS(rv, rv);
 
 
   nsCOMPtr<nsIScriptGlobalObject> scriptHandlingObject =
     do_QueryReferent(mScriptObject);
@@ -6171,26 +6169,18 @@ nsDocument::AdoptNode(nsIDOMNode *aAdopt
   if (adoptedNode->GetOwnerDoc() != this) {
     return NS_ERROR_DOM_WRONG_DOCUMENT_ERR;
   }
 
   return CallQueryInterface(adoptedNode, aResult);
 }
 
 NS_IMETHODIMP
-nsDocument::GetDomConfig(nsIDOMDOMConfiguration **aConfig)
-{
-  return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-NS_IMETHODIMP
 nsDocument::NormalizeDocument()
 {
-  // We don't support DOMConfigurations yet, so this just
-  // does a straight shot of normalization.
   return Normalize();
 }
 
 NS_IMETHODIMP
 nsDocument::RenameNode(nsIDOMNode *aNode,
                        const nsAString& namespaceURI,
                        const nsAString& qualifiedName,
                        nsIDOMNode **aReturn)
@@ -8280,17 +8270,20 @@ nsDocument::AddImage(imgIRequest* aImage
 
 nsresult
 nsDocument::RemoveImage(imgIRequest* aImage)
 {
   NS_ENSURE_ARG_POINTER(aImage);
 
   // Get the old count. It should exist and be > 0.
   PRUint32 count;
-  PRBool found = mImageTracker.Get(aImage, &count);
+#ifdef DEBUG
+  PRBool found =
+#endif
+  mImageTracker.Get(aImage, &count);
   NS_ABORT_IF_FALSE(found, "Removing image that wasn't in the tracker!");
   NS_ABORT_IF_FALSE(count > 0, "Entry in the cache tracker with count 0!");
 
   // We're removing, so decrement the count.
   count--;
 
   // If the count is now zero, remove from the tracker.
   // Otherwise, set the new value.
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -4577,17 +4577,19 @@ nsGenericElement::MaybeCheckSameAttrVal(
     if (info.mValue) {
       // Check whether the old value is the same as the new one.  Note that we
       // only need to actually _get_ the old value if we have listeners.
       PRBool valueMatches;
       if (*aHasListeners) {
         // Need to store the old value
         info.mValue->ToString(*aOldValue);
         valueMatches = aValue.Equals(*aOldValue);
-      } else if (aNotify) {
+      } else {
+        NS_ABORT_IF_FALSE(aNotify,
+                          "Either hasListeners or aNotify should be true.");
         valueMatches = info.mValue->Equals(aValue, eCaseMatters);
       }
       if (valueMatches && aPrefix == info.mName->GetPrefix()) {
         return PR_TRUE;
       }
       modification = PR_TRUE;
     }
   }
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -556,17 +556,16 @@ GK_ATOM(maxwidth, "maxwidth")
 GK_ATOM(mayscript, "mayscript")
 GK_ATOM(media, "media")
 GK_ATOM(mediaType, "media-type")
 GK_ATOM(member, "member")
 GK_ATOM(menu, "menu")
 GK_ATOM(menubar, "menubar")
 GK_ATOM(menubutton, "menubutton")
 GK_ATOM(menuButton, "menu-button")
-GK_ATOM(menugenerated, "menugenerated")
 GK_ATOM(menuitem, "menuitem")
 GK_ATOM(menulist, "menulist")
 GK_ATOM(menupopup, "menupopup")
 GK_ATOM(message, "message")
 GK_ATOM(meta, "meta")
 GK_ATOM(meter, "meter")
 GK_ATOM(method, "method")
 GK_ATOM(middle, "middle")
--- a/content/base/src/nsInProcessTabChildGlobal.cpp
+++ b/content/base/src/nsInProcessTabChildGlobal.cpp
@@ -124,17 +124,20 @@ nsInProcessTabChildGlobal::~nsInProcessT
   if (mListenerManager) {
     mListenerManager->Disconnect();
   }
 }
 
 nsresult
 nsInProcessTabChildGlobal::Init()
 {
-  nsresult rv = InitTabChildGlobal();
+#ifdef DEBUG
+  nsresult rv =
+#endif
+  InitTabChildGlobal();
   NS_WARN_IF_FALSE(NS_SUCCEEDED(rv),
                    "Couldn't initialize nsInProcessTabChildGlobal");
   mMessageManager = new nsFrameMessageManager(PR_FALSE,
                                               SendSyncMessageToParent,
                                               SendAsyncMessageToParent,
                                               nsnull,
                                               this,
                                               nsnull,
--- a/content/base/src/nsNodeInfoManager.h
+++ b/content/base/src/nsNodeInfoManager.h
@@ -133,18 +133,16 @@ public:
 
 protected:
   friend class nsDocument;
   friend class nsXULPrototypeDocument;
   friend nsresult NS_NewDOMDocumentType(nsIDOMDocumentType** ,
                                         nsNodeInfoManager *,
                                         nsIPrincipal *,
                                         nsIAtom *,
-                                        nsIDOMNamedNodeMap *,
-                                        nsIDOMNamedNodeMap *,
                                         const nsAString& ,
                                         const nsAString& ,
                                         const nsAString& );
 
   /**
    * Sets the principal of the document this nodeinfo manager belongs to.
    */
   void SetDocumentPrincipal(nsIPrincipal *aPrincipal);
--- a/content/base/src/nsObjectLoadingContent.cpp
+++ b/content/base/src/nsObjectLoadingContent.cpp
@@ -1072,16 +1072,20 @@ nsObjectLoadingContent::ObjectState() co
           state |= NS_EVENT_STATE_HANDLER_BLOCKED;
           break;
         case ePluginCrashed:
           state |= NS_EVENT_STATE_HANDLER_CRASHED;
           break;
         case ePluginUnsupported:
           state |= NS_EVENT_STATE_TYPE_UNSUPPORTED;
           break;
+        case ePluginOutdated:
+        case ePluginOtherState:
+          // Do nothing, but avoid a compile warning
+          break;
       }
       return state;
   };
   NS_NOTREACHED("unknown type?");
   // this return statement only exists to avoid a compile warning
   return nsEventStates();
 }
 
--- a/content/base/src/nsWebSocket.cpp
+++ b/content/base/src/nsWebSocket.cpp
@@ -892,16 +892,19 @@ IMPL_RUNNABLE_ON_MAIN_THREAD_METHOD_BEGI
 
       case secWebSocketKey2Header:
       {
         buf->AppendLiteral("Sec-WebSocket-Key2: ");
         buf->Append(key_2);
         buf->AppendLiteral("\r\n");
       }
       break;
+
+      case numberRequestHeaders:
+      break;
     }
 
     headersToSend.RemoveElementAt(headerPosToSendNow);
   }
 
   buf->AppendLiteral("\r\n");
   buf->Append(key_3);
 
@@ -1728,20 +1731,19 @@ nsWebSocketEstablishedConnection::DoConn
 IMPL_RUNNABLE_ON_MAIN_THREAD_METHOD_BEGIN(AddWSConnecting)
 {
 #ifdef DEBUG
   PRUint32 index =
     sWSsConnecting->BinaryIndexOf(this, nsWSNetAddressComparator());
   NS_ASSERTION(index == nsTArray<PRNetAddr>::NoIndex,
                "The ws connection shouldn't be already added in the "
                "serialization list.");
+  bool inserted = !!
 #endif
-
-  PRBool inserted =
-    !!(sWSsConnecting->InsertElementSorted(this, nsWSNetAddressComparator()));
+  sWSsConnecting->InsertElementSorted(this, nsWSNetAddressComparator());
   NS_ASSERTION(inserted, "Couldn't insert the ws connection into the "
                          "serialization list.");
 }
 IMPL_RUNNABLE_ON_MAIN_THREAD_METHOD_END
 
 IMPL_RUNNABLE_ON_MAIN_THREAD_METHOD_BEGIN(RemoveWSConnecting)
 {
   if (mStatus == CONN_NOT_CONNECTED) {
--- a/content/base/src/nsXMLContentSerializer.cpp
+++ b/content/base/src/nsXMLContentSerializer.cpp
@@ -1314,17 +1314,18 @@ nsXMLContentSerializer::AppendIndentatio
   mAddSpace = PR_FALSE;
   mMayIgnoreLineBreakSequence = PR_FALSE;
 }
 
 void
 nsXMLContentSerializer::IncrIndentation(nsIAtom* aName)
 {
   // we want to keep the source readable
-  if(mDoWrap && mIndent.Length() >= mMaxColumn - MIN_INDENTED_LINE_LENGTH) {
+  if (mDoWrap &&
+      mIndent.Length() >= PRUint32(mMaxColumn) - MIN_INDENTED_LINE_LENGTH) {
     ++mIndentOverflow;
   }
   else {
     mIndent.AppendLiteral(INDENT_STRING);
   }
 }
 
 void
@@ -1653,17 +1654,17 @@ nsXMLContentSerializer::AppendToStringFo
     }
   }
 
   // if the current line already has text on it, such as a tag,
   // leading whitespace is significant
   PRBool mayIgnoreStartOfLineWhitespaceSequence =
     (!mColPos || (mIsIndentationAddedOnCurrentLine &&
                   sequenceStartAfterAWhitespace &&
-                  mColPos == mIndent.Length()));
+                  PRUint32(mColPos) == mIndent.Length()));
 
   while (pos < end) {
     sequenceStart = pos;
 
     // if beginning of a whitespace sequence
     if (*pos == ' ' || *pos == '\n' || *pos == '\t') {
       AppendFormatedWrapped_WhitespaceSequence(pos, end, sequenceStart,
         mayIgnoreStartOfLineWhitespaceSequence, aOutputStr);
--- a/content/base/test/chrome/Makefile.in
+++ b/content/base/test/chrome/Makefile.in
@@ -55,15 +55,17 @@ include $(topsrcdir)/config/rules.mk
     test_bug467123.xul \
     test_title.xul \
     title_window.xul \
     test_bug549682.xul \
     file_bug549682.xul \
     test_bug616841.xul \
     file_bug616841.xul \
     test_bug635835.xul \
+    test_fileconstructor.xul \
+    fileconstructor_file.png \
     $(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
 
 libs:: $(_CHROME_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/chrome/$(relativesrcdir)
copy from content/canvas/test/image_yellow.png
copy to content/base/test/chrome/fileconstructor_file.png
new file mode 100644
--- /dev/null
+++ b/content/base/test/chrome/test_fileconstructor.xul
@@ -0,0 +1,70 @@
+<?xml version="1.0"?>
+<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
+<?xml-stylesheet
+  href="chrome://mochikit/content/tests/SimpleTest/test.css"
+  type="text/css"?>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=607114.xul
+-->
+<window title="Mozilla Bug 607114"
+  xmlns:html="http://www.w3.org/1999/xhtml"
+  xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+
+  <title>Test for Bug 607114</title>
+  <script type="application/javascript"
+    src="chrome://mochikit/content/MochiKit/packed.js"></script>
+  <script type="application/javascript"
+    src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+
+<body  xmlns="http://www.w3.org/1999/xhtml">
+<a target="_blank"
+   href="https://bugzilla.mozilla.org/show_bug.cgi?id=607114">
+   Mozilla Bug 607114</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+
+</div>
+<pre id="test">
+</pre>
+</body>
+
+<script class="testbody" type="application/javascript">
+<![CDATA[
+
+/** Test for Bug 607114 **/
+
+var file = Components.classes["@mozilla.org/file/directory_service;1"]
+           .getService(Components.interfaces.nsIProperties)
+           .get("CurWorkD", Components.interfaces.nsIFile);
+
+// man I wish this were simpler ...
+file.append("chrome");
+file.append("content");
+file.append("base");
+file.append("test");
+file.append("chrome");
+file.append("fileconstructor_file.png");
+
+var domfile = new File(file.path);
+ok(domfile instanceof File, "File() should return a File");
+is(domfile.type, "image/png", "File should be a PNG");
+is(domfile.size, 95, "File has size 95 (and more importantly we can read it)");
+
+try {
+  var boomfile = new File();
+  ok(false, "This should never be reached!");
+} catch (e) {
+  ok(true, "Botched file constructor attempts throw and do not crash.");
+}
+
+try {
+  var nonexistentfile = new File("i/sure/hope/this/does/not/exist/anywhere.txt");
+  ok(false, "This should never be reached!");
+} catch (e) {
+  ok(true, "Attempt to construct a non-existent file should fail.")
+}
+
+]]>
+</script>
+
+</window>
--- a/content/base/test/test_fileapi.html
+++ b/content/base/test/test_fileapi.html
@@ -15,16 +15,25 @@ https://bugzilla.mozilla.org/show_bug.cg
 <p id="display">
   <input id="fileList" type="file"></input>
 </p>
 <div id="content" style="display: none">
 </div>
 
 <pre id="test">
 <script class="testbody" type="text/javascript">
+
+// File constructors should not work from non-chrome code
+try {
+  var file = File("/etc/passwd");
+  ok(false, "Did not throw on unprivileged attempt to construct a File");
+} catch (e) {
+  ok(true, "Threw on an unprivileged attempt to construct a File");
+}
+
 const minFileSize = 20000;
 var fileNum = 1;
 var testRanCounter = 0;
 var expectedTestCount = 0;
 SimpleTest.waitForExplicitFinish();
 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
 is(FileReader.EMPTY, 0, "correct EMPTY value");
--- a/content/canvas/public/nsICanvasElementExternal.h
+++ b/content/canvas/public/nsICanvasElementExternal.h
@@ -43,17 +43,17 @@
 
 class gfxContext;
 class nsIFrame;
 struct gfxRect;
 
 #define NS_ICANVASELEMENTEXTERNAL_IID \
   { 0x51870f54, 0x6c4c, 0x469a, {0xad, 0x46, 0xf0, 0xa9, 0x8e, 0x32, 0xa7, 0xe2 } }
 
-class nsIRenderingContext;
+class nsRenderingContext;
 class nsICanvasRenderingContextInternal;
 
 struct _cairo_surface;
 
 /*
  * This interface contains methods that are needed outside of the content/layout
  * modules, specifically widget.  It should eventually go away when we support
  * libxul builds, and nsHTMLCanvasElement be used directly.
--- a/content/canvas/src/CustomQS_Canvas2D.h
+++ b/content/canvas/src/CustomQS_Canvas2D.h
@@ -1,11 +1,10 @@
-/* -*- Mode: C++; tab-width: 40; indent-tabs-mode: nil; c-basic-offset: 4 -*-
- *
- * ***** BEGIN LICENSE BLOCK *****
+/* -*- Mode: C++; tab-width: 40; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  *
  * The contents of this file are subject to the Mozilla Public License Version
  * 1.1 (the "License"); you may not use this file except in compliance with
  * the License. You may obtain a copy of the License at
  * http://www.mozilla.org/MPL/
  *
  * Software distributed under the License is distributed on an "AS IS" basis,
@@ -39,32 +38,33 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsDOMError.h"
 #include "nsIDOMCanvasRenderingContext2D.h"
 #include "CheckedInt.h"
 #include "nsMathUtils.h"
 
-typedef nsresult (NS_STDCALL nsIDOMCanvasRenderingContext2D::*CanvasStyleSetterType)(const nsAString &, nsISupports *);
-typedef nsresult (NS_STDCALL nsIDOMCanvasRenderingContext2D::*CanvasStyleGetterType)(nsAString &, nsISupports **, PRInt32 *);
+typedef NS_STDCALL_FUNCPROTO(nsresult, CanvasStyleSetterType, nsIDOMCanvasRenderingContext2D,
+                             SetStrokeStyle_multi, (const nsAString &, nsISupports *));
+typedef NS_STDCALL_FUNCPROTO(nsresult, CanvasStyleGetterType, nsIDOMCanvasRenderingContext2D,
+                             GetStrokeStyle_multi, (nsAString &, nsISupports **, PRInt32 *));
 
 static JSBool
 Canvas2D_SetStyleHelper(JSContext *cx, JSObject *obj, jsid id, jsval *vp,
                         CanvasStyleSetterType setfunc)
 {
     XPC_QS_ASSERT_CONTEXT_OK(cx);
     nsIDOMCanvasRenderingContext2D *self;
     xpc_qsSelfRef selfref;
     js::AutoValueRooter tvr(cx);
     if (!xpc_qsUnwrapThis(cx, obj, nsnull, &self, &selfref.ptr, tvr.jsval_addr(), nsnull))
         return JS_FALSE;
 
-    nsresult rv;
-
+    nsresult rv = NS_OK;
     if (JSVAL_IS_STRING(*vp)) {
         xpc_qsDOMString arg0(cx, *vp, vp,
                              xpc_qsDOMString::eDefaultNullBehavior,
                              xpc_qsDOMString::eDefaultUndefinedBehavior);
         if (!arg0.IsValid())
             return JS_FALSE;
 
         rv = (self->*setfunc)(arg0, nsnull);
--- a/content/canvas/src/CustomQS_WebGL.h
+++ b/content/canvas/src/CustomQS_WebGL.h
@@ -666,32 +666,30 @@ helper_nsIDOMWebGLRenderingContext_Unifo
 static inline JSBool
 helper_nsIDOMWebGLRenderingContext_UniformMatrix_x_fv(JSContext *cx, uintN argc, jsval *vp, int nElements)
 {
     XPC_QS_ASSERT_CONTEXT_OK(cx);
     JSObject *obj = JS_THIS_OBJECT(cx, vp);
     if (!obj)
         return JS_FALSE;
 
-    nsresult rv;
-
     nsIDOMWebGLRenderingContext *self;
     xpc_qsSelfRef selfref;
     js::AutoValueRooter tvr(cx);
     if (!xpc_qsUnwrapThis(cx, obj, nsnull, &self, &selfref.ptr, tvr.jsval_addr(), nsnull))
         return JS_FALSE;
 
     if (argc < 3)
         return xpc_qsThrow(cx, NS_ERROR_XPC_NOT_ENOUGH_ARGS);
 
     jsval *argv = JS_ARGV(cx, vp);
 
     nsIWebGLUniformLocation *location;
     xpc_qsSelfRef location_selfref;
-    rv = xpc_qsUnwrapArg(cx, argv[0], &location, &location_selfref.ptr, &argv[0]);
+    nsresult rv = xpc_qsUnwrapArg(cx, argv[0], &location, &location_selfref.ptr, &argv[0]);
     if (NS_FAILED(rv)) {
         xpc_qsThrowBadArg(cx, rv, vp, 0);
         return JS_FALSE;
     }
 
     int32 transpose;
     if (!JS_ValueToECMAInt32(cx, argv[1], &transpose))
         return JS_FALSE;
@@ -741,18 +739,16 @@ helper_nsIDOMWebGLRenderingContext_Unifo
 static inline JSBool
 helper_nsIDOMWebGLRenderingContext_VertexAttrib_x_fv(JSContext *cx, uintN argc, jsval *vp, int nElements)
 {
     XPC_QS_ASSERT_CONTEXT_OK(cx);
     JSObject *obj = JS_THIS_OBJECT(cx, vp);
     if (!obj)
         return JS_FALSE;
 
-    nsresult rv;
-
     nsIDOMWebGLRenderingContext *self;
     xpc_qsSelfRef selfref;
     js::AutoValueRooter tvr(cx);
     if (!xpc_qsUnwrapThis(cx, obj, nsnull, &self, &selfref.ptr, tvr.jsval_addr(), nsnull))
         return JS_FALSE;
 
     if (argc < 2)
         return xpc_qsThrow(cx, NS_ERROR_XPC_NOT_ENOUGH_ARGS);
@@ -785,16 +781,17 @@ helper_nsIDOMWebGLRenderingContext_Verte
 
         *obj_tvr.jsval_addr() = OBJECT_TO_JSVAL(nobj);
         wa = js::TypedArray::fromJSObject(nobj);
     } else {
         xpc_qsThrowBadArg(cx, NS_ERROR_FAILURE, vp, 1);
         return JS_FALSE;
     }
 
+    nsresult rv = NS_OK;
     if (nElements == 1) {
         rv = self->VertexAttrib1fv_array(location, wa);
     } else if (nElements == 2) {
         rv = self->VertexAttrib2fv_array(location, wa);
     } else if (nElements == 3) {
         rv = self->VertexAttrib3fv_array(location, wa);
     } else if (nElements == 4) {
         rv = self->VertexAttrib4fv_array(location, wa);
@@ -948,18 +945,17 @@ helper_nsIDOMWebGLRenderingContext_Unifo
         *obj_tvr.jsval_addr() = OBJECT_TO_JSVAL(nobj);
         wa = js::TypedArray::fromJSObject(nobj);
     } else {
         xpc_qsThrowMethodFailedWithDetails(cx, NS_ERROR_FAILURE, "nsIDOMWebGLRenderingContext", "uniformNiv");
         js_SetTraceableNativeFailed(cx);
         return;
     }
 
-    nsresult rv;
-
+    nsresult rv = NS_OK;
     if (nElements == 1) {
         rv = self->Uniform1iv_array(location, wa);
     } else if (nElements == 2) {
         rv = self->Uniform2iv_array(location, wa);
     } else if (nElements == 3) {
         rv = self->Uniform3iv_array(location, wa);
     } else if (nElements == 4) {
         rv = self->Uniform4iv_array(location, wa);
@@ -1020,18 +1016,17 @@ helper_nsIDOMWebGLRenderingContext_Unifo
         *obj_tvr.jsval_addr() = OBJECT_TO_JSVAL(nobj);
         wa = js::TypedArray::fromJSObject(nobj);
     } else {
         xpc_qsThrowMethodFailedWithDetails(cx, NS_ERROR_FAILURE, "nsIDOMWebGLRenderingContext", "uniformNfv");
         js_SetTraceableNativeFailed(cx);
         return;
     }
 
-    nsresult rv;
-
+    nsresult rv = NS_OK;
     if (nElements == 1) {
         rv = self->Uniform1fv_array(location, wa);
     } else if (nElements == 2) {
         rv = self->Uniform2fv_array(location, wa);
     } else if (nElements == 3) {
         rv = self->Uniform3fv_array(location, wa);
     } else if (nElements == 4) {
         rv = self->Uniform4fv_array(location, wa);
@@ -1094,17 +1089,17 @@ helper_nsIDOMWebGLRenderingContext_Unifo
         *obj_tvr.jsval_addr() = OBJECT_TO_JSVAL(nobj);
         wa = js::TypedArray::fromJSObject(nobj);
     } else {
         xpc_qsThrowMethodFailedWithDetails(cx, NS_ERROR_FAILURE, "nsIDOMWebGLRenderingContext", "uniformMatrixNfv");
         js_SetTraceableNativeFailed(cx);
         return;
     }
 
-    nsresult rv;
+    nsresult rv = NS_OK;
     if (nElements == 2) {
         rv = self->UniformMatrix2fv_array(location, transpose, wa);
     } else if (nElements == 3) {
         rv = self->UniformMatrix3fv_array(location, transpose, wa);
     } else if (nElements == 4) {
         rv = self->UniformMatrix4fv_array(location, transpose, wa);
     }
 
--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
@@ -71,17 +71,16 @@
 #include "nsComputedDOMStyle.h"
 #include "nsStyleSet.h"
 
 #include "nsPrintfCString.h"
 
 #include "nsReadableUtils.h"
 
 #include "nsColor.h"
-#include "nsIRenderingContext.h"
 #include "nsIDeviceContext.h"
 #include "nsGfxCIID.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIDocShell.h"
 #include "nsIDOMWindow.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
--- a/content/events/src/nsContentEventHandler.cpp
+++ b/content/events/src/nsContentEventHandler.cpp
@@ -859,17 +859,16 @@ nsContentEventHandler::OnQueryDOMWidgetH
     nsIObjectFrame* pluginFrame = do_QueryFrame(targetFrame);
     if (pluginFrame) {
       targetWidget = pluginFrame->GetWidget();
     } else if (targetFrame) {
       targetWidget = targetFrame->GetNearestWidget();
     }
     if (aEvent->widget == targetWidget)
       aEvent->mReply.mWidgetIsHit = PR_TRUE;
-    nsIWidget* pEventWidget = aEvent->widget.get();
   }
 
   aEvent->mSucceeded = PR_TRUE;
   return NS_OK;
 }
 
 nsresult
 nsContentEventHandler::GetFlatTextOffsetOfRange(nsIContent* aRootContent,
--- a/content/events/src/nsEventListenerManager.cpp
+++ b/content/events/src/nsEventListenerManager.cpp
@@ -692,18 +692,16 @@ nsEventListenerManager::AddScriptEventLi
   // such scripts based on the source of their code, not just the source
   // of the event.
   if (aPermitUntrustedEvents && 
       aLanguage != nsIProgrammingLanguage::JAVASCRIPT) {
     NS_WARNING("Discarding non-JS event listener from untrusted source");
     return NS_ERROR_FAILURE;
   }
 
-  nsresult rv;
-
   nsCOMPtr<nsINode> node(do_QueryInterface(aObject));
 
   nsCOMPtr<nsIDocument> doc;
 
   nsISupports *objiSupp = aObject;
   nsCOMPtr<nsIScriptGlobalObject> global;
 
   if (node) {
@@ -729,16 +727,17 @@ nsEventListenerManager::AddScriptEventLi
   }
 
   if (!global) {
     // This can happen; for example this document might have been
     // loaded as data.
     return NS_OK;
   }
 
+  nsresult rv = NS_OK;
   // return early preventing the event listener from being added
   // 'doc' is fetched above
   if (doc) {
     nsCOMPtr<nsIContentSecurityPolicy> csp;
     rv = doc->NodePrincipal()->GetCsp(getter_AddRefs(csp));
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (csp) {
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -139,17 +139,17 @@
 
 #include "imgIContainer.h"
 #include "nsIProperties.h"
 #include "nsISupportsPrimitives.h"
 #include "nsEventDispatcher.h"
 
 #include "nsServiceManagerUtils.h"
 #include "nsITimer.h"
-#include "nsIFontMetrics.h"
+#include "nsFontMetrics.h"
 #include "nsIDOMXULDocument.h"
 #include "nsIDragService.h"
 #include "nsIDragSession.h"
 #include "nsDOMDataTransfer.h"
 #include "nsContentAreaDragDrop.h"
 #ifdef MOZ_XUL
 #include "nsTreeBodyFrame.h"
 #endif
@@ -619,19 +619,21 @@ nsMouseWheelTransaction::SetTimeout()
 {
   if (!sTimer) {
     nsCOMPtr<nsITimer> timer = do_CreateInstance(NS_TIMER_CONTRACTID);
     if (!timer)
       return;
     timer.swap(sTimer);
   }
   sTimer->Cancel();
+#ifdef DEBUG
   nsresult rv =
-    sTimer->InitWithFuncCallback(OnTimeout, nsnull, GetTimeoutTime(),
-                                 nsITimer::TYPE_ONE_SHOT);
+#endif
+  sTimer->InitWithFuncCallback(OnTimeout, nsnull, GetTimeoutTime(),
+                               nsITimer::TYPE_ONE_SHOT);
   NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "nsITimer::InitWithFuncCallback failed");
 }
 
 nsIntPoint
 nsMouseWheelTransaction::GetScreenPoint(nsGUIEvent* aEvent)
 {
   NS_ASSERTION(aEvent, "aEvent is null");
   NS_ASSERTION(aEvent->widget, "aEvent-widget is null");
@@ -2483,22 +2485,21 @@ GetScrollableLineHeight(nsIFrame* aTarge
     nsIScrollableFrame* sf = f->GetScrollTargetFrame();
     if (sf)
       return sf->GetLineScrollAmount().height;
   }
 
   // Fall back to the font height of the target frame.
   const nsStyleFont* font = aTargetFrame->GetStyleFont();
   const nsFont& f = font->mFont;
-  nsCOMPtr<nsIFontMetrics> fm = aTargetFrame->PresContext()->GetMetricsFor(f);
+  nsRefPtr<nsFontMetrics> fm = aTargetFrame->PresContext()->GetMetricsFor(f);
   NS_ASSERTION(fm, "FontMetrics is null!");
-  nscoord lineHeight = 0;
   if (fm)
-    fm->GetHeight(lineHeight);
-  return lineHeight;
+    return fm->MaxHeight();
+  return 0;
 }
 
 void
 nsEventStateManager::SendLineScrollEvent(nsIFrame* aTargetFrame,
                                          nsMouseScrollEvent* aEvent,
                                          nsPresContext* aPresContext,
                                          nsEventStatus* aStatus,
                                          PRInt32 aNumLines)
@@ -3273,21 +3274,22 @@ nsEventStateManager::PostHandleEvent(nsP
           case NS_VK_TAB:
           case NS_VK_F6:
             EnsureDocument(mPresContext);
             nsIFocusManager* fm = nsFocusManager::GetFocusManager();
             if (fm && mDocument) {
               // Shift focus forward or back depending on shift key
               PRBool isDocMove = ((nsInputEvent*)aEvent)->isControl ||
                                  (keyEvent->keyCode == NS_VK_F6);
-              PRUint32 dir = ((nsInputEvent*)aEvent)->isShift ?
-                             (isDocMove ? nsIFocusManager::MOVEFOCUS_BACKWARDDOC :
-                                          nsIFocusManager::MOVEFOCUS_BACKWARD) :
-                             (isDocMove ? nsIFocusManager::MOVEFOCUS_FORWARDDOC :
-                                          nsIFocusManager::MOVEFOCUS_FORWARD);
+              PRUint32 dir =
+                static_cast<nsInputEvent*>(aEvent)->isShift ?
+                  (isDocMove ? static_cast<PRUint32>(nsIFocusManager::MOVEFOCUS_BACKWARDDOC) :
+                               static_cast<PRUint32>(nsIFocusManager::MOVEFOCUS_BACKWARD)) :
+                  (isDocMove ? static_cast<PRUint32>(nsIFocusManager::MOVEFOCUS_FORWARDDOC) :
+                               static_cast<PRUint32>(nsIFocusManager::MOVEFOCUS_FORWARD));
               nsCOMPtr<nsIDOMElement> result;
               fm->MoveFocus(mDocument->GetWindow(), nsnull, dir,
                             nsIFocusManager::FLAG_BYKEY,
                             getter_AddRefs(result));
             }
             *aStatus = nsEventStatus_eConsumeNoDefault;
             break;
         }
--- a/content/html/content/public/nsHTMLCanvasElement.h
+++ b/content/html/content/public/nsHTMLCanvasElement.h
@@ -43,18 +43,16 @@
 #include "nsGkAtoms.h"
 #include "nsSize.h"
 #include "nsIFrame.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsDOMError.h"
 #include "nsNodeInfoManager.h"
 
-#include "nsIRenderingContext.h"
-
 #include "nsICanvasRenderingContextInternal.h"
 #include "nsICanvasElementExternal.h"
 #include "nsIDOMCanvasRenderingContext2D.h"
 #include "nsLayoutUtils.h"
 
 #include "Layers.h"
 
 class nsIDOMFile;
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -1188,17 +1188,17 @@ nsGenericHTMLElement::SetAttr(PRInt32 aN
                               nsIAtom* aPrefix, const nsAString& aValue,
                               PRBool aNotify)
 {
   PRBool contentEditable = aNameSpaceID == kNameSpaceID_None &&
                            aName == nsGkAtoms::contenteditable;
   PRBool accessKey = aName == nsGkAtoms::accesskey && 
                      aNameSpaceID == kNameSpaceID_None;
 
-  PRInt32 change;
+  PRInt32 change = 0;
   if (contentEditable) {
     change = GetContentEditableValue() == eTrue ? -1 : 0;
     SetMayHaveContentEditableAttr();
   }
 
   if (accessKey) {
     UnregAccessKey();
   }
@@ -1223,17 +1223,17 @@ nsGenericHTMLElement::SetAttr(PRInt32 aN
   return NS_OK;
 }
 
 nsresult
 nsGenericHTMLElement::UnsetAttr(PRInt32 aNameSpaceID, nsIAtom* aAttribute,
                                 PRBool aNotify)
 {
   PRBool contentEditable = PR_FALSE;
-  PRInt32 contentEditableChange;
+  PRInt32 contentEditableChange = 0;
 
   // Check for event handlers
   if (aNameSpaceID == kNameSpaceID_None) {
     if (aAttribute == nsGkAtoms::name) {
       // Have to do this before clearing flag. See RemoveFromNameTable
       RemoveFromNameTable();
       ClearHasName();
     }
--- a/content/html/content/src/nsHTMLAudioElement.cpp
+++ b/content/html/content/src/nsHTMLAudioElement.cpp
@@ -56,17 +56,16 @@
 
 #include "nsIScriptSecurityManager.h"
 #include "nsIXPConnect.h"
 #include "jsapi.h"
 #include "jscntxt.h"
 #include "jstypedarray.h"
 #include "nsJSUtils.h"
 
-#include "nsIRenderingContext.h"
 #include "nsITimer.h"
 
 #include "nsEventDispatcher.h"
 #include "nsIDOMDocumentEvent.h"
 #include "nsIDOMProgressEvent.h"
 
 using namespace mozilla::dom;
 
--- a/content/html/content/src/nsHTMLBodyElement.cpp
+++ b/content/html/content/src/nsHTMLBodyElement.cpp
@@ -78,16 +78,19 @@ public:
 };
 
 //----------------------------------------------------------------------
 
 class nsHTMLBodyElement : public nsGenericHTMLElement,
                           public nsIDOMHTMLBodyElement
 {
 public:
+  using nsGenericElement::GetText;
+  using nsGenericElement::SetText;
+
   nsHTMLBodyElement(already_AddRefed<nsINodeInfo> aNodeInfo);
   virtual ~nsHTMLBodyElement();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsGenericHTMLElement::)
--- a/content/html/content/src/nsHTMLMediaElement.cpp
+++ b/content/html/content/src/nsHTMLMediaElement.cpp
@@ -60,17 +60,16 @@
 #include "nsIThreadInternal.h"
 #include "nsContentUtils.h"
 
 #include "nsFrameManager.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIXPConnect.h"
 #include "jsapi.h"
 
-#include "nsIRenderingContext.h"
 #include "nsITimer.h"
 
 #include "nsEventDispatcher.h"
 #include "nsIDOMDocumentEvent.h"
 #include "nsMediaError.h"
 #include "nsICategoryManager.h"
 #include "nsCharSeparatedTokenizer.h"
 #include "nsMediaStream.h"
--- a/content/html/content/src/nsHTMLScriptElement.cpp
+++ b/content/html/content/src/nsHTMLScriptElement.cpp
@@ -304,16 +304,19 @@ nsHTMLScriptEventHandler::Invoke(nsISupp
 }
 
 
 class nsHTMLScriptElement : public nsGenericHTMLElement,
                             public nsIDOMHTMLScriptElement,
                             public nsScriptElement
 {
 public:
+  using nsGenericElement::GetText;
+  using nsGenericElement::SetText;
+
   nsHTMLScriptElement(already_AddRefed<nsINodeInfo> aNodeInfo,
                       FromParser aFromParser);
   virtual ~nsHTMLScriptElement();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
--- a/content/html/content/src/nsHTMLTitleElement.cpp
+++ b/content/html/content/src/nsHTMLTitleElement.cpp
@@ -44,16 +44,19 @@
 #include "nsIDOMHTMLDocument.h"
 #include "nsContentUtils.h"
 
 class nsHTMLTitleElement : public nsGenericHTMLElement,
                            public nsIDOMHTMLTitleElement,
                            public nsStubMutationObserver
 {
 public:
+  using nsGenericElement::GetText;
+  using nsGenericElement::SetText;
+
   nsHTMLTitleElement(already_AddRefed<nsINodeInfo> aNodeInfo);
   virtual ~nsHTMLTitleElement();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsGenericHTMLElement::)
--- a/content/html/content/src/nsHTMLVideoElement.cpp
+++ b/content/html/content/src/nsHTMLVideoElement.cpp
@@ -53,17 +53,16 @@
 #include "nsXPCOMStrings.h"
 #include "prlock.h"
 #include "nsThreadUtils.h"
 
 #include "nsIScriptSecurityManager.h"
 #include "nsIXPConnect.h"
 #include "jsapi.h"
 
-#include "nsIRenderingContext.h"
 #include "nsITimer.h"
 
 #include "nsEventDispatcher.h"
 #include "nsIDOMDocumentEvent.h"
 #include "nsIDOMProgressEvent.h"
 #include "nsMediaError.h"
 
 using namespace mozilla::dom;
--- a/content/html/document/src/nsHTMLContentSink.cpp
+++ b/content/html/document/src/nsHTMLContentSink.cpp
@@ -2460,19 +2460,18 @@ HTMLContentSink::AddDocTypeDecl(const ns
     if (!nameAtom) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
 
     // Indicate that there is no internal subset (not just an empty one)
     nsAutoString voidString;
     voidString.SetIsVoid(PR_TRUE);
     rv = NS_NewDOMDocumentType(getter_AddRefs(docType),
-                               mDocument->NodeInfoManager(), nsnull,
-                               nameAtom, nsnull, nsnull, publicId, systemId,
-                               voidString);
+                               mDocument->NodeInfoManager(), nsnull, nameAtom,
+                               publicId, systemId, voidString);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (oldDocType) {
       // If we already have a doctype we replace the old one.
       nsCOMPtr<nsIDOMNode> tmpNode;
       rv = doc->ReplaceChild(oldDocType, docType, getter_AddRefs(tmpNode));
     } else {
       // If we don't already have one we insert it as the first child,
--- a/content/html/document/src/nsHTMLDocument.cpp
+++ b/content/html/document/src/nsHTMLDocument.cpp
@@ -1394,22 +1394,16 @@ nsHTMLDocument::SetDocumentURI(const nsA
 
 NS_IMETHODIMP
 nsHTMLDocument::AdoptNode(nsIDOMNode* aSource, nsIDOMNode** aRetval)
 {
   return nsDocument::AdoptNode(aSource, aRetval);
 }
 
 NS_IMETHODIMP
-nsHTMLDocument::GetDomConfig(nsIDOMDOMConfiguration** aDomConfig)
-{
-  return nsDocument::GetDomConfig(aDomConfig);
-}
-
-NS_IMETHODIMP
 nsHTMLDocument::NormalizeDocument()
 {
   return nsDocument::NormalizeDocument();
 }
 
 NS_IMETHODIMP
 nsHTMLDocument::RenameNode(nsIDOMNode* aNode,
                            const nsAString& aNamespaceURI,
@@ -3282,17 +3276,17 @@ nsHTMLDocument::EditingStateChanged()
 
   if (!HasPresShell(window)) {
     // We should not make the window editable or setup its editor.
     // It's probably style=display:none.
     return NS_OK;
   }
 
   PRBool makeWindowEditable = mEditingState == eOff;
-  PRBool updateState;
+  bool updateState = false;
   PRBool spellRecheckAll = PR_FALSE;
   nsCOMPtr<nsIEditor> editor;
 
   {
     EditingState oldState = mEditingState;
     nsAutoEditingState push(this, eSettingUp);
 
     if (makeWindowEditable) {
@@ -3351,31 +3345,27 @@ nsHTMLDocument::EditingStateChanged()
 
       rv = agentSheets.AppendObject(sheet);
       NS_ENSURE_SUCCESS(rv, rv);
 
       // Disable scripting and plugins.
       rv = editSession->DisableJSAndPlugins(window);
       NS_ENSURE_SUCCESS(rv, rv);
 
-      updateState = PR_TRUE;
+      updateState = true;
       spellRecheckAll = oldState == eContentEditable;
     }
     else if (oldState == eDesignMode) {
       // designMode is being turned off (contentEditable is still on).
       RemoveFromAgentSheets(agentSheets, NS_LITERAL_STRING("resource://gre/res/designmode.css"));
 
       rv = editSession->RestoreJSAndPlugins(window);
       NS_ENSURE_SUCCESS(rv, rv);
 
-      updateState = PR_TRUE;
-    }
-    else {
-      // contentEditable is being turned on (and designMode is off).
-      updateState = PR_FALSE;
+      updateState = true;
     }
 
     rv = presShell->SetAgentStyleSheets(agentSheets);
     NS_ENSURE_SUCCESS(rv, rv);
 
     presShell->ReconstructStyleData();
   }
 
--- a/content/html/document/src/nsHTMLFragmentContentSink.cpp
+++ b/content/html/document/src/nsHTMLFragmentContentSink.cpp
@@ -1181,21 +1181,17 @@ nsHTMLParanoidFragmentSink::CloseContain
             PRInt32 ruleCount = sheet->StyleRuleCount();
             for (PRInt32 i = 0; i < ruleCount; ++i) {
               nsRefPtr<nsICSSRule> rule;
               rv = sheet->GetStyleRuleAt(i, *getter_AddRefs(rule));
               if (NS_FAILED(rv))
                 continue;
               NS_ASSERTION(rule, "We should have a rule by now");
               switch (rule->GetType()) {
-                case nsICSSRule::UNKNOWN_RULE:
-                case nsICSSRule::CHARSET_RULE:
-                case nsICSSRule::IMPORT_RULE:
-                case nsICSSRule::MEDIA_RULE:
-                case nsICSSRule::PAGE_RULE:
+                default:
                   didSanitize = PR_TRUE;
                   // Ignore these rule types.
                   break;
                 case nsICSSRule::NAMESPACE_RULE:
                 case nsICSSRule::FONT_FACE_RULE: {
                   // Append @namespace and @font-face rules verbatim.
                   nsAutoString cssText;
                   nsCOMPtr<nsIDOMCSSRule> styleRule = do_QueryInterface(rule);
--- a/content/media/nsBuiltinDecoderReader.cpp
+++ b/content/media/nsBuiltinDecoderReader.cpp
@@ -203,18 +203,17 @@ VideoData* VideoData::Create(nsVideoInfo
   data.mStereoMode = aInfo.mStereoMode;
 
   videoImage->SetData(data); // Copies buffer
   return v.forget();
 }
 
 nsBuiltinDecoderReader::nsBuiltinDecoderReader(nsBuiltinDecoder* aDecoder)
   : mMonitor("media.decoderreader"),
-    mDecoder(aDecoder),
-    mDataOffset(0)
+    mDecoder(aDecoder)
 {
   MOZ_COUNT_CTOR(nsBuiltinDecoderReader);
 }
 
 nsBuiltinDecoderReader::~nsBuiltinDecoderReader()
 {
   ResetDecode();
   MOZ_COUNT_DTOR(nsBuiltinDecoderReader);
--- a/content/media/nsBuiltinDecoderReader.h
+++ b/content/media/nsBuiltinDecoderReader.h
@@ -87,20 +87,16 @@ public:
 
   // The picture region inside the video frame to be displayed.
   nsIntRect mPicture;
 
   // Display size of the video frame. The picture region will be scaled
   // to and displayed at this size.
   nsIntSize mDisplay;
 
-  // The offset of the first non-header page in the file, in bytes.
-  // Used to seek to the start of the media.
-  PRInt64 mDataOffset;
-
   // Indicates the frame layout for single track stereo videos.
   mozilla::layers::StereoMode mStereoMode;
 
   // PR_TRUE if we have an active audio bitstream.
   PRPackedBool mHasAudio;
 
   // PR_TRUE if we have an active video bitstream.
   PRPackedBool mHasVideo;
@@ -508,18 +504,14 @@ protected:
   // The lock which we hold whenever we read or decode. This ensures the thread
   // safety of the reader and its data fields.
   Monitor mMonitor;
 
   // Reference to the owning decoder object. Do not hold the
   // reader's monitor when accessing this.
   nsBuiltinDecoder* mDecoder;
 
-  // The offset of the start of the first non-header page in the file.
-  // Used to seek to media start time.
-  PRInt64 mDataOffset;
-
   // Stores presentation info required for playback. The reader's monitor
   // must be held when accessing this.
   nsVideoInfo mInfo;
 };
 
 #endif
--- a/content/media/nsBuiltinDecoderStateMachine.cpp
+++ b/content/media/nsBuiltinDecoderStateMachine.cpp
@@ -1552,20 +1552,19 @@ void nsBuiltinDecoderStateMachine::Wait(
 
 VideoData* nsBuiltinDecoderStateMachine::FindStartTime()
 {
   NS_ASSERTION(IsCurrentThread(mDecoder->mStateMachineThread), "Should be on state machine thread.");
   mDecoder->GetMonitor().AssertCurrentThreadIn();
   PRInt64 startTime = 0;
   mStartTime = 0;
   VideoData* v = nsnull;
-  PRInt64 dataOffset = mInfo.mDataOffset;
   {
     MonitorAutoExit exitMon(mDecoder->GetMonitor());
-    v = mReader->FindStartTime(dataOffset, startTime);
+    v = mReader->FindStartTime(0, startTime);
   }
   if (startTime != 0) {
     mStartTime = startTime;
     if (mGotDurationFromMetaData) {
       NS_ASSERTION(mEndTime != -1,
                    "We should have mEndTime as supplied duration here");
       // We were specified a duration from a Content-Duration HTTP header.
       // Adjust mEndTime so that mEndTime-mStartTime matches the specified
--- a/content/media/nsMediaDecoder.cpp
+++ b/content/media/nsMediaDecoder.cpp
@@ -42,17 +42,16 @@
 #include "prlog.h"
 #include "prmem.h"
 #include "nsIFrame.h"
 #include "nsIDocument.h"
 #include "nsThreadUtils.h"
 #include "nsIDOMHTMLMediaElement.h"
 #include "nsNetUtil.h"
 #include "nsHTMLMediaElement.h"
-#include "nsIRenderingContext.h"
 #include "gfxContext.h"
 #include "nsPresContext.h"
 #include "nsDOMError.h"
 #include "nsDisplayList.h"
 #ifdef MOZ_SVG
 #include "nsSVGEffects.h"
 #endif
 
--- a/content/media/nsMediaStream.cpp
+++ b/content/media/nsMediaStream.cpp
@@ -999,17 +999,17 @@ nsresult nsMediaFileStream::GetCachedRan
 nsresult nsMediaFileStream::Open(nsIStreamListener** aStreamListener)
 {
   NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
 
   if (aStreamListener) {
     *aStreamListener = nsnull;
   }
 
-  nsresult rv;
+  nsresult rv = NS_OK;
   if (aStreamListener) {
     // The channel is already open. We need a synchronous stream that
     // implements nsISeekableStream, so we have to find the underlying
     // file and reopen it
     nsCOMPtr<nsIFileChannel> fc(do_QueryInterface(mChannel));
     if (!fc)
       return NS_ERROR_UNEXPECTED;
 
--- a/content/media/ogg/nsOggReader.cpp
+++ b/content/media/ogg/nsOggReader.cpp
@@ -102,17 +102,18 @@ nsOggReader::nsOggReader(nsBuiltinDecode
   : nsBuiltinDecoderReader(aDecoder),
     mTheoraState(nsnull),
     mVorbisState(nsnull),
     mSkeletonState(nsnull),
     mVorbisSerial(0),
     mTheoraSerial(0),
     mPageOffset(0),
     mTheoraGranulepos(-1),
-    mVorbisGranulepos(-1)
+    mVorbisGranulepos(-1),
+    mDataOffset(0)
 {
   MOZ_COUNT_CTOR(nsOggReader);
 }
 
 nsOggReader::~nsOggReader()
 {
   ogg_sync_clear(&mOggState);
   MOZ_COUNT_DTOR(nsOggReader);
@@ -319,17 +320,16 @@ nsresult nsOggReader::ReadMetadata(nsVid
                                mTheoraState->mInfo.pic_y,
                                mTheoraState->mInfo.pic_width,
                                mTheoraState->mInfo.pic_height);
     mInfo.mFrame = nsIntSize(mTheoraState->mInfo.frame_width,
                              mTheoraState->mInfo.frame_height);
     mInfo.mDisplay = nsIntSize(mInfo.mPicture.width,
                                mInfo.mPicture.height);
   }
-  mInfo.mDataOffset = mDataOffset;
 
   if (mSkeletonState && mSkeletonState->HasIndex()) {
     // Extract the duration info out of the index, so we don't need to seek to
     // the end of stream to get it.
     nsAutoTArray<PRUint32, 2> tracks;
     if (HasVideo()) {
       tracks.AppendElement(mTheoraState->mSerial);
     }
@@ -901,29 +901,34 @@ GetChecksum(ogg_page* page)
 
 VideoData* nsOggReader::FindStartTime(PRInt64 aOffset,
                                       PRInt64& aOutStartTime)
 {
   NS_ASSERTION(mDecoder->OnStateMachineThread(),
                "Should be on state machine thread.");
   nsMediaStream* stream = mDecoder->GetCurrentStream();
   NS_ENSURE_TRUE(stream != nsnull, nsnull);
-  nsresult res = stream->Seek(nsISeekableStream::NS_SEEK_SET, aOffset);
+  // Ensure aOffset is after mDataOffset, the offset of the first non-header page.
+  // This prevents us from trying to parse header pages as content pages.
+  NS_ASSERTION(mDataOffset > 0, "Must know mDataOffset by now");
+  PRInt64 offset = NS_MAX(mDataOffset, aOffset);
+  nsresult res = stream->Seek(nsISeekableStream::NS_SEEK_SET, offset);
   NS_ENSURE_SUCCESS(res, nsnull);
-  return nsBuiltinDecoderReader::FindStartTime(aOffset, aOutStartTime);
+  return nsBuiltinDecoderReader::FindStartTime(offset, aOutStartTime);
 }
 
 PRInt64 nsOggReader::FindEndTime(PRInt64 aEndOffset)
 {
   MonitorAutoEnter mon(mMonitor);
   NS_ASSERTION(mDecoder->OnStateMachineThread(),
                "Should be on state machine thread.");
   NS_ASSERTION(mDataOffset > 0,
                "Should have offset of first non-header page");
-  PRInt64 endTime = FindEndTime(mDataOffset, aEndOffset, PR_FALSE, &mOggState);
+  PRInt64 offset = NS_MAX(mDataOffset, aEndOffset);
+  PRInt64 endTime = FindEndTime(mDataOffset, offset, PR_FALSE, &mOggState);
   // Reset read head to start of media data.
   nsMediaStream* stream = mDecoder->GetCurrentStream();
   NS_ENSURE_TRUE(stream != nsnull, -1);
   nsresult res = stream->Seek(nsISeekableStream::NS_SEEK_SET, mDataOffset);
   NS_ENSURE_SUCCESS(res, -1);
   return endTime;
 }
 
--- a/content/media/ogg/nsOggReader.h
+++ b/content/media/ogg/nsOggReader.h
@@ -277,11 +277,16 @@ private:
   // the page we're about to read.
   PRInt64 mPageOffset;
 
   // The granulepos of the last decoded Theora frame.
   PRInt64 mTheoraGranulepos;
 
   // The granulepos of the last decoded Vorbis sample.
   PRInt64 mVorbisGranulepos;
+
+  // The offset of the first non-header page in the file, in bytes.
+  // Used to seek to the start of the media, and to prevent us trying to
+  // decode pages before this offset (the header pages) as content pages.
+  PRInt64 mDataOffset;
 };
 
 #endif
--- a/content/media/raw/nsRawReader.h
+++ b/content/media/raw/nsRawReader.h
@@ -107,17 +107,16 @@ public:
 
   virtual PRBool HasVideo()
   {
     return PR_TRUE;
   }
 
   virtual nsresult ReadMetadata(nsVideoInfo* aInfo);
   virtual nsresult Seek(PRInt64 aTime, PRInt64 aStartTime, PRInt64 aEndTime, PRInt64 aCurrentTime);
-  virtual PRInt64 FindEndTime(PRInt64 aEndOffset);
   virtual nsresult GetBuffered(nsTimeRanges* aBuffered, PRInt64 aStartTime);
 
 private:
   PRBool ReadFromStream(nsMediaStream *aStream, PRUint8 *aBuf,
                         PRUint32 aLength);
 
   nsRawVideoHeader mMetadata;
   PRUint32 mCurrentFrame;
--- a/content/media/wave/nsWaveReader.cpp
+++ b/content/media/wave/nsWaveReader.cpp
@@ -159,17 +159,16 @@ nsresult nsWaveReader::ReadMetadata(nsVi
   if (!loaded) {
     return NS_ERROR_FAILURE;
   }
 
   mInfo.mHasAudio = PR_TRUE;
   mInfo.mHasVideo = PR_FALSE;
   mInfo.mAudioRate = mSampleRate;
   mInfo.mAudioChannels = mChannels;
-  mInfo.mDataOffset = -1;
 
   *aInfo = mInfo;
 
   MonitorAutoExit exitReaderMon(mMonitor);
   MonitorAutoEnter decoderMon(mDecoder->GetMonitor());
 
   mDecoder->GetStateMachine()->SetDuration(
     static_cast<PRInt64>(BytesToTime(GetDataLength()) * USECS_PER_S));
--- a/content/media/webm/nsWebMReader.cpp
+++ b/content/media/webm/nsWebMReader.cpp
@@ -325,21 +325,16 @@ nsresult nsWebMReader::ReadMetadata(nsVi
           break;
         case 4:
           mInfo.mStereoMode = STEREO_MODE_BOTTOM_TOP;
           break;
         default:
           mInfo.mStereoMode = STEREO_MODE_MONO;
         }
       }
-
-      // mDataOffset is not used by the WebM backend.
-      // See bug 566779 for a suggestion to refactor
-      // and remove it.
-      mInfo.mDataOffset = -1;
     }
     else if (!mHasAudio && type == NESTEGG_TRACK_AUDIO) {
       nestegg_audio_params params;
       r = nestegg_track_audio_params(mContext, track, &params);
       if (r == -1) {
         Cleanup();
         return NS_ERROR_FAILURE;
       }
@@ -780,17 +775,17 @@ nsresult nsWebMReader::Seek(PRInt64 aTar
   }
   return DecodeToTarget(aTarget);
 }
 
 nsresult nsWebMReader::GetBuffered(nsTimeRanges* aBuffered, PRInt64 aStartTime)
 {
   nsMediaStream* stream = mDecoder->GetCurrentStream();
 
-  PRUint64 timecodeScale;
+  uint64_t timecodeScale;
   if (!mContext || nestegg_tstamp_scale(mContext, &timecodeScale) == -1) {
     return NS_OK;
   }
 
   // Special case completely cached files.  This also handles local files.
   if (stream->IsDataCachedToEndOfStream(0)) {
     uint64_t duration = 0;
     if (nestegg_duration(mContext, &duration) == 0) {
--- a/content/svg/content/src/SVGAnimatedNumberList.cpp
+++ b/content/svg/content/src/SVGAnimatedNumberList.cpp
@@ -38,17 +38,17 @@
 #include "DOMSVGAnimatedNumberList.h"
 #include "nsSVGElement.h"
 #include "nsSVGAttrTearoffTable.h"
 #ifdef MOZ_SMIL
 #include "nsSMILValue.h"
 #include "SVGNumberListSMILType.h"
 #endif // MOZ_SMIL
 
-using namespace mozilla;
+namespace mozilla {
 
 nsresult
 SVGAnimatedNumberList::SetBaseValueString(const nsAString& aValue)
 {
   SVGNumberList newBaseValue;
   nsresult rv = newBaseValue.SetValueFromString(aValue);
   if (NS_FAILED(rv)) {
     return rv;
@@ -209,8 +209,10 @@ SVGAnimatedNumberList::SMILAnimatedNumbe
 void
 SVGAnimatedNumberList::SMILAnimatedNumberList::ClearAnimValue()
 {
   if (mVal->mAnimVal) {
     mVal->ClearAnimValue(mElement, mAttrEnum);
   }
 }
 #endif // MOZ_SMIL
+
+} // namespace mozilla
--- a/content/svg/content/src/SVGAnimatedPathSegList.cpp
+++ b/content/svg/content/src/SVGAnimatedPathSegList.cpp
@@ -40,17 +40,17 @@
 #include "nsSVGAttrTearoffTable.h"
 #ifdef MOZ_SMIL
 #include "nsSMILValue.h"
 #include "SVGPathSegListSMILType.h"
 #endif // MOZ_SMIL
 
 // See the comments in this file's header!
 
-using namespace mozilla;
+namespace mozilla {
 
 nsresult
 SVGAnimatedPathSegList::SetBaseValueString(const nsAString& aValue)
 {
   SVGPathData newBaseValue;
 
   // The spec says that the path data is parsed and accepted up to the first
   // error encountered, so we don't return early if an error occurs. However,
@@ -233,8 +233,9 @@ void
 SVGAnimatedPathSegList::SMILAnimatedPathSegList::ClearAnimValue()
 {
   if (mVal->mAnimVal) {
     mVal->ClearAnimValue(mElement);
   }
 }
 #endif // MOZ_SMIL
 
+} // namespace mozilla
--- a/content/svg/content/src/SVGAnimatedPointList.cpp
+++ b/content/svg/content/src/SVGAnimatedPointList.cpp
@@ -40,17 +40,17 @@
 #include "nsSVGAttrTearoffTable.h"
 #ifdef MOZ_SMIL
 #include "nsSMILValue.h"
 #include "SVGPointListSMILType.h"
 #endif // MOZ_SMIL
 
 // See the comments in this file's header!
 
-using namespace mozilla;
+namespace mozilla {
 
 nsresult
 SVGAnimatedPointList::SetBaseValueString(const nsAString& aValue)
 {
   SVGPointList newBaseValue;
 
   // The spec says that the point data is parsed and accepted up to the first
   // error encountered, so we don't return early if an error occurs. However,
@@ -236,8 +236,9 @@ void
 SVGAnimatedPointList::SMILAnimatedPointList::ClearAnimValue()
 {
   if (mVal->mAnimVal) {
     mVal->ClearAnimValue(mElement);
   }
 }
 #endif // MOZ_SMIL
 
+} // namespace mozilla
--- a/content/svg/content/src/SVGAnimatedPreserveAspectRatio.h
+++ b/content/svg/content/src/SVGAnimatedPreserveAspectRatio.h
@@ -48,16 +48,22 @@ namespace mozilla {
 
 class SVGAnimatedPreserveAspectRatio;
 
 class SVGPreserveAspectRatio
 {
   friend class SVGAnimatedPreserveAspectRatio;
 
 public:
+  SVGPreserveAspectRatio()
+    : mAlign(0)
+    , mMeetOrSlice(0)
+    , mDefer(false)
+  {};
+
   nsresult SetAlign(PRUint16 aAlign) {
     if (aAlign < nsIDOMSVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_NONE ||
         aAlign > nsIDOMSVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMAXYMAX)
       return NS_ERROR_FAILURE;
     mAlign = static_cast<PRUint8>(aAlign);
     return NS_OK;
   };
 
--- a/content/svg/content/src/SVGLengthList.h
+++ b/content/svg/content/src/SVGLengthList.h
@@ -131,24 +131,24 @@ private:
   }
 
   PRBool InsertItem(PRUint32 aIndex, const SVGLength &aLength) {
     if (aIndex >= mLengths.Length()) aIndex = mLengths.Length();
     return !!mLengths.InsertElementAt(aIndex, aLength);
   }
 
   void ReplaceItem(PRUint32 aIndex, const SVGLength &aLength) {
-    NS_ASSERTION(aIndex < mLengths.Length(),
-                 "DOM wrapper caller should have raised INDEX_SIZE_ERR");
+    NS_ABORT_IF_FALSE(aIndex < mLengths.Length(),
+                      "DOM wrapper caller should have raised INDEX_SIZE_ERR");
     mLengths[aIndex] = aLength;
   }
 
   void RemoveItem(PRUint32 aIndex) {
-    NS_ASSERTION(aIndex < mLengths.Length(),
-                 "DOM wrapper caller should have raised INDEX_SIZE_ERR");
+    NS_ABORT_IF_FALSE(aIndex < mLengths.Length(),
+                      "DOM wrapper caller should have raised INDEX_SIZE_ERR");
     mLengths.RemoveElementAt(aIndex);
   }
 
   PRBool AppendItem(SVGLength aLength) {
     return !!mLengths.AppendElement(aLength);
   }
 
 protected:
@@ -217,17 +217,17 @@ public:
     mCanZeroPadList = aCanZeroPadList;
   }
 
   nsSVGElement* Element() const {
     return mElement; // .get();
   }
 
   PRUint8 Axis() const {
-    NS_ASSERTION(mElement, "Axis() isn't valid");
+    NS_ABORT_IF_FALSE(mElement, "Axis() isn't valid");
     return mAxis;
   }
 
   /**
    * The value returned by this function depends on which attribute this object
    * is for. If appending a list of zeros to the attribute's list would have no
    * affect on rendering (e.g. the attributes 'dx' and 'dy' on <text>), then
    * this method will return PR_TRUE. If appending a list of zeros to the
--- a/content/svg/content/src/SVGLengthListSMILType.cpp
+++ b/content/svg/content/src/SVGLengthListSMILType.cpp
@@ -117,26 +117,51 @@ SVGLengthListSMILType::Add(nsSMILValue& 
   // and *not* vice versa! It's okay in the case of adding a shorter list to a
   // longer list because during the add operation we'll end up adding the
   // zeros to actual specified values. It's *not* okay in the case of adding a
   // longer list to a shorter list because then we end up adding to implicit
   // zeros when we'd actually need to add to whatever the underlying values
   // should be, not zeros, and those values are not explicit or otherwise
   // available.
 
+  NS_ABORT_IF_FALSE(!dest.IsEmpty() || !valueToAdd.IsEmpty(),
+                    "Expecting at least one non-identity operand");
+
+  if (!valueToAdd.Element()) { // Adding identity value - no-op
+    NS_ABORT_IF_FALSE(valueToAdd.IsEmpty(),
+                      "Identity values should be empty");
+    return NS_OK;
+  }
+
+  if (!dest.Element()) { // Adding *to* an identity value
+    NS_ABORT_IF_FALSE(dest.IsEmpty(),
+                      "Identity values should be empty");
+    if (!dest.SetLength(valueToAdd.Length())) {
+      return NS_ERROR_OUT_OF_MEMORY;
+    }
+    for (PRUint32 i = 0; i < dest.Length(); ++i) {
+      dest[i].SetValueAndUnit(valueToAdd[i].GetValueInCurrentUnits() * aCount,
+                              valueToAdd[i].GetUnit());
+    }
+    dest.SetInfo(valueToAdd.Element(), valueToAdd.Axis(),
+                 valueToAdd.CanZeroPadList()); // propagate target element info!
+    return NS_OK;
+  }
+  NS_ABORT_IF_FALSE(dest.Element() == valueToAdd.Element(),
+                    "adding values from different elements...?");
+
+  // Zero-pad our |dest| list, if necessary.
   if (dest.Length() < valueToAdd.Length()) {
     if (!dest.CanZeroPadList()) {
       // nsSVGUtils::ReportToConsole
       return NS_ERROR_FAILURE;
     }
 
-    NS_ASSERTION(valueToAdd.CanZeroPadList() || dest.Length() == 0,
-                 "Only \"zero\" nsSMILValues from the SMIL engine should "
-                 "return PR_TRUE for CanZeroPadList() when the attribute "
-                 "being animated can't be zero padded");
+    NS_ABORT_IF_FALSE(valueToAdd.CanZeroPadList(),
+                      "values disagree about attribute's zero-paddibility");
 
     PRUint32 i = dest.Length();
     if (!dest.SetLength(valueToAdd.Length())) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
     for (; i < valueToAdd.Length(); ++i) {
       dest[i].SetValueAndUnit(0.0f, valueToAdd[i].GetUnit());
     }
@@ -148,23 +173,24 @@ SVGLengthListSMILType::Add(nsSMILValue& 
       valToAdd = valueToAdd[i].GetValueInCurrentUnits();
     } else {
       // If units differ, we use the unit of the item in 'dest'.
       // We leave it to the frame code to check that values are finite.
       valToAdd = valueToAdd[i].GetValueInSpecifiedUnit(dest[i].GetUnit(),
                                                        dest.Element(),
                                                        dest.Axis());
     }
-    dest[i].SetValueAndUnit(dest[i].GetValueInCurrentUnits() + valToAdd,
-                            dest[i].GetUnit());
+    dest[i].SetValueAndUnit(
+      dest[i].GetValueInCurrentUnits() + valToAdd * aCount,
+      dest[i].GetUnit());
   }
 
-  // propagate flag:
-  dest.SetCanZeroPadList(dest.CanZeroPadList() &&
-                         valueToAdd.CanZeroPadList());
+  // propagate target element info!
+  dest.SetInfo(valueToAdd.Element(), valueToAdd.Axis(),
+               dest.CanZeroPadList() && valueToAdd.CanZeroPadList());
 
   return NS_OK;
 }
 
 nsresult
 SVGLengthListSMILType::ComputeDistance(const nsSMILValue& aFrom,
                                        const nsSMILValue& aTo,
                                        double& aDistance) const
@@ -176,18 +202,18 @@ SVGLengthListSMILType::ComputeDistance(c
     *static_cast<const SVGLengthListAndInfo*>(aFrom.mU.mPtr);
   const SVGLengthListAndInfo& to =
     *static_cast<const SVGLengthListAndInfo*>(aTo.mU.mPtr);
 
   // To understand this code, see the comments documenting our Init() method,
   // and documenting SVGLengthListAndInfo::CanZeroPadList().
 
   NS_ASSERTION((from.CanZeroPadList() == to.CanZeroPadList()) ||
-               (from.CanZeroPadList() && from.Length() == 0) ||
-               (to.CanZeroPadList() && to.Length() == 0),
+               (from.CanZeroPadList() && from.IsEmpty()) ||
+               (to.CanZeroPadList() && to.IsEmpty()),
                "Only \"zero\" nsSMILValues from the SMIL engine should "
                "return PR_TRUE for CanZeroPadList() when the attribute "
                "being animated can't be zero padded");
 
   if ((from.Length() < to.Length() && !from.CanZeroPadList()) ||
       (to.Length() < from.Length() && !to.CanZeroPadList())) {
     // nsSVGUtils::ReportToConsole
     return NS_ERROR_FAILURE;
@@ -251,18 +277,18 @@ SVGLengthListSMILType::Interpolate(const
     *static_cast<const SVGLengthListAndInfo*>(aEndVal.mU.mPtr);
   SVGLengthListAndInfo& result =
     *static_cast<SVGLengthListAndInfo*>(aResult.mU.mPtr);
 
   // To understand this code, see the comments documenting our Init() method,
   // and documenting SVGLengthListAndInfo::CanZeroPadList().
 
   NS_ASSERTION((start.CanZeroPadList() == end.CanZeroPadList()) ||
-               (start.CanZeroPadList() && start.Length() == 0) ||
-               (end.CanZeroPadList() && end.Length() == 0),
+               (start.CanZeroPadList() && start.IsEmpty()) ||
+               (end.CanZeroPadList() && end.IsEmpty()),
                "Only \"zero\" nsSMILValues from the SMIL engine should "
                "return PR_TRUE for CanZeroPadList() when the attribute "
                "being animated can't be zero padded");
 
   if ((start.Length() < end.Length() && !start.CanZeroPadList()) ||
       (end.Length() < start.Length() && !end.CanZeroPadList())) {
     // nsSVGUtils::ReportToConsole
     return NS_ERROR_FAILURE;
@@ -294,16 +320,16 @@ SVGLengthListSMILType::Interpolate(const
                               start[i].GetValueInCurrentUnits() * aUnitDistance,
                               start[i].GetUnit());
   }
   for (; i < end.Length(); ++i) {
     result[i].SetValueAndUnit(end[i].GetValueInCurrentUnits() * aUnitDistance,
                               end[i].GetUnit());
   }
 
-  // propagate flag:
-  result.SetCanZeroPadList(start.CanZeroPadList() &&
-                           end.CanZeroPadList());
+  // propagate target element info!
+  result.SetInfo(end.Element(), end.Axis(),
+                 start.CanZeroPadList() && end.CanZeroPadList());
 
   return NS_OK;
 }
 
 } // namespace mozilla
--- a/content/svg/content/src/SVGNumberList.cpp
+++ b/content/svg/content/src/SVGNumberList.cpp
@@ -42,17 +42,17 @@
 #include "nsContentUtils.h"
 #include "nsString.h"
 #include "nsSVGUtils.h"
 #include "string.h"
 #include "prdtoa.h"
 #include "nsTextFormatter.h"
 #include "nsCharSeparatedTokenizer.h"
 
-using namespace mozilla;
+namespace mozilla {
 
 nsresult
 SVGNumberList::CopyFrom(const SVGNumberList& rhs)
 {
   if (!mNumbers.SetCapacity(rhs.Length())) {
     // Yes, we do want fallible alloc here
     return NS_ERROR_OUT_OF_MEMORY;
   }
@@ -103,8 +103,10 @@ SVGNumberList::SetValueFromString(const 
     }
     temp.AppendItem(num);
   }
   if (tokenizer.lastTokenEndedWithSeparator()) {
     return NS_ERROR_DOM_SYNTAX_ERR; // trailing comma
   }
   return CopyFrom(temp);
 }
+
+} // namespace mozilla
--- a/content/svg/content/src/SVGNumberList.h
+++ b/content/svg/content/src/SVGNumberList.h
@@ -134,24 +134,24 @@ private:
   PRBool InsertItem(PRUint32 aIndex, const float &aNumber) {
     if (aIndex >= mNumbers.Length()) {
       aIndex = mNumbers.Length();
     }
     return !!mNumbers.InsertElementAt(aIndex, aNumber);
   }
 
   void ReplaceItem(PRUint32 aIndex, const float &aNumber) {
-    NS_ASSERTION(aIndex < mNumbers.Length(),
-                 "DOM wrapper caller should have raised INDEX_SIZE_ERR");
+    NS_ABORT_IF_FALSE(aIndex < mNumbers.Length(),
+                      "DOM wrapper caller should have raised INDEX_SIZE_ERR");
     mNumbers[aIndex] = aNumber;
   }
 
   void RemoveItem(PRUint32 aIndex) {
-    NS_ASSERTION(aIndex < mNumbers.Length(),
-                 "DOM wrapper caller should have raised INDEX_SIZE_ERR");
+    NS_ABORT_IF_FALSE(aIndex < mNumbers.Length(),
+                      "DOM wrapper caller should have raised INDEX_SIZE_ERR");
     mNumbers.RemoveElementAt(aIndex);
   }
 
   PRBool AppendItem(float aNumber) {
     return !!mNumbers.AppendElement(aNumber);
   }
 
 protected:
--- a/content/svg/content/src/SVGNumberListSMILType.cpp
+++ b/content/svg/content/src/SVGNumberListSMILType.cpp
@@ -51,17 +51,17 @@
  *
  * Note that we don't need to worry about that variation here, however. The way
  * that the SMIL engine creates and composites sandwich layers together allows
  * us to treat "identity" nsSMILValue objects as a number list of zeros. Such
  * identity nsSMILValues are identified by the fact that their
  # SVGNumberListAndInfo has not been given an element yet.
  */
 
-using namespace mozilla;
+namespace mozilla {
 
 /*static*/ SVGNumberListSMILType SVGNumberListSMILType::sSingleton;
 
 //----------------------------------------------------------------------
 // nsISMILType implementation
 
 void
 SVGNumberListSMILType::Init(nsSMILValue &aValue) const
@@ -235,8 +235,10 @@ SVGNumberListSMILType::Interpolate(const
     }
     return NS_OK;
   }
   for (PRUint32 i = 0; i < end.Length(); ++i) {
     result[i] = start[i] + (end[i] - start[i]) * aUnitDistance;
   }
   return NS_OK;
 }
+
+} // namespace mozilla
--- a/content/svg/content/src/SVGPathSegListSMILType.cpp
+++ b/content/svg/content/src/SVGPathSegListSMILType.cpp
@@ -34,17 +34,17 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "SVGPathSegListSMILType.h"
 #include "nsSMILValue.h"
 #include "SVGPathData.h"
 #include <math.h>
 
-using namespace mozilla;
+namespace mozilla {
 
 /*static*/ SVGPathSegListSMILType SVGPathSegListSMILType::sSingleton;
 
 //----------------------------------------------------------------------
 // nsISMILType implementation
 
 void
 SVGPathSegListSMILType::Init(nsSMILValue &aValue) const
@@ -464,8 +464,10 @@ SVGPathSegListSMILType::Interpolate(cons
 
     NS_ABORT_IF_FALSE(pStart == pStartDataEnd && pEnd == pEndDataEnd &&
                       pResult == result.end(),
                       "Very, very bad - path data corrupt");
   }
 
   return NS_OK;
 }
+
+} // namespace mozilla
--- a/content/svg/content/src/SVGPointList.cpp
+++ b/content/svg/content/src/SVGPointList.cpp
@@ -42,17 +42,17 @@
 #include "nsContentUtils.h"
 #include "nsString.h"
 #include "nsSVGUtils.h"
 #include "string.h"
 #include "prdtoa.h"
 #include "nsTextFormatter.h"
 #include "nsCharSeparatedTokenizer.h"
 
-using namespace mozilla;
+namespace mozilla {
 
 nsresult
 SVGPointList::CopyFrom(const SVGPointList& rhs)
 {
   if (!SetCapacity(rhs.Length())) {
     // Yes, we do want fallible alloc here
     return NS_ERROR_OUT_OF_MEMORY;
   }
@@ -147,8 +147,10 @@ SVGPointList::SetValueFromString(const n
     rv = NS_ERROR_DOM_SYNTAX_ERR; // trailing comma
   }
   nsresult rv2 = CopyFrom(temp);
   if (NS_FAILED(rv2)) {
     return rv2; // prioritize OOM error code over syntax errors
   }
   return rv;
 }
+
+} // namespace mozilla
--- a/content/svg/content/src/SVGPointList.h
+++ b/content/svg/content/src/SVGPointList.h
@@ -138,24 +138,24 @@ private:
   PRBool InsertItem(PRUint32 aIndex, const SVGPoint &aPoint) {
     if (aIndex >= mItems.Length()) {
       aIndex = mItems.Length();
     }
     return !!mItems.InsertElementAt(aIndex, aPoint);
   }
 
   void ReplaceItem(PRUint32 aIndex, const SVGPoint &aPoint) {
-    NS_ASSERTION(aIndex < mItems.Length(),
-                 "DOM wrapper caller should have raised INDEX_SIZE_ERR");
+    NS_ABORT_IF_FALSE(aIndex < mItems.Length(),
+                      "DOM wrapper caller should have raised INDEX_SIZE_ERR");
     mItems[aIndex] = aPoint;
   }
 
   void RemoveItem(PRUint32 aIndex) {
-    NS_ASSERTION(aIndex < mItems.Length(),
-                 "DOM wrapper caller should have raised INDEX_SIZE_ERR");
+    NS_ABORT_IF_FALSE(aIndex < mItems.Length(),
+                      "DOM wrapper caller should have raised INDEX_SIZE_ERR");
     mItems.RemoveElementAt(aIndex);
   }
 
   PRBool AppendItem(SVGPoint aPoint) {
     return !!mItems.AppendElement(aPoint);
   }
 
 protected:
--- a/content/svg/content/src/SVGPointListSMILType.cpp
+++ b/content/svg/content/src/SVGPointListSMILType.cpp
@@ -35,17 +35,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "SVGPointListSMILType.h"
 #include "nsSMILValue.h"
 #include "SVGPointList.h"
 #include "nsMathUtils.h"
 #include <math.h>
 
-using namespace mozilla;
+namespace mozilla {
 
 /*static*/ SVGPointListSMILType SVGPointListSMILType::sSingleton;
 
 //----------------------------------------------------------------------
 // nsISMILType implementation
 
 void
 SVGPointListSMILType::Init(nsSMILValue &aValue) const
@@ -220,8 +220,10 @@ SVGPointListSMILType::Interpolate(const 
     }
     return NS_OK;
   }
   for (PRUint32 i = 0; i < end.Length(); ++i) {
     result[i] = start[i] + (end[i] - start[i]) * aUnitDistance;
   }
   return NS_OK;
 }
+
+} // namespace mozilla
--- a/content/svg/content/src/nsSVGAngle.cpp
+++ b/content/svg/content/src/nsSVGAngle.cpp
@@ -332,18 +332,18 @@ nsSVGAngle::ToDOMAnimVal(nsIDOMSVGAngle 
 
 /* Implementation */
 
 nsresult
 nsSVGAngle::SetBaseValueString(const nsAString &aValueAsString,
                                nsSVGElement *aSVGElement,
                                PRBool aDoSetAttr)
 {
-  float value;
-  PRUint16 unitType;
+  float value = 0;
+  PRUint16 unitType = 0;
   
   nsresult rv = GetValueFromString(aValueAsString, &value, &unitType);
   if (NS_FAILED(rv)) {
     return rv;
   }
 
   mBaseVal = value;
   mBaseValUnit = PRUint8(unitType);
--- a/content/svg/content/src/nsSVGFilters.cpp
+++ b/content/svg/content/src/nsSVGFilters.cpp
@@ -558,17 +558,17 @@ BoxBlur(const PRUint8 *aInput, PRUint8 *
     pos = NS_MAX(pos, aStartMinor);
     pos = NS_MIN(pos, aEndMinor - 1);
 #define SUM(j)     sums[j] += aInput[aStrideMinor*pos + j];
     SUM(0); SUM(1); SUM(2); SUM(3);
 #undef SUM
   }
 
   aOutput += aStrideMinor*aStartMinor;
-  if (aStartMinor + boxSize <= aEndMinor) {
+  if (aStartMinor + PRInt32(boxSize) <= aEndMinor) {
     const PRUint8 *lastInput = aInput + aStartMinor*aStrideMinor;
     const PRUint8 *nextInput = aInput + (aStartMinor + aRightLobe + 1)*aStrideMinor;
 #define OUTPUT(j)     aOutput[j] = (sums[j]*scaledDivisor) >> 24;
 #define SUM(j)        sums[j] += nextInput[j] - lastInput[j];
     // process pixels in B, G, R, A order because that's 0, 1, 2, 3 for x86
 #define OUTPUT_PIXEL() \
         if (!aAlphaOnly) { OUTPUT(GFX_ARGB32_OFFSET_B); \
                            OUTPUT(GFX_ARGB32_OFFSET_G); \
@@ -4871,17 +4871,18 @@ nsSVGFELightingElement::Filter(nsSVGFilt
     static_cast<nsSVGFEDistantLightElement*>
       (distantLight.get())->GetAnimatedNumberValues(&azimuth,
                                                     &elevation,
                                                     nsnull);
     L[0] = cos(azimuth * radPerDeg) * cos(elevation * radPerDeg);
     L[1] = sin(azimuth * radPerDeg) * cos(elevation * radPerDeg);
     L[2] = sin(elevation * radPerDeg);
   }
-  float lightPos[3], pointsAt[3], specularExponent, cosConeAngle;
+  float lightPos[3], pointsAt[3], specularExponent;
+  float cosConeAngle = 0;
   if (pointLight) {
     static_cast<nsSVGFEPointLightElement*>
       (pointLight.get())->GetAnimatedNumberValues(lightPos,
                                                   lightPos + 1,
                                                   lightPos + 2,
                                                   nsnull);
     instance->ConvertLocation(lightPos);
   }
@@ -4898,18 +4899,16 @@ nsSVGFELightingElement::Filter(nsSVGFilt
                                                  &limitingConeAngle,
                                                  nsnull);
     instance->ConvertLocation(lightPos);
     instance->ConvertLocation(pointsAt);
 
     nsCOMPtr<nsIContent> spot = do_QueryInterface(spotLight);
     if (spot->HasAttr(kNameSpaceID_None, nsGkAtoms::limitingConeAngle)) {
       cosConeAngle = NS_MAX<double>(cos(limitingConeAngle * radPerDeg), 0.0);
-    } else {
-      cosConeAngle = 0;
     }
   }
 
   float surfaceScale = mNumberAttributes[SURFACE_SCALE].GetAnimValue();
 
   const nsIntRect& dataRect = info.mDataRect;
   PRInt32 stride = info.mSource->Stride();
   PRUint8 *sourceData = info.mSource->Data();
--- a/content/svg/content/src/nsSVGPolyElement.cpp
+++ b/content/svg/content/src/nsSVGPolyElement.cpp
@@ -110,17 +110,17 @@ nsSVGPolyElement::AttributeDefinesGeomet
 void
 nsSVGPolyElement::GetMarkPoints(nsTArray<nsSVGMark> *aMarks)
 {
   const SVGPointList &points = mPoints.GetAnimValue();
 
   if (!points.Length())
     return;
 
-  float px = 0.0, py = 0.0, prevAngle;
+  float px = 0.0, py = 0.0, prevAngle = 0.0;
 
   for (PRUint32 i = 0; i < points.Length(); ++i) {
     float x = points[i].mX;
     float y = points[i].mY;
     float angle = atan2(y-py, x-px);
     if (i == 1)
       aMarks->ElementAt(aMarks->Length() - 1).angle = angle;
     else if (i > 1)
--- a/content/svg/content/test/test_SVGxxxList.xhtml
+++ b/content/svg/content/test/test_SVGxxxList.xhtml
@@ -75,16 +75,20 @@ To have the battery of generic tests run
   attr_val_3a:
   attr_val_3b:
     Two attribute values containing three different items.
   attr_val_4
     An attribute value containing four items.
   attr_val_5a:
   attr_val_5b:
     Two attribute values containing five different items.
+  attr_val_5b_firstItem_x3_constructor:
+    Function to construct a list-item that should match the first item in a
+    SVGXxxList after three repeats of a cumulative animation to attr_val_5b.
+    This function takes t.item_constructor as its only argument.
   item_constructor:
     Function to create a dummy list item.
   item_is:
     Function to compare two list items for equality, like "is()". If this
     property is omitted, it is assumed that we can just compare
     "item.value" (which is the case for most list types).
 */
 
@@ -99,17 +103,22 @@ var tests = [
     el_type: 'SVGTextElement',
     prop_type: 'SVGAnimatedLengthList',
     list_type: 'SVGLengthList',
     item_type: 'SVGLength',
     attr_val_3a: '10 20ex, 30in',
     attr_val_3b: '30in 10, 20ex',
     attr_val_4 : '10 20ex, 30in ,40cm',
     attr_val_5a: '10 20ex, 30in ,40cm , 50%',
-    attr_val_5b: '50% 10, 20ex ,30in , 40cm',
+    attr_val_5b: '20 50%, 20ex ,30in , 40cm',
+    attr_val_5b_firstItem_x3_constructor: function(constructor) {
+      var expected = constructor();
+      expected.value = 60;
+      return expected;
+    },
     item_constructor: function() {
       // We need this function literal to avoid "Illegal operation on
       // WrappedNative prototype object" NS_ERROR_XPC_BAD_OP_ON_WN_PROTO.
       return document.getElementById('svg').createSVGLength();
     }
   },
   {
     // SVGNumberList test:
@@ -122,16 +131,21 @@ var tests = [
     prop_type: 'SVGAnimatedNumberList',
     list_type: 'SVGNumberList',
     item_type: 'SVGNumber',
     attr_val_3a: '0 20 40',
     attr_val_3b: '60 40 20',
     attr_val_4 : '40 20 10 80',
     attr_val_5a: '90 30 60 20 70',
     attr_val_5b: '30 20 70 30 90',
+    attr_val_5b_firstItem_x3_constructor: function(constructor) {
+      var expected = constructor();
+      expected.value = 90;
+      return expected;
+    },
     item_constructor: function() {
       // We need this function literal to avoid "Illegal operation on
       // WrappedNative prototype object" NS_ERROR_XPC_BAD_OP_ON_WN_PROTO.
       return document.getElementById('svg').createSVGNumber();
     }
   },
   {
     // SVGNumberList test:
@@ -144,16 +158,21 @@ var tests = [
     prop_type: 'SVGAnimatedNumberList',
     list_type: 'SVGNumberList',
     item_type: 'SVGNumber',
     attr_val_3a: '0 .5 .2',
     attr_val_3b: '1 .7 .1',
     attr_val_4 : '.5 .3 .8 .2',
     attr_val_5a: '3 4 5 6 7',
     attr_val_5b: '7 6 5 4 3',
+    attr_val_5b_firstItem_x3_constructor: function(constructor) {
+      var expected = constructor();
+      expected.value = 21;
+      return expected;
+    },
     item_constructor: function() {
       // We need this function literal to avoid "Illegal operation on
       // WrappedNative prototype object" NS_ERROR_XPC_BAD_OP_ON_WN_PROTO.
       return document.getElementById('svg').createSVGNumber();
     }
   },
   {
     // SVGPointList test:
@@ -166,16 +185,22 @@ var tests = [
     prop_type: null,
     list_type: 'SVGPointList',
     item_type: 'SVGPoint',
     attr_val_3a: ' 10,10 50,50 90,10 ',
     attr_val_3b: ' 10,50 50,10 90,50 ',
     attr_val_4 : ' 10,10 50,50 90,10 200,100 ',
     attr_val_5a: ' 10,10 50,50 90,10 130,50 170,10 ',
     attr_val_5b: ' 50,10 50,10 90,50 130,10 170,50 ',
+    attr_val_5b_firstItem_x3_constructor: function(constructor) {
+      var expected = constructor();
+      expected.x = 150;
+      expected.y = 30;
+      return expected;
+    },
     item_constructor: function() {
       // XXX return different values each time
       return document.getElementById('svg').createSVGPoint();
     },
     item_is: function(itemA, itemB, message) {
       ok(typeof(itemA.x) != 'undefined' &&
          typeof(itemB.x) != 'undefined',
          'expecting x property');
@@ -198,27 +223,53 @@ var tests = [
     prop_type: null,
     list_type: 'SVGPathSegList',
     item_type: 'SVGPathSeg',
     attr_val_3a: 'M 10,10 L 50,50 L 90,10',
     attr_val_3b: 'M 10,50 L 50,10 L 90,50',
     attr_val_4 : 'M 10,10 L 50,50 L 90,10 M 200,100',
     attr_val_5a: 'M 10,10 L 50,50 L 90,10 L 130,50 L 170,10',
     attr_val_5b: 'M 50,10 L 50,10 L 90,50 L 130,10 L 170,50',
+    attr_val_5b_firstItem_x3_constructor: function(constructor) {
+      var expected = constructor();
+      is(expected.pathSegTypeAsLetter, "M",
+         "test error -- expected constructor to generate a segment of type M");
+      expected.x = 150;
+      expected.y = 30;
+      return expected;
+    },
     item_constructor: function() {
       // XXX return different values each time
       return document.getElementById('path').createSVGPathSegMovetoAbs(1, 1);
     },
     item_is: function(itemA, itemB, message) {
-      ok(typeof(itemA.pathSegType) != 'undefined' &&
-         typeof(itemB.pathSegType) != 'undefined',
-         'expecting pathSegType property');
+      ok(typeof(itemA.pathSegTypeAsLetter) != 'undefined' &&
+         typeof(itemB.pathSegTypeAsLetter) != 'undefined',
+         'expecting pathSegTypeAsLetter property');
+
+      // First: are we dealing  with the same type of segment?
+      is(itemA.pathSegTypeAsLetter, itemB.pathSegTypeAsLetter, message);
+      if (itemA.pathSegTypeAsLetter != itemB.pathSegTypeAsLetter)
+        return;  // The rest of this function is nonsense if types don't match.
 
-      // NOTE: Just comparing pathSegType - probably sufficient for our purposes
-      is(itemA.pathSegType, itemB.pathSegType, message);
+      // Make sure property-counts match (so we can iterate across itemA's
+      // properties and not worry about itemB having extra properties that
+      // we might be skipping over).
+      is(keys(itemA).length, keys(itemB).length,
+        'expecting same property-count when comparing path segs of same type.');
+
+      // Compare the properties, skipping the constant properties inherited
+      // from 'SVGPathSeg', and skipping the pathSegTypeAsLetter field since we
+      // already checked that above. 
+      for (var prop in itemA) {
+        if (!SVGPathSeg.hasOwnProperty(prop) &&
+            prop != 'pathSegTypeAsLetter') {
+          is(itemA[prop], itemB[prop], message);
+        }
+      }
     }
   },
 /*
   {
     // SVGPathSegList test:
     target_element_id: 'path',
     attr_name: 'd',
     prop_name: null, // SVGAnimatedPathData is an inherited interface!
@@ -233,22 +284,40 @@ var tests = [
     attr_val_4 : '',
     attr_val_5a: '',
     attr_val_5b: '',
     item_constructor: function() {
       // XXX return different values each time
       return SVGPathElement.createSVGPathSegLinetoAbs(1, 1);
     },
     item_is: function(itemA, itemB, message) {
-      ok(typeof(itemA.pathSegType) != 'undefined' &&
-         typeof(itemB.pathSegType) != 'undefined',
-         'expecting pathSegType property');
+      ok(typeof(itemA.pathSegTypeAsLetter) != 'undefined' &&
+         typeof(itemB.pathSegTypeAsLetter) != 'undefined',
+         'expecting pathSegTypeAsLetter property');
+
+      // First: are we dealing  with the same type of segment?
+      is(itemA.pathSegTypeAsLetter, itemB.pathSegTypeAsLetter, message);
+      if (itemA.pathSegTypeAsLetter != itemB.pathSegTypeAsLetter)
+        return;  // The rest of this function is nonsense if types don't match.
 
-      // NOTE: Just comparing pathSegType - probably sufficient for our purposes
-      is(itemA.pathSegType, itemB.pathSegType, message);
+      // Make sure property-counts match (so we can iterate across itemA's
+      // properties and not worry about itemB having extra properties that
+      // we might be skipping over).
+      is(keys(itemA).length, keys(itemB).length,
+        'expecting same property-count when comparing path segs of same type.');
+
+      // Compare the properties, skipping the constant properties inherited
+      // from 'SVGPathSeg', and skipping the pathSegTypeAsLetter field since we
+      // already checked that above. 
+      for (var prop in itemA) {
+        if (!SVGPathSeg.hasOwnProperty(prop) &&
+            prop != 'pathSegTypeAsLetter') {
+          is(itemA[prop], itemB[prop], message);
+        }
+      }
     }
   },
   {
     // SVGStringList test:
     target_element_id: 'g',
     attr_name: 'requiredFeatures', // requiredExtensions, systemLanguage, viewTarget
     prop_name: null, // SVGStringList attributes are not animatable
     bv_name: 'requiredFeatures',
@@ -294,22 +363,22 @@ var tests = [
   },
   */
 ];
 
 
 /*
 This function returns a DocumentFragment with three 'animate' element children. The duration of the three animations is as follows:
 
-  animation 1: |  *-----------*-----------*
+  animation 1: |  *-----------*-----------*-----------*
   animation 2: |     *--*
   animation 3: |                    *--*
-               |__________________________________> time (s)
-               |  |  |  |  |  |  |  |  |  |  |  |
-               0  1  2  3  4  5  6  7  8  9 10 11
+               |___________________________________________> time (s)
+               |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
+               0  1  2  3  4  5  6  7  8  9 10 11 12 13 14
 
 The first animation repeats once so that we can test state on a repeat animation.
 
 The second animation overrides the first animation for a short time, and has fewer list items than the first animation. This allows us to test object identity and other state on and after an overriding animation. Specifically, it allows us to check whether animVal list items are kept or discarded after the end of an overriding animation that has fewer items.
 
 The third animation has additive="sum", with fewer items than the lower priority animation 1, allowing us to test object identity and other state in that scenario. TODO: some type aware tests to check whether the composite fails or works?
 
 At t=0s and t=1s we test the effect of an attribute value changes in the absence and presence of SMIL animation respectively.
@@ -338,17 +407,18 @@ function create_animate_elements(test)
     var animate3 = document.createElementNS(SVG_NS, 'animate');
   }
 
   animate1.setAttribute('attributeName', test.attr_name);
   animate1.setAttribute('from', test.attr_val_5a);
   animate1.setAttribute('to', test.attr_val_5b);
   animate1.setAttribute('begin', '1s');
   animate1.setAttribute('dur', '4s');
-  animate1.setAttribute('repeatCount', '2');
+  animate1.setAttribute('repeatCount', '3');
+  animate1.setAttribute('accumulate', 'sum');
   animate1.setAttribute('fill', 'freeze');
   df.appendChild(animate1);
 
   animate2.setAttribute('attributeName', test.attr_name);
   animate2.setAttribute('from', test.attr_val_3a);
   animate2.setAttribute('to', test.attr_val_3b);
   animate2.setAttribute('begin', '2s');
   animate2.setAttribute('dur', '1s');
@@ -1212,35 +1282,41 @@ function run_animation_timeline_tests()
     // all SVGLengthList attributes allow a short list to be added to longer
     // list, they do not all allow a longer list to be added to shorter list.
     // Specifically that would not be good for 'x' and 'y' on <text> since
     // lengths there are not naturally zero. See the comment in
     // SVGLengthListSMILAttr::Add().
   }
 
 
-  /********************    t = 10s    ********************/
+  /********************    t = 13s    ********************/
 
-  svg.setCurrentTime(10); // all animations have finished, but one is frozen
+  svg.setCurrentTime(13); // all animations have finished, but one is frozen
 
   for each (var t in tests) {
     if (!t.animVal)
       continue;
 
     ok(t.baseVal.numberOfItems == t.old_baseVal_items.length &&
        t.baseVal.getItem(3) === t.old_baseVal_items[3],
        'When a SMIL animation ends, it should never affect the '+
        t.list_type+' for '+t.bv_path+', or its list items.');
 
     is(t.animVal.numberOfItems, 5,
        'Even though all SMIL animation have finished, the number '+
        'of items in the '+t.list_type+' for '+t.av_path+
        ' should still be more than the same as the number of items in '+
        t.bv_path+' since one of the animations is still frozen.');
 
+    var expected = t.attr_val_5b_firstItem_x3_constructor(t.item_constructor);
+    t.item_is(t.animVal.getItem(0), expected,
+      'animation with accumulate="sum" and repeatCount="3" for attribute "'+
+       t.attr_name+'" should end up at 3x the "to" value.');
+
+    // Unfreeze frozen animation (removing its effects)
     var frozen_animate_element =
       t.element.querySelector('animate[fill][attributeName="'+t.attr_name+'"]');
     frozen_animate_element.removeAttribute('fill');
 
     ok(t.animVal.numberOfItems == t.baseVal.numberOfItems,
        'Once all SMIL animation have finished and been un-frozen, the number '+
        'of items in the '+t.list_type+' for '+t.av_path+
        ' should be the same as the number of items in '+t.bv_path+'.');
--- a/content/xbl/src/nsXBLBinding.cpp
+++ b/content/xbl/src/nsXBLBinding.cpp
@@ -1249,17 +1249,17 @@ nsXBLBinding::WalkRules(nsIStyleRuleProc
 nsresult
 nsXBLBinding::DoInitJSClass(JSContext *cx, JSObject *global, JSObject *obj,
                             const nsAFlatCString& aClassName,
                             nsXBLPrototypeBinding* aProtoBinding,
                             void **aClassObject)
 {
   // First ensure our JS class is initialized.
   jsval val;
-  JSObject* proto;
+  JSObject* proto = NULL;
 
   nsCAutoString className(aClassName);
   JSObject* parent_proto = nsnull;  // If we have an "obj" we can set this
   JSAutoRequest ar(cx);
 
   JSAutoEnterCompartment ac;
   if (!ac.enter(cx, global))
       return NS_ERROR_FAILURE;
--- a/content/xbl/src/nsXBLDocumentInfo.cpp
+++ b/content/xbl/src/nsXBLDocumentInfo.cpp
@@ -71,17 +71,17 @@ public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   
   // nsIScriptGlobalObject methods
   virtual nsresult EnsureScriptEnvironment(PRUint32 aLangID);
   virtual nsresult SetScriptContext(PRUint32 lang_id, nsIScriptContext *aContext);
 
   virtual nsIScriptContext *GetContext();
   virtual JSObject *GetGlobalJSObject();
-  virtual void OnFinalize(PRUint32 aLangID, void *aScriptGlobal);
+  virtual void OnFinalize(JSObject* aObject);
   virtual void SetScriptsEnabled(PRBool aEnabled, PRBool aFireTimeouts);
 
   // nsIScriptObjectPrincipal methods
   virtual nsIPrincipal* GetPrincipal();
 
   static JSBool doCheckAccess(JSContext *cx, JSObject *obj, jsid id,
                               PRUint32 accessType);
 
@@ -162,17 +162,17 @@ nsXBLDocGlobalObject_checkAccess(JSConte
 static void
 nsXBLDocGlobalObject_finalize(JSContext *cx, JSObject *obj)
 {
   nsISupports *nativeThis = (nsISupports*)JS_GetPrivate(cx, obj);
 
   nsCOMPtr<nsIScriptGlobalObject> sgo(do_QueryInterface(nativeThis));
 
   if (sgo)
-    sgo->OnFinalize(nsIProgrammingLanguage::JAVASCRIPT, obj);
+    sgo->OnFinalize(obj);
 
   // The addref was part of JSObject construction
   NS_RELEASE(nativeThis);
 }
 
 static JSBool
 nsXBLDocGlobalObject_resolve(JSContext *cx, JSObject *obj, jsid id)
 {
@@ -378,23 +378,20 @@ nsXBLDocGlobalObject::GetGlobalJSObject(
     return nsnull;
 
   JSObject *ret = ::JS_GetGlobalObject(cx);
   NS_ASSERTION(mJSObject == ret, "How did this magic switch happen?");
   return ret;
 }
 
 void
-nsXBLDocGlobalObject::OnFinalize(PRUint32 aLangID, void *aObject)
+nsXBLDocGlobalObject::OnFinalize(JSObject* aObject)
 {
-  NS_ASSERTION(aLangID == nsIProgrammingLanguage::JAVASCRIPT,
-               "Only JS supported");
   NS_ASSERTION(aObject == mJSObject, "Wrong object finalized!");
-
-  mJSObject = nsnull;
+  mJSObject = NULL;
 }
 
 void
 nsXBLDocGlobalObject::SetScriptsEnabled(PRBool aEnabled, PRBool aFireTimeouts)
 {
     // We don't care...
 }
 
--- a/content/xml/document/src/nsXMLContentSink.cpp
+++ b/content/xml/document/src/nsXMLContentSink.cpp
@@ -1226,18 +1226,17 @@ nsXMLContentSink::HandleDoctypeDecl(cons
   NS_ASSERTION(mDocument, "Shouldn't get here from a document fragment");
 
   nsCOMPtr<nsIAtom> name = do_GetAtom(aName);
   NS_ENSURE_TRUE(name, NS_ERROR_OUT_OF_MEMORY);
 
   // Create a new doctype node
   nsCOMPtr<nsIDOMDocumentType> docType;
   rv = NS_NewDOMDocumentType(getter_AddRefs(docType), mNodeInfoManager, nsnull,
-                             name, nsnull, nsnull, aPublicId, aSystemId,
-                             aSubset);
+                             name, aPublicId, aSystemId, aSubset);
   if (NS_FAILED(rv) || !docType) {
     return rv;
   }
 
   if (aCatalogData && mCSSLoader && mDocument) {
     // bug 124570 - we only expect additional agent sheets for now -- ignore
     // exit codes, error are not fatal here, just that the stylesheet won't apply
     nsCOMPtr<nsIURI> uri(do_QueryInterface(aCatalogData));
--- a/content/xslt/src/xpath/txCoreFunctionCall.cpp
+++ b/content/xslt/src/xpath/txCoreFunctionCall.cpp
@@ -324,17 +324,17 @@ txCoreFunctionCall::evaluate(txIEvalCont
             return NS_OK;
         }
         case STARTS_WITH:
         {
             nsAutoString arg2;
             rv = mParams[1]->evaluateToString(aContext, arg2);
             NS_ENSURE_SUCCESS(rv, rv);
 
-            PRBool result;
+            PRBool result = PR_FALSE;
             if (arg2.IsEmpty()) {
                 result = PR_TRUE;
             }
             else {
                 nsAutoString arg1;
                 rv = mParams[0]->evaluateToString(aContext, arg1);
                 NS_ENSURE_SUCCESS(rv, rv);
 
--- a/content/xslt/src/xpath/txExprParser.cpp
+++ b/content/xslt/src/xpath/txExprParser.cpp
@@ -597,18 +597,18 @@ txExprParser::createLocationStep(txExprL
             rv = resolveQName(tok->Value(), getter_AddRefs(prefix),
                               aContext, getter_AddRefs(lName),
                               nspace, PR_TRUE);
             NS_ENSURE_SUCCESS(rv, rv);
 
             nodeTest =
               new txNameTest(prefix, lName, nspace,
                              axisIdentifier == LocationStep::ATTRIBUTE_AXIS ?
-                             txXPathNodeType::ATTRIBUTE_NODE :
-                             txXPathNodeType::ELEMENT_NODE);
+                             static_cast<PRUint16>(txXPathNodeType::ATTRIBUTE_NODE) :
+                             static_cast<PRUint16>(txXPathNodeType::ELEMENT_NODE));
             NS_ENSURE_TRUE(nodeTest, NS_ERROR_OUT_OF_MEMORY);
         }
         else {
             lexer.pushBack();
             rv = createNodeTypeTest(lexer, getter_Transfers(nodeTest));
             NS_ENSURE_SUCCESS(rv, rv);
         }
     }
--- a/content/xslt/src/xpath/txXPCOMExtensionFunction.cpp
+++ b/content/xslt/src/xpath/txXPCOMExtensionFunction.cpp
@@ -264,17 +264,17 @@ LookupFunction(const char *aContractID, 
 
 /* static */
 nsresult
 TX_ResolveFunctionCallXPCOM(const nsCString &aContractID, PRInt32 aNamespaceID,
                             nsIAtom* aName, nsISupports *aState,
                             FunctionCall **aFunction)
 {
     nsIID iid;
-    PRUint16 methodIndex;
+    PRUint16 methodIndex = 0;
     nsCOMPtr<nsISupports> helper;
 
     nsresult rv = LookupFunction(aContractID.get(), aName, iid, methodIndex,
                                  getter_AddRefs(helper));
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!aFunction) {
         return NS_OK;
--- a/content/xslt/src/xslt/txMozillaXMLOutput.cpp
+++ b/content/xslt/src/xslt/txMozillaXMLOutput.cpp
@@ -944,17 +944,17 @@ txMozillaXMLOutput::createResultDocument
                 return NS_ERROR_OUT_OF_MEMORY;
             }
 
             // Indicate that there is no internal subset (not just an empty one)
             nsAutoString voidString;
             voidString.SetIsVoid(PR_TRUE);
             rv = NS_NewDOMDocumentType(getter_AddRefs(documentType),
                                        mNodeInfoManager, nsnull,
-                                       doctypeName, nsnull, nsnull,
+                                       doctypeName,
                                        mOutputFormat.mPublicId,
                                        mOutputFormat.mSystemId,
                                        voidString);
             NS_ENSURE_SUCCESS(rv, rv);
 
             nsCOMPtr<nsIContent> docType = do_QueryInterface(documentType);
             rv = mDocument->AppendChildTo(docType, PR_TRUE);
             NS_ENSURE_SUCCESS(rv, rv);
--- a/content/xul/content/src/nsXULElement.cpp
+++ b/content/xul/content/src/nsXULElement.cpp
@@ -769,18 +769,18 @@ nsScriptEventHandlerOwnerTearoff::Compil
 {
     nsresult rv;
 
     XUL_PROTOTYPE_ATTRIBUTE_METER(gNumCacheSets);
 
     // XXX sXBL/XBL2 issue! Owner or current document?
     nsCOMPtr<nsIXULDocument> xuldoc = do_QueryInterface(mElement->GetOwnerDoc());
 
-    nsIScriptContext *context;
-    nsXULPrototypeElement *elem = mElement->mPrototype;
+    nsIScriptContext* context = NULL;
+    nsXULPrototypeElement* elem = mElement->mPrototype;
     if (elem && xuldoc) {
         // It'll be shared among the instances of the prototype.
 
         // Use the prototype document's special context.  Because
         // scopeObject is null, the JS engine has no other source of
         // <the-new-shared-event-handler>.__proto__ than to look in
         // cx->globalObject for Function.prototype.  That prototype
         // keeps the global object alive, so if we use this document's
--- a/content/xul/document/src/nsXULPrototypeDocument.cpp
+++ b/content/xul/document/src/nsXULPrototypeDocument.cpp
@@ -76,17 +76,17 @@ class nsXULPDGlobalObject : public nsISc
 {
 public:
     nsXULPDGlobalObject(nsXULPrototypeDocument* owner);
 
     // nsISupports interface
     NS_DECL_CYCLE_COLLECTING_ISUPPORTS
 
     // nsIScriptGlobalObject methods
-    virtual void OnFinalize(PRUint32 aLangID, void *aGlobal);
+    virtual void OnFinalize(JSObject* aObject);
     virtual void SetScriptsEnabled(PRBool aEnabled, PRBool aFireTimeouts);
 
     virtual void *GetScriptGlobal(PRUint32 lang);
     virtual nsresult EnsureScriptEnvironment(PRUint32 aLangID);
 
     virtual nsIScriptContext *GetScriptContext(PRUint32 lang);
     virtual nsresult SetScriptContext(PRUint32 language, nsIScriptContext *ctx);
 
@@ -119,17 +119,17 @@ PRUint32 nsXULPrototypeDocument::gRefCnt
 void
 nsXULPDGlobalObject_finalize(JSContext *cx, JSObject *obj)
 {
     nsISupports *nativeThis = (nsISupports*)JS_GetPrivate(cx, obj);
 
     nsCOMPtr<nsIScriptGlobalObject> sgo(do_QueryInterface(nativeThis));
 
     if (sgo) {
-        sgo->OnFinalize(nsIProgrammingLanguage::JAVASCRIPT, obj);
+        sgo->OnFinalize(obj);
     }
 
     // The addref was part of JSObject construction
     NS_RELEASE(nativeThis);
 }
 
 
 JSBool
@@ -772,20 +772,18 @@ nsXULPDGlobalObject::ClearGlobalObjectOw
     mContext = NULL;
   }
 
   mGlobalObjectOwner = NULL;
 }
 
 
 void
-nsXULPDGlobalObject::OnFinalize(PRUint32 aLangID, void *aObject)
+nsXULPDGlobalObject::OnFinalize(JSObject* aObject)
 {
-  NS_ABORT_IF_FALSE(aLangID == nsIProgrammingLanguage::JAVASCRIPT,
-                    "We don't support this language ID");
   mJSObject = NULL;
 }
 
 void
 nsXULPDGlobalObject::SetScriptsEnabled(PRBool aEnabled, PRBool aFireTimeouts)
 {
   // We don't care...
 }
--- a/content/xul/templates/src/nsTemplateRule.cpp
+++ b/content/xul/templates/src/nsTemplateRule.cpp
@@ -202,18 +202,18 @@ nsTemplateCondition::CheckMatchStrings(c
             }
 
             case eBefore:
             {
                 nsICollation* collation = nsXULContentUtils::GetCollation();
                 if (collation) {
                     PRInt32 sortOrder;
                     collation->CompareString((mIgnoreCase ?
-                                              nsICollation::kCollationCaseInSensitive :
-                                              nsICollation::kCollationCaseSensitive),
+                                              static_cast<PRInt32>(nsICollation::kCollationCaseInSensitive) :
+                                              static_cast<PRInt32>(nsICollation::kCollationCaseSensitive)),
                                               aLeftString,
                                               aRightString,
                                               &sortOrder);
                     match = (sortOrder < 0);
                 }
                 else if (mIgnoreCase) {
                     match = (Compare(aLeftString, aRightString,
                                      nsCaseInsensitiveStringComparator()) < 0);
@@ -225,18 +225,18 @@ nsTemplateCondition::CheckMatchStrings(c
             }
 
             case eAfter:
             {
                 nsICollation* collation = nsXULContentUtils::GetCollation();
                 if (collation) {
                     PRInt32 sortOrder;
                     collation->CompareString((mIgnoreCase ?
-                                              nsICollation::kCollationCaseInSensitive :
-                                              nsICollation::kCollationCaseSensitive),
+                                              static_cast<PRInt32>(nsICollation::kCollationCaseInSensitive) :
+                                              static_cast<PRInt32>(nsICollation::kCollationCaseSensitive)),
                                               aLeftString,
                                               aRightString,
                                               &sortOrder);
                     match = (sortOrder > 0);
                 }
                 else if (mIgnoreCase) {
                     match = (Compare(aLeftString, aRightString,
                                      nsCaseInsensitiveStringComparator()) > 0);
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -1533,16 +1533,17 @@ struct nsConstructorFuncMapData
 
 #define NS_DEFINE_CONSTRUCTOR_FUNC_DATA(_class, _func)                        \
   { eDOMClassInfo_##_class##_id, _func },
 
 static const nsConstructorFuncMapData kConstructorFuncMap[] =
 {
   NS_DEFINE_CONSTRUCTOR_FUNC_DATA(Worker, nsDOMWorker::NewWorker)
   NS_DEFINE_CONSTRUCTOR_FUNC_DATA(ChromeWorker, nsDOMWorker::NewChromeWorker)
+  NS_DEFINE_CONSTRUCTOR_FUNC_DATA(File, nsDOMFile::NewFile)
 };
 
 nsIXPConnect *nsDOMClassInfo::sXPConnect = nsnull;
 nsIScriptSecurityManager *nsDOMClassInfo::sSecMan = nsnull;
 PRBool nsDOMClassInfo::sIsInitialized = PR_FALSE;
 PRBool nsDOMClassInfo::sDisableDocumentAllSupport = PR_FALSE;
 PRBool nsDOMClassInfo::sDisableGlobalScopePollutionSupport = PR_FALSE;
 
@@ -7073,17 +7074,17 @@ nsWindowSH::NewResolve(nsIXPConnectWrapp
 
 NS_IMETHODIMP
 nsWindowSH::Finalize(nsIXPConnectWrappedNative *wrapper, JSContext *cx,
                      JSObject *obj)
 {
   nsCOMPtr<nsIScriptGlobalObject> sgo(do_QueryWrappedNative(wrapper));
   NS_ENSURE_TRUE(sgo, NS_ERROR_UNEXPECTED);
 
-  sgo->OnFinalize(nsIProgrammingLanguage::JAVASCRIPT, obj);
+  sgo->OnFinalize(obj);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsWindowSH::Equality(nsIXPConnectWrappedNative *wrapper, JSContext * cx,
                      JSObject * obj, const jsval &val, PRBool *bp)
 {
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -2755,23 +2755,20 @@ nsGlobalWindow::DispatchDOMEvent(nsEvent
 {
   return
     nsEventDispatcher::DispatchDOMEvent(static_cast<nsPIDOMWindow*>(this),
                                        aEvent, aDOMEvent, aPresContext,
                                        aEventStatus);
 }
 
 void
-nsGlobalWindow::OnFinalize(PRUint32 aLangID, void *aObject)
-{
-  NS_ASSERTION(aLangID == nsIProgrammingLanguage::JAVASCRIPT,
-               "We don't support this language ID");
-
+nsGlobalWindow::OnFinalize(JSObject* aObject)
+{
   if (aObject == mJSObject) {
-    mJSObject = nsnull;
+    mJSObject = NULL;
   }
 }
 
 void
 nsGlobalWindow::SetScriptsEnabled(PRBool aEnabled, PRBool aFireTimeouts)
 {
   FORWARD_TO_INNER_VOID(SetScriptsEnabled, (aEnabled, aFireTimeouts));
 
--- a/dom/base/nsGlobalWindow.h
+++ b/dom/base/nsGlobalWindow.h
@@ -315,17 +315,17 @@ public:
 
   virtual nsIScriptContext *GetScriptContext(PRUint32 lang);
   virtual void *GetScriptGlobal(PRUint32 lang);
 
   // Set a new script language context for this global.  The native global
   // for the context is created by the context's GetNativeGlobal() method.
   virtual nsresult SetScriptContext(PRUint32 lang, nsIScriptContext *aContext);
   
-  virtual void OnFinalize(PRUint32 aLangID, void *aScriptGlobal);
+  virtual void OnFinalize(JSObject* aObject);
   virtual void SetScriptsEnabled(PRBool aEnabled, PRBool aFireTimeouts);
 
   // nsIScriptObjectPrincipal
   virtual nsIPrincipal* GetPrincipal();
 
   // nsIDOMWindow
   NS_DECL_NSIDOMWINDOW
 
--- a/dom/base/nsIScriptGlobalObject.h
+++ b/dom/base/nsIScriptGlobalObject.h
@@ -95,22 +95,22 @@ struct JSObject; // until we finally rem
 // aStatus will be filled in with the status.
 PRBool
 NS_HandleScriptError(nsIScriptGlobalObject *aScriptGlobal,
                      nsScriptErrorEvent *aErrorEvent,
                      nsEventStatus *aStatus);
 
 
 #define NS_ISCRIPTGLOBALOBJECT_IID \
-{ 0xe9f3f2c1, 0x2d94, 0x4722, \
-  { 0xbb, 0xd4, 0x2b, 0xf6, 0xfd, 0xf4, 0x2f, 0x48 } }
+{ 0x4eb16819, 0x4e81, 0x406e, \
+  { 0x93, 0x05, 0x6f, 0x30, 0xfc, 0xd2, 0x62, 0x4a } }
 
 /**
-  * The global object which keeps a script context for each supported script
-  * language. This often used to store per-window global state.
+ * The global object which keeps a script context for each supported script
+ * language. This often used to store per-window global state.
  */
 
 class nsIScriptGlobalObject : public nsISupports
 {
 public:
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISCRIPTGLOBALOBJECT_IID)
 
   /**
@@ -151,18 +151,17 @@ public:
 
   /**
    * Called when the global script for a language is finalized, typically as
    * part of its GC process.  By the time this call is made, the
    * nsIScriptContext for the language has probably already been removed.
    * After this call, the passed object is dead - which should generally be the
    * same object the global is using for a global for that language.
    */
-
-  virtual void OnFinalize(PRUint32 aLangID, void *aScriptGlobal) = 0;
+  virtual void OnFinalize(JSObject* aObject) = 0;
 
   /**
    * Called to enable/disable scripts.
    */
   virtual void SetScriptsEnabled(PRBool aEnabled, PRBool aFireTimeouts) = 0;
 
   /**
    * Handle a script error.  Generally called by a script context.
--- a/dom/interfaces/core/Makefile.in
+++ b/dom/interfaces/core/Makefile.in
@@ -71,17 +71,16 @@ XPIDLSRCS =                             
 	nsIDOM3Text.idl				\
 	nsIDOM3TypeInfo.idl			\
 	nsIDOM3Attr.idl				\
 	nsIDOMDOMStringList.idl			\
 	nsIDOMNameList.idl			\
 	nsIDOMNSDocument.idl			\
 	nsIDOMXMLDocument.idl			\
 	nsIDOMUserDataHandler.idl		\
-	nsIDOMDOMConfiguration.idl		\
 	nsIDOMNSEditableElement.idl		\
 	nsIDOMNSElement.idl			\
 	nsIDOMNodeSelector.idl			\
 	nsIDOMDOMTokenList.idl			\
 	nsIDOMDOMSettableTokenList.idl	\
 	$(NULL)
 
 include $(topsrcdir)/config/rules.mk
deleted file mode 100644
--- a/dom/interfaces/core/nsIDOMDOMConfiguration.idl
+++ /dev/null
@@ -1,61 +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) 2003
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Christopher A. Aillon <christopher@aillon.com> (Original Author)
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#include "domstubs.idl"
-
-interface nsIVariant;
-
-/**
- * The nsIDOMDOMConfiguration interface represents the configuration
- * of a document and maintains a table of recognized parameters.
- *
- * For more information on this interface, please see
- * http://www.w3.org/TR/DOM-Level-3-Core/
- */
-
-// Introduced in DOM Level 3:
-[scriptable, uuid(cfb5b821-9016-4a79-9d98-87b57c3ea0c7)]
-interface nsIDOMDOMConfiguration : nsISupports
-{
-  void               setParameter(in DOMString name, 
-                                  in nsIVariant value)
-                                        raises(DOMException);
-  nsIVariant         getParameter(in DOMString name)
-                                        raises(DOMException);
-  boolean            canSetParameter(in DOMString name, 
-                                     in nsIVariant value);
-};
--- a/dom/interfaces/core/nsIDOMDocument.idl
+++ b/dom/interfaces/core/nsIDOMDocument.idl
@@ -34,32 +34,30 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsIDOMNode.idl"
 
-interface nsIDOMDOMConfiguration;
-
 /**
  * The nsIDOMDocument interface represents the entire HTML or XML document.
  * Conceptually, it is the root of the document tree, and provides the 
  * primary access to the document's data.
  * Since elements, text nodes, comments, processing instructions, etc. 
  * cannot exist outside the context of a Document, the nsIDOMDocument 
  * interface also contains the factory methods needed to create these 
  * objects.
  *
  * For more information on this interface please see 
  * http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html
  */
 
-[scriptable, uuid(3e7421c4-9964-4184-8c75-d291eecdba35)]
+[scriptable, uuid(cf88ac5e-49d9-4294-9255-ff80a1727f91)]
 interface nsIDOMDocument : nsIDOMNode
 {
   readonly attribute nsIDOMDocumentType         doctype;
   readonly attribute nsIDOMDOMImplementation    implementation;
   readonly attribute nsIDOMElement              documentElement;
   nsIDOMElement                 createElement(in DOMString tagName)
                                   raises(DOMException);
   nsIDOMDocumentFragment        createDocumentFragment();
@@ -106,17 +104,15 @@ interface nsIDOMDocument : nsIDOMNode
   // Introduced in DOM Level 3:
            attribute boolean         strictErrorChecking;
   // Introduced in DOM Level 3:
            attribute DOMString       documentURI;
   // Introduced in DOM Level 3:
   nsIDOMNode         adoptNode(in nsIDOMNode source)
                                         raises(DOMException);
   // Introduced in DOM Level 3:
-  readonly attribute nsIDOMDOMConfiguration domConfig;
-  // Introduced in DOM Level 3:
   void               normalizeDocument();
   // Introduced in DOM Level 3:
   nsIDOMNode         renameNode(in nsIDOMNode node, 
                                 in DOMString namespaceURI, 
                                 in DOMString qualifiedName)
                                         raises(DOMException);
 };
--- a/dom/interfaces/core/nsIDOMDocumentType.idl
+++ b/dom/interfaces/core/nsIDOMDocumentType.idl
@@ -44,18 +44,16 @@
  * or a DocumentType object. 
  * The nsIDOMDocumentType interface in the DOM Core provides an 
  * interface to the list of entities that are defined for the document.
  *
  * For more information on this interface please see 
  * http://www.w3.org/TR/DOM-Level-2-Core/
  */
 
-[scriptable, uuid(5725a7de-2883-45a5-878e-30773cd82478)]
+[scriptable, uuid(bfd028d4-fbbd-4d69-8899-dbee1778dde2)]
 interface nsIDOMDocumentType : nsIDOMNode
 {
   readonly attribute  DOMString            name;
-  readonly attribute  nsIDOMNamedNodeMap   entities;
-  readonly attribute  nsIDOMNamedNodeMap   notations;
   readonly attribute  DOMString            publicId;
   readonly attribute  DOMString            systemId;
   readonly attribute  DOMString            internalSubset;
 };
--- a/dom/interfaces/core/nsIDOMXMLDocument.idl
+++ b/dom/interfaces/core/nsIDOMXMLDocument.idl
@@ -33,17 +33,17 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsIDOMDocument.idl"
 
-[scriptable, uuid(9f07f216-b3a3-4a08-81f1-a48075b91d1c)]
+[scriptable, uuid(207ccc34-b14f-4d2f-8cbf-028e0ed73d6f)]
 interface nsIDOMXMLDocument : nsIDOMDocument
 {
   // DOM Level 3 Load & Save, DocumentLS
   // http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS
   /**
    * Whether to load synchronously or asynchronously.
    * The default is async==true.
    */
--- a/dom/interfaces/html/nsIDOMHTMLDocument.idl
+++ b/dom/interfaces/html/nsIDOMHTMLDocument.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(0d3bef04-a890-4dbc-8571-b8e96ff5426b)]
+[scriptable, uuid(8f9cc6bb-539d-4d2a-bef8-aabb942d1b36)]
 interface nsIDOMHTMLDocument : nsIDOMDocument
 {
            attribute DOMString            title;
   readonly attribute DOMString            referrer;
   // domain is readonly per spec, but it's settable in
   // nsIDOMNSHTMLDocument
   [noscript] readonly attribute DOMString domain;
   readonly attribute DOMString            URL;
--- a/dom/interfaces/svg/nsIDOMSVGDocument.idl
+++ b/dom/interfaces/svg/nsIDOMSVGDocument.idl
@@ -34,17 +34,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsIDOMDocument.idl"
 
 interface nsIDOMSVGSVGElement;
 
-[scriptable, uuid(fc52bd3f-850c-4d80-819f-5bd8321b4b59)]
+[scriptable, uuid(19004064-4ba6-4d0e-bcaf-fb42b0d3038b)]
 interface nsIDOMSVGDocument : nsIDOMDocument
                          /* , nsIDOMDocumentEvent */
 {
   readonly attribute DOMString title;
   readonly attribute DOMString referrer;
   readonly attribute DOMString domain;
   readonly attribute DOMString URL;
   readonly attribute nsIDOMSVGSVGElement rootElement;
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -351,16 +351,17 @@ TabChild::ProvideWindow(nsIDOMWindow* aP
 {
     *aReturn = nsnull;
 
     PBrowserChild* newChild;
     if (!CallCreateWindow(&newChild)) {
         return NS_ERROR_NOT_AVAILABLE;
     }
 
+    *aWindowIsNew = PR_TRUE;
     nsCOMPtr<nsIDOMWindow> win =
         do_GetInterface(static_cast<TabChild*>(newChild)->mWebNav);
     win.forget(aReturn);
     return NS_OK;
 }
 
 static nsInterfaceHashtable<nsVoidPtrHashKey, nsIDialogParamBlock> gActiveDialogs;
 
--- a/dom/src/threads/nsDOMWorker.h
+++ b/dom/src/threads/nsDOMWorker.h
@@ -74,33 +74,33 @@ class nsIScriptGlobalObject;
 class nsIXPConnectWrappedNative;
 
 class nsDOMWorkerScope : public nsDOMWorkerMessageHandler,
                          public nsIWorkerScope,
                          public nsIXPCScriptable
 {
   friend class nsDOMWorker;
 
-  typedef nsresult (NS_STDCALL nsDOMWorkerScope::*SetListenerFunc)
-    (nsIDOMEventListener*);
-
 public:
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_NSIDOMEVENTTARGET
   // nsIDOMNSEventTarget
   NS_IMETHOD AddEventListener(const nsAString& aType,
                               nsIDOMEventListener* aListener,
                               PRBool aUseCapture,
                               PRBool aWantsUntrusted,
                               PRUint8 optional_argc);
   NS_DECL_NSIWORKERGLOBALSCOPE
   NS_DECL_NSIWORKERSCOPE
   NS_DECL_NSIXPCSCRIPTABLE
   NS_DECL_NSICLASSINFO
 
+  typedef NS_STDCALL_FUNCPROTO(nsresult, SetListenerFunc, nsDOMWorkerScope,
+                               SetOnmessage, (nsIDOMEventListener*));
+
   nsDOMWorkerScope(nsDOMWorker* aWorker);
 
 protected:
   already_AddRefed<nsIXPConnectWrappedNative> GetWrappedNative();
 
 private:
   nsDOMWorker* mWorker;
   nsIXPConnectWrappedNative* mWrappedNative;
--- a/dom/src/threads/nsDOMWorkerXHRProxy.h
+++ b/dom/src/threads/nsDOMWorkerXHRProxy.h
@@ -40,16 +40,17 @@
 #define __NSDOMWORKERXHRPROXY_H__
 
 // Bases
 #include "nsThreadUtils.h"
 #include "nsIDOMEventListener.h"
 #include "nsIRequestObserver.h"
 
 // Other includes
+#include "nsIDOMEventTarget.h"
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsStringGlue.h"
 #include "nsTArray.h"
 
 class nsIJSXMLHttpRequest;
 class nsIThread;
 class nsIVariant;
@@ -69,18 +70,19 @@ class nsDOMWorkerXHRProxy : public nsIRu
 {
   friend class nsDOMWorkerXHRAttachUploadListenersRunnable;
   friend class nsDOMWorkerXHREvent;
   friend class nsDOMWorkerXHRFinishSyncXHRRunnable;
   friend class nsDOMWorkerXHRLastProgressOrLoadEvent;
   friend class nsDOMWorkerXHR;
   friend class nsDOMWorkerXHRUpload;
 
-  typedef nsresult (NS_STDCALL nsIDOMEventTarget::*EventListenerFunction)
-    (const nsAString&, nsIDOMEventListener*, PRBool);
+  typedef NS_STDCALL_FUNCPROTO(nsresult, EventListenerFunction, nsIDOMEventTarget,
+                               AddEventListener,
+                               (const nsAString&, nsIDOMEventListener*, PRBool));
 
 public:
   typedef nsAutoTArray<nsCOMPtr<nsIRunnable>, 5> SyncEventQueue;
 
   NS_DECL_ISUPPORTS
   NS_DECL_NSIDOMEVENTLISTENER
   NS_DECL_NSIRUNNABLE
   NS_DECL_NSIREQUESTOBSERVER
--- a/dom/tests/mochitest/bugs/Makefile.in
+++ b/dom/tests/mochitest/bugs/Makefile.in
@@ -132,12 +132,13 @@ include $(topsrcdir)/config/rules.mk
 		file_bug593174_1.html \
 		file_bug593174_2.html \
 		test_bug612267.html \
 		test_bug617296.html \
 		test_bug620947.html \
 		test_bug622361.html \
 		test_bug633133.html \
 		test_bug642026.html \
+		test_bug648465.html \
 		$(NULL)
 
 libs:: 	$(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/bugs/test_bug648465.html
@@ -0,0 +1,34 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=648465
+-->
+<head>
+  <title>Test for Bug 648465</title>
+  <script type="text/javascript" src="/MochiKit/packed.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<a target="_blank"
+  href="https://bugzilla.mozilla.org/show_bug.cgi?id=648465">
+  Mozilla Bug 648465</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+
+/** Test for Bug 648465 **/
+var w = window.open('about:blank');
+try {
+  is(w.fullScreen, false, "can access non-allAccess properties of w");
+} finally {
+  w.close();
+}
+
+</script>
+</pre>
+</body>
+</html>
--- a/editor/libeditor/base/nsEditor.cpp
+++ b/editor/libeditor/base/nsEditor.cpp
@@ -1139,28 +1139,26 @@ nsEditor::GetDocumentModified(PRBool *ou
 
   *outDocModified = (modCount != 0);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsEditor::GetDocumentCharacterSet(nsACString &characterSet)
 {
-  nsresult rv = NS_OK;
   nsCOMPtr<nsIDocument> doc = do_QueryReferent(mDocWeak);
   NS_ENSURE_TRUE(doc, NS_ERROR_UNEXPECTED);
 
   characterSet = doc->GetDocumentCharacterSet();
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsEditor::SetDocumentCharacterSet(const nsACString& characterSet)
 {
-  nsresult rv = NS_OK;
   nsCOMPtr<nsIDocument> doc = do_QueryReferent(mDocWeak);
   NS_ENSURE_TRUE(doc, NS_ERROR_UNEXPECTED);
 
   doc->SetDocumentCharacterSet(characterSet);
   return NS_OK;
 }
 
 NS_IMETHODIMP
--- a/editor/libeditor/html/tests/test_bug520189.html
+++ b/editor/libeditor/html/tests/test_bug520189.html
@@ -53,16 +53,20 @@ https://bugzilla.mozilla.org/show_bug.cg
   <iframe id="kk" src="about:blank"></iframe>
   <div id="ll" contenteditable="true"></div>
   <iframe id="mm" src="about:blank"></iframe>
   <div id="nn" contenteditable="true"></div>
   <iframe id="oo" src="about:blank"></iframe>
   <div id="pp" contenteditable="true"></div>
   <iframe id="qq" src="about:blank"></iframe>
   <div id="rr" contenteditable="true"></div>
+  <iframe id="ss" src="about:blank"></iframe>
+  <div id="tt" contenteditable="true"></div>
+  <iframe id="uu" src="about:blank"></iframe>
+  <div id="vv" contenteditable="true"></div>
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 520182 **/
 
 const dataPayload = "foo<iframe src=\"data:text/html,bar\"></iframe>baz";
 const jsPayload = "foo<iframe src=\"javascript:void('bar');\"></iframe>baz";
@@ -75,16 +79,18 @@ const validStyle3Payload = "foo<style>@f
 const validStyle4Payload = "foo<style>@namespace xxx url(http://example.com/);</style>baz";
 const invalidStyle1Payload = "foo<style>#bar{-moz-binding:url('data:text/xml,<?xml version=\"1.0\"><binding xmlns=\"http://www.mozilla.org/xbl\"/>');}</style>baz";
 const invalidStyle2Payload = "foo<span style=\"-moz-binding:url('data:text/xml,<?xml version=&quot;1.0&quot;><binding xmlns=&quot;http://www.mozilla.org/xbl&quot;/>');\">bar</span>baz";
 const invalidStyle3Payload = "foo<style>@import 'xxx.css';</style>baz";
 const invalidStyle4Payload = "foo<span style=\"@import 'xxx.css';\">bar</span>baz";
 const invalidStyle5Payload = "foo<span style=\"@font-face{font-family:xxx;src:'xxx.ttf';}\">bar</span>baz";
 const invalidStyle6Payload = "foo<span style=\"@namespace xxx url(http://example.com/);\">bar</span>baz";
 const invalidStyle7Payload = "<html><head><title>xxx</title></head><body>foo</body></html>";
+const invalidStyle8Payload = "foo<style>@-moz-document url(http://example.com/) {};</style>baz";
+const invalidStyle9Payload = "foo<style>@-moz-keyframes bar {};</style>baz";
 const nestedStylePayload = "foo<style>#bar1{-moz-binding:url('data:text/xml,<?xml version=&quot;1.0&quot;><binding xmlns=&quot;http://www.mozilla.org/xbl&quot; id=&quot;binding-1&quot;/>');<style></style>#bar2{-moz-binding:url('data:text/xml,<?xml version=&quot;1.0&quot;><binding xmlns=&quot;http://www.mozilla.org/xbl&quot; id=&quot;binding-2&quot;/>');</style>baz";
 const validImgSrc1Payload = "foo<img src=\"data:image/png,bar\">baz";
 const validImgSrc2Payload = "foo<img src=\"javascript:void('bar');\">baz";
 const validImgSrc3Payload = "foo<img src=\"file:///bar.png\">baz";
 const validDataFooPayload = "foo<span data-bar=\"value\">baz</span>";
 const validDataFoo2Payload = "foo<span _bar=\"value\">baz</span>";
 
 var tests = [
@@ -384,16 +390,42 @@ var tests = [
     rootElement: function() document.getElementById("qq").contentDocument.documentElement,
     checkResult: function(html) isnot(html.indexOf("bar"), -1, "Should have retained the _bar attribute")
   },
   {
     id: "rr",
     payload: validDataFoo2Payload,
     rootElement: function() document.getElementById("rr"),
     checkResult: function(html) isnot(html.indexOf("bar"), -1, "Should have retained the _bar attribute")
+  },
+  {
+    id: "ss",
+    isIFrame: true,
+    payload: invalidStyle8Payload,
+    rootElement: function() document.getElementById("ss").contentDocument.documentElement,
+    checkResult: function(html) is(html.indexOf("@-moz-document"), -1, "Should not have retained the @-moz-document rule")
+  },
+  {
+    id: "tt",
+    payload: invalidStyle8Payload,
+    rootElement: function() document.getElementById("tt"),
+    checkResult: function(html) is(html.indexOf("@-moz-document"), -1, "Should not have retained the @-moz-document rule")
+  },
+  {
+    id: "uu",
+    isIFrame: true,
+    payload: invalidStyle9Payload,
+    rootElement: function() document.getElementById("uu").contentDocument.documentElement,
+    checkResult: function(html) is(html.indexOf("@-moz-keyframes"), -1, "Should not have retained the @-moz-keyframes rule")
+  },
+  {
+    id: "vv",
+    payload: invalidStyle9Payload,
+    rootElement: function() document.getElementById("vv"),
+    checkResult: function(html) is(html.indexOf("@-moz-keyframes"), -1, "Should not have retained the @-moz-keyframes rule")
   }
 ];
 
 function doNextTest() {
   if (typeof testCounter == "undefined")
     testCounter = 0;
   else if (++testCounter == tests.length) {
     SimpleTest.finish();
--- a/embedding/browser/webBrowser/nsWebBrowser.cpp
+++ b/embedding/browser/webBrowser/nsWebBrowser.cpp
@@ -71,17 +71,16 @@
 #include "nsCWebBrowserPersist.h"
 #include "nsIServiceManager.h"
 #include "nsAutoPtr.h"
 #include "nsFocusManager.h"
 #include "Layers.h"
 #include "gfxContext.h"
 
 // for painting the background window
-#include "nsIRenderingContext.h"
 #include "nsIDeviceContext.h"
 #include "nsIRegion.h"
 #include "nsILookAndFeel.h"
 
 // Printing Includes
 #ifdef NS_PRINTING
 #include "nsIWebBrowserPrint.h"
 #include "nsIContentViewer.h"
--- a/extensions/cookie/nsCookiePromptService.cpp
+++ b/extensions/cookie/nsCookiePromptService.cpp
@@ -67,22 +67,20 @@ nsCookiePromptService::CookieDialog(nsID
                                     PRBool *aRememberDecision,
                                     PRInt32 *aAccept)
 {
   nsresult rv;
 
   nsCOMPtr<nsIDialogParamBlock> block = do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID,&rv);
   if (NS_FAILED(rv)) return rv;
 
-  // since we're setting PRInt32's here, we have to sanitize the PRBool's first.
-  // (myBool != PR_FALSE) is guaranteed to return either 1 or 0.
   block->SetInt(nsICookieAcceptDialog::ACCEPT_COOKIE, 1);
   block->SetString(nsICookieAcceptDialog::HOSTNAME, NS_ConvertUTF8toUTF16(aHostname).get());
   block->SetInt(nsICookieAcceptDialog::COOKIESFROMHOST, aCookiesFromHost);
-  block->SetInt(nsICookieAcceptDialog::CHANGINGCOOKIE, aChangingCookie != PR_FALSE);
+  block->SetInt(nsICookieAcceptDialog::CHANGINGCOOKIE, aChangingCookie ? 1 : 0);
   
   nsCOMPtr<nsIMutableArray> objects =
     do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
   if (NS_FAILED(rv)) return rv;
 
   rv = objects->AppendElement(aCookie, PR_FALSE);
   if (NS_FAILED(rv)) return rv;
 
--- a/extensions/pref/autoconfig/src/nsAutoConfig.cpp
+++ b/extensions/pref/autoconfig/src/nsAutoConfig.cpp
@@ -239,17 +239,16 @@ NS_IMETHODIMP nsAutoConfig::Observe(nsIS
     return rv;
 }
 
 nsresult nsAutoConfig::downloadAutoConfig()
 {
     nsresult rv;
     nsCAutoString emailAddr;
     nsXPIDLCString urlName;
-    PRBool appendMail = PR_FALSE, offline = PR_FALSE;
     static PRBool firstTime = PR_TRUE;
     
     if (mConfigURL.IsEmpty()) {
         PR_LOG(MCD, PR_LOG_DEBUG, ("global config url is empty - did you set autoadmin.global_config_url?\n"));
         NS_WARNING("AutoConfig called without global_config_url");
         return NS_OK;
     }
     
@@ -262,61 +261,55 @@ nsresult nsAutoConfig::downloadAutoConfi
         mConfigURL.Truncate(index);
 
     // Clean up the previous read, the new read is going to use the same buffer
     if (!mBuf.IsEmpty())
         mBuf.Truncate(0);
 
     // Get the preferences branch and save it to the member variable
     if (!mPrefBranch) {
-
         nsCOMPtr<nsIPrefService> prefs =
             do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
         if (NS_FAILED(rv)) 
             return rv;
     
         rv = prefs->GetBranch(nsnull,getter_AddRefs(mPrefBranch));
         if (NS_FAILED(rv))
             return rv;
     }
     
     // Check to see if the network is online/offline 
     nsCOMPtr<nsIIOService> ios = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
     if (NS_FAILED(rv)) 
         return rv;
     
+    PRBool offline;
     rv = ios->GetOffline(&offline);
     if (NS_FAILED(rv)) 
         return rv;
     
     if (offline) {
-        
-        PRBool offlineFailover = PR_FALSE;
+        PRBool offlineFailover;
         rv = mPrefBranch->GetBoolPref("autoadmin.offline_failover", 
                                       &offlineFailover);
-        
         // Read the failover.jsc if the network is offline and the pref says so
-        if (offlineFailover) {
+        if (NS_SUCCEEDED(rv) && offlineFailover)
             return readOfflineFile();
-        }
     }
 
-
     /* Append user's identity at the end of the URL if the pref says so.
        First we are checking for the user's email address but if it is not
        available in the case where the client is used without messenger, user's
        profile name will be used as an unique identifier
     */
-    
+    PRBool appendMail;
     rv = mPrefBranch->GetBoolPref("autoadmin.append_emailaddr", &appendMail);
-    
     if (NS_SUCCEEDED(rv) && appendMail) {
         rv = getEmailAddr(emailAddr);
         if (NS_SUCCEEDED(rv) && emailAddr.get()) {
-
             /* Adding the unique identifier at the end of autoconfig URL. 
                In this case the autoconfig URL is a script and 
                emailAddr as passed as an argument 
             */
             mConfigURL.Append("?");
             mConfigURL.Append(emailAddr); 
         }
     }
@@ -333,29 +326,27 @@ nsresult nsAutoConfig::downloadAutoConfi
     }
 
     PR_LOG(MCD, PR_LOG_DEBUG, ("running MCD url %s\n", mConfigURL.get()));
     // open a channel for the url
     rv = NS_NewChannel(getter_AddRefs(channel),url, nsnull, nsnull, nsnull, nsIRequest::INHIBIT_PERSISTENT_CACHING | nsIRequest::LOAD_BYPASS_CACHE);
     if (NS_FAILED(rv)) 
         return rv;
 
-    
     rv = channel->AsyncOpen(this, nsnull); 
     if (NS_FAILED(rv)) {
         readOfflineFile();
         return rv;
     }
     
     // Set a repeating timer if the pref is set.
     // This is to be done only once.
     // Also We are having the event queue processing only for the startup
     // It is not needed with the repeating timer.
     if (firstTime) {
-
         firstTime = PR_FALSE;
     
         // Getting the current thread. If we start an AsyncOpen, the thread
         // needs to wait before the reading of autoconfig is done
 
         nsCOMPtr<nsIThread> thread = do_GetCurrentThread();
         NS_ENSURE_STATE(thread);
     
@@ -365,78 +356,74 @@ nsresult nsAutoConfig::downloadAutoConfi
            onStopRequest or readOfflineFile methods
            There is a possibility of deadlock so we need to make sure
            that mLoaded will be set to true in any case (success/failure)
         */
         
         while (!mLoaded)
             NS_ENSURE_STATE(NS_ProcessNextEvent(thread));
         
-        PRInt32 minutes = 0;
+        PRInt32 minutes;
         rv = mPrefBranch->GetIntPref("autoadmin.refresh_interval", 
                                      &minutes);
         if (NS_SUCCEEDED(rv) && minutes > 0) {
-
             // Create a new timer and pass this nsAutoConfig 
             // object as a timer callback. 
             mTimer = do_CreateInstance("@mozilla.org/timer;1",&rv);
             if (NS_FAILED(rv)) 
                 return rv;
             rv = mTimer->InitWithCallback(this, minutes * 60 * 1000, 
                              nsITimer::TYPE_REPEATING_SLACK);
             if (NS_FAILED(rv)) 
                 return rv;
         }
-    
     } //first_time
     
     return NS_OK;
-
 } // nsPref::downloadAutoConfig()
 
 
 
 nsresult nsAutoConfig::readOfflineFile()
 {
-    PRBool failCache = PR_TRUE;
     nsresult rv;
-    PRBool offline;
     
     /* Releasing the lock to allow main thread to start 
        execution. At this point we do not need to stall 
        the thread since all network activities are done.
     */
     mLoaded = PR_TRUE; 
 
+    PRBool failCache;
     rv = mPrefBranch->GetBoolPref("autoadmin.failover_to_cached", &failCache);
-    
-    if (failCache == PR_FALSE) {
-        
+    if (NS_SUCCEEDED(rv) && !failCache) {
         // disable network connections and return.
         
         nsCOMPtr<nsIIOService> ios =
             do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
         if (NS_FAILED(rv)) 
             return rv;
         
+        PRBool offline;
         rv = ios->GetOffline(&offline);
         if (NS_FAILED(rv)) 
             return rv;
 
         if (!offline) {
             rv = ios->SetOffline(PR_TRUE);
             if (NS_FAILED(rv)) 
                 return rv;
         }
         
         // lock the "network.online" prference so user cannot toggle back to
         // online mode.
         rv = mPrefBranch->SetBoolPref("network.online", PR_FALSE);
         if (NS_FAILED(rv)) 
             return rv;
+
         mPrefBranch->LockPref("network.online");
         return NS_OK;
     }
     
     /* faiover_to_cached is set to true so 
        Open the file and read the content.
        execute the javascript file
     */
@@ -513,17 +500,16 @@ nsresult nsAutoConfig::getEmailAddr(nsAC
        First getting a default account with 
        "mail.accountmanager.defaultaccount"
        second getting an associated id with the default account
        Third getting an email address with id
     */
     
     rv = mPrefBranch->GetCharPref("mail.accountmanager.defaultaccount", 
                                   getter_Copies(prefValue));
-    
     if (NS_SUCCEEDED(rv) && !prefValue.IsEmpty()) {
         emailAddr = NS_LITERAL_CSTRING("mail.account.") +
             prefValue + NS_LITERAL_CSTRING(".identities");
         rv = mPrefBranch->GetCharPref(PromiseFlatCString(emailAddr).get(),
                                       getter_Copies(prefValue));
         if (NS_FAILED(rv) || prefValue.IsEmpty())
             return PromptForEMailAddress(emailAddr);
         PRInt32 commandIndex = prefValue.FindChar(',');
@@ -575,9 +561,8 @@ nsresult nsAutoConfig::PromptForEMailAdd
     PRBool success;
     rv = promptService->Prompt(nsnull, title.get(), err.get(), getter_Copies(emailResult), nsnull, &check, &success);
     if (!success)
       return NS_ERROR_FAILURE;
     NS_ENSURE_SUCCESS(rv, rv);
     LossyCopyUTF16toASCII(emailResult, emailAddress);
     return NS_OK;
 }
-
--- a/extensions/pref/system-pref/src/nsSystemPref.cpp
+++ b/extensions/pref/system-pref/src/nsSystemPref.cpp
@@ -205,17 +205,17 @@ nsSystemPref::Observe(nsISupports *aSubj
                 rv = UseMozillaPrefs();
         }
     }
 
     // if the system pref notify us that some pref has been changed by user
     // outside mozilla. We need to read it again.
     else if (!nsCRT::strcmp(aTopic, NS_SYSTEMPREF_PREFCHANGE_TOPIC_ID) &&
              aData) {
-        NS_ASSERTION(mEnabled == PR_TRUE, "Should not listen when disabled");
+        NS_ASSERTION(mEnabled, "Should not listen when disabled");
         SYSPREF_LOG(("====== System Pref Notify topic=%s data=%s\n",
                      aTopic, (char*)aData));
         rv = ReadSystemPref(NS_LossyConvertUTF16toASCII(aData).get());
         return NS_OK;
     } else if (!nsCRT::strcmp(aTopic,"profile-before-change")) {
       //roll back to mozilla prefs
       if (mEnabled)
         UseMozillaPrefs();
--- a/gfx/layers/basic/BasicLayers.cpp
+++ b/gfx/layers/basic/BasicLayers.cpp
@@ -43,17 +43,16 @@
 #include "mozilla/layers/PLayersParent.h"
 #include "ipc/ShadowLayerChild.h"
 
 #include "BasicLayers.h"
 #include "ImageLayers.h"
 
 #include "nsTArray.h"
 #include "nsGUIEvent.h"
-#include "nsIRenderingContext.h"
 #include "gfxContext.h"
 #include "gfxImageSurface.h"
 #include "gfxPattern.h"
 #include "gfxPlatform.h"
 #include "gfxUtils.h"
 #include "ThebesLayerBuffer.h"
 #include "nsIWidget.h"
 #include "ReadbackProcessor.h"
--- a/gfx/src/Makefile.in
+++ b/gfx/src/Makefile.in
@@ -67,25 +67,25 @@ EXPORTS	= \
 	nsCoord.h \
 	nsFont.h \
 	nsRect.h \
 	nsRegion.h \
 	nsPoint.h \
 	nsSize.h \
 	nsMargin.h \
 	nsTransform2D.h \
-	nsIRenderingContext.h \
-	nsIFontMetrics.h \
+	nsRenderingContext.h \
+	nsFontMetrics.h \
 	nsIDeviceContext.h \
 	nsGfxCIID.h \
 	nsIRegion.h \
 	nsITheme.h \
 	nsThemeConstants.h \
 	gfxCrashReporterUtils.h \
-	nsIThebesFontMetrics.h \
+	nsBoundingMetrics.h \
 	$(NULL)
 
 ifdef MOZ_X11
 EXPORTS_NAMESPACES	= mozilla
 EXPORTS_mozilla		= X11Util.h
 endif
 
 CPPSRCS = \
@@ -94,18 +94,18 @@ CPPSRCS = \
         nsRect.cpp \
         nsRegion.cpp \
         nsTransform2D.cpp \
         nsScriptableRegion.cpp \
         gfxCrashReporterUtils.cpp \
         nsThebesDeviceContext.cpp \
         nsThebesRegion.cpp \
         nsThebesGfxFactory.cpp \
-        nsThebesRenderingContext.cpp \
-        nsThebesFontMetrics.cpp \
+        nsRenderingContext.cpp \
+        nsFontMetrics.cpp \
         nsThebesFontEnumerator.cpp \
        $(NULL)
 
 ifdef MOZ_X11
 CPPSRCS += X11Util.cpp
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),android)
new file mode 100644
--- /dev/null
+++ b/gfx/src/nsBoundingMetrics.h
@@ -0,0 +1,120 @@
+/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ * Christopher Blizzard <blizzard@mozilla.org>.
+ * Portions created by the Initial Developer are Copyright (C) 2002
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef __nsBoundingMetrics_h
+#define __nsBoundingMetrics_h
+
+#include "nsCoord.h"
+
+/* Struct used for accurate measurements of a string, in order to
+ * allow precise positioning when processing MathML.  This is in its
+ * own header file because some very-widely-included headers need it
+ * but not the rest of nsFontMetrics, or vice versa.
+ */
+
+#ifdef MOZ_MATHML
+struct nsBoundingMetrics {
+
+    ///////////
+    // Metrics that _exactly_ enclose the text:
+
+    // The character coordinate system is the one used on X Windows:
+    // 1. The origin is located at the intersection of the baseline
+    //    with the left of the character's cell.
+    // 2. All horizontal bearings are oriented from left to right.
+    // 2. All horizontal bearings are oriented from left to right.
+    // 3. The ascent is oriented from bottom to top (being 0 at the orgin).
+    // 4. The descent is oriented from top to bottom (being 0 at the origin).
+
+    // Note that Win32/Mac/PostScript use a different convention for
+    // the descent (all vertical measurements are oriented from bottom
+    // to top on these palatforms). Make sure to flip the sign of the
+    // descent on these platforms for cross-platform compatibility.
+
+    // Any of the following member variables listed here can have
+    // positive or negative value.
+
+    nscoord leftBearing;
+    /* The horizontal distance from the origin of the drawing
+       operation to the left-most part of the drawn string. */
+
+    nscoord rightBearing;
+    /* The horizontal distance from the origin of the drawing
+       operation to the right-most part of the drawn string.
+       The _exact_ width of the string is therefore:
+       rightBearing - leftBearing */
+
+    nscoord ascent;
+    /* The vertical distance from the origin of the drawing
+       operation to the top-most part of the drawn string. */
+
+    nscoord descent;
+    /* The vertical distance from the origin of the drawing
+       operation to the bottom-most part of the drawn string.
+       The _exact_ height of the string is therefore:
+       ascent + descent */
+
+    nscoord width;
+    /* The horizontal distance from the origin of the drawing
+       operation to the correct origin for drawing another string
+       to follow the current one. Depending on the font, this
+       could be greater than or less than the right bearing. */
+
+    nsBoundingMetrics() : leftBearing(0), rightBearing(0),
+                          ascent(0), descent(0), width(0)
+    {}
+
+    void
+    operator += (const nsBoundingMetrics& bm) {
+        if (ascent + descent == 0 && rightBearing - leftBearing == 0) {
+            ascent = bm.ascent;
+            descent = bm.descent;
+            leftBearing = width + bm.leftBearing;
+            rightBearing = width + bm.rightBearing;
+        }
+        else {
+            if (ascent < bm.ascent) ascent = bm.ascent;
+            if (descent < bm.descent) descent = bm.descent;
+            leftBearing = PR_MIN(leftBearing, width + bm.leftBearing);
+            rightBearing = PR_MAX(rightBearing, width + bm.rightBearing);
+        }
+        width += bm.width;
+    }
+};
+#endif // MOZ_MATHML
+
+#endif // __nsBoundingMetrics_h
rename from gfx/src/nsThebesFontMetrics.cpp
rename to gfx/src/nsFontMetrics.cpp
--- a/gfx/src/nsThebesFontMetrics.cpp
+++ b/gfx/src/nsFontMetrics.cpp
@@ -31,130 +31,162 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
-#include "nsThebesFontMetrics.h"    
-#include "nsFont.h"
-
-#include "nsString.h"
-#include <stdio.h>
-
+#include "nsFontMetrics.h"
+#include "nsBoundingMetrics.h"
+#include "nsRenderingContext.h"
+#include "nsThebesDeviceContext.h"
 #include "gfxTextRunCache.h"
-#include "gfxPlatform.h"
-#include "gfxUserFontSet.h"
+
+namespace {
 
-NS_IMPL_ISUPPORTS1(nsThebesFontMetrics, nsIFontMetrics)
+class AutoTextRun : public gfxTextRunCache::AutoTextRun {
+public:
+    AutoTextRun(nsFontMetrics* aMetrics, nsRenderingContext* aRC,
+                const char* aString, PRInt32 aLength)
+        : gfxTextRunCache::AutoTextRun(gfxTextRunCache::MakeTextRun(
+            reinterpret_cast<const PRUint8*>(aString), aLength,
+            aMetrics->GetThebesFontGroup(), aRC->ThebesContext(),
+            aMetrics->AppUnitsPerDevPixel(),
+            ComputeFlags(aMetrics)))
+    {}
+
+    AutoTextRun(nsFontMetrics* aMetrics, nsRenderingContext* aRC,
+                const PRUnichar* aString, PRInt32 aLength)
+        : gfxTextRunCache::AutoTextRun(gfxTextRunCache::MakeTextRun(
+            aString, aLength, aMetrics->GetThebesFontGroup(),
+            aRC->ThebesContext(),
+            aMetrics->AppUnitsPerDevPixel(),
+            ComputeFlags(aMetrics)))
+    {}
 
-#include <stdlib.h>
+private:
+    static PRUint32 ComputeFlags(nsFontMetrics* aMetrics) {
+        PRUint32 flags = 0;
+        if (aMetrics->GetTextRunRTL()) {
+            flags |= gfxTextRunFactory::TEXT_IS_RTL;
+        }
+        return flags;
+    }
+};
 
-nsThebesFontMetrics::nsThebesFontMetrics()
+class StubPropertyProvider : public gfxTextRun::PropertyProvider {
+public:
+    virtual void GetHyphenationBreaks(PRUint32 aStart, PRUint32 aLength,
+                                      PRPackedBool* aBreakBefore) {
+        NS_ERROR("This shouldn't be called because we never call BreakAndMeasureText");
+    }
+    virtual gfxFloat GetHyphenWidth() {
+        NS_ERROR("This shouldn't be called because we never enable hyphens");
+        return 0;
+    }
+    virtual void GetSpacing(PRUint32 aStart, PRUint32 aLength,
+                            Spacing* aSpacing) {
+        NS_ERROR("This shouldn't be called because we never enable spacing");
+    }
+};
+
+} // anon namespace
+
+nsFontMetrics::nsFontMetrics()
+    : mDeviceContext(nsnull), mP2A(-1), mTextRunRTL(PR_FALSE)
 {
-    mFontStyle = nsnull;
-    mFontGroup = nsnull;
 }
 
-nsThebesFontMetrics::~nsThebesFontMetrics()
+nsFontMetrics::~nsFontMetrics()
 {
     if (mDeviceContext)
         mDeviceContext->FontMetricsDeleted(this);
-    delete mFontStyle;
-    //delete mFontGroup;
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::Init(const nsFont& aFont, nsIAtom* aLanguage,
-                          nsIDeviceContext *aContext, 
-                          gfxUserFontSet *aUserFontSet)
+nsresult
+nsFontMetrics::Init(const nsFont& aFont, nsIAtom* aLanguage,
+                    nsIDeviceContext *aContext,
+                    gfxUserFontSet *aUserFontSet)
 {
+    NS_ABORT_IF_FALSE(mP2A == -1, "already initialized");
+
     mFont = aFont;
     mLanguage = aLanguage;
     mDeviceContext = (nsThebesDeviceContext*)aContext;
     mP2A = mDeviceContext->AppUnitsPerDevPixel();
-    mIsRightToLeft = PR_FALSE;
-    mTextRunRTL = PR_FALSE;
-
-    gfxFloat size = gfxFloat(aFont.size) / mP2A;
 
-    PRBool printerFont = mDeviceContext->IsPrinterSurface();
-    mFontStyle = new gfxFontStyle(aFont.style, aFont.weight, aFont.stretch,
-                                  size, aLanguage,
-                                  aFont.sizeAdjust, aFont.systemFont,
-                                  printerFont,
-                                  aFont.featureSettings,
-                                  aFont.languageOverride);
+    gfxFontStyle style(aFont.style,
+                       aFont.weight,
+                       aFont.stretch,
+                       gfxFloat(aFont.size) / mP2A,
+                       aLanguage,
+                       aFont.sizeAdjust,
+                       aFont.systemFont,
+                       mDeviceContext->IsPrinterSurface(),
+                       aFont.featureSettings,
+                       aFont.languageOverride);
 
-    mFontGroup =
-        gfxPlatform::GetPlatform()->CreateFontGroup(aFont.name, mFontStyle, 
-                                                    aUserFontSet);
-    if (mFontGroup->FontListLength() < 1) 
+    mFontGroup = gfxPlatform::GetPlatform()->
+        CreateFontGroup(aFont.name, &style, aUserFontSet);
+    if (mFontGroup->FontListLength() < 1)
         return NS_ERROR_UNEXPECTED;
 
     return NS_OK;
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::Destroy()
+void
+nsFontMetrics::Destroy()
 {
     mDeviceContext = nsnull;
-    return NS_OK;
 }
 
 // XXXTODO get rid of this macro
 #define ROUND_TO_TWIPS(x) (nscoord)floor(((x) * mP2A) + 0.5)
 #define CEIL_TO_TWIPS(x) (nscoord)NS_ceil((x) * mP2A)
 
-const gfxFont::Metrics& nsThebesFontMetrics::GetMetrics() const
+const gfxFont::Metrics& nsFontMetrics::GetMetrics() const
 {
     return mFontGroup->GetFontAt(0)->GetMetrics();
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetXHeight(nscoord& aResult)
+nscoord
+nsFontMetrics::XHeight()
 {
-    aResult = ROUND_TO_TWIPS(GetMetrics().xHeight);
-    return NS_OK;
+    return ROUND_TO_TWIPS(GetMetrics().xHeight);
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetSuperscriptOffset(nscoord& aResult)
+nscoord
+nsFontMetrics::SuperscriptOffset()
 {
-    aResult = ROUND_TO_TWIPS(GetMetrics().superscriptOffset);
-    return NS_OK;
+    return ROUND_TO_TWIPS(GetMetrics().superscriptOffset);
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetSubscriptOffset(nscoord& aResult)
+nscoord
+nsFontMetrics::SubscriptOffset()
 {
-    aResult = ROUND_TO_TWIPS(GetMetrics().subscriptOffset);
-    return NS_OK;
+    return ROUND_TO_TWIPS(GetMetrics().subscriptOffset);
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetStrikeout(nscoord& aOffset, nscoord& aSize)
+void
+nsFontMetrics::GetStrikeout(nscoord& aOffset, nscoord& aSize)
 {
     aOffset = ROUND_TO_TWIPS(GetMetrics().strikeoutOffset);
     aSize = ROUND_TO_TWIPS(GetMetrics().strikeoutSize);
-    return NS_OK;
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetUnderline(nscoord& aOffset, nscoord& aSize)
+void
+nsFontMetrics::GetUnderline(nscoord& aOffset, nscoord& aSize)
 {
     aOffset = ROUND_TO_TWIPS(mFontGroup->GetUnderlineOffset());
     aSize = ROUND_TO_TWIPS(GetMetrics().underlineSize);
-
-    return NS_OK;
 }
 
-// GetHeight/GetMaxAscent/GetMaxDescent/GetMaxHeight must contain the
+// GetMaxAscent/GetMaxDescent/GetMaxHeight must contain the
 // text-decoration lines drawable area. See bug 421353.
 // BE CAREFUL for rounding each values. The logic MUST be same as
 // nsCSSRendering::GetTextDecorationRectInternal's.
 
 static gfxFloat ComputeMaxDescent(const gfxFont::Metrics& aMetrics,
                                   gfxFontGroup* aFontGroup)
 {
     gfxFloat offset = NS_floor(-aFontGroup->GetUnderlineOffset() + 0.5);
@@ -163,343 +195,175 @@ static gfxFloat ComputeMaxDescent(const 
     return PR_MAX(minDescent, aMetrics.maxDescent);
 }
 
 static gfxFloat ComputeMaxAscent(const gfxFont::Metrics& aMetrics)
 {
     return NS_floor(aMetrics.maxAscent + 0.5);
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetHeight(nscoord &aHeight)
+nscoord
+nsFontMetrics::InternalLeading()
 {
-    aHeight = CEIL_TO_TWIPS(ComputeMaxAscent(GetMetrics())) +
-        CEIL_TO_TWIPS(ComputeMaxDescent(GetMetrics(), mFontGroup));
-    return NS_OK;
+    return ROUND_TO_TWIPS(GetMetrics().internalLeading);
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetInternalLeading(nscoord &aLeading)
+nscoord
+nsFontMetrics::ExternalLeading()
 {
-    aLeading = ROUND_TO_TWIPS(GetMetrics().internalLeading);
-    return NS_OK;
+    return ROUND_TO_TWIPS(GetMetrics().externalLeading);
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetExternalLeading(nscoord &aLeading)
+nscoord
+nsFontMetrics::EmHeight()
 {
-    aLeading = ROUND_TO_TWIPS(GetMetrics().externalLeading);
-    return NS_OK;
+    return ROUND_TO_TWIPS(GetMetrics().emHeight);
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetEmHeight(nscoord &aHeight)
+nscoord
+nsFontMetrics::EmAscent()
 {
-    aHeight = ROUND_TO_TWIPS(GetMetrics().emHeight);
-    return NS_OK;
+    return ROUND_TO_TWIPS(GetMetrics().emAscent);
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetEmAscent(nscoord &aAscent)
+nscoord
+nsFontMetrics::EmDescent()
 {
-    aAscent = ROUND_TO_TWIPS(GetMetrics().emAscent);
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsThebesFontMetrics::GetEmDescent(nscoord &aDescent)
-{
-    aDescent = ROUND_TO_TWIPS(GetMetrics().emDescent);
-    return NS_OK;
+    return ROUND_TO_TWIPS(GetMetrics().emDescent);
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetMaxHeight(nscoord &aHeight)
+nscoord
+nsFontMetrics::MaxHeight()
 {
-    aHeight = CEIL_TO_TWIPS(ComputeMaxAscent(GetMetrics())) +
+    return CEIL_TO_TWIPS(ComputeMaxAscent(GetMetrics())) +
         CEIL_TO_TWIPS(ComputeMaxDescent(GetMetrics(), mFontGroup));
-    return NS_OK;
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetMaxAscent(nscoord &aAscent)
+nscoord
+nsFontMetrics::MaxAscent()
 {
-    aAscent = CEIL_TO_TWIPS(ComputeMaxAscent(GetMetrics()));
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsThebesFontMetrics::GetMaxDescent(nscoord &aDescent)
-{
-    aDescent = CEIL_TO_TWIPS(ComputeMaxDescent(GetMetrics(), mFontGroup));
-    return NS_OK;
+    return CEIL_TO_TWIPS(ComputeMaxAscent(GetMetrics()));
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetMaxAdvance(nscoord &aAdvance)
+nscoord
+nsFontMetrics::MaxDescent()
 {
-    aAdvance = CEIL_TO_TWIPS(GetMetrics().maxAdvance);
-    return NS_OK;
+    return CEIL_TO_TWIPS(ComputeMaxDescent(GetMetrics(), mFontGroup));
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetLanguage(nsIAtom** aLanguage)
+nscoord
+nsFontMetrics::MaxAdvance()
 {
-    *aLanguage = mLanguage;
-    NS_IF_ADDREF(*aLanguage);
-    return NS_OK;
+    return CEIL_TO_TWIPS(GetMetrics().maxAdvance);
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetFontHandle(nsFontHandle &aHandle)
-{
-    return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-NS_IMETHODIMP
-nsThebesFontMetrics::GetAveCharWidth(nscoord& aAveCharWidth)
+nscoord
+nsFontMetrics::AveCharWidth()
 {
     // Use CEIL instead of ROUND for consistency with GetMaxAdvance
-    aAveCharWidth = CEIL_TO_TWIPS(GetMetrics().aveCharWidth);
-    return NS_OK;
+    return CEIL_TO_TWIPS(GetMetrics().aveCharWidth);
 }
 
-NS_IMETHODIMP
-nsThebesFontMetrics::GetSpaceWidth(nscoord& aSpaceCharWidth)
+nscoord
+nsFontMetrics::SpaceWidth()
 {
-    aSpaceCharWidth = CEIL_TO_TWIPS(GetMetrics().spaceWidth);
-    return NS_OK;
+    return CEIL_TO_TWIPS(GetMetrics().spaceWidth);
 }
 
 PRInt32
-nsThebesFontMetrics::GetMaxStringLength()
+nsFontMetrics::GetMaxStringLength()
 {
     const gfxFont::Metrics& m = GetMetrics();
     const double x = 32767.0 / m.maxAdvance;
     PRInt32 len = (PRInt32)floor(x);
     return PR_MAX(1, len);
 }
 
-class StubPropertyProvider : public gfxTextRun::PropertyProvider {
-public:
-    virtual void GetHyphenationBreaks(PRUint32 aStart, PRUint32 aLength,
-                                      PRPackedBool* aBreakBefore) {
-        NS_ERROR("This shouldn't be called because we never call BreakAndMeasureText");
-    }
-    virtual gfxFloat GetHyphenWidth() {
-        NS_ERROR("This shouldn't be called because we never enable hyphens");
+nscoord
+nsFontMetrics::GetWidth(const char* aString, PRUint32 aLength,
+                        nsRenderingContext *aContext)
+{
+    if (aLength == 0)
         return 0;
-    }
-    virtual void GetSpacing(PRUint32 aStart, PRUint32 aLength,
-                            Spacing* aSpacing) {
-        NS_ERROR("This shouldn't be called because we never enable spacing");
-    }
-};
-
-nsresult 
-nsThebesFontMetrics::GetWidth(const char* aString, PRUint32 aLength, nscoord& aWidth,
-                              nsThebesRenderingContext *aContext)
-{
-    if (aLength == 0) {
-        aWidth = 0;
-        return NS_OK;
-    }
 
-    // callers that hit this should not be so stupid
-    if ((aLength == 1) && (aString[0] == ' '))
-        return GetSpaceWidth(aWidth);
-
-    StubPropertyProvider provider;
-    AutoTextRun textRun(this, aContext, aString, aLength);
-    if (!textRun.get())
-        return NS_ERROR_FAILURE;
-
-    aWidth = NSToCoordRound(textRun->GetAdvanceWidth(0, aLength, &provider));
-
-    return NS_OK;
-}
-
-nsresult
-nsThebesFontMetrics::GetWidth(const PRUnichar* aString, PRUint32 aLength,
-                              nscoord& aWidth, PRInt32 *aFontID,
-                              nsThebesRenderingContext *aContext)
-{
-    if (aLength == 0) {
-        aWidth = 0;
-        return NS_OK;
-    }
-
-    // callers that hit this should not be so stupid
-    if ((aLength == 1) && (aString[0] == ' '))
-        return GetSpaceWidth(aWidth);
+    if (aLength == 1 && aString[0] == ' ')
+        return SpaceWidth();
 
     StubPropertyProvider provider;
     AutoTextRun textRun(this, aContext, aString, aLength);
-    if (!textRun.get())
-        return NS_ERROR_FAILURE;
-
-    aWidth = NSToCoordRound(textRun->GetAdvanceWidth(0, aLength, &provider));
-
-    return NS_OK;
-}
-
-// Get the text dimensions for this string
-nsresult
-nsThebesFontMetrics::GetTextDimensions(const PRUnichar* aString,
-                                    PRUint32 aLength,
-                                    nsTextDimensions& aDimensions, 
-                                    PRInt32* aFontID)
-{
-    return NS_OK;
+    return NSToCoordRound(textRun->GetAdvanceWidth(0, aLength, &provider));
 }
 
-nsresult
-nsThebesFontMetrics::GetTextDimensions(const char*         aString,
-                                   PRInt32             aLength,
-                                   PRInt32             aAvailWidth,
-                                   PRInt32*            aBreaks,
-                                   PRInt32             aNumBreaks,
-                                   nsTextDimensions&   aDimensions,
-                                   PRInt32&            aNumCharsFit,
-                                   nsTextDimensions&   aLastWordDimensions,
-                                   PRInt32*            aFontID)
+nscoord
+nsFontMetrics::GetWidth(const PRUnichar* aString, PRUint32 aLength,
+                        nsRenderingContext *aContext)
 {
-    return NS_OK;
-}
-nsresult
-nsThebesFontMetrics::GetTextDimensions(const PRUnichar*    aString,
-                                   PRInt32             aLength,
-                                   PRInt32             aAvailWidth,
-                                   PRInt32*            aBreaks,
-                                   PRInt32             aNumBreaks,
-                                   nsTextDimensions&   aDimensions,
-                                   PRInt32&            aNumCharsFit,
-                                   nsTextDimensions&   aLastWordDimensions,
-                                   PRInt32*            aFontID)
-{
-    return NS_OK;
+    if (aLength == 0)
+        return 0;
+
+    if (aLength == 1 && aString[0] == ' ')
+        return SpaceWidth();
+
+    StubPropertyProvider provider;
+    AutoTextRun textRun(this, aContext, aString, aLength);
+    return NSToCoordRound(textRun->GetAdvanceWidth(0, aLength, &provider));
 }
 
-// Draw a string using this font handle on the surface passed in.  
-nsresult
-nsThebesFontMetrics::DrawString(const char *aString, PRUint32 aLength,
-                                nscoord aX, nscoord aY,
-                                const nscoord* aSpacing,
-                                nsThebesRenderingContext *aContext)
+// Draw a string using this font handle on the surface passed in.
+void
+nsFontMetrics::DrawString(const char *aString, PRUint32 aLength,
+                          nscoord aX, nscoord aY,
+                          nsRenderingContext *aContext)
 {
     if (aLength == 0)
-        return NS_OK;
+        return;
 
-    NS_ASSERTION(!aSpacing, "Spacing not supported here");
     StubPropertyProvider provider;
     AutoTextRun textRun(this, aContext, aString, aLength);
-    if (!textRun.get())
-        return NS_ERROR_FAILURE;
     gfxPoint pt(aX, aY);
     if (mTextRunRTL) {
         pt.x += textRun->GetAdvanceWidth(0, aLength, &provider);
     }
-    textRun->Draw(aContext->ThebesContext(), pt, 0, aLength,
-                  &provider, nsnull);
-    return NS_OK;
+    textRun->Draw(aContext->ThebesContext(), pt, 0, aLength, &provider, nsnull);
 }
 
-nsresult
-nsThebesFontMetrics::DrawString(const PRUnichar* aString, PRUint32 aLength,
-                                nscoord aX, nscoord aY,
-                                nsIRenderingContext *aContext,
-                                nsIRenderingContext *aTextRunConstructionContext)
+void
+nsFontMetrics::DrawString(const PRUnichar* aString, PRUint32 aLength,
+                          nscoord aX, nscoord aY,
+                          nsRenderingContext *aContext,
+                          nsRenderingContext *aTextRunConstructionContext)
 {
     if (aLength == 0)
-        return NS_OK;
+        return;
 
     StubPropertyProvider provider;
     AutoTextRun textRun(this, aTextRunConstructionContext, aString, aLength);
-    if (!textRun.get())
-        return NS_ERROR_FAILURE;
     gfxPoint pt(aX, aY);
     if (mTextRunRTL) {
         pt.x += textRun->GetAdvanceWidth(0, aLength, &provider);
     }
-    textRun->Draw(aContext->ThebesContext(), pt, 0, aLength,
-                  &provider, nsnull);
-    return NS_OK;
+    textRun->Draw(aContext->ThebesContext(), pt, 0, aLength, &provider, nsnull);
 }
 
 #ifdef MOZ_MATHML
-
-static void
-GetTextRunBoundingMetrics(gfxTextRun *aTextRun, PRUint32 aStart, PRUint32 aLength,
-                          nsThebesRenderingContext *aContext,
-                          nsBoundingMetrics &aBoundingMetrics)
+nsBoundingMetrics
+nsFontMetrics::GetBoundingMetrics(const PRUnichar *aString, PRUint32 aLength,
+                                  nsRenderingContext *aContext)
 {
-    StubPropertyProvider provider;
-    gfxTextRun::Metrics theMetrics =
-        aTextRun->MeasureText(aStart, aLength, gfxFont::TIGHT_HINTED_OUTLINE_EXTENTS,
-                              aContext->ThebesContext(), &provider);
-        // note that TIGHT_HINTED_OUTLINE_EXTENTS can be expensive (on Windows)
-        // but this is only used for MathML positioning so it's not critical
-
-    aBoundingMetrics.leftBearing = NSToCoordFloor(theMetrics.mBoundingBox.X());
-    aBoundingMetrics.rightBearing = NSToCoordCeil(theMetrics.mBoundingBox.XMost());
-    aBoundingMetrics.width = NSToCoordRound(theMetrics.mAdvanceWidth);
-    aBoundingMetrics.ascent = NSToCoordCeil(- theMetrics.mBoundingBox.Y());
-    aBoundingMetrics.descent = NSToCoordCeil(theMetrics.mBoundingBox.YMost());
-}
-
-nsresult
-nsThebesFontMetrics::GetBoundingMetrics(const char *aString, PRUint32 aLength,
-                                        nsThebesRenderingContext *aContext,
-                                        nsBoundingMetrics &aBoundingMetrics)
-{
-    if (aLength == 0) {
-        aBoundingMetrics.Clear();
-        return NS_OK;
-    }
-
-    AutoTextRun textRun(this, aContext, aString, aLength);
-    if (!textRun.get())
-        return NS_ERROR_FAILURE;
-
-    GetTextRunBoundingMetrics(textRun.get(), 0, aLength, aContext, aBoundingMetrics);
-    return NS_OK;
-}
+    if (aLength == 0)
+        return nsBoundingMetrics();
 
-nsresult
-nsThebesFontMetrics::GetBoundingMetrics(const PRUnichar *aString, PRUint32 aLength,
-                                        nsThebesRenderingContext *aContext,
-                                        nsBoundingMetrics &aBoundingMetrics)
-{
-    if (aLength == 0) {
-        aBoundingMetrics.Clear();
-        return NS_OK;
-    }
-
+    StubPropertyProvider provider;
     AutoTextRun textRun(this, aContext, aString, aLength);
-    if (!textRun.get())
-        return NS_ERROR_FAILURE;
-
-    GetTextRunBoundingMetrics(textRun.get(), 0, aLength, aContext, aBoundingMetrics);
-    return NS_OK;
-}
-
-#endif /* MOZ_MATHML */
+    gfxTextRun::Metrics theMetrics =
+        textRun->MeasureText(0, aLength,
+                             gfxFont::TIGHT_HINTED_OUTLINE_EXTENTS,
+                             aContext->ThebesContext(), &provider);
 
-// Set the direction of the text rendering
-nsresult
-nsThebesFontMetrics::SetRightToLeftText(PRBool aIsRTL)
-{
-    mIsRightToLeft = aIsRTL;
-    return NS_OK;
+    nsBoundingMetrics m;
+    m.leftBearing  = NSToCoordFloor( theMetrics.mBoundingBox.X());
+    m.rightBearing = NSToCoordCeil(  theMetrics.mBoundingBox.XMost());
+    m.ascent       = NSToCoordCeil( -theMetrics.mBoundingBox.Y());
+    m.descent      = NSToCoordCeil(  theMetrics.mBoundingBox.YMost());
+    m.width        = NSToCoordRound( theMetrics.mAdvanceWidth);
+    return m;
 }
-
-// Set the direction of the text rendering
-PRBool
-nsThebesFontMetrics::GetRightToLeftText()
-{
-    return mIsRightToLeft;
-}
-
-/* virtual */ gfxUserFontSet*
-nsThebesFontMetrics::GetUserFontSet()
-{
-    return mFontGroup->GetUserFontSet();
-}
+#endif /* MOZ_MATHML */
rename from gfx/src/nsThebesFontMetrics.h
rename to gfx/src/nsFontMetrics.h
--- a/gfx/src/nsThebesFontMetrics.h
+++ b/gfx/src/nsFontMetrics.h
@@ -31,178 +31,216 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
-#ifndef NSTHEBESFONTMETRICS__H__
-#define NSTHEBESFONTMETRICS__H__
+#ifndef NSFONTMETRICS__H__
+#define NSFONTMETRICS__H__
 
-#include "nsIThebesFontMetrics.h"
-#include "nsThebesRenderingContext.h"
 #include "nsCOMPtr.h"
-#include "nsThebesDeviceContext.h"
-#include "nsIAtom.h"
-
+#include "nsCoord.h"
+#include "nsFont.h"
 #include "gfxFont.h"
-#include "gfxTextRunCache.h"
+
+class nsIAtom;
+class nsIDeviceContext;
+class nsRenderingContext;
+class nsThebesDeviceContext;
+struct nsBoundingMetrics;
 
-class nsThebesFontMetrics : public nsIThebesFontMetrics
+/**
+ * Font metrics
+ *
+ * This class may be somewhat misnamed. A better name might be
+ * nsFontList. The style system uses the nsFont struct for various
+ * font properties, one of which is font-family, which can contain a
+ * *list* of font names. The nsFont struct is "realized" by asking the
+ * device context to cough up an nsFontMetrics object, which contains
+ * a list of real font handles, one for each font mentioned in
+ * font-family (and for each fallback when we fall off the end of that
+ * list).
+ *
+ * The style system needs to have access to certain metrics, such as
+ * the em height (for the CSS "em" unit), and we use the first Western
+ * font's metrics for that purpose. The platform-specific
+ * implementations are expected to select non-Western fonts that "fit"
+ * reasonably well with the Western font that is loaded at Init time.
+ */
+class nsFontMetrics
 {
 public:
-    nsThebesFontMetrics();
-    virtual ~nsThebesFontMetrics();
+    nsFontMetrics();
+    ~nsFontMetrics();
+
+    NS_INLINE_DECL_REFCOUNTING(nsFontMetrics)
+
+    /**
+     * Initialize the font metrics. Call this after creating the font metrics.
+     * Font metrics you get from the font cache do NOT need to be initialized
+     *
+     * @see nsIDeviceContext#GetMetricsFor()
+     */
+    nsresult Init(const nsFont& aFont, nsIAtom* aLanguage,
+                  nsIDeviceContext *aContext,
+                  gfxUserFontSet *aUserFontSet = nsnull);
 
-    NS_DECL_ISUPPORTS
+    /**
+     * Destroy this font metrics. This breaks the association between
+     * the font metrics and the device context.
+     */
+    void Destroy();
+
+    /**
+     * Return the font's x-height.
+     */
+    nscoord XHeight();
+
+    /**
+     * Return the font's superscript offset (the distance from the
+     * baseline to where a superscript's baseline should be placed).
+     * The value returned will be positive.
+     */
+    nscoord SuperscriptOffset();
 
-    NS_IMETHOD  Init(const nsFont& aFont, nsIAtom* aLanguage,
-                     nsIDeviceContext *aContext, 
-                     gfxUserFontSet *aUserFontSet = nsnull);
-    NS_IMETHOD  Destroy();
-    NS_IMETHOD  GetXHeight(nscoord& aResult);
-    NS_IMETHOD  GetSuperscriptOffset(nscoord& aResult);
-    NS_IMETHOD  GetSubscriptOffset(nscoord& aResult);
-    NS_IMETHOD  GetStrikeout(nscoord& aOffset, nscoord& aSize);
-    NS_IMETHOD  GetUnderline(nscoord& aOffset, nscoord& aSize);
-    NS_IMETHOD  GetHeight(nscoord &aHeight);
-    NS_IMETHOD  GetInternalLeading(nscoord &aLeading);
-    NS_IMETHOD  GetExternalLeading(nscoord &aLeading);
-    NS_IMETHOD  GetEmHeight(nscoord &aHeight);
-    NS_IMETHOD  GetEmAscent(nscoord &aAscent);
-    NS_IMETHOD  GetEmDescent(nscoord &aDescent);
-    NS_IMETHOD  GetMaxHeight(nscoord &aHeight);
-    NS_IMETHOD  GetMaxAscent(nscoord &aAscent);
-    NS_IMETHOD  GetMaxDescent(nscoord &aDescent);
-    NS_IMETHOD  GetMaxAdvance(nscoord &aAdvance);
-    NS_IMETHOD  GetLanguage(nsIAtom** aLanguage);
-    NS_IMETHOD  GetFontHandle(nsFontHandle &aHandle);
-    NS_IMETHOD  GetAveCharWidth(nscoord& aAveCharWidth);
-    NS_IMETHOD  GetSpaceWidth(nscoord& aSpaceCharWidth);
-    virtual PRInt32 GetMaxStringLength();
+    /**
+     * Return the font's subscript offset (the distance from the
+     * baseline to where a subscript's baseline should be placed).
+     * The value returned will be positive.
+     */
+    nscoord SubscriptOffset();
+
+    /**
+     * Return the font's strikeout offset (the distance from the
+     * baseline to where a strikeout should be placed) and size.
+     * Positive values are above the baseline, negative below.
+     */
+    void GetStrikeout(nscoord& aOffset, nscoord& aSize);
 
+    /**
+     * Return the font's underline offset (the distance from the
+     * baseline to where a underline should be placed) and size.
+     * Positive values are above the baseline, negative below.
+     */
+    void GetUnderline(nscoord& aOffset, nscoord& aSize);
 
-    virtual nsresult GetWidth(const char* aString, PRUint32 aLength, nscoord& aWidth,
-                              nsThebesRenderingContext *aContext);
-    virtual nsresult GetWidth(const PRUnichar* aString, PRUint32 aLength,
-                              nscoord& aWidth, PRInt32 *aFontID,
-                              nsThebesRenderingContext *aContext);
+    /**
+     * Returns the amount of internal leading for the font.
+     * This is normally the difference between the max ascent
+     * and the em ascent.
+     */
+    nscoord InternalLeading();
+
+    /**
+     * Returns the amount of external leading for the font.
+     * em ascent(?) plus external leading is the font designer's
+     * recommended line-height for this font.
+     */
+    nscoord ExternalLeading();
 
-    // Get the text dimensions for this string
-    virtual nsresult GetTextDimensions(const PRUnichar* aString,
-                                       PRUint32 aLength,
-                                       nsTextDimensions& aDimensions, 
-                                       PRInt32* aFontID);
-    virtual nsresult GetTextDimensions(const char*         aString,
-                                       PRInt32             aLength,
-                                       PRInt32             aAvailWidth,
-                                       PRInt32*            aBreaks,
-                                       PRInt32             aNumBreaks,
-                                       nsTextDimensions&   aDimensions,
-                                       PRInt32&            aNumCharsFit,
-                                       nsTextDimensions&   aLastWordDimensions,
-                                       PRInt32*            aFontID);
-    virtual nsresult GetTextDimensions(const PRUnichar*    aString,
-                                       PRInt32             aLength,
-                                       PRInt32             aAvailWidth,
-                                       PRInt32*            aBreaks,
-                                       PRInt32             aNumBreaks,
-                                       nsTextDimensions&   aDimensions,
-                                       PRInt32&            aNumCharsFit,
-                                       nsTextDimensions&   aLastWordDimensions,
-                                       PRInt32*            aFontID);
+    /**
+     * Returns the height of the em square.
+     * This is em ascent plus em descent.
+     */
+    nscoord EmHeight();
+
+    /**
+     * Returns the ascent part of the em square.
+     */
+    nscoord EmAscent();
+
+    /**
+     * Returns the descent part of the em square.
+     */
+    nscoord EmDescent();
+
+    /**
+     * Returns the height of the bounding box.
+     * This is max ascent plus max descent.
+     */
+    nscoord MaxHeight();
+
+    /**
+     * Returns the maximum distance characters in this font extend
+     * above the base line.
+     */
+    nscoord MaxAscent();
+
+    /**
+     * Returns the maximum distance characters in this font extend
+     * below the base line.
+     */
+    nscoord MaxDescent();
+
+    /**
+     * Returns the maximum character advance for the font.
+     */
+    nscoord MaxAdvance();
 
-    // Draw a string using this font handle on the surface passed in.  
-    virtual nsresult DrawString(const char *aString, PRUint32 aLength,
-                                nscoord aX, nscoord aY,
-                                const nscoord* aSpacing,
-                                nsThebesRenderingContext *aContext);
-    virtual nsresult DrawString(const PRUnichar* aString, PRUint32 aLength,
-                                nscoord aX, nscoord aY,
-                                PRInt32 aFontID,
-                                const nscoord* aSpacing,
-                                nsThebesRenderingContext *aContext)
-    {
-      NS_ASSERTION(!aSpacing, "Spacing not supported here");
-      return DrawString(aString, aLength, aX, aY, aContext, aContext);
-    }
-    virtual nsresult DrawString(const PRUnichar* aString, PRUint32 aLength,
-                                nscoord aX, nscoord aY,
-                                nsIRenderingContext *aContext,
-                                nsIRenderingContext *aTextRunConstructionContext);
+    /**
+     * Returns the average character width
+     */
+    nscoord AveCharWidth();
+
+    /**
+     * Returns the often needed width of the space character
+     */
+    nscoord SpaceWidth();
+
+    /**
+     * Returns the font associated with these metrics. The return value
+     * is only defined after Init() has been called.
+     */
+    const nsFont &Font() { return mFont; }
+
+    /**
+     * Returns the language associated with these metrics
+     */
+    nsIAtom* Language() { return mLanguage; }
+
+    PRInt32 GetMaxStringLength();
+
+    // Get the width for this string.  aWidth will be updated with the
+    // width in points, not twips.  Callers must convert it if they
+    // want it in another format.
+    nscoord GetWidth(const char* aString, PRUint32 aLength,
+                     nsRenderingContext *aContext);
+    nscoord GetWidth(const PRUnichar* aString, PRUint32 aLength,
+                     nsRenderingContext *aContext);
+
+    // Draw a string using this font handle on the surface passed in.
+    void DrawString(const char *aString, PRUint32 aLength,
+                    nscoord aX, nscoord aY,
+                    nsRenderingContext *aContext);
+    void DrawString(const PRUnichar* aString, PRUint32 aLength,
+                    nscoord aX, nscoord aY,
+                    nsRenderingContext *aContext,
+                    nsRenderingContext *aTextRunConstructionContext);
 
 #ifdef MOZ_MATHML
-    // These two functions get the bounding metrics for this handle,
-    // updating the aBoundingMetrics in app units.
-    virtual nsresult GetBoundingMetrics(const char *aString, PRUint32 aLength,
-                                        nsThebesRenderingContext *aContext,
-                                        nsBoundingMetrics &aBoundingMetrics);
-    virtual nsresult GetBoundingMetrics(const PRUnichar *aString,
-                                        PRUint32 aLength,
-                                        nsThebesRenderingContext *aContext,
-                                        nsBoundingMetrics &aBoundingMetrics);
+    nsBoundingMetrics GetBoundingMetrics(const PRUnichar *aString,
+                                         PRUint32 aLength,
+                                         nsRenderingContext *aContext);
 #endif /* MOZ_MATHML */
 
-    // Set the direction of the text rendering
-    virtual nsresult SetRightToLeftText(PRBool aIsRTL);
-    virtual PRBool GetRightToLeftText();
-    virtual void SetTextRunRTL(PRBool aIsRTL) { mTextRunRTL = aIsRTL; }
+    void SetTextRunRTL(PRBool aIsRTL) { mTextRunRTL = aIsRTL; }
+    PRBool GetTextRunRTL() { return mTextRunRTL; }
 
-    virtual gfxFontGroup* GetThebesFontGroup() { return mFontGroup; }
+    gfxFontGroup* GetThebesFontGroup() { return mFontGroup; }
+    gfxUserFontSet* GetUserFontSet() { return mFontGroup->GetUserFontSet(); }
 
-    virtual gfxUserFontSet* GetUserFontSet();
-    
-    PRBool GetRightToLeftTextRunMode() {
-        return mTextRunRTL;
-    }
+    PRInt32 AppUnitsPerDevPixel() { return mP2A; }
 
 protected:
-
     const gfxFont::Metrics& GetMetrics() const;
 
-    class AutoTextRun {
-    public:
-        AutoTextRun(nsThebesFontMetrics* aMetrics, nsIRenderingContext* aRC,
-                    const char* aString, PRInt32 aLength) {
-            mTextRun = gfxTextRunCache::MakeTextRun(
-                reinterpret_cast<const PRUint8*>(aString), aLength,
-                aMetrics->mFontGroup, aRC->ThebesContext(),
-                aMetrics->mP2A,
-                ComputeFlags(aMetrics));
-        }
-        AutoTextRun(nsThebesFontMetrics* aMetrics, nsIRenderingContext* aRC,
-                    const PRUnichar* aString, PRInt32 aLength) {
-            mTextRun = gfxTextRunCache::MakeTextRun(
-                aString, aLength, aMetrics->mFontGroup,
-                aRC->ThebesContext(),
-                aMetrics->mP2A,
-                ComputeFlags(aMetrics));
-        }
-        gfxTextRun* operator->() { return mTextRun.get(); }
-        gfxTextRun* get() { return mTextRun.get(); }
-
-    private:
-        gfxTextRunCache::AutoTextRun mTextRun;
-        
-        static PRUint32 ComputeFlags(nsThebesFontMetrics* aMetrics) {
-            PRUint32 flags = 0;
-            if (aMetrics->GetRightToLeftTextRunMode()) {
-                flags |= gfxTextRunFactory::TEXT_IS_RTL;
-            }
-            return flags;
-        }
-    };
-    friend class AutoTextRun;
-
+    nsFont mFont;
     nsRefPtr<gfxFontGroup> mFontGroup;
-    gfxFontStyle *mFontStyle;
-
-private:
+    nsCOMPtr<nsIAtom> mLanguage;
     nsThebesDeviceContext *mDeviceContext;
-    nsCOMPtr<nsIAtom> mLanguage;
     PRInt32 mP2A;
-    PRPackedBool mIsRightToLeft;
     PRPackedBool mTextRunRTL;
 };
 
-#endif /* NSTHEBESFONTMETRICS__H__ */
+#endif /* NSFONTMETRICS__H__ */
--- a/gfx/src/nsGfxCIID.h
+++ b/gfx/src/nsGfxCIID.h
@@ -41,28 +41,20 @@
 #include "nsISupports.h"
 #include "nsIFactory.h"
 #include "nsIComponentManager.h"
 
 #define NS_IMAGE_CID \
 { 0x6049b260, 0xc1e6, 0x11d1, \
 { 0xa8, 0x27, 0x00, 0x40, 0x95, 0x9a, 0x28, 0xc9 } }
 
-#define NS_RENDERING_CONTEXT_CID \
-{ 0x6049b261, 0xc1e6, 0x11d1, \
-{ 0xa8, 0x27, 0x00, 0x40, 0x95, 0x9a, 0x28, 0xc9 } }
-
 #define NS_DEVICE_CONTEXT_CID \
 { 0x6049b262, 0xc1e6, 0x11d1, \
 { 0xa8, 0x27, 0x00, 0x40, 0x95, 0x9a, 0x28, 0xc9 } }
 
-#define NS_FONT_METRICS_CID \
-{ 0x6049b263, 0xc1e6, 0x11d1, \
-{ 0xa8, 0x27, 0x00, 0x40, 0x95, 0x9a, 0x28, 0xc9 } }
-
 #define NS_FONT_ENUMERATOR_CID \
 { 0xa6cf9115, 0x15b3, 0x11d2, \
 { 0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32 } }
 
 #define NS_REGION_CID \
 { 0xe12752f0, 0xee9a, 0x11d1, \
 { 0xa8, 0x2a, 0x00, 0x40, 0x95, 0x9a, 0x28, 0xc9 } }
 
--- a/gfx/src/nsIDeviceContext.h
+++ b/gfx/src/nsIDeviceContext.h
@@ -37,26 +37,26 @@
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef nsIDeviceContext_h___
 #define nsIDeviceContext_h___
 
 #include "nsISupports.h"
 #include "nsCoord.h"
 #include "nsRect.h"
-#include "nsIRenderingContext.h"
-// XXX we need only gfxTypes.h, but we cannot include it directly.
-#include "gfxPoint.h"
+#include "gfxTypes.h"
+#include "nsStringFwd.h"
 
 class nsIView;
-class nsIFontMetrics;
+class nsFontMetrics;
 class nsIWidget;
 class nsIDeviceContextSpec;
 class nsIAtom;
 class gfxUserFontSet;
+class nsRenderingContext;
 
 struct nsFont;
 
 //a cross platform way of specifying a native device context
 typedef void * nsNativeDeviceContext;
 
 /* error codes for printer device contexts */
 #define NS_ERROR_GFX_PRINTER_BASE (1) /* adjustable :-) */
@@ -215,39 +215,39 @@ public:
   NS_IMETHOD  InitForPrinting(nsIDeviceContextSpec* aDevSpec) = 0;
 
   /**
    * Create a rendering context and initialize it from an nsIView
    * @param aView view to initialize context from
    * @param aContext out parameter for new rendering context
    * @return error status
    */
-  NS_IMETHOD  CreateRenderingContext(nsIView *aView, nsIRenderingContext *&aContext) = 0;
+  NS_IMETHOD  CreateRenderingContext(nsIView *aView, nsRenderingContext *&aContext) = 0;
 
   /**
    * Create a rendering context and initialize it from an nsIWidget
    * @param aWidget widget to initialize context from
    * @param aContext out parameter for new rendering context
    * @return error status
    */
-  NS_IMETHOD  CreateRenderingContext(nsIWidget *aWidget, nsIRenderingContext *&aContext) = 0;
+  NS_IMETHOD  CreateRenderingContext(nsIWidget *aWidget, nsRenderingContext *&aContext) = 0;
 
   /**
    * Create a rendering context and initialize it.
    * @param aContext out parameter for new rendering context
    * @return error status
    */
-  NS_IMETHOD  CreateRenderingContext(nsIRenderingContext *&aContext) = 0;
+  NS_IMETHOD  CreateRenderingContext(nsRenderingContext *&aContext) = 0;
 
   /**
    * Create an uninitalised rendering context.
    * @param aContext out parameter for new rendering context
    * @return error status
    */
-  NS_IMETHOD  CreateRenderingContextInstance(nsIRenderingContext *&aContext) = 0;
+  NS_IMETHOD  CreateRenderingContextInstance(nsRenderingContext *&aContext) = 0;
 
   /**
    * We are in the process of creating the native widget for aWidget.
    * Do any device-specific processing required to initialize the
    * native widget for this device. A pointer to some platform-specific data is
    * returned in aOut.
    *
    * GTK2 calls this to get the required visual for the window.
@@ -304,55 +304,55 @@ public:
    *
    * @param aID    The system font ID.
    * @param aInfo  The font structure to be filled in.
    * @return error status
    */
   NS_IMETHOD  GetSystemFont(nsSystemFontID aID, nsFont *aFont) const = 0;
 
   /**
-   * Get the nsIFontMetrics that describe the properties of
+   * Get the nsFontMetrics that describe the properties of
    * an nsFont.
    * @param aFont font description to obtain metrics for
    * @param aLanguage the language of the document
    * @param aMetrics out parameter for font metrics
    * @param aUserFontSet user font set
    * @return error status
    */
   NS_IMETHOD  GetMetricsFor(const nsFont& aFont, nsIAtom* aLanguage,
                             gfxUserFontSet* aUserFontSet,
-                            nsIFontMetrics*& aMetrics) = 0;
+                            nsFontMetrics*& aMetrics) = 0;
 
   /**
-   * Get the nsIFontMetrics that describe the properties of
+   * Get the nsFontMetrics that describe the properties of
    * an nsFont.
    * @param aFont font description to obtain metrics for
    * @param aMetrics out parameter for font metrics
    * @param aUserFontSet user font set
    * @return error status
    */
   NS_IMETHOD  GetMetricsFor(const nsFont& aFont, gfxUserFontSet* aUserFontSet,
-                            nsIFontMetrics*& aMetrics) = 0;
+                            nsFontMetrics*& aMetrics) = 0;
 
   /**
    * Check to see if a particular named font exists.
    * @param aFontName character string of font face name
    * @return NS_OK if font is available, else font is unavailable
    */
   NS_IMETHOD CheckFontExistence(const nsString& aFaceName) = 0;
   NS_IMETHOD FirstExistingFont(const nsFont& aFont, nsString& aFaceName) = 0;
 
   NS_IMETHOD GetLocalFontName(const nsString& aFaceName, nsString& aLocalName,
                               PRBool& aAliased) = 0;
 
   /**
    * Notification when a font metrics instance created for this device is
    * about to be deleted
    */
-  NS_IMETHOD FontMetricsDeleted(const nsIFontMetrics* aFontMetrics) = 0;
+  NS_IMETHOD FontMetricsDeleted(const nsFontMetrics* aFontMetrics) = 0;
 
   /**
    * Attempt to free up resoruces by flushing out any fonts no longer
    * referenced by anything other than the font cache itself.
    * @return error status
    */
   NS_IMETHOD FlushFontCache(void) = 0;
 
deleted file mode 100644
--- a/gfx/src/nsIFontMetrics.h
+++ /dev/null
@@ -1,226 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * 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 ***** */
-
-#ifndef nsIFontMetrics_h___
-#define nsIFontMetrics_h___
-
-#include "nsISupports.h"
-#include "nsCoord.h"
-#include "nsFont.h"
-
-class nsString;
-class nsIDeviceContext;
-class nsIAtom;
-class gfxUserFontSet;
-
-// IID for the nsIFontMetrics interface
-#define NS_IFONT_METRICS_IID   \
-{ 0x360C5575, 0xF7AC, 0x4079, \
-{ 0xB8, 0xA6, 0x56, 0x91, 0x4B, 0xEA, 0x2A, 0xEA } }
-
-//----------------------------------------------------------------------
-
-/**
- * A native font handle
- */
-typedef void* nsFontHandle;
-
-/**
- * Font metrics interface
- *
- * This interface may be somewhat misnamed. A better name might be
- * nsIFontList. The style system uses the nsFont struct for various font
- * properties, one of which is font-family, which can contain a *list* of
- * font names. The nsFont struct is "realized" by asking the device context
- * to cough up an nsIFontMetrics object, which contains a list of real font
- * handles, one for each font mentioned in font-family (and for each fallback
- * when we fall off the end of that list).
- *
- * The style system needs to have access to certain metrics, such as the
- * em height (for the CSS "em" unit), and we use the first Western font's
- * metrics for that purpose. The platform-specific implementations are
- * expected to select non-Western fonts that "fit" reasonably well with the
- * Western font that is loaded at Init time.
- */
-class nsIFontMetrics : public nsISupports
-{
-public:
-  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IFONT_METRICS_IID)
-
-  /**
-   * Initialize the font metrics. Call this after creating the font metrics.
-   * Font metrics you get from the font cache do NOT need to be initialized
-   *
-   * @see nsIDeviceContext#GetMetricsFor()
-   */
-  NS_IMETHOD  Init(const nsFont& aFont, nsIAtom* aLanguage,
-                   nsIDeviceContext *aContext, gfxUserFontSet *aUserFontSet = nsnull) = 0;
-
-  /**
-   * Destroy this font metrics. This breaks the association between
-   * the font metrics and the device context.
-   */
-  NS_IMETHOD  Destroy() = 0;
-
-  /**
-   * Return the font's xheight property, scaled into app-units.
-   */
-  NS_IMETHOD  GetXHeight(nscoord& aResult) = 0;
-
-  /**
-   * Return the font's superscript offset (the distance from the
-   * baseline to where a superscript's baseline should be placed). The
-   * value returned will be a positive value.
-   */
-  NS_IMETHOD  GetSuperscriptOffset(nscoord& aResult) = 0;
-
-  /**
-   * Return the font's subscript offset (the distance from the
-   * baseline to where a subscript's baseline should be placed). The
-   * value returned will be a positive value.
-   */
-  NS_IMETHOD  GetSubscriptOffset(nscoord& aResult) = 0;
-
-  /**
-   * Return the font's strikeout offset (the distance from the 
-   * baseline to where a strikeout should be placed) and size
-   * Positive values are above the baseline, negative below.
-   */
-  NS_IMETHOD  GetStrikeout(nscoord& aOffset, nscoord& aSize) = 0;
-
-  /**
-   * Return the font's underline offset (the distance from the 
-   * baseline to where a underline should be placed) and size.
-   * Positive values are above the baseline, negative below.
-   */
-  NS_IMETHOD  GetUnderline(nscoord& aOffset, nscoord& aSize) = 0;
-
-  /**
-   * Returns the height (in app units) of the font. This is ascent plus descent
-   * plus any internal leading
-   *
-   * This method will be removed once the callers have been moved over to the
-   * new GetEmHeight (and possibly GetMaxHeight).
-   */
-  NS_IMETHOD  GetHeight(nscoord &aHeight) = 0;
-
-  /**
-   * Returns the amount of internal leading (in app units) for the font. This
-   * is computed as the "height  - (ascent + descent)"
-   */
-  NS_IMETHOD  GetInternalLeading(nscoord &aLeading) = 0;
-
-  /**
-   * Returns the amount of external leading (in app units) as suggested by font
-   * vendor. This value is suggested by font vendor to add to normal line-height 
-   * beside font height.
-   */
-  NS_IMETHOD  GetExternalLeading(nscoord &aLeading) = 0;
-
-  /**
-   * Returns the height (in app units) of the Western font's em square. This is
-   * em ascent plus em descent.
-   */
-  NS_IMETHOD  GetEmHeight(nscoord &aHeight) = 0;
-
-  /**
-   * Returns, in app units, the ascent part of the Western font's em square.
-   */
-  NS_IMETHOD  GetEmAscent(nscoord &aAscent) = 0;
-
-  /**
-   * Returns, in app units, the descent part of the Western font's em square.
-   */
-  NS_IMETHOD  GetEmDescent(nscoord &aDescent) = 0;
-
-  /**
-   * Returns the height (in app units) of the Western font's bounding box.
-   * This is max ascent plus max descent.
-   */
-  NS_IMETHOD  GetMaxHeight(nscoord &aHeight) = 0;
-
-  /**
-   * Returns, in app units, the maximum distance characters in this font extend
-   * above the base line.
-   */
-  NS_IMETHOD  GetMaxAscent(nscoord &aAscent) = 0;
-
-  /**
-   * Returns, in app units, the maximum distance characters in this font extend
-   * below the base line.
-   */
-  NS_IMETHOD  GetMaxDescent(nscoord &aDescent) = 0;
-
-  /**
-   * Returns, in app units, the maximum character advance for the font
-   */
-  NS_IMETHOD  GetMaxAdvance(nscoord &aAdvance) = 0;
-
-  /**
-   * Returns the font associated with these metrics. The return value
-   * is only defined after Init() has been called.
-   */
-  const nsFont &Font() { return mFont; }
-
-  /**
-   * Returns the language associated with these metrics
-   */
-  NS_IMETHOD  GetLanguage(nsIAtom** aLanguage) = 0;
-
-  /**
-   * Returns the font handle associated with these metrics
-   */
-  NS_IMETHOD  GetFontHandle(nsFontHandle &aHandle) = 0;
-
-  /**
-   * Returns the average character width
-   */
-  NS_IMETHOD  GetAveCharWidth(nscoord& aAveCharWidth) = 0;
-
-  /**
-   * Returns the often needed width of the space character
-   */
-  NS_IMETHOD  GetSpaceWidth(nscoord& aSpaceCharWidth) = 0;
-
-protected:
-
-  nsFont mFont;		// The font for this metrics object.
-};
-
-NS_DEFINE_STATIC_IID_ACCESSOR(nsIFontMetrics, NS_IFONT_METRICS_IID)
-
-#endif /* nsIFontMetrics_h___ */
deleted file mode 100644
--- a/gfx/src/nsIRenderingContext.h
+++ /dev/null
@@ -1,824 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
- *   Leon Sha <leon.sha@sun.com>
- *   Boris Zbarsky <bzbarsky@mit.edu>
- *
- * 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 ***** */
-
-#ifndef nsIRenderingContext_h___
-#define nsIRenderingContext_h___
-
-#include "nscore.h"
-#include "nsISupports.h"
-#include "nsColor.h"
-#include "nsCoord.h"
-#include "nsRect.h"
-#include "nsPoint.h"
-#include "nsSize.h"
-#include <stdio.h>
-
-class nsIWidget;
-class nsIFontMetrics;
-class nsTransform2D;
-class nsString;
-class nsIDeviceContext;
-class nsIntRegion;
-class nsIAtom;
-
-struct nsFont;
-struct nsTextDimensions;
-class gfxUserFontSet;
-#ifdef MOZ_MATHML
-struct nsBoundingMetrics;
-#endif
-
-class gfxASurface;
-class gfxContext;
-
-/* gfx2 */
-class imgIContainer;
-
-//cliprect/region combination methods
-
-typedef enum
-{
-  nsClipCombine_kIntersect = 0,
-  nsClipCombine_kUnion = 1,
-  nsClipCombine_kSubtract = 2,
-  nsClipCombine_kReplace = 3
-} nsClipCombine;
-
-//linestyles
-typedef enum
-{
-  nsLineStyle_kNone   = 0,
-  nsLineStyle_kSolid  = 1,
-  nsLineStyle_kDashed = 2,
-  nsLineStyle_kDotted = 3
-} nsLineStyle;
-
-typedef enum
-{
-  nsPenMode_kNone   = 0,
-  nsPenMode_kInvert = 1
-} nsPenMode;
-
-
-// IID for the nsIRenderingContext interface
-#define NS_IRENDERING_CONTEXT_IID \
-{ 0xefbfeb6c, 0x937e, 0x4889, \
-  { 0x92, 0x46, 0x16, 0xc0, 0xe8, 0x4b, 0xfa, 0xae } }
-
-//----------------------------------------------------------------------
-
-// RenderingContext interface
-class nsIRenderingContext : public nsISupports
-{
-public:
-  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IRENDERING_CONTEXT_IID)
-
-  //TBD: bind/unbind, transformation of scalars (hacky), 
-  //potential drawmode for selection, polygons. MMP
-
-  /**
-   * Initialize the RenderingContext
-   * @param aContext the device context to use.
-   * @param aWidget the widget to hook up to
-   * @result The result of the initialization, NS_Ok if no errors
-   */
-  NS_IMETHOD Init(nsIDeviceContext* aContext, nsIWidget *aWidget) = 0;
-
-  /**
-   * Initialize the RenderingContext
-   * @param aContext the device context to use for the drawing.
-   * @param aThebesSurface the Thebes gfxASurface to which to draw
-   * @result The result of the initialization, NS_Ok if no errors
-   */
-  NS_IMETHOD Init(nsIDeviceContext* aContext, gfxASurface* aThebesSurface) = 0;
-
-  /**
-   * Initialize the RenderingContext
-   * @param aContext the device context to use for the drawing.
-   * @param aThebesContext an existing thebes context to use for the drawing
-   * @result The result of the initialization, NS_Ok if no errors
-   */
-  NS_IMETHOD Init(nsIDeviceContext* aContext, gfxContext* aThebesContext) = 0;
-
-  /**
-   * Get the DeviceContext that this RenderingContext was initialized
-   * with.  This function addrefs the device context.  Though it might
-   * be better if it just returned it directly, without addrefing.   
-   * @result the device context
-   */
-  NS_IMETHOD GetDeviceContext(nsIDeviceContext *& aDeviceContext) = 0;
-
-  /**
-   * Save a graphical state onto a stack.
-   */
-  NS_IMETHOD PushState(void) = 0;
-
-  /**
-   * Get and and set RenderingContext to this graphical state
-   */
-  NS_IMETHOD PopState(void) = 0;
-
-  // XXX temporary
-  NS_IMETHOD PushFilter(const nsRect& aRect, PRBool aAreaIsOpaque, float aOpacity)
-  { return NS_ERROR_NOT_IMPLEMENTED; }
-  NS_IMETHOD PopFilter()
-  { return NS_ERROR_NOT_IMPLEMENTED; }
-
-  /**
-   * Sets the clipping for the RenderingContext to the passed in rectangle.
-   * The rectangle is in app units!
-   * @param aRect The rectangle to set the clipping rectangle to
-   * @param aCombine how to combine this rect with the current clip region.
-   *        see the bottom of nsIRenderingContext.h
-   */
-  NS_IMETHOD SetClipRect(const nsRect& aRect, nsClipCombine aCombine) = 0;
-
-  /**
-   * Sets the line style for the RenderingContext 
-   * @param aLineStyle The line style
-   * @return NS_OK if the line style is correctly set
-   */
-  NS_IMETHOD SetLineStyle(nsLineStyle aLineStyle) = 0;
-
-  /**
-   * Sets the clipping for the RenderingContext to the passed in region.
-   * The region is in device coordinates!
-   * @param aRegion The region to set the clipping area to, IN DEVICE COORDINATES
-   * @param aCombine how to combine this region with the current clip region.
-   *        see the bottom of nsIRenderingContext.h
-   */
-  NS_IMETHOD SetClipRegion(const nsIntRegion& aRegion, nsClipCombine aCombine) = 0;
-
-  /**
-   * Sets the forground color for the RenderingContext
-   * @param aColor The color to set the RenderingContext to
-   */
-  NS_IMETHOD SetColor(nscolor aColor) = 0;
-
-  /**
-   * Get the forground color for the RenderingContext
-   * @return The current forground color of the RenderingContext
-   */
-  NS_IMETHOD GetColor(nscolor &aColor) const = 0;
-
-  /**
-   * Sets the font for the RenderingContext
-   * @param aFont The font to use in the RenderingContext
-   */
-  NS_IMETHOD SetFont(const nsFont& aFont, nsIAtom* aLanguage,
-                     gfxUserFontSet *aUserFontSet) = 0;
-
-  /**
-   * Sets the font for the RenderingContext, without language info
-   * @param aFont The font to use in the RenderingContext
-   */
-  NS_IMETHOD SetFont(const nsFont& aFont,
-                     gfxUserFontSet *aUserFontSet) = 0;
-
-  /**
-   * Sets the font for the RenderingContext
-   * @param aFontMetric The font metrics representing the
-   *        font to use in the RenderingContext
-   */
-  NS_IMETHOD SetFont(nsIFontMetrics *aFontMetrics) = 0;
-
-  /**
-   * Get the current fontmetrics for the RenderingContext
-   * @return The current font of the RenderingContext
-   */
-  NS_IMETHOD GetFontMetrics(nsIFontMetrics *&aFontMetrics) = 0;
-
-  /**
-   *  Add in a translate to the RenderingContext's transformation matrix
-   * @param aX The horizontal translation
-   * @param aY The vertical translation
-   */
-  NS_IMETHOD Translate(nscoord aX, nscoord aY) = 0;
-  
-  /**
-   * Set the translation compoennt of the current transformation matrix.
-   * Useful to set it to a known pixel value without incurring roundoff
-   * errors.
-   */
-  NS_IMETHOD SetTranslation(nscoord aX, nscoord aY) = 0;
-
-  /**
-   *  Add in a scale to the RenderingContext's transformation matrix
-   * @param aX The horizontal scale
-   * @param aY The vertical scale
-   */
-  NS_IMETHOD Scale(float aSx, float aSy) = 0;
-
-  struct PushedTranslation {
-    float mSavedX, mSavedY;
-  };
-
-  class AutoPushTranslation {
-    nsIRenderingContext* mCtx;
-    PushedTranslation mPushed;
-  public:
-    AutoPushTranslation(nsIRenderingContext* aCtx, nscoord aX, nscoord aY)
-      : mCtx(aCtx) {
-      mCtx->PushTranslation(&mPushed);
-      mCtx->Translate(aX, aY);
-    }
-    ~AutoPushTranslation() {
-      mCtx->PopTranslation(&mPushed);
-    }
-  };
-
-  NS_IMETHOD PushTranslation(PushedTranslation* aState) = 0;
-
-  NS_IMETHOD PopTranslation(PushedTranslation* aState) = 0;
-
-  /** 
-   * Get the current transformation matrix for the RenderingContext
-   * @return The transformation matrix for the RenderingContext
-   */
-  NS_IMETHOD GetCurrentTransform(nsTransform2D *&aTransform) = 0;
-
-  /**
-   * Draw a line
-   * @param aXO starting horiztonal coord in twips
-   * @param aY0 starting vertical coord in twips
-   * @param aX1 end horiztonal coord in twips
-   * @param aY1 end vertical coord in twips
-   */
-  NS_IMETHOD DrawLine(nscoord aX0, nscoord aY0, nscoord aX1, nscoord aY1) = 0;
-
-  /**
-   * Draw a rectangle
-   * @param aRect The rectangle to draw
-   */
-  NS_IMETHOD DrawRect(const nsRect& aRect) = 0;
-
-  /**
-   * Draw a rectangle
-   * @param aX Horizontal left Coordinate in twips
-   * @param aY Vertical top Coordinate in twips
-   * @param aWidth Width of rectangle in twips
-   * @param aHeight Height of rectangle in twips
-   */
-  NS_IMETHOD DrawRect(nscoord aX, nscoord aY, nscoord aWidth, nscoord aHeight) = 0;
-
-  /**
-   * Fill a rectangle in the current foreground color
-   * @param aRect The rectangle to draw
-   */
-  NS_IMETHOD FillRect(const nsRect& aRect) = 0;
-
-  /**
-   * Fill a rectangle in the current foreground color
-   * @param aX Horizontal left Coordinate in twips
-   * @param aY Vertical top Coordinate in twips
-   * @param aWidth Width of rectangle in twips
-   * @param aHeight Height of rectangle in twips
-   */
-  NS_IMETHOD FillRect(nscoord aX, nscoord aY, nscoord aWidth, nscoord aHeight) = 0;
-
-  /**
-   * XOR Invert a rectangle in the current foreground color
-   * @param aRect The rectangle to draw
-   */
-  NS_IMETHOD InvertRect(const nsRect& aRect) = 0;
-
-  /**
-   * XOR Invert a rectangle in the current foreground color
-   * @param aX Horizontal left Coordinate in twips
-   * @param aY Vertical top Coordinate in twips
-   * @param aWidth Width of rectangle in twips
-   * @param aHeight Height of rectangle in twips
-   */
-  NS_IMETHOD InvertRect(nscoord aX, nscoord aY, nscoord aWidth, nscoord aHeight) = 0;
-
-  /**
-   * Fill a poly in the current foreground color
-   * @param aPoints points to use for the drawing, last must equal first
-   * @param aNumPonts number of points in the polygon
-   */
-  NS_IMETHOD FillPolygon(const nsPoint aPoints[], PRInt32 aNumPoints) = 0;
-
-  /**
-   * Draw an ellipse in the current foreground color
-   * @param aRect The rectangle define bounds of ellipse to draw
-   */
-  NS_IMETHOD DrawEllipse(const nsRect& aRect) = 0;
-
-  /**
-   * Draw an ellipse in the current foreground color
-   * @param aX Horizontal left Coordinate in twips
-   * @param aY Vertical top Coordinate in twips
-   * @param aWidth Width of horizontal axis in twips
-   * @param aHeight Height of vertical axis in twips
-   */
-  NS_IMETHOD DrawEllipse(nscoord aX, nscoord aY, nscoord aWidth, nscoord aHeight) = 0;
-
-  /**
-   * Fill an ellipse in the current foreground color
-   * @param aRect The rectangle define bounds of ellipse to draw
-   */
-  NS_IMETHOD FillEllipse(const nsRect& aRect) = 0;
-
-  /**
-   * Fill an ellipse in the current foreground color
-   * @param aX Horizontal left Coordinate in twips
-   * @param aY Vertical top Coordinate in twips
-   * @param aWidth Width of horizontal axis in twips
-   * @param aHeight Height of vertical axis in twips
-   */
-  NS_IMETHOD FillEllipse(nscoord aX, nscoord aY, nscoord aWidth, nscoord aHeight) = 0;
-
-  /**
-   * Returns the width (in app units) of an 8-bit character
-   * If no font has been Set, the results are undefined.
-   * @param aC character to measure
-   * @param aWidth out parameter for width
-   * @return error status
-   */
-  NS_IMETHOD GetWidth(char aC, nscoord &aWidth) = 0;
-
-  /**
-   * Returns the width (in app units) of a unicode character
-   * If no font has been Set, the results are undefined.
-   * @param aC character to measure
-   * @param aWidth out parameter for width
-   * @param aFontID an optional out parameter used to store a
-   *        font identifier that can be passed into the DrawString()
-   *        methods to speed rendering
-   * @return error status
-   */
-  NS_IMETHOD GetWidth(PRUnichar aC, nscoord &aWidth,
-                      PRInt32 *aFontID = nsnull) = 0;
-
-  /**
-   * Returns the width (in app units) of an nsString
-   * If no font has been Set, the results are undefined.
-   * @param aString string to measure
-   * @param aWidth out parameter for width
-   * @param aFontID an optional out parameter used to store a
-   *        font identifier that can be passed into the DrawString()
-   *        methods to speed rendering
-   * @return error status
-   */
-  NS_IMETHOD GetWidth(const nsString& aString, nscoord &aWidth,
-                      PRInt32 *aFontID = nsnull) = 0;
-
-  /**
-   * Returns the width (in app units) of an 8-bit character string
-   * If no font has been Set, the results are undefined.
-   * @param aString string to measure
-   * @param aWidth out parameter for width
-   * @return error status
-   */
-  NS_IMETHOD GetWidth(const char* aString, nscoord& aWidth) = 0;
-
-  /**
-   * Returns the width (in app units) of an 8-bit character string
-   * If no font has been Set, the results are undefined.
-   * @param aString string to measure
-   * @param aLength number of characters in string
-   * @param aWidth out parameter for width
-   * @return error status
-   */
-  NS_IMETHOD GetWidth(const char* aString, PRUint32 aLength,
-                      nscoord& aWidth) = 0;
-
-  /**
-   * Returns the width (in app units) of a Unicode character string
-   * If no font has been Set, the results are undefined.
-   * @param aString string to measure
-   * @param aLength number of characters in string
-   * @param aWidth out parameter for width
-   * @param aFontID an optional out parameter used to store a
-   *        font identifier that can be passed into the DrawString()
-   *        methods to speed rendering
-   * @return error status
-   */
-  NS_IMETHOD GetWidth(const PRUnichar *aString, PRUint32 aLength,
-                      nscoord &aWidth, PRInt32 *aFontID = nsnull) = 0;
-
-  /**
-   * Returns the dimensions of a string, i.e., the overall extent of a string
-   * whose rendering may involve switching between different fonts that have
-   * different metrics.
-   * @param aString string to measure
-   * @param aLength number of characters in string
-   * @param aFontID an optional out parameter used to store a
-   *        font identifier that can be passed into the DrawString()
-   *        methods to speed measurements
-   * @return aDimensions struct that contains the extent of the string (see below)
-   */
-  NS_IMETHOD GetTextDimensions(const char* aString, PRUint32 aLength,
-                               nsTextDimensions& aDimensions) = 0;
-  NS_IMETHOD GetTextDimensions(const PRUnichar* aString, PRUint32 aLength,
-                               nsTextDimensions& aDimensions, PRInt32* aFontID = nsnull) = 0;
-
-#if defined(_WIN32) || defined(XP_OS2) || defined(MOZ_X11)
-  /**
-   * Given an available width and an array of break points,
-   * returns the dimensions (in app units) of the text that fit and
-   * the number of characters that fit. The number of characters
-   * corresponds to an entry in the break array.
-   * If no font has been set, the results are undefined.
-   * @param aString, string to measure
-   * @param aLength, number of characters in string
-   * @param aAvailWidth, the available space in which the text must fit
-   * @param aBreaks, array of places to break. Specified as offsets from the
-   *          start of the string
-   * @param aNumBreaks, the number of entries in the break array. The last
-   *          entry in the break array must equal the length of the string
-   * @param aDimensions, out parameter for the dimensions, the ascent and descent
-   *           of the last word are left out to allow possible line-breaking before
-   *           the last word. However, the width of the last word is included.
-   * @param aNumCharsFit, the number of characters that fit in the available space
-   * @param aLastWordDimensions, dimensions of the last word, the width field,
-   *             dimensions.width, should be -1 for an unknown width. But the 
-   *             ascent and descent are expected to be known.
-   * @param aFontID, an optional out parameter used to store a
-   *        font identifier that can be passed into the DrawString()
-   *        methods to speed rendering
-   * @return error status
-   */
-  NS_IMETHOD GetTextDimensions(const char*       aString,
-                               PRInt32           aLength,
-                               PRInt32           aAvailWidth,
-                               PRInt32*          aBreaks,
-                               PRInt32           aNumBreaks,
-                               nsTextDimensions& aDimensions,
-                               PRInt32&          aNumCharsFit,
-                               nsTextDimensions& aLastWordDimensions,
-                               PRInt32*          aFontID = nsnull) = 0;
-
-  NS_IMETHOD GetTextDimensions(const PRUnichar*  aString,
-                               PRInt32           aLength,
-                               PRInt32           aAvailWidth,
-                               PRInt32*          aBreaks,
-                               PRInt32           aNumBreaks,
-                               nsTextDimensions& aDimensions,
-                               PRInt32&          aNumCharsFit,
-                               nsTextDimensions& aLastWordDimensions,
-                               PRInt32*          aFontID = nsnull) = 0;
-#endif
-
-  /**
-   * Draw a string in the RenderingContext
-   * @param aString The string to draw
-   * @param aLength The length of the aString
-   * @param aX Horizontal starting point of baseline
-   * @param aY Vertical starting point of baseline.
-   * @param aSpacing inter-character spacing to apply
-   */
-  NS_IMETHOD DrawString(const char *aString, PRUint32 aLength,
-                        nscoord aX, nscoord aY,
-                        const nscoord* aSpacing = nsnull) = 0;
-
-  /**
-   * Draw a string in the RenderingContext
-   * @param aString A PRUnichar of the string
-   * @param aLength The length of the aString
-   * @param aX Horizontal starting point of baseline
-   * @param aY Vertical starting point of baseline.
-   * @param aFontID an optional parameter used to speed font
-   *        selection for complex unicode strings. the value
-   *        passed is returned by the DrawString() methods.
-   * @param aSpacing inter-character spacing to apply
-   */
-  NS_IMETHOD DrawString(const PRUnichar *aString, PRUint32 aLength,
-                        nscoord aX, nscoord aY,
-                        PRInt32 aFontID = -1,
-                        const nscoord* aSpacing = nsnull) = 0;
-
-  /**
-   * Draw a string in the RenderingContext
-   * @param aString A nsString of the string
-   * @param aX Horizontal starting point of baseline
-   * @param aY Vertical starting point of baseline.
-   * @param aFontID an optional parameter used to speed font
-   *        selection for complex unicode strings. the value
-   *        passed is returned by the DrawString() methods.
-   * @param aSpacing inter-character spacing to apply
-   */
-  NS_IMETHOD DrawString(const nsString& aString, nscoord aX, nscoord aY,
-                        PRInt32 aFontID = -1,
-                        const nscoord* aSpacing = nsnull) = 0;
-
-  enum GraphicDataType {
-    NATIVE_CAIRO_CONTEXT = 1,
-    NATIVE_GDK_DRAWABLE = 2,
-    NATIVE_WINDOWS_DC = 3,
-    NATIVE_MAC_THING = 4,
-    NATIVE_THEBES_CONTEXT = 5,
-    NATIVE_OS2_PS = 6
-  };
-  /**
-   * Retrieve the native graphic data given by aType. Return
-   * nsnull if not available.
-   */
-  virtual void* GetNativeGraphicData(GraphicDataType aType) = 0;
-
-#ifdef MOZ_MATHML
-  /**
-   * Returns bounding metrics (in app units) of an 8-bit character string
-   * @param aString string to measure
-   * @param aLength number of characters in string
-   * @return aBoundingMetrics struct that contains various metrics (see below)
-   * @return error status
-   */
-  NS_IMETHOD
-  GetBoundingMetrics(const char*        aString,
-                     PRUint32           aLength,
-                     nsBoundingMetrics& aBoundingMetrics) = 0;
-  /**
-   * Returns bounding metrics (in app units) of an Unicode character string
-   * @param aString string to measure
-   * @param aLength number of characters in string
-   * @param aFontID an optional out parameter used to store a
-   *        font identifier that can be passed into the GetBoundingMetrics()
-   *        methods to speed measurements
-   * @return aBoundingMetrics struct that contains various metrics (see below)
-   * @return error status
-   */
-  NS_IMETHOD
-  GetBoundingMetrics(const PRUnichar*   aString,
-                     PRUint32           aLength,
-                     nsBoundingMetrics& aBoundingMetrics,
-                     PRInt32*           aFontID = nsnull) = 0;
-#endif
-
-
-  /**
-   * Let the device context know whether we want text reordered with
-   * right-to-left base direction
-   */
-  NS_IMETHOD SetRightToLeftText(PRBool aIsRTL) = 0;
-
-  /**
-   * This sets the direction of the text; all characters should be
-   * overridden to have this direction.
-   */
-  virtual void SetTextRunRTL(PRBool aIsRTL) = 0;
-
-  /**
-   * Find the closest cursor position for a given x coordinate.
-   *
-   * This will find the closest byte index for a given x coordinate.
-   * This takes into account grapheme clusters and bidi text.
-   *
-   * @param aText Text on which to operate.
-   * @param aLength Length of the text.
-   * @param aPt the x/y position in the string to check.
-   *
-   * @return Index where the cursor falls.  If the return is zero,
-   *   it's before the first character, if it falls off the end of
-   *   the string it's the length of the string + 1.
-   *
-   */
-  virtual PRInt32 GetPosition(const PRUnichar *aText,
-                              PRUint32 aLength,
-                              nsPoint aPt) = 0;
-
-  /**
-   * Get the width for the specific range of a given string.
-   *
-   * This function is similar to other GetWidth functions, except that
-   * it gets the width for a part of the string instead of the entire
-   * string.  This is useful when you're interested in finding out the
-   * length of a chunk in the middle of the string.  Lots of languages
-   * require you to include surrounding information to accurately
-   * determine the length of a substring.
-   *
-   * @param aText Text on which to operate
-   * @param aLength Length of the text
-   * @param aStart Start index into the string
-   * @param aEnd End index into the string (inclusive)
-   * @param aWidth Returned with in app coordinates
-   *
-   */
-  NS_IMETHOD GetRangeWidth(const PRUnichar *aText,
-                           PRUint32 aLength,
-                           PRUint32 aStart,
-                           PRUint32 aEnd,
-                           PRUint32 &aWidth) = 0;
-
-  /**
-   * Get the width for the specific range of a given string.
-   *
-   * Same as GetRangeWidth for PRUnichar, but takes a char * as the
-   * text argument.
-   *
-   */
-  NS_IMETHOD GetRangeWidth(const char *aText,
-                           PRUint32 aLength,
-                           PRUint32 aStart,
-                           PRUint32 aEnd,
-                           PRUint32 &aWidth) = 0;
-
-  /**
-   * Render an encapsulated postscript object onto the current rendering
-   * surface.
-   *
-   * The EPS object must conform to the EPSF standard. See Adobe
-   * specification #5002, "Encapsulated PostScript File Format Specification"
-   * at <http://partners.adobe.com/asn/developer/pdfs/tn/5002.EPSF_Spec.pdf>.
-   * In particular, the EPS object must contain a BoundingBox comment.
-   *
-   * @param aRect  Rectangle in which to render the EPSF.
-   * @param aDataFile - plugin data stored in a file
-   * @return NS_OK for success, or a suitable error value.
-   *         NS_ERROR_NOT_IMPLEMENTED is returned if the rendering context
-   *         doesn't support rendering EPSF, 
-   */
-  NS_IMETHOD RenderEPS(const nsRect& aRect, FILE *aDataFile) = 0;
-
-  /**
-   * Return the Thebes gfxContext associated with this nsIRenderingContext.
-   */
-  virtual gfxContext *ThebesContext() = 0;
-};
-
-NS_DEFINE_STATIC_IID_ACCESSOR(nsIRenderingContext, NS_IRENDERING_CONTEXT_IID)
-
-//flags for copy CopyOffScreenBits
-
-//when performing the blit, use the region, if any,
-//that exists in the source drawingsurface as a
-//blit mask.
-#define NS_COPYBITS_USE_SOURCE_CLIP_REGION  0x0001
-
-//transform the source offsets by the xform in the
-//rendering context
-#define NS_COPYBITS_XFORM_SOURCE_VALUES     0x0002
-
-//transform the destination rect by the xform in the
-//rendering context
-#define NS_COPYBITS_XFORM_DEST_VALUES       0x0004
-
-//this is basically a hack and is used by callers
-//who have selected an alternate drawing surface and
-//wish the copy to happen to that buffer rather than
-//the "front" buffer. i'm not proud of this. MMP
-//XXX: This is no longer needed by the XPCODE. It will
-//be removed once all of the platform specific nsRenderingContext's
-//stop using it.
-#define NS_COPYBITS_TO_BACK_BUFFER          0x0008
-
-/* Struct used to represent the overall extent of a string
-   whose rendering may involve switching between different
-   fonts that have different metrics.
-*/
-struct nsTextDimensions {
-  // max ascent amongst all the fonts needed to represent the string
-  nscoord ascent;
-
-  // max descent amongst all the fonts needed to represent the string
-  nscoord descent;
-
-  // width of the string
-  nscoord width;
-
-
-  nsTextDimensions()
-  {
-    Clear();
-  }
-
-  /* Set all member data to zero */
-  void 
-  Clear() {
-    ascent = descent = width = 0;
-  }
-
-  /* Sum with another dimension */
-  void 
-  Combine(const nsTextDimensions& aOther) {
-    if (ascent < aOther.ascent) ascent = aOther.ascent;
-    if (descent < aOther.descent) descent = aOther.descent;   
-    width += aOther.width;
-  }
-};
-
-#ifdef MOZ_MATHML
-/* Struct used for accurate measurements of a string in order
-   to allow precise positioning when processing MathML.
-*/
-struct nsBoundingMetrics {
-
-  ///////////
-  // Metrics that _exactly_ enclose the text:
-
-  // The character coordinate system is the one used on X Windows:
-  // 1. The origin is located at the intersection of the baseline
-  //    with the left of the character's cell.
-  // 2. All horizontal bearings are oriented from left to right.
-  // 3. The ascent is oriented from bottom to top (being 0 at the orgin).
-  // 4. The descent is oriented from top to bottom (being 0 at the origin).
-
-  // Note that Win32/Mac/PostScript use a different convention for
-  // the descent (all vertical measurements are oriented from bottom
-  // to top on these palatforms). Make sure to flip the sign of the
-  // descent on these platforms for cross-platform compatibility.
-
-  // Any of the following member variables listed here can have 
-  // positive or negative value.
-
-  nscoord leftBearing;
-       /* The horizontal distance from the origin of the drawing
-          operation to the left-most part of the drawn string. */
-
-  nscoord rightBearing;
-       /* The horizontal distance from the origin of the drawing
-          operation to the right-most part of the drawn string.
-          The _exact_ width of the string is therefore:
-          rightBearing - leftBearing */
-  
-  nscoord ascent;
-       /* The vertical distance from the origin of the drawing 
-          operation to the top-most part of the drawn string. */
-
-  nscoord descent;
-       /* The vertical distance from the origin of the drawing 
-          operation to the bottom-most part of the drawn string.
-          The _exact_ height of the string is therefore:
-          ascent + descent */
-
-  //////////
-  // Metrics for placing other surrounding text:
-
-  nscoord width;
-       /* The horizontal distance from the origin of the drawing
-          operation to the correct origin for drawing another string
-          to follow the current one. Depending on the font, this
-          could be greater than or less than the right bearing. */
-
-  nsBoundingMetrics() {
-    Clear();
-  }
-
-  //////////
-  // Utility methods and operators:
-
-  /* Set all member data to zero */
-  void 
-  Clear() {
-    leftBearing = rightBearing = 0;
-    ascent = descent = width = 0;
-  }
-
-  /* Append another bounding metrics */
-  void 
-  operator += (const nsBoundingMetrics& bm) {
-    if (ascent + descent == 0 && rightBearing - leftBearing == 0) {
-      ascent = bm.ascent;
-      descent = bm.descent;
-      leftBearing = width + bm.leftBearing;
-      rightBearing = width + bm.rightBearing;
-    }
-    else {
-      if (ascent < bm.ascent) ascent = bm.ascent;
-      if (descent < bm.descent) descent = bm.descent;   
-      leftBearing = PR_MIN(leftBearing, width + bm.leftBearing);
-      rightBearing = PR_MAX(rightBearing, width + bm.rightBearing);
-    }
-    width += bm.width;
-  }
-};
-#endif // MOZ_MATHML
-
-#endif /* nsIRenderingContext_h___ */
deleted file mode 100644
--- a/gfx/src/nsIThebesFontMetrics.h
+++ /dev/null
@@ -1,127 +0,0 @@
-/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Christopher Blizzard <blizzard@mozilla.org>.  
- * Portions created by the Initial Developer are Copyright (C) 2002
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#ifndef __nsIThebesFontMetrics_h
-#define __nsIThebesFontMetrics_h
-
-#include "nsIFontMetrics.h"
-#include "nsIRenderingContext.h"
-
-class nsThebesRenderingContext;
-
-class gfxFontGroup;
-
-class nsIThebesFontMetrics : public nsIFontMetrics {
-public:
-    // Get the width for this string.  aWidth will be updated with the
-    // width in points, not twips.  Callers must convert it if they
-    // want it in another format.
-    virtual nsresult GetWidth(const char* aString, PRUint32 aLength,
-                              nscoord& aWidth, nsThebesRenderingContext *aContext) = 0;
-    virtual nsresult GetWidth(const PRUnichar* aString, PRUint32 aLength,
-                              nscoord& aWidth, PRInt32 *aFontID,
-                              nsThebesRenderingContext *aContext) = 0;
-
-    // Get the text dimensions for this string
-    virtual nsresult GetTextDimensions(const PRUnichar* aString,
-                                       PRUint32 aLength,
-                                       nsTextDimensions& aDimensions, 
-                                       PRInt32* aFontID) = 0;
-    virtual nsresult GetTextDimensions(const char*         aString,
-                                       PRInt32             aLength,
-                                       PRInt32             aAvailWidth,
-                                       PRInt32*            aBreaks,
-                                       PRInt32             aNumBreaks,
-                                       nsTextDimensions&   aDimensions,
-                                       PRInt32&            aNumCharsFit,
-                                       nsTextDimensions&   aLastWordDimensions,
-                                       PRInt32*            aFontID) = 0;
-    virtual nsresult GetTextDimensions(const PRUnichar*    aString,
-                                       PRInt32             aLength,
-                                       PRInt32             aAvailWidth,
-                                       PRInt32*            aBreaks,
-                                       PRInt32             aNumBreaks,
-                                       nsTextDimensions&   aDimensions,
-                                       PRInt32&            aNumCharsFit,
-                                       nsTextDimensions&   aLastWordDimensions,
-                                       PRInt32*            aFontID) = 0;
-
-    // Draw a string using this font handle on the surface passed in.  
-    virtual nsresult DrawString(const char *aString, PRUint32 aLength,
-                                nscoord aX, nscoord aY,
-                                const nscoord* aSpacing,
-                                nsThebesRenderingContext *aContext) = 0;
-    virtual nsresult DrawString(const PRUnichar* aString, PRUint32 aLength,
-                                nscoord aX, nscoord aY,
-                                PRInt32 aFontID,
-                                const nscoord* aSpacing,
-                                nsThebesRenderingContext *aContext) = 0;
-    virtual nsresult DrawString(const PRUnichar* aString, PRUint32 aLength,
-                                nscoord aX, nscoord aY,
-                                nsIRenderingContext *aContext,
-                                nsIRenderingContext *aTextRunConstructionContext) = 0;
-
-#ifdef MOZ_MATHML
-    // These two functions get the bounding metrics for this handle,
-    // updating the aBoundingMetrics in Points.  This means that the
-    // caller will have to update them to twips before passing it
-    // back.
-    virtual nsresult GetBoundingMetrics(const char *aString, PRUint32 aLength,
-                                        nsThebesRenderingContext *aContext,
-                                        nsBoundingMetrics &aBoundingMetrics) = 0;
-    // aCachedOffset will be updated with a new offset.
-    virtual nsresult GetBoundingMetrics(const PRUnichar *aString,
-                                        PRUint32 aLength,
-                                        nsThebesRenderingContext *aContext,
-                                        nsBoundingMetrics &aBoundingMetrics) = 0;
-#endif /* MOZ_MATHML */
-
-    // Set the direction of the text rendering
-    virtual nsresult SetRightToLeftText(PRBool aIsRTL) = 0;
-    virtual PRBool GetRightToLeftText() = 0;
-    virtual void SetTextRunRTL(PRBool aIsRTL) = 0;
-
-    virtual PRInt32 GetMaxStringLength() = 0;
-
-    virtual gfxFontGroup* GetThebesFontGroup() = 0;
-
-    // Needs to be virtual and at this level so that its caller in gkgfx can
-    // avoid linking against thebes.
-    virtual gfxUserFontSet* GetUserFontSet() = 0;
-};
-
-#endif /* __nsIThebesFontMetrics_h */
--- a/gfx/src/nsITheme.h
+++ b/gfx/src/nsITheme.h
@@ -46,17 +46,17 @@
 #include "nsColor.h"
 
 struct nsRect;
 struct nsIntRect;
 struct nsIntSize;
 struct nsFont;
 struct nsIntMargin;
 class nsPresContext;
-class nsIRenderingContext;
+class nsRenderingContext;
 class nsIDeviceContext;
 class nsIFrame;
 class nsIContent;
 class nsIAtom;
 class nsIWidget;
 
 // IID for the nsITheme interface
 // {887e8902-db6b-41b4-8481-a80f49c5a93a}
@@ -90,17 +90,17 @@ public:
   /**
    * Draw the actual theme background.
    * @param aContext the context to draw into
    * @param aFrame the frame for the widget that we're drawing
    * @param aWidgetType the -moz-appearance value to draw
    * @param aRect the rectangle defining the area occupied by the widget
    * @param aDirtyRect the rectangle that needs to be drawn
    */
-  NS_IMETHOD DrawWidgetBackground(nsIRenderingContext* aContext,
+  NS_IMETHOD DrawWidgetBackground(nsRenderingContext* aContext,
                                   nsIFrame* aFrame,
                                   PRUint8 aWidgetType,
                                   const nsRect& aRect,
                                   const nsRect& aDirtyRect) = 0;
 
   /**
    * XXX Unused. This is only here because the interface is frozen for 2.0.
    */
@@ -145,17 +145,17 @@ public:
   { return PR_FALSE; }
 
   /**
    * Get the minimum border-box size of a widget, in *pixels* (in
    * |aResult|).  If |aIsOverridable| is set to true, this size is a
    * minimum size; if false, this size is the only valid size for the
    * widget.
    */
-  NS_IMETHOD GetMinimumWidgetSize(nsIRenderingContext* aContext,
+  NS_IMETHOD GetMinimumWidgetSize(nsRenderingContext* aContext,
                                   nsIFrame* aFrame,
                                   PRUint8 aWidgetType,
                                   nsIntSize* aResult,
                                   PRBool* aIsOverridable)=0;
 
 
   enum Transparency {
     eOpaque = 0,
rename from gfx/src/nsThebesRenderingContext.cpp
rename to gfx/src/nsRenderingContext.cpp
--- a/gfx/src/nsThebesRenderingContext.cpp
+++ b/gfx/src/nsRenderingContext.cpp
@@ -32,64 +32,31 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
-#include "nsThebesRenderingContext.h"
-#include "nsThebesDeviceContext.h"
-
-#include "nsString.h"
-#include "nsTransform2D.h"
-#include "nsIServiceManager.h"
-#include "nsIInterfaceRequestorUtils.h"
-#include "nsGfxCIID.h"
-
-#include "nsThebesRegion.h"
-
-#include <stdlib.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-
-#include "gfxPlatform.h"
-
-#ifdef XP_WIN
-#include "gfxWindowsSurface.h"
-#include "cairo-win32.h"
-#endif
-
-static NS_DEFINE_CID(kRegionCID, NS_REGION_CID);
-
-//////////////////////////////////////////////////////////////////////
+#include "nsRenderingContext.h"
+#include "nsBoundingMetrics.h"
+#include "nsRegion.h"
 
 // XXXTodo: rename FORM_TWIPS to FROM_APPUNITS
 #define FROM_TWIPS(_x)  ((gfxFloat)((_x)/(mP2A)))
 #define FROM_TWIPS_INT(_x)  (NSToIntRound((gfxFloat)((_x)/(mP2A))))
 #define TO_TWIPS(_x)    ((nscoord)((_x)*(mP2A)))
 #define GFX_RECT_FROM_TWIPS_RECT(_r)   (gfxRect(FROM_TWIPS((_r).x), FROM_TWIPS((_r).y), FROM_TWIPS((_r).width), FROM_TWIPS((_r).height)))
 
-//////////////////////////////////////////////////////////////////////
-
-NS_IMPL_ISUPPORTS1(nsThebesRenderingContext, nsIRenderingContext)
-
 // Hard limit substring lengths to 8000 characters ... this lets us statically
 // size the cluster buffer array in FindSafeLength
 #define MAX_GFX_TEXT_BUF_SIZE 8000
-static PRInt32 GetMaxChunkLength(nsThebesRenderingContext* aContext)
-{
-    PRInt32 len = aContext->GetMaxStringLength();
-    return PR_MIN(len, MAX_GFX_TEXT_BUF_SIZE);
-}
 
-static PRInt32 FindSafeLength(nsThebesRenderingContext* aContext,
-                              const PRUnichar *aString, PRUint32 aLength,
+static PRInt32 FindSafeLength(const PRUnichar *aString, PRUint32 aLength,
                               PRUint32 aMaxChunkLength)
 {
     if (aLength <= aMaxChunkLength)
         return aLength;
 
     PRInt32 len = aMaxChunkLength;
 
     // Ensure that we don't break inside a surrogate pair
@@ -102,351 +69,164 @@ static PRInt32 FindSafeLength(nsThebesRe
         // unless there are languages that allow clusters of arbitrary size.
         // If there are and someone feeds us a 500+ character cluster, too
         // bad.
         return aMaxChunkLength;
     }
     return len;
 }
 
-static PRInt32 FindSafeLength(nsThebesRenderingContext* aContext,
-                              const char *aString, PRUint32 aLength,
+static PRInt32 FindSafeLength(const char *aString, PRUint32 aLength,
                               PRUint32 aMaxChunkLength)
 {
     // Since it's ASCII, we don't need to worry about clusters or RTL
     return PR_MIN(aLength, aMaxChunkLength);
 }
 
-nsThebesRenderingContext::nsThebesRenderingContext()
-  : mLineStyle(nsLineStyle_kNone)
-  , mColor(NS_RGB(0,0,0))
-{
-}
-
-nsThebesRenderingContext::~nsThebesRenderingContext()
-{
-}
-
 //////////////////////////////////////////////////////////////////////
-//// nsIRenderingContext
-
-NS_IMETHODIMP
-nsThebesRenderingContext::Init(nsIDeviceContext* aContext, gfxASurface *aThebesSurface)
-{
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::Init ctx %p thebesSurface %p\n", this, aContext, aThebesSurface));
-
-    mDeviceContext = aContext;
-    mWidget = nsnull;
-
-    mThebes = new gfxContext(aThebesSurface);
-
-    return (CommonInit());
-}
+//// nsRenderingContext
 
-NS_IMETHODIMP
-nsThebesRenderingContext::Init(nsIDeviceContext* aContext, gfxContext *aThebesContext)
+void
+nsRenderingContext::Init(nsIDeviceContext* aContext,
+                         gfxASurface *aThebesSurface)
 {
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::Init ctx %p thebesContext %p\n", this, aContext, aThebesContext));
-
-    mDeviceContext = aContext;
-    mWidget = nsnull;
-
-    mThebes = aThebesContext;
-
-    return (CommonInit());
-}
-
-NS_IMETHODIMP
-nsThebesRenderingContext::Init(nsIDeviceContext* aContext, nsIWidget *aWidget)
-{
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::Init ctx %p widget %p\n", this, aContext, aWidget));
-
-    mDeviceContext = aContext;
-    mWidget = aWidget;
-
-    mThebes = new gfxContext(aWidget->GetThebesSurface());
-
-    //mThebes->SetColor(gfxRGBA(0.9, 0.0, 0.0, 0.3));
-    //mThebes->Paint();
-
-    //mThebes->Translate(gfxPoint(300,0));
-    //mThebes->Rotate(M_PI/4);
-
-    return (CommonInit());
+    Init(aContext, new gfxContext(aThebesSurface));
 }
 
-NS_IMETHODIMP
-nsThebesRenderingContext::CommonInit(void)
+void
+nsRenderingContext::Init(nsIDeviceContext* aContext,
+                         gfxContext *aThebesContext)
 {
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::CommonInit\n", this));
+    mDeviceContext = aContext;
+    mThebes = aThebesContext;
 
     mThebes->SetLineWidth(1.0);
-
     mP2A = mDeviceContext->AppUnitsPerDevPixel();
-
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsThebesRenderingContext::GetDeviceContext(nsIDeviceContext *& aDeviceContext)
-{
-    aDeviceContext = mDeviceContext;
-    NS_IF_ADDREF(aDeviceContext);
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsThebesRenderingContext::PushTranslation(PushedTranslation* aState)
-{
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::PushTranslation\n", this));
-
-    // XXX this is slow!
-    PushState();
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsThebesRenderingContext::PopTranslation(PushedTranslation* aState)
-{
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::PopTranslation\n", this));
-
-    // XXX this is slow!
-    PopState();
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsThebesRenderingContext::SetTranslation(nscoord aX, nscoord aY)
-{
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::SetTranslation %d %d\n", this, aX, aY));
-
-    gfxMatrix newMat(mThebes->CurrentMatrix());
-    newMat.x0 = aX;
-    newMat.y0 = aY;
-    mThebes->SetMatrix(newMat);
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsThebesRenderingContext::PushState()
-{
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::PushState\n", this));
-
-    mThebes->Save();
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsThebesRenderingContext::PopState()
-{
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::PopState\n", this));
-
-    mThebes->Restore();
-    return NS_OK;
 }
 
 //
-// clipping
+// graphics state
 //
 
-NS_IMETHODIMP
-nsThebesRenderingContext::SetClipRect(const nsRect& aRect,
-                                      nsClipCombine aCombine)
+void
+nsRenderingContext::PushState()
 {
-    //return NS_OK;
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::SetClipRect [%d,%d,%d,%d] %d\n", this, aRect.x, aRect.y, aRect.width, aRect.height, aCombine));
+    mThebes->Save();
+}
 
-    if (aCombine == nsClipCombine_kReplace) {
-        mThebes->ResetClip();
-    } else if (aCombine != nsClipCombine_kIntersect) {
-        NS_WARNING("Unexpected usage of SetClipRect");
-    }
+void
+nsRenderingContext::PopState()
+{
+    mThebes->Restore();
+}
 
+void
+nsRenderingContext::IntersectClip(const nsRect& aRect)
+{
     mThebes->NewPath();
     gfxRect clipRect(GFX_RECT_FROM_TWIPS_RECT(aRect));
     if (mThebes->UserToDevicePixelSnapped(clipRect, PR_TRUE)) {
         gfxMatrix mat(mThebes->CurrentMatrix());
         mThebes->IdentityMatrix();
         mThebes->Rectangle(clipRect);
         mThebes->SetMatrix(mat);
     } else {
         mThebes->Rectangle(clipRect);
     }
 
     mThebes->Clip();
-
-    return NS_OK;
 }
 
-NS_IMETHODIMP
-nsThebesRenderingContext::SetClipRegion(const nsIntRegion& aRegion,
-                                        nsClipCombine aCombine)
+void
+nsRenderingContext::SetClip(const nsIntRegion& aRegion)
 {
-    // Region is in device coords, no transformation.
-    // This should only be called when there is no transform in place, when we
-    // we just start painting a widget. The region is set by the platform paint
-    // routine.
-    NS_ASSERTION(aCombine == nsClipCombine_kReplace,
-                 "Unexpected usage of SetClipRegion");
+    // Region is in device coords, no transformation.  This should
+    // only be called when there is no transform in place, when we we
+    // just start painting a widget. The region is set by the platform
+    // paint routine.  Therefore, there is no option to intersect with
+    // an existing clip.
 
     gfxMatrix mat = mThebes->CurrentMatrix();
     mThebes->IdentityMatrix();
 
     mThebes->ResetClip();
-    
+
     mThebes->NewPath();
     nsIntRegionRectIterator iter(aRegion);
     const nsIntRect* rect;
     while ((rect = iter.Next())) {
         mThebes->Rectangle(gfxRect(rect->x, rect->y, rect->width, rect->height),
                            PR_TRUE);
     }
     mThebes->Clip();
-
     mThebes->SetMatrix(mat);
-
-    return NS_OK;
 }
 
-//
-// other junk
-//
-
-NS_IMETHODIMP
-nsThebesRenderingContext::SetLineStyle(nsLineStyle aLineStyle)
+void
+nsRenderingContext::SetLineStyle(nsLineStyle aLineStyle)
 {
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::SetLineStyle %d\n", this, aLineStyle));
     switch (aLineStyle) {
         case nsLineStyle_kSolid:
             mThebes->SetDash(gfxContext::gfxLineSolid);
             break;
         case nsLineStyle_kDashed:
             mThebes->SetDash(gfxContext::gfxLineDashed);
             break;
         case nsLineStyle_kDotted:
             mThebes->SetDash(gfxContext::gfxLineDotted);
             break;
         case nsLineStyle_kNone:
         default:
             // nothing uses kNone
             NS_ERROR("SetLineStyle: Invalid line style");
             break;
     }
-
-    mLineStyle = aLineStyle;
-    return NS_OK;
 }
 
 
-NS_IMETHODIMP
-nsThebesRenderingContext::SetColor(nscolor aColor)
+void
+nsRenderingContext::SetColor(nscolor aColor)
 {
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::SetColor 0x%08x\n", this, aColor));
-    /* This sets the color assuming the sRGB color space, since that's what all
-     * CSS colors are defined to be in by the spec.
+    /* This sets the color assuming the sRGB color space, since that's
+     * what all CSS colors are defined to be in by the spec.
      */
     mThebes->SetColor(gfxRGBA(aColor));
-
-    mColor = aColor;
-    return NS_OK;
 }
 
-NS_IMETHODIMP
-nsThebesRenderingContext::GetColor(nscolor &aColor) const
-{
-    aColor = mColor;
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsThebesRenderingContext::Translate(nscoord aX, nscoord aY)
+void
+nsRenderingContext::Translate(const nsPoint& aPt)
 {
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::Translate %d %d\n", this, aX, aY));
-    mThebes->Translate (gfxPoint(FROM_TWIPS(aX), FROM_TWIPS(aY)));
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsThebesRenderingContext::Scale(float aSx, float aSy)
-{
-    // as far as I can tell, noone actually calls this
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::Scale %f %f\n", this, aSx, aSy));
-    mThebes->Scale (aSx, aSy);
-    return NS_OK;
+    mThebes->Translate(gfxPoint(FROM_TWIPS(aPt.x), FROM_TWIPS(aPt.y)));
 }
 
 void
-nsThebesRenderingContext::UpdateTempTransformMatrix()
+nsRenderingContext::Scale(float aSx, float aSy)
 {
-    //PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::UpdateTempTransformMatrix\n", this));
-
-    /*****
-     * Thebes matrix layout:   gfx matrix layout:
-     * | xx yx 0 |            | m00 m01  0 |
-     * | xy yy 0 |            | m10 m11  0 |
-     * | x0 y0 1 |            | m20 m21  1 |
-     *****/
-
-    const gfxMatrix& ctm = mThebes->CurrentMatrix();
-    NS_ASSERTION(ctm.yx == 0 && ctm.xy == 0, "Can't represent Thebes matrix to Gfx");
-    mTempTransform.SetToTranslate(TO_TWIPS(ctm.x0), TO_TWIPS(ctm.y0));
-    mTempTransform.AddScale(ctm.xx, ctm.yy);
+    mThebes->Scale(aSx, aSy);
 }
 
-nsTransform2D&
-nsThebesRenderingContext::CurrentTransform()
-{
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::CurrentTransform\n", this));
-    UpdateTempTransformMatrix();
-    return mTempTransform;
-}
+//
+// shapes
+//
 
-/****
- **** XXXXXX
- ****
- **** On other gfx implementations, the transform returned by this
- **** has a built in twips to pixels ratio.  That is, you pass in
- **** twips to any nsTransform2D TransformCoord method, and you
- **** get back pixels.  This makes no sense.  We don't do this.
- **** This in turn breaks SVG and <object>; those should just be
- **** fixed to not use this!
- ****/
-
-NS_IMETHODIMP
-nsThebesRenderingContext::GetCurrentTransform(nsTransform2D *&aTransform)
+void
+nsRenderingContext::DrawLine(const nsPoint& aStartPt, const nsPoint& aEndPt)
 {
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::GetCurrentTransform\n", this));
-    UpdateTempTransformMatrix();
-    aTransform = &mTempTransform;
-    return NS_OK;
+    DrawLine(aStartPt.x, aStartPt.y, aEndPt.x, aEndPt.y);
 }
 
 void
-nsThebesRenderingContext::TransformCoord (nscoord *aX, nscoord *aY)
+nsRenderingContext::DrawLine(nscoord aX0, nscoord aY0,
+                             nscoord aX1, nscoord aY1)
 {
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::TransformCoord\n", this));
-
-    gfxPoint pt(FROM_TWIPS(*aX), FROM_TWIPS(*aY));
-
-    pt = mThebes->UserToDevice (pt);
-
-    *aX = TO_TWIPS(pt.x);
-    *aY = TO_TWIPS(pt.y);
-}
-
-NS_IMETHODIMP
-nsThebesRenderingContext::DrawLine(nscoord aX0, nscoord aY0, nscoord aX1, nscoord aY1)
-{
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::DrawLine %d %d %d %d\n", this, aX0, aY0, aX1, aY1));
-
     gfxPoint p0 = gfxPoint(FROM_TWIPS(aX0), FROM_TWIPS(aY0));
     gfxPoint p1 = gfxPoint(FROM_TWIPS(aX1), FROM_TWIPS(aY1));
 
-    // we can't draw thick lines with gfx, so we always assume we want pixel-aligned
-    // lines if the rendering context is at 1.0 scale
+    // we can't draw thick lines with gfx, so we always assume we want
+    // pixel-aligned lines if the rendering context is at 1.0 scale
     gfxMatrix savedMatrix = mThebes->CurrentMatrix();
     if (!savedMatrix.HasNonTranslation()) {
         p0 = mThebes->UserToDevice(p0);
         p1 = mThebes->UserToDevice(p1);
 
         p0.Round();
         p1.Round();
 
@@ -468,37 +248,31 @@ nsThebesRenderingContext::DrawLine(nscoo
         mThebes->Stroke();
 
         mThebes->SetMatrix(savedMatrix);
     } else {
         mThebes->NewPath();
         mThebes->Line(p0, p1);
         mThebes->Stroke();
     }
-
-    return NS_OK;
 }
 
-NS_IMETHODIMP
-nsThebesRenderingContext::DrawRect(const nsRect& aRect)
+void
+nsRenderingContext::DrawRect(const nsRect& aRect)
 {
-    PR_LOG(gThebesGFXLog, PR_LOG_DEBUG, ("## %p nsTRC::DrawRect [%d,%d,%d,%d]\n", this, aRect.x, aRect.y, aRect.width, aRect.height));
-
     mThebes->NewPath();
     mThebes->Rectangle(GFX_RECT_FROM_TWIPS_RECT(aRect), PR_TRUE);
     mThebes->Stroke();
-