Merge mozilla-central to electrolysis.
authorBenjamin Smedberg <benjamin@smedbergs.us>
Tue, 19 Jan 2010 14:51:19 -0500
changeset 46536 3bfc0fbabb2ce583cc71f1bcbf4a4c296f076a63
parent 46535 f78daed09fdff6d199222e6e51c2e2f3257d7598 (current diff)
parent 37323 0aeedccc0125e651a885980430aeb00d978b1f82 (diff)
child 46537 ef50f036a188046c016b3cdc3cfa20477e0d914b
push idunknown
push userunknown
push dateunknown
milestone1.9.3a1pre
Merge mozilla-central to electrolysis.
accessible/src/base/nsAccessibleEventData.cpp
accessible/src/base/nsAccessibleEventData.h
build/automation.py.in
dom/plugins/PPluginInstance.ipdl
dom/plugins/PluginInstanceChild.cpp
dom/plugins/PluginInstanceParent.cpp
dom/plugins/PluginInstanceParent.h
dom/plugins/PluginMessageUtils.h
ipc/ipdl/ipdl/lower.py
toolkit/xre/nsSigHandlers.cpp
--- a/accessible/src/atk/nsAccessibleWrap.cpp
+++ b/accessible/src/atk/nsAccessibleWrap.cpp
@@ -1102,34 +1102,32 @@ nsAccessibleWrap *GetAccessibleWrap(AtkO
 
     if (tmpAppAccWrap != tmpAccWrap && !tmpAccWrap->IsValidObject())
         return nsnull;
 
     return tmpAccWrap;
 }
 
 nsresult
-nsAccessibleWrap::FireAccessibleEvent(nsIAccessibleEvent *aEvent)
+nsAccessibleWrap::HandleAccEvent(nsAccEvent *aEvent)
 {
-    nsresult rv = nsAccessible::FireAccessibleEvent(aEvent);
+    nsresult rv = nsAccessible::HandleAccEvent(aEvent);
     NS_ENSURE_SUCCESS(rv, rv);
 
     return FirePlatformEvent(aEvent);
 }
 
 nsresult
-nsAccessibleWrap::FirePlatformEvent(nsIAccessibleEvent *aEvent)
+nsAccessibleWrap::FirePlatformEvent(nsAccEvent *aEvent)
 {
     nsCOMPtr<nsIAccessible> accessible;
     aEvent->GetAccessible(getter_AddRefs(accessible));
     NS_ENSURE_TRUE(accessible, NS_ERROR_FAILURE);
 
-    PRUint32 type = 0;
-    nsresult rv = aEvent->GetEventType(&type);
-    NS_ENSURE_SUCCESS(rv, rv);
+    PRUint32 type = aEvent->GetEventType();
 
     AtkObject *atkObj = nsAccessibleWrap::GetAtkObject(accessible);
 
     // We don't create ATK objects for nsIAccessible plain text leaves,
     // just return NS_OK in such case
     if (!atkObj) {
         NS_ASSERTION(type == nsIAccessibleEvent::EVENT_SHOW ||
                      type == nsIAccessibleEvent::EVENT_HIDE,
--- a/accessible/src/atk/nsAccessibleWrap.h
+++ b/accessible/src/atk/nsAccessibleWrap.h
@@ -95,17 +95,17 @@ public:
 #ifdef MAI_LOGGING
     virtual void DumpnsAccessibleWrapInfo(int aDepth) {}
     static PRInt32 mAccWrapCreated;
     static PRInt32 mAccWrapDeleted;
 #endif
 
     // return the atk object for this nsAccessibleWrap
     NS_IMETHOD GetNativeInterface(void **aOutAccessible);
-    NS_IMETHOD FireAccessibleEvent(nsIAccessibleEvent *aEvent);
+    virtual nsresult HandleAccEvent(nsAccEvent *aEvent);
 
     AtkObject * GetAtkObject(void);
     static AtkObject * GetAtkObject(nsIAccessible * acc);
 
     PRBool IsValidObject();
     
     // get/set the MaiHyperlink object for this nsAccessibleWrap
     MaiHyperlink* GetMaiHyperlink(PRBool aCreate = PR_TRUE);
@@ -113,17 +113,17 @@ public:
 
     static const char * ReturnString(nsAString &aString) {
       static nsCString returnedString;
       returnedString = NS_ConvertUTF16toUTF8(aString);
       return returnedString.get();
     }
 
 protected:
-    virtual nsresult FirePlatformEvent(nsIAccessibleEvent *aEvent);
+    virtual nsresult FirePlatformEvent(nsAccEvent *aEvent);
 
     nsresult FireAtkStateChangeEvent(nsIAccessibleEvent *aEvent,
                                      AtkObject *aObject);
     nsresult FireAtkTextChangedEvent(nsIAccessibleEvent *aEvent,
                                      AtkObject *aObject);
     nsresult FireAtkPropChangedEvent(nsIAccessibleEvent *aEvent,
                                      AtkObject *aObject);
     nsresult FireAtkShowHideEvent(nsIAccessibleEvent *aEvent,
--- a/accessible/src/base/Makefile.in
+++ b/accessible/src/base/Makefile.in
@@ -44,42 +44,43 @@ include $(DEPTH)/config/autoconf.mk
 
 MODULE = accessibility
 LIBRARY_NAME = accessibility_base_s
 LIBXUL_LIBRARY = 1
 
 
 CPPSRCS = \
   nsAccessNode.cpp \
-  nsAccessibleEventData.cpp \
+  nsAccEvent.cpp \
   nsARIAGridAccessible.cpp \
   nsARIAMap.cpp \
   nsDocAccessible.cpp \
   nsOuterDocAccessible.cpp \
   nsAccessibilityAtoms.cpp \
   nsCoreUtils.cpp \
   nsAccUtils.cpp \
   nsRelUtils.cpp \
   nsAccessibilityService.cpp \
   nsAccessible.cpp \
   nsAccessibleRelation.cpp \
   nsAccessibleTreeWalker.cpp \
   nsBaseWidgetAccessible.cpp \
+  nsEventShell.cpp \
   nsFormControlAccessible.cpp \
   nsRootAccessible.cpp \
   nsApplicationAccessible.cpp \
   nsCaretAccessible.cpp \
   nsTextAccessible.cpp \
   nsTextEquivUtils.cpp \
   nsTextAttrs.cpp \
   $(NULL)
 
 EXPORTS = \
   nsRootAccessible.h \
-  nsAccessibleEventData.h \
+  nsAccEvent.h \
   nsAccessNode.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
 
rename from accessible/src/base/nsAccessibleEventData.cpp
rename to accessible/src/base/nsAccEvent.cpp
--- a/accessible/src/base/nsAccessibleEventData.cpp
+++ b/accessible/src/base/nsAccEvent.cpp
@@ -31,17 +31,17 @@
  * 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 "nsAccessibleEventData.h"
+#include "nsAccEvent.h"
 #include "nsAccessibilityAtoms.h"
 #include "nsApplicationAccessibleWrap.h"
 #include "nsCoreUtils.h"
 #include "nsIAccessibilityService.h"
 #include "nsIAccessNode.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsIEventStateManager.h"
rename from accessible/src/base/nsAccessibleEventData.h
rename to accessible/src/base/nsAccEvent.h
--- a/accessible/src/base/nsAccessibleEventData.h
+++ b/accessible/src/base/nsAccEvent.h
@@ -33,18 +33,18 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
-#ifndef _nsAccessibleEventData_H_
-#define _nsAccessibleEventData_H_
+#ifndef _nsAccEvent_H_
+#define _nsAccEvent_H_
 
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsCOMArray.h"
 #include "nsIAccessibleEvent.h"
 #include "nsIAccessible.h"
 #include "nsIAccessibleDocument.h"
 #include "nsIDOMNode.h"
@@ -100,16 +100,17 @@ public:
 
   NS_DECL_NSIACCESSIBLEEVENT
 
   // nsAccEvent
   PRUint32 GetEventType() const { return mEventType; }
   EEventRule GetEventRule() const { return mEventRule; }
   PRBool IsAsync() const { return mIsAsync; }
   PRBool IsFromUserInput() const { return mIsFromUserInput; }
+  nsIAccessible* GetAccessible() const { return mAccessible; }
 
   static void GetLastEventAttributes(nsIDOMNode *aNode,
                                      nsIPersistentProperties *aAttributes);
 
 protected:
   already_AddRefed<nsIAccessible> GetAccessibleByNode();
 
   void CaptureIsFromUserInput();
--- a/accessible/src/base/nsAccUtils.cpp
+++ b/accessible/src/base/nsAccUtils.cpp
@@ -37,17 +37,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsCoreUtils.h"
 #include "nsAccUtils.h"
 
 #include "nsIAccessibleStates.h"
 #include "nsIAccessibleTypes.h"
 
-#include "nsAccessibleEventData.h"
+#include "nsAccEvent.h"
 #include "nsHyperTextAccessible.h"
 #include "nsHTMLTableAccessible.h"
 #include "nsDocAccessible.h"
 #include "nsAccessibilityAtoms.h"
 #include "nsAccessibleTreeWalker.h"
 #include "nsAccessible.h"
 #include "nsARIAMap.h"
 #include "nsXULTreeGridAccessible.h"
@@ -343,31 +343,16 @@ nsAccUtils::HasDefinedARIAToken(nsIConte
                             nsAccessibilityAtoms::_empty, eCaseMatters) ||
       aContent->AttrValueIs(kNameSpaceID_None, aAtom,
                             nsAccessibilityAtoms::_undefined, eCaseMatters)) {
         return PR_FALSE;
   }
   return PR_TRUE;
 }
 
-nsresult
-nsAccUtils::FireAccEvent(PRUint32 aEventType, nsIAccessible *aAccessible,
-                         PRBool aIsAsynch)
-{
-  NS_ENSURE_ARG(aAccessible);
-
-  nsRefPtr<nsAccessible> acc(nsAccUtils::QueryAccessible(aAccessible));
-
-  nsCOMPtr<nsIAccessibleEvent> event =
-    new nsAccEvent(aEventType, aAccessible, aIsAsynch);
-  NS_ENSURE_TRUE(event, NS_ERROR_OUT_OF_MEMORY);
-
-  return acc->FireAccessibleEvent(event);
-}
-
 PRBool
 nsAccUtils::HasAccessibleChildren(nsIDOMNode *aNode)
 {
   if (!aNode)
     return PR_FALSE;
 
   nsCOMPtr<nsIContent> content(do_QueryInterface(aNode));
   if (!content)
--- a/accessible/src/base/nsAccUtils.h
+++ b/accessible/src/base/nsAccUtils.h
@@ -140,22 +140,16 @@ public:
    * property is not present, or is "" or "undefined". Do not call 
    * this method for properties of type string, decimal, IDREF or IDREFS.
    * 
    * Return PR_TRUE if the ARIA property is defined, otherwise PR_FALSE
    */
   static PRBool HasDefinedARIAToken(nsIContent *aContent, nsIAtom *aAtom);
 
   /**
-   * Fire accessible event of the given type for the given accessible.
-   */
-  static nsresult FireAccEvent(PRUint32 aEventType, nsIAccessible *aAccessible,
-                               PRBool aIsAsynch = PR_FALSE);
-
-  /**
    * Return true if the given DOM node contains accessible children.
    */
   static PRBool HasAccessibleChildren(nsIDOMNode *aNode);
 
   /**
     * If an ancestor in this document exists with the given role, return it
     * @param aDescendant Descendant to start search with
     * @param aRole Role to find matching ancestor for
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -282,27 +282,28 @@ nsAccessibilityService::NotifyOfAnchorJu
         nsAccessNode::GetDocAccessibleFor(documentNode);
       if (accessibleDoc)
         accessibleDoc->GetAccessibleInParentChain(targetNode, PR_TRUE,
                                                   getter_AddRefs(targetAcc));
     }
   }
 
   if (targetAcc)
-    return nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_SCROLLING_START,
-                                    targetAcc);
+    nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_SCROLLING_START,
+                            targetAcc);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsAccessibilityService::FireAccessibleEvent(PRUint32 aEvent,
                                             nsIAccessible *aTarget)
 {
-  return nsAccUtils::FireAccEvent(aEvent, aTarget);
+  nsEventShell::FireEvent(aEvent, aTarget);
+  return NS_OK;
 }
 
 void nsAccessibilityService::StartLoadCallback(nsITimer *aTimer, void *aClosure)
 {
   if (gAccessibilityService)
     gAccessibilityService->
       ProcessDocLoadEvent(aTimer, aClosure,
                           nsIAccessibleEvent::EVENT_DOCUMENT_LOAD_START);
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -1351,17 +1351,17 @@ nsAccessible::GetXULName(nsAString& aLab
     }
     parent = parent->GetParent();
   }
 
   return nsTextEquivUtils::GetNameFromSubtree(this, aLabel);
 }
 
 nsresult
-nsAccessible::FireAccessibleEvent(nsIAccessibleEvent *aEvent)
+nsAccessible::HandleAccEvent(nsAccEvent *aEvent)
 {
   NS_ENSURE_ARG_POINTER(aEvent);
   nsCOMPtr<nsIDOMNode> eventNode;
   aEvent->GetDOMNode(getter_AddRefs(eventNode));
   NS_ENSURE_TRUE(nsAccUtils::IsNodeRelevant(eventNode), NS_ERROR_FAILURE);
 
   nsCOMPtr<nsIObserverService> obsService =
     do_GetService("@mozilla.org/observer-service;1");
--- a/accessible/src/base/nsAccessible.h
+++ b/accessible/src/base/nsAccessible.h
@@ -37,16 +37,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _nsAccessible_H_
 #define _nsAccessible_H_
 
 #include "nsAccessNodeWrap.h"
 
 #include "nsARIAMap.h"
+#include "nsEventShell.h"
 #include "nsRelUtils.h"
 #include "nsTextEquivUtils.h"
 
 #include "nsIAccessible.h"
 #include "nsIAccessibleHyperLink.h"
 #include "nsIAccessibleSelectable.h"
 #include "nsIAccessibleValue.h"
 #include "nsIAccessibleRole.h"
@@ -98,21 +99,21 @@ public:
   }
 
 private:
   nsTArray<nsString> mNames;
 };
 
 
 #define NS_ACCESSIBLE_IMPL_CID                          \
-{  /* c734df37-7e12-49ec-8983-eea88a186bb8 */           \
-  0xc734df37,                                           \
-  0x7e12,                                               \
-  0x49ec,                                               \
-  { 0x89, 0x83, 0xee, 0xa8, 0x8a, 0x18, 0x6b, 0xb8 }    \
+{  /* 133c8bf4-4913-4355-bd50-426bd1d6e1ad */           \
+  0x133c8bf4,                                           \
+  0x4913,                                               \
+  0x4355,                                               \
+  { 0xbd, 0x50, 0x42, 0x6b, 0xd1, 0xd6, 0xe1, 0xad }    \
 }
 
 class nsAccessible : public nsAccessNodeWrap, 
                      public nsIAccessible, 
                      public nsIAccessibleHyperLink,
                      public nsIAccessibleSelectable,
                      public nsIAccessibleValue
 {
@@ -274,19 +275,20 @@ public:
    * Return first child accessible only if cached.
    */
   nsAccessible* GetCachedFirstChild();
 
   //////////////////////////////////////////////////////////////////////////////
   // Miscellaneous methods
 
   /**
-   * Fire accessible event.
+   * Handle accessible event, i.e. process it, notifies observers and fires
+   * platform specific event.
    */
-  virtual nsresult FireAccessibleEvent(nsIAccessibleEvent *aAccEvent);
+  virtual nsresult HandleAccEvent(nsAccEvent *aAccEvent);
 
   /**
    * Return true if there are accessible children in anonymous content
    */
   virtual PRBool GetAllowsAnonChildAccessibles();
 
   /**
    * Returns text of accessible if accessible has text role otherwise empty
@@ -440,23 +442,23 @@ protected:
    * (see nsARIAMap.h). Used by GetNumActions() and GetActionName().
    *
    * @param aStates  [in] states of the accessible
    */
   PRUint32 GetActionRule(PRUint32 aStates);
 
   /**
    * Fires platform accessible event. It's notification method only. It does
-   * change nothing on Gecko side. Mostly you should use
-   * nsIAccessible::FireAccessibleEvent excepting special cases like we have
-   * in xul:tree accessible to lie to AT. Must be overridden in wrap classes.
+   * change nothing on Gecko side. Don't use it until you're sure what you do
+   * (see example in XUL tree accessible), use nsEventShell::FireEvent()
+   * instead. MUST be overridden in wrap classes.
    *
    * @param aEvent  the accessible event to fire.
    */
-  virtual nsresult FirePlatformEvent(nsIAccessibleEvent *aEvent) = 0;
+  virtual nsresult FirePlatformEvent(nsAccEvent *aEvent) = 0;
 
   // Data Members
   nsRefPtr<nsAccessible> mParent;
   nsTArray<nsRefPtr<nsAccessible> > mChildren;
   PRBool mAreChildrenInitialized;
 
   nsRoleMapEntry *mRoleMapEntry; // Non-null indicates author-supplied role; possibly state & value as well
 };
--- a/accessible/src/base/nsCaretAccessible.cpp
+++ b/accessible/src/base/nsCaretAccessible.cpp
@@ -287,22 +287,22 @@ nsCaretAccessible::SpellcheckSelectionCh
   // @spellcheck="false" on html:body) then we won't fire any event.
 
   nsCOMPtr<nsIAccessibleText> textAcc =
     nsAccUtils::GetTextAccessibleFromSelection(aSel);
   NS_ENSURE_STATE(textAcc);
 
   nsCOMPtr<nsIAccessible> acc(do_QueryInterface(textAcc));
 
-  nsCOMPtr<nsIAccessibleEvent> event =
+  nsRefPtr<nsAccEvent> event =
     new nsAccEvent(nsIAccessibleEvent::EVENT_TEXT_ATTRIBUTE_CHANGED,
                    acc, nsnull);
-  NS_ENSURE_TRUE(event, NS_ERROR_OUT_OF_MEMORY);
 
-  return mRootAccessible->FireAccessibleEvent(event);
+  nsEventShell::FireEvent(event);
+  return NS_OK;
 }
 
 nsIntRect
 nsCaretAccessible::GetCaretRect(nsIWidget **aOutWidget)
 {
   nsIntRect caretRect;
   NS_ENSURE_TRUE(aOutWidget, caretRect);
   *aOutWidget = nsnull;
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -33,17 +33,17 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsRootAccessible.h"
 #include "nsAccessibilityAtoms.h"
-#include "nsAccessibleEventData.h"
+#include "nsAccEvent.h"
 #include "nsAccessibilityService.h"
 #include "nsIMutableArray.h"
 #include "nsICommandManager.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocument.h"
 #include "nsIDOMAttr.h"
 #include "nsIDOMCharacterData.h"
@@ -886,50 +886,50 @@ nsDocAccessible::FireDocLoadEvents(PRUin
     // Fire STATE_CHANGE event for doc load finish if focus is in same doc tree
     if (gLastFocusedNode) {
       nsCOMPtr<nsIDocShellTreeItem> focusedTreeItem =
         nsCoreUtils::GetDocShellTreeItemFor(gLastFocusedNode);
       if (focusedTreeItem) {
         nsCOMPtr<nsIDocShellTreeItem> sameTypeRootOfFocus;
         focusedTreeItem->GetSameTypeRootTreeItem(getter_AddRefs(sameTypeRootOfFocus));
         if (sameTypeRoot == sameTypeRootOfFocus) {
-          nsCOMPtr<nsIAccessibleEvent> accEvent =
+          nsRefPtr<nsAccEvent> accEvent =
             new nsAccStateChangeEvent(this, nsIAccessibleStates::STATE_BUSY, PR_FALSE, PR_FALSE);
-          FireAccessibleEvent(accEvent);
+          nsEventShell::FireEvent(accEvent);
         }
       }
     }
   }
 
   if (sameTypeRoot == treeItem) {
     // Not a frame or iframe
     if (!isFinished) {
       // Fire state change event to set STATE_BUSY when document is loading. For
       // example, Window-Eyes expects to get it.
-      nsCOMPtr<nsIAccessibleEvent> accEvent =
+      nsRefPtr<nsAccEvent> accEvent =
         new nsAccStateChangeEvent(this, nsIAccessibleStates::STATE_BUSY,
                                   PR_FALSE, PR_TRUE);
-      FireAccessibleEvent(accEvent);
+      nsEventShell::FireEvent(accEvent);
     }
 
-    nsAccUtils::FireAccEvent(aEventType, this);
+    nsEventShell::FireEvent(aEventType, this);
   }
 }
 
 void nsDocAccessible::ScrollTimerCallback(nsITimer *aTimer, void *aClosure)
 {
   nsDocAccessible *docAcc = reinterpret_cast<nsDocAccessible*>(aClosure);
 
   if (docAcc && docAcc->mScrollPositionChangedTicks &&
       ++docAcc->mScrollPositionChangedTicks > 2) {
     // Whenever scroll position changes, mScrollPositionChangeTicks gets reset to 1
     // We only want to fire accessibilty scroll event when scrolling stops or pauses
     // Therefore, we wait for no scroll events to occur between 2 ticks of this timer
     // That indicates a pause in scrolling, so we fire the accessibilty scroll event
-    nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_SCROLLING_END, docAcc);
+    nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_SCROLLING_END, docAcc);
 
     docAcc->mScrollPositionChangedTicks = 0;
     if (docAcc->mScrollWatchTimer) {
       docAcc->mScrollWatchTimer->Cancel();
       docAcc->mScrollWatchTimer = nsnull;
       NS_RELEASE(docAcc); // Release kung fu death grip
     }
   }
@@ -993,20 +993,20 @@ NS_IMETHODIMP nsDocAccessible::ScrollPos
 ////////////////////////////////////////////////////////////////////////////////
 // nsIObserver
 
 NS_IMETHODIMP nsDocAccessible::Observe(nsISupports *aSubject, const char *aTopic,
                                        const PRUnichar *aData)
 {
   if (!nsCRT::strcmp(aTopic,"obs_documentCreated")) {    
     // State editable will now be set, readonly is now clear
-    nsCOMPtr<nsIAccessibleEvent> event =
+    nsRefPtr<nsAccEvent> event =
       new nsAccStateChangeEvent(this, nsIAccessibleStates::EXT_STATE_EDITABLE,
                                 PR_TRUE, PR_TRUE);
-    FireAccessibleEvent(event);
+    nsEventShell::FireEvent(event);
   }
 
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsIDocumentObserver
 
@@ -1500,27 +1500,27 @@ nsDocAccessible::FireTextChangeEventForT
     if (NS_FAILED(rv))
       return;
 
     rv = textAccessible->ContentToRenderedOffset(frame, start + length,
                                                  &renderedEndOffset);
     if (NS_FAILED(rv))
       return;
 
-    nsCOMPtr<nsIAccessibleEvent> event =
+    nsRefPtr<nsAccEvent> event =
       new nsAccTextChangeEvent(accessible, offset,
                                renderedEndOffset - renderedStartOffset,
                                aIsInserted, PR_FALSE);
-    textAccessible->FireAccessibleEvent(event);
+    nsEventShell::FireEvent(event);
 
     FireValueChangeForTextFields(accessible);
   }
 }
 
