merge the last green changeset on m-c to fx-team
authorTim Taubert <tim.taubert@gmx.de>
Mon, 01 Aug 2011 23:45:17 +0200
changeset 74438 5dcdaeb9e25318a82e0234d2c77404cfc3e6bd89
parent 74437 30e5fe8a62c2a9f31c334ccdf3faed7db19f636f (current diff)
parent 74389 345ba237404d2ae78f4a4629799f9fc47a65ee2c (diff)
child 74439 968f8f50e4280a312f1130bf946470fc1b0f4cea
push id235
push userbzbarsky@mozilla.com
push dateTue, 27 Sep 2011 17:13:04 +0000
treeherdermozilla-beta@2d1e082d176a [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone8.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 the last green changeset on m-c to fx-team
content/html/document/src/nsHTMLFragmentContentSink.cpp
--- a/accessible/src/atk/nsAccessibleWrap.cpp
+++ b/accessible/src/atk/nsAccessibleWrap.cpp
@@ -62,16 +62,18 @@
 #include "nsMaiInterfaceHypertext.h"
 #include "nsMaiInterfaceHyperlinkImpl.h"
 #include "nsMaiInterfaceTable.h"
 #include "nsXPCOMStrings.h"
 #include "nsComponentManagerUtils.h"
 #include "nsMaiInterfaceDocument.h"
 #include "nsMaiInterfaceImage.h"
 
+using namespace mozilla::a11y;
+
 nsAccessibleWrap::EAvailableAtkSignals nsAccessibleWrap::gAvailableAtkSignals =
   eUnknown;
 
 //defined in nsApplicationAccessibleWrap.cpp
 extern "C" GType g_atk_hyperlink_impl_type;
 
 /* MaiAtkObject */
 
--- a/accessible/src/base/AccGroupInfo.cpp
+++ b/accessible/src/base/AccGroupInfo.cpp
@@ -34,16 +34,18 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "AccGroupInfo.h"
 
 #include "States.h"
 
+using namespace mozilla::a11y;
+
 AccGroupInfo::AccGroupInfo(nsAccessible* aItem, PRUint32 aRole) :
   mPosInSet(0), mSetSize(0), mParent(nsnull)
 {
   MOZ_COUNT_CTOR(AccGroupInfo);
   nsAccessible* parent = aItem->Parent();
   if (!parent)
     return;
 
--- a/accessible/src/base/Makefile.in
+++ b/accessible/src/base/Makefile.in
@@ -82,17 +82,22 @@ CPPSRCS = \
 
 EXPORTS = \
   a11yGeneric.h \
   nsAccDocManager.h \
   nsAccessibilityService.h \
   nsAccessible.h \
   nsAccessNode.h \
   nsARIAMap.h \
-	States.h \
+  $(NULL)
+
+EXPORTS_NAMESPACES = mozilla/a11y
+
+EXPORTS_mozilla/a11y = \
+  States.h \
   $(NULL)
 
 # we don't want the shared lib, but we want to force the creation of a static lib.
 FORCE_STATIC_LIB = 1
 
 include $(topsrcdir)/config/rules.mk
 
 LOCAL_INCLUDES += \
--- a/accessible/src/base/States.h
+++ b/accessible/src/base/States.h
@@ -37,16 +37,18 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _states_h_
 #define _states_h_
 
 #include <prtypes.h>
 
+namespace mozilla {
+namespace a11y {
 namespace states {
 
   /**
    * The object is disabled, opposite to enabled and sensitive.
    */
   const PRUint64 UNAVAILABLE = ((PRUint64) 0x1) << 0;
 
   /**
@@ -298,12 +300,14 @@ namespace states {
    */
   const PRUint64 SENSITIVE = ((PRUint64) 0x1) << 45;
 
   /**
    * The object is expandable, provides a UI to expand/collapse its children
    * @see EXPANDED and COLLAPSED states.
    */
   const PRUint64 EXPANDABLE = ((PRUint64) 0x1) << 46;
-}
+} // namespace states
+} // namespace a11y
+} // namespace mozilla
 
 #endif
 	
--- a/accessible/src/base/filters.cpp
+++ b/accessible/src/base/filters.cpp
@@ -36,16 +36,18 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "filters.h"
 
 #include "nsAccessible.h"
 #include "nsAccUtils.h"
 #include "States.h"
 
+using namespace mozilla::a11y;
+
 bool
 filters::GetSelected(nsAccessible* aAccessible)
 {
   return aAccessible->State() & states::SELECTED;
 }
 
 bool
 filters::GetSelectable(nsAccessible* aAccessible)
--- a/accessible/src/base/nsARIAGridAccessible.cpp
+++ b/accessible/src/base/nsARIAGridAccessible.cpp
@@ -40,16 +40,18 @@
 
 #include "AccIterator.h"
 #include "nsAccUtils.h"
 #include "States.h"
 
 #include "nsIMutableArray.h"
 #include "nsComponentManagerUtils.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsARIAGridAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 
 ////////////////////////////////////////////////////////////////////////////////
 // Constructor
 
--- a/accessible/src/base/nsARIAMap.cpp
+++ b/accessible/src/base/nsARIAMap.cpp
@@ -40,16 +40,18 @@
 #include "nsARIAMap.h"
 
 #include "nsIAccessibleRole.h"
 #include "States.h"
 
 #include "nsAccessibilityAtoms.h"
 #include "nsIContent.h"
 
+using namespace mozilla::a11y;
+
 /**
  *  This list of WAI-defined roles are currently hardcoded.
  *  Eventually we will most likely be loading an RDF resource that contains this information
  *  Using RDF will also allow for role extensibility. See bug 280138.
  *
  *  Definition of nsRoleMapEntry and nsStateMapEntry contains comments explaining this table.
  *
  *  When no nsIAccessibleRole enum mapping exists for an ARIA role, the
--- a/accessible/src/base/nsAccDocManager.cpp
+++ b/accessible/src/base/nsAccDocManager.cpp
@@ -52,16 +52,18 @@
 #include "nsIDOMDocument.h"
 #include "nsEventListenerManager.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIDOMWindow.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIWebNavigation.h"
 #include "nsServiceManagerUtils.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccDocManager
 ////////////////////////////////////////////////////////////////////////////////
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccDocManager public
 
 nsDocAccessible*
--- a/accessible/src/base/nsAccUtils.cpp
+++ b/accessible/src/base/nsAccUtils.cpp
@@ -52,16 +52,18 @@
 #include "nsXULTreeGridAccessible.h"
 
 #include "nsIDOMXULContainerElement.h"
 #include "nsIDOMXULSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsWhitespaceTokenizer.h"
 #include "nsComponentManagerUtils.h"
 
+using namespace mozilla::a11y;
+
 void
 nsAccUtils::GetAccAttr(nsIPersistentProperties *aAttributes,
                        nsIAtom *aAttrName, nsAString& aAttrValue)
 {
   aAttrValue.Truncate();
 
   aAttributes->GetStringProperty(nsAtomCString(aAttrName), aAttrValue);
 }
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -103,16 +103,18 @@
 #ifndef DISABLE_XFORMS_HOOKS
 #include "nsXFormsFormControlsAccessible.h"
 #include "nsXFormsWidgetsAccessible.h"
 #endif
 
 #include "mozilla/FunctionTimer.h"
 #include "mozilla/dom/Element.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessibilityService
 ////////////////////////////////////////////////////////////////////////////////
 
 nsAccessibilityService *nsAccessibilityService::gAccessibilityService = nsnull;
 PRBool nsAccessibilityService::gIsShutdown = PR_TRUE;
 
 nsAccessibilityService::nsAccessibilityService() : nsAccDocManager()
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -103,16 +103,17 @@
 #include "nsIDOMCharacterData.h"
 #endif
 
 #include "mozilla/unused.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/Element.h"
 
 using namespace mozilla;
+using namespace mozilla::a11y;
 
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessible. nsISupports
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsAccessible)
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsAccessible, nsAccessNode)
@@ -718,32 +719,43 @@ nsAccessible::NativeState()
   if (nsCoreUtils::IsXLink(mContent))
     state |= states::LINKED;
 
   return state;
 }
 
   /* readonly attribute boolean focusedChild; */
 NS_IMETHODIMP
-nsAccessible::GetFocusedChild(nsIAccessible **aFocusedChild) 
-{ 
-  nsAccessible *focusedChild = nsnull;
-  if (gLastFocusedNode == mContent) {
-    focusedChild = this;
-  }
-  else if (gLastFocusedNode) {
-    focusedChild = GetAccService()->GetAccessible(gLastFocusedNode);
-    if (focusedChild && focusedChild->Parent() != this)
-      focusedChild = nsnull;
-  }
-
-  NS_IF_ADDREF(*aFocusedChild = focusedChild);
+nsAccessible::GetFocusedChild(nsIAccessible** aChild)
+{
+  NS_ENSURE_ARG_POINTER(aChild);
+  *aChild = nsnull;
+
+  if (IsDefunct())
+    return NS_ERROR_FAILURE;
+
+  NS_IF_ADDREF(*aChild = FocusedChild());
   return NS_OK;
 }
 
+nsAccessible*
+nsAccessible::FocusedChild()
+{
+  if (!gLastFocusedNode)
+    return nsnull;
+  if (gLastFocusedNode == mContent)
+    return this;
+
+  nsAccessible* focusedChild = GetDocAccessible()->GetAccessible(gLastFocusedNode);
+  if (!focusedChild || focusedChild->Parent() != this)
+    return nsnull;
+
+  return focusedChild;
+}
+
 // nsAccessible::ChildAtPoint()
 nsAccessible*
 nsAccessible::ChildAtPoint(PRInt32 aX, PRInt32 aY,
                            EWhichChildAtPoint aWhichChild)
 {
   // If we can't find the point in a child, we will return the fallback answer:
   // we return |this| if the point is within it, otherwise nsnull.
   PRInt32 x = 0, y = 0, width = 0, height = 0;
--- a/accessible/src/base/nsAccessible.h
+++ b/accessible/src/base/nsAccessible.h
@@ -35,17 +35,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _nsAccessible_H_
 #define _nsAccessible_H_
 
 #include "nsAccessNodeWrap.h"
-#include "States.h"
+#include "mozilla/a11y/States.h"
 
 #include "nsIAccessible.h"
 #include "nsIAccessibleHyperLink.h"
 #include "nsIAccessibleSelectable.h"
 #include "nsIAccessibleValue.h"
 #include "nsIAccessibleRole.h"
 #include "nsIAccessibleStates.h"
 
@@ -213,16 +213,21 @@ public:
    * @param  aY           [in] y coordinate relative screen
    * @param  aWhichChild  [in] flag points if deepest or direct child
    *                        should be returned
    */
   virtual nsAccessible* ChildAtPoint(PRInt32 aX, PRInt32 aY,
                                      EWhichChildAtPoint aWhichChild);
 
   /**
+   * Return the focused child if any.
+   */
+  virtual nsAccessible* FocusedChild();
+
+  /**
    * Return calculated group level based on accessible hierarchy.
    */
   virtual PRInt32 GetLevelInternal();
 
   /**
    * Calculate position in group and group size ('posinset' and 'setsize') based
    * on accessible hierarchy.
    *
@@ -448,17 +453,17 @@ public:
   inline bool IsLinkValid()
   {
     NS_PRECONDITION(IsLink(), "IsLinkValid is called on not hyper link!");
 
     // XXX In order to implement this we would need to follow every link
     // Perhaps we can get information about invalid links from the cache
     // In the mean time authors can use role="link" aria-invalid="true"
     // to force it for links they internally know to be invalid
-    return (0 == (State() & states::INVALID));
+    return (0 == (State() & mozilla::a11y::states::INVALID));
   }
 
   /**
    * Return true if the link currently has the focus.
    */
   inline bool IsLinkSelected()
   {
     NS_PRECONDITION(IsLink(),
--- a/accessible/src/base/nsApplicationAccessible.cpp
+++ b/accessible/src/base/nsApplicationAccessible.cpp
@@ -48,16 +48,18 @@
 
 #include "nsIComponentManager.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMWindow.h"
 #include "nsIWindowMediator.h"
 #include "nsServiceManagerUtils.h"
 #include "mozilla/Services.h"
 
+using namespace mozilla::a11y;
+
 nsApplicationAccessible::nsApplicationAccessible() :
   nsAccessibleWrap(nsnull, nsnull)
 {
   mFlags |= eApplicationAccessible;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsISupports
--- a/accessible/src/base/nsBaseWidgetAccessible.cpp
+++ b/accessible/src/base/nsBaseWidgetAccessible.cpp
@@ -48,16 +48,18 @@
 
 #include "nsIDOMNSHTMLElement.h"
 #include "nsGUIEvent.h"
 #include "nsILink.h"
 #include "nsIFrame.h"
 #include "nsINameSpaceManager.h"
 #include "nsIURI.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsLeafAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsLeafAccessible::
   nsLeafAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -73,16 +73,17 @@
 #include "nsIWebNavigation.h"
 #include "nsFocusManager.h"
 #include "mozilla/dom/Element.h"
 #ifdef MOZ_XUL
 #include "nsIXULDocument.h"
 #endif
 
 namespace dom = mozilla::dom;
+using namespace mozilla::a11y;
 
 ////////////////////////////////////////////////////////////////////////////////
 // Static member initialization
 
 PRUint64 nsDocAccessible::gLastFocusedAccessiblesState = 0;
 
 static nsIAtom** kRelationAttrs[] =
 {
@@ -344,28 +345,25 @@ nsDocAccessible::GetAttributes(nsIPersis
 {
   nsAccessible::GetAttributes(aAttributes);
   if (mParent) {
     mParent->GetAttributes(aAttributes); // Add parent attributes (override inner)
   }
   return NS_OK;
 }
 
-NS_IMETHODIMP nsDocAccessible::GetFocusedChild(nsIAccessible **aFocusedChild)
+nsAccessible*
+nsDocAccessible::FocusedChild()
 {
   // XXXndeakin P3 accessibility shouldn't be caching the focus
-  if (!gLastFocusedNode) {
-    *aFocusedChild = nsnull;
-    return NS_OK;
-  }
 
   // Return an accessible for the current global focus, which does not have to
   // be contained within the current document.
-  NS_IF_ADDREF(*aFocusedChild = GetAccService()->GetAccessible(gLastFocusedNode));
-  return NS_OK;
+  return gLastFocusedNode ? GetAccService()->GetAccessible(gLastFocusedNode) :
+    nsnull;
 }
 
 NS_IMETHODIMP nsDocAccessible::TakeFocus()
 {
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   PRUint64 state = NativeState();
--- a/accessible/src/base/nsDocAccessible.h
+++ b/accessible/src/base/nsDocAccessible.h
@@ -89,17 +89,16 @@ public:
 
   nsDocAccessible(nsIDocument *aDocument, nsIContent *aRootContent,
                   nsIWeakReference* aShell);
   virtual ~nsDocAccessible();
 
   // nsIAccessible
   NS_IMETHOD GetName(nsAString& aName);
   NS_IMETHOD GetAttributes(nsIPersistentProperties **aAttributes);
-  NS_IMETHOD GetFocusedChild(nsIAccessible **aFocusedChild);
   NS_IMETHOD TakeFocus(void);
 
   // nsIScrollPositionListener
   virtual void ScrollPositionWillChange(nscoord aX, nscoord aY) {}
   virtual void ScrollPositionDidChange(nscoord aX, nscoord aY);
 
   // nsIDocumentObserver
   NS_DECL_NSIDOCUMENTOBSERVER
@@ -109,16 +108,17 @@ public:
   virtual void Shutdown();
   virtual nsIFrame* GetFrame() const;
   virtual bool IsDefunct() const;
   virtual nsINode* GetNode() const { return mDocument; }
   virtual nsIDocument* GetDocumentNode() const { return mDocument; }
 
   // nsAccessible
   virtual void Description(nsString& aDescription);
+  virtual nsAccessible* FocusedChild();
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
   virtual void ApplyARIAState(PRUint64* aState);
 
   virtual void SetRoleMapEntry(nsRoleMapEntry* aRoleMapEntry);
 
 #ifdef DEBUG_ACCDOCMGR
   virtual nsresult HandleAccEvent(AccEvent* aAccEvent);
--- a/accessible/src/base/nsOuterDocAccessible.cpp
+++ b/accessible/src/base/nsOuterDocAccessible.cpp
@@ -37,16 +37,18 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsOuterDocAccessible.h"
 
 #include "States.h"
 #include "nsAccUtils.h"
 #include "nsDocAccessible.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsOuterDocAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsOuterDocAccessible::
   nsOuterDocAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/base/nsRootAccessible.cpp
+++ b/accessible/src/base/nsRootAccessible.cpp
@@ -81,16 +81,17 @@
 
 #ifdef MOZ_XUL
 #include "nsXULTreeAccessible.h"
 #include "nsIXULDocument.h"
 #include "nsIXULWindow.h"
 #endif
 
 using namespace mozilla;
+using namespace mozilla::a11y;
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsISupports
 
 // Expanded version of NS_IMPL_ISUPPORTS_INHERITED2 
 // so we can QI directly to concrete nsRootAccessible
 NS_IMPL_QUERY_HEAD(nsRootAccessible)
 NS_IMPL_QUERY_BODY(nsIDOMEventListener)
--- a/accessible/src/html/nsHTMLFormControlAccessible.cpp
+++ b/accessible/src/html/nsHTMLFormControlAccessible.cpp
@@ -55,16 +55,18 @@
 #include "nsIFrame.h"
 #include "nsINameSpaceManager.h"
 #include "nsISelectionController.h"
 #include "jsapi.h"
 #include "nsIJSContextStack.h"
 #include "nsIServiceManager.h"
 #include "nsITextControlFrame.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLCheckboxAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLCheckboxAccessible::
   nsHTMLCheckboxAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsFormControlAccessible(aContent, aShell)
 {
--- a/accessible/src/html/nsHTMLImageAccessible.cpp
+++ b/accessible/src/html/nsHTMLImageAccessible.cpp
@@ -48,16 +48,18 @@
 #include "nsIImageLoadingContent.h"
 #include "nsILink.h"
 #include "nsIPresShell.h"
 #include "nsIServiceManager.h"
 #include "nsIDOMHTMLImageElement.h"
 #include "nsIDOMDocument.h"
 #include "nsPIDOMWindow.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLImageAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLImageAccessible::
   nsHTMLImageAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsLinkableAccessible(aContent, aShell)
 {
--- a/accessible/src/html/nsHTMLLinkAccessible.cpp
+++ b/accessible/src/html/nsHTMLLinkAccessible.cpp
@@ -40,16 +40,18 @@
 #include "nsHTMLLinkAccessible.h"
 
 #include "States.h"
 #include "nsCoreUtils.h"
 
 #include "nsEventStates.h"
 #include "mozilla/dom/Element.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLLinkAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLLinkAccessible::
   nsHTMLLinkAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsHyperTextAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/html/nsHTMLSelectAccessible.cpp
+++ b/accessible/src/html/nsHTMLSelectAccessible.cpp
@@ -52,16 +52,18 @@
 #include "nsIDocument.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIDOMHTMLOptGroupElement.h"
 #include "nsIDOMHTMLSelectElement.h"
 #include "nsIListControlFrame.h"
 #include "nsIServiceManager.h"
 #include "nsIMutableArray.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLSelectListAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLSelectListAccessible::
   nsHTMLSelectListAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/html/nsHTMLTableAccessible.cpp
+++ b/accessible/src/html/nsHTMLTableAccessible.cpp
@@ -61,16 +61,18 @@
 #include "nsIDocument.h"
 #include "nsIPresShell.h"
 #include "nsITableLayout.h"
 #include "nsITableCellLayout.h"
 #include "nsFrameSelection.h"
 #include "nsLayoutErrors.h"
 #include "nsArrayUtils.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLTableCellAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLTableCellAccessible::
   nsHTMLTableCellAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsHyperTextAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/html/nsHTMLTextAccessible.cpp
+++ b/accessible/src/html/nsHTMLTextAccessible.cpp
@@ -47,16 +47,18 @@
 
 #include "nsIFrame.h"
 #include "nsPresContext.h"
 #include "nsBlockFrame.h"
 #include "nsISelection.h"
 #include "nsISelectionController.h"
 #include "nsComponentManagerUtils.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLTextAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLTextAccessible::
   nsHTMLTextAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsTextAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/html/nsHyperTextAccessible.cpp
+++ b/accessible/src/html/nsHyperTextAccessible.cpp
@@ -61,16 +61,18 @@
 #include "nsIPlaintextEditor.h"
 #include "nsIScrollableFrame.h"
 #include "nsISelection2.h"
 #include "nsISelectionPrivate.h"
 #include "nsIServiceManager.h"
 #include "nsTextFragment.h"
 #include "gfxSkipChars.h"
 
+using namespace mozilla::a11y;
+
 static NS_DEFINE_IID(kRangeCID, NS_RANGE_CID);
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsHyperTextAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHyperTextAccessible::
   nsHyperTextAccessible(nsIContent *aNode, nsIWeakReference *aShell) :
--- a/accessible/src/mac/mozAccessible.mm
+++ b/accessible/src/mac/mozAccessible.mm
@@ -47,16 +47,18 @@
 #include "nsObjCExceptions.h"
 
 #include "nsIAccessible.h"
 #include "nsIAccessibleText.h"
 #include "nsIAccessibleEditableText.h"
 
 #include "nsRootAccessible.h"
 
+using namespace mozilla::a11y;
+
 // These constants are only defined in OS X SDK 10.4, so we define them in order
 // to be able to use for earlier OS versions.
 const NSString *kInstanceDescriptionAttribute = @"AXDescription";       // NSAccessibilityDescriptionAttribute
 const NSString *kTopLevelUIElementAttribute   = @"AXTopLevelUIElement"; // NSAccessibilityTopLevelUIElementAttribute
 const NSString *kTextLinkSubrole              = @"AXTextLink";          // NSAccessibilitySecureTextFieldSubrole
 const NSString *kURLAttribute                 = @"AXURL";
 
 // converts a screen-global point in the cocoa coordinate system (with origo in the bottom-left corner
@@ -329,19 +331,17 @@ GetNativeFromGeckoAccessible(nsIAccessib
 {
 }
 
 - (id)accessibilityFocusedUIElement
 {
   if (mIsExpired)
     return nil;
   
-  nsCOMPtr<nsIAccessible> focusedGeckoChild;
-  mGeckoAccessible->GetFocusedChild (getter_AddRefs (focusedGeckoChild));
-  
+  nsAccessible* focusedGeckoChild = mGeckoAccessible->FocusedChild();
   if (focusedGeckoChild) {
     mozAccessible *focusedChild = GetNativeFromGeckoAccessible(focusedGeckoChild);
     if (focusedChild)
       return GetClosestInterestingAccessible(focusedChild);
   }
   
   // return ourself if we can't get a native focused child.
   return GetClosestInterestingAccessible(self);
--- a/accessible/src/mac/mozActionElements.mm
+++ b/accessible/src/mac/mozActionElements.mm
@@ -36,16 +36,18 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #import "mozActionElements.h"
 #import "nsIAccessible.h"
 
 #include "nsObjCExceptions.h"
 
+using namespace mozilla::a11y;
+
 extern const NSString *kInstanceDescriptionAttribute; // NSAccessibilityDescriptionAttribute
 extern const NSString *kTopLevelUIElementAttribute;   // NSAccessibilityTopLevelUIElementAttribute
 
 enum CheckboxValue {
   // these constants correspond to the values in the OS
   kUnchecked = 0,
   kChecked = 1,
   kMixed = 2
--- a/accessible/src/mac/mozTextAccessible.mm
+++ b/accessible/src/mac/mozTextAccessible.mm
@@ -1,13 +1,15 @@
 #include "nsAccessibleWrap.h"
 #include "nsObjCExceptions.h"
 
 #import "mozTextAccessible.h"
 
+using namespace mozilla::a11y;
+
 extern const NSString *kInstanceDescriptionAttribute; // NSAccessibilityDescriptionAttribute
 extern const NSString *kTopLevelUIElementAttribute;   // NSAccessibilityTopLevelUIElementAttribute
 
 @interface mozTextAccessible (Private)
 - (NSString*)subrole;
 - (NSString*)selectedText;
 - (NSValue*)selectedTextRange;
 - (long)textLength;
--- a/accessible/src/mac/nsAccessibleWrap.h
+++ b/accessible/src/mac/nsAccessibleWrap.h
@@ -81,17 +81,17 @@ class nsAccessibleWrap : public nsAccess
 
     // ignored means that the accessible might still have children, but is not displayed
     // to the user. it also has no native accessible object represented for it.
     PRBool IsIgnored();
     
     PRInt32 GetUnignoredChildCount(PRBool aDeepCount);
     
     PRBool HasPopup () {
-      return (NativeState() & states::HASPOPUP);
+      return (NativeState() & mozilla::a11y::states::HASPOPUP);
     }
     
     // return this accessible's all children, adhering to "flat" accessibles by not returning their children.
     void GetUnignoredChildren(nsTArray<nsRefPtr<nsAccessibleWrap> > &aChildrenArray);
     virtual already_AddRefed<nsIAccessible> GetUnignoredParent();
     
   protected:
 
--- a/accessible/src/msaa/CAccessibleComponent.cpp
+++ b/accessible/src/msaa/CAccessibleComponent.cpp
@@ -45,16 +45,18 @@
 #include "nsAccessible.h"
 #include "States.h"
 
 #include "nsString.h"
 
 #include "nsIDOMCSSPrimitiveValue.h"
 #include "nsIDOMNSRGBAColor.h"
 
+using namespace mozilla::a11y;
+
 enum {
   IA2AlphaShift = 24,
   IA2RedShift = 16,
   IA2GreenShift = 8,
   IA2BlueShift = 0
 };
 
 // IUnknown
--- a/accessible/src/msaa/nsAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsAccessibleWrap.cpp
@@ -62,16 +62,18 @@
 #include "nsIServiceManager.h"
 #include "nsTextFormatter.h"
 #include "nsIView.h"
 #include "nsIViewManager.h"
 #include "nsRoleMap.h"
 #include "nsEventMap.h"
 #include "nsArrayUtils.h"
 
+using namespace mozilla::a11y;
+
 /* For documentation of the accessibility architecture,
  * see http://lxr.mozilla.org/seamonkey/source/accessible/accessible-docs.html
  */
 
 //#define DEBUG_LEAKS
 
 #ifdef DEBUG_LEAKS
 static gAccessibles = 0;
@@ -517,18 +519,17 @@ STDMETHODIMP nsAccessibleWrap::get_accFo
   //              for the child object with the keyboard focus.
 __try {
   if (IsDefunct())
     return E_FAIL;
 
   VariantInit(pvarChild);
 
   // Return the current IAccessible child that has focus
-  nsCOMPtr<nsIAccessible> focusedAccessible;
-  GetFocusedChild(getter_AddRefs(focusedAccessible));
+  nsAccessible* focusedAccessible = FocusedChild();
   if (focusedAccessible == this) {
     pvarChild->vt = VT_I4;
     pvarChild->lVal = CHILDID_SELF;
   }
   else if (focusedAccessible) {
     pvarChild->vt = VT_DISPATCH;
     pvarChild->pdispVal = NativeAccessible(focusedAccessible);
   }
--- a/accessible/src/msaa/nsHTMLWin32ObjectAccessible.cpp
+++ b/accessible/src/msaa/nsHTMLWin32ObjectAccessible.cpp
@@ -35,16 +35,18 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsHTMLWin32ObjectAccessible.h"
 
 #include "States.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLWin32ObjectOwnerAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLWin32ObjectOwnerAccessible::
   nsHTMLWin32ObjectOwnerAccessible(nsIContent *aContent,
                                    nsIWeakReference *aShell, void *aHwnd) :
   nsAccessibleWrap(aContent, aShell), mHwnd(aHwnd)
--- a/accessible/src/xforms/nsXFormsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsAccessible.cpp
@@ -47,16 +47,18 @@
 #include "nsServiceManagerUtils.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMNodeList.h"
 #include "nsIEditor.h"
 #include "nsIMutableArray.h"
 #include "nsIXFormsUtilityService.h"
 #include "nsIPlaintextEditor.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXFormsAccessibleBase
 ////////////////////////////////////////////////////////////////////////////////
 
 nsIXFormsUtilityService *nsXFormsAccessibleBase::sXFormsService = nsnull;
 
 nsXFormsAccessibleBase::nsXFormsAccessibleBase()
 {
--- a/accessible/src/xforms/nsXFormsFormControlsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsFormControlsAccessible.cpp
@@ -36,16 +36,18 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsXFormsFormControlsAccessible.h"
 
 #include "States.h"
 #include "nsTextEquivUtils.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXFormsLabelAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXFormsLabelAccessible::
   nsXFormsLabelAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsXFormsAccessible(aContent, aShell)
 {
--- a/accessible/src/xforms/nsXFormsWidgetsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsWidgetsAccessible.cpp
@@ -35,16 +35,18 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsXFormsWidgetsAccessible.h"
 
 #include "States.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXFormsDropmarkerWidgetAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXFormsDropmarkerWidgetAccessible::
   nsXFormsDropmarkerWidgetAccessible(nsIContent *aContent,
                                      nsIWeakReference *aShell) :
   nsLeafAccessible(aContent, aShell)
--- a/accessible/src/xul/nsXULAlertAccessible.cpp
+++ b/accessible/src/xul/nsXULAlertAccessible.cpp
@@ -34,16 +34,18 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsXULAlertAccessible.h"
 
 #include "States.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULAlertAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULAlertAccessible::
   nsXULAlertAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/xul/nsXULColorPickerAccessible.cpp
+++ b/accessible/src/xul/nsXULColorPickerAccessible.cpp
@@ -41,16 +41,17 @@
 #include "States.h"
 #include "nsAccUtils.h"
 #include "nsAccTreeWalker.h"
 #include "nsCoreUtils.h"
 #include "nsDocAccessible.h"
 
 #include "nsIDOMElement.h"
 
+using namespace mozilla::a11y;
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULColorPickerTileAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULColorPickerTileAccessible::
   nsXULColorPickerTileAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
--- a/accessible/src/xul/nsXULComboboxAccessible.cpp
+++ b/accessible/src/xul/nsXULComboboxAccessible.cpp
@@ -42,16 +42,18 @@
 
 #include "States.h"
 #include "nsAccessibilityService.h"
 #include "nsCoreUtils.h"
 
 #include "nsIDOMXULMenuListElement.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULComboboxAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULComboboxAccessible::
   nsXULComboboxAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/xul/nsXULFormControlAccessible.cpp
+++ b/accessible/src/xul/nsXULFormControlAccessible.cpp
@@ -57,16 +57,18 @@
 #include "nsIDOMXULMenuListElement.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsIDOMXULTextboxElement.h"
 #include "nsIEditor.h"
 #include "nsIFrame.h"
 #include "nsINameSpaceManager.h"
 #include "nsITextControlFrame.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULButtonAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULButtonAccessible::
   nsXULButtonAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/xul/nsXULListboxAccessible.cpp
+++ b/accessible/src/xul/nsXULListboxAccessible.cpp
@@ -43,16 +43,18 @@
 #include "States.h"
 #include "nsAccessibilityService.h"
 #include "nsAccUtils.h"
 
 #include "nsIDOMXULPopupElement.h"
 #include "nsIDOMXULMultSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULColumnsAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULColumnsAccessible::
   nsXULColumnsAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/xul/nsXULMenuAccessible.cpp
+++ b/accessible/src/xul/nsXULMenuAccessible.cpp
@@ -56,17 +56,17 @@
 #include "nsGUIEvent.h"
 #include "nsILookAndFeel.h"
 #include "nsWidgetsCID.h"
 
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/Element.h"
 
 using namespace mozilla;
-
+using namespace mozilla::a11y;
 
 static NS_DEFINE_CID(kLookAndFeelCID, NS_LOOKANDFEEL_CID);
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULSelectableAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULSelectableAccessible::
--- a/accessible/src/xul/nsXULSliderAccessible.cpp
+++ b/accessible/src/xul/nsXULSliderAccessible.cpp
@@ -40,16 +40,18 @@
 
 #include "nsAccessibilityAtoms.h"
 #include "States.h"
 
 #include "nsIDOMDocument.h"
 #include "nsIDOMDocumentXBL.h"
 #include "nsIFrame.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULSliderAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULSliderAccessible::
   nsXULSliderAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/xul/nsXULTabAccessible.cpp
+++ b/accessible/src/xul/nsXULTabAccessible.cpp
@@ -45,16 +45,18 @@
 // NOTE: alphabetically ordered
 #include "nsIDocument.h"
 #include "nsIFrame.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMXULSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsIDOMXULRelatedElement.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTabAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULTabAccessible::
   nsXULTabAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/xul/nsXULTextAccessible.cpp
+++ b/accessible/src/xul/nsXULTextAccessible.cpp
@@ -48,16 +48,18 @@
 #include "nsTextEquivUtils.h"
 #include "States.h"
 
 #include "nsIDOMXULDescriptionElement.h"
 #include "nsINameSpaceManager.h"
 #include "nsString.h"
 #include "nsNetUtil.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTextAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULTextAccessible::
   nsXULTextAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsHyperTextAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/xul/nsXULTreeAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeAccessible.cpp
@@ -47,16 +47,18 @@
 
 #include "nsIDOMXULElement.h"
 #include "nsIDOMXULMultSelectCntrlEl.h"
 #include "nsIDOMXULTreeElement.h"
 #include "nsITreeSelection.h"
 #include "nsIMutableArray.h"
 #include "nsComponentManagerUtils.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULTreeAccessible::
   nsXULTreeAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
@@ -195,38 +197,32 @@ nsXULTreeAccessible::NativeRole()
   return primaryCol ?
     static_cast<PRUint32>(nsIAccessibleRole::ROLE_OUTLINE) :
     static_cast<PRUint32>(nsIAccessibleRole::ROLE_LIST);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeAccessible: nsIAccessible implementation
 
-NS_IMETHODIMP
-nsXULTreeAccessible::GetFocusedChild(nsIAccessible **aFocusedChild) 
+nsAccessible*
+nsXULTreeAccessible::FocusedChild()
 {
-  NS_ENSURE_ARG_POINTER(aFocusedChild);
-  *aFocusedChild = nsnull;
-
-  if (IsDefunct())
-    return NS_ERROR_FAILURE;
-
   if (gLastFocusedNode != mContent)
-    return NS_OK;
+    return nsnull;
 
   nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelect =
     do_QueryInterface(mContent);
   if (multiSelect) {
     PRInt32 row = -1;
     multiSelect->GetCurrentIndex(&row);
     if (row >= 0)
-      NS_IF_ADDREF(*aFocusedChild = GetTreeItemAccessible(row));
+      return GetTreeItemAccessible(row);
   }
 
-  return NS_OK;
+  return nsnull;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeAccessible: nsAccessible implementation (DON'T put methods here)
 
 nsAccessible*
 nsXULTreeAccessible::ChildAtPoint(PRInt32 aX, PRInt32 aY,
                                   EWhichChildAtPoint aWhichChild)
@@ -656,39 +652,33 @@ NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION
                                 nsXULTreeItemAccessibleBase)
 NS_INTERFACE_TABLE_TAIL_INHERITING(nsAccessible)
 NS_IMPL_ADDREF_INHERITED(nsXULTreeItemAccessibleBase, nsAccessible)
 NS_IMPL_RELEASE_INHERITED(nsXULTreeItemAccessibleBase, nsAccessible)
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeItemAccessibleBase: nsIAccessible implementation
 
-NS_IMETHODIMP
-nsXULTreeItemAccessibleBase::GetFocusedChild(nsIAccessible **aFocusedChild) 
+nsAccessible*
+nsXULTreeItemAccessibleBase::FocusedChild()
 {
-  NS_ENSURE_ARG_POINTER(aFocusedChild);
-  *aFocusedChild = nsnull;
-
-  if (IsDefunct())
-    return NS_ERROR_FAILURE;
-
   if (gLastFocusedNode != mContent)
-    return NS_OK;
+    return nsnull;
 
   nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelect =
     do_QueryInterface(mContent);
 
   if (multiSelect) {
     PRInt32 row = -1;
     multiSelect->GetCurrentIndex(&row);
     if (row == mRow)
-      NS_ADDREF(*aFocusedChild = this);
+      return this;
   }
 
-  return NS_OK;
+  return nsnull;
 }
 
 NS_IMETHODIMP
 nsXULTreeItemAccessibleBase::GetBounds(PRInt32 *aX, PRInt32 *aY,
                                        PRInt32 *aWidth, PRInt32 *aHeight)
 {
   NS_ENSURE_ARG_POINTER(aX);
   *aX = 0;
--- a/accessible/src/xul/nsXULTreeAccessible.h
+++ b/accessible/src/xul/nsXULTreeAccessible.h
@@ -71,27 +71,27 @@ public:
 
   // nsISupports and cycle collection
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsXULTreeAccessible,
                                            nsAccessible)
 
   // nsIAccessible
   NS_IMETHOD GetValue(nsAString& aValue);
-  NS_IMETHOD GetFocusedChild(nsIAccessible **aFocusedChild);
 
   // nsAccessNode
   virtual bool IsDefunct() const;
   virtual void Shutdown();
 
   // nsAccessible
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
   virtual nsAccessible* ChildAtPoint(PRInt32 aX, PRInt32 aY,
                                      EWhichChildAtPoint aWhichChild);
+  virtual nsAccessible* FocusedChild();
 
   virtual nsAccessible* GetChildAt(PRUint32 aIndex);
   virtual PRInt32 GetChildCount();
 
   // SelectAccessible
   virtual bool IsSelect();
   virtual already_AddRefed<nsIArray> SelectedItems();
   virtual PRUint32 SelectedItemCount();
@@ -177,18 +177,16 @@ public:
                               nsITreeView *aTreeView, PRInt32 aRow);
 
   // nsISupports and cycle collection
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsXULTreeItemAccessibleBase,
                                            nsAccessibleWrap)
 
   // nsIAccessible
-  NS_IMETHOD GetFocusedChild(nsIAccessible **aFocusedChild);
-
   NS_IMETHOD GetBounds(PRInt32 *aX, PRInt32 *aY,
                        PRInt32 *aWidth, PRInt32 *aHeight);
 
   NS_IMETHOD SetSelected(PRBool aSelect); 
   NS_IMETHOD TakeFocus();
 
   NS_IMETHOD GetRelationByType(PRUint32 aRelationType,
                                nsIAccessibleRelation **aRelation);
@@ -204,16 +202,17 @@ public:
   // nsAccessNode
   virtual bool IsDefunct() const;
   virtual void Shutdown();
   virtual bool IsPrimaryForNode() const;
 
   // nsAccessible
   virtual PRUint64 NativeState();
   virtual PRInt32 IndexInParent() const;
+  virtual nsAccessible* FocusedChild();
 
   // nsXULTreeItemAccessibleBase
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_XULTREEITEMBASEACCESSIBLE_IMPL_CID)
 
   /**
    * Return row index associated with the accessible.
    */
   PRInt32 GetRowIndex() const { return mRow; }
--- a/accessible/src/xul/nsXULTreeGridAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeGridAccessible.cpp
@@ -42,16 +42,18 @@
 #include "nsAccessibilityService.h"
 #include "nsAccUtils.h"
 #include "nsDocAccessible.h"
 #include "nsEventShell.h"
 #include "States.h"
 
 #include "nsITreeSelection.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeGridAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULTreeGridAccessible::
   nsXULTreeGridAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsXULTreeAccessible(aContent, aShell)
 {
@@ -843,23 +845,20 @@ NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION
                                 nsXULTreeGridCellAccessible)
 NS_INTERFACE_TABLE_TAIL_INHERITING(nsLeafAccessible)
 NS_IMPL_ADDREF_INHERITED(nsXULTreeGridCellAccessible, nsLeafAccessible)
 NS_IMPL_RELEASE_INHERITED(nsXULTreeGridCellAccessible, nsLeafAccessible)
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeGridCellAccessible: nsIAccessible implementation
 
-NS_IMETHODIMP
-nsXULTreeGridCellAccessible::GetFocusedChild(nsIAccessible **aFocusedChild) 
+nsAccessible*
+nsXULTreeGridCellAccessible::FocusedChild()
 {
-  NS_ENSURE_ARG_POINTER(aFocusedChild);
-  *aFocusedChild = nsnull;
-
-  return IsDefunct() ? NS_ERROR_FAILURE : NS_OK;
+  return nsnull;
 }
 
 NS_IMETHODIMP
 nsXULTreeGridCellAccessible::GetName(nsAString& aName)
 {
   aName.Truncate();
 
   if (IsDefunct())
--- a/accessible/src/xul/nsXULTreeGridAccessible.h
+++ b/accessible/src/xul/nsXULTreeGridAccessible.h
@@ -138,17 +138,16 @@ public:
                               PRInt32 aRow, nsITreeColumn* aColumn);
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsXULTreeGridCellAccessible,
                                            nsLeafAccessible)
 
   // nsIAccessible
-  NS_IMETHOD GetFocusedChild(nsIAccessible **aFocusedChild);
 
   NS_IMETHOD GetName(nsAString& aName);
   NS_IMETHOD GetBounds(PRInt32 *aX, PRInt32 *aY,
                        PRInt32 *aWidth, PRInt32 *aHeight);
 
   NS_IMETHOD GetNumActions(PRUint8 *aCount);
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
   NS_IMETHOD DoAction(PRUint8 aIndex);
@@ -157,16 +156,17 @@ public:
   NS_DECL_NSIACCESSIBLETABLECELL
 
   // nsAccessNode
   virtual bool IsDefunct() const;
   virtual PRBool Init();
   virtual bool IsPrimaryForNode() const;
 
   // nsAccessible
+  virtual nsAccessible* FocusedChild();
   virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
   virtual PRInt32 IndexInParent() const;
 
   // nsXULTreeGridCellAccessible
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_XULTREEGRIDCELLACCESSIBLE_IMPL_CID)
 
--- a/build/autoconf/mozconfig-find
+++ b/build/autoconf/mozconfig-find
@@ -41,27 +41,33 @@
 #    command-line. The .mozconfig file is searched for in the 
 #    order:
 #       if $MOZCONFIG is set, use that.
 #       Otherwise, use $TOPSRCDIR/.mozconfig
 #       Otherwise, use $HOME/.mozconfig
 #
 topsrcdir=$1
 
-for _config in "$MOZCONFIG" \
-               "$MOZ_MYCONFIG"
-do
-  if [ -n "$_config" ] && ! [ -f "$_config" ]; then
-    echo "Specified MOZCONFIG \"$_config\" does not exist!"
+absolute_path() {
+  if [ -n "${1%%/*}" ]; then
+    echo $topsrcdir/$1
+  else
+    echo $1
+  fi
+}
+
+if [ -n "$MOZCONFIG" ]; then
+  MOZCONFIG=`absolute_path "$MOZCONFIG"`
+  if ! [ -f "$MOZCONFIG" ]; then
+    echo "Specified MOZCONFIG \"$MOZCONFIG\" does not exist!"
     exit 1
   fi
-done
+fi
 
 for _config in "$MOZCONFIG" \
-               "$MOZ_MYCONFIG" \
                "$topsrcdir/.mozconfig" \
                "$topsrcdir/mozconfig" \
                "$topsrcdir/mozconfig.sh" \
                "$topsrcdir/myconfig.sh" \
                "$HOME/.mozconfig" \
                "$HOME/.mozconfig.sh" \
                "$HOME/.mozmyconfig.sh"
 do
--- a/build/manifestparser.py
+++ b/build/manifestparser.py
@@ -50,20 +50,20 @@ Mozilla universal manifest parser
 
 import os
 import re
 import shutil
 import sys
 from fnmatch import fnmatch
 from optparse import OptionParser
 
-version = '0.5.2' # package version
+version = '0.5.3' # package version
 try:
     from setuptools import setup
-except ImportError:
+except:
     setup = None
 
 # we need relpath, but it is introduced in python 2.6
 # http://docs.python.org/library/os.path.html
 try:
     relpath = os.path.relpath
 except AttributeError:
     def relpath(path, start):
--- a/configure.in
+++ b/configure.in
@@ -4282,18 +4282,21 @@ AC_CACHE_CHECK(for trouble comparing to 
                                [Foo<int> f; return (0 != f);],
                                ac_cv_trouble_comparing_to_zero=no,
                                ac_cv_trouble_comparing_to_zero=yes)])
 if test "$ac_cv_trouble_comparing_to_zero" = yes ; then
   AC_DEFINE(HAVE_CPP_TROUBLE_COMPARING_TO_ZERO)
 fi
 
 # try harder, when checking for __thread support, see bug 521750 comment #33 and below
+# We pass MOZ_OPTIMIZE_LDFLAGS to the linker because if dead_strip is
+# enabled, the linker in xcode 4.1 will crash. Without this it would crash when
+# linking XUL.
 _SAVE_LDFLAGS=$LDFLAGS
-LDFLAGS="$LDFLAGS $DSO_PIC_CFLAGS $DSO_LDOPTS"
+LDFLAGS="$LDFLAGS $DSO_PIC_CFLAGS $DSO_LDOPTS $MOZ_OPTIMIZE_LDFLAGS"
 AC_CACHE_CHECK(for __thread keyword for TLS variables,
                ac_cv_thread_keyword,
                [AC_TRY_LINK([__thread bool tlsIsMainThread = false;],
                             [return tlsIsMainThread;],
                             ac_cv_thread_keyword=yes,
                             ac_cv_thread_keyword=no)])
 LDFLAGS=$_SAVE_LDFLAGS
 if test "$ac_cv_thread_keyword" = yes; then
@@ -7544,17 +7547,17 @@ else
       if test -z "$MOZ_DEBUG"; then
         WIN32_CRT_LIBS="msvcrt.lib msvcprt.lib"
       else
         WIN32_CRT_LIBS="msvcrtd.lib msvcprtd.lib"
       fi
       dnl Look for a broken crtdll.obj
       WIN32_CRTDLL_FULLPATH=`lib -nologo -list $WIN32_CRT_LIBS | grep crtdll\\.obj`
       lib -NOLOGO -OUT:crtdll.obj $WIN32_CRT_LIBS -EXTRACT:$WIN32_CRTDLL_FULLPATH
-      if grep -q __imp__\{0,1\}free crtdll.obj; then
+      if grep -q '__imp__\{0,1\}free' crtdll.obj; then
         MOZ_MEMORY_LDFLAGS='-MANIFEST:NO -LIBPATH:$(DIST)/lib -NODEFAULTLIB:msvcrt -NODEFAULTLIB:msvcrtd -NODEFAULTLIB:msvcprt -NODEFAULTLIB:msvcprtd -DEFAULTLIB:mozcrt'
       else
         MOZ_MEMORY_LDFLAGS='$(DIST)/../memory/jemalloc/jemalloc.lib'
       fi
       rm crtdll.obj
     fi
 
     dnl Also pass this to NSPR/NSS
--- a/content/base/public/nsContentUtils.h
+++ b/content/base/public/nsContentUtils.h
@@ -75,16 +75,18 @@ static fp_except_t oldmask = fpsetmask(~
 #include "nsIDOMEvent.h"
 #include "nsTArray.h"
 #include "nsTextFragment.h"
 #include "nsReadableUtils.h"
 #include "mozilla/AutoRestore.h"
 #include "nsINode.h"
 #include "nsHashtable.h"
 #include "nsIDOMNode.h"
+#include "nsAHtml5FragmentParser.h"
+#include "nsIFragmentContentSink.h"
 
 struct nsNativeKeyEvent; // Don't include nsINativeKeyBindings.h here: it will force strange compilation error!
 
 class nsIDOMScriptObjectFactory;
 class nsIXPConnect;
 class nsIContent;
 class nsIDOMKeyEvent;
 class nsIDocument;
@@ -1032,26 +1034,59 @@ public:
    *
    * Note! In the HTML case with the HTML5 parser enabled, this is only called
    * from Range.createContextualFragment() and the implementation here is
    * quirky accordingly (html context node behaves like a body context node).
    * If you don't want that quirky behavior, don't use this method as-is!
    *
    * @param aContextNode the node which is used to resolve namespaces
    * @param aFragment the string which is parsed to a DocumentFragment
-   * @param aWillOwnFragment is PR_TRUE if ownership of the fragment should be
-   *                         transferred to the caller.
-   * @param aReturn [out] the created DocumentFragment
+   * @param aReturn the resulting fragment
+   * @param aPreventScriptExecution whether to mark scripts as already started
    */
   static nsresult CreateContextualFragment(nsINode* aContextNode,
                                            const nsAString& aFragment,
-                                           PRBool aWillOwnFragment,
+                                           PRBool aPreventScriptExecution,
                                            nsIDOMDocumentFragment** aReturn);
 
   /**
+   * Invoke the fragment parsing algorithm (innerHTML) using the HTML parser.
+   *
+   * @param aSourceBuffer the string being set as innerHTML
+   * @param aTargetNode the target container
+   * @param aContextLocalName local name of context node
+   * @param aContextNamespace namespace of context node
+   * @param aQuirks true to make <table> not close <p>
+   * @param aPreventScriptExecution true to prevent scripts from executing;
+   *        don't set to false when parsing into a target node that has been
+   *        bound to tree.
+   */
+  static void ParseFragmentHTML(const nsAString& aSourceBuffer,
+                                nsIContent* aTargetNode,
+                                nsIAtom* aContextLocalName,
+                                PRInt32 aContextNamespace,
+                                PRBool aQuirks,
+                                PRBool aPreventScriptExecution);
+
+  /**
+   * Invoke the fragment parsing algorithm (innerHTML) using the XML parser.
+   *
+   * @param aSourceBuffer the string being set as innerHTML
+   * @param aTargetNode the target container
+   * @param aTagStack the namespace mapping context
+   * @param aPreventExecution whether to mark scripts as already started
+   * @param aReturn the result fragment
+   */
+  static nsresult ParseFragmentXML(const nsAString& aSourceBuffer,
+                                   nsIDocument* aDocument,
+                                   nsTArray<nsString>& aTagStack,
+                                   PRBool aPreventScriptExecution,
+                                   nsIDOMDocumentFragment** aReturn);
+
+  /**
    * Creates a new XML document, which is marked to be loaded as data.
    *
    * @param aNamespaceURI Namespace for the root element to create and insert in
    *                      the document. Only used if aQualifiedName is not
    *                      empty.
    * @param aQualifiedName Qualified name for the root element to create and
    *                       insert in the document. If empty no root element will
    *                       be created.
@@ -1659,16 +1694,22 @@ public:
   /**
    * Determine whether a content node is focused or not,
    *
    * @param aContent the content node to check
    * @return true if the content node is focused, false otherwise.
    */
   static PRBool IsFocusedContent(const nsIContent *aContent);
 
+  static void GetShiftText(nsAString& text);
+  static void GetControlText(nsAString& text);
+  static void GetMetaText(nsAString& text);
+  static void GetAltText(nsAString& text);
+  static void GetModifierSeparatorText(nsAString& text);
+
   /**
    * Returns if aContent has a tabbable subdocument.
    * A sub document isn't tabbable when it's a zombie document.
    *
    * @param aElement element to test.
    *
    * @return Whether the subdocument is tabbable.
    */
@@ -1683,16 +1724,21 @@ public:
   static void FlushLayoutForTree(nsIDOMWindow* aWindow);
 
   /**
    * Returns true if content with the given principal is allowed to use XUL
    * and XBL and false otherwise.
    */
   static bool AllowXULXBLForPrincipal(nsIPrincipal* aPrincipal);
 
+  /**
+   * Perform cleanup that's appropriate for XPCOM shutdown.
+   */
+  static void XPCOMShutdown();
+
   enum ContentViewerType
   {
       TYPE_UNSUPPORTED,
       TYPE_CONTENT,
       TYPE_PLUGIN,
       TYPE_UNKNOWN
   };
 
@@ -1745,16 +1791,20 @@ private:
                                 nsIPrincipal* aPrincipal);
 
   static nsresult WrapNative(JSContext *cx, JSObject *scope,
                              nsISupports *native, nsWrapperCache *cache,
                              const nsIID* aIID, jsval *vp,
                              nsIXPConnectJSObjectHolder** aHolder,
                              PRBool aAllowWrapping);
 
+  static void InitializeModifierStrings();
+
+  static void DropFragmentParsers();
+
   static nsIDOMScriptObjectFactory *sDOMScriptObjectFactory;
 
   static nsIXPConnect *sXPConnect;
 
   static nsIScriptSecurityManager *sSecurityManager;
 
   static nsIThreadJSContextStack *sThreadJSContextStack;
 
@@ -1807,16 +1857,26 @@ private:
   static nsCOMArray<nsIRunnable>* sBlockedScriptRunners;
   static PRUint32 sRunnersCountAtFirstBlocker;
   static PRUint32 sScriptBlockerCountWhereRunnersPrevented;
 
   static nsIInterfaceRequestor* sSameOriginChecker;
 
   static PRBool sIsHandlingKeyBoardEvent;
   static PRBool sAllowXULXBL_for_file;
+
+  static nsAHtml5FragmentParser* sHTMLFragmentParser;
+  static nsIParser* sXMLFragmentParser;
+  static nsIFragmentContentSink* sXMLFragmentSink;
+
+  static nsString* sShiftText;
+  static nsString* sControlText;
+  static nsString* sMetaText;
+  static nsString* sAltText;
+  static nsString* sModifierSeparator;
 };
 
 #define NS_HOLD_JS_OBJECTS(obj, clazz)                                         \
   nsContentUtils::HoldJSObjects(NS_CYCLE_COLLECTION_UPCAST(obj, clazz),        \
                                 &NS_CYCLE_COLLECTION_NAME(clazz))
 
 #define NS_DROP_JS_OBJECTS(obj, clazz)                                         \
   nsContentUtils::DropJSObjects(NS_CYCLE_COLLECTION_UPCAST(obj, clazz))
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -121,18 +121,18 @@ class Loader;
 namespace dom {
 class Link;
 class Element;
 } // namespace dom
 } // namespace mozilla
 
 
 #define NS_IDOCUMENT_IID \
-{ 0x18e4d4bd, 0x006b, 0x4008, \
-  { 0x90, 0x05, 0x27, 0x57, 0x35, 0xf0, 0xd4, 0x85 } }
+{ 0xfac563fb, 0x2b6a, 0x4ac8, \
+ { 0x85, 0xf7, 0xd5, 0x14, 0x4b, 0x3e, 0xce, 0x78 } }
 
 // Flag for AddStyleSheet().
 #define NS_STYLESHEET_FROM_CATALOG                (1 << 0)
 
 // Document states
 
 // RTL locale: specific to the XUL localedir attribute
 #define NS_DOCUMENT_STATE_RTL_LOCALE              NS_DEFINE_EVENT_STATE_MACRO(0)
@@ -1142,26 +1142,16 @@ public:
     return mMayStartLayout;
   }
 
   void SetMayStartLayout(PRBool aMayStartLayout)
   {
     mMayStartLayout = aMayStartLayout;
   }
 
-  // This method should return an addrefed nsIParser* or nsnull. Implementations
-  // should transfer ownership of the parser to the caller.
-  virtual already_AddRefed<nsIParser> GetFragmentParser() {
-    return nsnull;
-  }
-
-  virtual void SetFragmentParser(nsIParser* aParser) {
-    // Do nothing.
-  }
-
   already_AddRefed<nsIDocumentEncoder> GetCachedEncoder()
   {
     return mCachedEncoder.forget();
   }
 
   void SetCachedEncoder(already_AddRefed<nsIDocumentEncoder> aEncoder)
   {
     mCachedEncoder = aEncoder;
@@ -1381,17 +1371,18 @@ public:
    */
   nsIDocument* GetOriginalDocument() { return mOriginalDocument; }
 
   /**
    * Called by nsParser to preload images. Can be removed and code moved
    * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
    * parser-module is linked with gklayout-module.
    */
-  virtual void MaybePreLoadImage(nsIURI* uri) = 0;
+  virtual void MaybePreLoadImage(nsIURI* uri,
+                                 const nsAString& aCrossOriginAttr) = 0;
 
   /**
    * Called by nsParser to preload style sheets.  Can also be merged into
    * the parser if and when the parser is merged with libgklayout.
    */
   virtual void PreloadStyle(nsIURI* aURI, const nsAString& aCharset) = 0;
 
   /**
--- a/content/base/src/nsContentSink.cpp
+++ b/content/base/src/nsContentSink.cpp
@@ -98,16 +98,17 @@
 #include "nsIWebNavigation.h"
 #include "nsIDocumentLoader.h"
 #include "nsICachingChannel.h"
 #include "nsICacheEntryDescriptor.h"
 #include "nsGenericHTMLElement.h"
 #include "nsHTMLDNSPrefetch.h"
 #include "nsISupportsPrimitives.h"
 #include "mozilla/Preferences.h"
+#include "nsParserConstants.h"
 
 using namespace mozilla;
 
 PRLogModuleInfo* gContentSinkLogModuleInfo;
 
 class nsScriptLoaderObserverProxy : public nsIScriptLoaderObserver
 {
 public:
@@ -330,16 +331,17 @@ nsContentSink::Init(nsIDocument* aDoc,
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsContentSink::StyleSheetLoaded(nsCSSStyleSheet* aSheet,
                                 PRBool aWasAlternate,
                                 nsresult aStatus)
 {
+  NS_ASSERTION(!mFragmentMode, "How come a fragment parser observed sheets?");
   if (!aWasAlternate) {
     NS_ASSERTION(mPendingSheetCount > 0, "How'd that happen?");
     --mPendingSheetCount;
 
     if (mPendingSheetCount == 0 &&
         (mDeferredLayoutStart || mDeferredFlushTags)) {
       if (mDeferredFlushTags) {
         FlushTags();
@@ -636,17 +638,17 @@ nsContentSink::ProcessLinkHeader(nsICont
     last = end - 1;
 
     PRBool needsUnescape = PR_FALSE;
     
     // look for semicolon or comma
     while (*end != kNullCh && *end != kSemicolon && *end != kComma) {
       PRUnichar ch = *end;
 
-      if (ch == kApostrophe || ch == kQuote || ch == kLessThan) {
+      if (ch == kQuote || ch == kLessThan) {
         // quoted string
 
         PRUnichar quote = ch;
         if (quote == kLessThan) {
           quote = kGreaterThan;
         }
         
         needsUnescape = (ch == kQuote);
@@ -718,18 +720,17 @@ nsContentSink::ProcessLinkHeader(nsICont
           nsAutoString  attr(start);
           attr.StripWhitespace();
 
           PRUnichar* value = ++equals;
           while (nsCRT::IsAsciiSpace(*value)) {
             value++;
           }
 
-          if (((*value == kApostrophe) || (*value == kQuote)) &&
-              (*value == *last)) {
+          if ((*value == kQuote) && (*value == *last)) {
             *last = kNullCh;
             value++;
           }
 
           if (needsUnescape) {
             // unescape in-place
             PRUnichar* unescaped = value;
             PRUnichar *src = value;
@@ -869,22 +870,23 @@ nsContentSink::ProcessStyleLink(nsIConte
   nsresult rv = NS_NewURI(getter_AddRefs(url), aHref, nsnull,
                           mDocument->GetDocBaseURI());
   
   if (NS_FAILED(rv)) {
     // The URI is bad, move along, don't propagate the error (for now)
     return NS_OK;
   }
 
+  // If this is a fragment parser, we don't want to observe.
   PRBool isAlternate;
   rv = mCSSLoader->LoadStyleLink(aElement, url, aTitle, aMedia, aAlternate,
-                                 this, &isAlternate);
+                                 mFragmentMode ? nsnull : this, &isAlternate);
   NS_ENSURE_SUCCESS(rv, rv);
   
-  if (!isAlternate) {
+  if (!isAlternate && !mFragmentMode) {
     ++mPendingSheetCount;
     mScriptLoader->AddExecuteBlocker();
   }
 
   return NS_OK;
 }
 
 
--- a/content/base/src/nsContentSink.h
+++ b/content/base/src/nsContentSink.h
@@ -344,16 +344,18 @@ protected:
   // If true, we deferred notifications until sheets load
   PRUint8 mDeferredFlushTags : 1;
   // If false, we're not ourselves a document observer; that means we
   // shouldn't be performing any more content model notifications,
   // since we're not longer updating our child counts.
   PRUint8 mIsDocumentObserver : 1;
   // True if this is a fragment parser
   PRUint8 mFragmentMode : 1;
+  // True to call prevent script execution in the fragment mode.
+  PRUint8 mPreventScriptExecution : 1;
   
   //
   // -- Can interrupt parsing members --
   //
 
   // The number of tokens that have been processed since we measured
   // if it's time to return to the main event loop.
   PRUint32 mDeflectedCount;
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -197,16 +197,17 @@ static NS_DEFINE_CID(kXTFServiceCID, NS_
 #include "nsIChannelPolicy.h"
 #include "nsChannelPolicy.h"
 #include "nsIContentSecurityPolicy.h"
 #include "nsContentDLF.h"
 #ifdef MOZ_MEDIA
 #include "nsHTMLMediaElement.h"
 #endif
 #include "nsDOMTouchEvent.h"
+#include "nsIScriptElement.h"
 
 #include "mozilla/Preferences.h"
 
 using namespace mozilla::dom;
 using namespace mozilla::layers;
 using namespace mozilla;
 
 const char kLoadAsData[] = "loadAsData";
@@ -251,18 +252,28 @@ PRUint32 nsContentUtils::sDOMNodeRemoved
 nsCOMArray<nsIRunnable>* nsContentUtils::sBlockedScriptRunners = nsnull;
 PRUint32 nsContentUtils::sRunnersCountAtFirstBlocker = 0;
 PRUint32 nsContentUtils::sScriptBlockerCountWhereRunnersPrevented = 0;
 nsIInterfaceRequestor* nsContentUtils::sSameOriginChecker = nsnull;
 
 PRBool nsContentUtils::sIsHandlingKeyBoardEvent = PR_FALSE;
 PRBool nsContentUtils::sAllowXULXBL_for_file = PR_FALSE;
 
+nsString* nsContentUtils::sShiftText = nsnull;
+nsString* nsContentUtils::sControlText = nsnull;
+nsString* nsContentUtils::sMetaText = nsnull;
+nsString* nsContentUtils::sAltText = nsnull;
+nsString* nsContentUtils::sModifierSeparator = nsnull;
+
 PRBool nsContentUtils::sInitialized = PR_FALSE;
 
+nsAHtml5FragmentParser* nsContentUtils::sHTMLFragmentParser = nsnull;
+nsIParser* nsContentUtils::sXMLFragmentParser = nsnull;
+nsIFragmentContentSink* nsContentUtils::sXMLFragmentSink = nsnull;
+
 static PLDHashTable sEventListenerManagersHash;
 
 class EventListenerManagerMapEntry : public PLDHashEntryHdr
 {
 public:
   EventListenerManagerMapEntry(const void *aKey)
     : mKey(aKey)
   {
@@ -377,16 +388,91 @@ nsContentUtils::Init()
   Preferences::AddBoolVarCache(&sAllowXULXBL_for_file,
                                "dom.allow_XUL_XBL_for_file");
 
   sInitialized = PR_TRUE;
 
   return NS_OK;
 }
 
+void
+nsContentUtils::GetShiftText(nsAString& text)
+{
+  if (!sShiftText)
+    InitializeModifierStrings();
+  text.Assign(*sShiftText);
+}
+
+void
+nsContentUtils::GetControlText(nsAString& text)
+{
+  if (!sControlText)
+    InitializeModifierStrings();
+  text.Assign(*sControlText);
+}
+
+void
+nsContentUtils::GetMetaText(nsAString& text)
+{
+  if (!sMetaText)
+    InitializeModifierStrings();
+  text.Assign(*sMetaText);
+}
+
+void
+nsContentUtils::GetAltText(nsAString& text)
+{
+  if (!sAltText)
+    InitializeModifierStrings();
+  text.Assign(*sAltText);
+}
+
+void
+nsContentUtils::GetModifierSeparatorText(nsAString& text)
+{
+  if (!sModifierSeparator)
+    InitializeModifierStrings();
+  text.Assign(*sModifierSeparator);
+}
+
+void
+nsContentUtils::InitializeModifierStrings()
+{
+  //load the display strings for the keyboard accelerators
+  nsCOMPtr<nsIStringBundleService> bundleService =
+    mozilla::services::GetStringBundleService();
+  nsCOMPtr<nsIStringBundle> bundle;
+  nsresult rv = NS_OK;
+  if (bundleService) {
+    rv = bundleService->CreateBundle( "chrome://global-platform/locale/platformKeys.properties",
+                                      getter_AddRefs(bundle));
+  }
+  
+  NS_ASSERTION(NS_SUCCEEDED(rv) && bundle, "chrome://global/locale/platformKeys.properties could not be loaded");
+  nsXPIDLString shiftModifier;
+  nsXPIDLString metaModifier;
+  nsXPIDLString altModifier;
+  nsXPIDLString controlModifier;
+  nsXPIDLString modifierSeparator;
+  if (bundle) {
+    //macs use symbols for each modifier key, so fetch each from the bundle, which also covers i18n
+    bundle->GetStringFromName(NS_LITERAL_STRING("VK_SHIFT").get(), getter_Copies(shiftModifier));
+    bundle->GetStringFromName(NS_LITERAL_STRING("VK_META").get(), getter_Copies(metaModifier));
+    bundle->GetStringFromName(NS_LITERAL_STRING("VK_ALT").get(), getter_Copies(altModifier));
+    bundle->GetStringFromName(NS_LITERAL_STRING("VK_CONTROL").get(), getter_Copies(controlModifier));
+    bundle->GetStringFromName(NS_LITERAL_STRING("MODIFIER_SEPARATOR").get(), getter_Copies(modifierSeparator));
+  }
+  //if any of these don't exist, we get  an empty string
+  sShiftText = new nsString(shiftModifier);
+  sMetaText = new nsString(metaModifier);
+  sAltText = new nsString(altModifier);
+  sControlText = new nsString(controlModifier);
+  sModifierSeparator = new nsString(modifierSeparator);  
+}
+
 bool nsContentUtils::sImgLoaderInitialized;
 
 void
 nsContentUtils::InitImgLoader()
 {
   sImgLoaderInitialized = true;
 
   // Ignore failure and just don't load images
@@ -1141,16 +1227,27 @@ nsContentUtils::Shutdown()
   }
 
   NS_ASSERTION(!sBlockedScriptRunners ||
                sBlockedScriptRunners->Count() == 0,
                "How'd this happen?");
   delete sBlockedScriptRunners;
   sBlockedScriptRunners = nsnull;
 
+  delete sShiftText;
+  sShiftText = nsnull;
+  delete sControlText;  
+  sControlText = nsnull;
+  delete sMetaText;  
+  sMetaText = nsnull;
+  delete sAltText;  
+  sAltText = nsnull;
+  delete sModifierSeparator;
+  sModifierSeparator = nsnull;
+
   NS_IF_RELEASE(sSameOriginChecker);
   
   nsTextEditorState::ShutDown();
 }
 
 // static
 PRBool
 nsContentUtils::IsCallerTrustedForCapability(const char* aCapability)
@@ -3509,88 +3606,66 @@ nsContentUtils::IsValidNodeName(nsIAtom 
   return aPrefix != nsGkAtoms::xmlns &&
          (aNamespaceID == kNameSpaceID_XML || aPrefix != nsGkAtoms::xml);
 }
 
 /* static */
 nsresult
 nsContentUtils::CreateContextualFragment(nsINode* aContextNode,
                                          const nsAString& aFragment,
-                                         PRBool aWillOwnFragment,
+                                         PRBool aPreventScriptExecution,
                                          nsIDOMDocumentFragment** aReturn)
 {
   *aReturn = nsnull;
   NS_ENSURE_ARG(aContextNode);
 
-  nsresult rv;
-
   // If we don't have a document here, we can't get the right security context
   // for compiling event handlers... so just bail out.
   nsCOMPtr<nsIDocument> document = aContextNode->GetOwnerDoc();
   NS_ENSURE_TRUE(document, NS_ERROR_NOT_AVAILABLE);
 
   PRBool isHTML = document->IsHTML();
 #ifdef DEBUG
   nsCOMPtr<nsIHTMLDocument> htmlDoc = do_QueryInterface(document);
   NS_ASSERTION(!isHTML || htmlDoc, "Should have HTMLDocument here!");
 #endif
 
-  if (isHTML && nsHtml5Module::sEnabled) {
-    // See if the document has a cached fragment parser. nsHTMLDocument is the
-    // only one that should really have one at the moment.
-    nsCOMPtr<nsIParser> parser = document->GetFragmentParser();
-    if (parser) {
-      // Get the parser ready to use.
-      parser->Reset();
-    }
-    else {
-      // Create a new parser for this operation.
-      parser = nsHtml5Module::NewHtml5Parser();
-      if (!parser) {
-        return NS_ERROR_OUT_OF_MEMORY;
-      }
-    }
+  if (isHTML) {
     nsCOMPtr<nsIDOMDocumentFragment> frag;
-    rv = NS_NewDocumentFragment(getter_AddRefs(frag), document->NodeInfoManager());
-    NS_ENSURE_SUCCESS(rv, rv);
+    NS_NewDocumentFragment(getter_AddRefs(frag), document->NodeInfoManager());
     
     nsCOMPtr<nsIContent> contextAsContent = do_QueryInterface(aContextNode);
     if (contextAsContent && !contextAsContent->IsElement()) {
       contextAsContent = contextAsContent->GetParent();
       if (contextAsContent && !contextAsContent->IsElement()) {
         // can this even happen?
         contextAsContent = nsnull;
       }
     }
     
-    nsAHtml5FragmentParser* asFragmentParser =
-        static_cast<nsAHtml5FragmentParser*> (parser.get());
     nsCOMPtr<nsIContent> fragment = do_QueryInterface(frag);
-    if (contextAsContent &&
-        !(nsGkAtoms::html == contextAsContent->Tag() &&
-          contextAsContent->IsHTML())) {
-      asFragmentParser->ParseHtml5Fragment(aFragment,
-                                           fragment,
-                                           contextAsContent->Tag(),
-                                           contextAsContent->GetNameSpaceID(),
-                                           (document->GetCompatibilityMode() ==
-                                               eCompatibility_NavQuirks),
-                                           PR_FALSE);
+    if (contextAsContent && !contextAsContent->IsHTML(nsGkAtoms::html)) {
+      ParseFragmentHTML(aFragment,
+                        fragment,
+                        contextAsContent->Tag(),
+                        contextAsContent->GetNameSpaceID(),
+                        (document->GetCompatibilityMode() ==
+                            eCompatibility_NavQuirks),
+                        aPreventScriptExecution);
     } else {
-      asFragmentParser->ParseHtml5Fragment(aFragment,
-                                           fragment,
-                                           nsGkAtoms::body,
-                                           kNameSpaceID_XHTML,
-                                           (document->GetCompatibilityMode() ==
-                                               eCompatibility_NavQuirks),
-                                           PR_FALSE);
+      ParseFragmentHTML(aFragment,
+                        fragment,
+                        nsGkAtoms::body,
+                        kNameSpaceID_XHTML,
+                        (document->GetCompatibilityMode() ==
+                            eCompatibility_NavQuirks),
+                        aPreventScriptExecution);
     }
-  
-    frag.swap(*aReturn);
-    document->SetFragmentParser(parser);
+
+    frag.forget(aReturn);
     return NS_OK;
   }
 
   nsAutoTArray<nsString, 32> tagStack;
   nsAutoString uriStr, nameStr;
   nsCOMPtr<nsIContent> content = do_QueryInterface(aContextNode);
   // just in case we have a text node
   if (content && !content->IsElement())
@@ -3639,94 +3714,104 @@ nsContentUtils::CreateContextualFragment
         tagName.Append(NS_LITERAL_STRING(" xmlns=\"") + uriStr +
                        NS_LITERAL_STRING("\""));
       }
     }
 
     content = content->GetParent();
   }
 
-  nsCAutoString contentType;
-  nsAutoString buf;
-  document->GetContentType(buf);
-  LossyCopyUTF16toASCII(buf, contentType);
-
-  // See if the document has a cached fragment parser. nsHTMLDocument is the
-  // only one that should really have one at the moment.
-  nsCOMPtr<nsIParser> parser = document->GetFragmentParser();
-  if (parser) {
-    // Get the parser ready to use.
-    parser->Reset();
-  }
-  else {
-    // Create a new parser for this operation.
-    parser = do_CreateInstance(kCParserCID, &rv);
-    NS_ENSURE_SUCCESS(rv, rv);
-  }
-
-  // See if the parser already has a content sink that we can reuse.
-  nsCOMPtr<nsIFragmentContentSink> sink;
-  nsCOMPtr<nsIContentSink> contentsink = parser->GetContentSink();
-  if (contentsink) {
-    // Make sure it's the correct type.
-    if (isHTML) {
-      nsCOMPtr<nsIHTMLContentSink> htmlsink = do_QueryInterface(contentsink);
-      sink = do_QueryInterface(htmlsink);
-    }
-    else {
-      nsCOMPtr<nsIXMLContentSink> xmlsink = do_QueryInterface(contentsink);
-      sink = do_QueryInterface(xmlsink);
-    }
-  }
-
-  if (!sink) {
-    // Either there was no cached content sink or it was the wrong type. Make a
-    // new one.
-    if (isHTML) {
-      rv = NS_NewHTMLFragmentContentSink(getter_AddRefs(sink));
-    } else {
-      rv = NS_NewXMLFragmentContentSink(getter_AddRefs(sink));
-    }
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    contentsink = do_QueryInterface(sink);
-    NS_ASSERTION(contentsink, "Sink doesn't QI to nsIContentSink!");
-
-    parser->SetContentSink(contentsink);
-  }
-
-  sink->SetTargetDocument(document);
-
-  nsDTDMode mode = eDTDMode_autodetect;
-  switch (document->GetCompatibilityMode()) {
-    case eCompatibility_NavQuirks:
-      mode = eDTDMode_quirks;
-      break;
-    case eCompatibility_AlmostStandards:
-      mode = eDTDMode_almost_standards;
-      break;
-    case eCompatibility_FullStandards:
-      mode = eDTDMode_full_standards;
-      break;
-    default:
-      NS_NOTREACHED("unknown mode");
-      break;
-  }
-
-  rv = parser->ParseFragment(aFragment, nsnull, tagStack,
-                             !isHTML, contentType, mode);
-  if (NS_SUCCEEDED(rv)) {
-    rv = sink->GetFragment(aWillOwnFragment, aReturn);
-  }
-
-  document->SetFragmentParser(parser);
+  return ParseFragmentXML(aFragment,
+                          document,
+                          tagStack,
+                          aPreventScriptExecution,
+                          aReturn);
+}
+
+/* static */
+void
+nsContentUtils::DropFragmentParsers()
+{
+  NS_IF_RELEASE(sHTMLFragmentParser);
+  NS_IF_RELEASE(sXMLFragmentParser);
+  NS_IF_RELEASE(sXMLFragmentSink);
+}
+
+/* static */
+void
+nsContentUtils::XPCOMShutdown()
+{
+  nsContentUtils::DropFragmentParsers();
+}
+
+/* static */
+void
+nsContentUtils::ParseFragmentHTML(const nsAString& aSourceBuffer,
+                                  nsIContent* aTargetNode,
+                                  nsIAtom* aContextLocalName,
+                                  PRInt32 aContextNamespace,
+                                  PRBool aQuirks,
+                                  PRBool aPreventScriptExecution)
+{
+  if (!sHTMLFragmentParser) {
+    sHTMLFragmentParser =
+      static_cast<nsAHtml5FragmentParser*>(nsHtml5Module::NewHtml5Parser().get());
+    // Now sHTMLFragmentParser owns the object
+  }
+  sHTMLFragmentParser->ParseHtml5Fragment(aSourceBuffer,
+                                          aTargetNode,
+                                          aContextLocalName,
+                                          aContextNamespace,
+                                          aQuirks,
+                                          aPreventScriptExecution);
+  sHTMLFragmentParser->Reset();
+}
+
+/* static */
+nsresult
+nsContentUtils::ParseFragmentXML(const nsAString& aSourceBuffer,
+                                 nsIDocument* aDocument,
+                                 nsTArray<nsString>& aTagStack,
+                                 PRBool aPreventScriptExecution,
+                                 nsIDOMDocumentFragment** aReturn)
+{
+  if (!sXMLFragmentParser) {
+    nsCOMPtr<nsIParser> parser = do_CreateInstance(kCParserCID);
+    parser.forget(&sXMLFragmentParser);
+    // sXMLFragmentParser now owns the parser
+  }
+  if (!sXMLFragmentSink) {
+    NS_NewXMLFragmentContentSink(&sXMLFragmentSink);
+    // sXMLFragmentSink now owns the sink
+  }
+  nsCOMPtr<nsIContentSink> contentsink = do_QueryInterface(sXMLFragmentSink);
+  NS_ABORT_IF_FALSE(contentsink, "Sink doesn't QI to nsIContentSink!");
+  sXMLFragmentParser->SetContentSink(contentsink);
+
+  sXMLFragmentSink->SetTargetDocument(aDocument);
+  sXMLFragmentSink->SetPreventScriptExecution(aPreventScriptExecution);
+
+  nsresult rv =
+    sXMLFragmentParser->ParseFragment(aSourceBuffer,
+                                      aTagStack);
+  if (NS_FAILED(rv)) {
+    // Drop the fragment parser and sink that might be in an inconsistent state
+    NS_IF_RELEASE(sXMLFragmentParser);
+    NS_IF_RELEASE(sXMLFragmentSink);
+    return rv;
+  }
+
+  rv = sXMLFragmentSink->FinishFragmentParsing(aReturn);
+
+  sXMLFragmentParser->Reset();
 
   return rv;
 }
 
+
 /* static */
 nsresult
 nsContentUtils::CreateDocument(const nsAString& aNamespaceURI, 
                                const nsAString& aQualifiedName, 
                                nsIDOMDocumentType* aDoctype,
                                nsIURI* aDocumentURI, nsIURI* aBaseURI,
                                nsIPrincipal* aPrincipal,
                                nsIScriptGlobalObject* aEventObject,
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -198,16 +198,18 @@
 
 #include "mozilla/dom/Link.h"
 #include "nsIHTMLDocument.h"
 #include "nsXULAppAPI.h"
 #include "nsDOMTouchEvent.h"
 
 #include "mozilla/Preferences.h"
 
+#include "imgILoader.h"
+
 using namespace mozilla;
 using namespace mozilla::dom;
 
 typedef nsTArray<Link*> LinkArray;
 
 
 #ifdef PR_LOGGING
 static PRLogModuleInfo* gDocumentLeakPRLog;
@@ -7663,37 +7665,47 @@ FireOrClearDelayedEvents(nsTArray<nsCOMP
       if (shell) {
         shell->FireOrClearDelayedEvents(aFireEvents);
       }
     }
   }
 }
 
 void
-nsDocument::MaybePreLoadImage(nsIURI* uri)
+nsDocument::MaybePreLoadImage(nsIURI* uri, const nsAString &aCrossOriginAttr)
 {
   // Early exit if the img is already present in the img-cache
   // which indicates that the "real" load has already started and
   // that we shouldn't preload it.
   PRInt16 blockingStatus;
   if (nsContentUtils::IsImageInCache(uri) ||
       !nsContentUtils::CanLoadImage(uri, static_cast<nsIDocument *>(this),
                                     this, NodePrincipal(), &blockingStatus)) {
     return;
   }
 
+  nsLoadFlags loadFlags = nsIRequest::LOAD_NORMAL;
+  if (aCrossOriginAttr.LowerCaseEqualsLiteral("anonymous")) {
+    loadFlags |= imgILoader::LOAD_CORS_ANONYMOUS;
+  } else if (aCrossOriginAttr.LowerCaseEqualsLiteral("use-credentials")) {
+    loadFlags |= imgILoader::LOAD_CORS_USE_CREDENTIALS;
+  }
+  // else should we err on the side of not doing the preload if
+  // aCrossOriginAttr is nonempty?  Let's err on the side of doing the
+  // preload as CORS_NONE.
+
   // Image not in cache - trigger preload
   nsCOMPtr<imgIRequest> request;
   nsresult rv =
     nsContentUtils::LoadImage(uri,
                               this,
                               NodePrincipal(),
                               mDocumentURI, // uri of document used as referrer
                               nsnull,       // no observer
-                              nsIRequest::LOAD_NORMAL,
+                              loadFlags,
                               getter_AddRefs(request));
 
   // Pin image-reference to avoid evicting it from the img-cache before
   // the "real" load occurs. Unpinned in DispatchContentLoadedEvents and
   // unlink
   if (NS_SUCCEEDED(rv)) {
     mPreloadingImages.AppendObject(request);
   }
--- a/content/base/src/nsDocument.h
+++ b/content/base/src/nsDocument.h
@@ -880,17 +880,18 @@ public:
   void SetLoadedAsData(PRBool aLoadedAsData) { mLoadedAsData = aLoadedAsData; }
 
   nsresult CloneDocHelper(nsDocument* clone) const;
 
   void MaybeInitializeFinalizeFrameLoaders();
 
   void MaybeEndOutermostXBLUpdate();
 
-  virtual void MaybePreLoadImage(nsIURI* uri);
+  virtual void MaybePreLoadImage(nsIURI* uri,
+                                 const nsAString &aCrossOriginAttr);
 
   virtual void PreloadStyle(nsIURI* uri, const nsAString& charset);
 
   virtual nsresult LoadChromeSheetSync(nsIURI* uri, PRBool isAgentSheet,
                                        nsCSSStyleSheet** sheet);
 
   virtual nsISupports* GetCurrentContentSink();
 
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -4308,30 +4308,25 @@ nsGenericElement::AddScriptEventListener
   nsIDocument *ownerDoc = GetOwnerDoc();
   if (!ownerDoc || ownerDoc->IsLoadedAsData()) {
     // Make this a no-op rather than throwing an error to avoid
     // the error causing problems setting the attribute.
     return NS_OK;
   }
 
   NS_PRECONDITION(aEventName, "Must have event name!");
-  nsCOMPtr<nsISupports> target;
   PRBool defer = PR_TRUE;
-  nsRefPtr<nsEventListenerManager> manager;
-
-  GetEventListenerManagerForAttr(getter_AddRefs(manager),
-                                 getter_AddRefs(target),
-                                 &defer);
+  nsEventListenerManager* manager = GetEventListenerManagerForAttr(&defer);
   if (!manager) {
     return NS_OK;
   }
 
   defer = defer && aDefer; // only defer if everyone agrees...
   PRUint32 lang = GetScriptTypeID();
-  manager->AddScriptEventListener(target, aEventName, aValue, lang, defer,
+  manager->AddScriptEventListener(aEventName, aValue, lang, defer,
                                   !nsContentUtils::IsChromeDoc(ownerDoc));
   return NS_OK;
 }
 
 
 //----------------------------------------------------------------------
 
 const nsAttrName*
@@ -4590,27 +4585,21 @@ nsGenericElement::SetMappedAttribute(nsI
                                      nsIAtom* aName,
                                      nsAttrValue& aValue,
                                      nsresult* aRetval)
 {
   *aRetval = NS_OK;
   return PR_FALSE;
 }
 
-nsresult
-nsGenericElement::GetEventListenerManagerForAttr(nsEventListenerManager** aManager,
-                                                 nsISupports** aTarget,
-                                                 PRBool* aDefer)
-{
-  *aManager = GetListenerManager(PR_TRUE);
+nsEventListenerManager*
+nsGenericElement::GetEventListenerManagerForAttr(PRBool* aDefer)
+{
   *aDefer = PR_TRUE;
-  NS_ENSURE_STATE(*aManager);
-  NS_ADDREF(*aManager);
-  NS_ADDREF(*aTarget = static_cast<nsIContent*>(this));
-  return NS_OK;
+  return GetListenerManager(PR_TRUE);
 }
 
 nsGenericElement::nsAttrInfo
 nsGenericElement::GetAttrInfo(PRInt32 aNamespaceID, nsIAtom* aName) const
 {
   NS_ASSERTION(nsnull != aName, "must have attribute name");
   NS_ASSERTION(aNamespaceID != kNameSpaceID_Unknown,
                "must have a real namespace ID!");
--- a/content/base/src/nsGenericElement.h
+++ b/content/base/src/nsGenericElement.h
@@ -779,20 +779,18 @@ protected:
   {
     return NS_OK;
   }
 
   /**
    * Hook to allow subclasses to produce a different nsEventListenerManager if
    * needed for attachment of attribute-defined handlers
    */
-  virtual nsresult
-    GetEventListenerManagerForAttr(nsEventListenerManager** aManager,
-                                   nsISupports** aTarget,
-                                   PRBool* aDefer);
+  virtual nsEventListenerManager*
+    GetEventListenerManagerForAttr(PRBool* aDefer);
 
   /**
    * Copy attributes and state to another element
    * @param aDest the object to copy to
    */
   nsresult CopyInnerTo(nsGenericElement* aDest) const;
 
   /**
--- a/content/base/src/nsHTMLContentSerializer.cpp
+++ b/content/base/src/nsHTMLContentSerializer.cpp
@@ -68,16 +68,17 @@
 #include "nsLWBrkCIID.h"
 #include "nsIScriptElement.h"
 #include "nsAttrName.h"
 #include "nsIDocShell.h"
 #include "nsIEditorDocShell.h"
 #include "nsIEditor.h"
 #include "nsIHTMLEditor.h"
 #include "mozilla/dom/Element.h"
+#include "nsParserConstants.h"
 
 using namespace mozilla::dom;
 
 static const PRInt32 kLongLineLen = 128;
 
 nsresult NS_NewHTMLContentSerializer(nsIContentSerializer** aSerializer)
 {
   nsHTMLContentSerializer* it = new nsHTMLContentSerializer();
--- a/content/base/src/nsParserUtils.cpp
+++ b/content/base/src/nsParserUtils.cpp
@@ -35,22 +35,22 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Namespace class for some static parsing-related methods.
  */
 
 #include "nsParserUtils.h"
-#include "nsIParser.h" // for kQuote et. al.
 #include "jsapi.h"
 #include "nsReadableUtils.h"
 #include "nsCRT.h"
 #include "nsContentUtils.h"
 #include "nsIParserService.h"
+#include "nsParserConstants.h"
 
 #define SKIP_WHITESPACE(iter, end_iter, end_res)                 \
   while ((iter) != (end_iter) && nsCRT::IsAsciiSpace(*(iter))) { \
     ++(iter);                                                    \
   }                                                              \
   if ((iter) == (end_iter)) {                                    \
     return (end_res);                                            \
   }
--- a/content/base/src/nsRange.cpp
+++ b/content/base/src/nsRange.cpp
@@ -2049,17 +2049,17 @@ nsRange::Detach()
 
 // nsIDOMNSRange interface
 NS_IMETHODIMP    
 nsRange::CreateContextualFragment(const nsAString& aFragment,
                                   nsIDOMDocumentFragment** aReturn)
 {
   if (mIsPositioned) {
     return nsContentUtils::CreateContextualFragment(mStartParent, aFragment,
-                                                    PR_TRUE, aReturn);
+                                                    PR_FALSE, aReturn);
   }
   return NS_ERROR_FAILURE;
 }
 
 static void ExtractRectFromOffset(nsIFrame* aFrame,
                                   const nsIFrame* aRelativeTo, 
                                   const PRInt32 aOffset, nsRect* aR, PRBool aKeepLeft)
 {
--- a/content/base/src/nsXHTMLContentSerializer.cpp
+++ b/content/base/src/nsXHTMLContentSerializer.cpp
@@ -63,16 +63,17 @@
 #include "nsEscape.h"
 #include "nsITextToSubURI.h"
 #include "nsCRT.h"
 #include "nsIParserService.h"
 #include "nsContentUtils.h"
 #include "nsLWBrkCIID.h"
 #include "nsIScriptElement.h"
 #include "nsAttrName.h"
+#include "nsParserConstants.h"
 
 static const char kMozStr[] = "moz";
 
 static const PRInt32 kLongLineLen = 128;
 
 #define kXMLNS "xmlns"
 
 nsresult NS_NewXHTMLContentSerializer(nsIContentSerializer** aSerializer)
--- a/content/base/src/nsXMLContentSerializer.cpp
+++ b/content/base/src/nsXMLContentSerializer.cpp
@@ -60,16 +60,17 @@
 #include "nsString.h"
 #include "prprf.h"
 #include "nsUnicharUtils.h"
 #include "nsCRT.h"
 #include "nsContentUtils.h"
 #include "nsAttrName.h"
 #include "nsILineBreaker.h"
 #include "mozilla/dom/Element.h"
+#include "nsParserConstants.h"
 
 using namespace mozilla::dom;
 
 static const char kMozStr[] = "moz";
 
 #define kXMLNS "xmlns"
 
 // to be readable, we assume that an indented line contains
--- a/content/events/src/nsEventListenerManager.cpp
+++ b/content/events/src/nsEventListenerManager.cpp
@@ -583,30 +583,29 @@ nsEventListenerManager::FindJSEventListe
     }
   }
   return nsnull;
 }
 
 nsresult
 nsEventListenerManager::SetJSEventListener(nsIScriptContext *aContext,
                                            void *aScopeObject,
-                                           nsISupports *aObject,
                                            nsIAtom* aName,
                                            PRBool aIsString,
                                            PRBool aPermitUntrustedEvents)
 {
   nsresult rv = NS_OK;
   PRUint32 eventType = nsContentUtils::GetEventId(aName);
   nsListenerStruct* ls = FindJSEventListener(eventType, aName);
 
   if (!ls) {
     // If we didn't find a script listener or no listeners existed
     // create and add a new one.
     nsCOMPtr<nsIDOMEventListener> scriptListener;
-    rv = NS_NewJSEventListener(aContext, aScopeObject, aObject, aName,
+    rv = NS_NewJSEventListener(aContext, aScopeObject, mTarget, aName,
                                getter_AddRefs(scriptListener));
     if (NS_SUCCEEDED(rv)) {
       AddEventListener(scriptListener, eventType, aName, nsnull,
                        NS_EVENT_FLAG_BUBBLE | NS_PRIV_EVENT_FLAG_SCRIPT);
 
       ls = FindJSEventListener(eventType, aName);
     }
   }
@@ -619,18 +618,17 @@ nsEventListenerManager::SetJSEventListen
       ls->mFlags |= NS_PRIV_EVENT_UNTRUSTED_PERMITTED;
     }
   }
 
   return rv;
 }
 
 nsresult
-nsEventListenerManager::AddScriptEventListener(nsISupports *aObject,
-                                               nsIAtom *aName,
+nsEventListenerManager::AddScriptEventListener(nsIAtom *aName,
                                                const nsAString& aBody,
                                                PRUint32 aLanguage,
                                                PRBool aDeferCompilation,
                                                PRBool aPermitUntrustedEvents)
 {
   NS_PRECONDITION(aLanguage != nsIProgrammingLanguage::UNKNOWN,
                   "Must know the language for the script event listener");
   nsIScriptContext *context = nsnull;
@@ -641,42 +639,41 @@ 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;
   }
 
-  nsCOMPtr<nsINode> node(do_QueryInterface(aObject));
+  nsCOMPtr<nsINode> node(do_QueryInterface(mTarget));
 
   nsCOMPtr<nsIDocument> doc;
 
-  nsISupports *objiSupp = aObject;
   nsCOMPtr<nsIScriptGlobalObject> global;
 
   if (node) {
     // Try to get context from doc
     // XXX sXBL/XBL2 issue -- do we really want the owner here?  What
     // if that's the XBL document?
     doc = node->GetOwnerDoc();
     if (doc)
       global = doc->GetScriptGlobalObject();
   } else {
-    nsCOMPtr<nsPIDOMWindow> win(do_QueryInterface(aObject));
+    nsCOMPtr<nsPIDOMWindow> win(do_QueryInterface(mTarget));
     if (win) {
       NS_ASSERTION(win->IsInnerWindow(),
                    "Event listener added to outer window!");
 
       nsCOMPtr<nsIDOMDocument> domdoc;
       win->GetDocument(getter_AddRefs(domdoc));
       doc = do_QueryInterface(domdoc);
       global = do_QueryInterface(win);
     } else {
-      global = do_QueryInterface(aObject);
+      global = do_QueryInterface(mTarget);
     }
   }
 
   if (!global) {
     // This can happen; for example this document might have been
     // loaded as data.
     return NS_OK;
   }
@@ -697,17 +694,17 @@ nsEventListenerManager::AddScriptEventLi
       if ( !inlineOK ) {
         // gather information to log with violation report
         nsIURI* uri = doc->GetDocumentURI();
         nsCAutoString asciiSpec;
         if (uri)
           uri->GetAsciiSpec(asciiSpec);
         nsAutoString scriptSample, attr, tagName(NS_LITERAL_STRING("UNKNOWN"));
         aName->ToString(attr);
-        nsCOMPtr<nsIDOMNode> domNode(do_QueryInterface(aObject));
+        nsCOMPtr<nsIDOMNode> domNode(do_QueryInterface(mTarget));
         if (domNode)
           domNode->GetNodeName(tagName);
         // build a "script sample" based on what we know about this element
         scriptSample.Assign(attr);
         scriptSample.AppendLiteral(" attribute on ");
         scriptSample.Append(tagName);
         scriptSample.AppendLiteral(" element");
         csp->LogViolationDetails(nsIContentSecurityPolicy::VIOLATION_TYPE_INLINE_SCRIPT,
@@ -728,25 +725,25 @@ nsEventListenerManager::AddScriptEventLi
 
   context = global->GetScriptContext(aLanguage);
   NS_ENSURE_TRUE(context, NS_ERROR_FAILURE);
 
   void *scope = global->GetScriptGlobal(aLanguage);
 
   if (!aDeferCompilation) {
     nsCOMPtr<nsIScriptEventHandlerOwner> handlerOwner =
-      do_QueryInterface(aObject);
+      do_QueryInterface(mTarget);
 
     nsScriptObjectHolder handler(context);
     PRBool done = PR_FALSE;
 
     if (handlerOwner) {
       rv = handlerOwner->GetCompiledEventHandler(aName, handler);
       if (NS_SUCCEEDED(rv) && handler) {
-        rv = context->BindCompiledEventHandler(aObject, scope, aName, handler);
+        rv = context->BindCompiledEventHandler(mTarget, scope, aName, handler);
         if (NS_FAILED(rv))
           return rv;
         done = PR_TRUE;
       }
     }
 
     if (!done) {
       PRUint32 lineNo = 0;
@@ -757,17 +754,17 @@ nsEventListenerManager::AddScriptEventLi
           uri->GetSpec(url);
           lineNo = 1;
         }
       }
 
       if (handlerOwner) {
         // Always let the handler owner compile the event handler, as
         // it may want to use a special context or scope object.
-        rv = handlerOwner->CompileEventHandler(context, aObject, aName,
+        rv = handlerOwner->CompileEventHandler(context, mTarget, aName,
                                                aBody, url.get(), lineNo, handler);
       }
       else {
         PRInt32 nameSpace = kNameSpaceID_Unknown;
         if (node && node->IsNodeOfType(nsINode::eCONTENT)) {
           nsIContent* content = static_cast<nsIContent*>(node.get());
           nameSpace = content->GetNameSpaceID();
         }
@@ -792,24 +789,24 @@ nsEventListenerManager::AddScriptEventLi
                                           SCRIPTVERSION_DEFAULT, // for now?
                                           handler);
         if (rv == NS_ERROR_ILLEGAL_VALUE) {
           NS_WARNING("Probably a syntax error in the event handler!");
           return NS_SUCCESS_LOSS_OF_INSIGNIFICANT_DATA;
         }
         NS_ENSURE_SUCCESS(rv, rv);
         // And bind it.
-        rv = context->BindCompiledEventHandler(aObject, scope,
+        rv = context->BindCompiledEventHandler(mTarget, scope,
                                                aName, handler);
       }
       if (NS_FAILED(rv)) return rv;
     }
   }
 
-  return SetJSEventListener(context, scope, objiSupp, aName, aDeferCompilation,
+  return SetJSEventListener(context, scope, aName, aDeferCompilation,
                             aPermitUntrustedEvents);
 }
 
 void
 nsEventListenerManager::RemoveScriptEventListener(nsIAtom* aName)
 {
   PRUint32 eventType = nsContentUtils::GetEventId(aName);
   nsListenerStruct* ls = FindJSEventListener(eventType, aName);
@@ -822,25 +819,24 @@ nsEventListenerManager::RemoveScriptEven
 }
 
 jsid
 nsEventListenerManager::sAddListenerID = JSID_VOID;
 
 nsresult
 nsEventListenerManager::RegisterScriptEventListener(nsIScriptContext *aContext,
                                                     void *aScope,
-                                                    nsISupports *aObject, 
                                                     nsIAtom *aName)
 {
   // Check that we have access to set an event listener. Prevents
   // snooping attacks across domains by setting onkeypress handlers,
   // for instance.
   // You'd think it'd work just to get the JSContext from aContext,
   // but that's actually the JSContext whose private object parents
-  // the object in aObject.
+  // the object in mTarget.
   nsresult rv;
   nsCOMPtr<nsIJSContextStack> stack =
     do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv);
   if (NS_FAILED(rv))
     return rv;
   JSContext *cx;
   if (NS_FAILED(rv = stack->Peek(&cx)))
     return rv;
@@ -850,17 +846,17 @@ nsEventListenerManager::RegisterScriptEv
       JSAutoRequest ar(cx);
       sAddListenerID =
         INTERNED_STRING_TO_JSID(cx, ::JS_InternString(cx, "addEventListener"));
     }
 
     if (aContext->GetScriptTypeID() == nsIProgrammingLanguage::JAVASCRIPT) {
         nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
         jsval v;
-        rv = nsContentUtils::WrapNative(cx, (JSObject *)aScope, aObject, &v,
+        rv = nsContentUtils::WrapNative(cx, (JSObject *)aScope, mTarget, &v,
                                         getter_AddRefs(holder));
         NS_ENSURE_SUCCESS(rv, rv);
       
         rv = nsContentUtils::GetSecurityManager()->
           CheckPropertyAccess(cx, JSVAL_TO_OBJECT(v),
                               "EventTarget",
                               sAddListenerID,
                               nsIXPCSecurityManager::ACCESS_SET_PROPERTY);
@@ -871,39 +867,38 @@ nsEventListenerManager::RegisterScriptEv
     } else {
         NS_WARNING("Skipping CheckPropertyAccess for non JS language");
     }
         
   }
 
   // Untrusted events are always permitted for non-chrome script
   // handlers.
-  return SetJSEventListener(aContext, aScope, aObject, aName,
-                            PR_FALSE, !nsContentUtils::IsCallerChrome());
+  return SetJSEventListener(aContext, aScope, aName, PR_FALSE,
+                            !nsContentUtils::IsCallerChrome());
 }
 
 nsresult
 nsEventListenerManager::CompileScriptEventListener(nsIScriptContext *aContext, 
                                                    void *aScope,
-                                                   nsISupports *aObject, 
                                                    nsIAtom *aName,
                                                    PRBool *aDidCompile)
 {
   nsresult rv = NS_OK;
   *aDidCompile = PR_FALSE;
   PRUint32 eventType = nsContentUtils::GetEventId(aName);
   nsListenerStruct* ls = FindJSEventListener(eventType, aName);
 
   if (!ls) {
     //nothing to compile
     return NS_OK;
   }
 
   if (ls->mHandlerIsString) {
-    rv = CompileEventHandlerInternal(aContext, aScope, aObject, aName,
+    rv = CompileEventHandlerInternal(aContext, aScope, mTarget, aName,
                                      ls, /*XXX fixme*/nsnull, PR_TRUE);
   }
 
   // Set *aDidCompile to true even if we didn't really compile
   // anything right now, if we get here it means that this event
   // handler has been compiled at some point, that's good enough for
   // us.
 
--- a/content/events/src/nsEventListenerManager.h
+++ b/content/events/src/nsEventListenerManager.h
@@ -102,30 +102,27 @@ public:
   void RemoveEventListenerByIID(nsIDOMEventListener *aListener,
                                 const nsIID& aIID, PRInt32 aFlags);
   nsresult AddEventListenerByType(nsIDOMEventListener *aListener,
                                   const nsAString& type,
                                   PRInt32 aFlags);
   void RemoveEventListenerByType(nsIDOMEventListener *aListener,
                                  const nsAString& type,
                                  PRInt32 aFlags);
-  nsresult AddScriptEventListener(nsISupports *aObject,
-                                  nsIAtom *aName,
+  nsresult AddScriptEventListener(nsIAtom *aName,
                                   const nsAString& aFunc,
                                   PRUint32 aLanguage,
                                   PRBool aDeferCompilation,
                                   PRBool aPermitUntrustedEvents);
   nsresult RegisterScriptEventListener(nsIScriptContext *aContext,
                                        void *aScopeObject,
-                                       nsISupports *aObject,
                                        nsIAtom* aName);
   void RemoveScriptEventListener(nsIAtom *aName);
   nsresult CompileScriptEventListener(nsIScriptContext *aContext,
                                       void *aScopeObject,
-                                      nsISupports *aObject,
                                       nsIAtom* aName, PRBool *aDidCompile);
 
   void HandleEvent(nsPresContext* aPresContext,
                    nsEvent* aEvent, 
                    nsIDOMEvent** aDOMEvent,
                    nsIDOMEventTarget* aCurrentTarget,
                    PRUint32 aFlags,
                    nsEventStatus* aEventStatus,
@@ -211,17 +208,16 @@ protected:
                                        nsISupports *aObject,
                                        nsIAtom *aName,
                                        nsListenerStruct *aListenerStruct,
                                        nsISupports* aCurrentTarget,
                                        PRBool aNeedsCxPush);
   nsListenerStruct* FindJSEventListener(PRUint32 aEventType, nsIAtom* aTypeAtom);
   nsresult SetJSEventListener(nsIScriptContext *aContext,
                               void *aScopeGlobal,
-                              nsISupports *aObject,
                               nsIAtom* aName, PRBool aIsString,
                               PRBool aPermitUntrustedEvents);
   nsresult AddEventListener(nsIDOMEventListener *aListener, 
                             PRUint32 aType,
                             nsIAtom* aTypeAtom,
                             const EventTypeData* aTypeData,
                             PRInt32 aFlags);
   void RemoveEventListener(nsIDOMEventListener *aListener,
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -1503,16 +1503,45 @@ nsEventStateManager::ExecuteAccessKey(ns
         }
         return PR_TRUE;
       }
     }
   }
   return PR_FALSE;
 }
 
+PRBool
+nsEventStateManager::GetAccessKeyLabelPrefix(nsAString& aPrefix)
+{
+  aPrefix.Truncate();
+  nsAutoString separator, modifierText;
+  nsContentUtils::GetModifierSeparatorText(separator);
+
+  nsCOMPtr<nsISupports> container = mPresContext->GetContainer();
+  PRInt32 modifier = GetAccessModifierMask(container);
+
+  if (modifier & NS_MODIFIER_CONTROL) {
+    nsContentUtils::GetControlText(modifierText);
+    aPrefix.Append(modifierText + separator);
+  }
+  if (modifier & NS_MODIFIER_META) {
+    nsContentUtils::GetMetaText(modifierText);
+    aPrefix.Append(modifierText + separator);
+  }
+  if (modifier & NS_MODIFIER_ALT) {
+    nsContentUtils::GetAltText(modifierText);
+    aPrefix.Append(modifierText + separator);
+  }
+  if (modifier & NS_MODIFIER_SHIFT) {
+    nsContentUtils::GetShiftText(modifierText);
+    aPrefix.Append(modifierText + separator);
+  }
+  return !aPrefix.IsEmpty();
+}
+
 void
 nsEventStateManager::HandleAccessKey(nsPresContext* aPresContext,
                                      nsKeyEvent *aEvent,
                                      nsEventStatus* aStatus,
                                      nsIDocShellTreeItem* aBubbledFrom,
                                      ProcessingAccessKeyState aAccessKeyState,
                                      PRInt32 aModifierMask)
 {
--- a/content/events/src/nsEventStateManager.h
+++ b/content/events/src/nsEventStateManager.h
@@ -155,16 +155,18 @@ public:
   /**
    * Get accesskey registered on the given element or 0 if there is none.
    *
    * @param  aContent  the given element
    * @return           registered accesskey
    */
   PRUint32 GetRegisteredAccessKey(nsIContent* aContent);
 
+  PRBool GetAccessKeyLabelPrefix(nsAString& aPrefix);
+
   nsresult SetCursor(PRInt32 aCursor, imgIContainer* aContainer,
                      PRBool aHaveHotspot, float aHotspotX, float aHotspotY,
                      nsIWidget* aWidget, PRBool aLockCursor); 
 
   static void StartHandlingUserInput()
   {
     ++sUserInputEventDepth;
   }
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -458,16 +458,31 @@ nsresult
 nsGenericHTMLElement::SetClassName(const nsAString& aClassName)
 {
   SetAttr(kNameSpaceID_None, nsGkAtoms::_class, aClassName, PR_TRUE);
   return NS_OK;
 }
 
 NS_IMPL_STRING_ATTR(nsGenericHTMLElement, AccessKey, accesskey)
 
+NS_IMETHODIMP
+nsGenericHTMLElement::GetAccessKeyLabel(nsAString& aLabel)
+{
+  nsPresContext *presContext = GetPresContext();
+
+  if (presContext &&
+    presContext->EventStateManager()->GetAccessKeyLabelPrefix(aLabel)) {
+      nsAutoString suffix;
+      GetAccessKey(suffix);
+      aLabel.Append(suffix);
+  }
+
+  return NS_OK;
+}
+
 static PRBool
 IsBody(nsIContent *aContent)
 {
   return aContent->NodeInfo()->Equals(nsGkAtoms::body) &&
          aContent->IsHTML();
 }
 
 static PRBool IS_TABLE_CELL(nsIAtom* frameType) {
@@ -701,97 +716,179 @@ nsGenericHTMLElement::GetInnerHTML(nsASt
   NS_ENSURE_SUCCESS(rv, rv);
 
   docEncoder->SetNativeContainerNode(this);
   rv = docEncoder->EncodeToString(aInnerHTML);
   doc->SetCachedEncoder(docEncoder.forget());
   return rv;
 }
 
+void
+nsGenericHTMLElement::FireMutationEventsForDirectParsing(nsIDocument* aDoc,
+                                                         nsIContent* aDest,
+                                                         PRInt32 aOldChildCount)
+{
+  // Fire mutation events. Optimize for the case when there are no listeners
+  PRInt32 newChildCount = aDest->GetChildCount();
+  if (newChildCount && nsContentUtils::
+        HasMutationListeners(aDoc, NS_EVENT_BITS_MUTATION_NODEINSERTED)) {
+    nsAutoTArray<nsCOMPtr<nsIContent>, 50> childNodes;
+    NS_ASSERTION(newChildCount - aOldChildCount >= 0,
+                 "What, some unexpected dom mutation has happened?");
+    childNodes.SetCapacity(newChildCount - aOldChildCount);
+    for (nsINode::ChildIterator iter(aDest); !iter.IsDone(); iter.Next()) {
+      childNodes.AppendElement(iter);
+    }
+    nsGenericElement::FireNodeInserted(aDoc, aDest, childNodes);
+  }
+}
+
 nsresult
 nsGenericHTMLElement::SetInnerHTML(const nsAString& aInnerHTML)
 {
   nsIDocument* doc = GetOwnerDoc();
   NS_ENSURE_STATE(doc);
 
   nsresult rv = NS_OK;
 
   // Batch possible DOMSubtreeModified events.
   mozAutoSubtreeModified subtree(doc, nsnull);
 
   FireNodeRemovedForChildren();
 
-  // This BeginUpdate/EndUpdate pair is important to make us reenable the
-  // scriptloader before the last EndUpdate call.
+  // Needed when innerHTML is used in combination with contenteditable
   mozAutoDocUpdate updateBatch(doc, UPDATE_CONTENT_MODEL, PR_TRUE);
 
   // Remove childnodes.
   // i is unsigned, so i >= is always true
   for (PRUint32 i = GetChildCount(); i-- != 0; ) {
     RemoveChildAt(i, PR_TRUE);
   }
 
   nsCOMPtr<nsIDOMDocumentFragment> df;
 
-  // Strong ref since appendChild can fire events
-  nsRefPtr<nsScriptLoader> loader = doc->ScriptLoader();
-  PRBool scripts_enabled = loader->GetEnabled();
-  loader->SetEnabled(PR_FALSE);
-
-  if (doc->IsHTML() && nsHtml5Module::sEnabled) {
-    nsCOMPtr<nsIParser> parser = doc->GetFragmentParser();
-    if (parser) {
-      parser->Reset();
-    } else {
-      parser = nsHtml5Module::NewHtml5Parser();
-      NS_ENSURE_TRUE(parser, NS_ERROR_OUT_OF_MEMORY);
-    }
-
+  if (doc->IsHTML()) {
     PRInt32 oldChildCount = GetChildCount();
-    nsAHtml5FragmentParser* asFragmentParser =
-        static_cast<nsAHtml5FragmentParser*> (parser.get());
-    asFragmentParser->ParseHtml5Fragment(aInnerHTML,
-                                         this,
-                                         Tag(),
-                                         GetNameSpaceID(),
-                                         doc->GetCompatibilityMode() ==
-                                             eCompatibility_NavQuirks,
-                                         PR_TRUE);
-    doc->SetFragmentParser(parser);
-
+    nsContentUtils::ParseFragmentHTML(aInnerHTML,
+                                      this,
+                                      Tag(),
+                                      GetNameSpaceID(),
+                                      doc->GetCompatibilityMode() ==
+                                          eCompatibility_NavQuirks,
+                                      PR_TRUE);
     // HTML5 parser has notified, but not fired mutation events.
-    // Fire mutation events. Optimize for the case when there are no listeners
-    PRInt32 newChildCount = GetChildCount();
-    if (newChildCount && nsContentUtils::
-          HasMutationListeners(doc, NS_EVENT_BITS_MUTATION_NODEINSERTED)) {
-      nsAutoTArray<nsCOMPtr<nsIContent>, 50> childNodes;
-      NS_ASSERTION(newChildCount - oldChildCount >= 0,
-                   "What, some unexpected dom mutation has happened?");
-      childNodes.SetCapacity(newChildCount - oldChildCount);
-      for (nsINode::ChildIterator iter(this); !iter.IsDone(); iter.Next()) {
-        childNodes.AppendElement(iter);
-      }
-      nsGenericElement::FireNodeInserted(doc, this, childNodes);
-    }
+    FireMutationEventsForDirectParsing(doc, this, oldChildCount);
   } else {
-    rv = nsContentUtils::CreateContextualFragment(this, aInnerHTML, PR_FALSE,
+    rv = nsContentUtils::CreateContextualFragment(this, aInnerHTML,
+                                                  PR_TRUE,
                                                   getter_AddRefs(df));
     nsCOMPtr<nsINode> fragment = do_QueryInterface(df);
     if (NS_SUCCEEDED(rv)) {
       static_cast<nsINode*>(this)->AppendChild(fragment, &rv);
     }
   }
 
-  if (scripts_enabled) {
-    // If we disabled scripts, re-enable them now that we're
-    // done. Don't fire JS timeouts when enabling the context here.
-
-    loader->SetEnabled(PR_TRUE);
+  return rv;
+}
+
+enum nsAdjacentPosition {
+  eBeforeBegin,
+  eAfterBegin,
+  eBeforeEnd,
+  eAfterEnd
+};
+
+nsresult
+nsGenericHTMLElement::InsertAdjacentHTML(const nsAString& aPosition,
+                                         const nsAString& aText)
+{
+  nsAdjacentPosition position;
+  if (aPosition.LowerCaseEqualsLiteral("beforebegin")) {
+    position = eBeforeBegin;
+  } else if (aPosition.LowerCaseEqualsLiteral("afterbegin")) {
+    position = eAfterBegin;
+  } else if (aPosition.LowerCaseEqualsLiteral("beforeend")) {
+    position = eBeforeEnd;
+  } else if (aPosition.LowerCaseEqualsLiteral("afterend")) {
+    position = eAfterEnd;
+  } else {
+    return NS_ERROR_DOM_SYNTAX_ERR;
+  }
+
+  nsCOMPtr<nsIContent> destination;
+  if (position == eBeforeBegin || position == eAfterEnd) {
+    destination = GetParent();
+    if (!destination) {
+      return NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR;
+    }
+  } else {
+    destination = this;
   }
 
+  nsIDocument* doc = GetOwnerDoc();
+  NS_ENSURE_STATE(doc);
+
+  // Needed when insertAdjacentHTML is used in combination with contenteditable
+  mozAutoDocUpdate updateBatch(doc, UPDATE_CONTENT_MODEL, PR_TRUE);
+
+  // Batch possible DOMSubtreeModified events.
+  mozAutoSubtreeModified subtree(doc, nsnull);
+
+  // Parse directly into destination if possible
+  if (doc->IsHTML() &&
+      (position == eBeforeEnd ||
+       (position == eAfterEnd && !GetNextSibling()) ||
+       (position == eAfterBegin && !GetFirstChild()))) {
+    PRInt32 oldChildCount = destination->GetChildCount();
+    PRInt32 contextNs = destination->GetNameSpaceID();
+    nsIAtom* contextLocal = destination->Tag();
+    if (contextLocal == nsGkAtoms::html && contextNs == kNameSpaceID_XHTML) {
+      // For compat with IE6 through IE9. Willful violation of HTML5 as of
+      // 2011-04-06. CreateContextualFragment does the same already.
+      // Spec bug: http://www.w3.org/Bugs/Public/show_bug.cgi?id=12434
+      contextLocal = nsGkAtoms::body;
+    }
+    nsContentUtils::ParseFragmentHTML(aText,
+                                      destination,
+                                      contextLocal,
+                                      contextNs,
+                                      doc->GetCompatibilityMode() ==
+                                          eCompatibility_NavQuirks,
+                                      PR_TRUE);
+    // HTML5 parser has notified, but not fired mutation events.
+    FireMutationEventsForDirectParsing(doc, destination, oldChildCount);
+    return NS_OK;
+  }
+
+  // couldn't parse directly
+  nsCOMPtr<nsIDOMDocumentFragment> df;
+  nsresult rv = nsContentUtils::CreateContextualFragment(destination,
+                                                         aText,
+                                                         PR_TRUE,
+                                                         getter_AddRefs(df));
+  nsCOMPtr<nsINode> fragment = do_QueryInterface(df);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  switch (position) {
+    case eBeforeBegin:
+      destination->InsertBefore(fragment, this, &rv);
+      break;
+    case eAfterBegin:
+      static_cast<nsINode*>(this)->InsertBefore(fragment, GetFirstChild(), &rv);
+      break;
+    case eBeforeEnd:
+      static_cast<nsINode*>(this)->AppendChild(fragment, &rv);
+      break;
+    case eAfterEnd:
+      destination->InsertBefore(fragment, GetNextSibling(), &rv);
+      break;
+    default:
+      NS_NOTREACHED("Bad position.");
+      break;
+  }
   return rv;
 }
 
 nsresult
 nsGenericHTMLElement::ScrollIntoView(PRBool aTop, PRUint8 optional_argc)
 {
   nsIDocument *document = GetCurrentDoc();
 
@@ -1118,62 +1215,47 @@ nsGenericHTMLElement::AfterSetAttr(PRInt
       SyncEditorsOnSubtree(this);
     }
   }
 
   return nsGenericHTMLElementBase::AfterSetAttr(aNamespaceID, aName,
                                                 aValue, aNotify);
 }
 
-nsresult
-nsGenericHTMLElement::GetEventListenerManagerForAttr(nsEventListenerManager** aManager,
-                                                     nsISupports** aTarget,
-                                                     PRBool* aDefer)
+nsEventListenerManager*
+nsGenericHTMLElement::GetEventListenerManagerForAttr(PRBool* aDefer)
 {
   // Attributes on the body and frameset tags get set on the global object
   if (mNodeInfo->Equals(nsGkAtoms::body) ||
       mNodeInfo->Equals(nsGkAtoms::frameset)) {
     nsPIDOMWindow *win;
 
     // If we have a document, and it has a window, add the event
     // listener on the window (the inner window). If not, proceed as
     // normal.
     // XXXbz sXBL/XBL2 issue: should we instead use GetCurrentDoc() here,
     // override BindToTree for those classes and munge event listeners there?
     nsIDocument *document = GetOwnerDoc();
-    nsresult rv = NS_OK;
 
     // FIXME (https://bugzilla.mozilla.org/show_bug.cgi?id=431767)
     // nsDocument::GetInnerWindow can return an outer window in some cases,
     // we don't want to stick an event listener on an outer window, so
     // bail if it does.
+    *aDefer = PR_FALSE;
     if (document &&
         (win = document->GetInnerWindow()) && win->IsInnerWindow()) {
       nsCOMPtr<nsIDOMEventTarget> piTarget(do_QueryInterface(win));
-      NS_ENSURE_TRUE(piTarget, NS_ERROR_FAILURE);
-
-      *aManager = piTarget->GetListenerManager(PR_TRUE);
-
-      if (*aManager) {
-        NS_ADDREF(*aTarget = win);
-        NS_ADDREF(*aManager);
-      }
-      *aDefer = PR_FALSE;
-    } else {
-      *aManager = nsnull;
-      *aTarget = nsnull;
-      *aDefer = PR_FALSE;
+
+      return piTarget->GetListenerManager(PR_TRUE);
     }
 
-    return rv;
+    return nsnull;
   }
 
-  return nsGenericHTMLElementBase::GetEventListenerManagerForAttr(aManager,
-                                                                  aTarget,
-                                                                  aDefer);
+  return nsGenericHTMLElementBase::GetEventListenerManagerForAttr(aDefer);
 }
 
 nsresult
 nsGenericHTMLElement::SetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
                               nsIAtom* aPrefix, const nsAString& aValue,
                               PRBool aNotify)
 {
   PRBool contentEditable = aNameSpaceID == kNameSpaceID_None &&
--- a/content/html/content/src/nsGenericHTMLElement.h
+++ b/content/html/content/src/nsGenericHTMLElement.h
@@ -130,16 +130,18 @@ public:
   // methods.
   nsresult GetOffsetTop(PRInt32* aOffsetTop);
   nsresult GetOffsetLeft(PRInt32* aOffsetLeft);
   nsresult GetOffsetWidth(PRInt32* aOffsetWidth);
   nsresult GetOffsetHeight(PRInt32* aOffsetHeight);
   nsresult GetOffsetParent(nsIDOMElement** aOffsetParent);
   virtual nsresult GetInnerHTML(nsAString& aInnerHTML);
   virtual nsresult SetInnerHTML(const nsAString& aInnerHTML);
+  virtual nsresult InsertAdjacentHTML(const nsAString& aPosition,
+                                      const nsAString& aText);
   nsresult ScrollIntoView(PRBool aTop, PRUint8 optional_argc);
   // Declare Focus(), Blur(), GetTabIndex(), SetTabIndex(), GetHidden(),
   // SetHidden(), GetSpellcheck(), SetSpellcheck(), and GetDraggable() such that
   // classes that inherit interfaces with those methods properly override them.
   NS_IMETHOD Focus();
   NS_IMETHOD Blur();
   NS_IMETHOD Click();
   NS_IMETHOD GetTabIndex(PRInt32 *aTabIndex);
@@ -147,16 +149,17 @@ public:
   NS_IMETHOD GetHidden(PRBool* aHidden);
   NS_IMETHOD SetHidden(PRBool aHidden);
   NS_IMETHOD GetSpellcheck(PRBool* aSpellcheck);
   NS_IMETHOD SetSpellcheck(PRBool aSpellcheck);
   NS_IMETHOD GetDraggable(PRBool* aDraggable);
   NS_IMETHOD SetDraggable(PRBool aDraggable);
   NS_IMETHOD GetAccessKey(nsAString &aAccessKey);
   NS_IMETHOD SetAccessKey(const nsAString& aAccessKey);
+  NS_IMETHOD GetAccessKeyLabel(nsAString& aLabel);
   nsresult GetContentEditable(nsAString& aContentEditable);
   nsresult GetIsContentEditable(PRBool* aContentEditable);
   nsresult SetContentEditable(const nsAString &aContentEditable);
   nsresult GetDataset(nsIDOMDOMStringMap** aDataset);
   // Callback for destructor of of dataset to ensure to null out weak pointer.
   nsresult ClearDataset();
 
   // Implementation for nsIContent
@@ -565,33 +568,43 @@ protected:
   void UnregAccessKey()
   {
     if (HasFlag(NODE_HAS_ACCESSKEY)) {
       RegUnRegAccessKey(PR_FALSE);
     }
   }
 
 private:
+  /**
+   * Fire mutation events for changes caused by parsing directly into a
+   * context node.
+   *
+   * @param aDoc the document of the node
+   * @param aDest the destination node that got stuff appended to it
+   * @param aOldChildCount the number of children the node had before parsing
+   */
+  void FireMutationEventsForDirectParsing(nsIDocument* aDoc,
+                                          nsIContent* aDest,
+                                          PRInt32 aOldChildCount);
+
   void RegUnRegAccessKey(PRBool aDoReg);
 
 protected:
   /**
    * Determine whether an attribute is an event (onclick, etc.)
    * @param aName the attribute
    * @return whether the name is an event handler name
    */
   PRBool IsEventName(nsIAtom* aName);
 
   virtual nsresult AfterSetAttr(PRInt32 aNamespaceID, nsIAtom* aName,
                                 const nsAString* aValue, PRBool aNotify);
 
-  virtual nsresult
-    GetEventListenerManagerForAttr(nsEventListenerManager** aManager,
-                                   nsISupports** aTarget,
-                                   PRBool* aDefer);
+  virtual nsEventListenerManager*
+    GetEventListenerManagerForAttr(PRBool* aDefer);
 
   virtual const nsAttrName* InternalGetExistingAttrNameFromQName(const nsAString& aStr) const;
 
   /**
    * Helper method for NS_IMPL_STRING_ATTR macro.
    * Gets the value of an attribute, returns empty string if
    * attribute isn't set. Only works for attributes in null namespace.
    *
@@ -1468,16 +1481,17 @@ protected:
   NS_SCRIPTABLE NS_IMETHOD GetLang(nsAString & aLang) { return _to GetLang(aLang); } \
   NS_SCRIPTABLE NS_IMETHOD SetLang(const nsAString & aLang) { return _to SetLang(aLang); } \
   NS_SCRIPTABLE NS_IMETHOD GetDir(nsAString & aDir) { return _to GetDir(aDir); } \
   NS_SCRIPTABLE NS_IMETHOD SetDir(const nsAString & aDir) { return _to SetDir(aDir); } \
   NS_SCRIPTABLE NS_IMETHOD GetClassName(nsAString & aClassName) { return _to GetClassName(aClassName); } \
   NS_SCRIPTABLE NS_IMETHOD SetClassName(const nsAString & aClassName) { return _to SetClassName(aClassName); } \
   NS_SCRIPTABLE NS_IMETHOD GetAccessKey(nsAString & aAccessKey) { return _to GetAccessKey(aAccessKey); } \
   NS_SCRIPTABLE NS_IMETHOD SetAccessKey(const nsAString & aAccessKey) { return _to SetAccessKey(aAccessKey); } \
+  NS_SCRIPTABLE NS_IMETHOD GetAccessKeyLabel(nsAString & aLabel) { return _to GetAccessKeyLabel(aLabel); } \
   NS_SCRIPTABLE NS_IMETHOD Blur(void) { return _to Blur(); }
 
 /**
  * A macro to declare the NS_NewHTMLXXXElement() functions.
  */
 #define NS_DECLARE_NS_NEW_HTML_ELEMENT(_elementName)                       \
 nsGenericHTMLElement*                                                      \
 NS_NewHTML##_elementName##Element(already_AddRefed<nsINodeInfo> aNodeInfo, \
--- a/content/html/content/src/nsHTMLCanvasElement.cpp
+++ b/content/html/content/src/nsHTMLCanvasElement.cpp
@@ -507,17 +507,16 @@ nsHTMLCanvasElement::GetContext(const ns
         }
       }
 
       contextProps = newProps;
     }
 
     rv = UpdateContext(contextProps);
     if (NS_FAILED(rv)) {
-      mCurrentContext = nsnull;
       if (!forceThebes) {
         // Try again with a Thebes context
         forceThebes = PR_TRUE;
         continue;
       }
       return rv;
     }
 
@@ -553,20 +552,17 @@ nsHTMLCanvasElement::MozGetIPCContext(co
     NS_ENSURE_SUCCESS(rv, rv);
     if (!mCurrentContext) {
       return NS_OK;
     }
 
     mCurrentContext->SetIsIPC(PR_TRUE);
 
     rv = UpdateContext();
-    if (NS_FAILED(rv)) {
-      mCurrentContext = nsnull;
-      return rv;
-    }
+    NS_ENSURE_SUCCESS(rv, rv);
 
     mCurrentContextId.Assign(aContextId);
   } else if (!mCurrentContextId.Equals(aContextId)) {
     //XXX eventually allow for more than one active context on a given canvas
     return NS_ERROR_INVALID_ARG;
   }
 
   NS_ADDREF (*aContext = mCurrentContext);
--- a/content/html/content/test/Makefile.in
+++ b/content/html/content/test/Makefile.in
@@ -273,13 +273,14 @@ include $(topsrcdir)/config/rules.mk
 		test_bug658746.html \
 		test_bug659596.html \
 		test_bug659743.xml \
 		test_bug660663.html \
 		test_bug664299.html \
 		test_bug666200.html \
 		test_bug666666.html \
 		test_bug674558.html \
+		test_bug583533.html \
 		test_restore_from_parser_fragment.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug583533.html
@@ -0,0 +1,76 @@
+<!DOCTYPE HTML>
+<html>
+    <!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=583533
+-->
+    <head>
+        <title>Test for Bug 583514</title>
+        <script type="application/javascript" src="/MochiKit/packed.js"></script>
+        <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+        <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+    </head>
+    <body>
+        <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=583533">Mozilla Bug 583533</a>
+        <p id="display"></p>
+        <div id="content">
+            <div id="e" accesskey="a">
+  </div>
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+    /** Test for Bug 583533 **/
+
+    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+
+    var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"].
+    getService(Components.interfaces.nsIStringBundleService);
+    var bundle = sbs.createBundle("chrome://global-platform/locale/platformKeys.properties");
+    
+    var shiftText = bundle.GetStringFromName("VK_SHIFT");
+    var altText = bundle.GetStringFromName("VK_ALT");
+    var controlText = bundle.GetStringFromName("VK_CONTROL");
+    var metaText = bundle.GetStringFromName("VK_META");
+    var separatorText = bundle.GetStringFromName("MODIFIER_SEPARATOR");
+
+    var modifier = Components.classes["@mozilla.org/preferences-service;1"]
+                                      .getService(Components.interfaces.nsIPrefBranch)
+                                      .getIntPref("ui.key.contentAccess");
+                                      
+    var domEvent = Components.interfaces.nsIDOMNSEvent;
+    
+    var isShift;
+    var isAlt;
+    var isControl;
+    var isMeta;
+
+    is(modifier < 16 && modifier >= 0, true, "Modifier in range");
+
+    if (modifier & domEvent.META_MASK)
+        isMeta = true;
+    if (modifier & domEvent.SHIFT_MASK)
+        isShift = true;
+    if (modifier & domEvent.CONTROL_MASK)
+        isControl = true;
+    if (modifier & domEvent.ALT_MASK)
+        isAlt = true;
+
+    var label = "";
+
+    if (isControl)
+        label += controlText + separatorText;
+    if (isMeta)
+        label += metaText + separatorText;
+    if (isAlt)
+        label += altText + separatorText;
+    if (isShift)
+        label += shiftText + separatorText;
+
+    label += document.getElementById("e").accessKey;
+
+    is(label, document.getElementById("e").accessKeyLabel, "JS and C++ agree on accessKeyLabel");
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/html/document/src/Makefile.in
+++ b/content/html/document/src/Makefile.in
@@ -44,17 +44,16 @@ include $(DEPTH)/config/autoconf.mk
 
 MODULE		= content
 LIBRARY_NAME	= gkconhtmldoc_s
 LIBXUL_LIBRARY	= 1
 
 
 CPPSRCS		= \
 		nsHTMLContentSink.cpp \
-		nsHTMLFragmentContentSink.cpp \
 		nsHTMLDocument.cpp \
 		ImageDocument.cpp \
 		MediaDocument.cpp \
 		PluginDocument.cpp \
 		$(NULL)
 
 ifdef MOZ_MEDIA
 CPPSRCS += VideoDocument.cpp
--- a/content/html/document/src/nsHTMLContentSink.cpp
+++ b/content/html/document/src/nsHTMLContentSink.cpp
@@ -2627,18 +2627,20 @@ HTMLContentSink::ProcessLINKTag(const ns
     }
 
     mCurrentContext->AddLeaf(element); // <link>s are leaves
 
     if (ssle) {
       ssle->SetEnableUpdates(PR_TRUE);
       PRBool willNotify;
       PRBool isAlternate;
-      result = ssle->UpdateStyleSheet(this, &willNotify, &isAlternate);
-      if (NS_SUCCEEDED(result) && willNotify && !isAlternate) {
+      result = ssle->UpdateStyleSheet(mFragmentMode ? nsnull : this,
+                                      &willNotify,
+                                      &isAlternate);
+      if (NS_SUCCEEDED(result) && willNotify && !isAlternate && !mFragmentMode) {
         ++mPendingSheetCount;
         mScriptLoader->AddExecuteBlocker();
       }
 
       // look for <link rel="next" href="url">
       nsAutoString relVal;
       element->GetAttr(kNameSpaceID_None, nsGkAtoms::rel, relVal);
       if (!relVal.IsEmpty()) {
@@ -2840,18 +2842,20 @@ HTMLContentSink::ProcessSTYLEEndTag(nsGe
   nsresult rv = NS_OK;
 
   if (ssle) {
     // Note: if we are inside a noXXX tag, then we init'ed this style element
     // with mDontLoadStyle = PR_TRUE, so these two calls will have no effect.
     ssle->SetEnableUpdates(PR_TRUE);
     PRBool willNotify;
     PRBool isAlternate;
-    rv = ssle->UpdateStyleSheet(this, &willNotify, &isAlternate);
-    if (NS_SUCCEEDED(rv) && willNotify && !isAlternate) {
+    rv = ssle->UpdateStyleSheet(mFragmentMode ? nsnull : this,
+                                &willNotify,
+                                &isAlternate);
+    if (NS_SUCCEEDED(rv) && willNotify && !isAlternate && !mFragmentMode) {
       ++mPendingSheetCount;
       mScriptLoader->AddExecuteBlocker();
     }
   }
 
   return rv;
 }
 
--- a/content/html/document/src/nsHTMLDocument.cpp
+++ b/content/html/document/src/nsHTMLDocument.cpp
@@ -280,30 +280,28 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mEmbeds)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mLinks)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mAnchors)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mForms, nsIDOMNodeList)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mFormControls,
                                                        nsIDOMNodeList)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mWyciwygChannel)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mMidasCommandManager)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mFragmentParser)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsHTMLDocument, nsDocument)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mImages)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mApplets)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mEmbeds)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mLinks)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mAnchors)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mForms)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mFormControls)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mWyciwygChannel)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mMidasCommandManager)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mFragmentParser)
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_IMPL_ADDREF_INHERITED(nsHTMLDocument, nsDocument)
 NS_IMPL_RELEASE_INHERITED(nsHTMLDocument, nsDocument)
 
 
 DOMCI_NODE_DATA(HTMLDocument, nsHTMLDocument)
 
--- a/content/html/document/src/nsHTMLDocument.h
+++ b/content/html/document/src/nsHTMLDocument.h
@@ -189,23 +189,16 @@ public:
     EditingState    mSavedState;
   };
   friend class nsAutoEditingState;
 
   void EndUpdate(nsUpdateType aUpdateType);
 
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsHTMLDocument, nsDocument)
 
-  virtual already_AddRefed<nsIParser> GetFragmentParser() {
-    return mFragmentParser.forget();
-  }
-  virtual void SetFragmentParser(nsIParser* aParser) {
-    mFragmentParser = aParser;
-  }
-
   virtual nsresult SetEditingState(EditingState aState);
 
   virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const;
 
   virtual NS_HIDDEN_(void) RemovedFromDocShell();
 
   virtual mozilla::dom::Element *GetElementById(const nsAString& aElementId)
   {
@@ -337,19 +330,16 @@ protected:
   EditingState mEditingState;
 
   nsresult   DoClipboardSecurityCheck(PRBool aPaste);
   static jsid        sCutCopyInternal_id;
   static jsid        sPasteInternal_id;
 
   // When false, the .cookies property is completely disabled
   PRBool mDisableCookieAccess;
-
-  // Parser used for constructing document fragments.
-  nsCOMPtr<nsIParser> mFragmentParser;
 };
 
 #define NS_HTML_DOCUMENT_INTERFACE_TABLE_BEGIN(_class)                        \
     NS_DOCUMENT_INTERFACE_TABLE_BEGIN(_class)                                 \
     NS_INTERFACE_TABLE_ENTRY(_class, nsIHTMLDocument)                         \
     NS_INTERFACE_TABLE_ENTRY(_class, nsIDOMHTMLDocument)
 
 #endif /* nsHTMLDocument_h___ */
deleted file mode 100644
--- a/content/html/document/src/nsHTMLFragmentContentSink.cpp
+++ /dev/null
@@ -1,780 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set sw=2 ts=2 et tw=80: */
-/* ***** 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):
- *   Robert Sayre <sayrer@gmail.com>
- *
- * 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 ***** */
-#include "nsCOMPtr.h"
-#include "nsIServiceManager.h"
-#include "nsIFragmentContentSink.h"
-#include "nsIDTD.h"
-#include "nsIHTMLContentSink.h"
-#include "nsIParser.h"
-#include "nsIParserService.h"
-#include "nsGkAtoms.h"
-#include "nsHTMLTokens.h"
-#include "nsGenericHTMLElement.h"
-#include "nsIDOMText.h"
-#include "nsIDOMComment.h"
-#include "nsIDOMHTMLFormElement.h"
-#include "nsIDOMDocumentFragment.h"
-#include "nsTArray.h"
-#include "nsINameSpaceManager.h"
-#include "nsIDocument.h"
-#include "nsINodeInfo.h"
-#include "prmem.h"
-#include "nsReadableUtils.h"
-#include "nsUnicharUtils.h"
-#include "nsContentUtils.h"
-#include "nsEscape.h"
-#include "nsNodeInfoManager.h"
-#include "nsNullPrincipal.h"
-#include "nsContentCreatorFunctions.h"
-#include "nsNetUtil.h"
-#include "nsIScriptSecurityManager.h"
-#include "nsContentSink.h"
-#include "nsTHashtable.h"
-#include "nsCycleCollectionParticipant.h"
-#include "nsCSSParser.h"
-#include "nsCSSProperty.h"
-#include "mozilla/css/Declaration.h"
-#include "mozilla/css/StyleRule.h"
-#include "nsCSSStyleSheet.h"
-#include "nsICSSRuleList.h"
-#include "nsIDOMCSSRule.h"
-
-using namespace mozilla::dom;
-namespace css = mozilla::css;
-
-//
-// XXX THIS IS TEMPORARY CODE
-// There's a considerable amount of copied code from the
-// regular nsHTMLContentSink. All of it will be factored
-// at some pointe really soon!
-//
-
-class nsHTMLFragmentContentSink : public nsIFragmentContentSink,
-                                  public nsIHTMLContentSink {
-public:
-  /**
-   * @param aAllContent Whether there is context information available for the fragment.
-   */
-  nsHTMLFragmentContentSink(PRBool aAllContent = PR_FALSE);
-  virtual ~nsHTMLFragmentContentSink();
-
-  // nsISupports
-  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-  NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsHTMLFragmentContentSink,
-                                           nsIContentSink)
-
-  NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW
-
-  // nsIContentSink
-  NS_IMETHOD WillParse(void) { return NS_OK; }
-  NS_IMETHOD WillBuildModel(nsDTDMode aDTDMode);
-  NS_IMETHOD DidBuildModel(PRBool aTerminated);
-  NS_IMETHOD WillInterrupt(void);
-  NS_IMETHOD WillResume(void);
-  NS_IMETHOD SetParser(nsIParser* aParser);
-  virtual void FlushPendingNotifications(mozFlushType aType) { }
-  NS_IMETHOD SetDocumentCharset(nsACString& aCharset) { return NS_OK; }
-  virtual nsISupports *GetTarget() { return mTargetDocument; }
-
-  // nsIHTMLContentSink
-  NS_IMETHOD BeginContext(PRInt32 aID);
-  NS_IMETHOD EndContext(PRInt32 aID);
-  NS_IMETHOD OpenHead();
-  NS_IMETHOD IsEnabled(PRInt32 aTag, PRBool* aReturn) {
-    *aReturn = PR_TRUE;
-    return NS_OK;
-  }
-  NS_IMETHOD_(PRBool) IsFormOnStack() { return PR_FALSE; }
-  NS_IMETHOD DidProcessTokens(void) { return NS_OK; }
-  NS_IMETHOD WillProcessAToken(void) { return NS_OK; }
-  NS_IMETHOD DidProcessAToken(void) { return NS_OK; }
-  NS_IMETHOD NotifyTagObservers(nsIParserNode* aNode) { return NS_OK; }
-  NS_IMETHOD OpenContainer(const nsIParserNode& aNode);
-  NS_IMETHOD CloseContainer(const nsHTMLTag aTag);
-  NS_IMETHOD AddLeaf(const nsIParserNode& aNode);
-  NS_IMETHOD AddComment(const nsIParserNode& aNode);
-  NS_IMETHOD AddProcessingInstruction(const nsIParserNode& aNode);
-  NS_IMETHOD AddDocTypeDecl(const nsIParserNode& aNode);
-
-  // nsIFragmentContentSink
-  NS_IMETHOD GetFragment(PRBool aWillOwnFragment,
-                         nsIDOMDocumentFragment** aFragment);
-  NS_IMETHOD SetTargetDocument(nsIDocument* aDocument);
-  NS_IMETHOD WillBuildContent();
-  NS_IMETHOD DidBuildContent();
-  NS_IMETHOD IgnoreFirstContainer();
-
-  nsIContent* GetCurrentContent();
-  PRInt32 PushContent(nsIContent *aContent);
-  nsIContent* PopContent();
-
-  virtual nsresult AddAttributes(const nsIParserNode& aNode,
-                                 nsIContent* aContent);
-
-  nsresult AddText(const nsAString& aString);
-  nsresult FlushText();
-
-  PRPackedBool mAllContent;
-  PRPackedBool mProcessing;
-  PRPackedBool mSeenBody;
-  PRPackedBool mIgnoreContainer;
-  PRPackedBool mIgnoreNextCloseHead;
-
-  nsCOMPtr<nsIContent> mRoot;
-  nsCOMPtr<nsIParser> mParser;
-
-  nsTArray<nsIContent*>* mContentStack;
-
-  PRUnichar* mText;
-  PRInt32 mTextLength;
-  PRInt32 mTextSize;
-
-  nsCOMPtr<nsIDocument> mTargetDocument;
-  nsRefPtr<nsNodeInfoManager> mNodeInfoManager;
-
-  nsINodeInfo* mNodeInfoCache[NS_HTML_TAG_MAX + 1];
-};
-
-static nsresult
-NewHTMLFragmentContentSinkHelper(PRBool aAllContent, nsIFragmentContentSink** aResult)
-{
-  NS_PRECONDITION(aResult, "Null out ptr");
-  if (nsnull == aResult) {
-    return NS_ERROR_NULL_POINTER;
-  }
-
-  nsHTMLFragmentContentSink* it = new nsHTMLFragmentContentSink(aAllContent);
-  if (nsnull == it) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-  
-  NS_ADDREF(*aResult = it);
-  
-  return NS_OK;
-}
-
-nsresult
-NS_NewHTMLFragmentContentSink2(nsIFragmentContentSink** aResult)
-{
-  return NewHTMLFragmentContentSinkHelper(PR_TRUE,aResult);
-}
-
-nsresult
-NS_NewHTMLFragmentContentSink(nsIFragmentContentSink** aResult)
-{
-  return NewHTMLFragmentContentSinkHelper(PR_FALSE,aResult);
-}
-
-nsHTMLFragmentContentSink::nsHTMLFragmentContentSink(PRBool aAllContent)
-  : mAllContent(aAllContent),
-    mProcessing(aAllContent),
-    mSeenBody(!aAllContent)
-{
-  // Note: operator new zeros our memory
-}
-
-nsHTMLFragmentContentSink::~nsHTMLFragmentContentSink()
-{
-  // Should probably flush the text buffer here, just to make sure:
-  //FlushText();
-
-  if (nsnull != mContentStack) {
-    // there shouldn't be anything here except in an error condition
-    PRInt32 indx = mContentStack->Length();
-    while (0 < indx--) {
-      nsIContent* content = mContentStack->ElementAt(indx);
-      NS_RELEASE(content);
-    }
-    delete mContentStack;
-  }
-
-  PR_FREEIF(mText);
-
-  PRUint32 i;
-  for (i = 0; i < NS_ARRAY_LENGTH(mNodeInfoCache); ++i) {
-    NS_IF_RELEASE(mNodeInfoCache[i]);
-  }
-}
-
-NS_IMPL_CYCLE_COLLECTING_ADDREF(nsHTMLFragmentContentSink)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(nsHTMLFragmentContentSink)
-
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsHTMLFragmentContentSink)
-  NS_INTERFACE_MAP_ENTRY(nsIFragmentContentSink)
-  NS_INTERFACE_MAP_ENTRY(nsIHTMLContentSink)
-  NS_INTERFACE_MAP_ENTRY(nsIContentSink)
-  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIContentSink)
-NS_INTERFACE_MAP_END
-
-NS_IMPL_CYCLE_COLLECTION_CLASS(nsHTMLFragmentContentSink)
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsHTMLFragmentContentSink)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mParser)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mTargetDocument)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mRoot)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mNodeInfoManager)
-NS_IMPL_CYCLE_COLLECTION_UNLINK_END
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsHTMLFragmentContentSink)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mParser)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mTargetDocument)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mRoot)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NATIVE_MEMBER(mNodeInfoManager,
-                                                  nsNodeInfoManager)
-  {
-    PRUint32 i;
-    for (i = 0; i < NS_ARRAY_LENGTH(tmp->mNodeInfoCache); ++i) {
-      cb.NoteXPCOMChild(tmp->mNodeInfoCache[i]);
-    }
-  }
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::WillBuildModel(nsDTDMode)
-{
-  if (mRoot) {
-    return NS_OK;
-  }
-
-  NS_ASSERTION(mNodeInfoManager, "Need a nodeinfo manager!");
-
-  nsCOMPtr<nsIDOMDocumentFragment> frag;
-  nsresult rv = NS_NewDocumentFragment(getter_AddRefs(frag), mNodeInfoManager);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  mRoot = do_QueryInterface(frag, &rv);
-  
-  return rv;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::DidBuildModel(PRBool aTerminated)
-{
-  FlushText();
-
-  // Drop our reference to the parser to get rid of a circular
-  // reference.
-  mParser = nsnull;
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::WillInterrupt(void)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::WillResume(void)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::SetParser(nsIParser* aParser)
-{
-  mParser = aParser;
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::BeginContext(PRInt32 aID)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::EndContext(PRInt32 aID)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::OpenHead()
-{
-  mIgnoreNextCloseHead = PR_TRUE;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::OpenContainer(const nsIParserNode& aNode)
-{
-  NS_ENSURE_TRUE(mNodeInfoManager, NS_ERROR_NOT_INITIALIZED);
-
-  nsresult result = NS_OK;
-
-  nsHTMLTag nodeType = nsHTMLTag(aNode.GetNodeType());
-
-  if (nodeType == eHTMLTag_html) {
-    return NS_OK;
-  }
-
-  // Ignore repeated BODY elements. The DTD is just sending them
-  // to us for compatibility reasons that don't apply here.
-  if (nodeType == eHTMLTag_body) {
-    if (mSeenBody) {
-      return NS_OK;
-    }
-    mSeenBody = PR_TRUE;
-  }
-
-  if (mProcessing && !mIgnoreContainer) {
-    FlushText();
-
-    nsIContent *content = nsnull;
-
-    nsCOMPtr<nsINodeInfo> nodeInfo;
-
-    if (nodeType == eHTMLTag_userdefined) {
-      nsAutoString lower;
-      nsContentUtils::ASCIIToLower(aNode.GetText(), lower);
-      nsCOMPtr<nsIAtom> name = do_GetAtom(lower);
-      nodeInfo = mNodeInfoManager->GetNodeInfo(name, 
-                                               nsnull, 
-                                               kNameSpaceID_XHTML,
-                                               nsIDOMNode::ELEMENT_NODE);
-      NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
-    }
-    else if (mNodeInfoCache[nodeType]) {
-      nodeInfo = mNodeInfoCache[nodeType];
-    }
-    else {
-      nsIParserService* parserService = nsContentUtils::GetParserService();
-      if (!parserService)
-        return NS_ERROR_OUT_OF_MEMORY;
-
-      nsIAtom *name = parserService->HTMLIdToAtomTag(nodeType);
-      NS_ASSERTION(name, "This should not happen!");
-
-      nodeInfo = mNodeInfoManager->GetNodeInfo(name, 
-                                               nsnull, 
-                                               kNameSpaceID_XHTML,
-                                               nsIDOMNode::ELEMENT_NODE);
-      NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
-
-      NS_ADDREF(mNodeInfoCache[nodeType] = nodeInfo);
-    }
-
-    content =
-      CreateHTMLElement(nodeType, nodeInfo.forget(), NOT_FROM_PARSER).get();
-    NS_ENSURE_TRUE(content, NS_ERROR_OUT_OF_MEMORY);
-
-    result = AddAttributes(aNode, content);
-    if (NS_FAILED(result)) {
-      NS_RELEASE(content);
-      return result;
-    }
-
-    nsIContent *parent = GetCurrentContent();
-    if (!parent) {
-      parent = mRoot;
-    }
-
-    parent->AppendChildTo(content, PR_FALSE);
-    PushContent(content);
-  }
-  else if (mProcessing && mIgnoreContainer) {
-    mIgnoreContainer = PR_FALSE;
-  }
-
-  return result;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::CloseContainer(const nsHTMLTag aTag)
-{
-  if (aTag == eHTMLTag_html) {
-    return NS_OK;
-  }
-  if (mIgnoreNextCloseHead && aTag == eHTMLTag_head) {
-    mIgnoreNextCloseHead = PR_FALSE;
-    return NS_OK;
-  }
-
-  if (mProcessing && (nsnull != GetCurrentContent())) {
-    nsIContent* content;
-    FlushText();
-    content = PopContent();
-    NS_RELEASE(content);
-  }
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::AddLeaf(const nsIParserNode& aNode)
-{
-  NS_ENSURE_TRUE(mNodeInfoManager, NS_ERROR_NOT_INITIALIZED);
-
-  nsresult result = NS_OK;
-
-  switch (aNode.GetTokenType()) {
-    case eToken_start:
-      {
-        FlushText();
-
-        // Create new leaf content object
-        nsRefPtr<nsGenericHTMLElement> content;
-        nsHTMLTag nodeType = nsHTMLTag(aNode.GetNodeType());
-
-        nsIParserService* parserService = nsContentUtils::GetParserService();
-        if (!parserService)
-          return NS_ERROR_OUT_OF_MEMORY;
-
-        nsCOMPtr<nsINodeInfo> nodeInfo;
-
-        if (nodeType == eHTMLTag_userdefined) {
-          nsAutoString lower;
-          nsContentUtils::ASCIIToLower(aNode.GetText(), lower);
-          nsCOMPtr<nsIAtom> name = do_GetAtom(lower);
-          nodeInfo = mNodeInfoManager->GetNodeInfo(name, nsnull,
-                                                   kNameSpaceID_XHTML,
-                                                   nsIDOMNode::ELEMENT_NODE);
-          NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
-        }
-        else if (mNodeInfoCache[nodeType]) {
-          nodeInfo = mNodeInfoCache[nodeType];
-        }
-        else {
-          nsIAtom *name = parserService->HTMLIdToAtomTag(nodeType);
-          NS_ASSERTION(name, "This should not happen!");
-
-          nodeInfo = mNodeInfoManager->GetNodeInfo(name, nsnull,
-                                                   kNameSpaceID_XHTML,
-                                                   nsIDOMNode::ELEMENT_NODE);
-          NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
-          NS_ADDREF(mNodeInfoCache[nodeType] = nodeInfo);
-        }
-
-        content =
-          CreateHTMLElement(nodeType, nodeInfo.forget(), NOT_FROM_PARSER);
-        NS_ENSURE_TRUE(content, NS_ERROR_OUT_OF_MEMORY);
-
-        result = AddAttributes(aNode, content);
-        NS_ENSURE_SUCCESS(result, result);
-
-        nsIContent *parent = GetCurrentContent();
-        if (!parent) {
-          parent = mRoot;
-        }
-
-        parent->AppendChildTo(content, PR_FALSE);
-      }
-      break;
-    case eToken_text:
-    case eToken_whitespace:
-    case eToken_newline:
-      result = AddText(aNode.GetText());
-      break;
-
-    case eToken_entity:
-      {
-        nsAutoString tmp;
-        PRInt32 unicode = aNode.TranslateToUnicodeStr(tmp);
-        if (unicode < 0) {
-          result = AddText(aNode.GetText());
-        }
-        else {
-          result = AddText(tmp);
-        }
-      }
-      break;
-  }
-
-  return result;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::AddComment(const nsIParserNode& aNode)
-{
-  nsCOMPtr<nsIContent> comment;
-  nsresult result = NS_OK;
-
-  FlushText();
-
-  result = NS_NewCommentNode(getter_AddRefs(comment), mNodeInfoManager);
-  if (NS_SUCCEEDED(result)) {
-    comment->SetText(aNode.GetText(), PR_FALSE);
-
-    nsIContent *parent = GetCurrentContent();
-
-    if (nsnull == parent) {
-      parent = mRoot;
-    }
-
-    parent->AppendChildTo(comment, PR_FALSE);
-  }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::AddProcessingInstruction(const nsIParserNode& aNode)
-{
-  return NS_OK;
-}
-
-/**
- *  This gets called by the parser when it encounters
- *  a DOCTYPE declaration in the HTML document.
- */
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::AddDocTypeDecl(const nsIParserNode& aNode)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::GetFragment(PRBool aWillOwnFragment,
-                                       nsIDOMDocumentFragment** aFragment)
-{
-  if (mRoot) {
-    nsresult rv = CallQueryInterface(mRoot, aFragment);
-    if (NS_SUCCEEDED(rv) && aWillOwnFragment) {
-      mRoot = nsnull;
-    }
-    return rv;
-  }
-
-  *aFragment = nsnull;
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::SetTargetDocument(nsIDocument* aTargetDocument)
-{
-  NS_ENSURE_ARG_POINTER(aTargetDocument);
-
-  mTargetDocument = aTargetDocument;
-  mNodeInfoManager = aTargetDocument->NodeInfoManager();
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::WillBuildContent()
-{
-  mProcessing = PR_TRUE;
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::DidBuildContent()
-{
-  if (!mAllContent) {
-    FlushText();
-    DidBuildModel(PR_FALSE); // Release our ref to the parser now.
-    mProcessing = PR_FALSE;
-  }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHTMLFragmentContentSink::IgnoreFirstContainer()
-{
-  mIgnoreContainer = PR_TRUE;
-  return NS_OK;
-}
-
-nsIContent*
-nsHTMLFragmentContentSink::GetCurrentContent()
-{
-  if (nsnull != mContentStack) {
-    PRInt32 indx = mContentStack->Length() - 1;
-    if (indx >= 0)
-      return mContentStack->ElementAt(indx);
-  }
-  return nsnull;
-}
-
-PRInt32
-nsHTMLFragmentContentSink::PushContent(nsIContent *aContent)
-{
-  if (nsnull == mContentStack) {
-    mContentStack = new nsTArray<nsIContent*>();
-  }
-
-  mContentStack->AppendElement(aContent);
-  return mContentStack->Length();
-}
-
-nsIContent*
-nsHTMLFragmentContentSink::PopContent()
-{
-  nsIContent* content = nsnull;
-  if (nsnull != mContentStack) {
-    PRInt32 indx = mContentStack->Length() - 1;
-    if (indx >= 0) {
-      content = mContentStack->ElementAt(indx);
-      mContentStack->RemoveElementAt(indx);
-    }
-  }
-  return content;
-}
-
-#define NS_ACCUMULATION_BUFFER_SIZE 4096
-
-nsresult
-nsHTMLFragmentContentSink::AddText(const nsAString& aString)
-{
-  PRInt32 addLen = aString.Length();
-  if (0 == addLen) {
-    return NS_OK;
-  }
-
-  // Create buffer when we first need it
-  if (0 == mTextSize) {
-    mText = (PRUnichar *) PR_MALLOC(sizeof(PRUnichar) * NS_ACCUMULATION_BUFFER_SIZE);
-    if (nsnull == mText) {
-      return NS_ERROR_OUT_OF_MEMORY;
-    }
-    mTextSize = NS_ACCUMULATION_BUFFER_SIZE;
-  }
-
-  // Copy data from string into our buffer; flush buffer when it fills up
-  PRInt32 offset = 0;
-  PRBool  isLastCharCR = PR_FALSE;
-  while (0 != addLen) {
-    PRInt32 amount = mTextSize - mTextLength;
-    if (amount > addLen) {
-      amount = addLen;
-    }
-    if (0 == amount) {
-      nsresult rv = FlushText();
-      if (NS_OK != rv) {
-        return rv;
-      }
-    }
-    mTextLength +=
-      nsContentUtils::CopyNewlineNormalizedUnicodeTo(aString,
-                                                     offset,
-                                                     &mText[mTextLength],
-                                                     amount,
-                                                     isLastCharCR);
-    offset += amount;
-    addLen -= amount;
-  }
-
-  return NS_OK;
-}
-
-nsresult
-nsHTMLFragmentContentSink::FlushText()
-{
-  if (0 == mTextLength) {
-    return NS_OK;
-  }
-
-  nsCOMPtr<nsIContent> content;
-  nsresult rv = NS_NewTextNode(getter_AddRefs(content), mNodeInfoManager);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // Set the text in the text node
-  content->SetText(mText, mTextLength, PR_FALSE);
-
-  // Add text to its parent
-  nsIContent *parent = GetCurrentContent();
-
-  if (!parent) {
-    parent = mRoot;
-  }
-
-  rv = parent->AppendChildTo(content, PR_FALSE);
-
-  mTextLength = 0;
-
-  return rv;
-}
-
-// XXX Code copied from nsHTMLContentSink. It should be shared.
-nsresult
-nsHTMLFragmentContentSink::AddAttributes(const nsIParserNode& aNode,
-                                         nsIContent* aContent)
-{
-  // Add tag attributes to the content attributes
-
-  PRInt32 ac = aNode.GetAttributeCount();
-
-  if (ac == 0) {
-    // No attributes, nothing to do. Do an early return to avoid
-    // constructing the nsAutoString object for nothing.
-
-    return NS_OK;
-  }
-
-  nsAutoString k;
-  nsHTMLTag nodeType = nsHTMLTag(aNode.GetNodeType());
-
-  // The attributes are on the parser node in the order they came in in the
-  // source.  What we want to happen if a single attribute is set multiple
-  // times on an element is that the first time should "win".  That is, <input
-  // value="foo" value="bar"> should show "foo".  So we loop over the
-  // attributes backwards; this ensures that the first attribute in the set
-  // wins.  This does mean that we do some extra work in the case when the same
-  // attribute is set multiple times, but we save a HasAttr call in the much
-  // more common case of reasonable HTML.
-
-  for (PRInt32 i = ac - 1; i >= 0; i--) {
-    // Get lower-cased key
-    nsContentUtils::ASCIIToLower(aNode.GetKeyAt(i), k);
-    nsCOMPtr<nsIAtom> keyAtom = do_GetAtom(k);
-
-    // Get value and remove mandatory quotes
-    static const char* kWhitespace = "\n\r\t\b";
-    const nsAString& v =
-      nsContentUtils::TrimCharsInSet(kWhitespace, aNode.GetValueAt(i));
-
-    if (nodeType == eHTMLTag_a && keyAtom == nsGkAtoms::name) {
-      NS_ConvertUTF16toUTF8 cname(v);
-      NS_ConvertUTF8toUTF16 uv(nsUnescape(cname.BeginWriting()));
-
-      // Add attribute to content
-      aContent->SetAttr(kNameSpaceID_None, keyAtom, uv, PR_FALSE);
-    } else {
-      // Add attribute to content
-      aContent->SetAttr(kNameSpaceID_None, keyAtom, v, PR_FALSE);
-    }
-  }
-
-  return NS_OK;
-}
-
--- a/content/media/nsBuiltinDecoderReader.cpp
+++ b/content/media/nsBuiltinDecoderReader.cpp
@@ -330,22 +330,33 @@ nsresult nsBuiltinDecoderReader::DecodeT
       }
       if (startSample + audio->mSamples <= targetSample) {
         // Our seek target lies after the samples in this SoundData. Pop it
         // off the queue, and keep decoding forwards.
         delete mAudioQueue.PopFront();
         audio = nsnull;
         continue;
       }
+      if (startSample > targetSample) {
+        // The seek target doesn't lie in the audio block just after the last
+        // audio samples we've seen which were before the seek target. This
+        // could have been the first audio data we've seen after seek, i.e. the
+        // seek terminated after the seek target in the audio stream. Just
+        // abort the audio decode-to-target, the state machine will play
+        // silence to cover the gap. Typically this happens in poorly muxed
+        // files.
+        NS_WARNING("Audio not synced after seek, maybe a poorly muxed file?");
+        break;
+      }
 
       // The seek target lies somewhere in this SoundData's samples, strip off
       // any samples which lie before the seek target, so we'll begin playback
       // exactly at the seek target.
       NS_ASSERTION(targetSample >= startSample, "Target must at or be after data start.");
-      NS_ASSERTION(startSample + audio->mSamples > targetSample, "Data must end after target.");
+      NS_ASSERTION(targetSample < startSample + audio->mSamples, "Data must end after target.");
 
       PRInt64 samplesToPrune = targetSample - startSample;
       if (samplesToPrune > audio->mSamples) {
         // We've messed up somehow. Don't try to trim samples, the |samples|
         // variable below will overflow.
         NS_WARNING("Can't prune more samples that we have!");
         break;
       }
--- a/content/xml/document/src/nsXMLContentSink.cpp
+++ b/content/xml/document/src/nsXMLContentSink.cpp
@@ -589,16 +589,23 @@ nsXMLContentSink::CloseElement(nsIConten
 
   nsresult rv = NS_OK;
 
   if (nodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_XHTML)
       || nodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_SVG)
     ) {
     mConstrainSize = PR_TRUE; 
 
+    if (mPreventScriptExecution) {
+      nsCOMPtr<nsIScriptElement> sele = do_QueryInterface(aContent);
+      NS_ASSERTION(sele, "script did QI correctly!");
+      sele->PreventExecution();
+      return rv;
+    }
+
     // Now tell the script that it's ready to go. This may execute the script
     // or return NS_ERROR_HTMLPARSER_BLOCK. Or neither if the script doesn't
     // need executing.
     rv = aContent->DoneAddingChildren(PR_TRUE);
 
     // If the act of insertion evaluated the script, we're fine.
     // Else, block the parser till the script has loaded.
     if (rv == NS_ERROR_HTMLPARSER_BLOCK) {
@@ -626,18 +633,20 @@ nsXMLContentSink::CloseElement(nsIConten
   else if (nodeInfo->Equals(nsGkAtoms::link, kNameSpaceID_XHTML) ||
            nodeInfo->Equals(nsGkAtoms::style, kNameSpaceID_XHTML) ||
            nodeInfo->Equals(nsGkAtoms::style, kNameSpaceID_SVG)) {
     nsCOMPtr<nsIStyleSheetLinkingElement> ssle(do_QueryInterface(aContent));
     if (ssle) {
       ssle->SetEnableUpdates(PR_TRUE);
       PRBool willNotify;
       PRBool isAlternate;
-      rv = ssle->UpdateStyleSheet(this, &willNotify, &isAlternate);
-      if (NS_SUCCEEDED(rv) && willNotify && !isAlternate) {
+      rv = ssle->UpdateStyleSheet(mFragmentMode ? nsnull : this,
+                                  &willNotify,
+                                  &isAlternate);
+      if (NS_SUCCEEDED(rv) && willNotify && !isAlternate && !mFragmentMode) {
         ++mPendingSheetCount;
         mScriptLoader->AddExecuteBlocker();
       }
     }
     // Look for <link rel="dns-prefetch" href="hostname">
     if (nodeInfo->Equals(nsGkAtoms::link, kNameSpaceID_XHTML)) {
       nsAutoString relVal;
       aContent->GetAttr(kNameSpaceID_None, nsGkAtoms::rel, relVal);
@@ -1302,22 +1311,24 @@ nsXMLContentSink::HandleProcessingInstru
   DidAddContent();
 
   if (ssle) {
     // This is an xml-stylesheet processing instruction... but it might not be
     // a CSS one if the type is set to something else.
     ssle->SetEnableUpdates(PR_TRUE);
     PRBool willNotify;
     PRBool isAlternate;
-    rv = ssle->UpdateStyleSheet(this, &willNotify, &isAlternate);
+    rv = ssle->UpdateStyleSheet(mFragmentMode ? nsnull : this,
+                                &willNotify,
+                                &isAlternate);
     NS_ENSURE_SUCCESS(rv, rv);
     
     if (willNotify) {
       // Successfully started a stylesheet load
-      if (!isAlternate) {
+      if (!isAlternate && !mFragmentMode) {
         ++mPendingSheetCount;
         mScriptLoader->AddExecuteBlocker();
       }
 
       return NS_OK;
     }
   }
 
--- a/content/xml/document/src/nsXMLFragmentContentSink.cpp
+++ b/content/xml/document/src/nsXMLFragmentContentSink.cpp
@@ -58,24 +58,27 @@
 #include "nsServiceManagerUtils.h"
 #include "nsContentUtils.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsNetUtil.h"
 #include "nsTHashtable.h"
 #include "nsHashKeys.h"
 #include "nsTArray.h"
 #include "nsCycleCollectionParticipant.h"
+#include "nsIDocShell.h"
+#include "nsScriptLoader.h"
+#include "mozilla/css/Loader.h"
 
 using namespace mozilla::dom;
 
 class nsXMLFragmentContentSink : public nsXMLContentSink,
                                  public nsIFragmentContentSink
 {
 public:
-  nsXMLFragmentContentSink(PRBool aAllContent = PR_FALSE);
+  nsXMLFragmentContentSink();
   virtual ~nsXMLFragmentContentSink();
 
   NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED_NO_UNLINK(nsXMLFragmentContentSink,
                                                      nsXMLContentSink)
@@ -101,22 +104,22 @@ public:
   NS_IMETHOD DidBuildModel(PRBool aTerminated);
   NS_IMETHOD SetDocumentCharset(nsACString& aCharset);
   virtual nsISupports *GetTarget();
   NS_IMETHOD DidProcessATokenImpl();
 
   // nsIXMLContentSink
 
   // nsIFragmentContentSink
-  NS_IMETHOD GetFragment(PRBool aWillOwnFragment,
-                         nsIDOMDocumentFragment** aFragment);
+  NS_IMETHOD FinishFragmentParsing(nsIDOMDocumentFragment** aFragment);
   NS_IMETHOD SetTargetDocument(nsIDocument* aDocument);
   NS_IMETHOD WillBuildContent();
   NS_IMETHOD DidBuildContent();
   NS_IMETHOD IgnoreFirstContainer();
+  NS_IMETHOD SetPreventScriptExecution(PRBool aPreventScriptExecution);
 
 protected:
   virtual PRBool SetDocElement(PRInt32 aNameSpaceID, 
                                nsIAtom *aTagName,
                                nsIContent *aContent);
   virtual nsresult CreateElement(const PRUnichar** aAtts, PRUint32 aAttsCount,
                                  nsINodeInfo* aNodeInfo, PRUint32 aLineNumber,
                                  nsIContent** aResult, PRBool* aAppendContent,
@@ -134,49 +137,41 @@ protected:
                                     const nsSubstring& aMedia);
   nsresult LoadXSLStyleSheet(nsIURI* aUrl);
   void StartLayout();
 
   nsCOMPtr<nsIDocument> mTargetDocument;
   // the fragment
   nsCOMPtr<nsIContent>  mRoot;
   PRPackedBool          mParseError;
-
-  // if FALSE, take content inside endnote tag
-  PRPackedBool          mAllContent;
 };
 
 static nsresult
-NewXMLFragmentContentSinkHelper(PRBool aAllContent, nsIFragmentContentSink** aResult)
+NewXMLFragmentContentSinkHelper(nsIFragmentContentSink** aResult)
 {
-  nsXMLFragmentContentSink* it = new nsXMLFragmentContentSink(aAllContent);
+  nsXMLFragmentContentSink* it = new nsXMLFragmentContentSink();
   if (!it) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
   
   NS_ADDREF(*aResult = it);
   
   return NS_OK;
 }
 
 nsresult
-NS_NewXMLFragmentContentSink2(nsIFragmentContentSink** aResult)
+NS_NewXMLFragmentContentSink(nsIFragmentContentSink** aResult)
 {
-  return NewXMLFragmentContentSinkHelper(PR_TRUE, aResult);
+  return NewXMLFragmentContentSinkHelper(aResult);
 }
 
-nsresult
-NS_NewXMLFragmentContentSink(nsIFragmentContentSink** aResult)
+nsXMLFragmentContentSink::nsXMLFragmentContentSink()
+ : mParseError(PR_FALSE)
 {
-  return NewXMLFragmentContentSinkHelper(PR_FALSE, aResult);
-}
-
-nsXMLFragmentContentSink::nsXMLFragmentContentSink(PRBool aAllContent)
- : mParseError(PR_FALSE), mAllContent(aAllContent)
-{
+  mFragmentMode = PR_TRUE;
 }
 
 nsXMLFragmentContentSink::~nsXMLFragmentContentSink()
 {
 }
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsXMLFragmentContentSink)
   NS_INTERFACE_MAP_ENTRY(nsIFragmentContentSink)
@@ -205,31 +200,22 @@ nsXMLFragmentContentSink::WillBuildModel
   NS_ASSERTION(mTargetDocument, "Need a document!");
 
   nsCOMPtr<nsIDOMDocumentFragment> frag;
   nsresult rv = NS_NewDocumentFragment(getter_AddRefs(frag), mNodeInfoManager);
   NS_ENSURE_SUCCESS(rv, rv);
 
   mRoot = do_QueryInterface(frag);
   
-  if (mAllContent) {
-    // Preload content stack because we know all content goes in the fragment
-    PushContent(mRoot);
-  }
-
   return rv;
 }
 
 NS_IMETHODIMP 
 nsXMLFragmentContentSink::DidBuildModel(PRBool aTerminated)
 {
-  if (mAllContent) {
-    PopContent();  // remove mRoot pushed above
-  }
-
   nsCOMPtr<nsIParser> kungFuDeathGrip(mParser);
 
   // Drop our reference to the parser to get rid of a circular
   // reference.
   mParser = nsnull;
 
   return NS_OK;
 }
@@ -269,27 +255,34 @@ nsXMLFragmentContentSink::CreateElement(
   nsresult rv = nsXMLContentSink::CreateElement(aAtts, aAttsCount,
                                                 aNodeInfo, aLineNumber,
                                                 aResult, aAppendContent,
                                                 NOT_FROM_PARSER);
 
   // When we aren't grabbing all of the content we, never open a doc
   // element, we run into trouble on the first element, so we don't append,
   // and simply push this onto the content stack.
-  if (!mAllContent && mContentStack.Length() == 0) {
+  if (mContentStack.Length() == 0) {
     *aAppendContent = PR_FALSE;
   }
 
   return rv;
 }
 
 nsresult
 nsXMLFragmentContentSink::CloseElement(nsIContent* aContent)
 {
   // don't do fancy stuff in nsXMLContentSink
+  if (mPreventScriptExecution && aContent->Tag() == nsGkAtoms::script &&
+      (aContent->GetNameSpaceID() == kNameSpaceID_XHTML ||
+       aContent->GetNameSpaceID() == kNameSpaceID_SVG)) {
+    nsCOMPtr<nsIScriptElement> sele = do_QueryInterface(aContent);
+    NS_ASSERTION(sele, "script did QI correctly!");
+    sele->PreventExecution();
+  }
   return NS_OK;
 }
 
 void
 nsXMLFragmentContentSink::MaybeStartLayout(PRBool aIgnorePendingSheets)
 {
   return;
 }
@@ -405,28 +398,34 @@ void
 nsXMLFragmentContentSink::StartLayout()
 {
   NS_NOTREACHED("fragments shouldn't layout");
 }
 
 ////////////////////////////////////////////////////////////////////////
 
 NS_IMETHODIMP 
-nsXMLFragmentContentSink::GetFragment(PRBool aWillOwnFragment,
-                                      nsIDOMDocumentFragment** aFragment)
+nsXMLFragmentContentSink::FinishFragmentParsing(nsIDOMDocumentFragment** aFragment)
 {
   *aFragment = nsnull;
+  mTargetDocument = nsnull;
+  mNodeInfoManager = nsnull;
+  mScriptLoader = nsnull;
+  mCSSLoader = nsnull;
+  mContentStack.Clear();
+  mDocumentURI = nsnull;
+  mDocShell = nsnull;
   if (mParseError) {
     //XXX PARSE_ERR from DOM3 Load and Save would be more appropriate
+    mRoot = nsnull;
+    mParseError = PR_FALSE;
     return NS_ERROR_DOM_SYNTAX_ERR;
   } else if (mRoot) {
     nsresult rv = CallQueryInterface(mRoot, aFragment);
-    if (NS_SUCCEEDED(rv) && aWillOwnFragment) {
-      mRoot = nsnull;
-    }
+    mRoot = nsnull;
     return rv;
   } else {
     return NS_OK;
   }
 }
 
 NS_IMETHODIMP
 nsXMLFragmentContentSink::SetTargetDocument(nsIDocument* aTargetDocument)
@@ -437,45 +436,45 @@ nsXMLFragmentContentSink::SetTargetDocum
   mNodeInfoManager = aTargetDocument->NodeInfoManager();
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXMLFragmentContentSink::WillBuildContent()
 {
-  // If we're taking all of the content, then we've already pushed mRoot
-  // onto the content stack, otherwise, start here.
-  if (!mAllContent) {
-    PushContent(mRoot);
-  }
+  PushContent(mRoot);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXMLFragmentContentSink::DidBuildContent()
 {
-  // If we're taking all of the content, then this is handled in DidBuildModel
-  if (!mAllContent) {
-    // Note: we need to FlushText() here because if we don't, we might not get
-    // an end element to do it for us, so make sure.
-    if (!mParseError) {
-      FlushText();
-    }
-    PopContent();
+  // Note: we need to FlushText() here because if we don't, we might not get
+  // an end element to do it for us, so make sure.
+  if (!mParseError) {
+    FlushText();
   }
+  PopContent();
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXMLFragmentContentSink::DidProcessATokenImpl()
 {
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXMLFragmentContentSink::IgnoreFirstContainer()
 {
   NS_NOTREACHED("XML isn't as broken as HTML");
   return NS_ERROR_FAILURE;
 }
+
+NS_IMETHODIMP
+nsXMLFragmentContentSink::SetPreventScriptExecution(PRBool aPrevent)
+{
+  mPreventScriptExecution = aPrevent;
+  return NS_OK;
+}
--- a/content/xul/content/src/nsXULElement.cpp
+++ b/content/xul/content/src/nsXULElement.cpp
@@ -507,48 +507,38 @@ nsXULElement::GetElementsByAttributeNS(c
                           attrAtom,
                           nameSpaceId);
     NS_ENSURE_TRUE(list, NS_ERROR_OUT_OF_MEMORY);
 
     NS_ADDREF(*aReturn = list);
     return NS_OK;
 }
 
-nsresult
-nsXULElement::GetEventListenerManagerForAttr(nsEventListenerManager** aManager,
-                                             nsISupports** aTarget,
-                                             PRBool* aDefer)
+nsEventListenerManager*
+nsXULElement::GetEventListenerManagerForAttr(PRBool* aDefer)
 {
     // XXXbz sXBL/XBL2 issue: should we instead use GetCurrentDoc()
     // here, override BindToTree for those classes and munge event
     // listeners there?
     nsIDocument* doc = GetOwnerDoc();
     if (!doc)
-        return NS_ERROR_UNEXPECTED; // XXX
+        return nsnull; // XXX
 
     nsPIDOMWindow *window;
     Element *root = doc->GetRootElement();
     if ((!root || root == this) && !mNodeInfo->Equals(nsGkAtoms::overlay) &&
         (window = doc->GetInnerWindow()) && window->IsInnerWindow()) {
 
         nsCOMPtr<nsIDOMEventTarget> piTarget = do_QueryInterface(window);
-        if (!piTarget)
-            return NS_ERROR_UNEXPECTED;
 
         *aDefer = PR_FALSE;
-        *aManager = piTarget->GetListenerManager(PR_TRUE);
-        NS_ENSURE_STATE(*aManager);
-        NS_ADDREF(*aManager);
-        NS_ADDREF(*aTarget = window);
-        return NS_OK;
+        return piTarget->GetListenerManager(PR_TRUE);
     }
 
-    return nsStyledElement::GetEventListenerManagerForAttr(aManager,
-                                                           aTarget,
-                                                           aDefer);
+    return nsStyledElement::GetEventListenerManagerForAttr(aDefer);
 }
 
 // returns true if the element is not a list
 static PRBool IsNonList(nsINodeInfo* aNodeInfo)
 {
   return !aNodeInfo->Equals(nsGkAtoms::tree) &&
          !aNodeInfo->Equals(nsGkAtoms::listbox) &&
          !aNodeInfo->Equals(nsGkAtoms::richlistbox);
--- a/content/xul/content/src/nsXULElement.h
+++ b/content/xul/content/src/nsXULElement.h
@@ -652,20 +652,18 @@ protected:
 
     virtual void UpdateEditableState(PRBool aNotify);
 
     virtual PRBool ParseAttribute(PRInt32 aNamespaceID,
                                   nsIAtom* aAttribute,
                                   const nsAString& aValue,
                                   nsAttrValue& aResult);
 
-    virtual nsresult
-      GetEventListenerManagerForAttr(nsEventListenerManager** aManager,
-                                     nsISupports** aTarget,
-                                     PRBool* aDefer);
+    virtual nsEventListenerManager*
+      GetEventListenerManagerForAttr(PRBool* aDefer);
   
     /**
      * Return our prototype's attribute, if one exists.
      */
     nsXULPrototypeAttribute *FindPrototypeAttribute(PRInt32 aNameSpaceID,
                                                     nsIAtom *aName) const;
     /**
      * Add a listener for the specified attribute, if appropriate.
--- a/db/sqlite3/src/Makefile.in
+++ b/db/sqlite3/src/Makefile.in
@@ -72,27 +72,16 @@ sqlite-version.h: sqlite-version.py sqli
 $(DEFFILE): sqlite.def
 	@$(PYTHON) $(topsrcdir)/config/Preprocessor.py $(DEFINES) \
 	  $(srcdir)/sqlite.def > $(DEFFILE)
 
 export:: sqlite-version.h
 endif
 endif
 
-ifdef GNU_CC
-MODULE_OPTIMIZE_FLAGS = -O2
-else
-ifeq ($(OS_ARCH),SunOS)
-MODULE_OPTIMIZE_FLAGS = -xO5
-endif
-ifeq ($(OS_ARCH),WINNT)
-MODULE_OPTIMIZE_FLAGS = -O2
-endif
-endif
-
 EXPORTS = \
   sqlite3.h \
   $(NULL)
 
 CSRCS = \
   sqlite3.c \
   $(NULL)
 
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -7757,23 +7757,23 @@ nsEventReceiverSH::RegisterCompileHandle
   NS_ENSURE_TRUE(manager, NS_ERROR_UNEXPECTED);
 
   nsCOMPtr<nsIAtom> atom(do_GetAtom(nsDependentJSString(id)));
   NS_ENSURE_TRUE(atom, NS_ERROR_OUT_OF_MEMORY);
 
   JSObject *scope = ::JS_GetGlobalForObject(cx, obj);
 
   if (compile) {
-    nsresult rv = manager->CompileScriptEventListener(script_cx, scope, target,
+    nsresult rv = manager->CompileScriptEventListener(script_cx, scope,
                                                       atom, did_define);
     NS_ENSURE_SUCCESS(rv, rv);
   } else if (remove) {
     manager->RemoveScriptEventListener(atom);
   } else {
-    manager->RegisterScriptEventListener(script_cx, scope, target, atom);
+    manager->RegisterScriptEventListener(script_cx, scope, atom);
   }
 
   return NS_SUCCESS_I_DID_SOMETHING;
 }
 
 NS_IMETHODIMP
 nsEventReceiverSH::NewResolve(nsIXPConnectWrappedNative *wrapper,
                               JSContext *cx, JSObject *obj, jsid id,
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -1618,16 +1618,18 @@ nsJSContext::ExecuteScript(void *aScript
   JSAutoRequest ar(mContext);
   ++mExecuteDepth;
   ok = ::JS_ExecuteScript(mContext, (JSObject *)aScopeObject, scriptObj, &val);
 
   if (ok) {
     // If all went well, convert val to a string (XXXbe unless undefined?).
     rv = JSValueToAString(mContext, val, aRetValue, aIsUndefined);
   } else {
+    ReportPendingException();
+
     if (aIsUndefined) {
       *aIsUndefined = PR_TRUE;
     }
 
     if (aRetValue) {
       aRetValue->Truncate();
     }
   }
--- a/dom/interfaces/html/nsIDOMHTMLElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLElement.idl
@@ -46,23 +46,24 @@
  *
  * 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(164c7ebd-2245-42d2-a96f-2bf2d01c1697)]
+[scriptable, uuid(c6e10ab6-ecf4-48e4-aeaa-37724307dfd5)]
 interface nsIDOMHTMLElement : nsIDOMElement
 {
            attribute DOMString        id;
            attribute DOMString        title;
            attribute DOMString        lang;
            attribute DOMString        dir;
            attribute DOMString        className;
 
            attribute DOMString        accessKey;
+  readonly attribute DOMString        accessKeyLabel;
 
            void                       blur();
            void                       focus();
            void                       click();
 };
--- a/dom/interfaces/html/nsIDOMNSHTMLElement.idl
+++ b/dom/interfaces/html/nsIDOMNSHTMLElement.idl
@@ -35,17 +35,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "domstubs.idl"
 
 interface nsIDOMDOMStringMap;
 
-[scriptable, uuid(cf76761d-2d93-4e88-aaf1-b637878bad65)]
+[scriptable, uuid(4012e9a9-f6fb-48b3-9a80-b096c1dcb5ba)]
 interface nsIDOMNSHTMLElement : nsISupports
 {
   readonly attribute long             offsetTop;
   readonly attribute long             offsetLeft;
   readonly attribute long             offsetWidth;
   readonly attribute long             offsetHeight;
   readonly attribute nsIDOMElement    offsetParent;
            attribute DOMString        innerHTML;
@@ -60,14 +60,18 @@ interface nsIDOMNSHTMLElement : nsISuppo
            attribute long             tabIndex;
 
            attribute DOMString        contentEditable;
   readonly attribute boolean          isContentEditable;
 
            // for WHAT-WG drag and drop
            attribute boolean          draggable;
 
+  void insertAdjacentHTML(in DOMString position,
+                          in DOMString text)
+                          raises(DOMException);
+
   [optional_argc] void scrollIntoView([optional] in boolean top);
 
            attribute boolean         spellcheck;
            
   readonly attribute nsIDOMDOMStringMap dataset;
 };
--- a/dom/workers/Events.cpp
+++ b/dom/workers/Events.cpp
@@ -1046,42 +1046,42 @@ InitClasses(JSContext* aCx, JSObject* aG
          ErrorEvent::InitClass(aCx, aGlobal, eventProto, aMainRuntime) &&
          ProgressEvent::InitClass(aCx, aGlobal, eventProto);
 }
 
 JSObject*
 CreateGenericEvent(JSContext* aCx, JSString* aType, bool aBubbles,
                    bool aCancelable, bool aMainRuntime)
 {
-  JSObject* global = JS_GetGlobalObject(aCx);
+  JSObject* global = JS_GetGlobalForScopeChain(aCx);
   return Event::Create(aCx, global, aType, aBubbles, aCancelable, aMainRuntime);
 }
 
 JSObject*
 CreateMessageEvent(JSContext* aCx, JSAutoStructuredCloneBuffer& aData,
                    bool aMainRuntime)
 {
-  JSObject* global = JS_GetGlobalObject(aCx);
+  JSObject* global = JS_GetGlobalForScopeChain(aCx);
   return MessageEvent::Create(aCx, global, aData, aMainRuntime);
 }
 
 JSObject*
 CreateErrorEvent(JSContext* aCx, JSString* aMessage, JSString* aFilename,
                  uint32 aLineNumber, bool aMainRuntime)
 {
-  JSObject* global = JS_GetGlobalObject(aCx);
+  JSObject* global = JS_GetGlobalForScopeChain(aCx);
   return ErrorEvent::Create(aCx, global, aMessage, aFilename, aLineNumber,
                             aMainRuntime);
 }
 
 JSObject*
 CreateProgressEvent(JSContext* aCx, JSString* aType, bool aLengthComputable,
                     jsdouble aLoaded, jsdouble aTotal)
 {
-  JSObject* global = JS_GetGlobalObject(aCx);
+  JSObject* global = JS_GetGlobalForScopeChain(aCx);
   return ProgressEvent::Create(aCx, global, aType, aLengthComputable, aLoaded,
                                aTotal);
 }
 
 bool
 IsSupportedEventClass(JSContext* aCx, JSObject* aEvent)
 {
   return Event::IsSupportedClass(aCx, aEvent);
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -1201,25 +1201,27 @@ WorkerRunnable::PostDispatch(JSContext* 
     JS_ReportPendingException(aCx);
   }
 }
 
 NS_IMETHODIMP
 WorkerRunnable::Run()
 {
   JSContext* cx;
-
+  JSObject* targetCompartmentObject;
   nsIThreadJSContextStack* contextStack = nsnull;
 
   if (mTarget == WorkerThread) {
     mWorkerPrivate->AssertIsOnWorkerThread();
     cx = mWorkerPrivate->GetJSContext();
+    targetCompartmentObject = JS_GetGlobalObject(cx);
   } else {
     mWorkerPrivate->AssertIsOnParentThread();
     cx = mWorkerPrivate->ParentJSContext();
+    targetCompartmentObject = mWorkerPrivate->GetJSObject();
 
     if (!mWorkerPrivate->GetParent()) {
       AssertIsOnMainThread();
 
       contextStack = nsContentUtils::ThreadJSContextStack();
       NS_ASSERTION(contextStack, "This should never be null!");
 
       if (NS_FAILED(contextStack->Push(cx))) {
@@ -1228,20 +1230,18 @@ WorkerRunnable::Run()
       }
     }
   }
 
   NS_ASSERTION(cx, "Must have a context!");
 
   JSAutoRequest ar(cx);
 
-  JSObject* global = JS_GetGlobalObject(cx);
-
   JSAutoEnterCompartment ac;
-  if (global && !ac.enter(cx, global)) {
+  if (targetCompartmentObject && !ac.enter(cx, targetCompartmentObject)) {
     return false;
   }
 
   bool result = WorkerRun(cx, mWorkerPrivate);
 
   PostRun(cx, mWorkerPrivate, result);
 
   if (contextStack) {
--- a/editor/libeditor/html/nsHTMLDataTransfer.cpp
+++ b/editor/libeditor/html/nsHTMLDataTransfer.cpp
@@ -2684,34 +2684,27 @@ nsresult nsHTMLEditor::CreateDOMFragment
 
 
 nsresult nsHTMLEditor::ParseFragment(const nsAString & aFragStr,
                                      nsIAtom* aContextLocalName,
                                      nsIDocument* aTargetDocument,
                                      nsCOMPtr<nsIDOMNode> *outNode,
                                      PRBool aTrustedInput)
 {
-  // The old code created a new parser every time. This is inefficient.
-  // However, the target document is not required to be an HTML document,
-  // So avoid using the cached parser of aDocument. Once bug 596182 is fixed,
-  // use the global parser here.
-  nsCOMPtr<nsIParser> parser = nsHtml5Module::NewHtml5Parser();
-  nsAHtml5FragmentParser* asFragmentParser =
-      static_cast<nsAHtml5FragmentParser*> (parser.get());
   nsCOMPtr<nsIDOMDocumentFragment> frag;
   NS_NewDocumentFragment(getter_AddRefs(frag),
                          aTargetDocument->NodeInfoManager());
   nsCOMPtr<nsIContent> fragment = do_QueryInterface(frag);
-  asFragmentParser->ParseHtml5Fragment(aFragStr,
-                                      fragment,
-                                      aContextLocalName ?
-                                          aContextLocalName : nsGkAtoms::body,
-                                      kNameSpaceID_XHTML,
-                                      PR_FALSE,
-                                      PR_TRUE);
+  nsContentUtils::ParseFragmentHTML(aFragStr,
+                                    fragment,
+                                    aContextLocalName ?
+                                        aContextLocalName : nsGkAtoms::body,
+                                    kNameSpaceID_XHTML,
+                                    PR_FALSE,
+                                    PR_TRUE);
   if (!aTrustedInput) {
     nsTreeSanitizer sanitizer(!!aContextLocalName, !aContextLocalName);
     sanitizer.Sanitize(fragment);
   }
   *outNode = do_QueryInterface(frag);
   return NS_OK;
 }
 
--- a/gfx/cairo/cairo/src/Makefile.in
+++ b/gfx/cairo/cairo/src/Makefile.in
@@ -44,22 +44,17 @@ VPATH           = @srcdir@
 include $(DEPTH)/config/autoconf.mk
 
 MODULE          = cairo
 LIBRARY_NAME    = mozcairo
 LIBXUL_LIBRARY = 1
 
 ifdef GNU_CC
 OS_CXXFLAGS := $(filter-out -pedantic,$(OS_CXXFLAGS))
-MODULE_OPTIMIZE_FLAGS = -O2
-else
-ifeq ($(OS_ARCH),SunOS)
-MODULE_OPTIMIZE_FLAGS = -xO5
-endif
-ifeq ($(OS_ARCH),WINNT)
+ifeq ($(OS_TARGET),Android)
 MODULE_OPTIMIZE_FLAGS = -O2
 endif
 endif
 
 
 CSRCS   = \
         cairo.c \
         cairo-analysis-surface.c \
--- a/gfx/cairo/libpixman/src/Makefile.in
+++ b/gfx/cairo/libpixman/src/Makefile.in
@@ -43,25 +43,18 @@ srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE		= libpixman
 LIBRARY_NAME	= mozlibpixman
 LIBXUL_LIBRARY = 1
 
-ifdef GNU_CC
+ifeq ($(OS_TARGET),Android)
 MODULE_OPTIMIZE_FLAGS = -O2
-else
-ifeq ($(OS_ARCH),SunOS)
-MODULE_OPTIMIZE_FLAGS = -xO5
-endif
-ifeq ($(OS_ARCH),WINNT)
-MODULE_OPTIMIZE_FLAGS = -O2
-endif
 endif
 
 DEFINES += -DPIXMAN_NO_TLS
 
 # Build MMX code either with VC or with gcc-on-x86
 ifdef _MSC_VER
 ifeq (86,$(findstring 86,$(OS_TEST)))
 ifneq (64,$(findstring 64,$(OS_TEST)))
--- a/gfx/thebes/gfxAndroidPlatform.cpp
+++ b/gfx/thebes/gfxAndroidPlatform.cpp
@@ -437,29 +437,29 @@ gfxAndroidPlatform::FindFontsInDirectory
     DIR *d = opendir(aFontsDir.get());
     struct dirent *ent = NULL;
     while(d && (ent = readdir(d)) != NULL) {
         int namelen = strlen(ent->d_name);
         if (namelen > 4 &&
             strcasecmp(ent->d_name + namelen - 4, ".ttf") == 0)
         {
             bool isStdFont = false;
-            for (int i = 0; i < NS_ARRAY_LENGTH(sStandardFonts) && !isStdFont; i++) {
+            for (unsigned int i = 0; i < NS_ARRAY_LENGTH(sStandardFonts) && !isStdFont; i++) {
                 isStdFont = strcmp(sStandardFonts[i], ent->d_name) == 0;
             }
             if (!isStdFont) {
                 nsCString s(aFontsDir);
                 s.Append(nsDependentCString(ent->d_name));
 
                 AppendFacesFromFontFile(s.get(), aFontCache, &mFontList);
             }
         }
     }
     closedir(d);
-    for (int i = 0; i < NS_ARRAY_LENGTH(sStandardFonts); i++) {
+    for (unsigned int i = 0; i < NS_ARRAY_LENGTH(sStandardFonts); i++) {
         nsCString s(aFontsDir);
         s.Append(nsDependentCString(sStandardFonts[i]));
 
         AppendFacesFromFontFile(s.get(), aFontCache, &mFontList);
     }
 }
 
 void
--- a/gfx/thebes/gfxOS2Fonts.cpp
+++ b/gfx/thebes/gfxOS2Fonts.cpp
@@ -706,17 +706,17 @@ void gfxOS2FontGroup::CreateGlyphRunsFT(
     PRUint32 lastFont = FontListLength()-1;
     gfxOS2Font *font0 = GetFontAt(0);
     const PRUint8 *p = aUTF8;
     PRUint32 utf16Offset = 0;
     gfxTextRun::CompressedGlyph g;
     const PRUint32 appUnitsPerDevUnit = aTextRun->GetAppUnitsPerDevUnit();
     gfxOS2Platform *platform = gfxOS2Platform::GetPlatform();
 
-    aTextRun->AddGlyphRun(font0, 0);
+    aTextRun->AddGlyphRun(font0, gfxTextRange::kFontGroup, 0, PR_FALSE);
     // a textRun likely has the same font for most of the characters, so we can
     // lock it before the loop for efficiency
     FT_Face face0 = cairo_ft_scaled_font_lock_face(font0->CairoScaledFont());
     while (p < aUTF8 + aUTF8Length) {
         PRBool glyphFound = PR_FALSE;
         // convert UTF-8 character and step to the next one in line
         PRUint8 chLen;
         PRUint32 ch = getUTF8CharAndNext(p, &chLen);
@@ -767,17 +767,17 @@ void gfxOS2FontGroup::CreateGlyphRunsFT(
                         // likely to find more chars in this font, append it
                         // to the font list to find it quicker next time
                         mFonts.AppendElement(fontX);
                         lastFont = FontListLength()-1;
                     }
                 }
 
                 // select the current font into the text run
-                aTextRun->AddGlyphRun(font, utf16Offset);
+                aTextRun->AddGlyphRun(font, gfxTextRange::kFontGroup, utf16Offset, PR_FALSE);
 
                 PRInt32 advance = 0;
                 if (gid == font->GetSpaceGlyph()) {
                     advance = (int)(font->GetMetrics().spaceWidth * appUnitsPerDevUnit);
                 } else if (gid == 0) {
                     advance = -1; // trigger the missing glyphs case below
                 } else {
                     // find next character and its glyph -- in case they exist
@@ -869,16 +869,17 @@ void gfxOS2FontGroup::CreateGlyphRunsFT(
         ++utf16Offset;
     }
     cairo_ft_scaled_font_unlock_face(font0->CairoScaledFont());
 }
 
 // append aFontName to aClosure string array, if not already present
 PRBool gfxOS2FontGroup::FontCallback(const nsAString& aFontName,
                                      const nsACString& aGenericName,
+                                     PRBool aUseFontSet,
                                      void *aClosure)
 {
     nsTArray<nsString> *sa = static_cast<nsTArray<nsString>*>(aClosure);
     if (!aFontName.IsEmpty() && !sa->Contains(aFontName)) {
         sa->AppendElement(aFontName);
     }
     return PR_TRUE;
 }
--- a/gfx/thebes/gfxOS2Fonts.h
+++ b/gfx/thebes/gfxOS2Fonts.h
@@ -120,15 +120,17 @@ public:
     }
 
 protected:
     void InitTextRun(gfxTextRun *aTextRun, const PRUint8 *aUTF8Text,
                      PRUint32 aUTF8Length, PRUint32 aUTF8HeaderLength);
     void CreateGlyphRunsFT(gfxTextRun *aTextRun, const PRUint8 *aUTF8,
                            PRUint32 aUTF8Length);
     static PRBool FontCallback(const nsAString& aFontName,
-                               const nsACString& aGenericName, void *aClosure);
+                               const nsACString& aGenericName,
+                               PRBool aUseFontSet,
+                               void *aClosure);
 
 private:
     PRBool mEnableKerning;
 };
 
 #endif /* GFX_OS2_FONTS_H */
--- a/js/src/assembler/assembler/MacroAssemblerARM.h
+++ b/js/src/assembler/assembler/MacroAssemblerARM.h
@@ -486,18 +486,40 @@ public:
     }
 
     Jump branch32(Condition cond, RegisterID left, TrustedImm32 right, int useConstantPool = 0)
     {
         ASSERT(left != ARMRegisters::S0);
         if (right.m_isPointer) {
             m_assembler.ldr_un_imm(ARMRegisters::S0, right.m_value);
             m_assembler.cmp_r(left, ARMRegisters::S0);
-        } else
-            m_assembler.cmp_r(left, m_assembler.getImm(right.m_value, ARMRegisters::S0));
+        } else {
+            // This is a rather cute (if not confusing) pattern.
+            // unfortunately, it is not quite conducive to switching from
+            // cmp to cmn, so I'm doing so manually.
+            // m_assembler.cmp_r(left, m_assembler.getImm(right.m_value, ARMRegisters::S0));
+
+            // try to shoehorn the immediate into the compare instruction
+            ARMWord arg = m_assembler.getOp2(right.m_value);
+            if (arg != m_assembler.INVALID_IMM) {
+                m_assembler.cmp_r(left, arg);
+            } else {
+                // if it does not fit, try to shoehorn a negative in, and use a negated compare
+                // p.s. why couldn't arm just include the sign bit in the imm, rather than the inst.
+                arg = m_assembler.getOp2(-right.m_value);
+                if (arg != m_assembler.INVALID_IMM) {
+                    m_assembler.cmn_r(left, arg);
+                } else {
+                    // If we get here, we *need* to use a temp register and any way of loading a value
+                    // will enable us to load a negative easily, so there is no reason to switch from
+                    // cmp to cmn.
+                    m_assembler.cmp_r(left, m_assembler.getImm(right.m_value, ARMRegisters::S0));
+                }
+            }
+        }
         return Jump(m_assembler.jmp(ARMCondition(cond), useConstantPool));
     }
 
     // Like branch32, but emit a consistently-structured sequence such that the
     // number of instructions emitted is constant, regardless of the argument
     // values. For ARM, this is identical to branch32WithPatch, except that it
     // does not generate a DataLabel32.
     Jump branch32FixedLength(Condition cond, RegisterID left, TrustedImm32 right)
--- a/js/src/configure.in
+++ b/js/src/configure.in
@@ -4197,18 +4197,21 @@ AC_CACHE_CHECK(for trouble comparing to 
                                [Foo<int> f; return (0 != f);],
                                ac_cv_trouble_comparing_to_zero=no,
                                ac_cv_trouble_comparing_to_zero=yes)])
 if test "$ac_cv_trouble_comparing_to_zero" = yes ; then
   AC_DEFINE(HAVE_CPP_TROUBLE_COMPARING_TO_ZERO)
 fi
 
 # try harder, when checking for __thread support, see bug 521750 comment #33 and below
+# We pass MOZ_OPTIMIZE_LDFLAGS to the linker because if dead_strip is
+# enabled, the linker in xcode 4.1 will crash. Without this it would crash when
+# linking XUL.
 _SAVE_LDFLAGS=$LDFLAGS
-LDFLAGS="$LDFLAGS $DSO_PIC_CFLAGS $DSO_LDOPTS"
+LDFLAGS="$LDFLAGS $DSO_PIC_CFLAGS $DSO_LDOPTS $MOZ_OPTIMIZE_LDFLAGS"
 AC_CACHE_CHECK(for __thread keyword for TLS variables,
                ac_cv_thread_keyword,
                [AC_TRY_LINK([__thread bool tlsIsMainThread = false;],
                             [return tlsIsMainThread;],
                             ac_cv_thread_keyword=yes,
                             ac_cv_thread_keyword=no)])
 LDFLAGS=$_SAVE_LDFLAGS
 if test "$ac_cv_thread_keyword" = yes; then
--- a/js/src/jit-test/tests/basic/testBug653396.js
+++ b/js/src/jit-test/tests/basic/testBug653396.js
@@ -1,5 +1,6 @@
+// |jit-test| error: RangeError
 function g(a, b, c, d) {}
 function f(a, b, c) {
-        arguments.length=8.64e15;
+        arguments.length = getMaxArgs() + 1;
         g.apply(this, arguments);
 }f();
--- a/js/src/jit-test/tests/basic/testCompileScript.js
+++ b/js/src/jit-test/tests/basic/testCompileScript.js
@@ -23,16 +23,16 @@ var body = localstr +
  * monster apply to chew up most the stack.
  */
 var gotIn = false;
 var threwOut = false;
 try {
     (function() {
         gotIn = true;
         (new Function(arg, body))(10000000);
-     }).apply(null, new Array(500 * 1024));
+     }).apply(null, new Array(getMaxArgs()));
 } catch(e) {
     assertEq(""+e, "InternalError: too much recursion");
     threwOut = true;
 }
 assertEq(threwOut, true);
 /* If tweaking some stack parameter makes this fail, shrink monster apply. */
 assertEq(gotIn, true);
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/basic/throw-apply-too-many-args.js
@@ -0,0 +1,25 @@
+function g(a, b, c, d) {}
+function f(a, b, c)
+{
+  arguments.length = getMaxArgs() + 1;
+  g.apply(this, arr);
+}
+var args = [[5], [5], [5], [5], [5], [5], [5], [5], [5], [5], [5], let (x = []) (x.length = getMaxArgs() + 1, x)]
+try
+{
+  for (var i = 0; i < args.length; i++) { arr = args[i]; f(); }
+  throw new Error("didn't throw");
+}
+catch (e)
+{
+  assertEq(e instanceof RangeError, true, "wrong exception: " + e);
+}
+try
+{
+  for (var i = 0; i < args.length; i++) { arr = args[i]; f(); }
+  throw new Error("didn't throw");
+}
+catch (e)
+{
+  assertEq(e instanceof RangeError, true, "wrong exception: " + e);
+}
--- a/js/src/js.msg
+++ b/js/src/js.msg
@@ -139,17 +139,17 @@ MSG_DEF(JSMSG_PAREN_AFTER_LET,         5
 MSG_DEF(JSMSG_CURLY_AFTER_LET,         53, 0, JSEXN_SYNTAXERR, "missing } after let block")
 MSG_DEF(JSMSG_MISSING_PAREN,           54, 0, JSEXN_SYNTAXERR, "unterminated parenthetical")
 MSG_DEF(JSMSG_UNTERM_CLASS,            55, 1, JSEXN_SYNTAXERR, "unterminated character class {0}")
 MSG_DEF(JSMSG_TRAILING_SLASH,          56, 0, JSEXN_SYNTAXERR, "trailing \\ in regular expression")
 MSG_DEF(JSMSG_BAD_CLASS_RANGE,         57, 0, JSEXN_SYNTAXERR, "invalid range in character class")
 MSG_DEF(JSMSG_BAD_REGEXP_FLAG,         58, 1, JSEXN_SYNTAXERR, "invalid regular expression flag {0}")
 MSG_DEF(JSMSG_NO_INPUT,                59, 5, JSEXN_SYNTAXERR, "no input for /{0}/{1}{2}{3}{4}")
 MSG_DEF(JSMSG_CANT_OPEN,               60, 2, JSEXN_ERR, "can't open {0}: {1}")
-MSG_DEF(JSMSG_UNUSED61,                61, 0, JSEXN_NONE, "")
+MSG_DEF(JSMSG_TOO_MANY_FUN_APPLY_ARGS, 61, 0, JSEXN_RANGEERR, "arguments array passed to Function.prototype.apply is too large")
 MSG_DEF(JSMSG_UNMATCHED_RIGHT_PAREN,   62, 0, JSEXN_SYNTAXERR, "unmatched ) in regular expression")
 MSG_DEF(JSMSG_END_OF_DATA,             63, 0, JSEXN_INTERNALERR, "unexpected end of data")
 MSG_DEF(JSMSG_SEEK_BEYOND_START,       64, 0, JSEXN_INTERNALERR, "illegal seek beyond start")
 MSG_DEF(JSMSG_SEEK_BEYOND_END,         65, 0, JSEXN_INTERNALERR, "illegal seek beyond end")
 MSG_DEF(JSMSG_END_SEEK,                66, 0, JSEXN_INTERNALERR, "illegal end-based seek")
 MSG_DEF(JSMSG_WHITHER_WHENCE,          67, 1, JSEXN_INTERNALERR, "unknown seek whence: {0}")
 MSG_DEF(JSMSG_BAD_SCRIPT_MAGIC,        68, 0, JSEXN_INTERNALERR, "bad script XDR magic number")
 MSG_DEF(JSMSG_PAREN_BEFORE_FORMAL,     69, 0, JSEXN_SYNTAXERR, "missing ( before formal parameters")
--- a/js/src/jsapi-tests/Makefile.in
+++ b/js/src/jsapi-tests/Makefile.in
@@ -59,16 +59,17 @@ CPPSRCS = \
   testDeepFreeze.cpp \
   testDefineGetterSetterNonEnumerable.cpp \
   testDefineProperty.cpp \
   testExtendedEq.cpp \
   testFuncCallback.cpp \
   testFunctionProperties.cpp \
   testGCChunkAlloc.cpp \
   testGetPropertyDefault.cpp \
+  testIndexToString.cpp \
   testIntString.cpp \
   testIntern.cpp \
   testLookup.cpp \
   testLooselyEqual.cpp \
   testNewObject.cpp \
   testOps.cpp \
   testParseJSON.cpp \
   testPropCache.cpp \
new file mode 100644
--- /dev/null
+++ b/js/src/jsapi-tests/testIndexToString.cpp
@@ -0,0 +1,56 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: set ts=8 sw=4 et tw=99:
+ */
+
+#include "tests.h"
+
+#include "jsnum.h"
+
+#include "vm/String.h"
+
+BEGIN_TEST(testIndexToString)
+{
+    struct TestPair {
+        uint32 num;
+        const char *expected;
+    } tests[] = {
+        { 0, "0" },
+        { 1, "1" },
+        { 2, "2" },
+        { 9, "9" },
+        { 10, "10" },
+        { 15, "15" },
+        { 16, "16" },
+        { 17, "17" },
+        { 99, "99" },
+        { 100, "100" },
+        { 255, "255" },
+        { 256, "256" },
+        { 257, "257" },
+        { 999, "999" },
+        { 1000, "1000" },
+        { 4095, "4095" },
+        { 4096, "4096" },
+        { 9999, "9999" },
+        { 1073741823, "1073741823" },
+        { 1073741824, "1073741824" },
+        { 1073741825, "1073741825" },
+        { 2147483647, "2147483647" },
+        { 2147483648, "2147483648" },
+        { 2147483649, "2147483649" },
+        { 4294967294, "4294967294" },
+        { 4294967295, "4294967295" },
+    };
+
+    for (size_t i = 0, sz = JS_ARRAY_LENGTH(tests); i < sz; i++) {
+        JSString *str = js::IndexToString(cx, tests[i].num);
+        CHECK(str);
+
+        JSBool match = JS_FALSE;
+        CHECK(JS_StringEqualsAscii(cx, str, tests[i].expected, &match));
+        CHECK(match);
+    }
+
+    return true;
+}
+END_TEST(testIndexToString)
--- a/js/src/jsapi-tests/testScriptInfo.cpp
+++ b/js/src/jsapi-tests/testScriptInfo.cpp
@@ -11,17 +11,28 @@ const char code[] =
 try {              \n\
 	 debugger; \n\
                    \n\
 	 xx += 1;  \n\
 }                  \n\
 catch (e)          \n\
 {                  \n\
 	 xx += 1;  \n\
-}";
+}\n\
+//@sourceMappingURL=http://example.com/path/to/source-map.json";
+
+
+static bool
+CharsMatch(const jschar *p, const char *q) {
+    while (*q) {
+        if (*p++ != *q++)
+            return false;
+    }
+    return true;
+}
 
 // Bug 670958 - fix JS_GetScriptLineExtent, among others
 BEGIN_TEST(testScriptInfo)
 {
     uintN startLine = 1000;
 
     JSObject *scriptObj = JS_CompileScript(cx, global, code, strlen(code),
                                            __FILE__, startLine);
@@ -29,12 +40,13 @@ BEGIN_TEST(testScriptInfo)
     CHECK(scriptObj);
 
     JSScript *script = JS_GetScriptFromObject(scriptObj);
     jsbytecode *start = JS_LineNumberToPC(cx, script, startLine);
     CHECK_EQUAL(JS_GetScriptBaseLineNumber(cx, script), startLine);
     CHECK_EQUAL(JS_PCToLineNumber(cx, script, start), startLine);
     CHECK_EQUAL(JS_GetScriptLineExtent(cx, script), 10);
     CHECK(strcmp(JS_GetScriptFilename(cx, script), __FILE__) == 0);
-    
+    CHECK(CharsMatch(JS_GetScriptSourceMap(cx, script), "http://example.com/path/to/source-map.json"));
+
     return true;
 }
 END_TEST(testScriptInfo)
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -5184,19 +5184,25 @@ JS_IsRunning(JSContext *cx)
 {
     /*
      * The use of cx->fp below is safe. Rationale: Here we don't care if the
      * interpreter state is stale. We just want to know if there *is* any
      * interpreter state.
      */
     VOUCH_DOES_NOT_REQUIRE_STACK();
 
+#ifdef JS_THREADSAFE
+    if (!cx->thread())
+        return false;
+#endif
+
 #ifdef JS_TRACER
     JS_ASSERT_IF(JS_ON_TRACE(cx) && JS_TRACE_MONITOR_ON_TRACE(cx)->tracecx == cx, cx->hasfp());
 #endif
+
     StackFrame *fp = cx->maybefp();
     while (fp && fp->isDummyFrame())
         fp = fp->prev();
     return fp != NULL;
 }
 
 JS_PUBLIC_API(JSBool)
 JS_SaveFrameChain(JSContext *cx)
--- a/js/src/jsdbgapi.cpp
+++ b/js/src/jsdbgapi.cpp
@@ -18,16 +18,17 @@
  * March 31, 1998.
  *
  * 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):
+ *   Nick Fitzgerald <nfitzgerald@mozilla.com>
  *
  * 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
@@ -417,17 +418,17 @@ DestroyTrapAndUnlock(JSContext *cx, JSTr
     cx->free_(trap);
 }
 
 JS_PUBLIC_API(void)
 JS_ClearTrap(JSContext *cx, JSScript *script, jsbytecode *pc,
              JSTrapHandler *handlerp, jsval *closurep)
 {
     JSTrap *trap;
-    
+
     DBG_LOCK(cx->runtime);
     trap = FindTrap(cx->runtime, script, pc);
     if (handlerp)
         *handlerp = trap ? trap->handler : NULL;
     if (closurep)
         *closurep = trap ? trap->closure : JSVAL_NULL;
     if (trap)
         DestroyTrapAndUnlock(cx, trap);
@@ -1040,16 +1041,22 @@ JS_SetFrameReturnValue(JSContext *cx, JS
 /************************************************************************/
 
 JS_PUBLIC_API(const char *)
 JS_GetScriptFilename(JSContext *cx, JSScript *script)
 {
     return script->filename;
 }
 
+JS_PUBLIC_API(const jschar *)
+JS_GetScriptSourceMap(JSContext *cx, JSScript *script)
+{
+    return script->sourceMap;
+}
+
 JS_PUBLIC_API(uintN)
 JS_GetScriptBaseLineNumber(JSContext *cx, JSScript *script)
 {
     return script->lineno;
 }
 
 JS_PUBLIC_API(uintN)
 JS_GetScriptLineExtent(JSContext *cx, JSScript *script)
@@ -1126,17 +1133,17 @@ JS_PUBLIC_API(JSBool)
 JS_EvaluateInStackFrame(JSContext *cx, JSStackFrame *fp,
                         const char *bytes, uintN length,
                         const char *filename, uintN lineno,
                         jsval *rval)
 {
     jschar *chars;
     JSBool ok;
     size_t len = length;
-    
+
     if (!CheckDebugMode(cx))
         return JS_FALSE;
 
     chars = InflateString(cx, bytes, &len);
     if (!chars)
         return JS_FALSE;
     length = (uintN) len;
     ok = JS_EvaluateUCInStackFrame(cx, fp, chars, length, filename, lineno,
--- a/js/src/jsdbgapi.h
+++ b/js/src/jsdbgapi.h
@@ -18,16 +18,17 @@
  * March 31, 1998.
  *
  * 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):
+ *   Nick Fitzgerald <nfitzgerald@mozilla.com>
  *
  * 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
@@ -344,16 +345,19 @@ JS_GetFrameCalleeObject(JSContext *cx, J
 extern JS_PUBLIC_API(JSBool)
 JS_GetValidFrameCalleeObject(JSContext *cx, JSStackFrame *fp, jsval *vp);
 
 /************************************************************************/
 
 extern JS_PUBLIC_API(const char *)
 JS_GetScriptFilename(JSContext *cx, JSScript *script);
 
+extern JS_PUBLIC_API(const jschar *)
+JS_GetScriptSourceMap(JSContext *cx, JSScript *script);
+
 extern JS_PUBLIC_API(uintN)
 JS_GetScriptBaseLineNumber(JSContext *cx, JSScript *script);
 
 extern JS_PUBLIC_API(uintN)
 JS_GetScriptLineExtent(JSContext *cx, JSScript *script);
 
 extern JS_PUBLIC_API(JSVersion)
 JS_GetScriptVersion(JSContext *cx, JSScript *script);
--- a/js/src/jsfun.cpp
+++ b/js/src/jsfun.cpp
@@ -1866,28 +1866,31 @@ js_fun_apply(JSContext *cx, uintN argc, 
     JSObject *aobj = &vp[3].toObject();
     jsuint length;
     if (!js_GetLengthProperty(cx, aobj, &length))
         return false;
 
     LeaveTrace(cx);
 
     /* Step 6. */
-    uintN n = uintN(JS_MIN(length, StackSpace::ARGS_LENGTH_MAX));
+    if (length > StackSpace::ARGS_LENGTH_MAX) {
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_TOO_MANY_FUN_APPLY_ARGS);
+        return false;
+    }
 
     InvokeArgsGuard args;
-    if (!cx->stack.pushInvokeArgs(cx, n, &args))
+    if (!cx->stack.pushInvokeArgs(cx, length, &args))
         return false;
 
     /* Push fval, obj, and aobj's elements as args. */
     args.calleev() = fval;
     args.thisv() = vp[2];
 
     /* Steps 7-8. */
-    if (!GetElements(cx, aobj, n, args.argv()))
+    if (!GetElements(cx, aobj, length, args.argv()))
         return false;
 
     /* Step 9. */
     if (!Invoke(cx, args))
         return false;
     *vp = args.rval();
     return true;
 }
--- a/js/src/jsnum.cpp
+++ b/js/src/jsnum.cpp
@@ -46,16 +46,19 @@
 #define _MCW_EM MCW_EM
 #define _MCW_PC MCW_PC
 #endif
 #include <locale.h>
 #include <limits.h>
 #include <math.h>
 #include <stdlib.h>
 #include <string.h>
+
+#include "mozilla/RangedPtr.h"
+
 #include "jstypes.h"
 #include "jsstdint.h"
 #include "jsutil.h"
 #include "jsapi.h"
 #include "jsatom.h"
 #include "jsbuiltins.h"
 #include "jscntxt.h"
 #include "jsversion.h"
@@ -75,16 +78,17 @@
 #include "jsinterpinlines.h"
 #include "jsnuminlines.h"
 #include "jsobjinlines.h"
 #include "jsstrinlines.h"
 
 #include "vm/String-inl.h"
 
 using namespace js;
+using namespace mozilla;
 
 #ifndef JS_HAVE_STDINT_H /* Native support is innocent until proven guilty. */
 
 JS_STATIC_ASSERT(uint8_t(-1) == UINT8_MAX);
 JS_STATIC_ASSERT(uint16_t(-1) == UINT16_MAX);
 JS_STATIC_ASSERT(uint32_t(-1) == UINT32_MAX);
 JS_STATIC_ASSERT(uint64_t(-1) == UINT64_MAX);
 
@@ -1259,16 +1263,51 @@ namespace js {
 JSFixedString *
 NumberToString(JSContext *cx, jsdouble d)
 {
     if (JSString *str = js_NumberToStringWithBase(cx, d, 10))
         return &str->asFixed();
     return NULL;
 }
 
+JSFixedString *
+IndexToString(JSContext *cx, uint32 u)
+{
+    if (JSAtom::hasUintStatic(u))
+        return &JSAtom::uintStatic(u);
+
+    JSCompartment *c = cx->compartment;
+    if (JSFixedString *str = c->dtoaCache.lookup(10, u))
+        return str;
+
+    JSShortString *str = js_NewGCShortString(cx);
+    if (!str)
+        return NULL;
+
+    /* +1, since MAX_LENGTH does not count the null char. */
+    JS_STATIC_ASSERT(JSShortString::MAX_LENGTH + 1 >= sizeof("4294967295"));
+
+    jschar *storage = str->inlineStorageBeforeInit();
+    size_t length = JSShortString::MAX_SHORT_LENGTH;
+    const RangedPtr<jschar> end(storage + length, storage, length + 1);
+    RangedPtr<jschar> cp = end;
+    *cp = '\0';
+
+    do {
+        jsuint newu = u / 10, digit = u % 10;
+        *--cp = '0' + digit;
+        u = newu;
+    } while (u > 0);
+
+    str->initAtOffsetInBuffer(cp.get(), end - cp);
+
+    c->dtoaCache.cache(10, u, str);
+    return str;
+}
+
 bool JS_FASTCALL
 NumberValueToStringBuffer(JSContext *cx, const Value &v, StringBuffer &sb)
 {
     /* Convert to C-string. */
     ToCStringBuf cbuf;
     const char *cstr;
     if (v.isInt32()) {
         cstr = IntToCString(&cbuf, v.toInt32());
--- a/js/src/jsnum.h
+++ b/js/src/jsnum.h
@@ -203,16 +203,19 @@ namespace js {
  */
 extern bool JS_FASTCALL
 NumberValueToStringBuffer(JSContext *cx, const Value &v, StringBuffer &sb);
 
 /* Same as js_NumberToString, different signature. */
 extern JSFixedString *
 NumberToString(JSContext *cx, jsdouble d);
 
+extern JSFixedString *
+IndexToString(JSContext *cx, uint32 index);
+
 /*
  * Usually a small amount of static storage is enough, but sometimes we need
  * to dynamically allocate much more.  This struct encapsulates that.
  * Dynamically allocated memory will be freed when the object is destroyed.
  */
 struct ToCStringBuf
 {
     /*
--- a/js/src/jsscan.cpp
+++ b/js/src/jsscan.cpp
@@ -18,16 +18,17 @@
  * March 31, 1998.
  *
  * 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):
+ *   Nick Fitzgerald <nfitzgerald@mozilla.com>
  *
  * 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
@@ -174,16 +175,17 @@ TokenStream::init(const jschar *base, si
     filename = fn;
     lineno = ln;
     version = v;
     xml = VersionHasXML(v);
 
     userbuf.init(base, length);
     linebase = base;
     prevLinebase = NULL;
+    sourceMap = NULL;
 
     JSSourceHandler listener = cx->debugHooks->sourceHandler;
     void *listenerData = cx->debugHooks->sourceHandlerData;
 
     if (listener)
         listener(fn, ln, base, length, &listenerTSData, listenerData);
 
     /*
@@ -242,16 +244,18 @@ TokenStream::init(const jschar *base, si
     tokens[0].pos.begin.lineno = tokens[0].pos.end.lineno = ln;
     return true;
 }
 
 TokenStream::~TokenStream()
 {
     if (flags & TSF_OWNFILENAME)
         cx->free_((void *) filename);
+    if (sourceMap)
+        cx->free_(sourceMap);
 }
 
 /* Use the fastest available getc. */
 #if defined(HAVE_GETC_UNLOCKED)
 # define fast_getc getc_unlocked
 #elif defined(HAVE__GETC_NOLOCK)
 # define fast_getc _getc_nolock
 #else
@@ -1127,35 +1131,43 @@ TokenStream::matchUnicodeEscapeIdent(int
 {
     if (peekUnicodeEscape(cp) && IsIdentifierPart(*cp)) {
         skipChars(5);
         return true;
     }
     return false;
 }
 
+/*
+ * Helper function which returns true if the first length(q) characters in p are
+ * the same as the characters in q.
+ */
+static bool
+CharsMatch(const jschar *p, const char *q) {
+    while (*q) {
+        if (*p++ != *q++)
+            return false;
+    }
+    return true;
+}
+
 bool
 TokenStream::getAtLine()
 {
     int c;
     jschar cp[5];
     uintN i, line, temp;
     char filenameBuf[1024];
 
     /*
      * Hack for source filters such as the Mozilla XUL preprocessor:
      * "//@line 123\n" sets the number of the *next* line after the
      * comment to 123.  If we reach here, we've already seen "//".
      */
-    if (peekChars(5, cp) &&
-        cp[0] == '@' &&
-        cp[1] == 'l' &&
-        cp[2] == 'i' &&
-        cp[3] == 'n' &&
-        cp[4] == 'e') {
+    if (peekChars(5, cp) && CharsMatch(cp, "@line")) {
         skipChars(5);
         while ((c = getChar()) != '\n' && c != EOF && IsSpaceOrBOM2(c))
             continue;
         if (JS7_ISDEC(c)) {
             line = JS7_UNDEC(c);
             while ((c = getChar()) != EOF && JS7_ISDEC(c)) {
                 temp = 10 * line + JS7_UNDEC(c);
                 if (temp < line) {
@@ -1195,16 +1207,52 @@ TokenStream::getAtLine()
                 lineno = line;
             }
         }
         ungetChar(c);
     }
     return true;
 }
 
+bool
+TokenStream::getAtSourceMappingURL()
+{
+    jschar peeked[18];
+
+    /* Match comments of the form @sourceMappingURL=<url> */
+    if (peekChars(18, peeked) && CharsMatch(peeked, "@sourceMappingURL=")) {
+        skipChars(18);
+        tokenbuf.clear();
+
+        jschar c;
+        while (!IsSpaceOrBOM2((c = getChar())) &&
+               ((char) c) != '\0' &&
+               ((char) c) != EOF)
+            tokenbuf.append(c);
+
+        if (tokenbuf.empty())
+            /* The source map's URL was missing, but not quite an exception that
+             * we should stop and drop everything for, though. */
+            return true;
+
+        int len = tokenbuf.length();
+
+        if (sourceMap)
+            cx->free_(sourceMap);
+        sourceMap = (jschar *) cx->malloc_(sizeof(jschar) * (len + 1));
+        if (!sourceMap)
+            return false;
+
+        for (int i = 0; i < len; i++)
+            sourceMap[i] = tokenbuf[i];
+        sourceMap[len] = '\0';
+    }
+    return true;
+}
+
 Token *
 TokenStream::newToken(ptrdiff_t adjust)
 {
     cursor = (cursor + 1) & ntokensMask;
     Token *tp = &tokens[cursor];
     tp->ptr = userbuf.addressOfNextRawChar() + adjust;
     tp->pos.begin.index = tp->ptr - linebase;
     tp->pos.begin.lineno = tp->pos.end.lineno = lineno;
@@ -1249,17 +1297,17 @@ IsTokenSane(Token *tp)
     return true;
 }
 #endif
 
 bool
 TokenStream::putIdentInTokenbuf(const jschar *identStart)
 {
     int32 c, qc;
-    const jschar *tmp = userbuf.addressOfNextRawChar(); 
+    const jschar *tmp = userbuf.addressOfNextRawChar();
     userbuf.setAddressOfNextRawChar(identStart);
 
     tokenbuf.clear();
     for (;;) {
         c = getCharIgnoreEOL();
         if (!IsIdentifierPart(c)) {
             if (c != '\\' || !matchUnicodeEscapeIdent(&qc))
                 break;
@@ -1478,17 +1526,17 @@ TokenStream::getTokenInternal()
                 if ((kw->tokentype == TOK_LET || kw->tokentype == TOK_YIELD) &&
                     !ReportStrictModeError(cx, this, NULL, NULL, JSMSG_RESERVED_ID, kw->chars))
                 {
                     goto error;
                 }
             }
         }
 
-        /* 
+        /*
          * Identifiers containing no Unicode escapes can be atomized directly
          * from userbuf.  The rest must have the escapes converted via
          * tokenbuf before atomizing.
          */
         JSAtom *atom;
         if (!hadUnicodeEscape)
             atom = js_AtomizeChars(cx, identStart, userbuf.addressOfNextRawChar() - identStart);
         else if (putIdentInTokenbuf(identStart))
@@ -1676,17 +1724,17 @@ TokenStream::getTokenInternal()
         }
         ungetCharIgnoreEOL(c);
 
         if (c != EOF && IsIdentifierStart(c)) {
             ReportCompileErrorNumber(cx, this, NULL, JSREPORT_ERROR, JSMSG_IDSTART_AFTER_NUMBER);
             goto error;
         }
 
-        /* 
+        /*
          * Unlike identifiers and strings, numbers cannot contain escaped
          * chars, so we don't need to use tokenbuf.  Instead we can just
          * convert the jschars in userbuf directly to the numeric value.
          */
         jsdouble dval;
         const jschar *dummy;
         if (!hasFracOrExp) {
             if (!GetPrefixInteger(cx, numStart, userbuf.addressOfNextRawChar(), 10, &dummy, &dval))
@@ -1894,16 +1942,19 @@ TokenStream::getTokenInternal()
       case '/':
         /*
          * Look for a single-line comment.
          */
         if (matchChar('/')) {
             if (cx->hasAtLineOption() && !getAtLine())
                 goto error;
 
+            if (!getAtSourceMappingURL())
+                goto error;
+
   skipline:
             /* Optimize line skipping if we are not in an HTML comment. */
             if (flags & TSF_IN_HTML_COMMENT) {
                 while ((c = getChar()) != EOF && c != '\n') {
                     if (c == '-' && matchChar('-') && matchChar('>'))
                         flags &= ~TSF_IN_HTML_COMMENT;
                 }
             } else {
--- a/js/src/jsscan.h
+++ b/js/src/jsscan.h
@@ -17,16 +17,17 @@
  * March 31, 1998.
  *
  * 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):
+ *   Nick Fitzgerald <nfitzgerald@mozilla.com>
  *
  * 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
@@ -480,16 +481,24 @@ class TokenStream
         return false;
     }
 
     bool matchToken(TokenKind tt, uintN withFlags) {
         Flagger flagger(this, withFlags);
         return matchToken(tt);
     }
 
+    /*
+     * Give up responsibility for managing the sourceMap filename's memory.
+     */
+    const jschar *releaseSourceMap() {
+        const jschar* sm = sourceMap;
+        sourceMap = NULL;
+        return sm;
+    }
 
   private:
     /*
      * This is the low-level interface to the JS source code buffer.  It just
      * gets raw chars, basically.  TokenStreams functions are layered on top
      * and do some extra stuff like converting all EOL sequences to '\n',
      * tracking the line number, and setting the TSF_EOF flag.  (The "raw" in
      * "raw chars" refers to the lack of EOL sequence normalization.)
@@ -584,16 +593,17 @@ class TokenStream
     void ungetChar(int32 c);
     void ungetCharIgnoreEOL(int32 c);
     Token *newToken(ptrdiff_t adjust);
     bool peekUnicodeEscape(int32 *c);
     bool matchUnicodeEscapeIdStart(int32 *c);
     bool matchUnicodeEscapeIdent(int32 *c);
     bool peekChars(intN n, jschar *cp);
     bool getAtLine();
+    bool getAtSourceMappingURL();
 
     bool getXMLEntity();
     bool getXMLTextOrTag(TokenKind *ttp, Token **tpp);
     bool getXMLMarkup(TokenKind *ttp, Token **tpp);
 
     bool matchChar(int32 expect) {
         int32 c = getChar();
         if (c == expect)
@@ -621,16 +631,17 @@ class TokenStream
     uintN               cursor;         /* index of last parsed token */
     uintN               lookahead;      /* count of lookahead tokens */
     uintN               lineno;         /* current line number */
     uintN               flags;          /* flags -- see above */
     const jschar        *linebase;      /* start of current line;  points into userbuf */
     const jschar        *prevLinebase;  /* start of previous line;  NULL if on the first line */
     TokenBuf            userbuf;        /* user input buffer */
     const char          *filename;      /* input filename or null */
+    jschar              *sourceMap;     /* source map's filename or null */
     void                *listenerTSData;/* listener data for this TokenStream */
     CharBuffer          tokenbuf;       /* current token string buffer */
     int8                oneCharTokens[128];  /* table of one-char tokens */
     JSPackedBool        maybeEOL[256];       /* probabilistic EOL lookup table */
     JSPackedBool        maybeStrSpecial[256];/* speeds up string scanning */
     JSVersion           version;        /* (i.e. to identify keywords) */
     bool                xml;            /* see JSOPTION_XML */
 };
--- a/js/src/jsscript.cpp
+++ b/js/src/jsscript.cpp
@@ -18,16 +18,17 @@
  * March 31, 1998.
  *
  * 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):
+ *   Nick Fitzgerald <nfitzgerald@mozilla.com>
  *
  * 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
@@ -1185,16 +1186,18 @@ JSScript::NewScriptFromCG(JSContext *cx,
         goto bad;
     }
     script->nslots = script->nfixed + cg->maxStackDepth;
     script->staticLevel = uint16(cg->staticLevel);
     script->principals = cg->parser->principals;
     if (script->principals)
         JSPRINCIPALS_HOLD(cx, script->principals);
 
+    script->sourceMap = (jschar *) cg->parser->tokenStream.releaseSourceMap();
+
     if (!js_FinishTakingSrcNotes(cx, cg, script->notes()))
         goto bad;
     if (cg->ntrynotes != 0)
         js_FinishTakingTryNotes(cg, script->trynotes());
     if (cg->objectList.length != 0)
         cg->objectList.finish(script->objects());
     if (cg->regexpList.length != 0)
         cg->regexpList.finish(script->regexps());
@@ -1397,16 +1400,19 @@ DestroyScript(JSContext *cx, JSScript *s
 
 #ifdef JS_METHODJIT
     mjit::ReleaseScriptCode(cx, script);
 #endif
     JS_REMOVE_LINK(&script->links);
 
     script->pcCounters.destroy(cx);
 
+    if (script->sourceMap)
+        cx->free_(script->sourceMap);
+
     memset(script, JS_FREE_PATTERN, script->totalSize());
     cx->free_(script);
 }
 
 void
 js_DestroyScript(JSContext *cx, JSScript *script)
 {
     JS_ASSERT(!cx->runtime->gcRunning);
--- a/js/src/jsscript.h
+++ b/js/src/jsscript.h
@@ -500,16 +500,17 @@ struct JSScript {
     uint32          lineno;     /* base line number of script */
     uint16          nslots;     /* vars plus maximum stack depth */
     uint16          staticLevel;/* static level for display maintenance */
     uint16          nClosedArgs; /* number of args which are closed over. */
     uint16          nClosedVars; /* number of vars which are closed over. */
     js::Bindings    bindings;   /* names of top-level variables in this script
                                    (and arguments if this is a function script) */
     JSPrincipals    *principals;/* principals for this script */
+    jschar          *sourceMap; /* source map file or null */
 
     JSObject        *ownerObject;
 
     void setOwnerObject(JSObject *owner);
 
     union {
         /*
          * A script object of class js_ScriptClass, to ensure the script is GC'd.
--- a/js/src/jsval.h
+++ b/js/src/jsval.h
@@ -102,30 +102,30 @@ JS_ENUM_HEADER(JSValueType, uint8)
     JSVAL_TYPE_NULL                = 0x06,
     JSVAL_TYPE_OBJECT              = 0x07,
 
     /* The below types never appear in a jsval; they are only used in tracing. */
 
     JSVAL_TYPE_NONFUNOBJ           = 0x57,
     JSVAL_TYPE_FUNOBJ              = 0x67,
 
-    JSVAL_TYPE_STRORNULL           = 0x97,
-    JSVAL_TYPE_OBJORNULL           = 0x98,
+    JSVAL_TYPE_STRORNULL           = 0x77,
+    JSVAL_TYPE_OBJORNULL           = 0x78,
 
-    JSVAL_TYPE_BOXED               = 0x99
+    JSVAL_TYPE_BOXED               = 0x79
 } JS_ENUM_FOOTER(JSValueType);
 
 JS_STATIC_ASSERT(sizeof(JSValueType) == 1);
 
 #if JS_BITS_PER_WORD == 32
 
 /* Remember to propagate changes to the C defines below. */
 JS_ENUM_HEADER(JSValueTag, uint32)
 {
-    JSVAL_TAG_CLEAR                = 0xFFFF0000,
+    JSVAL_TAG_CLEAR                = 0xFFFFFF80,
     JSVAL_TAG_INT32                = JSVAL_TAG_CLEAR | JSVAL_TYPE_INT32,
     JSVAL_TAG_UNDEFINED            = JSVAL_TAG_CLEAR | JSVAL_TYPE_UNDEFINED,
     JSVAL_TAG_STRING               = JSVAL_TAG_CLEAR | JSVAL_TYPE_STRING,
     JSVAL_TAG_BOOLEAN              = JSVAL_TAG_CLEAR | JSVAL_TYPE_BOOLEAN,
     JSVAL_TAG_MAGIC                = JSVAL_TAG_CLEAR | JSVAL_TYPE_MAGIC,
     JSVAL_TAG_NULL                 = JSVAL_TAG_CLEAR | JSVAL_TYPE_NULL,
     JSVAL_TAG_OBJECT               = JSVAL_TAG_CLEAR | JSVAL_TYPE_OBJECT
 } JS_ENUM_FOOTER(JSValueTag);
@@ -173,25 +173,25 @@ typedef uint8 JSValueType;
 #define JSVAL_TYPE_UNDEFINED         ((uint8)0x02)
 #define JSVAL_TYPE_BOOLEAN           ((uint8)0x03)
 #define JSVAL_TYPE_MAGIC             ((uint8)0x04)
 #define JSVAL_TYPE_STRING            ((uint8)0x05)
 #define JSVAL_TYPE_NULL              ((uint8)0x06)
 #define JSVAL_TYPE_OBJECT            ((uint8)0x07)
 #define JSVAL_TYPE_NONFUNOBJ         ((uint8)0x57)
 #define JSVAL_TYPE_FUNOBJ            ((uint8)0x67)
-#define JSVAL_TYPE_STRORNULL         ((uint8)0x97)
-#define JSVAL_TYPE_OBJORNULL         ((uint8)0x98)
-#define JSVAL_TYPE_BOXED             ((uint8)0x99)
-#define JSVAL_TYPE_UNINITIALIZED     ((uint8)0xcd)
+#define JSVAL_TYPE_STRORNULL         ((uint8)0x77)
+#define JSVAL_TYPE_OBJORNULL         ((uint8)0x78)
+#define JSVAL_TYPE_BOXED             ((uint8)0x79)
+#define JSVAL_TYPE_UNINITIALIZED     ((uint8)0x7d)
 
 #if JS_BITS_PER_WORD == 32
 
 typedef uint32 JSValueTag;
-#define JSVAL_TAG_CLEAR              ((uint32)(0xFFFF0000))
+#define JSVAL_TAG_CLEAR              ((uint32)(0xFFFFFF80))
 #define JSVAL_TAG_INT32              ((uint32)(JSVAL_TAG_CLEAR | JSVAL_TYPE_INT32))
 #define JSVAL_TAG_UNDEFINED          ((uint32)(JSVAL_TAG_CLEAR | JSVAL_TYPE_UNDEFINED))
 #define JSVAL_TAG_STRING             ((uint32)(JSVAL_TAG_CLEAR | JSVAL_TYPE_STRING))
 #define JSVAL_TAG_BOOLEAN            ((uint32)(JSVAL_TAG_CLEAR | JSVAL_TYPE_BOOLEAN))
 #define JSVAL_TAG_MAGIC              ((uint32)(JSVAL_TAG_CLEAR | JSVAL_TYPE_MAGIC))
 #define JSVAL_TAG_NULL               ((uint32)(JSVAL_TAG_CLEAR | JSVAL_TYPE_NULL))
 #define JSVAL_TAG_OBJECT             ((uint32)(JSVAL_TAG_CLEAR | JSVAL_TYPE_OBJECT))
 
--- a/js/src/methodjit/ICLabels.h
+++ b/js/src/methodjit/ICLabels.h
@@ -210,17 +210,17 @@ struct GetPropLabels : MacroAssemblerTyp
      * Offset from lastStubStart to end of shape jump.
      * TODO: We can redefine the location of lastStubStart to be
      * after the jump -- at which point this is always 0.
      */
     int32 stubShapeJumpOffset : 8;
 
 #if defined JS_CPU_X86 
     static const int32 INLINE_SHAPE_JUMP = 12;
-    static const int32 INLINE_TYPE_JUMP = 12;
+    static const int32 INLINE_TYPE_JUMP = 9;
 #elif defined JS_CPU_X64
     static const int32 INLINE_SHAPE_JUMP = 6;
     static const int32 INLINE_TYPE_JUMP = 19;
 #elif defined JS_CPU_ARM
     /* Offset from the shape guard start to the shape guard jump. */
     static const int32 INLINE_SHAPE_JUMP = 12;
 
     /* Offset from the fast path to the type guard jump. */
--- a/js/src/methodjit/MonoIC.cpp
+++ b/js/src/methodjit/MonoIC.cpp
@@ -1092,18 +1092,23 @@ ic::SplatApplyArgs(VMFrame &f)
                 JSObject *aobj = &fp->argsObj();
 
                 /* Steps 4-5 */
                 uintN length;
                 if (!js_GetLengthProperty(cx, aobj, &length))
                     THROWV(false);
 
                 /* Step 6. */
-                n = Min(length, StackSpace::ARGS_LENGTH_MAX);
+                if (length > StackSpace::ARGS_LENGTH_MAX) {
+                    JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+                                         JSMSG_TOO_MANY_FUN_APPLY_ARGS);
+                    THROWV(false);
+                }
 
+                n = length;
                 if (!BumpStack(f, n))
                     THROWV(false);
 
                 /* Steps 7-8 */
                 Value *argv = JS_ARGV(cx, &vp[1]);  /* vp[1] is the callee */
                 f.regs.sp += n;  /* GetElements may reenter, so inc early. */
                 if (!GetElements(cx, aobj, n, argv))
                     THROWV(false);
@@ -1147,28 +1152,32 @@ ic::SplatApplyArgs(VMFrame &f)
     JSObject *aobj = &vp[3].toObject();
     jsuint length;
     if (!js_GetLengthProperty(cx, aobj, &length))
         THROWV(false);
 
     JS_ASSERT(!JS_ON_TRACE(cx));
 
     /* Step 6. */
-    uintN n = uintN(JS_MIN(length, StackSpace::ARGS_LENGTH_MAX));
+    if (length > StackSpace::ARGS_LENGTH_MAX) {
+        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
+                             JSMSG_TOO_MANY_FUN_APPLY_ARGS);
+        THROWV(false);
+    }
 
-    intN delta = n - 1;
+    intN delta = length - 1;
     if (delta > 0 && !BumpStack(f, delta))
         THROWV(false);
     f.regs.sp += delta;
 
     /* Steps 7-8. */
-    if (!GetElements(cx, aobj, n, f.regs.sp - n))
+    if (!GetElements(cx, aobj, length, f.regs.sp - length))
         THROWV(false);
 
-    f.u.call.dynamicArgc = n;
+    f.u.call.dynamicArgc = length;
     return true;
 }
 
 void
 JITScript::purgeMICs()
 {
     if (!nGetGlobalNames || !nSetGlobalNames)
         return;
--- a/js/src/vm/Stack.cpp
+++ b/js/src/vm/Stack.cpp
@@ -585,16 +585,18 @@ ContextStack::popSegment()
 
     if (!seg_)
         cx_->maybeMigrateVersionOverride();
 }
 
 bool
 ContextStack::pushInvokeArgs(JSContext *cx, uintN argc, InvokeArgsGuard *iag)
 {
+    JS_ASSERT(argc <= StackSpace::ARGS_LENGTH_MAX);
+
     uintN nvars = 2 + argc;
     Value *firstUnused = ensureOnTop(cx, REPORT_ERROR, nvars, CAN_EXTEND, &iag->pushedSeg_);
     if (!firstUnused)
         return false;
 
     ImplicitCast<CallArgs>(*iag) = CallArgsFromVp(argc, firstUnused);
 
     seg_->pushCall(*iag);
--- a/js/src/vm/String-inl.h
+++ b/js/src/vm/String-inl.h
@@ -193,26 +193,39 @@ JSAtom::hasUnitStatic(jschar c)
 inline JSStaticAtom &
 JSAtom::unitStatic(jschar c)
 {
     JS_ASSERT(hasUnitStatic(c));
     return (JSStaticAtom &)unitStaticTable[c];
 }
 
 inline bool
+JSAtom::hasUintStatic(uint32 u)
+{
+    return u < INT_STATIC_LIMIT;
+}
+
+inline JSStaticAtom &
+JSAtom::uintStatic(uint32 u)
+{
+    JS_ASSERT(hasUintStatic(u));
+    return *reinterpret_cast<JSStaticAtom *>(const_cast<JSString::Data *>(intStaticTable[u]));
+}
+
+inline bool
 JSAtom::hasIntStatic(int32 i)
 {
     return uint32(i) < INT_STATIC_LIMIT;
 }
 
 inline JSStaticAtom &
 JSAtom::intStatic(jsint i)
 {
     JS_ASSERT(hasIntStatic(i));
-    return (JSStaticAtom &)*intStaticTable[i];
+    return uintStatic(uint32(i));
 }
 
 inline JSLinearString *
 JSAtom::getUnitStringForElement(JSContext *cx, JSString *str, size_t index)
 {
     JS_ASSERT(index < str->length());
     const jschar *chars = str->getChars(cx);
     if (!chars)
--- a/js/src/vm/String.h
+++ b/js/src/vm/String.h
@@ -655,16 +655,19 @@ class JSAtom : public JSFixedString
 
   public:
     /*
      * While this query can be used for any pointer to GC thing, given a
      * JSString 'str', it is more efficient to use 'str->isStaticAtom()'.
      */
     static inline bool isStatic(const void *ptr);
 
+    static inline bool hasUintStatic(uint32 u);
+    static inline JSStaticAtom &uintStatic(uint32 u);
+
     static inline bool hasIntStatic(int32 i);
     static inline JSStaticAtom &intStatic(jsint i);
 
     static inline bool hasUnitStatic(jschar c);
     static JSStaticAtom &unitStatic(jschar c);
 
     /* May not return atom, returns null on (reported) failure. */
     static inline JSLinearString *getUnitStringForElement(JSContext *cx, JSString *str, size_t index);
--- a/js/src/xpconnect/idl/nsIJSContextStack.idl
+++ b/js/src/xpconnect/idl/nsIJSContextStack.idl
@@ -72,14 +72,14 @@ interface nsIJSContextStackIterator : ns
      *
      * @throws NS_ERROR_NOT_INITIALIZED If there has not been a previous call
      *         to reset.
      * @throws NS_ERROR_NOT_AVAILABLE if already at the end.
      */
     JSContext prev();
 };
 
-[uuid(a1339ae0-05c1-11d4-8f92-0010a4e73d9a)]
+[uuid(b7056a2a-a02d-43b1-abb9-47f81f8bf258)]
 interface nsIThreadJSContextStack : nsIJSContextStack
 {
     /* inherits methods of nsIJSContextStack */
-    attribute JSContext safeJSContext;
+    readonly attribute JSContext safeJSContext;
 };
--- a/js/src/xpconnect/idl/nsIXPConnect.idl
+++ b/js/src/xpconnect/idl/nsIXPConnect.idl
@@ -592,24 +592,16 @@ interface nsIXPConnect : nsISupports
     void debugDumpObject(in nsISupports aCOMObj, in short depth);
     void debugDumpJSStack(in PRBool showArgs,
                           in PRBool showLocals,
                           in PRBool showThisProps);
     void debugDumpEvalInJSStackFrame(in PRUint32 aFrameNumber,
                                      in string aSourceText);
 
     /**
-    * Set fallback JSContext to use when xpconnect can't find an appropriate
-    * context to use to execute JavaScript.
-    *
-    * @deprecated Use nsIThreadJSContextStack::safeJSContext instead.
-    */
-    [deprecated] void setSafeJSContextForCurrentThread(in JSContextPtr cx);
-
-    /**
     * wrapJSAggregatedToNative is just like wrapJS except it is used in cases
     * where the JSObject is also aggregated to some native xpcom Object.
     * At present XBL is the only system that might want to do this.
     *
     * XXX write more!
     *
     * Returns:
     *   success:
--- a/js/src/xpconnect/src/nsXPConnect.cpp
+++ b/js/src/xpconnect/src/nsXPConnect.cpp
@@ -1934,26 +1934,16 @@ nsXPConnect::GetFunctionThisTranslator(c
         XPCAutoLock lock(rt->GetMapLock()); // scoped lock
         old = map->Find(aIID);
         NS_IF_ADDREF(old);
         *_retval = old;
     }
     return NS_OK;
 }
 
-/* void setSafeJSContextForCurrentThread (in JSContextPtr cx); */
-NS_IMETHODIMP 
-nsXPConnect::SetSafeJSContextForCurrentThread(JSContext * cx)
-{
-    XPCCallContext ccx(NATIVE_CALLER);
-    if(!ccx.IsValid())
-        return UnexpectedFailure(NS_ERROR_FAILURE);
-    return ccx.GetThreadData()->GetJSContextStack()->SetSafeJSContext(cx);
-}
-
 /* void clearAllWrappedNativeSecurityPolicies (); */
 NS_IMETHODIMP
 nsXPConnect::ClearAllWrappedNativeSecurityPolicies()
 {
     XPCCallContext ccx(NATIVE_CALLER);
     if(!ccx.IsValid())
         return UnexpectedFailure(NS_ERROR_FAILURE);
 
@@ -2655,28 +2645,16 @@ nsXPConnect::GetSafeJSContext(JSContext 
     {
         *aSafeJSContext = nsnull;
         return NS_ERROR_FAILURE;
     }
 
     return data->GetJSContextStack()->GetSafeJSContext(aSafeJSContext);
 }
 
-/* attribute JSContext SafeJSContext; */
-NS_IMETHODIMP
-nsXPConnect::SetSafeJSContext(JSContext * aSafeJSContext)
-{
-    XPCPerThreadData* data = XPCPerThreadData::GetData(aSafeJSContext);
-
-    if(!data)
-        return NS_ERROR_FAILURE;
-
-    return data->GetJSContextStack()->SetSafeJSContext(aSafeJSContext);
-}
-
 nsIPrincipal*
 nsXPConnect::GetPrincipal(JSObject* obj, PRBool allowShortCircuit) const
 {
     NS_ASSERTION(IS_WRAPPER_CLASS(obj->getClass()),
                  "What kind of wrapper is this?");
 
     if(IS_WN_WRAPPER_OBJECT(obj))
     {
--- a/js/src/xpconnect/src/xpcprivate.h
+++ b/js/src/xpconnect/src/xpcprivate.h
@@ -3547,19 +3547,16 @@ public:
 #endif
 
     const nsTArray<XPCJSContextInfo>* GetStack()
     { return &mStack; }
 
 private:
     nsAutoTArray<XPCJSContextInfo, 16> mStack;
     JSContext*  mSafeJSContext;
-
-    // If non-null, we own it; same as mSafeJSContext if SetSafeJSContext
-    // not called.
     JSContext*  mOwnSafeJSContext;
 };
 
 /***************************************************************************/
 
 #define NS_XPC_JSCONTEXT_STACK_ITERATOR_CID \
 { 0x05bae29d, 0x8aef, 0x486d, \
   { 0x84, 0xaa, 0x53, 0xf4, 0x8f, 0x14, 0x68, 0x11 } }
--- a/js/src/xpconnect/src/xpcthreadcontext.cpp
+++ b/js/src/xpconnect/src/xpcthreadcontext.cpp
@@ -295,45 +295,25 @@ XPCJSContextStack::GetSafeJSContext(JSCo
             }
             if(mSafeJSContext && !glob)
             {
                 // Destroy the context outside the scope of JSAutoRequest that
                 // uses the context in its destructor.
                 JS_DestroyContext(mSafeJSContext);
                 mSafeJSContext = nsnull;
             }
-            // Save it off so we can destroy it later, even if
-            // mSafeJSContext has been set to another context
-            // via SetSafeJSContext.  If we don't get here,
-            // then mSafeJSContext must have been set via
-            // SetSafeJSContext, and we're not responsible for
-            // destroying the passed-in context.
+            // Save it off so we can destroy it later.
             mOwnSafeJSContext = mSafeJSContext;
         }
     }
 
     *aSafeJSContext = mSafeJSContext;
     return mSafeJSContext ? NS_OK : NS_ERROR_UNEXPECTED;
 }
 
-NS_IMETHODIMP
-XPCJSContextStack::SetSafeJSContext(JSContext * aSafeJSContext)
-{
-    if(mOwnSafeJSContext &&
-       mOwnSafeJSContext == mSafeJSContext &&
-       mOwnSafeJSContext != aSafeJSContext)
-    {
-        JS_DestroyContextNoGC(mOwnSafeJSContext);
-        mOwnSafeJSContext = nsnull;
-    }
-
-    mSafeJSContext = aSafeJSContext;
-    return NS_OK;
-}
-
 /***************************************************************************/
 
 PRUintn           XPCPerThreadData::gTLSIndex       = BAD_TLS_INDEX;
 Mutex*            XPCPerThreadData::gLock           = nsnull;
 XPCPerThreadData* XPCPerThreadData::gThreads        = nsnull;
 XPCPerThreadData *XPCPerThreadData::sMainThreadData = nsnull;
 void *            XPCPerThreadData::sMainJSThread   = nsnull;
 
--- a/js/src/xpconnect/src/xpcwrappednative.cpp
+++ b/js/src/xpconnect/src/xpcwrappednative.cpp
@@ -2764,16 +2764,19 @@ CallMethodHelper::InitializeDispatchPara
         }
     }
 
     if(wantsJSContext)
     {
         if(wantsOptArgc)
             // Need to bump mOptArgcIndex up one here.
             mJSContextIndex = mOptArgcIndex++;
+        else if(mMethodInfo->IsSetter() || mMethodInfo->IsGetter())
+            // For attributes, we always put the JSContext* first.
+            mJSContextIndex = 0;
         else
             mJSContextIndex = paramCount - hasRetval;
     }
 
     // iterate through the params to clear flags (for safe cleanup later)
     for(uint8 i = 0; i < paramCount + wantsJSContext + wantsOptArgc; i++)
     {
         nsXPTCVariant* dp = mDispatchParams.AppendElement();
--- a/layout/build/nsLayoutModule.cpp
+++ b/layout/build/nsLayoutModule.cpp
@@ -57,17 +57,16 @@
 #include "nsIControllers.h"
 #include "nsIDOMDOMImplementation.h"
 #include "nsIDOMRange.h"
 #include "nsIDocument.h"
 #include "nsIDocumentEncoder.h"
 #include "nsIDocumentViewer.h"
 #include "nsIFactory.h"
 #include "nsIFrameUtil.h"
-#include "nsIFragmentContentSink.h"
 #include "nsHTMLStyleSheet.h"
 #include "nsIHTMLToTextSink.h"
 #include "nsILayoutDebugger.h"
 #include "nsINameSpaceManager.h"
 #include "nsINodeInfo.h"
 #include "nsIObserver.h"
 #include "nsIObserverService.h"
 #include "nsIPresShell.h"
@@ -343,18 +342,20 @@ public:
 
 NS_IMPL_ISUPPORTS1(LayoutShutdownObserver, nsIObserver)
 
 NS_IMETHODIMP
 LayoutShutdownObserver::Observe(nsISupports *aSubject,
                                 const char *aTopic,
                                 const PRUnichar *someData)
 {
-  if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID))
+  if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
     Shutdown();
+    nsContentUtils::XPCOMShutdown();
+  }
   return NS_OK;
 }
 
 //-----------------------------------------------------------------------------
 
 static PRBool gInitialized = PR_FALSE;
 
 // Perform our one-time intialization for this module
@@ -524,20 +525,16 @@ MAKE_CTOR(CreateSubtreeIterator,        
 // CreateHTMLOptionElement, see below
 // CreateHTMLAudioElement, see below
 MAKE_CTOR(CreateTextEncoder,              nsIDocumentEncoder,          NS_NewTextEncoder)
 MAKE_CTOR(CreateHTMLCopyTextEncoder,      nsIDocumentEncoder,          NS_NewHTMLCopyTextEncoder)
 MAKE_CTOR(CreateXMLContentSerializer,     nsIContentSerializer,        NS_NewXMLContentSerializer)
 MAKE_CTOR(CreateHTMLContentSerializer,    nsIContentSerializer,        NS_NewHTMLContentSerializer)
 MAKE_CTOR(CreateXHTMLContentSerializer,   nsIContentSerializer,        NS_NewXHTMLContentSerializer)
 MAKE_CTOR(CreatePlainTextSerializer,      nsIContentSerializer,        NS_NewPlainTextSerializer)
-MAKE_CTOR(CreateHTMLFragmentSink,         nsIFragmentContentSink,      NS_NewHTMLFragmentContentSink)
-MAKE_CTOR(CreateHTMLFragmentSink2,        nsIFragmentContentSink,      NS_NewHTMLFragmentContentSink2)
-MAKE_CTOR(CreateXMLFragmentSink,          nsIFragmentContentSink,      NS_NewXMLFragmentContentSink)
-MAKE_CTOR(CreateXMLFragmentSink2,         nsIFragmentContentSink,      NS_NewXMLFragmentContentSink2)
 MAKE_CTOR(CreateSanitizingHTMLSerializer, nsIContentSerializer,        NS_NewSanitizingHTMLSerializer)
 MAKE_CTOR(CreateXBLService,               nsIXBLService,               NS_NewXBLService)
 MAKE_CTOR(CreateContentPolicy,            nsIContentPolicy,            NS_NewContentPolicy)
 #ifdef MOZ_XUL
 MAKE_CTOR(CreateXULSortService,           nsIXULSortService,           NS_NewXULSortService)
 // NS_NewXULContentBuilder
 // NS_NewXULTreeBuilder
 MAKE_CTOR(CreateXULDocument,              nsIXULDocument,              NS_NewXULDocument)
@@ -771,21 +768,17 @@ NS_DEFINE_NAMED_CID(NS_CANVASRENDERINGCO
 NS_DEFINE_NAMED_CID(NS_CANVASRENDERINGCONTEXT2DAZURE_CID);
 NS_DEFINE_NAMED_CID(NS_CANVASRENDERINGCONTEXTWEBGL_CID);
 NS_DEFINE_NAMED_CID(NS_TEXT_ENCODER_CID);
 NS_DEFINE_NAMED_CID(NS_HTMLCOPY_TEXT_ENCODER_CID);
 NS_DEFINE_NAMED_CID(NS_XMLCONTENTSERIALIZER_CID);
 NS_DEFINE_NAMED_CID(NS_XHTMLCONTENTSERIALIZER_CID);
 NS_DEFINE_NAMED_CID(NS_HTMLCONTENTSERIALIZER_CID);
 NS_DEFINE_NAMED_CID(NS_PLAINTEXTSERIALIZER_CID);
-NS_DEFINE_NAMED_CID(NS_HTMLFRAGMENTSINK_CID);
-NS_DEFINE_NAMED_CID(NS_HTMLFRAGMENTSINK2_CID);
 NS_DEFINE_NAMED_CID(MOZ_SANITIZINGHTMLSERIALIZER_CID);
-NS_DEFINE_NAMED_CID(NS_XMLFRAGMENTSINK_CID);
-NS_DEFINE_NAMED_CID(NS_XMLFRAGMENTSINK2_CID);
 NS_DEFINE_NAMED_CID(NS_XBLSERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_CONTENTPOLICY_CID);
 NS_DEFINE_NAMED_CID(NS_DATADOCUMENTCONTENTPOLICY_CID);
 NS_DEFINE_NAMED_CID(NS_NODATAPROTOCOLCONTENTPOLICY_CID);
 NS_DEFINE_NAMED_CID(NS_XULCONTROLLERS_CID);
 #ifdef MOZ_XUL
 NS_DEFINE_NAMED_CID(NS_XULSORTSERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_XULTEMPLATEBUILDER_CID);
@@ -910,21 +903,17 @@ static const mozilla::Module::CIDEntry k
   { &kNS_CANVASRENDERINGCONTEXT2D_CID, false, NULL, CreateCanvasRenderingContext2D },
   { &kNS_CANVASRENDERINGCONTEXTWEBGL_CID, false, NULL, CreateCanvasRenderingContextWebGL },
   { &kNS_TEXT_ENCODER_CID, false, NULL, CreateTextEncoder },
   { &kNS_HTMLCOPY_TEXT_ENCODER_CID, false, NULL, CreateHTMLCopyTextEncoder },
   { &kNS_XMLCONTENTSERIALIZER_CID, false, NULL, CreateXMLContentSerializer },
   { &kNS_HTMLCONTENTSERIALIZER_CID, false, NULL, CreateHTMLContentSerializer },
   { &kNS_XHTMLCONTENTSERIALIZER_CID, false, NULL, CreateXHTMLContentSerializer },
   { &kNS_PLAINTEXTSERIALIZER_CID, false, NULL, CreatePlainTextSerializer },
-  { &kNS_HTMLFRAGMENTSINK_CID, false, NULL, CreateHTMLFragmentSink },
-  { &kNS_HTMLFRAGMENTSINK2_CID, false, NULL, CreateHTMLFragmentSink2 },
   { &kMOZ_SANITIZINGHTMLSERIALIZER_CID, false, NULL, CreateSanitizingHTMLSerializer },
-  { &kNS_XMLFRAGMENTSINK_CID, false, NULL, CreateXMLFragmentSink },
-  { &kNS_XMLFRAGMENTSINK2_CID, false, NULL, CreateXMLFragmentSink2 },
   { &kNS_XBLSERVICE_CID, false, NULL, CreateXBLService },
   { &kNS_CONTENTPOLICY_CID, false, NULL, CreateContentPolicy },
   { &kNS_DATADOCUMENTCONTENTPOLICY_CID, false, NULL, nsDataDocumentContentPolicyConstructor },
   { &kNS_NODATAPROTOCOLCONTENTPOLICY_CID, false, NULL, nsNoDataProtocolContentPolicyConstructor },
   { &kNS_XULCONTROLLERS_CID, false, NULL, NS_NewXULControllers },
 #ifdef MOZ_XUL
   { &kNS_XULSORTSERVICE_CID, false, NULL, CreateXULSortService },
   { &kNS_XULTEMPLATEBUILDER_CID, false, NULL, NS_NewXULContentBuilder },
@@ -1050,21 +1039,17 @@ static const mozilla::Module::ContractID
   { NS_CONTENTSERIALIZER_CONTRACTID_PREFIX "text/xml", &kNS_XMLCONTENTSERIALIZER_CID },
   { NS_CONTENTSERIALIZER_CONTRACTID_PREFIX "application/xml", &kNS_XMLCONTENTSERIALIZER_CID },
   { NS_CONTENTSERIALIZER_CONTRACTID_PREFIX "application/xhtml+xml", &kNS_XHTMLCONTENTSERIALIZER_CID },
   { NS_CONTENTSERIALIZER_CONTRACTID_PREFIX "image/svg+xml", &kNS_XMLCONTENTSERIALIZER_CID },
   { NS_CONTENTSERIALIZER_CONTRACTID_PREFIX "text/html", &kNS_HTMLCONTENTSERIALIZER_CID },
   { NS_CONTENTSERIALIZER_CONTRACTID_PREFIX "application/vnd.mozilla.xul+xml", &kNS_XMLCONTENTSERIALIZER_CID },
   { NS_CONTENTSERIALIZER_CONTRACTID_PREFIX "text/plain", &kNS_PLAINTEXTSERIALIZER_CID },
   { NS_PLAINTEXTSINK_CONTRACTID, &kNS_PLAINTEXTSERIALIZER_CID },
-  { NS_HTMLFRAGMENTSINK_CONTRACTID, &kNS_HTMLFRAGMENTSINK_CID },
-  { NS_HTMLFRAGMENTSINK2_CONTRACTID, &kNS_HTMLFRAGMENTSINK2_CID },
   { MOZ_SANITIZINGHTMLSERIALIZER_CONTRACTID, &kMOZ_SANITIZINGHTMLSERIALIZER_CID },
-  { NS_XMLFRAGMENTSINK_CONTRACTID, &kNS_XMLFRAGMENTSINK_CID },
-  { NS_XMLFRAGMENTSINK2_CONTRACTID, &kNS_XMLFRAGMENTSINK2_CID },
   { "@mozilla.org/xbl;1", &kNS_XBLSERVICE_CID },
   { NS_CONTENTPOLICY_CONTRACTID, &kNS_CONTENTPOLICY_CID },
   { NS_DATADOCUMENTCONTENTPOLICY_CONTRACTID, &kNS_DATADOCUMENTCONTENTPOLICY_CID },
   { NS_NODATAPROTOCOLCONTENTPOLICY_CONTRACTID, &kNS_NODATAPROTOCOLCONTENTPOLICY_CID },
   { "@mozilla.org/xul/xul-controllers;1", &kNS_XULCONTROLLERS_CID },
 #ifdef MOZ_XUL
   { "@mozilla.org/xul/xul-sort-service;1", &kNS_XULSORTSERVICE_CID },
   { "@mozilla.org/xul/xul-template-builder;1", &kNS_XULTEMPLATEBUILDER_CID },
--- a/layout/mathml/nsMathMLmpaddedFrame.cpp
+++ b/layout/mathml/nsMathMLmpaddedFrame.cpp
@@ -336,17 +336,16 @@ nsMathMLmpaddedFrame::UpdateValue(PRInt3
 
     if (eCSSUnit_Number == unit)
       amount = NSToCoordRound(float(scaler) * aCSSValue.GetFloatValue());
     else if (eCSSUnit_Percent == unit)
       amount = NSToCoordRound(float(scaler) * aCSSValue.GetPercentValue());
     else
       amount = CalcLength(PresContext(), mStyleContext, aCSSValue);
 
-    nscoord oldValue = aValueToUpdate;
     if (NS_MATHML_SIGN_PLUS == aSign)
       aValueToUpdate += amount;
     else if (NS_MATHML_SIGN_MINUS == aSign)
       aValueToUpdate -= amount;
     else
       aValueToUpdate  = amount;
   }
 }
--- a/layout/reftests/reftest.list
+++ b/layout/reftests/reftest.list
@@ -201,16 +201,19 @@ skip-if(Android) include native-theme/re
 include ../../netwerk/test/reftest/reftest.list
 
 # object/
 include object/reftest.list
 
 # ogg-video/
 include ogg-video/reftest.list
 
+# webm-video/
+include webm-video/reftest.list
+
 # parser/
 include ../../parser/htmlparser/tests/reftest/reftest.list
 
 # percent-overflow-sizing/
 include percent-overflow-sizing/reftest.list
 
 # pixel-rounding/
 include pixel-rounding/reftest.list
--- a/layout/reftests/svg/reftest.list
+++ b/layout/reftests/svg/reftest.list
@@ -199,16 +199,17 @@ random-if(winWidget) == text-gradient-02
 == text-in-link-03.svg text-in-link-03-ref.svg
 # Tests for bug 546813: sanity-check using HTML text, then test SVG behavior.
 fails-if(Android) != text-language-00.xhtml text-language-00-ref.xhtml
 fails-if(Android) random-if(gtk2Widget) != text-language-01.xhtml text-language-01-ref.xhtml # Fails on Linux tryserver due to lack of CJK fonts.
 == text-layout-01.svg text-layout-01-ref.svg
 == text-layout-02.svg text-layout-02-ref.svg
 == text-layout-03.svg text-layout-03-ref.svg
 == text-layout-04.svg text-layout-04-ref.svg
+== text-layout-05.svg text-layout-05-ref.svg
 == text-scale-01.svg text-scale-01-ref.svg
 == text-stroke-scaling-01.svg text-stroke-scaling-01-ref.svg
 == stroke-linecap-square-w-zero-length-segs-01.svg pass.svg
 == stroke-linecap-square-w-zero-length-segs-02.svg pass.svg
 == textPath-01.svg textPath-01-ref.svg
 == text-style-01a.svg text-style-01-ref.svg
 == text-style-01b.svg text-style-01-ref.svg
 == text-style-01c.svg text-style-01-ref.svg
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/text-layout-05-ref.svg
@@ -0,0 +1,13 @@
+<!--
+     Any copyright is dedicated to the Public Domain.
+     http://creativecommons.org/publicdomain/zero/1.0/
+-->
+<svg xmlns="http://www.w3.org/2000/svg">
+  <title>Reference to check that dominant-baseline works for tspan</title>
+
+  <!-- From https://bugzilla.mozilla.org/show_bug.cgi?id=672519 -->
+
+  <rect width="100%" height="100%" fill="lime"/>
+  <text x="20" y="200" dominant-baseline="central"
+        font-family="monospace" font-size="50px">foo bar baz</text>
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/text-layout-05.svg
@@ -0,0 +1,13 @@
+<!--
+     Any copyright is dedicated to the Public Domain.
+     http://creativecommons.org/publicdomain/zero/1.0/
+-->
+<svg xmlns="http://www.w3.org/2000/svg">
+  <title>Testcase to check that dominant-baseline works for tspan</title>
+
+  <!-- From https://bugzilla.mozilla.org/show_bug.cgi?id=672519 -->
+
+  <rect width="100%" height="100%" fill="lime"/>
+  <text x="20" y="200" dominant-baseline="central"
+        font-family="monospace" font-size="50px"><tspan>foo </tspan><tspan>bar </tspan><tspan>baz</tspan></text>
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/aspect-ratio-1-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<div style="width:140px; height:100px; position:relative; left:100px; top:100px; background:black;"></div>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/aspect-ratio-1a.xhtml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body style="background:white;">
+<video src="black140x100.webm" style="width:340px; height:100px; position:relative; top:100px;"></video>
+</body>
+</html>
+</foreignObject>
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/aspect-ratio-1b.xhtml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body style="background:white;">
+<video src="black140x100.webm" style="width:140px; height:300px; position:relative; left:100px;"></video>
+</body>
+</html>
+</foreignObject>
+</svg>  
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/aspect-ratio-2-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<div style="width:280px; height:200px; position:relative; left:200px; top:200px; background:black;"></div>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/aspect-ratio-2a.xhtml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body style="background:white;">
+<video src="black140x100.webm" style="width:680px; height:200px; position:relative; top:200px;"></video>
+</body>
+</html>
+</foreignObject>
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/aspect-ratio-2b.xhtml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body style="background:white;">
+<video src="black140x100.webm" style="width:280px; height:600px; position:relative; left:200px;"></video>
+</body>
+</html>
+</foreignObject>
+</svg>  
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/aspect-ratio-3-ref.xhtml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body style="background:white;">
+<video src="black140x100.webm" style="width:280px; height:200px;"></video>
+</body>
+</html>
+</foreignObject>
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/aspect-ratio-3a.xhtml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body style="background:white;">
+<video src="black140x100.webm" width="280"></video>
+</body>
+</html>
+</foreignObject>
+</svg>  
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/aspect-ratio-3b.xhtml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body style="background:white;">
+<video src="black140x100.webm" height="200"></video>
+</body>
+</html>
+</foreignObject>
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/basic-1-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<div style="width:140px; height:100px; background:black;"></div>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/basic-1.xhtml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body style="background:white;">
+<video src="black140x100.webm"></video>
+</body>
+</html>
+</foreignObject>
+</svg>
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..c972bea5b83f77adde1926d0944d4ccdc4f8bd10
GIT binary patch
literal 561
zc$|}Ry}y`|0Sx4w+8P<1z60^6Mi!^fjT}x*E#;|6xlZkkOirzhOcKEj=@6xizXW|}
zmpEAa?(Pm=-6HC_GA(#b<9*-VJwTpV$hz#{HBF2<5Uxz{ZZP*KgbUIK;@*D)wR9@O
zU<4p9K^^F*b$w$qzmtP+L$^<2S(>Slo|%cBQMe;AuXxFXugB7M7|#vgT;8ebv?cS~
zM3>GE2Umy*pb&u?=DZHdu)5yJSbVgRaZV$H($+c6rFkiBtzq$D0T#`TjLMIjTbQa(
zWIceY<=fDhva2yAWJBY$5Fjn@ysZ=}WB0s~Ve!sJ28M<UEDUoQwNe;T7#P?&T3b6>
zTRIq)2{0HI%x5vZI_HVN^|0az&asi_9C=IAEtx+s{QJK;paB#&FgtelY;I)O-VTiY
Vk4=o#plE{1@IxXFWGg7*ssSIRi^~82
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..9942f3db5c5340ff94ac37e9be74b73043d3709a
GIT binary patch
literal 585
zc$|}Ry}y`|0Sx4w+8P<1z60^6Mi!^fjT}x*E#;|6xlZkkOirzhOcKEj=@6w%LV~`t
zOB}3ycXtP`ZV~ldnHIdJ@xJfw9w1LFWL<XfnkGga2v;U}H<)`D!UgFAalgNTS~`_s
zFanU5pbm7@y1ucQ-^szZq1z|1EX~wN&&)*6DBKa5SG;6G?ZFvMCP&|@OI|+2+q1Y~
zrb}msLkPqKP>4Vcvt9>f7+r5<EI!)EIH!?8Y3rQk(!7+m*0A`n0E^~EM&-xNElf#K
z3=g1c*)}xx>}pJrcivVC6^VP^$gp^SBLhRj1XhN*j9NVmDGUtk9IdS#tt}l4%LEt<
z9V(nxExBIEw`y|i5vx_c<pQr(n%;p5<uLsFze=@X@r*_W4F*9b24;aA1_=g<2>mY%
r91X9&F))DQ3~CeK?w-w!4BOj*sp4Z3V=*ZDpfdcB2nD$c6rsfctLl)J
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..199db19e6c053965bc7f8f8461ef0e12da53265e
GIT binary patch
literal 6781
zc$|}Ry}x+AQ(GgW({~{L)X3uWxsk)EsiizMDc7mJk;$pGkx3%BA)S!{1f+ZgeP@@f
z_1)bQyt+lyb7flankE5e2v;m*T{eij7{Zka-VNePS-tT;$1n;;!6+C7qhJ(_f>AIE
zM!_f;1*2dTjDjHsK>dD)Sz6aOHuF0<_%<xg$xKR3%FR(IGt@KCGf>c001D(LmK5a|
zXD31h!yS+2W|!rr7Nw^ul$n5)X{d)}q$&iLBo-Abl&2P@D&%J7rK)QxB$a07lqlrq
zDR`CUDHxh77#SEEC>UB;nV4G{8Mt(|xXCy$xFmM4%r{-`CQ!mqykx>kL-ur5?&W`{
zJAddb+`(c58i+W*?(FqO#^R%mjLnUV9gPgR&l?%rTEpVQ0xXmtH@8^NI>n&0bxw0>
zUdn?d8yX#UH9CZBXaV|7He?rsI@2f{vb&Kb<ZdHd$f`#9H!d;*9qglE6pVtw3FMu(
zl{z~<Z)8~PRNctH&=4TRFqcuwfx&@+ft{nZwWGDAgJGF~q^3svfqI6ji#hWhYvMn!
ze>wl4d{g<gZ}-1Szg>33!~F;UgX^d2Kgge}7pn5CXQ+1g+4$G<U;10sfBnDNH^~3o
zH|^hK`Fpl4^})5>{~c;o?GMy%{^9*!`(OTF`BiKGu<n@}@jt=7t(>zn-F$iio7t@n
z)z43j-8QxO<cmyMySg&lOVoKe!@qy>_hv9Xa?ldEP?F=zvnt^3tR^w<|Gzb>6Y32a
zPfX*ti|l7Cu}?abdZgfr&cb^OuYCEkfqg?zjs(ZTP3jlV_ZQq;DiZZ*$?Oalf&cQC
zZ7<izbsPD5+f58n72L+pQ*{0Rm)QEhbB+K1$&mjq@Am!wzxm$vZz{iT`^>rJ*b+X5
zrn>)K#dT|r#XbA38`mij=xi4J{MSF<NP!pi8a1&c3-sgvZJB@Jv*o8~hl9JmpX>db
zp1g(8LSWm6tNYeiu3=~h6xed}+OOngQ{8_)V4nGM(F>ofNY!l_JG-lGR_yE!F|n-w
z|8gd0jPGP~RaM=`p=k>or`d?cD}2qES7h?j$$YlkFDHjj)eGjWQ%&EzxW39IwDmlD
z&#@8>@wVrTyiXr&-XkQQ(3cnS@1gu3+yAfg|3_{V-v9gAk@auf^0o!Ot<rMjW?!#d
zQO;qT{pQ5-|B7G2|9)VR`KB_>OEcxrsSBEg&lpc8-<No@S?CaJ1FztYsPB3I1&&O2
zowD?P57Ynu%fJ5rpW*)h$Kg2*B5T(@wt336#5C;8i;H$rol7gHotKEOshkmF+Q5>b
zB`92wn?HvuVW<4Iv%mMRsn1sOK9FwqP&GJGGo>Tav@ocm=fTD^PL7)8J>dcIU6x<6
z7#9C%WPZW0k(q%(fYpHEfS>K<N#QXGOD=r<FOii0vq31Q<4Snj0bl}nlpv}swBWYz
z@23?)ub0*BVf@kb<>b5osdXG{a!smq${yMMYRQch+?&H}7|W-0V2}P3g`&7A?g#7)
z{hAZ*PjBD%=;(RYbcP2!rRI^zZk{X*i;pz2UtpNX1hqNKt^BV4od&;JW;^9G6(9>Q
zaY(11-Scmk|KYWKhJQcXcgQE%Y}|IDaFz2r7N5WyCnUcbo&jegha=CMxOXhx2h2tc
zg)s9N^_2fFU|5m3>(tJI22A5V%q^G`-qrX#x%RmG)e@ec4;X;@fgwSWexQHI*AMfF
zcmY*?vY3HoNB_SDriE><wVobgpqEd89#Phy)FYq?p}yTcn;RLnw|{SB{MaNa1^|%R
B22lV2
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..5eb0b52511b5ae9244b7819f2d05fae947bb0b25
GIT binary patch
literal 1157
zc%17D@N?(olHy`uVBq!ia0vp^zkv7z2NRI=v&lXKq&N#aB8wRq_zr_G<MI3zDL_HS
z;vjb?hIQv;UIIBR>5jgR3=A9lx&I`x0{IHb9znhg3{`3j3=J(16B}MIFq9fFFuY1&
zV6d9Oz#v{QXIG#N0|WCrPZ!6KinzDe7<rE<h_E^eL};!!&fv<xRi>BT@OSd`bNO!{
zE_YaR;QZbAMvq3p%H`==1@<W+0Skf|%I_B~WZKc*cQ^9mb??ICwjm7PFKk?E{ccA)
z*8@4LZKcO$zXvehaX!B7-Hyj{S`F1NZd{WszvIkWz%P4y*W<qG6%6kdCP$awDdZPD
wU|W*&y3hI@*u31kqlS$dHfk944g1a5)3fh}Q}Z`7V3EM!>FVdQ&MBb@0GhKZc>n+a
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/canvas-1a.xhtml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1" class="reftest-wait">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body>
+<canvas id="canvas" width="200" height="200"></canvas>
+<script>
+var video = document.createElement("video");
+video.src = "black140x100.webm";
+video.load();
+function draw() {
+  var canvas = document.getElementById("canvas");
+  var ctx = canvas.getContext("2d");
+  try {
+    ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
+  } catch (e) {
+  }
+  document.documentElement.removeAttribute("class");
+}
+video.addEventListener("loadeddata", draw, false);
+</script>
+</body>
+</html>
+</foreignObject>
+</svg>  
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/canvas-1b.xhtml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body>
+<canvas id="canvas" width="200" height="200"></canvas>
+<script>
+function draw() {
+  var video = document.getElementById("video");
+  var canvas = document.getElementById("canvas");
+  var ctx = canvas.getContext("2d");
+  try {
+    ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
+  } catch (e) {
+  }
+  document.documentElement.removeAttribute("class");
+}
+</script>
+<video id="video" src="black140x100.webm" onloadeddata="draw()" style="opacity:0"></video>
+</body>
+</html>
+</foreignObject>
+</svg>  
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/clipping-1-ref.html
@@ -0,0 +1,9 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white">
+<div style="position:absolute; left:0; top:0; width:200px; height:600px;">
+  <video src="black140x100.webm" style="width:400px; margin-left:-100px;"></video>
+</div>
+<div style="position:absolute; left:200px; top:0; background:white; width:200px; height:600px;"></div>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/clipping-1a.html
@@ -0,0 +1,8 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white">
+<div style="overflow:hidden; position:absolute; left:0; top:0; width:200px; height:600px;">
+  <video src="black140x100.webm" style="width:400px; margin-left:-100px;"></video>
+</div>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/empty-1-ref.html
@@ -0,0 +1,5 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/empty-1a.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<video src="black140x100.webm" style="width:0"></video>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/empty-1b.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<video src="black140x100.webm" style="height:0"></video>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/encoded-aspect-ratio-1-ref.html
@@ -0,0 +1,19 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<div style="background-color: black; width: 150px; height: 100px; position: absolute; left: 10px; top: 10px;"></div>
+
+<!-- Left side vertical. -->
+<div style="position: absolute; left: 9px; top: 9px; width: 2px; height: 102px; z-index: 2; background: red;"></div>
+
+<!-- Right side vertical. -->
+<div style="position: absolute; left: 159px; top: 9px; width: 2px; height: 102px; z-index: 2; background: red;"></div>
+
+<!-- Top horizontal bar. -->
+<div style="position: absolute; left: 9px; top: 9px; width: 152px; height: 2px; z-index: 2; background: red;"></div>
+
+<!-- Bottom horizontal bar. -->
+<div style="position: absolute; left: 9px; top: 109px; width: 152px; height: 2px; z-index: 2; background: red;"></div>
+
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/encoded-aspect-ratio-1.html
@@ -0,0 +1,29 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<!--
+     Test if video displays correctly with a 3:2 aspect ratio.
+     It should display at w=150 h=100.
+     On some Linux systems, the scaling to preserve the aspect ratio can sample
+     the pixels outside visible region. This results in a thin grey line down
+     some sides of the scaled picture. We add red bars over the edges to
+     overwrite such happenings, to make the test reliable.
+-->
+<video src="black100x100-aspect3to2.webm"
+       style="position:absolute; left: 10px; top: 10px; z-index: 1;">
+</video>
+
+<!-- Left side vertical. -->
+<div style="position: absolute; left: 9px; top: 9px; width: 2px; height: 102px; z-index: 2; background: red;"></div>
+
+<!-- Right side vertical. -->
+<div style="position: absolute; left: 159px; top: 9px; width: 2px; height: 102px; z-index: 2; background: red;"></div>
+
+<!-- Top horizontal bar. -->
+<div style="position: absolute; left: 9px; top: 9px; width: 152px; height: 2px; z-index: 2; background: red;"></div>
+
+<!-- Bottom horizontal bar. -->
+<div style="position: absolute; left: 9px; top: 109px; width: 152px; height: 2px; z-index: 2; background: red;"></div>
+
+</body>
+</html>
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..b2bf32762d7d6b4b59df156d759629e10bfd1988
GIT binary patch
literal 224
zc%17D@N?(olHy`uVBq!ia0vp^Za^%@!2}{F{`Uk@jKx9jP7LeL$-D$|SkfJR9T^xl
z_H+M9WCijSl0AZa85pY67#JE_7#My5g&JNkFq9fFFuY1&V6d9Oz#v{QXIG#NP$JIL
z#W5tp{q0ppUIqmo7RL=ua%Ub12pm}N>1@oxoSXmsSHxz~>hvW^`$cCzZ#(B9zvRl)
zx`Iyaok3lGto|QZ^p_pq*rKYF_|lQl_5w2q9Z6yEHmttlU8UK&l(#SJX*OHvwjQ8O
N44$rjF6*2UngGHvMJ@mU
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/object-aspect-ratio-1a.xhtml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body style="background:white;">
+<object data="black140x100.webm" style="width:340px; height:100px; position:relative; top:100px;"></object>
+</body>
+</html>
+</foreignObject>
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/object-aspect-ratio-1b.xhtml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body style="background:white;">
+<object data="black140x100.webm" style="width:140px; height:300px; position:relative; left:100px;"></object>
+</body>
+</html>
+</foreignObject>
+</svg>  
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/object-aspect-ratio-2a.xhtml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body style="background:white;">
+<object data="black140x100.webm" style="width:680px; height:200px; position:relative; top:200px;"></object>
+</body>
+</html>
+</foreignObject>
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/object-aspect-ratio-2b.xhtml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body style="background:white;">
+<object data="black140x100.webm" style="width:280px; height:600px; position:relative; left:200px;"></object>
+</body>
+</html>
+</foreignObject>
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/offset-1-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<div style="width:29px; height:29px; background:black;"></div>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/offset-1.xhtml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject filter="url(../filters.svg#ThresholdRGB)" x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body style="background:white;">
+<video src="black29x19offset.webm"></video>
+</body>
+</html>
+</foreignObject>
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-1.html
@@ -0,0 +1,7 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<!-- Test if poster frame displays correctly when poster is different size. -->
+<video src="black140x100.webm" poster="blue250x200.png"></video>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-10.html
@@ -0,0 +1,18 @@
+<!DOCTYPE HTML>
+<html class="reftest-wait">
+<!-- Test: Create video, add poster, load. Should display poster. -->
+<script>
+function runTest() {
+  var v = document.createElement('video');
+  v.addEventListener('loadeddata', function(){setTimeout(function(){document.documentElement.className = '';}, 0);}, false);
+  v.id = 'v';
+  v.src = "black140x100.webm";
+  v.poster = "blue250x200.png";
+  v.preload = "auto";
+  document.body.appendChild(v);
+}
+
+</script>
+<body style="background:white;" onload="runTest();">
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-11.html
@@ -0,0 +1,29 @@
+<!DOCTYPE HTML>
+<html class="reftest-wait">
+<!-- Test: Create video, load. Add poster frame, load again, poster should show. -->
+<script>
+function runTest() {
+  var v = document.createElement('video');
+  
+  var endTest = function() {
+    setTimeout(function(){document.documentElement.className = '';}, 0);
+  };  
+  
+  var addPoster = function() {
+    v.removeEventListener('loadeddata', addPoster, false);
+    v.poster = "blue250x200.png";
+    v.addEventListener('loadeddata', endTest, false);
+    v.load();
+  };
+  
+  v.addEventListener('loadeddata', addPoster, false);
+  v.id = 'v';
+  v.src = "black140x100.webm";
+  v.preload = "auto";
+  document.body.appendChild(v);
+}
+
+</script>
+<body style="background:white;" onload="runTest();">
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-12.html
@@ -0,0 +1,40 @@
+<!DOCTYPE HTML>
+<html class="reftest-wait">
+<!-- Test: Create video, load, play. Add poster frame, load again, poster should show. -->
+<script>
+function runTest() {
+  var v = document.createElement('video');
+  
+  var endTest = function() {
+    setTimeout(function(){document.documentElement.className = '';}, 0);
+  };
+  
+  var play = 
+    function() {
+      v.removeEventListener('loadeddata', play, false);
+      v.play();
+    }
+
+  var addPoster = function() {
+    v.removeEventListener('playing', addPoster,false);
+    v.poster = "blue250x200.png";
+    v.addEventListener('loadeddata', endTest, false);
+    v.load();
+  };
+
+  v.addEventListener('loadeddata',
+                     play,
+                     false);
+  v.addEventListener('playing',
+                     addPoster,
+                     false);
+  v.id = 'v';
+  v.src = "black140x100.webm";
+  v.preload = "auto";
+  document.body.appendChild(v);
+}
+
+</script>
+<body style="background:white;" onload="runTest();">
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-13.html
@@ -0,0 +1,8 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<!-- Test that poster is stretched by css styling. -->
+<video src="black140x100.webm" poster="blue250x200.png" style="width: 400px; height: 300px;"></video>
+
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-15.html
@@ -0,0 +1,13 @@
+<!DOCTYPE HTML>
+<html>
+<!-- Test that poster is correctly laid out inside borders. Also test that 
+     poster frames smaller than video don't have the video frame drawn behind
+     them etc. -->
+<body style="background:white;">
+<video src="black140x100.webm"
+       poster="green70x30.png"
+       preload="auto"
+       style="border: solid blue 2px;">
+</video>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-2.html
@@ -0,0 +1,7 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<!-- Test if poster frame with invalid poster displays video frame. -->
+<video src="black140x100.webm" poster="not-a-valid-file"></video>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-3.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<html class="reftest-wait">
+<body style="background:white;">
+<!-- Test if poster hides after playing with autoplay. -->
+<video src="black140x100.webm"
+       poster="blue250x200.png"
+       preload="auto"
+       autoplay
+       onplaying="setTimeout(function(){document.documentElement.className = '';},0);"></video>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-4.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<html class="reftest-wait">
+<body style="background:white;">
+<!-- Test if we show video frame after removing valid poster. -->
+<video src="black140x100.webm"
+       preload="auto"
+       id="v"
+       onload="document.getElementById('v').poster = ''; setTimeout(function(){document.documentElement.className = '';}, 0);"
+       poster="blue250x200.png"></video>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-5.html
@@ -0,0 +1,13 @@
+<!DOCTYPE HTML>
+<html class="reftest-wait">
+<body style="background:white;">
+<!-- Test to ensure that changing the poster after video has painted its first
+     frame doesn't render the poster. The video frame should not change to the
+     poster, since it's already painted its first video frame. -->
+<video src="black140x100.webm"
+       preload="auto"
+       id="v"
+       autoplay
+       onended="document.getElementById('v').poster = 'blue250x200.png'; setTimeout(function(){document.documentElement.className = '';},0);"></video>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-6.html
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML>
+<html class="reftest-wait">
+<body style="background:white;">
+<!-- Test that poster frame should hide after completing a seek. -->
+<video src="black140x100.webm"
+       preload="auto"
+       id="v"
+       onloadeddata="var v = document.getElementById('v'); v.currentTime = v.duration;"
+       onseeked="setTimeout(function(){document.documentElement.className = '';}, 0);"
+       poster="blue250x200.png"></video>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-7.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<html class="reftest-wait">
+<body style="background:white;">
+<!-- Test that poster frame changes when you change the poster attribute. -->
+<video src="black140x100.webm"
+       preload="auto"
+       id="v"
+       onload="document.getElementById('v').poster = 'red160x120.png'; setTimeout(function(){document.documentElement.className = '';}, 0);"
+       poster="blue250x200.png"></video>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-8.html
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML>
+<html class="reftest-wait">
+<body style="background:white;">
+<!-- Test if poster hides after playing with play() call. -->
+<video src="black140x100.webm"
+       poster="blue250x200.png"
+       id="v"
+       preload="auto"
+       onloadeddata="document.getElementById('v').play();"
+       onplaying="setTimeout(function(){document.documentElement.className = '';}, 0);"></video>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-ref-black140x100.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<video src="black140x100.webm" preload="auto"></video>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-ref-blue250x200.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<img src="blue250x200.png" alt="poster">
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-ref-blue400x300.html
@@ -0,0 +1,8 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<img src="blue250x200.png" style="width: 400px; height: 300px;">
+</body>
+</html>
+
+
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-ref-green70x30.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<img src="green70x30.png" alt="poster" style="border: solid blue 2px;">
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/poster-ref-red160x120.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white;">
+<img src="red160x120.png" alt="poster">
+</body>
+</html>
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..21737a0e8eb88b704ff2f540ed68945db45fd6a4
GIT binary patch
literal 720
zc%17D@N?(olHy`uVBq!ia0vp^3xK$Sg9%9fI*?}pq&N#aB8wRq_zr_G<MI3zDL_HS
z;vjb?hIQv;UIIBR>5jgR3=A9lx&I`x0{IHb9znhg3{`3j3=J(nbAUn(FBlj~4Hy_+
zB``2p&0t^<FPO6{(1wA5$<ousF{C2y?d6Sv42nEQ9QOTR^w4`pg*(qeVb5>n{{3bj
z*xwyyTh%Rn;NyeKG8egefQ)0N?Z?54QIU}=B3E`<>O1?lImdvhi^0>?&t;ucLK6To
CNL5w<
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/reftest.list
@@ -0,0 +1,33 @@
+fails-if(Android) HTTP(..) == aspect-ratio-1a.xhtml aspect-ratio-1-ref.html
+fails-if(Android) HTTP(..) == aspect-ratio-1b.xhtml aspect-ratio-1-ref.html
+fails-if(Android) skip-if(gtk2Widget) HTTP(..) == aspect-ratio-2a.xhtml aspect-ratio-2-ref.html
+fails-if(Android) skip-if(gtk2Widget) HTTP(..) == aspect-ratio-2b.xhtml aspect-ratio-2-ref.html
+HTTP(..) == aspect-ratio-3a.xhtml aspect-ratio-3-ref.xhtml
+HTTP(..) == aspect-ratio-3b.xhtml aspect-ratio-3-ref.xhtml
+fails-if(Android) random-if(layersGPUAccelerated) fails-if(/^Windows\x20NT\x205\.1/.test(http.oscpu))  == encoded-aspect-ratio-1.html encoded-aspect-ratio-1-ref.html # bug 623460 for WinXP
+fails-if(Android) HTTP(..) == basic-1.xhtml basic-1-ref.html
+skip-if(Android) HTTP(..) == canvas-1a.xhtml basic-1-ref.html
+fails-if(Android) HTTP(..) == canvas-1b.xhtml basic-1-ref.html
+== clipping-1a.html clipping-1-ref.html
+== empty-1a.html empty-1-ref.html
+== empty-1b.html empty-1-ref.html
+#these is skipped because we hang on the htmlparser tests when this is ran
+random skip-if(Android) HTTP(..) == object-aspect-ratio-1a.xhtml aspect-ratio-1-ref.html
+random skip-if(Android) HTTP(..) == object-aspect-ratio-1b.xhtml aspect-ratio-1-ref.html
+skip-if(Android) HTTP(..) == offset-1.xhtml offset-1-ref.html
+random skip-if(Android) HTTP(..) == object-aspect-ratio-2a.xhtml aspect-ratio-2-ref.html
+random skip-if(Android) HTTP(..) == object-aspect-ratio-2b.xhtml aspect-ratio-2-ref.html
+skip-if(Android) skip-if(gtk2Widget) HTTP(..) == zoomed-1.xhtml zoomed-1-ref.html
+skip-if(Android) == poster-1.html poster-ref-blue250x200.html
+skip-if(Android) == poster-2.html poster-ref-black140x100.html
+skip-if(Android) == poster-3.html poster-ref-black140x100.html
+skip-if(Android) == poster-4.html poster-ref-black140x100.html
+skip-if(Android) == poster-5.html poster-ref-black140x100.html
+skip-if(Android) == poster-6.html poster-ref-black140x100.html
+skip-if(Android) == poster-7.html poster-ref-red160x120.html
+skip-if(Android) == poster-8.html poster-ref-black140x100.html
+skip-if(Android) == poster-10.html poster-ref-blue250x200.html
+skip-if(Android) == poster-11.html poster-ref-blue250x200.html
+skip-if(Android) == poster-12.html poster-ref-blue250x200.html
+skip-if(Android) == poster-13.html poster-ref-blue400x300.html
+skip-if(Android) == poster-15.html poster-ref-green70x30.html
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/zoomed-1-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<html>
+<body style="background:white; margin:0;">
+<div style="width:210px; height:150px; background:#010101;"></div>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/webm-video/zoomed-1.xhtml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     version="1.1" reftest-zoom="1.5">
+<!-- use an empty g to force filters.svg to load before onload -->
+<use xlink:href="../filters.svg#empty" />
+<foreignObject x="0" y="0" height="100%" width="100%">
+<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+<body style="background:white; margin:0">
+<video src="black140x100.webm"></video>
+</body>
+</html>
+</foreignObject>
+</svg>
--- a/layout/svg/base/src/nsSVGGlyphFrame.cpp
+++ b/layout/svg/base/src/nsSVGGlyphFrame.cpp
@@ -1058,17 +1058,17 @@ nsSVGGlyphFrame::SetGlyphPosition(gfxPoi
           mTextRun->GetAdvanceWidth(xCount, strLength - xCount, nsnull) *
             metricsScale;
       }
   } else {
     x += mTextRun->GetAdvanceWidth(0, strLength, nsnull) * metricsScale;
   }
 
   gfxFloat y = (textPath || yCount <= 1) ? aPosition->y : yList[yCount - 1];
-  aPosition->MoveTo(x, y - GetBaselineOffset(metricsScale));
+  aPosition->MoveTo(x, y);
 
   gfxFloat pathScale = 1.0;
   if (textPath)
     pathScale = textPath->GetPathScale();
 
   nsTArray<float> dxList, dyList;
   GetEffectiveDxDy(strLength, dxList, dyList);
 
--- a/layout/xul/base/src/nsMenuFrame.cpp
+++ b/layout/xul/base/src/nsMenuFrame.cpp
@@ -87,22 +87,16 @@ using namespace mozilla;
 #if defined(XP_WIN) || defined(XP_OS2)
 #define NSCONTEXTMENUISMOUSEUP 1
 #endif
 
 static PRInt32 gEatMouseMove = PR_FALSE;
 
 static NS_DEFINE_IID(kLookAndFeelCID, NS_LOOKANDFEEL_CID);
 
-nsrefcnt nsMenuFrame::gRefCnt = 0;
-nsString *nsMenuFrame::gShiftText = nsnull;
-nsString *nsMenuFrame::gControlText = nsnull;
-nsString *nsMenuFrame::gMetaText = nsnull;
-nsString *nsMenuFrame::gAltText = nsnull;
-nsString *nsMenuFrame::gModifierSeparator = nsnull;
 const PRInt32 kBlinkDelay = 67; // milliseconds
 
 // this class is used for dispatching menu activation events asynchronously.
 class nsMenuActivateEvent : public nsRunnable
 {
 public:
   nsMenuActivateEvent(nsIContent *aMenu,
                       nsPresContext* aPresContext,
@@ -295,74 +289,23 @@ nsMenuFrame::Init(nsIContent*      aCont
 
   // Set up a mediator which can be used for callbacks on this frame.
   mTimerMediator = new nsMenuTimerMediator(this);
   if (NS_UNLIKELY(!mTimerMediator))
     return NS_ERROR_OUT_OF_MEMORY;
 
   InitMenuParent(aParent);
 
-  //load the display strings for the keyboard accelerators, but only once
-  if (gRefCnt++ == 0) {
-    nsCOMPtr<nsIStringBundleService> bundleService =
-      mozilla::services::GetStringBundleService();
-    nsCOMPtr<nsIStringBundle> bundle;
-    if (bundleService) {
-      rv = bundleService->CreateBundle( "chrome://global-platform/locale/platformKeys.properties",
-                                        getter_AddRefs(bundle));
-    }
-    
-    NS_ASSERTION(NS_SUCCEEDED(rv) && bundle, "chrome://global/locale/platformKeys.properties could not be loaded");
-    nsXPIDLString shiftModifier;
-    nsXPIDLString metaModifier;
-    nsXPIDLString altModifier;
-    nsXPIDLString controlModifier;
-    nsXPIDLString modifierSeparator;
-    if (NS_SUCCEEDED(rv) && bundle) {
-      //macs use symbols for each modifier key, so fetch each from the bundle, which also covers i18n
-      rv = bundle->GetStringFromName(NS_LITERAL_STRING("VK_SHIFT").get(), getter_Copies(shiftModifier));
-      rv = bundle->GetStringFromName(NS_LITERAL_STRING("VK_META").get(), getter_Copies(metaModifier));
-      rv = bundle->GetStringFromName(NS_LITERAL_STRING("VK_ALT").get(), getter_Copies(altModifier));
-      rv = bundle->GetStringFromName(NS_LITERAL_STRING("VK_CONTROL").get(), getter_Copies(controlModifier));
-      rv = bundle->GetStringFromName(NS_LITERAL_STRING("MODIFIER_SEPARATOR").get(), getter_Copies(modifierSeparator));
-    } else {
-      rv = NS_ERROR_NOT_AVAILABLE;
-    }
-    //if any of these don't exist, we get  an empty string
-    gShiftText = new nsString(shiftModifier);
-    gMetaText = new nsString(metaModifier);
-    gAltText = new nsString(altModifier);
-    gControlText = new nsString(controlModifier);
-    gModifierSeparator = new nsString(modifierSeparator);    
-  }
-
   BuildAcceleratorText(PR_FALSE);
   nsIReflowCallback* cb = new nsASyncMenuInitialization(this);
   NS_ENSURE_TRUE(cb, NS_ERROR_OUT_OF_MEMORY);
   PresContext()->PresShell()->PostReflowCallback(cb);
   return rv;
 }
 
-nsMenuFrame::~nsMenuFrame()
-{
-  // Clean up shared statics
-  if (--gRefCnt == 0) {
-    delete gShiftText;
-    gShiftText = nsnull;
-    delete gControlText;  
-    gControlText = nsnull;
-    delete gMetaText;  
-    gMetaText = nsnull;
-    delete gAltText;  
-    gAltText = nsnull;
-    delete gModifierSeparator;
-    gModifierSeparator = nsnull;
-  }
-}
-
 // The following methods are all overridden to ensure that the menupopup frame
 // is placed in the appropriate list.
 nsFrameList
 nsMenuFrame::GetChildList(nsIAtom* aListName) const
 {
   if (nsGkAtoms::popupList == aListName) {
     return nsFrameList(mPopupFrame, mPopupFrame);
   }
@@ -1138,45 +1081,58 @@ nsMenuFrame::BuildAcceleratorText(PRBool
   }
 
   nsAutoString modifiers;
   keyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::modifiers, modifiers);
   
   char* str = ToNewCString(modifiers);
   char* newStr;
   char* token = nsCRT::strtok(str, ", \t", &newStr);
+
+  nsAutoString shiftText;
+  nsAutoString altText;
+  nsAutoString metaText;
+  nsAutoString controlText;
+  nsAutoString modifierSeparator;
+
+  nsContentUtils::GetShiftText(shiftText);
+  nsContentUtils::GetAltText(altText);
+  nsContentUtils::GetMetaText(metaText);
+  nsContentUtils::GetControlText(controlText);
+  nsContentUtils::GetModifierSeparatorText(modifierSeparator);
+
   while (token) {
       
     if (PL_strcmp(token, "shift") == 0)
-      accelText += *gShiftText;
+      accelText += shiftText;
     else if (PL_strcmp(token, "alt") == 0) 
-      accelText += *gAltText; 
+      accelText += altText; 
     else if (PL_strcmp(token, "meta") == 0) 
-      accelText += *gMetaText; 
+      accelText += metaText; 
     else if (PL_strcmp(token, "control") == 0) 
-      accelText += *gControlText; 
+      accelText += controlText; 
     else if (PL_strcmp(token, "accel") == 0) {
       switch (accelKey)
       {
         case nsIDOMKeyEvent::DOM_VK_META:
-          accelText += *gMetaText;
+          accelText += metaText;
           break;
 
         case nsIDOMKeyEvent::DOM_VK_ALT:
-          accelText += *gAltText;
+          accelText += altText;
           break;
 
         case nsIDOMKeyEvent::DOM_VK_CONTROL:
         default:
-          accelText += *gControlText;
+          accelText += controlText;
           break;
       }
     }
     
-    accelText += *gModifierSeparator;
+    accelText += modifierSeparator;
 
     token = nsCRT::strtok(newStr, ", \t", &newStr);
   }
 
   nsMemory::Free(str);
 
   accelText += accelString;
 
--- a/layout/xul/base/src/nsMenuFrame.h
+++ b/layout/xul/base/src/nsMenuFrame.h
@@ -248,17 +248,17 @@ protected:
 
   // Called to execute our command handler. This method can destroy the frame.
   void Execute(nsGUIEvent *aEvent);
 
   // This method can destroy the frame
   NS_IMETHOD AttributeChanged(PRInt32 aNameSpaceID,
                               nsIAtom* aAttribute,
                               PRInt32 aModType);
-  virtual ~nsMenuFrame();
+  virtual ~nsMenuFrame() { };
 
   PRBool SizeToPopup(nsBoxLayoutState& aState, nsSize& aSize);
 
   PRBool ShouldBlink();
   void StartBlinking(nsGUIEvent *aEvent, PRBool aFlipChecked);
   void StopBlinking();
   void CreateMenuCommandEvent(nsGUIEvent *aEvent, PRBool aFlipChecked);
   void PassMenuCommandEventToPopupManager();
@@ -284,20 +284,12 @@ protected:
 
   nsCOMPtr<nsITimer> mOpenTimer;
   nsCOMPtr<nsITimer> mBlinkTimer;
 
   PRUint8 mBlinkState; // 0: not blinking, 1: off, 2: on
   nsRefPtr<nsXULMenuCommandEvent> mDelayedMenuCommandEvent;
 
   nsString mGroupName;
-  
-  //we load some display strings from platformKeys.properties only once
-  static nsrefcnt gRefCnt; 
-  static nsString *gShiftText;
-  static nsString *gControlText;
-  static nsString *gMetaText;
-  static nsString *gAltText;
-  static nsString *gModifierSeparator;
 
 }; // class nsMenuFrame
 
 #endif
--- a/memory/jemalloc/Makefile.in
+++ b/memory/jemalloc/Makefile.in
@@ -121,17 +121,16 @@ DEFFILE = $(srcdir)/jemalloc.def
 
 LDFLAGS += -ENTRY:DllMain
 
 NO_INSTALL_IMPORT_LIBRARY = 1
 
 endif
 else # Not Windows
 
-MODULE_OPTIMIZE_FLAGS = -O2
 ifeq ($(OS_ARCH),SunOS)
 ifndef GNU_CC
 MODULE_OPTIMIZE_FLAGS = -xO5
 endif
 endif
 
 LIBRARY_NAME	= jemalloc
 
--- a/mobile/chrome/content/browser.js
+++ b/mobile/chrome/content/browser.js
@@ -2726,18 +2726,18 @@ Tab.prototype = {
       } else if (!validW && !validH) {
         viewportW = this.useFallbackWidth ? kFallbackBrowserWidth : kDefaultBrowserWidth;
         viewportH = kDefaultBrowserWidth * (screenH / screenW);
       }
     }
 
     // Make sure the viewport height is not shorter than the window when
     // the page is zoomed out to show its full width.
-    if (viewportH * this.clampZoomLevel(this.getPageZoomLevel()) < screenH)
-      viewportH = Math.max(viewportH, screenH * (browser.contentDocumentWidth / screenW));
+    let minScale = this.clampZoomLevel(this.getPageZoomLevel());
+    viewportH = Math.max(viewportH, screenH / minScale);
 
     if (browser.contentWindowWidth != viewportW || browser.contentWindowHeight != viewportH)
       browser.setWindowSize(viewportW, viewportH);
   },
 
   restoreViewportPosition: function restoreViewportPosition(aOldWidth, aNewWidth) {
     let browser = this._browser;
 
@@ -2860,20 +2860,23 @@ Tab.prototype = {
       this._browser = null;
       this._loading = false;
 
       Elements.browsers.removeChild(notification);
     }
   },
 
   clampZoomLevel: function clampZoomLevel(aScale) {
+    let md = this.metadata;
+    if (!this.allowZoom)
+      return (md && md.defaultZoom) ? md.defaultZoom : this.getPageZoomLevel();
+
     let browser = this._browser;
     let bounded = Util.clamp(aScale, ZoomManager.MIN, ZoomManager.MAX);
 
-    let md = this.metadata;
     if (md && md.minZoom)
       bounded = Math.max(bounded, md.minZoom);
     if (md && md.maxZoom)
       bounded = Math.min(bounded, md.maxZoom);
 
     bounded = Math.max(bounded, this.getPageZoomLevel());
 
     let rounded = Math.round(bounded * kBrowserViewZoomLevelPrecision) / kBrowserViewZoomLevelPrecision;
--- a/mobile/themes/core/config.css
+++ b/mobile/themes/core/config.css
@@ -87,16 +87,17 @@ richlistitem .prefvalue {
 }
 
 #editor-container > #editor > hbox > #editor-reset {
   display: none;
 }
 
 #editor-container > hbox > label {
   pointer-events: none;
+  color: black;
 }
 
 #editor + richlistitem {
   display: none;
 }
 
 #editor[default="false"] .preferences-title {
   font-weight: bold;
--- a/modules/libimg/png/CHANGES
+++ b/modules/libimg/png/CHANGES
@@ -2786,19 +2786,50 @@ version 1.4.6rc02 [April 6, 2011]
   Improved the optimization of the zlib CMF byte (see libpng-1.2.6beta03).
 
 version 1.4.6 [April 8, 2011]
   No changes.
 
 version 1.4.7rc01 [April 9, 2011]
   Relocated misplaced new declarations in pngwutil.c.
 
-version 1.4.7 [April 10, 2011]
+version 1.4.7 [April 9, 2011]
   Disabled PNG_PEDANTIC_WARNINGS for all MSC versions as in libpng-1.4.5.
 
+version 1.4.8beta01 [June 4, 2011]
+  Undef "_ALL_SOURCE" for AIX, to prevent "jmpbuf" from being redefined.
+  Copied png_debug macros from pngpriv.h into pngtest.c and removed
+    "#include pngpriv.h" from pngtest.c, to avoid setting a bad example.
+  Pass "" instead of '\0' to png_default_error() in png_err().  This mistake
+    was introduced in libpng-1.2.20beta01.
+  Check for up->location !PNG_AFTER_IDAT when writing unknown chunks
+    before IDAT.
+  Ported bugfix in pngrtran.c from 1.5.3: when expanding a paletted image,
+    always expand to RGBA if transparency is present.
+
+version 1.4.8beta02 [June 5, 2011]
+  Ported bugfix in pngrtran.c from 1.5.3: Ensure coefficients are OK for
+    png_rgb_to_gray_fixed().
+
+version 1.4.8beta03 [June 6, 2011]
+  Check for integer overflow in png_set_rgb_to_gray().
+
+version 1.4.8beta04 [June 7, 2011]
+  Fixed uninitialized memory read in png_format_buffer() (Bug report by
+    Frank Busse, related to CVE-2004-0421).
+
+version 1.4.8beta05 [June 19, 2011]
+  Fixed error in "ACCURATE" 16-to-8 scaling (John Bowler).
+  Check for sCAL chunk too short.
+
+version 1.4.8rc01 [June 30, 2011]
+  No changes.
+
+version 1.4.8 [July 7, 2011]
+  No changes.
 
 Send comments/corrections/commendations to glennrp at users.sourceforge.net
 or to png-mng-implement at lists.sf.net (subscription required; visit
 https://lists.sourceforge.net/lists/listinfo/png-mng-implement).
 
 Glenn R-P
 */ }
 #endif
--- a/modules/libimg/png/LICENSE
+++ b/modules/libimg/png/LICENSE
@@ -5,17 +5,17 @@ included in the libpng distribution, the
 
 COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
 
 If you modify libpng you may insert additional notices immediately following
 this sentence.
 
 This code is released under the libpng license.
 
-libpng versions 1.2.6, August 15, 2004, through 1.4.7, April 10, 2011, are
+libpng versions 1.2.6, August 15, 2004, through 1.4.8, July 7, 2011, are
 Copyright (c) 2004, 2006-2010 Glenn Randers-Pehrson, and are
 distributed according to the same disclaimer and license as libpng-1.2.5
 with the following individual added to the list of Contributing Authors
 
    Cosmin Truta
 
 libpng versions 1.0.7, July 1, 2000, through 1.2.5 - October 3, 2002, are
 Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
@@ -103,9 +103,9 @@ boxes and the like:
 Also, the PNG logo (in PNG format, of course) is supplied in the
 files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
 
 Libpng is OSI Certified Open Source Software.  OSI Certified Open Source is a
 certification mark of the Open Source Initiative.
 
 Glenn Randers-Pehrson
 glennrp at users.sourceforge.net
-April 10, 2011
+July 7, 2011
--- a/modules/libimg/png/MOZCHANGES
+++ b/modules/libimg/png/MOZCHANGES
@@ -1,11 +1,13 @@
 
 Changes made to pristine png source by mozilla.org developers.
 
+2011/07/20  -- Synced with libpng-1.4.8 (bug #669863).
+
 2011/04/08  -- Synced with libpng-1.4.7 (bug #624133).
 
 2010/06/30  -- Synced with libpng-1.4.3 (bug #564792).
 
 2010/02/26  -- Synced with libpng-1.4.1 (bug #544747).
 
 2010/01/04  -- Synced with libpng-1.4.0 (bug #532645).
 
--- a/modules/libimg/png/README
+++ b/modules/libimg/png/README
@@ -1,9 +1,9 @@
-README for libpng version 1.4.7 - April 10, 2011 (shared library 14.0)
+README for libpng version 1.4.8 - July 7, 2011 (shared library 14.0)
 See the note about version numbers near the top of png.h
 
 See INSTALL for instructions on how to install libpng.
 
 Libpng comes in several distribution formats.  Get libpng-*.tar.gz,
 libpng-*.tar.xz or libpng-*.tar.bz2 if you want UNIX-style line endings
 in the text files, or lpng*.zip if you want DOS-style line endings.
 
@@ -109,29 +109,26 @@ lists.sourceforge.net (subscription requ
 https://lists.sourceforge.net/lists/listinfo/png-mng-implement
 to subscribe) or to glennrp at users.sourceforge.net
 
 You can't reach Guy, the original libpng author, at the addresses
 given in previous versions of this document.  He and Andreas will
 read mail addressed to the png-implement list, however.
 
 Please do not send general questions about PNG.  Send them to
-the (png-list at ccrc.wustl.edu, subscription required, write to
-majordomo at ccrc.wustl.edu with "subscribe png-list" in your message).
-On the other hand,
-please do not send libpng questions to that address, send them to me
-or to the png-implement list.  I'll
-get them in the end anyway.  If you have a question about something
+png-mng-misc at lists.sf.net (subscription required; visit
+https://lists.sourceforge.net/lists/listinfo/png-mng-misc to
+subscribe).  If you have a question about something
 in the PNG specification that is related to using libpng, send it
 to me.  Send me any questions that start with "I was using libpng,
 and ...".  If in doubt, send questions to me.  I'll bounce them
 to others, if necessary.
 
 Please do not send suggestions on how to change PNG.  We have
-been discussing PNG for nine years now, and it is official and
+been discussing PNG for sixteen years now, and it is official and
 finished.  If you have suggestions for libpng, however, I'll
 gladly listen.  Even if your suggestion is not used immediately,
 it may be used later.
 
 Files in this distribution:
 
       ANNOUNCE      =>  Announcement of this version, with recent changes
       CHANGES       =>  Description of changes between libpng versions
@@ -180,19 +177,19 @@ Files in this distribution:
                             libpng and zlib
        visualc6         =>  Contains a Microsoft Visual C++ (MSVC)
                             workspace for building libpng and zlib
       scripts       =>  Directory containing scripts for building libpng:
        descrip.mms      =>  VMS makefile for MMS or MMK
        makefile.std     =>  Generic UNIX makefile (cc, creates static
                             libpng.a)
        makefile.elf     =>  Linux/ELF makefile symbol versioning,
-                            (gcc, creates libpng14.so.14.1.4.7)
+                            (gcc, creates libpng14.so.14.1.4.8)
        makefile.linux   =>  Linux/ELF makefile
-                            (gcc, creates libpng14.so.14.1.4.7)
+                            (gcc, creates libpng14.so.14.1.4.8)
        makefile.gcc     =>  Generic makefile (gcc, creates static libpng.a)
        makefile.knr     =>  Archaic UNIX Makefile that converts files with
                             ansi2knr (Requires ansi2knr.c from
                             ftp://ftp.cs.wisc.edu/ghost)
        makefile.aix     =>  AIX makefile
        makefile.cygwin  =>  Cygwin/gcc makefile
        makefile.darwin  =>  Darwin makefile
        makefile.dec     =>  DEC Alpha UNIX makefile
@@ -204,22 +201,22 @@ Files in this distribution:
        makefile.intel   =>  Intel C/C++ version 4.0 and later
        makefile.mingw   =>  Mingw/gcc makefile
        makefile.netbsd  =>  NetBSD/cc makefile, makes libpng.so.
        makefile.ne14bsd  =>  NetBSD/cc makefile, makes
                             libpng14.so
        makefile.openbsd =>  OpenBSD makefile
        makefile.sgi     =>  Silicon Graphics IRIX (cc, creates static lib)
        makefile.sggcc   =>  Silicon Graphics
-                            (gcc, creates libpng14.so.14.1.4.7)
+                            (gcc, creates libpng14.so.14.1.4.8)
        makefile.sunos   =>  Sun makefile
        makefile.solaris =>  Solaris 2.X makefile
-                            (gcc, creates libpng14.so.14.1.4.7)
+                            (gcc, creates libpng14.so.14.1.4.8)
        makefile.so9     =>  Solaris 9 makefile
-                            (gcc, creates libpng14.so.14.1.4.7)
+                            (gcc, creates libpng14.so.14.1.4.8)
        makefile.32sunu  =>  Sun Ultra 32-bit makefile
        makefile.64sunu  =>  Sun Ultra 64-bit makefile
        makefile.sco     =>  For SCO OSr5  ELF and Unixware 7 with Native cc
        makefile.mips    =>  MIPS makefile
        makefile.acorn   =>  Acorn makefile
        makefile.amiga   =>  Amiga makefile
        smakefile.ppc    =>  AMIGA smakefile for SAS C V6.58/7.00 PPC
                             compiler (Requires SCOPTIONS, copied from
--- a/modules/libimg/png/libpng.txt
+++ b/modules/libimg/png/libpng.txt
@@ -1,24 +1,24 @@
 libpng.txt - A description on how to use and modify libpng
 
- libpng version 1.4.3 - June 26, 2010
+ libpng version 1.4.8 - July 7, 2011
  Updated and distributed by Glenn Randers-Pehrson
  <glennrp at users.sourceforge.net>
- Copyright (c) 1998-2009 Glenn Randers-Pehrson
+ Copyright (c) 1998-2010 Glenn Randers-Pehrson
 
  This document is released under the libpng license.
  For conditions of distribution and use, see the disclaimer
  and license in png.h
 
  Based on:
 
- libpng versions 0.97, January 1998, through 1.4.3 - June 26, 2010
+ libpng versions 0.97, January 1998, through 1.4.8 - July 7, 2011
  Updated and distributed by Glenn Randers-Pehrson
- Copyright (c) 1998-2009 Glenn Randers-Pehrson
+ Copyright (c) 1998-2010 Glenn Randers-Pehrson
 
  libpng 1.0 beta 6  version 0.96 May 28, 1997
  Updated and distributed by Andreas Dilger
  Copyright (c) 1996, 1997 Andreas Dilger
 
  libpng 1.0 beta 2 - version 0.88  January 26, 1996
  For conditions of distribution and use, see copyright
  notice in png.h. Copyright (c) 1995, 1996 Guy Eric
@@ -273,17 +273,17 @@ where the default size is 8192 bytes.  N
 is changed immediately and the buffer is reallocated immediately,
 instead of setting a flag to be acted upon later.
 
 Setting up callback code
 
 You can set up a callback function to handle any unknown chunks in the
 input stream. You must supply the function
 
-    read_chunk_callback(png_ptr ptr,
+    read_chunk_callback(png_structp png_ptr,
          png_unknown_chunkp chunk);
     {
        /* The unknown chunk structure contains your
           chunk data, along with similar data for any other
           unknown chunks: */
 
            png_byte name[5];
            png_byte *data;
@@ -319,18 +319,18 @@ chunks will be saved when read, in case 
 one or more of them.  This behavior can be changed with the
 png_set_keep_unknown_chunks() function, described below.
 
 At this point, you can set up a callback function that will be
 called after each row has been read, which you can use to control
 a progress meter or the like.  It's demonstrated in pngtest.c.
 You must supply a function
 
-    void read_row_callback(png_ptr ptr, png_uint_32 row,
-       int pass);
+    void read_row_callback(png_structp png_ptr,
+       png_uint_32 row, int pass);
     {
       /* put your code here */
     }
 
 (You can give it another name that you like instead of "read_row_callback")
 
 To inform libpng about your function, use
 
@@ -571,25 +571,27 @@ in until png_read_end() has read the chu
                         (bit_depths 8, 16)
                      PNG_COLOR_TYPE_RGB_ALPHA
                         (bit_depths 8, 16)
 
                      PNG_COLOR_MASK_PALETTE
                      PNG_COLOR_MASK_COLOR
                      PNG_COLOR_MASK_ALPHA
 
+    interlace_type - (PNG_INTERLACE_NONE or
+                     PNG_INTERLACE_ADAM7)
+
+    compression_type - (must be PNG_COMPRESSION_TYPE_BASE
+                     for PNG 1.0)
+
     filter_method  - (must be PNG_FILTER_TYPE_BASE
                      for PNG 1.0, and can also be
                      PNG_INTRAPIXEL_DIFFERENCING if
                      the PNG datastream is embedded in
                      a MNG-1.0 datastream)
-    compression_type - (must be PNG_COMPRESSION_TYPE_BASE
-                     for PNG 1.0)
-    interlace_type - (PNG_INTERLACE_NONE or
-                     PNG_INTERLACE_ADAM7)
 
     Any or all of interlace_type, compression_type, or
     filter_method can be NULL if you are
     not interested in their values.
 
     Note that png_get_IHDR() returns 32-bit data into
     the application's width and height variables.
     This is an unsafe situation if these are 16-bit
@@ -600,21 +602,21 @@ in until png_read_end() has read the chu
     width            = png_get_image_width(png_ptr,
                          info_ptr);
     height           = png_get_image_height(png_ptr,
                          info_ptr);
     bit_depth        = png_get_bit_depth(png_ptr,
                          info_ptr);
     color_type       = png_get_color_type(png_ptr,
                          info_ptr);
-    filter_method    = png_get_filter_type(png_ptr,
+    interlace_type   = png_get_interlace_type(png_ptr,
                          info_ptr);
     compression_type = png_get_compression_type(png_ptr,
                          info_ptr);
-    interlace_type   = png_get_interlace_type(png_ptr,
+    filter_method    = png_get_filter_type(png_ptr,
                          info_ptr);
 
     channels = png_get_channels(png_ptr, info_ptr);
     channels       - number of channels of info for the
                      color type (valid values are 1 (GRAY,
                      PALETTE), 2 (GRAY_ALPHA), 3 (RGB),
                      4 (RGB_ALPHA or RGB + filler byte))
     rowbytes = png_get_rowbytes(png_ptr, info_ptr);
@@ -653,41 +655,41 @@ pointer into the info_ptr is returned fo
                      The presence of the sRGB chunk
                      means that the pixel data is in the
                      sRGB color space.  This chunk also
                      implies specific values of gAMA and
                      cHRM.
 
     png_get_iCCP(png_ptr, info_ptr, &name,
        &compression_type, &profile, &proflen);
-    name            - The profile name.
-    compression     - The compression type; always
-                      PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
-                      You may give NULL to this argument to
-                      ignore it.
-    profile         - International Color Consortium color
-                      profile data. May contain NULs.
-    proflen         - length of profile data in bytes.
+    name             - The profile name.
+    compression_type - The compression type; always
+                       PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
+                       You may give NULL to this argument to
+                       ignore it.
+    profile          - International Color Consortium color
+                       profile data. May contain NULs.
+    proflen          - length of profile data in bytes.
 
     png_get_sBIT(png_ptr, info_ptr, &sig_bit);
     sig_bit        - the number of significant bits for
                      (PNG_INFO_sBIT) each of the gray,
                      red, green, and blue channels,
                      whichever are appropriate for the
                      given color type (png_color_16)
 
     png_get_tRNS(png_ptr, info_ptr, &trans_alpha,
                      &num_trans, &trans_color);
     trans_alpha    - array of alpha (transparency)
                      entries for palette (PNG_INFO_tRNS)
+    num_trans      - number of transparent entries
+                     (PNG_INFO_tRNS)
     trans_color    - graylevel or color sample values of
                      the single transparent color for
                      non-paletted images (PNG_INFO_tRNS)
-    num_trans      - number of transparent entries
-                     (PNG_INFO_tRNS)
 
     png_get_hIST(png_ptr, info_ptr, &hist);
                      (PNG_INFO_hIST)
     hist           - histogram of palette (array of
                      png_uint_16)
 
     png_get_tIME(png_ptr, info_ptr, &mod_time);
     mod_time       - time image was last modified
@@ -898,17 +900,17 @@ viewing application that wishes to treat
 These three functions are actually aliases for png_set_expand(), added
 in libpng version 1.0.4, with the function names expanded to improve code
 readability.  In some future version they may actually do different
 things.
 
 As of libpng version 1.2.9, png_set_expand_gray_1_2_4_to_8() was
 added.  It expands the sample depth without changing tRNS to alpha.
 
-As of libpng version 1.4.3, not all possible expansions are supported.
+As of libpng version 1.4.8, not all possible expansions are supported.
 
 In the following table, the 01 means grayscale with depth<8, 31 means
 indexed with depth<8, other numerals represent the color type, "T" means
 the tRNS chunk is present, A means an alpha channel is present, and O
 means tRNS or alpha is present but all pixels in the image are opaque.
 
   FROM  01  31   0  0T  0O   2  2T  2O   3  3T  3O  4A  4O  6A  6O 
    TO
@@ -1228,18 +1230,18 @@ Finally, you can write your own transfor
 the existing ones meets your needs.  This is done by setting a callback
 with
 
     png_set_read_user_transform_fn(png_ptr,
        read_transform_fn);
 
 You must supply the function
 
-    void read_transform_fn(png_ptr ptr, row_info_ptr
-       row_info, png_bytep data)
+    void read_transform_fn(png_structp png_ptr, png_row_infop
+        row_info, png_bytep data)
 
 See pngtest.c for a working example.  Your function will be called
 after all of the other transformations have been processed.
 
 You can also set up a pointer to a user structure for use by your
 callback function, and you can inform libpng that your transform
 function will change the number of channels or bit depth with the
 function
@@ -1752,17 +1754,17 @@ to inform libpng that it should not writ
 
 Write callbacks
 
 At this point, you can set up a callback function that will be
 called after each row has been written, which you can use to control
 a progress meter or the like.  It's demonstrated in pngtest.c.
 You must supply a function
 
-    void write_row_callback(png_ptr, png_uint_32 row,
+    void write_row_callback(png_structp png_ptr, png_uint_32 row,
        int pass);
     {
       /* put your code here */
     }
 
 (You can give it another name that you like instead of "write_row_callback")
 
 To inform libpng about your function, use
@@ -1927,24 +1929,24 @@ width, height, bit_depth, and color_type
                      data is in the sRGB color space.
                      This function also causes gAMA and
                      cHRM chunks with the specific values
                      that are consistent with sRGB to be
                      written.
 
     png_set_iCCP(png_ptr, info_ptr, name, compression_type,
                       profile, proflen);
-    name            - The profile name.
-    compression     - The compression type; always
-                      PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
-                      You may give NULL to this argument to
-                      ignore it.
-    profile         - International Color Consortium color
-                      profile data. May contain NULs.
-    proflen         - length of profile data in bytes.
+    name             - The profile name.
+    compression_type - The compression type; always
+                       PNG_COMPRESSION_TYPE_BASE for PNG 1.0.
+                       You may give NULL to this argument to
+                       ignore it.
+    profile          - International Color Consortium color
+                       profile data. May contain NULs.
+    proflen          - length of profile data in bytes.
 
     png_set_sBIT(png_ptr, info_ptr, sig_bit);
     sig_bit        - the number of significant bits for
                      (PNG_INFO_sBIT) each of the gray, red,
                      green, and blue channels, whichever are
                      appropriate for the given color type
                      (png_color_16)
 
@@ -2309,17 +2311,17 @@ Finally, you can write your own transfor
 the existing ones meets your needs.  This is done by setting a callback
 with
 
     png_set_write_user_transform_fn(png_ptr,
        write_transform_fn);
 
 You must supply the function
 
-    void write_transform_fn(png_ptr ptr, row_info_ptr
+    void write_transform_fn(png_structp png_ptr, png_row_infop
        row_info, png_bytep data)
 
 See pngtest.c for a working example.  Your function will be called
 before any of the other transformations are processed.
 
 You can also set up a pointer to a user structure for use by your
 callback function.
 
@@ -3117,16 +3119,22 @@ We removed the obsolete png_check_sig(),
 png_memset_check() functions.  Instead use !png_sig_cmp(), png_memcpy(),
 and png_memset(), respectively.
 
 The function png_set_gray_1_2_4_to_8() was removed. It has been
 deprecated since libpng-1.0.18 and 1.2.9, when it was replaced with
 png_set_expand_gray_1_2_4_to_8() because the former function also
 expanded palette images.
 
+Macros for png_get_uint_16, png_get_uint_32, and png_get_int_32
+were added and are used by default instead of the corresponding
+functions. Unfortunately,
+from libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the  
+function) incorrectly returned a value of type png_uint_32.
+
 We changed the prototype for png_malloc() from
     png_malloc(png_structp png_ptr, png_uint_32 size)
 to
     png_malloc(png_structp png_ptr, png_alloc_size_t size)
 
 This also applies to the prototype for the user replacement malloc_fn().
 
 The png_calloc() function was added and is used in place of
@@ -3144,17 +3152,18 @@ Support for numbered error messages was 
 never got around to actually numbering the error messages. The function
 png_set_strip_error_numbers() was removed from the library by default.
 
 The png_zalloc() and png_zfree() functions are no longer exported.
 The png_zalloc() function no longer zeroes out the memory that it
 allocates.
 
 Support for dithering was disabled by default in libpng-1.4.0, because
-been well tested and doesn't actually "dither".  The code was not
+it has not been well tested and doesn't actually "dither".
+The code was not
 removed, however, and could be enabled by building libpng with
 PNG_READ_DITHER_SUPPORTED defined.  In libpng-1.4.2, this support
 was reenabled, but the function was renamed png_set_quantize() to
 reflect more accurately what it actually does.  At the same time,
 the PNG_DITHER_[RED,GREEN_BLUE]_BITS macros were also renamed to
 PNG_QUANTIZE_[RED,GREEN,BLUE]_BITS.
 
 We removed the trailing '.' from the warning and error messages.
@@ -3267,19 +3276,20 @@ We mark all non-exported functions with 
 
 The prototypes for non-exported functions (except for those in
 pngtest) appear in
 pngpriv.h
 above the comment that says
 
   /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
 
-The names of all exported functions and variables begin
-with  "png_", and all publicly visible C preprocessor
-macros begin with "PNG_".
+To avoid polluting the global namespace, the names of all exported
+functions and variables begin with  "png_", and all publicly visible C
+preprocessor macros begin with "PNG_".  We request that applications that
+use libpng *not* begin any of their own symbols with either of these strings.
 
 We put a space after each comma and after each semicolon
 in "for" statments, and we put spaces before and after each
 C binary operator and after "for" or "while", and before
 "?".  We don't put a space between a typecast and the expression
 being cast, nor do we put one between a function name and the
 left parenthesis that follows it:
 
@@ -3292,23 +3302,23 @@ when there is only one macro being teste
 We do not use the TAB character for indentation in the C sources.
 
 Lines do not exceed 80 characters.
 
 Other rules can be inferred by inspecting the libpng source.
 
 XIII. Y2K Compliance in libpng
 
-June 26, 2010
+July 7, 2011
 
 Since the PNG Development group is an ad-hoc body, we can't make
 an official declaration.
 
 This is your unofficial assurance that libpng from version 0.71 and
-upward through 1.4.3 are Y2K compliant.  It is my belief that earlier
+upward through 1.4.8 are Y2K compliant.  It is my belief that earlier
 versions were also Y2K compliant.
 
 Libpng only has three year fields.  One is a 2-byte unsigned integer that
 will hold years up to 65535.  The other two hold the date in text
 format, and will hold years up to 9999.
 
 The integer is
     "png_uint_16 year" in png_time_struct.
--- a/modules/libimg/png/png.c
+++ b/modules/libimg/png/png.c
@@ -12,17 +12,17 @@
  */
 
 #define PNG_NO_EXTERN
 #define PNG_NO_PEDANTIC_WARNINGS
 #include "png.h"
 #include "pngpriv.h"
 
 /* Generate a compiler error if there is an old png.h in the search path. */
-typedef version_1_4_7 Your_png_h_is_not_version_1_4_7;
+typedef version_1_4_8 Your_png_h_is_not_version_1_4_8;
 
 /* Tells libpng that we have already handled the first "num_bytes" bytes
  * of the PNG file signature.  If the PNG data is embedded into another
  * stream we can set num_bytes = 8 so that libpng will not attempt to read
  * or write any of the magic bytes before it starts on the IHDR.
  */
 
 #ifdef PNG_READ_SUPPORTED
@@ -542,23 +542,23 @@ png_charp PNGAPI
 png_get_copyright(png_const_structp png_ptr)
 {
    PNG_UNUSED(png_ptr)  /* Silence compiler warning about unused png_ptr */
 #ifdef PNG_STRING_COPYRIGHT
       return PNG_STRING_COPYRIGHT
 #else
 #ifdef __STDC__
    return ((png_charp) PNG_STRING_NEWLINE \
-     "libpng version 1.4.7 - April 10, 2011" PNG_STRING_NEWLINE \
+     "libpng version 1.4.8 - July 7, 2011" PNG_STRING_NEWLINE \
      "Copyright (c) 1998-2010 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \
      "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
      "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
      PNG_STRING_NEWLINE);
 #else
-      return ((png_charp) "libpng version 1.4.7 - April 10, 2011\
+      return ((png_charp) "libpng version 1.4.8 - July 7, 2011\
       Copyright (c) 1998-2010 Glenn Randers-Pehrson\
       Copyright (c) 1996-1997 Andreas Dilger\
       Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.");
 #endif
 #endif
 }
 
 /* The following return the library version as a short string in the
--- a/modules/libimg/png/png.h
+++ b/modules/libimg/png/png.h
@@ -1,22 +1,22 @@
 
 /* png.h - header file for PNG reference library
  *
- * libpng version 1.4.7 - April 10, 2011
+ * libpng version 1.4.8 - July 7, 2011
  * Copyright (c) 1998-2011 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
  * This code is released under the libpng license (See LICENSE, below)
  *
  * Authors and maintainers:
  *  libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  *  libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
- *  libpng versions 0.97, January 1998, through 1.4.7 - April 10, 2011: Glenn
+ *  libpng versions 0.97, January 1998, through 1.4.8 - July 7, 2011: Glenn
  *  See also "Contributing Authors", below.
  *
  * Note about libpng version numbers:
  *
  *    Due to various miscommunications, unforeseen code incompatibilities
  *    and occasional factors outside the authors' control, version numbering
  *    on the library has not always been consistent and straightforward.
  *    The following table summarizes matters since version 0.89c, which was
@@ -153,16 +153,19 @@
  *    1.4.5beta05-07          14    10405  14.so.14.5[.0]
  *    1.4.5rc02-03            14    10405  14.so.14.5[.0]
  *    1.4.5                   14    10405  14.so.14.5[.0]
  *    1.4.6beta01-07          14    10406  14.so.14.6[.0]
  *    1.4.6rc01               14    10406  14.so.14.6[.0]
  *    1.4.6                   14    10406  14.so.14.6[.0]
  *    1.4.7rc01               14    10407  14.so.14.7[.0]
  *    1.4.7                   14    10407  14.so.14.7[.0]
+ *    1.4.8beta01-05          14    10408  14.so.14.8[.0]
+ *    1.4.8rc01               14    10408  14.so.14.8[.0]
+ *    1.4.8                   14    10408  14.so.14.8[.0]
  *
  *    Henceforth the source version will match the shared-library major
  *    and minor numbers; the shared-library major version number will be
  *    used for changes in backward compatibility, as it is intended.  The
  *    PNG_LIBPNG_VER macro, which is not used within libpng but is available
  *    for applications, is an unsigned integer of the form xyyzz corresponding
  *    to the source version x.y.z (leading zeros in y and z).  Beta versions
  *    were given the previous public release number plus a letter, until
@@ -184,17 +187,17 @@
 /*
  * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  *
  * If you modify libpng you may insert additional notices immediately following
  * this sentence.
  *
  * This code is released under the libpng license.
  *
- * libpng versions 1.2.6, August 15, 2004, through 1.4.7, April 10, 2011, are
+ * libpng versions 1.2.6, August 15, 2004, through 1.4.8, July 7, 2011, are
  * Copyright (c) 2004, 2006-2010 Glenn Randers-Pehrson, and are
  * distributed according to the same disclaimer and license as libpng-1.2.5
  * with the following individual added to the list of Contributing Authors:
  *
  *    Cosmin Truta
  *
  * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
@@ -296,23 +299,23 @@
  *
  * Thanks to Frank J. T. Wojcik for helping with the documentation.
  */
 
 /*
  * Y2K compliance in libpng:
  * =========================
  *
- *    April 10, 2011
+ *    July 7, 2011
  *
  *    Since the PNG Development group is an ad-hoc body, we can't make
  *    an official declaration.
  *
  *    This is your unofficial assurance that libpng from version 0.71 and
- *    upward through 1.4.7 are Y2K compliant.  It is my belief that earlier
+ *    upward through 1.4.8 are Y2K compliant.  It is my belief that earlier
  *    versions were also Y2K compliant.
  *
  *    Libpng only has three year fields.  One is a 2-byte unsigned integer
  *    that will hold years up to 65535.  The other two hold the date in text
  *    format, and will hold years up to 9999.
  *
  *    The integer is
  *        "png_uint_16 year" in png_time_struct.
@@ -358,27 +361,27 @@
 
 /* This is not the place to learn how to use libpng.  The file libpng.txt
  * describes how to use libpng, and the file example.c summarizes it
  * with some code on which to build.  This file is useful for looking
  * at the actual function definitions and structure components.
  */
 
 /* Version information for png.h - this should match the version in png.c */
-#define PNG_LIBPNG_VER_STRING "1.4.7"
+#define PNG_LIBPNG_VER_STRING "1.4.8"
 #define PNG_HEADER_VERSION_STRING \
-   " libpng version 1.4.7 - April 10, 2011\n"
+   " libpng version 1.4.8 - July 7, 2011\n"
 
 #define PNG_LIBPNG_VER_SONUM   14
 #define PNG_LIBPNG_VER_DLLNUM  14
 
 /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
 #define PNG_LIBPNG_VER_MAJOR   1
 #define PNG_LIBPNG_VER_MINOR   4
-#define PNG_LIBPNG_VER_RELEASE 7
+#define PNG_LIBPNG_VER_RELEASE 8
 /* This should match the numeric part of the final component of
  * PNG_LIBPNG_VER_STRING, omitting any leading zero:
  */
 
 #define PNG_LIBPNG_VER_BUILD  0
 
 /* Release Status */
 #define PNG_LIBPNG_BUILD_ALPHA    1
@@ -398,17 +401,17 @@
 #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_BETA
 
 /* Careful here.  At one time, Guy wanted to use 082, but that would be octal.
  * We must not include leading zeros.
  * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  * version 1.0.0 was mis-numbered 100 instead of 10000).  From
  * version 1.0.1 it's    xxyyzz, where x=major, y=minor, z=release
  */
-#define PNG_LIBPNG_VER 10407 /* 1.4.7 */
+#define PNG_LIBPNG_VER 10408 /* 1.4.8 */
 
 #ifndef PNG_VERSION_INFO_ONLY
 /* Include the compression library's header */
 #include "zlib.h"
 #endif
 
 /* Include all user configurable info, including optional assembler routines */
 #include "pngconf.h"
@@ -1540,17 +1543,17 @@ struct png_struct_def
 /* blend_op flags from inside fcTL */
 #define PNG_BLEND_OP_SOURCE        0x00
 #define PNG_BLEND_OP_OVER          0x01
 #endif /* PNG_APNG_SUPPORTED */
 
 /* This triggers a compiler error in png.c, if png.c and png.h
  * do not agree upon the version number.
  */
-typedef png_structp version_1_4_7;
+typedef png_structp version_1_4_8;
 
 typedef png_struct FAR * FAR * png_structpp;
 
 /* Here are the function definitions most commonly used.  This is not
  * the place to find out how to use libpng.  See libpng.txt for the
  * full explanation, see example.c for the summary.  This just provides
  * a simple one line description of the use of each function.
  */
--- a/modules/libimg/png/pngconf.h
+++ b/modules/libimg/png/pngconf.h
@@ -1,12 +1,12 @@
 
 /* pngconf.h - machine configurable file for libpng
  *
- * libpng version 1.4.7 - April 10, 2011
+ * libpng version 1.4.8 - July 7, 2011
  * For conditions of distribution and use, see copyright notice in png.h
  * Copyright (c) 1998-2011 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
  * This code is released under the libpng license.
  * For conditions of distribution and use, see the disclaimer
  * and license in png.h
--- a/modules/libimg/png/pngerror.c
+++ b/modules/libimg/png/pngerror.c
@@ -1,12 +1,12 @@
 
 /* pngerror.c - stub functions for i/o and memory allocation
  *
- * Last changed in libpng 1.4.6 [March 8, 2011]
+ * Last changed in libpng 1.4.8 [July 7, 2011]
  * Copyright (c) 1998-2011 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
  * This code is released under the libpng license.
  * For conditions of distribution and use, see the disclaimer
  * and license in png.h
  *
@@ -82,22 +82,27 @@ png_error(png_structp png_ptr, png_const
    /* If the custom handler doesn't exist, or if it returns,
       use the default handler, which will not return. */
    png_default_error(png_ptr, error_message);
 }
 #else
 void PNGAPI
 png_err(png_structp png_ptr)
 {
+   /* Prior to 1.4.8 the error_fn received a NULL pointer, expressed
+    * erroneously as '\0', instead of the empty string "".  This was
+    * apparently an error, introduced in libpng-1.2.20, and png_default_error
+    * will crash in this case.
+    */
    if (png_ptr != NULL && png_ptr->error_fn != NULL)
-      (*(png_ptr->error_fn))(png_ptr, '\0');
+      (*(png_ptr->error_fn))(png_ptr, "");
 
    /* If the custom handler doesn't exist, or if it returns,
       use the default handler, which will not return. */
-   png_default_error(png_ptr, '\0');
+   png_default_error(png_ptr, "");
 }
 #endif /* PNG_ERROR_TEXT_SUPPORTED */
 
 #ifdef PNG_WARNINGS_SUPPORTED
 /* This function is called whenever there is a non-fatal error.  This function
  * should not be changed.  If there is a need to handle warnings differently,
  * you should supply a replacement warning function and use
  * png_set_error_fn() to replace the warning function at run-time.
@@ -176,18 +181,23 @@ png_format_buffer(png_structp png_ptr, p
    }
 
    if (error_message == NULL)
       buffer[iout] = '\0';
    else
    {
       buffer[iout++] = ':';
       buffer[iout++] = ' ';
-      png_memcpy(buffer + iout, error_message, PNG_MAX_ERROR_TEXT);
-      buffer[iout + PNG_MAX_ERROR_TEXT - 1] = '\0';
+
+      iin = 0;
+      while (iin < PNG_MAX_ERROR_TEXT-1 && error_message[iin] != '\0')
+         buffer[iout++] = error_message[iin++];
+
+      /* iin < PNG_MAX_ERROR_TEXT, so the following is safe: */
+      buffer[iout] = '\0';
    }
 }
 
 #ifdef PNG_READ_SUPPORTED
 void PNGAPI
 png_chunk_error(png_structp png_ptr, png_const_charp error_message)
 {
    char msg[18+PNG_MAX_ERROR_TEXT];
--- a/modules/libimg/png/pngget.c
+++ b/modules/libimg/png/pngget.c
@@ -1,12 +1,12 @@
 
 /* pngget.c - retrieval of values from info struct
  *
- * Last changed in libpng 1.4.6 [April 10, 2011]
+ * Last changed in libpng 1.4.6 [April 8, 2010]
  * Copyright (c) 1998-2011 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
  * This code is released under the libpng license.
  * For conditions of distribution and use, see the disclaimer
  * and license in png.h
  *
--- a/modules/libimg/png/pngmem.c
+++ b/modules/libimg/png/pngmem.c
@@ -1,12 +1,12 @@
 
 /* pngmem.c - stub functions for memory allocation
  *
- * Last changed in libpng 1.4.6 [April 10, 2011]
+ * Last changed in libpng 1.4.6 [April 8, 2010]
  * Copyright (c) 1998-2011 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
  * This code is released under the libpng license.
  * For conditions of distribution and use, see the disclaimer
  * and license in png.h
  *
--- a/modules/libimg/png/pngpriv.h
+++ b/modules/libimg/png/pngpriv.h
@@ -1,12 +1,12 @@
 
 /* pngpriv.h - private declarations for use inside libpng
  *
- * libpng version 1.4.7 - April 10, 2011
+ * libpng version 1.4.8 - July 7, 2011
  * For conditions of distribution and use, see copyright notice in png.h
  * Copyright (c) 1998-2011 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
  * This code is released under the libpng license.
  * For conditions of distribution and use, see the disclaimer
  * and license in png.h
@@ -21,16 +21,25 @@
  * they should be well aware of the issues that may arise from doing so.
  */
 
 #ifndef PNGPRIV_H
 #define PNGPRIV_H
 
 #ifndef PNG_VERSION_INFO_ONLY
 
+#if defined(_AIX) && defined(_ALL_SOURCE)
+   /* On AIX if _ALL_SOURCE is defined standard header files (including
+    * stdlib.h) define identifiers that are not permitted by the ANSI and
+    * POSIX standards.  In particular 'jmpbuf' is #defined and this will
+    * prevent compilation of libpng.  The following prevents this:
+    */
+#  undef _ALL_SOURCE
+#endif
+
 #include <stdlib.h>
 
 #ifndef PNG_EXTERN
 /* The functions exported by PNG_EXTERN are internal functions, which
  * aren't usually used outside the library (as far as I know), so it is
  * debatable if they should be exported at all.  In the future, when it
  * is possible to have run-time registry of chunk-handling functions,
  * some of these will be made available again.
--- a/modules/libimg/png/pngrtran.c
+++ b/modules/libimg/png/pngrtran.c
@@ -1,12 +1,12 @@
 
 /* pngrtran.c - transforms the data in a row for PNG readers
  *
- * Last changed in libpng 1.4.6 [%RDATE%]
+ * Last changed in libpng 1.4.8 [July 7, 2011]
  * Copyright (c) 1998-2011 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
  * This code is released under the libpng license.
  * For conditions of distribution and use, see the disclaimer
  * and license in png.h
  *
@@ -655,20 +655,31 @@ png_set_gray_to_rgb(png_structp png_ptr)
 /* Convert a RGB image to a grayscale of the same width.  This allows us,
  * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  */
 
 void PNGAPI
 png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
    double green)
 {
-   int red_fixed = (int)((float)red*100000.0 + 0.5);
-   int green_fixed = (int)((float)green*100000.0 + 0.5);
+   int red_fixed, green_fixed;
    if (png_ptr == NULL)
       return;
+   if (red > 21474.83647 || red < -21474.83648 ||
+       green > 21474.83647 || green < -21474.83648)
+   {
+      png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
+      red_fixed = -1;
+      green_fixed = -1;
+   }
+   else
+   {
+      red_fixed = (int)((float)red*100000.0 + 0.5);
+      green_fixed = (int)((float)green*100000.0 + 0.5);
+   }
    png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
 }
 #endif
 
 void PNGAPI
 png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
    png_fixed_point red, png_fixed_point green)
 {
@@ -698,37 +709,48 @@ png_set_rgb_to_gray_fixed(png_structp pn
 #else
    {
       png_warning(png_ptr,
         "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED");
       png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
    }
 #endif
    {
-      png_uint_16 red_int, green_int;
-      if (red < 0 || green < 0)
+      if (red >= 0 && green >= 0 && red + green <= 100000L)
       {
-         red_int   =  6968; /* .212671 * 32768 + .5 */
-         green_int = 23434; /* .715160 * 32768 + .5 */
-      }
-      else if (red + green < 100000L)
-      {
+         png_uint_16 red_int, green_int;
+
          red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
          green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
+
+         png_ptr->rgb_to_gray_red_coeff   = red_int;
+         png_ptr->rgb_to_gray_green_coeff = green_int;
+         png_ptr->rgb_to_gray_blue_coeff  =
+          (png_uint_16)(32768 - red_int - green_int);
       }
+
       else
       {
-         png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
-         red_int   =  6968;
-         green_int = 23434;
+         if (red >= 0 && green >= 0)
+            png_warning(png_ptr,
+               "ignoring out of range rgb_to_gray coefficients");
+
+         /* Use the defaults, from the cHRM chunk if set, else the built in Rec
+          * 709 values (which correspond to sRGB, so we don't have to worry
+          * about the sRGB chunk!)
+          */
+         if (png_ptr->rgb_to_gray_red_coeff == 0 &&
+            png_ptr->rgb_to_gray_green_coeff == 0 &&
+            png_ptr->rgb_to_gray_blue_coeff == 0)
+         {
+            png_ptr->rgb_to_gray_red_coeff   = 6968;  /* .212671 * 32768 + .5 */
+            png_ptr->rgb_to_gray_green_coeff = 23434; /* .715160 * 32768 + .5 */
+            png_ptr->rgb_to_gray_blue_coeff  = 2366;
+         }
       }
-      png_ptr->rgb_to_gray_red_coeff   = red_int;
-      png_ptr->rgb_to_gray_green_coeff = green_int;
-      png_ptr->rgb_to_gray_blue_coeff  =
-         (png_uint_16)(32768 - red_int - green_int);
    }
 }
 #endif
 
 #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
     defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
 void PNGAPI
 png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
@@ -1176,18 +1198,17 @@ png_read_transform_info(png_structp png_
 {
    png_debug(1, "in png_read_transform_info");
 
 #ifdef PNG_READ_EXPAND_SUPPORTED
    if (png_ptr->transformations & PNG_EXPAND)
    {
       if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
       {
-         if (png_ptr->num_trans &&
-              (png_ptr->transformations & PNG_EXPAND_tRNS))
+         if (png_ptr->num_trans)
             info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
          else
             info_ptr->color_type = PNG_COLOR_TYPE_RGB;
          info_ptr->bit_depth = 8;
          info_ptr->num_trans = 0;
       }
       else
       {
@@ -1773,42 +1794,28 @@ png_do_chop(png_row_infop row_info, png_
       png_bytep sp = row;
       png_bytep dp = row;
       png_uint_32 i;
       png_uint_32 istop = row_info->width * row_info->channels;
 
       for (i = 0; i<istop; i++, sp += 2, dp++)
       {
 #ifdef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
-      /* This does a more accurate scaling of the 16-bit color
-       * value, rather than a simple low-byte truncation.
-       *
-       * What the ideal calculation should be:
-       *   *dp = (((((png_uint_32)(*sp) << 8) |
-       *          (png_uint_32)(*(sp + 1))) * 255 + 127)
-       *          / (png_uint_32)65535L;
-       *
-       * GRR: no, I think this is what it really should be:
-       *   *dp = (((((png_uint_32)(*sp) << 8) |
-       *           (png_uint_32)(*(sp + 1))) + 128L)
-       *           / (png_uint_32)257L;
-       *
-       * GRR: here's the exact calculation with shifts:
-       *   temp = (((png_uint_32)(*sp) << 8) |
-       *           (png_uint_32)(*(sp + 1))) + 128L;
-       *   *dp = (temp - (temp >> 8)) >> 8;
-       *
-       * Approximate calculation with shift/add instead of multiply/divide:
-       *   *dp = ((((png_uint_32)(*sp) << 8) |
-       *          (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
-       *
-       * What we actually do to avoid extra shifting and conversion:
-       */
-
-         *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
+         /* This does a more accurate scaling of the 16-bit color
+          * value, rather than a simple low-byte truncation.
+          *
+          * Prior to libpng-1.4.8 and 1.5.4, the calculation here was
+          * incorrect, so if you used ACCURATE_SCALE you will now see
+          * a slightly different result.  In libpng-1.5.4 and
+          * later you will need to use the new png_set_scale_16_to_8()
+          * API to obtain accurate 16-to-8 scaling.
+          */
+         png_int_32 tmp = *sp; /* must be signed! */
+         tmp += (((int)sp[1] - tmp + 128) * 65535) >> 24;
+         *dp = (png_byte)tmp;
 #else
        /* Simply discard the low order byte */
          *dp = *sp;
 #endif
       }
       row_info->bit_depth = 8;
       row_info->pixel_depth = (png_byte)(8 * row_info->channels);
       row_info->rowbytes = row_info->width * row_info->channels;
--- a/modules/libimg/png/pngrutil.c
+++ b/modules/libimg/png/pngrutil.c
@@ -1,12 +1,12 @@
 
 /* pngrutil.c - utilities to read a PNG file
  *
- * Last changed in libpng 1.4.6 [March 8, 2011]
+ * Last changed in libpng 1.4.8 [July 7, 2011]
  * Copyright (c) 1998-2011 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
  * This code is released under the libpng license.
  * For conditions of distribution and use, see the disclaimer
  * and license in png.h
  *
@@ -1861,16 +1861,24 @@ png_handle_sCAL(png_structp png_ptr, png
    }
    else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
    {
       png_warning(png_ptr, "Duplicate sCAL chunk");
       png_crc_finish(png_ptr, length);
       return;
    }
 
+   /* Need unit type, width, \0, height: minimum 4 bytes */
+   else if (length < 4)
+   {
+      png_warning(png_ptr, "sCAL chunk too short");
+      png_crc_finish(png_ptr, length);
+      return;
+   }
+
    png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)",
       (unsigned long)(length + 1));
    png_ptr->chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
    if (png_ptr->chunkdata == NULL)
    {
       png_warning(png_ptr, "Out of memory while processing sCAL chunk");
       png_crc_finish(png_ptr, length);
       return;
@@ -2455,17 +2463,17 @@ png_handle_fcTL(png_structp png_ptr, png
     png_uint_16 delay_num;
     png_uint_16 delay_den;
     png_byte dispose_op;
     png_byte blend_op;
 
     png_debug(1, "in png_handle_fcTL");
 
     png_ensure_sequence_number(png_ptr, length);
-   
+
     if (!(png_ptr->mode & PNG_HAVE_IHDR))
     {
         png_error(png_ptr, "Missing IHDR before fcTL");
     }
     else if (png_ptr->mode & PNG_HAVE_IDAT)
     {
         /* for any frames other then the first this message may be misleading,
         * but correct. PNG_HAVE_IDAT is unset before the frame head is read
@@ -2478,55 +2486,57 @@ png_handle_fcTL(png_structp png_ptr, png
     {
         png_warning(png_ptr, "Duplicate fcTL within one frame skipped");
         png_crc_finish(png_ptr, length-4);
         return;
     }
     else if (length != 26)
     {
         png_warning(png_ptr, "fcTL with invalid length skipped");
-        png_crc_finish(png_ptr, length);
+        png_crc_finish(png_ptr, length-4);
         return;
     }
 
     png_crc_read(png_ptr, data, 22);
     png_crc_finish(png_ptr, 0);
 
     width = png_get_uint_31(png_ptr, data);
     height = png_get_uint_31(png_ptr, data + 4);
     x_offset = png_get_uint_31(png_ptr, data + 8);
     y_offset = png_get_uint_31(png_ptr, data + 12);
     delay_num = png_get_uint_16(data + 16);
     delay_den = png_get_uint_16(data + 18);
     dispose_op = data[20];
     blend_op = data[21];
 
     if (png_ptr->num_frames_read == 0 && (x_offset != 0 || y_offset != 0))
-        png_error(png_ptr, "fcTL for the first frame must have zero offset");
-    if (png_ptr->num_frames_read == 0 &&
-        (width != info_ptr->width || height != info_ptr->height))
-        png_error(png_ptr, "size in first frame's fcTL must match "
-                           "the size in IHDR");
+    {
+        png_warning(png_ptr, "fcTL for the first frame must have zero offset");
+        return;
+    }
 
     if (info_ptr != NULL)
     {
         if (png_ptr->num_frames_read == 0 &&
             (width != info_ptr->width || height != info_ptr->height))
-            png_error(png_ptr, "size in first frame's fcTL must match "
+        {
+            png_warning(png_ptr, "size in first frame's fcTL must match "
                                "the size in IHDR");
-        
-        /* the set function will do more error checking */
+            return;
+        }
+
+        /* The set function will do more error checking */
         png_set_next_frame_fcTL(png_ptr, info_ptr, width, height,
                                 x_offset, y_offset, delay_num, delay_den,
                                 dispose_op, blend_op);
-        
+
         png_read_reinit(png_ptr, info_ptr);
+
+        png_ptr->mode |= PNG_HAVE_fcTL;
     }
-
-    png_ptr->mode |= PNG_HAVE_fcTL;
 }
 
 void /* PRIVATE */
 png_have_info(png_structp png_ptr, png_infop info_ptr)
 {
     if((info_ptr->valid & PNG_INFO_acTL) && !(info_ptr->valid & PNG_INFO_fcTL))
     {
         png_ptr->apng_flags |= PNG_FIRST_FRAME_HIDDEN;
--- a/modules/libimg/png/pngtrans.c
+++ b/modules/libimg/png/pngtrans.c
@@ -1,12 +1,12 @@
 
 /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  *
- * Last changed in libpng 1.4.6 [April 10, 2011]
+ * Last changed in libpng 1.4.6 [ April 8, 2010]
  * Copyright (c) 1998-2011 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
  * This code is released under the libpng license.
  * For conditions of distribution and use, see the disclaimer
  * and license in png.h
  */
--- a/modules/libimg/png/pngwrite.c
+++ b/modules/libimg/png/pngwrite.c
@@ -1,12 +1,12 @@
 
 /* pngwrite.c - general routines to write a PNG file
  *
- * Last changed in libpng 1.4.6 [March 8, 2011]
+ * Last changed in libpng 1.4.8 [July 7, 2011]
  * Copyright (c) 1998-2011 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
  * This code is released under the libpng license.
  * For conditions of distribution and use, see the disclaimer
  * and license in png.h
  */
@@ -294,16 +294,17 @@ png_write_info(png_structp png_ptr, png_
       for (up = info_ptr->unknown_chunks;
            up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
            up++)
       {
          int keep = png_handle_as_unknown(png_ptr, up->name);
          if (keep != PNG_HANDLE_CHUNK_NEVER &&
             up->location && (up->location & PNG_HAVE_PLTE) &&
             !(up->location & PNG_HAVE_IDAT) &&
+            !(up->location & PNG_AFTER_IDAT) &&
             ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
             (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
          {
             png_write_chunk(png_ptr, up->name, up->data, up->size);
          }
       }
    }
 #endif
@@ -1414,17 +1415,17 @@ png_write_png(png_structp png_ptr, png_i
 
 #ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
    /* Swap location of alpha bytes from ARGB to RGBA */
    if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
       png_set_swap_alpha(png_ptr);
 #endif
 
 #ifdef PNG_WRITE_FILLER_SUPPORTED
-   /* Pack XRGB/RGBX/ARGB/RGBA into * RGB (4 channels -> 3 channels) */
+   /* Pack XRGB/RGBX/ARGB/RGBA into RGB (4 channels -> 3 channels) */
    if (transforms & PNG_TRANSFORM_STRIP_FILLER_AFTER)
       png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
    else if (transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE)
       png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
 #endif
 
 #ifdef PNG_WRITE_BGR_SUPPORTED
    /* Flip BGR pixels to RGB */
--- a/modules/libimg/png/pngwutil.c
+++ b/modules/libimg/png/pngwutil.c
@@ -1,13 +1,13 @@
 
 /* pngwutil.c - utilities to write a PNG file
  *
- * Last changed in libpng 1.4.1 [February 25, 2010]
- * Copyright (c) 1998-2010 Glenn Randers-Pehrson
+ * Last changed in libpng 1.4.8 [July 7, 2011]
+ * Copyright (c) 1998-2011 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
  * This code is released under the libpng license.
  * For conditions of distribution and use, see the disclaimer
  * and license in png.h
  */
 
@@ -690,17 +690,17 @@ png_write_IDAT(png_structp png_ptr, png_
          if (length >= 2 &&
              png_ptr->height < 16384 && png_ptr->width < 16384)
          {
             unsigned int z_cinfo;
             unsigned int half_z_window_size;
 
             /* Compute the maximum possible length of the datastream */
 
-            /* Number of pixels, plus for each row a filter byte and possible
+            /* Number of pixels, plus for each row a filter byte
              * and possibly a padding byte, so increase the maximum
              * size to account for these.
              */
             png_uint_32 uncompressed_idat_size = png_ptr->height *
                ((png_ptr->width *
                png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
 
             /* If it's interlaced, each block of 8 rows is sent as up to
--- a/netwerk/test/httpserver/httpd.js
+++ b/netwerk/test/httpserver/httpd.js
@@ -1838,48 +1838,68 @@ const CR = 0x0D, LF = 0x0A;
  * Calculates the number of characters before the first CRLF pair in array, or
  * -1 if the array contains no CRLF pair.
  *
  * @param array : Array
  *   an array of numbers in the range [0, 256), each representing a single
  *   character; the first CRLF is the lowest index i where
  *   |array[i] == "\r".charCodeAt(0)| and |array[i+1] == "\n".charCodeAt(0)|,
  *   if such an |i| exists, and -1 otherwise
+ * @param start : uint
+ *   start index from which to begin searching in array
  * @returns int
  *   the index of the first CRLF if any were present, -1 otherwise
  */
-function findCRLF(array)
+function findCRLF(array, start)
 {
-  for (var i = array.indexOf(CR); i >= 0; i = array.indexOf(CR, i + 1))
+  for (var i = array.indexOf(CR, start); i >= 0; i = array.indexOf(CR, i + 1))
   {
     if (array[i + 1] == LF)
       return i;
   }
   return -1;
 }
 
 
 /**
  * A container which provides line-by-line access to the arrays of bytes with
  * which it is seeded.
  */
 function LineData()
 {
   /** An array of queued bytes from which to get line-based characters. */
   this._data = [];
+
+  /** Start index from which to search for CRLF. */
+  this._start = 0;
 }
 LineData.prototype =
 {
   /**
    * Appends the bytes in the given array to the internal data cache maintained
    * by this.
    */
   appendBytes: function(bytes)
   {
-    Array.prototype.push.apply(this._data, bytes);
+    var count = bytes.length;
+    var quantum = 262144; // just above half SpiderMonkey's argument-count limit
+    if (count < quantum)
+    {
+      Array.prototype.push.apply(this._data, bytes);
+      return;
+    }
+
+    // Large numbers of bytes may cause Array.prototype.push to be called with
+    // more arguments than the JavaScript engine supports.  In that case append
+    // bytes in fixed-size amounts until all bytes are appended.
+    for (var start = 0; start < count; start += quantum)
+    {
+      var slice = bytes.slice(start, Math.min(start + quantum, count));
+      Array.prototype.push.apply(this._data, slice);
+    }
   },
 
   /**
    * Removes and returns a line of data, delimited by CRLF, from this.
    *
    * @param out
    *   an object whose "value" property will be set to the first line of text
    *   present in this, sans CRLF, if this contains a full CRLF-delimited line
@@ -1887,33 +1907,41 @@ LineData.prototype =
    *   is undefined
    * @returns boolean
    *   true if a full line of data could be read from the data in this, false
    *   otherwise
    */
   readLine: function(out)
   {
     var data = this._data;
-    var length = findCRLF(data);
+    var length = findCRLF(data, this._start);
     if (length < 0)
+    {
+      this._start = data.length;
       return false;
+    }
+
+    // Reset for future lines.
+    this._start = 0;
 
     //
     // We have the index of the CR, so remove all the characters, including
-    // CRLF, from the array with splice, and convert the removed array into the
-    // corresponding string, from which we then strip the trailing CRLF.
+    // CRLF, from the array with splice, and convert the removed array
+    // (excluding the trailing CRLF characters) into the corresponding string.
     //
-    // Getting the line in this matter acknowledges that substring is an O(1)
-    // operation in SpiderMonkey because strings are immutable, whereas two
-    // splices, both from the beginning of the data, are less likely to be as
-    // cheap as a single splice plus two extra character conversions.
-    //
-    var line = String.fromCharCode.apply(null, data.splice(0, length + 2));
-    out.value = line.substring(0, length);
-
+    var leading = data.splice(0, length + 2);
+    var quantum = 262144;
+    var line = "";
+    for (var start = 0; start < length; start += quantum)
+    {
+      var slice = leading.slice(start, Math.min(start + quantum, length));
+      line += String.fromCharCode.apply(null, slice);
+    }
+
+    out.value = line;
     return true;
   },
 
   /**
    * Removes the bytes currently within this and returns them in an array.
    *
    * @returns Array
    *   the bytes within this when this method is called
--- a/netwerk/test/httpserver/test/head_utils.js
+++ b/netwerk/test/httpserver/test/head_utils.js
@@ -330,17 +330,16 @@ function runHttpTests(testArray, done)
     {
       /** Current channel being observed by this. */
       _channel: null,
       /** Array of bytes of data in body of response. */
       _data: [],
 
       onStartRequest: function(request, cx)
       {
-        dumpn("*** TEST ONSTARTREQUEST: " + testArray[testIndex].path);
         do_check_true(request === this._channel);
         var ch = request.QueryInterface(Ci.nsIHttpChannel)
                         .QueryInterface(Ci.nsIHttpChannelInternal);
 
         this._data.length = 0;
         try
         {
           try
@@ -355,28 +354,26 @@ function runHttpTests(testArray, done)
         catch (e)
         {
           do_note_exception(e, "!!! swallowing onStartRequest exception so onStopRequest is " +
                 "called...");
         }
       },
       onDataAvailable: function(request, cx, inputStream, offset, count)
       {
-        dumpn("*** DATA AVAILABLE FOR TEST " + testArray[testIndex].path);
-        dumpn("*** COUNT:    " + count);
-        dumpn("*** OFFSET:   " + offset);
-        dumpn("*** ALREADY:  " + this._data.length);
-        var newData = makeBIS(inputStream).readByteArray(count);
-        dumpn("*** READ NOW: " + newData.length);
-        Array.prototype.push.apply(this._data, newData);
-        dumpn("*** UPDATED:  " + this._data.length);
+        var quantum = 262144; // just above half the argument-count limit
+        var bis = makeBIS(inputStream);
+        for (var start = 0; start < count; start += quantum)
+        {
+          var newData = bis.readByteArray(Math.min(quantum, count - start));
+          Array.prototype.push.apply(this._data, newData);
+        }
       },
       onStopRequest: function(request, cx, status)
       {
-        dumpn("*** TEST FINISHED: " + this._data.length + " for " + testArray[testIndex].path);
         this._channel = null;
 
         var ch = request.QueryInterface(Ci.nsIHttpChannel)
                         .QueryInterface(Ci.nsIHttpChannelInternal);
 
         // NB: The onStopRequest callback must run before performNextTest here,
         //     because the latter runs the next test's initChannel callback, and
         //     we want one test to be sequentially processed before the next
@@ -436,17 +433,17 @@ function runHttpTests(testArray, done)
 function RawTest(host, port, data, responseCheck)
 {
   if (0 > port || 65535 < port || port % 1 !== 0)
     throw "bad port";
   if (!(data instanceof Array))
     data = [data];
   if (data.length <= 0)
     throw "bad data length";
-  if (!data.every(function(v) { return /^[\x00-\xff]*$/.test(data); }))
+  if (!data.every(function(v) { return /^[\x00-\xff]*$/.test(v); }))
     throw "bad data contained non-byte-valued character";
 
   this.host = host;
   this.port = port;
   this.data = data;
   this.responseCheck = responseCheck;
 }
 
@@ -550,17 +547,22 @@ function runRawTests(testArray, done)
           catch (e)
           {
             /* default to 0 */
             do_note_exception(e);
           }
 
           if (av > 0)
           {
-            received += String.fromCharCode.apply(null, bis.readByteArray(av));
+            var quantum = 262144;
+            for (var start = 0; start < av; start += quantum)
+            {
+              var bytes = bis.readByteArray(Math.min(quantum, av - start));
+              received += String.fromCharCode.apply(null, bytes);
+            }
             waitForMoreInput(stream);
             return;
           }
         }
         catch(e)
         {
           do_report_unexpected_exception(e);
         }
--- a/netwerk/test/httpserver/test/test_request_line_split_in_two_packets.js
+++ b/netwerk/test/httpserver/test/test_request_line_split_in_two_packets.js
@@ -70,25 +70,32 @@ var tests = [];
 
 function veryLongRequestLine(request, response)
 {
   writeDetails(request, response);
   response.setStatusLine(request.httpVersion, 200, "TEST PASSED");
 }
 
 var path = "/very-long-request-line?";
-var gibberish = "dfsasdbfjkbnsldkjnewiunfasjkn";
-for (var i = 0; i < 10; i++)
-  gibberish += gibberish;
-str = "GET /very-long-request-line?" + gibberish + " HTTP/1.1\r\n" +
+var reallyLong = "0123456789ABCDEF0123456789ABCDEF"; // 32
+reallyLong = reallyLong + reallyLong + reallyLong + reallyLong; // 128
+reallyLong = reallyLong + reallyLong + reallyLong + reallyLong; // 512
+reallyLong = reallyLong + reallyLong + reallyLong + reallyLong; // 2048
+reallyLong = reallyLong + reallyLong + reallyLong + reallyLong; // 8192
+reallyLong = reallyLong + reallyLong + reallyLong + reallyLong; // 32768
+reallyLong = reallyLong + reallyLong + reallyLong + reallyLong; // 131072
+reallyLong = reallyLong + reallyLong + reallyLong + reallyLong; // 524288
+if (reallyLong.length !== 524288)
+  throw new TypeError("generated length not as long as expected");
+str = "GET /very-long-request-line?" + reallyLong + " HTTP/1.1\r\n" +
       "Host: localhost:4444\r\n" +
       "\r\n";
 data = [];
-for (var i = 0; i < str.length; i += 50)
-  data.push(str.substr(i, 50));
+for (var i = 0; i < str.length; i += 16384)
+  data.push(str.substr(i, 16384));
 
 function checkVeryLongRequestLine(data)
 {
   var iter = LineIterator(data);
 
   print("data length: " + data.length);
   print("iter object: " + iter);
 
@@ -97,17 +104,17 @@ function checkVeryLongRequestLine(data)
 
   skipHeaders(iter);
 
   // Okay, next line must be the data we expected to be written
   var body =
     [
      "Method:  GET",
      "Path:    /very-long-request-line",
-     "Query:   " + gibberish,
+     "Query:   " + reallyLong,
      "Version: 1.1",
      "Scheme:  http",
      "Host:    localhost",
      "Port:    4444",
     ];
 
   expectLines(iter, body);
 }
--- a/parser/html/javasrc/AttributeName.java
+++ b/parser/html/javasrc/AttributeName.java
@@ -1089,16 +1089,17 @@ public final class AttributeName
     public static final AttributeName ARIA_SECRET = new AttributeName(ALL_NO_NS, SAME_LOCAL("aria-secret"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName ARIA_ATOMIC = new AttributeName(ALL_NO_NS, SAME_LOCAL("aria-atomic"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName ARIA_HIDDEN = new AttributeName(ALL_NO_NS, SAME_LOCAL("aria-hidden"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName ARIA_FLOWTO = new AttributeName(ALL_NO_NS, SAME_LOCAL("aria-flowto"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName ARABIC_FORM = new AttributeName(ALL_NO_NS, SAME_LOCAL("arabic-form"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName CELLPADDING = new AttributeName(ALL_NO_NS, SAME_LOCAL("cellpadding"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName CELLSPACING = new AttributeName(ALL_NO_NS, SAME_LOCAL("cellspacing"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName COLUMNWIDTH = new AttributeName(ALL_NO_NS, SAME_LOCAL("columnwidth"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
+    public static final AttributeName CROSSORIGIN = new AttributeName(ALL_NO_NS, SAME_LOCAL("crossorigin"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName COLUMNALIGN = new AttributeName(ALL_NO_NS, SAME_LOCAL("columnalign"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName COLUMNLINES = new AttributeName(ALL_NO_NS, SAME_LOCAL("columnlines"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName CONTEXTMENU = new AttributeName(ALL_NO_NS, SAME_LOCAL("contextmenu"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName BASEPROFILE = new AttributeName(ALL_NO_NS, SVG_DIFFERENT("baseprofile", "baseProfile"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName FONT_FAMILY = new AttributeName(ALL_NO_NS, SAME_LOCAL("font-family"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName FRAMEBORDER = new AttributeName(ALL_NO_NS, SAME_LOCAL("frameborder"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName FILTERUNITS = new AttributeName(ALL_NO_NS, SVG_DIFFERENT("filterunits", "filterUnits"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
     public static final AttributeName FLOOD_COLOR = new AttributeName(ALL_NO_NS, SAME_LOCAL("flood-color"), ALL_NO_PREFIX, NCNAME_HTML | NCNAME_FOREIGN | NCNAME_LANG);
@@ -1671,16 +1672,17 @@ public final class AttributeName
     ARIA_SECRET,
     ARIA_ATOMIC,
     ARIA_HIDDEN,
     ARIA_FLOWTO,
     ARABIC_FORM,
     CELLPADDING,
     CELLSPACING,
     COLUMNWIDTH,
+    CROSSORIGIN,
     COLUMNALIGN,
     COLUMNLINES,
     CONTEXTMENU,
     BASEPROFILE,
     FONT_FAMILY,
     FRAMEBORDER,
     FILTERUNITS,
     FLOOD_COLOR,
@@ -2254,16 +2256,17 @@ public final class AttributeName
     370353345,
     370710317,
     371074566,
     371122285,
     371194213,
     371448425,
     371448430,
     371545055,
+    371593469,
     371596922,
     371758751,
     371964792,
     372151328,
     376550136,
     376710172,
     376795771,
     376826271,
--- a/parser/html/nsHtml5AtomList.h
+++ b/parser/html/nsHtml5AtomList.h
@@ -453,16 +453,17 @@ HTML5_ATOM(accentunder, "accentunder")
 HTML5_ATOM(aria_secret, "aria-secret")
 HTML5_ATOM(aria_atomic, "aria-atomic")
 HTML5_ATOM(aria_hidden, "aria-hidden")
 HTML5_ATOM(aria_flowto, "aria-flowto")
 HTML5_ATOM(arabic_form, "arabic-form")
 HTML5_ATOM(cellpadding, "cellpadding")
 HTML5_ATOM(cellspacing, "cellspacing")
 HTML5_ATOM(columnwidth, "columnwidth")
+HTML5_ATOM(crossorigin, "crossorigin")
 HTML5_ATOM(columnalign, "columnalign")
 HTML5_ATOM(columnlines, "columnlines")
 HTML5_ATOM(contextmenu, "contextmenu")
 HTML5_ATOM(baseprofile, "baseprofile")
 HTML5_ATOM(baseProfile, "baseProfile")
 HTML5_ATOM(font_family, "font-family")
 HTML5_ATOM(frameborder, "frameborder")
 HTML5_ATOM(filterunits, "filterunits")
--- a/parser/html/nsHtml5AttributeName.cpp
+++ b/parser/html/nsHtml5AttributeName.cpp
@@ -571,16 +571,17 @@ nsHtml5AttributeName* nsHtml5AttributeNa
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_ARIA_SECRET = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_ARIA_ATOMIC = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_ARIA_HIDDEN = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_ARIA_FLOWTO = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_ARABIC_FORM = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_CELLPADDING = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_CELLSPACING = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_COLUMNWIDTH = nsnull;
+nsHtml5AttributeName* nsHtml5AttributeName::ATTR_CROSSORIGIN = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_COLUMNALIGN = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_COLUMNLINES = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_CONTEXTMENU = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_BASEPROFILE = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_FONT_FAMILY = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_FRAMEBORDER = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_FILTERUNITS = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_FLOOD_COLOR = nsnull;
@@ -776,17 +777,17 @@ nsHtml5AttributeName* nsHtml5AttributeNa
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_VERYVERYTHICKMATHSPACE = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_STRIKETHROUGH_POSITION = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_STRIKETHROUGH_THICKNESS = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_EXTERNALRESOURCESREQUIRED = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_GLYPH_ORIENTATION_VERTICAL = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_COLOR_INTERPOLATION_FILTERS = nsnull;
 nsHtml5AttributeName* nsHtml5AttributeName::ATTR_GLYPH_ORIENTATION_HORIZONTAL = nsnull;
 nsHtml5AttributeName** nsHtml5AttributeName::ATTRIBUTE_NAMES = 0;
-static PRInt32 const ATTRIBUTE_HASHES_DATA[] = { 1153, 1383, 1601, 1793, 1827, 1857, 68600, 69146, 69177, 70237, 70270, 71572, 71669, 72415, 72444, 74846, 74904, 74943, 75001, 75276, 75590, 84742, 84839, 85575, 85963, 85992, 87204, 88074, 88171, 89130, 89163, 3207892, 3283895, 3284791, 3338752, 3358197, 3369562, 3539124, 3562402, 3574260, 3670335, 3696933, 3721879, 135280021, 135346322, 136317019, 136475749, 136548517, 136652214, 136884919, 136902418, 136942992, 137292068, 139120259, 139785574, 142250603, 142314056, 142331176, 142519584, 144752417, 145106895, 146147200, 146765926, 148805544, 149655723, 149809441, 150018784, 150445028, 150923321, 152528754, 152536216, 152647366, 152962785, 155219321, 155654904, 157317483, 157350248, 157437941, 157447478, 157604838, 157685404, 157894402, 158315188, 166078431, 169409980, 169700259, 169856932, 170007032, 170409695, 170466488, 170513710, 170608367, 173028944, 173896963, 176090625, 176129212, 179390001, 179489057, 179627464, 179840468, 179849042, 180004216, 181779081, 183027151, 183645319, 183698797, 185922012, 185997252, 188312483, 188675799, 190977533, 190992569, 191006194, 191033518, 191038774, 191096249, 191166163, 191194426, 191522106, 191568039, 200104642, 202506661, 202537381, 202602917, 203070590, 203120766, 203389054, 203690071, 203971238, 203986524, 209040857, 209125756, 212055489, 212322418, 212746849, 213002877, 213055164, 213088023, 213259873, 213273386, 213435118, 213437318, 213438231, 213493071, 213532268, 213542834, 213584431, 213659891, 215285828, 215880731, 216112976, 216684637, 217369699, 217565298, 217576549, 218186795, 219743185, 220082234, 221623802, 221986406, 222283890, 223089542, 223138630, 223311265, 224547358, 224587256, 224589550, 224655650, 224785518, 224810917, 224813302, 225429618, 225432950, 225440869, 236107233, 236709921, 236838947, 237117095, 237143271, 237172455, 237209953, 237354143, 237372743, 237668065, 237703073, 237714273, 239743521, 240512803, 240522627, 240560417, 240656513, 241015715, 241062755, 241065383, 243523041, 245865199, 246261793, 246556195, 246774817, 246923491, 246928419, 246981667, 247014847, 247058369, 247112833, 247118177, 247119137, 247128739, 247316903, 249533729, 250235623, 250269543, 251083937, 251402351, 252339047, 253260911, 253293679, 254844367, 255547879, 256077281, 256345377, 258124199, 258354465, 258605063, 258744193, 258845603, 258856961, 258926689, 269869248, 270174334, 270709417, 270778994, 270781796, 271102503, 271478858, 271490090, 272870654, 273335275, 273369140, 273924313, 274108530, 274116736, 276818662, 277476156, 279156579, 279349675, 280108533, 280128712, 280132869, 280162403, 280280292, 280413430, 280506130, 280677397, 280678580, 280686710, 280689066, 282736758, 283110901, 283275116, 283823226, 283890012, 284479340, 284606461, 286700477, 286798916, 291557706, 291665349, 291804100, 292138018, 292166446, 292418738, 292451039, 300298041, 300374839, 300597935, 303073389, 303083839, 303266673, 303354997, 303430688, 303576261, 303724281, 303819694, 304242723, 304382625, 306247792, 307227811, 307468786, 307724489, 309671175, 310252031, 310358241, 310373094, 311015256, 313357609, 313683893, 313701861, 313706996, 313707317, 313710350, 314027746, 314038181, 314091299, 314205627, 314233813, 316741830, 316797986, 317486755, 317794164, 318721061, 320076137, 322657125, 322887778, 323506876, 323572412, 323605180, 323938869, 325060058, 325320188, 325398738, 325541490, 325671619, 333868843, 336806130, 337212108, 337282686, 337285434, 337585223, 338036037, 338298087, 338566051, 340943551, 341190970, 342995704, 343352124, 343912673, 344585053, 346977248, 347218098, 347262163, 347278576, 347438191, 347655959, 347684788, 347726430, 347727772, 347776035, 347776629, 349500753, 350880161, 350887073, 353384123, 355496998, 355906922, 355979793, 356545959, 358637867, 358905016, 359164318, 359247286, 359350571, 359579447, 365560330, 367399355, 367420285, 367510727, 368013212, 370234760, 370353345, 370710317, 371074566, 371122285, 371194213, 371448425, 371448430, 371545055, 371596922, 371758751, 371964792, 372151328, 376550136, 376710172, 376795771, 376826271, 376906556, 380514830, 380774774, 380775037, 381030322, 381136500, 381281631, 381282269, 381285504, 381330595, 381331422, 381335911, 381336484, 383907298, 383917408, 384595009, 384595013, 387799894, 387823201, 392581647, 392584937, 392742684, 392906485, 393003349, 400644707, 400973830, 404428547, 404432113, 404432865, 404469244, 404478897, 404694860, 406887479, 408294949, 408789955, 410022510, 410467324, 410586448, 410945965, 411845275, 414327152, 414327932, 414329781, 414346257, 414346439, 414639928, 414835998, 414894517, 414986533, 417465377, 417465381, 417492216, 418259232, 419310946, 420103495, 420242342, 420380455, 420658662, 420717432, 423183880, 424539259, 425929170, 425972964, 426050649, 426126450, 426142833, 426607922, 437289840, 437347469, 437412335, 437423943, 437455540, 437462252, 437597991, 437617485, 437986305, 437986507, 437986828, 437987072, 438015591, 438034813, 438038966, 438179623, 438347971, 438483573, 438547062, 438895551, 441592676, 442032555, 443548979, 447881379, 447881655, 447881895, 447887844, 448416189, 448445746, 448449012, 450942191, 452816744, 453668677, 454434495, 456610076, 456642844, 456738709, 457544600, 459451897, 459680944, 468058810, 468083581, 470964084, 471470955, 471567278, 472267822, 481177859, 481210627, 481435874, 481455115, 481485378, 481490218, 485105638, 486005878, 486383494, 487988916, 488103783, 490661867, 491574090, 491578272, 493041952, 493441205, 493582844, 493716979, 504577572, 504740359, 505091638, 505592418, 505656212, 509516275, 514998531, 515571132, 515594682, 518712698, 521362273, 526592419, 526807354, 527348842, 538294791, 539214049, 544689535, 545535009, 548544752, 548563346, 548595116, 551679010, 558034099, 560329411, 560356209, 560671018, 560671152, 560692590, 560845442, 569212097, 569474241, 572252718, 572768481, 575326764, 576174758, 576190819, 582099184, 582099438, 582372519, 582558889, 586552164, 591325418, 594231990, 594243961, 605711268, 615672071, 616086845, 621792370, 624879850, 627432831, 640040548, 654392808, 658675477, 659420283, 672891587, 694768102, 705890982, 725543146, 759097578, 761686526, 795383908, 843809551, 878105336, 908643300, 945213471 };
+static PRInt32 const ATTRIBUTE_HASHES_DATA[] = { 1153, 1383, 1601, 1793, 1827, 1857, 68600, 69146, 69177, 70237, 70270, 71572, 71669, 72415, 72444, 74846, 74904, 74943, 75001, 75276, 75590, 84742, 84839, 85575, 85963, 85992, 87204, 88074, 88171, 89130, 89163, 3207892, 3283895, 3284791, 3338752, 3358197, 3369562, 3539124, 3562402, 3574260, 3670335, 3696933, 3721879, 135280021, 135346322, 136317019, 136475749, 136548517, 136652214, 136884919, 136902418, 136942992, 137292068, 139120259, 139785574, 142250603, 142314056, 142331176, 142519584, 144752417, 145106895, 146147200, 146765926, 148805544, 149655723, 149809441, 150018784, 150445028, 150923321, 152528754, 152536216, 152647366, 152962785, 155219321, 155654904, 157317483, 157350248, 157437941, 157447478, 157604838, 157685404, 157894402, 158315188, 166078431, 169409980, 169700259, 169856932, 170007032, 170409695, 170466488, 170513710, 170608367, 173028944, 173896963, 176090625, 176129212, 179390001, 179489057, 179627464, 179840468, 179849042, 180004216, 181779081, 183027151, 183645319, 183698797, 185922012, 185997252, 188312483, 188675799, 190977533, 190992569, 191006194, 191033518, 191038774, 191096249, 191166163, 191194426, 191522106, 191568039, 200104642, 202506661, 202537381, 202602917, 203070590, 203120766, 203389054, 203690071, 203971238, 203986524, 209040857, 209125756, 212055489, 212322418, 212746849, 213002877, 213055164, 213088023, 213259873, 213273386, 213435118, 213437318, 213438231, 213493071, 213532268, 213542834, 213584431, 213659891, 215285828, 215880731, 216112976, 216684637, 217369699, 217565298, 217576549, 218186795, 219743185, 220082234, 221623802, 221986406, 222283890, 223089542, 223138630, 223311265, 224547358, 224587256, 224589550, 224655650, 224785518, 224810917, 224813302, 225429618, 225432950, 225440869, 236107233, 236709921, 236838947, 237117095, 237143271, 237172455, 237209953, 237354143, 237372743, 237668065, 237703073, 237714273, 239743521, 240512803, 240522627, 240560417, 240656513, 241015715, 241062755, 241065383, 243523041, 245865199, 246261793, 246556195, 246774817, 246923491, 246928419, 246981667, 247014847, 247058369, 247112833, 247118177, 247119137, 247128739, 247316903, 249533729, 250235623, 250269543, 251083937, 251402351, 252339047, 253260911, 253293679, 254844367, 255547879, 256077281, 256345377, 258124199, 258354465, 258605063, 258744193, 258845603, 258856961, 258926689, 269869248, 270174334, 270709417, 270778994, 270781796, 271102503, 271478858, 271490090, 272870654, 273335275, 273369140, 273924313, 274108530, 274116736, 276818662, 277476156, 279156579, 279349675, 280108533, 280128712, 280132869, 280162403, 280280292, 280413430, 280506130, 280677397, 280678580, 280686710, 280689066, 282736758, 283110901, 283275116, 283823226, 283890012, 284479340, 284606461, 286700477, 286798916, 291557706, 291665349, 291804100, 292138018, 292166446, 292418738, 292451039, 300298041, 300374839, 300597935, 303073389, 303083839, 303266673, 303354997, 303430688, 303576261, 303724281, 303819694, 304242723, 304382625, 306247792, 307227811, 307468786, 307724489, 309671175, 310252031, 310358241, 310373094, 311015256, 313357609, 313683893, 313701861, 313706996, 313707317, 313710350, 314027746, 314038181, 314091299, 314205627, 314233813, 316741830, 316797986, 317486755, 317794164, 318721061, 320076137, 322657125, 322887778, 323506876, 323572412, 323605180, 323938869, 325060058, 325320188, 325398738, 325541490, 325671619, 333868843, 336806130, 337212108, 337282686, 337285434, 337585223, 338036037, 338298087, 338566051, 340943551, 341190970, 342995704, 343352124, 343912673, 344585053, 346977248, 347218098, 347262163, 347278576, 347438191, 347655959, 347684788, 347726430, 347727772, 347776035, 347776629, 349500753, 350880161, 350887073, 353384123, 355496998, 355906922, 355979793, 356545959, 358637867, 358905016, 359164318, 359247286, 359350571, 359579447, 365560330, 367399355, 367420285, 367510727, 368013212, 370234760, 370353345, 370710317, 371074566, 371122285, 371194213, 371448425, 371448430, 371545055, 371593469, 371596922, 371758751, 371964792, 372151328, 376550136, 376710172, 376795771, 376826271, 376906556, 380514830, 380774774, 380775037, 381030322, 381136500, 381281631, 381282269, 381285504, 381330595, 381331422, 381335911, 381336484, 383907298, 383917408, 384595009, 384595013, 387799894, 387823201, 392581647, 392584937, 392742684, 392906485, 393003349, 400644707, 400973830, 404428547, 404432113, 404432865, 404469244, 404478897, 404694860, 406887479, 408294949, 408789955, 410022510, 410467324, 410586448, 410945965, 411845275, 414327152, 414327932, 414329781, 414346257, 414346439, 414639928, 414835998, 414894517, 414986533, 417465377, 417465381, 417492216, 418259232, 419310946, 420103495, 420242342, 420380455, 420658662, 420717432, 423183880, 424539259, 425929170, 425972964, 426050649, 426126450, 426142833, 426607922, 437289840, 437347469, 437412335, 437423943, 437455540, 437462252, 437597991, 437617485, 437986305, 437986507, 437986828, 437987072, 438015591, 438034813, 438038966, 438179623, 438347971, 438483573, 438547062, 438895551, 441592676, 442032555, 443548979, 447881379, 447881655, 447881895, 447887844, 448416189, 448445746, 448449012, 450942191, 452816744, 453668677, 454434495, 456610076, 456642844, 456738709, 457544600, 459451897, 459680944, 468058810, 468083581, 470964084, 471470955, 471567278, 472267822, 481177859, 481210627, 481435874, 481455115, 481485378, 481490218, 485105638, 486005878, 486383494, 487988916, 488103783, 490661867, 491574090, 491578272, 493041952, 493441205, 493582844, 493716979, 504577572, 504740359, 505091638, 505592418, 505656212, 509516275, 514998531, 515571132, 515594682, 518712698, 521362273, 526592419, 526807354, 527348842, 538294791, 539214049, 544689535, 545535009, 548544752, 548563346, 548595116, 551679010, 558034099, 560329411, 560356209, 560671018, 560671152, 560692590, 560845442, 569212097, 569474241, 572252718, 572768481, 575326764, 576174758, 576190819, 582099184, 582099438, 582372519, 582558889, 586552164, 591325418, 594231990, 594243961, 605711268, 615672071, 616086845, 621792370, 624879850, 627432831, 640040548, 654392808, 658675477, 659420283, 672891587, 694768102, 705890982, 725543146, 759097578, 761686526, 795383908, 843809551, 878105336, 908643300, 945213471 };
 staticJArray<PRInt32,PRInt32> nsHtml5AttributeName::ATTRIBUTE_HASHES = { ATTRIBUTE_HASHES_DATA, NS_ARRAY_LENGTH(ATTRIBUTE_HASHES_DATA) };
 void
 nsHtml5AttributeName::initializeStatics()
 {
   ALL_NO_NS = new PRInt32[3];
   ALL_NO_NS[0] = kNameSpaceID_None;
   ALL_NO_NS[1] = kNameSpaceID_None;
   ALL_NO_NS[2] = kNameSpaceID_None;
@@ -1190,16 +1191,17 @@ nsHtml5AttributeName::initializeStatics(
   ATTR_ARIA_SECRET = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::aria_secret), ALL_NO_PREFIX);
   ATTR_ARIA_ATOMIC = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::aria_atomic), ALL_NO_PREFIX);
   ATTR_ARIA_HIDDEN = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::aria_hidden), ALL_NO_PREFIX);
   ATTR_ARIA_FLOWTO = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::aria_flowto), ALL_NO_PREFIX);
   ATTR_ARABIC_FORM = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::arabic_form), ALL_NO_PREFIX);
   ATTR_CELLPADDING = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::cellpadding), ALL_NO_PREFIX);
   ATTR_CELLSPACING = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::cellspacing), ALL_NO_PREFIX);
   ATTR_COLUMNWIDTH = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::columnwidth), ALL_NO_PREFIX);
+  ATTR_CROSSORIGIN = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::crossorigin), ALL_NO_PREFIX);
   ATTR_COLUMNALIGN = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::columnalign), ALL_NO_PREFIX);
   ATTR_COLUMNLINES = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::columnlines), ALL_NO_PREFIX);
   ATTR_CONTEXTMENU = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::contextmenu), ALL_NO_PREFIX);
   ATTR_BASEPROFILE = new nsHtml5AttributeName(ALL_NO_NS, SVG_DIFFERENT(nsHtml5Atoms::baseprofile, nsHtml5Atoms::baseProfile), ALL_NO_PREFIX);
   ATTR_FONT_FAMILY = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::font_family), ALL_NO_PREFIX);
   ATTR_FRAMEBORDER = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::frameborder), ALL_NO_PREFIX);
   ATTR_FILTERUNITS = new nsHtml5AttributeName(ALL_NO_NS, SVG_DIFFERENT(nsHtml5Atoms::filterunits, nsHtml5Atoms::filterUnits), ALL_NO_PREFIX);
   ATTR_FLOOD_COLOR = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::flood_color), ALL_NO_PREFIX);
@@ -1394,17 +1396,17 @@ nsHtml5AttributeName::initializeStatics(
   ATTR_VERYVERYTHINMATHSPACE = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::veryverythinmathspace), ALL_NO_PREFIX);
   ATTR_VERYVERYTHICKMATHSPACE = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::veryverythickmathspace), ALL_NO_PREFIX);
   ATTR_STRIKETHROUGH_POSITION = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::strikethrough_position), ALL_NO_PREFIX);
   ATTR_STRIKETHROUGH_THICKNESS = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::strikethrough_thickness), ALL_NO_PREFIX);
   ATTR_EXTERNALRESOURCESREQUIRED = new nsHtml5AttributeName(ALL_NO_NS, SVG_DIFFERENT(nsHtml5Atoms::externalresourcesrequired, nsHtml5Atoms::externalResourcesRequired), ALL_NO_PREFIX);
   ATTR_GLYPH_ORIENTATION_VERTICAL = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::glyph_orientation_vertical), ALL_NO_PREFIX);
   ATTR_COLOR_INTERPOLATION_FILTERS = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::color_interpolation_filters), ALL_NO_PREFIX);
   ATTR_GLYPH_ORIENTATION_HORIZONTAL = new nsHtml5AttributeName(ALL_NO_NS, SAME_LOCAL(nsHtml5Atoms::glyph_orientation_horizontal), ALL_NO_PREFIX);
-  ATTRIBUTE_NAMES = new nsHtml5AttributeName*[581];
+  ATTRIBUTE_NAMES = new nsHtml5AttributeName*[582];
   ATTRIBUTE_NAMES[0] = ATTR_D;
   ATTRIBUTE_NAMES[1] = ATTR_K;
   ATTRIBUTE_NAMES[2] = ATTR_R;
   ATTRIBUTE_NAMES[3] = ATTR_X;
   ATTRIBUTE_NAMES[4] = ATTR_Y;
   ATTRIBUTE_NAMES[5] = ATTR_Z;
   ATTRIBUTE_NAMES[6] = ATTR_BY;
   ATTRIBUTE_NAMES[7] = ATTR_CX;
@@ -1772,220 +1774,221 @@ nsHtml5AttributeName::initializeStatics(
   ATTRIBUTE_NAMES[369] = ATTR_ARIA_SECRET;
   ATTRIBUTE_NAMES[370] = ATTR_ARIA_ATOMIC;
   ATTRIBUTE_NAMES[371] = ATTR_ARIA_HIDDEN;
   ATTRIBUTE_NAMES[372] = ATTR_ARIA_FLOWTO;
   ATTRIBUTE_NAMES[373] = ATTR_ARABIC_FORM;
   ATTRIBUTE_NAMES[374] = ATTR_CELLPADDING;
   ATTRIBUTE_NAMES[375] = ATTR_CELLSPACING;
   ATTRIBUTE_NAMES[376] = ATTR_COLUMNWIDTH;
-  ATTRIBUTE_NAMES[377] = ATTR_COLUMNALIGN;
-  ATTRIBUTE_NAMES[378] = ATTR_COLUMNLINES;
-  ATTRIBUTE_NAMES[379] = ATTR_CONTEXTMENU;
-  ATTRIBUTE_NAMES[380] = ATTR_BASEPROFILE;
-  ATTRIBUTE_NAMES[381] = ATTR_FONT_FAMILY;
-  ATTRIBUTE_NAMES[382] = ATTR_FRAMEBORDER;
-  ATTRIBUTE_NAMES[383] = ATTR_FILTERUNITS;
-  ATTRIBUTE_NAMES[384] = ATTR_FLOOD_COLOR;
-  ATTRIBUTE_NAMES[385] = ATTR_FONT_WEIGHT;
-  ATTRIBUTE_NAMES[386] = ATTR_HORIZ_ADV_X;
-  ATTRIBUTE_NAMES[387] = ATTR_ONDRAGLEAVE;
-  ATTRIBUTE_NAMES[388] = ATTR_ONMOUSEMOVE;
-  ATTRIBUTE_NAMES[389] = ATTR_ORIENTATION;
-  ATTRIBUTE_NAMES[390] = ATTR_ONMOUSEDOWN;
-  ATTRIBUTE_NAMES[391] = ATTR_ONMOUSEOVER;
-  ATTRIBUTE_NAMES[392] = ATTR_ONDRAGENTER;
-  ATTRIBUTE_NAMES[393] = ATTR_IDEOGRAPHIC;
-  ATTRIBUTE_NAMES[394] = ATTR_ONBEFORECUT;
-  ATTRIBUTE_NAMES[395] = ATTR_ONFORMINPUT;
-  ATTRIBUTE_NAMES[396] = ATTR_ONDRAGSTART;
-  ATTRIBUTE_NAMES[397] = ATTR_ONMOVESTART;
-  ATTRIBUTE_NAMES[398] = ATTR_MARKERUNITS;
-  ATTRIBUTE_NAMES[399] = ATTR_MATHVARIANT;
-  ATTRIBUTE_NAMES[400] = ATTR_MARGINWIDTH;
-  ATTRIBUTE_NAMES[401] = ATTR_MARKERWIDTH;
-  ATTRIBUTE_NAMES[402] = ATTR_TEXT_ANCHOR;
-  ATTRIBUTE_NAMES[403] = ATTR_TABLEVALUES;
-  ATTRIBUTE_NAMES[404] = ATTR_SCRIPTLEVEL;
-  ATTRIBUTE_NAMES[405] = ATTR_REPEATCOUNT;
-  ATTRIBUTE_NAMES[406] = ATTR_STITCHTILES;
-  ATTRIBUTE_NAMES[407] = ATTR_STARTOFFSET;
-  ATTRIBUTE_NAMES[408] = ATTR_SCROLLDELAY;
-  ATTRIBUTE_NAMES[409] = ATTR_XMLNS_XLINK;
-  ATTRIBUTE_NAMES[410] = ATTR_XLINK_TITLE;
-  ATTRIBUTE_NAMES[411] = ATTR_ARIA_INVALID;
-  ATTRIBUTE_NAMES[412] = ATTR_ARIA_PRESSED;
-  ATTRIBUTE_NAMES[413] = ATTR_ARIA_CHECKED;
-  ATTRIBUTE_NAMES[414] = ATTR_AUTOCOMPLETE;
-  ATTRIBUTE_NAMES[415] = ATTR_ARIA_SETSIZE;
-  ATTRIBUTE_NAMES[416] = ATTR_ARIA_CHANNEL;
-  ATTRIBUTE_NAMES[417] = ATTR_EQUALCOLUMNS;
-  ATTRIBUTE_NAMES[418] = ATTR_DISPLAYSTYLE;
-  ATTRIBUTE_NAMES[419] = ATTR_DATAFORMATAS;
-  ATTRIBUTE_NAMES[420] = ATTR_FILL_OPACITY;
-  ATTRIBUTE_NAMES[421] = ATTR_FONT_VARIANT;
-  ATTRIBUTE_NAMES[422] = ATTR_FONT_STRETCH;
-  ATTRIBUTE_NAMES[423] = ATTR_FRAMESPACING;
-  ATTRIBUTE_NAMES[424] = ATTR_KERNELMATRIX;
-  ATTRIBUTE_NAMES[425] = ATTR_ONDEACTIVATE;
-  ATTRIBUTE_NAMES[426] = ATTR_ONROWSDELETE;
-  ATTRIBUTE_NAMES[427] = ATTR_ONMOUSELEAVE;
-  ATTRIBUTE_NAMES[428] = ATTR_ONFORMCHANGE;
-  ATTRIBUTE_NAMES[429] = ATTR_ONCELLCHANGE;
-  ATTRIBUTE_NAMES[430] = ATTR_ONMOUSEWHEEL;
-  ATTRIBUTE_NAMES[431] = ATTR_ONMOUSEENTER;
-  ATTRIBUTE_NAMES[432] = ATTR_ONAFTERPRINT;
-  ATTRIBUTE_NAMES[433] = ATTR_ONBEFORECOPY;
-  ATTRIBUTE_NAMES[434] = ATTR_MARGINHEIGHT;
-  ATTRIBUTE_NAMES[435] = ATTR_MARKERHEIGHT;
-  ATTRIBUTE_NAMES[436] = ATTR_MARKER_START;
-  ATTRIBUTE_NAMES[437] = ATTR_MATHEMATICAL;
-  ATTRIBUTE_NAMES[438] = ATTR_LENGTHADJUST;
-  ATTRIBUTE_NAMES[439] = ATTR_UNSELECTABLE;
-  ATTRIBUTE_NAMES[440] = ATTR_UNICODE_BIDI;
-  ATTRIBUTE_NAMES[441] = ATTR_UNITS_PER_EM;
-  ATTRIBUTE_NAMES[442] = ATTR_WORD_SPACING;
-  ATTRIBUTE_NAMES[443] = ATTR_WRITING_MODE;
-  ATTRIBUTE_NAMES[444] = ATTR_V_ALPHABETIC;
-  ATTRIBUTE_NAMES[445] = ATTR_PATTERNUNITS;
-  ATTRIBUTE_NAMES[446] = ATTR_SPREADMETHOD;
-  ATTRIBUTE_NAMES[447] = ATTR_SURFACESCALE;
-  ATTRIBUTE_NAMES[448] = ATTR_STROKE_WIDTH;
-  ATTRIBUTE_NAMES[449] = ATTR_REPEAT_START;
-  ATTRIBUTE_NAMES[450] = ATTR_STDDEVIATION;
-  ATTRIBUTE_NAMES[451] = ATTR_STOP_OPACITY;
-  ATTRIBUTE_NAMES[452] = ATTR_ARIA_CONTROLS;
-  ATTRIBUTE_NAMES[453] = ATTR_ARIA_HASPOPUP;
-  ATTRIBUTE_NAMES[454] = ATTR_ACCENT_HEIGHT;
-  ATTRIBUTE_NAMES[455] = ATTR_ARIA_VALUENOW;
-  ATTRIBUTE_NAMES[456] = ATTR_ARIA_RELEVANT;
-  ATTRIBUTE_NAMES[457] = ATTR_ARIA_POSINSET;
-  ATTRIBUTE_NAMES[458] = ATTR_ARIA_VALUEMAX;
-  ATTRIBUTE_NAMES[459] = ATTR_ARIA_READONLY;
-  ATTRIBUTE_NAMES[460] = ATTR_ARIA_SELECTED;
-  ATTRIBUTE_NAMES[461] = ATTR_ARIA_REQUIRED;
-  ATTRIBUTE_NAMES[462] = ATTR_ARIA_EXPANDED;
-  ATTRIBUTE_NAMES[463] = ATTR_ARIA_DISABLED;
-  ATTRIBUTE_NAMES[464] = ATTR_ATTRIBUTETYPE;
-  ATTRIBUTE_NAMES[465] = ATTR_ATTRIBUTENAME;
-  ATTRIBUTE_NAMES[466] = ATTR_ARIA_DATATYPE;
-  ATTRIBUTE_NAMES[467] = ATTR_ARIA_VALUEMIN;
-  ATTRIBUTE_NAMES[468] = ATTR_BASEFREQUENCY;
-  ATTRIBUTE_NAMES[469] = ATTR_COLUMNSPACING;
-  ATTRIBUTE_NAMES[470] = ATTR_COLOR_PROFILE;
-  ATTRIBUTE_NAMES[471] = ATTR_CLIPPATHUNITS;
-  ATTRIBUTE_NAMES[472] = ATTR_DEFINITIONURL;
-  ATTRIBUTE_NAMES[473] = ATTR_GRADIENTUNITS;
-  ATTRIBUTE_NAMES[474] = ATTR_FLOOD_OPACITY;
-  ATTRIBUTE_NAMES[475] = ATTR_ONAFTERUPDATE;
-  ATTRIBUTE_NAMES[476] = ATTR_ONERRORUPDATE;
-  ATTRIBUTE_NAMES[477] = ATTR_ONBEFOREPASTE;
-  ATTRIBUTE_NAMES[478] = ATTR_ONLOSECAPTURE;
-  ATTRIBUTE_NAMES[479] = ATTR_ONCONTEXTMENU;
-  ATTRIBUTE_NAMES[480] = ATTR_ONSELECTSTART;
-  ATTRIBUTE_NAMES[481] = ATTR_ONBEFOREPRINT;
-  ATTRIBUTE_NAMES[482] = ATTR_MOVABLELIMITS;
-  ATTRIBUTE_NAMES[483] = ATTR_LINETHICKNESS;
-  ATTRIBUTE_NAMES[484] = ATTR_UNICODE_RANGE;
-  ATTRIBUTE_NAMES[485] = ATTR_THINMATHSPACE;
-  ATTRIBUTE_NAMES[486] = ATTR_VERT_ORIGIN_X;
-  ATTRIBUTE_NAMES[487] = ATTR_VERT_ORIGIN_Y;
-  ATTRIBUTE_NAMES[488] = ATTR_V_IDEOGRAPHIC;
-  ATTRIBUTE_NAMES[489] = ATTR_PRESERVEALPHA;
-  ATTRIBUTE_NAMES[490] = ATTR_SCRIPTMINSIZE;
-  ATTRIBUTE_NAMES[491] = ATTR_SPECIFICATION;
-  ATTRIBUTE_NAMES[492] = ATTR_XLINK_ACTUATE;
-  ATTRIBUTE_NAMES[493] = ATTR_XLINK_ARCROLE;
-  ATTRIBUTE_NAMES[494] = ATTR_ACCEPT_CHARSET;
-  ATTRIBUTE_NAMES[495] = ATTR_ALIGNMENTSCOPE;
-  ATTRIBUTE_NAMES[496] = ATTR_ARIA_MULTILINE;
-  ATTRIBUTE_NAMES[497] = ATTR_BASELINE_SHIFT;
-  ATTRIBUTE_NAMES[498] = ATTR_HORIZ_ORIGIN_X;
-  ATTRIBUTE_NAMES[499] = ATTR_HORIZ_ORIGIN_Y;
-  ATTRIBUTE_NAMES[500] = ATTR_ONBEFOREUPDATE;
-  ATTRIBUTE_NAMES[501] = ATTR_ONFILTERCHANGE;
-  ATTRIBUTE_NAMES[502] = ATTR_ONROWSINSERTED;
-  ATTRIBUTE_NAMES[503] = ATTR_ONBEFOREUNLOAD;
-  ATTRIBUTE_NAMES[504] = ATTR_MATHBACKGROUND;
-  ATTRIBUTE_NAMES[505] = ATTR_LETTER_SPACING;
-  ATTRIBUTE_NAMES[506] = ATTR_LIGHTING_COLOR;
-  ATTRIBUTE_NAMES[507] = ATTR_THICKMATHSPACE;
-  ATTRIBUTE_NAMES[508] = ATTR_TEXT_RENDERING;
-  ATTRIBUTE_NAMES[509] = ATTR_V_MATHEMATICAL;
-  ATTRIBUTE_NAMES[510] = ATTR_POINTER_EVENTS;
-  ATTRIBUTE_NAMES[511] = ATTR_PRIMITIVEUNITS;
-  ATTRIBUTE_NAMES[512] = ATTR_SYSTEMLANGUAGE;
-  ATTRIBUTE_NAMES[513] = ATTR_STROKE_LINECAP;
-  ATTRIBUTE_NAMES[514] = ATTR_SUBSCRIPTSHIFT;
-  ATTRIBUTE_NAMES[515] = ATTR_STROKE_OPACITY;
-  ATTRIBUTE_NAMES[516] = ATTR_ARIA_DROPEFFECT;
-  ATTRIBUTE_NAMES[517] = ATTR_ARIA_LABELLEDBY;
-  ATTRIBUTE_NAMES[518] = ATTR_ARIA_TEMPLATEID;
-  ATTRIBUTE_NAMES[519] = ATTR_COLOR_RENDERING;
-  ATTRIBUTE_NAMES[520] = ATTR_CONTENTEDITABLE;
-  ATTRIBUTE_NAMES[521] = ATTR_DIFFUSECONSTANT;
-  ATTRIBUTE_NAMES[522] = ATTR_ONDATAAVAILABLE;
-  ATTRIBUTE_NAMES[523] = ATTR_ONCONTROLSELECT;
-  ATTRIBUTE_NAMES[524] = ATTR_IMAGE_RENDERING;
-  ATTRIBUTE_NAMES[525] = ATTR_MEDIUMMATHSPACE;
-  ATTRIBUTE_NAMES[526] = ATTR_TEXT_DECORATION;
-  ATTRIBUTE_NAMES[527] = ATTR_SHAPE_RENDERING;
-  ATTRIBUTE_NAMES[528] = ATTR_STROKE_LINEJOIN;
-  ATTRIBUTE_NAMES[529] = ATTR_REPEAT_TEMPLATE;
-  ATTRIBUTE_NAMES[530] = ATTR_ARIA_DESCRIBEDBY;
-  ATTRIBUTE_NAMES[531] = ATTR_CONTENTSTYLETYPE;
-  ATTRIBUTE_NAMES[532] = ATTR_FONT_SIZE_ADJUST;
-  ATTRIBUTE_NAMES[533] = ATTR_KERNELUNITLENGTH;
-  ATTRIBUTE_NAMES[534] = ATTR_ONBEFOREACTIVATE;
-  ATTRIBUTE_NAMES[535] = ATTR_ONPROPERTYCHANGE;
-  ATTRIBUTE_NAMES[536] = ATTR_ONDATASETCHANGED;
-  ATTRIBUTE_NAMES[537] = ATTR_MASKCONTENTUNITS;
-  ATTRIBUTE_NAMES[538] = ATTR_PATTERNTRANSFORM;
-  ATTRIBUTE_NAMES[539] = ATTR_REQUIREDFEATURES;
-  ATTRIBUTE_NAMES[540] = ATTR_RENDERING_INTENT;
-  ATTRIBUTE_NAMES[541] = ATTR_SPECULAREXPONENT;
-  ATTRIBUTE_NAMES[542] = ATTR_SPECULARCONSTANT;
-  ATTRIBUTE_NAMES[543] = ATTR_SUPERSCRIPTSHIFT;
-  ATTRIBUTE_NAMES[544] = ATTR_STROKE_DASHARRAY;
-  ATTRIBUTE_NAMES[545] = ATTR_XCHANNELSELECTOR;
-  ATTRIBUTE_NAMES[546] = ATTR_YCHANNELSELECTOR;
-  ATTRIBUTE_NAMES[547] = ATTR_ARIA_AUTOCOMPLETE;
-  ATTRIBUTE_NAMES[548] = ATTR_CONTENTSCRIPTTYPE;
-  ATTRIBUTE_NAMES[549] = ATTR_ENABLE_BACKGROUND;
-  ATTRIBUTE_NAMES[550] = ATTR_DOMINANT_BASELINE;
-  ATTRIBUTE_NAMES[551] = ATTR_GRADIENTTRANSFORM;
-  ATTRIBUTE_NAMES[552] = ATTR_ONBEFORDEACTIVATE;
-  ATTRIBUTE_NAMES[553] = ATTR_ONDATASETCOMPLETE;
-  ATTRIBUTE_NAMES[554] = ATTR_OVERLINE_POSITION;
-  ATTRIBUTE_NAMES[555] = ATTR_ONBEFOREEDITFOCUS;
-  ATTRIBUTE_NAMES[556] = ATTR_LIMITINGCONEANGLE;
-  ATTRIBUTE_NAMES[557] = ATTR_VERYTHINMATHSPACE;
-  ATTRIBUTE_NAMES[558] = ATTR_STROKE_DASHOFFSET;
-  ATTRIBUTE_NAMES[559] = ATTR_STROKE_MITERLIMIT;
-  ATTRIBUTE_NAMES[560] = ATTR_ALIGNMENT_BASELINE;
-  ATTRIBUTE_NAMES[561] = ATTR_ONREADYSTATECHANGE;
-  ATTRIBUTE_NAMES[562] = ATTR_OVERLINE_THICKNESS;
-  ATTRIBUTE_NAMES[563] = ATTR_UNDERLINE_POSITION;
-  ATTRIBUTE_NAMES[564] = ATTR_VERYTHICKMATHSPACE;
-  ATTRIBUTE_NAMES[565] = ATTR_REQUIREDEXTENSIONS;
-  ATTRIBUTE_NAMES[566] = ATTR_COLOR_INTERPOLATION;
-  ATTRIBUTE_NAMES[567] = ATTR_UNDERLINE_THICKNESS;
-  ATTRIBUTE_NAMES[568] = ATTR_PRESERVEASPECTRATIO;
-  ATTRIBUTE_NAMES[569] = ATTR_PATTERNCONTENTUNITS;
-  ATTRIBUTE_NAMES[570] = ATTR_ARIA_MULTISELECTABLE;
-  ATTRIBUTE_NAMES[571] = ATTR_SCRIPTSIZEMULTIPLIER;
-  ATTRIBUTE_NAMES[572] = ATTR_ARIA_ACTIVEDESCENDANT;
-  ATTRIBUTE_NAMES[573] = ATTR_VERYVERYTHINMATHSPACE;
-  ATTRIBUTE_NAMES[574] = ATTR_VERYVERYTHICKMATHSPACE;
-  ATTRIBUTE_NAMES[575] = ATTR_STRIKETHROUGH_POSITION;
-  ATTRIBUTE_NAMES[576] = ATTR_STRIKETHROUGH_THICKNESS;
-  ATTRIBUTE_NAMES[577] = ATTR_EXTERNALRESOURCESREQUIRED;
-  ATTRIBUTE_NAMES[578] = ATTR_GLYPH_ORIENTATION_VERTICAL;
-  ATTRIBUTE_NAMES[579] = ATTR_COLOR_INTERPOLATION_FILTERS;
-  ATTRIBUTE_NAMES[580] = ATTR_GLYPH_ORIENTATION_HORIZONTAL;
+  ATTRIBUTE_NAMES[377] = ATTR_CROSSORIGIN;
+  ATTRIBUTE_NAMES[378] = ATTR_COLUMNALIGN;
+  ATTRIBUTE_NAMES[379] = ATTR_COLUMNLINES;
+  ATTRIBUTE_NAMES[380] = ATTR_CONTEXTMENU;
+  ATTRIBUTE_NAMES[381] = ATTR_BASEPROFILE;
+  ATTRIBUTE_NAMES[382] = ATTR_FONT_FAMILY;
+  ATTRIBUTE_NAMES[383] = ATTR_FRAMEBORDER;
+  ATTRIBUTE_NAMES[384] = ATTR_FILTERUNITS;
+  ATTRIBUTE_NAMES[385] = ATTR_FLOOD_COLOR;
+  ATTRIBUTE_NAMES[386] = ATTR_FONT_WEIGHT;
+  ATTRIBUTE_NAMES[387] = ATTR_HORIZ_ADV_X;
+  ATTRIBUTE_NAMES[388] = ATTR_ONDRAGLEAVE;
+  ATTRIBUTE_NAMES[389] = ATTR_ONMOUSEMOVE;
+  ATTRIBUTE_NAMES[390] = ATTR_ORIENTATION;
+  ATTRIBUTE_NAMES[391] = ATTR_ONMOUSEDOWN;
+  ATTRIBUTE_NAMES[392] = ATTR_ONMOUSEOVER;
+  ATTRIBUTE_NAMES[393] = ATTR_ONDRAGENTER;
+  ATTRIBUTE_NAMES[394] = ATTR_IDEOGRAPHIC;
+  ATTRIBUTE_NAMES[395] = ATTR_ONBEFORECUT;
+  ATTRIBUTE_NAMES[396] = ATTR_ONFORMINPUT;
+  ATTRIBUTE_NAMES[397] = ATTR_ONDRAGSTART;
+  ATTRIBUTE_NAMES[398] = ATTR_ONMOVESTART;
+  ATTRIBUTE_NAMES[399] = ATTR_MARKERUNITS;
+  ATTRIBUTE_NAMES[400] = ATTR_MATHVARIANT;
+  ATTRIBUTE_NAMES[401] = ATTR_MARGINWIDTH;
+  ATTRIBUTE_NAMES[402] = ATTR_MARKERWIDTH;
+  ATTRIBUTE_NAMES[403] = ATTR_TEXT_ANCHOR;
+  ATTRIBUTE_NAMES[404] = ATTR_TABLEVALUES;
+  ATTRIBUTE_NAMES[405] = ATTR_SCRIPTLEVEL;
+  ATTRIBUTE_NAMES[406] = ATTR_REPEATCOUNT;
+  ATTRIBUTE_NAMES[407] = ATTR_STITCHTILES;
+  ATTRIBUTE_NAMES[408] = ATTR_STARTOFFSET;
+  ATTRIBUTE_NAMES[409] = ATTR_SCROLLDELAY;
+  ATTRIBUTE_NAMES[410] = ATTR_XMLNS_XLINK;
+  ATTRIBUTE_NAMES[411] = ATTR_XLINK_TITLE;
+  ATTRIBUTE_NAMES[412] = ATTR_ARIA_INVALID;
+  ATTRIBUTE_NAMES[413] = ATTR_ARIA_PRESSED;
+  ATTRIBUTE_NAMES[414] = ATTR_ARIA_CHECKED;
+  ATTRIBUTE_NAMES[415] = ATTR_AUTOCOMPLETE;
+  ATTRIBUTE_NAMES[416] = ATTR_ARIA_SETSIZE;
+  ATTRIBUTE_NAMES[417] = ATTR_ARIA_CHANNEL;
+  ATTRIBUTE_NAMES[418] = ATTR_EQUALCOLUMNS;
+  ATTRIBUTE_NAMES[419] = ATTR_DISPLAYSTYLE;
+  ATTRIBUTE_NAMES[420] = ATTR_DATAFORMATAS;
+  ATTRIBUTE_NAMES[421] = ATTR_FILL_OPACITY;
+  ATTRIBUTE_NAMES[422] = ATTR_FONT_VARIANT;
+  ATTRIBUTE_NAMES[423] = ATTR_FONT_STRETCH;
+  ATTRIBUTE_NAMES[424] = ATTR_FRAMESPACING;
+  ATTRIBUTE_NAMES[425] = ATTR_KERNELMATRIX;
+  ATTRIBUTE_NAMES[426] = ATTR_ONDEACTIVATE;
+  ATTRIBUTE_NAMES[427] = ATTR_ONROWSDELETE;
+  ATTRIBUTE_NAMES[428] = ATTR_ONMOUSELEAVE;
+  ATTRIBUTE_NAMES[429] = ATTR_ONFORMCHANGE;
+  ATTRIBUTE_NAMES[430] = ATTR_ONCELLCHANGE;
+  ATTRIBUTE_NAMES[431] = ATTR_ONMOUSEWHEEL;
+  ATTRIBUTE_NAMES[432] = ATTR_ONMOUSEENTER;
+  ATTRIBUTE_NAMES[433] = ATTR_ONAFTERPRINT;
+  ATTRIBUTE_NAMES[434] = ATTR_ONBEFORECOPY;
+  ATTRIBUTE_NAMES[435] = ATTR_MARGINHEIGHT;
+  ATTRIBUTE_NAMES[436] = ATTR_MARKERHEIGHT;
+  ATTRIBUTE_NAMES[437] = ATTR_MARKER_START;
+  ATTRIBUTE_NAMES[438] = ATTR_MATHEMATICAL;
+  ATTRIBUTE_NAMES[439] = ATTR_LENGTHADJUST;
+  ATTRIBUTE_NAMES[440] = ATTR_UNSELECTABLE;
+  ATTRIBUTE_NAMES[441] = ATTR_UNICODE_BIDI;
+  ATTRIBUTE_NAMES[442] = ATTR_UNITS_PER_EM;
+  ATTRIBUTE_NAMES[443] = ATTR_WORD_SPACING;
+  ATTRIBUTE_NAMES[444] = ATTR_WRITING_MODE;
+  ATTRIBUTE_NAMES[445] = ATTR_V_ALPHABETIC;
+  ATTRIBUTE_NAMES[446] = ATTR_PATTERNUNITS;
+  ATTRIBUTE_NAMES[447] = ATTR_SPREADMETHOD;
+  ATTRIBUTE_NAMES[448] = ATTR_SURFACESCALE;
+  ATTRIBUTE_NAMES[449] = ATTR_STROKE_WIDTH;
+  ATTRIBUTE_NAMES[450] = ATTR_REPEAT_START;
+  ATTRIBUTE_NAMES[451] = ATTR_STDDEVIATION;
+  ATTRIBUTE_NAMES[452] = ATTR_STOP_OPACITY;
+  ATTRIBUTE_NAMES[453] = ATTR_ARIA_CONTROLS;
+  ATTRIBUTE_NAMES[454] = ATTR_ARIA_HASPOPUP;
+  ATTRIBUTE_NAMES[455] = ATTR_ACCENT_HEIGHT;
+  ATTRIBUTE_NAMES[456] = ATTR_ARIA_VALUENOW;
+  ATTRIBUTE_NAMES[457] = ATTR_ARIA_RELEVANT;
+  ATTRIBUTE_NAMES[458] = ATTR_ARIA_POSINSET;
+  ATTRIBUTE_NAMES[459] = ATTR_ARIA_VALUEMAX;
+  ATTRIBUTE_NAMES[460] = ATTR_ARIA_READONLY;
+  ATTRIBUTE_NAMES[461] = ATTR_ARIA_SELECTED;
+  ATTRIBUTE_NAMES[462] = ATTR_ARIA_REQUIRED;
+  ATTRIBUTE_NAMES[463] = ATTR_ARIA_EXPANDED;
+  ATTRIBUTE_NAMES[464] = ATTR_ARIA_DISABLED;
+  ATTRIBUTE_NAMES[465] = ATTR_ATTRIBUTETYPE;
+  ATTRIBUTE_NAMES[466] = ATTR_ATTRIBUTENAME;
+  ATTRIBUTE_NAMES[467] = ATTR_ARIA_DATATYPE;
+  ATTRIBUTE_NAMES[468] = ATTR_ARIA_VALUEMIN;
+  ATTRIBUTE_NAMES[469] = ATTR_BASEFREQUENCY;
+  ATTRIBUTE_NAMES[470] = ATTR_COLUMNSPACING;
+  ATTRIBUTE_NAMES[471] = ATTR_COLOR_PROFILE;
+  ATTRIBUTE_NAMES[472] = ATTR_CLIPPATHUNITS;
+  ATTRIBUTE_NAMES[473] = ATTR_DEFINITIONURL;
+  ATTRIBUTE_NAMES[474] = ATTR_GRADIENTUNITS;
+  ATTRIBUTE_NAMES[475] = ATTR_FLOOD_OPACITY;
+  ATTRIBUTE_NAMES[476] = ATTR_ONAFTERUPDATE;
+  ATTRIBUTE_NAMES[477] = ATTR_ONERRORUPDATE;
+  ATTRIBUTE_NAMES[478] = ATTR_ONBEFOREPASTE;
+  ATTRIBUTE_NAMES[479] = ATTR_ONLOSECAPTURE;
+  ATTRIBUTE_NAMES[480] = ATTR_ONCONTEXTMENU;
+  ATTRIBUTE_NAMES[481] = ATTR_ONSELECTSTART;
+  ATTRIBUTE_NAMES[482] = ATTR_ONBEFOREPRINT;
+  ATTRIBUTE_NAMES[483] = ATTR_MOVABLELIMITS;
+  ATTRIBUTE_NAMES[484] = ATTR_LINETHICKNESS;
+  ATTRIBUTE_NAMES[485] = ATTR_UNICODE_RANGE;
+  ATTRIBUTE_NAMES[486] = ATTR_THINMATHSPACE;
+  ATTRIBUTE_NAMES[487] = ATTR_VERT_ORIGIN_X;
+  ATTRIBUTE_NAMES[488] = ATTR_VERT_ORIGIN_Y;
+  ATTRIBUTE_NAMES[489] = ATTR_V_IDEOGRAPHIC;
+  ATTRIBUTE_NAMES[490] = ATTR_PRESERVEALPHA;
+  ATTRIBUTE_NAMES[491] = ATTR_SCRIPTMINSIZE;
+  ATTRIBUTE_NAMES[492] = ATTR_SPECIFICATION;
+  ATTRIBUTE_NAMES[493] = ATTR_XLINK_ACTUATE;
+  ATTRIBUTE_NAMES[494] = ATTR_XLINK_ARCROLE;
+  ATTRIBUTE_NAMES[495] = ATTR_ACCEPT_CHARSET;
+  ATTRIBUTE_NAMES[496] = ATTR_ALIGNMENTSCOPE;
+  ATTRIBUTE_NAMES[497] = ATTR_ARIA_MULTILINE;
+  ATTRIBUTE_NAMES[498] = ATTR_BASELINE_SHIFT;
+  ATTRIBUTE_NAMES[499] = ATTR_HORIZ_ORIGIN_X;
+  ATTRIBUTE_NAMES[500] = ATTR_HORIZ_ORIGIN_Y;
+  ATTRIBUTE_NAMES[501] = ATTR_ONBEFOREUPDATE;
+  ATTRIBUTE_NAMES[502] = ATTR_ONFILTERCHANGE;
+  ATTRIBUTE_NAMES[503] = ATTR_ONROWSINSERTED;
+  ATTRIBUTE_NAMES[504] = ATTR_ONBEFOREUNLOAD;
+  ATTRIBUTE_NAMES[505] = ATTR_MATHBACKGROUND;
+  ATTRIBUTE_NAMES[506] = ATTR_LETTER_SPACING;
+  ATTRIBUTE_NAMES[507] = ATTR_LIGHTING_COLOR;
+  ATTRIBUTE_NAMES[508] = ATTR_THICKMATHSPACE;
+  ATTRIBUTE_NAMES[509] = ATTR_TEXT_RENDERING;
+  ATTRIBUTE_NAMES[510] = ATTR_V_MATHEMATICAL;
+  ATTRIBUTE_NAMES[511] = ATTR_POINTER_EVENTS;
+  ATTRIBUTE_NAMES[512] = ATTR_PRIMITIVEUNITS;
+  ATTRIBUTE_NAMES[513] = ATTR_SYSTEMLANGUAGE;
+  ATTRIBUTE_NAMES[514] = ATTR_STROKE_LINECAP;
+  ATTRIBUTE_NAMES[515] = ATTR_SUBSCRIPTSHIFT;
+  ATTRIBUTE_NAMES[516] = ATTR_STROKE_OPACITY;
+  ATTRIBUTE_NAMES[517] = ATTR_ARIA_DROPEFFECT;
+  ATTRIBUTE_NAMES[518] = ATTR_ARIA_LABELLEDBY;
+  ATTRIBUTE_NAMES[519] = ATTR_ARIA_TEMPLATEID;
+  ATTRIBUTE_NAMES[520] = ATTR_COLOR_RENDERING;
+  ATTRIBUTE_NAMES[521] = ATTR_CONTENTEDITABLE;
+  ATTRIBUTE_NAMES[522] = ATTR_DIFFUSECONSTANT;
+  ATTRIBUTE_NAMES[523] = ATTR_ONDATAAVAILABLE;
+  ATTRIBUTE_NAMES[524] = ATTR_ONCONTROLSELECT;
+  ATTRIBUTE_NAMES[525] = ATTR_IMAGE_RENDERING;
+  ATTRIBUTE_NAMES[526] = ATTR_MEDIUMMATHSPACE;
+  ATTRIBUTE_NAMES[527] = ATTR_TEXT_DECORATION;
+  ATTRIBUTE_NAMES[528] = ATTR_SHAPE_RENDERING;
+  ATTRIBUTE_NAMES[529] = ATTR_STROKE_LINEJOIN;
+  ATTRIBUTE_NAMES[530] = ATTR_REPEAT_TEMPLATE;
+  ATTRIBUTE_NAMES[531] = ATTR_ARIA_DESCRIBEDBY;
+  ATTRIBUTE_NAMES[532] = ATTR_CONTENTSTYLETYPE;
+  ATTRIBUTE_NAMES[533] = ATTR_FONT_SIZE_ADJUST;
+  ATTRIBUTE_NAMES[534] = ATTR_KERNELUNITLENGTH;
+  ATTRIBUTE_NAMES[535] = ATTR_ONBEFOREACTIVATE;
+  ATTRIBUTE_NAMES[536] = ATTR_ONPROPERTYCHANGE;
+  ATTRIBUTE_NAMES[537] = ATTR_ONDATASETCHANGED;
+  ATTRIBUTE_NAMES[538] = ATTR_MASKCONTENTUNITS;
+  ATTRIBUTE_NAMES[539] = ATTR_PATTERNTRANSFORM;
+  ATTRIBUTE_NAMES[540] = ATTR_REQUIREDFEATURES;
+  ATTRIBUTE_NAMES[541] = ATTR_RENDERING_INTENT;
+  ATTRIBUTE_NAMES[542] = ATTR_SPECULAREXPONENT;
+  ATTRIBUTE_NAMES[543] = ATTR_SPECULARCONSTANT;
+  ATTRIBUTE_NAMES[544] = ATTR_SUPERSCRIPTSHIFT;
+  ATTRIBUTE_NAMES[545] = ATTR_STROKE_DASHARRAY;
+  ATTRIBUTE_NAMES[546] = ATTR_XCHANNELSELECTOR;
+  ATTRIBUTE_NAMES[547] = ATTR_YCHANNELSELECTOR;
+  ATTRIBUTE_NAMES[548] = ATTR_ARIA_AUTOCOMPLETE;
+  ATTRIBUTE_NAMES[549] = ATTR_CONTENTSCRIPTTYPE;
+  ATTRIBUTE_NAMES[550] = ATTR_ENABLE_BACKGROUND;
+  ATTRIBUTE_NAMES[551] = ATTR_DOMINANT_BASELINE;
+  ATTRIBUTE_NAMES[552] = ATTR_GRADIENTTRANSFORM;
+  ATTRIBUTE_NAMES[553] = ATTR_ONBEFORDEACTIVATE;
+  ATTRIBUTE_NAMES[554] = ATTR_ONDATASETCOMPLETE;
+  ATTRIBUTE_NAMES[555] = ATTR_OVERLINE_POSITION;
+  ATTRIBUTE_NAMES[556] = ATTR_ONBEFOREEDITFOCUS;
+  ATTRIBUTE_NAMES[557] = ATTR_LIMITINGCONEANGLE;
+  ATTRIBUTE_NAMES[558] = ATTR_VERYTHINMATHSPACE;
+  ATTRIBUTE_NAMES[559] = ATTR_STROKE_DASHOFFSET;
+  ATTRIBUTE_NAMES[560] = ATTR_STROKE_MITERLIMIT;
+  ATTRIBUTE_NAMES[561] = ATTR_ALIGNMENT_BASELINE;
+  ATTRIBUTE_NAMES[562] = ATTR_ONREADYSTATECHANGE;
+  ATTRIBUTE_NAMES[563] = ATTR_OVERLINE_THICKNESS;
+  ATTRIBUTE_NAMES[564] = ATTR_UNDERLINE_POSITION;
+  ATTRIBUTE_NAMES[565] = ATTR_VERYTHICKMATHSPACE;
+  ATTRIBUTE_NAMES[566] = ATTR_REQUIREDEXTENSIONS;
+  ATTRIBUTE_NAMES[567] = ATTR_COLOR_INTERPOLATION;
+  ATTRIBUTE_NAMES[568] = ATTR_UNDERLINE_THICKNESS;
+  ATTRIBUTE_NAMES[569] = ATTR_PRESERVEASPECTRATIO;
+  ATTRIBUTE_NAMES[570] = ATTR_PATTERNCONTENTUNITS;
+  ATTRIBUTE_NAMES[571] = ATTR_ARIA_MULTISELECTABLE;
+  ATTRIBUTE_NAMES[572] = ATTR_SCRIPTSIZEMULTIPLIER;
+  ATTRIBUTE_NAMES[573] = ATTR_ARIA_ACTIVEDESCENDANT;
+  ATTRIBUTE_