Merge from cvs-trunk-mirror.
authorjorendorff@mozilla.com
Fri, 31 Aug 2007 17:27:11 -0400
changeset 5523 e6d3dadeba51a8d413f57c1ae6154fe96178187c
parent 5234 8c0e585ea7ddc69d65c650a25bab81fbd0e47826 (current diff)
parent 5522 40c79e4011e3b5ff17fa80042ff1d0977525b185 (diff)
child 5648 412cc3929707170f23248ea3e777a343ce90d63d
push idunknown
push userunknown
push dateunknown
milestone1.9a8pre
Merge from cvs-trunk-mirror.
client.mk
client.py
config/autoconf.mk.in
config/rules.mk
configure.in
content/svg/content/src/nsISVGEnum.h
content/svg/content/src/nsSVGAnimatedEnumeration.cpp
content/svg/content/src/nsSVGAnimatedEnumeration.h
editor/ui/composer/content/EditorCommandsDebug.js
editor/ui/composer/content/EditorInitPage.html
editor/ui/composer/content/EditorInitPagePlain.html
editor/ui/composer/content/TextEditorAppShell.xul
extensions/spellcheck/src/cattable.h
gfx/cairo/scaled-font-create-deadlock.patch
js/src/js.cpp
js/src/jsapi.cpp
js/src/jsarena.cpp
js/src/jscntxt.cpp
js/src/jsopcode.cpp
js/src/jsparse.cpp
js/src/jsregexp.cpp
js/src/jsscope.cpp
layout/base/nsISelectionImageService.idl
toolkit/content/widgets/tabbrowser.xml
toolkit/locales/en-US/chrome/global/tabbrowser.dtd
toolkit/locales/en-US/chrome/global/tabbrowser.properties
toolkit/themes/pinstripe/global/activetab-left.png
toolkit/themes/pinstripe/global/activetab-middle.png
toolkit/themes/pinstripe/global/activetab-right.png
toolkit/themes/pinstripe/global/alltabs-box-bkgnd.png
toolkit/themes/pinstripe/global/alltabs-box-overflow-bkgnd-animate.png
toolkit/themes/pinstripe/global/alltabs-box-overflow-bkgnd.png
toolkit/themes/pinstripe/global/browser.css
toolkit/themes/pinstripe/global/globalBindings.xml
toolkit/themes/pinstripe/global/inactive-icon-black.png
toolkit/themes/pinstripe/global/inactivetab-icon-black.png
toolkit/themes/pinstripe/global/inactivetab-icon-grey.png
toolkit/themes/pinstripe/global/inactivetab-left.png
toolkit/themes/pinstripe/global/inactivetab-right.png
toolkit/themes/pinstripe/global/tab-arrow-end-bkgnd-animate.png
toolkit/themes/pinstripe/global/tab-arrow-end-bkgnd.png
toolkit/themes/pinstripe/global/tab-arrow-end.png
toolkit/themes/pinstripe/global/tab-arrow-start-bkgnd-animate.png
toolkit/themes/pinstripe/global/tab-arrow-start-bkgnd.png
toolkit/themes/pinstripe/global/tab-arrow-start.png
toolkit/themes/pinstripe/global/tab-left-bkgnd.png
toolkit/themes/pinstripe/global/tab-left-hover.png
toolkit/themes/pinstripe/global/tab-left.png
toolkit/themes/pinstripe/global/tab-middle-bkgnd.png
toolkit/themes/pinstripe/global/tab-middle-hover.png
toolkit/themes/pinstripe/global/tab-middle.png
toolkit/themes/pinstripe/global/tab-right-bkgnd.png
toolkit/themes/pinstripe/global/tab-right-hover.png
toolkit/themes/pinstripe/global/tab-right.png
toolkit/themes/pinstripe/global/tabDragDrop/tabDragIndicator.png
toolkit/themes/pinstripe/global/tabbrowser-tabs-bkgnd.png
toolkit/themes/pinstripe/global/tabs-bottom-bg.png
toolkit/themes/winstripe/global/browser.css
toolkit/themes/winstripe/global/icons/alltabs-box-overflow-end-bkgnd-animate.png
toolkit/themes/winstripe/global/icons/alltabs-box-overflow-end-bkgnd-hover.png
toolkit/themes/winstripe/global/icons/alltabs-box-overflow-end-bkgnd.png
toolkit/themes/winstripe/global/icons/alltabs-box-overflow-start-bkgnd-animate.png
toolkit/themes/winstripe/global/icons/alltabs-box-overflow-start-bkgnd-hover.png
toolkit/themes/winstripe/global/icons/alltabs-box-overflow-start-bkgnd.png
toolkit/themes/winstripe/global/icons/alltabs.png
toolkit/themes/winstripe/global/icons/tab-arrow-end-bkgnd-animate.png
toolkit/themes/winstripe/global/icons/tab-arrow-end-bkgnd-disabled.png
toolkit/themes/winstripe/global/icons/tab-arrow-end-bkgnd-enabled.png
toolkit/themes/winstripe/global/icons/tab-arrow-end-bkgnd-hover.png
toolkit/themes/winstripe/global/icons/tab-arrow-end.png
toolkit/themes/winstripe/global/icons/tab-arrow-start-bkgnd-animate.png
toolkit/themes/winstripe/global/icons/tab-arrow-start-bkgnd-disabled.png
toolkit/themes/winstripe/global/icons/tab-arrow-start-bkgnd-enabled.png
toolkit/themes/winstripe/global/icons/tab-arrow-start-bkgnd-hover.png
toolkit/themes/winstripe/global/icons/tab-arrow-start.png
toolkit/themes/winstripe/global/icons/tab-left-bkgnd.png
toolkit/themes/winstripe/global/icons/tab-left.png
toolkit/themes/winstripe/global/icons/tab-middle-bkgnd.png
toolkit/themes/winstripe/global/icons/tab-middle.png
toolkit/themes/winstripe/global/icons/tab-right-bkgnd.png
toolkit/themes/winstripe/global/icons/tab-right.png
toolkit/themes/winstripe/global/icons/tabDragDrop/tabDragIndicator.png
toolkit/themes/winstripe/global/icons/tabbrowser-tabs-bkgnd.png
toolkit/themes/winstripe/global/icons/tabstrip-bottom.png
toolkit/themes/winstripe/global/tabDragDrop/tabDragIndicator.png
--- a/accessible/public/ia2/Makefile.in
+++ b/accessible/public/ia2/Makefile.in
@@ -94,18 +94,16 @@ CSRCS	= \
 MIDL_GENERATED_FILES = \
   dlldata.c \
   $(MIDL_INTERFACES:%.idl=%_p.c) \
   $(MIDL_INTERFACES:%.idl=%_i.c) \
   $(MIDL_INTERFACES:%.idl=%.h) \
   $(MIDL_ENUMS:%.idl=%.h) \
   $(NULL)
 
-EMBED_MANIFEST_AT = 2
-
 include $(topsrcdir)/config/rules.mk
 
 OS_LIBS = \
   kernel32.lib \
   rpcndr.lib \
   rpcns4.lib \
   rpcrt4.lib \
   ole32.lib \
--- a/accessible/public/msaa/Makefile.in
+++ b/accessible/public/msaa/Makefile.in
@@ -114,12 +114,10 @@ EXPORTS = \
 	$(NULL)
 
 export:: done_gen
 
 # This marshall dll is also registered in the installer
 register::
 	regsvr32 -s $(DIST)/bin/$(SHARED_LIBRARY)
 
-EMBED_MANIFEST_AT = 2
-
 include $(topsrcdir)/config/rules.mk
 
--- a/accessible/public/nsIAccessibilityService.idl
+++ b/accessible/public/nsIAccessibilityService.idl
@@ -93,18 +93,18 @@ interface nsIAccessibilityService : nsIA
    * @param aEvent             The event from nsIAccessibleEvent that
    *                           caused the change:
    *                           Must be one of:
    *                           EVENT_REORDER (change),
    *                           EVENT_SHOW (make visible or create) or 
    *                           EVENT_HIDE (destroy or hide)
    */
   void invalidateSubtreeFor(in nsIPresShell aPresShell,
-                                       in nsIContent aChangedContent,
-                                       in PRUint32 aEvent);
+                            in nsIContent aChangedContent,
+                            in PRUint32 aEvent);
 };
 
 
 %{ C++
 
 // for component registration
 // {DE401C37-9A7F-4278-A6F8-3DE2833989EF}
 #define NS_ACCESSIBILITY_SERVICE_CID \
--- a/accessible/public/nsIAccessibleEvent.idl
+++ b/accessible/public/nsIAccessibleEvent.idl
@@ -548,16 +548,21 @@ interface nsIAccessibleTextChangeEvent :
    * Returns length of changed text.
    */
   readonly attribute unsigned long length;
 
   /**
    * Returns true if text was inserted, otherwise false.
    */
   boolean isInserted();
+
+  /**
+   * The inserted or removed text
+   */
+  readonly attribute DOMString modifiedText;
 };
 
 [scriptable, uuid(b9076dce-4cd3-4e3d-a7f6-7f33a7f40c31)]
 interface nsIAccessibleCaretMoveEvent: nsIAccessibleEvent
 {
   /**
    * Return caret offset.
    */
--- a/accessible/public/nsIAccessibleRelation.idl
+++ b/accessible/public/nsIAccessibleRelation.idl
@@ -52,16 +52,19 @@ interface nsIAccessibleRelation : nsISup
 
   const unsigned long RELATION_NUL = 0x00;
 
   /**
    * Some attribute of this object is affected by a target object.
    */
   const unsigned long RELATION_CONTROLLED_BY = 0x01;
 
+  // First relation
+  const unsigned long RELATION_FIRST = RELATION_CONTROLLED_BY;
+
   /**
    * This object is interactive and controls some attribute of a target object.
    */
   const unsigned long RELATION_CONTROLLER_FOR = 0x02;
 
   /**
    * This object is label for a target object.
    */
@@ -130,16 +133,19 @@ interface nsIAccessibleRelation : nsISup
    */
   const unsigned long RELATION_DESCRIBED_BY = 0x0e;
 
   /**
    * This object is describes the target object.
    */
   const unsigned long RELATION_DESCRIPTION_FOR = 0x0f;
 
+  // Last relation that is standard to desktop accessibility APIs
+  const unsigned long RELATION_LAST = RELATION_DESCRIPTION_FOR;
+
   /**
    * Part of a form/dialog with a related default button. It is used for
    * MSAA only, no for IA2 nor ATK.
    */
   const unsigned long RELATION_DEFAULT_BUTTON = 0x4000;
 
   /**
    * Returns the type of the relation.
--- a/accessible/public/nsIAccessibleText.idl
+++ b/accessible/public/nsIAccessibleText.idl
@@ -40,17 +40,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsISupports.idl"
 
 typedef long nsAccessibleTextBoundary;
 
 interface nsIAccessible;
 
-[scriptable, uuid(17389a66-5cc5-4550-80e0-49e7b63990a4)]
+[scriptable, uuid(948419b2-53f6-4a74-bb69-1345faf3e8e8)]
 interface nsIAccessibleText : nsISupports
 {
   const nsAccessibleTextBoundary BOUNDARY_CHAR = 0;
   const nsAccessibleTextBoundary BOUNDARY_WORD_START = 1;
   const nsAccessibleTextBoundary BOUNDARY_WORD_END = 2;
   const nsAccessibleTextBoundary BOUNDARY_SENTENCE_START = 3; // don't use, deprecated
   const nsAccessibleTextBoundary BOUNDARY_SENTENCE_END = 4;  // don't use, deprecated
   const nsAccessibleTextBoundary BOUNDARY_LINE_START = 5;
@@ -162,16 +162,30 @@ interface nsIAccessibleText : nsISupport
 
   void setSelectionBounds (in long selectionNum,
                               in long startOffset,
                               in long endOffset);
 
   void addSelection (in long startOffset, in long endOffset);
 
   void removeSelection (in long selectionNum);
+
+
+  /**
+   * Makes a specific part of string visible on screen.
+   *
+   * @param aStartIndex - 0-based character offset.
+   * @param aEndIndex - 0-based character offset - the offset of the
+   *                        character just past the last character of the
+   *                        string.
+   * @param aScrollType - defines how to scroll (see nsIAccessibleScrollType for
+   *                      available constants).
+   */
+  void scrollSubstringTo(in long aStartIndex, in long aEndIndex,
+                         in unsigned long aScrollType);
 };
 
 /*
  Assumptions:
 
  Using wstring (UCS2) instead of string encoded in UTF-8.
  Multibyte encodings (or at least potentially multi-byte
  encodings) would be preferred for the reasons cited above.
--- a/accessible/public/nsIAccessibleTypes.idl
+++ b/accessible/public/nsIAccessibleTypes.idl
@@ -75,16 +75,22 @@ interface nsIAccessibleScrollType : nsIS
    */
   const unsigned long SCROLL_TYPE_LEFT_EDGE =0x04;
 
   /**
    * Scroll the right edge of the object or substring to the right edge of the
    * window (or as close as possible).
    */
   const unsigned long SCROLL_TYPE_RIGHT_EDGE = 0x05;
+
+  /**
+   * Scroll an object the minimum amount necessary in order for the entire
+   * frame to be visible (if possible).
+   */
+  const unsigned long SCROLL_TYPE_ANYWHERE = 0x06;
 };
 
 
 /**
  * These constants define which coordinate system a point is located in. Note,
  * keep them synchronized with IA2CoordinateType.
  */
 [scriptable, uuid(c9fbdf10-619e-436f-bf4b-8566686f1577)]
@@ -101,8 +107,9 @@ interface nsIAccessibleCoordinateType : 
   const unsigned long COORDTYPE_WINDOW_RELATIVE = 0x01;
 
   /**
    * The coordinates are relative to the upper left corner of the bounding box
    * of the immediate parent.
    */
   const unsigned long COORDTYPE_PARENT_RELATIVE = 0x02;
 };
+
--- a/accessible/src/atk/nsAccessibleWrap.cpp
+++ b/accessible/src/atk/nsAccessibleWrap.cpp
@@ -787,17 +787,17 @@ GetAttributeSet(nsIAccessible* aAccessib
 {
     AtkAttributeSet *objAttributeSet = nsnull;
     nsCOMPtr<nsIPersistentProperties> attributes;
     aAccessible->GetAttributes(getter_AddRefs(attributes));
     
     if (attributes) {
         // Deal with attributes that we only need to expose in ATK
         PRUint32 state, extraState;
-        aAccessible->GetFinalState(&state, &extraState);
+        aAccessible->GetFinalState(&state, nsnull);
         if (state & nsIAccessibleStates::STATE_HASPOPUP) {
           // There is no ATK state for haspopup, must use object attribute to expose the same info
           nsAutoString oldValueUnused;
           attributes->SetStringProperty(NS_LITERAL_CSTRING("haspopup"), NS_LITERAL_STRING("true"),
                                         oldValueUnused);
         }
         if (state & nsIAccessibleStates::STATE_CHECKABLE) {
           // There is no ATK state for haspopup, must use object attribute to expose the same info
--- a/accessible/src/base/nsAccessNode.cpp
+++ b/accessible/src/base/nsAccessNode.cpp
@@ -421,45 +421,18 @@ nsAccessNode::ScrollTo(PRUint32 aScrollT
   NS_ENSURE_TRUE(shell, NS_ERROR_FAILURE);
 
   nsIFrame *frame = GetFrame();
   NS_ENSURE_TRUE(frame, NS_ERROR_FAILURE);
 
   nsCOMPtr<nsIContent> content = frame->GetContent();
   NS_ENSURE_TRUE(content, NS_ERROR_FAILURE);
 
-  PRInt32 vPercent, hPercent;
-  switch (aScrollType)
-  {
-    case nsIAccessibleScrollType::SCROLL_TYPE_TOP_LEFT:
-      vPercent = NS_PRESSHELL_SCROLL_TOP;
-      hPercent = NS_PRESSHELL_SCROLL_LEFT;
-      break;
-    case nsIAccessibleScrollType::SCROLL_TYPE_BOTTOM_RIGHT:
-      vPercent = NS_PRESSHELL_SCROLL_BOTTOM;
-      hPercent = NS_PRESSHELL_SCROLL_RIGHT;
-      break;
-    case nsIAccessibleScrollType::SCROLL_TYPE_TOP_EDGE:
-      vPercent = NS_PRESSHELL_SCROLL_TOP;
-      hPercent = NS_PRESSHELL_SCROLL_ANYWHERE;
-      break;
-    case nsIAccessibleScrollType::SCROLL_TYPE_BOTTOM_EDGE:
-      vPercent = NS_PRESSHELL_SCROLL_BOTTOM;
-      hPercent = NS_PRESSHELL_SCROLL_ANYWHERE;
-      break;
-    case nsIAccessibleScrollType::SCROLL_TYPE_LEFT_EDGE:
-      vPercent = NS_PRESSHELL_SCROLL_ANYWHERE;
-      hPercent = NS_PRESSHELL_SCROLL_LEFT;
-      break;
-    case nsIAccessibleScrollType::SCROLL_TYPE_RIGHT_EDGE:
-      vPercent = NS_PRESSHELL_SCROLL_ANYWHERE;
-      hPercent = NS_PRESSHELL_SCROLL_RIGHT;
-      break;
-  }
-
+  PRInt16 vPercent, hPercent;
+  nsAccUtils::ConvertScrollTypeToPercents(aScrollType, &vPercent, &hPercent);
   return shell->ScrollContentIntoView(content, vPercent, hPercent);
 }
 
 NS_IMETHODIMP
 nsAccessNode::ScrollToPoint(PRUint32 aCoordinateType, PRInt32 aX, PRInt32 aY)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -1799,21 +1799,24 @@ NS_IMETHODIMP nsAccessibilityService::Re
 
 // Called from layout when the frame tree owned by a node changes significantly
 NS_IMETHODIMP nsAccessibilityService::InvalidateSubtreeFor(nsIPresShell *aShell,
                                                            nsIContent *aChangeContent,
                                                            PRUint32 aEvent)
 {
   NS_ASSERTION(aEvent == nsIAccessibleEvent::EVENT_ASYNCH_SIGNIFICANT_CHANGE ||
                aEvent == nsIAccessibleEvent::EVENT_ASYNCH_SHOW ||
-               aEvent == nsIAccessibleEvent::EVENT_ASYNCH_HIDE,
+               aEvent == nsIAccessibleEvent::EVENT_ASYNCH_HIDE ||
+               aEvent == nsIAccessibleEvent::EVENT_DOM_SIGNIFICANT_CHANGE ||
+               aEvent == nsIAccessibleEvent::EVENT_DOM_CREATE ||
+               aEvent == nsIAccessibleEvent::EVENT_DOM_DESTROY,
                "Incorrect aEvent passed in");
 
+  NS_ENSURE_ARG_POINTER(aShell);
   nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aShell));
-  NS_ASSERTION(aShell, "No pres shell in call to InvalidateSubtreeFor");
   nsCOMPtr<nsIAccessibleDocument> accessibleDoc =
     nsAccessNode::GetDocAccessibleFor(weakShell);
   nsCOMPtr<nsPIAccessibleDocument> privateAccessibleDoc =
     do_QueryInterface(accessibleDoc);
   if (!privateAccessibleDoc) {
     return NS_OK;
   }
   return privateAccessibleDoc->InvalidateCacheSubtree(aChangeContent, aEvent);
--- a/accessible/src/base/nsAccessibilityService.h
+++ b/accessible/src/base/nsAccessibilityService.h
@@ -335,12 +335,13 @@ static const char kEventTypeNames[][40] 
   "hyperlink number of anchors changed",     // EVENT_HYPERLINK_NUMBER_OF_ANCHORS_CHANGED
   "hyperlink selected link changed",         // EVENT_HYPERLINK_SELECTED_LINK_CHANGED
   "hypertext link activated",                // EVENT_HYPERTEXT_LINK_ACTIVATED
   "hypertext link selected",                 // EVENT_HYPERTEXT_LINK_SELECTED
   "hyperlink start index changed",           // EVENT_HYPERLINK_START_INDEX_CHANGED
   "hypertext changed",                       // EVENT_HYPERTEXT_CHANGED
   "hypertext links count changed",           // EVENT_HYPERTEXT_NLINKS_CHANGED
   "object attribute changed",                // EVENT_OBJECT_ATTRIBUTE_CHANGED
-  "internal load"                            // EVENT_INTERNAL_LOAD
+  "internal load",                           // EVENT_INTERNAL_LOAD
+  "reorder"                                  // EVENT_REORDER
 };
 
 #endif /* __nsIAccessibilityService_h__ */
--- a/accessible/src/base/nsAccessibilityUtils.cpp
+++ b/accessible/src/base/nsAccessibilityUtils.cpp
@@ -33,22 +33,34 @@
  * 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 "nsAccessibilityUtils.h"
 
+#include "nsIAccessibleTypes.h"
 #include "nsPIAccessible.h"
 #include "nsAccessibleEventData.h"
 
+#include "nsIDOMRange.h"
 #include "nsIDOMXULSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsIEventListenerManager.h"
+#include "nsIPresShell.h"
+#include "nsPresContext.h"
+#include "nsIEventStateManager.h"
+#include "nsISelection2.h"
+#include "nsISelectionController.h"
+
+#include "nsContentCID.h"
+#include "nsComponentManagerUtils.h"
+
+static NS_DEFINE_IID(kRangeCID, NS_RANGE_CID);
 
 void
 nsAccUtils::GetAccAttr(nsIPersistentProperties *aAttributes, nsIAtom *aAttrName,
                        nsAString& aAttrValue)
 {
   nsCAutoString attrName;
   aAttrName->ToUTF8String(attrName);
   aAttributes->GetStringProperty(attrName, aAttrValue);
@@ -162,16 +174,49 @@ nsAccUtils::HasListener(nsIContent *aCon
 {
   NS_ENSURE_ARG_POINTER(aContent);
   nsCOMPtr<nsIEventListenerManager> listenerManager;
   aContent->GetListenerManager(PR_FALSE, getter_AddRefs(listenerManager));
 
   return listenerManager && listenerManager->HasListenersFor(aEventType);  
 }
 
+PRUint32
+nsAccUtils::GetAccessKeyFor(nsIContent *aContent)
+{
+  if (!aContent)
+    return 0;
+
+  // Accesskeys are registered by @accesskey attribute only. At first check
+  // whether it is presented on the given element to avoid the slow
+  // nsIEventStateManager::GetRegisteredAccessKey() method.
+  if (!aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::accesskey))
+    return 0;
+
+  nsCOMPtr<nsIDocument> doc = aContent->GetOwnerDoc();
+  if (!doc)
+    return 0;
+
+  nsCOMPtr<nsIPresShell> presShell = doc->GetPrimaryShell();
+  if (!presShell)
+    return 0;
+
+  nsPresContext *presContext = presShell->GetPresContext();
+  if (!presContext)
+    return 0;
+
+  nsIEventStateManager *esm = presContext->EventStateManager();
+  if (!esm)
+    return 0;
+
+  PRUint32 key = 0;
+  esm->GetRegisteredAccessKey(aContent, &key);
+  return key;
+}
+
 nsresult
 nsAccUtils::FireAccEvent(PRUint32 aEventType, nsIAccessible *aAccessible,
                          PRBool aIsAsynch)
 {
   NS_ENSURE_ARG(aAccessible);
 
   nsCOMPtr<nsPIAccessible> pAccessible(do_QueryInterface(aAccessible));
   NS_ASSERTION(pAccessible, "Accessible doesn't implement nsPIAccessible");
@@ -218,8 +263,87 @@ nsAccUtils::GetAncestorWithRole(nsIAcces
     nsCOMPtr<nsIAccessibleDocument> docAccessible = do_QueryInterface(testRoleAccessible);
     if (docAccessible) {
       break;
     }
     parentAccessible.swap(testRoleAccessible);
   }
   return nsnull;
 }
+
+nsresult
+nsAccUtils::ScrollSubstringTo(nsIFrame *aFrame,
+                              nsIDOMNode *aStartNode, PRInt32 aStartIndex,
+                              nsIDOMNode *aEndNode, PRInt32 aEndIndex,
+                              PRUint32 aScrollType)
+{
+  if (!aFrame || !aStartNode || !aEndNode)
+    return NS_ERROR_FAILURE;
+
+  nsPresContext *presContext = aFrame->PresContext();
+
+  nsCOMPtr<nsIDOMRange> scrollToRange = do_CreateInstance(kRangeCID);
+  NS_ENSURE_TRUE(scrollToRange, NS_ERROR_FAILURE);
+
+  nsCOMPtr<nsISelectionController> selCon;
+  aFrame->GetSelectionController(presContext, getter_AddRefs(selCon));
+  NS_ENSURE_TRUE(selCon, NS_ERROR_FAILURE);
+
+  scrollToRange->SetStart(aStartNode, aStartIndex);
+  scrollToRange->SetEnd(aEndNode, aEndIndex);
+
+  nsCOMPtr<nsISelection> selection1;
+  selCon->GetSelection(nsISelectionController::SELECTION_ACCESSIBILITY,
+                       getter_AddRefs(selection1));
+
+  nsCOMPtr<nsISelection2> selection(do_QueryInterface(selection1));
+  if (selection) {
+    selection->RemoveAllRanges();
+    selection->AddRange(scrollToRange);
+
+    PRInt16 vPercent, hPercent;
+    ConvertScrollTypeToPercents(aScrollType, &vPercent, &hPercent);
+    selection->ScrollIntoView(nsISelectionController::SELECTION_ANCHOR_REGION,
+                              PR_TRUE, vPercent, hPercent);
+
+    selection->CollapseToStart();
+  }
+
+  return NS_OK;
+}
+
+void
+nsAccUtils::ConvertScrollTypeToPercents(PRUint32 aScrollType,
+                                        PRInt16 *aVPercent,
+                                        PRInt16 *aHPercent)
+{
+  switch (aScrollType)
+  {
+    case nsIAccessibleScrollType::SCROLL_TYPE_TOP_LEFT:
+      *aVPercent = NS_PRESSHELL_SCROLL_TOP;
+      *aHPercent = NS_PRESSHELL_SCROLL_LEFT;
+      break;
+    case nsIAccessibleScrollType::SCROLL_TYPE_BOTTOM_RIGHT:
+      *aVPercent = NS_PRESSHELL_SCROLL_BOTTOM;
+      *aHPercent = NS_PRESSHELL_SCROLL_RIGHT;
+      break;
+    case nsIAccessibleScrollType::SCROLL_TYPE_TOP_EDGE:
+      *aVPercent = NS_PRESSHELL_SCROLL_TOP;
+      *aHPercent = NS_PRESSHELL_SCROLL_ANYWHERE;
+      break;
+    case nsIAccessibleScrollType::SCROLL_TYPE_BOTTOM_EDGE:
+      *aVPercent = NS_PRESSHELL_SCROLL_BOTTOM;
+      *aHPercent = NS_PRESSHELL_SCROLL_ANYWHERE;
+      break;
+    case nsIAccessibleScrollType::SCROLL_TYPE_LEFT_EDGE:
+      *aVPercent = NS_PRESSHELL_SCROLL_ANYWHERE;
+      *aHPercent = NS_PRESSHELL_SCROLL_LEFT;
+      break;
+    case nsIAccessibleScrollType::SCROLL_TYPE_RIGHT_EDGE:
+      *aVPercent = NS_PRESSHELL_SCROLL_ANYWHERE;
+      *aHPercent = NS_PRESSHELL_SCROLL_RIGHT;
+      break;
+    default:
+      *aVPercent = NS_PRESSHELL_SCROLL_ANYWHERE;
+      *aHPercent = NS_PRESSHELL_SCROLL_ANYWHERE;
+  }
+}
+
--- a/accessible/src/base/nsAccessibilityUtils.h
+++ b/accessible/src/base/nsAccessibilityUtils.h
@@ -40,16 +40,17 @@
 #define nsAccessibilityUtils_h_
 
 #include "nsAccessibilityAtoms.h"
 #include "nsIAccessible.h"
 
 #include "nsIDOMNode.h"
 #include "nsIPersistentProperties2.h"
 #include "nsIContent.h"
+#include "nsIFrame.h"
 
 class nsAccUtils
 {
 public:
   /**
    * Returns value of attribute from the given attributes container.
    *
    * @param aAttributes - attributes container
@@ -104,34 +105,67 @@ public:
 
   /**
    * Return true if the given node has registered event listener of the given
    * type.
    */
   static PRBool HasListener(nsIContent *aContent, const nsAString& aEventType);
 
   /**
+   * Return an accesskey registered on the given element by
+   * nsIEventStateManager or 0 if there is no registered accesskey.
+   *
+   * @param aContent - the given element.
+   */
+  static PRUint32 GetAccessKeyFor(nsIContent *aContent);
+
+  /**
    * Fire accessible event of the given type for the given accessible.
    */
   static nsresult FireAccEvent(PRUint32 aEventType, nsIAccessible *aAccessible,
                                PRBool aIsAsynch = PR_FALSE);
 
   /**
    * Is the first passed in node an ancestor of the second?
    * Note: A node is not considered to be the ancestor of itself.
    * @param aPossibleAncestorNode -- node to test for ancestor-ness of aPossibleDescendantNode
    * @param aPossibleDescendantNode -- node to test for descendant-ness of aPossibleAncestorNode
    * @return PR_TRUE if aPossibleAncestorNode is an ancestor of aPossibleDescendantNode
    */
    static PRBool IsAncestorOf(nsIDOMNode *aPossibleAncestorNode,
                               nsIDOMNode *aPossibleDescendantNode);
 
-   /**
+  /**
     * 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
     * @return The ancestor accessible with the given role, or nsnull if no match is found
     */
    static already_AddRefed<nsIAccessible>
      GetAncestorWithRole(nsIAccessible *aDescendant, PRUint32 aRole);
+
+  /**
+   * Helper method to scroll range into view, used for implementation of
+   * nsIAccessibleText::scrollSubstringTo().
+   *
+   * @param aFrame        the frame for accessible the range belongs to.
+   * @param aStartNode    start node of a range
+   * @param aStartOffset  an offset inside the start node
+   * @param aEndNode      end node of a range
+   * @param aEndOffset    an offset inside the end node
+   * @param aScrollType   the place a range should be scrolled to
+   */
+  static nsresult ScrollSubstringTo(nsIFrame *aFrame,
+                                    nsIDOMNode *aStartNode, PRInt32 aStartIndex,
+                                    nsIDOMNode *aEndNode, PRInt32 aEndIndex,
+                                    PRUint32 aScrollType);
+
+  /**
+   * Converts scroll type constant defined in nsIAccessibleScrollType to
+   * vertical and horizontal percents.
+   */
+  static void ConvertScrollTypeToPercents(PRUint32 aScrollType,
+                                          PRInt16 *aVPercent,
+                                          PRInt16 *aHPercent);
 };
 
 #endif
+
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -344,17 +344,17 @@ NS_IMETHODIMP nsAccessible::GetDescripti
 #define NS_MODIFIER_SHIFT    1
 #define NS_MODIFIER_CONTROL  2
 #define NS_MODIFIER_ALT      4
 #define NS_MODIFIER_META     8
 
 // returns the accesskey modifier mask used in the given node's context
 // (i.e. chrome or content), or 0 if an error occurs
 static PRInt32
-GetAccessModifierMask(nsIDOMElement* aDOMNode)
+GetAccessModifierMask(nsIContent* aContent)
 {
   nsCOMPtr<nsIPrefBranch> prefBranch =
     do_GetService(NS_PREFSERVICE_CONTRACTID);
   if (!prefBranch)
     return 0;
 
   // use ui.key.generalAccessKey (unless it is -1)
   PRInt32 accessKey;
@@ -365,18 +365,17 @@ GetAccessModifierMask(nsIDOMElement* aDO
       case nsIDOMKeyEvent::DOM_VK_CONTROL: return NS_MODIFIER_CONTROL;
       case nsIDOMKeyEvent::DOM_VK_ALT:     return NS_MODIFIER_ALT;
       case nsIDOMKeyEvent::DOM_VK_META:    return NS_MODIFIER_META;
       default:                             return 0;
     }
   }
 
   // get the docShell to this DOMNode, return 0 on failure
-  nsCOMPtr<nsIContent> content(do_QueryInterface(aDOMNode));
-  nsCOMPtr<nsIDocument> document = content->GetCurrentDoc();
+  nsCOMPtr<nsIDocument> document = aContent->GetCurrentDoc();
   if (!document)
     return 0;
   nsCOMPtr<nsISupports> container = document->GetContainer();
   if (!container)
     return 0;
   nsCOMPtr<nsIDocShellTreeItem> treeItem(do_QueryInterface(container));
   if (!treeItem)
     return 0;
@@ -393,57 +392,59 @@ GetAccessModifierMask(nsIDOMElement* aDO
   case nsIDocShellTreeItem::typeContent:
     rv = prefBranch->GetIntPref("ui.key.contentAccess", &accessModifierMask);
     break;
   }
 
   return NS_SUCCEEDED(rv) ? accessModifierMask : 0;
 }
 
-NS_IMETHODIMP nsAccessible::GetKeyboardShortcut(nsAString& _retval)
+NS_IMETHODIMP
+nsAccessible::GetKeyboardShortcut(nsAString& aAccessKey)
 {
-  nsCOMPtr<nsIDOMElement> elt(do_QueryInterface(mDOMNode));
-  if (elt) {
-    nsAutoString accesskey;
-    elt->GetAttribute(NS_LITERAL_STRING("accesskey"), accesskey);
-    if (accesskey.IsEmpty()) {
-      nsCOMPtr<nsIContent> content = do_QueryInterface(elt);
-      nsIContent *labelContent = GetLabelContent(content);
-      if (labelContent) {
-        labelContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::accesskey, accesskey);
-      }
-      if (accesskey.IsEmpty()) {
-        return NS_ERROR_FAILURE;
-      }
-    }
-
-    // append the modifiers in reverse order
-    // (result: Control+Alt+Shift+Meta+<key>)
-    nsAutoString propertyKey;
-    PRInt32 modifierMask = GetAccessModifierMask(elt);
-    if (modifierMask & NS_MODIFIER_META) {
-      propertyKey.AssignLiteral("VK_META");
-      nsAccessible::GetFullKeyName(propertyKey, accesskey, accesskey);
-    }
-    if (modifierMask & NS_MODIFIER_SHIFT) {
-      propertyKey.AssignLiteral("VK_SHIFT");
-      nsAccessible::GetFullKeyName(propertyKey, accesskey, accesskey);
-    }
-    if (modifierMask & NS_MODIFIER_ALT) {
-      propertyKey.AssignLiteral("VK_ALT");
-      nsAccessible::GetFullKeyName(propertyKey, accesskey, accesskey);
-    }
-    if (modifierMask & NS_MODIFIER_CONTROL) {
-      propertyKey.AssignLiteral("VK_CONTROL");
-      nsAccessible::GetFullKeyName(propertyKey, accesskey, accesskey);
-    }
-    _retval= accesskey;
+  aAccessKey.Truncate();
+
+  nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
+  if (!content)
+    return NS_ERROR_FAILURE;
+
+  PRUint32 key = nsAccUtils::GetAccessKeyFor(content);
+  if (!key) {
+    nsCOMPtr<nsIContent> labelContent(GetLabelContent(content));
+    if (labelContent)
+      key = nsAccUtils::GetAccessKeyFor(labelContent);
+  }
+
+  if (!key)
     return NS_OK;
+
+  nsAutoString accesskey(key);
+
+  // Append the modifiers in reverse order, result: Control+Alt+Shift+Meta+<key>
+  nsAutoString propertyKey;
+  PRInt32 modifierMask = GetAccessModifierMask(content);
+  if (modifierMask & NS_MODIFIER_META) {
+    propertyKey.AssignLiteral("VK_META");
+    nsAccessible::GetFullKeyName(propertyKey, accesskey, accesskey);
   }
-  return NS_ERROR_FAILURE;
+  if (modifierMask & NS_MODIFIER_SHIFT) {
+    propertyKey.AssignLiteral("VK_SHIFT");
+    nsAccessible::GetFullKeyName(propertyKey, accesskey, accesskey);
+  }
+  if (modifierMask & NS_MODIFIER_ALT) {
+    propertyKey.AssignLiteral("VK_ALT");
+    nsAccessible::GetFullKeyName(propertyKey, accesskey, accesskey);
+  }
+  if (modifierMask & NS_MODIFIER_CONTROL) {
+    propertyKey.AssignLiteral("VK_CONTROL");
+    nsAccessible::GetFullKeyName(propertyKey, accesskey, accesskey);
+  }
+
+  aAccessKey = accesskey;
+  return NS_OK;
 }
 
 NS_IMETHODIMP nsAccessible::SetParent(nsIAccessible *aParent)
 {
   mParent = aParent;
   return NS_OK;
 }
 
@@ -987,17 +988,17 @@ PRBool nsAccessible::IsVisible(PRBool *a
 
   PRBool isVisible = CheckVisibilityInParentChain(doc, containingView);
   if (isVisible && rectVisibility == nsRectVisibility_kVisible) {
     *aIsOffscreen = PR_FALSE;
   }
   return isVisible;
 }
 
-NS_IMETHODIMP
+nsresult
 nsAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   *aState = 0;
 
   if (aExtraState)
     *aExtraState = 0;
 
   if (!mDOMNode && aExtraState) {
@@ -1045,55 +1046,16 @@ nsAccessible::GetState(PRUint32 *aState,
   PRBool isOffscreen;
   if (!IsVisible(&isOffscreen)) {
     *aState |= nsIAccessibleStates::STATE_INVISIBLE;
   }
   if (isOffscreen) {
     *aState |= nsIAccessibleStates::STATE_OFFSCREEN;
   }
 
-  if (!aExtraState)
-    return NS_OK;
-
-  PRUint32 state = *aState;
-  nsresult rv = GetARIAState(&state);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsIFrame *frame = GetFrame();
-  if (frame) {
-    const nsStyleDisplay* display = frame->GetStyleDisplay();
-    if (display && display->mOpacity == 1.0f &&
-        !(state & nsIAccessibleStates::STATE_INVISIBLE)) {
-      *aExtraState |= nsIAccessibleStates::EXT_STATE_OPAQUE;
-    }
-
-    const nsStyleXUL *xulStyle = frame->GetStyleXUL();
-    if (xulStyle) {
-      // In XUL all boxes are either vertical or horizontal
-      if (xulStyle->mBoxOrient == NS_STYLE_BOX_ORIENT_VERTICAL) {
-        *aExtraState |= nsIAccessibleStates::EXT_STATE_VERTICAL;
-      }
-      else {
-        *aExtraState |= nsIAccessibleStates::EXT_STATE_HORIZONTAL;
-      }
-    }
-  }
-
-  // XXX We can remove this hack once we support RDF-based role & state maps
-  if (mRoleMapEntry && (mRoleMapEntry->role == nsIAccessibleRole::ROLE_ENTRY ||
-      mRoleMapEntry->role == nsIAccessibleRole::ROLE_PASSWORD_TEXT)) {
-    if (content->AttrValueIs(kNameSpaceID_WAIProperties , nsAccessibilityAtoms::multiline,
-                             nsAccessibilityAtoms::_true, eCaseMatters)) {
-      *aExtraState |= nsIAccessibleStates::EXT_STATE_MULTI_LINE;
-    }
-    else {
-      *aExtraState |= nsIAccessibleStates::EXT_STATE_SINGLE_LINE;
-    }
-  }
-
   return NS_OK;
 }
 
   /* readonly attribute boolean focusedChild; */
 NS_IMETHODIMP nsAccessible::GetFocusedChild(nsIAccessible **aFocusedChild) 
 { 
   nsCOMPtr<nsIAccessible> focusedChild;
   if (gLastFocusedNode == mDOMNode) {
@@ -2042,17 +2004,17 @@ NS_IMETHODIMP nsAccessible::GetFinalRole
   if (mRoleMapEntry) {
     *aRole = mRoleMapEntry->role;
 
     // These unfortunate exceptions don't fit into the ARIA table
     // This is where the nsIAccessible role depends on both the role and ARIA state
     if (*aRole == nsIAccessibleRole::ROLE_ENTRY) {
       nsCOMPtr<nsIContent> content = do_QueryInterface(mDOMNode);
       if (content && 
-          content->AttrValueIs(kNameSpaceID_WAIProperties , nsAccessibilityAtoms::secret,
+          content->AttrValueIs(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::secret,
                                nsAccessibilityAtoms::_true, eCaseMatters)) {
         // For entry field with aaa:secret="true"
         *aRole = nsIAccessibleRole::ROLE_PASSWORD_TEXT;
       }
     }
     else if (*aRole == nsIAccessibleRole::ROLE_PUSHBUTTON) {
       nsCOMPtr<nsIContent> content = do_QueryInterface(mDOMNode);
       if (content) {
@@ -2277,18 +2239,17 @@ NS_IMETHODIMP
 nsAccessible::GetFinalState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   NS_ENSURE_ARG_POINTER(aState);
 
   nsresult rv = GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Apply ARIA states to be sure accessible states will be overriden.
-  rv = GetARIAState(aState);
-  NS_ENSURE_SUCCESS(rv, rv);
+  *aState |= GetARIAState();
 
   // Set additional states which presence depends on another states.
   if (aExtraState) {
     if (!(*aState & nsIAccessibleStates::STATE_UNAVAILABLE)) {
       *aExtraState |= nsIAccessibleStates::EXT_STATE_ENABLED |
                       nsIAccessibleStates::EXT_STATE_SENSITIVE;
     }
 
@@ -2300,63 +2261,95 @@ nsAccessible::GetFinalState(PRUint32 *aS
         // Cannot be both expanded and collapsed -- this happens 
         // in ARIA expanded combobox because of limitation of nsARIAMap
         // XXX Perhaps we will be able to make this less hacky if 
         // we support extended states in nsARIAMap, e.g. derive
         // COLLAPSED from EXPANDABLE && !EXPANDED
         *aExtraState &= ~nsIAccessibleStates::STATE_COLLAPSED;
       } 
     }
+    nsIFrame *frame = GetFrame();
+    if (frame) {
+      const nsStyleDisplay* display = frame->GetStyleDisplay();
+      if (display && display->mOpacity == 1.0f &&
+          !(*aState & nsIAccessibleStates::STATE_INVISIBLE)) {
+        *aExtraState |= nsIAccessibleStates::EXT_STATE_OPAQUE;
+      }
+
+      const nsStyleXUL *xulStyle = frame->GetStyleXUL();
+      if (xulStyle) {
+        // In XUL all boxes are either vertical or horizontal
+        if (xulStyle->mBoxOrient == NS_STYLE_BOX_ORIENT_VERTICAL) {
+          *aExtraState |= nsIAccessibleStates::EXT_STATE_VERTICAL;
+        }
+        else {
+          *aExtraState |= nsIAccessibleStates::EXT_STATE_HORIZONTAL;
+        }
+      }
+    }
+
+    // XXX We can remove this hack once we support RDF-based role & state maps
+    if (mRoleMapEntry && (mRoleMapEntry->role == nsIAccessibleRole::ROLE_ENTRY ||
+        mRoleMapEntry->role == nsIAccessibleRole::ROLE_PASSWORD_TEXT)) {
+      nsCOMPtr<nsIContent> content = do_QueryInterface(mDOMNode);
+      NS_ENSURE_TRUE(content, NS_ERROR_FAILURE);
+      if (content->AttrValueIs(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::multiline,
+                               nsAccessibilityAtoms::_true, eCaseMatters)) {
+        *aExtraState |= nsIAccessibleStates::EXT_STATE_MULTI_LINE;
+      }
+      else {
+        *aExtraState |= nsIAccessibleStates::EXT_STATE_SINGLE_LINE;
+      }
+    }
   }
 
   return NS_OK;
 }
 
-nsresult
-nsAccessible::GetARIAState(PRUint32 *aState)
+PRUint32
+nsAccessible::GetARIAState()
 {
-  if (!mDOMNode) {
-    return NS_ERROR_FAILURE; // Node already shut down
-  }
-
   // Test for universal states first
   nsIContent *content = GetRoleContent(mDOMNode);
-  NS_ENSURE_TRUE(content, NS_ERROR_FAILURE); // Node already shut down
-
+  if (!content) {
+    return 0;
+  }
+
+  PRUint32 ariaState = 0;
   PRUint32 index = 0;
   while (nsARIAMap::gWAIUnivStateMap[index].attributeName != nsnull) {
-    MappedAttrState(content, aState, &nsARIAMap::gWAIUnivStateMap[index]);
+    MappedAttrState(content, &ariaState, &nsARIAMap::gWAIUnivStateMap[index]);
     ++ index;
   }
 
   if (!mRoleMapEntry)
-    return NS_OK;
+    return ariaState;
 
   // Once DHTML role is used, we're only readonly if DHTML readonly used
-  (*aState) &= ~nsIAccessibleStates::STATE_READONLY;
-
-  if ((*aState) & nsIAccessibleStates::STATE_UNAVAILABLE) {
+  ariaState &= ~nsIAccessibleStates::STATE_READONLY;
+
+  if (ariaState & nsIAccessibleStates::STATE_UNAVAILABLE) {
     // Disabled elements are not selectable or focusable, even if disabled
     // via DHTML accessibility disabled property
-    (*aState) &= ~(nsIAccessibleStates::STATE_SELECTABLE |
+    ariaState &= ~(nsIAccessibleStates::STATE_SELECTABLE |
                    nsIAccessibleStates::STATE_FOCUSABLE);
   }
 
-  (*aState) |= mRoleMapEntry->state;
-  if (MappedAttrState(content, aState, &mRoleMapEntry->attributeMap1) &&
-      MappedAttrState(content, aState, &mRoleMapEntry->attributeMap2) &&
-      MappedAttrState(content, aState, &mRoleMapEntry->attributeMap3) &&
-      MappedAttrState(content, aState, &mRoleMapEntry->attributeMap4) &&
-      MappedAttrState(content, aState, &mRoleMapEntry->attributeMap5) &&
-      MappedAttrState(content, aState, &mRoleMapEntry->attributeMap6) &&
-      MappedAttrState(content, aState, &mRoleMapEntry->attributeMap7)) {
-    MappedAttrState(content, aState, &mRoleMapEntry->attributeMap8);
+  ariaState |= mRoleMapEntry->state;
+  if (MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap1) &&
+      MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap2) &&
+      MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap3) &&
+      MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap4) &&
+      MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap5) &&
+      MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap6) &&
+      MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap7)) {
+    MappedAttrState(content, &ariaState, &mRoleMapEntry->attributeMap8);
   }
 
-  return NS_OK;
+  return ariaState;
 }
 
 // Not implemented by this class
 
 /* DOMString getValue (); */
 NS_IMETHODIMP nsAccessible::GetValue(nsAString& aValue)
 {
   if (!mDOMNode) {
@@ -2788,21 +2781,21 @@ nsAccessible::GetRelation(PRUint32 aInde
 NS_IMETHODIMP
 nsAccessible::GetRelations(nsIArray **aRelations)
 {
   NS_ENSURE_ARG_POINTER(aRelations);
 
   nsCOMPtr<nsIMutableArray> relations = do_CreateInstance(NS_ARRAY_CONTRACTID);
   NS_ENSURE_TRUE(relations, NS_ERROR_OUT_OF_MEMORY);
 
-  // Latest nsIAccessibleRelation is RELATION_DESCRIPTION_FOR (0xof)
-  for (PRUint32 relType = 0; relType < 0x0f; ++relType) {
+  for (PRUint32 relType = nsIAccessibleRelation::RELATION_FIRST;
+       relType < nsIAccessibleRelation::RELATION_LAST;
+       ++relType) {
     nsCOMPtr<nsIAccessible> accessible;
-    nsresult rv = GetAccessibleRelated(relType, getter_AddRefs(accessible));
-    NS_ENSURE_SUCCESS(rv, rv);
+    GetAccessibleRelated(relType, getter_AddRefs(accessible));
 
     if (accessible) {
       nsCOMPtr<nsIAccessibleRelation> relation =
         new nsAccessibleRelationWrap(relType, accessible);
       NS_ENSURE_TRUE(relation, NS_ERROR_OUT_OF_MEMORY);
 
       relations->AppendElement(relation, PR_FALSE);
     }
--- a/accessible/src/base/nsAccessible.h
+++ b/accessible/src/base/nsAccessible.h
@@ -131,22 +131,17 @@ public:
    */
   virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
 
   /**
    * Maps ARIA state attributes to state of accessible. Note the given state
    * argument should hold states for accessible before you pass it into this
    * method.
    */
-  nsresult GetARIAState(PRUint32 *aState);
-
-#ifdef MOZ_ACCESSIBILITY_ATK
-  static PRBool FindTextFrame(PRInt32 &index, nsPresContext *aPresContext, nsIFrame *aCurFrame, 
-                                   nsIFrame **aFirstTextFrame, const nsIFrame *aTextFrame);
-#endif
+  PRUint32 GetARIAState();
 
 #ifdef DEBUG_A11Y
   static PRBool IsTextInterfaceSupportCorrect(nsIAccessible *aAccessible);
 #endif
 
   static PRBool IsCorrectFrameType(nsIFrame* aFrame, nsIAtom* aAtom);
   static PRUint32 State(nsIAccessible *aAcc) { PRUint32 state; aAcc->GetFinalState(&state, nsnull); return state; }
   static PRUint32 Role(nsIAccessible *aAcc) { PRUint32 role; aAcc->GetFinalRole(&role); return role; }
--- a/accessible/src/base/nsAccessibleEventData.cpp
+++ b/accessible/src/base/nsAccessibleEventData.cpp
@@ -354,17 +354,17 @@ nsAccStateChangeEvent::
   mState(aState), mIsExtraState(aIsExtraState)
 {
   // Use GetAccessibleByNode() because we do not want to store an accessible
   // since it leads to problems with delayed events in the case when
   // an accessible gets reorder event before delayed event is processed.
   nsCOMPtr<nsIAccessible> accessible(GetAccessibleByNode());
   if (accessible) {
     PRUint32 state = 0, extraState = 0;
-    accessible->GetFinalState(&state, &extraState);
+    accessible->GetFinalState(&state, mIsExtraState ? &extraState : nsnull);
     mIsEnabled = ((mIsExtraState ? extraState : state) & mState) != 0;
   } else {
     mIsEnabled = PR_FALSE;
   }
 }
 
 NS_IMETHODIMP
 nsAccStateChangeEvent::GetState(PRUint32 *aState)
@@ -389,21 +389,26 @@ nsAccStateChangeEvent::IsEnabled(PRBool 
 
 
 // nsAccTextChangeEvent
 NS_IMPL_ISUPPORTS_INHERITED1(nsAccTextChangeEvent, nsAccEvent,
                              nsIAccessibleTextChangeEvent)
 
 nsAccTextChangeEvent::
   nsAccTextChangeEvent(nsIAccessible *aAccessible,
-                       PRInt32 aStart, PRUint32 aLength, PRBool aIsInserted):
+                       PRInt32 aStart, PRUint32 aLength, PRBool aIsInserted, PRBool aIsAsynch):
   nsAccEvent(aIsInserted ? nsIAccessibleEvent::EVENT_TEXT_INSERTED : nsIAccessibleEvent::EVENT_TEXT_REMOVED,
-             aAccessible, nsnull),
+             aAccessible, nsnull, aIsAsynch),
   mStart(aStart), mLength(aLength), mIsInserted(aIsInserted)
 {
+  nsCOMPtr<nsIAccessibleText> textAccessible = do_QueryInterface(aAccessible);
+  NS_ASSERTION(textAccessible, "Should not be firing test change event for non-text accessible!!!");
+  if (textAccessible) {
+    textAccessible->GetText(aStart, aStart + aLength, mModifiedText);
+  }
 }
 
 NS_IMETHODIMP
 nsAccTextChangeEvent::GetStart(PRInt32 *aStart)
 {
   *aStart = mStart;
   return NS_OK;
 }
@@ -417,16 +422,23 @@ nsAccTextChangeEvent::GetLength(PRUint32
 
 NS_IMETHODIMP
 nsAccTextChangeEvent::IsInserted(PRBool *aIsInserted)
 {
   *aIsInserted = mIsInserted;
   return NS_OK;
 }
 
+NS_IMETHODIMP
+nsAccTextChangeEvent::GetModifiedText(nsAString& aModifiedText)
+{
+  aModifiedText = mModifiedText;
+  return NS_OK;
+}
+
 // nsAccCaretMoveEvent
 NS_IMPL_ISUPPORTS_INHERITED1(nsAccCaretMoveEvent, nsAccEvent,
                              nsIAccessibleCaretMoveEvent)
 
 nsAccCaretMoveEvent::
   nsAccCaretMoveEvent(nsIAccessible *aAccessible, PRInt32 aCaretOffset) :
   nsAccEvent(::nsIAccessibleEvent::EVENT_TEXT_CARET_MOVED, aAccessible, nsnull, PR_TRUE), // Currently always asynch
   mCaretOffset(aCaretOffset)
--- a/accessible/src/base/nsAccessibleEventData.h
+++ b/accessible/src/base/nsAccessibleEventData.h
@@ -41,16 +41,18 @@
 #ifndef _nsAccessibleEventData_H_
 #define _nsAccessibleEventData_H_
 
 #include "nsCOMPtr.h"
 #include "nsIAccessibleEvent.h"
 #include "nsIAccessible.h"
 #include "nsIAccessibleDocument.h"
 #include "nsIDOMNode.h"
+#include "nsString.h"
+
 class nsIPresShell;
 
 class nsAccEvent: public nsIAccessibleEvent
 {
 public:
   // Initialize with an nsIAccessible
   nsAccEvent(PRUint32 aEventType, nsIAccessible *aAccessible, void *aEventData, PRBool aIsAsynch = PR_FALSE);
   // Initialize with an nsIDOMNode
@@ -123,27 +125,28 @@ private:
   PRBool mIsExtraState;
   PRBool mIsEnabled;
 };
 
 class nsAccTextChangeEvent: public nsAccEvent,
                             public nsIAccessibleTextChangeEvent
 {
 public:
-  nsAccTextChangeEvent(nsIAccessible *aAccessible,
-                       PRInt32 aStart, PRUint32 aLength, PRBool aIsInserted);
+  nsAccTextChangeEvent(nsIAccessible *aAccessible, PRInt32 aStart, PRUint32 aLength,
+                       PRBool aIsInserted, PRBool aIsAsynch = PR_FALSE);
 
   NS_DECL_ISUPPORTS_INHERITED
   NS_FORWARD_NSIACCESSIBLEEVENT(nsAccEvent::)
   NS_DECL_NSIACCESSIBLETEXTCHANGEEVENT
 
 private:
   PRInt32 mStart;
   PRUint32 mLength;
   PRBool mIsInserted;
+  nsString mModifiedText;
 };
 
 class nsAccCaretMoveEvent: public nsAccEvent,
                            public nsIAccessibleCaretMoveEvent
 {
 public:
   nsAccCaretMoveEvent(nsIAccessible *aAccessible, PRInt32 aCaretOffset);
   nsAccCaretMoveEvent(nsIDOMNode *aNode);
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -1133,30 +1133,25 @@ nsDocAccessible::ARIAAttributeChanged(ns
     }
   }
 }
 
 void nsDocAccessible::ContentAppended(nsIDocument *aDocument,
                                       nsIContent* aContainer,
                                       PRInt32 aNewIndexInContainer)
 {
-  if (!mIsContentLoaded || !mDocument) {
-    if (mAccessNodeCache.Count() <= 1) {
-      // See comments in nsDocAccessible::InvalidateCacheSubtree
-      InvalidateChildren();
-    }
+  if ((!mIsContentLoaded || !mDocument) && mAccessNodeCache.Count() <= 1) {
+    // See comments in nsDocAccessible::InvalidateCacheSubtree
+    InvalidateChildren();
     return;
   }
 
   PRUint32 childCount = aContainer->GetChildCount();
   for (PRUint32 index = aNewIndexInContainer; index < childCount; index ++) {
     nsCOMPtr<nsIContent> child(aContainer->GetChildAt(index));
-
-    FireTextChangedEventOnDOMNodeInserted(child, aContainer, index);
-
     // InvalidateCacheSubtree will not fire the EVENT_SHOW for the new node
     // unless an accessible can be created for the passed in node, which it
     // can't do unless the node is visible. The right thing happens there so
     // no need for an extra visibility check here.
     InvalidateCacheSubtree(child, nsIAccessibleEvent::EVENT_DOM_CREATE);
   }
 }
 
@@ -1179,33 +1174,32 @@ void nsDocAccessible::CharacterDataChang
 {
   FireTextChangedEventOnDOMCharacterDataModified(aContent, aInfo);
 }
 
 void
 nsDocAccessible::ContentInserted(nsIDocument *aDocument, nsIContent* aContainer,
                                  nsIContent* aChild, PRInt32 aIndexInContainer)
 {
-  FireTextChangedEventOnDOMNodeInserted(aChild, aContainer, aIndexInContainer);
-
   // InvalidateCacheSubtree will not fire the EVENT_SHOW for the new node
   // unless an accessible can be created for the passed in node, which it
   // can't do unless the node is visible. The right thing happens there so
   // no need for an extra visibility check here.
   InvalidateCacheSubtree(aChild, nsIAccessibleEvent::EVENT_DOM_CREATE);
 }
 
 void
 nsDocAccessible::ContentRemoved(nsIDocument *aDocument, nsIContent* aContainer,
                                 nsIContent* aChild, PRInt32 aIndexInContainer)
 {
-  FireTextChangedEventOnDOMNodeRemoved(aChild, aContainer, aIndexInContainer);
-
   // Invalidate the subtree of the removed element.
-  InvalidateCacheSubtree(aChild, nsIAccessibleEvent::EVENT_DOM_DESTROY);
+  // InvalidateCacheSubtree(aChild, nsIAccessibleEvent::EVENT_DOM_DESTROY);
+  // This is no longer needed, we get our notifications directly from content
+  // *before* the frame for the content is destroyed, or any other side effects occur.
+  // That allows us to correctly calculate the TEXT_REMOVED event if there is one.
 }
 
 void
 nsDocAccessible::ParentChainChanged(nsIContent *aContent)
 {
 }
 
 void
@@ -1251,132 +1245,92 @@ nsDocAccessible::FireTextChangedEventOnD
   // Text has been added.
   if (replaceLen) {
     nsCOMPtr<nsIAccessibleTextChangeEvent> event =
       new nsAccTextChangeEvent(accessible, offset, replaceLen, PR_TRUE);
     textAccessible->FireAccessibleEvent(event);
   }
 }
 
-void
-nsDocAccessible::FireTextChangedEventOnDOMNodeInserted(nsIContent *aChild,
-                                                       nsIContent *aContainer,
-                                                       PRInt32 aIndexInContainer)
+already_AddRefed<nsIAccessibleTextChangeEvent>
+nsDocAccessible::CreateTextChangeEventForNode(nsIAccessible *aContainerAccessible,
+                                              nsIDOMNode *aChangeNode,
+                                              nsIAccessible *aAccessibleForChangeNode,
+                                              PRBool aIsInserting,
+                                              PRBool aIsAsynch)
 {
-  if (!mIsContentLoaded || !mDocument) {
-    return;
+  nsRefPtr<nsHyperTextAccessible> textAccessible;
+  aContainerAccessible->QueryInterface(NS_GET_IID(nsHyperTextAccessible),
+                                       getter_AddRefs(textAccessible));
+  if (!textAccessible) {
+    return nsnull;
   }
 
-  nsCOMPtr<nsIDOMNode> node(do_QueryInterface(aChild));
-  if (!node)
-    return;
-
-  nsCOMPtr<nsIAccessible> accessible;
-  nsresult rv = GetAccessibleInParentChain(node, getter_AddRefs(accessible));
-  if (NS_FAILED(rv) || !accessible)
-    return;
-
-  nsRefPtr<nsHyperTextAccessible> textAccessible;
-  rv = accessible->QueryInterface(NS_GET_IID(nsHyperTextAccessible),
-                                  getter_AddRefs(textAccessible));
-  if (NS_FAILED(rv) || !textAccessible)
-    return;
+  PRInt32 offset;
+  PRInt32 length = 0;
+  nsCOMPtr<nsIAccessible> changeAccessible;
+  nsresult rv = textAccessible->DOMPointToHypertextOffset(aChangeNode, -1, &offset,
+                                                          getter_AddRefs(changeAccessible));
+  NS_ENSURE_SUCCESS(rv, nsnull);
 
-  PRUint32 length = 1;
-  if (aChild && aChild->IsNodeOfType(nsINode::eTEXT)) {
-    length = aChild->TextLength();
-    if (!length)
-      return;
-  } else {
-    // Don't fire event for the first html:br in an editor.
-    nsCOMPtr<nsIEditor> editor;
-    textAccessible->GetAssociatedEditor(getter_AddRefs(editor));
-    if (editor) {
-      PRBool isEmpty = PR_FALSE;
-      editor->GetDocumentIsEmpty(&isEmpty);
-      if (isEmpty)
-        return;
+  if (!aAccessibleForChangeNode) {
+    // A span-level object or something else without an accessible is being removed, where
+    // it has no accessible but it has descendant content which is aggregated as text
+    // into the parent hypertext.
+    // In this case, accessibleToBeRemoved may just be the first
+    // accessible that is removed, which affects the text in the hypertext container
+    if (!changeAccessible) {
+      return nsnull; // No descendant content that represents any text in the hypertext parent
+    }
+    nsCOMPtr<nsIAccessible> child = changeAccessible;
+    while (PR_TRUE) {
+      nsCOMPtr<nsIAccessNode> childAccessNode =
+        do_QueryInterface(changeAccessible);
+      nsCOMPtr<nsIDOMNode> childNode;
+      childAccessNode->GetDOMNode(getter_AddRefs(childNode));
+      if (!nsAccUtils::IsAncestorOf(aChangeNode, childNode)) {
+        break;  // We only want accessibles with DOM nodes as children of this node
+      }
+      length += TextLength(child);
+      child->GetNextSibling(getter_AddRefs(changeAccessible));
+      if (!changeAccessible) {
+        break;
+      }
+      child.swap(changeAccessible);
+    }
+  }
+  else {
+    NS_ASSERTION(changeAccessible == aAccessibleForChangeNode,
+                 "Hypertext is reporting a different accessible for this node");
+    length = TextLength(aAccessibleForChangeNode);
+    if (Role(aAccessibleForChangeNode) == nsIAccessibleRole::ROLE_WHITESPACE) {  // newline
+      // Don't fire event for the first html:br in an editor.
+      nsCOMPtr<nsIEditor> editor;
+      textAccessible->GetAssociatedEditor(getter_AddRefs(editor));
+      if (editor) {
+        PRBool isEmpty = PR_FALSE;
+        editor->GetDocumentIsEmpty(&isEmpty);
+        if (isEmpty) {
+          return nsnull;
+        }
+      }
     }
   }
 
-  nsCOMPtr<nsIDOMNode> parentNode(do_QueryInterface(aContainer));
-  if (!parentNode)
-    return;
-
-  PRInt32 offset = 0;
-  rv = textAccessible->DOMPointToHypertextOffset(parentNode, aIndexInContainer, &offset);
-  if (NS_FAILED(rv))
-    return;
-
-  nsCOMPtr<nsIAccessibleTextChangeEvent> event =
-    new nsAccTextChangeEvent(accessible, offset, length, PR_TRUE);
-  if (!event)
-    return;
-
-  textAccessible->FireAccessibleEvent(event);
-}
-
-void
-nsDocAccessible::FireTextChangedEventOnDOMNodeRemoved(nsIContent *aChild,
-                                                      nsIContent *aContainer,
-                                                      PRInt32 aIndexInContainer)
-{
-  if (!mIsContentLoaded || !mDocument) {
-    return;
+  if (length <= 0) {
+    return nsnull;
   }
 
-  nsCOMPtr<nsIDOMNode> node(do_QueryInterface(aChild));
-  if (!node)
-    return;
-
-  nsCOMPtr<nsIAccessible> accessible;
-  nsresult rv = GetAccessibleInParentChain(node, getter_AddRefs(accessible));
-  if (NS_FAILED(rv) || !accessible)
-    return;
-
-  nsRefPtr<nsHyperTextAccessible> textAccessible;
-  rv = accessible->QueryInterface(NS_GET_IID(nsHyperTextAccessible),
-                                  getter_AddRefs(textAccessible));
-  if (NS_FAILED(rv) || !textAccessible)
-    return;
+  nsIAccessibleTextChangeEvent *event =
+    new nsAccTextChangeEvent(aContainerAccessible, offset, length, aIsInserting, aIsAsynch);
+  NS_IF_ADDREF(event);
 
-  PRUint32 length = 1;
-  if (aChild && aChild->IsNodeOfType(nsINode::eTEXT)) {
-    length = aChild->TextLength();
-    if (!length)
-      return;
-  } else {
-    // Don't fire event for the last html:br in an editor.
-    nsCOMPtr<nsIEditor> editor;
-    textAccessible->GetAssociatedEditor(getter_AddRefs(editor));
-    if (editor) {
-      PRBool isEmpty = PR_FALSE;
-      editor->GetDocumentIsEmpty(&isEmpty);
-      if (isEmpty)
-        return;
-    }
-  }
-
-  nsCOMPtr<nsIDOMNode> parentNode(do_QueryInterface(aContainer));
-  if (!parentNode)
-    return;
-
-  PRInt32 offset = 0;
-  rv = textAccessible->DOMPointToHypertextOffset(parentNode, aIndexInContainer, &offset);
-  if (NS_FAILED(rv))
-    return;
-
-  nsCOMPtr<nsIAccessibleTextChangeEvent> event =
-    new nsAccTextChangeEvent(accessible, offset, length, PR_FALSE);
-  if (!event)
-    return;
-
-  textAccessible->FireAccessibleEvent(event);
+  return event;
 }
-
+  
 nsresult nsDocAccessible::FireDelayedToolkitEvent(PRUint32 aEvent,
                                                   nsIDOMNode *aDOMNode,
                                                   void *aData,
                                                   EDupeEventRule aAllowDupes,
                                                   PRBool aIsAsynch)
 {
   nsCOMPtr<nsIAccessibleEvent> event =
     new nsAccEvent(aEvent, aDOMNode, aData, PR_TRUE);
@@ -1487,19 +1441,48 @@ NS_IMETHODIMP nsDocAccessible::FlushPend
   PRUint32 index;
   for (index = 0; index < length; index ++) {
     nsCOMPtr<nsIAccessibleEvent> accessibleEvent(
       do_QueryInterface(mEventsToFire[index]));
     NS_ASSERTION(accessibleEvent, "Array item is not an accessible event");
 
     nsCOMPtr<nsIAccessible> accessible;
     accessibleEvent->GetAccessible(getter_AddRefs(accessible));
+
+    PRUint32 eventType;
+    accessibleEvent->GetEventType(&eventType);
+    if (eventType == nsIAccessibleEvent::EVENT_DOM_CREATE || 
+        eventType == nsIAccessibleEvent::EVENT_ASYNCH_SHOW) {
+      // 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.
+      nsCOMPtr<nsIDOMNode> domNode;
+      accessibleEvent->GetDOMNode(getter_AddRefs(domNode));
+      if (domNode && domNode != mDOMNode) {
+        nsCOMPtr<nsIAccessible> containerAccessible;
+        GetAccessibleInParentChain(domNode, getter_AddRefs(containerAccessible));
+        nsCOMPtr<nsIAccessibleTextChangeEvent> textChangeEvent =
+          CreateTextChangeEventForNode(containerAccessible, domNode, accessible, PR_TRUE, PR_TRUE);
+        if (textChangeEvent) {
+          PRBool isFromUserInput;
+          accessibleEvent->GetIsFromUserInput(&isFromUserInput);
+          nsCOMPtr<nsIDOMNode> hyperTextNode;
+          textChangeEvent->GetDOMNode(getter_AddRefs(hyperTextNode));
+          nsAccEvent::PrepareForEvent(hyperTextNode, 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);
+        }
+      }
+    }
+
     if (accessible) {
-      PRUint32 eventType;
-      accessibleEvent->GetEventType(&eventType);
       if (eventType == nsIAccessibleEvent::EVENT_INTERNAL_LOAD) {
         nsCOMPtr<nsPIAccessibleDocument> docAccessible =
           do_QueryInterface(accessible);
         NS_ASSERTION(docAccessible, "No doc accessible for doc load event");
         if (docAccessible) {
           docAccessible->FireDocLoadEvents(nsIAccessibleEvent::EVENT_DOCUMENT_LOAD_COMPLETE);
         }
       }
@@ -1529,16 +1512,24 @@ NS_IMETHODIMP nsDocAccessible::FlushPend
       else {
         // The input state was previously stored with the nsIAccessibleEvent,
         // so use that state now when firing the event
         nsAccEvent::PrepareForEvent(accessibleEvent);
         FireAccessibleEvent(accessibleEvent);
         // Post event processing
         if (eventType == nsIAccessibleEvent::EVENT_ASYNCH_HIDE ||
             eventType == nsIAccessibleEvent::EVENT_DOM_DESTROY) {
+          // Invalidate children
+          nsCOMPtr<nsIAccessible> containerAccessible;
+          accessible->GetParent(getter_AddRefs(containerAccessible));
+          nsCOMPtr<nsPIAccessible> privateContainerAccessible =
+            do_QueryInterface(containerAccessible);
+          if (privateContainerAccessible) {
+            privateContainerAccessible->InvalidateChildren();
+          }
           // Shutdown nsIAccessNode's or nsIAccessibles for any DOM nodes in this subtree
           nsCOMPtr<nsIDOMNode> hidingNode;
           accessibleEvent->GetDOMNode(getter_AddRefs(hidingNode));
           if (hidingNode) {
             RefreshNodes(hidingNode); // Will this bite us with asynch events
           }
         }
       }
@@ -1697,48 +1688,61 @@ NS_IMETHODIMP nsDocAccessible::Invalidat
   else if (aChangeEventType == nsIAccessibleEvent::EVENT_DOM_DESTROY) {
     printf("[Destroy  %s %s]\n", NS_ConvertUTF16toUTF8(localName).get(), hasAccessible);
   }
   else if (aChangeEventType == nsIAccessibleEvent::EVENT_DOM_SIGNIFICANT_CHANGE) {
     printf("[Type change %s %s]\n", NS_ConvertUTF16toUTF8(localName).get(), hasAccessible);
   }
 #endif
 
+  nsCOMPtr<nsIAccessible> containerAccessible;
+  GetAccessibleInParentChain(childNode, getter_AddRefs(containerAccessible));
+  if (!containerAccessible) {
+    containerAccessible = this;
+  }
+
   if (!isShowing) {
     // Fire EVENT_ASYNCH_HIDE or EVENT_DOM_DESTROY if previous accessible existed for node being hidden.
     // Fire this before the accessible goes away.
     if (childAccessible) {
       PRUint32 removalEventType = isAsynch ? nsIAccessibleEvent::EVENT_ASYNCH_HIDE :
                                   nsIAccessibleEvent::EVENT_DOM_DESTROY;
       nsCOMPtr<nsIAccessibleEvent> removalEvent =
         new nsAccEvent(removalEventType, childAccessible, nsnull, PR_TRUE);
       NS_ENSURE_TRUE(removalEvent, NS_ERROR_OUT_OF_MEMORY);
       FireDelayedAccessibleEvent(removalEvent, eCoalesceFromSameSubtree, isAsynch);
     }
+    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<nsIAccessibleTextChangeEvent> textChangeEvent =
+        CreateTextChangeEventForNode(containerAccessible, childNode, childAccessible,
+                                     PR_FALSE, isAsynch);
+      if (textChangeEvent) {
+        FireAccessibleEvent(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.
   // We're guaranteed success, because we will eventually end up at the doc accessible,
   // and there is always one of those.
 
-  nsCOMPtr<nsIAccessible> containerAccessible;
-  GetAccessibleInParentChain(childNode, getter_AddRefs(containerAccessible));
-  if (!containerAccessible) {
-    containerAccessible = this;
-  }
-  nsCOMPtr<nsPIAccessible> privateContainerAccessible =
-    do_QueryInterface(containerAccessible);
-  if (privateContainerAccessible) {
-    privateContainerAccessible->InvalidateChildren();
-  }
-
   if (aChild && !isHiding) {
+    nsCOMPtr<nsPIAccessible> privateContainerAccessible =
+      do_QueryInterface(containerAccessible);
+    if (privateContainerAccessible) {
+      privateContainerAccessible->InvalidateChildren();
+    }
     // Fire EVENT_SHOW, EVENT_MENUPOPUP_START for newly visible content.
     // Fire after a short timer, because we want to make sure the view has been
     // updated to make this accessible content visible. If we don't wait,
     // the assistive technology may receive the event and then retrieve
     // nsIAccessibleStates::STATE_INVISIBLE for the event's accessible object.
     PRUint32 additionEvent = isAsynch ? nsIAccessibleEvent::EVENT_ASYNCH_SHOW :
                                         nsIAccessibleEvent::EVENT_DOM_CREATE;
     FireDelayedToolkitEvent(additionEvent, childNode, nsnull,
--- a/accessible/src/base/nsDocAccessible.h
+++ b/accessible/src/base/nsDocAccessible.h
@@ -102,17 +102,17 @@ class nsDocAccessible : public nsHyperTe
     // nsIAccessibleText
     NS_IMETHOD GetAssociatedEditor(nsIEditor **aEditor);
 
     enum EDupeEventRule { eAllowDupes, eCoalesceFromSameSubtree, eRemoveDupes };
 
     /**
       * Non-virtual method to fire a delayed event after a 0 length timeout
       *
-      * @param aEvent - the nsIAccessibleEvent event ype
+      * @param aEvent - the nsIAccessibleEvent event type
       * @param aDOMNode - DOM node the accesible event should be fired for
       * @param aData - any additional data for the event
       * @param aAllowDupes - eAllowDupes: more than one event of the same type is allowed. 
       *                      eCoalesceFromSameSubtree: if two events are in the same subtree,
       *                                                only the event on ancestor is used
       *                      eRemoveDupes (default): events of the same type are discarded
       *                                              (the last one is used)
       *
@@ -156,31 +156,30 @@ class nsDocAccessible : public nsHyperTe
      */
     void ARIAAttributeChanged(nsIContent* aContent, nsIAtom* aAttribute);
 
     /**
      * Fire text changed event for charackter data changed.
      */
     void FireTextChangedEventOnDOMCharacterDataModified(nsIContent *aContent,
                                                         CharacterDataChangeInfo* aInfo);
-    /**
-     * Fire text changed event for the inserted element if it is inside a text
-     * accessible.
-     */
-    void FireTextChangedEventOnDOMNodeInserted(nsIContent *aChild,
-                                               nsIContent *aContainer,
-                                               PRInt32 aIndexInContainer);
 
     /**
-     * Fire text changed event for the removed element if it is inside a text
-     * accessible.
+     * 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)
      */
-    void FireTextChangedEventOnDOMNodeRemoved(nsIContent *aChild,
-                                              nsIContent *aContainer,
-                                              PRInt32 aIndexInContainer);
+    already_AddRefed<nsIAccessibleTextChangeEvent>
+    CreateTextChangeEventForNode(nsIAccessible *aContainerAccessible,
+                                 nsIDOMNode *aChangeNode,
+                                 nsIAccessible *aAccessibleForNode,
+                                 PRBool aIsInserting,
+                                 PRBool aIsAsynch);
 
     nsAccessNodeHashtable mAccessNodeCache;
     void *mWnd;
     nsCOMPtr<nsIDocument> mDocument;
     nsCOMPtr<nsITimer> mScrollWatchTimer;
     nsCOMPtr<nsITimer> mFireEventTimer;
     PRUint16 mScrollPositionChangedTicks; // Used for tracking scroll events
     PRPackedBool mIsContentLoaded;
--- a/accessible/src/base/nsRootAccessible.cpp
+++ b/accessible/src/base/nsRootAccessible.cpp
@@ -464,16 +464,19 @@ PRBool nsRootAccessible::FireAccessibleF
       finalFocusNode = do_QueryInterface(relatedEl);
       if (!finalFocusNode) {
         return PR_FALSE;
       }
       GetAccService()->GetAccessibleFor(finalFocusNode, getter_AddRefs(finalFocusAccessible));      
       // For activedescendant, the ARIA spec does not require that the user agent
       // checks whether finalFocusNode is actually a descendant of the element with
       // the activedescendant attribute.
+      if (!finalFocusAccessible) {
+        return PR_FALSE;
+      }
     }
   }
 
   // Fire focus only if it changes, but always fire focus events when aForceEvent == PR_TRUE
   if (gLastFocusedNode == finalFocusNode && !aForceEvent) {
     return PR_FALSE;
   }
 
@@ -931,16 +934,19 @@ nsRootAccessible::GetContentDocShell(nsI
     // don't use this one. This happens for example if it's inside
     // a background tab (tabbed browsing)
     while (accessible) {
       if (State(accessible) & nsIAccessibleStates::STATE_INVISIBLE) {
         return nsnull;
       }
       nsCOMPtr<nsIAccessible> ancestor;
       accessible->GetParent(getter_AddRefs(ancestor));
+      if (ancestor == this) {
+        break; // Don't check past original root accessible we started with
+      }
       accessible.swap(ancestor);
     }
 
     NS_ADDREF(aStart);
     return aStart;
   }
   nsCOMPtr<nsIDocShellTreeNode> treeNode(do_QueryInterface(aStart));
   if (treeNode) {
--- a/accessible/src/html/nsHTMLTextAccessible.cpp
+++ b/accessible/src/html/nsHTMLTextAccessible.cpp
@@ -57,19 +57,19 @@ NS_IMETHODIMP nsHTMLTextAccessible::GetN
 {
   aName.Truncate();
   return AppendTextTo(aName, 0, PR_UINT32_MAX);
 }
 
 NS_IMETHODIMP nsHTMLTextAccessible::GetRole(PRUint32 *aRole)
 {
   nsIFrame *frame = GetFrame();
-  NS_ENSURE_TRUE(frame, NS_ERROR_NULL_POINTER);
-
-  if (frame->IsGeneratedContentFrame()) {
+  // Don't return on null frame -- we still return a role
+  // after accessible is shutdown/DEFUNCT
+  if (frame && frame->IsGeneratedContentFrame()) {
     *aRole = nsIAccessibleRole::ROLE_STATICTEXT;
     return NS_OK;
   }
 
   return nsTextAccessible::GetRole(aRole);
 }
 
 NS_IMETHODIMP
--- a/accessible/src/html/nsHyperTextAccessible.cpp
+++ b/accessible/src/html/nsHyperTextAccessible.cpp
@@ -310,17 +310,19 @@ nsIntRect nsHyperTextAccessible::GetBoun
 }
 
 /*
  * Gets the specified text.
  */
 nsIFrame*
 nsHyperTextAccessible::GetPosAndText(PRInt32& aStartOffset, PRInt32& aEndOffset,
                                      nsAString *aText, nsIFrame **aEndFrame,
-                                     nsIntRect *aBoundsRect)
+                                     nsIntRect *aBoundsRect,
+                                     nsIAccessible **aStartAcc,
+                                     nsIAccessible **aEndAcc)
 {
   PRInt32 startOffset = aStartOffset;
   PRInt32 endOffset = aEndOffset;
 
   // Clear out parameters and set up loop
   if (aText) {
     aText->Truncate();
   }
@@ -334,16 +336,20 @@ nsHyperTextAccessible::GetPosAndText(PRI
 
   nsIFrame *startFrame = nsnull;
   if (aEndFrame) {
     *aEndFrame = nsnull;
   }
   if (aBoundsRect) {
     aBoundsRect->Empty();
   }
+  if (aStartAcc)
+    *aStartAcc = nsnull;
+  if (aEndAcc)
+    *aEndAcc = nsnull;
 
   nsIntRect unionRect;
   nsCOMPtr<nsIAccessible> accessible;
 
   gfxSkipChars skipChars;
   gfxSkipCharsIterator iter;
 
   // Loop through children and collect valid offsets, text and bounds
@@ -380,16 +386,18 @@ nsHyperTextAccessible::GetPosAndText(PRI
           // Get out the continuing text frame with this offset
           PRInt32 outStartLineUnused;
           PRInt32 contentOffset = iter.ConvertSkippedToOriginal(startOffset) +
                                   ourRenderedStart - ourContentStart;
           frame->GetChildFrameContainingOffset(contentOffset, PR_TRUE,
                                                &outStartLineUnused, &frame);
           if (aEndFrame) {
             *aEndFrame = frame; // We ended in the current frame
+            if (aEndAcc)
+              NS_ADDREF(*aEndAcc = accessible);
           }
           if (substringEndOffset > endOffset) {
             // Need to stop before the end of the available text
             substringEndOffset = endOffset;
           }
           aEndOffset = endOffset;
         }
         if (aText) {
@@ -400,16 +408,18 @@ nsHyperTextAccessible::GetPosAndText(PRI
         if (aBoundsRect) {    // Caller wants the bounds of the text
           aBoundsRect->UnionRect(*aBoundsRect,
                                  GetBoundsForString(primaryFrame, startOffset,
                                                     substringEndOffset));
         }
         if (!startFrame) {
           startFrame = frame;
           aStartOffset = startOffset;
+          if (aStartAcc)
+            NS_ADDREF(*aStartAcc = accessible);
         }
         // We already started copying in this accessible's string,
         // for the next accessible we'll start at offset 0
         startOffset = 0;
       }
       else {
         // We have not found the start position yet, get the new startOffset
         // that is relative to next accessible
@@ -433,27 +443,31 @@ nsHyperTextAccessible::GetPosAndText(PRI
           if (aBoundsRect) {
             aBoundsRect->UnionRect(*aBoundsRect,
                                    frame->GetScreenRectExternal());
           }
         }
         if (!startFrame) {
           startFrame = frame;
           aStartOffset = 0;
+          if (aStartAcc)
+            NS_ADDREF(*aStartAcc = accessible);
         }
       }
       -- endOffset;
     }
     if (endOffset <= 0 && startFrame) {
       break; // If we don't have startFrame yet, get that in next loop iteration
     }
   }
 
   if (aEndFrame && !*aEndFrame) {
     *aEndFrame = startFrame;
+    if (aStartAcc && aEndAcc)
+      NS_ADDREF(*aEndAcc = *aStartAcc);
   }
 
   return startFrame;
 }
 
 NS_IMETHODIMP nsHyperTextAccessible::GetText(PRInt32 aStartOffset, PRInt32 aEndOffset, nsAString &aText)
 {
   if (!mDOMNode) {
@@ -507,27 +521,29 @@ nsresult nsHyperTextAccessible::DOMPoint
                                                           PRInt32* aHyperTextOffset,
                                                           nsIAccessible **aFinalAccessible)
 {
   // Turn a DOM Node and offset into an offset into this hypertext.
   // On failure, return null. On success, return the DOM node which contains the offset.
   NS_ENSURE_ARG_POINTER(aHyperTextOffset);
   *aHyperTextOffset = 0;
   NS_ENSURE_ARG_POINTER(aNode);
-  NS_ENSURE_TRUE(aNodeOffset >= 0, NS_ERROR_INVALID_ARG);
   if (aFinalAccessible) {
     *aFinalAccessible = nsnull;
   }
 
   PRUint32 addTextOffset = 0;
   nsCOMPtr<nsIDOMNode> findNode;
 
   unsigned short nodeType;
   aNode->GetNodeType(&nodeType);
-  if (nodeType == nsIDOMNode::TEXT_NODE) {
+  if (aNodeOffset == -1) {
+    findNode = aNode;
+  }
+  else if (nodeType == nsIDOMNode::TEXT_NODE) {
     // For text nodes, aNodeOffset comes in as a character offset
     // Text offset will be added at the end, if we find the offset in this hypertext
     // We want the "skipped" offset into the text (rendered text without the extra whitespace)
     nsCOMPtr<nsIContent> content = do_QueryInterface(aNode);
     NS_ASSERTION(content, "No nsIContent for dom node");
     nsCOMPtr<nsIPresShell> presShell = GetPresShell();
     NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
     nsIFrame *frame = presShell->GetPrimaryFrameFor(content);
@@ -599,38 +615,54 @@ nsresult nsHyperTextAccessible::DOMPoint
   if (accessible) {
     *aHyperTextOffset += addTextOffset;
     NS_ASSERTION(accessible == childAccessible, "These should be equal whenever we exit loop and accessible != nsnull");
     if (aFinalAccessible && (NextChild(accessible) || static_cast<PRInt32>(addTextOffset) < TextLength(childAccessible))) {  
       // If not at end of last text node, we will return the accessible we were in
       NS_ADDREF(*aFinalAccessible = childAccessible);
     }
   }
+
   return NS_OK;
 }
 
-PRInt32 nsHyperTextAccessible::GetRelativeOffset(nsIPresShell *aPresShell, nsIFrame *aFromFrame, PRInt32 aFromOffset,
-                                                 nsSelectionAmount aAmount, nsDirection aDirection, PRBool aNeedsStart)
+PRInt32
+nsHyperTextAccessible::GetRelativeOffset(nsIPresShell *aPresShell,
+                                         nsIFrame *aFromFrame,
+                                         PRInt32 aFromOffset,
+                                         nsIAccessible *aFromAccessible,
+                                         nsSelectionAmount aAmount,
+                                         nsDirection aDirection,
+                                         PRBool aNeedsStart)
 {
   const PRBool kIsJumpLinesOk = PR_TRUE;          // okay to jump lines
   const PRBool kIsScrollViewAStop = PR_FALSE;     // do not stop at scroll views
   const PRBool kIsKeyboardSelect = PR_TRUE;       // is keyboard selection
   const PRBool kIsVisualBidi = PR_FALSE;          // use visual order for bidi text
 
   EWordMovementType wordMovementType = aNeedsStart ? eStartWord : eEndWord;
   if (aAmount == eSelectLine) {
     aAmount = (aDirection == eDirNext) ? eSelectEndLine : eSelectBeginLine;
   }
 
   // Ask layout for the new node and offset, after moving the appropriate amount
   nsPeekOffsetStruct pos;
 
-  PRInt32 contentOffset;
-  nsresult rv = RenderedToContentOffset(aFromFrame, aFromOffset, &contentOffset);
-  NS_ENSURE_SUCCESS(rv, -1);
+  nsresult rv;
+  PRInt32 contentOffset = aFromOffset;
+  if (IsText(aFromAccessible)) {
+    nsCOMPtr<nsPIAccessNode> accessNode(do_QueryInterface(aFromAccessible));
+    NS_ASSERTION(accessNode, "nsIAccessible doesn't support nsPIAccessNode");
+
+    nsIFrame *frame = accessNode->GetFrame();
+    NS_ENSURE_TRUE(frame, -1);
+
+    rv = RenderedToContentOffset(frame, aFromOffset, &contentOffset);
+    NS_ENSURE_SUCCESS(rv, -1);
+  }
 
   pos.SetData(aAmount, aDirection, contentOffset,
               0, kIsJumpLinesOk, kIsScrollViewAStop, kIsKeyboardSelect, kIsVisualBidi,
               wordMovementType);
   rv = aFromFrame->PeekOffset(&pos);
   if (NS_FAILED(rv)) {
     if (aDirection == eDirPrevious) {
       // Use passed-in frame as starting point in failure case for now,
@@ -718,17 +750,20 @@ nsresult nsHyperTextAccessible::GetTextH
   PRInt32 endOffset = aOffset;
 
   if (aBoundaryType == BOUNDARY_LINE_END) {
     // Avoid getting the previous line
     ++ startOffset;
     ++ endOffset;
   }
   // Convert offsets to frame-relative
-  nsIFrame *startFrame = GetPosAndText(startOffset, endOffset);
+  nsCOMPtr<nsIAccessible> startAcc;
+  nsIFrame *startFrame = GetPosAndText(startOffset, endOffset, nsnull, nsnull,
+                                       nsnull, getter_AddRefs(startAcc));
+
   if (!startFrame) {
     PRInt32 textLength;
     GetCharacterCount(&textLength);
     return (aOffset < 0 || aOffset > textLength) ? NS_ERROR_FAILURE : NS_OK;
   }
 
   nsSelectionAmount amount;
   PRBool needsStart = PR_FALSE;
@@ -787,35 +822,38 @@ nsresult nsHyperTextAccessible::GetTextH
   PRInt32 finalStartOffset, finalEndOffset;
 
   // If aType == eGetAt we'll change both the start and end offset from
   // the original offset
   if (aType == eGetAfter) {
     finalStartOffset = aOffset;
   }
   else {
-    finalStartOffset = GetRelativeOffset(presShell, startFrame,  startOffset,
-                                         amount, eDirPrevious, needsStart);
+    finalStartOffset = GetRelativeOffset(presShell, startFrame, startOffset,
+                                         startAcc, amount, eDirPrevious,
+                                         needsStart);
     NS_ENSURE_TRUE(finalStartOffset >= 0, NS_ERROR_FAILURE);
   }
 
   if (aType == eGetBefore) {
     endOffset = aOffset;
   }
   else {
     // Start moving forward from the start so that we don't get 
     // 2 words/lines if the offset occured on whitespace boundary
     // Careful, startOffset and endOffset are passed by reference to GetPosAndText() and changed
     startOffset = endOffset = finalStartOffset;
-    nsIFrame *endFrame = GetPosAndText(startOffset, endOffset);
+    nsCOMPtr<nsIAccessible> endAcc;
+    nsIFrame *endFrame = GetPosAndText(startOffset, endOffset, nsnull, nsnull,
+                                       nsnull, getter_AddRefs(endAcc));
     if (!endFrame) {
       return NS_ERROR_FAILURE;
     }
-    finalEndOffset = GetRelativeOffset(presShell, endFrame, endOffset, amount,
-                                       eDirNext, needsStart);
+    finalEndOffset = GetRelativeOffset(presShell, endFrame, endOffset, endAcc,
+                                       amount, eDirNext, needsStart);
     NS_ENSURE_TRUE(endOffset >= 0, NS_ERROR_FAILURE);
     if (finalEndOffset == aOffset) {
       // This happens sometimes when current character at finalStartOffset 
       // is an embedded object character representing another hypertext, that
       // the AT really needs to dig into separately
       ++ finalEndOffset;
     }
   }
@@ -1504,16 +1542,68 @@ NS_IMETHODIMP nsHyperTextAccessible::Rem
   if (aSelectionNum < 0 || aSelectionNum >= rangeCount)
     return NS_ERROR_INVALID_ARG;
 
   nsCOMPtr<nsIDOMRange> range;
   domSel->GetRangeAt(aSelectionNum, getter_AddRefs(range));
   return domSel->RemoveRange(range);
 }
 
+NS_IMETHODIMP
+nsHyperTextAccessible::ScrollSubstringTo(PRInt32 aStartIndex, PRInt32 aEndIndex,
+                                         PRUint32 aScrollType)
+{
+  PRInt32 startOffset = aStartIndex, endOffset = aEndIndex;
+  nsIFrame *startFrame = nsnull, *endFrame = nsnull;
+  nsCOMPtr<nsIAccessible> startAcc, endAcc;
+
+  startFrame = GetPosAndText(startOffset, endOffset,
+                             nsnull, &endFrame, nsnull,
+                             getter_AddRefs(startAcc), getter_AddRefs(endAcc));
+  if (!startFrame || !endFrame)
+    return NS_ERROR_FAILURE;
+
+  nsCOMPtr<nsIDOMNode> startNode;
+  nsCOMPtr<nsIContent> startContent(startFrame->GetContent());
+
+  PRBool isStartAccText = IsText(startAcc);
+  if (isStartAccText) {
+    nsresult rv = RenderedToContentOffset(startFrame, startOffset,
+                                          &startOffset);
+    NS_ENSURE_SUCCESS(rv, rv);
+    startNode = do_QueryInterface(startContent);
+  } else {
+    nsCOMPtr<nsIContent> startParent(startContent->GetParent());
+    NS_ENSURE_STATE(startParent);
+    startOffset = startParent->IndexOf(startContent);
+    startNode = do_QueryInterface(startParent);
+  }
+  NS_ENSURE_STATE(startNode);
+
+  nsCOMPtr<nsIDOMNode> endNode;
+  nsCOMPtr<nsIContent> endContent(endFrame->GetContent());
+
+  PRBool isEndAccText = IsText(endAcc);
+  if (isEndAccText) {
+    nsresult rv = RenderedToContentOffset(endFrame, endOffset,
+                                          &endOffset);
+    NS_ENSURE_SUCCESS(rv, rv);
+    endNode = do_QueryInterface(endContent);
+  } else {
+    nsCOMPtr<nsIContent> endParent(endContent->GetParent());
+    NS_ENSURE_STATE(endParent);
+    endOffset = endParent->IndexOf(endContent);
+    endNode = do_QueryInterface(endParent);
+  }
+  NS_ENSURE_STATE(endNode);
+
+  return nsAccUtils::ScrollSubstringTo(GetFrame(), startNode, startOffset,
+                                       endNode, endOffset, aScrollType);
+}
+
 nsresult nsHyperTextAccessible::ContentToRenderedOffset(nsIFrame *aFrame, PRInt32 aContentOffset,
                                                         PRUint32 *aRenderedOffset)
 {
   gfxSkipChars skipChars;
   gfxSkipCharsIterator iter;
   // Only get info up to original ofset, we know that will be larger than skipped offset
   nsresult rv = aFrame->GetRenderedText(nsnull, &skipChars, &iter, 0, aContentOffset);
   NS_ENSURE_SUCCESS(rv, rv);
--- a/accessible/src/html/nsHyperTextAccessible.h
+++ b/accessible/src/html/nsHyperTextAccessible.h
@@ -96,16 +96,19 @@ public:
   /**
     * Turn a DOM Node and offset into a character offset into this hypertext.
     * Will look for closest match when the DOM node does not have an accessible
     * object associated with it. Will return an offset for the end of
     * the string if the node is not found.
     *
     * @param aNode - the node to look for
     * @param aNodeOffset - the offset to look for
+    *                      if -1 just look directly for the node
+    *                      if >=0 and aNode is text, this represents a char offset
+    *                      if >=0 and aNode is not text, this represents a child node offset
     * @param aResultOffset - the character offset into the current
     *                        nsHyperTextAccessible
     * @param aFinalAccessible [optional] - returns the accessible child which
     *                                      contained the offset, if it is within
     *                                      the current nsHyperTextAccessible,
     *                                      otherwise it is set to nsnull.
     */
   nsresult DOMPointToHypertextOffset(nsIDOMNode* aNode, PRInt32 aNodeOffset,
@@ -123,41 +126,65 @@ protected:
    * @param aText, the resulting substring
    * @return success/failure code
    */
   nsresult GetTextHelper(EGetTextType aType, nsAccessibleTextBoundary aBoundaryType,
                          PRInt32 aOffset, PRInt32 *aStartOffset, PRInt32 *aEndOffset,
                          nsAString & aText);
 
   /**
-    * Used by GetPosAndText to move backward/forward from a given point by word/line/etc.
-    * @param aPresShell, the current presshell we're moving in
-    * @param aFromFrame, the starting frame we're moving from
-    * @param aFromOffset, the starting offset we're moving from
-    * @param aAmount, how much are we moving (word/line/etc.) ?
-    * @param aDirection, forward or backward?
-    * @param aNeedsStart, for word and line cases, are we basing this on the start or end?
-    * @return, the resulting offset into this hypertext
+    * Used by GetTextHelper() to move backward/forward from a given point
+    * by word/line/etc.
+    *
+    * @param  aPresShell       the current presshell we're moving in
+    * @param  aFromFrame       the starting frame we're moving from
+    * @param  aFromOffset      the starting offset we're moving from
+    * @param  aFromAccessible  the starting accessible we're moving from
+    * @param  aAmount          how much are we moving (word/line/etc.) ?
+    * @param  aDirection       forward or backward?
+    * @param  aNeedsStart      for word and line cases, are we basing this on
+    *                          the start or end?
+    * @return                  the resulting offset into this hypertext
     */
-  PRInt32 GetRelativeOffset(nsIPresShell *aPresShell, nsIFrame *aFromFrame, PRInt32 aFromOffset,
-                            nsSelectionAmount aAmount, nsDirection aDirection, PRBool aNeedsStart);
+  PRInt32 GetRelativeOffset(nsIPresShell *aPresShell, nsIFrame *aFromFrame,
+                            PRInt32 aFromOffset, nsIAccessible *aFromAccessible,
+                            nsSelectionAmount aAmount, nsDirection aDirection,
+                            PRBool aNeedsStart);
+
   /**
-    * Given a start offset and end offset, get substring information. Different info is returned depending
-    * on what optional paramters are provided.
-    * @param aStartOffset, the start offset into the hyper text. This is also an out parameter used to return
-    *                      the offset into the start frame's rendered text content (start frame is the @return)
-    * @param aEndHyperOffset, the endoffset into the hyper text. This is also an out parameter used to return
-    *                    the offset into the end frame's rendered text content
-    * @param aText (optional), return the substring's text
-    * @param aEndFrame (optional), return the end frame for this substring
-    * @param aBoundsRect (optional), return the bounds rectangle for this substring
-    * @return the start frame for this substring
+    * Provides information for substring that is defined by the given start
+    * and end offsets for this hyper text.
+    *
+    * @param  aStartOffset  [inout] the start offset into the hyper text. This
+    *                       is also an out parameter used to return the offset
+    *                       into the start frame's rendered text content
+    *                       (start frame is the @return)
+    *
+    * @param  aEndOffset    [inout] the end offset into the hyper text. This is
+    *                       also an out parameter used to return
+    *                       the offset into the end frame's rendered
+    *                       text content.
+    *
+    * @param  aText         [out, optional] return the substring's text
+    * @param  aEndFrame     [out, optional] return the end frame for this
+    *                       substring
+    * @param  aBoundsRect   [out, optional] return the bounds rectangle for this
+    *                       substring
+    * @param  aStartAcc     [out, optional] return the start accessible for this
+    *                       substring
+    * @param  aEndAcc       [out, optional] return the end accessible for this
+    *                       substring
+    * @return               the start frame for this substring
     */
-  nsIFrame* GetPosAndText(PRInt32& aStartOffset, PRInt32& aEndOffset, nsAString *aText = nsnull,
-                          nsIFrame **aEndFrame = nsnull, nsIntRect *aBoundsRect = nsnull);
+  nsIFrame* GetPosAndText(PRInt32& aStartOffset, PRInt32& aEndOffset,
+                          nsAString *aText = nsnull,
+                          nsIFrame **aEndFrame = nsnull,
+                          nsIntRect *aBoundsRect = nsnull,
+                          nsIAccessible **aStartAcc = nsnull,
+                          nsIAccessible **aEndAcc = nsnull);
 
   nsIntRect GetBoundsForString(nsIFrame *aFrame, PRUint32 aStartRenderedOffset, PRUint32 aEndRenderedOffset);
 
   // Selection helpers
   nsresult GetSelections(nsISelectionController **aSelCon, nsISelection **aDomSel);
   nsresult SetSelectionRange(PRInt32 aStartPos, PRInt32 aEndPos);
 };
 
--- a/accessible/src/msaa/CAccessibleAction.cpp
+++ b/accessible/src/msaa/CAccessibleAction.cpp
@@ -105,18 +105,20 @@ CAccessibleAction::get_description(long 
     return E_FAIL;
 
   nsAutoString description;
   PRUint8 index = static_cast<PRUint8>(aActionIndex);
   if (NS_FAILED(acc->GetActionDescription(index, description)))
     return E_FAIL;
 
   if (!description.IsVoid()) {
-    return ::SysReAllocStringLen(aDescription, description.get(),
-                                 description.Length());
+    INT result = ::SysReAllocStringLen(aDescription, description.get(),
+                                       description.Length());
+    if (!result)
+      return E_OUTOFMEMORY;
   }
 
   return S_OK;
 }
 
 STDMETHODIMP
 CAccessibleAction::get_keyBinding(long aActionIndex, long aNumMaxBinding,
                                  BSTR **aKeyBinding,
@@ -147,20 +149,20 @@ CAccessibleAction::get_keyBinding(long a
 
   *aKeyBinding = new BSTR[numBinding];
   if (!*aKeyBinding)
     return E_OUTOFMEMORY;
 
   for (PRUint32 i = 0; i < numBinding; i++) {
     nsAutoString key;
     keys->Item(i, key);
-    HRESULT hr = ::SysReAllocStringLen(aKeyBinding[i], key.get(),
+    INT result = ::SysReAllocStringLen(aKeyBinding[i], key.get(),
                                        key.Length());
-    if (FAILED(hr))
-      return hr;
+    if (!result)
+      return E_OUTOFMEMORY;
   }
 
   return S_OK;
 }
 
 STDMETHODIMP
 CAccessibleAction::get_name(long aActionIndex, BSTR *aName)
 {
@@ -170,18 +172,21 @@ CAccessibleAction::get_name(long aAction
   if (!acc)
     return E_FAIL;
 
   nsAutoString name;
   PRUint8 index = static_cast<PRUint8>(aActionIndex);
   if (NS_FAILED(acc->GetActionName(index, name)))
     return E_FAIL;
 
-  if (!name.IsVoid())
-    return ::SysReAllocStringLen(aName, name.get(), name.Length());
+  if (!name.IsVoid()) {
+    INT result = ::SysReAllocStringLen(aName, name.get(), name.Length());
+    if (!result)
+      return E_OUTOFMEMORY;
+  }
 
   return S_OK;
 }
 
 STDMETHODIMP
 CAccessibleAction::get_localizedName(long aActionIndex, BSTR *aLocalizedName)
 {
   return E_NOTIMPL;
--- a/accessible/src/msaa/CAccessibleComponent.cpp
+++ b/accessible/src/msaa/CAccessibleComponent.cpp
@@ -83,18 +83,18 @@ CAccessibleComponent::get_locationInPare
   *aX = 0;
   *aY = 0;
 
   nsCOMPtr<nsIAccessible> acc(do_QueryInterface(this));
   if (!acc)
     return E_FAIL;
 
   // If the object is not on any screen the returned position is (0,0).
-  PRUint32 states = 0, extraStates = 0;
-  nsresult rv = acc->GetFinalState(&states, &extraStates);
+  PRUint32 states = 0;
+  nsresult rv = acc->GetFinalState(&states, nsnull);
   if (NS_FAILED(rv))
     return E_FAIL;
 
   if (states & nsIAccessibleStates::STATE_INVISIBLE)
     return S_OK;
 
   PRInt32 x = 0, y = 0, width = 0, height = 0;
   rv = acc->GetBounds(&x, &y, &width, &height);
--- a/accessible/src/msaa/CAccessibleHyperlink.cpp
+++ b/accessible/src/msaa/CAccessibleHyperlink.cpp
@@ -130,18 +130,19 @@ CAccessibleHyperlink::get_anchorTarget(l
   if (NS_SUCCEEDED(rv))
     return E_FAIL;
 
   nsAutoString stringURI;
   AppendUTF8toUTF16(prePath, stringURI);
   AppendUTF8toUTF16(path, stringURI);
 
   aAnchorTarget->vt = VT_BSTR;
-  return ::SysReAllocStringLen(&aAnchorTarget->bstrVal, stringURI.get(),
-                               stringURI.Length());
+  INT result = ::SysReAllocStringLen(&aAnchorTarget->bstrVal, stringURI.get(),
+                                     stringURI.Length());
+  return result ? NS_OK : E_OUTOFMEMORY;
 }
 
 STDMETHODIMP
 CAccessibleHyperlink::get_startIndex(long *aIndex)
 {
   *aIndex = 0;
 
   nsCOMPtr<nsIAccessibleHyperLink> acc(do_QueryInterface(this));
--- a/accessible/src/msaa/CAccessibleImage.cpp
+++ b/accessible/src/msaa/CAccessibleImage.cpp
@@ -77,18 +77,19 @@ CAccessibleImage::get_description(BSTR *
   if (!acc)
     return E_FAIL;
 
   nsAutoString description;
   nsresult rv = acc->GetName(description);
   if (NS_FAILED(rv))
     return E_FAIL;
 
-  return ::SysReAllocStringLen(aDescription, description.get(),
-                               description.Length());
+  INT result = ::SysReAllocStringLen(aDescription, description.get(),
+                                     description.Length());
+  return result ? NS_OK : E_OUTOFMEMORY;
 }
 
 STDMETHODIMP
 CAccessibleImage::get_imagePosition(enum IA2CoordinateType aCoordinateType,
                                     long *aX,
                                     long *aY)
 {
   *aX = 0;
--- a/accessible/src/msaa/CAccessibleTable.cpp
+++ b/accessible/src/msaa/CAccessibleTable.cpp
@@ -154,17 +154,18 @@ CAccessibleTable::get_columnDescription(
   if (!tableAcc)
     return E_FAIL;
 
   nsAutoString descr;
   nsresult rv = tableAcc->GetColumnDescription (aColumn, descr);
   if (NS_FAILED(rv))
     return E_FAIL;
 
-  return ::SysReAllocStringLen(aDescription, descr.get(), descr.Length());
+  INT result = ::SysReAllocStringLen(aDescription, descr.get(), descr.Length());
+  return result ? NS_OK : E_OUTOFMEMORY;
 }
 
 STDMETHODIMP
 CAccessibleTable::get_columnExtentAt(long aRow, long aColumn,
                                      long *nColumnsSpanned)
 {
   *nColumnsSpanned = 0;
 
@@ -324,17 +325,18 @@ CAccessibleTable::get_rowDescription(lon
   if (!tableAcc)
     return E_FAIL;
 
   nsAutoString descr;
   nsresult rv = tableAcc->GetRowDescription (aRow, descr);
   if (NS_FAILED(rv))
     return E_FAIL;
 
-  return ::SysReAllocStringLen(aDescription, descr.get(), descr.Length());
+  INT result = ::SysReAllocStringLen(aDescription, descr.get(), descr.Length());
+  return result ? NS_OK : E_OUTOFMEMORY;
 }
 
 STDMETHODIMP
 CAccessibleTable::get_rowExtentAt(long aRow, long aColumn, long *aNRowsSpanned)
 {
   *aNRowsSpanned = 0;
 
   nsCOMPtr<nsIAccessibleTable> tableAcc(do_QueryInterface(this));
--- a/accessible/src/msaa/CAccessibleText.cpp
+++ b/accessible/src/msaa/CAccessibleText.cpp
@@ -206,17 +206,18 @@ CAccessibleText::get_text(long aStartOff
 {
   GET_NSIACCESSIBLETEXT
 
   nsAutoString text;
   nsresult rv = textAcc->GetText(aStartOffset, aEndOffset, text);
   if (NS_FAILED(rv))
     return E_FAIL;
 
-  return ::SysReAllocStringLen(aText, text.get(), text.Length());
+  INT result = ::SysReAllocStringLen(aText, text.get(), text.Length());
+  return result ? NS_OK : E_OUTOFMEMORY;
 }
 
 STDMETHODIMP
 CAccessibleText::get_textBeforeOffset(long aOffset,
                                       enum IA2TextBoundaryType aBoundaryType,
                                       long *aStartOffset, long *aEndOffset,
                                       BSTR *aText)
 {
@@ -239,17 +240,18 @@ CAccessibleText::get_textBeforeOffset(lo
   }
 
   if (NS_FAILED(rv))
     return E_FAIL;
 
   *aStartOffset = startOffset;
   *aEndOffset = endOffset;
 
-  return ::SysReAllocStringLen(aText, text.get(), text.Length());
+  INT result = ::SysReAllocStringLen(aText, text.get(), text.Length());
+  return result ? NS_OK : E_OUTOFMEMORY;
 }
 
 STDMETHODIMP
 CAccessibleText::get_textAfterOffset(long aOffset,
                                      enum IA2TextBoundaryType aBoundaryType,
                                      long *aStartOffset, long *aEndOffset,
                                      BSTR *aText)
 {
@@ -272,17 +274,18 @@ CAccessibleText::get_textAfterOffset(lon
   }
 
   if (NS_FAILED(rv))
     return E_FAIL;
 
   *aStartOffset = startOffset;
   *aEndOffset = endOffset;
 
-  return ::SysReAllocStringLen(aText, text.get(), text.Length());
+  INT result = ::SysReAllocStringLen(aText, text.get(), text.Length());
+  return result ? NS_OK : E_OUTOFMEMORY;
 }
 
 STDMETHODIMP
 CAccessibleText::get_textAtOffset(long aOffset,
                                   enum IA2TextBoundaryType aBoundaryType,
                                   long *aStartOffset, long *aEndOffset,
                                   BSTR *aText)
 {
@@ -305,17 +308,18 @@ CAccessibleText::get_textAtOffset(long a
   }
 
   if (NS_FAILED(rv))
     return E_FAIL;
 
   *aStartOffset = startOffset;
   *aEndOffset = endOffset;
 
-  return ::SysReAllocStringLen(aText, text.get(), text.Length());
+  INT result = ::SysReAllocStringLen(aText, text.get(), text.Length());
+  return result ? NS_OK : E_OUTOFMEMORY;
 }
 
 STDMETHODIMP
 CAccessibleText::removeSelection(long aSelectionIndex)
 {
   GET_NSIACCESSIBLETEXT
 
   nsresult rv = textAcc->RemoveSelection(aSelectionIndex);
@@ -355,39 +359,18 @@ CAccessibleText::get_nCharacters(long *a
 }
 
 STDMETHODIMP
 CAccessibleText::scrollSubstringTo(long aStartIndex, long aEndIndex,
                                    enum IA2ScrollType aScrollType)
 {
   GET_NSIACCESSIBLETEXT
 
-  nsCOMPtr<nsIAccessible> accessible;
-  PRInt32 startOffset = 0, endOffset = 0;
-
-  // XXX: aEndIndex isn't used.
-  textAcc->GetAttributeRange(aStartIndex, &startOffset, &endOffset,
-                             getter_AddRefs(accessible));
-  if (!accessible)
-    return E_FAIL;
-
-  nsCOMPtr<nsIWinAccessNode> winAccessNode(do_QueryInterface(accessible));
-  if (!winAccessNode)
-    return E_FAIL;
-
-  void **instancePtr = 0;
-  winAccessNode->QueryNativeInterface(IID_IAccessible2, instancePtr);
-  if (!instancePtr)
-    return E_FAIL;
-
-  IAccessible2 *pAccessible2 = static_cast<IAccessible2*>(*instancePtr);
-  HRESULT hr = pAccessible2->scrollTo(aScrollType);
-  pAccessible2->Release();
-
-  return hr;
+  nsresult rv = textAcc->ScrollSubstringTo(aStartIndex, aEndIndex, aScrollType);
+  return NS_FAILED(rv) ? E_FAIL : S_OK;
 }
 
 STDMETHODIMP
 CAccessibleText::scrollSubstringToPoint(long aStartIndex, long aEndIndex,
                                         enum IA2CoordinateType aCoordinateType,
                                         long aX, long aY)
 {
   GET_NSIACCESSIBLETEXT
@@ -441,17 +424,18 @@ CAccessibleText::GetModifiedText(PRBool 
   nsresult rv = GetModifiedText(aGetInsertedText, text,
                                 &startOffset, &endOffset);
   if (NS_FAILED(rv))
     return E_FAIL;
 
   aText->start = startOffset;
   aText->end = endOffset;
 
-  return ::SysReAllocStringLen(&(aText->text), text.get(), text.Length());
+  INT result = ::SysReAllocStringLen(&(aText->text), text.get(), text.Length());
+  return result ? NS_OK : E_OUTOFMEMORY;
 }
 
 nsAccessibleTextBoundary
 CAccessibleText::GetGeckoTextBoundary(enum IA2TextBoundaryType aBoundaryType)
 {
   switch (aBoundaryType) {
     case IA2_TEXT_BOUNDARY_CHAR:
       return nsIAccessibleText::BOUNDARY_CHAR;
--- a/accessible/src/msaa/nsAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsAccessibleWrap.cpp
@@ -493,18 +493,18 @@ STDMETHODIMP nsAccessibleWrap::get_accSt
   pvarState->vt = VT_I4;
   pvarState->lVal = 0;
 
   nsCOMPtr<nsIAccessible> xpAccessible;
   GetXPAccessibleFor(varChild, getter_AddRefs(xpAccessible));
   if (!xpAccessible)
     return E_FAIL;
 
-  PRUint32 state = 0, extraState;
-  if (NS_FAILED(xpAccessible->GetFinalState(&state, &extraState)))
+  PRUint32 state = 0;
+  if (NS_FAILED(xpAccessible->GetFinalState(&state, nsnull)))
     return E_FAIL;
 
   pvarState->lVal = state;
 
   return S_OK;
 }
 
 
--- a/accessible/src/msaa/nsApplicationAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsApplicationAccessibleWrap.cpp
@@ -76,33 +76,35 @@ nsApplicationAccessibleWrap::get_appName
 
   nsCAutoString cname;
   nsresult rv = sAppInfo->GetName(cname);
 
   if (NS_FAILED(rv))
     return E_FAIL;
 
   NS_ConvertUTF8toUTF16 name(cname);
-  return ::SysReAllocStringLen(aName, name.get(), name.Length());
+  INT result = ::SysReAllocStringLen(aName, name.get(), name.Length());
+  return result ? NS_OK : E_OUTOFMEMORY;
 }
 
 STDMETHODIMP
 nsApplicationAccessibleWrap::get_appVersion(BSTR *aVersion)
 {
   if (!sAppInfo)
     return E_FAIL;
 
   nsCAutoString cversion;
   nsresult rv = sAppInfo->GetVersion(cversion);
 
   if (NS_FAILED(rv))
     return E_FAIL;
 
   NS_ConvertUTF8toUTF16 version(cversion);
-  return ::SysReAllocStringLen(aVersion, version.get(), version.Length());
+  INT result = ::SysReAllocStringLen(aVersion, version.get(), version.Length());
+  return result ? NS_OK : E_OUTOFMEMORY;
 }
 
 STDMETHODIMP
 nsApplicationAccessibleWrap::get_toolkitName(BSTR *aName)
 {
   return ::SysReAllocString(aName, L"Gecko");
 }
 
@@ -114,17 +116,18 @@ nsApplicationAccessibleWrap::get_toolkit
 
   nsCAutoString cversion;
   nsresult rv = sAppInfo->GetPlatformVersion(cversion);
 
   if (NS_FAILED(rv))
     return E_FAIL;
 
   NS_ConvertUTF8toUTF16 version(cversion);
-  return ::SysReAllocStringLen(aVersion, version.get(), version.Length());
+  INT result = ::SysReAllocStringLen(aVersion, version.get(), version.Length());
+  return result ? NS_OK : E_OUTOFMEMORY;
 }
 
 // nsApplicationAccessibleWrap
 
 void
 nsApplicationAccessibleWrap::PreCreate()
 {
   nsresult rv = CallGetService("@mozilla.org/xre/app-info;1", &sAppInfo);
--- a/accessible/src/msaa/nsHyperTextAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsHyperTextAccessibleWrap.cpp
@@ -84,33 +84,29 @@ nsHyperTextAccessibleWrap::GetModifiedTe
                                            PRUint32 *aEndOffset)
 {
   aText.Truncate();
   *aStartOffset = 0;
   *aEndOffset = 0;
 
   if (!gTextEvent)
     return NS_OK;
+    
+  PRBool isInserted;
+  gTextEvent->IsInserted(&isInserted);
+  if (aGetInsertedText != isInserted)
+    return NS_OK;
 
   nsCOMPtr<nsIAccessible> targetAcc;
   gTextEvent->GetAccessible(getter_AddRefs(targetAcc));
   if (targetAcc != this)
     return NS_OK;
 
-  PRBool isInserted;
-  gTextEvent->IsInserted(&isInserted);
-
-  if (aGetInsertedText != isInserted)
-    return NS_OK;
-
-  nsAutoString text;
   PRInt32 offset;
   PRUint32 length;
 
   gTextEvent->GetStart(&offset);
   gTextEvent->GetLength(&length);
-  GetText(offset, offset + length, aText);
   *aStartOffset = offset;
   *aEndOffset = offset + length;
-
-  return NS_OK;
+  return gTextEvent->GetModifiedText(aText);
 }
 
--- a/accessible/src/msaa/nsTextAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsTextAccessibleWrap.cpp
@@ -34,31 +34,25 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 // NOTE: alphabetically ordered
 #include "nsTextAccessibleWrap.h"
 #include "ISimpleDOMText_i.c"
-#include "nsContentCID.h"
 #include "nsIAccessibleDocument.h"
-#include "nsIDOMRange.h"
 #include "nsIFontMetrics.h"
 #include "nsIFrame.h"
 #include "nsPresContext.h"
 #include "nsIPresShell.h"
 #include "nsIRenderingContext.h"
-#include "nsISelection.h"
-#include "nsISelectionController.h"
 #include "nsIWidget.h"
 #include "nsIComponentManager.h"
 
-static NS_DEFINE_IID(kRangeCID, NS_RANGE_CID);
-
 // --------------------------------------------------------
 // nsTextAccessibleWrap Accessible
 // --------------------------------------------------------
 
 nsTextAccessibleWrap::nsTextAccessibleWrap(nsIDOMNode* aDOMNode, nsIWeakReference* aShell):
 nsTextAccessible(aDOMNode, aShell)
 { 
 }
@@ -153,51 +147,24 @@ STDMETHODIMP nsTextAccessibleWrap::get_u
                                     aX, aY, aWidth, aHeight))) {
     return NS_ERROR_FAILURE;
   }
 
   return S_OK;
 }
 
 
-STDMETHODIMP nsTextAccessibleWrap::scrollToSubstring( 
+STDMETHODIMP nsTextAccessibleWrap::scrollToSubstring(
     /* [in] */ unsigned int aStartIndex,
     /* [in] */ unsigned int aEndIndex)
 {
-  nsCOMPtr<nsIPresShell> presShell(GetPresShell());
-  nsIFrame *frame = GetFrame();
-
-  if (!frame || !presShell) {
-    return E_FAIL;  // This accessible has been shut down
-  }
-
-  nsPresContext *presContext = presShell->GetPresContext();
-  nsCOMPtr<nsIDOMRange> scrollToRange = do_CreateInstance(kRangeCID);
-  nsCOMPtr<nsISelectionController> selCon;
-  frame->GetSelectionController(presContext, getter_AddRefs(selCon));
-  if (!presContext || !scrollToRange || !selCon) {
-    return E_FAIL;
-  }
-
-  scrollToRange->SetStart(mDOMNode, aStartIndex);
-  scrollToRange->SetEnd(mDOMNode, aEndIndex);
-  nsCOMPtr<nsISelection> domSel;
-  selCon->GetSelection(nsISelectionController::SELECTION_ACCESSIBILITY, 
-                       getter_AddRefs(domSel));
-  if (domSel) {
-    domSel->RemoveAllRanges();
-    domSel->AddRange(scrollToRange);
-
-    selCon->ScrollSelectionIntoView(nsISelectionController::SELECTION_ACCESSIBILITY, 
-      nsISelectionController::SELECTION_ANCHOR_REGION, PR_TRUE);
-
-    domSel->CollapseToStart();
-  }
-
-  return S_OK;
+  nsresult rv = nsAccUtils::ScrollSubstringTo(GetFrame(), mDOMNode, aStartIndex,
+                                              mDOMNode, aEndIndex,
+                                              nsIAccessibleScrollType::SCROLL_TYPE_ANYWHERE);
+  return NS_FAILED(rv) ? E_FAIL : S_OK;
 }
 
 nsIFrame* nsTextAccessibleWrap::GetPointFromOffset(nsIFrame *aContainingFrame, 
                                                    PRInt32 aOffset, 
                                                    PRBool aPreferNext, 
                                                    nsPoint& aOutPoint)
 {
   nsIFrame *textFrame = nsnull;
--- a/accessible/src/xul/nsXULMenuAccessible.cpp
+++ b/accessible/src/xul/nsXULMenuAccessible.cpp
@@ -386,23 +386,28 @@ NS_IMETHODIMP nsXULMenuitemAccessible::G
     return NS_ERROR_FAILURE;
   }
   element->GetAttribute(NS_LITERAL_STRING("description"), aDescription);
 
   return NS_OK;
 }
 
 //return menu accesskey: N or Alt+F
-NS_IMETHODIMP nsXULMenuitemAccessible::GetKeyboardShortcut(nsAString& _retval)
+NS_IMETHODIMP
+nsXULMenuitemAccessible::GetKeyboardShortcut(nsAString& aAccessKey)
 {
+  aAccessKey.Truncate();
+
   static PRInt32 gMenuAccesskeyModifier = -1;  // magic value of -1 indicates unitialized state
 
   nsCOMPtr<nsIDOMElement> elt(do_QueryInterface(mDOMNode));
   if (elt) {
     nsAutoString accesskey;
+    // We do not use nsAccUtils::GetAccesskeyFor() because accesskeys for
+    // menu are't registered by nsIEventStateManager.
     elt->GetAttribute(NS_LITERAL_STRING("accesskey"), accesskey);
     if (accesskey.IsEmpty())
       return NS_OK;
 
     nsCOMPtr<nsIAccessible> parentAccessible(GetParent());
     if (parentAccessible) {
       PRUint32 role;
       parentAccessible->GetRole(&role);
@@ -418,21 +423,21 @@ NS_IMETHODIMP nsXULMenuitemAccessible::G
         }
         nsAutoString propertyKey;
         switch (gMenuAccesskeyModifier) {
           case nsIDOMKeyEvent::DOM_VK_CONTROL: propertyKey.AssignLiteral("VK_CONTROL"); break;
           case nsIDOMKeyEvent::DOM_VK_ALT: propertyKey.AssignLiteral("VK_ALT"); break;
           case nsIDOMKeyEvent::DOM_VK_META: propertyKey.AssignLiteral("VK_META"); break;
         }
         if (!propertyKey.IsEmpty())
-          nsAccessible::GetFullKeyName(propertyKey, accesskey, _retval);
+          nsAccessible::GetFullKeyName(propertyKey, accesskey, aAccessKey);
       }
     }
-    if (_retval.IsEmpty())
-      _retval = accesskey;
+    if (aAccessKey.IsEmpty())
+      aAccessKey = accesskey;
     return NS_OK;
   }
   return NS_ERROR_FAILURE;
 }
 
 //return menu shortcut: Ctrl+F or Ctrl+Shift+L
 NS_IMETHODIMP
 nsXULMenuitemAccessible::GetDefaultKeyBinding(nsAString& aKeyBinding)
@@ -607,17 +612,18 @@ nsXULMenupopupAccessible::GetState(PRUin
       accessNode->GetDOMNode(getter_AddRefs(parentNode));
     element = do_QueryInterface(parentNode);
     if (element)
       element->HasAttribute(NS_LITERAL_STRING("open"), &isActive);
   }
 
   if (!isActive)
     *aState |= (nsIAccessibleStates::STATE_OFFSCREEN |
-                nsIAccessibleStates::STATE_INVISIBLE);
+                nsIAccessibleStates::STATE_INVISIBLE |
+                nsIAccessibleStates::STATE_COLLAPSED);
 
   return NS_OK;
 }
 
 already_AddRefed<nsIDOMNode>
 nsXULMenupopupAccessible::FindInNodeList(nsIDOMNodeList *aNodeList, 
                                          nsIAtom *aAtom, PRUint32 aNameSpaceID)
 {
--- a/allmakefiles.sh
+++ b/allmakefiles.sh
@@ -31,1334 +31,60 @@
 # 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 *****
 
-# allmakefiles.sh - List of all makefiles. 
+# allmakefiles.sh - List of all makefiles.
 #   Appends the list of makefiles to the variable, MAKEFILES.
 #   There is no need to rerun autoconf after adding makefiles.
 #   You only need to run configure.
-#
-#   Please keep the modules in this file in sync with those in
-#   mozilla/build/unix/modules.mk
-#
 
 MAKEFILES=""
 
 # add_makefiles - Shell function to add makefiles to MAKEFILES
 add_makefiles() {
-    MAKEFILES="$MAKEFILES $*"
+  MAKEFILES="$MAKEFILES $*"
 }
 
 if [ "$srcdir" = "" ]; then
-    srcdir=.
+  srcdir=.
 fi
 
 #
 # Common makefiles used by everyone
 #
 add_makefiles "
 Makefile
 build/Makefile
 build/unix/Makefile
 config/Makefile
 config/autoconf.mk
 config/mkdepend/Makefile
 config/doxygen.cfg
-"
-
-if [ "$MOZ_COMPOSER" ]; then
-MAKEFILES_composer="
-editor/composer/Makefile
-editor/ui/Makefile
-editor/ui/locales/Makefile
-"
-fi
-
-MAKEFILES_db="
-db/Makefile
-db/mdb/Makefile
-db/mdb/public/Makefile
-db/mork/Makefile
-db/mork/build/Makefile
-db/mork/src/Makefile
-"
-
-MAKEFILES_storage="
-db/sqlite3/src/Makefile
-db/morkreader/Makefile
-storage/Makefile
-storage/public/Makefile
-storage/src/Makefile
-storage/build/Makefile
-storage/test/Makefile
-"
-
-MAKEFILES_dom="
-dom/Makefile
-dom/public/Makefile
-dom/public/base/Makefile
-dom/public/coreEvents/Makefile
-dom/public/idl/Makefile
-dom/public/idl/base/Makefile
-dom/public/idl/canvas/Makefile
-dom/public/idl/core/Makefile
-dom/public/idl/css/Makefile
-dom/public/idl/events/Makefile
-dom/public/idl/html/Makefile
-dom/public/idl/range/Makefile
-dom/public/idl/stylesheets/Makefile
-dom/public/idl/views/Makefile
-dom/public/idl/xbl/Makefile
-dom/public/idl/xpath/Makefile
-dom/public/idl/xul/Makefile
-dom/src/Makefile
-dom/src/base/Makefile
-dom/src/events/Makefile
-dom/src/jsurl/Makefile
-dom/locales/Makefile
-"
-
-MAKEFILES_editor="
-editor/Makefile
-editor/public/Makefile
-editor/idl/Makefile
-editor/txmgr/Makefile
-editor/txmgr/idl/Makefile
-editor/txmgr/public/Makefile
-editor/txmgr/src/Makefile
-editor/txmgr/tests/Makefile
-editor/txtsvc/Makefile
-editor/txtsvc/public/Makefile
-editor/txtsvc/src/Makefile
-"
-
-MAKEFILES_expat="
-parser/expat/Makefile
-parser/expat/lib/Makefile
-"
-
-MAKEFILES_extensions="
 extensions/Makefile
 "
 
-MAKEFILES_gfx="
-gfx/Makefile
-gfx/idl/Makefile
-gfx/public/Makefile
-gfx/src/Makefile
-gfx/src/beos/Makefile
-gfx/src/psshared/Makefile
-gfx/src/photon/Makefile
-gfx/src/mac/Makefile
-gfx/src/os2/Makefile
-gfx/src/windows/Makefile
-gfx/src/thebes/Makefile
-gfx/tests/Makefile
-"
-
-if [ "$MOZ_TREE_CAIRO" ] ; then
-MAKEFILES_gfx="$MAKEFILES_gfx
-gfx/cairo/Makefile
-gfx/cairo/libpixman/src/Makefile
-gfx/cairo/cairo/src/Makefile
-gfx/cairo/cairo/src/cairo-features.h
-gfx/cairo/glitz/src/Makefile
-gfx/cairo/glitz/src/glx/Makefile
-gfx/cairo/glitz/src/wgl/Makefile
-"
-fi
-
-if [ ! "$MOZ_NATIVE_LCMS" ] ; then
-MAKEFILES_gfx="$MAKEFILES_gfx
-modules/lcms/Makefile
-modules/lcms/include/Makefile
-modules/lcms/src/Makefile
-"
-fi
-
-MAKEFILES_htmlparser="
-parser/htmlparser/Makefile
-parser/htmlparser/robot/Makefile
-parser/htmlparser/robot/test/Makefile
-parser/htmlparser/public/Makefile
-parser/htmlparser/src/Makefile
-parser/htmlparser/tests/Makefile
-parser/htmlparser/tests/grabpage/Makefile
-parser/htmlparser/tests/logparse/Makefile
-parser/htmlparser/tests/html/Makefile
-parser/htmlparser/tests/outsinks/Makefile
-"
-
-MAKEFILES_intl="
-intl/Makefile
-intl/chardet/Makefile
-intl/chardet/public/Makefile
-intl/chardet/src/Makefile
-intl/uconv/Makefile
-intl/uconv/idl/Makefile
-intl/uconv/public/Makefile
-intl/uconv/src/Makefile
-intl/uconv/tests/Makefile
-intl/uconv/ucvja/Makefile
-intl/uconv/ucvlatin/Makefile
-intl/uconv/ucvcn/Makefile
-intl/uconv/ucvtw/Makefile
-intl/uconv/ucvtw2/Makefile
-intl/uconv/ucvko/Makefile
-intl/uconv/ucvibm/Makefile
-intl/uconv/native/Makefile
-intl/locale/Makefile
-intl/locale/public/Makefile
-intl/locale/idl/Makefile
-intl/locale/src/Makefile
-intl/locale/src/unix/Makefile
-intl/locale/src/os2/Makefile
-intl/locale/src/windows/Makefile
-intl/locale/tests/Makefile
-intl/lwbrk/Makefile
-intl/lwbrk/src/Makefile
-intl/lwbrk/public/Makefile
-intl/lwbrk/tests/Makefile
-intl/unicharutil/Makefile
-intl/unicharutil/util/Makefile
-intl/unicharutil/util/internal/Makefile
-intl/unicharutil/idl/Makefile
-intl/unicharutil/src/Makefile
-intl/unicharutil/public/Makefile
-intl/unicharutil/tables/Makefile
-intl/unicharutil/tests/Makefile
-intl/unicharutil/tools/Makefile
-intl/strres/Makefile
-intl/strres/public/Makefile
-intl/strres/src/Makefile
-intl/strres/tests/Makefile
-"
-
-if [ "$SUNCTL" ] ; then
-MAKEFILES_intl="$MAKEFILES_intl
-intl/ctl/Makefile
-intl/ctl/public/Makefile
-intl/ctl/src/Makefile
-intl/ctl/src/pangoLite/Makefile
-intl/ctl/src/thaiShaper/Makefile
-intl/ctl/src/hindiShaper/Makefile
-"
-fi
-
-if [ "$MOZ_UNIVERSALCHARDET" ] ; then
-MAKEFILES_intl="$MAKEFILES_intl
-extensions/universalchardet/Makefile
-extensions/universalchardet/src/Makefile
-extensions/universalchardet/src/base/Makefile
-extensions/universalchardet/src/xpcom/Makefile
-extensions/universalchardet/tests/Makefile
-"
-fi
-
-MAKEFILES_js="
-js/src/Makefile
-js/src/fdlibm/Makefile
-"
-
-MAKEFILES_liveconnect="
-js/src/liveconnect/Makefile
-js/src/liveconnect/classes/Makefile
-"
-
-MAKEFILES_xpconnect="
-js/src/xpconnect/Makefile
-js/src/xpconnect/public/Makefile
-js/src/xpconnect/idl/Makefile
-js/src/xpconnect/shell/Makefile
-js/src/xpconnect/src/Makefile
-js/src/xpconnect/loader/Makefile
-js/src/xpconnect/tests/Makefile
-js/src/xpconnect/tests/components/Makefile
-js/src/xpconnect/tests/idl/Makefile
-js/src/xpconnect/shell/Makefile
-js/src/xpconnect/tools/Makefile
-js/src/xpconnect/tools/idl/Makefile
-js/src/xpconnect/tools/idl/Makefile
-"
-
-MAKEFILES_jsdebugger="
-js/jsd/Makefile
-js/jsd/idl/Makefile
-"
-
-MAKEFILES_content="
-content/Makefile
-content/base/Makefile
-content/base/public/Makefile
-content/base/src/Makefile
-content/canvas/Makefile
-content/canvas/public/Makefile
-content/canvas/src/Makefile
-content/events/Makefile
-content/events/public/Makefile
-content/events/src/Makefile
-content/html/Makefile
-content/html/content/Makefile
-content/html/content/public/Makefile
-content/html/content/src/Makefile
-content/html/document/Makefile
-content/html/document/public/Makefile
-content/html/document/src/Makefile
-content/xml/Makefile
-content/xml/content/Makefile
-content/xml/content/src/Makefile
-content/xml/document/Makefile
-content/xml/document/public/Makefile
-content/xml/document/src/Makefile
-content/xul/Makefile
-content/xul/content/Makefile
-content/xul/content/src/Makefile
-content/xul/document/Makefile
-content/xul/document/public/Makefile
-content/xul/document/src/Makefile
-content/xul/templates/public/Makefile
-content/xul/templates/src/Makefile
-content/xbl/Makefile
-content/xbl/public/Makefile
-content/xbl/src/Makefile
-content/xbl/builtin/Makefile
-content/xslt/Makefile
-content/xslt/public/Makefile
-content/xslt/src/Makefile
-content/xslt/src/base/Makefile
-content/xslt/src/xml/Makefile
-content/xslt/src/xpath/Makefile
-content/xslt/src/xslt/Makefile
-content/xslt/src/main/Makefile
-"
-
-MAKEFILES_layout="
-layout/Makefile
-layout/base/Makefile
-layout/base/tests/Makefile
-layout/build/Makefile
-layout/forms/Makefile
-layout/html/tests/Makefile
-layout/style/Makefile
-layout/printing/Makefile
-layout/tools/Makefile
-layout/xul/Makefile
-layout/xul/base/Makefile
-layout/xul/base/public/Makefile
-layout/xul/base/src/Makefile
-layout/xul/base/src/tree/Makefile
-layout/xul/base/src/tree/src/Makefile
-layout/xul/base/src/tree/public/Makefile
-"
-
-MAKEFILES_libimg="
-modules/libimg/Makefile
-"
-
-MAKEFILES_libjar="
-modules/libjar/Makefile
-modules/libjar/standalone/Makefile
-modules/libjar/test/Makefile
-"
-
-MAKEFILES_libreg="
-modules/libreg/Makefile
-modules/libreg/include/Makefile
-modules/libreg/src/Makefile
-modules/libreg/standalone/Makefile
-"
-
-MAKEFILES_libpref="
-modules/libpref/Makefile
-modules/libpref/public/Makefile
-modules/libpref/src/Makefile
-"
-
-MAKEFILES_libutil="
-modules/libutil/Makefile
-modules/libutil/public/Makefile
-modules/libutil/src/Makefile
-"
-
-MAKEFILES_oji="
-modules/oji/Makefile
-modules/oji/public/Makefile
-modules/oji/src/Makefile
-plugin/oji/JEP/Makefile
-"
-
-MAKEFILES_plugin="
-modules/plugin/Makefile
-modules/plugin/base/src/Makefile
-modules/plugin/base/public/Makefile
-modules/plugin/samples/simple/Makefile
-modules/plugin/samples/SanePlugin/Makefile
-modules/plugin/samples/default/unix/Makefile
-modules/plugin/tools/sdk/Makefile
-modules/plugin/tools/sdk/samples/Makefile
-modules/plugin/tools/sdk/samples/common/Makefile
-modules/plugin/tools/sdk/samples/basic/windows/Makefile
-modules/plugin/tools/sdk/samples/scriptable/windows/Makefile
-modules/plugin/tools/sdk/samples/simple/Makefile
-modules/plugin/tools/sdk/samples/winless/windows/Makefile
-"
-
-MAKEFILES_netwerk="
-netwerk/Makefile
-netwerk/base/Makefile
-netwerk/base/public/Makefile
-netwerk/base/src/Makefile
-netwerk/build/Makefile
-netwerk/cache/Makefile
-netwerk/cache/public/Makefile
-netwerk/cache/src/Makefile
-netwerk/cookie/Makefile
-netwerk/cookie/public/Makefile
-netwerk/cookie/src/Makefile
-netwerk/dns/Makefile
-netwerk/dns/public/Makefile
-netwerk/dns/src/Makefile
-netwerk/protocol/Makefile
-netwerk/protocol/about/Makefile
-netwerk/protocol/about/public/Makefile
-netwerk/protocol/about/src/Makefile
-netwerk/protocol/data/Makefile
-netwerk/protocol/data/src/Makefile
-netwerk/protocol/file/Makefile
-netwerk/protocol/file/public/Makefile
-netwerk/protocol/file/src/Makefile
-netwerk/protocol/ftp/Makefile
-netwerk/protocol/ftp/public/Makefile
-netwerk/protocol/ftp/src/Makefile
-netwerk/protocol/gopher/Makefile
-netwerk/protocol/gopher/src/Makefile
-netwerk/protocol/http/Makefile
-netwerk/protocol/http/public/Makefile
-netwerk/protocol/http/src/Makefile
-netwerk/protocol/res/Makefile
-netwerk/protocol/res/public/Makefile
-netwerk/protocol/res/src/Makefile
-netwerk/mime/Makefile
-netwerk/mime/public/Makefile
-netwerk/mime/src/Makefile
-netwerk/socket/Makefile
-netwerk/socket/base/Makefile
-netwerk/streamconv/Makefile
-netwerk/streamconv/converters/Makefile
-netwerk/streamconv/public/Makefile
-netwerk/streamconv/src/Makefile
-netwerk/streamconv/test/Makefile
-netwerk/test/Makefile
-netwerk/testserver/Makefile
-netwerk/resources/Makefile
-netwerk/locales/Makefile
-netwerk/system/Makefile
-netwerk/system/win32/Makefile
-uriloader/exthandler/Makefile
-intl/strres/public/Makefile
-intl/locale/idl/Makefile
-$MAKEFILES_js
-modules/libpref/public/Makefile
-"
-
-if [ "$MOZ_AUTH_EXTENSION" ]; then
-    MAKEFILES_netwerk="$MAKEFILES_netwerk
-        extensions/auth/Makefile
-    "
+#
+# Application-specific makefiles
+#
+if test -f "${srcdir}/${MOZ_BUILD_APP}/makefiles.sh"; then
+  . "${srcdir}/${MOZ_BUILD_APP}/makefiles.sh"
 fi
 
-MAKEFILES_uriloader="
-uriloader/Makefile
-uriloader/base/Makefile
-uriloader/exthandler/Makefile
-"
-
-MAKEFILES_profile="
-profile/Makefile
-profile/public/Makefile
-profile/dirserviceprovider/Makefile
-profile/dirserviceprovider/public/Makefile
-profile/dirserviceprovider/src/Makefile
-"
-
-MAKEFILES_rdf="
-rdf/Makefile
-rdf/base/Makefile
-rdf/base/idl/Makefile
-rdf/base/public/Makefile
-rdf/base/src/Makefile
-rdf/util/Makefile
-rdf/util/public/Makefile
-rdf/util/src/Makefile
-rdf/util/src/internal/Makefile
-rdf/build/Makefile
-rdf/datasource/Makefile
-rdf/datasource/public/Makefile
-rdf/datasource/src/Makefile
-rdf/tests/Makefile
-rdf/tests/rdfcat/Makefile
-rdf/tests/rdfpoll/Makefile
-"
-
-MAKEFILES_sun_java="
-sun-java/Makefile
-sun-java/stubs/Makefile
-sun-java/stubs/include/Makefile
-sun-java/stubs/jri/Makefile
-"
-
-MAKEFILES_caps="
-caps/Makefile
-caps/idl/Makefile
-caps/include/Makefile
-caps/src/Makefile
-"
-
-MAKEFILES_chrome="
-chrome/Makefile
-chrome/public/Makefile
-chrome/src/Makefile
-embedding/minimo/chromelite/Makefile
-rdf/chrome/Makefile
-rdf/chrome/public/Makefile
-rdf/chrome/build/Makefile
-rdf/chrome/src/Makefile
-rdf/chrome/tools/Makefile
-rdf/chrome/tools/chromereg/Makefile
-"
-
-
-MAKEFILES_view="
-view/Makefile
-view/public/Makefile
-view/src/Makefile
-"
-
-MAKEFILES_docshell="
-docshell/Makefile
-docshell/base/Makefile
-docshell/shistory/Makefile
-docshell/shistory/public/Makefile
-docshell/shistory/src/Makefile
-docshell/build/Makefile
-"
-
-MAKEFILES_webshell="
-webshell/Makefile
-webshell/public/Makefile
-"
-
-MAKEFILES_widget="
-widget/Makefile
-widget/public/Makefile
-widget/src/Makefile
-widget/src/beos/Makefile
-widget/src/build/Makefile
-widget/src/gtkxtbin/Makefile
-widget/src/photon/Makefile
-widget/src/cocoa/Makefile
-widget/src/os2/Makefile
-widget/src/windows/Makefile
-widget/src/xpwidgets/Makefile
-widget/src/support/Makefile
-"
-
-MAKEFILES_xpcom="
-xpcom/string/Makefile
-xpcom/string/public/Makefile
-xpcom/string/src/Makefile
-xpcom/Makefile
-xpcom/base/Makefile
-xpcom/build/Makefile
-xpcom/components/Makefile
-xpcom/ds/Makefile
-xpcom/glue/Makefile
-xpcom/glue/standalone/Makefile
-xpcom/io/Makefile
-xpcom/typelib/Makefile
-xpcom/reflect/Makefile
-xpcom/typelib/xpt/Makefile
-xpcom/typelib/xpt/public/Makefile
-xpcom/typelib/xpt/src/Makefile
-xpcom/typelib/xpt/tests/Makefile
-xpcom/typelib/xpt/tools/Makefile
-xpcom/typelib/xpidl/Makefile
-xpcom/reflect/xptcall/Makefile
-xpcom/reflect/xptcall/public/Makefile
-xpcom/reflect/xptcall/src/Makefile
-xpcom/reflect/xptcall/src/md/Makefile
-xpcom/reflect/xptcall/src/md/os2/Makefile
-xpcom/reflect/xptcall/src/md/test/Makefile
-xpcom/reflect/xptcall/src/md/unix/Makefile
-xpcom/reflect/xptcall/src/md/win32/Makefile
-xpcom/reflect/xptcall/tests/Makefile
-xpcom/reflect/xptinfo/Makefile
-xpcom/reflect/xptinfo/public/Makefile
-xpcom/reflect/xptinfo/src/Makefile
-xpcom/reflect/xptinfo/tests/Makefile
-xpcom/proxy/Makefile
-xpcom/proxy/public/Makefile
-xpcom/proxy/src/Makefile
-xpcom/proxy/tests/Makefile
-xpcom/sample/Makefile
-xpcom/threads/Makefile
-xpcom/tools/Makefile
-xpcom/tools/registry/Makefile
-xpcom/stub/Makefile
-xpcom/windbgdlg/Makefile
-xpcom/system/Makefile
-$MAKEFILES_libreg
-$MAKEFILES_libjar
-intl/unicharutil/public/Makefile
-intl/uconv/public/Makefile
-netwerk/base/public/Makefile
-netwerk/build/Makefile
-"
-MAKEFILES_xpcom_obsolete="
-xpcom/obsolete/Makefile
-xpcom/obsolete/component/Makefile
-"
-
-MAKEFILES_xpcom_tests="
-xpcom/tests/Makefile
-xpcom/tests/dynamic/Makefile
-xpcom/tests/services/Makefile
-xpcom/tests/windows/Makefile
-"
-
-MAKEFILES_string="$MAKEFILES_xpcom"
-
-MAKEFILES_xpinstall="
-xpinstall/Makefile
-xpinstall/public/Makefile
-xpinstall/res/Makefile
-xpinstall/src/Makefile
-xpinstall/stub/Makefile
-"
-
-MAKEFILES_xpfe="
-widget/src/xremoteclient/Makefile
-toolkit/components/Makefile
-toolkit/components/remote/Makefile
-xpfe/Makefile
-xpfe/browser/Makefile
-xpfe/browser/public/Makefile
-xpfe/browser/src/Makefile
-xpfe/components/Makefile
-xpfe/components/bookmarks/Makefile
-xpfe/components/bookmarks/public/Makefile
-xpfe/components/bookmarks/src/Makefile
-xpfe/components/directory/Makefile
-xpfe/components/download-manager/Makefile
-xpfe/components/download-manager/src/Makefile
-xpfe/components/download-manager/public/Makefile
-xpfe/components/download-manager/resources/Makefile
-xpfe/components/extensions/Makefile
-xpfe/components/extensions/src/Makefile
-xpfe/components/extensions/public/Makefile
-xpfe/components/find/Makefile
-xpfe/components/find/public/Makefile
-xpfe/components/find/src/Makefile
-xpfe/components/filepicker/Makefile
-xpfe/components/filepicker/public/Makefile
-xpfe/components/filepicker/src/Makefile
-xpfe/components/history/Makefile
-xpfe/components/history/src/Makefile
-xpfe/components/history/public/Makefile
-xpfe/components/intl/Makefile
-xpfe/components/related/Makefile
-xpfe/components/related/src/Makefile
-xpfe/components/related/public/Makefile
-xpfe/components/search/Makefile
-xpfe/components/search/public/Makefile
-xpfe/components/search/src/Makefile
-xpfe/components/sidebar/Makefile
-xpfe/components/sidebar/src/Makefile
-xpfe/components/startup/Makefile
-xpfe/components/startup/public/Makefile
-xpfe/components/startup/src/Makefile
-xpfe/components/autocomplete/Makefile
-xpfe/components/autocomplete/public/Makefile
-xpfe/components/autocomplete/src/Makefile
-xpfe/components/updates/Makefile
-xpfe/components/updates/src/Makefile
-xpfe/components/winhooks/Makefile
-xpfe/components/windowds/Makefile
-xpfe/components/alerts/Makefile
-xpfe/components/alerts/public/Makefile
-xpfe/components/alerts/src/Makefile
-xpfe/components/console/Makefile
-xpfe/components/resetPref/Makefile
-xpfe/components/build/Makefile
-xpfe/components/xremote/Makefile
-xpfe/components/xremote/public/Makefile
-xpfe/components/xremote/src/Makefile
-xpfe/appshell/Makefile
-xpfe/appshell/src/Makefile
-xpfe/appshell/public/Makefile
-xpfe/bootstrap/appleevents/Makefile
-xpfe/browser/Makefile
-xpfe/browser/src/Makefile
-xpfe/global/Makefile
-xpfe/global/buildconfig.html
-xpfe/global/resources/Makefile
-xpfe/global/resources/content/Makefile
-xpfe/global/resources/content/os2/Makefile
-xpfe/global/resources/content/unix/Makefile
-xpfe/global/resources/locale/Makefile
-xpfe/global/resources/locale/en-US/Makefile
-xpfe/global/resources/locale/en-US/mac/Makefile
-xpfe/global/resources/locale/en-US/os2/Makefile
-xpfe/global/resources/locale/en-US/unix/Makefile
-xpfe/global/resources/locale/en-US/win/Makefile
-xpfe/communicator/Makefile
-extensions/spellcheck/Makefile
-extensions/spellcheck/hunspell/Makefile
-extensions/spellcheck/idl/Makefile
-extensions/spellcheck/locales/Makefile
-extensions/spellcheck/src/Makefile
-"
-
-MAKEFILES_embedding="
-embedding/Makefile
-embedding/base/Makefile
-embedding/browser/Makefile
-embedding/browser/activex/src/Makefile
-embedding/browser/activex/src/control/Makefile
-embedding/browser/activex/src/control_kicker/Makefile
-embedding/browser/build/Makefile
-embedding/browser/chrome/Makefile
-embedding/browser/webBrowser/Makefile
-embedding/browser/gtk/Makefile
-embedding/browser/gtk/src/Makefile
-embedding/browser/gtk/tests/Makefile
-embedding/browser/photon/Makefile
-embedding/browser/photon/src/Makefile
-embedding/browser/photon/tests/Makefile
-embedding/browser/cocoa/Makefile
-embedding/components/Makefile
-embedding/components/build/Makefile
-embedding/components/windowwatcher/Makefile
-embedding/components/windowwatcher/public/Makefile
-embedding/components/windowwatcher/src/Makefile
-embedding/components/ui/Makefile
-embedding/components/ui/helperAppDlg/Makefile
-embedding/components/ui/progressDlg/Makefile
-embedding/config/Makefile
-embedding/tests/Makefile
-embedding/tests/cocoaEmbed/Makefile
-embedding/tests/winEmbed/Makefile
-"
-
-MAKEFILES_minimo="
-minimo/Makefile
-minimo/base/Makefile
-minimo/base/wince/Makefile
-minimo/components/Makefile
-minimo/components/phone/Makefile
-minimo/components/softkb/Makefile
-minimo/components/ssr/Makefile
-minimo/customization/Makefile
-minimo/chrome/Makefile
-"
-
-MAKEFILES_psm2="
-security/manager/Makefile
-security/manager/boot/Makefile
-security/manager/boot/src/Makefile
-security/manager/boot/public/Makefile
-security/manager/ssl/Makefile
-security/manager/ssl/src/Makefile
-security/manager/ssl/resources/Makefile
-security/manager/ssl/public/Makefile
-security/manager/pki/Makefile
-security/manager/pki/resources/Makefile
-security/manager/pki/src/Makefile
-security/manager/pki/public/Makefile
-security/manager/locales/Makefile
-netwerk/protocol/http/public/Makefile
-netwerk/build/Makefile
-netwerk/base/public/Makefile
-netwerk/socket/base/Makefile
-uriloader/base/Makefile
-intl/locale/idl/Makefile
-intl/strres/public/Makefile
-dom/public/Makefile
-dom/public/base/Makefile
-rdf/base/idl/Makefile
-xpfe/appshell/public/Makefile
-caps/idl/Makefile
-gfx/public/Makefile
-gfx/idl/Makefile
-widget/public/Makefile
-modules/libpref/public/Makefile
-content/base/public/Makefile
-intl/locale/public/Makefile
-"
-
-MAKEFILES_xulrunner="
-xulrunner/Makefile
-xulrunner/app/Makefile
-xulrunner/app/profile/Makefile
-xulrunner/app/profile/chrome/Makefile
-xulrunner/app/profile/extensions/Makefile
-xulrunner/installer/Makefile
-xulrunner/installer/mac/Makefile
-"
-
-MAKEFILES_xulapp="
-toolkit/Makefile
-toolkit/library/Makefile
-toolkit/crashreporter/Makefile
-toolkit/crashreporter/client/Makefile
-toolkit/crashreporter/google-breakpad/src/client/Makefile
-toolkit/crashreporter/google-breakpad/src/client/mac/handler/Makefile
-toolkit/crashreporter/google-breakpad/src/client/windows/Makefile
-toolkit/crashreporter/google-breakpad/src/client/windows/handler/Makefile
-toolkit/crashreporter/google-breakpad/src/client/windows/sender/Makefile
-toolkit/crashreporter/google-breakpad/src/common/Makefile
-toolkit/crashreporter/google-breakpad/src/common/mac/Makefile
-toolkit/crashreporter/google-breakpad/src/common/windows/Makefile
-toolkit/crashreporter/google-breakpad/src/tools/mac/dump_syms/Makefile
-toolkit/content/Makefile
-toolkit/content/buildconfig.html
-toolkit/obsolete/Makefile
-toolkit/components/alerts/Makefile
-toolkit/components/alerts/public/Makefile
-toolkit/components/alerts/src/Makefile
-toolkit/components/autocomplete/Makefile
-toolkit/components/autocomplete/public/Makefile
-toolkit/components/autocomplete/src/Makefile
-toolkit/components/Makefile
-toolkit/components/build/Makefile
-toolkit/components/commandlines/Makefile
-toolkit/components/commandlines/public/Makefile
-toolkit/components/commandlines/src/Makefile
-toolkit/components/console/Makefile
-toolkit/components/cookie/Makefile
-toolkit/components/downloads/public/Makefile
-toolkit/components/downloads/Makefile
-toolkit/components/downloads/src/Makefile
-toolkit/components/filepicker/Makefile
-toolkit/system/gnome/Makefile
-toolkit/components/help/Makefile
-toolkit/components/history/Makefile
-toolkit/components/history/public/Makefile
-toolkit/components/history/src/Makefile
-toolkit/components/passwordmgr/Makefile
-toolkit/components/passwordmgr/public/Makefile
-toolkit/components/passwordmgr/src/Makefile
-toolkit/components/passwordmgr/content/Makefile
-toolkit/components/passwordmgr/test/Makefile
-toolkit/components/places/Makefile
-toolkit/components/places/public/Makefile
-toolkit/components/places/src/Makefile
-toolkit/components/printing/Makefile
-toolkit/components/satchel/Makefile
-toolkit/components/satchel/public/Makefile
-toolkit/components/satchel/src/Makefile
-toolkit/components/startup/Makefile
-toolkit/components/startup/public/Makefile
-toolkit/components/startup/src/Makefile
-toolkit/components/typeaheadfind/Makefile
-toolkit/components/typeaheadfind/public/Makefile
-toolkit/components/typeaheadfind/src/Makefile
-toolkit/components/viewconfig/Makefile
-toolkit/components/viewsource/Makefile
-toolkit/locales/Makefile
-toolkit/mozapps/Makefile
-toolkit/mozapps/downloads/content/Makefile
-toolkit/mozapps/downloads/Makefile
-toolkit/mozapps/downloads/src/Makefile
-toolkit/mozapps/extensions/Makefile
-toolkit/mozapps/extensions/public/Makefile
-toolkit/mozapps/extensions/src/Makefile
-toolkit/mozapps/update/Makefile
-toolkit/mozapps/update/public/Makefile
-toolkit/mozapps/update/src/Makefile
-toolkit/mozapps/xpinstall/Makefile
-toolkit/profile/Makefile
-toolkit/profile/public/Makefile
-toolkit/profile/skin/Makefile
-toolkit/profile/src/Makefile
-toolkit/themes/Makefile
-toolkit/themes/gnomestripe/global/Makefile
-toolkit/themes/gnomestripe/Makefile
-toolkit/themes/pmstripe/global/Makefile
-toolkit/themes/pmstripe/Makefile
-toolkit/themes/pinstripe/communicator/Makefile
-toolkit/themes/pinstripe/Makefile
-toolkit/themes/pinstripe/global/Makefile
-toolkit/themes/pinstripe/help/Makefile
-toolkit/themes/pinstripe/mozapps/Makefile
-toolkit/themes/winstripe/communicator/Makefile
-toolkit/themes/winstripe/Makefile
-toolkit/themes/winstripe/global/Makefile
-toolkit/themes/winstripe/help/Makefile
-toolkit/themes/winstripe/mozapps/Makefile
-toolkit/xre/Makefile
-"
-
-MAKEFILES_standalone_composer="
-composer/Makefile
-composer/app/Makefile
-composer/app/profile/Makefile
-composer/base/Makefile
-xpfe/components/build2/Makefile
-"
-
-MAKEFILES_calendar="
-calendar/Makefile
-calendar/resources/Makefile
-calendar/libical/Makefile
-calendar/libical/src/Makefile
-calendar/libical/src/libical/Makefile
-calendar/libical/src/libicalss/Makefile
-calendar/base/Makefile
-calendar/base/public/Makefile
-calendar/base/src/Makefile
-calendar/base/build/Makefile
-calendar/providers/Makefile
-calendar/providers/memory/Makefile
-calendar/providers/storage/Makefile
-calendar/providers/composite/Makefile
-"
-
-MAKEFILES_sunbird="
-calendar/installer/Makefile
-calendar/installer/windows/Makefile
-calendar/locales/Makefile
-calendar/sunbird/Makefile
-calendar/sunbird/app/Makefile
-calendar/sunbird/base/Makefile
-"
-
-MAKEFILES_macbrowser="
-camino/Makefile
-camino/flashblock/Makefile
-camino/installer/Makefile
-"
-
-if [ "$MOZ_MAIL_NEWS" ]; then
-    if [ -f ${srcdir}/mailnews/makefiles ]; then
-        MAKEFILES_mailnews=`cat ${srcdir}/mailnews/makefiles`
-    fi
-fi
-
-MAKEFILES_ipcd="
-ipc/ipcd/Makefile
-ipc/ipcd/daemon/public/Makefile
-ipc/ipcd/daemon/src/Makefile
-ipc/ipcd/client/public/Makefile
-ipc/ipcd/client/src/Makefile
-ipc/ipcd/shared/src/Makefile
-ipc/ipcd/test/Makefile
-ipc/ipcd/test/module/Makefile
-ipc/ipcd/extensions/Makefile
-ipc/ipcd/extensions/lock/Makefile
-ipc/ipcd/extensions/lock/public/Makefile
-ipc/ipcd/extensions/lock/src/Makefile
-ipc/ipcd/extensions/lock/src/module/Makefile
-ipc/ipcd/util/Makefile
-ipc/ipcd/util/public/Makefile
-ipc/ipcd/util/src/Makefile
-"
-
-MAKEFILES_transmngr="
-ipc/ipcd/extensions/transmngr/Makefile
-ipc/ipcd/extensions/transmngr/public/Makefile
-ipc/ipcd/extensions/transmngr/src/Makefile
-ipc/ipcd/extensions/transmngr/build/Makefile
-ipc/ipcd/extensions/transmngr/test/Makefile
-ipc/ipcd/extensions/transmngr/common/Makefile
-ipc/ipcd/extensions/transmngr/module/Makefile
-"
-
-MAKEFILES_profilesharingsetup="
-embedding/components/profilesharingsetup/Makefile
-embedding/components/profilesharingsetup/public/Makefile
-embedding/components/profilesharingsetup/src/Makefile
-"
-
-    MAKEFILES_libpr0n="
-        modules/libpr0n/Makefile
-        modules/libpr0n/build/Makefile
-        modules/libpr0n/public/Makefile
-        modules/libpr0n/src/Makefile
-        modules/libpr0n/decoders/Makefile
-        modules/libpr0n/decoders/gif/Makefile
-        modules/libpr0n/decoders/png/Makefile
-        modules/libpr0n/decoders/jpeg/Makefile
-        modules/libpr0n/decoders/bmp/Makefile
-        modules/libpr0n/decoders/icon/Makefile
-        modules/libpr0n/decoders/icon/win/Makefile
-        modules/libpr0n/decoders/icon/gtk/Makefile
-        modules/libpr0n/decoders/icon/beos/Makefile
-        modules/libpr0n/decoders/xbm/Makefile
-        modules/libpr0n/encoders/Makefile
-        modules/libpr0n/encoders/png/Makefile
-        modules/libpr0n/encoders/jpeg/Makefile
-"
-
-    MAKEFILES_accessible="
-       accessible/Makefile
-       accessible/public/Makefile
-       accessible/public/msaa/Makefile
-       accessible/src/Makefile
-       accessible/src/base/Makefile
-       accessible/src/html/Makefile
-       accessible/src/xul/Makefile
-       accessible/src/msaa/Makefile
-       accessible/src/atk/Makefile
-       accessible/src/mac/Makefile
-       accessible/build/Makefile
-"
-
-if [ ! "$SYSTEM_JPEG" ]; then
-    MAKEFILES_jpeg="jpeg/Makefile"
-fi
-
-if [ ! "$SYSTEM_ZLIB" ]; then
-    MAKEFILES_zlib="
-	modules/zlib/Makefile
-	modules/zlib/src/Makefile
-"
-fi
-
-MAKEFILES_zlib="
-    $MAKEFILES_zlib
-    modules/zlib/standalone/Makefile
-"
-
-MAKEFILES_libbz2="
-    modules/libbz2/Makefile
-    modules/libbz2/src/Makefile
-"
-
-MAKEFILES_libmar="
-    modules/libmar/Makefile
-    modules/libmar/src/Makefile
-    modules/libmar/tool/Makefile
-"
-
-if test -n "$MOZ_UPDATE_PACKAGING"; then
-    MAKEFILES_update_packaging="
-        tools/update-packaging/Makefile
-        other-licenses/bsdiff/Makefile
-    "
-fi
-
-if [ ! "$SYSTEM_PNG" ]; then
-    MAKEFILES_libimg="$MAKEFILES_libimg modules/libimg/png/Makefile"
-fi
-
-MAKEFILES_gnome="
-    toolkit/Makefile
-    toolkit/system/gnome/Makefile
-"
-
 #
-# l10n/
+# Extension makefiles
 #
-if [ -f ${srcdir}/l10n/makefiles.all ]; then
-    MAKEFILES_langpacks=`cat ${srcdir}/l10n/makefiles.all`
-fi
-
-if [ "$MOZ_L10N" ]; then
-    MAKEFILES_l10n="l10n/Makefile"
-
-    if [ "$MOZ_L10N_LANG" ]; then
-	MAKEFILES_l10n_lang="
-		l10n/lang/Makefile
-		l10n/lang/addressbook/Makefile
-		l10n/lang/bookmarks/Makefile
-		l10n/lang/directory/Makefile
-		l10n/lang/editor/Makefile
-		l10n/lang/global/Makefile
-		l10n/lang/history/Makefile
-		l10n/lang/messenger/Makefile
-		l10n/lang/messengercompose/Makefile
-		l10n/lang/navigator/Makefile
-		l10n/lang/pref/Makefile
-		l10n/lang/related/Makefile
-		l10n/lang/sidebar/Makefile
-		l10n/lang/addressbook/locale/Makefile
-		l10n/lang/bookmarks/locale/Makefile
-		l10n/lang/directory/locale/Makefile
-		l10n/lang/editor/locale/Makefile
-		l10n/lang/global/locale/Makefile
-		l10n/lang/history/locale/Makefile
-		l10n/lang/messenger/locale/Makefile
-		l10n/lang/messengercompose/locale/Makefile
-		l10n/lang/navigator/locale/Makefile
-		l10n/lang/pref/locale/Makefile
-		l10n/lang/related/locale/Makefile
-		l10n/lang/sidebar/locale/Makefile
-"
-	fi
-fi
-
-# tools/jprof
-if [ "$MOZ_JPROF" ]; then
-    MAKEFILES_jprof="tools/jprof/Makefile
-        tools/jprof/stub/Makefile"
-fi
-
-# tools/leaky
-if [ "$MOZ_LEAKY" ]; then
-    MAKEFILES_leaky="tools/leaky/Makefile"
-fi
-
-# tools/trace-malloc
-if [ "$NS_TRACE_MALLOC" ]; then
-    MAKEFILES_tracemalloc="tools/trace-malloc/Makefile tools/trace-malloc/lib/Makefile"
-fi
-
-# tools/codesighs
-if [ "$MOZ_MAPINFO" ]; then
-    MAKEFILES_codesighs="tools/codesighs/Makefile"
-fi
-
-# MathML
-if [ "$MOZ_MATHML" ]; then
-    MAKEFILES_intl="$MAKEFILES_intl
-	intl/uconv/ucvmath/Makefile
-"
-    MAKEFILES_layout="$MAKEFILES_layout
-	layout/mathml/Makefile
-	layout/mathml/base/Makefile
-	layout/mathml/base/src/Makefile
-	layout/mathml/content/Makefile
-	layout/mathml/content/src/Makefile
-"
-fi
-
-# svg
-if [ "$MOZ_SVG" ]; then
-    MAKEFILES_content="$MAKEFILES_content
-	content/svg/Makefile
-	content/svg/document/Makefile
-	content/svg/document/src/Makefile
-	content/svg/content/Makefile
-	content/svg/content/src/Makefile
-"
-    MAKEFILES_dom="$MAKEFILES_dom
-	dom/public/idl/svg/Makefile
-"
-    MAKEFILES_layout="$MAKEFILES_layout
-	layout/svg/Makefile
-	layout/svg/base/Makefile
-	layout/svg/base/src/Makefile
-"
-fi
-
-# xtf
-if [ "$MOZ_XTF" ]; then
-    MAKEFILES_content="$MAKEFILES_content
-	content/xtf/Makefile
-	content/xtf/public/Makefile
-	content/xtf/src/Makefile
-"
-fi
-
-if [ "$MOZ_XMLEXTRAS" ]; then
-    MAKEFILES_content="$MAKEFILES_content
-        extensions/xmlextras/Makefile
-        extensions/xmlextras/pointers/Makefile
-        extensions/xmlextras/pointers/src/Makefile
-        extensions/xmlextras/build/Makefile
-        extensions/xmlextras/build/src/Makefile
-"
-fi
-
-if [ "$MOZ_WEBSERVICES" ]; then
-    MAKEFILES_content="$MAKEFILES_content
-        extensions/webservices/Makefile
-        extensions/webservices/build/Makefile
-        extensions/webservices/build/src/Makefile
-        extensions/webservices/interfaceinfo/Makefile
-        extensions/webservices/interfaceinfo/src/Makefile
-        extensions/webservices/proxy/Makefile
-        extensions/webservices/proxy/src/Makefile
-        extensions/webservices/public/Makefile
-        extensions/webservices/security/Makefile
-        extensions/webservices/security/src/Makefile
-        extensions/webservices/schema/Makefile
-        extensions/webservices/schema/src/Makefile
-        extensions/webservices/soap/Makefile
-        extensions/webservices/soap/src/Makefile
-        extensions/webservices/wsdl/Makefile
-        extensions/webservices/wsdl/src/Makefile
-"
-fi
-
-if [ "$MOZ_JAVAXPCOM" ]; then
-    MAKEFILES_javaxpcom="
-        extensions/java/Makefile
-        extensions/java/xpcom/Makefile
-        extensions/java/xpcom/interfaces/Makefile
-        extensions/java/xpcom/src/Makefile
-        extensions/java/xpcom/glue/Makefile
-"
-fi
-
-# directory/xpcom
-if [ "$MOZ_LDAP_XPCOM" ]; then
-    MAKEFILES_ldap="
-	directory/xpcom/Makefile
-	directory/xpcom/base/Makefile
-	directory/xpcom/base/public/Makefile
-	directory/xpcom/base/src/Makefile
-"
-fi
-
-# embedding/componentlib
-
-if [ "$MOZ_COMPONENTLIB" ]; then
-    MAKEFILES_static_components="$MAKEFILE_static_components
-	embedding/componentlib/Makefile
-"
-
-else
-
-# modules/staticmod
-
-if [ "$MOZ_STATIC_COMPONENTS" -o "$MOZ_META_COMPONENTS" ]; then
-    MAKEFILES_static_components="$MAKEFILES_static_components
-	modules/staticmod/Makefile
-"
-fi
-fi
-
-if [ "$MOZ_PREF_EXTENSIONS" ]; then
-  MOZ_EXTENSIONS="$MOZ_EXTENSIONS pref"
-fi
-
 for extension in $MOZ_EXTENSIONS; do
   if [ -f "${srcdir}/extensions/${extension}/makefiles.sh" ]; then
     . "${srcdir}/extensions/${extension}/makefiles.sh"
   fi
 done
 
-MAKEFILES_themes=`cat ${srcdir}/themes/makefiles`
-
-add_makefiles "
-$MAKEFILES_caps
-$MAKEFILES_chrome
-$MAKEFILES_db
-$MAKEFILES_docshell
-$MAKEFILES_dom
-$MAKEFILES_editor
-$MAKEFILES_codesighs
-$MAKEFILES_composer
-$MAKEFILES_embedding
-$MAKEFILES_expat
-$MAKEFILES_extensions
-$MAKEFILES_gfx
-$MAKEFILES_accessible
-$MAKEFILES_htmlparser
-$MAKEFILES_intl
-$MAKEFILES_javaxpcom
-$MAKEFILES_ldap
-$MAKEFILES_leaky
-$MAKEFILES_jpeg
-$MAKEFILES_jprof
-$MAKEFILES_js
-$MAKEFILES_jsdebugger
-$MAKEFILES_l10n
-$MAKEFILES_l10n_lang
-$MAKEFILES_langpacks
-$MAKEFILES_content
-$MAKEFILES_layout
-$MAKEFILES_libart
-$MAKEFILES_libreg
-$MAKEFILES_libimg
-$MAKEFILES_libpr0n
-$MAKEFILES_libjar
-$MAKEFILES_libpref
-$MAKEFILES_libutil
-$MAKEFILES_liveconnect
-$MAKEFILES_macmorefiles
-$MAKEFILES_mailnews
-$MAKEFILES_oji
-$MAKEFILES_plugin
-$MAKEFILES_netwerk
-$MAKEFILES_profile
-$MAKEFILES_rdf
-$MAKEFILES_static_components
-$MAKEFILES_sun_java
-$MAKEFILES_themes
-$MAKEFILES_tracemalloc
-$MAKEFILES_uriloader
-$MAKEFILES_view
-$MAKEFILES_webshell
-$MAKEFILES_widget
-$MAKEFILES_xft
-$MAKEFILES_xpcom
-$MAKEFILES_xpcom_obsolete
-$MAKEFILES_xpcom_tests
-$MAKEFILES_xpconnect
-$MAKEFILES_xpinstall
-$MAKEFILES_xpfe
-$MAKEFILES_zlib
-$MAKEFILES_libbz2
-$MAKEFILES_libmar
-$MAKEFILES_update_packaging
-"
-
-if test -n "$MOZ_PSM"; then
-    add_makefiles "$MAKEFILES_psm2"
+#
+# Toolkit makefiles
+#
+if test -z "$LIBXUL_SDK"; then
+  . "${srcdir}/toolkit/toolkit-makefiles.sh"
 fi
-
-if test -n "$MOZ_CALENDAR"; then
-    add_makefiles "$MAKEFILES_calendar"
-fi
-
-if test -n "$MOZ_XUL_APP"; then
-    add_makefiles "$MAKEFILES_xulapp"
-fi
-
-if test -n "$MOZ_XULRUNNER"; then
-    add_makefiles "$MAKEFILES_xulrunner"
-fi
-
-if test -n "$MOZ_STANDALONE_COMPOSER"; then
-    add_makefiles "$MAKEFILES_standalone_composer"
-fi
-
-if test -n "$MOZ_SUNBIRD"; then
-    add_makefiles "$MAKEFILES_sunbird"
-fi
-
-if test "$MOZ_BUILD_APP" = "camino"; then
-    add_makefiles "$MAKEFILES_macbrowser"
-fi
-
-if test -n "$MOZ_IPCD"; then
-    add_makefiles "$MAKEFILES_ipcd"
-fi
-
-if test -n "$MOZ_PROFILESHARING"; then
-    add_makefiles "$MAKEFILES_transmngr"
-    add_makefiles "$MAKEFILES_profilesharingsetup"
-fi
-
-if test -n "$MINIMO"; then
-    add_makefiles "$MAKEFILES_minimo"
-    add_makefiles "$MAKEFILES_xulapp"
-fi
-
-if test -n "$MOZ_ENABLE_GTK2"; then
-    add_makefiles "$MAKEFILES_gnome"
-fi
-
-if test -n "$MOZ_STORAGE"; then
-    add_makefiles "$MAKEFILES_storage"
-fi
-
-if test -f "${srcdir}/${MOZ_BUILD_APP}/makefiles.sh"; then
-  . "${srcdir}/${MOZ_BUILD_APP}/makefiles.sh"
-fi
--- a/browser/base/content/browser-places.js
+++ b/browser/base/content/browser-places.js
@@ -48,22 +48,58 @@ var PlacesCommandHook = {
     throw Cr.NS_NOINTERFACE;
   },
 
   // Edit-bookmark panel
   get panel() {
     return document.getElementById("editBookmarkPanel");
   },
 
+  // list of command elements (by id) to disable when the panel is opened
+  _blockedCommands: ["cmd_close", "cmd_closeWindow"],
+
+  _blockCommands: function PCH__blockCommands() {
+    for each(var key in this._blockedCommands) {
+      var elt = document.getElementById(key);
+      if (elt.getAttribute("disabled") == "true")
+        elt.setAttribute("wasDisabled", "true");
+      else {
+        elt.setAttribute("wasDisabled", "false");
+        elt.setAttribute("disabled", "true");
+      }
+    }
+  },
+
+  _restoreCommandsState: function PCH__restoreCommandsState() {
+    for each(var key in this._blockedCommands) {
+      var elt = document.getElementById(key);
+      if (elt.getAttribute("wasDisabled") != "true")
+        elt.removeAttribute("disabled");
+      elt.removeAttribute("wasDisabled");
+    }
+  },
+
   // nsIDOMEventListener
   handleEvent: function PCH_handleEvent(aEvent) {
-    if (aEvent.originalTarget != this.panel)
-      return;
-
-    gEditItemOverlay.uninitPanel(true);
+    switch (aEvent.type) {
+      case "popuphiding":
+        if (aEvent.originalTarget == this.panel) {
+          gEditItemOverlay.uninitPanel(true);
+          this._restoreCommandsState();
+        }
+        break;
+      case "keypress":
+        if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE ||
+            aEvent.keyCode == KeyEvent.DOM_VK_RETURN) {
+          // focus the content area and hide the panel
+          window.content.focus();
+          this.panel.hidePopup();
+        }
+        break;
+    }
   },
 
   _overlayLoaded: false,
   _overlayLoading: false,
   showEditBookmarkPopup:
   function PCH_showEditBookmarkPopup(aItemId, aAnchorElement, aPosition) {
     // Performance: load the overlay the first time the panel is opened
     // (see bug 392443).
@@ -93,38 +129,47 @@ var PlacesCommandHook = {
     this._overlayLoading = true;
     document.loadOverlay("chrome://browser/content/places/editBookmarkOverlay.xul",
                          loadObserver);
     this.panel.addEventListener("popuphiding", this, false);
   },
 
   _doShowEditBookmarkPanel:
   function PCH__doShowEditBookmarkPanel(aItemId, aAnchorElement, aPosition) {
+    this.panel.addEventListener("keypress", this, true);
+    this._blockCommands(); // un-done in the popuphiding handler
     this.panel.openPopup(aAnchorElement, aPosition, -1, -1);
 
     gEditItemOverlay.initPanel(aItemId,
                                { hiddenRows: ["description", "location"] });
+    setTimeout(function() {
+                 var namePicker = document.getElementById("editBMPanel_namePicker");
+                 namePicker.focus();
+                 namePicker.editor.selectAll();
+              }, 0);
   },
 
   /**
-   * Adds a bookmark to the page loaded in the given browser
+   * Adds a bookmark to the page loaded in the given browser.
    *
    * @param aBrowser
-   *        a <browser> element
+   *        a <browser> element.
+   * @param [optional] aParent
+   *        The folder in which to create a new bookmark if the page loaded in
+   *        aBrowser isn't bookmarked yet, defaults to the places root.
    * @param [optional] aShowEditUI
    *        whether or not to show the edit-bookmark UI for the bookmark item
    * @param [optional] aAnchorElement
    *        required if aShowEditUI is set, see popup's openPopup.
    * @param [optional] aPosition
    *        required if aShowEditUI is set, see popup's openPopup.
    */  
-  bookmarkPage: function PCH_bookmarkPage(aBrowser, aShowEditUI,
+  bookmarkPage: function PCH_bookmarkPage(aBrowser, aParent, aShowEditUI,
                                           aAnchorElement, aPosition) {
     var uri = aBrowser.currentURI;
-
     var itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
     if (itemId == -1) {
       // Copied over from addBookmarkForBrowser:
       // Bug 52536: We obtain the URL and title from the nsIWebNavigation
       // associated with a <browser/> rather than from a DOMWindow.
       // This is because when a full page plugin is loaded, there is
       // no DOMWindow (?) but information about the loaded document
       // may still be obtained from the webNavigation.
@@ -133,58 +178,62 @@ var PlacesCommandHook = {
       var title;
       var description;
       try {
         title = webNav.document.title;
         description = PlacesUtils.getDescriptionFromDocument(webNav.document);
       }
       catch (e) { }
 
+      var parent = aParent != undefined ? aParent : PlacesUtils.placesRootId;
       var descAnno = { name: DESCRIPTION_ANNO, value: description };
-      var txn = PlacesUtils.ptm.createItem(uri, PlacesUtils.placesRootId, -1,
+      var txn = PlacesUtils.ptm.createItem(uri, parent, -1,
                                            title, null, [descAnno]);
       PlacesUtils.ptm.commitTransaction(txn);
       if (aShowEditUI)
         itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
     }
 
     if (aShowEditUI)
       this.showEditBookmarkPopup(itemId, aAnchorElement, aPosition);
   },
 
   /**
    * Adds a bookmark to the page loaded in the current tab. 
    */
-  bookmarkCurrentPage: function PCH_bookmarkCurrentPage(aShowEditUI) {
+  bookmarkCurrentPage: function PCH_bookmarkCurrentPage(aShowEditUI, aParent) {
     // dock the panel to the star icon if it is visible, otherwise dock
     // it to the content area
-    var starIcon = document.getElementById("star-icon");
+    var starIcon = document.getElementById("star-button");
     if (starIcon && isElementVisible(starIcon)) {
-      this.bookmarkPage(getBrowser().selectedBrowser, aShowEditUI, starIcon,
-                        "after_end");
+      var dockTo = document.getElementById("go-button-bottom");
+      this.bookmarkPage(getBrowser().selectedBrowser, aParent, aShowEditUI,
+                        dockTo, "after_start");
     }
     else {
-      this.bookmarkPage(getBrowser().selectedBrowser, aShowEditUI, getBrowser(),
-                        "overlap");
+      this.bookmarkPage(getBrowser().selectedBrowser, aParent, aShowEditUI,
+                        getBrowser(), "overlap");
     }
   },
 
   /**
    * Adds a bookmark to the page targeted by a link.
-   * @param   url
-   *          The address of the link target
-   * @param   title
-   *          The link text
+   * @param aParent
+   *        The folder in which to create a new bookmark if aURL isn't
+   *        bookmarked.
+   * @param aURL (string)
+   *        the address of the link target
+   * @param aTitle
+   *        The link text
    */
-  bookmarkLink: function PCH_bookmarkLink(url, title) {
-    var linkURI = IO.newURI(url)
+  bookmarkLink: function PCH_bookmarkLink(aParent, aURL, aTitle) {
+    var linkURI = IO.newURI(aURL)
     var itemId = PlacesUtils.getMostRecentBookmarkForURI(linkURI);
     if (itemId == -1) {
-      var txn = PlacesUtils.ptm.createItem(linkURI, PlacesUtils.placesRootId, -1,
-                                           title);
+      var txn = PlacesUtils.ptm.createItem(linkURI, aParent, -1, aTitle);
       PlacesUtils.ptm.commitTransaction(txn);
       itemId = PlacesUtils.getMostRecentBookmarkForURI(linkURI);
     }
 
     PlacesCommandHook.showEditBookmarkPopup(itemId, getBrowser(), "overlap");
   },
 
   /**
@@ -548,28 +597,16 @@ var BookmarksMenuDropHandler = {
   }
 };
 
 /**
  * Handles special drag and drop functionality for menus on the Bookmarks 
  * Toolbar and Bookmarks Menu.
  */
 var PlacesMenuDNDController = {
-  
-  /**
-   * Attach a special context menu hiding listener that ensures that popups 
-   * are properly closed after a context menu is hidden. See bug 332845 for 
-   * why we have to do this.
-   */
-  init: function PMDC_init() {
-    var placesContext = document.getElementById("placesContext");
-    var self = this;
-    placesContext.addEventListener("popuphidden", function () { self._closePopups() }, false);
-  },
-
   _springLoadDelay: 350, // milliseconds
 
   /**
    * All Drag Timers set for the Places UI
    */
   _timers: { },
   
   /**
@@ -723,22 +760,22 @@ var PlacesStarButton = {
 
     throw Cr.NS_NOINTERFACE;
   },
 
   _starred: false,
   _batching: false,
 
   updateState: function PSB_updateState() {
-    var starIcon = document.getElementById("star-icon");
+    var starIcon = document.getElementById("star-button");
     if (!starIcon)
       return;
 
     var uri = getBrowser().currentURI;
-    this._starred = uri && PlacesUtils.bookmarks.isBookmarked(uri);
+    this._starred = uri && (PlacesUtils.getMostRecentBookmarkForURI(uri) != -1);
     if (this._starred)
       starIcon.setAttribute("starred", "true");
     else
       starIcon.removeAttribute("starred");
   },
 
   onClick: function PSB_onClick(aEvent) {
     PlacesCommandHook.bookmarkCurrentPage(this._starred);
--- a/browser/base/content/browser-sets.inc
+++ b/browser/base/content/browser-sets.inc
@@ -83,17 +83,17 @@
     <command id="cmd_findAgain"
              oncommand="gFindBar.onFindAgainCommand(false);"
              observes="isImage"/>
     <command id="cmd_findPrevious"
              oncommand="gFindBar.onFindAgainCommand(true);"
              observes="isImage"/>
     <!-- work-around bug 392512 -->
     <command id="Browser:AddBookmarkAs" 
-             oncommand="setTimeout(function() { PlacesCommandHook.bookmarkCurrentPage(true); }, 0);"/>
+             oncommand="PlacesCommandHook.bookmarkCurrentPage(true, PlacesUtils.bookmarksRootId);"/>
     <!-- The command is disabled for the hidden window. Otherwise its enabled
          state is handled by the BookmarkAllTabsHandler object. -->
     <command id="Browser:BookmarkAllTabs"
              oncommand="gBookmarkAllTabsHandler.doCommand();"
              disabled="true"/>
     <command id="Browser:Home"    oncommand="BrowserHome();"/>
     <command id="Browser:Back"    oncommand="BrowserBack();" disabled="true"/>
     <command id="Browser:Forward" oncommand="BrowserForward();" disabled="true"/>
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -279,20 +279,19 @@ function addBookmarkMenuitems()
 }
 
 function BookmarkThisTab()
 {
   var tab = getBrowser().mContextTab;
   if (tab.localName != "tab")
     tab = getBrowser().mCurrentTab;
 
-  setTimeout(function() { // workaround bug 392512
-    PlacesCommandHook.bookmarkPage(tab.linkedBrowser, true, getBrowser(),
-                                   "overlap")
-  }, 0);
+  PlacesCommandHook.bookmarkPage(tab.linkedBrowser,
+                                 PlacesUtils.bookmarksRootId,
+                                 true, getBrowser(), "overlap");
 }
 
 /**
  * Global bookmarks observer for browser-window specific stuff
  */
 var gBookmarksObserver = {
   QueryInterface: function G_BO_QueryInterface(aIID) {
     if (aIID.equals(Ci.nsINavBookmarkObserver) ||
@@ -658,23 +657,26 @@ const gXPInstallObserver = {
     }
     return null;
   },
 
   observe: function (aSubject, aTopic, aData)
   {
     var brandBundle = document.getElementById("bundle_brand");
     var browserBundle = document.getElementById("bundle_browser");
-    var browser, webNav, wm;
     switch (aTopic) {
     case "xpinstall-install-blocked":
-      var shell = aSubject.QueryInterface(Components.interfaces.nsIDocShell);
-      browser = this._getBrowser(shell);
+      var installInfo = aSubject.QueryInterface(Components.interfaces.nsIXPIInstallInfo);
+      var win = installInfo.originatingWindow;
+      var shell = win.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
+                     .getInterface(Components.interfaces.nsIWebNavigation)
+                     .QueryInterface(Components.interfaces.nsIDocShell);
+      var browser = this._getBrowser(shell);
       if (browser) {
-        var host = aData;
+        var host = installInfo.originatingURI.host;
         var brandShortName = brandBundle.getString("brandShortName");
         var notificationName, messageString, buttons;
         if (!gPrefService.getBoolPref("xpinstall.enabled")) {
           notificationName = "xpinstall-disabled"
           if (gPrefService.prefIsLocked("xpinstall.enabled")) {
             messageString = browserBundle.getString("xpinstallDisabledMessageLocked");
             buttons = [];
           }
@@ -694,64 +696,41 @@ const gXPInstallObserver = {
           }
         }
         else {
           notificationName = "xpinstall"
           messageString = browserBundle.getFormattedString("xpinstallPromptWarning",
                                                            [brandShortName, host]);
 
           buttons = [{
-            label: browserBundle.getString("xpinstallPromptWarningButton"),
-            accessKey: browserBundle.getString("xpinstallPromptWarningButton.accesskey"),
+            label: browserBundle.getString("xpinstallPromptAllowButton"),
+            accessKey: browserBundle.getString("xpinstallPromptAllowButton.accesskey"),
             popup: null,
-            callback: function() { return xpinstallEditPermissions(shell, host); }
+            callback: function() {
+              var mgr = Components.classes["@mozilla.org/xpinstall/install-manager;1"]
+                                  .createInstance(Components.interfaces.nsIXPInstallManager);
+              mgr.initManagerWithInstallInfo(installInfo);
+              return false;
+            }
           }];
         }
 
         var notificationBox = gBrowser.getNotificationBox(browser);
         if (!notificationBox.getNotificationWithValue(notificationName)) {
           const priority = notificationBox.PRIORITY_WARNING_MEDIUM;
           const iconURL = "chrome://mozapps/skin/xpinstall/xpinstallItemGeneric.png";
           notificationBox.appendNotification(messageString, notificationName,
                                              iconURL, priority, buttons);
         }
       }
       break;
     }
   }
 };
 
-function xpinstallEditPermissions(aDocShell, aHost)
-{
-  var browser = gXPInstallObserver._getBrowser(aDocShell);
-  if (browser) {
-    var bundlePreferences = document.getElementById("bundle_preferences");
-    var params = { blockVisible   : false,
-                   sessionVisible : false,
-                   allowVisible   : true,
-                   prefilledHost  : aHost,
-                   permissionType : "install",
-                   windowTitle    : bundlePreferences.getString("addons_permissions_title"),
-                   introText      : bundlePreferences.getString("addonspermissionstext") };
-    var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
-                   .getService(Components.interfaces.nsIWindowMediator);
-    var existingWindow = wm.getMostRecentWindow("Browser:Permissions");
-    if (existingWindow) {
-      existingWindow.initWithParams(params);
-      existingWindow.focus();
-    }
-    else
-      window.openDialog("chrome://browser/content/preferences/permissions.xul",
-                        "_blank", "resizable,dialog=no,centerscreen", params);
-    return false;
-  }
-
-  return true;
-}
-
 function BrowserStartup()
 {
   gBrowser = document.getElementById("content");
 
   var uriToLoad = null;
   // Check for window.arguments[0]. If present, use that for uriToLoad.
   if ("arguments" in window && window.arguments[0])
     uriToLoad = window.arguments[0];
@@ -1008,18 +987,16 @@ function delayedStartup()
     var sidebar = document.getElementById("sidebar");
     var sidebarBox = document.getElementById("sidebar-box");
     sidebar.setAttribute("src", sidebarBox.getAttribute("src"));
   }
 
   // add bookmark options to context menu for tabs
   addBookmarkMenuitems();
 
-  PlacesMenuDNDController.init();
-
   initBookmarksToolbar();
   PlacesUtils.bookmarks.addObserver(gBookmarksObserver, false);
   PlacesStarButton.init();
 
   // called when we go into full screen, even if it is
   // initiated by a web page script
   window.addEventListener("fullscreen", onFullScreen, true);
 
@@ -1112,19 +1089,19 @@ function delayedStartup()
   }
   catch(ex) {
     Components.utils.reportError("Failed to init content pref service:\n" + ex);
   }
 
 #ifdef XP_WIN
   // For Vista, flip the default download folder pref once from Desktop to Downloads
   // on new profiles.
-  try {
-    var sysInfo = Cc["@mozilla.org/system-info;1"].
-                  getService(Ci.nsIPropertyBag2);
+  try {
+    var sysInfo = Cc["@mozilla.org/system-info;1"].
+                  getService(Ci.nsIPropertyBag2);
     if (parseFloat(sysInfo.getProperty("version")) >= 6 &&
         !gPrefService.getPrefType("browser.download.dir") &&
         gPrefService.getIntPref("browser.download.folderList") == 0) {
       var dnldMgr = Cc["@mozilla.org/download-manager;1"]
                               .getService(Ci.nsIDownloadManager);
       gPrefService.setCharPref("browser.download.dir", 
         dnldMgr.defaultDownloadsDirectory.path);
       gPrefService.setIntPref("browser.download.folderList", 1);
@@ -1221,18 +1198,19 @@ function BrowserShutdown()
   window.QueryInterface(Ci.nsIDOMChromeWindow).browserDOMWindow = null;
 
   // Close the app core.
   if (appCore)
     appCore.close();
 }
 
 #ifdef XP_MACOSX
-// nonBrowserWindowStartup() and nonBrowserWindowDelayedStartup() are used for
-// non-browser windows in macBrowserOverlay
+// nonBrowserWindowStartup(), nonBrowserWindowDelayedStartup(), and
+// nonBrowserWindowShutdown() are used for non-browser windows in
+// macBrowserOverlay
 function nonBrowserWindowStartup()
 {
   // Disable inappropriate commands / submenus
   var disabledItems = ['cmd_newNavigatorTab', 'Browser:SavePage', 'Browser:SendLink',
                        'cmd_pageSetup', 'cmd_print', 'cmd_find', 'cmd_findAgain', 'viewToolbarsMenu',
                        'cmd_toggleTaskbar', 'viewSidebarMenuMenu', 'Browser:Reload', 'Browser:ReloadSkipCache',
                        'viewTextZoomMenu', 'pageStyleMenu', 'charsetMenu', 'View:PageSource', 'View:FullScreen',
                        'viewHistorySidebar', 'Browser:AddBookmarkAs', 'View:PageInfo', 'Tasks:InspectPage'];
@@ -1271,16 +1249,22 @@ function nonBrowserWindowDelayedStartup(
 {
   // init global pref service
   gPrefService = Components.classes["@mozilla.org/preferences-service;1"]
                            .getService(Components.interfaces.nsIPrefBranch2);
 
   // Set up Sanitize Item
   gSanitizeListener = new SanitizeListener();
 }
+
+function nonBrowserWindowShutdown()
+{
+  if (gSanitizeListener)
+    gSanitizeListener.shutdown();
+}
 #endif
 
 function AutoHideTabbarPrefListener()
 {
   this.toggleAutoHideTabbar();
 }
 
 AutoHideTabbarPrefListener.prototype =
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -219,16 +219,17 @@
             <textbox id="urlbar" flex="1"
                      chromedir="&locale.dir;"
                      type="autocomplete"
                      autocompletesearch="history" 
                      autocompletepopup="PopupAutoComplete"
                      completeselectedindex="true"
                      tabscrolling="true"
                      showcommentcolumn="true"
+                     showimagecolumn="true" 
                      enablehistory="true"
                      maxrows="10"
                      newlines="stripsurroundingwhitespace"
                      oninput="gBrowser.userTypedValue = this.value"
                      ontextentered="return handleURLBarCommand(param);"
                      ontextreverted="return handleURLBarRevert();">
               <deck id="page-proxy-deck" onclick="PageProxyClickHandler(event);">
                 <image id="page-proxy-button"
@@ -256,17 +257,16 @@
                              onclick="checkForMiddleClick(this, event);"/>
                 </button>
                 <image id="lock-icon" onclick="if (event.button == 0) displaySecurityInfo(); event.stopPropagation();"/>
 #ifdef MOZ_SAFE_BROWSING
                 <image id="safebrowsing-urlbar-icon" tooltiptext="&safeb.urlbaricon.tooltip;"
                        level="safe"
                        onclick="goDoCommand('safebrowsing-show-warning')" />
 #endif
-                <image id="star-icon" onclick="if (event.button == 0) PlacesStarButton.onClick(event);"/>
               </hbox>
             </textbox>
             <stack id="go-button-stack">
               <vbox>
                 <!-- These image segments allow the button to stretch nicely
                      in larger urlbars. -->
                 <image id="go-button-top"
                        class="go-button-background"
@@ -279,25 +279,27 @@
                        id="go-button-mid-bottom"
                       class="go-button-background"
                       chromedir="&locale.dir;" />
                 <image id="go-button-bottom"
                        class="go-button-background"
                        chromedir="&locale.dir;" />
               </vbox>
 							
-            <toolbarbutton id="go-button"
-                           flex="1"
-                           chromedir="&locale.dir;"
-                           label="&goEndCap.label;"
-                           onclick="handleURLBarCommand(event);"
-                           ondragover="nsDragAndDrop.dragOver(event, goButtonObserver);"
-                           ondragdrop="nsDragAndDrop.drop(event, goButtonObserver);"
-                           ondragexit="nsDragAndDrop.dragExit(event, goButtonObserver);"
-                           tooltiptext="&goEndCap.tooltip;"/>
+              <hbox>
+                <toolbarbutton id="star-button" onclick="if (event.button == 0) PlacesStarButton.onClick(event);"/>
+                <toolbarbutton id="go-button"
+                               chromedir="&locale.dir;"
+                               label="&goEndCap.label;"
+                               onclick="handleURLBarCommand(event);"
+                               ondragover="nsDragAndDrop.dragOver(event, goButtonObserver);"
+                               ondragdrop="nsDragAndDrop.drop(event, goButtonObserver);"
+                               ondragexit="nsDragAndDrop.dragExit(event, goButtonObserver);"
+                               tooltiptext="&goEndCap.tooltip;"/>
+              </hbox>
           </stack>
         </hbox>
       </toolbaritem>
 
       <toolbaritem id="search-container" title="&searchItem.title;" 
                    align="center" class="chromeclass-toolbar-additional"
                    flex="100" persist="width">
         <searchbar id="searchbar" flex="1" chromedir="&locale.dir;"/>
--- a/browser/base/content/macBrowserOverlay.xul
+++ b/browser/base/content/macBrowserOverlay.xul
@@ -57,16 +57,17 @@
 
 # All JS files which are not content (only) dependent that browser.xul
 # wishes to include *must* go into the global-scripts.inc file
 # so that they can be shared by this overlay.
 #include global-scripts.inc
 
 <script type="application/x-javascript">
   addEventListener("load", nonBrowserWindowStartup, false);
+  addEventListener("unload", nonBrowserWindowShutdown, false);
 </script>
 
 # All sets except for popupsets (commands, keys, stringbundles and broadcasters) *must* go into the 
 # browser-sets.inc file for sharing with hiddenWindow.xul.
 #include browser-sets.inc
 
 # The entire main menubar is placed into browser-menubar.inc, so that it can be shared by 
 # hiddenWindow.xul.
--- a/browser/base/content/nsContextMenu.js
+++ b/browser/base/content/nsContextMenu.js
@@ -622,40 +622,43 @@ nsContextMenu.prototype = {
 
   // Open linked-to URL in a new tab.
   openLinkInTab: function() {
     openNewTabWith(this.linkURL, this.target.ownerDocument, null, null, false);
   },
 
   // Open frame in a new tab.
   openFrameInTab: function() {
-    openNewTabWith(this.target.ownerDocument.location.href,
-                   null, null, null, false);
+    var doc = this.target.ownerDocument;
+    var frameURL = doc.documentURIObject.spec;
+
+    openNewTabWith(frameURL, null, null, null, false, makeURI(doc.referrer));
   },
 
   // Reload clicked-in frame.
   reloadFrame: function() {
     this.target.ownerDocument.location.reload();
   },
 
   // Open clicked-in frame in its own window.
   openFrame: function() {
-    openNewWindowWith(this.target.ownerDocument.location.href,
-                      null, null, false);
+    var doc = this.target.ownerDocument;
+    var frameURL = doc.documentURIObject.spec;
+
+    openNewWindowWith(frameURL, null, null, false, makeURI(doc.referrer));
   },
 
   // Open clicked-in frame in the same window.
   showOnlyThisFrame: function() {
-    var frameURL = this.target.ownerDocument.location.href;
+    var doc = this.target.ownerDocument;
+    var frameURL = doc.documentURIObject.spec;
 
-    try {
-      urlSecurityCheck(frameURL, this.browser.contentPrincipal,
-                       Ci.nsIScriptSecurityManager.DISALLOW_SCRIPT);
-      this.browser.loadURI(frameURL);
-    } catch(e) {}
+    urlSecurityCheck(frameURL, this.browser.contentPrincipal,
+                     Ci.nsIScriptSecurityManager.DISALLOW_SCRIPT);
+    this.browser.loadURI(frameURL, makeURI(doc.referrer));
   },
 
   // View Partial Source
   viewPartialSource: function(aContext) {
     var focusedWindow = document.commandDispatcher.focusedWindow;
     if (focusedWindow == window)
       focusedWindow = content;
 
@@ -1115,49 +1118,42 @@ nsContextMenu.prototype = {
 
     var newWindowPref = gPrefService.getIntPref("browser.link.open_newwindow");
     var where = newWindowPref == 3 ? "tab" : "window";
 
     openUILinkIn(uri, where);
   },
 
   bookmarkThisPage: function CM_bookmarkThisPage() {
-    // workaround bug 392512
-    setTimeout(function(aSelf) {
-      PlacesCommandHook.bookmarkPage(aSelf.browser, true, aSelf.browser,
-                                     "overlap"); }, 0, this);
+    PlacesCommandHook.bookmarkPage(this.browser, PlacesUtils.bookmarksRootId,
+                                   true, this.browser, "overlap");
   },
 
   bookmarkLink: function CM_bookmarkLink() {
-    // workaround bug 392512
-    setTimeout(function(aSelf) {
-      PlacesCommandHook.bookmarkLink(aSelf.linkURL, aSelf.linkText());
-    }, 0, this);
+    PlacesCommandHook.bookmarkLink(PlacesUtils.bookmarksRootId, this.linkURL,
+                                   this.linkText());
   },
 
   addBookmarkForFrame: function CM_addBookmarkForFrame() {
     var doc = this.target.ownerDocument;
     var uri = doc.documentURIObject;
 
     var itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
     if (itemId == -1) {
       var title = doc.title;
       var description = PlacesUtils.getDescriptionFromDocument(doc);
 
       var descAnno = { name: DESCRIPTION_ANNO, value: description };
-      var txn = PlacesUtils.ptm.createItem(uri, PlacesUtils.placesRootId, -1,
+      var txn = PlacesUtils.ptm.createItem(uri, PlacesUtils.bookmarksRootId, -1,
                                            title, null, [descAnno]);
       PlacesUtils.ptm.commitTransaction(txn);
       itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
     }
 
-    // workaround bug 392512
-    setTimeout(function(aSelf) {
-      PlacesCommandHook.showEditBookmarkPopup(itemId, aSelf.browser, "overlap");
-    }, 0, this);
+    PlacesCommandHook.showEditBookmarkPopup(itemId, this.browser, "overlap");
   },
 
   savePageAs: function CM_savePageAs() {
     saveDocument(this.browser.contentDocument);
   },
 
   sendPage: function CM_sendPage() {
     MailIntegration.sendLinkForWindow(this.browser.contentWindow);  
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -2495,34 +2495,38 @@
     </handlers>
   </binding>
 
   <binding id="tabbrowser-arrowscrollbox" extends="chrome://global/content/bindings/scrollbox.xml#arrowscrollbox-clicktoscroll">
     <content>
       <xul:toolbarbutton class="scrollbutton-up" collapsed="true"
                          xbl:inherits="orient"
                          anonid="scrollbutton-up"
+                         onclick="_distanceScroll(event);"
                          onmousedown="_startScroll(-1);"
+                         onmouseover="_continueScroll(-1);"
                          onmouseup="_stopScroll();"
-                         onmouseout="_stopScroll();"
+                         onmouseout="_pauseScroll();"
                          chromedir="&locale.dir;"/>
       <xul:scrollbox xbl:inherits="orient,align,pack,dir" flex="1" anonid="scrollbox">
         <children/>
       </xul:scrollbox>
       <xul:stack align="center" pack="end" class="scrollbutton-down-stack">
         <xul:hbox flex="1" class="scrollbutton-down-box" 
                            collapsed="true" anonid="down-box"/>
         <xul:hbox flex="1" class="scrollbutton-down-box-animate" 
                            collapsed="true" anonid="down-box-animate"/>
         <xul:toolbarbutton class="scrollbutton-down" collapsed="true"
                            xbl:inherits="orient"
                            anonid="scrollbutton-down"
+                           onclick="_distanceScroll(event);"
                            onmousedown="_startScroll(1);"
+                           onmouseover="_continueScroll(1);"
                            onmouseup="_stopScroll();"
-                           onmouseout="_stopScroll();"
+                           onmouseout="_pauseScroll();"
                            chromedir="&locale.dir;"/>
       </xul:stack>
     </content>
     <implementation>
       <field name="_scrollButtonDownBox">
         document.getAnonymousElementByAttribute(this, "anonid", "down-box");
       </field>
       <field name="_scrollButtonDownBoxAnimate">
@@ -2592,17 +2596,18 @@
         <xul:toolbarbutton class="tabs-alltabs-button" type="menu"
                            anonid="alltabs-button"
                            tooltipstring="&listAllTabs.label;">
           <xul:menupopup class="tabs-alltabs-popup"
                          anonid="alltabs-popup" 
                          position="after_end"/>
         </xul:toolbarbutton>
       </xul:stack>
-      <xul:hbox class="tabs-closebutton-box" align="center" pack="end" anonid="tabstrip-closebutton">
+      <xul:hbox anonid="tabstrip-closebutton" class="tabs-closebutton-box"
+                align="center" pack="end" chromedir="&locale.dir;">
         <xul:toolbarbutton class="close-button tabs-closebutton"/>
       </xul:hbox>
     </content>
     <implementation implements="nsITimerCallback, nsIDOMEventListener">
       <constructor>
         <![CDATA[
           var pb2 =
               Components.classes['@mozilla.org/preferences-service;1'].
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -216,46 +216,55 @@
               // try to decode as UTF-8
               value = decodeURI(value);
             } catch(e) {}
             this.inputField.value = value;
           }
 
           this._protocol.setAttribute("value", this._uri.scheme + "://");
           this._protocolHidden = this._hideProtocols.indexOf(this._uri.scheme) > -1;
-          this._subDomain.removeAttribute("value");
-          this._port.removeAttribute("value");
 
           var host = this._uri.host;
           if (host) {
-            //XXX Bug 386727: Disabled for now due to perf/leak regressions
-            //XXX workaround for bug 364129
-            if (0 && !/^[.0-9]+$/.test(host)) {
+            var subdomain;
+            var port = (this._uri.port > -1) ? ":" + this._uri.port : "";
+            if (this._uri.hostPort[0] == "[") {
+              // IPv6 address
+              subdomain = "[";
+              port = "]" + port;
+            }
+            else if (0 && !/^[.0-9]+$/.test(host)) {
+              //XXX subdomain detection disabled (bug 386727)
+              //XXX subdomain detection disabled for IP addresses (bug 364129)
+
               // getEffectiveTLDLength might convert our host and return a misleading length.
               // To avoid this, pass the ASCII host, count the dots of its effective TLD
               // and use that number to operate on our actual host.
 
               var asciiHost = this._uri.asciiHost;
               var domainSegments = host.split(".");
               var cSubdomain = domainSegments.length -
                                asciiHost.slice(asciiHost.length -
                                                this.tldService.getEffectiveTLDLength(asciiHost))
                                         .split(".").length - 1;
               if (cSubdomain > 0) {
                 host = domainSegments;
-                var subdomain = host.splice(0, cSubdomain);
-                this._subDomain.setAttribute("value", subdomain.join(".") + ".");
+                subdomain = host.splice(0, cSubdomain).join(".") + ".";
                 host = host.join(".");
               }
+            } else {
+              subdomain = "";
             }
+            this._subDomain.setAttribute("value", subdomain);
             this._domain.setAttribute("value", host);
-            if (this._uri.port > -1)
-              this._port.setAttribute("value", ":" + this._uri.port);
+            this._port.setAttribute("value", port);
           } else {
+            this._subDomain.removeAttribute("value");
             this._domain.removeAttribute("value");
+            this._port.removeAttribute("value");
           }
 
           var path = this._uri.path;
           try {
             // try to decode as UTF-8
             path = decodeURI(path);
           } catch(e) {}
           this._path.setAttribute("value", path);
@@ -424,17 +433,17 @@
       </method>
 
       <method name="handleEvent">
         <parameter name="aEvent"/>
         <body><![CDATA[
           if (aEvent.type == "mousedown" &&
               aEvent.button == 0 && aEvent.detail == 2 &&
               this.doubleClickSelectsAll) {
-            this.inputField.select();
+            this.editor.selectAll();
             aEvent.preventDefault();
           }
         ]]></body>
       </method>
     </implementation>
 
     <handlers>
       <handler event="input"
--- a/browser/base/content/utilityOverlay.js
+++ b/browser/base/content/utilityOverlay.js
@@ -520,19 +520,22 @@ function getBrowserFromContentWindow(aCo
  *        Form POST data, or null.
  * @param aEvent
  *        The triggering event (for the purpose of determining whether to open
  *        in the background), or null.
  * @param aAllowThirdPartyFixup
  *        If true, then we allow the URL text to be sent to third party services
  *        (e.g., Google's I Feel Lucky) for interpretation. This parameter may
  *        be undefined in which case it is treated as false.
+ * @param [optional] aReferrer
+ *        If aDocument is null, then this will be used as the referrer.
+ *        There will be no security check.
  */ 
 function openNewTabWith(aURL, aDocument, aPostData, aEvent,
-                        aAllowThirdPartyFixup)
+                        aAllowThirdPartyFixup, aReferrer)
 {
   if (aDocument)
     urlSecurityCheck(aURL, aDocument.nodePrincipal);
 
   var prefSvc = Components.classes["@mozilla.org/preferences-service;1"]
                           .getService(Components.interfaces.nsIPrefService);
   prefSvc = prefSvc.getBranch(null);
 
@@ -550,37 +553,38 @@ function openNewTabWith(aURL, aDocument,
   // As in openNewWindowWith(), we want to pass the charset of the
   // current document over to a new tab. 
   var wintype = document.documentElement.getAttribute("windowtype");
   var originCharset;
   if (wintype == "navigator:browser")
     originCharset = window.content.document.characterSet;
 
   // open link in new tab
-  var referrerURI = aDocument ? aDocument.documentURIObject : null;
+  var referrerURI = aDocument ? aDocument.documentURIObject : aReferrer;
   var browser = top.document.getElementById("content");
   browser.loadOneTab(aURL, referrerURI, originCharset, aPostData,
                      loadInBackground, aAllowThirdPartyFixup || false);
 }
 
-function openNewWindowWith(aURL, aDocument, aPostData, aAllowThirdPartyFixup)
+function openNewWindowWith(aURL, aDocument, aPostData, aAllowThirdPartyFixup,
+                           aReferrer)
 {
   if (aDocument)
     urlSecurityCheck(aURL, aDocument.nodePrincipal);
 
   // if and only if the current window is a browser window and it has a
   // document with a character set, then extract the current charset menu
   // setting from the current document and use it to initialize the new browser
   // window...
   var charsetArg = null;
   var wintype = document.documentElement.getAttribute("windowtype");
   if (wintype == "navigator:browser")
     charsetArg = "charset=" + window.content.document.characterSet;
 
-  var referrerURI = aDocument ? aDocument.documentURIObject : null;
+  var referrerURI = aDocument ? aDocument.documentURIObject : aReferrer;
   window.openDialog(getBrowserURL(), "_blank", "chrome,all,dialog=no",
                     aURL, charsetArg, referrerURI, aPostData,
                     aAllowThirdPartyFixup);
 }
 
 /**
  * recognizeFeedFromLink: recognizes RSS/ATOM feeds from DOM link elements.
  *
--- a/browser/components/migration/src/nsBrowserProfileMigratorUtils.cpp
+++ b/browser/components/migration/src/nsBrowserProfileMigratorUtils.cpp
@@ -54,16 +54,18 @@
 #include "nsAppDirectoryServiceDefs.h"
 #include "nsIRDFService.h"
 #include "nsIStringBundle.h"
 #include "nsISupportsArray.h"
 #include "nsXPCOMCID.h"
 
 #define MIGRATION_BUNDLE "chrome://browser/locale/migration/migration.properties"
 
+#define BOOKMARKS_FILE_NAME NS_LITERAL_STRING("bookmarks.html")
+
 void SetUnicharPref(const char* aPref, const nsAString& aValue,
                     nsIPrefBranch* aPrefs)
 {
   nsCOMPtr<nsISupportsString> supportsString =
     do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID);    
   if (supportsString) {
      supportsString->SetData(aValue); 
      aPrefs->SetComplexValue(aPref, NS_GET_IID(nsISupportsString),
@@ -212,21 +214,35 @@ AnnotatePersonalToolbarFolder(nsIFile* a
   
   outputStream->Close();
   
   return NS_OK;
 }
 
 nsresult
 ImportBookmarksHTML(nsIFile* aBookmarksFile, 
+                    PRBool aImportIntoRoot,
+                    PRBool aOverwriteDefaults,
                     const PRUnichar* aImportSourceNameKey)
 {
   nsresult rv;
 
-  // Look for the localized name of the bookmarks toolbar
+  nsCOMPtr<nsILocalFile> localFile(do_QueryInterface(aBookmarksFile));
+  NS_ENSURE_TRUE(localFile, NS_ERROR_FAILURE);
+  nsCOMPtr<nsIPlacesImportExportService> importer = do_GetService(NS_PLACESIMPORTEXPORTSERVICE_CONTRACTID, &rv);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  // Import file directly into the bookmarks root folder.
+  if (aImportIntoRoot) {
+    rv = importer->ImportHTMLFromFile(localFile, aOverwriteDefaults);
+    NS_ENSURE_SUCCESS(rv, rv);
+    return NS_OK;
+  }
+
+  // Get the source application name.
   nsCOMPtr<nsIStringBundleService> bundleService =
     do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIStringBundle> bundle;
   rv = bundleService->CreateBundle(MIGRATION_BUNDLE, getter_AddRefs(bundle));
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -234,29 +250,37 @@ ImportBookmarksHTML(nsIFile* aBookmarksF
   bundle->GetStringFromName(aImportSourceNameKey, getter_Copies(sourceName));
 
   const PRUnichar* sourceNameStrings[] = { sourceName.get() };
   nsString importedBookmarksTitle;
   bundle->FormatStringFromName(NS_LITERAL_STRING("importedBookmarksFolder").get(),
                                sourceNameStrings, 1, 
                                getter_Copies(importedBookmarksTitle));
 
-  // Get the bookmarks service
+  // Get the bookmarks service.
   nsCOMPtr<nsINavBookmarksService> bms =
     do_GetService(NS_NAVBOOKMARKSSERVICE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Create an imported bookmarks folder under the bookmarks menu.
   PRInt64 root;
   rv = bms->GetBookmarksRoot(&root);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRInt64 folder;
   rv = bms->CreateFolder(root, importedBookmarksTitle, -1, &folder);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Import the bookmarks into the folder.
-  nsCOMPtr<nsILocalFile> localFile(do_QueryInterface(aBookmarksFile));
-  NS_ENSURE_TRUE(localFile, NS_ERROR_FAILURE);
-  nsCOMPtr<nsIPlacesImportExportService> importer = do_GetService(NS_PLACESIMPORTEXPORTSERVICE_CONTRACTID, &rv);
-  NS_ENSURE_SUCCESS(rv, rv);
   return importer->ImportHTMLFromFileToFolder(localFile, folder, PR_FALSE);
 }
+
+nsresult
+InitializeBookmarks(nsIFile* aTargetProfile)
+{
+  nsCOMPtr<nsIFile> bookmarksFile;
+  aTargetProfile->Clone(getter_AddRefs(bookmarksFile));
+  bookmarksFile->Append(BOOKMARKS_FILE_NAME);
+  
+  nsresult rv = ImportBookmarksHTML(bookmarksFile, PR_TRUE, PR_TRUE, EmptyString().get());
+  NS_ENSURE_SUCCESS(rv, rv);
+  return NS_OK;
+}
--- a/browser/components/migration/src/nsBrowserProfileMigratorUtils.h
+++ b/browser/components/migration/src/nsBrowserProfileMigratorUtils.h
@@ -96,16 +96,23 @@ void GetProfilePath(nsIProfileStartup* a
 // each browser vendor seems to have their own way of identifying the 
 // Personal Toolbar Folder. This function scans for the vendor-specific
 // name in the source Bookmarks file and then writes out a normalized
 // variant into the target folder. 
 nsresult AnnotatePersonalToolbarFolder(nsIFile* aSourceBookmarksFile,
                                        nsIFile* aTargetBookmarksFile,
                                        const char* aToolbarFolderName);
 
-// In-place import from aBookmarksFile into a folder in the user's bookmarks
-// with the name "From (STR:aImportSourceNameKey)" (aImportSourceNameKey
-// is a key into migration.properties with the pretty name of the application.
+// In-place import from aBookmarksFile into a folder in the user's bookmarks.
+// If the importIntoRoot parameter has a value of true, the bookmarks will be
+// imported into the bookmarks root folder. Otherwise, they'll be imported into
+// a new folder with the name "From (STR:aImportSourceNameKey)".
+// aImportSourceNameKey is a key into migration.properties with the pretty name
+// of the application.
 nsresult ImportBookmarksHTML(nsIFile* aBookmarksFile, 
+                             PRBool aImportIntoRoot,
+                             PRBool aOverwriteDefaults,
                              const PRUnichar* aImportSourceNameKey);
 
+nsresult InitializeBookmarks(nsIFile* aTargetProfile);
+
 #endif
 
--- a/browser/components/migration/src/nsDogbertProfileMigrator.cpp
+++ b/browser/components/migration/src/nsDogbertProfileMigrator.cpp
@@ -617,18 +617,21 @@ nsDogbertProfileMigrator::FixDogbertCook
 
 #endif // NEED_TO_FIX_4X_COOKIES
 
 
 nsresult
 nsDogbertProfileMigrator::CopyBookmarks(PRBool aReplace)
 {
   // If we're blowing away existing content, just copy the file, don't do fancy importing.
-  if (aReplace)
+  if (aReplace) {
+    nsresult rv = InitializeBookmarks(mTargetProfile);
+    NS_ENSURE_SUCCESS(rv, rv);
     return MigrateDogbertBookmarks();
+  }
 
   return ImportNetscapeBookmarks(BOOKMARKS_FILE_NAME_IN_4x, 
                                  NS_LITERAL_STRING("sourceNameDogbert").get());
 }
 
 nsresult
 nsDogbertProfileMigrator::MigrateDogbertBookmarks()
 {
--- a/browser/components/migration/src/nsIEProfileMigrator.cpp
+++ b/browser/components/migration/src/nsIEProfileMigrator.cpp
@@ -1194,16 +1194,22 @@ nsIEProfileMigrator::CopyFavorites(PRBoo
     const PRUnichar* sourceNameStrings[] = { sourceNameIE.get() };
     nsString importedIEFavsTitle;
     bundle->FormatStringFromName(NS_LITERAL_STRING("importedBookmarksFolder").get(),
                                  sourceNameStrings, 1, getter_Copies(importedIEFavsTitle));
 
     bms->CreateFolder(root, importedIEFavsTitle, -1, &folder);
   }
   else {
+    // Initialize the default bookmarks
+    nsCOMPtr<nsIFile> profile;
+    GetProfilePath(nsnull, profile);
+    rv = InitializeBookmarks(profile);
+    NS_ENSURE_SUCCESS(rv, rv);
+
     // Locate the Links toolbar folder, we want to replace the Personal Toolbar content with 
     // Favorites in this folder. 
     nsCOMPtr<nsIWindowsRegKey> regKey = 
       do_CreateInstance("@mozilla.org/windows-registry-key;1");
     NS_NAMED_LITERAL_STRING(toolbarKey,
                             "Software\\Microsoft\\Internet Explorer\\Toolbar");
     if (regKey && 
         NS_SUCCEEDED(regKey->Open(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER,
@@ -1414,19 +1420,16 @@ nsIEProfileMigrator::ParseFavoritesFolde
                                              bookmarkName, &id);
       NS_ENSURE_SUCCESS(rv, rv);
       if (NS_FAILED(rv)) continue;
     }
     else if (isDir) {
       PRInt64 folder;
       if (bookmarkName.Equals(aPersonalToolbarFolderName)) {
         aBookmarksService->GetToolbarFolder(&folder);
-        // If we're here, it means the user's doing a _replace_ import which means
-        // clear out the content of this folder, and replace it with the new content
-        aBookmarksService->RemoveFolderChildren(folder);
       }
       else {
         rv = aBookmarksService->CreateFolder(aParentFolder,
                                              bookmarkName,
                                              nsINavBookmarksService::DEFAULT_INDEX,
                                              &folder);
         if (NS_FAILED(rv)) continue;
       }
--- a/browser/components/migration/src/nsMacIEProfileMigrator.cpp
+++ b/browser/components/migration/src/nsMacIEProfileMigrator.cpp
@@ -46,17 +46,17 @@
 #include "nsIStringBundle.h"
 #include "nsISupportsArray.h"
 #include "nsISupportsPrimitives.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIProperties.h"
 
 #define MACIE_BOOKMARKS_FILE_NAME NS_LITERAL_STRING("Favorites.html")
 #define MACIE_PREFERENCES_FOLDER_NAME NS_LITERAL_STRING("Explorer")
-#define FIREFOX_BOOKMARKS_FILE_NAME NS_LITERAL_STRING("bookmarks.html")
+#define TEMP_BOOKMARKS_FILE_NAME NS_LITERAL_STRING("bookmarks_tmp.html")
 
 #define MIGRATION_BUNDLE "chrome://browser/locale/migration/migration.properties"
 
 ///////////////////////////////////////////////////////////////////////////////
 // nsMacIEProfileMigrator
 
 NS_IMPL_ISUPPORTS1(nsMacIEProfileMigrator, nsIBrowserProfileMigrator)
 
@@ -167,60 +167,67 @@ nsMacIEProfileMigrator::GetSourceHomePag
 }
 
 ///////////////////////////////////////////////////////////////////////////////
 // nsMacIEProfileMigrator
 
 nsresult
 nsMacIEProfileMigrator::CopyBookmarks(PRBool aReplace)
 {
+  nsresult rv;
   nsCOMPtr<nsIFile> sourceFile;
   mSourceProfile->Clone(getter_AddRefs(sourceFile));
 
   sourceFile->Append(MACIE_BOOKMARKS_FILE_NAME);
   PRBool exists = PR_FALSE;
   sourceFile->Exists(&exists);
   if (!exists)
     return NS_OK;
 
-  nsCOMPtr<nsIFile> targetFile;
-  mTargetProfile->Clone(getter_AddRefs(targetFile));
-  targetFile->Append(FIREFOX_BOOKMARKS_FILE_NAME);
+  // it's an import
+  if (!aReplace)
+    return ImportBookmarksHTML(sourceFile,
+                               PR_FALSE,
+                               PR_FALSE,
+                               NS_LITERAL_STRING("sourceNameIE").get());
+
+  // Initialize the default bookmarks
+  rv = InitializeBookmarks(mTargetProfile);
+  NS_ENSURE_SUCCESS(rv, rv);
 
   // If we're blowing away existing content, annotate the Personal Toolbar and
-  // then just copy the file. 
-  if (aReplace) {
-    nsresult rv;
-
-    // Look for the localized name of the IE Favorites Bar
-    nsCOMPtr<nsIStringBundleService> bundleService =
-      do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
-    NS_ENSURE_SUCCESS(rv, rv);
+  // then import the file. 
+  nsCOMPtr<nsIFile> tempFile;
+  mTargetProfile->Clone(getter_AddRefs(tempFile));
+  tempFile->Append(TEMP_BOOKMARKS_FILE_NAME);
 
-    nsCOMPtr<nsIStringBundle> bundle;
-    rv = bundleService->CreateBundle(MIGRATION_BUNDLE, getter_AddRefs(bundle));
-    NS_ENSURE_SUCCESS(rv, rv);
+  // Look for the localized name of the IE Favorites Bar
+  nsCOMPtr<nsIStringBundleService> bundleService =
+    do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
+  NS_ENSURE_SUCCESS(rv, rv);
 
-    nsString toolbarFolderNameMacIE;
-    bundle->GetStringFromName(NS_LITERAL_STRING("toolbarFolderNameMacIE").get(), 
-                              getter_Copies(toolbarFolderNameMacIE));
-    nsCAutoString ctoolbarFolderNameMacIE;
-    CopyUTF16toUTF8(toolbarFolderNameMacIE, ctoolbarFolderNameMacIE);
+  nsCOMPtr<nsIStringBundle> bundle;
+  rv = bundleService->CreateBundle(MIGRATION_BUNDLE, getter_AddRefs(bundle));
+  NS_ENSURE_SUCCESS(rv, rv);
 
-    // If we can't find it for some reason, just copy the file. 
-    if (NS_FAILED(rv)) {
-      targetFile->Exists(&exists);
-      if (exists)
-        targetFile->Remove(PR_FALSE);
-
-      return sourceFile->CopyTo(mTargetProfile, FIREFOX_BOOKMARKS_FILE_NAME);
-    }
+  nsString toolbarFolderNameMacIE;
+  bundle->GetStringFromName(NS_LITERAL_STRING("toolbarFolderNameMacIE").get(), 
+                            getter_Copies(toolbarFolderNameMacIE));
+  nsCAutoString ctoolbarFolderNameMacIE;
+  CopyUTF16toUTF8(toolbarFolderNameMacIE, ctoolbarFolderNameMacIE);
 
-    // Now read the 4.x bookmarks file, correcting the Personal Toolbar Folder 
-    // line and writing to the new location.
-    return AnnotatePersonalToolbarFolder(sourceFile,
-                                         targetFile,
-                                         ctoolbarFolderNameMacIE.get());
-  }
+  // Now read the 4.x bookmarks file, correcting the Personal Toolbar Folder 
+  // line and writing to the temporary file.
+  rv = AnnotatePersonalToolbarFolder(sourceFile,
+                                     tempFile,
+                                     ctoolbarFolderNameMacIE.get());
+  NS_ENSURE_SUCCESS(rv, rv);
 
-  return ImportBookmarksHTML(sourceFile,
-                             NS_LITERAL_STRING("sourceNameIE").get());
+  // import the temp file
+  rv = ImportBookmarksHTML(tempFile,
+                           PR_TRUE,
+                           PR_FALSE,
+                           EmptyString().get());
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  // remove the temp file
+  return tempFile->Remove(PR_FALSE);
 }
--- a/browser/components/migration/src/nsNetscapeProfileMigratorBase.cpp
+++ b/browser/components/migration/src/nsNetscapeProfileMigratorBase.cpp
@@ -313,17 +313,17 @@ nsNetscapeProfileMigratorBase::CopyFile(
 nsresult
 nsNetscapeProfileMigratorBase::ImportNetscapeBookmarks(const nsAString& aBookmarksFileName,
                                                        const PRUnichar* aImportSourceNameKey)
 {
   nsCOMPtr<nsIFile> bookmarksFile;
   mSourceProfile->Clone(getter_AddRefs(bookmarksFile));
   bookmarksFile->Append(aBookmarksFileName);
   
-  return ImportBookmarksHTML(bookmarksFile, aImportSourceNameKey);
+  return ImportBookmarksHTML(bookmarksFile, PR_FALSE, PR_FALSE, aImportSourceNameKey);
 }
 
 nsresult
 nsNetscapeProfileMigratorBase::ImportNetscapeCookies(nsIFile* aCookiesFile)
 {
   nsresult rv;
   nsCOMPtr<nsIInputStream> cookiesStream;
   rv = NS_NewLocalFileInputStream(getter_AddRefs(cookiesStream), aCookiesFile);
--- a/browser/components/migration/src/nsOperaProfileMigrator.cpp
+++ b/browser/components/migration/src/nsOperaProfileMigrator.cpp
@@ -958,25 +958,25 @@ nsOperaCookieMigrator::ReadHeader()
     return NS_OK;
   }
   return NS_ERROR_FAILURE;
 }
 
 nsresult
 nsOperaProfileMigrator::CopyHistory(PRBool aReplace)
 {
-  nsresult rv;
-  nsCOMPtr<nsINavHistoryService> history = do_GetService(NS_NAVHISTORYSERVICE_CONTRACTID, &rv);
-  NS_ENSURE_SUCCESS(rv, rv);
- 
-  return history->RunInBatchMode(this, nsnull);
-}
- 
-NS_IMETHODIMP
-nsOperaProfileMigrator::RunBatched(nsISupports* aUserData)
+  nsresult rv;
+  nsCOMPtr<nsINavHistoryService> history = do_GetService(NS_NAVHISTORYSERVICE_CONTRACTID, &rv);
+  NS_ENSURE_SUCCESS(rv, rv);
+ 
+  return history->RunInBatchMode(this, nsnull);
+}
+ 
+NS_IMETHODIMP
+nsOperaProfileMigrator::RunBatched(nsISupports* aUserData)
 {
   nsCOMPtr<nsIBrowserHistory> hist(do_GetService(NS_GLOBALHISTORY2_CONTRACTID));
 
   nsCOMPtr<nsIFile> temp;
   mOperaProfile->Clone(getter_AddRefs(temp));
   nsCOMPtr<nsILocalFile> historyFile(do_QueryInterface(temp));
   historyFile->Append(OPERA_HISTORY_FILE_NAME);
 
@@ -1047,17 +1047,17 @@ nsOperaProfileMigrator::CopyBookmarks(PR
   nsCOMPtr<nsILineInputStream> lineInputStream(do_QueryInterface(fileInputStream));
 
   nsresult rv;
   nsCOMPtr<nsINavBookmarksService> bms(do_GetService(NS_NAVBOOKMARKSSERVICE_CONTRACTID, &rv));
   NS_ENSURE_SUCCESS(rv, rv);
   PRInt64 root;
   rv = bms->GetBookmarksRoot(&root);
   NS_ENSURE_SUCCESS(rv, rv);
-  PRInt64 parentFolder;
+  PRInt64 parentFolder = root;
 
   nsCOMPtr<nsIStringBundleService> bundleService(do_GetService(NS_STRINGBUNDLE_CONTRACTID));
   nsCOMPtr<nsIStringBundle> bundle;
   bundleService->CreateBundle(MIGRATION_BUNDLE, getter_AddRefs(bundle));
   if (!aReplace) {
     nsString sourceNameOpera;
     bundle->GetStringFromName(NS_LITERAL_STRING("sourceNameOpera").get(), 
                               getter_Copies(sourceNameOpera));
@@ -1066,18 +1066,22 @@ nsOperaProfileMigrator::CopyBookmarks(PR
     nsString importedOperaHotlistTitle;
     bundle->FormatStringFromName(NS_LITERAL_STRING("importedBookmarksFolder").get(),
                                  sourceNameStrings, 1, 
                                  getter_Copies(importedOperaHotlistTitle));
 
     bms->CreateFolder(parentFolder, importedOperaHotlistTitle,
                       nsINavBookmarksService::DEFAULT_INDEX, &parentFolder);
   }
-  else
-    parentFolder = root;
+  else {
+    nsCOMPtr<nsIFile> profile;
+    GetProfilePath(nsnull, profile);
+    rv = InitializeBookmarks(profile);
+    NS_ENSURE_SUCCESS(rv, rv);
+  }
 
 #if defined(XP_WIN) || (defined(XP_UNIX) && !defined(XP_MACOSX))
   printf("*** about to copy smart keywords\n");
   CopySmartKeywords(bms, bundle, parentFolder);
   printf("*** done copying smart keywords\n");
 #endif
 
   PRInt64 toolbar;
--- a/browser/components/migration/src/nsPhoenixProfileMigrator.cpp
+++ b/browser/components/migration/src/nsPhoenixProfileMigrator.cpp
@@ -418,16 +418,17 @@ nsPhoenixProfileMigrator::CopyPasswords(
 
   NS_ConvertASCIItoUTF16 fileName(signonsFileName);
   return aReplace ? CopyFile(fileName, fileName) : NS_OK;
 }
 
 nsresult
 nsPhoenixProfileMigrator::CopyBookmarks(PRBool aReplace)
 {
+  // This overwrites the defaults. This might be ok in this instance.
   return aReplace ? CopyFile(FILE_NAME_BOOKMARKS, FILE_NAME_BOOKMARKS) : NS_OK;
 }
 
 nsresult
 nsPhoenixProfileMigrator::CopyOtherData(PRBool aReplace)
 {
   if (!aReplace)
     return NS_OK;
--- a/browser/components/migration/src/nsSafariProfileMigrator.cpp
+++ b/browser/components/migration/src/nsSafariProfileMigrator.cpp
@@ -894,17 +894,17 @@ nsSafariProfileMigrator::RunBatched(nsIS
 
   return NS_OK;
 }
 
 nsresult
 nsSafariProfileMigrator::CopyBookmarks(PRBool aReplace)
 {
   // If "aReplace" is true, merge into the root level of bookmarks. Otherwise, create
-  // a folder called "Imported IE Favorites" and place all the Bookmarks there.
+  // a folder called "Imported Safari Favorites" and place all the Bookmarks there.
   nsresult rv;
 
   nsCOMPtr<nsINavBookmarksService> bms(do_GetService(NS_NAVBOOKMARKSSERVICE_CONTRACTID, &rv));
   NS_ENSURE_SUCCESS(rv, rv);
   PRInt64 root;
   rv = bms->GetBookmarksRoot(&root);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -925,17 +925,21 @@ nsSafariProfileMigrator::CopyBookmarks(P
     bundle->FormatStringFromName(NS_LITERAL_STRING("importedBookmarksFolder").get(),
                                  sourceNameStrings, 1,
                                  getter_Copies(importedSafariBookmarksTitle));
 
     bms->CreateFolder(root, importedSafariBookmarksTitle, nsINavBookmarksService::DEFAULT_INDEX,
                       &folder);
   }
   else {
-    // In non-replace mode we are merging at the top level.
+    nsCOMPtr<nsIFile> profile;
+    GetProfilePath(nsnull, profile);
+    rv = InitializeBookmarks(profile);
+    NS_ENSURE_SUCCESS(rv, rv);
+    // In replace mode we are merging at the top level.
     folder = root;
   }
 
   nsCOMPtr<nsIProperties> fileLocator(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID));
   nsCOMPtr<nsILocalFile> safariBookmarksFile;
   fileLocator->Get(NS_MAC_USER_LIB_DIR, NS_GET_IID(nsILocalFile),
                    getter_AddRefs(safariBookmarksFile));
   safariBookmarksFile->Append(NS_LITERAL_STRING("Safari"));
--- a/browser/components/migration/src/nsSeamonkeyProfileMigrator.cpp
+++ b/browser/components/migration/src/nsSeamonkeyProfileMigrator.cpp
@@ -718,18 +718,21 @@ nsSeamonkeyProfileMigrator::CopyPassword
     NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, hostnames);
   }
   return rv;
 }
 
 nsresult
 nsSeamonkeyProfileMigrator::CopyBookmarks(PRBool aReplace)
 {
-  if (aReplace)
+  if (aReplace) {
+    nsresult rv = InitializeBookmarks(mTargetProfile);
+    NS_ENSURE_SUCCESS(rv, rv);
     return CopyFile(FILE_NAME_BOOKMARKS, FILE_NAME_BOOKMARKS);
+  }
   return ImportNetscapeBookmarks(FILE_NAME_BOOKMARKS, 
                                  NS_LITERAL_STRING("sourceNameSeamonkey").get());
 }
 
 nsresult
 nsSeamonkeyProfileMigrator::CopyOtherData(PRBool aReplace)
 {
   return aReplace ? CopyFile(FILE_NAME_DOWNLOADS, FILE_NAME_DOWNLOADS) : NS_OK;
--- a/browser/components/nsBrowserContentHandler.js
+++ b/browser/components/nsBrowserContentHandler.js
@@ -817,16 +817,23 @@ var Module = {
 
     if (cid.equals(dch_CID))
       return nsDefaultCommandLineHandler.QueryInterface(iid);
 
     throw Components.results.NS_ERROR_NO_INTERFACE;
   },
     
   registerSelf: function mod_regself(compMgr, fileSpec, location, type) {
+    // Don't register these if Firefox is launching a XULRunner application
+    const FIREFOX_UID = "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}";
+    var appInfo = Components.classes["@mozilla.org/xre/app-info;1"]
+                            .getService(Components.interfaces.nsIXULAppInfo);
+    if (appInfo.ID != FIREFOX_UID)
+      return;
+
     var compReg =
       compMgr.QueryInterface( Components.interfaces.nsIComponentRegistrar );
 
     compReg.registerFactoryLocation( bch_CID,
                                      "nsBrowserContentHandler",
                                      bch_contractID,
                                      fileSpec,
                                      location,
--- a/browser/components/places/content/controller.js
+++ b/browser/components/places/content/controller.js
@@ -440,16 +440,17 @@ PlacesController.prototype = {
     }
   },
 
   /** 
    * Gathers information about the selected nodes according to the following
    * rules:
    *    "link"              node is a URI
    *    "bookmark"          node is a bookamrk
+   *    "livemarkChild"     node is a child of a livemark
    *    "folder"            node is a folder
    *    "query"             node is a query
    *    "dynamiccontainer"  node is a dynamic container
    *    "separator"         node is a separator line
    *    "host"              node is a host
    *    "mutable"           node can have items inserted or reordered
    *    "allLivemarks"      node is a query containing every livemark
    *    
@@ -501,16 +502,19 @@ PlacesController.prototype = {
         case Ci.nsINavHistoryResultNode.RESULT_TYPE_FULL_VISIT:
           nodeData["link"] = true;
           uri = PlacesUtils._uri(node.uri);
           if (PlacesUtils.nodeIsBookmark(node)) {
             nodeData["bookmark"] = true;
             var mss = PlacesUtils.microsummaries;
             if (mss.hasMicrosummary(node.itemId))
               nodeData["microsummary"] = true;
+            else if (node.parent &&
+                     PlacesUtils.nodeIsLivemarkContainer(node.parent))
+              nodeData["livemarkChild"] = true;
           }
           break;
         case Ci.nsINavHistoryResultNode.RESULT_TYPE_DAY:
           nodeData["day"] = true;
       }
 
       // Mutability is whether or not a container can have selected items
       // inserted or reordered. It does _not_ dictate whether or not the 
--- a/browser/components/places/content/editBookmarkOverlay.js
+++ b/browser/components/places/content/editBookmarkOverlay.js
@@ -343,17 +343,17 @@ var gEditItemOverlay = {
     if (aHideCollapsibleElements) {
       // hide the folder tree if it was previously visible
       if (!this._folderTree.collapsed)
         this.toggleFolderTreeVisibility();
 
       // hide the tag selector if it was previously visible
       var tagsSelector = this._element("tagsSelector");
       if (!tagsSelector.collapsed)
-        tagsSelector.collapsed = true;
+        this._toggleTagsSelector();
     }
 
     if (this._observersAdded) {
       PlacesUtils.bookmarks.removeObserver(this);
       this._observersAdded = false;
     }
     if (this._microsummaries) {
       this._microsummaries.removeObserver(this);
@@ -542,34 +542,28 @@ var gEditItemOverlay = {
       // "All Bookmarks" root
       if (container != PlacesUtils.placesRootId)
         this._markFolderAsRecentlyUsed(container);
     }
 
     // Update folder-tree selection
     if (isElementVisible(this._folderTree)) {
       var selectedNode = this._folderTree.selectedNode;
-      if (selectedNode.itemId != container)
+      if (!selectedNode || selectedNode.itemId != container)
         this._folderTree.selectFolders([container]);
     }
   },
 
   onFolderTreeSelect: function EIO_onFolderTreeSelect() {
     var selectedNode = this._folderTree.selectedNode;
     if (!selectedNode)
       return;
 
     var folderId = selectedNode.itemId;
-    // Don't set the selected item if the static item for the folder is
-    // already selected
-    var oldSelectedItem = this._folderMenuList.selectedItem;
-    if ((oldSelectedItem.id == "editBMPanel_toolbarFolderItem" &&
-         folderId == PlacesUtils.toolbarFolderId) ||
-        (oldSelectedItem.id == "editBMPanel_bmRootItem" &&
-         folderId == PlacesUtils.bookmarksRootId))
+    if (this._getFolderIdFromMenuList() == folderId)
       return;
 
     var folderItem = this._getFolderMenuItem(folderId, false);
     this._folderMenuList.selectedItem = folderItem;
     folderItem.doCommand();
   },
 
   _markFolderAsRecentlyUsed:
@@ -600,19 +594,19 @@ var gEditItemOverlay = {
       tagsSelector.appendChild(elt);
     }
   },
 
   toggleTagsSelector: function EIO_toggleTagsSelector() {
     var tagsSelector = this._element("tagsSelector");
     var expander = this._element("tagsSelectorExpander");
     if (!isElementVisible(tagsSelector)) {
-      expander.className = "expander-down";
+      expander.className = "expander-up";
       expander.setAttribute("tooltiptext",
-                            expander.getAttribute("tooltiptextdown"));
+                            expander.getAttribute("tooltiptextup"));
 
       this._rebuildTagsSelectorList();
 
       // This is a no-op if we've added the listener.
       tagsSelector.addEventListener("CheckboxStateChange", this, false);
     }
     else {
       expander.className = "expander-down";
--- a/browser/components/places/content/editBookmarkOverlay.xul
+++ b/browser/components/places/content/editBookmarkOverlay.xul
@@ -69,22 +69,24 @@
               <menuitem id="editBMPanel_userEnteredName"/>
               <menuitem disabled="true">
                 <menuseparator flex="1"/>
                 <label value="&editBookmarkOverlay.liveTitlesSeparator.label;"/>
               </menuitem>
             </menupopup>
           </menulist>
         </row>
+
         <row align="center" id="editBMPanel_locationRow">
           <label value="&editBookmarkOverlay.location.label;"
                  contorl="editBMPanel_locationField"/>
           <textbox id="editBMPanel_locationField"
                    onblur="gEditItemOverlay.onLocationFieldBlur();"/>
         </row>
+
         <row align="center" id="editBMPanel_folderRow">
           <label value="&editBookmarkOverlay.folder.label;"
                  control="editBMPanel_folderMenuList"/>
           <menulist id="editBMPanel_folderMenuList"
                     class="folder-icon"
                     oncommand="gEditItemOverlay.onFolderMenuListCommand();">
             <menupopup>
               <!-- Static item for special folders -->
@@ -102,47 +104,46 @@
           </menulist>
           <button id="editBMPanel_foldersExpander"
                   class="expander-down"
                   tooltiptext="&editBookmarkOverlay.foldersExpanderDown.tooltip;"
                   tooltiptextdown="&editBookmarkOverlay.foldersExpanderDown.tooltip;"
                   tooltiptextup="&editBookmarkOverlay.expanderUp.tooltip;"
                   oncommand="gEditItemOverlay.toggleFolderTreeVisibility();"/>
         </row>
+
         <tree id="editBMPanel_folderTree"
               class="placesTree"
               type="places"
               height="150"
               collapsed="true"
               onselect="gEditItemOverlay.onFolderTreeSelect();"
               showRoot="true"
               place="place:folder=2&amp;group=3&amp;excludeItems=1&amp;excludeQueries=1&amp;excludeReadOnlyFolders=1"
               hidecolumnpicker="true">
           <treecols>
             <treecol anonid="title" flex="1" primary="true" hideheader="true"/>
           </treecols>
           <treechildren flex="1"/>
         </tree>
+
         <row align="center" id="editBMPanel_tagsRow">
           <label value="&editBookmarkOverlay.tags.label;"
                  control="tagsField"/>
           <textbox id="editBMPanel_tagsField"
                    onblur="gEditItemOverlay.onTagsFieldBlur();"/>
           <button id="editBMPanel_tagsSelectorExpander"
                   class="expander-down"
                   tooltiptext="&editBookmarkOverlay.tagsExpanderDown.tooltip;"
                   tooltiptextdown="&editBookmarkOverlay.tagsExpanderDown.tooltip;"
                   tooltiptextup="&editBookmarkOverlay.expanderUp.tooltip;"
                   oncommand="gEditItemOverlay.toggleTagsSelector();"/>
         </row>
 
-        <!-- XXX: Temporary workaround -->
-        </rows></grid>
         <listbox id="editBMPanel_tagsSelector" height="150" collapsed="true"/>
-        <grid flex="1"><columns><column/><column flex="1"/></columns><rows>
 
         <row id="editBMPanel_descriptionRow" align="center">
           <label value="&editBookmarkOverlay.description.label;"
                  control="editBMPanel_descriptionField"/>
           <textbox id="editBMPanel_descriptionField"
                    onblur="gEditItemOverlay.onDescriptionFieldBlur();"/>
         </row>
       </rows>
--- a/browser/components/places/content/places.js
+++ b/browser/components/places/content/places.js
@@ -1031,35 +1031,38 @@ var ViewMenu = {
     var columns = content.columns;
     for (var i = 0; i < columns.count; ++i) {
       var column = columns.getColumnAt(i).element;
       var menuitem = document.createElementNS(XUL_NS, "menuitem");
       menuitem.id = "menucol_" + column.id;
       menuitem.setAttribute("column", column.id);
       var label = column.getAttribute("label");
       if (propertyPrefix) {
-        var menuitemPrefix = propertyPrefix + column.id;
+        var menuitemPrefix = propertyPrefix;
+        // for string properties, use "name" as the id, instead of "title"
+        // see bug #386287 for details
+        menuitemPrefix += (column.id == "title" ? "name" : column.id);
         label = PlacesUtils.getString(menuitemPrefix + ".label");
         var accesskey = PlacesUtils.getString(menuitemPrefix + ".accesskey");
         menuitem.setAttribute("accesskey", accesskey);
       }
       menuitem.setAttribute("label", label);
       if (type == "radio") {
         menuitem.setAttribute("type", "radio");
         menuitem.setAttribute("name", "columns");
         // This column is the sort key. Its item is checked. 
         if (column.getAttribute("sortDirection") != "") {
           menuitem.setAttribute("checked", "true");
           isSorted = true;
         }
       }
       else if (type == "checkbox") {
         menuitem.setAttribute("type", "checkbox");
-        // Cannot uncheck the primary column. 
-        if (column.primary)
+        // Cannot uncheck the primary column.
+        if (column.getAttribute("primary") == "true")
           menuitem.setAttribute("disabled", "true");
         // Items for visible columns are checked. 
         if (!column.hidden)
           menuitem.setAttribute("checked", "true");
       }
       if (pivot)
         popup.insertBefore(menuitem, pivot);
       else
--- a/browser/components/places/content/places.xul
+++ b/browser/components/places/content/places.xul
@@ -373,17 +373,17 @@
           </hbox>
 #include advancedSearch.inc          
           <tree id="placeContent" class="placesTree" context="placesContext" 
                 flex="1" type="places" 
                 ondblclick="this.controller.openSelectedNodeWithEvent(event);"
                 onclick="PlacesOrganizer.onTreeClick(event);"
                 onselect="PlacesOrganizer.updateStatusBarForView(this);">
             <treecols id="placeContentColumns">
-              <treecol label="&col.title.label;" id="title" flex="5" primary="true" 
+              <treecol label="&col.name.label;" id="title" flex="5" primary="true" 
                        persist="width hidden ordinal sortActive sortDirection"/>
               <splitter class="tree-splitter"/>
               <treecol label="&col.tags.label;" id="tags" flex="2"
                        persist="width hidden ordinal sortActive sortDirection"/>
               <splitter class="tree-splitter"/>
               <treecol label="&col.url.label;" id="url" flex="5" 
                        persist="width hidden ordinal sortActive sortDirection"/>
               <splitter class="tree-splitter"/>
--- a/browser/components/places/content/placesOverlay.xul
+++ b/browser/components/places/content/placesOverlay.xul
@@ -143,59 +143,64 @@
               command="placesCmd_new:folder"
               label="&cmd.new_folder.label;"
               accesskey="&cmd.context_new_folder.accesskey;"
               selection="mutable"/>
     <menuitem id="placesContext_new:separator"
               command="placesCmd_new:separator"
               label="&cmd.new_separator.label;"
               accesskey="&cmd.new_separator.accesskey;"
+              closemenu="single"
               selection="mutable"/>
     <menuseparator id="placesContext_newSeparator"/>
     <menuitem id="placesContext_cut"
-               command="cmd_cut"
-               label="&cutCmd.label;"
-               accesskey="&cutCmd.accesskey;" 
-               selection="separator|link|folder|mixed"
-               forcehideselection="livemark/bookmarkFeedURI"/>
+              command="cmd_cut"
+              label="&cutCmd.label;"
+              accesskey="&cutCmd.accesskey;" 
+              selection="separator|link|folder|mixed"
+              forcehideselection="livemarkChild"/>
     <menuitem id="placesContext_copy"
               command="cmd_copy"
               label="&copyCmd.label;"
               accesskey="&copyCmd.accesskey;" 
               selection="separator|link|folder"/>
     <menuitem id="placesContext_paste"
               command="cmd_paste"
               label="&pasteCmd.label;"
               accesskey="&pasteCmd.accesskey;"
               selection="mutable"/>
     <menuseparator id="placesContext_editSeparator"/>
     <menuitem id="placesContext_delete"
               command="cmd_delete"
               label="&deleteCmd.label;"
               accesskey="&deleteCmd.accesskey;"
+              closemenu="single"
               selection="host|separator|link|folder|day"
-              forcehideselection="livemark/bookmarkFeedURI"/>
+              forcehideselection="livemarkChild"/>
     <menuseparator id="placesContext_deleteSeparator"/>
     <menuitem id="placesContext_reload"
               command="placesCmd_reload"
               label="&cmd.reloadLivebookmark.label;"
               accesskey="&cmd.reloadLivebookmark.accesskey;"
+              closemenu="single"
               selection="livemark/feedURI|allLivemarks"/>
     <menuitem id="placesContext_reloadMicrosummary"
               command="placesCmd_reloadMicrosummary"
               label="&cmd.reloadMicrosummary.label;"
               accesskey="&cmd.reloadMicrosummary.accesskey;"
+              closemenu="single"
               selection="microsummary"/>
     <menuitem id="placesContext_sortBy:name"
               command="placesCmd_sortBy:name"
               label="&cmd.sortby_name.label;"
               accesskey="&cmd.context_sortby_name.accesskey;"
+              closemenu="single"
               selection="mutable"/>
     <menuseparator id="placesContext_sortSeparator"/>
     <menuitem id="placesContext_show:info"
               command="placesCmd_show:info"
               label="&cmd.properties.label;" 
               accesskey="&cmd.properties.accesskey;"
               selection="bookmark|folder"
-              forcehideselection="livemark/bookmarkFeedURI"/>
+              forcehideselection="livemarkChild"/>
   </popup>
 
 </overlay>
--- a/browser/components/places/content/utils.js
+++ b/browser/components/places/content/utils.js
@@ -385,41 +385,35 @@ var PlacesUtils = {
   nodeIsDynamicContainer: function PU_nodeIsDynamicContainer(aNode) {
     NS_ASSERT(aNode, "null node");
     if (aNode.type == NHRN.RESULT_TYPE_DYNAMIC_CONTAINER)
       return true;
     return false;
   },
 
  /**
-  * Determines whether a ResultNode is a remote container registered by the
+  * Determines whether a result node is a remote container registered by the
   * livemark service.
   * @param aNode
-  *        A NavHistory Result Node
+  *        A result Node
   * @returns true if the node is a livemark container item
   */
   nodeIsLivemarkContainer: function PU_nodeIsLivemarkContainer(aNode) {
     return this.nodeIsFolder(aNode) &&
            this.annotations.itemHasAnnotation(aNode.itemId, "livemark/feedURI");
   },
 
  /**
-  * Determines whether a ResultNode is a live-bookmark item
+  * Determines whether a result node is a live-bookmark item
   * @param aNode
-  *        A NavHistory Result Node
+  *        A result node
   * @returns true if the node is a livemark container item
   */
   nodeIsLivemarkItem: function PU_nodeIsLivemarkItem(aNode) {
-    if (this.nodeIsBookmark(aNode)) {
-      if (this.annotations
-              .itemHasAnnotation(aNode.itemId, "livemark/bookmarkFeedURI"))
-        return true;
-    }
-
-    return false;
+    return aNode.parent && this.nodeIsLivemarkContainer(aNode.parent);
   },
 
   /**
    * Determines whether or not a node is a readonly folder.
    * @param   aNode
    *          The node to test.
    * @returns true if the node is a readonly folder.
   */
@@ -1496,28 +1490,30 @@ var PlacesUtils = {
   getItemDescription: function PU_getItemDescription(aItemId) {
     if (this.annotations.itemHasAnnotation(aItemId, DESCRIPTION_ANNO))
       return this.annotations.getItemAnnotation(aItemId, DESCRIPTION_ANNO);
     return "";
   },
 
   /**
    * Get the most recently added/modified bookmark for a URL, excluding items
-   * under tag containers. -1 is returned if no item is found.
+   * under tag or livemark containers. -1 is returned if no item is found.
    */
   getMostRecentBookmarkForURI:
   function PU_getMostRecentBookmarkForURI(aURI) {
     var bmkIds = this.bookmarks.getBookmarkIdsForURI(aURI, {});
     for each (var bk in bmkIds) {
       // Find the first folder which isn't a tag container
       var folder = this.bookmarks.getFolderIdForItem(bk);
-      if (folder == this.placesRootId ||
-        this.bookmarks.getFolderIdForItem(folder) != this.tagRootId) {
+      if (folder == this.placesRootId)
         return bk;
-      }
+      var parent = this.bookmarks.getFolderIdForItem(folder)
+      if (parent != this.tagRootId &&
+          !this.annotations.itemHasAnnotation(parent, "livemark/feedURI"))
+        return bk;
     }
     return -1;
   }
 };
 
 PlacesUtils.GENERIC_VIEW_DROP_TYPES = [PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER,
                                        PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR,
                                        PlacesUtils.TYPE_X_MOZ_PLACE,
--- a/browser/components/preferences/main.js
+++ b/browser/components/preferences/main.js
@@ -175,36 +175,36 @@ var gMainPane = {
    *   True if the Download Manager should be opened when a download is
    *   started, false if it shouldn't be opened.
    * browser.download.closeWhenDone - bool
    *   True if the Download Manager should be closed when all downloads
    *   complete, false if it should be left open.
    * browser.download.useDownloadDir - bool
    *   True if downloads are saved with no save-as UI shown, false if
    *   the user should always be asked where to save a file.
-   * browser.download.dir - str path
-   *   A local path the user may have selected for downloaded files to be
+   * browser.download.dir - local file handle
+   *   A local folder the user may have selected for downloaded files to be
    *   saved. Migration of other browser settings may also set this path.
-   *   This path is enabled when folderList is equals 2.
-   * browser.download.lastDir - str path
+   *   This folder is enabled when folderList equals 2.
+   * browser.download.lastDir - local file handle
    *   May contain the last folder path accessed when the user browsed
    *   via the file save-as dialog. (see contentAreaUtils.js)
    * browser.download.folderList - int
    *   Indicates the location users wish to save downloaded files too.
    *   It is also used to display special file labels when the default
    *   download location is either the Desktop or the Downloads folder.
    *   Values:
    *     0 - The desktop is the default download location.
    *     1 - The system's downloads folder is the default download location.
    *     2 - The default download location is elsewhere as specified in
    *         browser.download.dir.
    * browser.download.downloadDir
    *   depreciated.
-   * browser.download.defaultFolder
-   *   depreciated.
+   * browser.download.defaultFolder
+   *   depreciated.
    */
 
   /**
    * Updates preferences which depend upon the value of the preference which
    * determines whether the Downloads manager is opened at the start of a
    * download.
    */
   readShowDownloadsWhenStarting: function ()
@@ -293,27 +293,27 @@ var gMainPane = {
    */
   displayDownloadDirPref: function ()
   {
     var folderListPref = document.getElementById("browser.download.folderList");
     var bundlePreferences = document.getElementById("bundlePreferences");
     var downloadFolder = document.getElementById("downloadFolder");
     var currentDirPref = document.getElementById("browser.download.dir");
 
-    // The user's download folder is based on the preferences listed above.
-    // However, if the system does not support a download folder, the
-    // actual path returned will be the system's desktop or home folder.
-    // If this is the case, skip off displaying the Download label and
-    // display Desktop, even though folderList might be 1.
-    var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"]
-                                .getService(Components.interfaces.nsIProperties);
-    var desk = fileLocator.get("Desk", Components.interfaces.nsILocalFile);
-    var dnldMgr = Components.classes["@mozilla.org/download-manager;1"]
-                            .getService(Components.interfaces.nsIDownloadManager);
-    var supportDownloadLabel = !dnldMgr.defaultDownloadsDirectory.equals(desk);
+    // The user's download folder is based on the preferences listed above.
+    // However, if the system does not support a download folder, the
+    // actual path returned will be the system's desktop or home folder.
+    // If this is the case, skip off displaying the Download label and
+    // display Desktop, even though folderList might be 1.
+    var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"]
+                                .getService(Components.interfaces.nsIProperties);
+    var desk = fileLocator.get("Desk", Components.interfaces.nsILocalFile);
+    var dnldMgr = Components.classes["@mozilla.org/download-manager;1"]
+                            .getService(Components.interfaces.nsIDownloadManager);
+    var supportDownloadLabel = !dnldMgr.defaultDownloadsDirectory.equals(desk);
 
     // Used in defining the correct path to the folder icon.
     var ios = Components.classes["@mozilla.org/network/io-service;1"]
                         .getService(Components.interfaces.nsIIOService);
     var fph = ios.getProtocolHandler("file")
                  .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
     var iconUrlSpec;
       
@@ -439,16 +439,35 @@ var gMainPane = {
         if (currentDirPref.value) {
           // Resolve to a known location if possible. We are writing out
           // to prefs on this call, so now would be a good time to do it.
           return this._folderToIndex(currentDirPref.value);
         }
         return 0;
       break;
     }
+  },
+
+  /**
+   * Displays the Add-ons Manager.
+   */
+  showAddonsMgr: function ()
+  {
+    const EMTYPE = "Extension:Manager";
+    var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
+                       .getService(Components.interfaces.nsIWindowMediator);
+    var theEM = wm.getMostRecentWindow(EMTYPE);
+    if (theEM) {
+      theEM.focus();
+      return;
+    }
+
+    const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
+    const EMFEATURES = "chrome,menubar,extra-chrome,toolbar,dialog=no,resizable";
+    window.openDialog(EMURL, "", EMFEATURES);
   }
 
 #ifdef HAVE_SHELL_SERVICE
   ,
 
   // SYSTEM DEFAULTS
 
   /*
--- a/browser/components/preferences/main.xul
+++ b/browser/components/preferences/main.xul
@@ -85,17 +85,17 @@
                   name="browser.download.manager.closeWhenDone"
                   type="bool"/>
       <preference id="browser.download.useDownloadDir"
                   name="browser.download.useDownloadDir"
                   type="bool"/>
       <preference id="browser.download.dir"
                   name="browser.download.dir"
                   type="file"
-                  onchange="gMainPane.readDownloadDirPref();"/>
+                  onchange="gMainPane.displayDownloadDirPref();"/>
       <preference id="browser.download.folderList"        name="browser.download.folderList"        type="int"/>
 
       <!-- SYSTEM DEFAULTS -->
       <preference id="browser.shell.checkDefaultBrowser"
                   name="browser.shell.checkDefaultBrowser"
                   type="bool"/>
 
       <preference id="pref.general.disable_button.default_browser"
@@ -157,17 +157,17 @@
       <checkbox id="showWhenDownloading" label="&showWhenDownloading.label;"
                 accesskey="&showWhenDownloading.accesskey;"
                 preference="browser.download.manager.showWhenStarting"
                 onsyncfrompreference="return gMainPane.readShowDownloadsWhenStarting();"/>
       <checkbox id="closeWhenDone" label="&closeWhenDone.label;"
                 accesskey="&closeWhenDone.accesskey;" class="indent"
                 preference="browser.download.manager.closeWhenDone"/>
 
-      <separator/>
+      <separator class="thin"/>
 
       <radiogroup id="saveWhere"
                   preference="browser.download.useDownloadDir"
                   onsyncfrompreference="return gMainPane.readUseDownloadDir();">
         <hbox id="saveToRow">
           <radio id="saveTo" value="true"
                  label="&saveTo.label;"
                  accesskey="&saveTo.accesskey;"
@@ -198,20 +198,35 @@
 #ifdef HAVE_SHELL_SERVICE
     <!-- System Defaults -->
     <groupbox id="systemDefaultsGroup" orient="horizontal">
       <caption label="&systemDefaults.label;"/>
 
       <hbox id="checkDefaultBox" align="center" flex="1">      
         <checkbox id="alwaysCheckDefault" preference="browser.shell.checkDefaultBrowser"
                   label="&alwaysCheckDefault.label;" accesskey="&alwaysCheckDefault.accesskey;"
-                  flex="1" style="height: &alwaysCheckDefault.height;"/>
+                  flex="1"/>
         <button id="checkDefaultButton"
                 label="&checkNow.label;" accesskey="&checkNow.accesskey;"
                 oncommand="gMainPane.checkNow()"
                 preference="pref.general.disable_button.default_browser"/>
       </hbox>
     </groupbox>
 #endif
+    <hbox class="bottomBox">
+      <groupbox id="addonsMgrGroup" orient="horizontal" flex="1">
+        <caption label="&addonsMgr.label;"/>
+
+        <description control="manageAddons"
+#ifdef XP_WIN
+                     flex="1">&manageAddonsDesc.label;</description>
+#else
+                     flex="1">&manageAddonsDescUnix.label;</description>
+#endif
+        <button id="manageAddons" label="&manageAddons.label;"
+                accesskey="&manageAddons.accesskey;"
+                oncommand="gMainPane.showAddonsMgr();"/>
+      </groupbox>
+    </hbox>
 
   </prefpane>
 
 </overlay>
--- a/browser/components/preferences/security.xul
+++ b/browser/components/preferences/security.xul
@@ -158,24 +158,23 @@
         <button id="showPasswords"
                 label="&showPasswords.label;" accesskey="&showPasswords.accesskey;"
                 oncommand="gSecurityPane.showPasswords();"
                 preference="pref.privacy.disable_button.view_passwords"/>
       </hbox>
     </groupbox>
 
     <!-- Warning Messages -->
-    <groupbox id="warningMessagesGroup">
-      <caption label="&warnings.label;"/>
+    <hbox class="bottomBox">
+      <groupbox id="warningMessagesGroup" orient="horizontal" flex="1">
+        <caption label="&warnings.label;"/>
 
-      <hbox id="chooseWarningsBox" align="center">
         <description control="warningSettings" flex="1">&chooseWarnings.label;</description>
         <button id="warningSettings"
                 label="&warningSettings.label;"
                 accesskey="&warningSettings.accesskey;"
                 oncommand="gSecurityPane.showWarningMessageSettings();"/>
-      </hbox>
-      <separator/>
-    </groupbox>
+      </groupbox>
+    </hbox>
 
   </prefpane>
 
 </overlay>
--- a/browser/components/sessionstore/src/nsSessionStore.js
+++ b/browser/components/sessionstore/src/nsSessionStore.js
@@ -95,19 +95,16 @@ const WINDOW_HIDEABLE_FEATURES = [
 docShell capabilities to (re)store
 Restored in restoreHistory()
 eg: browser.docShell["allow" + aCapability] = false;
 */
 const CAPABILITIES = [
   "Subframes", "Plugins", "Javascript", "MetaRedirects", "Images"
 ];
 
-// sandbox to evaluate JavaScript code from non-trustable sources
-var EVAL_SANDBOX = new Cu.Sandbox("about:blank");
-
 // module for JSON conversion (needed for the nsISessionStore API)
 Cu.import("resource://gre/modules/JSON.jsm");
 
 function debug(aMsg) {
   aMsg = ("SessionStore: " + aMsg).replace(/\S{80}/g, "$&\n");
   Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService)
                                      .logStringMessage(aMsg);
 }
@@ -1625,51 +1622,19 @@ SessionStoreService.prototype = {
       catch (ex) { Cu.reportError(ex); } // don't let a single cookie stop recovering
     }
   },
 
   /**
    * Restart incomplete downloads
    */
   retryDownloads: function sss_retryDownloads() {
-    var ioService = Cc["@mozilla.org/network/io-service;1"].
-                    getService(Ci.nsIIOService);
+    // The download manager cleans up after itself when it is created.
     var dlManager = Cc["@mozilla.org/download-manager;1"].
                     getService(Ci.nsIDownloadManager);
-    
-    function AsyncDownloadRetrier(aDlId) {
-      this._dlId = aDlId;
-      this._dlManager = dlManager;
-    }
-    AsyncDownloadRetrier.prototype = {
-      onStartRequest: function(aRequest, aContext) { },
-      onStopRequest: function(aRequest, aContext, aStatus) {
-        if (Components.isSuccessCode(aStatus))
-          this._dlManager.retryDownload(this._dlId);
-      }
-    };
-    
-    var stmt = dlManager.DBConnection.
-                         createStatement("SELECT id, source " +
-                                         "FROM moz_downloads " +
-                                         "WHERE state = ?1");
-    stmt.bindInt32Parameter(0, Ci.nsIDownloadManager.DOWNLOAD_DOWNLOADING);
-
-    // restart all downloads that were in progress before the crash
-    // and which are currently available through the network
-    while (stmt.executeStep()) {
-      var dlId = stmt.getInt64(0);
-      var url = stmt.getUTF8String(1);
-      
-      var linkChecker = Cc["@mozilla.org/network/urichecker;1"].
-                        createInstance(Ci.nsIURIChecker);
-      linkChecker.init(ioService.newURI(url, null, null));
-      linkChecker.loadFlags = Ci.nsIRequest.LOAD_BACKGROUND;
-      linkChecker.asyncCheck(new AsyncDownloadRetrier(dlId), null);
-    }
   },
 
 /* ........ Disk Access .............. */
 
   /**
    * save state delayed by N ms
    * marks window as dirty (i.e. data update can't be skipped)
    * @param aWindow
@@ -1908,17 +1873,17 @@ SessionStoreService.prototype = {
     }
     catch (ex) { debug(ex); }
   },
 
   /**
    * safe eval'ing
    */
   _safeEval: function sss_safeEval(aStr) {
-    return Cu.evalInSandbox(aStr, EVAL_SANDBOX);
+    return Cu.evalInSandbox(aStr, new Cu.Sandbox("about:blank"));
   },
 
   /**
    * Converts a JavaScript object into a JSON string
    * (see http://www.json.org/ for more information).
    *
    * The inverse operation consists of eval("(" + JSON_string + ")");
    * and should be provably safe.
--- a/browser/components/shell/src/Makefile.in
+++ b/browser/components/shell/src/Makefile.in
@@ -78,22 +78,18 @@ REQUIRES += mozgnome
 endif
 endif
 endif
 
 ifdef CPPSRCS
 LIBRARY_NAME = shellservice_s
 endif
 
+EXTRA_COMPONENTS = nsSetDefaultBrowser.js
+
 include $(topsrcdir)/config/rules.mk
 
 DEFINES += -DMOZ_APP_NAME=\"$(MOZ_APP_NAME)\"
 
-JS_SET_BROWSER_COMPONENT = nsSetDefaultBrowser.js
-
 CXXFLAGS += $(TK_CFLAGS)
 
-libs::
-	$(INSTALL) $(srcdir)/$(JS_SET_BROWSER_COMPONENT) $(DIST)/bin/components
-
 clobber::
 	rm -f $(DIST)/lib/$(LIBRARY_NAME).lib
-	rm -f $(DIST)/bin/components/$(JS_SET_BROWSER_COMPONENT)
--- a/browser/components/shell/src/nsSetDefaultBrowser.js
+++ b/browser/components/shell/src/nsSetDefaultBrowser.js
@@ -30,112 +30,43 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
-/* This file implements the nsICommandLineHandler interface.
- *
- * This component handles the startup command line argument of the form:
- *   -setDefaultBrowser
- * by making the current executable the "default browser."
+/* 
+ * -setDefaultBrowser commandline handler
+ * Makes the current executable the "default browser".
  */
 
-function nsSetDefaultBrowser() {
-}
+const Cc = Components.classes;
+const Ci = Components.interfaces;
+Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
+
+function nsSetDefaultBrowser() {}
 
 nsSetDefaultBrowser.prototype = {
-  /* nsISupports */
-  QueryInterface: function nsSetDefault_QI(iid) {
-    if (!iid.equals(Components.interfaces.nsICommandLineHandler) &&
-        !iid.equals(Components.interfaces.nsISupports))
-      throw Components.results.NS_ERROR_NO_INTERFACE;
-
-    return this;
-  },
-
-  /* nsICommandLineHandler */
-  handle : function nsSetDefault_handle(cmdline) {
-    if (cmdline.handleFlag("setDefaultBrowser", false)) {
-      var shell = Components.classes["@mozilla.org/browser/shell-service;1"]
-                            .getService(Components.interfaces.nsIShellService);
+  handle: function nsSetDefault_handle(aCmdline) {
+    if (aCmdline.handleFlag("setDefaultBrowser", false)) {
+      var shell = Cc["@mozilla.org/browser/shell-service;1"].
+                  getService(Ci.nsIShellService);
       shell.setDefaultBrowser(true, true);
     }
   },
 
-  helpInfo : "  -setDefaultBrowser   Set this app as the default browser.\n"
+  helpInfo: "  -setDefaultBrowser   Set this app as the default browser.\n",
+
+  classDescription: "Default Browser Cmdline Handler",
+  contractID: "@mozilla.org/browser/default-browser-clh;1",
+  classID: Components.ID("{F57899D0-4E2C-4ac6-9E29-50C736103B0C}"),
+  QueryInterface: XPCOMUtils.generateQI([Ci.nsICommandLineHandler]),
+  _xpcom_categories: [{
+    category: "command-line-handler",
+    entry: "m-setdefaultbrowser"
+  }]
 }
 
-// This Component's module and factory implementation.
-
-const contractID = "@mozilla.org/browser/default-browser-clh;1";
-const CID = Components.ID("{F57899D0-4E2C-4ac6-9E29-50C736103B0C}");
-
-var ModuleAndFactory = {
-  /* nsISupports */
-  QueryInterface: function nsSetDefault_QI(iid) {
-    if (!iid.equals(Components.interfaces.nsIModule) &&
-        !iid.equals(Components.interfaces.nsIFactory) &&
-        !iid.equals(Components.interfaces.nsISupports))
-      throw Components.results.NS_ERROR_NO_INTERFACE;
-
-    return this;
-  },
-
-  /* nsIModule */
-  getClassObject: function (compMgr, cid, iid) {
-    if (!cid.equals(CID))
-      throw Components.results.NS_ERROR_NO_INTERFACE;
-    
-    return this.QueryInterface(iid);
-  },
-    
-  registerSelf: function mod_regself(compMgr, fileSpec, location, type) {
-    var compReg =
-      compMgr.QueryInterface( Components.interfaces.nsIComponentRegistrar );
-
-    compReg.registerFactoryLocation( CID,
-                                     "Default Browser Cmdline Handler",
-                                     contractID,
-                                     fileSpec,
-                                     location,
-                                     type );
-
-    var catMan = Components.classes["@mozilla.org/categorymanager;1"]
-                           .getService(Components.interfaces.nsICategoryManager);
-
-    catMan.addCategoryEntry("command-line-handler",
-                            "m-setdefaultbrowser",
-                            contractID, true, true);
-  },
-    
-  unregisterSelf : function mod_unregself(compMgr, location, type) {
-    var catMan = Components.classes["@mozilla.org/categorymanager;1"]
-                           .getService(Components.interfaces.nsICategoryManager);
-
-    catMan.deleteCategoryEntry("command-line-handler",
-                               "m-setdefaultbrowser", true);
-  },
-
-  canUnload: function(compMgr) {
-    return true;
-  },
-
-  /* nsIFactory */
-  createInstance: function mod_CI(outer, iid) {
-    if (outer != null)
-      throw Components.results.NS_ERROR_NO_AGGREGATION;
-  
-    return new nsSetDefaultBrowser().QueryInterface(iid);
-  },
-    
-  lockFactory : function mod_lock(lock) {
-    /* no-op */
-  }
+function NSGetModule(compMgr, fileSpec) {
+  return XPCOMUtils.generateModule([nsSetDefaultBrowser]);
 }
-
-// NSGetModule: Return the nsIModule object.
-function NSGetModule(compMgr, fileSpec) {
-  return ModuleAndFactory;
-}
--- a/browser/fuel/src/fuelApplication.js
+++ b/browser/fuel/src/fuelApplication.js
@@ -522,20 +522,17 @@ Extensions.prototype = {
     for (var i = 0; i < items.length; i++) {
       retVal.push(this._get(items[i].id));
     }
 
     return retVal;
   },
   
   has : function exts_has(aId) {
-    // getItemForID never returns null for a non-existent id, so we
-    // check the type of the returned update item, which should be
-    // greater than 1 for a valid extension.
-    return !!(this._extmgr.getItemForID(aId).type);
+    return this._extmgr.getItemForID(aId) != null;
   },
   
   get : function exts_get(aId) {
     return this.has(aId) ? this._get(aId) : null;
   },
   
   QueryInterface : XPCOMUtils.generateQI([Ci.fuelIExtensions])
 };
@@ -1098,22 +1095,36 @@ BookmarkFolder.prototype = {
     // handle this folder event, root folder cannot be moved
     if (this._id == aId) {
       this._parent = new BookmarkFolder(aNewParent, Utilities.bookmarks.getFolderIdForItem(aNewParent));    
       this._events.dispatch("move", aId);
     }
   },
 
   QueryInterface : XPCOMUtils.generateQI([Ci.fuelIBookmarkFolder, Ci.nsINavBookmarkObserver])
-}; 
-
+};
 
-const CLASS_ID = Components.ID("fe74cf80-aa2d-11db-abbd-0800200c9a66");
-const CLASS_NAME = "Application wrapper";
-const CONTRACT_ID = "@mozilla.org/fuel/application;1";
+//=================================================
+// Factory - Treat Application as a singleton
+// XXX This is required, because we're registered for the 'JavaScript global
+// privileged property' category, whose handler always calls createInstance.
+// See bug 386535.
+var gSingleton = null;
+var ApplicationFactory = {
+  createInstance: function af_ci(aOuter, aIID) {
+    if (aOuter != null)
+      throw Components.results.NS_ERROR_NO_AGGREGATION;
+
+    if (gSingleton == null) {
+      gSingleton = new Application();
+    }
+
+    return gSingleton.QueryInterface(aIID);
+  }
+};
 
 //=================================================
 // Application constructor
 function Application() {
   this._console = null;
   this._prefs = null;
   this._storage = null;
   this._events = null;
@@ -1130,16 +1141,33 @@ function Application() {
   os.addObserver(this, "quit-application-granted", false);
   os.addObserver(this, "quit-application", false);
   os.addObserver(this, "xpcom-shutdown", false);
 }
 
 //=================================================
 // Application implementation
 Application.prototype = {
+  // for nsIClassInfo + XPCOMUtils
+  classDescription: "Application",
+  classID:          Components.ID("fe74cf80-aa2d-11db-abbd-0800200c9a66"),
+  contractID:       "@mozilla.org/fuel/application;1",
+
+  // redefine the default factory for XPCOMUtils
+  _xpcom_factory: ApplicationFactory,
+
+  // get this contractID registered for certain categories via XPCOMUtils
+  _xpcom_categories: [
+    // make Application a startup observer
+    { category: "app-startup", service: true },
+
+    // add Application as a global property for easy access
+    { category: "JavaScript global privileged property" }
+  ],
+
   get id() {
     return this._info.ID;
   },
   
   get name() {
     return this._info.name;
   },
   
@@ -1189,19 +1217,16 @@ Application.prototype = {
       this._extensions = null;
       this._bookmarks = null;
       
       Utilities.free();
     }
   },
 
   // for nsIClassInfo
-  classDescription : "Application",
-  classID : CLASS_ID,
-  contractID : CONTRACT_ID,
   flags : Ci.nsIClassInfo.SINGLETON,
   implementationLanguage : Ci.nsIProgrammingLanguage.JAVASCRIPT,
 
   getInterfaces : function app_gi(aCount) {
     var interfaces = [Ci.fuelIApplication, Ci.nsIObserver, Ci.nsIClassInfo];
     aCount.value = interfaces.length;
     return interfaces;
   },
@@ -1262,66 +1287,12 @@ Application.prototype = {
     return win;
   },
   
   get activeWindow() {
     return new Window(Utilities.windowMediator.getMostRecentWindow("navigator:browser"));
   }
 };
 
-//=================================================
-// Factory - Treat Application as a singleton
-var gSingleton = null;
-var ApplicationFactory = {
-  createInstance: function af_ci(aOuter, aIID) {
-    if (aOuter != null)
-      throw Components.results.NS_ERROR_NO_AGGREGATION;
-      
-    if (gSingleton == null) {
-      gSingleton = new Application();
-    }
-
-    return gSingleton.QueryInterface(aIID);
-  }
-};
-
-//=================================================
-// Module
-var ApplicationModule = {
-  registerSelf: function am_rs(aCompMgr, aFileSpec, aLocation, aType) {
-    aCompMgr = aCompMgr.QueryInterface(Ci.nsIComponentRegistrar);
-    aCompMgr.registerFactoryLocation(CLASS_ID, CLASS_NAME, CONTRACT_ID, aFileSpec, aLocation, aType);
-    
-    var categoryManager = Components.classes["@mozilla.org/categorymanager;1"]
-                                    .getService(Ci.nsICategoryManager);
-    // make Application a startup observer
-    categoryManager.addCategoryEntry("app-startup", CLASS_NAME, "service," + CONTRACT_ID, true, true);
-
-    // add Application as a global property for easy access
-    categoryManager.addCategoryEntry("JavaScript global privileged property", "Application", CONTRACT_ID, true, true);
-  },
-
-  unregisterSelf: function am_us(aCompMgr, aLocation, aType) {
-    aCompMgr = aCompMgr.QueryInterface(Ci.nsIComponentRegistrar);
-    aCompMgr.unregisterFactoryLocation(CLASS_ID, aLocation);        
-
-    // cleanup categories
-    var categoryManager = Components.classes["@mozilla.org/categorymanager;1"]
-                                    .getService(Ci.nsICategoryManager);
-    categoryManager.deleteCategoryEntry("app-startup", "service," + CONTRACT_ID, true);
-    categoryManager.deleteCategoryEntry("JavaScript global property", CONTRACT_ID, true);
-  },
-  
-  getClassObject: function am_gco(aCompMgr, aCID, aIID) {
-    if (!aIID.equals(Ci.nsIFactory))
-      throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
-
-    if (aCID.equals(CLASS_ID))
-      return ApplicationFactory;
-
-    throw Components.results.NS_ERROR_NO_INTERFACE;
-  },
-
-  canUnload: function am_cu(aCompMgr) { return true; }
-};
-
 //module initialization
-function NSGetModule(aCompMgr, aFileSpec) { return ApplicationModule; }
+function NSGetModule(aCompMgr, aFileSpec) {
+  return XPCOMUtils.generateModule([Application]);
+}
--- a/browser/installer/unix/packages-static
+++ b/browser/installer/unix/packages-static
@@ -206,16 +206,17 @@ bin/components/nsLoginInfo.js
 bin/components/nsLoginManager.js
 bin/components/nsLoginManagerPrompter.js
 bin/components/storage-Legacy.js
 bin/components/jsconsole-clhandler.js
 bin/components/nsTryToClose.js
 bin/components/nsDictionary.js
 bin/components/nsFilePicker.js
 bin/components/nsHelperAppDlg.js
+bin/components/nsDownloadManagerUI.js
 bin/components/nsInterfaceInfoToIDL.js
 ; bin/components/nsProgressDialog.js   not needed for firefox
 bin/components/nsProxyAutoConfig.js
 ; bin/components/nsResetPref.js    not needed for firefox
 bin/components/nsSidebar.js
 ; bin/components/nsUpdateNotifier.js not needed for firefox
 bin/components/nsXmlRpcClient.js
 bin/components/nsExtensionManager.js
--- a/browser/installer/windows/packages-static
+++ b/browser/installer/windows/packages-static
@@ -200,16 +200,17 @@ bin\components\FeedWriter.js
 bin\components\fuelApplication.js
 bin\components\WebContentConverter.js
 bin\components\nsBrowserContentHandler.js
 bin\components\nsBrowserGlue.js
 bin\components\nsSetDefaultBrowser.js
 bin\components\nsTryToClose.js
 bin\components\nsDictionary.js
 bin\components\nsHelperAppDlg.js
+bin\components\nsDownloadManagerUI.js
 bin\components\nsProxyAutoConfig.js
 bin\components\nsSearchService.js
 bin\components\nsSearchSuggestions.js
 bin\components\nsSidebar.js
 bin\components\nsXmlRpcClient.js
 bin\components\nsExtensionManager.js
 bin\components\nsBlocklistService.js
 bin\components\nsUpdateService.js
--- a/browser/locales/en-US/chrome/browser/browser.properties
+++ b/browser/locales/en-US/chrome/browser/browser.properties
@@ -23,21 +23,21 @@ bookmarkAllTabs_accesskey=T
 bookmarkCurTab_label=Bookmark This Tab...
 bookmarkCurTab_accesskey=B
 
 # bookmark dialog strings
 
 bookmarkAllTabsDefault=[Folder Name]
 
 xpinstallPromptWarning=%S prevented this site (%S) from asking you to install software on your computer.
-xpinstallPromptWarningButton=Edit Options...
+xpinstallPromptAllowButton=Allow
 # Accessibility Note:
 # Be sure you do not choose an accesskey that is used elsewhere in the active context (e.g. main menu bar, submenu of the warning popup button)
 # See http://www.mozilla.org/access/keyboard/accesskey for details
-xpinstallPromptWarningButton.accesskey=O
+xpinstallPromptAllowButton.accesskey=A
 xpinstallDisabledMessageLocked=Software installation has been disabled by your system administrator.
 xpinstallDisabledMessage=Software installation is currently disabled. Click Enable and try again.
 xpinstallDisabledButton=Enable
 xpinstallDisabledButton.accesskey=n
 popupWarning=%S prevented this site from opening a popup window.
 popupWarningMultiple=%S prevented this site from opening %S popup windows.
 popupWarningButton=Options
 popupWarningButton.accesskey=O
--- a/browser/locales/en-US/chrome/browser/places/places.dtd
+++ b/browser/locales/en-US/chrome/browser/places/places.dtd
@@ -190,17 +190,17 @@
          "Move Bookmark(s)...">
 <!ENTITY cmd.moveBookmarks.menuAccesskey
          "M">
 <!ENTITY cmd.personalToolbarFolder.menuLabel
          "Set as Bookmarks Toolbar Folder">
 <!ENTITY cmd.personalToolbarFolder.menuAccesskey
          "b">
 
-<!ENTITY col.title.label
+<!ENTITY col.name.label
   "Name">
 <!ENTITY col.tags.label
   "Tags">
 <!ENTITY col.url.label
   "Location">
 <!ENTITY col.lastvisit.label
   "Visit Date">
 <!ENTITY col.visitcount.label
--- a/browser/locales/en-US/chrome/browser/places/places.properties
+++ b/browser/locales/en-US/chrome/browser/places/places.properties
@@ -40,32 +40,34 @@ livemarkGroupOffLabel=No Grouping
 livemarkGroupOffAccesskey=N
 
 livemarkReload=Reload
 livemarkReloadAll=Reload All Live Bookmarks
 livemarkReloadOne=Reload %S
 
 sortByName=Sort '%S' by Name
 sortByNameGeneric=Sort by Name
-view.sortBy.title.label=Sort by Name
-view.sortBy.title.accesskey=T
+view.sortBy.name.label=Sort by Name
+view.sortBy.name.accesskey=N
 view.sortBy.url.label=Sort by Location
 view.sortBy.url.accesskey=L
 view.sortBy.date.label=Sort by Visit Date
 view.sortBy.date.accesskey=V
 view.sortBy.visitCount.label=Sort by Visit Count
 view.sortBy.visitCount.accesskey=C
 view.sortBy.keyword.label=Sort by Keyword
 view.sortBy.keyword.accesskey=K
 view.sortBy.description.label=Sort by Description
 view.sortBy.description.accesskey=D
 view.sortBy.dateAdded.label=Sort by Added
 view.sortBy.dateAdded.accesskey=A
 view.sortBy.lastModified.label=Sort by Last Modified
 view.sortBy.lastModified.accesskey=M
+view.sortBy.tags.label=Sort by Tags
+view.sortBy.tags.accesskey=T
 
 searchByDefault=Search in Bookmarks
 searchCurrentDefault=Search in '%S'
 findInPrefix=Find in '%S'...
 
 tabs.openWarningTitle=Confirm open
 tabs.openWarningMultipleBranded=You are about to open %S tabs.  This might slow down %S while the pages are loading.  Are you sure you want to continue?
 tabs.openButtonMultiple=Open tabs
--- a/browser/locales/en-US/chrome/browser/preferences/advanced.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/advanced.dtd
@@ -1,21 +1,21 @@
 <!-- Note: due to bug 143065, the only remaining accesskeys available to be used
-     in the Advanced pane are: "b", "j", "q", "z" -->
+     in the Advanced pane are: "j", "q", "z" -->
 
 <!ENTITY generalTab.label                "General">
 
 <!ENTITY accessibility.label             "Accessibility">
 
 <!ENTITY useCursorNavigation.label       "Always use the cursor keys to navigate within pages">
 <!ENTITY useCursorNavigation.accesskey   "c">
 <!ENTITY searchStartTyping.label         "Search for text when I start typing">
 <!ENTITY searchStartTyping.accesskey     "x">
 <!ENTITY blockAutoRefresh.label          "Warn me when web sites try to redirect or reload the page">
-<!ENTITY blockAutoRefresh.accesskey      "r">
+<!ENTITY blockAutoRefresh.accesskey      "b">
 
 <!ENTITY browsing.label                  "Browsing">
 
 <!ENTITY useAutoScroll.label             "Use autoscrolling">
 <!ENTITY useAutoScroll.accesskey         "a">
 <!ENTITY useSmoothScrolling.label        "Use smooth scrolling">
 <!ENTITY useSmoothScrolling.accesskey    "m">
 <!ENTITY checkSpelling.label             "Check my spelling as I type">
--- a/browser/locales/en-US/chrome/browser/preferences/main.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/main.dtd
@@ -31,17 +31,16 @@
 <!ENTITY alwaysAsk.accesskey "A">
 
 
 <!ENTITY systemDefaults.label  "System Defaults">
 
 <!ENTITY alwaysCheckDefault.label      "Always check to see if &brandShortName; is the default browser on startup"><!--XXX-->
 <!ENTITY alwaysCheckDefault.accesskey  "y">
 
-<!-- LOCALIZATION NOTE (alwaysCheckDefault.height):
-  There's some sort of bug which makes wrapping checkboxes not properly reflow,
-  causing the bottom border of the groupbox to be cut off; set this
-  appropriately if your localization causes this checkbox to wrap.
--->
-<!ENTITY alwaysCheckDefault.height  "3em">
-
 <!ENTITY checkNow.label             "Check Now">
 <!ENTITY checkNow.accesskey         "N">
+
+<!ENTITY addonsMgr.label            "Add-ons">
+<!ENTITY manageAddonsDesc.label     "Change options for your add-ons.">
+<!ENTITY manageAddonsDescUnix.label "Change preferences for your add-ons.">
+<!ENTITY manageAddons.label         "Manage Add-ons...">
+<!ENTITY manageAddons.accesskey     "M">
--- a/browser/locales/en-US/chrome/browser/preferences/preferences.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/preferences.dtd
@@ -1,12 +1,14 @@
 
 <!ENTITY  prefWindow.titleWin     "Options">
 <!ENTITY  prefWindow.titleGNOME   "&brandShortName; Preferences">
-<!ENTITY  prefWindow.styleWin     "width: 42em; height: 40em;">
+<!-- When making changes to prefWindow.styleWin test both Windows Classic and
+     Luna since widget heights are different based on the OS theme -->
+<!ENTITY  prefWindow.styleWin     "width: 42em; height: 44em;">
 <!ENTITY  prefWindow.styleMac     "width: 47em;">
 <!ENTITY  prefWindow.styleGNOME   "width: 42em; height: 38.5em;">
 
 <!ENTITY  paneMain.title          "Main">
 <!ENTITY  paneTabs.title          "Tabs">
 <!ENTITY  paneContent.title       "Content">
 <!ENTITY  paneFeeds.title         "Feeds">
 <!ENTITY  panePrivacy.title       "Privacy">
--- a/browser/locales/en-US/chrome/browser/quitDialog.properties
+++ b/browser/locales/en-US/chrome/browser/quitDialog.properties
@@ -1,11 +1,11 @@
 quitDialogTitle=Quit %S
 restartDialogTitle=Restart %S
 
 quitTitle=&Quit
 restartTitle=&Restart
 cancelTitle=&Cancel
-saveTitle=&Save and quit
+saveTitle=&Save and Quit
 neverAsk=Do not ask next time
 message=Do you want %S to save your tabs and windows for the next time it starts?
 messageNoWindows=Do you want %S to save your tabs for the next time it starts?
 messageRestart=%S will try to restore your tabs and windows when it restarts.
--- a/browser/themes/pinstripe/browser/browser.css
+++ b/browser/themes/pinstripe/browser/browser.css
@@ -972,16 +972,33 @@ statusbarpanel#statusbar-display {
   height: 16px;
 }
 
 .autocomplete-treebody::-moz-tree-image(bookmark, treecolAutoCompleteValue) {
   width: 16px;
   height: 16px;
 }
 
+#treecolAutoCompleteImage {
+ max-width : 36px; 
+ padding-end: 18px;
+}
+
+.autocomplete-treebody::-moz-tree-image(favicon, treecolAutoCompleteImage) {
+  list-style-image: url("chrome://browser/skin/places/starPage.png");
+  width: 16px;
+  height: 16px;
+}
+
+.autocomplete-treebody::-moz-tree-image(bookmark, treecolAutoCompleteImage) {
+  list-style-image: url("chrome://browser/skin/places/pageStarred.png");
+  width: 16px;
+  height: 16px;
+}
+
 .autocomplete-treebody::-moz-tree-cell-text(treecolAutoCompleteComment) {
   color: #555566;
 }
 
 .autocomplete-treebody::-moz-tree-cell-text(suggesthint, treecolAutoCompleteComment), 
 .autocomplete-treebody::-moz-tree-cell-text(suggestfirst, treecolAutoCompleteComment) 
 {
   color: GrayText;
@@ -1032,16 +1049,36 @@ toolbarpaletteitem:not([place="toolbar"]
 #go-button > .button-box {
   border: none;
 }
 
 #go-button > .toolbarbutton-icon {
   padding: 0px;
 }
 
+/* STAR BUTTON */
+#star-button {
+  list-style-image: url("chrome://browser/skin/places/starPage.png");
+  margin: 0;
+  padding: 0;
+  max-width: 0;
+  height: 24px;
+}
+
+#star-button > .toolbarbutton-icon {
+  padding: 2px 2px 2px 0;
+  border: 1px solid #A3A3A3;
+  border-left: 0;
+  background: url("chrome://global/skin/10pct_transparent_grey.png") repeat;
+}
+
+#star-button[starred="true"] {
+  list-style-image: url("chrome://browser/skin/places/pageStarred.png");
+}
+
 /* ----- SIDEBAR ELEMENTS ----- */
 
 sidebarheader {
 	border-bottom: 1px solid #A3A3A3;
         background: url("chrome://global/skin/inset_gradient_1px.png") repeat !important;
 }
 
 #sidebar-box {
@@ -1242,16 +1279,20 @@ toolbarbutton.chevron > .toolbarbutton-m
   min-width: 1px !important;
   text-align: center;
 }
 
 .tabbrowser-tab[selected="true"] {
   -moz-user-focus: normal;
 }
 
+.tabbrowser-tab[selected="true"] > .tab-image-middle > .tab-icon {
+  cursor: -moz-grab;
+}
+
 .tabbrowser-tab > .tab-image-middle > .tab-text {
   border: 1.4pt solid transparent;
 }
 
 .tabbrowser-tab:focus > .tab-image-middle > .tab-text {
   border: 1.4pt solid -moz-mac-focusring;
 }
 
@@ -1657,18 +1698,8 @@ toolbarbutton.bookmark-item[dragover="tr
   border-left: 2px solid;
   border-right: 2px solid;
   border-bottom: 3px solid;
   -moz-border-right-colors: -moz-mac-menushadow ThreeDLightShadow  !important;
   -moz-border-bottom-colors: -moz-mac-menushadow -moz-mac-menushadow ThreeDShadow  !important;
   -moz-border-left-colors: ThreeDLightShadow ThreeDHighlight !important;
 }
 
-/* star icon */
-#star-icon {
-  list-style-image: url("chrome://browser/skin/places/starPage.png");
-  width: 16px;
-  height: 16px;
-}
-
-#star-icon[starred="true"] {
-  list-style-image: url("chrome://browser/skin/places/pageStarred.png");
-}
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..6224ba294a5b25cc8c30599f1a32088a02ab208b
GIT binary patch
literal 6527
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
H`sM!t{%?p<
--- a/browser/themes/winstripe/browser/browser.css
+++ b/browser/themes/winstripe/browser/browser.css
@@ -965,16 +965,33 @@ statusbarpanel#statusbar-display {
   height: 16px;
 }
 
 .autocomplete-treebody::-moz-tree-image(bookmark, treecolAutoCompleteValue) {
   width: 16px;
   height: 16px;
 }
 
+#treecolAutoCompleteImage {
+ max-width : 36px; 
+ padding-end: 18px;
+}
+
+.autocomplete-treebody::-moz-tree-image(favicon, treecolAutoCompleteImage) {
+  list-style-image: url("chrome://browser/skin/places/starPage.png");
+  width: 16px;
+  height: 16px;
+}
+
+.autocomplete-treebody::-moz-tree-image(bookmark, treecolAutoCompleteImage) {
+  list-style-image: url("chrome://browser/skin/places/pageStarred.png");
+  width: 16px;
+  height: 16px;
+}
+
 .autocomplete-treebody::-moz-tree-cell-text(treecolAutoCompleteComment) {
   color: #555566;
 }
 
 .autocomplete-treebody::-moz-tree-cell-text(suggesthint, treecolAutoCompleteComment), 
 .autocomplete-treebody::-moz-tree-cell-text(suggestfirst, treecolAutoCompleteComment) 
 {
   color: GrayText;
@@ -1020,16 +1037,30 @@ toolbar:not([mode="text"]) #go-button,
 #palette-box #go-button {
   -moz-appearance: none;
   list-style-image: url("chrome://browser/skin/Go-arrow.png");
   -moz-image-region: rect(0px 25px 22px 0px);
   border: none;
   padding: 0;
 }
 
+/* star button */
+toolbar:not([mode="text"]) #star-button,
+#palette-box #star-button {
+  -moz-appearance: none;
+  list-style-image: url("chrome://browser/skin/places/starPage.png");
+  padding: 0;
+  border: none;
+}
+
+toolbar:not([mode="text"]) #star-button[starred="true"],
+#palette-box #star-button[starred="true"] {
+  list-style-image: url("chrome://browser/skin/places/pageStarred.png");
+}
+
 #go-button[chromedir="rtl"] {
   list-style-image: url("chrome://browser/skin/Go-arrow-rtl.png");
 }
 
 #go-button-top {
   list-style-image: url("chrome://browser/skin/Go-bkgnd.png");
   -moz-image-region: rect(0px, 25px, 10px, 0px);
   height: 10px;
@@ -1266,79 +1297,76 @@ toolbar[mode="text"] #navigator-throbber
   list-style-image: url("chrome://global/skin/throbber/Throbber-small.gif") !important;
   opacity: 0.6;
 }
 
 .tabbrowser-tab[selected="true"] {
   font-weight: bold;
 }
 
-.tabbrowser-tab[selected="true"] > .tab-image-middle > .tab-text {
-  opacity: 1.0 !important;
+.tabbrowser-tab[selected="true"] > * {
+  background-color: -moz-dialog;
+}
+
+.tabbrowser-tab[selected="true"] > .tab-image-middle > .tab-icon {
+  cursor: -moz-grab;
 }
 
 .tabbrowser-tab > .tab-image-left {
   width: 8px;
   height: 24px;
-  background: url("chrome://browser/skin/tabbrowser/tab-left.png") no-repeat;
-  background-color: -moz-dialog;
+  background-image: url("chrome://browser/skin/tabbrowser/tab-left.png");
+  background-repeat: no-repeat;
   -moz-border-radius-topleft: 4px;
 }
 
 .tabbrowser-tab[chromedir="rtl"] > .tab-image-left {
-  background: url("chrome://browser/skin/tabbrowser/tab-right.png") no-repeat;
-  background-color: -moz-dialog;
+  background-image: url("chrome://browser/skin/tabbrowser/tab-right.png");
   -moz-border-radius-topleft: 0px;
   -moz-border-radius-topright: 4px;
 }
 
 .tabbrowser-tab:not([selected="true"]):not(:hover) > .tab-image-left {
-  background: url("chrome://browser/skin/tabbrowser/tab-left-bkgnd.png") no-repeat;
-  background-color: -moz-dialog;
+  background-image: url("chrome://browser/skin/tabbrowser/tab-left-bkgnd.png");
 }
 
 .tabbrowser-tab[chromedir="rtl"]:not([selected="true"]):not(:hover) > .tab-image-left {
-  background: url("chrome://browser/skin/tabbrowser/tab-right-bkgnd.png") no-repeat;
-  background-color: -moz-dialog;
+  background-image: url("chrome://browser/skin/tabbrowser/tab-right-bkgnd.png");
 }
 
 .tabbrowser-tab > .tab-image-middle {
   height: 24px;
-  background: url("chrome://browser/skin/tabbrowser/tab-middle.png") repeat-x;
-  background-color: -moz-dialog;
+  background-image: url("chrome://browser/skin/tabbrowser/tab-middle.png");
+  background-repeat: repeat-x;
 }
 
 .tabbrowser-tab:not([selected="true"]):not(:hover) > .tab-image-middle {
-  background: url("chrome://browser/skin/tabbrowser/tab-middle-bkgnd.png") repeat-x;
-  background-color: -moz-dialog;
+  background-image: url("chrome://browser/skin/tabbrowser/tab-middle-bkgnd.png");
 }
 
 .tabbrowser-tab > .tab-image-right {
   width: 8px;
   height: 24px;
-  background: url("chrome://browser/skin/tabbrowser/tab-right.png") no-repeat;
-  background-color: -moz-dialog;
+  background-image: url("chrome://browser/skin/tabbrowser/tab-right.png");
+  background-repeat: no-repeat;
   -moz-border-radius-topright: 4px;
 }
 
 .tabbrowser-tab[chromedir="rtl"] > .tab-image-right {
-  background: url("chrome://browser/skin/tabbrowser/tab-left.png") no-repeat;
-  background-color: -moz-dialog;
+  background-image: url("chrome://browser/skin/tabbrowser/tab-left.png");
   -moz-border-radius-topleft: 4px;
   -moz-border-radius-topright: 0px;
 }
 
 .tabbrowser-tab:not([selected="true"]):not(:hover) > .tab-image-right {
-  background: url("chrome://browser/skin/tabbrowser/tab-right-bkgnd.png") no-repeat;
-  background-color: -moz-dialog;
+  background-image: url("chrome://browser/skin/tabbrowser/tab-right-bkgnd.png");
 }
 
 .tabbrowser-tab[chromedir="rtl"]:not([selected="true"]):not(:hover) > .tab-image-right {
-  background: url("chrome://browser/skin/tabbrowser/tab-left-bkgnd.png") no-repeat;
-  background-color: -moz-dialog;
+  background-image: url("chrome://browser/skin/tabbrowser/tab-left-bkgnd.png");
 }
 
 .tabbrowser-tab:not([selected="true"]) > .tab-image-left,
 .tabbrowser-tab:not([selected="true"]) > .tab-image-middle,
 .tabbrowser-tab:not([selected="true"]) > .tab-image-right {
   height: 23px;
   margin-bottom: 1px;
 }
@@ -1427,28 +1455,25 @@ tabpanels {
 
 .tabbrowser-tab:not([selected="true"]) > .tab-close-button > .toolbarbutton-icon {
   margin-top: 2px;
 }
 
 .tab-close-button:hover,
 .tabbrowser-tab[selected="true"] > .tab-close-button:hover {
   -moz-image-region: rect(0px, 32px, 16px, 16px);
-  opacity: 1.0;
 }
 
 .tab-close-button:hover:active,
 .tabbrowser-tab[selected="true"] > .tab-close-button:hover:active {
   -moz-image-region: rect(0px, 48px, 16px, 32px);
-  opacity: 1.0;
 }
 
 .tabbrowser-tab > .tab-close-button {
   background-image: url("chrome://browser/skin/tabbrowser/tab-middle-bkgnd.png");
-  background-color: -moz-dialog;
 }
 
 .tabbrowser-tab:hover > .tab-close-button {
   background-image: url("chrome://browser/skin/tabbrowser/tab-middle.png");
 }
 
 .tabbrowser-tab[selected="true"] > .tab-close-button {
   background-image: url("chrome://browser/skin/tabbrowser/tab-middle.png");
@@ -1458,16 +1483,34 @@ tabpanels {
   -moz-user-focus: normal;
 }
 
 .tab-close-button:focus {
   outline: none !important;
 }
 
 /**
+ * Tabstrip close button
+ */
+
+.tabs-closebutton-box > .tabs-closebutton {
+  padding-top: 5px;
+  -moz-padding-end: 1px;
+  padding-bottom: 3px;
+  -moz-padding-start: 2px;
+  background-image: url("chrome://browser/skin/tabbrowser/close-bkgnd.png");
+  background-color: -moz-dialog;
+}
+
+.tabs-closebutton-box[chromedir="rtl"] > .tabs-closebutton {
+  background-image: url("chrome://browser/skin/tabbrowser/close-bkgnd-rtl.png");
+  background-position: top right;
+}
+
+/**
  * Tab Scrollbox Arrow Buttons
  */
 
 .tabbrowser-tabs[overflow="true"] .tabs-left {
   display: none;
 }
 
 .tabbrowser-arrowscrollbox > .scrollbutton-up {
@@ -1479,17 +1522,16 @@ tabpanels {
   width: 18px;
   height: 23px;
   -moz-margin-start: 0px;
   -moz-margin-end: 0px;
   list-style-image: url("chrome://browser/skin/tabbrowser/tab-arrow-start.png");
   -moz-image-region: rect(0, 11px, 14px, 0);
   background-repeat: no-repeat;
   background-image: url("chrome://browser/skin/tabbrowser/tab-arrow-start-bkgnd-enabled.png");
-  background-color: -moz-dialog;
   -moz-border-radius-topright: 4px;
 }
 
 .tabbrowser-arrowscrollbox[chromedir="rtl"] > .scrollbutton-up {
   list-style-image: url("chrome://browser/skin/tabbrowser/tab-arrow-end.png");
   background-image: url("chrome://browser/skin/tabbrowser/tab-arrow-end-bkgnd-enabled.png");
   -moz-border-radius-topleft: 4px;
   -moz-border-radius-topright: 0px;
@@ -1527,18 +1569,17 @@ tabpanels {
   height: 23px;
 }
 
 .tabbrowser-arrowscrollbox > stack > .scrollbutton-down-box {
   -moz-appearance: none !important;
   border: none !important;
   width: 18px;
   background-image: url("chrome://browser/skin/tabbrowser/tab-arrow-end-bkgnd-enabled.png");
-  background-repeat: no-repeat;	
-  background-color: -moz-dialog;
+  background-repeat: no-repeat;
   -moz-border-radius-topleft: 4px;
 }
 
 .tabbrowser-arrowscrollbox[chromedir="rtl"] > stack > .scrollbutton-down-box {
   background-image: url("chrome://browser/skin/tabbrowser/tab-arrow-start-bkgnd-enabled.png");
   -moz-border-radius-topleft: 0px;
   -moz-border-radius-topright: 4px;
 }
@@ -1604,17 +1645,16 @@ tabpanels {
 
 .tabs-alltabs-box {
   margin-top: 2px;
   margin-bottom: 4px;
   width: 18px !important;
   height: 23px !important;
   background-image: url("chrome://browser/skin/tabbrowser/tab-arrow-end-bkgnd-enabled.png");
   background-repeat: no-repeat;
-  background-color: -moz-dialog; 
   -moz-border-radius-topleft: 4px;
 }
 
 stack[chromedir="rtl"] > hbox > .tabs-alltabs-box {
   background-image: url("chrome://browser/skin/tabbrowser/tab-arrow-start-bkgnd-enabled.png");
   -moz-border-radius-topleft: 0px;
   -moz-border-radius-topright: 4px;
 }
@@ -1914,19 +1954,8 @@ toolbarbutton.bookmark-item[dragover="tr
 
 .bookmark-item[dragover-top="true"] {
   -moz-border-top-colors: #000000;
 }
 
 .bookmark-item[dragover-bottom="true"] {
   -moz-border-bottom-colors: #000000;
 }
-
-/* star icon */
-#star-icon {
-  list-style-image: url("chrome://browser/skin/places/starPage.png");
-  width: 16px;
-  height: 16px;
-}
-
-#star-icon[starred="true"] {
-  list-style-image: url("chrome://browser/skin/places/pageStarred.png");
-}
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..6224ba294a5b25cc8c30599f1a32088a02ab208b
GIT binary patch
literal 6527
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
H`sM!t{%?p<
--- a/browser/themes/winstripe/browser/jar.mn
+++ b/browser/themes/winstripe/browser/jar.mn
@@ -66,16 +66,18 @@ classic.jar:
         skin/classic/browser/preferences/Options.png            (preferences/Options.png)
         skin/classic/browser/preferences/preferences.css        (preferences/preferences.css)
         skin/classic/browser/tabbrowser/alltabs-box-overflow-end-bkgnd.png           (tabbrowser/alltabs-box-overflow-end-bkgnd.png)
         skin/classic/browser/tabbrowser/alltabs-box-overflow-end-bkgnd-animate.png   (tabbrowser/alltabs-box-overflow-end-bkgnd-animate.png)
         skin/classic/browser/tabbrowser/alltabs-box-overflow-end-bkgnd-hover.png     (tabbrowser/alltabs-box-overflow-end-bkgnd-hover.png)
         skin/classic/browser/tabbrowser/alltabs-box-overflow-start-bkgnd.png         (tabbrowser/alltabs-box-overflow-start-bkgnd.png)
         skin/classic/browser/tabbrowser/alltabs-box-overflow-start-bkgnd-animate.png (tabbrowser/alltabs-box-overflow-start-bkgnd-animate.png)        
         skin/classic/browser/tabbrowser/alltabs-box-overflow-start-bkgnd-hover.png   (tabbrowser/alltabs-box-overflow-start-bkgnd-hover.png)
+        skin/classic/browser/tabbrowser/close-bkgnd.png                    (tabbrowser/close-bkgnd.png)
+        skin/classic/browser/tabbrowser/close-bkgnd-rtl.png                (tabbrowser/close-bkgnd-rtl.png)
         skin/classic/browser/tabbrowser/tab-arrow-end.png                  (tabbrowser/tab-arrow-end.png)
         skin/classic/browser/tabbrowser/tab-arrow-end-bkgnd-animate.png    (tabbrowser/tab-arrow-end-bkgnd-animate.png)
         skin/classic/browser/tabbrowser/tab-arrow-end-bkgnd-disabled.png   (tabbrowser/tab-arrow-end-bkgnd-disabled.png)
         skin/classic/browser/tabbrowser/tab-arrow-end-bkgnd-enabled.png    (tabbrowser/tab-arrow-end-bkgnd-enabled.png)
         skin/classic/browser/tabbrowser/tab-arrow-end-bkgnd-hover.png      (tabbrowser/tab-arrow-end-bkgnd-hover.png)
         skin/classic/browser/tabbrowser/tab-arrow-start.png                (tabbrowser/tab-arrow-start.png)
         skin/classic/browser/tabbrowser/tab-arrow-start-bkgnd-animate.png  (tabbrowser/tab-arrow-start-bkgnd-animate.png)
         skin/classic/browser/tabbrowser/tab-arrow-start-bkgnd-disabled.png (tabbrowser/tab-arrow-start-bkgnd-disabled.png)
--- a/browser/themes/winstripe/browser/preferences/preferences.css
+++ b/browser/themes/winstripe/browser/preferences/preferences.css
@@ -259,8 +259,14 @@ filefield[disabled="true"] .fileFieldIco
   -moz-margin-start: 6px !important; 
   font-weight: bold;
 }
 
 /* Feeds pane */
 #chooseClientAppCell {
   -moz-padding-end: 12px;
 }
+
+/* bottom-most box containing a groupbox in a prefpane. Prevents the bottom
+   of the groupbox from being cutoff */
+.bottomBox {
+  padding-bottom: 2px;
+}
index 754fd3385d92f4afa371c0929047b666327b19ec..883ad64f1ace86344e37f7d87cf2b5bc6dffca2e
GIT binary patch
literal 460
zc$@*u0W<!IP)<h;3K|Lk000e1NJLTq000sI000>X1^@s6JPCf300007bV*G`2iFD|
z4hs{s*17lq000SaNLh0L03N{r03N{s!)a7g00004XF*Lt006O%3;baP00047Nkl<Z
zc-pO%O>%=U426+@2*Yu@=pnl1g4~ZCL!mLqm5fALT1+*gK!W}8o-8{}^G^Z8FnrPV
zlfP{1>YjoEL&kCZxc``QegrDfb=?90p7Qln(G@8rJdR^?&SlOJLbbHu9b~q$@B2y#
z-g|~L1VK_)uL$VPd_$1$TYdNgP1gAB{ANU4MM0LZDGFpoX0HknMVghM7|UQ%v~Ynn
z%peD#iWZ(P5VV8b*~~P5BUM>d-C)(AGI*ZnOvNp|!x_o4KC1$OJBvL{Q<=zpq%af6
z!)c9dCAP$>sJj_rvliQ^#ZC;lt(XneNYl~$gH$!FL>n?2jse<hS3@Sb;-gjb{#yP+
ztSP_-(#|Hxn?Y<%juG^-ed=l?LrKY={{qd5K(+|Q4^LE8q{gPmx$CGXHIhWNSPhD?
zz1OG_Kv85mYEycb8`@imt+Z{6^hbbw-(!@8sEJ>}^$InDfJ`O;0000<MNUMnLSTX|
COT<<H
index 79e592bbeb32fba5e5df7b2a1e902391a82660b0..e6a06de857359884c2bccec26152c8fdbf3c6de8
GIT binary patch
literal 348
zc%17D@N?(olHy`uVBq!ia0vp^LO?9Z!3HF4IP0bWDfSXiUsv|)Y!c$~dKaJXas~=<
z7I;J!Gcd><1YyR*nIXYIL6&q!Uq=Rpjs4tz5?O)#*PbqpAr-gQPI2UGRuFKV$rx<7
zGF#l%*|ziU?W$bi{Dtd$4kkHnDb;4?Hk$F_)BkdbgfiPzT876Mlyxeul`5u&Wvsnp
z$<4~io;mCK*SKls-xYm>x9Oa&oN!yl#p~p)ZL&HqgqCy^pPAFO?ls#v%ga&wn;kmr
z9#_t5W~k48;OM0(#qnUd$7BbYLftRl{vUQUdvI3D_hMe|tYsFGk=gS#78J@%<oG1{
zwf4NH!X1&D-%~vlCU(e{{97vL*nZo@l|zEFMS%TCYX@^wk3XkiCU516%&u)_o02&@
qYE>p}-4NW6mMiaEId8H^En``7(0?Z0<6nW^X7F_Nb6Mw<&;$VX!hk6N
index 3431d0635e11af8cb862817381d568751b7f89b5..0561d67bae469587b3b115996fc7aec8bd33b31a
GIT binary patch
literal 466
zc$@*!0WJQCP)<h;3K|Lk000e1NJLTq000sI000>X1^@s6JPCf300007bV*G`2iFD|
z4hs^)(TQ#V000SaNLh0L03N{r03N{s!)a7g00004XF*Lt006O%3;baP0004DNkl<Z
zc-pO%&27Ul424BXjvM&ut<oK`OGfG#J#-P@47YXSAC;siA-Rc01rP}x@XO<)Bs=#{
z3*Il6+tK2;^Lf{=pD<0+hxy+DUh?bp`W3pai$~PN81EF@JkK5Hfs*gq;&okN-**Y`
zeGDO#-vY_}sReN%!7xLUu-JKo$jE9%x{!)NVaYQ@0aYs^00%1qhH;LF5+)D>o*<Bw
z1@_C>+6zQYccE$QAcbLWO-zGi_ODS9W;MAr@n{^!>J3T7ZdsPd)8b%7ZQC*^hG7^?
zAOZ+z+cwGjzNhh%*_12>5D)<Mv$W<RjlUYCX6FrAK+TD!#s{yKqLYehHs-0(bzoQY
zH2MPam^S2ku(fjLyhq;M{$T-OTGATm4VQPeNs+e1v1dgt%6ap5t0EGD+9o8g>4?yC
z)6}>~qkss_mtHvHk*LZqfu=b{zWl2}bk4+NmnJ5>^!(xe0Q=nywfZ3_q5uE@07*qo
IM6N<$g7}il(f|Me
index 785f79c36297bf882ad8c5e1b9e4df46bbc7bad2..05ef810c161d1cf1a855940279b63bacd727ad0a
GIT binary patch
literal 365
zc%17D@N?(olHy`uVBq!ia0vp^LO?9Z!3HF4IP0bWDfSXiUsv|)Y!c$~dKaJXas~=<
z7I;J!Gcd><1YyR*nIXYIL6&q!Uq=Rpjs4tz5?O)#Kb|g*Ar-gQPBG*=WWeJpdptE^
zg#|-(yVr)|)*?nWi`bnEb6CW7l_n-=i;8OcDq47Wthw@Wl1^pSzfFs$MVc`=DlWSH
z_Ip_Fwb!i;#r=x}C5rd2Se6;~e_xoF<Lzzpe}62nc>eR7TWaJiMJ=AHC7D(;&pr=6
zv0Z)BHM_QkE!P4>j+%N->bz#LY~OqK#yajm#?n}Iw!(}Dy=&$iRyem}a+ArU<)#}a
z^3UrreAKgVt!;C|t6j$w7OYyeMdpa4<@2~8fhuJ-OU(`?rbod!Pkfsi0umJ_#NQH7
z@SP+0f9Ipd5`FPwC&WL7bUE6%Iqcc_=vs%;0*k(*ZvVWineQG<5r6llBpw(J44$rj
JF6*2UngC6gkj(%9
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..b109f41743987fb54d1e215e2843d2cc0d096e13
GIT binary patch
literal 482
zc$@*^0UiE{P)<h;3K|Lk000e1NJLTq000;O000>X1^@s6D=Y3@00007bV*G`2iF7y
z2rVZvJ_(!v000SaNLh0L03N{r03N{s!)a7g00004XF*Lt006O%3;baP0004TNkl<Z
zc-pO%O>)B^426-vaWh_clUt>C@LhVO9;6rX&f~U@|A-_6ldKUlniw+kKAt21KJWK0
zXFNWx*E4^^JkQ@&!T|6#ABN#4bX^xMcOPSXP#nv$bUY6<`K=Y*_Z`mjl<?li5JLGc
zkgdO301FZXGb|a2okxg_s&=3QNfZ<!3xFtqY6m3D!47~SJV!(c695aph(mS~xE@9+
zdK1@TyU;Xt0EJ*q5f6k^<bNXvn0KF3BsG|(srsOisN1$Ja`$ksgSKrM5W_f*CIAu^
zz;PThzuj)src`8_Yz6=zVbtG}A`hues{t+*IUlqFXfD)6d@<FkYv)8QGUhI#>($P|
zON$nO$8^wk;}n%U$$R9}>{kl_rXeW;eR=XpHgTY-;W)Dc7v(<k4=V?>any7P0Qjn)
zb(1b)F^vKsBtJ&MvIgQJKmJW~iTvnS1Lz)-;=0s9!b$6^3w_^L*I->&26(5%)^}OP
Y6Vmw^_LL10k^lez07*qoM6N<$f^qY_2><{9
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..00d3e9c8b10753e3938dd6beafb521f426366f6e
GIT binary patch
literal 473
zc$@**0Ve*5P)<h;3K|Lk000e1NJLTq000;O000>X1^@s6D=Y3@00007bV*G`2iF7x
z6DSIYGS!3t000SaNLh0L03N{r03N{s!)a7g00004XF*Lt006O%3;baP0004KNkl<Z
zc-pO2L5_nk3?vC*5eFW#Z{b1vmHv+#VxbK<I}SF>J+@?sT4}~Jj@`OxntmFIecOCv
z94$Xyuh;kU!<@4%0Y~5Wt8*?OzswbAq?G79&)s{UIor0ameL0AGFx&S$A)wv1O{&a
zPEb>?z@bt;0Q{HV;y*vg#3HViD<z^$D$Wu%3R+kqsGEX|0?kT-7z+p#tlU@)GXn3N
zDp(m;z{!rlU&9OB9V)V_c#u>R6p&?EGMZZMK4*k=`dt-)^H-DSc`krF2TEc>5Zq-E
z>`815tH3lfxQ#`zi`wMG;Ex+*L(s@D0r!N8hAY=W%LZ!|yXYRYByTdkMIqeR^c0H}
z*oHtS8Q>o#V2fm3Q;;=MMW8jJ@+1ETnJI9xDiCi5R28V+MuGSDN-jN+B(<uVAja<5
zgGPXh0+XN2ls@Hv-ILgouImVY0B9HnigE#}2=oB3H&-m+c^t<RWYq+JZ<r8)T1eDD
P00000NkvXXu0mjfoOZh5
index 9c96befeb11a56bb4e850af10f59786b303dc5bd..5bef4e0e07d2444a7d72fce25466d3db2622f2c7
GIT binary patch
literal 400
zc$@){0dM|^P)<h;3K|Lk000e1NJLTq000sI000>X1^@s6JPCf300007bV*G`2iFJ?
z4igcgN7e%X000SaNLh0L03N{r03N{s!)a7g00004XF*Lt006O%3;baP0003WNkl<Z
zc-pO#L2kn!5Ji~*Y&Q1F3tu6trkgr<NvP81xK)p1FG36%Y$KH@QZX^oXaK>}|KFIg
zjRu6tr`9`a>Lt+E`TVZ6=5PCbtCV8Sxz!+X`M&H<rz7tUhqkJ!pK%=5Q#^=sR3BZ}
zHcj(e*R?FmQW|4!G;H7Zw`33^FuDk22?-+1OtHf-Ot54SgE{Y_C^!JPP_z{)4Mdli
zl+p<yz|AS=fjHtcAqFg8%Xcp`RBG5f0xf+t2mzAM{-4q0XUXNIuqSDV)`v}N>x;HR
zrGofVMSoPKfp9BpLW&6VFi!`ClN(sW5Vp_S`JST){ZG5a5M0C=Wm|LBMb<pv!Co5Z
uiPzkh%_3_al%ojgA#D@3G1n-gTt#;{o2)K!4Yf!B0000<MNUMnLSTY%T%hj&
index 91e6813923db7f6ff12ccb24454b0ab1a5c841dc..f025aa00a832da08bde7660fab2bf9039508ad6a
GIT binary patch
literal 348
zc%17D@N?(olHy`uVBq!ia0vp^LO?9Z!3HF4IP0bWDfSXiUsv|)90GhoW^!Rcnm{4W
z0*}aI1_rr<Ak26;Gb9)&$dc~p>&U>cv7h@-A}f&p+SA1`q~g}vDUN*23IeV(8G{X1
zW{cZ8+jic)U6m`Gzi^$;!6e5mrP|EgMl(Kq`d==QP-eSI%kUV3vQEXdQpMD;jJ0<x
zxmh{cGiP1@8aK`SyP|LKHl5Rz6K>16c%8hpO;+cH(2|bgGjqDuy=FUSc{yr-vqOj7
z<H~u>4E5O$9KAH9I36tbnCu`^sQcyH|HF=E56(*YUd+p#wah{?GJC$pf<l>z9G@h=
z)}HrNxFd4&d#Z=R#17e#e@o>Y+i#n=a!7Et2(TY%?O=}T@#hrG<gHwh*|p7VQ!-~q
pt;(dW8-g3sa^;;X=S>!=Wh_e$`p?9B{43Dg44$rjF6*2UngGn0eop`Z
index ce4a54ffbd3208979c805bb351a57f2b12929f26..7ea7b8bf42b039f62b58ce3a1993baab486b6c98
GIT binary patch
literal 492
zc$@+30Tcd-P)<h;3K|Lk000e1NJLTq000sI000>X1^@s6JPCf300007bV*G`2iFJ?
z4iYHjS#L@J000SaNLh0L03N{r03N{s!)a7g00004XF*Lt006O%3;baP0004dNkl<Z
zc-pO%&u+pn494@PX%XjXuQ9X(<t5mK6FavzUSRLc4Y78lb!G>fag3{3N*js#m+y0&
zV9Y;-mC46`e*%ElrJ#x)pU2}@*LCh~v)QaxE0a>vgARwosqcH&?shFgMr&=eND(H!
zY}@v|X_{+{(a!TcI_DCNs;Y{mRo>Y|R;Fnha9Hm>K@36w7f~p}m1%;IZ+dfm=m9Eg
zv^uSfJ2tR_#GzAEp%u;^1j34B6oNv?AETlx6<9(Ia@LBXE9El;^dPJegGN-9MAZ|l
z7?eN0TrLTVn|p^wK+E!55y-lGvCrpoPNY5(m<r_W-5T18WQkN^cN0WsE!07Z9SQQZ
zV>*!Gro;RhRT)wu4Ve_z0G_o+Lq>kXqFwX;vHde!6MzmRosEzifyf$PBjEY?l+}no
zMI}@E3s5Vvd_*vQC{a|Q8l58N9#=)K5f2cH#h?)C=NcIXWJRj0HpW|?;Ms~~rLJqh
iKLJ>;*ARFkO5ztKybs^Z+!e6^0000<MNUMnLSTZMt;_`g
index aa26d3ec994ea18e11b667afa5247c865dad7d83..dcab660ddc4b5c2b63dea7853d71536bcbdcdf06
GIT binary patch
literal 401
zc$@)|0dD?@P)<h;3K|Lk000e1NJLTq000sI000>X1^@s6JPCf300007bV*G`2iFJ?
z4iX68H&229000SaNLh0L03N{r03N{s!)a7g00004XF*Lt006O%3;baP0003XNkl<Z
zc-pO#L2AP=5JjcY$Qav8U!u!Wa*JLey;?)H@LdX}>8d9v1iZ8{cI8-=MBFHWfHkpT
z7=tuV|9@o0R$BaJyM4T4zJF8d+k@J+eU84JbJq7g``YghN~z=PZuf~rQM^;62qAdW
zG#d*&0Eh>)i!U9{^W2>WDJ2fWpv$uSsO$Qvs;VCx$MLun)ODT7vJ9;XlcuTfT5Ar#
z8QOgl;mEk*xsoIir_gAixw}}bP513Vi!*X(jWImzK6n5cXs&;d5DX$9x9QZ3g1P`r
zk+)B75CB}~Bt=(h0!3mSYjDRqVj&16u4BysNQ!LGzRuQQop%)d)84WskdV>I(uFlM
v8G1(78ze=us`G<n>x7Lc>59UPwEks(O*M;#=A$wr00000NkvXXu0mjfAzi1$
index 7550d9c2f588e948a18cbb387d554646418701df..639da473e2c9a4c8c29470641a8fc8e9c52f25fe
GIT binary patch
literal 365
zc%17D@N?(olHy`uVBq!ia0vp^LO?9Z!3HF4IP0bWDfSXiUsv|)90Gho($SrKF+d^C
z0*}aI1_rr<Ak26;Gb9)&$dc~p>&U>cv7h@-A}f&p$J50zq~g}vDTaK940v2+kEbTA
zuwbZe_u5e0TExg^5xbLN4vW~X(!>O9QBh4_MGFs)HCH}P(y6Taw`uXTNHZo!#YMN@
zeh<sN_PVv9xPOtLMDhL=%QD0M?+f#CyuEGy?~er*&wqY%OO2eRsKryYB-3i<+2_G0
zwySTtX4lrR<ywHqQB%)Jo!2au?R(GOSjQd6SQ@L&R+#aicg>u`3g=c#ZZdha+;rna
z{&_uyk9zj4wQX*Awd<I|f>o=w$Q+Thd>$7hP^HXfso9~#^e8yziEmRwK%&Bg_*()B
zzH<cs?|jr)qAz~zg!sphE=L<ThdnzVUF%R<V9|Hf?Voow^WB3f;_u#+!~?^D!PC{x
JWt~$(698Apk2e4S
index 89746a47d3febb7e654109889776a0e1d5dce39c..131acc2e0c52dfdc3cd02cffadf66c3b0b624ace
GIT binary patch
literal 499
zc$@+A0Sx|$P)<h;3K|Lk000e1NJLTq000sI000>X1^@s6JPCf300007bV*G`2iFJ?
z4iXPRQ`#W_000SaNLh0L03N{r03N{s!)a7g00004XF*Lt006O%3;baP0004kNkl<Z
zc-pO$J#ND=424BXP7rv_UD})>y@M~%Q*`MCI%ZDx<P=$o^cu|;xNYJ;m82vi-9)1T
z2!n?C`SDSbG5@sSX}x}#T8xOF`@`W)Ky_X3)qe*t*Xz}MoKDBhW;1MeyH{71rJtf^
zu~^(5SE~nt9&b(a48t&NbBnvK<L@P`wca`BNm*G{)w?6&cP@wu8HNc;4^OMK2;Nch
zrS+JKA;N-Zhyu!1L;wy}1PtSxCMTf+G2jjYNtt86l&$@NMAMBc3Oy*oFtsM8K`{GA
zsR)yr)S7s7xm>b0Bo&*sZ9PwmgB8u^a|U^LKA%+}0tl$@d&!r}C5@lVrleJXfB+bu
zV`~<|__IOL?6e_AP%)#aQPSs9;-q{u8`IS2I?yY+8~q5f7&c@#v9<BcS&O{8ZKDBU
zSkfBs4M!{OY?Y$e6337f887F}-n5EH2*x%ccuhxy-m9j@MKMMYq50BtQ#=w?(IQh6
pGtZZQHi*udm~6ttgcsg7<`)rw8L~}|_&ops002ovPDHLkV1mC}(TV^7
index 60cf0c097a1d8bc58b83e81423b43acb6f439373..f04c048e272e8ee26ad0a7cac9665ff0bf0aa127
GIT binary patch
literal 373
zc$@)s0gC>KP)<h;3K|Lk000e1NJLTq000O8002t}1^@s6O~b}X00007bV*G`2iFJ?
z4iP3O%n^<N000SaNLh0L03N{r03N{s!)a7g00004XF*Lt006O%3;baP00035Nkl<Z
zc-rmK!ES>v3;@vB2^v8f=N|SA>z8!*to>~y{(^Es#Vnaqpldfbn^f%<ACL(T+k}AP
zc-!p??>#6X;N7{6wbh1bjQ7=dVB*8WVgLNP-M++yvMf~y;S0n|d}yszP1771Jl#~#
z8mstL+qOrowIZU^4M3b{o2KccgfI$bFpi@P04^0s1RC+2(DI!>0S~scpk#|-7}7Iv
zi;pDe`yTIrd4{g*v<Psi!29n-U<$K>AcCt^xdH<I0ua(b8<PgX&r=|xyir%VTw&P;
zJ{E9iA53vh_^-+>)?-lDwOnCM7*G;$g#QQr;R+A7aL$Pp#FLys1{q|K!Qa6rsPkQ$
TN6=6g00000NkvXXu0mjfn-G`$
index bc955065c33dc741e2c4f5e45693546d5edc4c67..4f20cab922eece148aad3ae7d1f90f7fa05be058
GIT binary patch
literal 219
zc%17D@N?(olHy`uVBq!ia0vp^j6m$o!3HEZUVGaNq}WS5eO=kFvq|upO8@Me@(w7(
zS>O>_%)lUb5QG^IXNCj=1zFM^eI0?i`nmrkvI6;8o-U3d6}Rqo9^^fuz{7G@>FLSl
zsCC^j%q!;!2?z->HP8L=Zt9c?wLN8JFL%F}PU?|gwN=hT)6}5&_?*qjJs-1kZX2X-
zxwh-2lP2p4%jy-YBt%?P{9_{jKbs?5@m}1CBPqf93ty$iUOn~8*>3H5EC)+~wla9S
L`njxgN@xNANmEO^
index 967b59fa391051f375edcf65bb69fb798dbb6ac2..b2f57867833fce9b6d6a7a4515514980a8ab7470
GIT binary patch
literal 400
zc%17D@N?(olHy`uVBq!ia0vp^96;>N!3HFK4<GXcQtTz3zOL-oIRy9w)#FbqN&tm8
z3p^r=85raaf-vLZ%#dK9AWOQVuOkD)#(wTUiL49^jPjl?jv*Dd-cGX3YjzN5O;2a%
z-sxcJkk=sceP>fGBiHkiA50%T=ctvKXkHQ&`S3~HY_rC+7=zb`ypDTh2>yOM`}pm^
z-EYfSjaxgueXV$N^>p2To6YrnO`;OT|3X4TRj04_(#)8ZR#k63*Y47n55AT2X1`v{
zv!zhR-X_<qe}de-jqiVd`*ktOd0J|GqD0fR9m^6Wq6D}C8B1f;nR2-1IO)GPK2U4T
zd7&eiJMf^ST5`{ehnF55=bn<<8Mi=#OPBf0!6@r4M@v?=H7o%R4tu(|-YpS#Xf<aj
zkF;|Tu6}S+xOvm!ui8HKhcY`Ejx!uFSKFq*)v!oINc7GM3x_%EKe$i*vp2Z6wjjM*
r#WPLx)vkGAEz(;VxHo{%zhA7obZQ=6YnsXf3_1o+S3j3^P6<r_l=YdQ
--- a/browser/themes/winstripe/browser/tabbrowser/tabbrowserBindings.xml
+++ b/browser/themes/winstripe/browser/tabbrowser/tabbrowserBindings.xml
@@ -57,17 +57,18 @@
                         anonid="alltabs-box-animate"/>
               <xul:toolbarbutton class="tabs-alltabs-button" type="menu"
                                  anonid="alltabs-button" 
                                  tooltipstring="&listAllTabs.label;">
                 <xul:menupopup class="tabs-alltabs-popup"
                                anonid="alltabs-popup" position="after_end"/>
               </xul:toolbarbutton>
             </xul:stack>
-            <xul:hbox class="tabs-closebutton-box" align="center" pack="end" anonid="tabstrip-closebutton">
+            <xul:hbox anonid="tabstrip-closebutton" class="tabs-closebutton-box"
+                      align="center" pack="end" chromedir="&locale.dir;">
               <xul:toolbarbutton class="close-button tabs-closebutton"/>
             </xul:hbox>
           </xul:hbox>
           <xul:spacer class="tabs-bottom-spacer"/>
         </xul:vbox>
       </xul:stack>
     </content>
   </binding>
--- a/client.py
+++ b/client.py
@@ -1,11 +1,11 @@
 #!/usr/bin/python
 
-NSPR_CO_TAG = 'NSPR_HEAD_20070713'
+NSPR_CO_TAG = 'NSPR_HEAD_20070820'
 NSS_CO_TAG  = 'NSS_3_12_ALPHA1B'
 
 NSPR_DIRS = ('nsprpub',)
 NSS_DIRS  = ('dbm',
              'security/nss',
              'security/coreconf',
              'security/dbm')
 
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -259,16 +259,18 @@ OS_LDFLAGS	= @LDFLAGS@
 
 OS_COMPILE_CFLAGS = $(OS_CPPFLAGS) @COMPILE_CFLAGS@
 OS_COMPILE_CXXFLAGS = $(OS_CPPFLAGS) @COMPILE_CXXFLAGS@
 
 OS_INCLUDES	= $(NSPR_CFLAGS) $(JPEG_CFLAGS) $(PNG_CFLAGS) $(ZLIB_CFLAGS) $(LCMS_CFLAGS)
 OS_LIBS		= @LIBS@
 ACDEFINES	= @MOZ_DEFINES@
 
+WARNINGS_AS_ERRORS = @WARNINGS_AS_ERRORS@
+
 MOZ_OPTIMIZE	= @MOZ_OPTIMIZE@
 MOZ_OPTIMIZE_FLAGS = @MOZ_OPTIMIZE_FLAGS@
 MOZ_OPTIMIZE_LDFLAGS = @MOZ_OPTIMIZE_LDFLAGS@
 
 MOZ_RTTI_FLAGS_ON = @_MOZ_RTTI_FLAGS_ON@
 
 PROFILE_GEN_CFLAGS = @PROFILE_GEN_CFLAGS@
 PROFILE_USE_CFLAGS = @PROFILE_USE_CFLAGS@
--- a/config/nsinstall.c
+++ b/config/nsinstall.c
@@ -106,18 +106,17 @@ mkdirs(char *path, mode_t mode)
 
     /* strip trailing "/." */
     l = strlen(path);
     if(l > 1 && path[l - 1] == '.' && path[l - 2] == '/')
         path[l - 2] = 0;
 
     while (*path == '/' && path[1] == '/')
 	path++;
-    while ((cp = strrchr(path, '/')) && cp[1] == '\0')
-	*cp = '\0';
+    for (cp = strrchr(path, '/'); cp && cp != path && *(cp - 1) == '/'; cp--);
     if (cp && cp != path) {
 	*cp = '\0';
 	if ((lstat(path, &sb) < 0 || !S_ISDIR(sb.st_mode)) &&
 	    mkdirs(path, mode) < 0) {
 	    return -1;
 	}
 	*cp = '/';
     }
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -1064,22 +1064,20 @@ ifdef NO_LD_ARCHIVE_FLAGS
 ifdef SHARED_LIBRARY_LIBS
 	@rm -f $(SUB_SHLOBJS)
 	@for lib in $(SHARED_LIBRARY_LIBS); do $(AR_EXTRACT) $${lib}; $(CLEANUP2); done
 endif # SHARED_LIBRARY_LIBS
 endif # NO_LD_ARCHIVE_FLAGS
 	$(MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(RESFILE) $(LDFLAGS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
 ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
 ifdef MSMANIFEST_TOOL
-ifdef EMBED_MANIFEST_AT
 	@if test -f $@.manifest; then \
-		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;$(EMBED_MANIFEST_AT); \
+		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;2; \
 		rm -f $@.manifest; \
 	fi
-endif   # embed manifest
 endif	# MSVC with manifest tool
 endif	# WINNT && !GCC
 ifeq ($(OS_ARCH),Darwin)
 	@for lib in $(SHARED_LIBRARY_LIBS); do \
 		libdir=`echo $$lib|sed -e 's,/[^/]*\.a,,'`; \
 		ofiles=`$(AR_LIST) $${lib}`; \
 		for ofile in $$ofiles; do \
 			if [ -f $$libdir/$$ofile ]; then \
@@ -1132,37 +1130,22 @@ fi
 endef
 endif # Sun Studio on Solaris
 else # COMPILER_DEPEND
 #
 # Generate dependencies on the fly
 #
 _MDDEPFILE = $(MDDEPDIR)/$(@F).pp
 
-ifeq (,$(CROSS_COMPILE)$(filter-out WINCE WINNT,$(OS_ARCH)))
 define MAKE_DEPS_AUTO
 if test -d $(@D); then \
 	echo "Building deps for $<"; \
-	touch $(_MDDEPFILE) && \
-	$(MKDEPEND) -o'.$(OBJ_SUFFIX)' -f$(_MDDEPFILE) $(DEFINES) $(ACDEFINES) $(INCLUDES) $< >/dev/null 2>&1 && \
-	mv $(_MDDEPFILE) $(_MDDEPFILE).old && \
-	cat $(_MDDEPFILE).old | sed -e "s|^$(srcdir)[^ ]*/||" -e "s|^$(win_srcdir)[^ ]*/||" > $(_MDDEPFILE) && rm -f $(_MDDEPFILE).old ; \
+	$(MKDEPEND) -o'.$(OBJ_SUFFIX)' -f- $(DEFINES) $(ACDEFINES) $(INCLUDES) $< 2>/dev/null | sed -e "s|^[^ ]*/||" > $(_MDDEPFILE) ; \
 fi
 endef
-else
-define MAKE_DEPS_AUTO
-if test -d $(@D); then \
-	echo "Building deps for $<"; \
-	touch $(_MDDEPFILE) && \
-	$(MKDEPEND) -o'.$(OBJ_SUFFIX)' -f$(_MDDEPFILE) $(DEFINES) $(ACDEFINES) $(INCLUDES) $< >/dev/null 2>&1 && \
-	mv $(_MDDEPFILE) $(_MDDEPFILE).old && \
-	cat $(_MDDEPFILE).old | sed -e "s|^$(<D)/||g" > $(_MDDEPFILE) && rm -f $(_MDDEPFILE).old ; \
-fi
-endef
-endif # WINNT
 
 MAKE_DEPS_AUTO_CC = $(MAKE_DEPS_AUTO)
 MAKE_DEPS_AUTO_CXX = $(MAKE_DEPS_AUTO)
 
 endif # COMPILER_DEPEND
 
 endif # MOZ_AUTO_DEPS
 
@@ -1893,31 +1876,19 @@ else
 		it is on by default.' 1>&2; \
 	echo "$$space"'To turn it off, pass --disable-md to configure.' 1>&2
 endif
 
 else # ! COMPILER_DEPEND
 
 ifndef MOZ_AUTO_DEPS
 
-ifeq ($(OS_ARCH),WINNT)
 define MAKE_DEPS_NOAUTO
-	set -e ; \
-	touch $@ && \
-	$(MKDEPEND) -w1024 -o'.$(OBJ_SUFFIX)' -f$@ $(DEFINES) $(ACDEFINES) $(INCLUDES) $(srcdir)/$(<F) >/dev/null 2>&1 && \
-	mv $@ $@.old && cat $@.old | sed "s|^$(srcdir)[^ ]*/||g" > $@ && rm -f $@.old
+	$(MKDEPEND) -w1024 -o'.$(OBJ_SUFFIX)' -f- $(DEFINES) $(ACDEFINES) $(INCLUDES) $< 2>/dev/null | sed -e "s|^[^ ]*/||" > $@
 endef
-else
-define MAKE_DEPS_NOAUTO
-	set -e ; \
-	touch $@ && \
-	$(MKDEPEND) -w1024 -o'.$(OBJ_SUFFIX)' -f$@ $(DEFINES) $(ACDEFINES) $(INCLUDES) $< >/dev/null 2>&1 && \
-	mv $@ $@.old && cat $@.old | sed "s|^$(<D)/||g" > $@ && rm -f $@.old
-endef
-endif # WINNT
 
 $(MDDEPDIR)/%.pp: %.c
 	$(REPORT_BUILD)
 	@$(MAKE_DEPS_NOAUTO)
 
 $(MDDEPDIR)/%.pp: %.cpp
 	$(REPORT_BUILD)
 	@$(MAKE_DEPS_NOAUTO)
--- a/configure.in
+++ b/configure.in
@@ -1209,16 +1209,17 @@ dnl ====================================
 if test "$GNU_CC"; then
     MKSHLIB='$(CXX) $(CXXFLAGS) $(DSO_PIC_CFLAGS) $(DSO_LDOPTS) -Wl,-h,$@ -o $@'
     MKCSHLIB='$(CC) $(CFLAGS) $(DSO_PIC_CFLAGS) $(DSO_LDOPTS) -Wl,-h,$@ -o $@'
     DSO_LDOPTS='-shared'
     if test "$GCC_USE_GNU_LD"; then
         # Don't allow undefined symbols in libraries
         DSO_LDOPTS="$DSO_LDOPTS -Wl,-z,defs"
     fi
+    WARNINGS_AS_ERRORS='-Werror'
     DSO_CFLAGS=''
     DSO_PIC_CFLAGS='-fPIC'
     _MOZ_RTTI_FLAGS_ON=${_COMPILER_PREFIX}-frtti
     _MOZ_RTTI_FLAGS_OFF=${_COMPILER_PREFIX}-fno-rtti
     _MOZ_EXCEPTIONS_FLAGS_ON='-fhandle-exceptions'
     _MOZ_EXCEPTIONS_FLAGS_OFF='-fno-handle-exceptions'
 
     # Turn on GNU specific features
@@ -1729,16 +1730,17 @@ case "$target" in
     SYSTEM_MAKEDEPEND=
 
     HOST_CC=cl
     HOST_CXX=cl
     HOST_LD=link
     HOST_AR='lib -OUT:$@'
     HOST_RANLIB='echo ranlib'
         
+    WARNINGS_AS_ERRORS='-WX'
 	MOZ_OPTIMIZE_FLAGS='-O1'
     AR_FLAGS='-NOLOGO -OUT:"$@"'
     ASM_SUFFIX=asm
     CFLAGS="$CFLAGS -W3 -Gy -Fd\$(PDBFILE)"
     CXXFLAGS="$CXXFLAGS -W3 -Gy -Fd\$(PDBFILE)"
     DLL_PREFIX=
     DOXYGEN=:
     DSO_LDOPTS=-SUBSYSTEM:WINDOWSCE
@@ -1754,17 +1756,16 @@ case "$target" in
     MKSHLIB_FORCE_ALL=
     MKSHLIB_UNFORCE_ALL=
     MOZ_COMPONENT_NSPR_LIBS='$(NSPR_LIBS)'
     MOZ_COMPONENT_NSPR_LIBS='$(NSPR_LIBS)'
     MOZ_DEBUG_FLAGS='-Zi'
     MOZ_DEBUG_LDFLAGS='-DEBUG -DEBUGTYPE:CV'
     MOZ_FIX_LINK_PATHS=
     MOZ_JS_LIBS='$(LIBXUL_DIST)/lib/js$(MOZ_BITS)$(VERSION_NUMBER).lib'
-    MOZ_OPTIMIZE_FLAGS='-O1'
     MOZ_XPCOM_OBSOLETE_LIBS='$(LIBXUL_DIST)/lib/xpcom_compat.lib'
     OBJ_SUFFIX=obj
     RANLIB='echo not_ranlib'
     STRIP='echo not_strip'
     TARGET_NSPR_MDCPUCFG='\"md/_wince.cfg\"'
     UNZIP=unzip
     XARGS=xargs
     XPCOM_FROZEN_LDOPTS='$(LIBXUL_DIST)/lib/xpcom.lib'
@@ -1846,16 +1847,17 @@ case "$target" in
         MKSHLIB_FORCE_ALL=
         MKSHLIB_UNFORCE_ALL=
         DSO_LDOPTS=-SUBSYSTEM:WINDOWS
         CFLAGS="$CFLAGS -W3 -Gy -Fd\$(PDBFILE)"
         CXXFLAGS="$CXXFLAGS -W3 -Gy -Fd\$(PDBFILE)"
         LIBS="$LIBS kernel32.lib user32.lib gdi32.lib winmm.lib wsock32.lib advapi32.lib"
         MOZ_DEBUG_FLAGS='-Zi'
         MOZ_DEBUG_LDFLAGS='-DEBUG -DEBUGTYPE:CV'
+        WARNINGS_AS_ERRORS='-WX'
     	MOZ_OPTIMIZE_FLAGS='-O1'
         MOZ_JS_LIBS='$(LIBXUL_DIST)/lib/js$(MOZ_BITS)$(VERSION_NUMBER).lib'
         MOZ_FIX_LINK_PATHS=
         DYNAMIC_XPCOM_LIBS='$(LIBXUL_DIST)/lib/xpcom.lib $(LIBXUL_DIST)/lib/xpcom_core.lib'
         XPCOM_FROZEN_LDOPTS='$(LIBXUL_DIST)/lib/xpcom.lib'
         LIBXUL_LIBS='$(LIBXUL_DIST)/lib/xpcom.lib $(LIBXUL_DIST)/lib/xul.lib'
         MOZ_COMPONENT_NSPR_LIBS='$(NSPR_LIBS)'
         MOZ_XPCOM_OBSOLETE_LIBS='$(LIBXUL_DIST)/lib/xpcom_compat.lib'
@@ -2037,16 +2039,17 @@ case "$target" in
     MKCSHLIB='$(CC) $(CFLAGS) $(DSO_PIC_CFLAGS) $(DSO_LDOPTS) -Wl,-soname,lib$(LIBRARY_NAME)$(DLL_SUFFIX) -o $@'
     ;;
 
 *-nto*) 
 	AC_DEFINE(NTO)	
 	AC_DEFINE(_QNX_SOURCE)
 	AC_DEFINE(_i386)
 	OS_TARGET=NTO
+	WARNINGS_AS_ERRORS=''
 	MOZ_OPTIMIZE_FLAGS="-O"
 	MOZ_DEBUG_FLAGS="-gstabs"
 	USE_PTHREADS=1
 	_PEDANTIC=
 	LIBS="$LIBS -lsocket -lstdc++"
 	_DEFINES_CFLAGS='-Wp,-include -Wp,$(DEPTH)/mozilla-config.h -DMOZILLA_CLIENT -D_POSIX_C_SOURCE=199506'
 	_DEFINES_CXXFLAGS='-DMOZILLA_CLIENT -Wp,-include -Wp,$(DEPTH)/mozilla-config.h -D_POSIX_C_SOURCE=199506'
 	if test "$with_x" != "yes"
@@ -2131,16 +2134,17 @@ case "$target" in
         AR_FLAGS='r $@'
         CFLAGS="$CFLAGS -Zomf"
         CXXFLAGS="$CXXFLAGS -Zomf"
         DSO_LDOPTS='-Zdll'
         BIN_FLAGS='-Zlinker /ST:0x100000'
         IMPLIB='emximp -o'
         FILTER='emxexp -o'
         LDFLAGS='-Zmap'
+        WARNINGS_AS_ERRORS='-Werror'
         MOZ_DEBUG_FLAGS="-g -fno-inline"
         MOZ_OPTIMIZE_FLAGS="-O2 -s"
         MOZ_OPTIMIZE_LDFLAGS="-Zlinker /EXEPACK:2 -Zlinker /PACKCODE -Zlinker /PACKDATA"
         MOZ_XPCOM_OBSOLETE_LIBS='-L$(LIBXUL_DIST)/lib $(LIBXUL_DIST)/lib/xpcomct.lib'
         DYNAMIC_XPCOM_LIBS='-L$(LIBXUL_DIST)/lib $(LIBXUL_DIST)/lib/xpcom.lib $(LIBXUL_DIST)/lib/xpcomcor.lib'
         LIBXUL_LIBS='-L$(LIBXUL_DIST)/lib $(LIBXUL_DIST)/lib/xpcom.lib $(LIBXUL_DIST)/lib/xul.lib'
         if test -n "$MOZ_OS2_HIGH_MEMORY"; then
           DSO_LDOPTS="$DSO_LDOPTS -Zhigh-mem"
@@ -2176,16 +2180,17 @@ case "$target" in
         AS=alp
         ASFLAGS='-Mb'
         AS_DASH_C_FLAG=''
         ASM_SUFFIX=asm
         LD='-ilink'
         CFLAGS="/Q /qlibansi /Gm+ /Su4 /Mp /Tl9"
         CXXFLAGS="/Q /qlibansi /Gm+ /Su4 /Mp /Tl9 /Gx+"
         MOZ_DEBUG_FLAGS="/Ti+"
+        WARNINGS_AS_ERRORS='-WX'
         MOZ_OPTIMIZE_FLAGS="/O+ /Gl+ /G5 /qarch=pentium"
         LDFLAGS="/NOL /M"
         MOZ_DEBUG_LDFLAGS="/DE"
         MOZ_OPTIMIZE_LDFLAGS="/OPTFUNC /EXEPACK:2 /PACKCODE /PACKDATA"
         DSO_LDOPTS=''
         DSO_PIC_CFLAGS=
         IMPLIB='implib /NOL /NOI'
         FILTER='cppfilt -q -B -P'
@@ -2274,16 +2279,17 @@ dnl the qsort routine under solaris is f
        if test -z "$CROSS_COMPILE" && test -f /usr/lib/ld/map.noexstk; then
            _SAVE_LDFLAGS=$LDFLAGS
            LDFLAGS="-M /usr/lib/ld/map.noexstk $LDFLAGS" 
            AC_TRY_LINK([#include <stdio.h>],
                        [printf("Hello World\n");],
                        ,
                        [LDFLAGS=$_SAVE_LDFLAGS])
        fi
+       WARNINGS_AS_ERRORS='-Werror'
        MOZ_OPTIMIZE_FLAGS="-xO4"
        MKSHLIB='$(CXX) $(CXXFLAGS) $(DSO_PIC_FLAGS) $(DSO_LDOPTS) -h $@ -o $@'
        MKCSHLIB='$(CC) $(CFLAGS) $(DSO_PIC_FLAGS) -G -z muldefs -h $@ -o $@'
        MKSHLIB_FORCE_ALL='-z allextract'
        MKSHLIB_UNFORCE_ALL='-z defaultextract'
        DSO_LDOPTS='-G -z muldefs'
        AR_LIST="$AR t"
        AR_EXTRACT="$AR x"
@@ -7420,16 +7426,17 @@ AC_SUBST(MOZ_JS_LIBS)
 AC_SUBST(MOZ_PSM)
 AC_SUBST(MOZ_DEBUG)
 AC_SUBST(MOZ_DEBUG_MODULES)
 AC_SUBST(MOZ_PROFILE_MODULES)
 AC_SUBST(MOZ_DEBUG_ENABLE_DEFS)
 AC_SUBST(MOZ_DEBUG_DISABLE_DEFS)
 AC_SUBST(MOZ_DEBUG_FLAGS)
 AC_SUBST(MOZ_DEBUG_LDFLAGS)
+AC_SUBST(WARNINGS_AS_ERRORS)
 AC_SUBST(MOZ_DBGRINFO_MODULES)
 AC_SUBST(MOZ_EXTENSIONS)
 AC_SUBST(MOZ_IMG_DECODERS)
 AC_SUBST(MOZ_IMG_ENCODERS)
 AC_SUBST(MOZ_JSDEBUGGER)
 AC_SUBST(MOZ_OJI)
 AC_SUBST(MOZ_NO_XPCOM_OBSOLETE)
 AC_SUBST(MOZ_PLUGINS)
@@ -7696,16 +7703,17 @@ dnl ====================================
 if test "$OS_ARCH" = "OS2" -a "$VACPP" = "yes"; then
       LIBS='so32dll.lib tcp32dll.lib'
 elif test "$OS_ARCH" = "BeOS"; then
   AC_DEFINE(XP_BEOS)
   MOZ_MOVEMAIL=1
 elif test "$OS_ARCH" = "Darwin"; then
   AC_DEFINE(XP_UNIX)
   AC_DEFINE(UNIX_ASYNC_DNS)
+  MOZ_MOVEMAIL=1
 elif test "$OS_ARCH" = "OpenVMS"; then
   AC_DEFINE(XP_UNIX)
 elif test "$OS_ARCH" != "WINNT" -a "$OS_ARCH" != "OS2" -a "$OS_ARCH" != "WINCE"; then
   AC_DEFINE(XP_UNIX)
   AC_DEFINE(UNIX_ASYNC_DNS)
   MOZ_MOVEMAIL=1
 fi
 AC_SUBST(MOZ_MOVEMAIL)
--- a/content/base/public/nsISelection2.idl
+++ b/content/base/public/nsISelection2.idl
@@ -42,24 +42,60 @@ interface nsIDOMNode;
 interface nsIDOMRange;
 
 %{C++
 #include "nsCOMArray.h"
 %}
 
 [ptr] native RangeArray(nsCOMArray<nsIDOMRange>);
 
-[scriptable, uuid(eab4ae76-efdc-4e09-828c-bd921e9a662f)]
+[scriptable, uuid(b515878d-3b06-433b-bc9e-5c53d2fa3eff)]
 interface nsISelection2 : nsISelection
 {
   void GetRangesForInterval(
       in nsIDOMNode beginNode, in PRInt32 beginOffset,
       in nsIDOMNode endNode, in PRInt32 endOffset,
       in PRBool allowAdjacent,
       out PRUint32 resultCount,
       [retval, array, size_is(resultCount)] out nsIDOMRange results);
 
   [noscript] void GetRangesForIntervalCOMArray(
       in nsIDOMNode beginNode, in PRInt32 beginOffset,
       in nsIDOMNode endNode, in PRInt32 endOffset,
       in PRBool allowAdjacent,
       in RangeArray results);
+
+  /**
+   * Scrolls a region of the selection, so that it is visible in
+   * the scrolled view.
+   *
+   * @param aRegion - the region inside the selection to scroll into view
+   *                  (see selection region constants defined in
+   *                   nsISelectionController).
+   * @param aIsSynchronous - when true, scrolls the selection into view
+   *                         before returning. If false, posts a request which
+   *                         is processed at some point after the method returns.
+   * @param aVPercent - how to align the frame vertically. A value of 0
+   *                   means the frame's upper edge is aligned with the top edge
+   *                   of the visible area. A value of 100 means the frame's
+   *                   bottom edge is aligned with the bottom edge of
+   *                   the visible area. For values in between, the point
+   *                   "aVPercent" down the frame is placed at the point
+   *                   "aVPercent" down the visible area. A value of 50 centers
+   *                   the frame vertically. A value of -1 means move
+   *                   the frame the minimum amount necessary in order for
+   *                   the entire frame to be visible vertically (if possible).
+   * @param aHPercent - how to align the frame horizontally. A value of 0
+   *                    means the frame's left edge is aligned with the left
+   *                    edge of the visible area. A value of 100 means the
+   *                    frame's right edge is aligned with the right edge of
+   *                    the visible area. For values in between, the point
+   *                    "aHPercent" across the frame is placed at the point
+   *                    "aHPercent" across the visible area. A value of 50
+   *                    centers the frame horizontally . A value of -1 means
+   *                    move the frame the minimum amount necessary in order
+   *                    for the entire frame to be visible horizontally
+   *                    (if possible).
+   */
+  void scrollIntoView(in short aRegion, in boolean aIsSynchronous,
+                      in short aVPercent, in short aHPercent);
 };
+
--- a/content/base/src/Makefile.in
+++ b/content/base/src/Makefile.in
@@ -77,16 +77,17 @@ REQUIRES	= xpcom \
 		  prefetch \
 		  xuldoc \
 		  uriloader \
 		  rdf \
 		  xultmpl \
 		  util \
 		  appshell \
 		  shistory \
+		  accessibility \
 		  $(NULL)
 
 EXPORTS		= \
 		nsAtomListUtils.h \
 		nsAttrName.h \
 		nsContentList.h \
 		nsGkAtomList.h \
 		nsGkAtoms.h \
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -72,16 +72,18 @@
 #include "nsIDOMAbstractView.h"
 #include "nsIDOMDocumentXBL.h"
 #include "nsGenericElement.h"
 #include "nsIDOMEventGroup.h"
 #include "nsIDOMCDATASection.h"
 #include "nsIDOMProcessingInstruction.h"
 #include "nsDOMString.h"
 #include "nsNodeUtils.h"
+#include "nsLayoutUtils.h" // for GetFrameForPoint
+#include "nsIFrame.h"
 
 #include "nsRange.h"
 #include "nsIDOMText.h"
 #include "nsIDOMComment.h"
 #include "nsDOMDocumentType.h"
 #include "nsTreeWalker.h"
 
 #include "nsIServiceManager.h"
@@ -1646,16 +1648,70 @@ nsDocument::GetActiveElement(nsIDOMEleme
     }
   }
 
   // If we couldn't get a BODY, return the root element.
   return GetDocumentElement(aElement);
 }
 
 NS_IMETHODIMP
+nsDocument::ElementFromPoint(PRInt32 aX, PRInt32 aY, nsIDOMElement** aReturn)
+{
+  NS_ENSURE_ARG_POINTER(aReturn);
+  *aReturn = nsnull;
+  // As per the the spec, we return null if either coord is negative
+  if (aX < 0 || aY < 0)
+    return NS_OK;
+
+  nscoord x = nsPresContext::CSSPixelsToAppUnits(aX);
+  nscoord y = nsPresContext::CSSPixelsToAppUnits(aY);
+  nsPoint pt(x, y);
+
+  // Make sure the layout information we get is up-to-date, and
+  // ensure we get a root frame (for everything but XUL)
+  FlushPendingNotifications(Flush_Layout);
+
+  nsIPresShell *ps = GetPrimaryShell();
+  NS_ENSURE_STATE(ps);
+  nsIFrame *rootFrame = ps->GetRootFrame();
+
+  // XUL docs, unlike HTML, have no frame tree until everything's done loading
+  if (!rootFrame)
+    return NS_OK; // return null to premature XUL callers as a reminder to wait
+
+  nsIFrame *ptFrame = nsLayoutUtils::GetFrameForPoint(rootFrame, pt, PR_TRUE);
+  if (!ptFrame)
+    return NS_OK;
+
+  nsIContent* ptContent = ptFrame->GetContent();
+  NS_ENSURE_STATE(ptContent);
+
+  // If the content is in a subdocument, try to get the element from |this| doc
+  nsIDocument *currentDoc = ptContent->GetCurrentDoc();
+  if (currentDoc && (currentDoc != this)) {
+    *aReturn = CheckAncestryAndGetFrame(currentDoc).get();
+    return NS_OK;
+  }
+
+  // If we have an anonymous element (such as an internal div from a textbox),
+  // or a node that isn't an element (such as a text frame node),
+  // replace it with the first non-anonymous parent node of type element.
+  while (ptContent &&
+         !ptContent->IsNodeOfType(nsINode::eELEMENT) ||
+         ptContent->GetBindingParent() ||
+         ptContent->IsNativeAnonymous()) {
+    ptContent = ptContent->GetParent();
+  }
+ 
+  if (ptContent)
+    CallQueryInterface(ptContent, aReturn);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
 nsDocument::GetElementsByClassName(const nsAString& aClasses,
                                    nsIDOMNodeList** aReturn)
 {
   return GetElementsByClassNameHelper(mRootContent, aClasses, aReturn);
 }
 
 
 // static GetElementsByClassName helpers
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -120,16 +120,21 @@
 #include "nsContentCreatorFunctions.h"
 #include "nsIFocusController.h"
 #include "nsIControllers.h"
 #include "nsXBLInsertionPoint.h"
 #ifdef MOZ_XUL
 #include "nsIXULDocument.h"
 #endif /* MOZ_XUL */
 
+#ifdef ACCESSIBILITY
+#include "nsIAccessibilityService.h"
+#include "nsIAccessibleEvent.h"
+#endif /* ACCESSIBILITY */
+
 #include "nsCycleCollectionParticipant.h"
 #include "nsCCUncollectableMarker.h"
 #include "nsCycleCollector.h"
 
 #ifdef MOZ_SVG
 PRBool NS_SVG_TestFeature(const nsAString &fstr);
 #endif /* MOZ_SVG */
 
@@ -2689,16 +2694,32 @@ nsGenericElement::doRemoveChildAt(PRUint
                                   nsIContent* aKid, nsIContent* aParent,
                                   nsIDocument* aDocument,
                                   nsAttrAndChildArray& aChildArray)
 {
   NS_PRECONDITION(aParent || aDocument, "Must have document if no parent!");
   NS_PRECONDITION(!aParent || aParent->GetCurrentDoc() == aDocument,
                   "Incorrect aDocument");
 
+#ifdef ACCESSIBILITY
+  // A11y needs to be notified of content removals first, so accessibility
+  // events can be fired before any changes occur
+  if (aNotify && aDocument) {
+    nsIPresShell *presShell = aDocument->GetPrimaryShell();
+    if (presShell && presShell->IsAccessibilityActive()) {
+      nsCOMPtr<nsIAccessibilityService> accService = 
+        do_GetService("@mozilla.org/accessibilityService;1");
+      if (accService) {
+        accService->InvalidateSubtreeFor(presShell, aKid,
+                                         nsIAccessibleEvent::EVENT_DOM_DESTROY);
+      }
+    }
+  }
+#endif
+
   nsMutationGuard::DidMutate();
 
   nsINode* container = NODE_FROM(aParent, aDocument);
   
   NS_PRECONDITION(aKid && aKid->GetParent() == aParent &&
                   aKid == container->GetChildAt(aIndex) &&
                   container->IndexOf(aKid) == (PRInt32)aIndex, "Bogus aKid");
 
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -180,16 +180,17 @@ GK_ATOM(cite, "cite")
 GK_ATOM(_class, "class")
 GK_ATOM(classid, "classid")
 GK_ATOM(clear, "clear")
 GK_ATOM(click, "click")
 GK_ATOM(clickcount, "clickcount")
 GK_ATOM(clip, "clip")
 GK_ATOM(close, "close")
 GK_ATOM(closed, "closed")
+GK_ATOM(closemenu, "closemenu")
 GK_ATOM(coalesceduplicatearcs, "coalesceduplicatearcs")
 GK_ATOM(code, "code")
 GK_ATOM(codebase, "codebase")
 GK_ATOM(codetype, "codetype")
 GK_ATOM(col, "col")
 GK_ATOM(colgroup, "colgroup")
 GK_ATOM(colGroupList, "ColGroup-list")
 GK_ATOM(collapse, "collapse")
--- a/content/base/src/nsTreeWalker.cpp
+++ b/content/base/src/nsTreeWalker.cpp
@@ -95,28 +95,32 @@ nsTreeWalker::nsTreeWalker(nsINode *aRoo
 }
 
 nsTreeWalker::~nsTreeWalker()
 {
     /* destructor code */
 }
 
 /*
- * nsISupports stuff
+ * nsISupports and cycle collection stuff
  */
 
+NS_IMPL_CYCLE_COLLECTION_3(nsTreeWalker, mFilter, mCurrentNode, mRoot)
+
 // QueryInterface implementation for nsTreeWalker
-NS_INTERFACE_MAP_BEGIN(nsTreeWalker)
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsTreeWalker)
     NS_INTERFACE_MAP_ENTRY(nsIDOMTreeWalker)
     NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMTreeWalker)
     NS_INTERFACE_MAP_ENTRY_CONTENT_CLASSINFO(TreeWalker)
 NS_INTERFACE_MAP_END
 
-NS_IMPL_ADDREF(nsTreeWalker)
-NS_IMPL_RELEASE(nsTreeWalker)
+NS_IMPL_CYCLE_COLLECTING_ADDREF(nsTreeWalker)
+NS_IMPL_CYCLE_COLLECTING_RELEASE(nsTreeWalker)
+
+
 
 /*
  * nsIDOMTreeWalker Getters/Setters
  */
 
 /* readonly attribute nsIDOMNode root; */
 NS_IMETHODIMP nsTreeWalker::GetRoot(nsIDOMNode * *aRoot)
 {
--- a/content/base/src/nsTreeWalker.h
+++ b/content/base/src/nsTreeWalker.h
@@ -43,33 +43,36 @@
 
 #ifndef nsTreeWalker_h___
 #define nsTreeWalker_h___
 
 #include "nsIDOMTreeWalker.h"
 #include "nsCOMPtr.h"
 #include "nsVoidArray.h"
 #include "nsJSUtils.h"
+#include "nsCycleCollectionParticipant.h"
 
 class nsINode;
 class nsIDOMNode;
 class nsIDOMNodeFilter;
 
 class nsTreeWalker : public nsIDOMTreeWalker
 {
 public:
-    NS_DECL_ISUPPORTS
+    NS_DECL_CYCLE_COLLECTING_ISUPPORTS
     NS_DECL_NSIDOMTREEWALKER
 
     nsTreeWalker(nsINode *aRoot,
                  PRUint32 aWhatToShow,
                  nsIDOMNodeFilter *aFilter,
                  PRBool aExpandEntityReferences);
     virtual ~nsTreeWalker();
-    /* additional members */
+
+    NS_DECL_CYCLE_COLLECTION_CLASS(nsTreeWalker)
+
 private:
     nsCOMPtr<nsINode> mRoot;
     PRUint32 mWhatToShow;
     nsCOMPtr<nsIDOMNodeFilter> mFilter;
     PRBool mExpandEntityReferences;
     nsCOMPtr<nsINode> mCurrentNode;
     
     /*
--- a/content/events/public/nsIEventStateManager.h
+++ b/content/events/public/nsIEventStateManager.h
@@ -49,18 +49,18 @@ class nsIView;
 class nsIWidget;
 class imgIContainer;
 
 /*
  * Event state manager interface.
  */
 // {fb7516ff-2f01-4893-84e8-e4b282813023}
 #define NS_IEVENTSTATEMANAGER_IID \
-{ 0xfb7516ff, 0x2f01, 0x4893, \
-  { 0x84, 0xe8, 0xe4, 0xb2, 0x82, 0x81, 0x30, 0x23 } }
+{ 0x522d12ec, 0xde51, 0x4635, \
+  { 0xb0, 0x10, 0x4, 0x2a, 0x6d, 0x5, 0xa0, 0x3e } }
 
 #define NS_EVENT_NEEDS_FRAME(event) (!NS_IS_FOCUS_EVENT(event))
 
 class nsIEventStateManager : public nsISupports {
 
 public:
   enum EFocusedWithType {
     eEventFocusedByUnknown,     // focus gained via unknown method
@@ -127,19 +127,43 @@ public:
   NS_IMETHOD MoveFocusToCaret(PRBool aCanFocusDoc, PRBool *aIsSelectionWithFocus) = 0;
   NS_IMETHOD MoveCaretToFocus() = 0;
 
   // Set focus on any element that can receive focus, or on document via aFocusContent == nsnull
   // Must supply method that focus is being set with
   NS_IMETHOD ChangeFocusWith(nsIContent *aFocusContent, EFocusedWithType aFocusedWith) = 0;
 
   // Access Key Registration
+
+  /**
+   * Register accesskey on the given element. When accesskey is activated then
+   * the element will be notified via nsIContent::PerformAccesskey() method.
+   *
+   * @param  aContent  the given element
+   * @param  aKey      accesskey
+   */
   NS_IMETHOD RegisterAccessKey(nsIContent* aContent, PRUint32 aKey) = 0;
+
+  /**
+   * Unregister accesskey for the given element.
+   *
+   * @param  aContent  the given element
+   * @param  aKey      accesskey
+   */
   NS_IMETHOD UnregisterAccessKey(nsIContent* aContent, PRUint32 aKey) = 0;
 
+  /**
+   * Get accesskey registered on the given element or 0 if there is none.
+   *
+   * @param  aContent  the given element
+   * @param  aKey      registered accesskey
+   * @return           NS_OK
+   */
+  NS_IMETHOD GetRegisteredAccessKey(nsIContent* aContent, PRUint32* aKey) = 0;
+
   NS_IMETHOD SetCursor(PRInt32 aCursor, imgIContainer* aContainer,
                        PRBool aHaveHotspot, float aHotspotX, float aHotspotY,
                        nsIWidget* aWidget, PRBool aLockCursor) = 0;
 
   // Method for moving the focus forward/back.
   NS_IMETHOD ShiftFocus(PRBool aDirection, nsIContent* aStart)=0;
 
   NS_IMETHOD NotifyDestroyPresContext(nsPresContext* aPresContext) = 0;
--- a/content/events/src/nsDOMBeforeUnloadEvent.cpp
+++ b/content/events/src/nsDOMBeforeUnloadEvent.cpp
@@ -56,18 +56,18 @@ nsDOMBeforeUnloadEvent::nsDOMBeforeUnloa
     mEvent->time = PR_Now();
   }
 }
 
 nsDOMBeforeUnloadEvent::~nsDOMBeforeUnloadEvent() 
 {
   if (mEventIsInternal &&
       mEvent->eventStructType == NS_BEFORE_PAGE_UNLOAD_EVENT) {
-      delete static_cast<nsBeforePageUnloadEvent*>(mEvent);
-      mEvent = nsnull;
+    delete static_cast<nsBeforePageUnloadEvent*>(mEvent);
+    mEvent = nsnull;
   }
 }
 
 NS_IMPL_ADDREF_INHERITED(nsDOMBeforeUnloadEvent, nsDOMEvent)
 NS_IMPL_RELEASE_INHERITED(nsDOMBeforeUnloadEvent, nsDOMEvent)
 
 NS_INTERFACE_MAP_BEGIN(nsDOMBeforeUnloadEvent)
   NS_INTERFACE_MAP_ENTRY(nsIDOMBeforeUnloadEvent)
--- a/content/events/src/nsDOMPopupBlockedEvent.cpp
+++ b/content/events/src/nsDOMPopupBlockedEvent.cpp
@@ -58,16 +58,19 @@ nsDOMPopupBlockedEvent::nsDOMPopupBlocke
 }
 
 nsDOMPopupBlockedEvent::~nsDOMPopupBlockedEvent() 
 {
   if (mEventIsInternal) {
     if (mEvent->eventStructType == NS_POPUPBLOCKED_EVENT) {
       nsPopupBlockedEvent* event = static_cast<nsPopupBlockedEvent*>(mEvent);
       NS_IF_RELEASE(event->mPopupWindowURI);
+
+      delete event;
+      mEvent = nsnull;
     }
   }
 }
 
 NS_IMPL_ADDREF_INHERITED(nsDOMPopupBlockedEvent, nsDOMEvent)
 NS_IMPL_RELEASE_INHERITED(nsDOMPopupBlockedEvent, nsDOMEvent)
 
 NS_INTERFACE_MAP_BEGIN(nsDOMPopupBlockedEvent)
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -88,17 +88,19 @@
 #include "nsIDOMEventTarget.h"
 #include "nsIEnumerator.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocShellTreeNode.h"
 #include "nsIWebNavigation.h"
 #include "nsIContentViewer.h"
 #include "nsIPrefBranch2.h"
 #include "nsIObjectFrame.h"
+#ifdef MOZ_XUL
 #include "nsXULPopupManager.h"
+#endif
 
 #include "nsIServiceManager.h"
 #include "nsIScriptSecurityManager.h"
 
 #include "nsIFocusController.h"
 
 #include "nsIDOMXULElement.h"
 #include "nsIDOMDocument.h"
@@ -172,16 +174,37 @@ PRInt32 nsEventStateManager::sUserInputE
 enum {
  MOUSE_SCROLL_N_LINES,
  MOUSE_SCROLL_PAGE,
  MOUSE_SCROLL_HISTORY,
  MOUSE_SCROLL_TEXTSIZE,
  MOUSE_SCROLL_PIXELS
 };
 
+struct AccessKeyInfo {
+  PRUint32 mAccessKey;
+  nsIContent* mTarget;
+
+  AccessKeyInfo(nsIContent* aTarget) : mAccessKey(0), mTarget(aTarget) {}
+};
+
+static PRIntn PR_CALLBACK
+FindTargetForAccessKey(nsHashKey *aKey, void *aData, void* aClosure)
+{
+  AccessKeyInfo* info = static_cast<AccessKeyInfo*>(aClosure);
+  nsIContent* aTarget = static_cast<nsIContent*>(aData);
+
+  if (aTarget == info->mTarget) {
+    info->mAccessKey = aKey->HashCode();
+    return kHashEnumerateStop;
+  }
+
+  return kHashEnumerateNext;
+}
+
 // mask values for ui.key.chromeAccess and ui.key.contentAccess
 #define NS_MODIFIER_SHIFT    1
 #define NS_MODIFIER_CONTROL  2
 #define NS_MODIFIER_ALT      4
 #define NS_MODIFIER_META     8
 
 static nsIDocument *
 GetDocumentFromWindow(nsIDOMWindow *aWindow)
@@ -3385,24 +3408,26 @@ nsEventStateManager::ShiftFocusInternal(
   nsIFrame* popupFrame = nsnull;
   if (curFocusFrame) {
     // check if the focus is currently inside a popup. Elements such as the
     // autocomplete widget use the noautofocus attribute to allow the focus to
     // remain outside the popup when it is opened.
     popupFrame = nsLayoutUtils::GetClosestFrameOfType(curFocusFrame,
                                                       nsGkAtoms::menuPopupFrame);
   }
+#ifdef MOZ_XUL
   else {
     // if there is no focus, yet a panel is open, focus the
     // first item in the popup
     nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
     if (pm) {
       popupFrame = pm->GetTopPopup(ePopupTypePanel);
     }
   }
+#endif
 
   if (popupFrame) {
     // Don't navigate outside of a popup, so pretend that the
     // root content is the popup itself
     rootContent = popupFrame->GetContent();
     NS_ASSERTION(rootContent, "Popup frame doesn't have a content node");
   }
 
@@ -4650,16 +4675,18 @@ nsEventStateManager::RegisterAccessKey(n
       return NS_ERROR_FAILURE;
     }
   }
 
   if (aContent) {
     PRUint32 accKey = (IS_IN_BMP(aKey)) ? ToLowerCase((PRUnichar)aKey) : aKey;
 
     nsVoidKey key(NS_INT32_TO_PTR(accKey));
+    NS_ASSERTION(key.HashCode() == accKey,
+                 "nsHashKey::HashCode() doesn't return an accesskey");
 
 #ifdef DEBUG_jag
     nsCOMPtr<nsIContent> oldContent = dont_AddRef(static_cast<nsIContent*>(mAccessKeys->Get(&key)));
     NS_ASSERTION(!oldContent, "Overwriting accesskey registration");
 #endif
     mAccessKeys->Put(&key, aContent);
   }
 
@@ -4685,16 +4712,34 @@ nsEventStateManager::UnregisterAccessKey
     if (oldContent != aContent)
       return NS_OK;
 
     mAccessKeys->Remove(&key);
   }
   return NS_OK;
 }
 
+NS_IMETHODIMP
+nsEventStateManager::GetRegisteredAccessKey(nsIContent* aContent,
+                                            PRUint32* aKey)
+{
+  NS_ENSURE_ARG(aContent);
+  NS_ENSURE_ARG_POINTER(aKey);
+  *aKey = 0;
+
+  if (!mAccessKeys)
+    return NS_OK;
+
+  AccessKeyInfo info(aContent);
+  mAccessKeys->Enumerate(FindTargetForAccessKey, &info);
+
+  *aKey = info.mAccessKey;
+  return NS_OK;
+}
+
 void
 nsEventStateManager::ForceViewUpdate(nsIView* aView)
 {
   // force the update to happen now, otherwise multiple scrolls can
   // occur before the update is processed. (bug #7354)
 
   nsIViewManager* vm = aView->GetViewManager();
   if (vm) {
--- a/content/events/src/nsEventStateManager.h
+++ b/content/events/src/nsEventStateManager.h
@@ -122,16 +122,17 @@ public:
   NS_IMETHOD GetLastFocusedContent(nsIContent **aContent);
   NS_IMETHOD GetFocusedFrame(nsIFrame **aFrame);
   NS_IMETHOD ContentRemoved(nsIContent* aContent);
   NS_IMETHOD EventStatusOK(nsGUIEvent* aEvent, PRBool *aOK);
 
   // Access Key Registration
   NS_IMETHOD RegisterAccessKey(nsIContent* aContent, PRUint32 aKey);
   NS_IMETHOD UnregisterAccessKey(nsIContent* aContent, PRUint32 aKey);
+  NS_IMETHOD GetRegisteredAccessKey(nsIContent* aContent, PRUint32* aKey);
 
   NS_IMETHOD SetCursor(PRInt32 aCursor, imgIContainer* aContainer,
                        PRBool aHaveHotspot, float aHotspotX, float aHotspotY,
                        nsIWidget* aWidget, PRBool aLockCursor);
 
   NS_IMETHOD ShiftFocus(PRBool aForward, nsIContent* aStart=nsnull);
 
   virtual PRBool GetBrowseWithCaret();
--- a/content/html/content/src/nsHTMLOptGroupElement.cpp
+++ b/content/html/content/src/nsHTMLOptGroupElement.cpp
@@ -43,16 +43,17 @@
 #include "nsIFrame.h"
 #include "nsIFormControlFrame.h"
 #include "nsIEventStateManager.h"
 #include "nsIDocument.h"
 
 #include "nsISelectElement.h"
 #include "nsIDOMHTMLSelectElement.h"
 #include "nsEventDispatcher.h"
+#include "nsHTMLSelectElement.h"
 
 /**
  * The implementation of &lt;optgroup&gt;
  */
 class nsHTMLOptGroupElement : public nsGenericHTMLElement,
                               public nsIDOMHTMLOptGroupElement
 {
 public:
@@ -169,33 +170,33 @@ nsHTMLOptGroupElement::GetSelect()
   return nsnull;
 }
 
 nsresult
 nsHTMLOptGroupElement::InsertChildAt(nsIContent* aKid,
                                      PRUint32 aIndex,
                                      PRBool aNotify)
 {
-  nsCOMPtr<nsISelectElement> sel = do_QueryInterface(GetSelect());
-  if (sel) {
-    sel->WillAddOptions(aKid, this, aIndex);
+  nsSafeOptionListMutation safeMutation(GetSelect(), this, aKid, aIndex);
+  nsresult rv = nsGenericHTMLElement::InsertChildAt(aKid, aIndex, aNotify);
+  if (NS_FAILED(rv)) {
+    safeMutation.MutationFailed();
   }
-
-  return nsGenericHTMLElement::InsertChildAt(aKid, aIndex, aNotify);
+  return rv;
 }
 
 nsresult
 nsHTMLOptGroupElement::RemoveChildAt(PRUint32 aIndex, PRBool aNotify)
 {
-  nsCOMPtr<nsISelectElement> sel = do_QueryInterface(GetSelect());
-  if (sel) {
-    sel->WillRemoveOptions(this, aIndex);
+  nsSafeOptionListMutation safeMutation(GetSelect(), this, nsnull, aIndex);
+  nsresult rv = nsGenericHTMLElement::RemoveChildAt(aIndex, aNotify);
+  if (NS_FAILED(rv)) {
+    safeMutation.MutationFailed();
   }
-
-  return nsGenericHTMLElement::RemoveChildAt(aIndex, aNotify);
+  return rv;
 }
 
 PRInt32
 nsHTMLOptGroupElement::IntrinsicState() const
 {
   PRInt32 state = nsGenericHTMLElement::IntrinsicState();
   PRBool disabled;
   GetBoolAttr(nsGkAtoms::disabled, &disabled);
--- a/content/html/content/src/nsHTMLSelectElement.cpp
+++ b/content/html/content/src/nsHTMLSelectElement.cpp
@@ -31,465 +31,101 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-#include "nsCOMPtr.h"
-#include "nsCOMArray.h"
-#include "nsIDOMHTMLSelectElement.h"
-#include "nsIDOMNSHTMLSelectElement.h"
-#include "nsIDOMNSXBLFormControl.h"
-#include "nsIDOMHTMLFormElement.h"
+
+#include "nsHTMLSelectElement.h"
 #include "nsIDOMEventTarget.h"
 #include "nsContentCreatorFunctions.h"
-#include "nsGenericHTMLElement.h"
 #include "nsGkAtoms.h"
 #include "nsStyleConsts.h"
 #include "nsPresContext.h"
 #include "nsLayoutUtils.h"
 #include "nsMappedAttributes.h"
 #include "nsIForm.h"
 #include "nsIFormSubmission.h"
-#include "nsIDOMHTMLCollection.h"
-#include "nsIDOMHTMLOptionElement.h"
+
 #include "nsIDOMHTMLOptGroupElement.h"
 #include "nsIOptionElement.h"
 #include "nsIEventStateManager.h"
-#include "nsISelectElement.h"
-#include "nsISelectControlFrame.h"
-#include "nsIDOMHTMLOptionsCollection.h"
-#include "nsIDOMNSHTMLOptionCollectn.h"
 #include "nsGUIEvent.h"
 #include "nsIPrivateDOMEvent.h"
 #include "nsIBoxObject.h"
 #include "nsIDOMNSDocument.h"
 #include "nsIDOMDocumentEvent.h"
 
-// PresState
-#include "nsXPCOM.h"
-#include "nsPresState.h"
-#include "nsIComponentManager.h"
-#include "nsCheapSets.h"
-#include "nsLayoutErrors.h"
-
 // Notify/query select frame for selectedIndex
 #include "nsIDocument.h"
 #include "nsIPresShell.h"
 #include "nsIFormControlFrame.h"
 #include "nsIComboboxControlFrame.h"
 #include "nsIListControlFrame.h"
 #include "nsIFrame.h"
 
 #include "nsDOMError.h"
 #include "nsRuleData.h"
 #include "nsEventDispatcher.h"
 
-class nsHTMLSelectElement;
-
-/**
- * The collection of options in the select (what you get back when you do
- * select.options in DOM)
- */
-class nsHTMLOptionCollection: public nsIDOMHTMLOptionsCollection,
-                              public nsIDOMNSHTMLOptionCollection,
-                              public nsIDOMHTMLCollection
-{
-public:
-  nsHTMLOptionCollection(nsHTMLSelectElement* aSelect);
-  virtual ~nsHTMLOptionCollection();
-
-  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-
-  // nsIDOMHTMLOptionsCollection interface
-  NS_DECL_NSIDOMHTMLOPTIONSCOLLECTION
-
-  // nsIDOMNSHTMLOptionCollection interface
-  NS_DECL_NSIDOMNSHTMLOPTIONCOLLECTION
-
-  // nsIDOMHTMLCollection interface, all its methods are defined in
-  // nsIDOMHTMLOptionsCollection
-
-  NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsHTMLOptionCollection,
-                                           nsIDOMNSHTMLOptionCollection)
-
-  // Helpers for nsHTMLSelectElement
-  /**
-   * Insert an option
-   * @param aOption the option to insert
-   * @param aIndex the index to insert at
-   */
-  PRBool InsertOptionAt(nsIDOMHTMLOptionElement* aOption, PRInt32 aIndex)
-  {
-    return mElements.InsertObjectAt(aOption, aIndex);
-  }
-
-  /**
-   * Remove an option
-   * @param aIndex the index of the option to remove
-   */
-  void RemoveOptionAt(PRInt32 aIndex)
-  {
-    mElements.RemoveObjectAt(aIndex);
-  }
-
-  /**
-   * Get the option at the index
-   * @param aIndex the index
-   * @param aReturn the option returned [OUT]
-   */
-  nsIDOMHTMLOptionElement *ItemAsOption(PRInt32 aIndex)
-  {
-    return mElements.SafeObjectAt(aIndex);
-  }
-
-  /**
-   * Clears out all options
-   */
-  void Clear()
-  {
-    mElements.Clear();
-  }
-
-  /**
-   * Append an option to end of array
-   */
-  PRBool AppendOption(nsIDOMHTMLOptionElement* aOption)
-  {
-    return mElements.AppendObject(aOption);
-  }
-
-  /**
-   * Drop the reference to the select.  Called during select destruction.
-   */
-  void DropReference();
-
-  /**
-   * See nsISelectElement.idl for documentation on this method
-   */
-  nsresult GetOptionIndex(nsIDOMHTMLOptionElement* aOption,
-                          PRInt32 aStartIndex, PRBool aForward,
-                          PRInt32* aIndex);
-
-private:
-  /** The list of options (holds strong references) */
-  nsCOMArray<nsIDOMHTMLOptionElement> mElements;
-  /** The select element that contains this array */
-  nsHTMLSelectElement* mSelect;
-};
-
-
-/**
- * The restore state used by select
- */
-class nsSelectState : public nsISupports {
-public:
-  nsSelectState()
-  {
-  }
-  virtual ~nsSelectState()
-  {
-  }
-
-  NS_DECL_ISUPPORTS
-
-  void PutOption(PRInt32 aIndex, const nsAString& aValue)
-  {
-    // If the option is empty, store the index.  If not, store the value.
-    if (aValue.IsEmpty()) {
-      mIndices.Put(aIndex);
-    } else {
-      mValues.Put(aValue);
-    }
-  }
-
-  PRBool ContainsOption(PRInt32 aIndex, const nsAString& aValue)
-  {
-    return mValues.Contains(aValue) || mIndices.Contains(aIndex);
-  }
-
-private:
-  nsCheapStringSet mValues;
-  nsCheapInt32Set mIndices;
-};
-
 NS_IMPL_ISUPPORTS0(nsSelectState)
 
-
-/**
- * Implementation of &lt;select&gt;
- */
-class nsHTMLSelectElement : public nsGenericHTMLFormElement,
-                            public nsIDOMHTMLSelectElement,
-                            public nsIDOMNSHTMLSelectElement,
-                            public nsIDOMNSXBLFormControl,
-                            public nsISelectElement
-{
-public:
-  nsHTMLSelectElement(nsINodeInfo *aNodeInfo, PRBool aFromParser = PR_FALSE);
-  virtual ~nsHTMLSelectElement();
-
-  // nsISupports
-  NS_DECL_ISUPPORTS_INHERITED
-
-  // nsIDOMNode
-  NS_FORWARD_NSIDOMNODE(nsGenericHTMLFormElement::)
-
-  // nsIDOMElement
-  NS_FORWARD_NSIDOMELEMENT(nsGenericHTMLFormElement::)
-
-  // nsIDOMHTMLElement
-  NS_FORWARD_NSIDOMHTMLELEMENT(nsGenericHTMLFormElement::)
-
-  // nsIDOMHTMLSelectElement
-  NS_DECL_NSIDOMHTMLSELECTELEMENT
-
-  // nsIDOMNSHTMLSelectElement
-  NS_DECL_NSIDOMNSHTMLSELECTELEMENT
-
-  // nsIDOMNSXBLFormControl
-  NS_DECL_NSIDOMNSXBLFORMCONTROL
-
-  // nsIContent
-  virtual nsresult PreHandleEvent(nsEventChainPreVisitor& aVisitor);
-
-  virtual void SetFocus(nsPresContext* aPresContext);
-  virtual PRBool IsFocusable(PRInt32 *aTabIndex = nsnull);
-  virtual nsresult InsertChildAt(nsIContent* aKid, PRUint32 aIndex,
-                                 PRBool aNotify);
-  virtual nsresult RemoveChildAt(PRUint32 aIndex, PRBool aNotify);
-
-  // Overriden nsIFormControl methods
-  NS_IMETHOD_(PRInt32) GetType() const { return NS_FORM_SELECT; }
-  NS_IMETHOD Reset();
-  NS_IMETHOD SubmitNamesValues(nsIFormSubmission* aFormSubmission,
-                               nsIContent* aSubmitElement);
-  NS_IMETHOD SaveState();
-  virtual PRBool RestoreState(nsPresState* aState);
-
-  // nsISelectElement
-  NS_DECL_NSISELECTELEMENT
-
-  /**
-   * Called when an attribute is about to be changed
-   */
-  virtual nsresult BeforeSetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
-                                 const nsAString* aValue, PRBool aNotify);
-  virtual nsresult UnsetAttr(PRInt32 aNameSpaceID, nsIAtom* aAttribute,
-                             PRBool aNotify);
-  
-  virtual nsresult DoneAddingChildren(PRBool aHaveNotified);
-  virtual PRBool IsDoneAddingChildren();
-
-  virtual PRBool ParseAttribute(PRInt32 aNamespaceID,
-                                nsIAtom* aAttribute,
-                                const nsAString& aValue,
-                                nsAttrValue& aResult);
-  virtual nsMapRuleToAttributesFunc GetAttributeMappingFunction() const;
-  virtual nsChangeHint GetAttributeChangeHint(const nsIAtom* aAttribute,
-                                              PRInt32 aModType) const;
-  NS_IMETHOD_(PRBool) IsAttributeMapped(const nsIAtom* aAttribute) const;
-
-  virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const;
-
-  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED_NO_UNLINK(nsHTMLSelectElement,
-                                                     nsGenericHTMLFormElement)
-
-protected:
-  // Helper Methods
-  /**
-   * Check whether the option specified by the index is selected
-   * @param aIndex the index
-   * @return whether the option at the index is selected
-   */
-  PRBool IsOptionSelectedByIndex(PRInt32 aIndex);
-  /**
-   * Starting with (and including) aStartIndex, find the first selected index
-   * and set mSelectedIndex to it.
-   * @param aStartIndex the index to start with
-   */
-  void FindSelectedIndex(PRInt32 aStartIndex);
-  /**
-   * Select some option if possible (generally the first non-disabled option).
-   * @return true if something was selected, false otherwise
-   */
-  PRBool SelectSomething();
-  /**
-   * Call SelectSomething(), but only if nothing is selected
-   * @see SelectSomething()
-   * @return true if something was selected, false otherwise
-   */
-  PRBool CheckSelectSomething();
-  /**
-   * Called to trigger notifications of frames and fixing selected index
-   *
-   * @param aSelectFrame the frame for this content (could be null)
-   * @param aPresContext the current pres context
-   * @param aIndex the index that was selected or deselected
-   * @param aSelected whether the index was selected or deselected
-   * @param aNotify whether to notify the style system and such
-   */
-  void OnOptionSelected(nsISelectControlFrame* aSelectFrame,
-                        nsPresContext* aPresContext,
-                        PRInt32 aIndex,
-                        PRBool aSelected,
-                        PRBool aNotify);
-  /**
-   * Restore state to a particular state string (representing the options)
-   * @param aNewSelected the state string to restore to
-   */
-  void RestoreStateTo(nsSelectState* aNewSelected);
-
-#ifdef DEBUG_john
-  // Don't remove these, por favor.  They're very useful in debugging
-  nsresult PrintOptions(nsIContent* aOptions, PRInt32 tabs);
-#endif
+//----------------------------------------------------------------------
+//
+// nsSafeOptionListMutation
+//
 
-  // Adding options
-  /**
-   * Insert option(s) into the options[] array and perform notifications
-   * @param aOptions the option or optgroup being added
-   * @param aListIndex the index to start adding options into the list at
-   * @param aDepth the depth of aOptions (1=direct child of select ...)
-   */
-  nsresult InsertOptionsIntoList(nsIContent* aOptions,
-                                 PRInt32 aListIndex,
-                                 PRInt32 aDepth);
-  /**
-   * Remove option(s) from the options[] array
-   * @param aOptions the option or optgroup being added
-   * @param aListIndex the index to start removing options from the list at
-   * @param aDepth the depth of aOptions (1=direct child of select ...)
-   */
-  nsresult RemoveOptionsFromList(nsIContent* aOptions,
-                                 PRInt32 aListIndex,
-                                 PRInt32 aDepth);
-  /**
-   * Insert option(s) into the options[] array (called by InsertOptionsIntoList)
-   * @param aOptions the option or optgroup being added
-   * @param aInsertIndex the index to start adding options into the list at
-   * @param aDepth the depth of aOptions (1=direct child of select ...)
-   */
-  nsresult InsertOptionsIntoListRecurse(nsIContent* aOptions,
-                                        PRInt32* aInsertIndex,
-                                        PRInt32 aDepth);
-  /**
-   * Remove option(s) from the options[] array (called by RemoveOptionsFromList)
-   * @param aOptions the option or optgroup being added
-   * @param aListIndex the index to start removing options from the list at
-   * @param aNumRemoved the number removed so far [OUT]
-   * @param aDepth the depth of aOptions (1=direct child of select ...)
-   */
-  nsresult RemoveOptionsFromListRecurse(nsIContent* aOptions,
-                                        PRInt32 aRemoveIndex,
-                                        PRInt32* aNumRemoved,
-                                        PRInt32 aDepth);
-  /**
-   * Find out how deep this content is from the select (1=direct child)
-   * @param aContent the content to check
-   * @return the depth
-   */
-  PRInt32 GetContentDepth(nsIContent* aContent);
-  /**
-   * Get the index of the first option at, under or following the content in
-   * the select, or length of options[] if none are found
-   * @param aOptions the content
-   * @return the index of the first option
-   */
-  PRInt32 GetOptionIndexAt(nsIContent* aOptions);
-  /**
-   * Get the next option following the content in question (not at or under)
-   * (this could include siblings of the current content or siblings of the
-   * parent or children of siblings of the parent).
-   * @param aOptions the content
-   * @return the index of the next option after the content
-   */
-  PRInt32 GetOptionIndexAfter(nsIContent* aOptions);
-  /**
-   * Get the first option index at or under the content in question.
-   * @param aOptions the content
-   * @return the index of the first option at or under the content
-   */
-  PRInt32 GetFirstOptionIndex(nsIContent* aOptions);
-  /**
-   * Get the first option index under the content in question, within the
-   * range specified.
-   * @param aOptions the content
-   * @param aStartIndex the first child to look at
-   * @param aEndIndex the child *after* the last child to look at
-   * @return the index of the first option at or under the content
-   */
-  PRInt32 GetFirstChildOptionIndex(nsIContent* aOptions,
-                                   PRInt32 aStartIndex,
-                                   PRInt32 aEndIndex);
+nsSafeOptionListMutation::nsSafeOptionListMutation(nsIContent* aSelect,
+                                                   nsIContent* aParent,
+                                                   nsIContent* aKid,
+                                                   PRUint32 aIndex)
+  : mSelect(do_QueryInterface(aSelect)), mTopLevelMutation(PR_FALSE),
+    mNeedsRebuild(PR_FALSE)
+{
+  nsHTMLSelectElement* select = static_cast<nsHTMLSelectElement*>(mSelect.get());
+  if (select) {
+    mTopLevelMutation = !select->mMutating;
+    if (mTopLevelMutation) {
+      select->mMutating = PR_TRUE;
+    } else {
+      // This is very unfortunate, but to handle mutation events properly,
+      // option list must be up-to-date before inserting or removing options.
+      // Fortunately this is called only if mutation event listener
+      // adds or removes options.
+      select->RebuildOptionsArray();
+    }
+    nsresult rv;
+    if (aKid) {
+      rv = mSelect->WillAddOptions(aKid, aParent, aIndex);
+    } else {
+      rv = mSelect->WillRemoveOptions(aParent, aIndex);
+    }
+    mNeedsRebuild = NS_FAILED(rv);
+  }
+}
 
-  /**
-   * Get the frame as an nsISelectControlFrame (MAY RETURN NULL)
-   * @return the select frame, or null
-   */
-  nsISelectControlFrame *GetSelectFrame();
-
-  /**
-   * Helper method for dispatching custom DOM events to our anonymous subcontent
-   * (for XBL form controls)
-   * @param aName the name of the event to dispatch
-   */
-  void DispatchDOMEvent(const nsAString& aName);
-
-  /**
-   * Is this a combobox?
-   */
-  PRBool IsCombobox() {
-    PRBool isMultiple = PR_TRUE;
-    PRInt32 size = 1;
-    GetSize(&size);
-    GetMultiple(&isMultiple);
-    return !isMultiple && size <= 1;
+nsSafeOptionListMutation::~nsSafeOptionListMutation()
+{
+  if (mSelect) {
+    nsHTMLSelectElement* select =
+      static_cast<nsHTMLSelectElement*>(mSelect.get());
+    if (mNeedsRebuild || (mTopLevelMutation && mGuard.Mutated(1))) {
+      select->RebuildOptionsArray();
+    }
+    if (mTopLevelMutation) {
+      select->mMutating = PR_FALSE;
+    }
+#ifdef DEBUG
+    select->VerifyOptionsArray();
+#endif
   }
-
-  /**
-   * Helper method for dispatching ContentReset notifications to list
-   * and combo box frames.
-   */
-  void DispatchContentReset();
-
-  /**
-   * Rebuilds the options array from scratch as a fallback in error cases.
-   */
-  void RebuildOptionsArray();
-
-#ifdef DEBUG
-  void VerifyOptionsArray();
-#endif
-
-  /** The options[] array */
-  nsRefPtr<nsHTMLOptionCollection> mOptions;
-  /** false if the parser is in the middle of adding children. */
-  PRPackedBool    mIsDoneAddingChildren;
-  /** true if our disabled state has changed from the default **/
-  PRPackedBool    mDisabledChanged;
-  /** The number of non-options as children of the select */
-  PRUint32  mNonOptionChildren;
-  /** The number of optgroups anywhere under the select */
-  PRUint32  mOptGroupCount;
-  /**
-   * The current selected index for selectedIndex (will be the first selected
-   * index if multiple are selected)
-   */
-  PRInt32   mSelectedIndex;
-  /**
-   * The temporary restore state in case we try to restore before parser is
-   * done adding options
-   */
-  nsRefPtr<nsSelectState> mRestoreState;
-};
-
+}
 
 //----------------------------------------------------------------------
 //
 // nsHTMLSelectElement
 //
 
 // construction, destruction
 
@@ -497,16 +133,17 @@ protected:
 NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(Select)
 
 nsHTMLSelectElement::nsHTMLSelectElement(nsINodeInfo *aNodeInfo,
                                          PRBool aFromParser)
   : nsGenericHTMLFormElement(aNodeInfo),
     mOptions(new nsHTMLOptionCollection(this)),
     mIsDoneAddingChildren(!aFromParser),
     mDisabledChanged(PR_FALSE),
+    mMutating(PR_FALSE),
     mNonOptionChildren(0),
     mOptGroupCount(0),
     mSelectedIndex(-1)
 {
   // FIXME: Bug 328908, set mOptions in an Init function and get rid of null
   // checks.
 
   // DoneAddingChildren() will be called later if it's from the parser,
@@ -556,49 +193,33 @@ nsHTMLSelectElement::GetForm(nsIDOMHTMLF
   return nsGenericHTMLFormElement::GetForm(aForm);
 }
 
 nsresult
 nsHTMLSelectElement::InsertChildAt(nsIContent* aKid,
                                    PRUint32 aIndex,
                                    PRBool aNotify)
 {
-  nsresult rv = WillAddOptions(aKid, this, aIndex);
-  PRBool rebuild = NS_FAILED(rv);
-
-  rv = nsGenericHTMLFormElement::InsertChildAt(aKid, aIndex, aNotify);
-  if (rebuild || NS_FAILED(rv)) {
-    RebuildOptionsArray();
-    return rv;
+  nsSafeOptionListMutation safeMutation(this, this, aKid, aIndex);
+  nsresult rv = nsGenericHTMLFormElement::InsertChildAt(aKid, aIndex, aNotify);
+  if (NS_FAILED(rv)) {
+    safeMutation.MutationFailed();
   }
-
-#ifdef DEBUG
-  VerifyOptionsArray();
-#endif
-
-  return NS_OK;
+  return rv;
 }
 
 nsresult
 nsHTMLSelectElement::RemoveChildAt(PRUint32 aIndex, PRBool aNotify)
 {
-  nsresult rv = WillRemoveOptions(this, aIndex);
-  PRBool rebuild = NS_FAILED(rv);
-
-  rv = nsGenericHTMLFormElement::RemoveChildAt(aIndex, aNotify);
-  if (rebuild || NS_FAILED(rv)) {
-    RebuildOptionsArray();
-    return rv;
+  nsSafeOptionListMutation safeMutation(this, this, nsnull, aIndex);
+  nsresult rv = nsGenericHTMLFormElement::RemoveChildAt(aIndex, aNotify);
+  if (NS_FAILED(rv)) {
+    safeMutation.MutationFailed();
   }
-
-#ifdef DEBUG
-  VerifyOptionsArray();
-#endif
-
-  return NS_OK;
+  return rv;
 }
 
 
 // SelectElement methods
 
 nsresult
 nsHTMLSelectElement::InsertOptionsIntoList(nsIContent* aOptions,
                                            PRInt32 aListIndex,
new file mode 100644
--- /dev/null
+++ b/content/html/content/src/nsHTMLSelectElement.h
@@ -0,0 +1,496 @@
+/* -*- 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 Communicator client code.
+ *
+ * The Initial Developer of the Original Code is
+ * Netscape Communications Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 1998
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Pierre Phaneuf <pp@ludusdesign.com>
+ *   Mats Palmgren <mats.palmgren@bredband.net>
+ *   Olli Pettay <Olli.Pettay@helsinki.fi>
+ *
+ * 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 nsHTMLSelectElement_h___
+#define nsHTMLSelectElement_h___
+
+#include "nsCOMPtr.h"
+#include "nsCOMArray.h"
+#include "nsGenericHTMLElement.h"
+#include "nsISelectElement.h"
+#include "nsIDOMHTMLSelectElement.h"
+#include "nsIDOMNSHTMLSelectElement.h"
+#include "nsIDOMNSXBLFormControl.h"
+#include "nsIDOMHTMLFormElement.h"
+#include "nsIDOMHTMLOptionElement.h"
+#include "nsIDOMHTMLCollection.h"
+#include "nsIDOMHTMLOptionsCollection.h"
+#include "nsIDOMNSHTMLOptionCollectn.h"
+#include "nsISelectControlFrame.h"
+
+// PresState
+#include "nsXPCOM.h"
+#include "nsPresState.h"
+#include "nsIComponentManager.h"
+#include "nsCheapSets.h"
+#include "nsLayoutErrors.h"
+
+
+class nsHTMLSelectElement;
+
+/**
+ * The collection of options in the select (what you get back when you do
+ * select.options in DOM)
+ */
+class nsHTMLOptionCollection: public nsIDOMHTMLOptionsCollection,
+                              public nsIDOMNSHTMLOptionCollection,
+                              public nsIDOMHTMLCollection
+{
+public:
+  nsHTMLOptionCollection(nsHTMLSelectElement* aSelect);
+  virtual ~nsHTMLOptionCollection();
+
+  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
+
+  // nsIDOMHTMLOptionsCollection interface
+  NS_DECL_NSIDOMHTMLOPTIONSCOLLECTION
+
+  // nsIDOMNSHTMLOptionCollection interface
+  NS_DECL_NSIDOMNSHTMLOPTIONCOLLECTION
+
+  // nsIDOMHTMLCollection interface, all its methods are defined in
+  // nsIDOMHTMLOptionsCollection
+
+  NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsHTMLOptionCollection,
+                                           nsIDOMNSHTMLOptionCollection)
+
+  // Helpers for nsHTMLSelectElement
+  /**
+   * Insert an option
+   * @param aOption the option to insert
+   * @param aIndex the index to insert at
+   */
+  PRBool InsertOptionAt(nsIDOMHTMLOptionElement* aOption, PRInt32 aIndex)
+  {
+    return mElements.InsertObjectAt(aOption, aIndex);
+  }
+
+  /**
+   * Remove an option
+   * @param aIndex the index of the option to remove
+   */
+  void RemoveOptionAt(PRInt32 aIndex)
+  {
+    mElements.RemoveObjectAt(aIndex);
+  }
+
+  /**
+   * Get the option at the index
+   * @param aIndex the index
+   * @param aReturn the option returned [OUT]
+   */
+  nsIDOMHTMLOptionElement *ItemAsOption(PRInt32 aIndex)
+  {
+    return mElements.SafeObjectAt(aIndex);
+  }
+
+  /**
+   * Clears out all options
+   */
+  void Clear()
+  {
+    mElements.Clear();
+  }
+
+  /**
+   * Append an option to end of array
+   */
+  PRBool AppendOption(nsIDOMHTMLOptionElement* aOption)
+  {
+    return mElements.AppendObject(aOption);
+  }
+
+  /**
+   * Drop the reference to the select.  Called during select destruction.
+   */
+  void DropReference();
+
+  /**
+   * See nsISelectElement.idl for documentation on this method
+   */
+  nsresult GetOptionIndex(nsIDOMHTMLOptionElement* aOption,
+                          PRInt32 aStartIndex, PRBool aForward,
+                          PRInt32* aIndex);
+
+private:
+  /** The list of options (holds strong references) */
+  nsCOMArray<nsIDOMHTMLOptionElement> mElements;
+  /** The select element that contains this array */
+  nsHTMLSelectElement* mSelect;
+};
+
+
+/**
+ * The restore state used by select
+ */
+class nsSelectState : public nsISupports {
+public:
+  nsSelectState()
+  {
+  }
+  virtual ~nsSelectState()
+  {
+  }
+
+  NS_DECL_ISUPPORTS
+
+  void PutOption(PRInt32 aIndex, const nsAString& aValue)
+  {
+    // If the option is empty, store the index.  If not, store the value.
+    if (aValue.IsEmpty()) {
+      mIndices.Put(aIndex);
+    } else {
+      mValues.Put(aValue);
+    }
+  }
+
+  PRBool ContainsOption(PRInt32 aIndex, const nsAString& aValue)
+  {
+    return mValues.Contains(aValue) || mIndices.Contains(aIndex);
+  }
+
+private:
+  nsCheapStringSet mValues;
+  nsCheapInt32Set mIndices;
+};
+
+class nsSafeOptionListMutation
+{
+public:
+  /**
+   * @param aSelect The select element which option list is being mutated.
+   *                Can be null.
+   * @param aParent The content object which is being mutated.
+   * @param aKid    If not null, a new child element is being inserted to
+   *                aParent. Otherwise a child element will be removed.
+   * @param aIndex  The index of the content object in the parent.
+   */
+  nsSafeOptionListMutation(nsIContent* aSelect, nsIContent* aParent,
+                           nsIContent* aKid, PRUint32 aIndex);
+  ~nsSafeOptionListMutation();
+  void MutationFailed() { mNeedsRebuild = PR_TRUE; }
+private:
+  static void* operator new(size_t) CPP_THROW_NEW { return 0; }
+  static void operator delete(void*, size_t) {}
+  /** The select element which option list is being mutated. */
+  nsCOMPtr<nsISelectElement> mSelect;
+  /** PR_TRUE if the current mutation is the first one in the stack. */
+  PRBool                     mTopLevelMutation;
+  /** PR_TRUE if it is known that the option list must be recreated. */
+  PRBool                     mNeedsRebuild;
+  /** Option list must be recreated if more than one mutation is detected. */
+  nsMutationGuard            mGuard;
+};
+
+
+/**
+ * Implementation of &lt;select&gt;
+ */
+class nsHTMLSelectElement : public nsGenericHTMLFormElement,
+                            public nsIDOMHTMLSelectElement,
+                            public nsIDOMNSHTMLSelectElement,
+                            public nsIDOMNSXBLFormControl,
+                            public nsISelectElement
+{
+public:
+  nsHTMLSelectElement(nsINodeInfo *aNodeInfo, PRBool aFromParser = PR_FALSE);
+  virtual ~nsHTMLSelectElement();
+
+  // nsISupports
+  NS_DECL_ISUPPORTS_INHERITED
+
+  // nsIDOMNode
+  NS_FORWARD_NSIDOMNODE(nsGenericHTMLFormElement::)
+
+  // nsIDOMElement
+  NS_FORWARD_NSIDOMELEMENT(nsGenericHTMLFormElement::)
+
+  // nsIDOMHTMLElement
+  NS_FORWARD_NSIDOMHTMLELEMENT(nsGenericHTMLFormElement::)
+
+  // nsIDOMHTMLSelectElement
+  NS_DECL_NSIDOMHTMLSELECTELEMENT
+
+  // nsIDOMNSHTMLSelectElement
+  NS_DECL_NSIDOMNSHTMLSELECTELEMENT
+
+  // nsIDOMNSXBLFormControl
+  NS_DECL_NSIDOMNSXBLFORMCONTROL
+
+  // nsIContent
+  virtual nsresult PreHandleEvent(nsEventChainPreVisitor& aVisitor);
+
+  virtual void SetFocus(nsPresContext* aPresContext);
+  virtual PRBool IsFocusable(PRInt32 *aTabIndex = nsnull);
+  virtual nsresult InsertChildAt(nsIContent* aKid, PRUint32 aIndex,
+                                 PRBool aNotify);
+  virtual nsresult RemoveChildAt(PRUint32 aIndex, PRBool aNotify);
+
+  // Overriden nsIFormControl methods
+  NS_IMETHOD_(PRInt32) GetType() const { return NS_FORM_SELECT; }
+  NS_IMETHOD Reset();
+  NS_IMETHOD SubmitNamesValues(nsIFormSubmission* aFormSubmission,
+                               nsIContent* aSubmitElement);
+  NS_IMETHOD SaveState();
+  virtual PRBool RestoreState(nsPresState* aState);
+
+  // nsISelectElement
+  NS_DECL_NSISELECTELEMENT
+
+  /**
+   * Called when an attribute is about to be changed
+   */
+  virtual nsresult BeforeSetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
+                                 const nsAString* aValue, PRBool aNotify);
+  virtual nsresult UnsetAttr(PRInt32 aNameSpaceID, nsIAtom* aAttribute,
+                             PRBool aNotify);
+  
+  virtual nsresult DoneAddingChildren(PRBool aHaveNotified);
+  virtual PRBool IsDoneAddingChildren();
+
+  virtual PRBool ParseAttribute(PRInt32 aNamespaceID,
+                                nsIAtom* aAttribute,
+                                const nsAString& aValue,
+                                nsAttrValue& aResult);
+  virtual nsMapRuleToAttributesFunc GetAttributeMappingFunction() const;
+  virtual nsChangeHint GetAttributeChangeHint(const nsIAtom* aAttribute,
+                                              PRInt32 aModType) const;
+  NS_IMETHOD_(PRBool) IsAttributeMapped(const nsIAtom* aAttribute) const;
+
+  virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const;
+
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED_NO_UNLINK(nsHTMLSelectElement,
+                                                     nsGenericHTMLFormElement)
+
+protected:
+  friend class nsSafeOptionListMutation;
+
+  // Helper Methods
+  /**
+   * Check whether the option specified by the index is selected
+   * @param aIndex the index
+   * @return whether the option at the index is selected
+   */
+  PRBool IsOptionSelectedByIndex(PRInt32 aIndex);
+  /**
+   * Starting with (and including) aStartIndex, find the first selected index
+   * and set mSelectedIndex to it.
+   * @param aStartIndex the index to start with
+   */
+  void FindSelectedIndex(PRInt32 aStartIndex);
+  /**
+   * Select some option if possible (generally the first non-disabled option).
+   * @return true if something was selected, false otherwise
+   */
+  PRBool SelectSomething();
+  /**
+   * Call SelectSomething(), but only if nothing is selected
+   * @see SelectSomething()
+   * @return true if something was selected, false otherwise
+   */
+  PRBool CheckSelectSomething();
+  /**
+   * Called to trigger notifications of frames and fixing selected index
+   *
+   * @param aSelectFrame the frame for this content (could be null)
+   * @param aPresContext the current pres context
+   * @param aIndex the index that was selected or deselected
+   * @param aSelected whether the index was selected or deselected
+   * @param aNotify whether to notify the style system and such
+   */
+  void OnOptionSelected(nsISelectControlFrame* aSelectFrame,
+                        nsPresContext* aPresContext,
+                        PRInt32 aIndex,
+                        PRBool aSelected,
+                        PRBool aNotify);
+  /**
+   * Restore state to a particular state string (representing the options)
+   * @param aNewSelected the state string to restore to
+   */
+  void RestoreStateTo(nsSelectState* aNewSelected);
+
+#ifdef DEBUG_john
+  // Don't remove these, por favor.  They're very useful in debugging
+  nsresult PrintOptions(nsIContent* aOptions, PRInt32 tabs);
+#endif
+
+  // Adding options
+  /**
+   * Insert option(s) into the options[] array and perform notifications
+   * @param aOptions the option or optgroup being added
+   * @param aListIndex the index to start adding options into the list at
+   * @param aDepth the depth of aOptions (1=direct child of select ...)
+   */
+  nsresult InsertOptionsIntoList(nsIContent* aOptions,
+                                 PRInt32 aListIndex,
+                                 PRInt32 aDepth);
+  /**
+   * Remove option(s) from the options[] array
+   * @param aOptions the option or optgroup being added
+   * @param aListIndex the index to start removing options from the list at
+   * @param aDepth the depth of aOptions (1=direct child of select ...)
+   */
+  nsresult RemoveOptionsFromList(nsIContent* aOptions,
+                                 PRInt32 aListIndex,
+                                 PRInt32 aDepth);
+  /**
+   * Insert option(s) into the options[] array (called by InsertOptionsIntoList)
+   * @param aOptions the option or optgroup being added
+   * @param aInsertIndex the index to start adding options into the list at
+   * @param aDepth the depth of aOptions (1=direct child of select ...)
+   */
+  nsresult InsertOptionsIntoListRecurse(nsIContent* aOptions,
+                                        PRInt32* aInsertIndex,
+                                        PRInt32 aDepth);
+  /**
+   * Remove option(s) from the options[] array (called by RemoveOptionsFromList)
+   * @param aOptions the option or optgroup being added
+   * @param aListIndex the index to start removing options from the list at
+   * @param aNumRemoved the number removed so far [OUT]
+   * @param aDepth the depth of aOptions (1=direct child of select ...)
+   */
+  nsresult RemoveOptionsFromListRecurse(nsIContent* aOptions,
+                                        PRInt32 aRemoveIndex,
+                                        PRInt32* aNumRemoved,
+                                        PRInt32 aDepth);
+  /**
+   * Find out how deep this content is from the select (1=direct child)
+   * @param aContent the content to check
+   * @return the depth
+   */
+  PRInt32 GetContentDepth(nsIContent* aContent);
+  /**
+   * Get the index of the first option at, under or following the content in
+   * the select, or length of options[] if none are found
+   * @param aOptions the content
+   * @return the index of the first option
+   */
+  PRInt32 GetOptionIndexAt(nsIContent* aOptions);
+  /**
+   * Get the next option following the content in question (not at or under)
+   * (this could include siblings of the current content or siblings of the
+   * parent or children of siblings of the parent).
+   * @param aOptions the content
+   * @return the index of the next option after the content
+   */
+  PRInt32 GetOptionIndexAfter(nsIContent* aOptions);
+  /**
+   * Get the first option index at or under the content in question.
+   * @param aOptions the content
+   * @return the index of the first option at or under the content
+   */
+  PRInt32 GetFirstOptionIndex(nsIContent* aOptions);
+  /**
+   * Get the first option index under the content in question, within the
+   * range specified.
+   * @param aOptions the content
+   * @param aStartIndex the first child to look at
+   * @param aEndIndex the child *after* the last child to look at
+   * @return the index of the first option at or under the content
+   */
+  PRInt32 GetFirstChildOptionIndex(nsIContent* aOptions,
+                                   PRInt32 aStartIndex,
+                                   PRInt32 aEndIndex);
+
+  /**
+   * Get the frame as an nsISelectControlFrame (MAY RETURN NULL)
+   * @return the select frame, or null
+   */
+  nsISelectControlFrame *GetSelectFrame();
+
+  /**
+   * Helper method for dispatching custom DOM events to our anonymous subcontent
+   * (for XBL form controls)
+   * @param aName the name of the event to dispatch
+   */
+  void DispatchDOMEvent(const nsAString& aName);
+
+  /**
+   * Is this a combobox?
+   */
+  PRBool IsCombobox() {
+    PRBool isMultiple = PR_TRUE;
+    PRInt32 size = 1;
+    GetSize(&size);
+    GetMultiple(&isMultiple);
+    return !isMultiple && size <= 1;
+  }
+
+  /**
+   * Helper method for dispatching ContentReset notifications to list
+   * and combo box frames.
+   */
+  void DispatchContentReset();
+
+  /**
+   * Rebuilds the options array from scratch as a fallback in error cases.
+   */
+  void RebuildOptionsArray();
+
+#ifdef DEBUG
+  void VerifyOptionsArray();
+#endif
+
+  /** The options[] array */
+  nsRefPtr<nsHTMLOptionCollection> mOptions;
+  /** false if the parser is in the middle of adding children. */
+  PRPackedBool    mIsDoneAddingChildren;
+  /** true if our disabled state has changed from the default **/
+  PRPackedBool    mDisabledChanged;
+  /** true if child nodes are being added or removed.
+   *  Used by nsSafeOptionListMutation.
+   */
+  PRPackedBool    mMutating;
+  /** The number of non-options as children of the select */
+  PRUint32  mNonOptionChildren;
+  /** The number of optgroups anywhere under the select */
+  PRUint32  mOptGroupCount;
+  /**
+   * The current selected index for selectedIndex (will be the first selected
+   * index if multiple are selected)
+   */
+  PRInt32   mSelectedIndex;
+  /**
+   * The temporary restore state in case we try to restore before parser is
+   * done adding options
+   */
+  nsRefPtr<nsSelectState> mRestoreState;
+};
+
+#endif
--- a/content/html/document/src/nsWyciwygChannel.cpp
+++ b/content/html/document/src/nsWyciwygChannel.cpp
@@ -40,27 +40,30 @@
 #include "nsWyciwygChannel.h"
 #include "nsIServiceManager.h"
 #include "nsILoadGroup.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsNetUtil.h"
 #include "nsContentUtils.h"
 #include "nsICacheService.h"
 #include "nsICacheSession.h"
+#include "nsIParser.h"
 
 
 PRLogModuleInfo * gWyciwygLog = nsnull;
 
 #define wyciwyg_TYPE "text/html"
 #define LOG(args)  PR_LOG(gWyciwygLog, 4, args)
 
 // nsWyciwygChannel methods 
 nsWyciwygChannel::nsWyciwygChannel()
   : mStatus(NS_OK),
     mIsPending(PR_FALSE),
+    mNeedToWriteCharset(PR_FALSE),
+    mCharsetSource(kCharsetUninitialized),
     mContentLength(-1),
     mLoadFlags(LOAD_NORMAL)
 {
 }
 
 nsWyciwygChannel::~nsWyciwygChannel() 
 {
 }
@@ -342,16 +345,21 @@ nsWyciwygChannel::WriteToCacheEntry(cons
     rv = OpenCacheEntry(spec, nsICache::ACCESS_WRITE);
     if (NS_FAILED(rv)) return rv;
   }
 
   if (mSecurityInfo) {
     mCacheEntry->SetSecurityInfo(mSecurityInfo);
   }
 
+  if (mNeedToWriteCharset) {
+    WriteCharsetAndSourceToCache(mCharsetSource, mCharset);
+    mNeedToWriteCharset = PR_FALSE;
+  }
+  
   PRUint32 out;
   if (!mCacheOutputStream) {
     // Get the outputstream from the cache entry.
     rv = mCacheEntry->OpenOutputStream(0, getter_AddRefs(mCacheOutputStream));    
     if (NS_FAILED(rv)) return rv;
 
     // Write out a Byte Order Mark, so that we'll know if the data is
     // BE or LE when we go to read it.
@@ -390,30 +398,24 @@ nsWyciwygChannel::SetSecurityInfo(nsISup
 }
 
 NS_IMETHODIMP
 nsWyciwygChannel::SetCharsetAndSource(PRInt32 aSource,
                                       const nsACString& aCharset)
 {
   NS_ENSURE_ARG(!aCharset.IsEmpty());
 
-  if (!mCacheEntry) {
-    nsCAutoString spec;
-    nsresult rv = mURI->GetAsciiSpec(spec);
-    if (NS_FAILED(rv)) return rv;
-    rv = OpenCacheEntry(spec, nsICache::ACCESS_WRITE);
-    if (NS_FAILED(rv)) return rv;
+  if (mCacheEntry) {
+    WriteCharsetAndSourceToCache(aSource, PromiseFlatCString(aCharset));
+  } else {
+    mNeedToWriteCharset = PR_TRUE;
+    mCharsetSource = aSource;
+    mCharset = aCharset;
   }
 
-  mCacheEntry->SetMetaDataElement("charset",
-                                  PromiseFlatCString(aCharset).get());
-  nsCAutoString source;
-  source.AppendInt(aSource);
-  mCacheEntry->SetMetaDataElement("charset-source", source.get());
-  
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsWyciwygChannel::GetCharsetAndSource(PRInt32* aSource, nsACString& aCharset)
 {
   if (!mCacheEntry) {
     return NS_ERROR_NOT_AVAILABLE;
@@ -632,9 +634,22 @@ nsWyciwygChannel::ReadFromCache()