-already_AddRefed<nsIAccessibleEvent>
+already_AddRefed<nsAccEvent>
 nsDocAccessible::CreateTextChangeEventForNode(nsIAccessible *aContainerAccessible,
                                               nsIDOMNode *aChangeNode,
                                               nsIAccessible *aAccessibleForChangeNode,
                                               PRBool aIsInserting,
                                               PRBool aIsAsynch)
 {
   nsRefPtr<nsHyperTextAccessible> textAccessible;
   aContainerAccessible->QueryInterface(NS_GET_IID(nsHyperTextAccessible),
@@ -1580,18 +1580,19 @@ nsDocAccessible::CreateTextChangeEventFo
       }
     }
   }
 
   if (length <= 0) {
     return nsnull;
   }
 
-  nsIAccessibleEvent *event =
-    new nsAccTextChangeEvent(aContainerAccessible, offset, length, aIsInserting, aIsAsynch);
+  nsAccEvent *event =
+    new nsAccTextChangeEvent(aContainerAccessible, offset, length, aIsInserting,
+                             aIsAsynch);
   NS_IF_ADDREF(event);
 
   return event;
 }
 
 // nsDocAccessible public member
 nsresult
 nsDocAccessible::FireDelayedAccessibleEvent(PRUint32 aEventType,
@@ -1748,24 +1749,24 @@ nsDocAccessible::FlushPendingEvents()
       }
 
       // Also fire text changes if the node being created could affect the text in an nsIAccessibleText parent.
       // When a node is being made visible or is inserted, the text in an ancestor hyper text will gain characters
       // At this point we now have the frame and accessible for this node if there is one. That is why we
       // wait to fire this here, instead of in InvalidateCacheSubtree(), where we wouldn't be able to calculate
       // the offset, length and text for the text change.
       if (domNode && domNode != mDOMNode) {
-        nsCOMPtr<nsIAccessibleEvent> textChangeEvent =
+        nsRefPtr<nsAccEvent> textChangeEvent =
           CreateTextChangeEventForNode(containerAccessible, domNode, accessible, PR_TRUE, PR_TRUE);
         if (textChangeEvent) {
           nsAccEvent::PrepareForEvent(textChangeEvent, isFromUserInput);
           // XXX Queue them up and merge the text change events
           // XXX We need a way to ignore SplitNode and JoinNode() when they
           // do not affect the text within the hypertext
-          FireAccessibleEvent(textChangeEvent);
+          nsEventShell::FireEvent(textChangeEvent);
         }
       }
 
       // Fire show/create events for this node or first accessible descendants of it
       FireShowHideEvents(domNode, PR_FALSE, eventType, eNormalEvent, isAsync,
                          isFromUserInput); 
       continue;
     }
@@ -1788,49 +1789,49 @@ nsDocAccessible::FlushPendingEvents()
           accessibleText->GetCharacterAtOffset(caretOffset, &chAtOffset);
           printf("\nCaret moved to %d with char %c", caretOffset, chAtOffset);
 #endif
 #ifdef DEBUG_CARET
           // Test caret line # -- fire an EVENT_ALERT on the focused node so we can watch the
           // line-number object attribute on it
           nsCOMPtr<nsIAccessible> accForFocus;
           GetAccService()->GetAccessibleFor(gLastFocusedNode, getter_AddRefs(accForFocus));
-          nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_ALERT, accForFocus);
+          nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_ALERT, accForFocus);
 #endif
-          nsCOMPtr<nsIAccessibleEvent> caretMoveEvent =
+          nsRefPtr<nsAccEvent> caretMoveEvent =
             new nsAccCaretMoveEvent(accessible, caretOffset);
           if (!caretMoveEvent)
             break; // Out of memory, break out to release kung fu death grip
 
-          FireAccessibleEvent(caretMoveEvent);
+          nsEventShell::FireEvent(caretMoveEvent);
 
           PRInt32 selectionCount;
           accessibleText->GetSelectionCount(&selectionCount);
           if (selectionCount) {  // There's a selection so fire selection change as well
-            nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_TEXT_SELECTION_CHANGED,
-                                     accessible, PR_TRUE);
+            nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_TEXT_SELECTION_CHANGED,
+                                    accessible, PR_TRUE);
           }
         } 
       }
       else if (eventType == nsIAccessibleEvent::EVENT_REORDER) {
         // Fire reorder event if it's unconditional (see InvalidateCacheSubtree
         // method) or if changed node (that is the reason of this reorder event)
         // is accessible or has accessible children.
         nsCOMPtr<nsAccReorderEvent> reorderEvent = do_QueryInterface(accEvent);
         if (reorderEvent->IsUnconditionalEvent() ||
             reorderEvent->HasAccessibleInReasonSubtree()) {
           nsAccEvent::PrepareForEvent(accEvent);
-          FireAccessibleEvent(accEvent);
+          nsEventShell::FireEvent(accEvent);
         }
       }
       else {
         // The input state was previously stored with the nsIAccessibleEvent,
         // so use that state now when firing the event
         nsAccEvent::PrepareForEvent(accEvent);
-        FireAccessibleEvent(accEvent);
+        nsEventShell::FireEvent(accEvent);
         // Post event processing
         if (eventType == nsIAccessibleEvent::EVENT_HIDE) {
           // Shutdown nsIAccessNode's or nsIAccessibles for any DOM nodes in
           // this subtree.
           nsCOMPtr<nsIDOMNode> hidingNode;
           accEvent->GetDOMNode(getter_AddRefs(hidingNode));
           if (hidingNode) {
             RefreshNodes(hidingNode); // Will this bite us with asynch events
@@ -1905,18 +1906,18 @@ void nsDocAccessible::RefreshNodes(nsIDO
     PRUint32 role = nsAccUtils::Role(accessible);
     if (role == nsIAccessibleRole::ROLE_MENUPOPUP) {
       nsCOMPtr<nsIDOMNode> domNode;
       accessNode->GetDOMNode(getter_AddRefs(domNode));
       nsCOMPtr<nsIDOMXULPopupElement> popup(do_QueryInterface(domNode));
       if (!popup) {
         // Popup elements already fire these via DOMMenuInactive
         // handling in nsRootAccessible::HandleEvent
-        nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_MENUPOPUP_END,
-                                 accessible);
+        nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_MENUPOPUP_END,
+                                accessible);
       }
     }
     nsRefPtr<nsAccessible> acc = nsAccUtils::QueryAccessible(accessible);
 
     // We only need to shutdown the accessibles here if one of them has been
     // created.
     if (acc->GetCachedFirstChild()) {
       nsCOMPtr<nsIArray> children;
@@ -2108,21 +2109,21 @@ nsDocAccessible::InvalidateCacheSubtree(
     NS_ENSURE_SUCCESS(rv,);
 
     if (childNode != mDOMNode) { // Fire text change unless the node being removed is for this doc
       // When a node is hidden or removed, the text in an ancestor hyper text will lose characters
       // At this point we still have the frame and accessible for this node if there was one
       // XXX Collate events when a range is deleted
       // XXX We need a way to ignore SplitNode and JoinNode() when they
       // do not affect the text within the hypertext
-      nsCOMPtr<nsIAccessibleEvent> textChangeEvent =
+      nsRefPtr<nsAccEvent> textChangeEvent =
         CreateTextChangeEventForNode(containerAccessible, childNode, childAccessible,
                                      PR_FALSE, isAsynch);
       if (textChangeEvent) {
-        FireAccessibleEvent(textChangeEvent);
+        nsEventShell::FireEvent(textChangeEvent);
       }
     }
   }
 
   // We need to get an accessible for the mutation event's container node
   // If there is no accessible for that node, we need to keep moving up the parent
   // chain so there is some accessible.
   // We will use this accessible to fire the accessible mutation event.
@@ -2268,29 +2269,30 @@ nsDocAccessible::FireShowHideEvents(nsID
       GetAccService()->GetAttachedAccessibleFor(aDOMNode,
                                                 getter_AddRefs(accessible));
     }
   }
 
   if (accessible) {
     // Found an accessible, so fire the show/hide on it and don't look further
     // into this subtree.
-    nsCOMPtr<nsIAccessibleEvent> event =
+    nsRefPtr<nsAccEvent> event =
       new nsAccEvent(aEventType, accessible, aIsAsyncChange,
                      nsAccEvent::eCoalesceFromSameSubtree);
     NS_ENSURE_TRUE(event, NS_ERROR_OUT_OF_MEMORY);
 
     if (aForceIsFromUserInput) {
       nsAccEvent::PrepareForEvent(event, aForceIsFromUserInput);
     }
 
     if (aDelayedOrNormal == eDelayedEvent)
       return FireDelayedAccessibleEvent(event);
 
-    return FireAccessibleEvent(event);
+    nsEventShell::FireEvent(event);
+    return NS_OK;
   }
 
   // Could not find accessible to show hide yet, so fire on any
   // accessible descendants in this subtree
   nsCOMPtr<nsINode> node(do_QueryInterface(aDOMNode));
   PRUint32 count = node->GetChildCount();
   for (PRUint32 index = 0; index < count; index++) {
     nsCOMPtr<nsIDOMNode> childNode = do_QueryInterface(node->GetChildAt(index));
--- a/accessible/src/base/nsDocAccessible.h
+++ b/accessible/src/base/nsDocAccessible.h
@@ -238,17 +238,17 @@ protected:
 
     /**
      * Create a text change event for a changed node
      * @param aContainerAccessible, the first accessible in the container
      * @param aChangeNode, the node that is being inserted or removed, or shown/hidden
      * @param aAccessibleForChangeNode, the accessible for that node, or nsnull if none exists
      * @param aIsInserting, is aChangeNode being created or shown (vs. removed or hidden)
      */
-    already_AddRefed<nsIAccessibleEvent>
+    already_AddRefed<nsAccEvent>
     CreateTextChangeEventForNode(nsIAccessible *aContainerAccessible,
                                  nsIDOMNode *aChangeNode,
                                  nsIAccessible *aAccessibleForNode,
                                  PRBool aIsInserting,
                                  PRBool aIsAsynch);
 
   /**
    * Used to define should the event be fired on a delay.
new file mode 100644
--- /dev/null
+++ b/accessible/src/base/nsEventShell.cpp
@@ -0,0 +1,66 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Alexander Surkov <surkov.alexander@gmail.com> (original author)
+ *
+ * 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 "nsEventShell.h"
+
+#include "nsAccessible.h"
+
+void
+nsEventShell::FireEvent(nsAccEvent *aEvent)
+{
+  if (!aEvent)
+    return;
+
+  nsRefPtr<nsAccessible> acc =
+    nsAccUtils::QueryObject<nsAccessible>(aEvent->GetAccessible());
+  NS_ENSURE_TRUE(acc,);
+
+  acc->HandleAccEvent(aEvent);
+}
+
+void
+nsEventShell::FireEvent(PRUint32 aEventType, nsIAccessible *aAccessible,
+                        PRBool aIsAsynch)
+{
+  NS_ENSURE_TRUE(aAccessible,);
+
+  nsRefPtr<nsAccEvent> event = new nsAccEvent(aEventType, aAccessible,
+                                              aIsAsynch);
+
+  FireEvent(event);
+}
new file mode 100644
--- /dev/null
+++ b/accessible/src/base/nsEventShell.h
@@ -0,0 +1,65 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Alexander Surkov <surkov.alexander@gmail.com> (original author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of the GNU General Public License Version 2 or later (the "GPL"),
+ * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef _nsEventShell_H_
+#define _nsEventShell_H_
+
+#include "nsAccEvent.h"
+
+class nsEventShell
+{
+public:
+
+  /**
+   * Fire the accessible event.
+   */
+  static void FireEvent(nsAccEvent *aEvent);
+
+  /**
+   * Fire accessible event of the given type for the given accessible.
+   *
+   * @param  aEventType   [in] the event type
+   * @param  aAccessible  [in] the event target
+   * @param  aIsAsync     [in, optional] specifies whether the origin change
+   *                        this event is fired owing to is async.
+   */
+  static void FireEvent(PRUint32 aEventType, nsIAccessible *aAccessible,
+                        PRBool aIsAsynch = PR_FALSE);
+};
+
+#endif
--- a/accessible/src/base/nsRootAccessible.cpp
+++ b/accessible/src/base/nsRootAccessible.cpp
@@ -32,17 +32,17 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 // NOTE: alphabetically ordered
 #include "nsAccessibilityService.h"
-#include "nsAccessibleEventData.h"
+#include "nsAccEvent.h"
 #include "nsApplicationAccessibleWrap.h"
 
 #include "nsHTMLSelectAccessible.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocShellTreeNode.h"
 #include "nsIDocShellTreeOwner.h"
 #include "nsIDOMDocument.h"
@@ -474,18 +474,18 @@ nsRootAccessible::FireAccessibleFocusEve
       if (role != naturalRole) { // Must be a DHTML menuitem
         nsCOMPtr<nsIAccessible> menuBarAccessible =
           nsAccUtils::GetAncestorWithRole(finalFocusAccessible,
                                           nsIAccessibleRole::ROLE_MENUBAR);
         nsCOMPtr<nsIAccessNode> menuBarAccessNode = do_QueryInterface(menuBarAccessible);
         if (menuBarAccessNode) {
           menuBarAccessNode->GetDOMNode(getter_AddRefs(mCurrentARIAMenubar));
           if (mCurrentARIAMenubar) {
-            nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_MENU_START,
-                                     menuBarAccessible);
+            nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_MENU_START,
+                                    menuBarAccessible);
           }
         }
       }
     }
   }
   else if (mCurrentARIAMenubar) {
     nsCOMPtr<nsIAccessibleEvent> menuEndEvent =
       new nsAccEvent(nsIAccessibleEvent::EVENT_MENU_END, mCurrentARIAMenubar,
@@ -676,38 +676,39 @@ nsresult nsRootAccessible::HandleEventWi
 
     // radiogroup in prefWindow is exposed as a list,
     // and panebutton is exposed as XULListitem in A11y.
     // nsXULListitemAccessible::GetStateInternal uses STATE_SELECTED in this case,
     // so we need to check nsIAccessibleStates::STATE_SELECTED also.
     PRBool isEnabled = (state & (nsIAccessibleStates::STATE_CHECKED |
                         nsIAccessibleStates::STATE_SELECTED)) != 0;
 
-    nsCOMPtr<nsIAccessibleEvent> accEvent =
+    nsRefPtr<nsAccEvent> accEvent =
       new nsAccStateChangeEvent(accessible, nsIAccessibleStates::STATE_CHECKED,
                                 PR_FALSE, isEnabled);
-    acc->FireAccessibleEvent(accEvent);
+    nsEventShell::FireEvent(accEvent);
 
     if (isEnabled)
       FireAccessibleFocusEvent(accessible, aTargetNode, aEvent);
 
     return NS_OK;
   }
 
   if (eventType.EqualsLiteral("CheckboxStateChange")) {
     PRUint32 state = nsAccUtils::State(accessible);
 
     PRBool isEnabled = !!(state & nsIAccessibleStates::STATE_CHECKED);
 
-    nsCOMPtr<nsIAccessibleEvent> accEvent =
+    nsRefPtr<nsAccEvent> accEvent =
       new nsAccStateChangeEvent(accessible,
                                 nsIAccessibleStates::STATE_CHECKED,
                                 PR_FALSE, isEnabled);
 
-    return acc->FireAccessibleEvent(accEvent);
+    nsEventShell::FireEvent(accEvent);
+    return NS_OK;
   }
 
   nsCOMPtr<nsIAccessible> treeItemAccessible;
 #ifdef MOZ_XUL
   // If it's a tree element, need the currently selected item
   if (isTree) {
     nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelect =
       do_QueryInterface(aTargetNode);
@@ -728,40 +729,43 @@ nsresult nsRootAccessible::HandleEventWi
   }
 #endif
 
 #ifdef MOZ_XUL
   if (treeItemAccessible && eventType.EqualsLiteral("OpenStateChange")) {
     PRUint32 state = nsAccUtils::State(accessible); // collapsed/expanded changed
     PRBool isEnabled = (state & nsIAccessibleStates::STATE_EXPANDED) != 0;
 
-    nsCOMPtr<nsIAccessibleEvent> accEvent =
+    nsRefPtr<nsAccEvent> accEvent =
       new nsAccStateChangeEvent(accessible, nsIAccessibleStates::STATE_EXPANDED,
                                 PR_FALSE, isEnabled);
-    return FireAccessibleEvent(accEvent);
+    nsEventShell::FireEvent(accEvent);
+    return NS_OK;
   }
 
   if (treeItemAccessible && eventType.EqualsLiteral("select")) {
     // If multiselect tree, we should fire selectionadd or selection removed
     if (gLastFocusedNode == aTargetNode) {
       nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSel =
         do_QueryInterface(aTargetNode);
       nsAutoString selType;
       multiSel->GetSelType(selType);
       if (selType.IsEmpty() || !selType.EqualsLiteral("single")) {
         // XXX: We need to fire EVENT_SELECTION_ADD and EVENT_SELECTION_REMOVE
         // for each tree item. Perhaps each tree item will need to cache its
         // selection state and fire an event after a DOM "select" event when
         // that state changes. nsXULTreeAccessible::UpdateTreeSelection();
-        return nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_SELECTION_WITHIN,
-                                        accessible);
+        nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_SELECTION_WITHIN,
+                                accessible);
+        return NS_OK;
       }
 
-      return nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_SELECTION,
-                                      treeItemAccessible);
+      nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_SELECTION,
+                              treeItemAccessible);
+      return NS_OK;
     }
   }
   else
 #endif
   if (eventType.EqualsLiteral("focus")) {
     if (aTargetNode == mDOMNode && mDOMNode != gLastFocusedNode) {
       // Got focus event for the window, we will make sure that an accessible
       // focus event for initial focus is fired. We do this on a short timer
@@ -802,25 +806,25 @@ nsresult nsRootAccessible::HandleEventWi
           if (!accessible)
             return NS_OK;
         }
       }
     }
     FireAccessibleFocusEvent(accessible, focusedItem, aEvent);
   }
   else if (eventType.EqualsLiteral("AlertActive")) { 
-    nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_ALERT, accessible);
+    nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_ALERT, accessible);
   }
   else if (eventType.EqualsLiteral("popupshown")) {
     HandlePopupShownEvent(accessible);
   }
   else if (eventType.EqualsLiteral("DOMMenuInactive")) {
     if (nsAccUtils::Role(accessible) == nsIAccessibleRole::ROLE_MENUPOPUP) {
-      nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_MENUPOPUP_END,
-                               accessible);
+      nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_MENUPOPUP_END,
+                              accessible);
     }
   }
   else if (eventType.EqualsLiteral("DOMMenuItemActive")) {
     PRBool fireFocus = PR_FALSE;
     if (!treeItemAccessible) {
 #ifdef MOZ_XUL
       if (isTree) {
         return NS_OK; // Tree with nothing selected
@@ -876,33 +880,33 @@ nsresult nsRootAccessible::HandleEventWi
     }
     if (fireFocus) {
       nsAccEvent::PrepareForEvent(aTargetNode, PR_TRUE);  // Always asynch, always from user input
       FireAccessibleFocusEvent(accessible, aTargetNode, aEvent, PR_TRUE, PR_TRUE);
     }
   }
   else if (eventType.EqualsLiteral("DOMMenuBarActive")) {  // Always asynch, always from user input
     nsAccEvent::PrepareForEvent(aTargetNode, PR_TRUE);
-    nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_MENU_START,
-                             accessible, PR_TRUE);
+    nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_MENU_START,
+                            accessible, PR_TRUE);
   }
   else if (eventType.EqualsLiteral("DOMMenuBarInactive")) {  // Always asynch, always from user input
     nsAccEvent::PrepareForEvent(aTargetNode, PR_TRUE);
-    nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_MENU_END,
-                             accessible, PR_TRUE);
+    nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_MENU_END,
+                            accessible, PR_TRUE);
     FireCurrentFocusEvent();
   }
   else if (eventType.EqualsLiteral("ValueChange")) {
     FireDelayedAccessibleEvent(nsIAccessibleEvent::EVENT_VALUE_CHANGE,
                                aTargetNode, nsAccEvent::eRemoveDupes);
   }
 #ifdef DEBUG
   else if (eventType.EqualsLiteral("mouseover")) {
-    nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_DRAGDROP_START,
-                             accessible);
+    nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_DRAGDROP_START,
+                            accessible);
   }
 #endif
   return NS_OK;
 }
 
 void nsRootAccessible::GetTargetNode(nsIDOMEvent *aEvent, nsIDOMNode **aTargetNode)
 {
   *aTargetNode = nsnull;
@@ -1098,46 +1102,48 @@ nsRootAccessible::FireDocLoadEvents(PRUi
 
 nsresult
 nsRootAccessible::HandlePopupShownEvent(nsIAccessible *aAccessible)
 {
   PRUint32 role = nsAccUtils::Role(aAccessible);
 
   if (role == nsIAccessibleRole::ROLE_MENUPOPUP) {
     // Don't fire menupopup events for combobox and autocomplete lists.
-    return nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_MENUPOPUP_START,
-                                    aAccessible);
+    nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_MENUPOPUP_START,
+                            aAccessible);
+    return NS_OK;
   }
 
   if (role == nsIAccessibleRole::ROLE_TOOLTIP) {
     // There is a single <xul:tooltip> node which Mozilla moves around.
     // The accessible for it stays the same no matter where it moves. 
     // AT's expect to get an EVENT_SHOW for the tooltip. 
     // In event callback the tooltip's accessible will be ready.
-    return nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_SHOW,
-                                    aAccessible);
+    nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_SHOW, aAccessible);
+    return NS_OK;
   }
 
   if (role == nsIAccessibleRole::ROLE_COMBOBOX_LIST) {
     // Fire expanded state change event for comboboxes and autocompeletes.
     nsCOMPtr<nsIAccessible> comboboxAcc;
     nsresult rv = aAccessible->GetParent(getter_AddRefs(comboboxAcc));
     NS_ENSURE_SUCCESS(rv, rv);
 
     PRUint32 comboboxRole = nsAccUtils::Role(comboboxAcc);
     if (comboboxRole == nsIAccessibleRole::ROLE_COMBOBOX ||
         comboboxRole == nsIAccessibleRole::ROLE_AUTOCOMPLETE) {
-      nsCOMPtr<nsIAccessibleEvent> event =
+      nsRefPtr<nsAccEvent> event =
         new nsAccStateChangeEvent(comboboxAcc,
                                   nsIAccessibleStates::STATE_EXPANDED,
                                   PR_FALSE, PR_TRUE);
       NS_ENSURE_TRUE(event, NS_ERROR_OUT_OF_MEMORY);
 
       nsRefPtr<nsAccessible> acc(nsAccUtils::QueryAccessible(comboboxAcc));
-      return acc->FireAccessibleEvent(event);
+      nsEventShell::FireEvent(event);
+      return NS_OK;
     }
   }
 
   return NS_OK;
 }
 
 nsresult
 nsRootAccessible::HandlePopupHidingEvent(nsIDOMNode *aNode,
@@ -1164,24 +1170,25 @@ nsRootAccessible::HandlePopupHidingEvent
 
   nsCOMPtr<nsIAccessible> comboboxAcc;
   nsresult rv = aAccessible->GetParent(getter_AddRefs(comboboxAcc));
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRUint32 comboboxRole = nsAccUtils::Role(comboboxAcc);
   if (comboboxRole == nsIAccessibleRole::ROLE_COMBOBOX ||
       comboboxRole == nsIAccessibleRole::ROLE_AUTOCOMPLETE) {
-    nsCOMPtr<nsIAccessibleEvent> event =
+    nsRefPtr<nsAccEvent> event =
       new nsAccStateChangeEvent(comboboxAcc,
                                 nsIAccessibleStates::STATE_EXPANDED,
                                 PR_FALSE, PR_FALSE);
     NS_ENSURE_TRUE(event, NS_ERROR_OUT_OF_MEMORY);
 
     nsRefPtr<nsAccessible> acc(nsAccUtils::QueryAccessible(comboboxAcc));
-    return acc->FireAccessibleEvent(event);
+    nsEventShell::FireEvent(event);
+    return NS_OK;
   }
 
   return NS_OK;
 }
 
 #ifdef MOZ_XUL
 nsresult
 nsRootAccessible::HandleTreeRowCountChangedEvent(nsIDOMEvent *aEvent,
--- a/accessible/src/html/nsHTMLSelectAccessible.cpp
+++ b/accessible/src/html/nsHTMLSelectAccessible.cpp
@@ -806,29 +806,29 @@ void nsHTMLSelectOptionAccessible::Selec
     return;
 
   nsCOMPtr<nsIAccessible> optionAccessible;
   GetAccService()->GetAccessibleFor(optionNode,
                                     getter_AddRefs(optionAccessible));
   if (!optionAccessible)
     return;
 
-  nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_SELECTION_WITHIN,
-                           multiSelect);
+  nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_SELECTION_WITHIN,
+                          multiSelect);
 
   PRUint32 state = nsAccUtils::State(optionAccessible);
   PRUint32 eventType;
   if (state & nsIAccessibleStates::STATE_SELECTED) {
     eventType = nsIAccessibleEvent::EVENT_SELECTION_ADD;
   }
   else {
     eventType = nsIAccessibleEvent::EVENT_SELECTION_REMOVE;
   }
 
-  nsAccUtils::FireAccEvent(eventType, optionAccessible);
+  nsEventShell::FireEvent(eventType, optionAccessible);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLSelectOptionAccessible: private methods
 
 nsIContent* nsHTMLSelectOptionAccessible::GetSelectState(PRUint32* aState,
                                                          PRUint32* aExtraState)
 {
--- a/accessible/src/html/nsHyperTextAccessible.h
+++ b/accessible/src/html/nsHyperTextAccessible.h
@@ -39,17 +39,17 @@
 
 #ifndef _nsHyperTextAccessible_H_
 #define _nsHyperTextAccessible_H_
 
 #include "nsAccessibleWrap.h"
 #include "nsIAccessibleText.h"
 #include "nsIAccessibleHyperText.h"
 #include "nsIAccessibleEditableText.h"
-#include "nsAccessibleEventData.h"
+#include "nsAccEvent.h"
 #include "nsTextAttrs.h"
 
 #include "nsFrameSelection.h"
 #include "nsISelectionController.h"
 
 enum EGetTextType { eGetBefore=-1, eGetAt=0, eGetAfter=1 };
 
 // This character marks where in the text returned via nsIAccessibleText(),
--- a/accessible/src/mac/nsAccessibleWrap.h
+++ b/accessible/src/mac/nsAccessibleWrap.h
@@ -72,17 +72,17 @@ class nsAccessibleWrap : public nsAccess
     virtual objc_class* GetNativeType ();
     
     // returns a pointer to the native window for this accessible tree.
     void GetNativeWindow (void **aOutNativeWindow);
     
     virtual nsresult Shutdown ();
     virtual void InvalidateChildren();
 
-    virtual nsresult FireAccessibleEvent(nsIAccessibleEvent *aEvent);
+    virtual nsresult HandleAccEvent(nsAccEvent *aEvent);
 
     // 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 () {
@@ -92,17 +92,17 @@ class nsAccessibleWrap : public nsAccess
     }
     
     // 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:
 
-    virtual nsresult FirePlatformEvent(nsIAccessibleEvent *aEvent);
+    virtual nsresult FirePlatformEvent(nsAccEvent *aEvent);
 
     PRBool AncestorIsFlat() {
       // we don't create a native object if we're child of a "flat" accessible; for example, on OS X buttons 
       // shouldn't have any children, because that makes the OS confused. 
       //
       // to maintain a scripting environment where the XPCOM accessible hierarchy look the same 
       // on all platforms, we still let the C++ objects be created though.
 
--- a/accessible/src/mac/nsAccessibleWrap.mm
+++ b/accessible/src/mac/nsAccessibleWrap.mm
@@ -155,46 +155,42 @@ nsAccessibleWrap::Shutdown ()
     delete mNativeWrapper;
     mNativeWrapper = nsnull;
   }
   
   return nsAccessible::Shutdown();
 }
 
 nsresult
-nsAccessibleWrap::FireAccessibleEvent(nsIAccessibleEvent *aEvent)
+nsAccessibleWrap::HandleAccEvent(nsAccEvent *aEvent)
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT;
 
-  NS_ENSURE_ARG_POINTER(aEvent);
-
-  nsresult rv = nsAccessible::FireAccessibleEvent(aEvent);
+  nsresult rv = nsAccessible::HandleAccEvent(aEvent);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return FirePlatformEvent(aEvent);
 
   NS_OBJC_END_TRY_ABORT_BLOCK_NSRESULT;
 }
 
 nsresult
-nsAccessibleWrap::FirePlatformEvent(nsIAccessibleEvent *aEvent)
+nsAccessibleWrap::FirePlatformEvent(nsAccEvent *aEvent)
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT;
 
-  PRUint32 eventType;
-  nsresult rv = aEvent->GetEventType(&eventType);
-  NS_ENSURE_SUCCESS(rv, rv);
+  PRUint32 eventType = aEvent->GetEventType();
 
   // ignore everything but focus-changed and value-changed events for now.
   if (eventType != nsIAccessibleEvent::EVENT_FOCUS &&
       eventType != nsIAccessibleEvent::EVENT_VALUE_CHANGE)
     return NS_OK;
 
   nsCOMPtr<nsIAccessible> accessible;
-  rv = aEvent->GetAccessible(getter_AddRefs(accessible));
+  nsresult rv = aEvent->GetAccessible(getter_AddRefs(accessible));
   NS_ENSURE_STATE(accessible);
 
   mozAccessible *nativeAcc = nil;
   accessible->GetNativeInterface((void**)&nativeAcc);
   if (!nativeAcc)
     return NS_ERROR_FAILURE;
 
   switch (eventType) {
--- a/accessible/src/msaa/nsAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsAccessibleWrap.cpp
@@ -1651,31 +1651,28 @@ NS_IMETHODIMP nsAccessibleWrap::GetNativ
   *aOutAccessible = static_cast<IAccessible*>(this);
   NS_ADDREF_THIS();
   return NS_OK;
 }
 
 // nsAccessible
 
 nsresult
-nsAccessibleWrap::FireAccessibleEvent(nsIAccessibleEvent *aEvent)
+nsAccessibleWrap::HandleAccEvent(nsAccEvent *aEvent)
 {
-  NS_ENSURE_ARG(aEvent);
-
-  nsresult rv = nsAccessible::FireAccessibleEvent(aEvent);
+  nsresult rv = nsAccessible::HandleAccEvent(aEvent);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return FirePlatformEvent(aEvent);
 }
 
 nsresult
-nsAccessibleWrap::FirePlatformEvent(nsIAccessibleEvent *aEvent)
+nsAccessibleWrap::FirePlatformEvent(nsAccEvent *aEvent)
 {
-  PRUint32 eventType = 0;
-  aEvent->GetEventType(&eventType);
+  PRUint32 eventType = aEvent->GetEventType();
 
   NS_ENSURE_TRUE(eventType > 0 &&
                  eventType < nsIAccessibleEvent::EVENT_LAST_ENTRY,
                  NS_ERROR_FAILURE);
 
   PRUint32 winLastEntry = gWinEventMap[nsIAccessibleEvent::EVENT_LAST_ENTRY];
   NS_ASSERTION(winLastEntry == kEVENT_LAST_ENTRY,
                "MSAA event map skewed");
--- a/accessible/src/msaa/nsAccessibleWrap.h
+++ b/accessible/src/msaa/nsAccessibleWrap.h
@@ -302,17 +302,17 @@ class nsAccessibleWrap : public nsAccess
   virtual HRESULT STDMETHODCALLTYPE Invoke(DISPID dispIdMember, REFIID riid,
                                            LCID lcid, WORD wFlags,
                                            DISPPARAMS *pDispParams,
                                            VARIANT *pVarResult,
                                            EXCEPINFO *pExcepInfo,
                                            UINT *puArgErr);
 
   // nsAccessible
-  virtual nsresult FireAccessibleEvent(nsIAccessibleEvent *aEvent);
+  virtual nsresult HandleAccEvent(nsAccEvent *aEvent);
 
   // Helper methods
   static PRInt32 GetChildIDFor(nsIAccessible* aAccessible);
   static HWND GetHWNDFor(nsIAccessible *aAccessible);
   static HRESULT ConvertToIA2Attributes(nsIPersistentProperties *aAttributes,
                                         BSTR *aIA2Attributes);
 
   /**
@@ -337,17 +337,17 @@ class nsAccessibleWrap : public nsAccess
   /**
    * Drops the IEnumVariant current position so that navigation methods
    * Next() and Skip() doesn't work until Reset() method is called. The method
    * is used when children of the accessible are changed.
    */
   void UnattachIEnumVariant();
 
 protected:
-  virtual nsresult FirePlatformEvent(nsIAccessibleEvent *aEvent);
+  virtual nsresult FirePlatformEvent(nsAccEvent *aEvent);
 
   // mEnumVARIANTPosition not the current accessible's position, but a "cursor" of 
   // where we are in the current list of children, with respect to
   // nsIEnumVariant::Reset(), Skip() and Next().
   PRInt32 mEnumVARIANTPosition;
 
   /**
    * Creates ITypeInfo for LIBID_Accessibility if it's needed and returns it.
--- a/accessible/src/msaa/nsHyperTextAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsHyperTextAccessibleWrap.cpp
@@ -44,20 +44,19 @@ NS_IMPL_ISUPPORTS_INHERITED0(nsHyperText
                              nsHyperTextAccessible)
 
 IMPL_IUNKNOWN_INHERITED2(nsHyperTextAccessibleWrap,
                          nsAccessibleWrap,
                          CAccessibleHypertext,
                          CAccessibleEditableText);
 
 nsresult
-nsHyperTextAccessibleWrap::FireAccessibleEvent(nsIAccessibleEvent *aEvent)
+nsHyperTextAccessibleWrap::HandleAccEvent(nsAccEvent *aEvent)
 {
-  PRUint32 eventType;
-  aEvent->GetEventType(&eventType);
+  PRUint32 eventType = aEvent->GetEventType();
 
   if (eventType == nsIAccessibleEvent::EVENT_TEXT_REMOVED ||
       eventType == nsIAccessibleEvent::EVENT_TEXT_INSERTED) {
     nsCOMPtr<nsIAccessible> accessible;
     aEvent->GetAccessible(getter_AddRefs(accessible));
     if (accessible) {
       nsCOMPtr<nsIWinAccessNode> winAccessNode(do_QueryInterface(accessible));
       if (winAccessNode) {
@@ -69,17 +68,17 @@ nsHyperTextAccessibleWrap::FireAccessibl
 
           CallQueryInterface(aEvent, &gTextEvent);
           (static_cast<IUnknown*>(instancePtr))->Release();
         }
       }
     }
   }
 
-  return nsHyperTextAccessible::FireAccessibleEvent(aEvent);
+  return nsHyperTextAccessible::HandleAccEvent(aEvent);
 }
 
 nsresult
 nsHyperTextAccessibleWrap::GetModifiedText(PRBool aGetInsertedText,
                                            nsAString& aText,
                                            PRUint32 *aStartOffset,
                                            PRUint32 *aEndOffset)
 {
--- a/accessible/src/msaa/nsHyperTextAccessibleWrap.h
+++ b/accessible/src/msaa/nsHyperTextAccessibleWrap.h
@@ -56,17 +56,17 @@ public:
 
   // IUnknown
   DECL_IUNKNOWN_INHERITED
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsAccessible
-  virtual nsresult FireAccessibleEvent(nsIAccessibleEvent *aEvent);
+  virtual nsresult HandleAccEvent(nsAccEvent *aEvent);
 
 protected:
   virtual nsresult GetModifiedText(PRBool aGetInsertedText, nsAString& aText,
                                    PRUint32 *aStartOffset,
                                    PRUint32 *aEndOffset);
 };
 
 #endif
--- a/accessible/src/other/nsAccessibleWrap.h
+++ b/accessible/src/other/nsAccessibleWrap.h
@@ -48,14 +48,14 @@
 
 class nsAccessibleWrap : public nsAccessible
 {
   public: // construction, destruction
     nsAccessibleWrap(nsIDOMNode*, nsIWeakReference *aShell);
     virtual ~nsAccessibleWrap();
 
   protected:
-    virtual nsresult FirePlatformEvent(nsIAccessibleEvent *aEvent) {
+    virtual nsresult FirePlatformEvent(nsAccEvent *aEvent) {
       return NS_OK;
     }
 };
 
 #endif
--- a/accessible/src/xul/nsXULTabAccessible.cpp
+++ b/accessible/src/xul/nsXULTabAccessible.cpp
@@ -39,27 +39,29 @@
 // NOTE: alphabetically ordered
 #include "nsXULTabAccessible.h"
 #include "nsIDocument.h"
 #include "nsIFrame.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMXULSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 
-/**
-  * XUL Tab
-  */
+////////////////////////////////////////////////////////////////////////////////
+// nsXULTabAccessible
+////////////////////////////////////////////////////////////////////////////////
 
-/** Constructor */
-nsXULTabAccessible::nsXULTabAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell):
-nsLeafAccessible(aNode, aShell)
-{ 
+nsXULTabAccessible::
+  nsXULTabAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell) :
+  nsAccessibleWrap(aNode, aShell)
+{
 }
 
-/** Only one action available */
+////////////////////////////////////////////////////////////////////////////////
+// nsXULTabAccessible: nsIAccessible
+
 NS_IMETHODIMP nsXULTabAccessible::GetNumActions(PRUint8 *_retval)
 {
   *_retval = 1;
   return NS_OK;
 }
 
 /** Return the name of our only action  */
 NS_IMETHODIMP nsXULTabAccessible::GetActionName(PRUint8 aIndex, nsAString& aName)
@@ -81,32 +83,33 @@ NS_IMETHODIMP nsXULTabAccessible::DoActi
       tab->Click();
       return NS_OK;
     }
     return NS_ERROR_FAILURE;
   }
   return NS_ERROR_INVALID_ARG;
 }
 
-/** We are a tab */
+////////////////////////////////////////////////////////////////////////////////
+// nsXULTabAccessible: nsAccessible
+
 nsresult
 nsXULTabAccessible::GetRoleInternal(PRUint32 *aRole)
 {
   *aRole = nsIAccessibleRole::ROLE_PAGETAB;
   return NS_OK;
 }
 
-/**
-  * Possible states: focused, focusable, unavailable(disabled), offscreen
-  */
 nsresult
 nsXULTabAccessible::GetStateInternal(PRUint32 *aState, PRUint32 *aExtraState)
 {
+  // Possible states: focused, focusable, unavailable(disabled), offscreen.
+
   // get focus and disable status from base class
-  nsresult rv = nsLeafAccessible::GetStateInternal(aState, aExtraState);
+  nsresult rv = nsAccessibleWrap::GetStateInternal(aState, aExtraState);
   NS_ENSURE_A11Y_SUCCESS(rv, rv);
 
   // In the past, tabs have been focusable in classic theme
   // They may be again in the future
   // Check style for -moz-user-focus: normal to see if it's focusable
   *aState &= ~nsIAccessibleStates::STATE_FOCUSABLE;
   nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
   if (content) {
@@ -124,21 +127,22 @@ nsXULTabAccessible::GetStateInternal(PRU
   if (tab) {
     PRBool selected = PR_FALSE;
     if (NS_SUCCEEDED(tab->GetSelected(&selected)) && selected)
       *aState |= nsIAccessibleStates::STATE_SELECTED;
   }
   return NS_OK;
 }
 
+// nsIAccessible
 NS_IMETHODIMP
 nsXULTabAccessible::GetRelationByType(PRUint32 aRelationType,
                                       nsIAccessibleRelation **aRelation)
 {
-  nsresult rv = nsLeafAccessible::GetRelationByType(aRelationType,
+  nsresult rv = nsAccessibleWrap::GetRelationByType(aRelationType,
                                                     aRelation);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (aRelationType != nsIAccessibleRelation::RELATION_LABEL_FOR)
     return NS_OK;
 
   // Expose 'LABEL_FOR' relation on tab accessible for tabpanel accessible.
   // XXX: It makes sense to require the interface from xul:tab to get linked
--- a/accessible/src/xul/nsXULTabAccessible.h
+++ b/accessible/src/xul/nsXULTabAccessible.h
@@ -41,17 +41,17 @@
 
 // NOTE: alphabetically ordered
 #include "nsBaseWidgetAccessible.h"
 #include "nsXULMenuAccessible.h"
 
 /**
  * An individual tab, xul:tab element
  */
-class nsXULTabAccessible : public nsLeafAccessible
+class nsXULTabAccessible : public nsAccessibleWrap
 {
 public:
   enum { eAction_Switch = 0 };
 
   nsXULTabAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell);
 
   // nsIAccessible
   NS_IMETHOD GetNumActions(PRUint8 *_retval);
--- a/accessible/src/xul/nsXULTreeAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeAccessible.cpp
@@ -565,19 +565,19 @@ nsXULTreeAccessible::InvalidateCache(PRI
 
     nsCOMPtr<nsIAccessNode> accessNode;
     GetCacheEntry(mAccessNodeCache, key, getter_AddRefs(accessNode));
 
     if (accessNode) {
       nsRefPtr<nsAccessible> accessible =
         nsAccUtils::QueryAccessible(accessNode);
 
-      nsCOMPtr<nsIAccessibleEvent> event =
+      nsRefPtr<nsAccEvent> event =
         new nsAccEvent(nsIAccessibleEvent::EVENT_HIDE, accessible, PR_FALSE);
-      FireAccessibleEvent(event);
+      nsEventShell::FireEvent(event);
 
       accessible->Shutdown();
 
       // Remove accessible from document cache and tree cache.
       nsCOMPtr<nsIAccessibleDocument> docAccessible = GetDocAccessible();
       if (docAccessible) { 
         nsRefPtr<nsDocAccessible> docAcc =
           nsAccUtils::QueryAccessibleDocument(docAccessible);
@@ -678,28 +678,28 @@ void
 nsXULTreeAccessible::TreeViewChanged()
 {
   if (IsDefunct())
     return;
 
   // Fire only notification destroy/create events on accessible tree to lie to
   // AT because it should be expensive to fire destroy events for each tree item
   // in cache.
-  nsCOMPtr<nsIAccessibleEvent> eventDestroy =
+  nsRefPtr<nsAccEvent> eventDestroy =
     new nsAccEvent(nsIAccessibleEvent::EVENT_HIDE, this, PR_FALSE);
   if (!eventDestroy)
     return;
 
   FirePlatformEvent(eventDestroy);
 
   ClearCache(mAccessNodeCache);
 
   mTree->GetView(getter_AddRefs(mTreeView));
 
-  nsCOMPtr<nsIAccessibleEvent> eventCreate =
+  nsRefPtr<nsAccEvent> eventCreate =
     new nsAccEvent(nsIAccessibleEvent::EVENT_SHOW, this, PR_FALSE);
   if (!eventCreate)
     return;
 
   FirePlatformEvent(eventCreate);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -1269,17 +1269,17 @@ nsXULTreeItemAccessible::GetRoleInternal
 void
 nsXULTreeItemAccessible::RowInvalidated(PRInt32 aStartColIdx,
                                         PRInt32 aEndColIdx)
 {
   nsAutoString name;
   GetName(name);
 
   if (name != mCachedName) {
-    nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_NAME_CHANGE, this);
+    nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_NAME_CHANGE, this);
     mCachedName = name;
   }
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeItemAccessible: nsAccessible protected implementation
 
 void
--- a/accessible/src/xul/nsXULTreeGridAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeGridAccessible.cpp
@@ -1247,31 +1247,30 @@ nsXULTreeGridCellAccessible::CellInvalid
   nsAutoString textEquiv;
 
   PRInt16 type;
   mColumn->GetType(&type);
   if (type == nsITreeColumn::TYPE_CHECKBOX) {
     mTreeView->GetCellValue(mRow, mColumn, textEquiv);
     if (mCachedTextEquiv != textEquiv) {
       PRBool isEnabled = textEquiv.EqualsLiteral("true");
-      nsCOMPtr<nsIAccessibleEvent> accEvent =
+      nsRefPtr<nsAccEvent> accEvent =
         new nsAccStateChangeEvent(this, nsIAccessibleStates::STATE_CHECKED,
                                   PR_FALSE, isEnabled);
-      if (accEvent)
-        FireAccessibleEvent(accEvent);
+      nsEventShell::FireEvent(accEvent);
 
       mCachedTextEquiv = textEquiv;
     }
 
     return;
   }
 
   mTreeView->GetCellText(mRow, mColumn, textEquiv);
   if (mCachedTextEquiv != textEquiv) {
-    nsAccUtils::FireAccEvent(nsIAccessibleEvent::EVENT_NAME_CHANGE, this);
+    nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_NAME_CHANGE, this);
     mCachedTextEquiv = textEquiv;
   }
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeGridCellAccessible: nsAccessible protected implementation
 
 nsIAccessible*
--- a/accessible/tests/mochitest/role.js
+++ b/accessible/tests/mochitest/role.js
@@ -32,33 +32,38 @@ const ROLE_LIST = nsIAccessibleRole.ROLE
 const ROLE_LISTBOX = nsIAccessibleRole.ROLE_LISTBOX;
 const ROLE_LISTITEM = nsIAccessibleRole.ROLE_LISTITEM;
 const ROLE_MENUITEM = nsIAccessibleRole.ROLE_MENUITEM;
 const ROLE_MENUPOPUP = nsIAccessibleRole.ROLE_MENUPOPUP;
 const ROLE_NOTHING = nsIAccessibleRole.ROLE_NOTHING;
 const ROLE_OPTION = nsIAccessibleRole.ROLE_OPTION;
 const ROLE_OUTLINE = nsIAccessibleRole.ROLE_OUTLINE;
 const ROLE_OUTLINEITEM = nsIAccessibleRole.ROLE_OUTLINEITEM;
+const ROLE_PAGETAB = nsIAccessibleRole.ROLE_PAGETAB;
+const ROLE_PAGETABLIST = nsIAccessibleRole.ROLE_PAGETABLIST;
+const ROLE_PANE = nsIAccessibleRole.ROLE_PANE;
 const ROLE_PARAGRAPH = nsIAccessibleRole.ROLE_PARAGRAPH;
 const ROLE_PARENT_MENUITEM = nsIAccessibleRole.ROLE_PARENT_MENUITEM;
 const ROLE_PASSWORD_TEXT = nsIAccessibleRole.ROLE_PASSWORD_TEXT;
 const ROLE_PROGRESSBAR = nsIAccessibleRole.ROLE_PROGRESSBAR;
+const ROLE_PROPERTYPAGE = nsIAccessibleRole.ROLE_PROPERTYPAGE;
 const ROLE_PUSHBUTTON = nsIAccessibleRole.ROLE_PUSHBUTTON;
 const ROLE_RADIOBUTTON = nsIAccessibleRole.ROLE_RADIOBUTTON;
 const ROLE_ROW = nsIAccessibleRole.ROLE_ROW;
 const ROLE_ROWHEADER = nsIAccessibleRole.ROLE_ROWHEADER;
 const ROLE_SCROLLBAR = nsIAccessibleRole.ROLE_SCROLLBAR;
 const ROLE_SECTION = nsIAccessibleRole.ROLE_SECTION;
 const ROLE_SEPARATOR = nsIAccessibleRole.ROLE_SEPARATOR;
 const ROLE_SLIDER = nsIAccessibleRole.ROLE_SLIDER;
 const ROLE_STATICTEXT = nsIAccessibleRole.ROLE_STATICTEXT;
 const ROLE_TABLE = nsIAccessibleRole.ROLE_TABLE;
 const ROLE_TEXT_CONTAINER = nsIAccessibleRole.ROLE_TEXT_CONTAINER;
 const ROLE_TEXT_LEAF = nsIAccessibleRole.ROLE_TEXT_LEAF;
 const ROLE_TOGGLE_BUTTON = nsIAccessibleRole.ROLE_TOGGLE_BUTTON;
+const ROLE_TOOLTIP = nsIAccessibleRole.ROLE_TOOLTIP;
 const ROLE_TREE_TABLE = nsIAccessibleRole.ROLE_TREE_TABLE;
 const ROLE_WHITESPACE = nsIAccessibleRole.ROLE_WHITESPACE;
 
 ////////////////////////////////////////////////////////////////////////////////
 // Public methods
 
 /**
  * Test that the role of the given accessible is the role passed in.
--- a/accessible/tests/mochitest/tree/Makefile.in
+++ b/accessible/tests/mochitest/tree/Makefile.in
@@ -55,16 +55,18 @@ include $(topsrcdir)/config/rules.mk
 		test_groupbox.xul \
 		test_iframe.html \
 		test_img.html \
 		test_list.html \
 		test_list_invalidate.html \
 		test_media.html \
 		test_menu.xul \
 		test_select.html \
+		test_tabbox.xul \
+		test_tabbrowser.xul \
 		test_table.html \
 		test_tree.xul \
 		test_txtcntr.html \
 		test_txtctrl.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/a11y/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/tree/test_tabbox.xul
@@ -0,0 +1,94 @@
+<?xml version="1.0"?>
+<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
+<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
+                 type="text/css"?>
+
+<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+        title="Accessible XUL tabbox hierarchy tests">
+
+  <script type="application/javascript" 
+          src="chrome://mochikit/content/MochiKit/packed.js" />
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
+
+  <script type="application/javascript"
+          src="chrome://mochikit/content/a11y/accessible/common.js" />
+  <script type="application/javascript"
+          src="chrome://mochikit/content/a11y/accessible/role.js" />
+
+  <script type="application/javascript">
+  <![CDATA[
+    ////////////////////////////////////////////////////////////////////////////
+    // Test
+
+    function doTest()
+    {
+      //////////////////////////////////////////////////////////////////////////
+      // tabbox
+
+      var accTree = {
+        role: ROLE_PANE,
+        children: [
+          {
+            role: ROLE_PAGETABLIST,
+            children: [
+              {
+                role: ROLE_PAGETAB,
+                children: []
+              },
+              {
+                role: ROLE_PAGETAB,
+                children: []
+              }
+            ]
+          },
+          {
+            role: ROLE_PROPERTYPAGE,
+            children: []
+          },
+          {
+            role: ROLE_PROPERTYPAGE,
+            children: []
+          }
+        ]
+      };
+      testAccessibleTree("tabbox", accTree);
+
+      SimpleTest.finish()
+    }
+
+    SimpleTest.waitForExplicitFinish();
+    addA11yLoadEvent(doTest);
+  ]]>
+  </script>
+
+  <hbox flex="1" style="overflow: auto;">
+    <body xmlns="http://www.w3.org/1999/xhtml">
+      <a target="_blank"
+         href="https://bugzilla.mozilla.org/show_bug.cgi?id=540389"
+         title=" WARNING: Bad accessible tree!: [tabbrowser tab] ">
+        Mozilla Bug 540389
+      </a><br/>
+      <p id="display"></p>
+      <div id="content" style="display: none">
+      </div>
+      <pre id="test">
+      </pre>
+    </body>
+
+    <vbox flex="1">
+      <tabbox id="tabbox">
+        <tabs>
+          <tab label="tab1"/>
+          <tab label="tab2"/>
+        </tabs>
+        <tabpanels>
+          <tabpanel/>
+          <tabpanel/>
+        </tabpanels>
+      </tabbox>
+    </vbox>
+  </hbox>
+
+</window>
+
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/tree/test_tabbrowser.xul
@@ -0,0 +1,152 @@
+<?xml version="1.0"?>
+<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
+<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
+                 type="text/css"?>
+<?xml-stylesheet href="chrome://browser/content/browser.css"
+                 type="text/css"?>
+
+<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+        title="Accessible XUL tabbrowser hierarchy tests">
+
+  <script type="application/javascript" 
+          src="chrome://mochikit/content/MochiKit/packed.js" />
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
+
+  <script type="application/javascript"
+          src="chrome://mochikit/content/a11y/accessible/common.js" />
+  <script type="application/javascript"
+          src="chrome://mochikit/content/a11y/accessible/role.js" />
+
+  <script type="application/javascript">
+  <![CDATA[
+    ////////////////////////////////////////////////////////////////////////////
+    // Test
+
+    const Ci = Components.interfaces;
+
+    // Hack to make xul:tabbrowser work.
+    var XULBrowserWindow = {
+      isBusy: false,
+      setOverLink: function (link, b) {
+      }
+    };
+    var gFindBar = {
+      hidden: true
+    };
+
+    function doTest()
+    {
+      if (LINUX) {
+        // XXX: bug 540529
+
+        todo(false, "Failure on Linux.");
+        SimpleTest.finish();
+        return;
+      }
+
+      var tabBrowser = document.getElementById("tabbrowser");
+
+      var progressListener =
+      {
+        onStateChange: function onStateChange(aWebProgress,
+                                              aRequest,
+                                              aStateFlags,
+                                              aStatus)
+       {
+        if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP)
+          testAccTree();
+       }
+      };
+
+      tabBrowser.addProgressListener(progressListener,
+                                     Ci.nsIWebProgress.NOTIFY_STATE_WINDOW);
+
+      tabBrowser.loadTabs(["about:", "about:mozilla"], false, true);
+    }
+
+    function testAccTree()
+    {
+      var accTree = {
+        role: ROLE_PANE,
+        children: [
+          {
+            role: ROLE_TOOLTIP
+          },
+          {
+            role: ROLE_MENUPOPUP
+          },
+          {
+            role: ROLE_PAGETABLIST,
+            children: [
+              {
+                role: ROLE_PAGETAB,
+                children: [
+                  {
+                    role: ROLE_PUSHBUTTON
+                  }
+                ]
+              },
+              {
+                role: ROLE_PAGETAB,
+                children: [
+                  {
+                    role: ROLE_PUSHBUTTON
+                  }
+                ]
+              },
+              {
+                role: ROLE_PUSHBUTTON
+              },
+              {
+                role: ROLE_PUSHBUTTON
+              }
+            ]
+          },
+          {
+            role: ROLE_PROPERTYPAGE
+          },
+          {
+            role: ROLE_PROPERTYPAGE
+          }
+        ]
+      };
+      testAccessibleTree(getNode("tabbrowser").mTabBox, accTree);
+
+      SimpleTest.finish()
+    }
+
+    SimpleTest.waitForExplicitFinish();
+    addA11yLoadEvent(doTest);
+  ]]>
+  </script>
+
+  <hbox flex="1" style="overflow: auto;">
+    <body xmlns="http://www.w3.org/1999/xhtml">
+      <a target="_blank"
+         href="https://bugzilla.mozilla.org/show_bug.cgi?id=540389"
+         title=" WARNING: Bad accessible tree!: [tabbrowser tab] ">
+        Mozilla Bug 540389
+      </a><br/>
+      <p id="display"></p>
+      <div id="content" style="display: none">
+      </div>
+      <pre id="test">
+      </pre>
+    </body>
+
+    <!-- Hack to make xul:tabbrowser work -->
+    <menubar>
+      <menu label="menu">
+        <menupopup>
+          <menuitem label="close window hook" id="menu_closeWindow"/>
+          <menuitem label="close hook" id="menu_close"/>
+        </menupopup>
+      </menu>
+    </menubar>
+
+    <tabbrowser type="content-primary" flex="1" id="tabbrowser"/>
+  </hbox>
+
+</window>
+
--- a/browser/base/content/browser-menubar.inc
+++ b/browser/base/content/browser-menubar.inc
@@ -600,18 +600,18 @@
                         accesskey="&privateBrowsingCmd.start.accesskey;"
                         startlabel="&privateBrowsingCmd.start.label;"
                         startaccesskey="&privateBrowsingCmd.start.accesskey;"
                         stoplabel="&privateBrowsingCmd.stop.label;"
                         stopaccesskey="&privateBrowsingCmd.stop.accesskey;"
                         key="key_privatebrowsing"
                         command="Tools:PrivateBrowsing"/>
               <menuitem id="sanitizeItem"
-                        accesskey="&clearRecentHistoryCmd.accesskey;"
-                        label="&clearRecentHistoryCmd.label;"
+                        accesskey="&clearRecentHistory.accesskey;"
+                        label="&clearRecentHistory.label;"
                         key="key_sanitize"
                         command="Tools:Sanitize"/>
 #ifndef XP_UNIX
               <menuseparator id="prefSep"/>
               <menuitem id="menu_preferences"
                         label="&preferencesCmd.label;"
                         accesskey="&preferencesCmd.accesskey;"
                         oncommand="openPreferences();"/>
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -1531,20 +1531,16 @@ var gAutoHideTabbarPrefListener = {
       }
       gBrowser.setStripVisibilityTo(aVisible);
     }
   }
 }
 
 function initializeSanitizer()
 {
-  // Always use the label with ellipsis
-  var label = gNavigatorBundle.getString("sanitizeWithPromptLabel2");
-  document.getElementById("sanitizeItem").setAttribute("label", label);
-
   const kDidSanitizeDomain = "privacy.sanitize.didShutdownSanitize";
   if (gPrefService.prefHasUserValue(kDidSanitizeDomain)) {
     gPrefService.clearUserPref(kDidSanitizeDomain);
     // We need to persist this preference change, since we want to
     // check it at next app start even if the browser exits abruptly
     gPrefService.savePrefFile(null);
   }
 
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -3235,19 +3235,26 @@
         event.stopPropagation();
       </handler>
     </handlers>
   </binding>
 
   <binding id="tabbrowser-tab" display="xul:hbox"
            extends="chrome://global/content/bindings/tabbox.xml#tab">
     <content closetabtext="&closeTab.label;">
-      <xul:image xbl:inherits="validate,src=image" class="tab-icon-image"/>
-      <xul:label flex="1" xbl:inherits="value=label,crop,accesskey" class="tab-text"/>
-      <xul:toolbarbutton anonid="close-button" tabindex="-1" class="tab-close-button"/>
+      <xul:image xbl:inherits="validate,src=image"
+                 class="tab-icon-image"
+                 role="presentation"/>
+      <xul:label flex="1"
+                 xbl:inherits="value=label,crop,accesskey"
+                 class="tab-text"
+                 role="presentation"/>
+      <xul:toolbarbutton anonid="close-button"
+                         tabindex="-1"
+                         class="tab-close-button"/>
     </content>
 
     <implementation>
       <field name="mOverCloseButton">false</field>
       <field name="mCorrespondingMenuitem">null</field>
     </implementation>
 
     <handlers>
--- a/browser/base/content/utilityOverlay.js
+++ b/browser/base/content/utilityOverlay.js
@@ -138,34 +138,29 @@ function whereToOpenLink( e, ignoreButto
 
   // ignoreButton allows "middle-click paste" to use function without always opening in a new window.
   var middle = !ignoreButton && e.button == 1;
   var middleUsesTabs = getBoolPref("browser.tabs.opentabfor.middleclick", true);
 
   // Don't do anything special with right-mouse clicks.  They're probably clicks on context menu items.
 
 #ifdef XP_MACOSX
-  if (meta || (middle && middleUsesTabs)) {
+  if (meta || (middle && middleUsesTabs))
 #else
-  if (ctrl || (middle && middleUsesTabs)) {
+  if (ctrl || (middle && middleUsesTabs))
 #endif
-    if (shift)
-      return "tabshifted";
-    else
-      return "tab";
-  }
-  else if (alt) {
+    return shift ? "tabshifted" : "tab";
+
+  if (alt)
     return "save";
-  }
-  else if (shift || (middle && !middleUsesTabs)) {
+
+  if (shift || (middle && !middleUsesTabs))
     return "window";
-  }
-  else {
-    return "current";
-  }
+
+  return "current";
 }
 
 /* openUILinkIn opens a URL in a place specified by the parameter |where|.
  *
  * |where| can be:
  *  "current"     current tab            (if there aren't any browser windows, then in a new window instead)
  *  "tab"         new tab                (if there aren't any browser windows, then in a new window instead)
  *  "tabshifted"  same as "tab" but in background if default is to select new tabs, and vice versa
--- a/browser/installer/windows/nsis/shared.nsh
+++ b/browser/installer/windows/nsis/shared.nsh
@@ -533,17 +533,17 @@
   ; should be ${FileMainEXE} so if it is in use the CheckForFilesInUse macro
   ; returns after the first check.
   Push "end"
   Push "AccessibleMarshal.dll"
   Push "freebl3.dll"
   Push "nssckbi.dll"
   Push "nspr4.dll"
   Push "nssdbm3.dll"
-  Push "sqlite3.dll"
+  Push "mozsqlite3.dll"
   Push "xpcom.dll"
   Push "crashreporter.exe"
   Push "updater.exe"
   Push "xpicleanup.exe"
   Push "${FileMainEXE}"
 !macroend
 !define PushFilesToCheck "!insertmacro PushFilesToCheck"
 
--- a/browser/locales/en-US/chrome/browser/browser.dtd
+++ b/browser/locales/en-US/chrome/browser/browser.dtd
@@ -167,18 +167,18 @@
 <!ENTITY selectAllCmd.label         "Select All">  
 <!ENTITY selectAllCmd.key         "A">  
 <!ENTITY selectAllCmd.accesskey       "A"> 
 <!ENTITY preferencesCmd.label       "Options…">
 <!ENTITY preferencesCmd.accesskey     "O"> 
 <!ENTITY preferencesCmdUnix.label       "Preferences">
 <!ENTITY preferencesCmdUnix.accesskey     "n"> 
 
-<!ENTITY clearRecentHistoryCmd.label            "Clear Recent History">
-<!ENTITY clearRecentHistoryCmd.accesskey        "H">
+<!ENTITY clearRecentHistory.label               "Clear Recent History…">
+<!ENTITY clearRecentHistory.accesskey           "H">
 
 <!-- LOCALIZATION NOTE : These two strings can share an access key beause they never appear together on the menu -->
 <!ENTITY privateBrowsingCmd.start.label         "Start Private Browsing">
 <!ENTITY privateBrowsingCmd.start.accesskey     "P">
 <!ENTITY privateBrowsingCmd.stop.label          "Stop Private Browsing">
 <!ENTITY privateBrowsingCmd.stop.accesskey      "P">
 <!ENTITY privateBrowsingCmd.commandkey          "P">
 
--- a/browser/locales/en-US/chrome/browser/browser.properties
+++ b/browser/locales/en-US/chrome/browser/browser.properties
@@ -71,17 +71,16 @@ outdatedpluginsMessage.updateButton.label=Update Plugins…
 outdatedpluginsMessage.updateButton.accesskey=U
 blockedpluginsMessage.title=Some plugins required by this page have been blocked for your protection.
 blockedpluginsMessage.infoButton.label=Details…
 blockedpluginsMessage.infoButton.accesskey=D
 blockedpluginsMessage.searchButton.label=Update Plugins…
 blockedpluginsMessage.searchButton.accesskey=U
 
 # Sanitize
-sanitizeWithPromptLabel2=Clear Recent History…
 # LOCALIZATION NOTE (sanitizeDialog2.everything.title): When "Time range to
 # clear" is set to "Everything", the Clear Recent History dialog's title is
 # changed to this.  See UI mockup and comment 11 at bug 480169 -->
 sanitizeDialog2.everything.title=Clear All History
 sanitizeButtonOK=Clear Now
 # LOCALIZATION NOTE (sanitizeEverythingWarning2): Warning that appears when
 # "Time range to clear" is set to "Everything" in Clear Recent History dialog,
 # provided that the user has not modified the default set of history items to clear.
--- a/build/automation.py.in
+++ b/build/automation.py.in
@@ -572,16 +572,113 @@ user_pref("camino.use_system_proxy_setti
         # We should have a "crashinject" program in our utility path
         crashinject = os.path.normpath(os.path.join(utilityPath, "crashinject.exe"))
         if os.path.exists(crashinject) and subprocess.Popen([crashinject, str(proc.pid)]).wait() == 0:
           return
     #TODO: kill the process such that it triggers Breakpad on OS X (bug 525296)
     self.log.info("Can't trigger Breakpad, just killing process")
     proc.kill()
 
+  def waitForFinish(self, proc, utilityPath, timeout, maxTime):
+    """ Look for timeout or crashes and return the status after the process terminates """
+    stackFixerProcess = None
+    didTimeout = False
+    if proc.stdout is None:
+      self.log.info("TEST-INFO: Not logging stdout or stderr due to debugger connection")
+    else:
+      logsource = proc.stdout
+      if self.IS_DEBUG_BUILD:
+        stackFixerCommand = None
+        if self.IS_MAC:
+          stackFixerCommand = "fix-macosx-stack.pl"
+        elif self.IS_LINUX:
+          stackFixerCommand = "fix-linux-stack.pl"
+        if stackFixerCommand is not None:
+          stackFixerProcess = self.Process([self.PERL, os.path.join(utilityPath, stackFixerCommand)], 
+                                           stdin=logsource, 
+                                           stdout=subprocess.PIPE)
+          logsource = stackFixerProcess.stdout
+
+      (line, didTimeout) = self.readWithTimeout(logsource, timeout)
+      hitMaxTime = False
+      while line != "" and not didTimeout:
+        self.log.info(line.rstrip())
+        (line, didTimeout) = self.readWithTimeout(logsource, timeout)
+        if not hitMaxTime and maxTime and datetime.now() - startTime > timedelta(seconds = maxTime):
+          # Kill the application, but continue reading from stack fixer so as not to deadlock on stackFixerProcess.wait().
+          hitMaxTime = True
+          self.log.info("TEST-UNEXPECTED-FAIL | automation.py | application ran for longer than allowed maximum time of %d seconds", int(maxTime))
+          self.triggerBreakpad(proc, utilityPath)
+      if didTimeout:
+        self.log.info("TEST-UNEXPECTED-FAIL | automation.py | application timed out after %d seconds with no output", int(timeout))
+        self.triggerBreakpad(proc, utilityPath)
+
+    status = proc.wait()
+    if status != 0 and not didTimeout and not hitMaxTime:
+      self.log.info("TEST-UNEXPECTED-FAIL | automation.py | Exited with code %d during test run", status)
+    if stackFixerProcess is not None:
+      fixerStatus = stackFixerProcess.wait()
+      if fixerStatus != 0 and not didTimeout and not hitMaxTime:
+        self.log.info("TEST-UNEXPECTED-FAIL | automation.py | Stack fixer process exited with code %d during test run", fixerStatus)
+    return status
+
+  def buildCommandLine(self, app, debuggerInfo, profileDir, testURL, extraArgs):
+    """ build the application command line """
+
+    cmd = app
+    if self.IS_MAC and not self.IS_CAMINO and not cmd.endswith("-bin"):
+      cmd += "-bin"
+    cmd = os.path.abspath(cmd)
+
+    args = []
+
+    if debuggerInfo:
+      args.extend(debuggerInfo["args"])
+      args.append(cmd)
+      cmd = os.path.abspath(debuggerInfo["path"])
+
+    if self.IS_MAC:
+      args.append("-foreground")
+
+    if self.IS_CYGWIN:
+      profileDirectory = commands.getoutput("cygpath -w \"" + profileDir + "/\"")
+    else:
+      profileDirectory = profileDir + "/"
+
+    args.extend(("-no-remote", "-profile", profileDirectory))
+    if testURL is not None:
+      if self.IS_CAMINO:
+        args.extend(("-url", testURL))
+      else:
+        args.append((testURL))
+    args.extend(extraArgs)
+    return cmd, args
+
+  def checkForZombies(self, processLog):
+    """ Look for hung processes """
+    if not os.path.exists(processLog):
+      self.log.info('INFO | automation.py | PID log not found: %s', processLog)
+    else:
+      self.log.info('INFO | automation.py | Reading PID log: %s', processLog)
+      processList = []
+      pidRE = re.compile(r'launched child process (\d+)$')
+      processLogFD = open(processLog)
+      for line in processLogFD:
+        self.log.info(line.rstrip())
+        m = pidRE.search(line)
+        if m:
+          processList.append(int(m.group(1)))
+      processLogFD.close()
+
+      for processPID in processList:
+        self.log.info("INFO | automation.py | Checking for orphan process with PID: %d", processPID)
+        if self.isPidAlive(processPID):
+          self.log.info("TEST-UNEXPECTED-FAIL | automation.py | child process %d still alive after shutdown", processPID)
+          self.killPid(processPID)
+
   def runApp(self, testURL, env, app, profileDir, extraArgs,
              runSSLTunnel = False, utilityPath = None,
              xrePath = None, certPath = None,
              debuggerInfo = None, symbolsPath = None,
              timeout = -1, maxTime = None):
     """
     Run the app, log the duration it took to execute, return the status code.
     Kills the app if it runs for longer than |maxTime| seconds, or outputs nothing for |timeout| seconds.
@@ -612,122 +709,37 @@ user_pref("camino.use_system_proxy_setti
 
       # start ssltunnel to provide https:// URLs capability
       ssltunnel = os.path.join(utilityPath, "ssltunnel" + self.BIN_SUFFIX)
       ssltunnelProcess = self.Process([ssltunnel, 
                                os.path.join(profileDir, "ssltunnel.cfg")], 
                                env = self.environment(xrePath = xrePath))
       self.log.info("INFO | automation.py | SSL tunnel pid: %d", ssltunnelProcess.pid)
 
-    # now run with the profile we created
-    cmd = app
-    if self.IS_MAC and not self.IS_CAMINO and not cmd.endswith("-bin"):
-      cmd += "-bin"
-    cmd = os.path.abspath(cmd)
-
-    args = []
-
-    if debuggerInfo:
-      args.extend(debuggerInfo["args"])
-      args.append(cmd)
-      cmd = os.path.abspath(debuggerInfo["path"])
-
-    if self.IS_MAC:
-      args.append("-foreground")
-
-    if self.IS_CYGWIN:
-      profileDirectory = commands.getoutput("cygpath -w \"" + profileDir + "/\"")
-    else:
-      profileDirectory = profileDir + "/"
-
-    args.extend(("-no-remote", "-profile", profileDirectory))
-    if testURL is not None:
-      if self.IS_CAMINO:
-        args.extend(("-url", testURL))
-      else:
-        args.append((testURL))
-    args.extend(extraArgs)
-
+    cmd, args = self.buildCommandLine(app, debuggerInfo, profileDir, testURL, extraArgs)
     startTime = datetime.now()
 
     # Don't redirect stdout and stderr if an interactive debugger is attached
     if debuggerInfo and debuggerInfo["interactive"]:
       outputPipe = None
     else:
       outputPipe = subprocess.PIPE
 
     proc = self.Process([cmd] + args,
                  env = self.environment(env, xrePath = xrePath,
                                    crashreporter = not debuggerInfo),
                  stdout = outputPipe,
                  stderr = subprocess.STDOUT)
     self.log.info("INFO | automation.py | Application pid: %d", proc.pid)
 
-    stackFixerProcess = None
-    didTimeout = False
-    if outputPipe is None:
-      self.log.info("TEST-INFO: Not logging stdout or stderr due to debugger connection")
-    else:
-      logsource = proc.stdout
-      if self.IS_DEBUG_BUILD:
-        stackFixerCommand = None
-        if self.IS_MAC:
-          stackFixerCommand = "fix-macosx-stack.pl"
-        elif self.IS_LINUX:
-          stackFixerCommand = "fix-linux-stack.pl"
-        if stackFixerCommand is not None:
-          stackFixerProcess = self.Process([self.PERL, os.path.join(utilityPath, stackFixerCommand)], 
-                                           stdin=logsource, 
-                                           stdout=subprocess.PIPE)
-          logsource = stackFixerProcess.stdout
-
-      (line, didTimeout) = self.readWithTimeout(logsource, timeout)
-      hitMaxTime = False
-      while line != "" and not didTimeout:
-        self.log.info(line.rstrip())
-        (line, didTimeout) = self.readWithTimeout(logsource, timeout)
-        if not hitMaxTime and maxTime and datetime.now() - startTime > timedelta(seconds = maxTime):
-          # Kill the application, but continue reading from stack fixer so as not to deadlock on stackFixerProcess.wait().
-          hitMaxTime = True
-          self.log.info("TEST-UNEXPECTED-FAIL | automation.py | application ran for longer than allowed maximum time of %d seconds", int(maxTime))
-          self.triggerBreakpad(proc, utilityPath)
-      if didTimeout:
-        self.log.info("TEST-UNEXPECTED-FAIL | automation.py | application timed out after %d seconds with no output", int(timeout))
-        self.triggerBreakpad(proc, utilityPath)
-
-    status = proc.wait()
-    if status != 0 and not didTimeout and not hitMaxTime:
-      self.log.info("TEST-UNEXPECTED-FAIL | automation.py | Exited with code %d during test run", status)
-    if stackFixerProcess is not None:
-      fixerStatus = stackFixerProcess.wait()
-      if fixerStatus != 0 and not didTimeout and not hitMaxTime:
-        self.log.info("TEST-UNEXPECTED-FAIL | automation.py | Stack fixer process exited with code %d during test run", fixerStatus)
+    status = self.waitForFinish(proc, utilityPath, timeout, maxTime)
     self.log.info("INFO | automation.py | Application ran for: %s", str(datetime.now() - startTime))
 
     # Do a final check for zombie child processes.
-    if not os.path.exists(processLog):
-      self.log.info('INFO | automation.py | PID log not found: %s', processLog)
-    else:
-      self.log.info('INFO | automation.py | Reading PID log: %s', processLog)
-      processList = []
-      pidRE = re.compile(r'launched child process (\d+)$')
-      processLogFD = open(processLog)
-      for line in processLogFD:
-        self.log.info(line.rstrip())
-        m = pidRE.search(line)
-        if m:
-          processList.append(int(m.group(1)))
-      processLogFD.close()
-
-      for processPID in processList:
-        self.log.info("INFO | automation.py | Checking for orphan process with PID: %d", processPID)
-        if self.isPidAlive(processPID):
-          self.log.info("TEST-UNEXPECTED-FAIL | automation.py | child process %d still alive after shutdown", processPID)
-          self.killPid(processPID)
-
+    self.checkForZombies(processLog)
     self.automationutils.checkForCrashes(os.path.join(profileDir, "minidumps"), symbolsPath)
 
     if os.path.exists(processLog):
       os.unlink(processLog)
 
     if self.IS_TEST_BUILD and runSSLTunnel:
       ssltunnelProcess.kill()
 
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -556,17 +556,16 @@ MOZ_AUTO_DEPS	= @MOZ_AUTO_DEPS@
 COMPILER_DEPEND = @COMPILER_DEPEND@
 MDDEPDIR        := @MDDEPDIR@
 
 MOZ_DEMANGLE_SYMBOLS = @MOZ_DEMANGLE_SYMBOLS@
 
 # XXX - these need to be cleaned up and have real checks added -cls
 CM_BLDTYPE=dbg
 AWT_11=1
-MOZ_BITS=32
 OS_TARGET=@OS_TARGET@
 OS_ARCH=@OS_ARCH@
 OS_RELEASE=@OS_RELEASE@
 OS_TEST=@OS_TEST@
 
 # For Solaris build
 SOLARIS_SUNPRO_CC = @SOLARIS_SUNPRO_CC@
 SOLARIS_SUNPRO_CXX = @SOLARIS_SUNPRO_CXX@
--- a/configure.in
+++ b/configure.in
@@ -2235,17 +2235,17 @@ case "$target" in
             dnl XXX: should be -LTCG:PGOPTIMIZE, but that fails on libxul.
             dnl Probably also a compiler bug, but what can you do?
             PROFILE_USE_LDFLAGS="-LTCG:PGUPDATE"
             if test -n "$_USE_DYNAMICBASE"; then
                LDFLAGS="$LDFLAGS -DYNAMICBASE"
             fi
         fi
     fi
-    MOZ_JPEG_LIBS='$(call EXPAND_LIBNAME_PATH,jpeg$(MOZ_BITS)$(VERSION_NUMBER),$(DEPTH)/jpeg)'
+    MOZ_JPEG_LIBS='$(call EXPAND_LIBNAME_PATH,jpeg32$(VERSION_NUMBER),$(DEPTH)/jpeg)'
     MOZ_PNG_LIBS='$(call EXPAND_LIBNAME_PATH,png,$(DEPTH)/modules/libimg/png)'
     AC_DEFINE(HAVE_SNPRINTF)
     AC_DEFINE(_WINDOWS)
     AC_DEFINE(WIN32)
     AC_DEFINE(XP_WIN)
     AC_DEFINE(XP_WIN32)
     AC_DEFINE(HW_THREADS)
     AC_DEFINE(STDC_HEADERS)
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -2651,26 +2651,26 @@ nsEventStateManager::DecideGestureEvent(
           break;
         }
 
         if (canScrollHorizontally) {
           panDirection = nsGestureNotifyEvent::ePanHorizontal;
           displayPanFeedback = PR_FALSE;
         }
       } else { //Not a XUL box
-        nsMargin scrollbarSizes = scrollableFrame->GetActualScrollbarSizes();
+        PRUint32 scrollbarVisibility = scrollableFrame->GetScrollbarVisibility();
 
         //Check if we have visible scrollbars
-        if (scrollbarSizes.LeftRight()) {
+        if (scrollbarVisibility & nsIScrollableFrame::VERTICAL) {
           panDirection = nsGestureNotifyEvent::ePanVertical;
           displayPanFeedback = PR_TRUE;
           break;
         }
 
-        if (scrollbarSizes.TopBottom()) {
+        if (scrollbarVisibility & nsIScrollableFrame::HORIZONTAL) {
           panDirection = nsGestureNotifyEvent::ePanHorizontal;
           displayPanFeedback = PR_TRUE;
         }
       }
     } //scrollableFrame
   } //ancestor chain
 
   aEvent->displayPanFeedback = displayPanFeedback;
--- a/content/html/content/src/nsHTMLTextAreaElement.cpp
+++ b/content/html/content/src/nsHTMLTextAreaElement.cpp
@@ -368,16 +368,17 @@ nsHTMLTextAreaElement::IsHTMLFocusable(P
   // disabled textareas are not focusable
   *aIsFocusable = !HasAttr(kNameSpaceID_None, nsGkAtoms::disabled);
   return PR_FALSE;
 }
 
 NS_IMPL_STRING_ATTR(nsHTMLTextAreaElement, AccessKey, accesskey)
 NS_IMPL_INT_ATTR(nsHTMLTextAreaElement, Cols, cols)
 NS_IMPL_BOOL_ATTR(nsHTMLTextAreaElement, Disabled, disabled)
+NS_IMPL_INT_ATTR(nsHTMLTextAreaElement, MaxLength, maxlength)
 NS_IMPL_STRING_ATTR(nsHTMLTextAreaElement, Name, name)
 NS_IMPL_BOOL_ATTR(nsHTMLTextAreaElement, ReadOnly, readonly)
 NS_IMPL_INT_ATTR(nsHTMLTextAreaElement, Rows, rows)
 NS_IMPL_INT_ATTR_DEFAULT_VALUE(nsHTMLTextAreaElement, TabIndex, tabindex, 0)
   
 
 NS_IMETHODIMP 
 nsHTMLTextAreaElement::GetType(nsAString& aType)
@@ -518,16 +519,19 @@ nsHTMLTextAreaElement::SetDefaultValue(c
 
 PRBool
 nsHTMLTextAreaElement::ParseAttribute(PRInt32 aNamespaceID,
                                       nsIAtom* aAttribute,
                                       const nsAString& aValue,
                                       nsAttrValue& aResult)
 {
   if (aNamespaceID == kNameSpaceID_None) {
+    if (aAttribute == nsGkAtoms::maxlength) {
+      return aResult.ParseIntWithBounds(aValue, 0);
+    }
     if (aAttribute == nsGkAtoms::cols) {
       return aResult.ParseIntWithBounds(aValue, 0);
     }
     if (aAttribute == nsGkAtoms::rows) {
       return aResult.ParseIntWithBounds(aValue, 0);
     }
   }
   return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
--- a/content/html/content/test/Makefile.in
+++ b/content/html/content/test/Makefile.in
@@ -139,12 +139,13 @@ include $(topsrcdir)/config/rules.mk
 		test_bug500885.html \
 		test_bug514856.html \
 		bug514856_iframe.html \
 		test_bug519987.html \
 		test_bug523771.html \
 		form_submit_server.sjs \
 		test_bug529819.html \
 		test_bug529859.html \
+		test_bug535043.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_bug535043.html
@@ -0,0 +1,87 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=535043
+-->
+<head>
+  <title>Test for Bug 535043</title>
+  <script type="text/javascript" src="/MochiKit/packed.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/EventUtils.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=535043">Mozilla Bug 535043</a>
+<p id="display"></p>
+<div id="content">
+  <textarea></textarea>
+  <textarea maxlength="-1"></textarea>
+  <textarea maxlength="0"></textarea>
+  <textarea maxlength="2"></textarea>
+  <textarea maxlength="257"></textarea>
+</div>
+<pre id="test">
+<script type="text/javascript">
+
+/** Test for Bug 535043 **/
+function checkTextArea(textArea) {
+  textArea.value = '';
+  textArea.focus();
+  for (var j = 0; j < 259; j++) {
+    synthesizeKey('x', {});
+  }
+  var htmlMaxLength = textArea.getAttribute('maxlength');
+  var domMaxLength = textArea.maxLength;
+  if (htmlMaxLength == null) {
+    is(domMaxLength, -1,
+      'maxlength is unset but maxLength DOM attribute is not -1');
+  } else if (htmlMaxLength < 0) {
+    // Per the HTML5 spec, out-of-range values are supposed to translate to -1,
+    // not 0, but they don't?
+    todo_is(domMaxLength, -1,
+      'maxlength is out of range but maxLength DOM attribute is not -1');
+  } else {
+    is(domMaxLength, parseInt(htmlMaxLength),
+      'maxlength in DOM does not match provided value');
+  }
+  if (textArea.maxLength == -1) {
+    is(textArea.value.length, 259,
+      'textarea with maxLength -1 should have no length limit');
+  } else {
+    is(textArea.value.length, textArea.maxLength, 'textarea has maxLength ' +
+      textArea.maxLength + ' but length ' + textArea.value.length );
+  }
+}
+
+SimpleTest.waitForFocus(function() {
+  var textAreas = document.getElementsByTagName('textarea');
+  for (var i = 0; i < textAreas.length; i++) {
+    checkTextArea(textAreas[i]);
+  }
+
+  textArea = textAreas[0];
+  testNums = [-42, -1, 0, 2, 257];
+  for (var i = 0; i < testNums.length; i++) {
+    textArea.removeAttribute('maxlength');
+
+    var caught = false;
+    try {
+      textArea.maxLength = testNums[i];
+    } catch (e) {
+      caught = true;
+    }
+    if (testNums[i] < 0) {
+      todo(caught, 'Setting negative maxLength should throw exception');
+    } else {
+      ok(!caught, 'Setting nonnegative maxLength should not throw exception');
+    }
+    checkTextArea(textArea);
+
+    textArea.setAttribute('maxlength', testNums[i]);
+    checkTextArea(textArea);
+  }
+});
+</script>
+</pre>
+</body>
+</html>
--- a/dbm/include/Makefile.win
+++ b/dbm/include/Makefile.win
@@ -36,22 +36,16 @@
 
 
 #//------------------------------------------------------------------------
 #//
 #// Makefile to build the cert library
 #//
 #//------------------------------------------------------------------------
 
-!if "$(MOZ_BITS)" == "16"
-!ifndef MOZ_DEBUG
-OPTIMIZER=-Os -UDEBUG -DNDEBUG
-!endif
-!endif
-
 #//------------------------------------------------------------------------
 #//
 #// Specify the depth of the current directory relative to the
 #// root of NS
 #//
 #//------------------------------------------------------------------------
 DEPTH= ..\..
 
--- a/dbm/src/Makefile.in
+++ b/dbm/src/Makefile.in
@@ -41,17 +41,17 @@ srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 LIBRARY_NAME	= mozdbm_s
 LIB_IS_C_ONLY	= 1
 
 ifeq ($(OS_ARCH),WINNT)
-LIBRARY_NAME	= dbm$(MOZ_BITS)
+LIBRARY_NAME	= dbm32
 endif
 
 CSRCS		= \
 		db.c \
 		h_bigkey.c \
 		h_func.c \
 		h_log2.c \
 		h_page.c \
--- a/dbm/src/Makefile.win
+++ b/dbm/src/Makefile.win
@@ -36,22 +36,16 @@
 
 
 #//------------------------------------------------------------------------
 #//
 #// Makefile to build the cert library
 #//
 #//------------------------------------------------------------------------
 
-!if "$(MOZ_BITS)" == "16"
-!ifndef MOZ_DEBUG
-OPTIMIZER=-Os -UDEBUG -DNDEBUG
-!endif
-!endif
-
 #//------------------------------------------------------------------------
 #//
 #// Specify the depth of the current directory relative to the
 #// root of NS
 #//
 #//------------------------------------------------------------------------
 DEPTH= ..\..
 
@@ -59,17 +53,17 @@ DEPTH= ..\..
 MAKE_OBJ_TYPE=EXE
 !endif
 
 #//------------------------------------------------------------------------
 #//
 #// Define any Public Make Variables here: (ie. PDFFILE, MAPFILE, ...)
 #//
 #//------------------------------------------------------------------------
-LIBNAME=dbm$(MOZ_BITS)
+LIBNAME=dbm32
 PDBFILE=$(LIBNAME).pdb
 
 #//------------------------------------------------------------------------
 #// 
 #// Define the files necessary to build the target (ie. OBJS)
 #//
 #//------------------------------------------------------------------------
 OBJS=                         \
--- a/dbm/tests/Makefile.in
+++ b/dbm/tests/Makefile.in
@@ -46,17 +46,17 @@ MODULE		= dbm
 
 PACKAGE_FILE = dbmtest.pkg
 
 PROGRAM		= lots$(BIN_SUFFIX)
 
 CSRCS		= lots.c
 
 ifeq ($(OS_ARCH),WINNT)
-EXTRA_DSO_LIBS	= dbm$(MOZ_BITS)
+EXTRA_DSO_LIBS	= dbm32
 else
 EXTRA_DSO_LIBS	= mozdbm_s
 endif
 
 LIBS		= $(EXTRA_DSO_LIBS)
 
 include $(topsrcdir)/config/rules.mk
 
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -4806,21 +4806,21 @@ nsDocShell::SetDefaultScrollbarPreferenc
 
 NS_IMETHODIMP
 nsDocShell::GetScrollbarVisibility(PRBool * verticalVisible,
                                    PRBool * horizontalVisible)
 {
     nsIScrollableFrame* sf = GetRootScrollFrame();
     NS_ENSURE_TRUE(sf, NS_ERROR_FAILURE);
 
-    nsMargin scrollbars = sf->GetActualScrollbarSizes();
+    PRUint32 scrollbarVisibility = sf->GetScrollbarVisibility();
     if (verticalVisible)
-        *verticalVisible = scrollbars.left != 0 || scrollbars.right != 0;
+        *verticalVisible = (scrollbarVisibility & nsIScrollableFrame::VERTICAL) != 0;
     if (horizontalVisible)
-        *horizontalVisible = scrollbars.top != 0 || scrollbars.bottom != 0;
+        *horizontalVisible = (scrollbarVisibility & nsIScrollableFrame::HORIZONTAL) != 0;
 
     return NS_OK;
 }
 
 //*****************************************************************************
 // nsDocShell::nsITextScroll
 //*****************************************************************************   
 
--- a/dom/interfaces/html/nsIDOMNSHTMLTextAreaElement.idl
+++ b/dom/interfaces/html/nsIDOMNSHTMLTextAreaElement.idl
@@ -37,20 +37,21 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "domstubs.idl"
 
 interface nsIControllers;
 
 
-[scriptable, uuid(ca066b44-9ddf-11d3-bccc-0060b0fc76bd)]
+[scriptable, uuid(7a5e4bfb-0530-4c35-a7f9-7859b472ef8d)]
 interface nsIDOMNSHTMLTextAreaElement : nsISupports
 {
   readonly attribute nsIControllers   controllers;
 
   readonly attribute long    textLength;
   attribute long             selectionStart;
   attribute long             selectionEnd;
+  attribute long             maxLength;
 
   void                       setSelectionRange(in long selectionStart,
                                                in long selectionEnd);
 };
--- a/gfx/cairo/README
+++ b/gfx/cairo/README
@@ -59,16 +59,18 @@ quartz-repeating-radial-gradients.patch:
 quartz-const-globals.patch: make some Quartz color function data const globals instead of local variables
 
 quartz-minimze-gradient-repeat.patch: reduce the number of gradient stop repetitions we use, to improve quality of Quartz's gradient rendering
 
 quartz-first-stop.patch: return the first stop for negative positions on the gradient line of a nonrepeating linear gradient
 
 quartz-glyph-extents.patch: bug 534260; work around incorrect glyph extents returned by quartz for anomalous empty glyphs
 
+premultiply-alpha-solid-gradients.patch: bug 539165; multiply the solid color by the alpha component before using it for a solid surface
+
 ==== pixman patches ====
 
 pixman-neon.patch: add ARM NEON optimized compositing functions
 
 pixman-rename-and-endian.patch: include cairo-platform.h for renaming of external symbols and endian macros
 
 ==== disable printing patch ====
 
--- a/gfx/cairo/cairo/src/cairo-pattern.c
+++ b/gfx/cairo/cairo/src/cairo-pattern.c
@@ -2257,18 +2257,27 @@ cairo_int_status_t
 
 	/* fast path for gradients with less than 2 color stops */
 	if (src->n_stops < 2)
 	{
 	    cairo_solid_pattern_t solid;
 
 	    if (src->n_stops)
 	    {
+		cairo_color_t color;
+
+		/* multiply by alpha */
+		_cairo_color_init_rgba (&color,
+			src->stops->color.red,
+			src->stops->color.green,
+			src->stops->color.blue,
+			src->stops->color.alpha);
+
 		_cairo_pattern_init_solid (&solid,
-					   &src->stops->color,
+					   &color,
 					   CAIRO_CONTENT_COLOR_ALPHA);
 	    }
 	    else
 	    {
 		_cairo_pattern_init_solid (&solid,
 					   CAIRO_COLOR_TRANSPARENT,
 					   CAIRO_CONTENT_ALPHA);
 	    }
@@ -2290,19 +2299,27 @@ cairo_int_status_t
 		if (! _cairo_color_equal (&src->stops[0].color,
 					  &src->stops[i].color))
 		{
 		    break;
 		}
 	    }
 	    if (i == src->n_stops) {
 		cairo_solid_pattern_t solid;
+		cairo_color_t color;
+
+		/* multiply by alpha */
+		_cairo_color_init_rgba (&color,
+			src->stops->color.red,
+			src->stops->color.green,
+			src->stops->color.blue,
+			src->stops->color.alpha);
 
 		_cairo_pattern_init_solid (&solid,
-					   &src->stops->color,
+					   &color,
 					   CAIRO_CONTENT_COLOR_ALPHA);
 
 		status =
 		    _cairo_pattern_acquire_surface_for_solid (&solid, dst,
 							      x, y,
 							      width, height,
 							      surface_out,
 							      attributes);
new file mode 100644
--- /dev/null
+++ b/gfx/cairo/premultiply-alpha-solid-gradients.patch
@@ -0,0 +1,46 @@
+Fix single and multi-stop solid gradients by multiplying by the alpha component. r=roc
+
+This cairo commit that caused the problem: 2d790daa957471670f4ae0d3b22da89e4ee7111f.
+It was merged into mozilla-central with 1effb72d30cf
+
+diff --git a/gfx/cairo/cairo/src/cairo-pattern.c b/gfx/cairo/cairo/src/cairo-pattern.c
+--- a/gfx/cairo/cairo/src/cairo-pattern.c
++++ b/gfx/cairo/cairo/src/cairo-pattern.c
+@@ -2262,8 +2262,17 @@ _cairo_pattern_acquire_surface (const ca
+ 
+ 	    if (src->n_stops)
+ 	    {
++		cairo_color_t color;
++
++		/* multiply by alpha */
++		_cairo_color_init_rgba (&color,
++			src->stops->color.red,
++			src->stops->color.green,
++			src->stops->color.blue,
++			src->stops->color.alpha);
++
+ 		_cairo_pattern_init_solid (&solid,
+-					   &src->stops->color,
++					   &color,
+ 					   CAIRO_CONTENT_COLOR_ALPHA);
+ 	    }
+ 	    else
+@@ -2295,9 +2304,17 @@ _cairo_pattern_acquire_surface (const ca
+ 	    }
+ 	    if (i == src->n_stops) {
+ 		cairo_solid_pattern_t solid;
++		cairo_color_t color;
++
++		/* multiply by alpha */
++		_cairo_color_init_rgba (&color,
++			src->stops->color.red,
++			src->stops->color.green,
++			src->stops->color.blue,
++			src->stops->color.alpha);
+ 
+ 		_cairo_pattern_init_solid (&solid,
+-					   &src->stops->color,
++					   &color,
+ 					   CAIRO_CONTENT_COLOR_ALPHA);
+ 
+ 		status =
--- a/jpeg/Makefile.in
+++ b/jpeg/Makefile.in
@@ -41,17 +41,17 @@ srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE		= jpeg
 LIBRARY_NAME	= mozjpeg
 
 ifeq ($(OS_ARCH),WINNT)
-LIBRARY_NAME	= jpeg$(MOZ_BITS)$(VERSION_NUMBER)
+LIBRARY_NAME	= jpeg32$(VERSION_NUMBER)
 # FIXME: bug 413019
 ifndef GNU_CC
 OS_COMPILE_CFLAGS += -GL-
 endif
 endif
 
 GRE_MODULE	= 1
 
--- a/js/jsd/Makefile.in
+++ b/js/jsd/Makefile.in
@@ -44,17 +44,17 @@ VPATH		= @srcdir@
 srcdir		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE		= jsdebug
 LIBRARY_NAME	= jsd
 FORCE_SHARED_LIB= 1
 ifeq ($(OS_ARCH)$(MOZ_ENABLE_LIBXUL),WINNT)
-LIBRARY_NAME	= jsd$(MOZ_BITS)$(VERSION_NUMBER)
+LIBRARY_NAME	= jsd32$(VERSION_NUMBER)
 endif
 
 # REQUIRES	= java js
 
 
 EXTRA_DSO_LDOPTS += \
 		$(MOZ_COMPONENT_LIBS) \
 		$(MOZ_JS_LIBS) \
--- a/js/src/config/autoconf.mk.in
+++ b/js/src/config/autoconf.mk.in
@@ -291,17 +291,16 @@ MOZ_AUTO_DEPS	= @MOZ_AUTO_DEPS@
 COMPILER_DEPEND = @COMPILER_DEPEND@
 MDDEPDIR        := @MDDEPDIR@
 
 MOZ_DEMANGLE_SYMBOLS = @MOZ_DEMANGLE_SYMBOLS@
 
 # XXX - these need to be cleaned up and have real checks added -cls
 CM_BLDTYPE=dbg
 AWT_11=1
-MOZ_BITS=32
 OS_TARGET=@OS_TARGET@
 OS_ARCH=@OS_ARCH@
 OS_RELEASE=@OS_RELEASE@
 OS_TEST=@OS_TEST@
 
 # For Solaris build
 SOLARIS_SUNPRO_CC = @SOLARIS_SUNPRO_CC@
 SOLARIS_SUNPRO_CXX = @SOLARIS_SUNPRO_CXX@
--- a/js/src/tests/js1_8_1/trace/jstests.list
+++ b/js/src/tests/js1_8_1/trace/jstests.list
@@ -1,23 +1,23 @@
 url-prefix ../../jsreftest.html?test=js1_8_1/trace/
 script math-trace-tests.js
-script regress-451673.js # slow
-script regress-451974-01.js
-random script regress-451974-02.js # this is a bogus timing test (see bug 524734)
-random script regress-452498-01.js
+skip script regress-451673.js # bogus perf test (bug 540512)
+skip script regress-451974-01.js # bogus perf test (bug 540512)
+skip script regress-451974-02.js # bogus perf test (bug 540512)
+skip script regress-452498-01.js # bogus perf test (bug 540512)
 script regress-458838.js
 script regress-462459-01.js
 script regress-462459-02.js
 script regress-462459-03.js
 script regress-462459-04.js
 script regress-462459-05.js
 script regress-462459-06.js
 script regress-462459-07.js
 script regress-462459-08.js
 script regress-462459-09.js
 script regress-462459-10.js
 script regress-462459-11.js
 script regress-462459-12.js
-script regress-469927.js
-script regress-470739.js
+skip script regress-469927.js # bogus perf test (bug 540512)
+skip script regress-470739.js # bogus perf test (bug 540512)
 script regress-471635.js
 script trace-test.js
--- a/js/src/xpconnect/src/Makefile.in
+++ b/js/src/xpconnect/src/Makefile.in
@@ -47,18 +47,18 @@ include $(DEPTH)/config/autoconf.mk
 MODULE		= xpconnect
 LIBRARY_NAME	= xpconnect
 EXPORT_LIBRARY = 1
 SHORT_LIBNAME	= xpconect
 IS_COMPONENT	= 1
 MODULE_NAME	= xpconnect
 GRE_MODULE	= 1
 ifeq ($(OS_ARCH)$(MOZ_ENABLE_LIBXUL),WINNT)
-LIBRARY_NAME	= xpc$(MOZ_BITS)$(VERSION_NUMBER)
-SHORT_LIBNAME	= xpc$(MOZ_BITS)$(VERSION_NUMBER)
+LIBRARY_NAME	= xpc32$(VERSION_NUMBER)
+SHORT_LIBNAME	= xpc32$(VERSION_NUMBER)
 endif
 LIBXUL_LIBRARY = 1
 
 
 # These modules are required because the auto-generated file
 # dom_quickstubs.cpp #includes header files from many places.
 
 
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -674,25 +674,27 @@ nsIScrollableFrame*
 nsLayoutUtils::GetNearestScrollableFrameForDirection(nsIFrame* aFrame,
                                                      Direction aDirection)
 {
   NS_ASSERTION(aFrame, "GetNearestScrollableFrameForDirection expects a non-null frame");
   for (nsIFrame* f = aFrame; f; f = nsLayoutUtils::GetCrossDocParentFrame(f)) {
     nsIScrollableFrame* scrollableFrame = do_QueryFrame(f);
     if (scrollableFrame) {
       nsPresContext::ScrollbarStyles ss = scrollableFrame->GetScrollbarStyles();
-      nsMargin scrollbarSizes = scrollableFrame->GetActualScrollbarSizes();
+      PRUint32 scrollbarVisibility = scrollableFrame->GetScrollbarVisibility();
       nsRect scrollRange = scrollableFrame->GetScrollRange();
       // Require visible scrollbars or something to scroll to in
       // the given direction.
       if (aDirection == eVertical ?
           (ss.mVertical != NS_STYLE_OVERFLOW_HIDDEN &&
-           (scrollbarSizes.LeftRight() || scrollRange.height > 0)) :
+           ((scrollbarVisibility & nsIScrollableFrame::VERTICAL) ||
+            scrollRange.height > 0)) :
           (ss.mHorizontal != NS_STYLE_OVERFLOW_HIDDEN &&
-           (scrollbarSizes.TopBottom() || scrollRange.width > 0)))
+           ((scrollbarVisibility & nsIScrollableFrame::HORIZONTAL) ||
+            scrollRange.width > 0)))
         return scrollableFrame;
     }
   }
   return nsnull;
 }
 
 // static
 nsIScrollableFrame*
--- a/layout/generic/nsFrame.cpp
+++ b/layout/generic/nsFrame.cpp
@@ -5980,23 +5980,20 @@ nsIFrame::IsFocusable(PRInt32 *aTabIndex
         // Elements with scrollable view are focusable with script & tabbable
         // Otherwise you couldn't scroll them with keyboard, which is
         // an accessibility issue (e.g. Section 508 rules)
         // However, we don't make them to be focusable with the mouse,
         // because the extra focus outlines are considered unnecessarily ugly.
         // When clicked on, the selection position within the element 
         // will be enough to make them keyboard scrollable.
         nsIScrollableFrame *scrollFrame = do_QueryFrame(this);
-        if (scrollFrame) {
-          nsMargin margin = scrollFrame->GetActualScrollbarSizes();
-          if (margin.top || margin.right || margin.bottom || margin.left) {
-            // Scroll bars will be used for overflow
-            isFocusable = PR_TRUE;
-            tabIndex = 0;
-          }
+        if (scrollFrame && scrollFrame->GetScrollbarVisibility() != 0) {
+          // Scroll bars will be used for overflow
+          isFocusable = PR_TRUE;
+          tabIndex = 0;
         }
       }
     }
   }
 
   if (aTabIndex) {
     *aTabIndex = tabIndex;
   }
--- a/layout/generic/nsGfxScrollFrame.cpp
+++ b/layout/generic/nsGfxScrollFrame.cpp
@@ -279,22 +279,20 @@ GetScrollbarMetrics(nsBoxLayoutState& aS
                     nsSize* aPref, PRBool aVertical)
 {
   NS_ASSERTION(aState.GetRenderingContext(),
                "Must have rendering context in layout state for size "
                "computations");
   
   if (aMin) {
     *aMin = aBox->GetMinSize(aState);
-    nsBox::AddMargin(aBox, *aMin);
   }
  
   if (aPref) {
     *aPref = aBox->GetPrefSize(aState);
-    nsBox::AddMargin(aBox, *aPref);
   }
 }
 
 /**
  * Assuming that we know the metrics for our wrapped frame and
  * whether the horizontal and/or vertical scrollbars are present,
  * compute the resulting layout and return PR_TRUE if the layout is
  * consistent. If the layout is consistent then we fill in the
@@ -480,20 +478,31 @@ nsHTMLScrollFrame::ReflowScrolledFrame(S
   kidReflowState.Init(presContext, -1, -1, nsnull,
                       &aState->mReflowState.mComputedPadding);
   kidReflowState.mFlags.mAssumingHScrollbar = aAssumeHScroll;
   kidReflowState.mFlags.mAssumingVScrollbar = aAssumeVScroll;
   kidReflowState.SetComputedHeight(computedHeight);
   kidReflowState.mComputedMinHeight = computedMinHeight;
   kidReflowState.mComputedMaxHeight = computedMaxHeight;
 
+  // Temporarily set mHasHorizontalScrollbar/mHasVerticalScrollbar to
+  // reflect our assumptions while we reflow the child.
+  PRBool didHaveHorizonalScrollbar = mInner.mHasHorizontalScrollbar;
+  PRBool didHaveVerticalScrollbar = mInner.mHasVerticalScrollbar;
+  mInner.mHasHorizontalScrollbar = aAssumeHScroll;
+  mInner.mHasVerticalScrollbar = aAssumeVScroll;
+
   nsReflowStatus status;
   nsresult rv = ReflowChild(mInner.mScrolledFrame, presContext, *aMetrics,
                             kidReflowState, 0, 0,
                             NS_FRAME_NO_MOVE_FRAME | NS_FRAME_NO_MOVE_VIEW, status);
+
+  mInner.mHasHorizontalScrollbar = didHaveHorizonalScrollbar;
+  mInner.mHasVerticalScrollbar = didHaveVerticalScrollbar;
+
   // Don't resize or position the view (if any) because we're going to resize
   // it to the correct size anyway in PlaceScrollArea. Allowing it to
   // resize here would size it to the natural height of the frame,
   // which will usually be different from the scrollport height;
   // invalidating the difference will cause unnecessary repainting.
   FinishReflowChild(mInner.mScrolledFrame, presContext,
                     &kidReflowState, *aMetrics, 0, 0,
                     NS_FRAME_NO_MOVE_FRAME | NS_FRAME_NO_MOVE_VIEW | NS_FRAME_NO_SIZE_VIEW);
@@ -916,26 +925,24 @@ nsMargin nsGfxScrollFrameInner::GetDesir
   NS_ASSERTION(aState && aState->GetRenderingContext(),
                "Must have rendering context in layout state for size "
                "computations");
   
   nsMargin result(0, 0, 0, 0);
 
   if (mVScrollbarBox) {
     nsSize size = mVScrollbarBox->GetPrefSize(*aState);
-    nsBox::AddMargin(mVScrollbarBox, size);
     if (IsScrollbarOnRight())
       result.left = size.width;
     else
       result.right = size.width;
   }
 
   if (mHScrollbarBox) {
     nsSize size = mHScrollbarBox->GetPrefSize(*aState);
-    nsBox::AddMargin(mHScrollbarBox, size);
     // We don't currently support any scripts that would require a scrollbar
     // at the top. (Are there any?)
     result.bottom = size.height;
   }
 
   return result;
 }
 
@@ -1059,24 +1066,22 @@ nsXULScrollFrame::GetPrefSize(nsBoxLayou
 
   nsGfxScrollFrameInner::ScrollbarStyles styles = GetScrollbarStyles();
 
   // scrolled frames don't have their own margins
 
   if (mInner.mVScrollbarBox &&
       styles.mVertical == NS_STYLE_OVERFLOW_SCROLL) {
     nsSize vSize = mInner.mVScrollbarBox->GetPrefSize(aState);
-    nsBox::AddMargin(mInner.mVScrollbarBox, vSize);
     pref.width += vSize.width;
   }
    
   if (mInner.mHScrollbarBox &&
       styles.mHorizontal == NS_STYLE_OVERFLOW_SCROLL) {
     nsSize hSize = mInner.mHScrollbarBox->GetPrefSize(aState);
-    nsBox::AddMargin(mInner.mHScrollbarBox, hSize);
     pref.height += hSize.height;
   }
 
   AddBorderAndPadding(pref);
   nsIBox::AddCSSPrefSize(aState, this, pref);
   return pref;
 }
 
@@ -1089,26 +1094,24 @@ nsXULScrollFrame::GetMinSize(nsBoxLayout
 
   nsSize min = mInner.mScrolledFrame->GetMinSizeForScrollArea(aState);
 
   nsGfxScrollFrameInner::ScrollbarStyles styles = GetScrollbarStyles();
      
   if (mInner.mVScrollbarBox &&
       styles.mVertical == NS_STYLE_OVERFLOW_SCROLL) {
      nsSize vSize = mInner.mVScrollbarBox->GetMinSize(aState);
-     AddMargin(mInner.mVScrollbarBox, vSize);
      min.width += vSize.width;
      if (min.height < vSize.height)
         min.height = vSize.height;
   }
         
   if (mInner.mHScrollbarBox &&
       styles.mHorizontal == NS_STYLE_OVERFLOW_SCROLL) {
      nsSize hSize = mInner.mHScrollbarBox->GetMinSize(aState);
-     AddMargin(mInner.mHScrollbarBox, hSize);
      min.height += hSize.height;
      if (min.width < hSize.width)
         min.width = hSize.width;
   }
 
   AddBorderAndPadding(min);
   nsIBox::AddCSSMinSize(aState, this, min);
   return min;
@@ -2410,17 +2413,16 @@ PRBool
 nsXULScrollFrame::AddRemoveScrollbar(nsBoxLayoutState& aState,
                                      PRBool aOnTop, PRBool aHorizontal, PRBool aAdd)
 {
   if (aHorizontal) {
      if (mInner.mNeverHasHorizontalScrollbar || !mInner.mHScrollbarBox)
        return PR_FALSE;
 
      nsSize hSize = mInner.mHScrollbarBox->GetPrefSize(aState);
-     nsBox::AddMargin(mInner.mHScrollbarBox, hSize);
 
      mInner.SetScrollbarVisibility(mInner.mHScrollbarBox, aAdd);
 
      PRBool hasHorizontalScrollbar;
      PRBool fit = AddRemoveScrollbar(hasHorizontalScrollbar,
                                      mInner.mScrollPort.y,
                                      mInner.mScrollPort.height,
                                      hSize.height, aOnTop, aAdd);
@@ -2429,17 +2431,16 @@ nsXULScrollFrame::AddRemoveScrollbar(nsB
         mInner.SetScrollbarVisibility(mInner.mHScrollbarBox, !aAdd);
 
      return fit;
   } else {
      if (mInner.mNeverHasVerticalScrollbar || !mInner.mVScrollbarBox)
        return PR_FALSE;
 
      nsSize vSize = mInner.mVScrollbarBox->GetPrefSize(aState);
-     nsBox::AddMargin(mInner.mVScrollbarBox, vSize);
 
      mInner.SetScrollbarVisibility(mInner.mVScrollbarBox, aAdd);
 
      PRBool hasVerticalScrollbar;
      PRBool fit = AddRemoveScrollbar(hasVerticalScrollbar,
                                      mInner.mScrollPort.x,
                                      mInner.mScrollPort.width,
                                      vSize.width, aOnTop, aAdd);
@@ -2957,31 +2958,35 @@ nsGfxScrollFrameInner::LayoutScrollbars(
                "This should have been suppressed");
 
   nsPresContext* presContext = mScrolledFrame->PresContext();
   if (mVScrollbarBox) {
     NS_PRECONDITION(mVScrollbarBox->IsBoxFrame(), "Must be a box frame!");
     nsRect vRect(mScrollPort);
     vRect.width = aContentArea.width - mScrollPort.width;
     vRect.x = IsScrollbarOnRight() ? mScrollPort.XMost() : aContentArea.x;
+#ifdef DEBUG
     nsMargin margin;
     mVScrollbarBox->GetMargin(margin);
-    vRect.Deflate(margin);
+    NS_ASSERTION(margin == nsMargin(0,0,0,0), "Scrollbar margin not supported");
+#endif
     AdjustScrollbarRect(mOuter, presContext, vRect, PR_TRUE);
     LayoutAndInvalidate(aState, mVScrollbarBox, vRect);
   }
 
   if (mHScrollbarBox) {
     NS_PRECONDITION(mHScrollbarBox->IsBoxFrame(), "Must be a box frame!");
     nsRect hRect(mScrollPort);
     hRect.height = aContentArea.height - mScrollPort.height;
     hRect.y = PR_TRUE ? mScrollPort.YMost() : aContentArea.y;
+#ifdef DEBUG
     nsMargin margin;
     mHScrollbarBox->GetMargin(margin);
-    hRect.Deflate(margin);
+    NS_ASSERTION(margin == nsMargin(0,0,0,0), "Scrollbar margin not supported");
+#endif
     AdjustScrollbarRect(mOuter, presContext, hRect, PR_FALSE);
     LayoutAndInvalidate(aState, mHScrollbarBox, hRect);
   }
 
   // place the scrollcorner
   if (mScrollCornerBox) {
     NS_PRECONDITION(mScrollCornerBox->IsBoxFrame(), "Must be a box frame!");
     nsRect r(0, 0, 0, 0);
@@ -3095,22 +3100,30 @@ nsGfxScrollFrameInner::GetScrolledRectIn
     // effectively repositioning the frame.
     nscoord extraWidth = NS_MAX(0, mScrolledFrame->GetSize().width - aScrollPortSize.width);
     x2 += extraWidth;
   }
   return nsRect(x1, y1, x2 - x1, y2 - y1);
 }
 
 nsMargin
-nsGfxScrollFrameInner::GetActualScrollbarSizes() const {
-  nsRect r = mOuter->GetPaddingRect() - mOuter->GetPosition();
-
-  return nsMargin(mScrollPort.x - r.x, mScrollPort.y - r.y,
-                  r.XMost() - mScrollPort.XMost(),
-                  r.YMost() - mScrollPort.YMost());
+nsGfxScrollFrameInner::GetActualScrollbarSizes() const
+{
+  nsMargin result(0, 0, 0, 0);
+  if (mVScrollbarBox) {
+    if (IsScrollbarOnRight()) {
+      result.right = mVScrollbarBox->GetRect().width;
+    } else {
+      result.left = mVScrollbarBox->GetRect().width;
+    }
+  }
+  if (mHScrollbarBox) {
+    result.bottom = mHScrollbarBox->GetRect().height;
+  }
+  return result;
 }
 
 void
 nsGfxScrollFrameInner::SetScrollbarVisibility(nsIBox* aScrollbar, PRBool aVisible)
 {
   if (!aScrollbar)
     return;
 
--- a/layout/generic/nsGfxScrollFrame.h
+++ b/layout/generic/nsGfxScrollFrame.h
@@ -201,16 +201,20 @@ public:
    * Currently it allows scrolling down and to the right for
    * nsHTMLScrollFrames with LTR directionality and for all
    * nsXULScrollFrames, and allows scrolling down and to the left for
    * nsHTMLScrollFrames with RTL directionality.
    */
   nsRect GetScrolledRectInternal(const nsRect& aScrolledOverflowArea,
                                  const nsSize& aScrollPortSize) const;
 
+  PRUint32 GetScrollbarVisibility() const {
+    return (mHasVerticalScrollbar ? nsIScrollableFrame::VERTICAL : 0) |
+           (mHasHorizontalScrollbar ? nsIScrollableFrame::HORIZONTAL : 0);
+  }
   nsMargin GetActualScrollbarSizes() const;
   nsMargin GetDesiredScrollbarSizes(nsBoxLayoutState* aState);
   PRBool IsLTR() const;
   PRBool IsScrollbarOnRight() const;
   void LayoutScrollbars(nsBoxLayoutState& aState,
                         const nsRect& aContentArea,
                         const nsRect& aOldScrollArea);
 
@@ -371,16 +375,19 @@ public:
 
   // nsIScrollableFrame
   virtual nsIFrame* GetScrolledFrame() const {
     return mInner.GetScrolledFrame();
   }
   virtual nsGfxScrollFrameInner::ScrollbarStyles GetScrollbarStyles() const {
     return mInner.GetScrollbarStylesFromFrame();
   }
+  virtual PRUint32 GetScrollbarVisibility() const {
+    return mInner.GetScrollbarVisibility();
+  }
   virtual nsMargin GetActualScrollbarSizes() const {
     return mInner.GetActualScrollbarSizes();
   }
   virtual nsMargin GetDesiredScrollbarSizes(nsBoxLayoutState* aState) {
     return mInner.GetDesiredScrollbarSizes(aState);
   }
   virtual nsMargin GetDesiredScrollbarSizes(nsPresContext* aPresContext,
           nsIRenderingContext* aRC) {
@@ -593,16 +600,19 @@ public:
 
   // nsIScrollableFrame
   virtual nsIFrame* GetScrolledFrame() const {
     return mInner.GetScrolledFrame();
   }
   virtual nsGfxScrollFrameInner::ScrollbarStyles GetScrollbarStyles() const {
     return mInner.GetScrollbarStylesFromFrame();
   }
+  virtual PRUint32 GetScrollbarVisibility() const {
+    return mInner.GetScrollbarVisibility();
+  }
   virtual nsMargin GetActualScrollbarSizes() const {
     return mInner.GetActualScrollbarSizes();
   }
   virtual nsMargin GetDesiredScrollbarSizes(nsBoxLayoutState* aState) {
     return mInner.GetDesiredScrollbarSizes(aState);
   }
   virtual nsMargin GetDesiredScrollbarSizes(nsPresContext* aPresContext,
           nsIRenderingContext* aRC) {
--- a/layout/generic/nsIScrollableFrame.h
+++ b/layout/generic/nsIScrollableFrame.h
@@ -69,31 +69,40 @@ public:
   typedef nsPresContext::ScrollbarStyles ScrollbarStyles;
   /**
    * Get the styles (NS_STYLE_OVERFLOW_SCROLL, NS_STYLE_OVERFLOW_HIDDEN,
    * or NS_STYLE_OVERFLOW_AUTO) governing the horizontal and vertical
    * scrollbars for this frame.
    */
   virtual ScrollbarStyles GetScrollbarStyles() const = 0;
 
+  enum { HORIZONTAL = 0x01, VERTICAL = 0x02 };
+  /**
+   * Return the scrollbars which are visible. It's OK to call this during reflow
+   * of the scrolled contents, in which case it will reflect the current
+   * assumptions about scrollbar visibility.
+   */
+  virtual PRUint32 GetScrollbarVisibility() const = 0;
   /**
    * Return the actual sizes of all possible scrollbars. Returns 0 for scrollbar
    * positions that don't have a scrollbar or where the scrollbar is not visible.
    * Do not call this while this frame's descendants are being reflowed, it won't be
    * accurate.
    */
   virtual nsMargin GetActualScrollbarSizes() const = 0;
   /**
    * Return the sizes of all scrollbars assuming that any scrollbars that could
-   * be visible due to overflowing content, are.
+   * be visible due to overflowing content, are. This can be called during reflow
+   * of the scrolled contents.
    */
   virtual nsMargin GetDesiredScrollbarSizes(nsBoxLayoutState* aState) = 0;
   /**
    * Return the sizes of all scrollbars assuming that any scrollbars that could
-   * be visible due to overflowing content, are.
+   * be visible due to overflowing content, are. This can be called during reflow
+   * of the scrolled contents.
    */
   virtual nsMargin GetDesiredScrollbarSizes(nsPresContext* aPresContext,
                                             nsIRenderingContext* aRC) = 0;
 
   /**
    * Get the area of the scrollport relative to the origin of this frame's
    * border-box.
    * This is the area of this frame minus border and scrollbars.
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/opacity-and-gradient-02-ref.svg
@@ -0,0 +1,34 @@
+<!--
+     Any copyright is dedicated to the Public Domain.
+     http://creativecommons.org/licenses/publicdomain/
+-->
+<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
+
+  <title>Testcase for opacity on elements referencing a gradient</title>
+
+  <!-- From https://bugzilla.mozilla.org/show_bug.cgi?id=539165 -->
+
+  <defs>
+    <linearGradient id="lime" gradientUnits="userSpaceOnUse">
+      <stop stop-color="lime"/>
+    </linearGradient>
+    <!-- OS X doesn't draw solid gradients as a solid color so we need to use
+         a gradient fill below
+      -->
+    <linearGradient id="red" gradientUnits="userSpaceOnUse">
+      <stop stop-color="red"/>
+    </linearGradient>
+ </defs>
+
+  <rect width="100%" height="100%" fill="url(#lime)"/>
+
+  <!-- test 'opacity' -->
+  <rect width="25%" height="100%" fill="url(#red)" opacity="1"/>
+  
+  <!-- test 'fill-opacity' -->
+  <rect x="25%" width="25%" height="100%" fill="url(#red)" opacity="0.5"/>
+
+  <!-- test 'fill-opacity' -->
+  <rect x="50%" width="25%" height="100%" fill="url(#red)" opacity="0.5"/>
+
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/opacity-and-gradient-02.svg
@@ -0,0 +1,42 @@
+<!--
+     Any copyright is dedicated to the Public Domain.
+     http://creativecommons.org/licenses/publicdomain/
+-->
+<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
+
+  <title>Testcase for opacity on elements referencing a gradient</title>
+
+  <!-- From https://bugzilla.mozilla.org/show_bug.cgi?id=539165 -->
+
+  <defs>
+    <linearGradient id="lime" gradientUnits="userSpaceOnUse">
+      <stop stop-color="lime"/>
+    </linearGradient>
+    <linearGradient id="red" gradientUnits="userSpaceOnUse">
+      <stop stop-color="red"/>
+    </linearGradient>
+    <linearGradient id="red2" gradientUnits="userSpaceOnUse">
+      <stop stop-color="red" offset="0%"/>
+      <stop stop-color="red" offset="100%"/>
+    </linearGradient>
+    <linearGradient id="redgreen" gradientUnits="userSpaceOnUse">
+      <stop stop-color="red" offset="0%"/>
+      <stop stop-color="lime" offset="100%"/>
+    </linearGradient>
+  </defs>
+
+  <rect width="100%" height="100%" fill="url(#lime)"/>
+
+  <!-- test 'opacity' -->
+  <rect width="25%" height="100%" fill="red" opacity="1"/>
+  
+  <!-- test 'fill-opacity' -->
+  <rect x="25%" width="25%" height="100%" fill="url(#red)" fill-opacity="0.5"/>
+
+  <!-- test 'fill-opacity' -->
+  <rect x="50%" width="25%" height="100%" fill="url(#red2)" fill-opacity="0.5"/>
+  
+  <!-- test 'fill-opacity' -->
+  <rect x="75%" width="25%" height="100%" fill="url(#redgreen)" fill-opacity="0"/>
+
+</svg>
--- a/layout/reftests/svg/reftest.list
+++ b/layout/reftests/svg/reftest.list
@@ -96,16 +96,17 @@ fails == inline-in-xul-basic-01.xul pass
 # == mask-transformed-01.svg mask-transformed-01-ref.svg
 == nested-viewBox-01.svg pass.svg
 == objectBoundingBox-and-clipPath.svg pass.svg
 == objectBoundingBox-and-mask.svg pass.svg
 == objectBoundingBox-and-pattern-01a.svg objectBoundingBox-and-pattern-01-ref.svg
 == objectBoundingBox-and-pattern-01b.svg objectBoundingBox-and-pattern-01-ref.svg
 == objectBoundingBox-and-pattern-01c.svg objectBoundingBox-and-pattern-01-ref.svg
 fails-if(http.oscpu.match(/Mac\x20OS\x20X\x2010\.4$/)) == opacity-and-gradient-01.svg pass.svg # fails on OS X 10.4 (bug 379610)
+== opacity-and-gradient-02.svg opacity-and-gradient-02-ref.svg
 == opacity-and-pattern-01.svg pass.svg
 == path-01.svg path-01-ref.svg
 == pattern-live-01a.svg pattern-live-01-ref.svg
 == pattern-live-01b.svg pattern-live-01-ref.svg
 == pattern-live-01c.svg pattern-live-01-ref.svg
 == pseudo-classes-01.svg pass.svg
 == pseudo-classes-02.svg pseudo-classes-02-ref.svg
 == radialGradient-basic-01.svg pass.svg
--- a/layout/style/test/test_css_cross_domain.html
+++ b/layout/style/test/test_css_cross_domain.html
@@ -86,18 +86,15 @@ function check_iframe(ifr) {
 	    .getPropertyValue("background-color");
 
 	is(color, "rgb(0, 255, 0)", ifr.id + " " + cases[i].id);
     }
 }
 
 SimpleTest.waitForExplicitFinish();
 window.onload = function() {
-    // The quirks-mode tests are inexplicably failing intermittently
-    // on Mac (bug 536603), so disable them for now.
-    if (navigator.platform.substring(0,3) != "Mac")
-        check_iframe(document.getElementById("quirks"));
+    check_iframe(document.getElementById("quirks"));
     check_iframe(document.getElementById("standards"));
     SimpleTest.finish();
 };
 </script>
 </body>
 </html>
--- a/layout/tables/nsTableFrame.cpp
+++ b/layout/tables/nsTableFrame.cpp
@@ -6162,17 +6162,19 @@ BCPaintBorderIterator::BCPaintBorderIter
   mTableCellMap        = mTable->GetCellMap();
   // y position of first row in damage area
   mInitialOffsetY = (mTable->GetPrevInFlow()) ? 0 : childAreaOffset.top;
   mNumTableRows  = mTable->GetRowCount();
   mNumTableCols  = mTable->GetColCount();
 
   // Get the ordered row groups
   mTable->OrderRowGroups(mRowGroups);
-
+  // initialize to a non existing index
+  mRepeatedHeaderRowIndex = -99;
+  
   mTableIsLTR = mTable->GetStyleVisibility()->mDirection ==
                    NS_STYLE_DIRECTION_LTR;
   mColInc = (mTableIsLTR) ? 1 : -1;
 
   nsStyleContext* bgContext =
     nsCSSRendering::FindNonTransparentBackground(mTable->GetStyleContext());
   mTableBgColor = bgContext->GetStyleBackground();
 }
--- a/layout/tools/reftest/reftest.js
+++ b/layout/tools/reftest/reftest.js
@@ -578,16 +578,17 @@ function StartCurrentURI(aState)
     if (gURICanvases[gCurrentURL] &&
         (gURLs[0].type == TYPE_REFTEST_EQUAL ||
          gURLs[0].type == TYPE_REFTEST_NOTEQUAL) &&
         gURLs[0].maxAsserts == 0) {
         // Pretend the document loaded --- DocumentLoaded will notice
         // there's already a canvas for this URL
         setTimeout(DocumentLoaded, 0);
     } else {
+        dump("REFTEST INFO | Loading " + gCurrentURL + "\n");
         gBrowser.loadURI(gCurrentURL);
     }
 }
 
 function DoneTests()
 {
     // TEMPORARILY DISABLE REPORTING OF ASSERTION FAILURES.
     gTestResults.AssertionUnexpected = 0;
@@ -1093,16 +1094,17 @@ function LoadFailed()
          gURLs[0]["url" + gState].spec + " | " + gFailureReason + "\n");
     FinishTestItem();
 }
 
 function FinishTestItem()
 {
     // Replace document with BLANK_URL_FOR_CLEARING in case there are
     // assertions when unloading.
+    dump("REFTEST INFO | Loading a blank page\n");
     gClearingForAssertionCheck = true;
     gBrowser.loadURI(BLANK_URL_FOR_CLEARING);
 }
 
 function DoAssertionCheck()
 {
     gClearingForAssertionCheck = false;
 
--- a/layout/xul/base/src/grid/nsGridRowLeafLayout.cpp
+++ b/layout/xul/base/src/grid/nsGridRowLeafLayout.cpp
@@ -263,21 +263,25 @@ nsGridRowLeafLayout::ComputeChildSizes(n
     nscoord diff = 0;
     nsCOMPtr<nsIGridPart> parent;
     nsIBox* parentBox;
     GetParentGridPart(aBox, &parentBox, getter_AddRefs(parent));
     while (parentBox) {
       nsIBox* scrollbox = nsGrid::GetScrollBox(parentBox);
       nsIScrollableFrame *scrollable = do_QueryFrame(scrollbox);
       if (scrollable) {
-        nsMargin scrollbarSizes = scrollable->GetActualScrollbarSizes();
+        // Don't call GetActualScrollbarSizes here because it's not safe
+        // to call that while we're reflowing the contents of the scrollframe,
+        // which we are here.
+        nsMargin scrollbarSizes = scrollable->GetDesiredScrollbarSizes(&aState);
+        PRUint32 visible = scrollable->GetScrollbarVisibility();
 
-        if (isHorizontal) {
+        if (isHorizontal && (visible & nsIScrollableFrame::VERTICAL)) {
           diff += scrollbarSizes.left + scrollbarSizes.right;
-        } else {
+        } else if (!isHorizontal && (visible & nsIScrollableFrame::HORIZONTAL)) {
           diff += scrollbarSizes.top + scrollbarSizes.bottom;
         }
       }
 
       GetParentGridPart(parentBox, &parentBox, getter_AddRefs(parent));
     }
 
     if (diff > 0) {
--- a/modules/libpref/src/Makefile.in
+++ b/modules/libpref/src/Makefile.in
@@ -43,17 +43,17 @@ VPATH		= @srcdir@
 include $(DEPTH)/config/autoconf.mk
 
 MODULE		= pref
 LIBRARY_NAME	= pref
 EXPORT_LIBRARY = 1
 IS_COMPONENT	= 1
 MODULE_NAME	= nsPrefModule
 ifeq ($(OS_ARCH)$(MOZ_ENABLE_LIBXUL),WINNT)
-LIBRARY_NAME	= xppref$(MOZ_BITS)
+LIBRARY_NAME	= xppref32
 endif
 GRE_MODULE	= 1
 LIBXUL_LIBRARY = 1
 
 include $(topsrcdir)/config/config.mk
 
 CPPSRCS		= nsPref.cpp \
 			  nsPrefBranch.cpp	\
--- a/netwerk/test/httpserver/httpd.js
+++ b/netwerk/test/httpserver/httpd.js
@@ -473,17 +473,20 @@ nsHttpServer.prototype =
 
     this._port = port;
     this._doQuit = this._socketClosed = false;
 
     try
     {
       var socket = new ServerSocket(this._port,
                                     true, // loopback only
-                                    -1);  // default number of pending connections
+                                    20);  // the listen queue needs to be
+                                          // larger than the browser's max
+                                          // number of concurrent connections
+                                          // (presently 15).
 
       dumpn(">>> listening on port " + socket.port);
       socket.asyncListen(this);
       this._identity._initialize(port, true);
       this._socket = socket;
     }
     catch (e)
     {
--- a/testing/mochitest/runtests.py.in
+++ b/testing/mochitest/runtests.py.in
@@ -49,17 +49,17 @@ import os.path
 import sys
 import time
 import shutil
 from urllib import quote_plus as encodeURIComponent
 import urllib2
 import commands
 from automation import Automation
 from automationutils import *
-
+import tempfile
 
 #######################
 # COMMANDLINE OPTIONS #
 #######################
 
 class MochitestOptions(optparse.OptionParser):
   """Parses Mochitest commandline options."""
   def __init__(self, automation, scriptdir, **kwargs):
@@ -207,30 +207,30 @@ class MochitestOptions(optparse.OptionPa
 Usage instructions for runtests.py.
 All arguments are optional.
 If --chrome is specified, chrome tests will be run instead of web content tests.
 If --browser-chrome is specified, browser-chrome tests will be run instead of web content tests.
 See <http://mochikit.com/doc/html/MochiKit/Logging.html> for details on the logging levels."""
     self.set_usage(usage)
 
 
-
 #######################
 # HTTP SERVER SUPPORT #
 #######################
 
 class MochitestServer:
   "Web server used to serve Mochitests, for closer fidelity to the real web."
 
-  def __init__(self, automation, options, profileDir):
+  def __init__(self, automation, options, profileDir, shutdownURL):
     self._automation = automation
     self._closeWhenDone = options.closeWhenDone
     self._utilityPath = options.utilityPath
     self._xrePath = options.xrePath
     self._profileDir = profileDir
+    self.shutdownURL = shutdownURL
 
   def start(self):
     "Run the Mochitest server, returning the process ID of the server."
     
     env = self._automation.environment(xrePath = self._xrePath)
     env["XPCOM_DEBUG_BREAK"] = "warn"
     if self._automation.IS_WIN32:
       env["PATH"] = env["PATH"] + ";" + self._xrePath
@@ -261,34 +261,32 @@ class MochitestServer:
       i += 1
     else:
       print "Timed out while waiting for server startup."
       self.stop()
       sys.exit(1)
 
   def stop(self):
     try:
-      c = urllib2.urlopen(SERVER_SHUTDOWN_URL)
+      c = urllib2.urlopen(self.shutdownURL)
       c.read()
       c.close()
       self._process.wait()
     except:
       self._process.kill()
 
 
 class Mochitest(object):
   # Path to the test script on the server
   TEST_SERVER_HOST = "localhost:8888"
   TEST_PATH = "/tests/"
   CHROME_PATH = "/redirect.html";
   A11Y_PATH = "/redirect-a11y.html"
-  TESTS_URL = "http://" + TEST_SERVER_HOST + TEST_PATH
-  CHROMETESTS_URL = "http://" + TEST_SERVER_HOST + CHROME_PATH
-  A11YTESTS_URL = "http://" + TEST_SERVER_HOST + A11Y_PATH
-  SERVER_SHUTDOWN_URL = "http://" + TEST_SERVER_HOST + "/server/shutdown"
+  urlOpts = []
+  runSSLTunnel = True
  
   oldcwd = os.getcwd()
 
   def __init__(self, automation):
     self.automation = automation
 
     # Max time in seconds to wait for server startup before tests will fail -- if
     # this seems big, it's mostly for debug machines where cold startup
@@ -304,152 +302,190 @@ class Mochitest(object):
     self.PROFILE_DIRECTORY = os.path.abspath("./mochitesttestingprofile")
 
     self.LEAK_REPORT_FILE = os.path.join(self.PROFILE_DIRECTORY, "runtests_leaks.log")
 
   def getFullPath(self, path):
     "Get an absolute path relative to self.oldcwd."
     return os.path.normpath(os.path.join(self.oldcwd, os.path.expanduser(path)))
 
-  def runTests(self, options):
-    debuggerInfo = getDebuggerInfo(self.oldcwd, options.debugger, options.debuggerArgs,
-                      options.debuggerInteractive);
+  def buildTestPath(self, options):
+    """ build the url path to the specific test harness and test file or directory """
+    testHost = "http://" + self.TEST_SERVER_HOST
+    testURL = testHost + self.TEST_PATH + options.testPath
+    if options.chrome:
+      testURL = testHost + self.CHROME_PATH
+      if options.testPath:
+        self.urlOpts.append("testPath=" + encodeURIComponent(options.testPath))
+    elif options.a11y:
+      testURL = testHost + self.A11Y_PATH
+      if options.testPath:
+        self.urlOpts.append("testPath=" + encodeURIComponent(options.testPath))
+    elif options.browserChrome:
+      testURL = "about:blank"
+    return testURL
+
+  def startWebServer(self, options):
+    """ create the webserver and start it up """
+    shutdownURL = "http://" + self.TEST_SERVER_HOST + "/server/shutdown"
+    self.server = MochitestServer(self.automation, options, self.PROFILE_DIRECTORY, shutdownURL)
+    self.server.start()
 
-    # browser environment
+    # If we're lucky, the server has fully started by now, and all paths are
+    # ready, etc.  However, xpcshell cold start times suck, at least for debug
+    # builds.  We'll try to connect to the server for awhile, and if we fail,
+    # we'll try to kill the server and exit with an error.
+    self.server.ensureReady(self.SERVER_STARTUP_TIMEOUT)
+
+  def stopWebServer(self):
+    """ Server's no longer needed, and perhaps more importantly, anything it might
+        spew to console shouldn't disrupt the leak information table we print next.
+    """
+    self.server.stop()
+
+  def getLogFilePath(self, logFile):
+    """ return the log file path relative to the device we are testing on, in most cases 
+        it will be the full path on the local system
+    """
+    return self.getFullPath(logFile)
+
+  def buildProfile(self, options):
+    """ create the profile and add optional chrome bits and files if requested """
+    self.automation.initializeProfile(self.PROFILE_DIRECTORY, options.extraPrefs)
+    manifest = self.addChromeToProfile(options)
+    self.copyExtraFilesToProfile(options)
+    return manifest
+
+  def buildBrowserEnv(self, options):
+    """ build the environment variables for the specific test and operating system """
     browserEnv = self.automation.environment(xrePath = options.xrePath)
 
     # These variables are necessary for correct application startup; change
     # via the commandline at your own risk.
     browserEnv["XPCOM_DEBUG_BREAK"] = "stack"
 
     for v in options.environment:
       ix = v.find("=")
       if ix <= 0:
         print "Error: syntax error in --setenv=" + v
-        return 1
+        return None
       browserEnv[v[:ix]] = v[ix + 1:]
 
-    self.automation.initializeProfile(self.PROFILE_DIRECTORY, options.extraPrefs)
-    manifest = self.addChromeToProfile(options)
-    self.copyExtraFilesToProfile(options)
-    server = MochitestServer(self.automation, options, self.PROFILE_DIRECTORY)
-    server.start()
-
-    # If we're lucky, the server has fully started by now, and all paths are
-    # ready, etc.  However, xpcshell cold start times suck, at least for debug
-    # builds.  We'll try to connect to the server for awhile, and if we fail,
-    # we'll try to kill the server and exit with an error.
-    server.ensureReady(self.SERVER_STARTUP_TIMEOUT)
-
-    # URL parameters to test URL:
-    #
-    # autorun -- kick off tests automatically
-    # closeWhenDone -- runs quit.js after tests
-    # logFile -- logs test run to an absolute path
-    # totalChunks -- how many chunks to split tests into
-    # thisChunk -- which chunk to run
-    # timeout -- per-test timeout in seconds
-    #
-  
-    # consoleLevel, fileLevel: set the logging level of the console and
-    # file logs, if activated.
-    # <http://mochikit.com/doc/html/MochiKit/Logging.html>
-
-    testURL = self.TESTS_URL + options.testPath
-    urlOpts = []
-    if options.chrome:
-      testURL = self.CHROMETESTS_URL
-      if options.testPath:
-        urlOpts.append("testPath=" + encodeURIComponent(options.testPath))
-    elif options.a11y:
-      testURL = self.A11YTESTS_URL
-      if options.testPath:
-        urlOpts.append("testPath=" + encodeURIComponent(options.testPath))
-    elif options.browserChrome:
-      testURL = "about:blank"
-
-    # allow relative paths for logFile
-    if options.logFile:
-      options.logFile = self.getFullPath(options.logFile)
-    if options.browserChrome:
-      self.makeTestConfig(options)
-    else:
-      if options.autorun:
-        urlOpts.append("autorun=1")
-      if options.timeout:
-        urlOpts.append("timeout=%d" % options.timeout)
-      if options.closeWhenDone:
-        urlOpts.append("closeWhenDone=1")
-      if options.logFile:
-        urlOpts.append("logFile=" + encodeURIComponent(options.logFile))
-        urlOpts.append("fileLevel=" + encodeURIComponent(options.fileLevel))
-      if options.consoleLevel:
-        urlOpts.append("consoleLevel=" + encodeURIComponent(options.consoleLevel))
-      if options.totalChunks:
-        urlOpts.append("totalChunks=%d" % options.totalChunks)
-        urlOpts.append("thisChunk=%d" % options.thisChunk)
-      if options.chunkByDir:
-        urlOpts.append("chunkByDir=%d" % options.chunkByDir)
-      if options.shuffle:
-        urlOpts.append("shuffle=1")
-      if len(urlOpts) > 0:
-        testURL += "?" + "&".join(urlOpts)
-
     browserEnv["XPCOM_MEM_BLOAT_LOG"] = self.LEAK_REPORT_FILE
 
     if options.fatalAssertions:
       browserEnv["XPCOM_DEBUG_BREAK"] = "stack-and-abort"
 
-    # run once with -silent to let the extension manager do its thing
-    # and then exit the app
+    return browserEnv
+
+  def runExtensionRegistration(self, options, browserEnv):
+    """ run once with -silent to let the extension manager do its thing
+        and then exit the app
+    """
     self.automation.log.info("INFO | runtests.py | Performing extension manager registration: start.\n")
     # Don't care about this |status|: |runApp()| reporting it should be enough.
     status = self.automation.runApp(None, browserEnv, options.app,
                                 self.PROFILE_DIRECTORY, ["-silent"],
                                 utilityPath = options.utilityPath,
                                 xrePath = options.xrePath,
                                 symbolsPath=options.symbolsPath)
     # We don't care to call |processLeakLog()| for this step.
     self.automation.log.info("\nINFO | runtests.py | Performing extension manager registration: end.")
 
+  def buildURLOptions(self, options):
+    """ Add test control options from the command line to the url 
+
+        URL parameters to test URL:
+
+        autorun -- kick off tests automatically
+        closeWhenDone -- runs quit.js after tests
+        logFile -- logs test run to an absolute path
+        totalChunks -- how many chunks to split tests into
+        thisChunk -- which chunk to run
+        timeout -- per-test timeout in seconds
+    """
+  
+    # allow relative paths for logFile
+    if options.logFile:
+      options.logFile = self.getFullPath(options.logFile)
+    if options.browserChrome:
+      self.makeTestConfig(options)
+    else:
+      if options.autorun:
+        self.urlOpts.append("autorun=1")
+      if options.timeout:
+        self.urlOpts.append("timeout=%d" % options.timeout)
+      if options.closeWhenDone:
+        self.urlOpts.append("closeWhenDone=1")
+      if options.logFile:
+        self.urlOpts.append("logFile=" + encodeURIComponent(options.logFile))
+        self.urlOpts.append("fileLevel=" + encodeURIComponent(options.fileLevel))
+      if options.consoleLevel:
+        self.urlOpts.append("consoleLevel=" + encodeURIComponent(options.consoleLevel))
+      if options.totalChunks:
+        self.urlOpts.append("totalChunks=%d" % options.totalChunks)
+        self.urlOpts.append("thisChunk=%d" % options.thisChunk)
+      if options.chunkByDir:
+        self.urlOpts.append("chunkByDir=%d" % options.chunkByDir)
+      if options.shuffle:
+        self.urlOpts.append("shuffle=1")
+
+  def cleanup(self, manifest):
+    """ remove temporary files and profile """
+    os.remove(manifest)
+    shutil.rmtree(self.PROFILE_DIRECTORY)
+
+  def runTests(self, options):
+    """ Prepare, configure, run tests and cleanup """
+    debuggerInfo = getDebuggerInfo(self.oldcwd, options.debugger, options.debuggerArgs,
+                      options.debuggerInteractive);
+
+    browserEnv = self.buildBrowserEnv(options)
+    if (browserEnv == None):
+      return 1
+
+    manifest = self.buildProfile(options)
+    self.startWebServer(options)
+
+
+    testURL = self.buildTestPath(options)
+    self.buildURLOptions(options)
+    if (len(self.urlOpts) > 0):
+      testURL += "?" + "&".join(self.urlOpts)
+
+    self.runExtensionRegistration(options, browserEnv)
+
     # Remove the leak detection file so it can't "leak" to the tests run.
     # The file is not there if leak logging was not enabled in the application build.
     if os.path.exists(self.LEAK_REPORT_FILE):
       os.remove(self.LEAK_REPORT_FILE)
 
     # then again to actually run mochitest
     if options.timeout:
       timeout = options.timeout + 30
     elif options.autorun:
       timeout = None
     else:
       timeout = 330.0 # default JS harness timeout is 300 seconds
     self.automation.log.info("INFO | runtests.py | Running tests: start.\n")
     status = self.automation.runApp(testURL, browserEnv, options.app,
                                 self.PROFILE_DIRECTORY, options.browserArgs,
-                                runSSLTunnel = True,
+                                runSSLTunnel = self.runSSLTunnel,
                                 utilityPath = options.utilityPath,
                                 xrePath = options.xrePath,
                                 certPath=options.certPath,
                                 debuggerInfo=debuggerInfo,
                                 symbolsPath=options.symbolsPath,
                                 timeout = timeout)
 
-    # Server's no longer needed, and perhaps more importantly, anything it might
-    # spew to console shouldn't disrupt the leak information table we print next.
-    server.stop()
-
+    self.stopWebServer()
     processLeakLog(self.LEAK_REPORT_FILE, options.leakThreshold)
     self.automation.log.info("\nINFO | runtests.py | Running tests: end.")
 
-    # delete the profile and manifest
-    os.remove(manifest)
-
-    # hanging due to non-halting threads is no fun; assume we hit the errors we
-    # were going to hit already and exit.
+    self.cleanup(manifest)
     return status
 
   def makeTestConfig(self, options):
     "Creates a test configuration file for customizing test execution."
     def boolString(b):
       if b:
         return "true"
       return "false"
@@ -495,28 +531,33 @@ toolbar#nav-bar {
     chromeFile.close()
 
 
     # register our chrome dir
     chrometestDir = os.path.abspath(".") + "/"
     if self.automation.IS_WIN32:
       chrometestDir = "file:///" + chrometestDir.replace("\\", "/")
 
-
-    (path, leaf) = os.path.split(options.app)
-    manifest = os.path.join(path, "chrome", "mochikit.manifest")
-    manifestFile = open(manifest, "w")
+    temp_file = os.path.join(tempfile.mkdtemp(), "mochikit.manifest")
+    manifestFile = open(temp_file, "w")
     manifestFile.write("content mochikit " + chrometestDir + " contentaccessible=yes\n")
 
     if options.browserChrome:
       manifestFile.write("""overlay chrome://navigator/content/navigator.xul chrome://mochikit/content/browser-test-overlay.xul
 overlay chrome://browser/content/browser.xul chrome://mochikit/content/browser-test-overlay.xul
 """)
     manifestFile.close()
 
+    return self.installChromeFile(temp_file, options)
+
+  def installChromeFile(self, filename, options):
+    (p, file) = os.path.split(filename)
+    (path, leaf) = os.path.split(options.app)
+    manifest = os.path.join(path, "chrome", file)
+    shutil.copy(filename, manifest)
     return manifest
 
   def copyExtraFilesToProfile(self, options):
     "Copy extra files or dirs specified on the command line to the testing profile."
     for f in options.extraProfileFiles:
       abspath = self.getFullPath(f)
       dest = os.path.join(self.PROFILE_DIRECTORY, os.path.basename(abspath))
       if os.path.isdir(abspath):
--- a/testing/mochitest/ssltunnel/ssltunnel.cpp
+++ b/testing/mochitest/ssltunnel/ssltunnel.cpp
@@ -207,43 +207,51 @@ bool ReadConnectRequest(server_info_t* s
   if (strncmp(buffer.buffertail-4, "\r\n\r\n", 4)) {
     printf(" !! request is not tailed with CRLFCRLF but with %x %x %x %x", 
            *(buffer.buffertail-4),
            *(buffer.buffertail-3),
            *(buffer.buffertail-2),
            *(buffer.buffertail-1));
     return false;
   }
+  
+  printf(" parsing initial connect request, dump:\n%.*s\n", (int)buffer.present(), buffer.bufferhead);
 
   *result = 400;
 
   char* token;
   token = strtok(buffer.bufferhead, " ");
-  if (!token) 
+  if (!token) {
+    printf(" no space found");
     return true;
-  if (strcmp(token, "CONNECT")) 
+  }
+  if (strcmp(token, "CONNECT")) {
+    printf(" not CONNECT request but %s", token);
     return true;
+  }
 
   token = strtok(NULL, " ");
   void* c = PL_HashTableLookup(server_info->host_cert_table, token);
   if (c)
     certificate = static_cast<char*>(c);
 
   host = "https://";
   host += token;
 
   c = PL_HashTableLookup(server_info->host_clientauth_table, token);
   if (c)
     *clientauth = *static_cast<client_auth_option*>(c);
   else
     *clientauth = caNone;
 
   token = strtok(NULL, "/");
-  if (strcmp(token, "HTTP"))
+  if (strcmp(token, "HTTP")) {  
+    printf(" not tailed with HTTP but with %s", token);
     return true;
+  }
 
   *result = 200;
   return true;
 }
 
 bool ConfigureSSLServerSocket(PRFileDesc* socket, server_info_t* si, string &certificate, client_auth_option clientAuth)
 {
   const char* certnick = certificate.empty() ?
@@ -487,16 +495,17 @@ void HandleConnection(void* data)
                 &response, certificateToUse, &clientAuth, fullHost))
             {
               // Clean the request as it would be read
               buffers[s].bufferhead = buffers[s].buffertail = buffers[s].buffer;
 
               // Store response to the oposite buffer
               if (response != 200)
               {
+                printf(" could not read the connect request, closing connection with %d", response);
                 client_done = true;
                 sprintf(buffers[s2].buffer, "HTTP/1.1 %d ERROR\r\nConnection: close\r\n\r\n", response);
                 buffers[s2].buffertail = buffers[s2].buffer + strlen(buffers[s2].buffer);
                 break;
               }
 
               strcpy(buffers[s2].buffer, "HTTP/1.1 200 Connected\r\nConnection: keep-alive\r\n\r\n");
               buffers[s2].buffertail = buffers[s2].buffer + strlen(buffers[s2].buffer);
--- a/toolkit/components/search/Makefile.in
+++ b/toolkit/components/search/Makefile.in
@@ -46,15 +46,11 @@ include $(DEPTH)/config/autoconf.mk
 MODULE = toolkitsearch
 XPIDL_MODULE = toolkitsearch
 
 XPIDLSRCS = nsIBrowserSearchService.idl
 
 EXTRA_PP_COMPONENTS = nsSearchService.js \
 	nsSearchSuggestions.js
 
-ifdef MOZILLA_OFFICIAL
-DEFINES += -DOFFICIAL_BUILD=1
-endif
-
 DEFINES += -DMOZ_DISTRIBUTION_ID=$(MOZ_DISTRIBUTION_ID)
 
 include $(topsrcdir)/config/rules.mk
--- a/toolkit/components/search/nsSearchService.js
+++ b/toolkit/components/search/nsSearchService.js
@@ -141,17 +141,17 @@ const EMPTY_DOC = "<?xml version=\"1.0\"
                   " xmlns:os=\"" + OPENSEARCH_NS_11 + "\"" +
                   "/>";
 
 const BROWSER_SEARCH_PREF = "browser.search.";
 
 const USER_DEFINED = "{searchTerms}";
 
 // Custom search parameters
-#ifdef OFFICIAL_BUILD
+#ifdef MOZ_OFFICIAL_BRANDING
 const MOZ_OFFICIAL = "official";
 #else
 const MOZ_OFFICIAL = "unofficial";
 #endif
 #expand const MOZ_DISTRIBUTION_ID = __MOZ_DISTRIBUTION_ID__;
 
 const MOZ_PARAM_LOCALE         = /\{moz:locale\}/g;
 const MOZ_PARAM_DIST_ID        = /\{moz:distributionID\}/g;
--- a/toolkit/content/widgets/tabbox.xml
+++ b/toolkit/content/widgets/tabbox.xml
@@ -602,18 +602,23 @@
   <binding id="tab" display="xul:button"
            extends="chrome://global/content/bindings/general.xml#control-item">
     <resources>
       <stylesheet src="chrome://global/skin/tabbox.css"/>
     </resources>
 
     <content>
       <xul:hbox class="tab-middle box-inherit" xbl:inherits="align,dir,pack,orient,selected" flex="1">
-        <xul:image class="tab-icon" xbl:inherits="validate,src=image"/>
-        <xul:label class="tab-text" xbl:inherits="value=label,accesskey,crop,disabled" flex="1"/>
+        <xul:image class="tab-icon"
+                   xbl:inherits="validate,src=image"
+                   role="presentation"/>
+        <xul:label class="tab-text"
+                   xbl:inherits="value=label,accesskey,crop,disabled"
+                   flex="1"
+                   role="presentation"/>
       </xul:hbox>
     </content>
 
     <implementation implements="nsIDOMXULSelectControlItemElement, nsIAccessibleProvider">
       <property name="accessibleType" readonly="true">
         <getter>
           <![CDATA[
             return Components.interfaces.nsIAccessibleProvider.XULTab;
--- a/toolkit/xre/MacApplicationDelegate.mm
+++ b/toolkit/xre/MacApplicationDelegate.mm
@@ -154,16 +154,18 @@ SetupMacApplicationDelegate()
 // It will be called once for each selected document.
 
 - (BOOL)application:(NSApplication*)theApplication openFile:(NSString*)filename
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK_RETURN;
 
   // Take advantage of the existing "command line" code for Macs.
   nsMacCommandLine& cmdLine = nsMacCommandLine::GetMacCommandLine();
+  // URLWithString expects our string to be a legal URL with percent escapes.
+  filename = [filename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
   // We don't actually care about Mac filetypes in this context, just pass a placeholder.
   cmdLine.HandleOpenOneDoc((CFURLRef)[NSURL URLWithString:filename], 'abcd');
 
   return YES;
 
   NS_OBJC_END_TRY_ABORT_BLOCK_RETURN(NO);
 }
 
--- a/toolkit/xre/nsSigHandlers.cpp
+++ b/toolkit/xre/nsSigHandlers.cpp
@@ -394,18 +394,23 @@ void InstallSignalHandlers(const char *P
 #endif
 
 #ifdef _M_X64
 #define MXCSR(ctx) (ctx)->MxCsr
 #endif
 
 #if defined(_M_IX86) || defined(_M_X64)
 
+#ifdef _M_X64
+#define X87CW(ctx) (ctx)->FltSave.ControlWord
+#define X87SW(ctx) (ctx)->FltSave.StatusWord
+#else
 #define X87CW(ctx) (ctx)->FloatSave.ControlWord
 #define X87SW(ctx) (ctx)->FloatSave.StatusWord
+#endif
 
 /*
  * SSE traps raise these exception codes, which are defined in internal NT headers
  * but not winbase.h
  */
 #define STATUS_FLOAT_MULTIPLE_FAULTS 0xC00002B4
 #define STATUS_FLOAT_MULTIPLE_TRAPS  0xC00002B5
 
--- a/toolkit/xre/nsSigHandlers.h
+++ b/toolkit/xre/nsSigHandlers.h
@@ -31,17 +31,17 @@
  * 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 ***** */
 
-#if defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(__amd64__)
+#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__amd64__)
 
 /*
  * x87 FPU Control Word:
  *
  * 0 -> IM  Invalid Operation
  * 1 -> DM  Denormalized Operand
  * 2 -> ZM  Zero Divide
  * 3 -> OM  Overflow
--- a/toolkit/xre/nsWindowsDllBlocklist.h
+++ b/toolkit/xre/nsWindowsDllBlocklist.h
@@ -92,14 +92,17 @@ static DllBlockInfo sWindowsDllBlocklist
   {"googledesktopnetwork3.dll", UNVERSIONED},
 
   // rdolib.dll - Suspected malware
   {"rdolib.dll", MAKE_VERSION(6,0,88,4)},
 
   // fgjk4wvb.dll - Suspected malware
   {"fgjk4wvb.dll", MAKE_VERSION(8,8,8,8)},
   
+  // radhslib.dll - Naomi internet filter - unmaintained since 2006
+  {"radhslib.dll", UNVERSIONED},
+  
   // leave these two in always for tests
   { "mozdllblockingtest.dll", ALL_VERSIONS },
   { "mozdllblockingtest_versioned.dll", 0x0000000400000000ULL },
 
   { NULL, 0 }
 };
--- a/tools/update-packaging/generatesnippet.py
+++ b/tools/update-packaging/generatesnippet.py
@@ -65,16 +65,20 @@ def main():
                       "--product",
                       action="store",
                       dest="product",
                       help="[Required] This option is used to generate the URL to download the MAR file.")
     parser.add_option("--platform",
                       action="store",
                       dest="platform",
                       help="[Required] This option is used to indicate which target platform.")
+    parser.add_option("--branch",
+                      action="store",
+                      dest="branch",
+                      help="This option is used to indicate which branch name to use for FTP file names.")
     parser.add_option("--download-base-URL",
                       action="store",
                       dest="downloadBaseURL",
                       help="This option indicates under which.")
     parser.add_option("-v",
                       "--verbose",
                       action="store_true",
                       dest="verbose",
@@ -87,41 +91,45 @@ def main():
                      ('product', "specify a product."),
                      ('platform', "specify the platform.")):
         if not hasattr(options, req):
             parser.error('You must specify %s' % msg)
 
     if not options.downloadBaseURL or options.downloadBaseURL == '':
         options.downloadBaseURL = 'http://ftp.mozilla.org/pub/mozilla.org/%s/nightly' % options.product
 
+    if not options.branch or options.branch == '':
+        options.branch = None
+
     snippet = generateSnippet(options.marPath,
                               options.applicationIniFile,
                               options.locale,
                               options.downloadBaseURL,
                               options.product,
-                              options.platform)
+                              options.platform,
+                              options.branch)
     f = open(os.path.join(options.marPath, 'complete.update.snippet'), 'wb')
     f.write(snippet)
     f.close()
 
     if options.verbose:
         # Show in our logs what the contents of the snippet are
         print snippet
 
 def generateSnippet(abstDistDir, applicationIniFile, locale,
-                    downloadBaseURL, product, platform):
+                    downloadBaseURL, product, platform, branch):
     # Let's extract information from application.ini
     c = ConfigParser()
     try:
         c.readfp(open(applicationIniFile))
     except IOError, (stderror):
        sys.exit(stderror) 
     buildid = c.get("App", "BuildID")
     appVersion = c.get("App", "Version")
-    branchName = c.get("App", "SourceRepository").split('/')[-1]
+    branchName = branch or c.get("App", "SourceRepository").split('/')[-1]
 
     marFileName = '%s-%s.%s.%s.complete.mar' % (
         product,
         appVersion,
         locale,
         platform)
     # Let's determine the hash and the size of the MAR file
     # This function exits the script if the file does not exist
--- a/widget/src/cocoa/nsMenuBarX.h
+++ b/widget/src/cocoa/nsMenuBarX.h
@@ -39,16 +39,18 @@
 #ifndef nsMenuBarX_h_
 #define nsMenuBarX_h_
 
 #import <Cocoa/Cocoa.h>
 
 #include "nsMenuBaseX.h"
 #include "nsIMutationObserver.h"
 #include "nsHashtable.h"
+#include "nsHashKeys.h"
+#include "nsDataHashtable.h"
 #include "nsINativeMenuService.h"
 #include "nsAutoPtr.h"
 #include "nsString.h"
 
 class nsMenuX;
 class nsMenuItemX;
 class nsChangeObserver;
 class nsIWidget;
@@ -157,12 +159,17 @@ protected:
                                             int tag, NativeMenuItemTarget* target);
   nsresult          CreateApplicationMenu(nsMenuX* inMenu);
 
   nsTArray< nsAutoPtr<nsMenuX> > mMenuArray;
   nsIWidget*         mParentWindow;        // [weak]
   PRUint32           mCurrentCommandID;    // unique command id (per menu-bar) to give to next item that asks
   nsIDocument*       mDocument;            // pointer to document
   GeckoNSMenu*       mNativeMenu;            // root menu, representing entire menu bar
-  nsHashtable        mObserverTable;       // stores observers for content change notification
+
+  // stores observers for content change notification
+  nsDataHashtable<nsPtrHashKey<nsIContent>, nsChangeObserver *> mContentToObserverTable;
+
+  // stores mapping of command IDs to menu objects
+  nsDataHashtable<nsUint32HashKey, nsMenuItemX *> mCommandToMenuObjectTable;
 };
 
 #endif // nsMenuBarX_h_
--- a/widget/src/cocoa/nsMenuBarX.mm
+++ b/widget/src/cocoa/nsMenuBarX.mm
@@ -99,16 +99,18 @@ NS_IMETHODIMP nsNativeMenuServiceX::Crea
 
 nsMenuBarX::nsMenuBarX()
 : mParentWindow(nsnull),
   mCurrentCommandID(eCommand_ID_Last),
   mDocument(nsnull)
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
 
+  mContentToObserverTable.Init();
+  mCommandToMenuObjectTable.Init();
   mNativeMenu = [[GeckoNSMenu alloc] initWithTitle:@"MainMenuBar"];
 
   NS_OBJC_END_TRY_ABORT_BLOCK;
 }
 
 nsMenuBarX::~nsMenuBarX()
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
@@ -784,63 +786,64 @@ void nsMenuBarX::ParentChainChanged(nsIC
 }
 
 // For change management, we don't use a |nsSupportsHashtable| because we know that the
 // lifetime of all these items is bounded by the lifetime of the menubar. No need to add
 // any more strong refs to the picture because the containment hierarchy already uses
 // strong refs.
 void nsMenuBarX::RegisterForContentChanges(nsIContent *aContent, nsChangeObserver *aMenuObject)
 {
-  nsVoidKey key(aContent);
-  mObserverTable.Put(&key, aMenuObject);
+  mContentToObserverTable.Put(aContent, aMenuObject);
 }
 
 void nsMenuBarX::UnregisterForContentChanges(nsIContent *aContent)
 {
-  nsVoidKey key(aContent);
-  mObserverTable.Remove(&key);
+  mContentToObserverTable.Remove(aContent);
 }
 
 nsChangeObserver* nsMenuBarX::LookupContentChangeObserver(nsIContent* aContent)
 {
-  nsVoidKey key(aContent);
-  return reinterpret_cast<nsChangeObserver*>(mObserverTable.Get(&key));
+  nsChangeObserver * result;
+  if (mContentToObserverTable.Get(aContent, &result))
+    return result;
+  else
+    return nsnull;
 }
 
 // Given a menu item, creates a unique 4-character command ID and
 // maps it to the item. Returns the id for use by the client.
 PRUint32 nsMenuBarX::RegisterForCommand(nsMenuItemX* inMenuItem)
 {
   // no real need to check for uniqueness. We always start afresh with each
   // window at 1. Even if we did get close to the reserved Apple command id's,
   // those don't start until at least '    ', which is integer 538976288. If
   // we have that many menu items in one window, I think we have other problems.
 
   // make id unique
   ++mCurrentCommandID;
 
-  // put it in the table, set out param for client
-  nsPRUint32Key key(mCurrentCommandID);
-  mObserverTable.Put(&key, inMenuItem);
+  mCommandToMenuObjectTable.Put(mCurrentCommandID, inMenuItem);
 
   return mCurrentCommandID;
 }
 
 // Removes the mapping between the given 4-character command ID
 // and its associated menu item.
 void nsMenuBarX::UnregisterCommand(PRUint32 inCommandID)
 {
-  nsPRUint32Key key(inCommandID);
-  mObserverTable.Remove(&key);
+  mCommandToMenuObjectTable.Remove(inCommandID);
 }
 
 nsMenuItemX* nsMenuBarX::GetMenuItemForCommandID(PRUint32 inCommandID)
 {
-  nsPRUint32Key key(inCommandID);
-  return reinterpret_cast<nsMenuItemX*>(mObserverTable.Get(&key));
+  nsMenuItemX * result;
+  if (mCommandToMenuObjectTable.Get(inCommandID, &result))
+    return result;
+  else
+    return nsnull;
 }
 
 //
 // Objective-C class used to allow us to have keyboard commands
 // look like they are doing something but actually do nothing.
 // We allow mouse actions to work normally.
 //
 
--- a/xpcom/ds/nsIObserver.idl
+++ b/xpcom/ds/nsIObserver.idl
@@ -39,17 +39,17 @@
 
 /**
  * This interface is implemented by an object that wants
  * to observe an event corresponding to a topic.
  *
  * @status FROZEN
  */
 
-[scriptable, uuid(DB242E01-E4D9-11d2-9DDE-000064657374)]
+[scriptable, function, uuid(DB242E01-E4D9-11d2-9DDE-000064657374)]
 interface nsIObserver : nsISupports {
 
    /**
     * Observe will be called when there is a notification for the
     * topic |aTopic|.  This assumes that the object implementing
     * this interface has been registered with an observer service
     * such as the nsIObserverService. 
     *
--- a/xpcom/reflect/xptcall/src/md/win32/xptcinvoke_asm_ce.asm
+++ b/xpcom/reflect/xptcall/src/md/win32/xptcinvoke_asm_ce.asm
@@ -11,18 +11,17 @@
 ;                        nsXPTCVariant* params,
 ;                        PRUint32 pfn_CopyToStack,
 ;                        PRUint32 pfn_CountWords);  
 
     EXTERN writeArgs
 
     GLOBAL asmXPTC_InvokeByIndex
 asmXPTC_InvokeByIndex
-    mov     r12, sp
-    stmdb   sp!, {r4 - r6, r12, lr} ; we're using registers 4, 5 and 6. Save them
+    stmdb   sp!, {r4 - r6, lr} ; we're using registers 4, 5 and 6. Save them
     sub     sp, sp, #24
     mov     r6, r0          ; store 'that' (the target's this)
     mov     r5, r1, lsl #2  ; a vtable index = methodIndex * 4
     mov     r4, sp          ; Back up the initial stack pointer.
     ; Move the stack pointer to allow for `paramCount` 64-bit values. We'll get
     ; any unused space back as writeArgs tells us where the SP should end up.
     sub     sp, sp, r2, lsl #3  ; worst case estimate for stack space
 
@@ -52,11 +51,11 @@ asmXPTC_InvokeByIndex
     ldr     r1, [sp, #-12]
     ldr     r2, [sp, #-8]
     ldr     r3, [sp, #-4]
     blx     ip              ; call function
 
     mov     sp, r4          ; Restore the original stack pointer.
 
     add     sp, sp, #24
-    ldmia   sp!, {r4 - r6, sp, pc} ; Restore registers and return.
+    ldmia   sp!, {r4 - r6, pc} ; Restore registers and return.
 
     END