Merge backout with previous tip
authorGavin Sharp <gavin@mozilla.com>
Tue, 23 Sep 2008 11:47:43 -0400
changeset 19608 1ca0b62225b3c5057ffb352a2a455dd54b202b1a
parent 19607 a7283e0ff39dff363ae9dc3a9af6fbc09c14fd51 (current diff)
parent 19606 15aecdaab936f81b0ff03ac3764d604127767985 (diff)
child 19609 31f1081d96818a14f5dbb524b56e880d2e9f430c
push idunknown
push userunknown
push dateunknown
milestone1.9.1b1pre
Merge backout with previous tip
browser/components/search/nsIBrowserSearchService.idl
browser/components/search/nsSearchService.js
browser/components/search/nsSearchSuggestions.js
browser/locales/generic/chrome/inspector/contents.rdf
browser/themes/pinstripe/browser/bookmark_toolbar_background-inactive.png
browser/themes/pinstripe/browser/bookmark_toolbar_background.gif
browser/themes/pinstripe/browser/tabbrowser/tab-left-hover.png
browser/themes/pinstripe/browser/tabbrowser/tab-left-inactive.png
browser/themes/pinstripe/browser/tabbrowser/tab-middle-hover.png
browser/themes/pinstripe/browser/tabbrowser/tab-middle-inactive.png
browser/themes/pinstripe/browser/tabbrowser/tab-right-hover.png
browser/themes/pinstripe/browser/tabbrowser/tab-right-inactive.png
config/chrome-versions.sh
content/xslt/tests/buster/contents.rdf
embedding/browser/chrome/Makefile.in
embedding/browser/chrome/content/contents.rdf
embedding/browser/chrome/content/mini-nav.js
embedding/browser/chrome/content/mini-nav.xul
embedding/browser/chrome/content/simple-shell.xul
embedding/browser/chrome/jar.mn
embedding/browser/chrome/locale/en-US/contents.rdf
embedding/browser/chrome/locale/en-US/embedding.dtd
embedding/browser/chrome/locale/en-US/jar.mn
embedding/browser/chrome/manifest.rdf
embedding/browser/chrome/skin/back.gif
embedding/browser/chrome/skin/contents.rdf
embedding/browser/chrome/skin/embedding.css
embedding/browser/chrome/skin/forward.gif
embedding/browser/chrome/skin/reload.gif
embedding/browser/chrome/skin/simple-shell.css
embedding/browser/chrome/skin/stop.gif
embedding/browser/gtk/src/EmbedPasswordMgr.cpp
embedding/browser/gtk/src/EmbedPasswordMgr.h
embedding/browser/gtk/src/nsIPassword.idl
embedding/browser/gtk/src/nsIPasswordInternal.idl
embedding/lite/Makefile.in
embedding/lite/embedlite.pkg
embedding/lite/nsEmbedChromeRegistry.cpp
embedding/lite/nsEmbedChromeRegistry.h
embedding/lite/nsEmbedGlobalHistory.cpp
embedding/lite/nsEmbedGlobalHistory.h
embedding/lite/nsEmbedLiteModule.cpp
embedding/tests/cocoaEmbed/CocoaEmbed.pbproj/project.pbxproj
embedding/tests/cocoaEmbed/Makefile.in
embedding/tests/cocoaEmbed/res/English.lproj/InfoPlist.strings
embedding/tests/cocoaEmbed/res/English.lproj/MainMenu.nib/classes.nib
embedding/tests/cocoaEmbed/res/English.lproj/MainMenu.nib/info.nib
embedding/tests/cocoaEmbed/res/English.lproj/MainMenu.nib/objects.nib
embedding/tests/cocoaEmbed/src/MyBrowserView.h
embedding/tests/cocoaEmbed/src/MyBrowserView.mm
embedding/tests/cocoaEmbed/src/main.mm
extensions/pref/autoconfig/resources/Makefile.in
extensions/pref/autoconfig/resources/content/contents.rdf
extensions/pref/autoconfig/resources/jar.mn
extensions/pref/autoconfig/resources/locale/en-US/contents.rdf
extensions/python/dom/test/pyxultest/chrome/contents.rdf
extensions/reporter/locales/generic/chrome/contents.rdf
extensions/reporter/resources/content/reporter/contents.rdf
extensions/reporter/resources/skin/classic/reporter/contents.rdf
layout/forms/resources/content/contents.rdf
layout/forms/resources/locale/en-US/contents.rdf
layout/forms/resources/skin/contents.rdf
layout/style/xbl-marquee/contents.rdf
modules/plugin/base/src/ns4xPlugin.cpp
modules/plugin/base/src/ns4xPlugin.h
modules/plugin/base/src/ns4xPluginInstance.cpp
modules/plugin/base/src/ns4xPluginInstance.h
modules/plugin/base/src/ns4xPluginStreamListener.h
modules/plugin/sdk/samples/basic/mac/Basic.rsrc
modules/plugin/sdk/samples/basic/mac/plugin.cpp
modules/plugin/sdk/samples/basic/mac/plugin.h
modules/plugin/sdk/samples/basic/mac/pluginCarbonPrefix.h
modules/plugin/sdk/samples/basic/mac/pluginPrefix.h
netwerk/locales/generic/contents.rdf
netwerk/resources/Makefile.in
netwerk/resources/content/contents.rdf
netwerk/resources/jar.mn
security/manager/locales/generic/chrome/pipnss/contents.rdf
security/manager/locales/generic/chrome/pippki/contents.rdf
security/manager/pki/resources/content/contents.rdf
security/manager/ssl/resources/Makefile.in
security/manager/ssl/resources/content/contents.rdf
security/manager/ssl/resources/jar.mn
toolkit/components/cookie/content/contents.rdf
toolkit/components/history/Makefile.in
toolkit/components/history/public/Makefile.in
toolkit/components/history/public/nsIBrowserHistory.idl
toolkit/components/history/src/Makefile.in
toolkit/components/history/src/nsGlobalHistory.cpp
toolkit/components/history/src/nsGlobalHistory.h
toolkit/components/history/src/nsHistoryLoadListener.h
toolkit/content/buildconfig.html.in
toolkit/locales/en-US/installer/windows/install.it
xpcom/string/public/nsObsoleteAString.h
xpcom/string/public/nsTAString.h
xpcom/string/public/nsTObsoleteAString.h
xpcom/string/src/nsAString.cpp
xpcom/string/src/nsObsoleteAStringThunk.cpp
xpcom/string/src/nsTAString.cpp
xpcom/string/src/nsTObsoleteAStringThunk.cpp
xpfe/bootstrap/nsDocLoadObserver.cpp
xpfe/bootstrap/nsDocLoadObserver.h
xpfe/bootstrap/nsSigHandlers.cpp
xpfe/bootstrap/showOSAlert.cpp
xpfe/components/download-manager/resources/mac/contents.rdf
xpfe/components/download-manager/resources/unix/Makefile.in
xpfe/components/download-manager/resources/unix/contents.rdf
xpfe/components/download-manager/resources/unix/jar.mn
xpfe/components/download-manager/resources/win/Makefile.in
xpfe/components/download-manager/resources/win/contents.rdf
xpfe/components/download-manager/resources/win/jar.mn
--- a/accessible/public/nsIAccessible.idl
+++ b/accessible/public/nsIAccessible.idl
@@ -53,17 +53,17 @@ interface nsIAccessibleRelation;
  * Can also be used by in-process accessibility clients to get information
  * about objects in the accessible tree. The accessible tree is a subset of 
  * nodes in the DOM tree -- such as documents, focusable elements and text.
  * Mozilla creates the implementations of nsIAccessible on demand.
  * See http://www.mozilla.org/projects/ui/accessibility for more information.
  *
  * @status UNDER_REVIEW
  */
-[scriptable, uuid(004b6882-2df1-49df-bb5f-0fb81a5b1edf)]
+[scriptable, uuid(c7520419-87ec-42bc-98cc-04c0bf173530)]
 interface nsIAccessible : nsISupports
 {
   /**
    * Parent node in accessible tree.
    */
   readonly attribute nsIAccessible parent;
 
   /**
@@ -194,20 +194,36 @@ interface nsIAccessible : nsISupports
                      out long aPositionInGroup);
 
   /**
    * Accessible child which contains the coordinate at (x, y) in screen pixels.
    * If the point is in the current accessible but not in a child, the
    * current accessible will be returned.
    * If the point is in neither the current accessible or a child, then
    * null will be returned.
+   *
+   * @param x  screen's x coordinate
+   * @param y  screen's y coordinate
+   * @return   the deepest accessible child containing the given point
    */
   nsIAccessible getChildAtPoint(in long x, in long y);
 
   /**
+   * Deepest accessible child which contains the coordinate at (x, y) in screen
+   * pixels. If the point is in the current accessible but not in a child, the
+   * current accessible will be returned. If the point is in neither the current
+   * accessible or a child, then null will be returned.
+   *
+   * @param x  screen's x coordinate
+   * @param y  screen's y coordinate
+   * @return   the deepest accessible child containing the given point
+   */
+  nsIAccessible getDeepestChildAtPoint(in long x, in long y);
+
+  /**
    * Nth accessible child using zero-based index or last child if index less than zero
    */
   nsIAccessible getChildAt(in long aChildIndex);
 
   /**
    * Accessible node geometrically to the right of this one
    */
   nsIAccessible getAccessibleToRight();
--- a/accessible/src/base/nsAccessNode.cpp
+++ b/accessible/src/base/nsAccessNode.cpp
@@ -603,76 +603,76 @@ nsAccessNode::GetChildNodeAt(PRInt32 aCh
 
   nsCOMPtr<nsIDOMNode> domNode =
     do_QueryInterface(content->GetChildAt(aChildNum));
 
   return domNode ? MakeAccessNode(domNode, aAccessNode) : NS_OK;
 }
 
 NS_IMETHODIMP
-nsAccessNode::GetComputedStyleValue(const nsAString& aPseudoElt, const nsAString& aPropertyName, nsAString& aValue)
+nsAccessNode::GetComputedStyleValue(const nsAString& aPseudoElt,
+                                    const nsAString& aPropertyName,
+                                    nsAString& aValue)
 {
-  nsCOMPtr<nsIDOMElement> domElement(do_QueryInterface(mDOMNode));
-  if (!domElement) {
+  if (IsDefunct())
     return NS_ERROR_FAILURE;
-  }
+
   nsCOMPtr<nsIDOMCSSStyleDeclaration> styleDecl;
-  GetComputedStyleDeclaration(aPseudoElt, domElement, getter_AddRefs(styleDecl));
+  GetComputedStyleDeclaration(aPseudoElt, mDOMNode, getter_AddRefs(styleDecl));
   NS_ENSURE_TRUE(styleDecl, NS_ERROR_FAILURE);
-  
+
   return styleDecl->GetPropertyValue(aPropertyName, aValue);
 }
 
 NS_IMETHODIMP
 nsAccessNode::GetComputedStyleCSSValue(const nsAString& aPseudoElt,
                                        const nsAString& aPropertyName,
                                        nsIDOMCSSPrimitiveValue **aCSSValue)
 {
   NS_ENSURE_ARG_POINTER(aCSSValue);
-
   *aCSSValue = nsnull;
 
-  nsCOMPtr<nsIDOMElement> domElement(do_QueryInterface(mDOMNode));
-  if (!domElement)
+  if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIDOMCSSStyleDeclaration> styleDecl;
-  GetComputedStyleDeclaration(aPseudoElt, domElement,
+  GetComputedStyleDeclaration(aPseudoElt, mDOMNode,
                               getter_AddRefs(styleDecl));
   NS_ENSURE_STATE(styleDecl);
 
   nsCOMPtr<nsIDOMCSSValue> cssValue;
   styleDecl->GetPropertyCSSValue(aPropertyName, getter_AddRefs(cssValue));
   NS_ENSURE_TRUE(cssValue, NS_ERROR_FAILURE);
 
   return CallQueryInterface(cssValue, aCSSValue);
 }
 
-void nsAccessNode::GetComputedStyleDeclaration(const nsAString& aPseudoElt,
-                                               nsIDOMElement *aElement,
-                                               nsIDOMCSSStyleDeclaration **aCssDecl)
+void
+nsAccessNode::GetComputedStyleDeclaration(const nsAString& aPseudoElt,
+                                          nsIDOMNode *aNode,
+                                          nsIDOMCSSStyleDeclaration **aCssDecl)
 {
   *aCssDecl = nsnull;
-  // Returns number of items in style declaration
-  nsCOMPtr<nsIContent> content = do_QueryInterface(aElement);
-  if (!content) {
+
+  nsCOMPtr<nsIDOMElement> domElement = nsAccUtils::GetDOMElementFor(aNode);
+  if (!domElement)
     return;
-  }
+
+  // Returns number of items in style declaration
+  nsCOMPtr<nsIContent> content = do_QueryInterface(domElement);
   nsCOMPtr<nsIDocument> doc = content->GetDocument();
-  if (!doc) {
+  if (!doc)
     return;
-  }
 
   nsCOMPtr<nsIDOMViewCSS> viewCSS(do_QueryInterface(doc->GetWindow()));
-  if (!viewCSS) {
+  if (!viewCSS)
     return;
-  }
 
   nsCOMPtr<nsIDOMCSSStyleDeclaration> cssDecl;
-  viewCSS->GetComputedStyle(aElement, aPseudoElt, getter_AddRefs(cssDecl));
+  viewCSS->GetComputedStyle(domElement, aPseudoElt, getter_AddRefs(cssDecl));
   NS_IF_ADDREF(*aCssDecl = cssDecl);
 }
 
 /***************** Hashtable of nsIAccessNode's *****************/
 
 already_AddRefed<nsIAccessibleDocument>
 nsAccessNode::GetDocAccessibleFor(nsIDocument *aDocument)
 {
--- a/accessible/src/base/nsAccessNode.h
+++ b/accessible/src/base/nsAccessNode.h
@@ -109,17 +109,17 @@ class nsAccessNode: public nsIAccessNode
     static already_AddRefed<nsIAccessibleDocument> GetDocAccessibleFor(nsIWeakReference *aWeakShell);
     static already_AddRefed<nsIAccessibleDocument> GetDocAccessibleFor(nsIDocShellTreeItem *aContainer, PRBool aCanCreate = PR_FALSE);
     static already_AddRefed<nsIAccessibleDocument> GetDocAccessibleFor(nsIDOMNode *aNode);
 
     static already_AddRefed<nsIDOMNode> GetDOMNodeForContainer(nsISupports *aContainer);
     static already_AddRefed<nsIPresShell> GetPresShellFor(nsIDOMNode *aStartNode);
     
     static void GetComputedStyleDeclaration(const nsAString& aPseudoElt,
-                                            nsIDOMElement *aElement,
+                                            nsIDOMNode *aNode,
                                             nsIDOMCSSStyleDeclaration **aCssDecl);
 
     already_AddRefed<nsRootAccessible> GetRootAccessible();
 
     static nsIDOMNode *gLastFocusedNode;
     static nsIAccessibilityService* GetAccService();
     already_AddRefed<nsIDOMNode> GetCurrentFocus();
 
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -1099,20 +1099,20 @@ NS_IMETHODIMP nsAccessible::GetFocusedCh
       }
     }
   }
 
   NS_IF_ADDREF(*aFocusedChild = focusedChild);
   return NS_OK;
 }
 
-  /* nsIAccessible getChildAtPoint (in long x, in long y); */
+// nsIAccessible getDeepestChildAtPoint(in long x, in long y)
 NS_IMETHODIMP
-nsAccessible::GetChildAtPoint(PRInt32 aX, PRInt32 aY,
-                              nsIAccessible **aAccessible)
+nsAccessible::GetDeepestChildAtPoint(PRInt32 aX, PRInt32 aY,
+                                     nsIAccessible **aAccessible)
 {
   NS_ENSURE_ARG_POINTER(aAccessible);
   *aAccessible = nsnull;
 
   if (!mDOMNode) {
     return NS_ERROR_FAILURE;  // Already shut down
   }
 
@@ -1200,39 +1200,62 @@ nsAccessible::GetChildAtPoint(PRInt32 aX
         // Don't walk into offscreen or invisible items
         NS_IF_ADDREF(*aAccessible = child);
         return NS_OK;
       }
     }
     // Fall through -- the point is in this accessible but not in a child
     // We are allowed to return |this| as the answer
   }
-  else {
-    nsCOMPtr<nsIAccessible> parent;
-    while (PR_TRUE) {
-      accessible->GetParent(getter_AddRefs(parent));
-      if (!parent) {
-        // Reached the top of the hierarchy
-        // these bounds were inside an accessible that is not a descendant of this one
-        NS_IF_ADDREF(*aAccessible = fallbackAnswer);
-        return NS_OK;
-      }
-      if (parent == this) {
-        // We reached |this|, so |accessible| is the
-        // child we want to return
-        break;
-      }
-      accessible.swap(parent);
-    }
-  }
 
   NS_IF_ADDREF(*aAccessible = accessible);
   return NS_OK;
 }
 
+// nsIAccessible getChildAtPoint(in long x, in long y)
+NS_IMETHODIMP
+nsAccessible::GetChildAtPoint(PRInt32 aX, PRInt32 aY,
+                              nsIAccessible **aAccessible)
+{
+  nsresult rv = GetDeepestChildAtPoint(aX, aY, aAccessible);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  if (!*aAccessible)
+    return NS_OK;
+
+  nsCOMPtr<nsIAccessible> parent, accessible(*aAccessible);
+  while (PR_TRUE) {
+    accessible->GetParent(getter_AddRefs(parent));
+    if (!parent) {
+      NS_ASSERTION(PR_FALSE,
+                   "Obtained accessible isn't a child of this accessible.");
+      // Reached the top of the hierarchy. These bounds were inside an
+      // accessible that is not a descendant of this one.
+
+      // If we can't find the point in a child, we will return the fallback
+      // answer: we return |this| if the point is within it, otherwise nsnull.
+      PRInt32 x, y, width, height;
+      GetBounds(&x, &y, &width, &height);
+      if (aX >= x && aX < x + width && aY >= y && aY < y + height)
+        NS_ADDREF(*aAccessible = this);
+
+      return NS_OK;
+    }
+
+    if (parent == this) {
+      // We reached |this|, so |accessible| is the child we want to return.
+      NS_ADDREF(*aAccessible = accessible);
+      return NS_OK;
+    }
+    accessible.swap(parent);
+  }
+
+  return NS_OK;
+}
+
 void nsAccessible::GetBoundsRect(nsRect& aTotalBounds, nsIFrame** aBoundingFrame)
 {
 /*
  * This method is used to determine the bounds of a content node.
  * Because HTML wraps and links are not always rectangular, this
  * method uses the following algorithm:
  *
  * 1) Start with an empty rectangle
--- a/accessible/src/base/nsCaretAccessible.cpp
+++ b/accessible/src/base/nsCaretAccessible.cpp
@@ -242,18 +242,27 @@ nsCaretAccessible::NormalSelectionChange
     return NS_OK;
   }
   PRUint32 docState;
   accessibleForDoc->GetFinalState(&docState, nsnull);
   if (docState & nsIAccessibleStates::STATE_BUSY) {
     return NS_OK;  // Don't fire caret moves until doc loaded
   }
 
-  nsCOMPtr<nsIDOMNode> nodeWithCaret = focusNode;
+  // Get focused node.
+  nsCOMPtr<nsIContent> focusContainer(do_QueryInterface(focusNode));
+  if (focusContainer && focusContainer->IsNodeOfType(nsINode::eELEMENT)) {
+    PRInt32 focusOffset = 0;
+    aSel->GetFocusOffset(&focusOffset);
 
+    nsCOMPtr<nsIContent> focusContent = focusContainer->GetChildAt(focusOffset);
+    focusNode = do_QueryInterface(focusContent);
+  }
+
+  // Get relevant accessible for the focused node.
   nsCOMPtr<nsIAccessibleText> textAcc;
   while (focusNode) {
     // Make sure to get the correct starting node for selection events inside XBL content trees
     nsCOMPtr<nsIDOMNode> relevantNode;
     if (NS_SUCCEEDED(accService->GetRelevantContentNodeFor(focusNode, getter_AddRefs(relevantNode))) && relevantNode) {
       focusNode  = relevantNode;
     }
 
@@ -302,16 +311,26 @@ nsCaretAccessible::SpellcheckSelectionCh
   // the same accessible for newly appended range of the selection (for every
   // misspelled word). If spellchecking is disabled (for example,
   // @spellcheck="false" on html:body) then we won't fire any event.
   nsCOMPtr<nsIDOMNode> targetNode;
   aSel->GetFocusNode(getter_AddRefs(targetNode));
   if (!targetNode)
     return NS_OK;
 
+  // Get focused node.
+  nsCOMPtr<nsIContent> focusContainer(do_QueryInterface(targetNode));
+  if (focusContainer && focusContainer->IsNodeOfType(nsINode::eELEMENT)) {
+    PRInt32 focusOffset = 0;
+    aSel->GetFocusOffset(&focusOffset);
+    
+    nsCOMPtr<nsIContent> focusContent = focusContainer->GetChildAt(focusOffset);
+    targetNode = do_QueryInterface(focusContent);
+  }
+
   nsCOMPtr<nsIAccessibleDocument> docAccessible =
     nsAccessNode::GetDocAccessibleFor(targetNode);
   NS_ENSURE_STATE(docAccessible);
 
   nsCOMPtr<nsIAccessible> containerAccessible;
   nsresult rv =
     docAccessible->GetAccessibleInParentChain(targetNode, PR_TRUE,
                                               getter_AddRefs(containerAccessible));
--- a/accessible/src/base/nsOuterDocAccessible.cpp
+++ b/accessible/src/base/nsOuterDocAccessible.cpp
@@ -62,16 +62,17 @@ NS_IMETHODIMP nsOuterDocAccessible::GetR
 NS_IMETHODIMP
 nsOuterDocAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   nsAccessible::GetState(aState, aExtraState);
   *aState &= ~nsIAccessibleStates::STATE_FOCUSABLE;
   return NS_OK;
 }
 
+// nsIAccessible::getChildAtPoint(in long x, in long y)
 NS_IMETHODIMP
 nsOuterDocAccessible::GetChildAtPoint(PRInt32 aX, PRInt32 aY,
                                       nsIAccessible **aAccessible)
 {
   NS_ENSURE_ARG_POINTER(aAccessible);
   *aAccessible = nsnull;
   if (!mDOMNode) {
     return NS_ERROR_FAILURE;
@@ -80,16 +81,33 @@ nsOuterDocAccessible::GetChildAtPoint(PR
   GetBounds(&docX, &docY, &docWidth, &docHeight);
   if (aX < docX || aX >= docX + docWidth || aY < docY || aY >= docY + docHeight) {
     return NS_ERROR_FAILURE;
   }
 
   return GetFirstChild(aAccessible);  // Always return the inner doc unless bounds outside of it
 }
 
+// nsIAccessible::getDeepestChildAtPoint(in long x, in long y)
+NS_IMETHODIMP
+nsOuterDocAccessible::GetDeepestChildAtPoint(PRInt32 aX, PRInt32 aY,
+                                      nsIAccessible **aAccessible)
+{
+  // Call getDeepestChildAtPoint on the fist child accessible of the outer
+  // document accessible if the given point is inside of outer document.
+  nsCOMPtr<nsIAccessible> childAcc;
+  nsresult rv = GetChildAtPoint(aX, aY, getter_AddRefs(childAcc));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  if (!childAcc)
+    return NS_OK;
+
+  return childAcc->GetDeepestChildAtPoint(aX, aY, aAccessible);
+}
+
 void nsOuterDocAccessible::CacheChildren()
 {  
   // An outer doc accessible usually has 1 nsDocAccessible child,
   // but could have none if we can't get to the inner documnet
   if (!mWeakShell) {
     mAccChildCount = eChildCountUninitialized;
     return;   // This outer doc node has been shut down
   }
--- a/accessible/src/base/nsOuterDocAccessible.h
+++ b/accessible/src/base/nsOuterDocAccessible.h
@@ -49,18 +49,22 @@ class nsOuterDocAccessible : public nsAc
   NS_DECL_ISUPPORTS_INHERITED
 
   public:
     nsOuterDocAccessible(nsIDOMNode* aNode, 
                          nsIWeakReference* aShell);
 
     NS_IMETHOD GetRole(PRUint32 *aRole);
     NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
+
     NS_IMETHOD GetChildAtPoint(PRInt32 aX, PRInt32 aY,
                                nsIAccessible **aAccessible);
+    NS_IMETHOD GetDeepestChildAtPoint(PRInt32 aX, PRInt32 aY,
+                                      nsIAccessible **aAccessible);
+
     void CacheChildren();
     nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
     NS_IMETHOD GetNumActions(PRUint8 *aNumActions);
     NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
     NS_IMETHODIMP GetActionDescription(PRUint8 aIndex, nsAString& aDescription);
     NS_IMETHOD DoAction(PRUint8 aIndex);
 };
 
--- a/accessible/src/html/nsHTMLTableAccessible.cpp
+++ b/accessible/src/html/nsHTMLTableAccessible.cpp
@@ -1133,20 +1133,22 @@ NS_IMETHODIMP nsHTMLTableAccessible::IsP
   tableElt->GetElementsByTagName(NS_LITERAL_STRING("tr"), getter_AddRefs(nodeList));
   NS_ENSURE_TRUE(nodeList, NS_ERROR_FAILURE);
   PRUint32 length;
   nodeList->GetLength(&length);
   nsAutoString color, lastRowColor;
   for (PRInt32 rowCount = 0; rowCount < rows; rowCount ++) {
     nsCOMPtr<nsIDOMNode> rowNode;
     nodeList->Item(rowCount, getter_AddRefs(rowNode));
-    nsCOMPtr<nsIDOMElement> rowElement = do_QueryInterface(rowNode);
+
     nsCOMPtr<nsIDOMCSSStyleDeclaration> styleDecl;
-    GetComputedStyleDeclaration(EmptyString(), rowElement, getter_AddRefs(styleDecl));
+    GetComputedStyleDeclaration(EmptyString(), rowNode,
+                                getter_AddRefs(styleDecl));
     NS_ENSURE_TRUE(styleDecl, NS_ERROR_FAILURE);
+
     lastRowColor = color;
     styleDecl->GetPropertyValue(NS_LITERAL_STRING("background-color"), color);
     if (rowCount > 0 && PR_FALSE == lastRowColor.Equals(color)) {
       RETURN_LAYOUT_ANSWER(PR_FALSE, "2 styles of row background color, non-bordered");
     }
   }
 
   // Check for many rows
--- a/accessible/src/html/nsHTMLTextAccessible.cpp
+++ b/accessible/src/html/nsHTMLTextAccessible.cpp
@@ -99,17 +99,17 @@ nsHTMLTextAccessible::GetAttributesInter
   if (!mDOMNode) {
     return NS_ERROR_FAILURE;  // Node already shut down
   }
 
   PRUint32 role;
   GetRole(&role);
   if (role == nsIAccessibleRole::ROLE_STATICTEXT) {
     nsAutoString oldValueUnused;
-    aAttributes->SetStringProperty(NS_LITERAL_CSTRING("static"),
+    aAttributes->SetStringProperty(NS_LITERAL_CSTRING("auto-generated"),
                                   NS_LITERAL_STRING("true"), oldValueUnused);
   }
 
   return NS_OK;
 }
 
 nsHTMLHRAccessible::nsHTMLHRAccessible(nsIDOMNode* aDomNode, nsIWeakReference* aShell):
 nsLeafAccessible(aDomNode, aShell)
--- a/accessible/src/mac/mozAccessible.mm
+++ b/accessible/src/mac/mozAccessible.mm
@@ -288,32 +288,27 @@ GetNativeFromGeckoAccessible(nsIAccessib
 
   NS_OBJC_END_TRY_ABORT_BLOCK;
 }
 
 - (id)accessibilityHitTest:(NSPoint)point
 {
   if (mIsExpired)
     return nil;
-  
+
   // Convert from cocoa's coordinate system to gecko's. According to the docs
   // the point we're given is guaranteed to be bottom-left screen coordinates.
   nsPoint geckoPoint;
   ConvertCocoaToGeckoPoint (point, geckoPoint);
 
-  // start iterating as deep down as we can on this point, with the current accessible as the root.
-  // as soon as GetChildAtPoint() returns null, or can't descend further (without getting the same accessible again)
-  // we stop.
-  nsCOMPtr<nsIAccessible> deepestFoundChild, newChild(mGeckoAccessible);
-  do {
-    deepestFoundChild = newChild;
-    deepestFoundChild->GetChildAtPoint((PRInt32)geckoPoint.x, (PRInt32)geckoPoint.y, getter_AddRefs(newChild));
-  } while (newChild && newChild.get() != deepestFoundChild.get());
+  nsCOMPtr<nsIAccessible> deepestFoundChild;
+  mGeckoAccessible->GetDeepestChildAtPoint((PRInt32)geckoPoint.x,
+                                           (PRInt32)geckoPoint.y,
+                                           getter_AddRefs(deepestFoundChild));
   
-
   // if we found something, return its native accessible.
   if (deepestFoundChild) {
     mozAccessible *nativeChild = GetNativeFromGeckoAccessible(deepestFoundChild);
     if (nativeChild)
       return GetClosestInterestingAccessible(nativeChild);
   }
   
   // if we didn't find anything, return ourself (or the first unignored ancestor).
--- a/accessible/src/msaa/nsAccessNodeWrap.cpp
+++ b/accessible/src/msaa/nsAccessNodeWrap.cpp
@@ -305,23 +305,23 @@ STDMETHODIMP nsAccessNodeWrap::get_attri
 STDMETHODIMP nsAccessNodeWrap::get_computedStyle( 
     /* [in] */ unsigned short aMaxStyleProperties,
     /* [in] */ boolean aUseAlternateView,
     /* [length_is][size_is][out] */ BSTR __RPC_FAR *aStyleProperties,
     /* [length_is][size_is][out] */ BSTR __RPC_FAR *aStyleValues,
     /* [out] */ unsigned short __RPC_FAR *aNumStyleProperties)
 {
 __try{
-  nsCOMPtr<nsIDOMElement> domElement(do_QueryInterface(mDOMNode));
-  if (!domElement)
+  *aNumStyleProperties = 0;
+
+  if (IsDefunct())
     return E_FAIL;
-  
-  *aNumStyleProperties = 0;
+
   nsCOMPtr<nsIDOMCSSStyleDeclaration> cssDecl;
-  GetComputedStyleDeclaration(EmptyString(), domElement, getter_AddRefs(cssDecl));
+  GetComputedStyleDeclaration(EmptyString(), mDOMNode, getter_AddRefs(cssDecl));
   NS_ENSURE_TRUE(cssDecl, E_FAIL);
 
   PRUint32 length;
   cssDecl->GetLength(&length);
 
   PRUint32 index, realIndex;
   for (index = realIndex = 0; index < length && realIndex < aMaxStyleProperties; index ++) {
     nsAutoString property, value;
@@ -342,22 +342,21 @@ STDMETHODIMP nsAccessNodeWrap::get_compu
 
 STDMETHODIMP nsAccessNodeWrap::get_computedStyleForProperties( 
     /* [in] */ unsigned short aNumStyleProperties,
     /* [in] */ boolean aUseAlternateView,
     /* [length_is][size_is][in] */ BSTR __RPC_FAR *aStyleProperties,
     /* [length_is][size_is][out] */ BSTR __RPC_FAR *aStyleValues)
 {
 __try {
-  nsCOMPtr<nsIDOMElement> domElement(do_QueryInterface(mDOMNode));
-  if (!domElement)
+  if (IsDefunct())
     return E_FAIL;
  
   nsCOMPtr<nsIDOMCSSStyleDeclaration> cssDecl;
-  GetComputedStyleDeclaration(EmptyString(), domElement, getter_AddRefs(cssDecl));
+  GetComputedStyleDeclaration(EmptyString(), mDOMNode, getter_AddRefs(cssDecl));
   NS_ENSURE_TRUE(cssDecl, E_FAIL);
 
   PRUint32 index;
   for (index = 0; index < aNumStyleProperties; index ++) {
     nsAutoString value;
     if (aStyleProperties[index])
       cssDecl->GetPropertyValue(nsDependentString(static_cast<PRUnichar*>(aStyleProperties[index])), value);  // Get property value
     aStyleValues[index] = ::SysAllocString(value.get());
--- a/accessible/src/xul/nsXULTreeAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeAccessible.cpp
@@ -350,16 +350,25 @@ nsXULTreeAccessible::GetChildAtPoint(PRI
   // If we failed to find tree cell for the given point then it might be
   // tree columns.
   if (row == -1 || !column)
     return nsXULSelectableAccessible::GetChildAtPoint(aX, aY, aAccessible);
 
   return GetCachedTreeitemAccessible(row, column, aAccessible);
 }
 
+// nsIAccessible::getDeepestChildAtPoint(in long x, in long y)
+NS_IMETHODIMP
+nsXULTreeAccessible::GetDeepestChildAtPoint(PRInt32 aX, PRInt32 aY,
+                                            nsIAccessible **aAccessible)
+{
+  // Call getChildAtPoint until tree doesn't support complex content.
+  return GetChildAtPoint(aX, aY, aAccessible);
+}
+
 // Ask treeselection to get all selected children
 NS_IMETHODIMP nsXULTreeAccessible::GetSelectedChildren(nsIArray **_retval)
 {
   *_retval = nsnull;
 
   NS_ENSURE_TRUE(mTree && mTreeView, NS_ERROR_FAILURE);
 
   nsCOMPtr<nsITreeSelection> selection;
--- a/accessible/src/xul/nsXULTreeAccessible.h
+++ b/accessible/src/xul/nsXULTreeAccessible.h
@@ -66,18 +66,21 @@ public:
   NS_IMETHOD GetRole(PRUint32 *_retval);
   NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
   NS_IMETHOD GetValue(nsAString& _retval);
 
   NS_IMETHOD GetFirstChild(nsIAccessible **_retval);
   NS_IMETHOD GetLastChild(nsIAccessible **_retval);
   NS_IMETHOD GetChildCount(PRInt32 *_retval);
   NS_IMETHOD GetFocusedChild(nsIAccessible **aFocusedChild);
+
   NS_IMETHOD GetChildAtPoint(PRInt32 aX, PRInt32 aY,
                              nsIAccessible **aAccessible);
+  NS_IMETHOD GetDeepestChildAtPoint(PRInt32 aX, PRInt32 aY,
+                                    nsIAccessible **aAccessible);
 
   static void GetTreeBoxObject(nsIDOMNode* aDOMNode, nsITreeBoxObject** aBoxObject);
   static nsresult GetColumnCount(nsITreeBoxObject* aBoxObject, PRInt32 *aCount);
 
   static PRBool IsColumnHidden(nsITreeColumn *aColumn);
   static already_AddRefed<nsITreeColumn> GetNextVisibleColumn(nsITreeColumn *aColumn);
   static already_AddRefed<nsITreeColumn> GetFirstVisibleColumn(nsITreeBoxObject *aTree);
   static already_AddRefed<nsITreeColumn> GetLastVisibleColumn(nsITreeBoxObject *aTree);
--- a/accessible/tests/mochitest/Makefile.in
+++ b/accessible/tests/mochitest/Makefile.in
@@ -48,40 +48,44 @@ include $(topsrcdir)/config/rules.mk
 _TEST_FILES =\
 		moz.png \
 		longdesc_src.html \
 		common.js \
 		nsIAccessible_actions.js \
 		nsIAccessible_name.css \
 		nsIAccessible_name.js \
 		nsIAccessible_name.xbl \
+ 		nsIAccessible_selects.js \
 		nsIAccessibleEditableText.js \
 		test_aria_activedescendant.html \
 		test_aria_role_article.html \
 		test_bug368835.xul \
 		test_bug420863.html \
 		test_cssattrs.html \
+		test_events_caretmove.html \
 		test_groupattrs.xul \
 	$(warning test_table_indexes.html temporarily disabled) \
 		test_nsIAccessible_actions.html \
 		test_nsIAccessible_actions.xul \
 		test_nsIAccessible_name.html \
 		test_nsIAccessible_name.xul \
+ 		test_nsIAccessible_selects.html \
 		test_nsIAccessible_focus.html \
 		test_nsIAccessibleDocument.html \
 		test_nsIAccessibleEditableText.html \
 		test_nsIAccessibleHyperLink.html \
 		test_nsIAccessibleHyperLink.xul \
 		test_nsIAccessibleHyperText.html \
 		test_nsIAccessibleImage.html \
 		test_nsIAccessibleTable_1.html \
 		test_nsIAccessibleTable_2.html \
 		test_nsIAccessibleTable_3.html \
 		test_nsIAccessibleTable_4.html \
 		test_nsIAccessibleTable_listboxes.xul \
+		test_nsIAccessNode_utils.html \
 		test_nsOuterDocAccessible.html \
 		test_textattrs.html \
 		test_textboxes.html \
 		test_textboxes.xul \
 		testTextboxes.js \
 		test_bug428479.html \
 		test_bug429285.html \
 		test_bug434464.html \
--- a/accessible/tests/mochitest/common.js
+++ b/accessible/tests/mochitest/common.js
@@ -26,16 +26,38 @@ const nsIAccessibleSelectable = Componen
 const nsIAccessibleTable = Components.interfaces.nsIAccessibleTable;
 const nsIAccessibleValue = Components.interfaces.nsIAccessibleValue;
 
 const nsIObserverService = Components.interfaces.nsIObserverService;
 
 const nsIDOMNode = Components.interfaces.nsIDOMNode;
 
 ////////////////////////////////////////////////////////////////////////////////
+// Roles
+const ROLE_COMBOBOX = nsIAccessibleRole.ROLE_COMBOBOX;
+const ROLE_COMBOBOX_LIST = nsIAccessibleRole.ROLE_COMBOBOX_LIST;
+const ROLE_COMBOBOX_OPTION = nsIAccessibleRole.ROLE_COMBOBOX_OPTION;
+const ROLE_LABEL = nsIAccessibleRole.ROLE_LABEL;
+const ROLE_LIST = nsIAccessibleRole.ROLE_LIST;
+const ROLE_OPTION = nsIAccessibleRole.ROLE_OPTION;
+const ROLE_TEXT_LEAF = nsIAccessibleRole.ROLE_TEXT_LEAF;
+
+////////////////////////////////////////////////////////////////////////////////
+// States
+const STATE_COLLAPSED = nsIAccessibleStates.STATE_COLLAPSED;
+const STATE_EXPANDED = nsIAccessibleStates.STATE_EXPANDED;
+const STATE_EXTSELECTABLE = nsIAccessibleStates.STATE_EXTSELECTABLE;
+const STATE_FOCUSABLE = nsIAccessibleStates.STATE_FOCUSABLE;
+const STATE_FOCUSED = nsIAccessibleStates.STATE_FOCUSED;
+const STATE_HASPOPUP = nsIAccessibleStates.STATE_HASPOPUP;
+const STATE_MULTISELECTABLE = nsIAccessibleStates.STATE_MULTISELECTABLE;
+const STATE_SELECTABLE = nsIAccessibleStates.STATE_SELECTABLE;
+const STATE_SELECTED = nsIAccessibleStates.STATE_SELECTED;
+
+////////////////////////////////////////////////////////////////////////////////
 // Accessible general
 
 /**
  * nsIAccessibleRetrieval, initialized when test is loaded.
  */
 var gAccRetrieval = null;
 
 /**
@@ -72,26 +94,26 @@ function getAccessible(aAccOrElmOrID, aI
     aElmObj.value = elm;
 
   var acc = (aAccOrElmOrID instanceof nsIAccessible) ? aAccOrElmOrID : null;
   if (!acc) {
     try {
       acc = gAccRetrieval.getAccessibleFor(elm);
     } catch (e) {
     }
-    
+
     if (!acc) {
-      ok(false, "Can't get accessible for " + aID);
+      ok(false, "Can't get accessible for " + aAccOrElmOrID);
       return null;
     }
   }
-  
+
   if (!aInterfaces)
     return acc;
-  
+
   if (aInterfaces instanceof Array) {
     for (var index = 0; index < aInterfaces.length; index++) {
       try {
         acc.QueryInterface(aInterfaces[index]);
       } catch (e) {
         ok(false, "Can't query " + aInterfaces[index] + " for " + aID);
         return null;
       }
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/nsIAccessible_selects.js
@@ -0,0 +1,111 @@
+/**
+ * Tests an accessible and its children.
+ * The accessible is one of the following:
+ * - HTML:select (ROLE_COMBOBOX)
+ * - HTML:select @size (ROLE_LIST)
+ * - HTML:label containing either of the above (ROLE_LABEL)
+ *
+ * @param aID               The ID of the base element to test.
+ * @param aNames            The array of expected names for the accessible and
+ *                          its children.
+ * @param aRoles            The array of expected roles for the accessible and
+ *                          its children.
+ * @param aStates           The array of states to test for on each accessible.
+ * @param aUndesiredStates  Array of states we don't want to have for each
+ *                          accessible.
+ *
+ * @note Each of the three arrays must have an equal number of elements. The
+ * order of elements corresponds to the order in which the tree is walked from
+ * the base accessible downwards.
+ */
+function testSelect(aID, aNames, aRoles, aStates, aUndesiredStates)
+{
+  // used to walk the tree starting at the aID's accessible.
+  var acc = getAccessible(aID);
+  if (!acc) {
+    return;
+  }
+
+  testThis(aID, acc, aNames, aRoles, aStates, aUndesiredStates, 0);
+}
+
+/**
+ * Tests a single accessible.
+ * Recursively calls itself until it reaches the last option item.
+ * Called first time from the testSelect function.
+ *
+ * @param aID               @see testSelect
+ * @param aAcc              The accessible to test.
+ * @param aNames            @see testSelect
+ * @param aRoles            @see testSelect
+ * @param aStates           @see testSelect
+ * @param aUndesiredStates  @see testSelect
+ * @param aIndex            The index in the three arrays to use. Used for both
+ *                          the error message and for walking the tree downwards
+ *                          from the base accessible.
+ */
+function testThis(aID, aAcc, aNames, aRoles, aStates, aUndesiredStates, aIndex)
+{
+  if (aIndex >= aNames.length)
+    return;  // End of test
+  else if (!aAcc) {
+    ok(false, "No accessible for " + aID + " at index " + aIndex + "!");
+    return;
+  }
+
+  is(aAcc.name, aNames[aIndex],
+     "wrong name for " + aID + " at index " + aIndex + "!");
+  var role = aAcc.role;
+  is(role, aRoles[aIndex],
+     "Wrong role for " + aID + " at index " + aIndex + "!");
+  testStates(aID, aAcc, aStates, aUndesiredStates, aIndex);
+  switch(role) {
+    case ROLE_COMBOBOX:
+    case ROLE_COMBOBOX_LIST:
+    case ROLE_LABEL:
+    case ROLE_LIST:
+      // All of these expect the next item to be the first child of the current
+      // accessible.
+      var acc = null;
+      try {
+        acc = aAcc.firstChild;
+      } catch(e) {}
+      testThis(aID, acc, aNames, aRoles, aStates, aUndesiredStates, ++aIndex);
+      break;
+    case ROLE_COMBOBOX_OPTION:
+    case ROLE_OPTION:
+    case ROLE_TEXT_LEAF:
+      // All of these expect the next item's accessible to be the next sibling.
+      var acc = null;
+      try {
+        acc = aAcc.nextSibling;
+      } catch(e) {}
+      testThis(aID, acc, aNames, aRoles, aStates, aUndesiredStates, ++aIndex);
+      break;
+    default:
+      break;
+  }
+}
+
+/**
+ * Tests the states for the given accessible.
+ * Does not test for extraStates since we don't need these.
+ *
+ * @param aID  the ID of the base element.
+ * @param aAcc  the current accessible from the recursive algorithm.
+ * @param aStates  the states array passed down from the testThis function.
+ * @param aUndesiredStates  the array of states we don't want to see, if any.
+ * @param aIndex  the index of the item to test, determined and passed in from
+ *                the testThis function.
+ */
+function testStates(aID, aAcc, aStates, aUndesiredStates, aIndex)
+{
+  var state = {}, extraState = {};
+  aAcc.getFinalState(state, extraState);
+  if (aStates[aIndex] != 0)
+    is(state.value & aStates[aIndex], aStates[aIndex],
+       "Wrong state bits for " + aID + " at index " + aIndex + "!");
+  if (aUndesiredStates[aIndex] != 0)
+    is(state.value & aUndesiredStates[aIndex], 0,
+       "Wrong undesired state bits for " + aID + " at index " + aIndex + "!");
+}
--- a/accessible/tests/mochitest/testTextboxes.js
+++ b/accessible/tests/mochitest/testTextboxes.js
@@ -1,33 +1,21 @@
-const nsIAccessibleRetrieval = Components.interfaces.nsIAccessibleRetrieval;
+// Mapping needed state flags for easier handling.
+const state_focusable = nsIAccessibleStates.STATE_FOCUSABLE;
+const state_focused = nsIAccessibleStates.STATE_FOCUSED;
+const state_readonly = nsIAccessibleStates.STATE_READONLY;
 
-// Mapping needed state flags for easier handling.
-const state_focusable = 
-      Components.interfaces.nsIAccessibleStates.STATE_FOCUSABLE;
-const state_focused = 
-      Components.interfaces.nsIAccessibleStates.STATE_FOCUSED;
-const state_readonly = 
-      Components.interfaces.nsIAccessibleStates.STATE_READONLY;
-
-const ext_state_multi_line = 
-      Components.interfaces.nsIAccessibleStates.EXT_STATE_MULTI_LINE;
-const ext_state_editable = 
-      Components.interfaces.nsIAccessibleStates.EXT_STATE_EDITABLE;
-const ext_state_required = 
-      Components.interfaces.nsIAccessibleStates.STATE_REQUIRED;
-const ext_state_invalid = 
-      Components.interfaces.nsIAccessibleStates.STATE_INVALID;
+const ext_state_multi_line = nsIAccessibleStates.EXT_STATE_MULTI_LINE;
+const ext_state_editable = nsIAccessibleStates.EXT_STATE_EDITABLE;
+const ext_state_required = nsIAccessibleStates.STATE_REQUIRED;
+const ext_state_invalid = nsIAccessibleStates.STATE_INVALID;
 
 // Mapping needed final roles
-const role_entry = Components.interfaces.nsIAccessibleRole.ROLE_ENTRY;
-const role_password_text =
-      Components.interfaces.nsIAccessibleRole.ROLE_PASSWORD_TEXT;
-
-var gAccRetrieval = null;
+const role_entry = nsIAccessibleRole.ROLE_ENTRY;
+const role_password_text = nsIAccessibleRole.ROLE_PASSWORD_TEXT;
 
 function testValue(aID, aAcc, aValue, aRole)
 {
   if (aRole == role_password_text) {
     var value;
     try {
       value = aAcc.value;
       do_throw("We do not want a value on " + aID + "!");
--- a/accessible/tests/mochitest/test_bug368835.xul
+++ b/accessible/tests/mochitest/test_bug368835.xul
@@ -100,23 +100,23 @@
       gTreeInvalidatedCount++;
 
       switch (gTreeInvalidatedCount) {
         case 1:
           TreeInvalidatedHandlerHelper(aEvent, 0, 5, null, null,
                                        "nsITreeBoxObject::rowCountChanged");
           break;
         case 2:
-          TreeInvalidatedHandlerHelper(aEvent, null, null, 0, 0,
-                                       "nsITreeBoxObject::invalidateColumn");
+// XXX see bug 454647          TreeInvalidatedHandlerHelper(aEvent, null, null, 0, 0,
+//                                       "nsITreeBoxObject::invalidateColumn");
           gTreeColumnInvalidated = true;
           break;
         case 3:
-          TreeInvalidatedHandlerHelper(aEvent, 1, 1, null, null,
-                                       "nsITreeBoxObject::invalidateRow");
+// XXX see bug 454647          TreeInvalidatedHandlerHelper(aEvent, 1, 1, null, null,
+//                                       "nsITreeBoxObject::invalidateRow");
           gTreeRowInvalidated = true;
           break;
         }
     }
 
     function TreeInvalidatedHandlerHelper(aEvent, aStartRow, aEndRow,
                                           aStartCol, aEndCol, aCauseMsg)
     {
--- a/accessible/tests/mochitest/test_bug420863.html
+++ b/accessible/tests/mochitest/test_bug420863.html
@@ -89,17 +89,29 @@ https://bugzilla.mozilla.org/show_bug.cg
       //////////////////////////////////////////////////////////////////////////
       // td with registered 'click' event handler (sequel, see doTest2())
       ok(gTdClickEventHandler, gID + ": 'click' action hasn't been performed");
 
       // unregister click event handler
       gNode.removeEventListener("click", gClickHandler, false);
 
       // check actions
-      is(gAcc.numActions, 0, gID + ": shouldn't have actions");
+      // XXX see bug 456347, sometimes after removing the event listener, the
+      // accessible is no longer valid. When fixing that bug, remove the
+      // try/exception and simply test for the gAcc.numActions value directly.
+      var numActions = -1;
+      try {
+        numActions = gAcc.numActions;
+      } catch(e) {}
+
+      if (numActions == -1)
+        todo(false,
+             "gAcc.numActions should not throw after click handler was removed!");
+      else
+        is(numActions, 0, gID + ": shouldn't have actions");
 
       SimpleTest.finish();
     }
 
     SimpleTest.waitForExplicitFinish();
     addLoadEvent(doTest);
   </script>
 </head>
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/test_events_caretmove.html
@@ -0,0 +1,130 @@
+<html>
+
+<head>
+  <title>Accessible caret move events testing</title>
+
+  <link rel="stylesheet" type="text/css"
+        href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+
+  <script type="application/javascript"
+          src="chrome://mochikit/content/MochiKit/packed.js"></script>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"></script>
+
+  <script type="application/javascript"
+          src="chrome://mochikit/content/a11y/accessible/common.js"></script>
+
+  <script type="application/javascript">
+    function synthMouseTest(aNode)
+    {
+      this.node = aNode;
+      this.testFunc = function testFunc()
+      {
+        synthesizeMouse(this.node, 1, 1, {});
+      }
+    }
+
+    function synthKeyTest(aNode, aKey)
+    {
+      this.node = aNode;
+      this.testFunc = function testFunc()
+      {
+        synthesizeKey(aKey, {});
+      }
+    }
+
+    function synthTabTest(aNode, aBackTab)
+    {
+      this.node = aNode;
+      this.testFunc = function testFunc()
+      {
+        synthesizeKey("VK_TAB", {shiftKey: aBackTab});
+      }
+    }
+
+    var gTestsArray = [];
+    var gTestIdx = -1;
+
+    var gCaretMoveHandler =
+    {
+      handleEvent: function handleEvent(aEvent)
+      {
+        if (aEvent.DOMNode == gTestsArray[gTestIdx].node)
+          gTestsArray[gTestIdx].wasCaught = true;
+      }
+    };
+
+    function doTest()
+    {
+      window.setTimeout(
+        function()
+        {
+          if (gTestIdx == gTestsArray.length - 1) {
+          
+            unregisterA11yEventListener(nsIAccessibleEvent.EVENT_TEXT_CARET_MOVED,
+                                        gCaretMoveHandler);
+
+            for (var idx = 0; idx < gTestsArray.length; idx++)
+              ok(gTestsArray[idx].wasCaught, "test " + idx + " failed");
+
+            SimpleTest.finish();
+            return;
+          }
+
+          gTestsArray[++gTestIdx].testFunc();
+          doTest();
+        },
+        100
+      );
+    }
+
+    function doTests()
+    {
+      var textbox = document.getElementById("textbox");
+      gTestsArray.push(new synthMouseTest(textbox));
+      gTestsArray.push(new synthKeyTest(textbox, "VK_RIGHT"));
+
+      var textarea = document.getElementById("textarea");
+      gTestsArray.push(new synthMouseTest(textarea));
+      gTestsArray.push(new synthKeyTest(textarea, "VK_RIGHT"));
+      gTestsArray.push(new synthKeyTest(textarea, "VK_DOWN"));
+
+      var p = document.getElementById("p");
+      gTestsArray.push(new synthMouseTest(p));
+      gTestsArray.push(new synthKeyTest(p, "VK_RIGHT"));
+      gTestsArray.push(new synthKeyTest(p, "VK_DOWN"));
+
+      gTestsArray.push(new synthTabTest(textarea, true));
+      gTestsArray.push(new synthTabTest(p));
+
+      registerA11yEventListener(nsIAccessibleEvent.EVENT_TEXT_CARET_MOVED,
+                                gCaretMoveHandler);
+
+      doTest();
+    }
+
+    SimpleTest.waitForExplicitFinish();
+    addLoadEvent(doTests);
+  </script>
+</head>
+
+<body>
+
+  <a target="_blank"
+     href="https://bugzilla.mozilla.org/show_bug.cgi?id=454377"
+     title="Accessible caret move events testing">
+    Mozilla Bug 454377
+  </a>
+  <p id="display"></p>
+  <div id="content" style="display: none"></div>
+  <pre id="test">
+  </pre>
+
+  <input id="textbox" value="hello"/>
+  <textarea id="textarea">text<br>text</textarea>
+  <p id="p" contentEditable="true"><span>text</span><br/>text</p>
+
+</body>
+</html>
--- a/accessible/tests/mochitest/test_groupattrs.xul
+++ b/accessible/tests/mochitest/test_groupattrs.xul
@@ -49,41 +49,46 @@
 
       //////////////////////////////////////////////////////////////////////////
       // xul:listbox (bug 417317)
       testGroupAttrs("item1", "1", "2");
       testGroupAttrs("item2", "2", "2");
 
       //////////////////////////////////////////////////////////////////////////
       // xul:menu (bug 443881)
-      var menu1 = document.getElementById("menu_item1");
-      menu1.open = true;
-
-      window.setTimeout(function() {
-        var menu2 = document.getElementById("menu_item2");
-        menu2.open = true;
-
-        window.setTimeout(function() {
-          testGroupAttrs("menu_item1.1", "1", "1");
-          testGroupAttrs("menu_item1.2", "1", "3");
-          testGroupAttrs("menu_item1.4", "2", "3");
-          testGroupAttrs("menu_item2", "3", "3");
-          testGroupAttrs("menu_item2.1", "1", "2", "1");
-          testGroupAttrs("menu_item2.2", "2", "2", "1");
-
-          SimpleTest.finish();
-        }, 0);
-      }, 0);
+      if (navigator.platform == "Win32") {
+	      var menu1 = document.getElementById("menu_item1");
+	      menu1.open = true;
+	
+	      window.setTimeout(function() {
+	        var menu2 = document.getElementById("menu_item2");
+	        menu2.open = true;
+	
+	        window.setTimeout(function() {
+	          testGroupAttrs("menu_item1.1", "1", "1");
+	          testGroupAttrs("menu_item1.2", "1", "3");
+	          testGroupAttrs("menu_item1.4", "2", "3");
+	          testGroupAttrs("menu_item2", "3", "3");
+	          testGroupAttrs("menu_item2.1", "1", "2", "1");
+	          testGroupAttrs("menu_item2.2", "2", "2", "1");
+	
+	          SimpleTest.finish();
+	        }, 0);
+	      }, 0);
+      }
 
       //////////////////////////////////////////////////////////////////////////
       // ARIA menu (bug 441888)
       testGroupAttrs("aria-menuitem", "1", "3");
       testGroupAttrs("aria-menuitemcheckbox", "2", "3");
       testGroupAttrs("aria-menuitemradio", "3", "3");
       testGroupAttrs("aria-menuitem2", "1", "1");
+      if (navigator.platform != "Win32")
+        SimpleTest.finish();
+
     }
 
     SimpleTest.waitForExplicitFinish();
     addLoadEvent(doTest);
   ]]>
   </script>
 
   <body xmlns="http://www.w3.org/1999/xhtml">
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/test_nsIAccessNode_utils.html
@@ -0,0 +1,55 @@
+<html>
+
+<head>
+  <title>nsIAccessNode util methods testing</title>
+
+  <link rel="stylesheet" type="text/css"
+        href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+
+  <script type="application/javascript"
+          src="chrome://mochikit/content/MochiKit/packed.js"></script>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/a11y/accessible/common.js"></script>
+
+  <script type="application/javascript">
+    function doTest()
+    {
+      var elmObj = {};
+      var acc = getAccessible("span", [nsIAccessNode], elmObj);
+      computedStyle = document.defaultView.getComputedStyle(elmObj.value, "");
+
+      // html:span element
+      is(acc.getComputedStyleValue("", "color"), computedStyle.color,
+         "Wrong color for element with ID 'span'");
+
+      // text child of html:span element
+      acc = getAccessible(acc.firstChild, [nsIAccessNode]);
+      is(acc.getComputedStyleValue("", "color"), computedStyle.color,
+         "Wrong color for text child of element with ID 'span'");
+
+      SimpleTest.finish();
+    }
+
+    SimpleTest.waitForExplicitFinish();
+    addLoadEvent(doTest);
+  </script>
+</head>
+
+<body>
+
+  <a target="_blank"
+     href="https://bugzilla.mozilla.org/show_bug.cgi?id=454211"
+     title="nsIAccessNode util methods testing">
+    Mozilla Bug 454211
+  </a>
+  <p id="display"></p>
+  <div id="content" style="display: none"></div>
+  <pre id="test">
+  </pre>
+
+  <span role="description" style="color: red" id="span">text</span>
+
+</body>
+</html>
--- a/accessible/tests/mochitest/test_nsIAccessibleHyperText.html
+++ b/accessible/tests/mochitest/test_nsIAccessibleHyperText.html
@@ -51,17 +51,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 
       // ARIA hyperlink with status invalid
       testThis("InvalidAriaHyperlink", 64, 2, "Invalid link");
 
       // image map, but not its link children. They are not part of hypertext.
       testThis("imgmap", 78, 3, "b");
 
       // empty hyperlink
-      testThis("emptyLink", 93, 4, "");
+// XXX see bug 434636      testThis("emptyLink", 93, 4, "");
 
       // normal hyperlink with embedded span
       testThis("LinkWithSpan", 119, 5, "Heise Online");
 
       // Named anchor
       testThis("namedAnchor", 197, 6, "This should never be of state_linked");
 
       SimpleTest.finish();
--- a/accessible/tests/mochitest/test_nsIAccessibleImage.html
+++ b/accessible/tests/mochitest/test_nsIAccessibleImage.html
@@ -70,18 +70,18 @@ https://bugzilla.mozilla.org/show_bug.cg
         // See if parent's screen coordinates plus image's parent relative
         // coordinates equal to image's screen coordinates.
         var parentAccX = {}, parentAccY = {}, parentAccWidth = {},
             parentAccHeight = {};
         imageParentAcc.getBounds(parentAccX, parentAccY, parentAccWidth,
                                  parentAccHeight);
         is(parentAccX.value + parentX.value, screenX.value,
            "Wrong screen x coordinate for " + aID + "!");
-        is(parentAccY.value + parentY.value, screenY.value,
-           "Wrong screen y coordinate for " + aID + "!");
+// XXX see bug 456344        is(parentAccY.value + parentY.value, screenY.value,
+//           "Wrong screen y coordinate for " + aID + "!");
       }
 
       var width = {}, height = {};
       imageAcc.getImageSize(width, height);
       is(width.value, aWidth, "Wrong width for " + aID + "!");
       is(height.value, aHeight, "wrong height for " + aID + "!");
     }
 
--- a/accessible/tests/mochitest/test_nsIAccessibleTable_1.html
+++ b/accessible/tests/mochitest/test_nsIAccessibleTable_1.html
@@ -72,17 +72,18 @@ function doTest()
   try {
     columnHeader = accTable.columnHeader;
     columnHeaderIndex =columnHeader.getIndexAt(0,2);
     is(columnHeaderIndex, 2, "columnheaderindex is wrong");
   }
   catch (e) {
     works = false;
   }
-  todo(works, "columnHeader should not throw");
+  if (!works)
+    todo(works, "columnHeader should not throw");
 
   var columnDescription;
   works = true;
   try{
     columnDescription = accTable.getColumnDescription(1);
   }
   catch (e) {
     works = false;
--- a/accessible/tests/mochitest/test_nsIAccessible_focus.html
+++ b/accessible/tests/mochitest/test_nsIAccessible_focus.html
@@ -93,18 +93,24 @@
           {
             unregisterA11yEventListener(nsIAccessibleEvent.EVENT_FOCUS, this);
 
             ok(aFocusMgr.mIsFocusHandled,
                "Focus wasn't recieved for element with ID " + aFocusMgr.mName + ".");
 
             var states = {}, extraStates = {};
             aFocusMgr.mAcc.getFinalState(states, extraStates);
-            ok(states.value & nsIAccessibleStates.STATE_FOCUSED,
-               "No focused state for element with ID " + aFocusMgr.mName + ".");
+// XXX see bug 455840. Only fails on aria-link, the other two are OK.
+// When fixing this bug, remove the if statement and else block and "todo" statement.
+            if (states.value & nsIAccessibleStates.STATE_FOCUSED)
+              ok(states.value & nsIAccessibleStates.STATE_FOCUSED,
+                 "No focused state for element with ID " + aFocusMgr.mName + ".");
+            else
+              todo(states.value & nsIAccessibleStates.STATE_FOCUSED,
+                   "No focused state for element with ID " + aFocusMgr.mName + ".");
 
             aFocusMgr.mCallback();
           }, 0, this);
       },
 
       mAcc: null,
       mElm: null,
       mName: "",
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/test_nsIAccessible_selects.html
@@ -0,0 +1,210 @@
+<html>
+
+<head>
+  <title>nsIAccessible selects tests</title>
+  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+
+  <script type="application/javascript"
+          src="chrome://mochikit/content/MochiKit/packed.js"></script>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/a11y/accessible/common.js"></script>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/a11y/accessible/nsIAccessible_selects.js"></script>
+
+  <script type="application/javascript">
+    function doTest()
+    {
+      // Label and combo, separate tags
+      var names = [
+        "Foo:", // combobox
+        "Foo:", // combobox list
+        "item 1", // first item
+        "item 2" // second item
+      ];
+      var roles = [
+        ROLE_COMBOBOX, // root
+        ROLE_COMBOBOX_LIST, // list accessible
+        ROLE_COMBOBOX_OPTION, // first option
+        ROLE_COMBOBOX_OPTION // second option
+      ];
+      var states = [
+        (STATE_FOCUSABLE | STATE_HASPOPUP | STATE_COLLAPSED), // combobox
+        (0), // combobox_list
+        (STATE_SELECTABLE | STATE_SELECTED | STATE_FOCUSABLE | STATE_FOCUSED),
+        (STATE_SELECTABLE | STATE_FOCUSABLE) // second item, not focused
+      ];
+      var undesiredStates = [
+        (STATE_FOCUSED), // combobox
+        (STATE_FOCUSED), // combobox_list
+        (0), // first item
+        (STATE_SELECTED | STATE_FOCUSED) // second, not currently focused, item
+      ];
+      testSelect("combo1", names, roles, states, undesiredStates);
+
+      // Select nested within label element.
+      // XXX see bug 455482: The accName for the label, combobox, and
+      // combobox_list contains the label text and the names of each option.
+      // When fixing bug 455482, please fix below names and remove this comment.
+      names = [
+        "Search in: Newsticker Entire site", // label
+        "Search in:", // text leaf
+        "Search in: Newsticker Entire site", // combobox
+        "Search in: Newsticker Entire site", // combobox_list
+        "Newsticker", // option 1
+        "Entire site" // Option 2
+      ];
+      roles = [
+        ROLE_LABEL, // root
+        ROLE_TEXT_LEAF, // inner text
+        ROLE_COMBOBOX, // combobox accessible
+        ROLE_COMBOBOX_LIST, // list accessible
+        ROLE_COMBOBOX_OPTION, // first option
+        ROLE_COMBOBOX_OPTION // second option
+      ];
+      states = [
+        (0), // label
+        (0), // text leaf
+        (STATE_FOCUSABLE | STATE_HASPOPUP | STATE_COLLAPSED), // combobox
+        (0), // combobox_list
+        (STATE_SELECTABLE | STATE_SELECTED | STATE_FOCUSABLE | STATE_FOCUSED),
+        (STATE_SELECTABLE | STATE_FOCUSABLE) // second item, not focused
+      ];
+      undesiredStates = [
+        (0), // label
+        (0), // text leaf
+        (STATE_FOCUSED), // combobox
+        (STATE_FOCUSED), // combobox_list
+        (0), // first item
+        (STATE_SELECTED | STATE_FOCUSED) // second, not currently focused, item
+      ];
+      testSelect("combo2", names, roles, states, undesiredStates);
+
+      // select @size with label as separate tags.
+      names = [
+        "Component:", // list
+        "Build", // item 1
+        "Disability Access APIs", // item 2
+        "General", // item 3
+        "UI" // item 4
+      ];
+      roles = [
+        ROLE_LIST, // root
+        ROLE_OPTION, // item 1
+        ROLE_OPTION, // item 2
+        ROLE_OPTION, // item 4
+        ROLE_OPTION // item 4
+      ];
+      states = [
+        (STATE_FOCUSABLE), // list
+        (STATE_SELECTABLE | STATE_FOCUSABLE | STATE_FOCUSED),
+        (STATE_SELECTABLE | STATE_FOCUSABLE), // second item, not focused
+        (STATE_SELECTABLE | STATE_FOCUSABLE), // third item, not focused
+        (STATE_SELECTABLE | STATE_FOCUSABLE) // fourth item, not focused
+      ];
+      undesiredStates = [
+        (STATE_FOCUSED), // listbox
+        (STATE_SELECTED), // first item
+        (STATE_SELECTED | STATE_FOCUSED), // second, not currently focused, item
+        (STATE_SELECTED | STATE_FOCUSED), // third, not currently focused, item
+        (STATE_SELECTED | STATE_FOCUSED) // fourth, not currently focused, item
+      ];
+      testSelect("list1", names, roles, states, undesiredStates);
+
+      // Select @size nested within label element.
+      // XXX see bug 455482: The accName for the label and listbox
+      // contains the label text and the names of each option.
+      // When fixing bug 455482, please fix below names and remove this comment.
+      names = [
+        "Version: 2.0 3.0 3.1 trunk", // label
+        "Version:", // text leaf
+        "Version: 2.0 3.0 3.1 trunk", // list
+        "2.0", // option 1
+        "3.0", // Option 2
+        "3.1", // Option 3
+        "trunk" // Option 4
+      ];
+      roles = [
+        ROLE_LABEL, // root
+        ROLE_TEXT_LEAF, // inner text
+        ROLE_LIST, // listbox accessible
+        ROLE_OPTION, // first option
+        ROLE_OPTION, // second option
+        ROLE_OPTION, // third option
+        ROLE_OPTION // fourth option
+      ];
+      states = [
+        (0), // label
+        (0), // text leaf
+        (STATE_FOCUSABLE), // listbox
+        (STATE_SELECTABLE | STATE_FOCUSABLE | STATE_FOCUSED), // Option 1
+        (STATE_SELECTABLE | STATE_FOCUSABLE), // second item, not focused
+        (STATE_SELECTABLE | STATE_FOCUSABLE), // third item, not focused
+        (STATE_SELECTABLE | STATE_FOCUSABLE) // fourth item, not focused
+      ];
+      undesiredStates = [
+        (0), // label
+        (0), // text leaf
+        (STATE_FOCUSED | STATE_HASPOPUP | STATE_COLLAPSED), // listbox
+        (STATE_SELECTED), // first item
+        (STATE_SELECTED | STATE_FOCUSED), // second, not currently focused, item
+        (STATE_SELECTED | STATE_FOCUSED), // third, not currently focused, item
+        (STATE_SELECTED | STATE_FOCUSED) // fourth, not currently focused, item
+      ];
+      testSelect("list2", names, roles, states, undesiredStates);
+
+      SimpleTest.finish();
+    }
+
+    SimpleTest.waitForExplicitFinish();
+    addLoadEvent(doTest);
+  </script>
+
+</head>
+
+<body>
+
+  <a target="_blank"
+     href="https://bugzilla.mozilla.org/show_bug.cgi?id=443889"
+     title="mochitest for selects and lists">
+    Mozilla Bug 443889
+  </a>
+  <p id="display"></p>
+  <div id="content" style="display: none"></div>
+  <pre id="test">
+  </pre>
+
+  <form action="post.php" method="post">
+  <!-- Label and select separate tags -->
+  <label for="combo1">Foo:</label>
+  <select id="combo1" name="combo1">
+    <option>item 1</option>
+    <option>item 2</option>
+  </select><br />
+
+  <!-- Select embedded in label -->
+  <label id="combo2">Search in:<select name="search">
+    <option>Newsticker</option>
+    <option>Entire site</option>
+  </select></label><br />
+
+  <!-- Label and select @size -->
+  <label for="list1">Component:</label>
+  <select id="list1" name="component" size="3">
+    <option>Build</option>
+    <option>Disability Access APIs</option>
+    <option>General</option>
+    <option>UI</option>
+  </select><br />
+
+  <!-- Select @size nested within label -->
+  <label id="list2">Version:<select name="version" size="3">
+    <option>2.0</option>
+    <option>3.0</option>
+    <option>3.1</option>
+    <option>trunk</option>
+  </select></label><br />
+  </form>
+</body>
+</html>
--- a/accessible/tests/mochitest/test_nsOuterDocAccessible.html
+++ b/accessible/tests/mochitest/test_nsOuterDocAccessible.html
@@ -47,17 +47,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 
           // check if it is focusable, not desired.
           var state = {}, extraState = {}
           outerDocAcc.getFinalState(state, extraState);
           is(state.value & state_focusable, 0,
              "Wrong focusable state bit for internal frame!");
 
           // see bug 428954: No name wanted for internal frame
-          is(outerDocAcc.name, "", "Wrong name for internal frame!");
+// xxx see bug 454636          is(outerDocAcc.name, "", "Wrong name for internal frame!");
 
           // see bug 440770, no actions wanted on outer doc
           is(outerDocAcc.numActions, 0,
              "Wrong number of actions for internal frame!");
           var actionTempStr; // not really used, just needs to receive a value
           try {
             actionTempStr = outerDocAcc.getActionName(0);
             do_throw("No exception thrown for actionName!");
--- a/accessible/tests/mochitest/test_textattrs.html
+++ b/accessible/tests/mochitest/test_textattrs.html
@@ -12,16 +12,17 @@
     const nsIAccessibleText = Components.interfaces.nsIAccessibleText;
     const nsIAccessibleEvent = Components.interfaces.nsIAccessibleEvent;
 
     const nsIDOMNSEditableElement =
       Components.interfaces.nsIDOMNSEditableElement;
     const nsIObserverService = Components.interfaces.nsIObserverService;
 
     var gAccRetrieval = null;
+    var gComputedStyle = null;
 
     /**
      * Test text attributes.
      *
      * @param aID               the ID of DOM element having text accessible
      * @param aOffset           the offset inside text accessible to fetch
      *                          text attributes
      * @param aAttrs            the map of text attributes (name/value pairs)
@@ -171,26 +172,27 @@
       node.focus();
 
       var editor = node.QueryInterface(nsIDOMNSEditableElement).editor;
       var spellchecker = editor.getInlineSpellChecker(true);
       spellchecker.enableRealTimeSpell = true;
 
       window.setTimeout(function()
         {
+          gComputedStyle = document.defaultView.getComputedStyle(node, "");
           var defAttrs = {
-            "font-style": "normal",
-            "text-align": "start",
-            "font-size": "11px",
-            "background-color": "rgb(255, 255, 255)",
-            "font-weight": "400",
-            "text-indent": "0px",
-            "color": "rgb(0, 0, 0)",
-            "font-family": "Lucida Grande",
-            "text-position": "baseline"
+            "font-style": gComputedStyle.fontStyle,
+            "text-align": gComputedStyle.textAlign,
+            "font-size": gComputedStyle.fontSize,
+            "background-color": gComputedStyle.backgroundColor,
+            "font-weight": gComputedStyle.fontWeight,
+            "text-indent": gComputedStyle.textIndent,
+            "color": gComputedStyle.color,
+            "font-family": gComputedStyle.fontFamily,
+            "text-position": gComputedStyle.verticalAlign
           };
           testDefaultTextAttrs(ID, defAttrs);
 
           var attrs = { };
           var misspelledAttrs = {
             "invalid": "spelling"
           };
 
@@ -213,241 +215,303 @@
     function doTest()
     {
       gAccRetrieval = Components.classes["@mozilla.org/accessibleRetrieval;1"].
                       getService(nsIAccessibleRetrieval);
 
       //////////////////////////////////////////////////////////////////////////
       // area1
       var ID = "area1";
+      var tempElem = document.getElementById(ID);
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
       var defAttrs = {
-        "font-style": "normal",
-        "text-align": "start",
-        "font-size": "16px",
-        "background-color": "rgb(255, 255, 255)",
-        "font-weight": "400",
-        "text-indent": "0px",
-        "color": "rgb(0, 0, 0)",
-        "font-family": "serif",
-        "text-position": "baseline"
+        "font-style": gComputedStyle.fontStyle,
+        "text-align": gComputedStyle.textAlign,
+        "font-size": gComputedStyle.fontSize,
+        "background-color": "rgb(0, 0, 0)", // XXX 455834
+        "font-weight": gComputedStyle.fontWeight,
+        "text-indent": gComputedStyle.textIndent,
+        "color": gComputedStyle.color,
+        "font-family": gComputedStyle.fontFamily,
+        "text-position": gComputedStyle.verticalAlign
       };
 
       testDefaultTextAttrs(ID, defAttrs);
 
       var attrs = {};
       testTextAttrs(ID, 0, attrs, 0, 7);
 
-      attrs = {"font-weight": "401"};
+      tempElem = tempElem.firstChild.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"font-weight": gComputedStyle.fontWeight};
       testTextAttrs(ID, 7, attrs, 7, 11);
 
       attrs = {};
       testTextAttrs(ID, 12, attrs, 11, 18);
 
       //////////////////////////////////////////////////////////////////////////
       // area2
       ID = "area2";
+      tempElem = document.getElementById(ID);
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
       defAttrs = {
-        "font-style": "normal",
-        "text-align": "start",
-        "font-size": "16px",
-        "background-color": "rgb(255, 255, 255)",
-        "font-weight": "400",
-        "text-indent": "0px",
-        "color": "rgb(0, 0, 0)",
-        "font-family": "serif",
-        "text-position": "baseline"
+        "font-style": gComputedStyle.fontStyle,
+        "text-align": gComputedStyle.textAlign,
+        "font-size": gComputedStyle.fontSize,
+        "background-color": "rgb(0, 0, 0)", // XXX bug 455834
+        "font-weight": gComputedStyle.fontWeight,
+        "text-indent": gComputedStyle.textIndent,
+        "color": gComputedStyle.color,
+        "font-family": gComputedStyle.fontFamily,
+        "text-position": gComputedStyle.verticalAlign
       };
 
       testDefaultTextAttrs(ID, defAttrs);
 
       attrs = {};
       testTextAttrs(ID, 0, attrs, 0, 7);
 
-      attrs = {"font-weight": "401"};
+      tempElem = tempElem.firstChild.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"font-weight": gComputedStyle.fontWeight};
       testTextAttrs(ID, 7, attrs, 7, 12);
 
-      attrs = {"font-style": "italic", "font-weight": "401"};
+      tempElem = tempElem.firstChild.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"font-style": gComputedStyle.fontStyle,
+               "font-weight": gComputedStyle.fontWeight};
       testTextAttrs(ID, 13, attrs, 12, 19);
 
+      tempElem = tempElem.parentNode;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
       attrs = {"font-weight": "401"};
       testTextAttrs(ID, 20, attrs, 19, 23);
 
       attrs = {};
       testTextAttrs(ID, 24, attrs, 23, 30);
 
       //////////////////////////////////////////////////////////////////////////
       // area3
       ID = "area3";
+      tempElem = document.getElementById(ID);
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
       defAttrs = {
-        "font-style": "normal",
-        "text-align": "start",
-        "font-size": "16px",
-        "background-color": "rgb(0, 0, 255)",
-        "font-weight": "400",
-        "text-indent": "0px",
-        "color": "rgb(0, 0, 0)",
-        "font-family": "serif",
-        "text-position": "baseline"
+        "font-style": gComputedStyle.fontStyle,
+        "text-align": gComputedStyle.textAlign,
+        "font-size": gComputedStyle.fontSize,
+        "background-color": gComputedStyle.backgroundColor,
+        "font-weight": gComputedStyle.fontWeight,
+        "text-indent": gComputedStyle.textIndent,
+        "color": gComputedStyle.color,
+        "font-family": gComputedStyle.fontFamily,
+        "text-position": gComputedStyle.verticalAlign
       };
 
       testDefaultTextAttrs(ID, defAttrs);
 
-      attrs = {"color": "rgb(0, 128, 0)"};
+      tempElem = tempElem.firstChild.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"color": gComputedStyle.color};
       testTextAttrs(ID, 0, attrs, 0, 6);
 
-      attrs = {"color": "rgb(255, 0, 0)"};
+      tempElem = tempElem.firstChild.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"color": gComputedStyle.color};
       testTextAttrs(ID, 6, attrs, 6, 26);
 
-      attrs = {"color": "rgb(0, 128, 0)"};
+      tempElem = tempElem.parentNode;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"color": gComputedStyle.color};
       testTextAttrs(ID, 26, attrs, 26, 27);
 
-      attrs = {"color": "rgb(0, 128, 0)", "background-color": "rgb(255, 255, 0)"};
+      tempElem = tempElem.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"color": gComputedStyle.color,
+               "background-color": gComputedStyle.backgroundColor};
       testTextAttrs(ID, 27, attrs, 27, 50);
 
       //////////////////////////////////////////////////////////////////////////
       // area4
       ID = "area4";
+      tempElem = document.getElementById(ID);
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
       defAttrs = {
-        "font-style": "normal",
-        "text-align": "start",
-        "font-size": "16px",
-        "background-color": "rgb(255, 255, 255)",
-        "font-weight": "400",
-        "text-indent": "0px",
-        "color": "rgb(0, 0, 0)",
-        "font-family": "serif",
-        "text-position": "baseline"
+        "font-style": gComputedStyle.fontStyle,
+        "text-align": gComputedStyle.textAlign,
+        "font-size": gComputedStyle.fontSize,
+        "background-color": "rgb(0, 0, 0)", // XXX bug 455834
+        "font-weight": gComputedStyle.fontWeight,
+        "text-indent": gComputedStyle.textIndent,
+        "color": gComputedStyle.color,
+        "font-family": gComputedStyle.fontFamily,
+        "text-position": gComputedStyle.verticalAlign
       };
 
       testDefaultTextAttrs(ID, defAttrs);
 
-      attrs = {"color": "rgb(0, 128, 0)"};
+      tempElem = tempElem.firstChild.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"color": gComputedStyle.color};
       testTextAttrs(ID, 0, attrs, 0, 16);
 
-      attrs = {"color": "rgb(255, 0, 0)"};
+      tempElem = tempElem.nextSibling.firstChild.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"color": gComputedStyle.color};
       testTextAttrs(ID, 16, attrs, 16, 33);
 
-      attrs = {"color": "rgb(0, 128, 0)"};
+      tempElem = tempElem.parentNode;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"color": gComputedStyle.color};
       testTextAttrs(ID, 34, attrs, 33, 46);
 
       //////////////////////////////////////////////////////////////////////////
       // area5
       ID = "area5";
+      tempElem = document.getElementById(ID);
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
       defAttrs = {
-        "font-style": "normal",
-        "text-align": "start",
-        "font-size": "16px",
-        "background-color": "rgb(255, 255, 255)",
-        "font-weight": "400",
-        "text-indent": "0px",
-        "color": "rgb(0, 0, 0)",
-        "font-family": "serif",
-        "text-position": "baseline"
+        "font-style": gComputedStyle.fontStyle,
+        "text-align": gComputedStyle.textAlign,
+        "font-size": gComputedStyle.fontSize,
+        "background-color": "rgb(0, 0, 0)", // XXX bug 455834
+        "font-weight": gComputedStyle.fontWeight,
+        "text-indent": gComputedStyle.textIndent,
+        "color": gComputedStyle.color,
+        "font-family": gComputedStyle.fontFamily,
+        "text-position": gComputedStyle.verticalAlign
       };
 
       testDefaultTextAttrs(ID, defAttrs);
 
-      attrs = {"color": "rgb(0, 128, 0)"};
+      tempElem = tempElem.firstChild.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"color": gComputedStyle.color};
       testTextAttrs(ID, 0, attrs, 0, 5);
 
       attrs = {};
       testTextAttrs(ID, 7, attrs, 5, 8);
 
-      attrs = {"color": "rgb(255, 0, 0)"};
+      tempElem = tempElem.nextSibling.nextSibling.nextSibling.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"color": gComputedStyle.color};
       testTextAttrs(ID, 9, attrs, 8, 11);
 
       attrs = {};
       testTextAttrs(ID, 11, attrs, 11, 18);
 
       //////////////////////////////////////////////////////////////////////////
       // area6 (CSS vertical-align property, bug 445938)
       ID = "area6";
+      tempElem = document.getElementById(ID);
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
       defAttrs = {
-        "font-style": "normal",
-        "text-align": "start",
-        "font-size": "16px",
-        "background-color": "rgb(255, 255, 255)",
-        "font-weight": "400",
-        "text-indent": "0px",
-        "color": "rgb(0, 0, 0)",
-        "font-family": "serif",
-        "text-position": "baseline"
+        "font-style": gComputedStyle.fontStyle,
+        "text-align": gComputedStyle.textAlign,
+        "font-size": gComputedStyle.fontSize,
+        "background-color": "rgb(0, 0, 0)", // XXX bug 455834
+        "font-weight": gComputedStyle.fontWeight,
+        "text-indent": gComputedStyle.textIndent,
+        "color": gComputedStyle.color,
+        "font-family": gComputedStyle.fontFamily,
+        "text-position": gComputedStyle.verticalAlign
       };
 
       testDefaultTextAttrs(ID, defAttrs);
 
       attrs = {};
       testTextAttrs(ID, 0, attrs, 0, 5);
 
-      attrs = {"text-position": "super", "font-size": "13px" };
+      tempElem = tempElem.firstChild.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"text-position": gComputedStyle.verticalAlign,
+               "font-size": gComputedStyle.fontSize};
       testTextAttrs(ID, 5, attrs, 5, 13);
 
       attrs = {};
       testTextAttrs(ID, 13, attrs, 13, 27);
 
-      attrs = {"text-position": "super" };
+      tempElem = tempElem.nextSibling.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"text-position": gComputedStyle.verticalAlign};
       testTextAttrs(ID, 27, attrs, 27, 35);
 
       attrs = {};
       testTextAttrs(ID, 35, attrs, 35, 39);
 
-      attrs = {"text-position": "sub", "font-size": "13px" };
+      tempElem = tempElem.nextSibling.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"text-position": gComputedStyle.verticalAlign,
+               "font-size": gComputedStyle.fontSize};
       testTextAttrs(ID, 39, attrs, 39, 50);
 
       attrs = {};
       testTextAttrs(ID, 50, attrs, 50, 55);
 
-      attrs = {"text-position": "sub" };
+      tempElem = tempElem.nextSibling.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"text-position": gComputedStyle.verticalAlign};
       testTextAttrs(ID, 55, attrs, 55, 64);
 
       //////////////////////////////////////////////////////////////////////////
       // area7
       ID = "area7";
+      tempElem = document.getElementById(ID);
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
       defAttrs = {
-        "font-style": "normal",
-        "text-align": "start",
-        "font-size": "16px",
-        "background-color": "rgb(255, 255, 255)",
-        "font-weight": "400",
-        "text-indent": "0px",
-        "color": "rgb(0, 0, 0)",
-        "font-family": "serif",
-        "text-position": "baseline"
+        "font-style": gComputedStyle.fontStyle,
+        "text-align": gComputedStyle.textAlign,
+        "font-size": gComputedStyle.fontSize,
+        "background-color": "rgb(0, 0, 0)", // XXX 455834
+        "font-weight": gComputedStyle.fontWeight,
+        "text-indent": gComputedStyle.textIndent,
+        "color": gComputedStyle.color,
+        "font-family": gComputedStyle.fontFamily,
+        "text-position": gComputedStyle.verticalAlign
       };
 
       testDefaultTextAttrs(ID, defAttrs);
 
       attrs = {"language": "ru"};
       testTextAttrs(ID, 0, attrs, 0, 12);
 
       attrs = {"language": "en"};
       testTextAttrs(ID, 12, attrs, 12, 13);
 
-      attrs = {"language" :"en", "background-color": "rgb(0, 0, 255)"};
+      tempElem = tempElem.firstChild.nextSibling.nextSibling.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"language" :"en",
+               "background-color": gComputedStyle.backgroundColor};
       testTextAttrs(ID, 13, attrs, 13, 26);
 
       attrs = {"language": "en" };
       testTextAttrs(ID, 26, attrs, 26, 27);
 
       attrs = {"language": "de"};
       testTextAttrs(ID, 27, attrs, 27, 42);
 
       attrs = {"language": "en"};
       testTextAttrs(ID, 42, attrs, 42, 43);
 
       attrs = {};
       testTextAttrs(ID, 43, attrs, 43, 50);
 
-      attrs = {"color": "rgb(255, 0, 255)"};
+      tempElem = tempElem.nextSibling.nextSibling.nextSibling.nextSibling.firstChild.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"color": gComputedStyle.color};
       testTextAttrs(ID, 50, attrs, 50, 57);
 
-      attrs = {"font-weight": "401", "color": "rgb(255, 0, 255)" };
+      tempElem = tempElem.firstChild.nextSibling;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"font-weight": gComputedStyle.fontWeight,
+               "color": gComputedStyle.color};
       testTextAttrs(ID, 57, attrs, 57, 61);
 
-      attrs = {"color": "rgb(255, 0, 255)"};
+      tempElem = tempElem.parentNode;
+      gComputedStyle = document.defaultView.getComputedStyle(tempElem, "");
+      attrs = {"color": gComputedStyle.color};
       testTextAttrs(ID, 61, attrs, 61, 68);
 
       //////////////////////////////////////////////////////////////////////////
       // test spelling text attributes
       testSpellTextAttrs(); // Will call SimpleTest.finish();
     }
 
     SimpleTest.waitForExplicitFinish();
--- a/accessible/tests/mochitest/test_textboxes.html
+++ b/accessible/tests/mochitest/test_textboxes.html
@@ -2,27 +2,29 @@
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=442648
 -->
 <head>
   <title>nsIAccessible textboxes chrome tests</title>
   <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
 
-  <script type="application/javascript" src="chrome://mochikit/content/MochiKit/packed.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/MochiKit/packed.js"></script>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
 
-  <script type="application/javascript" src="chrome://mochikit/content/a11y/accessible/testTextboxes.js"></script>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/a11y/accessible/common.js"></script>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/a11y/accessible/testTextboxes.js"></script>
 
   <script type="application/javascript">
     function doTest()
     {
-      gAccRetrieval = Components.classes["@mozilla.org/accessibleRetrieval;1"].
-                      getService(nsIAccessibleRetrieval);
-
       //////////////////////////////////////////////////////////////////////////
       // normal textbox without content and with no proper label
       testThis("unlabelled_Textbox", // ID
                null, // name
                "", // value
                "", // description
                role_entry, // role
                (state_focusable), // state
--- a/accessible/tests/mochitest/test_textboxes.xul
+++ b/accessible/tests/mochitest/test_textboxes.xul
@@ -7,25 +7,24 @@
         title="nsIAccessible XUL textboxes chrome tests">
 
   <script type="application/javascript" 
           src="chrome://mochikit/content/MochiKit/packed.js"></script>
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
 
   <script type="application/javascript"
-          src="chrome://mochikit/content/a11y/accessible/testTextboxes.js"></script>
+          src="chrome://mochikit/content/a11y/accessible/common.js" />
+  <script type="application/javascript"
+          src="chrome://mochikit/content/a11y/accessible/testTextboxes.js" />
 
   <script type="application/javascript">
   <![CDATA[
     function doTest()
     {
-      gAccRetrieval = Components.classes["@mozilla.org/accessibleRetrieval;1"].
-                      getService(nsIAccessibleRetrieval);
-
       //////////////////////////////////////////////////////////////////////////
       // normal textbox without content and with no proper label
       testThis("unlabelled_Textbox", // ID
                "", // name
                "", // value
                "", // description
                role_entry, // role
                (state_focusable), // state
--- a/browser/app/Makefile.in
+++ b/browser/app/Makefile.in
@@ -67,22 +67,28 @@ DEFINES += -DAPP_UA_NAME="$(APP_UA_NAME)
 
 DIST_FILES = application.ini
 
 GRE_MILESTONE = $(shell $(PYTHON) $(topsrcdir)/config/printconfigsetting.py $(LIBXUL_DIST)/bin/platform.ini Build Milestone)
 GRE_BUILDID = $(shell $(PYTHON) $(topsrcdir)/config/printconfigsetting.py $(LIBXUL_DIST)/bin/platform.ini Build BuildID)
 
 DEFINES += -DGRE_MILESTONE=$(GRE_MILESTONE) -DGRE_BUILDID=$(GRE_BUILDID)
 
-ifdef MOZ_MEMORY
-ifneq ($(OS_ARCH),WINNT)
-LIBS += -ljemalloc
+SOURCE_STAMP := $(shell cd $(topsrcdir) ; hg identify 2>/dev/null | cut -f1 -d' ')
+ifdef SOURCE_STAMP
+DEFINES += -DMOZ_SOURCE_STAMP="$(SOURCE_STAMP)"
 endif
+
+SOURCE_REPO := $(shell hg -R $(topsrcdir) showconfig paths.default 2>/dev/null | sed s/^ssh:/http:/)
+ifdef SOURCE_REPO
+DEFINES += -DMOZ_SOURCE_REPO="$(SOURCE_REPO)"
 endif
 
+LIBS += $(JEMALLOC_LIBS)
+
 ifdef LIBXUL_SDK
 include $(topsrcdir)/config/rules.mk
 else
 # Build a binary bootstrapping with XRE_main
 
 ifeq ($(USE_SHORT_LIBNAME), 1)
 PROGRAM = $(MOZ_APP_NAME)$(BIN_SUFFIX)
 else
@@ -112,21 +118,28 @@ else
 EXTRA_DSO_LIBS += xul
 endif
 endif
 
 ifneq (,$(filter mac cocoa,$(MOZ_WIDGET_TOOLKIT)))
 TK_LIBS := $(TK_LIBS)
 endif
 
+ifdef MOZ_ENABLE_LIBXUL
+APP_XPCOM_LIBS = $(XPCOM_GLUE_LDOPTS)
+else
+MOZILLA_INTERNAL_API = 1
+APP_XPCOM_LIBS = $(XPCOM_LIBS)
+endif
+
 LIBS += \
 	$(STATIC_COMPONENTS_LINKER_PATH) \
 	$(EXTRA_DSO_LIBS) \
 	$(MOZ_JS_LIBS) \
-	$(XPCOM_GLUE_LDOPTS) \
+	$(APP_XPCOM_LIBS) \
 	$(NSPR_LIBS) \
 	$(TK_LIBS) \
 	$(NULL)
 
 # Add explicit X11 dependency when building against X11 toolkits
 ifneq (,$(filter gtk2,$(MOZ_WIDGET_TOOLKIT)))
 LIBS += $(XLDFLAGS) $(XLIBS) $(ZLIB_LIBS)
 endif
--- a/browser/app/application.ini
+++ b/browser/app/application.ini
@@ -36,16 +36,22 @@
 ; ***** END LICENSE BLOCK *****
 
 #filter substitution
 [App]
 Vendor=Mozilla
 Name=Firefox
 Version=@APP_VERSION@
 BuildID=@GRE_BUILDID@
+#ifdef MOZ_SOURCE_REPO
+SourceRepository=@MOZ_SOURCE_REPO@
+#endif
+#ifdef MOZ_SOURCE_STAMP
+SourceStamp=@MOZ_SOURCE_STAMP@
+#endif
 Copyright=Copyright (c) 1998 - 2008 mozilla.org
 ID={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
 
 [Gecko]
 MinVersion=@GRE_MILESTONE@
 MaxVersion=@GRE_MILESTONE@
 
 [XRE]
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -304,18 +304,18 @@ pref("browser.link.open_external", 3);
 pref("browser.link.open_newwindow", 3);
 
 // 0: no restrictions - divert everything
 // 1: don't divert window.open at all
 // 2: don't divert window.open with features
 pref("browser.link.open_newwindow.restriction", 2);
 
 // Tabbed browser
-pref("browser.tabs.autoHide", true);
-pref("browser.tabs.forceHide", false);
+pref("browser.tabs.autoHide", false);
+pref("browser.tabs.closeWindowWithLastTab", true);
 pref("browser.tabs.warnOnClose", true);
 pref("browser.tabs.warnOnOpen", true);
 pref("browser.tabs.maxOpenBeforeWarn", 15);
 pref("browser.tabs.loadInBackground", true);
 pref("browser.tabs.loadFolderAndReplace", true);
 pref("browser.tabs.opentabfor.middleclick", true);
 pref("browser.tabs.loadDivertedInBackground", false);
 pref("browser.tabs.loadBookmarksInBackground", false);
@@ -333,16 +333,17 @@ pref("browser.tabs.closeButtons", 1);
 // When tabs opened by links in other tabs via a combination of 
 // browser.link.open_newwindow being set to 3 and target="_blank" etc are
 // closed:
 // true   return to the tab that opened this tab (its owner)
 // false  return to the adjacent tab (old default)
 pref("browser.tabs.selectOwnerOnClose", true);
 
 pref("browser.ctrlTab.mostRecentlyUsed", true);
+pref("browser.ctrlTab.recentlyUsedLimit", 7);
 pref("browser.ctrlTab.smoothScroll", true);
 
 // Default bookmark sorting
 pref("browser.bookmarks.sort.direction", "descending");
 pref("browser.bookmarks.sort.resource", "rdf:http://home.netscape.com/NC-rdf#Name");
 
 // By default, do not export HTML at shutdown.
 // If true, at shutdown the bookmarks in your menu and toolbar will
@@ -690,25 +691,16 @@ pref("browser.sessionstore.postdata", 0)
 // 0 = everywhere, 1 = unencrypted sites, 2 = nowhere
 pref("browser.sessionstore.privacy_level", 1);
 // how many tabs can be reopened (per window)
 pref("browser.sessionstore.max_tabs_undo", 10);
 
 // allow META refresh by default
 pref("accessibility.blockautorefresh", false);
 
-// If true, will migrate uri post-data annotations to
-// bookmark post-data annotations (bug 398914)
-// XXX to be removed after beta 2 (bug 391419)
-pref("browser.places.migratePostDataAnnotations", true);
-
-// If true, will update the Smart Bookmarks uri for
-// recent tags (bug 385245). Useful just for FX3 beta users.
-pref("browser.places.updateRecentTagsUri", true);
-
 // the (maximum) number of the recent visits to sample
 // when calculating frecency
 pref("places.frecency.numVisits", 10);
 
 // Number of records to update frecency for when idle.
 pref("places.frecency.numCalcOnIdle", 50);
 
 // Number of records to update frecency for when migrating from
--- a/browser/base/content/browser-menubar.inc
+++ b/browser/base/content/browser-menubar.inc
@@ -379,29 +379,30 @@
                           oncommand="BrowserGoHome(event);"
                           onclick="checkForMiddleClick(this, event);"
                           key="goHome"/>
                 <menuitem label="&showAllHistoryCmd2.label;"
 #ifndef XP_MACOSX
                           key="showAllHistoryKb"
 #endif
                           command="Browser:ShowAllHistory"/>
-                <menuseparator id="startHistorySeparator" builder="start"/>
+                <menuseparator id="startHistorySeparator"/>
                 <menuseparator id="endHistorySeparator" builder="end"/>
                 <menu id="historyUndoMenu" label="&historyUndoMenu.label;" disabled="true">
                   <menupopup id="historyUndoPopup" onpopupshowing="HistoryMenu.populateUndoSubmenu();"/>
                 </menu>
               </menupopup>
             </menu>
 
   <menu id="bookmarksMenu" 
         label="&bookmarksMenu.label;" accesskey="&bookmarksMenu.accesskey;"
         ondragenter="PlacesMenuDNDController.onBookmarksMenuDragEnter(event);"
         ondragdrop="nsDragAndDrop.drop(event, BookmarksMenuDropHandler);"
-        ondragover="nsDragAndDrop.dragOver(event, BookmarksMenuDropHandler);">
+        ondragover="nsDragAndDrop.dragOver(event, BookmarksMenuDropHandler);"
+        ondragexit="nsDragAndDrop.dragExit(event, BookmarksMenuDropHandler);">
     <menupopup id="bookmarksMenuPopup"
                type="places"
                place="place:folder=BOOKMARKS_MENU"
                context="placesContext"
                openInTabs="children"
                oncommand="BookmarksEventHandler.onCommand(event);"
                onclick="BookmarksEventHandler.onClick(event);"
                onpopupshowing="BookmarksEventHandler.onPopupShowing(event);">
@@ -432,17 +433,17 @@
             label="&personalbarCmd.label;"
             container="true">
         <menupopup id="bookmarksToolbarFolderPopup"
                    type="places"
                    place="place:folder=TOOLBAR"
                    context="placesContext"
                    onpopupshowing="BookmarksEventHandler.onPopupShowing(event);"/>
       </menu>
-      <menuseparator builder="start"/>
+      <menuseparator/>
     </menupopup>
   </menu>
 
             <menu id="tools-menu" label="&toolsMenu.label;" accesskey="&toolsMenu.accesskey;">
               <menupopup id="menu_ToolsPopup">
               <menuitem label="&search.label;" accesskey="&search.accesskey;" 
                         key="key_search" command="Tools:Search"/>
               <menuseparator id="browserToolsSeparator"/>
--- a/browser/base/content/browser-places.js
+++ b/browser/base/content/browser-places.js
@@ -706,17 +706,16 @@ var BookmarksEventHandler = {
         target._endMarker = -1;
       }
       return;
     }
 
     if (!target._endOptSeparator) {
       // create a separator before options
       target._endOptSeparator = document.createElement("menuseparator");
-      target._endOptSeparator.setAttribute("builder", "end");
       target._endMarker = target.childNodes.length;
       target.appendChild(target._endOptSeparator);
     }
 
     if (siteURIString && !target._endOptOpenSiteURI) {
       // Add "Open (Feed Name)" menuitem if it's a livemark with a siteURI
       target._endOptOpenSiteURI = document.createElement("menuitem");
       target._endOptOpenSiteURI.setAttribute("siteURI", siteURIString);
@@ -784,17 +783,18 @@ var BookmarksEventHandler = {
  */
 var BookmarksMenuDropHandler = {
   /**
    * Need to tell the session to update the state of the cursor as we drag
    * over the Bookmarks Menu to show the "can drop" state vs. the "no drop"
    * state.
    */
   onDragOver: function BMDH_onDragOver(event, flavor, session) {
-    session.canDrop = this.canDrop(event, session);
+    if (!this.canDrop(event, session))
+      event.dataTransfer.effectAllowed = "none";
   },
 
   /**
    * Advertises the set of data types that can be dropped on the Bookmarks
    * Menu
    * @returns a FlavourSet object per nsDragAndDrop parlance.
    */
   getSupportedFlavours: function BMDH_getSupportedFlavours() {
@@ -807,33 +807,47 @@ var BookmarksMenuDropHandler = {
    * @param   event
    *          A dragover event
    * @param   session
    *          The active DragSession
    * @returns true if the user can drop onto the Bookmarks Menu item, false 
    *          otherwise.
    */
   canDrop: function BMDH_canDrop(event, session) {
+    PlacesControllerDragHelper.currentDataTransfer = event.dataTransfer;
+
     var ip = new InsertionPoint(PlacesUtils.bookmarksMenuFolderId, -1);  
     return ip && PlacesControllerDragHelper.canDrop(ip);
   },
 
   /**
    * Called when the user drops onto the top level Bookmarks Menu item.
    * @param   event
    *          A drop event
    * @param   data
    *          Data that was dropped
    * @param   session
    *          The active DragSession
    */
   onDrop: function BMDH_onDrop(event, data, session) {
-    // Put the item at the end of bookmark menu
-    var ip = new InsertionPoint(PlacesUtils.bookmarksMenuFolderId, -1);
+    PlacesControllerDragHelper.currentDataTransfer = event.dataTransfer;
+
+  // Put the item at the end of bookmark menu
+    var ip = new InsertionPoint(PlacesUtils.bookmarksMenuFolderId, -1,
+                                Ci.nsITreeView.DROP_ON);
     PlacesControllerDragHelper.onDrop(ip);
+  },
+
+  /**
+   * Called when drop target leaves the menu or after a drop.
+   * @param   aEvent
+   *          A drop event
+   */
+  onDragExit: function BMDH_onDragExit(event, session) {
+    PlacesControllerDragHelper.currentDataTransfer = null;
   }
 };
 
 /**
  * Handles special drag and drop functionality for menus on the Bookmarks 
  * Toolbar and Bookmarks Menu.
  */
 var PlacesMenuDNDController = {
@@ -898,18 +912,19 @@ var PlacesMenuDNDController = {
   },
   
   /**
    * Determines if a XUL element represents a container in the Bookmarks system
    * @returns true if the element is a container element (menu or 
    *`         menu-toolbarbutton), false otherwise.
    */
   _isContainer: function PMDC__isContainer(node) {
-    return node.localName == "menu" || 
-           node.localName == "toolbarbutton" && node.getAttribute("type") == "menu";
+    return node.localName == "menu" ||
+           (node.localName == "toolbarbutton" &&
+            node.getAttribute("type") == "menu");
   },
   
   /**
    * Opens the Bookmarks Menu when it is dragged over. (This is special-cased, 
    * since the toplevel Bookmarks <menu> is not a member of an existing places
    * container, as folders on the personal toolbar or submenus are. 
    * @param   event
    *          The DragEnter event that spawned the opening. 
@@ -1004,67 +1019,8 @@ var PlacesStarButton = {
                                             aIsAnnotationProperty, aValue) {
     if (!this._batching && aProperty == "uri")
       this.updateState();
   },
 
   onItemVisited: function() { },
   onItemMoved: function() { }
 };
-
-/**
- * Various migration tasks.
- */
-function placesMigrationTasks() {
-  // bug 398914 - move all post-data annotations from URIs to bookmarks
-  // XXX - REMOVE ME FOR BETA 3 (bug 391419)
-  if (gPrefService.getBoolPref("browser.places.migratePostDataAnnotations")) {
-    const annosvc = PlacesUtils.annotations;
-    var bmsvc = PlacesUtils.bookmarks;
-    const oldPostDataAnno = "URIProperties/POSTData";
-    var pages = annosvc.getPagesWithAnnotation(oldPostDataAnno, {});
-    for (let i = 0; i < pages.length; i++) {
-      try {
-        let uri = pages[i];
-        var postData = annosvc.getPageAnnotation(uri, oldPostDataAnno);
-        // We can't know which URI+keyword combo this postdata was for, but
-        // it's very likely that if this URI is bookmarked and has a keyword
-        // *and* the URI has postdata, then this bookmark was using the
-        // postdata. Propagate the annotation to all bookmarks for this URI
-        // just to be safe.
-        let bookmarks = bmsvc.getBookmarkIdsForURI(uri, {});
-        for (let i = 0; i < bookmarks.length; i++) {
-          var keyword = bmsvc.getKeywordForBookmark(bookmarks[i]);
-          if (keyword)
-            annosvc.setItemAnnotation(bookmarks[i], POST_DATA_ANNO, postData, 0, annosvc.EXPIRE_NEVER); 
-        }
-        // Remove the old annotation.
-        annosvc.removePageAnnotation(uri, oldPostDataAnno);
-      } catch(ex) {}
-    }
-    gPrefService.setBoolPref("browser.places.migratePostDataAnnotations", false);
-  }
-
-  if (gPrefService.getBoolPref("browser.places.updateRecentTagsUri")) {
-    var oldUriSpec = "place:folder=TAGS&group=3&queryType=1" +
-                     "&applyOptionsToContainers=1&sort=12&maxResults=10";
-
-    var maxResults = 10;
-    var newUriSpec = "place:type=" + 
-                     Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_QUERY +
-                     "&sort=" + 
-                     Ci.nsINavHistoryQueryOptions.SORT_BY_LASTMODIFIED_DESCENDING +
-                     "&maxResults=" + maxResults;
-                     
-    var ios = Cc["@mozilla.org/network/io-service;1"].
-              getService(Ci.nsIIOService);
-
-    var oldUri = ios.newURI(oldUriSpec, null, null);
-    var newUri = ios.newURI(newUriSpec, null, null);
-
-    let bmsvc = PlacesUtils.bookmarks;
-    let bookmarks = bmsvc.getBookmarkIdsForURI( oldUri, {});
-    for (let i = 0; i < bookmarks.length; i++) {
-      bmsvc.changeBookmarkURI( bookmarks[i], newUri);
-    }
-    gPrefService.setBoolPref("browser.places.updateRecentTagsUri", false);
-  }
-}
--- a/browser/base/content/browser-tabPreviews.js
+++ b/browser/base/content/browser-tabPreviews.js
@@ -37,19 +37,19 @@
  * ***** END LICENSE BLOCK *****
 #endif
  */
 
 /**
  * Tab previews utility, produces thumbnails
  */
 var tabPreviews = {
-  aspectRatio: 0.6875, // 16:11
+  aspectRatio: 0.5625, // 16:9
   init: function () {
-    this.width = Math.ceil(screen.availWidth / 7);
+    this.width = Math.ceil(screen.availWidth / 5);
     this.height = Math.round(this.width * this.aspectRatio);
 
     gBrowser.tabContainer.addEventListener("TabSelect", this, false);
     gBrowser.tabContainer.addEventListener("SSTabRestored", this, false);
   },
   uninit: function () {
     gBrowser.tabContainer.removeEventListener("TabSelect", this, false);
     gBrowser.tabContainer.removeEventListener("SSTabRestored", this, false);
@@ -59,26 +59,29 @@ var tabPreviews = {
     if (aTab.__thumbnail_lastURI &&
         aTab.__thumbnail_lastURI != aTab.linkedBrowser.currentURI.spec) {
       aTab.__thumbnail = null;
       aTab.__thumbnail_lastURI = null;
     }
     return aTab.__thumbnail || this.capture(aTab, !aTab.hasAttribute("busy"));
   },
   capture: function (aTab, aStore) {
-    var win = aTab.linkedBrowser.contentWindow;
     var thumbnail = document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
     thumbnail.mozOpaque = true;
     thumbnail.height = this.height;
     thumbnail.width = this.width;
+
     var ctx = thumbnail.getContext("2d");
-    var widthScale = this.width / win.innerWidth;
-    ctx.scale(widthScale, widthScale);
+    var win = aTab.linkedBrowser.contentWindow;
+    var snippetWidth = win.innerWidth * .6;
+    var scale = this.width / snippetWidth;
+    ctx.scale(scale, scale);
     ctx.drawWindow(win, win.scrollX, win.scrollY,
-                   win.innerWidth, win.innerWidth * this.aspectRatio, "rgb(255,255,255)");
+                   snippetWidth, snippetWidth * this.aspectRatio, "rgb(255,255,255)");
+
     var data = thumbnail.toDataURL("image/jpeg", "quality=60");
     if (aStore) {
       aTab.__thumbnail = data;
       aTab.__thumbnail_lastURI = aTab.linkedBrowser.currentURI.spec;
     }
     return data;
   },
   handleEvent: function (event) {
@@ -106,17 +109,16 @@ var tabPreviews = {
     }
   }
 };
 
 /**
  * Ctrl-Tab panel
  */
 var ctrlTab = {
-  tabs: null,
   visibleCount: 3,
   _uniqid: 0,
   get panel () {
     delete this.panel;
     return this.panel = document.getElementById("ctrlTab-panel");
   },
   get label () {
     delete this.label;
@@ -147,52 +149,54 @@ var ctrlTab = {
     return this.iconSize = Math.max(16, Math.round(tabPreviews.height / 5));
   },
   get closeCharCode () {
     delete this.closeCharCode;
     return this.closeCharCode = document.getElementById("key_close")
                                         .getAttribute("key")
                                         .toLowerCase().charCodeAt(0);
   },
+  get recentlyUsedLimit () {
+    delete this.recentlyUsedLimit;
+    return this.recentlyUsedLimit = gPrefService.getIntPref("browser.ctrlTab.recentlyUsedLimit");
+  },
   get smoothScroll () {
     delete this.smoothScroll;
     return this.smoothScroll = gPrefService.getBoolPref("browser.ctrlTab.smoothScroll");
   },
+  get tabCount () {
+    return gBrowser.mTabs.length;
+  },
   get offscreenStart () {
     return Array.indexOf(this.container.childNodes, this.selected) - 1;
   },
   get offscreenEnd () {
     return this.container.childNodes.length - this.visibleCount - this.offscreenStart;
   },
   get offsetX () {
     return - tabPreviews.width * (this.rtl ? this.offscreenEnd : this.offscreenStart);
   },
   get isOpen () {
     return this.panel.state == "open" || this.panel.state == "showing";
   },
   init: function () {
-    if (this.tabs)
+    if (this._recentlyUsedTabs)
       return;
+    this._recentlyUsedTabs = [gBrowser.selectedTab];
 
     var tabContainer = gBrowser.tabContainer;
-
-    this.tabs = [];
-    Array.forEach(tabContainer.childNodes, function (tab) {
-      this.attachTab(tab, tab == gBrowser.selectedTab);
-    }, this);
-
     tabContainer.addEventListener("TabOpen", this, false);
     tabContainer.addEventListener("TabSelect", this, false);
     tabContainer.addEventListener("TabClose", this, false);
 
     gBrowser.mTabBox.handleCtrlTab = false;
     document.addEventListener("keypress", this, false);
   },
   uninit: function () {
-    this.tabs = null;
+    this._recentlyUsedTabs = null;
 
     var tabContainer = gBrowser.tabContainer;
     tabContainer.removeEventListener("TabOpen", this, false);
     tabContainer.removeEventListener("TabSelect", this, false);
     tabContainer.removeEventListener("TabClose", this, false);
 
     this.panel.removeEventListener("popuphiding", this, false);
     document.removeEventListener("keypress", this, false);
@@ -343,22 +347,22 @@ var ctrlTab = {
       this._scrollTimer = 0;
       this.advanceSelected();
       this.arrangeBoxes();
     }
   },
   advanceSelected: function () {
     // regardless of visibleCount, the new highlighted tab will be
     // the first or third-visible tab, depending on whether Shift is pressed
-    var index = ((this.invertDirection ? 0 : 2) + this.offscreenStart + this.tabs.length)
-                % this.tabs.length;
+    var index = ((this.invertDirection ? 0 : 2) + this.offscreenStart + this.tabCount)
+                % this.tabCount;
     if (index < 2)
-      index += this.tabs.length;
+      index += this.tabCount;
     if (index > this.container.childNodes.length - this.visibleCount + 1)
-      index -= this.tabs.length;
+      index -= this.tabCount;
     this.selected = this.container.childNodes[index];
   },
   arrangeBoxes: function () {
     this.addOffscreenBox(this.invertDirection);
     this.addOffscreenBox(!this.invertDirection);
 
     // having lots of off-screen boxes reduces the scrolling speed, remove some
     for (let i = this.offscreenStart; i > 1; i--)
@@ -367,23 +371,24 @@ var ctrlTab = {
       this.removeBox(this.container.lastChild);
 
     this.container.setAttribute("transform", "translate("+ this.offsetX +", 0)");
 
     for (let i = 0, l = this.container.childNodes.length; i < l; i++)
       this.arrange(i);
   },
   addOffscreenBox: function (aAtStart) {
-    if (this.container.childNodes.length < this.tabs.length + this.visibleCount + 1 &&
+    if (this.container.childNodes.length < this.tabCount + this.visibleCount + 1 &&
         !(aAtStart ? this.offscreenStart : this.offscreenEnd)) {
+      let tabs = this.getTabList();
       let i = aAtStart ?
-              this.tabs.indexOf(this.container.firstChild._tab) - 1:
-              this.tabs.indexOf(this.container.lastChild._tab) + 1;
-      i = (i + this.tabs.length) % this.tabs.length;
-      this.addPreview(this.addBox(aAtStart), this.tabs[i]);
+              tabs.indexOf(this.container.firstChild._tab) - 1:
+              tabs.indexOf(this.container.lastChild._tab) + 1;
+      i = (i + tabs.length) % tabs.length;
+      this.addPreview(this.addBox(aAtStart), tabs[i]);
     }
   },
   arrange: function (aIndex) {
     var box = this.container.childNodes[aIndex];
     var selected = box == this.selected;
     if (selected) {
       box.setAttribute("selected", "true");
       this.setStatusbarValue(box);
@@ -417,62 +422,82 @@ var ctrlTab = {
       } else {
         try {
           value = decodeURI(value);
         } catch (e) {}
       }
     }
     XULBrowserWindow.setOverLink(value, null);
   },
-  attachTab: function (aTab, aSelected) {
-    if (aSelected)
-      this.tabs.unshift(aTab);
+  getTabList: function () {
+    var list = Array.slice(gBrowser.mTabs);
+    for (let i = 0; i < gBrowser.tabContainer.selectedIndex; i++)
+      list.push(list.shift());
+    if (!this._useTabBarOrder && this.recentlyUsedLimit > 0) {
+      let recentlyUsedTabs = this._recentlyUsedTabs.slice(0, this.recentlyUsedLimit);
+      for (let i = recentlyUsedTabs.length - 1; i >= 0; i--) {
+        list.splice(list.indexOf(recentlyUsedTabs[i]), 1);
+        list.unshift(recentlyUsedTabs[i]);
+      }
+    }
+    return list;
+  },
+  attachTab: function (aTab, aPos) {
+    if (aPos == 0)
+      this._recentlyUsedTabs.unshift(aTab);
+    else if (aPos)
+      this._recentlyUsedTabs.splice(aPos, 0, aTab);
     else
-      this.tabs.push(aTab);
+      this._recentlyUsedTabs.push(aTab);
   },
   detachTab: function (aTab) {
-    var i = this.tabs.indexOf(aTab);
+    var i = this._recentlyUsedTabs.indexOf(aTab);
     if (i >= 0)
-      this.tabs.splice(i, 1);
+      this._recentlyUsedTabs.splice(i, 1);
   },
   open: function () {
     this._deferOnTabSelect = [];
+    if (this.invertDirection)
+      this._useTabBarOrder = true;
 
     document.addEventListener("keyup", this, false);
     document.addEventListener("keydown", this, false);
     this.panel.addEventListener("popuphiding", this, false);
     this.panel.hidden = false;
     this.panel.width = tabPreviews.width * this.visibleCount;
     this.panel.openPopupAtScreen(screen.availLeft + (screen.availWidth - this.panel.width) / 2,
                                  screen.availTop + (screen.availHeight - this.svgRoot.getAttribute("height")) / 2,
                                  false);
 
     // display $visibleCount tabs, starting with the first or
     // the second to the last tab, depending on whether Shift is pressed
-    for (let index = this.invertDirection ? this.tabs.length - 2 : 0,
-             i = this.visibleCount; i > 0; i--)
-      this.addPreview(this.addBox(), this.tabs[index++ % this.tabs.length]);
+    {
+      let tabs = this.getTabList();
+      let index = this.invertDirection ? tabs.length - 2 : 0;
+      for (let i = this.visibleCount; i > 0; i--)
+        this.addPreview(this.addBox(), tabs[index++ % tabs.length]);
+    }
 
     // regardless of visibleCount, highlight the second-visible tab
     this.selected = this.container.childNodes[1];
     this.arrangeBoxes();
   },
   onKeyPress: function (event) {
     var isOpen = this.isOpen;
     var propagate = !isOpen;
     switch (event.keyCode) {
       case event.DOM_VK_TAB:
         if (event.ctrlKey && !event.altKey && !event.metaKey) {
           propagate = false;
           this.invertDirection = event.shiftKey;
           if (isOpen)
             this.scroll();
-          else if (this.tabs.length == 2)
-            gBrowser.selectedTab = this.tabs[1];
-          else if (this.tabs.length > 2)
+          else if (this.tabCount == 2)
+            gBrowser.selectedTab = this.getTabList()[1];
+          else if (this.tabCount > 2)
             this.open();
         }
         break;
       case event.DOM_VK_ESCAPE:
         if (isOpen)
           this.panel.hidePopup();
         break;
       default:
@@ -489,49 +514,50 @@ var ctrlTab = {
   onPopupHiding: function () {
     this.stopScroll();
     document.removeEventListener("keyup", this, false);
     document.removeEventListener("keydown", this, false);
     while (this.container.childNodes.length)
       this.removeBox(this.container.lastChild);
     this.selected = null;
     this.invertDirection = false;
+    this._useTabBarOrder = false;
     this._uniqid = 0;
     this.label.value = "";
     this.setStatusbarValue();
     this.container.removeAttribute("transform");
     this.svgRoot.forceRedraw();
 
     this._deferOnTabSelect.forEach(this.onTabSelect, this);
     this._deferOnTabSelect = null;
   },
   onTabSelect: function (aTab) {
     if (aTab.parentNode) {
       this.detachTab(aTab);
-      this.attachTab(aTab, true);
+      this.attachTab(aTab, 0);
     }
   },
   handleEvent: function (event) {
     switch (event.type) {
       case "DOMAttrModified":
         this.tabAttrModified(event.target, event.attrName);
         break;
       case "TabSelect":
         if (this.isOpen)
           // don't change the tab order while the panel is open
           this._deferOnTabSelect.push(event.target);
         else
           this.onTabSelect(event.target);
         break;
       case "TabOpen":
-        this.attachTab(event.target);
+        this.attachTab(event.target, 1);
         break;
       case "TabClose":
         if (this.isOpen) {
-          if (this.tabs.length == 2) {
+          if (this.tabCount == 2) {
             // we have two tabs, one is being closed, so the panel isn't needed anymore
             this.panel.hidePopup();
           } else {
             if (event.target == this.selected._tab)
               this.advanceSelected();
             this.detachTab(event.target);
             Array.slice(this.container.childNodes).forEach(function (box) {
               if (box._tab == event.target) {
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -64,17 +64,16 @@ Cu.import("resource://gre/modules/XPCOMU
 
 const nsIWebNavigation = Components.interfaces.nsIWebNavigation;
 
 const MAX_HISTORY_MENU_ITEMS = 15;
 
 // We use this once, for Clear Private Data
 const GLUE_CID = "@mozilla.org/browser/browserglue;1";
 
-var gURIFixup = null;
 var gCharsetMenu = null;
 var gLastBrowserCharset = null;
 var gPrevCharset = null;
 var gProxyFavIcon = null;
 var gLastValidURLStr = "";
 var gProgressCollapseTimer = null;
 var appCore = null;
 var gSidebarCommand = "";
@@ -981,20 +980,16 @@ function delayedStartup(isLoadingBlank, 
   if (mustLoadSidebar) {
     let sidebar = document.getElementById("sidebar");
     let sidebarBox = document.getElementById("sidebar-box");
     sidebar.setAttribute("src", sidebarBox.getAttribute("src"));
   }
 
   UpdateUrlbarSearchSplitterState();
   
-  try {
-    placesMigrationTasks();
-  } catch(ex) {}
-
   PlacesStarButton.init();
 
   // called when we go into full screen, even if it is
   // initiated by a web page script
   window.addEventListener("fullscreen", onFullScreen, true);
 
   if (isLoadingBlank && gURLBar && isElementVisible(gURLBar))
     focusElement(gURLBar);
@@ -1313,17 +1308,16 @@ AutoHideTabbarPrefListener.prototype =
         window.toolbar.visible) {
       var aVisible = false;
       try {
         aVisible = !gPrefService.getBoolPref(this.domain);
       }
       catch (e) {
       }
       gBrowser.setStripVisibilityTo(aVisible);
-      gPrefService.setBoolPref("browser.tabs.forceHide", false);
     }
   }
 }
 
 function SanitizeListener()
 {
   gPrefService.addObserver(this.promptDomain, this, false);
 
@@ -1636,43 +1630,27 @@ function BrowserOpenFileWindow()
                      nsIFilePicker.filterXML | nsIFilePicker.filterHTML);
 
     if (fp.show() == nsIFilePicker.returnOK)
       openTopWin(fp.fileURL.spec);
   } catch (ex) {
   }
 }
 
-function BrowserCloseTabOrWindow()
-{
+function BrowserCloseTabOrWindow() {
 #ifdef XP_MACOSX
   // If we're not a browser window, just close the window
   if (window.location.href != getBrowserURL()) {
     closeWindow(true);
     return;
   }
 #endif
 
-  if (gBrowser.tabContainer.childNodes.length > 1) {
-    gBrowser.removeCurrentTab(); 
-    return;
-  }
-
-#ifndef XP_MACOSX
-  if (gBrowser.localName == "tabbrowser" && window.toolbar.visible &&
-      !gPrefService.getBoolPref("browser.tabs.autoHide")) {
-    // Replace the remaining tab with a blank one and focus the address bar
-    gBrowser.removeCurrentTab();
-    if (gURLBar)
-      setTimeout(function() { gURLBar.focus(); }, 0);
-    return;
-  }
-#endif
-
-  closeWindow(true);
+  // If the current tab is the last one, this will close the window.
+  gBrowser.removeCurrentTab();
 }
 
 function BrowserTryToCloseWindow()
 {
   if (WindowIsClosing()) {
     if (window.fullScreen) {
       gBrowser.mPanelContainer.removeEventListener("mousemove",
                                                    FullScreen._collapseCallback, false);
@@ -1965,47 +1943,35 @@ function checkForDirectoryListing()
 {
   if ( "HTTPIndex" in content &&
        content.HTTPIndex instanceof Components.interfaces.nsIHTTPIndex ) {
     content.wrappedJSObject.defaultCharacterset =
       getMarkupDocumentViewer().defaultCharacterSet;
   }
 }
 
-function URLBarSetURI(aURI) {
+function URLBarSetURI(aURI, aValid) {
   var value = gBrowser.userTypedValue;
-  var state = "invalid";
+  var valid = false;
 
   if (!value) {
-    if (aURI) {
-      // If the url has "wyciwyg://" as the protocol, strip it off.
-      // Nobody wants to see it on the urlbar for dynamically generated
-      // pages.
-      if (!gURIFixup)
-        gURIFixup = Cc["@mozilla.org/docshell/urifixup;1"]
-                      .getService(Ci.nsIURIFixup);
-      try {
-        aURI = gURIFixup.createExposableURI(aURI);
-      } catch (ex) {}
-    } else {
-      aURI = getWebNavigation().currentURI;
-    }
-
-    if (aURI.spec == "about:blank") {
-      // Replace "about:blank" with an empty string
-      // only if there's no opener (bug 370555).
-      value = content.opener ? aURI.spec : "";
-    } else {
-      value = losslessDecodeURI(aURI);
-      state = "valid";
-    }
+    let uri = aURI || getWebNavigation().currentURI;
+
+    // Replace "about:blank" with an empty string
+    // only if there's no opener (bug 370555).
+    if (uri.spec == "about:blank")
+      value = content.opener ? "about:blank" : "";
+    else
+      value = losslessDecodeURI(uri);
+
+    valid = value && (!aURI || aValid);
   }
 
   gURLBar.value = value;
-  SetPageProxyState(state);
+  SetPageProxyState(valid ? "valid" : "invalid");
 }
 
 function losslessDecodeURI(aURI) {
   var value = aURI.spec;
   // Try to decode as UTF-8 if there's no encoding sequence that we would break.
   if (!/%25(?:3B|2F|3F|3A|40|26|3D|2B|24|2C|23)/i.test(value))
     try {
       value = decodeURI(value)
@@ -2071,17 +2037,17 @@ function canonizeUrl(aTriggeringEvent, a
     return;
 
   var url = gURLBar.value;
 
   // Only add the suffix when the URL bar value isn't already "URL-like".
   // Since this function is called from handleURLBarCommand, which receives
   // both mouse (from the go button) and keyboard events, we also make sure not
   // to do the fixup unless we get a keyboard event, to match user expectations.
-  if (!/^(www|https?)\b|\/\s*$/i.test(url) &&
+  if (!/^\s*(www|https?)\b|\/\s*$/i.test(url) &&
       (aTriggeringEvent instanceof KeyEvent)) {
 #ifdef XP_MACOSX
     var accel = aTriggeringEvent.metaKey;
 #else
     var accel = aTriggeringEvent.ctrlKey;
 #endif
     var shift = aTriggeringEvent.shiftKey;
 
@@ -3755,16 +3721,21 @@ var XULBrowserWindow = {
   get securityButton () {
     delete this.securityButton;
     return this.securityButton = document.getElementById("security-button");
   },
   get isImage () {
     delete this.isImage;
     return this.isImage = document.getElementById("isImage");
   },
+  get _uriFixup () {
+    delete this._uriFixup;
+    return this._uriFixup = Cc["@mozilla.org/docshell/urifixup;1"]
+                              .getService(Ci.nsIURIFixup);
+  },
 
   init: function () {
     this.throbberElement = document.getElementById("navigator-throbber");
 
     // Initialize the security button's state and tooltip text.  Remember to reset
     // _hostChanged, otherwise onSecurityChange will short circuit.
     var securityUI = gBrowser.securityUI;
     this._hostChanged = true;
@@ -3887,19 +3858,20 @@ var XULBrowserWindow = {
         }
       }
 
       // This (thanks to the filter) is a network stop or the last
       // request stop outside of loading the document, stop throbbers
       // and progress bars and such
       if (aRequest) {
         let msg = "";
+        let location;
         // Get the URI either from a channel or a pseudo-object
         if (aRequest instanceof nsIChannel || "URI" in aRequest) {
-          let location = aRequest.URI;
+          location = aRequest.URI;
 
           // For keyword URIs clear the user typed value since they will be changed into real URIs
           if (location.scheme == "keyword" && aWebProgress.DOMWindow == content)
             gBrowser.userTypedValue = null;
 
           if (location.spec != "about:blank") {
             switch (aStatus) {
               case Components.results.NS_BINDING_ABORTED:
@@ -4012,18 +3984,25 @@ var XULBrowserWindow = {
       } else {
         this.reloadCommand.removeAttribute("disabled");
       }
 
       if (!gBrowser.mTabbedMode && aWebProgress.isLoadingDocument)
         gBrowser.setIcon(gBrowser.mCurrentTab, null);
 
       if (gURLBar) {
-        URLBarSetURI(aLocationURI);
-        PlacesStarButton.updateState(); // Update starring UI
+        // Strip off "wyciwyg://" and passwords for the location bar
+        let uri = aLocationURI;
+        try {
+          uri = this._uriFixup.createExposableURI(uri);
+        } catch (e) {}
+        URLBarSetURI(uri, true);
+
+        // Update starring UI
+        PlacesStarButton.updateState();
       }
 
       FullZoom.onLocationChange(aLocationURI);
     }
     UpdateBackForwardCommands(gBrowser.webNavigation);
 
     if (gFindBar.findMode != gFindBar.FIND_NORMAL) {
       // Close the Find toolbar if we're in old-style TAF mode
@@ -4220,32 +4199,36 @@ var XULBrowserWindow = {
 
   startDocumentLoad: function (aRequest) {
     // clear out feed data
     gBrowser.mCurrentBrowser.feeds = null;
 
     // clear out search-engine data
     gBrowser.mCurrentBrowser.engines = null;    
 
-    const nsIChannel = Components.interfaces.nsIChannel;
-    var urlStr = aRequest.QueryInterface(nsIChannel).URI.spec;
-    var observerService = Components.classes["@mozilla.org/observer-service;1"]
-                                    .getService(Components.interfaces.nsIObserverService);
+    var uri = aRequest.QueryInterface(Ci.nsIChannel).URI;
+    var observerService = Cc["@mozilla.org/observer-service;1"]
+                            .getService(Ci.nsIObserverService);
+
+    if (gURLBar &&
+        gURLBar.value == "" &&
+        getWebNavigation().currentURI.spec == "about:blank")
+      URLBarSetURI(uri);
+
     try {
-      observerService.notifyObservers(content, "StartDocumentLoad", urlStr);
+      observerService.notifyObservers(content, "StartDocumentLoad", uri.spec);
     } catch (e) {
     }
   },
 
   endDocumentLoad: function (aRequest, aStatus) {
-    const nsIChannel = Components.interfaces.nsIChannel;
-    var urlStr = aRequest.QueryInterface(nsIChannel).originalURI.spec;
-
-    var observerService = Components.classes["@mozilla.org/observer-service;1"]
-                                    .getService(Components.interfaces.nsIObserverService);
+    var urlStr = aRequest.QueryInterface(Ci.nsIChannel).originalURI.spec;
+
+    var observerService = Cc["@mozilla.org/observer-service;1"]
+                            .getService(Ci.nsIObserverService);
 
     var notification = Components.isSuccessCode(aStatus) ? "EndDocumentLoad" : "FailDocumentLoad";
     try {
       observerService.notifyObservers(content, notification, urlStr);
     } catch (e) {
     }
   }
 }
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -94,20 +94,20 @@
     <menupopup id="backForwardMenu"
                chromedir="&locale.dir;"
                onpopupshowing="return FillHistoryMenu(event.target);"
                oncommand="gotoHistoryIndex(event);"
                onclick="checkForMiddleClick(this, event);"/>
     <tooltip id="aHTMLTooltip" onpopupshowing="return FillInHTMLTooltip(document.tooltipNode);"/>
 
     <!-- for search and content formfill/pw manager -->
-    <panel type="autocomplete" chromedir="&locale.dir;" id="PopupAutoComplete" noautofocus="true" hidden="true" level="top"/>
+    <panel type="autocomplete" chromedir="&locale.dir;" id="PopupAutoComplete" noautofocus="true" hidden="true"/>
 
     <!-- for url bar autocomplete -->
-    <panel type="autocomplete-richlistbox" chromedir="&locale.dir;" id="PopupAutoCompleteRichResult" noautofocus="true" hidden="true" level="top"/>
+    <panel type="autocomplete-richlistbox" chromedir="&locale.dir;" id="PopupAutoCompleteRichResult" noautofocus="true" hidden="true"/>
 
     <panel id="editBookmarkPanel"
            orient="vertical"
            ignorekeys="true"
            hidden="true"
            onpopupshown="StarUI.panelShown(event);"
            aria-labelledby="editBookmarkPanelTitle">
       <hbox flex="1" align="top">
--- a/browser/base/content/pageinfo/pageInfo.js
+++ b/browser/base/content/pageinfo/pageInfo.js
@@ -1101,17 +1101,17 @@ function setItemValue(id, value)
 
 function formatNumber(number)
 {
   return (+number).toLocaleString();  // coerce number to a numeric value before calling toLocaleString()
 }
 
 function formatDate(datestr, unknown)
 {
-  // scriptable date formater, for pretty printing dates
+  // scriptable date formatter, for pretty printing dates
   var dateService = Components.classes["@mozilla.org/intl/scriptabledateformat;1"]
                               .getService(Components.interfaces.nsIScriptableDateFormat);
 
   var date = new Date(datestr);
   if (!date.valueOf())
     return unknown;
 
   return dateService.FormatDateTime("", dateService.dateFormatLong,
--- a/browser/base/content/pageinfo/pageInfo.xul
+++ b/browser/base/content/pageinfo/pageInfo.xul
@@ -196,18 +196,18 @@
           <treechildren flex="1"/>
         </tree>        
       </groupbox>
       <groupbox id="securityBox">
         <caption id="securityBoxCaption" label="&securityHeader;"/>
         <description id="general-security-identity" class="header"/>
         <description id="general-security-privacy"  class="header"/>
         <hbox align="right">
-          <button id="security-view-more" label="&generalSecurityMore;"
-                  accesskey="&generalSecurityMore.accesskey;"
+          <button id="security-view-details" label="&generalSecurityDetails;"
+                  accesskey="&generalSecurityDetails.accesskey;"
                   oncommand="onClickMore();"/>
         </hbox>
       </groupbox>
     </vbox>
 
     <!-- Media information -->
     <vbox id="mediaPanel">
       <tree id="imagetree" onselect="onImageSelect();" contextmenu="picontext"
--- a/browser/base/content/sanitize.js
+++ b/browser/base/content/sanitize.js
@@ -174,35 +174,49 @@ Sanitizer.prototype = {
         // the browser:purge-session-history notification. (like error console)
         return true;
       }
     },
     
     formdata: {
       clear: function ()
       {
-        //Clear undo history of all searchBars
-        var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
-        var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
-        var windows = windowManagerInterface.getEnumerator("navigator:browser");
+        // Clear undo history of all searchBars
+        var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1']
+                                      .getService(Components.interfaces.nsIWindowMediator);
+        var windows = windowManager.getEnumerator("navigator:browser");
         while (windows.hasMoreElements()) {
           var searchBar = windows.getNext().document.getElementById("searchbar");
           if (searchBar) {
             searchBar.value = "";
             searchBar.textbox.editor.transactionManager.clear();
           }
         }
 
         var formHistory = Components.classes["@mozilla.org/satchel/form-history;1"]
                                     .getService(Components.interfaces.nsIFormHistory2);
         formHistory.removeAllEntries();
       },
-      
+
       get canClear()
       {
+        var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1']
+                                      .getService(Components.interfaces.nsIWindowMediator);
+        var windows = windowManager.getEnumerator("navigator:browser");
+        while (windows.hasMoreElements()) {
+          var searchBar = windows.getNext().document.getElementById("searchbar");
+          if (searchBar) {
+            var transactionMgr = searchBar.textbox.editor.transactionManager;
+            if (searchBar.value ||
+                transactionMgr.numberOfUndoItems ||
+                transactionMgr.numberOfRedoItems)
+              return true;
+          }
+        }
+
         var formHistory = Components.classes["@mozilla.org/satchel/form-history;1"]
                                     .getService(Components.interfaces.nsIFormHistory2);
         return formHistory.hasEntries;
       }
     },
     
     downloads: {
       clear: function ()
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -1212,18 +1212,16 @@
             b.setAttribute("flex", "1");
             this.mPanelContainer.appendChild(notificationbox);
 
             b.addEventListener("DOMTitleChanged", this.onTitleChanged, true);
 
             if (this.mStrip.collapsed)
               this.setStripVisibilityTo(true);
 
-            this.mPrefs.setBoolPref("browser.tabs.forceHide", false);
-
             // wire up a progress listener for the new browser object.
             var position = this.mTabContainer.childNodes.length-1;
             var tabListener = this.mTabProgressListener(t, b, blank);
             const filter = Components.classes["@mozilla.org/appshell/component/browser-status-filter;1"]
                                      .createInstance(Components.interfaces.nsIWebProgress);
             filter.addProgressListener(tabListener, Components.interfaces.nsIWebProgress.NOTIFY_ALL);
             b.webProgress.addProgressListener(filter, Components.interfaces.nsIWebProgress.NOTIFY_ALL);
             this.mTabListeners[position] = tabListener;
@@ -1399,50 +1397,45 @@
         <parameter name="aTab"/>
         <parameter name="aFireBeforeUnload"/>
         <body>
           <![CDATA[
             this._browsers = null; // invalidate cache
             if (aTab.localName != "tab")
               aTab = this.mCurrentTab;
 
-            var l = this.mTabContainer.childNodes.length;
-            if (l == 1 && this.mPrefs.getBoolPref("browser.tabs.autoHide")) {
-              // hide the tab bar
-              this.mPrefs.setBoolPref("browser.tabs.forceHide", true);
-              this.setStripVisibilityTo(false);
-              return;
-            }
-
             if (aFireBeforeUnload) {
-              var ds = this.getBrowserForTab(aTab).docShell;
+              let ds = this.getBrowserForTab(aTab).docShell;
               if (ds.contentViewer && !ds.contentViewer.permitUnload())
-                return;
+                return null;
             }
 
-            // see notes in addTab
-            var _delayedUpdate = function(aTabContainer) {
-              aTabContainer.adjustTabstrip();
-              aTabContainer.mTabstrip._updateScrollButtonsDisabledState();
-            }
-            setTimeout(_delayedUpdate, 0, this.mTabContainer);
-
+            var l = this.mTabContainer.childNodes.length;
             if (l == 1) {
-              // add a new blank tab to replace the one we're about to close
-              // (this ensures that the remaining tab is as good as new)
-              this.addTab("about:blank");
+              if (this.mPrefs.getBoolPref("browser.tabs.closeWindowWithLastTab")) {
+                closeWindow(true);
+                return null;
+              }
+              BrowserOpenTab();
               l++;
             }
-            else if (l == 2) {
+            if (l == 2) {
               var autohide = this.mPrefs.getBoolPref("browser.tabs.autoHide");
               var tabStripHide = !window.toolbar.visible;
               if (autohide || tabStripHide)
                 this.setStripVisibilityTo(false);
             }
 
+            // see notes in addTab
+            var _delayedUpdate = function (aTabContainer) {
+              aTabContainer.adjustTabstrip();
+              aTabContainer.mTabstrip._updateScrollButtonsDisabledState();
+            };
+            setTimeout(_delayedUpdate, 0, this.mTabContainer);
+
             // We're committed to closing the tab now.  
             // Dispatch a notification.
             // We dispatch it before any teardown so that event listeners can
             // inspect the tab that's about to close.
             var evt = document.createEvent("Events");
             evt.initEvent("TabClose", true, false);
             aTab.dispatchEvent(evt);
 
@@ -1474,16 +1467,19 @@
           ]]>
         </body>
       </method>
 
       <method name="_endRemoveTab">
         <parameter name="aTab"/>
         <body>
           <![CDATA[
+            if (!aTab)
+              return;
+
             var browser = this.getBrowserForTab(aTab);
             var length = this.mTabs.length;
 
             // Get the index of the tab we're removing before unselecting it
             var currentIndex = this.mTabContainer.selectedIndex;
             var index = aTab._tPos;
 
             // clean up the before/afterselected attributes before removing the
@@ -1663,19 +1659,18 @@
       <method name="addProgressListener">
         <parameter name="aListener"/>
         <parameter name="aMask"/>
         <body>
           <![CDATA[
             if (!this.mAddProgressListenerWasCalled) {
               this.mAddProgressListenerWasCalled = true;
               var autoHide = this.mPrefs.getBoolPref("browser.tabs.autoHide");
-              var forceHide = this.mPrefs.getBoolPref("browser.tabs.forceHide");
               var tabStripHide = !window.toolbar.visible;
-              if (!autoHide && !forceHide && !tabStripHide)
+              if (!autoHide && !tabStripHide)
                 this.setStripVisibilityTo(true);
             }
 
             if (!this.mTabbedMode && this.mProgressListeners.length == 1) {
               // If we are adding a 2nd progress listener, we need to enter tabbed mode
               // because the browser status filter can only handle one progress listener.
               // In tabbed mode, mTabProgressListener is used which will iterate over all listeners.
               this.enterTabbedMode();
@@ -1922,30 +1917,26 @@
       </method>
 
       <method name="onDrop">
         <parameter name="aEvent"/>
         <parameter name="aXferData"/>
         <parameter name="aDragSession"/>
         <body>
           <![CDATA[
-#ifndef XP_MACOSX
-            var accelKeyPressed = aEvent.ctrlKey;
-#else
-            var accelKeyPressed = aEvent.metaKey;
-#endif
+            var isCopy = aEvent.dataTransfer.dropEffect == "copy";
             var draggedTab;
             if (aDragSession.sourceNode && aDragSession.sourceNode.localName == "tab" &&
                 (aDragSession.sourceNode.parentNode == this.mTabContainer ||
                  aDragSession.sourceNode.ownerDocument.defaultView instanceof ChromeWindow &&
                  aDragSession.sourceNode.ownerDocument.documentElement.getAttribute("windowtype") == "navigator:browser"))
               draggedTab = aDragSession.sourceNode;
-            if (draggedTab && (accelKeyPressed || draggedTab.parentNode == this.mTabContainer)) {
+            if (draggedTab && (isCopy || draggedTab.parentNode == this.mTabContainer)) {
               var newIndex = this.getNewIndex(aEvent);
-              if (accelKeyPressed) {
+              if (isCopy) {
                 // copy the dropped tab (wherever it's from)
                 var newTab = this.duplicateTab(draggedTab);
                 this.moveTabTo(newTab, newIndex);
                 if (draggedTab.parentNode != this.mTabContainer || aEvent.shiftKey)
                   this.selectedTab = newTab;
               }
               else {
                 // move the dropped tab
@@ -1992,17 +1983,17 @@
               try {
                 bgLoad = this.mPrefs.getBoolPref("browser.tabs.loadInBackground");
               }
               catch (e) { }
 
               if (aEvent.shiftKey)
                 bgLoad = !bgLoad;
 
-              if (document.getBindingParent(aEvent.originalTarget).localName != "tab" || accelKeyPressed) {
+              if (document.getBindingParent(aEvent.originalTarget).localName != "tab" || isCopy) {
                 // We're adding a new tab.
                 newIndex = this.getNewIndex(aEvent);
                 newTab = this.loadOneTab(getShortcutOrURI(url), null, null, null, bgLoad, false);
                 this.moveTabTo(newTab, newIndex);
               }
               else {
                 // Load in an existing tab.
                 var tab = aEvent.target;
--- a/browser/base/content/test/browser_ctrlTab.js
+++ b/browser/base/content/test/browser_ctrlTab.js
@@ -44,17 +44,17 @@ function test() {
     pressCtrlTab(true);
     pressCtrlTab(true);
     releaseCtrl();
     ok(gBrowser.selectedTab == selectedTab,
        "Ctrl+Tab*2 -> Ctrl+W -> Ctrl+Shift+Tab*2 keeps the selected tab");
   }
   assertTabs(2);
 
-  ctrlTabTest([1]      , 1, 0);
+  //ctrlTabTest([1], 1, 0);
 
   gBrowser.removeTab(gBrowser.tabContainer.lastChild);
 
   assertTabs(1);
 
   { // test for bug 445768
     let focusedWindow = document.commandDispatcher.focusedWindow;
     let eventConsumed = true;
--- a/browser/build.mk
+++ b/browser/build.mk
@@ -57,16 +57,24 @@ installer:
 package:
 	@$(MAKE) -C browser/installer
 
 install::
 	@$(MAKE) -C browser/installer install
 
 ifdef ENABLE_TESTS
 # Implemented in testing/testsuite-targets.mk
+
+# Browser tests live in a slightly different location, so we correct the path
+ifdef TEST_PATH
+BROWSER_TEST_PATH = --test-path=../browser/$(TEST_PATH)
+else
+BROWSER_TEST_PATH =
+endif
+
 mochitest-browser-chrome:
-	$(RUN_MOCHITEST) --browser-chrome
+	$(RUN_MOCHITEST) --browser-chrome $(BROWSER_TEST_PATH)
 	$(CHECK_TEST_ERROR)
 
 mochitest:: mochitest-browser-chrome
 
 .PHONY: mochitest-browser-chrome
 endif
--- a/browser/components/feeds/src/WebContentConverter.js
+++ b/browser/components/feeds/src/WebContentConverter.js
@@ -161,17 +161,20 @@ ServiceInfo.prototype = {
   QueryInterface: function SI_QueryInterface(iid) {
     if (iid.equals(Ci.nsIWebContentHandlerInfo) ||
         iid.equals(Ci.nsISupports))
       return this;
     throw Cr.NS_ERROR_NO_INTERFACE;
   }
 };
 
-function WebContentConverterRegistrar() {}
+function WebContentConverterRegistrar() {
+  this._contentTypes = { };
+  this._autoHandleContentTypes = { };
+}
 
 WebContentConverterRegistrar.prototype = {
   get stringBundle() {
     var sb = Cc["@mozilla.org/intl/stringbundle;1"].
               getService(Ci.nsIStringBundleService).
               createBundle(STRING_BUNDLE_URI);
     delete WebContentConverterRegistrar.prototype.stringBundle;
     return WebContentConverterRegistrar.prototype.stringBundle = sb;
@@ -180,24 +183,16 @@ WebContentConverterRegistrar.prototype =
   _getFormattedString: function WCCR__getFormattedString(key, params) {
     return this.stringBundle.formatStringFromName(key, params, params.length);
   },
   
   _getString: function WCCR_getString(key) {
     return this.stringBundle.GetStringFromName(key);
   },
 
-  _contentTypes: { },
-
-  /**
-   * Track auto handlers for various content types using a content-type to 
-   * handler map.
-   */
-  _autoHandleContentTypes: { },
-
   /**
    * See nsIWebContentConverterService
    */
   getAutoHandler: 
   function WCCR_getAutoHandler(contentType) {
     contentType = this._resolveContentType(contentType);
     if (contentType in this._autoHandleContentTypes)
       return this._autoHandleContentTypes[contentType];
--- a/browser/components/nsBrowserGlue.js
+++ b/browser/components/nsBrowserGlue.js
@@ -172,20 +172,19 @@ BrowserGlue.prototype = {
     distro.applyPrefDefaults();
   },
 
   // profile startup handler (contains profile initialization routines)
   _onProfileStartup: function() 
   {
     // Check to see if the EULA must be shown on startup
 
-    // Global override for tinderbox machines
     var prefBranch = Cc["@mozilla.org/preferences-service;1"].
                      getService(Ci.nsIPrefBranch);
-    var mustDisplayEULA = true;
+    var mustDisplayEULA = false;
     try {
       mustDisplayEULA = !prefBranch.getBoolPref("browser.EULA.override");
     } catch (e) {
       // Pref might not exist
     }
 
     // Make sure it hasn't already been accepted
     if (mustDisplayEULA) {
--- a/browser/components/places/content/controller.js
+++ b/browser/components/places/content/controller.js
@@ -17,17 +17,17 @@
  * The Initial Developer of the Original Code is Google Inc.
  * Portions created by the Initial Developer are Copyright (C) 2005
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
  *   Ben Goodger <beng@google.com>
  *   Myk Melez <myk@mozilla.org>
  *   Asaf Romano <mano@mozilla.com>
- *   Marco Bonardo <mak77@supereva.it>
+ *   Marco Bonardo <mak77@bonardo.net>
  *
  * Alternatively, the contents of this file may be used under the terms of
  * either the GNU General Public License Version 2 or later (the "GPL"), or
  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  * in which case the provisions of the GPL or the LGPL are applicable instead
  * of those above. If you wish to allow use of your version of this file only
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
@@ -293,17 +293,17 @@ PlacesController.prototype = {
     var root = this._view.getResultNode();
 
     for (var i = 0; i < nodes.length; ++i) {
       // Disallow removing the view's root node
       if (nodes[i] == root)
         return false;
 
       if (PlacesUtils.nodeIsFolder(nodes[i]) &&
-          !PlacesControllerDragHelper.canMoveContainerNode(nodes[i]))
+          !PlacesControllerDragHelper.canMoveNode(nodes[i]))
         return false;
 
       // We don't call nodeIsReadOnly here, because nodeIsReadOnly means that
       // a node has children that cannot be edited, reordered or removed. Here,
       // we don't care if a node's children can't be reordered or edited, just
       // that they're removable. All history results have removable children
       // (based on the principle that any URL in the history table should be
       // removable), but some special bookmark folders may have non-removable
@@ -346,17 +346,17 @@ PlacesController.prototype = {
    * @returns true if: - clipboard data is of a TYPE_X_MOZ_PLACE_* flavor,
                        - clipboard data is of type TEXT_UNICODE and
                          is a valid URI.
    */
   _isClipboardDataPasteable: function PC__isClipboardDataPasteable() {
     // if the clipboard contains TYPE_X_MOZ_PLACE_* data, it is definitely
     // pasteable, with no need to unwrap all the nodes.
 
-    var flavors = PlacesUIUtils.placesFlavors;
+    var flavors = PlacesControllerDragHelper.placesFlavors;
     var clipboard = PlacesUIUtils.clipboard;
     var hasPlacesData =
       clipboard.hasDataMatchingFlavors(flavors, flavors.length,
                                        Ci.nsIClipboard.kGlobalClipboard);
     if (hasPlacesData)
       return this._view.insertionPoint != null;
 
     // if the clipboard doesn't have TYPE_X_MOZ_PLACE_* data, we also allow
@@ -858,21 +858,23 @@ PlacesController.prototype = {
 
   /**
    * Creates a set of transactions for the removal of a range of items. 
    * A range is an array of adjacent nodes in a view.
    * @param   [in] range
    *          An array of nodes to remove. Should all be adjacent. 
    * @param   [out] transactions
    *          An array of transactions.
+   * @param   [optional] removedFolders
+   *          An array of folder nodes that have already been removed.
    */
-  _removeRange: function PC__removeRange(range, transactions) {
+  _removeRange: function PC__removeRange(range, transactions, removedFolders) {
     NS_ASSERT(transactions instanceof Array, "Must pass a transactions array");
-
-    var removedFolders = [];
+    if (!removedFolders)
+      removedFolders = [];
 
     for (var i = 0; i < range.length; ++i) {
       var node = range[i];
       if (this._shouldSkipNode(node, removedFolders))
         continue;
 
       if (PlacesUtils.nodeIsFolder(node))
         removedFolders.push(node);
@@ -901,20 +903,21 @@ PlacesController.prototype = {
   /**
    * Removes the set of selected ranges from bookmarks.
    * @param   txnName
    *          See |remove|.
    */
   _removeRowsFromBookmarks: function PC__removeRowsFromBookmarks(txnName) {
     var ranges = this._view.getRemovableSelectionRanges();
     var transactions = [];
-    // Delete the selected rows. Do this by walking the selection backward, so
-    // that when undo is performed they are re-inserted in the correct order.
-    for (var i = ranges.length - 1; i >= 0 ; --i)
-      this._removeRange(ranges[i], transactions);
+    var removedFolders = [];
+
+    for (var i = 0; i < ranges.length; i++)
+      this._removeRange(ranges[i], transactions, removedFolders);
+
     if (transactions.length > 0) {
       var txn = PlacesUIUtils.ptm.aggregateTransactions(txnName, transactions);
       PlacesUIUtils.ptm.doTransaction(txn);
     }
   },
 
   /**
    * Removes the set of selected ranges from history.
@@ -1007,72 +1010,60 @@ PlacesController.prototype = {
       else
         NS_ASSERT(false, "implement support for QUERY_TYPE_UNIFIED");
     }
     else
       NS_ASSERT(false, "unexpected root");
   },
 
   /**
-   * Get a TransferDataSet containing the content of the selection that can be
-   * dropped elsewhere. 
-   * @param   dragAction
-   *          The action to happen when dragging, i.e. copy
-   * @returns A TransferDataSet object that can be dragged and dropped 
-   *          elsewhere.
+   * Fills a DataTransfer object with the content of the selection that can be
+   * dropped elsewhere.
+   * @param   aEvent
+   *          The dragstart event.
    */
-  getTransferData: function PC_getTransferData(dragAction) {
-    var copy = dragAction == Ci.nsIDragService.DRAGDROP_ACTION_COPY;
+  setDataTransfer: function PC_setDataTransfer(aEvent) {
+    var dt = aEvent.dataTransfer;
+    var doCopy = dt.effectAllowed == "copyLink" || dt.effectAllowed == "copy";
+
     var result = this._view.getResult();
     var oldViewer = result.viewer;
     try {
       result.viewer = null;
       var nodes = this._view.getDragableSelection();
-      if (dragAction == Ci.nsIDragService.DRAGDROP_ACTION_MOVE) {
-        nodes = nodes.filter(function(node) {
-          var parent = node.parent;
-          return parent && !PlacesUtils.nodeIsReadOnly(parent);
-        });
-      }
 
-      var dataSet = new TransferDataSet();
       for (var i = 0; i < nodes.length; ++i) {
         var node = nodes[i];
 
-        var data = new TransferData();
-        function addData(type, overrideURI) {
-          data.addDataForFlavour(type, PlacesUIUtils._wrapString(
-                                 PlacesUtils.wrapNode(node, type, overrideURI, copy)));
+        function addData(type, index, overrideURI) {
+          var wrapNode = PlacesUtils.wrapNode(node, type, overrideURI, doCopy);
+          dt.mozSetDataAt(type, wrapNode, index);
         }
 
-        function addURIData(overrideURI) {
-          addData(PlacesUtils.TYPE_X_MOZ_URL, overrideURI);
-          addData(PlacesUtils.TYPE_UNICODE, overrideURI);
-          addData(PlacesUtils.TYPE_HTML, overrideURI);
+        function addURIData(index, overrideURI) {
+          addData(PlacesUtils.TYPE_X_MOZ_URL, index, overrideURI);
+          addData(PlacesUtils.TYPE_UNICODE, index, overrideURI);
+          addData(PlacesUtils.TYPE_HTML, index, overrideURI);
         }
 
         // This order is _important_! It controls how this and other 
         // applications select data to be inserted based on type.
-        addData(PlacesUtils.TYPE_X_MOZ_PLACE);
-      
-        var uri;
-      
-        // Allow dropping the feed uri of live-bookmark folders
+        addData(PlacesUtils.TYPE_X_MOZ_PLACE, i);
+
+        // Drop the feed uri for livemark containers
         if (PlacesUtils.nodeIsLivemarkContainer(node))
-          uri = PlacesUtils.livemarks.getFeedURI(node.itemId).spec;
-      
-        addURIData(uri);
-        dataSet.push(data);
+          addURIData(i, PlacesUtils.livemarks.getFeedURI(node.itemId).spec);
+        else if (node.uri)
+          addURIData(i);
       }
     }
     finally {
       if (oldViewer)
         result.viewer = oldViewer;
     }
-    return dataSet;
   },
 
   /**
    * Copy Bookmarks and Folders to the clipboard
    */
   copy: function PC_copy() {
     var result = this._view.getResult();
     var oldViewer = result.viewer;
@@ -1103,17 +1094,17 @@ PlacesController.prototype = {
           mozURLString += (PlacesUtils.wrapNode(node, PlacesUtils.TYPE_X_MOZ_URL,
                                                  uri) + suffix);
           unicodeString += (PlacesUtils.wrapNode(node, PlacesUtils.TYPE_UNICODE,
                                                  uri) + suffix);
           htmlString += (PlacesUtils.wrapNode(node, PlacesUtils.TYPE_HTML,
                                                  uri) + suffix);
 
           var placeSuffix = i < (nodes.length - 1) ? "," : "";
-          var resolveShortcuts = !PlacesControllerDragHelper.canMoveContainerNode(node);
+          var resolveShortcuts = !PlacesControllerDragHelper.canMoveNode(node);
           return PlacesUtils.wrapNode(node, type, overrideURI, resolveShortcuts) + placeSuffix;
         }
 
         // all items wrapped as TYPE_X_MOZ_PLACE
         placeString += generateChunk(PlacesUtils.TYPE_X_MOZ_PLACE);
       }
 
       function addData(type, data) {
@@ -1240,16 +1231,28 @@ PlacesController.prototype = {
 
 /**
  * Handles drag and drop operations for views. Note that this is view agnostic!
  * You should not use PlacesController._view within these methods, since
  * the view that the item(s) have been dropped on was not necessarily active. 
  * Drop functions are passed the view that is being dropped on. 
  */
 var PlacesControllerDragHelper = {
+  /**
+   * DOM Element currently being dragged over
+   */
+  currentDropTarget: null,
+
+  /**
+   * Current nsIDOMDataTransfer
+   * We need to cache this because we don't have access to the event in the
+   * treeView's canDrop or drop methods, and session.dataTransfer would not be
+   * filled for drag and drop from external sources (eg. the OS).
+   */
+  currentDataTransfer: null,
 
   /**
    * Determines if the mouse is currently being dragged over a child node of
    * this menu. This is necessary so that the menu doesn't close while the
    * mouse is dragging over one of its submenus
    * @param   node
    *          The container node
    * @returns true if the user is dragging over a node within the hierarchy of
@@ -1261,112 +1264,110 @@ var PlacesControllerDragHelper = {
       if (currentNode == node)
         return true;
       currentNode = currentNode.parentNode;
     }
     return false;
   },
 
   /**
-   * DOM Element currently being dragged over
-   */
-  currentDropTarget: null,
-
-  /**
    * @returns The current active drag session. Returns null if there is none.
    */
   getSession: function PCDH__getSession() {
     var dragService = Cc["@mozilla.org/widget/dragservice;1"].
                       getService(Ci.nsIDragService);
     return dragService.getCurrentSession();
   },
 
   /**
+   * Extract the first accepted flavor from a flavors array.
+   * @param aFlavors
+   *        The flavors array.
+   */
+  getFirstValidFlavor: function PCDH_getFirstValidFlavor(aFlavors) {
+    for (var i = 0; i < aFlavors.length; i++) {
+      if (this.GENERIC_VIEW_DROP_TYPES.indexOf(aFlavors[i]) != -1)
+        return aFlavors[i];
+    }
+    return null;
+  },
+
+  /**
    * Determines whether or not the data currently being dragged can be dropped
    * on a places view.
    * @param ip
    *        The insertion point where the items should be dropped
    */
   canDrop: function PCDH_canDrop(ip) {
-    var session = this.getSession();
-    if (!session)
-      return false;
-
-    var types = PlacesUIUtils.GENERIC_VIEW_DROP_TYPES;
-    var foundType = false;
-    for (var i = 0; i < types.length && !foundType; ++i) {
-      if (session.isDataFlavorSupported(types[i]))
-        foundType = true;
-    }
-
-    if (!foundType)
-      return false;
+    var dt = this.currentDataTransfer;
+    var dropCount = dt.mozItemCount;
 
     // Check every dragged item
-    var xferable = this._initTransferable(session);
-    var dropCount = session.numDropItems;
-    for (i = 0; i < dropCount; i++) {
-      // Get the information of the dragged item
-      session.getData(xferable, i);
-      var data = { }, flavor = { };
-      xferable.getAnyTransferData(flavor, data, { });
-      data.value.QueryInterface(Ci.nsISupportsString);
-      var dragged = PlacesUtils.unwrapNodes(data.value.data, flavor.value)[0];
+    for (var i = 0; i < dropCount; i++) {
+      var flavor = this.getFirstValidFlavor(dt.mozTypesAt(i));
+      if (!flavor)
+        return false;
+
+      var data = dt.mozGetDataAt(flavor, i);
+
+      try {
+        var dragged = PlacesUtils.unwrapNodes(data, flavor)[0];
+      } catch (e) {
+        return false;
+      }
 
       // Only bookmarks and urls can be dropped into tag containers
-      if (ip.isTag && dragged.type != PlacesUtils.TYPE_X_MOZ_URL &&
-                      (dragged.type != PlacesUtils.TYPE_X_MOZ_PLACE ||
-                       /^place:/.test(dragged.uri)))
+      if (ip.isTag && ip.orientation == Ci.nsITreeView.DROP_ON &&
+          dragged.type != PlacesUtils.TYPE_X_MOZ_URL &&
+          (dragged.type != PlacesUtils.TYPE_X_MOZ_PLACE ||
+           /^place:/.test(dragged.uri)))
         return false;
 
       // The following loop disallows the dropping of a folder on itself or
       // on any of its descendants.
       if (dragged.type == PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER ||
           /^place:/.test(dragged.uri)) {
         var parentId = ip.itemId;
         while (parentId != PlacesUtils.placesRootId) {
           if (dragged.concreteId == parentId || dragged.id == parentId)
             return false;
           parentId = PlacesUtils.bookmarks.getFolderIdForItem(parentId);
         }
       }
     }
-
     return true;
   },
 
   /**
-   * Determines if a container node can be moved.
+   * Determines if a node can be moved.
    * 
    * @param   aNode
-   *          A bookmark folder node.
-   * @param   [optional] aInsertionPoint
-   *          The insertion point of the drop target.
-   * @returns True if the container can be moved.
+   *          A nsINavHistoryResultNode node.
+   * @returns True if the node can be moved, false otherwise.
    */
-  canMoveContainerNode:
-  function PCDH_canMoveContainerNode(aNode, aInsertionPoint) {
+  canMoveNode:
+  function PCDH_canMoveNode(aNode) {
     // can't move query root
     if (!aNode.parent)
       return false;
 
-    var targetId = aInsertionPoint ? aInsertionPoint.itemId : -1;
     var parentId = PlacesUtils.getConcreteItemId(aNode.parent);
     var concreteId = PlacesUtils.getConcreteItemId(aNode);
 
-    // can't move tag containers 
-    if (PlacesUtils.nodeIsTagQuery(aNode))
+    // can't move children of tag containers
+    if (PlacesUtils.nodeIsTagQuery(aNode.parent))
       return false;
 
-    // check is child of a read-only container 
+    // can't move children of read-only containers
     if (PlacesUtils.nodeIsReadOnly(aNode.parent))
       return false;
 
     // check for special folders, etc
-    if (!this.canMoveContainer(aNode.itemId, parentId))
+    if (PlacesUtils.nodeIsContainer(aNode) &&
+        !this.canMoveContainer(aNode.itemId, parentId))
       return false;
 
     return true;
   },
 
   /**
    * Determines if a container node can be moved.
    * 
@@ -1387,99 +1388,105 @@ var PlacesControllerDragHelper = {
                    PlacesUtils.toolbarFolderId];
     if (ROOTS.indexOf(aId) != -1)
       return false;
 
     // Get parent id if necessary
     if (aParentId == null || aParentId == -1)
       aParentId = PlacesUtils.bookmarks.getFolderIdForItem(aId);
 
-    if(PlacesUtils.bookmarks.getFolderReadonly(aParentId))
+    if (PlacesUtils.bookmarks.getFolderReadonly(aParentId))
       return false;
 
     return true;
   },
 
-  /** 
-   * Creates a Transferable object that can be filled with data of types
-   * supported by a view. 
-   * @param   session
-   *          The active drag session
-   * @returns An object implementing nsITransferable that can receive data
-   *          dropped onto a view. 
-   */
-  _initTransferable: function PCDH__initTransferable(session) {
-    var xferable = Cc["@mozilla.org/widget/transferable;1"].
-                   createInstance(Ci.nsITransferable);
-    var types = PlacesUIUtils.GENERIC_VIEW_DROP_TYPES;
-    for (var i = 0; i < types.length; ++i) {
-      if (session.isDataFlavorSupported(types[i]))
-        xferable.addDataFlavor(types[i]);
-    }
-    return xferable;
-  },
-
   /**
    * Handles the drop of one or more items onto a view.
    * @param   insertionPoint
    *          The insertion point where the items should be dropped
    */
   onDrop: function PCDH_onDrop(insertionPoint) {
-    var session = this.getSession();
-    // XXX dragAction is not valid, so we also set copy below by checking
-    // whether the dropped item is moveable, before creating the transaction
-    var copy = session.dragAction & Ci.nsIDragService.DRAGDROP_ACTION_COPY;
-    var transactions = [];
-    var xferable = this._initTransferable(session);
-    var dropCount = session.numDropItems;
-
-    var movedCount = 0;
+    var dt = this.currentDataTransfer;
+    var doCopy = dt.dropEffect == "copy";
 
+    var transactions = [];
+    var dropCount = dt.mozItemCount;
+    var movedCount = 0;
     for (var i = 0; i < dropCount; ++i) {
-      session.getData(xferable, i);
+      var flavor = this.getFirstValidFlavor(dt.mozTypesAt(i));
+      if (!flavor)
+        return false;
 
-      var data = { }, flavor = { };
-      xferable.getAnyTransferData(flavor, data, { });
-      data.value.QueryInterface(Ci.nsISupportsString);
-
-      // There's only ever one in the D&D case. 
-      var unwrapped = PlacesUtils.unwrapNodes(data.value.data, 
-                                              flavor.value)[0];
+      var data = dt.mozGetDataAt(flavor, i);
+      // There's only ever one in the D&D case.
+      var unwrapped = PlacesUtils.unwrapNodes(data, flavor)[0];
 
       var index = insertionPoint.index;
 
       // Adjust insertion index to prevent reversal of dragged items. When you
       // drag multiple elts upward: need to increment index or each successive
       // elt will be inserted at the same index, each above the previous.
-      if (index != -1 && index < unwrapped.index) {
-        index = index + movedCount;
-        movedCount++;
-      }
+      var dragginUp = insertionPoint.itemId == unwrapped.parent &&
+                      index < PlacesUtils.bookmarks.getItemIndex(unwrapped.id);
+      if (index != -1 && dragginUp)
+        index+= movedCount++;
 
       // if dragging over a tag container we should tag the item
-      if (insertionPoint.isTag) {
+      if (insertionPoint.isTag &&
+          insertionPoint.orientation == Ci.nsITreeView.DROP_ON) {
         var uri = PlacesUtils._uri(unwrapped.uri);
         var tagItemId = insertionPoint.itemId;
         transactions.push(PlacesUIUtils.ptm.tagURI(uri,[tagItemId]));
       }
       else {
-        if (unwrapped.id && !this.canMoveContainer(unwrapped.id, null))
-          copy = true;
-        else if (unwrapped.concreteId &&
-                 !this.canMoveContainer(unwrapped.concreteId, null))
-          copy = true;
-
         transactions.push(PlacesUIUtils.makeTransaction(unwrapped,
-                          flavor.value, insertionPoint.itemId,
-                          index, copy));
+                          flavor, insertionPoint.itemId,
+                          index, doCopy));
       }
     }
 
     var txn = PlacesUIUtils.ptm.aggregateTransactions("DropItems", transactions);
     PlacesUIUtils.ptm.doTransaction(txn);
+  },
+
+  /**
+   * Checks if we can insert into a container.
+   * @param   aContainer
+   *          The container were we are want to drop
+   */
+  disallowInsertion: function(aContainer) {
+    NS_ASSERT(aContainer, "empty container");
+    // allow dropping into Tag containers
+    if (PlacesUtils.nodeIsTagQuery(aContainer))
+      return false;
+    // Disallow insertion of items under readonly folders
+    return (!PlacesUtils.nodeIsFolder(aContainer) ||
+             PlacesUtils.nodeIsReadOnly(aContainer));
+  },
+
+  placesFlavors: [PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER,
+                  PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR,
+                  PlacesUtils.TYPE_X_MOZ_PLACE],
+
+  GENERIC_VIEW_DROP_TYPES: [PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER,
+                            PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR,
+                            PlacesUtils.TYPE_X_MOZ_PLACE,
+                            PlacesUtils.TYPE_X_MOZ_URL,
+                            PlacesUtils.TYPE_UNICODE],
+
+  /**
+   * Returns our flavourSet
+   */
+  get flavourSet() {
+    delete this.flavourSet;
+    var flavourSet = new FlavourSet();
+    var acceptedDropFlavours = this.GENERIC_VIEW_DROP_TYPES;
+    acceptedDropFlavours.forEach(flavourSet.appendFlavour, flavourSet);
+    return this.flavourSet = flavourSet;
   }
 };
 
 function goUpdatePlacesCommands() {
   var placesController;
   try {
     // Or any other command...
     placesController = top.document.commandDispatcher
--- a/browser/components/places/content/menu.xml
+++ b/browser/components/places/content/menu.xml
@@ -19,17 +19,17 @@
 # Portions created by the Initial Developer are Copyright (C) 2005-2006
 # the Initial Developer. All Rights Reserved.
 #
 # Contributor(s):
 #   Annie Sullivan <annie.sullivan@gmail.com>
 #   Ben Goodger <beng@google.com>
 #   Asaf Romano <mano@mozilla.com>
 #   Simon Bünzli <zeniko@gmail.com>
-#   Marco Bonardo <mak77@supereva.it>
+#   Marco Bonardo <mak77@bonardo.net>
 #
 # Alternatively, the contents of this file may be used under the terms of
 # either the GNU General Public License Version 2 or later (the "GPL"), or
 # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 # in which case the provisions of the GPL or the LGPL are applicable instead
 # of those above. If you wish to allow use of your version of this file only
 # under the terms of either the GPL or the LGPL, and not to allow others to
 # use your version of this file under the terms of the MPL, indicate your
@@ -83,18 +83,21 @@
       <method name="onDragOver">
         <parameter name="aEvent"/>
         <parameter name="aFlavour"/>
         <parameter name="aDragSession"/>
         <body><![CDATA[
           PlacesControllerDragHelper.currentDropTarget = aEvent.target;
           // check if we have a valid dropPoint
           var dropPoint = this._getDropPoint(aEvent);
-          if (!dropPoint)
+          if (!dropPoint || !dropPoint.ip ||
+              !PlacesControllerDragHelper.canDrop(dropPoint.ip)) {
+            aEvent.dataTransfer.effectAllowed = "none";
             return;
+          }
 
           // add a dragover attribute to this popup
           this.setAttribute("dragover", "true");
 
           if (dropPoint.folderNode) {
             // We are dragging over a folder
             // _overFolder should take the care of opening it on a timer
             if (this._overFolder.node &&
@@ -104,133 +107,139 @@
             }
             if (!this._overFolder.node) {
               this._overFolder.node = dropPoint.folderNode;
               // create the timer to open this folder
               this._overFolder.openTimer = this._overFolder
                                                .setTimer(this._overFolder.hoverTime);
             }
             // since we are dropping into a folder set the corresponding style
-            dropPoint.folderNode.setAttribute("dragover-into", "true");
+            dropPoint.folderNode.setAttribute("_moz-menuactive", true);
           }
           else {
             // We are not dragging over a folder
             // Clear out old _overFolder information
             this._overFolder.clear();
           }
 
+          // Autoscroll the popup strip if we drag over the scroll buttons
+          var anonid = aEvent.originalTarget.getAttribute('anonid');
+          var scrollDir = anonid == "scrollbutton-up" ? -1 :
+                          anonid == "scrollbutton-down" ? 1 : 0;
+          if (scrollDir != 0) {
+              this._scrollBox.scrollByIndex(scrollDir);
+          }
+
           // Check if we should hide the drop indicator for this target
           if (!aDragSession.canDrop ||
               !dropPoint || dropPoint.folderNode ||
               this._hideDropIndicator(aEvent, dropPoint)) {
             this._indicatorBar.hidden = true;
             return;
           }
 
-          var scrollBoxObject = this._scrollBox.scrollBoxObject;
-          // Autoscroll the popup strip if we drag over the scroll buttons
-          var anonid = aEvent.originalTarget.getAttribute("anonid");
-          var scrollDir = anonid == "scrollbutton-up" ? -1 :
-                          anonid == "scrollbutton-down" ? 1 : 0;
-          if (scrollDir != 0)
-            this._scrollBox.scrollByIndex(scrollDir);
-
           // We should display the drop indicator relative to the arrowscrollbox
+          var sbo = this._scrollBox.scrollBoxObject;
           var newMarginTop = 0;
           if (scrollDir == 0) {
             var node = this.firstChild;
             while (node && aEvent.screenY > node.boxObject.screenY +
                                             node.boxObject.height / 2)
               node = node.nextSibling;
-            newMarginTop = node ? node.boxObject.screenY - scrollBoxObject.screenY :
-                                  scrollBoxObject.height;
+            newMarginTop = node ? node.boxObject.screenY - sbo.screenY :
+                                  sbo.height;
           }
           else if (scrollDir == 1)
-            newMarginTop = scrollBoxObject.height;
+            newMarginTop = sbo.height;
 
           // set the new marginTop based on arrowscrollbox
-          newMarginTop += scrollBoxObject.y - this._scrollBox.boxObject.y;
+          newMarginTop += sbo.y - this._scrollBox.boxObject.y;
           this._indicatorBar.firstChild.style.marginTop = newMarginTop + "px";
           this._indicatorBar.hidden = false;
         ]]></body>
       </method>
 
       <method name="onDragExit">
         <parameter name="aEvent"/>
         <parameter name="aDragSession"/>
         <body><![CDATA[
           PlacesControllerDragHelper.currentDropTarget = null;
+          PlacesControllerDragHelper.currentDataTransfer = null;
           this.removeAttribute("dragover");
-          // remove dragover-into style from previous target
-          aEvent.target.removeAttribute("dragover-into");
 
           // if we have not moved to a valid new target clear the drop indicator
           // this happens when moving out of the popup
           var target = aEvent.relatedTarget;
           if (!target)
             this._indicatorBar.hidden = true;
 
           // Close any folder being hovered over
           if (this._overFolder.node) {
             this._overFolder.closeTimer = this._overFolder
                                               .setTimer(this._overFolder.hoverTime);
           }
 
           // The autoopened attribute is set when this folder was automatically
           // opened after the user dragged over it.  If this attribute is set,
           // auto-close the folder on drag exit.
-          if (this.hasAttribute("autoopened")) {
+          // We should also try to close this popup if the drag has started
+          // from here, the timer will check if we are dragging over a child.
+          if (this.hasAttribute("autoopened") ||
+              this.hasAttribute("dragstart")) {
             this._overFolder.closeMenuTimer = this._overFolder
                                                   .setTimer(this._overFolder.hoverTime);
           }
 
           this._rootView._draggedNode = null;
         ]]></body>
       </method>
 
       <method name="onDragStart">
         <parameter name="aEvent"/>
         <parameter name="aXferData"/>
         <parameter name="aDragAction"/>
         <body><![CDATA[
-          // Force a copy action if parent node is a query or not-removable
-          if (aEvent.ctrlKey ||
-              PlacesUtils.nodeIsQuery(aEvent.target.node.parent) ||
-              !PlacesControllerDragHelper.canMoveContainerNode(aEvent.target.node))
-            aDragAction.action = Ci.nsIDragService.DRAGDROP_ACTION_COPY;
+          var draggedNode = aEvent.target.node;
+
+          // Force a copy action if parent node is a query or we are dragging a
+          // not-removable node
+          if (!PlacesControllerDragHelper.canMoveNode(draggedNode))
+            aEvent.dataTransfer.effectAllowed = "copyLink";
 
           // activate the view and cache the dragged node
-          this._rootView._draggedNode = aEvent.target.node;
+          this._rootView._draggedNode = draggedNode;
           this._rootView.focus();
 
-          aXferData.data = this._rootView.controller
-                                         .getTransferData(aDragAction.action);
+          // Fill the dataTransfer
+          this._rootView._controller.setDataTransfer(aEvent);
+
+          this.setAttribute("dragstart", "true");
         ]]></body>
       </method>
 
       <method name="onDrop">
         <parameter name="aEvent"/>
-         <parameter name="aDropData"/>
+        <parameter name="aDropData"/>
         <parameter name="aSession"/>
         <body><![CDATA[
+          // Cache the dataTransfer
+          PlacesControllerDragHelper.currentDataTransfer = aEvent.dataTransfer;
+
           var dropPoint = this._getDropPoint(aEvent);
           if (!dropPoint)
             return;
 
           PlacesControllerDragHelper.onDrop(dropPoint.ip);
         ]]></body>
       </method>
 
       <!-- This returns the FavourSet accepted by this popup -->
       <method name="getSupportedFlavours">
         <body><![CDATA[
-          var flavourSet = new FlavourSet();
-          var acceptedDropFlavours = PlacesUIUtils.GENERIC_VIEW_DROP_TYPES;
-          acceptedDropFlavours.forEach(flavourSet.appendFlavour, flavourSet);
-          return flavourSet;
+          return PlacesControllerDragHelper.flavourSet;
         ]]></body>
       </method>
 
       <!-- Check if we should hide the drop indicator for the target -->
       <method name="_hideDropIndicator">
         <parameter name="aEvent"/>
         <body><![CDATA[
           var target = aEvent.target;
@@ -241,103 +250,123 @@
           if (this._startMarker != -1 &&
               target.boxObject.y <= this.childNodes[this._startMarker].boxObject.y)
             betweenMarkers = false;
           if (this._endMarker != -1 &&
               target.boxObject.y >= this.childNodes[this._endMarker].boxObject.y)
             betweenMarkers = false;
 
           // hide the dropmarker if current node is not a places bookmark item
-          return !(target && target.node && betweenMarkers && this.canDrop());
+          return !(target && target.node && betweenMarkers &&
+                   this.canDrop(aEvent));
         ]]></body>
       </method>
 
       <!-- This function returns information about where to drop when
            dragging over this popup insertion point -->
       <method name="_getDropPoint">
         <parameter name="aEvent"/>
           <body><![CDATA[
             // Can't drop if the menu isn't a folder
             var resultNode = this._resultNode;
-            if (!PlacesUtils.nodeIsFolder(resultNode))
+
+            if (!PlacesUtils.nodeIsFolder(resultNode) ||
+                PlacesControllerDragHelper.disallowInsertion(resultNode)) {
+              aEvent.dataTransfer.effectAllowed = "none";
               return null;
+            }
 
-            var dropPoint = { ip: null, beforeIndex: null, folderNode: null };
+            var dropPoint = { ip: null, folderNode: null };
 
-            // set the limits for valid items
-            var start = 0;
-            var popup = this;
-            var end = popup.childNodes.length;
-            if (this._startMarker != -1)
-              start = this._startMarker + 1;
-            if (this._endMarker != -1)
-              end = this._endMarker;
+            // The node we are dragging over
+            var xulNode = aEvent.target;
+
+            // Calculate positions taking care of arrowscrollbox
+            var sbo = this._scrollBox.scrollBoxObject;
+            var eventY = aEvent.layerY;
+            var nodeY = xulNode.boxObject.y - sbo.y;
+            var nodeHeight = xulNode.boxObject.height;
 
-            // Loop through all the nodes to find the correct dropPoint
-            var popupY = popup.boxObject.y;
-            // we should add the scrollBox button height if visible
-            popupY += this._scrollBox.scrollBoxObject.y - popup.boxObject.y;
-            for (var i = start; i < end; i++) {
-              var xulNode = popup.childNodes[i];
-              var nodeY = xulNode.boxObject.y - popupY;
-              var nodeHeight = xulNode.boxObject.height;
-              if (xulNode.node &&
-                  (PlacesUtils.nodeIsFolder(xulNode.node) ||
-                   PlacesUtils.nodeIsTagQuery(xulNode.node)) &&
-                  !PlacesUtils.nodeIsReadOnly(xulNode.node)) {
-                // This is a folder. If the mouse is in the top 25% of the
-                // node, drop above the folder.  If it's in the middle
-                // 50%, drop into the folder.  If it's past that, drop below.
-                if (aEvent.layerY < nodeY + (nodeHeight * 0.25)) {
-                  // Drop above this folder.
-                  dropPoint.ip = new InsertionPoint(resultNode.itemId,
-                                                    i - start, -1);
-                  dropPoint.beforeIndex = i;
-                  return dropPoint;
-                }
-                else if (aEvent.layerY < nodeY + (nodeHeight * 0.75)) {
-                  // Drop inside this folder.
-                  dropPoint.ip = new InsertionPoint(xulNode.node.itemId, -1, 1);
-                  dropPoint.beforeIndex = i;
-                  dropPoint.folderNode = xulNode;
-                  return dropPoint;
-                }
+            if (!xulNode.node) {
+              // if we are dragging over a non places node drop at the end
+              dropPoint.ip = new InsertionPoint(resultNode.itemId,
+                                                -1,
+                                                Ci.nsITreeView.DROP_ON);
+              return dropPoint;
+            }
+            else if ((PlacesUtils.nodeIsFolder(xulNode.node) ||
+                      PlacesUtils.nodeIsTagQuery(xulNode.node)) &&
+                     !PlacesUtils.nodeIsReadOnly(xulNode.node)) {
+              // This is a folder or a tag container.
+              if (eventY - nodeY < nodeHeight * 0.25) {
+                // If the mouse is in the top 25% of the node,
+                // drop above the folder.
+                dropPoint.ip = new InsertionPoint(
+                                    resultNode.itemId,
+                                    -1,
+                                    Ci.nsITreeView.DROP_BEFORE,
+                                    PlacesUtils.nodeIsTagQuery(xulNode.node),
+                                    xulNode.node.itemId);
+                return dropPoint;
               }
-              else {
-                // This is a non-folder node. If the mouse is above the middle,
-                // drop above the folder.  Otherwise, drop below.
-                if (aEvent.layerY <= nodeY + (nodeHeight / 2)) {
-                  // Drop above this bookmark.
-                  dropPoint.ip = new InsertionPoint(resultNode.itemId,
-                                                    i - start, -1);
-                  dropPoint.beforeIndex = i;
-                  return dropPoint;
-                }
+              else if (eventY - nodeY < nodeHeight * 0.75) {
+                // If the mouse is before the 75 % of the node drop
+                // inside this folder.
+                dropPoint.ip = new InsertionPoint(
+                                    PlacesUtils.getConcreteItemId(xulNode.node),
+                                    -1,
+                                    Ci.nsITreeView.DROP_ON,
+                                    PlacesUtils.nodeIsTagQuery(xulNode.node));
+                dropPoint.folderNode = xulNode;
+                return dropPoint;
               }
             }
-            // Should drop below the last node.
-            dropPoint.ip = new InsertionPoint(resultNode.itemId, -1, 1);
-            dropPoint.beforeIndex = -1;
+            else if (eventY - nodeY <= nodeHeight / 2) {
+              // This is a non-folder node or a readonly folder.
+              // If the mouse is above the middle, drop above this item.
+              dropPoint.ip = new InsertionPoint(
+                                  resultNode.itemId,
+                                  -1,
+                                  Ci.nsITreeView.DROP_BEFORE,
+                                  PlacesUtils.nodeIsTagQuery(xulNode.node),
+                                  xulNode.node.itemId);
+              return dropPoint;
+            }
+
+            // Drop below the item.
+            dropPoint.ip = new InsertionPoint(
+                                resultNode.itemId,
+                                -1,
+                                Ci.nsITreeView.DROP_AFTER,
+                                PlacesUtils.nodeIsTagQuery(xulNode.node),
+                                xulNode.node.itemId);
             return dropPoint;
         ]]></body>
       </method>
 
       <method name="canDrop">
+        <parameter name="aEvent"/>
         <body><![CDATA[
+          // Cache the dataTransfer
+          PlacesControllerDragHelper.currentDataTransfer = aEvent.dataTransfer;
+
           var ip = this._rootView.insertionPoint;
           return ip && PlacesControllerDragHelper.canDrop(ip);
         ]]></body>
       </method>
 
       <!-- Sub-menus should be opened when the mouse drags over them, and closed
            when the mouse drags off.  The overFolder object manages opening and
            closing of folders when the mouse hovers. -->
       <field name="_overFolder"><![CDATA[({
         _self: this,
-        _folder: {node: null, openTimer: null, hoverTime: 350, closeTimer: null},
+        _folder: {node: null,
+                  openTimer: null,
+                  hoverTime: 350,
+                  closeTimer: null},
         _closeMenuTimer: null,
 
         get node() {
           return this._folder.node;
         },
         set node(val) {
           return this._folder.node = val;
         },
@@ -401,23 +430,27 @@
             // open while its children are being dragged over.)
             if (!draggingOverChild)
               this.closeParentMenus();
           }
 
           else if (aTimer == this.closeMenuTimer) {
             // Timer to close this menu after the drag exit.
             var popup = this._self;
-            if (!PlacesControllerDragHelper.draggingOverChildNode(popup.parentNode)) {
+            // if we are no more dragging we can leave the menu open to allow
+            // for better D&D bookmark organization
+            if (PlacesControllerDragHelper.getSession() &&
+                !PlacesControllerDragHelper.draggingOverChildNode(popup.parentNode)) {
               popup.hidePopup();
               // Close any parent menus that aren't being dragged over;
               // otherwise they'll stay open because they couldn't close
               // while this menu was being dragged over.
               this.closeParentMenus();
             }
+            this._closeMenuTimer = null;
           }
         },
 
         //  Helper function to close all parent menus of this menu,
         //  as long as none of the parent's children are currently being
         //  dragged over.
         closeParentMenus: function OF__closeParentMenus() {
           var popup = this._self;
@@ -434,18 +467,18 @@
 
         //  The mouse is no longer dragging over the stored menubutton.
         //  Close the menubutton, clear out drag styles, and clear all
         //  timers for opening/closing it.
         clear: function OF__clear() {
           if (this._folder.node && this._folder.node.lastChild) {
             if (!this._folder.node.lastChild.hasAttribute("dragover"))
               this._folder.node.lastChild.hidePopup();
-            // remove dragover-into style
-            this._folder.node.removeAttribute("dragover-into");
+            // remove menuactive style
+            this._folder.node.removeAttribute("_moz-menuactive");
             this._folder.node = null;
           }
           if (this._folder.openTimer) {
             this._folder.openTimer.cancel();
             this._folder.openTimer = null;
           }
           if (this._folder.closeTimer) {
             this._folder.closeTimer.cancel();
@@ -569,16 +602,19 @@
           }
 
           // if document.popupNode pointed to this child, null it out,
           // otherwise controller's command-updating may rely on the removed
           // item still being "selected".
           if (document.popupNode == child)
             document.popupNode = null;
           child.parentNode.removeChild(child);
+
+          if (this._endMarker != -1)
+            this._endMarker--;
         ]]></body>
       </method>
 
       <method name="insertNewItem">
         <parameter name="aChild"/>
         <parameter name="aParentPopup"/>
         <parameter name="aBefore"/>
         <body><![CDATA[
@@ -586,22 +622,26 @@
             PlacesUIUtils.createMenuItemForNode(aChild, this._containerNodesMap);
 
           if (aBefore)
             aParentPopup.insertBefore(element, aBefore);
           else {
             // Add the new element to the menu.  If there is static content at
             // the end of the menu, add the element before that.  Otherwise,
             // just add to the end.
-            if (aParentPopup._endMarker != -1)
+            if (aParentPopup._endMarker != -1) {
               aParentPopup.insertBefore(element,
-                                        aParentPopup.childNodes[aParentPopup._endMarker++]);
+                                        aParentPopup.childNodes[aParentPopup._endMarker]);
+            }
             else
               aParentPopup.appendChild(element);
           }
+
+          if (aParentPopup._endMarker != -1)
+            aParentPopup._endMarker++;
         ]]></body>
       </method>
 
       <method name="_showEmptyMenuItem">
         <parameter name="aPopup"/>
         <body><![CDATA[
           if (aPopup._emptyMenuItem) {
             aPopup._emptyMenuItem.hidden = false;
@@ -697,16 +737,17 @@
           for (var i = 0; i < children.length; i++) {
             if (children[i].node == aNode) {
               this._self.removeItem(children[i]);
               if (!popup.hasChildNodes() ||
                   (popup.childNodes.length == 1 &&
                    popup.firstChild == popup._emptyMenuItem)) {
                 this._self._showEmptyMenuItem(popup);
               }
+              return;
             }
           }
         },
 
         itemMoved:
         function PMV_itemMoved(aItem, aOldParent, aOldIndex, aNewParent,
                                aNewIndex) {
           // This cannot actually happen yet (see IDL)
@@ -895,25 +936,33 @@
           }
           return null;
         ]]></getter>
       </property>
 
       <!-- nsIPlacesView -->
       <property name="insertionPoint">
         <getter><![CDATA[
+          // there is no insertion point for history queries
+          // so bail out now and save a lot of work when updating commands
+          var resultNode = this._resultNode;
+          if (PlacesUtils.nodeIsQuery(resultNode) &&
+              asQuery(resultNode).queryOptions.queryType ==
+                Ci.nsINavHistoryQueryOptions.QUERY_TYPE_HISTORY)
+              return null;
+
           // By default, the insertion point is at the top level, at the end.
           var index = PlacesUtils.bookmarks.DEFAULT_INDEX;
           var container = null;
           var orientation = Ci.nsITreeView.DROP_BEFORE;
           var isTag = false;
 
-          if (PlacesUtils.nodeIsFolder(this._resultNode)) {
-            container = this._resultNode;
-            isTag = PlacesUtils.nodeIsTagQuery(this._resultNode);
+          if (PlacesUtils.nodeIsFolder(resultNode)) {
+            container = resultNode;
+            isTag = PlacesUtils.nodeIsTagQuery(resultNode);
           }
 
           var selectedNode = this.selectedNode;
           if (selectedNode) {
             var popupNode = document.popupNode;
             if (!popupNode.node) {
               // If a static menuitem is selected the insertion point
               // is inside the folder, at the end.
@@ -923,36 +972,24 @@
             else {
               // In all other cases the insertion point is before that node.
               container = selectedNode.parent;
               index = PlacesUtils.getIndexOfNode(selectedNode);
               isTag = PlacesUtils.nodeIsTagQuery(selectedNode.parent);
             }
           }
 
-          if (this._disallowInsertion(container))
+          if (PlacesControllerDragHelper.disallowInsertion(container))
             return null;
 
           return new InsertionPoint(PlacesUtils.getConcreteItemId(container),
                                     index, orientation, isTag);
         ]]></getter>
       </property>
 
-      <method name="_disallowInsertion">
-        <parameter name="aContainer"/>
-        <body><![CDATA[
-          // allow dropping into Tag containers
-          if (PlacesUtils.nodeIsTagQuery(aContainer))
-            return false;
-          // Disallow insertion of items under readonly folders
-          return (!PlacesUtils.nodeIsFolder(aContainer) ||
-                   PlacesUtils.nodeIsReadOnly(aContainer));
-        ]]></body>
-      </method>
-
       <!-- nsIPlacesView -->
       <method name="selectAll">
         <body/>
       </method>
 
       <method name="selectItems">
         <body/>
       </method>
@@ -960,16 +997,20 @@
       <property name="selType" readonly="true" onget="return 'single';"/>
 
       <method name="buildContextMenu">
         <parameter name="aPopup"/>
         <body><![CDATA[
           this._ensureInitialized();
           this._contextMenuShown = true;
           this.focus();
+          // The above call to focus activates the controller, but it may not
+          // always fire a consumable event for commandUpdater, so we force a
+          // command update.
+          window.updateCommands("focus");
           var show = this.controller.buildContextMenu(aPopup);
           if (show) {
             // disable the Delete command if the selection isn't explicit
             if (document.popupNode && document.popupNode.localName == "menupopup")
               document.getElementById("cmd_delete").setAttribute("disabled", "true");
             return true;
           }
           return false;
@@ -1008,13 +1049,14 @@
         // so we don't rebuild its contents whenever the popup is reopened.
         if (!PlacesUtils.nodeIsFolder(popup._resultNode))
           popup._resultNode.containerOpen = false;
 
         // The autoopened attribute is set for folders which have been
         // automatically opened when dragged over.  Turn off this attribute
         // when the folder closes because it is no longer applicable.
         popup.removeAttribute("autoopened");
+        popup.removeAttribute("dragstart");
       ]]></handler>
     </handlers>
   </binding>
 
 </bindings>
--- a/browser/components/places/content/toolbar.xml
+++ b/browser/components/places/content/toolbar.xml
@@ -18,16 +18,17 @@
 # The Initial Developer of the Original Code is Google Inc.
 # Portions created by the Initial Developer are Copyright (C) 2005-2006
 # the Initial Developer. All Rights Reserved.
 #
 # Contributor(s):
 #   Annie Sullivan <annie.sullivan@gmail.com>
 #   Ben Goodger <beng@google.com>
 #   Myk Melez <myk@mozilla.org>
+#   Marco Bonardo <mak77@bonardo.net>
 #
 # Alternatively, the contents of this file may be used under the terms of
 # either the GNU General Public License Version 2 or later (the "GPL"), or
 # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 # in which case the provisions of the GPL or the LGPL are applicable instead
 # of those above. If you wish to allow use of your version of this file only
 # under the terms of either the GPL or the LGPL, and not to allow others to
 # use your version of this file under the terms of the MPL, indicate your
@@ -302,16 +303,24 @@
           if (!(this._chevron.collapsed = !overflowed)) {
             // Attach the popup binding to the chevron popup
             var popup = this._chevron.firstChild;
             if (!popup.hasAttribute("type")) {
               popup.setAttribute("place", this.place);
               popup.setAttribute("type", "places");
             }
           }
+
+          // We rebuild the chevron on popupShowing, so if it is open
+          // we must force a rebuild
+          if (this._chevron.open) {
+            var popup = this._chevron.firstChild;
+            for (var i = 0; i < popup.childNodes.length; i++)
+              popup.childNodes[i].hidden = !this.childNodes[i].collapsed;
+          }
         ]]></body>
       </method>
 
       <!-- nsIPlacesView -->
       <property name="place">
         <getter><![CDATA[
           return this.getAttribute("place");
         ]]></getter>
@@ -401,36 +410,24 @@
             else {
               // In all other cases the insertion point is before that node.
               container = selectedNode.parent;
               index = PlacesUtils.getIndexOfNode(selectedNode);
               isTag = PlacesUtils.nodeIsTagQuery(selectedNode.parent);
             }
           }
 
-          if (this._disallowInsertion(container))
+          if (PlacesControllerDragHelper.disallowInsertion(container))
             return null;
 
           return new InsertionPoint(PlacesUtils.getConcreteItemId(container),
                                     index, orientation, isTag);
         ]]></getter>
       </property>
 
-      <method name="_disallowInsertion">
-        <parameter name="aContainer"/>
-        <body><![CDATA[
-          // allow dropping into Tag containers
-          if (PlacesUtils.nodeIsTagQuery(aContainer))
-            return false;
-          // Disallow insertion of items under readonly folders
-          return (!PlacesUtils.nodeIsFolder(aContainer) ||
-                   PlacesUtils.nodeIsReadOnly(aContainer));
-        ]]></body>
-      </method>
-
       <!-- nsIPlacesView -->
       <method name="selectAll">
         <body><![CDATA[ 
           // Nothing
         ]]></body>
       </method>
 
       <method name="selectItems">
@@ -515,35 +512,46 @@
             for (var i = 0; i < children.length; i++) {
               if (children[i].node == aNode) {
                 this._self.removeItem(children[i]);
                 if (!popup.hasChildNodes() ||
                     (popup.childNodes.length == 1 &&
                      popup.firstChild == popup._emptyMenuItem)) {
                   this._self._showEmptyMenuItem(popup);
                 }
+                if (popup._endMarker != -1)
+                  popup._endMarker--;
+                return;
               }
             }
           }
         },
 
         itemMoved:
         function TV_V_itemMoved(aItem, aOldParent, aOldIndex, aNewParent,
                                 aNewIndex) {
           // This cannot actually happen yet (see IDL)
           if (aNewParent != aOldParent)
             return;
 
           if (aNewParent == this._self.getResultNode()) {
             var children = this._self.childNodes;
+            var chevronPopup = this._self._chevron.firstChild;
             for (var i = 0; i < children.length; i++) {
               var button = children[i];
               if (button.node == aItem) {
                 this._self.removeChild(button);
                 this._self.insertBefore(button, children[aNewIndex]);
+                if (chevronPopup) {
+                  // Maintain chevron in sync
+                  menuitem = chevronPopup.childNodes[i];
+                  chevronPopup.removeChild(menuitem);
+                  chevronPopup.insertBefore(menuitem,
+                                            chevronPopup.childNodes[aNewIndex]);
+                }
                 this._self.updateChevron();
                 return;
               }
             }
           }
           var popup = this._getPopupForContainer(aNewParent);
           var children = popup.childNodes;
           for (var i = 0; i < children.length; i++) {
@@ -692,17 +700,20 @@
       <field name="_DNDObserver"><![CDATA[({
         // Inside the _DNDObserver object's functions, this points to 
         // the _DNDObserver object.  _self points to the toolbar xbl object.
         _self: this,
 
         // Menu buttons should be opened when the mouse drags over them, and closed
         // when the mouse drags off.  The overFolder object manages opening and closing
         // of folders when the mouse hovers.
-        _overFolder: {node: null, openTimer: null, hoverTime: 350, closeTimer: null},
+        _overFolder: {node: null,
+                      openTimer: null,
+                      hoverTime: 350,
+                      closeTimer: null},
 
         // timer for turning of indicator bar, to get rid of flicker
         _ibTimer: null, 
  
         _setTimer: function TBV_DO_setTimer(time) {
           var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
           timer.initWithCallback(this, time, timer.TYPE_ONE_SHOT);
           return timer;
@@ -789,31 +800,36 @@
           for (var i = 0; i < this._self.childNodes.length; i++) {
             var xulNode = this._self.childNodes[i];
             if (PlacesUtils.nodeIsFolder(xulNode.node) &&
                 !PlacesUtils.nodeIsReadOnly(xulNode.node)) {
               // This is a folder. If the mouse is in the left 25% of the
               // node (or 25% of the right, in RTL UI), drop before the folder.
               // If it's in the middle 50%, drop into the folder. If it's past
               // that, drop after.
-              if ((isRTL && event.clientX > xulNode.boxObject.x + (xulNode.boxObject.width * 0.75)) ||
-                  (!isRTL && event.clientX < xulNode.boxObject.x + (xulNode.boxObject.width * 0.25))) {
+              if ((isRTL && event.clientX > xulNode.boxObject.x +
+                                            (xulNode.boxObject.width * 0.75)) ||
+                  (!isRTL && event.clientX < xulNode.boxObject.x + 
+                                             (xulNode.boxObject.width * 0.25))) {
                 // Drop to the left of this folder.
                 dropPoint.ip =
                   new InsertionPoint(PlacesUtils.getConcreteItemId(result.root),
                                      i, -1);
                 dropPoint.beforeIndex = i;
                 return dropPoint;
               }
-              else if ((isRTL && event.clientX > xulNode.boxObject.x + (xulNode.boxObject.width * 0.25)) ||
-                       (!isRTL && event.clientX < xulNode.boxObject.x + (xulNode.boxObject.width * 0.75))) {
+              else if ((isRTL && event.clientX > xulNode.boxObject.x + 
+                                                 (xulNode.boxObject.width * 0.25)) ||
+                       (!isRTL && event.clientX < xulNode.boxObject.x +
+                                                  (xulNode.boxObject.width * 0.75))) {
                 // Drop inside this folder.
                 dropPoint.ip =
                   new InsertionPoint(PlacesUtils.getConcreteItemId(xulNode.node),
-                                     -1, 1);
+                                     -1, 1,
+                                     PlacesUtils.nodeIsTagQuery(xulNode.node));
                 dropPoint.beforeIndex = i;
                 dropPoint.folderNode = xulNode;
                 return dropPoint;
               }
             }
             else {
               // This is a non-folder node. If the mouse is left (or right, in
               // RTL UI) of the middle, drop before the folder.  Otehrwise,
@@ -831,49 +847,53 @@
           }
           // Should drop after the last node.
           dropPoint.ip =
         	  new InsertionPoint(PlacesUtils.getConcreteItemId(result.root),
 	                             -1, 1);
           dropPoint.beforeIndex = -1;
           return dropPoint;
         },
-        
-        onDragStart: function TBV_DO_onDragStart(event, xferData, dragAction) {
+
+        onDragStart: function TBV_DO_onDragStart(aEvent, aXferData, aDragAction) {
+          var draggedXulNode = aEvent.target;
           // sub menus have their own d&d handlers
-          if (event.target.parentNode != this._self)
+          if (draggedXulNode.parentNode != this._self)
             return false;
 
-          if (event.target.localName == "toolbarbutton" &&
-              event.target.getAttribute("type") == "menu") {
+          if (draggedXulNode.localName == "toolbarbutton" &&
+              draggedXulNode.getAttribute("type") == "menu") {
 #ifdef XP_WIN
-            // Support folder dragging on the personal toolbar when the user 
-            // holds the "alt" key while they drag (Ctrl+drag has another 
-            // meaning - Copy). This does not appear to work at all on Linux.
-            if (!event.shiftKey && !event.altKey && !event.ctrlKey)
+            // Support folder dragging on the personal toolbar when the user
+            // holds the "alt" or "shift" key while dragging.
+            // Ctrl+drag is Copy
+            if (!aEvent.shiftKey && !aEvent.altKey && !aEvent.ctrlKey)
               return false;
-            event.target.firstChild.hidePopup();
 #else
-            return;
+            // Support folder dragging on the personal toolbar when the user
+            // holds the "shift" key while dragging
+            // Ctrl+drag is Copy
+            if (!aEvent.shiftKey && !aEvent.ctrlKey)
+              return false;
 #endif
+            draggedXulNode.firstChild.hidePopup();
           }
 
-          if (event.ctrlKey)
-            dragAction.action = Ci.nsIDragService.DRAGDROP_ACTION_COPY;
+          // activate the view and cache the dragged node
+          this._self._draggedNode = draggedXulNode.node;
+          this._self.focus();
 
-          // activate the view and cache the dragged node
-          this._self._draggedNode = event.target.node;
-          this._self.focus();
-          xferData.data = this._self._controller.getTransferData(dragAction.action);
-#ifdef XP_WIN
+          this._self._controller.setDataTransfer(aEvent);
           return true;
-#endif
         },
 
-        canDrop: function TBV_DO_canDrop(event, session) {
+        canDrop: function TBV_DO_canDrop(aEvent, aDragSession) {
+          // Cache the dataTransfer
+          PlacesControllerDragHelper.currentDataTransfer = aEvent.dataTransfer;
+
           var ip = this._self.insertionPoint;
           return ip && PlacesControllerDragHelper.canDrop(ip);
         },
 
         onDragOver: function TBV_DO_onDragOver(event, flavor, session) {
           PlacesControllerDragHelper.currentDropTarget = event.target;
           var dropPoint = this._getDropPoint(event);
 
@@ -934,43 +954,44 @@
               }
             }
             // Clear out old folder information
             this._clearOverFolder();
           }
         },
 
         onDrop: function TBV_DO_onDrop(event, dropData, session) {
+          // Cache the dataTransfer
+          PlacesControllerDragHelper.currentDataTransfer = event.dataTransfer;
+
           var dropPoint = this._getDropPoint(event);
-          if (dropPoint == null)
+          if (!dropPoint)
             return;
           PlacesControllerDragHelper.onDrop(dropPoint.ip);
         },
 
         onDragExit: function TBV_DO_onDragExit(event, session) {
+          PlacesControllerDragHelper.currentDropTarget = null;
+          PlacesControllerDragHelper.currentDataTransfer = null;
+
           // Set timer to turn off indicator bar (if we turn it off
           // here, dragenter might be called immediately after, creating
           // flicker.)
           if (this._ibTimer)
             this._ibTimer.cancel();
           this._ibTimer = this._setTimer(10);
           // Close any folder being hovered over
           if (this._overFolder.node)
             this._overFolder.closeTimer = this._setTimer(this._overFolder.hoverTime);
-          PlacesControllerDragHelper.currentDropTarget = null;
 
           this._self._draggedNode = null;
         },
 
         getSupportedFlavours: function TBV_DO_getSupportedFlavours() {
-          var flavorSet = new FlavourSet();
-          var types = PlacesUIUtils.GENERIC_VIEW_DROP_TYPES;
-          for (var i = 0; i < types.length; ++i)
-            flavorSet.appendFlavour(types[i]);
-          return flavorSet;
+          return PlacesControllerDragHelper.flavourSet;
         }
       })]]></field>
 
       <method name="checkForMenuEvent">
         <parameter name="event"/>
         <parameter name="action"/>
         <body><![CDATA[
           // It seems that even if the menu drag/drop event
@@ -995,16 +1016,20 @@
 
       <property name="selType" onget="return 'single';"/>
 
       <method name="buildContextMenu">
         <parameter name="aPopup"/>
         <body><![CDATA[
           this._contextMenuShown = true;
           this.focus();
+          // The above call to focus activates the controller, but it may not
+          // always fire a consumable event for commandUpdater, so we force a
+          // command update.
+          window.updateCommands("focus");
           var show = this.controller.buildContextMenu(aPopup);
           if (show) {
             // disable the Delete command if the selection isn't explicit
             if (document.popupNode && document.popupNode.localName == "menupopup")
               document.getElementById("cmd_delete").setAttribute("disabled", "true");
             return true;
           }
           return false;
@@ -1047,21 +1072,24 @@
           if (aBefore)
             aParentPopup.insertBefore(element, aBefore);
           else {
             // Add the new element to the menu.  If there is static content at
             // the end of the menu, add the element before that.  Otherwise,
             // just add to the end.
             if (aParentPopup._endMarker != -1) {
               aParentPopup.insertBefore(element,
-                                        aParentPopup.childNodes[aParentPopup._endMarker++]);
+                                        aParentPopup.childNodes[aParentPopup._endMarker]);
             }
             else
               aParentPopup.appendChild(element);
           }
+
+          if (aParentPopup._endMarker != -1)
+            aParentPopup._endMarker++;
         ]]></body>
       </method>
 
       <method name="_containerPopupShowing">
         <parameter name="aPopup"/>
         <body><![CDATA[
           if (!aPopup._built)
             this._rebuildPopup(aPopup);
@@ -1121,16 +1149,27 @@
         if (!this.checkForMenuEvent(event, "drop"))
           nsDragAndDrop.drop(event, this._DNDObserver);
       ]]></handler>
       <handler event="dragexit"><![CDATA[
         if (!this.checkForMenuEvent(event, "dragExit"))
           nsDragAndDrop.dragExit(event, this._DNDObserver);
       ]]></handler>
       <handler event="popupshowing" phase="capturing"><![CDATA[
+      // Don't show the popup if we are dragging a container.
+      if (this._draggingContainer) {
+          this._draggingContainer = false;
+#ifdef MOZ_WIDGET_GTK2
+          // Allow drag and drop of folders in Linux.
+          // We must prevent popupshowing event from firing when shift is pressed.
+          event.preventDefault();
+          return false;
+#endif
+        }
+
         var popup = event.originalTarget;
 
         // Avoid handling popupshowing of inner views
         if (popup._resultNode && PlacesUIUtils.getViewForNode(popup) == this)
           this._containerPopupShowing(popup);
 
         var parent = popup.parentNode;
         if (parent.localName == "toolbarbutton" &&
@@ -1149,18 +1188,28 @@
         }
 
         var parent = popup.parentNode;
         if (parent.localName == "toolbarbutton" &&
             !PlacesControllerDragHelper.getSession())
           this._openedMenuButton = null;
       ]]></handler>
 
+      <handler event="mousedown"><![CDATA[
+        // Allow drag and drop of folders in Linux.
+        // We must prevent popupshowing event from firing when shift is pressed.
+        var target = event.originalTarget;
+        if (event.button == 1 && event.shiftKey &&
+            target.localName == "toolbarbutton" && target.type == "menu")
+          this._draggingContainer = true;
+      ]]></handler>
+
       <handler event="mousemove"><![CDATA[
-        if (this._openedMenuButton == null || PlacesControllerDragHelper.getSession())
+        if (this._openedMenuButton == null ||
+            PlacesControllerDragHelper.getSession())
           return;
 
         var target = event.originalTarget;
         if (this._openedMenuButton != target &&
             target.localName == "toolbarbutton" &&
             target.type == "menu") {
           this._openedMenuButton.open = false;
           target.open = true;
--- a/browser/components/places/content/tree.xml
+++ b/browser/components/places/content/tree.xml
@@ -17,16 +17,17 @@
 #
 # The Initial Developer of the Original Code is Google Inc.
 # Portions created by the Initial Developer are Copyright (C) 2005-2006
 # the Initial Developer. All Rights Reserved.
 #
 # Contributor(s):
 #   Ben Goodger <beng@google.com>
 #   Annie Sullivan <annie.sullivan@gmail.com>
+#   Marco Bonardo <mak77@bonardo.net>
 #
 # Alternatively, the contents of this file may be used under the terms of
 # either the GNU General Public License Version 2 or later (the "GPL"), or
 # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 # in which case the provisions of the GPL or the LGPL are applicable instead
 # of those above. If you wish to allow use of your version of this file only
 # under the terms of either the GPL or the LGPL, and not to allow others to
 # use your version of this file under the terms of the MPL, indicate your
@@ -429,21 +430,20 @@
         <getter><![CDATA[
           // invalidated on selection and focus changes
           if (this._cachedInsertionPoint !== undefined)
             return this._cachedInsertionPoint;
 
           // there is no insertion point for history queries
           // so bail out now and save a lot of work when updating commands
           var resultNode = this.getResultNode();
-          if (PlacesUtils.nodeIsQuery(resultNode)) {
-            var options = asQuery(resultNode).queryOptions;
-            if (options.queryType == options.QUERY_TYPE_HISTORY)
+          if (PlacesUtils.nodeIsQuery(resultNode) &&
+              asQuery(resultNode).queryOptions.queryType ==
+                Ci.nsINavHistoryQueryOptions.QUERY_TYPE_HISTORY)
               return this._cachedInsertionPoint = null;
-          }
 
           var orientation = Ci.nsITreeView.DROP_BEFORE;
           // If there is no selection, insert at the end of the container. 
           if (!this.hasSelection) {
             var index = this.view.rowCount - 1;
             this._cachedInsertionPoint =
               this._getInsertionPoint(index, orientation);
             return this._cachedInsertionPoint;
@@ -483,28 +483,16 @@
             orientation = Ci.nsITreeView.DROP_ON;
 
           this._cachedInsertionPoint =
             this._getInsertionPoint(max.value, orientation);
           return this._cachedInsertionPoint;
         ]]></getter>
       </property>
 
-      <method name="_disallowInsertion">
-        <parameter name="aContainer"/>
-        <body><![CDATA[
-          // allow dropping into Tag containers
-          if (PlacesUtils.nodeIsTagQuery(aContainer))
-            return false;
-          // Disallow insertion of items under readonly folders
-          return (!PlacesUtils.nodeIsFolder(aContainer) ||
-                   PlacesUtils.nodeIsReadOnly(aContainer));
-        ]]></body>
-      </method>
-
       <method name="_getInsertionPoint">
         <parameter name="index"/>
         <parameter name="orientation"/>
         <body><![CDATA[ 
           var result = this.getResult();
           var resultview = this.getResultView();
           var container = result.root;
           var dropNearItemId = -1;
@@ -514,35 +502,34 @@
           if (index != -1) {
             var lastSelected = resultview.nodeForTreeIndex(index);
             if (resultview.isContainer(index) && orientation == Ci.nsITreeView.DROP_ON) {
               // If the last selected item is an open container, append _into_
               // it, rather than insert adjacent to it. 
               container = lastSelected;
               index = -1;
             }
-            else if (!this._disallowInsertion(lastSelected) &&
-                     lastSelected.containerOpen &&
+            else if (lastSelected.containerOpen &&
                      orientation == Ci.nsITreeView.DROP_AFTER &&
                      lastSelected.hasChildren) {
              // If the last selected item is an open container and the user is
              // trying to drag into it as a first item, really insert into it.
              container = lastSelected;
-             orientation = Ci.nsITreeView.DROP_BEFORE;
+             orientation = Ci.nsITreeView.DROP_ON;
              index = 0;
             }
             else {
               // Use the last-selected node's container unless the root node
               // is selected, in which case we use the root node itself as the
               // insertion point.
               container = lastSelected.parent || container;
 
               // avoid the potentially expensive call to getIndexOfNode() 
               // if we know this container doesn't allow insertion
-              if (this._disallowInsertion(container))
+              if (PlacesControllerDragHelper.disallowInsertion(container))
                 return null;
 
               var queryOptions = asQuery(result.root).queryOptions;
               if (queryOptions.sortingMode !=
                     Ci.nsINavHistoryQueryOptions.SORT_BY_NONE) {
                 // If we are within a sorted view, insert at the end
                 index = -1;
               }
@@ -557,17 +544,17 @@
               }
               else {
                 var lsi = PlacesUtils.getIndexOfNode(lastSelected);
                 index = orientation == Ci.nsITreeView.DROP_BEFORE ? lsi : lsi + 1;
               }
             }
           }
 
-          if (this._disallowInsertion(container))
+          if (PlacesControllerDragHelper.disallowInsertion(container))
             return null;
 
           return new InsertionPoint(PlacesUtils.getConcreteItemId(container),
                                     index, orientation,
                                     PlacesUtils.nodeIsTagQuery(container),
                                     dropNearItemId);
         ]]></body>
       </method>
@@ -670,86 +657,104 @@
             selection.rangedSelect(index, index, true);
           }
           selection.selectEventsSuppressed = false;
         ]]></body>
       </method>
 
       <!-- nsDragAndDrop -->
       <method name="onDragStart">
-        <parameter name="event"/>
-        <parameter name="xferData"/>
-        <parameter name="dragAction"/>
+        <parameter name="aEvent"/>
+        <parameter name="aXferData"/>
+        <parameter name="aDragAction"/>
         <body><![CDATA[ 
-          // Drag and Drop does not work while a tree view is sorted.
-          if (this.getAttribute("sortActive") == "true")
-            throw Cr.NS_OK;
-
           var nodes = this.getSelectionNodes();
           for (var i = 0; i < nodes.length; ++i) {
             var node = nodes[i];
 
             // Disallow dragging the root node of a tree
             var parent = node.parent;
             if (!parent)
-              throw Cr.NS_OK;
+              return;
 
-            // If this node is part of a readonly container (e.g. a livemark) it 
-            // cannot be moved, only copied, so we must change the action used
-            // by the drag session.
-            if (PlacesUtils.nodeIsTagQuery(parent) ||
-                !PlacesControllerDragHelper.canMoveContainerNode(node)) {
-              // XXX DOES NOTHING! dragAction doesn't persist
-              dragAction.action = Ci.nsIDragService.DRAGDROP_ACTION_COPY;
+            // If this node is child of a readonly container (e.g. a livemark)
+            // or cannot be moved, we must force a copy.
+            if (!PlacesControllerDragHelper.canMoveNode(node)) {
+              aEvent.dataTransfer.effectAllowed = "copyLink";
               break;
             }
           }
- 
-          // XXXben - the drag wrapper should do this automatically.
-          if (event.ctrlKey)
-            dragAction.action = Ci.nsIDragService.DRAGDROP_ACTION_COPY;
+
           // Stuff the encoded selection into the transferable data object
-          xferData.data = this._controller.getTransferData(dragAction.action);
+          this._controller.setDataTransfer(aEvent);
         ]]></body>
       </method>
       
       <!-- nsDragAndDrop -->
       <method name="canDrop">
-        <parameter name="event"/>
-        <parameter name="session"/>
-        <body><![CDATA[ 
+        <parameter name="aEvent"/>
+        <parameter name="aDragSession"/>
+        <body><![CDATA[
+          // Cache the dataTransfer for the view
+          PlacesControllerDragHelper.currentDataTransfer = aEvent.dataTransfer;
+
           var row = { }, col = { }, child = { };
-          this.treeBoxObject.getCellAt(event.clientX, event.clientY, row, col, 
-                                       child);
-          return this.view.canDrop(row.value, -1);
+          this.treeBoxObject.getCellAt(aEvent.clientX, aEvent.clientY,
+                                       row, col, child);
+          var node = row.value != -1 ?
+                     this.getResultView().nodeForTreeIndex(row.value) :
+                     this.getResultNode();
+          // cache the dropTarget for the view
+          PlacesControllerDragHelper.currentDropTarget = node;
+
+          // We have to calculate the orientation since view.canDrop will use
+          // it and we want to be consistent with the dropfeedback
+          var tbo = this.treeBoxObject;
+          var rowHeight = tbo.rowHeight;
+          var eventY = aEvent.clientY - tbo.treeBody.boxObject.y -
+                       rowHeight * (row.value - tbo.getFirstVisibleRow());
+
+          var orientation = Ci.nsITreeView.DROP_BEFORE;
+
+          if (row.value == -1) {
+            // If the row is not valid we try to insert inside the resultNode.
+            orientation = Ci.nsITreeView.DROP_ON;
+          }
+          else if (PlacesUtils.nodeIsContainer(node) &&
+                   eventY > rowHeight * 0.75) {
+            // If we are below the 75% of a container the treeview we try
+            // to drop after the node.
+            orientation = Ci.nsITreeView.DROP_AFTER;
+          }
+          else if (PlacesUtils.nodeIsContainer(node) &&
+                   eventY > rowHeight * 0.25) {
+            // If we are below the 25% of a container the treeview we try
+            // to drop inside the node.
+            orientation = Ci.nsITreeView.DROP_ON;
+          }
+
+          return this.view.canDrop(row.value, orientation);
         ]]></body>
       </method>
       
       <!-- nsDragAndDrop -->
       <method name="onDragOver">
-        <parameter name="event"/>
-        <parameter name="flavor"/>
-        <parameter name="session"/>
-        <body><![CDATA[ 
-          var dragService = 
-              Cc["@mozilla.org/widget/dragservice;1"].
-              getService(Ci.nsIDragService);
-          var dragSession = dragService.getCurrentSession();
-          dragSession.canDrop = this.canDrop(event, session);
+        <parameter name="aEvent"/>
+        <parameter name="aFlavour"/>
+        <parameter name="aDragSession"/>
+        <body><![CDATA[      
+          if (!this.canDrop(aEvent, aDragSession))
+            aEvent.dataTransfer.effectAllowed = "none";
         ]]></body>
       </method>
 
       <!-- nsDragAndDrop -->
       <method name="getSupportedFlavours">
         <body><![CDATA[
-          var flavorSet = new FlavourSet();
-          var types = PlacesUIUtils.GENERIC_VIEW_DROP_TYPES;
-          for (var i = 0; i < types.length; ++i)
-            flavorSet.appendFlavour(types[i]);
-          return flavorSet;
+          return PlacesControllerDragHelper.flavourSet;
         ]]></body>
       </method>
 
       <method name="buildContextMenu">
         <parameter name="aPopup"/>
         <body><![CDATA[
           return this.controller.buildContextMenu(aPopup);
         ]]></body>
@@ -777,21 +782,27 @@
           win.document.commandDispatcher.updateCommands("focus");
           if (win == window.top)
             break;
 
           win = win.parent;
         }
       ]]></handler>
       <handler event="draggesture"><![CDATA[
-        // XXXben ew.
         if (event.target.localName == "treechildren")
           nsDragAndDrop.startDrag(event, this);
       ]]></handler>
       <handler event="dragover"><![CDATA[
         if (event.target.localName == "treechildren")
           nsDragAndDrop.dragOver(event, this);
       ]]></handler>
+      <handler event="drop"><![CDATA[
+          PlacesControllerDragHelper.currentDataTransfer = event.dataTransfer;
+      ]]></handler>
+      <handler event="dragexit"><![CDATA[
+        PlacesControllerDragHelper.currentDataTransfer = null;
+        PlacesControllerDragHelper.currentDropTarget = null;
+      ]]></handler>
     </handlers>
   </binding>
 
 </bindings>
 
--- a/browser/components/places/content/treeView.js
+++ b/browser/components/places/content/treeView.js
@@ -991,82 +991,61 @@ PlacesTreeView.prototype = {
     return this._result.sortingMode !=
            Components.interfaces.nsINavHistoryQueryOptions.SORT_BY_NONE;
   },
 
   canDrop: function PTV_canDrop(aRow, aOrientation) {
     if (!this._result)
       throw Cr.NS_ERROR_UNEXPECTED;
 
-    var node = aRow != -1 ? this.nodeForTreeIndex(aRow) : this._result.root;
+    // drop position into a sorted treeview would be wrong
+    if (this.isSorted())
+      return false;
 
-    if (aOrientation == Ci.nsITreeView.DROP_ON) {
-      // The user cannot drop an item into itself or a read-only container
-      var dragService =  Cc["@mozilla.org/widget/dragservice;1"].
-                         getService(Ci.nsIDragService);
-      var dragSession = dragService.getCurrentSession();
-      var elt = dragSession.sourceNode.parentNode;
-      if (elt.localName == "tree" && elt.view == this &&
-          this.selection.isSelected(aRow))
-        return false;
-    }
-  
     var ip = this._getInsertionPoint(aRow, aOrientation);
     return ip && PlacesControllerDragHelper.canDrop(ip);
   },
 
-  // XXXmano: these two are copied over from tree.xml, to fix this we need to
-  // either add a helper to PlacesUtils or keep it here and add insertionPoint
-  // to the view interface.
-  _disallowInsertion: function PTV__disallowInsertion(aContainer) {
-    // allow dropping into Tag containers
-    if (PlacesUtils.nodeIsTagQuery(aContainer))
-      return false;
-    // Disallow insertion of items under readonly folders
-    return (!PlacesUtils.nodeIsFolder(aContainer) ||
-            PlacesUtils.nodeIsReadOnly(aContainer));
-  },
-
   _getInsertionPoint: function PTV__getInsertionPoint(index, orientation) {
     var container = this._result.root;
     var dropNearItemId = -1;
     // When there's no selection, assume the container is the container
     // the view is populated from (i.e. the result's itemId).
     if (index != -1) {
       var lastSelected = this.nodeForTreeIndex(index);
       if (this.isContainer(index) && orientation == Ci.nsITreeView.DROP_ON) {
         // If the last selected item is an open container, append _into_
         // it, rather than insert adjacent to it. 
         container = lastSelected;
         index = -1;
       }
-      else if (!this._disallowInsertion(lastSelected) &&
-               lastSelected.containerOpen &&
+      else if (lastSelected.containerOpen &&
                orientation == Ci.nsITreeView.DROP_AFTER &&
                lastSelected.hasChildren) {
         // If the last selected item is an open container and the user is
         // trying to drag into it as a first item, really insert into it.
         container = lastSelected;
-        orientation = Ci.nsITreeView.DROP_BEFORE;
+        orientation = Ci.nsITreeView.DROP_ON;
         index = 0;
       }
       else {
         // Use the last-selected node's container unless the root node
         // is selected, in which case we use the root node itself as the
         // insertion point.
         container = lastSelected.parent || container;
 
         // avoid the potentially expensive call to getIndexOfNode() 
         // if we know this container doesn't allow insertion
-        if (this._disallowInsertion(container))
+        if (PlacesControllerDragHelper.disallowInsertion(container))
           return null;
 
         var queryOptions = asQuery(this._result.root).queryOptions;
-        if (queryOptions.sortingMode != Ci.nsINavHistoryQueryOptions.SORT_BY_NONE) {
-          // If we are within a sorted view, insert at the end
+        if (queryOptions.sortingMode !=
+              Ci.nsINavHistoryQueryOptions.SORT_BY_NONE) {
+          // If we are within a sorted view, insert at the ends
           index = -1;
         }
         else if (queryOptions.excludeItems ||
                  queryOptions.excludeQueries ||
                  queryOptions.excludeReadOnlyFolders) {
           // Some item may be invisible, insert near last selected one.
           // We don't replace index here to avoid requests to the db,
           // instead it will be calculated later by the controller.
@@ -1075,32 +1054,32 @@ PlacesTreeView.prototype = {
         }
         else {
           var lsi = PlacesUtils.getIndexOfNode(lastSelected);
           index = orientation == Ci.nsITreeView.DROP_BEFORE ? lsi : lsi + 1;
         }
       }
     }
 
-    if (this._disallowInsertion(container))
+    if (PlacesControllerDragHelper.disallowInsertion(container))
       return null;
 
     return new InsertionPoint(PlacesUtils.getConcreteItemId(container),
                               index, orientation,
                               PlacesUtils.nodeIsTagQuery(container),
                               dropNearItemId);
   },
 
   drop: function PTV_drop(aRow, aOrientation) {
     // We are responsible for translating the |index| and |orientation| 
     // parameters into a container id and index within the container, 
     // since this information is specific to the tree view.
     var ip = this._getInsertionPoint(aRow, aOrientation);
     if (!ip)
-      throw Cr.NS_ERROR_NOT_AVAILABLE;
+      return;
     PlacesControllerDragHelper.onDrop(ip);
   },
 
   getParentIndex: function PTV_getParentIndex(aRow) {
     this._ensureValidRow(aRow);
     var parent = this._visibleElements[aRow].node.parent;
     if (!parent || parent.viewIndex < 0)
       return -1;
--- a/browser/components/places/content/utils.js
+++ b/browser/components/places/content/utils.js
@@ -19,16 +19,17 @@
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
  *   Ben Goodger <beng@google.com>
  *   Myk Melez <myk@mozilla.org>
  *   Asaf Romano <mano@mozilla.com>
  *   Sungjoon Steve Won <stevewon@gmail.com>
  *   Dietrich Ayala <dietrich@mozilla.com>
+ *   Marco Bonardo <mak77@bonardo.net>
  *
  * Alternatively, the contents of this file may be used under the terms of
  * either the GNU General Public License Version 2 or later (the "GPL"), or
  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  * in which case the provisions of the GPL or the LGPL are applicable instead
  * of those above. If you wish to allow use of your version of this file only
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
@@ -372,20 +373,22 @@ var PlacesUIUtils = {
         // There is no data in a separator, so copying it just amounts to
         // inserting a new separator.
         if (copy)
           return this.ptm.createSeparator(container, index);
         // Move the separator otherwise
         return this.ptm.moveItem(data.id, container, index);
         break;
       default:
-        if (type == PlacesUtils.TYPE_X_MOZ_URL || type == PlacesUtils.TYPE_UNICODE) {
-          var title = (type == PlacesUtils.TYPE_X_MOZ_URL) ? data.title : data.uri;
-          return this.ptm.createItem(PlacesUtils._uri(data.uri), container, index,
-                                     title);
+        if (type == PlacesUtils.TYPE_X_MOZ_URL ||
+            type == PlacesUtils.TYPE_UNICODE) {
+          var title = (type == PlacesUtils.TYPE_X_MOZ_URL) ? data.title :
+                                                             data.uri;
+          return this.ptm.createItem(PlacesUtils._uri(data.uri),
+                                     container, index, title);
         }
     }
     return null;
   },
 
   /**
    * Methods to show the bookmarkProperties dialog in its various modes.
    *
@@ -1030,60 +1033,54 @@ var PlacesUIUtils = {
     }
     element.node = aNode;
     element.node.viewIndex = 0;
 
     return element;
   },
 
   cleanPlacesPopup: function PU_cleanPlacesPopup(aPopup) {
-    // Find static menuitems at the start and at the end of the menupopup,
-    // marked by builder="start" and builder="end" attributes, and set
-    // markers to keep track of their indices.
+    // Remove places popup children and update markers to keep track of
+    // their indices.
+    var start = aPopup._startMarker != -1 ? aPopup._startMarker + 1 : 0;
+    var end = aPopup._endMarker != -1 ? aPopup._endMarker :
+                                        aPopup.childNodes.length;
     var items = [];
-    aPopup._startMarker = -1;
-    aPopup._endMarker = -1;
-    for (var i = 0; i < aPopup.childNodes.length; ++i) {
+    var placesNodeFound = false;
+    for (var i = start; i < end; ++i) {
       var item = aPopup.childNodes[i];
-      if (item.getAttribute("builder") == "start") {
-        aPopup._startMarker = i;
-        continue;
-      }
       if (item.getAttribute("builder") == "end") {
+        // we need to do this for menus that have static content at the end but
+        // are initially empty, eg. the history menu, we need to know where to
+        // start inserting new items.
         aPopup._endMarker = i;
-        continue;
+        break;
       }
-      if ((aPopup._startMarker != -1) && (aPopup._endMarker == -1))
+      if (item.node) {
         items.push(item);
-    }
-
-    // If static items at the beginning were found, remove all items between
-    // them and the static content at the end.
-    for (var i = 0; i < items.length; ++i) {
-      // skip the empty menu item
-      if (aPopup._emptyMenuItem != items[i]) {
-        aPopup.removeChild(items[i]);
-        if (aPopup._endMarker > 0)
-          --aPopup._endMarker;
+        placesNodeFound = true;
+      }
+      else {
+        // This is static content...
+        if (!placesNodeFound)
+          // ...at the start of the popup
+          // Initialized in menu.xml, in the base binding
+          aPopup._startMarker++;
+        else {
+          // ...after places nodes
+          aPopup._endMarker = i;
+          break;
+        }
       }
     }
 
-    // If no static items were found at the beginning, remove all items before
-    // the static items at the end.
-    if (aPopup._startMarker == -1) {
-      var end = aPopup._endMarker == -1 ?
-                aPopup.childNodes.length - 1 : aPopup._endMarker - 1;
-      for (var i = end; i >= 0; i--) {
-        // skip the empty menu item
-        if (aPopup._emptyMenuItem != aPopup.childNodes[i]) {
-          aPopup.removeChild(aPopup.childNodes[i]);
-          if (aPopup._endMarker > 0)
-            --aPopup._endMarker;
-        }
-      }
+    for (var i = 0; i < items.length; ++i) {
+      aPopup.removeChild(items[i]);
+      if (aPopup._endMarker != -1)
+        aPopup._endMarker--;
     }
   },
 
   getBestTitle: function PU_getBestTitle(aNode) {
     var title;
     if (!aNode.title && PlacesUtils.uriTypes.indexOf(aNode.type) != -1) {
       // if node title is empty, try to set the label using host and filename
       // PlacesUtils._uri() will throw if aNode.uri is not a valid URI
@@ -1227,18 +1224,8 @@ var PlacesUIUtils = {
 
   get allBookmarksFolderId() {
     // ensure the left-pane root is initialized;
     this.leftPaneFolderId;
     delete this.allBookmarksFolderId;
     return this.allBookmarksFolderId = this.leftPaneQueries["AllBookmarks"];
   }
 };
-
-PlacesUIUtils.placesFlavors = [PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER,
-                             PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR,
-                             PlacesUtils.TYPE_X_MOZ_PLACE];
-
-PlacesUIUtils.GENERIC_VIEW_DROP_TYPES = [PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER,
-                                       PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR,
-                                       PlacesUtils.TYPE_X_MOZ_PLACE,
-                                       PlacesUtils.TYPE_X_MOZ_URL,
-                                       PlacesUtils.TYPE_UNICODE];
--- a/browser/components/places/src/nsPlacesTransactionsService.js
+++ b/browser/components/places/src/nsPlacesTransactionsService.js
@@ -291,18 +291,21 @@ placesAggregateTransactions.prototype = 
       };
       PlacesUtils.bookmarks.runInBatchMode(callback, null);
     }
     else
       this.commit(true);
   },
 
   commit: function PAT_commit(aUndo) {
-    for (var i=0; i < this._transactions.length; ++i) {
-      var txn = this._transactions[i];
+    var transactions = this._transactions;
+    if (aUndo)
+      transactions.reverse();
+    for (var i = 0; i < transactions.length; i++) {
+      var txn = transactions[i];
       if (this.container > -1) 
         txn.wrappedJSObject.container = this.container;
       if (aUndo)
         txn.undoTransaction();
       else
         txn.doTransaction();
     }
   }
@@ -392,16 +395,17 @@ placesCreateItemTransactions.prototype =
     }
   }
 };
 
 function placesCreateSeparatorTransactions(aContainer, aIndex) {
   this._container = aContainer;
   this._index = typeof(aIndex) == "number" ? aIndex : -1;
   this._id = null;
+  this.redoTransaction = this.doTransaction;
 }
 
 placesCreateSeparatorTransactions.prototype = {
   __proto__: placesBaseTransaction.prototype,
 
   // childItemsTransaction support
   get container() { return this._container; },
   set container(val) { return this._container = val; },
@@ -445,37 +449,35 @@ placesCreateLivemarkTransactions.prototy
   undoTransaction: function PCLT_undoTransaction() {
     PlacesUtils.bookmarks.removeFolder(this._id);
   }
 };
 
 function placesMoveItemTransactions(aItemId, aNewContainer, aNewIndex) {
   this._id = aItemId;
   this._oldContainer = PlacesUtils.bookmarks.getFolderIdForItem(this._id);
-  this._oldIndex = PlacesUtils.bookmarks.getItemIndex(this._id);
   this._newContainer = aNewContainer;
   this._newIndex = aNewIndex;
   this.redoTransaction = this.doTransaction;
 }
 
 placesMoveItemTransactions.prototype = {
   __proto__: placesBaseTransaction.prototype,
 
   doTransaction: function PMIT_doTransaction() {
+    this._oldIndex = PlacesUtils.bookmarks.getItemIndex(this._id);
     PlacesUtils.bookmarks.moveItem(this._id, this._newContainer, this._newIndex);
-    // if newIndex == DEFAULT_INDEX we append, so get correct index for undo
-    if (this._newIndex == PlacesUtils.bookmarks.DEFAULT_INDEX)
-      this._newIndex = PlacesUtils.bookmarks.getItemIndex(this._id);
+    this._undoIndex = PlacesUtils.bookmarks.getItemIndex(this._id);
   },
 
   undoTransaction: function PMIT_undoTransaction() {
     // moving down in the same container takes in count removal of the item
     // so to revert positions we must move to oldIndex + 1
     if (this._newContainer == this._oldContainer &&
-        this._oldIndex > this._newIndex)
+        this._oldIndex > this._undoIndex)
       PlacesUtils.bookmarks.moveItem(this._id, this._oldContainer, this._oldIndex + 1);
     else
       PlacesUtils.bookmarks.moveItem(this._id, this._oldContainer, this._oldIndex);
   }
 };
 
 function placesRemoveItemTransaction(aItemId) {
   this.redoTransaction = this.doTransaction;
@@ -536,17 +538,17 @@ placesRemoveItemTransaction.prototype = 
     }
     else if (this._itemType == Ci.nsINavBookmarksService.TYPE_FOLDER) {
       this._removeTxn.undoTransaction();
       // Create children forwards to preserve parent-child relationships.
       for (var i = 0; i < this._transactions.length; ++i)
         this._transactions[i].undoTransaction();
     }
     else // TYPE_SEPARATOR
-      PlacesUtils.bookmarks.insertSeparator(this._oldContainer, this._oldIndex);
+      this._id = PlacesUtils.bookmarks.insertSeparator(this._oldContainer, this._oldIndex);
 
     if (this._annotations.length > 0)
       PlacesUtils.setAnnotationsForItem(this._id, this._annotations);
 
     PlacesUtils.bookmarks.setItemDateAdded(this._id, this._dateAdded);
     PlacesUtils.bookmarks.setItemLastModified(this._id, this._lastModified);
   },
 
--- a/browser/components/places/tests/browser/browser_423515.js
+++ b/browser/components/places/tests/browser/browser_423515.js
@@ -56,17 +56,17 @@ function test() {
       this.id =
         PlacesUtils.bookmarks.createFolder(rootId, "", IDX);
     },
     validate: function() {
       is(rootNode.childCount, 1,
         "populate added data to the test root");
       is(PlacesControllerDragHelper.canMoveContainer(this.id),
          true, "can move regular folder id");
-      is(PlacesControllerDragHelper.canMoveContainerNode(rootNode.getChild(0)),
+      is(PlacesControllerDragHelper.canMoveNode(rootNode.getChild(0)),
          true, "can move regular folder node");
     }
   });
 
   // add a regular folder shortcut, should be moveable
   tests.push({
     populate: function() {
       this.folderId =
@@ -87,17 +87,17 @@ function test() {
       is(this.shortcutId, shortcutNode.itemId, "shortcut id and shortcut node item id match");
 
       var concreteId = PlacesUtils.getConcreteItemId(shortcutNode);
       is(concreteId, folderNode.itemId, "shortcut node id and concrete id match");
 
       is(PlacesControllerDragHelper.canMoveContainer(this.shortcutId),
          true, "can move folder shortcut id");
 
-      is(PlacesControllerDragHelper.canMoveContainerNode(shortcutNode),
+      is(PlacesControllerDragHelper.canMoveNode(shortcutNode),
          true, "can move folder shortcut node");
     }
   });
 
   // add a regular query, should be moveable
   tests.push({
     populate: function() {
       this.bookmarkId =
@@ -113,17 +113,17 @@ function test() {
       is(bmNode.itemId, this.bookmarkId, "bookmark id and bookmark node item id match");
 
       var queryNode = rootNode.getChild(1);
       is(queryNode.itemId, this.queryId, "query id and query node item id match");
 
       is(PlacesControllerDragHelper.canMoveContainer(this.queryId),
          true, "can move query id");
 
-      is(PlacesControllerDragHelper.canMoveContainerNode(queryNode),
+      is(PlacesControllerDragHelper.canMoveNode(queryNode),
          true, "can move query node");
     }
   });
 
   // test that special folders cannot be moved
   // test that special folders shortcuts can be moved
   tests.push({
     folders: [PlacesUtils.bookmarksMenuFolderId,
@@ -154,30 +154,30 @@ function test() {
       for (var i = 0; i < this.folders.length; i++) {
         var id = this.folders[i];
 
         is(PlacesControllerDragHelper.canMoveContainer(id),
            false, "shouldn't be able to move special folder id");
 
         //var node = PlacesUtils.getFolderContents(id, false, true).root;
         var node = getRootChildNode(id);
-        is(PlacesControllerDragHelper.canMoveContainerNode(node),
+        is(PlacesControllerDragHelper.canMoveNode(node),
            false, "shouldn't be able to move special folder node");
 
         var shortcutId = this.shortcuts[id];
         var shortcutNode = rootNode.getChild(i);
 
         is(shortcutNode.itemId, shortcutId, "shortcut id and shortcut node item id match");
 
         LOG("can move shortcut id?");
         is(PlacesControllerDragHelper.canMoveContainer(shortcutId),
            true, "should be able to move special folder shortcut id");
 
         LOG("can move shortcut node?");
-        is(PlacesControllerDragHelper.canMoveContainerNode(shortcutNode),
+        is(PlacesControllerDragHelper.canMoveNode(shortcutNode),
            true, "should be able to move special folder shortcut node");
       }
     }
   });
 
   // test that a tag container cannot be moved
   tests.push({
     populate: function() {
@@ -192,17 +192,17 @@ function test() {
       options.resultType = Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_QUERY;
       var tagsNode = PlacesUtils.history.executeQuery(query, options).root;
 
       tagsNode.containerOpen = true;
       is(tagsNode.childCount, 1, "has new tag");
 
       var tagNode = tagsNode.getChild(0);
       
-      is(PlacesControllerDragHelper.canMoveContainerNode(tagNode),
+      is(PlacesControllerDragHelper.canMoveNode(tagNode),
          false, "should not be able to move tag container node");
     }
   });
 
   // test that any child of a read-only node cannot be moved
   tests.push({
     populate: function() {
       this.id =
@@ -213,27 +213,27 @@ function test() {
     validate: function() {
       is(rootNode.childCount, 1,
         "populate added data to the test root");
       var readOnlyFolder = rootNode.getChild(0);
 
       // test that we can move the read-only folder
       is(PlacesControllerDragHelper.canMoveContainer(this.id),
          true, "can move read-only folder id");
-      is(PlacesControllerDragHelper.canMoveContainerNode(readOnlyFolder),
+      is(PlacesControllerDragHelper.canMoveNode(readOnlyFolder),
          true, "can move read-only folder node");
 
       // test that we cannot move the child of a read-only folder
       readOnlyFolder.QueryInterface(Ci.nsINavHistoryContainerResultNode);
       readOnlyFolder.containerOpen = true;
       var childFolder = readOnlyFolder.getChild(0);
 
       is(PlacesControllerDragHelper.canMoveContainer(childFolder.itemId),
          false, "cannot move a child of a read-only folder");
-      is(PlacesControllerDragHelper.canMoveContainerNode(childFolder),
+      is(PlacesControllerDragHelper.canMoveNode(childFolder),
          false, "cannot move a child node of a read-only folder node");
     }
   });
 
   tests.forEach(function(aTest) {
     PlacesUtils.bookmarks.removeFolderChildren(rootId);
     aTest.populate();
     aTest.validate();
--- a/browser/components/places/tests/unit/test_placesTxn.js
+++ b/browser/components/places/tests/unit/test_placesTxn.js
@@ -146,46 +146,74 @@ function run_test() {
               annotationService.getItemAnnotation(folderId, DESCRIPTION_ANNO));
   do_check_eq(observer._itemAddedIndex, bmStartIndex);
   do_check_eq(observer._itemAddedParent, root);
   do_check_eq(observer._itemAddedId, folderId);
   txn1.undoTransaction();
   do_check_eq(observer._itemRemovedId, folderId);
   do_check_eq(observer._itemRemovedFolder, root);
   do_check_eq(observer._itemRemovedIndex, bmStartIndex);
+  txn1.redoTransaction();
+  do_check_eq(observer._itemAddedIndex, bmStartIndex);
+  do_check_eq(observer._itemAddedParent, root);
+  do_check_eq(observer._itemAddedId, folderId);
+  txn1.undoTransaction();
+  do_check_eq(observer._itemRemovedId, folderId);
+  do_check_eq(observer._itemRemovedFolder, root);
+  do_check_eq(observer._itemRemovedIndex, bmStartIndex);
 
   // Test creating an item
   // Create to Root
   var txn2 = ptSvc.createItem(uri("http://www.example.com"), root, bmStartIndex, "Testing1");
   ptSvc.doTransaction(txn2); //Also testing doTransaction
   var b = (bmsvc.getBookmarkIdsForURI(uri("http://www.example.com"), {}))[0];
   do_check_eq(observer._itemAddedId, b);
   do_check_eq(observer._itemAddedIndex, bmStartIndex);
   do_check_true(bmsvc.isBookmarked(uri("http://www.example.com")));
   txn2.undoTransaction();
   do_check_eq(observer._itemRemovedId, b);
   do_check_eq(observer._itemRemovedIndex, bmStartIndex);
+  do_check_false(bmsvc.isBookmarked(uri("http://www.example.com")));
+  txn2.redoTransaction();
+  do_check_true(bmsvc.isBookmarked(uri("http://www.example.com")));
+  var newId = (bmsvc.getBookmarkIdsForURI(uri("http://www.example.com"), {}))[0];
+  do_check_eq(observer._itemAddedIndex, bmStartIndex);
+  do_check_eq(observer._itemAddedParent, root);
+  do_check_eq(observer._itemAddedId, newId);
+  txn2.undoTransaction();
+  do_check_eq(observer._itemRemovedId, newId);
+  do_check_eq(observer._itemRemovedFolder, root);
+  do_check_eq(observer._itemRemovedIndex, bmStartIndex);
 
-  // Create to a folder
+  // Create item to a folder
   var txn2a = ptSvc.createFolder("Folder", root, bmStartIndex);
   ptSvc.doTransaction(txn2a);
   var fldrId = bmsvc.getChildFolder(root, "Folder");
   var txn2b = ptSvc.createItem(uri("http://www.example2.com"), fldrId, bmStartIndex, "Testing1b");
   ptSvc.doTransaction(txn2b);
   var b2 = (bmsvc.getBookmarkIdsForURI(uri("http://www.example2.com"), {}))[0];
   do_check_eq(observer._itemAddedId, b2);
   do_check_eq(observer._itemAddedIndex, bmStartIndex);
   do_check_true(bmsvc.isBookmarked(uri("http://www.example2.com")));
   txn2b.undoTransaction();
   do_check_eq(observer._itemRemovedId, b2);
   do_check_eq(observer._itemRemovedIndex, bmStartIndex);
+  txn2b.redoTransaction();
+  newId = (bmsvc.getBookmarkIdsForURI(uri("http://www.example2.com"), {}))[0];
+  do_check_eq(observer._itemAddedIndex, bmStartIndex);
+  do_check_eq(observer._itemAddedParent, fldrId);
+  do_check_eq(observer._itemAddedId, newId);
+  txn2b.undoTransaction();
+  do_check_eq(observer._itemRemovedId, newId);
+  do_check_eq(observer._itemRemovedFolder, fldrId);
+  do_check_eq(observer._itemRemovedIndex, bmStartIndex);
 
   // Testing moving an item
   ptSvc.doTransaction(ptSvc.createItem(uri("http://www.example3.com"), root, -1, "Testing2"));
-  ptSvc.doTransaction(ptSvc.createItem(uri("http://www.example3.com"), root, -1, "Testing3"));   
+  ptSvc.doTransaction(ptSvc.createItem(uri("http://www.example3.com"), root, -1, "Testing3"));
   ptSvc.doTransaction(ptSvc.createItem(uri("http://www.example3.com"), fldrId, -1, "Testing4"));
   var bkmkIds = bmsvc.getBookmarkIdsForURI(uri("http://www.example3.com"), {});
   bkmkIds.sort();
   var bkmk1Id = bkmkIds[0];
   var bkmk2Id = bkmkIds[1];
   var bkmk3Id = bkmkIds[2];
 
   // Moving items between the same folder
@@ -197,100 +225,172 @@ function run_test() {
   do_check_eq(observer._itemMovedNewParent, root);
   do_check_eq(observer._itemMovedNewIndex, 2);
   txn3.undoTransaction();
   do_check_eq(observer._itemMovedId, bkmk1Id);
   do_check_eq(observer._itemMovedOldParent, root);
   do_check_eq(observer._itemMovedOldIndex, 2);
   do_check_eq(observer._itemMovedNewParent, root);
   do_check_eq(observer._itemMovedNewIndex, 1);
+  txn3.redoTransaction();
+  do_check_eq(observer._itemMovedId, bkmk1Id);
+  do_check_eq(observer._itemMovedOldParent, root);
+  do_check_eq(observer._itemMovedOldIndex, 1);
+  do_check_eq(observer._itemMovedNewParent, root);
+  do_check_eq(observer._itemMovedNewIndex, 2);
+  txn3.undoTransaction();
+  do_check_eq(observer._itemMovedId, bkmk1Id);
+  do_check_eq(observer._itemMovedOldParent, root);
+  do_check_eq(observer._itemMovedOldIndex, 2);
+  do_check_eq(observer._itemMovedNewParent, root);
+  do_check_eq(observer._itemMovedNewIndex, 1);
 
   // Moving items between different folders
   var txn3b = ptSvc.moveItem(bkmk1Id, fldrId, -1);
   txn3b.doTransaction();
   do_check_eq(observer._itemMovedId, bkmk1Id);
   do_check_eq(observer._itemMovedOldParent, root);
   do_check_eq(observer._itemMovedOldIndex, 1);
   do_check_eq(observer._itemMovedNewParent, fldrId);
   do_check_eq(observer._itemMovedNewIndex, 1);
   txn3.undoTransaction();
   do_check_eq(observer._itemMovedId, bkmk1Id);
   do_check_eq(observer._itemMovedOldParent, fldrId);
   do_check_eq(observer._itemMovedOldIndex, 1);
   do_check_eq(observer._itemMovedNewParent, root);
   do_check_eq(observer._itemMovedNewIndex, 1);
+  txn3b.redoTransaction();
+  do_check_eq(observer._itemMovedId, bkmk1Id);
+  do_check_eq(observer._itemMovedOldParent, root);
+  do_check_eq(observer._itemMovedOldIndex, 1);
+  do_check_eq(observer._itemMovedNewParent, fldrId);
+  do_check_eq(observer._itemMovedNewIndex, 1);
+  txn3.undoTransaction();
+  do_check_eq(observer._itemMovedId, bkmk1Id);
+  do_check_eq(observer._itemMovedOldParent, fldrId);
+  do_check_eq(observer._itemMovedOldIndex, 1);
+  do_check_eq(observer._itemMovedNewParent, root);
+  do_check_eq(observer._itemMovedNewIndex, 1);
 
   // Test Removing a Folder
   ptSvc.doTransaction(ptSvc.createFolder("Folder2", root, -1));
   var fldrId2 = bmsvc.getChildFolder(root, "Folder2");
   var txn4 = ptSvc.removeItem(fldrId2);
   txn4.doTransaction();
   do_check_eq(observer._itemRemovedId, fldrId2);
   do_check_eq(observer._itemRemovedFolder, root);
   do_check_eq(observer._itemRemovedIndex, 3);
   txn4.undoTransaction();
   do_check_eq(observer._itemAddedId, fldrId2);
   do_check_eq(observer._itemAddedParent, root);
   do_check_eq(observer._itemAddedIndex, 3);
+  txn4.redoTransaction();
+  do_check_eq(observer._itemRemovedId, fldrId2);
+  do_check_eq(observer._itemRemovedFolder, root);
+  do_check_eq(observer._itemRemovedIndex, 3);
+  txn4.undoTransaction();
+  do_check_eq(observer._itemAddedId, fldrId2);
+  do_check_eq(observer._itemAddedParent, root);
+  do_check_eq(observer._itemAddedIndex, 3);
 
   // Test removing an item
   var txn5 = ptSvc.removeItem(bkmk2Id);
   txn5.doTransaction();
   do_check_eq(observer._itemRemovedId, bkmk2Id);
   do_check_eq(observer._itemRemovedFolder, root);
   do_check_eq(observer._itemRemovedIndex, 2);
   txn5.undoTransaction();
+  var newbkmk2Id = observer._itemAddedId;
+  do_check_eq(observer._itemAddedParent, root);
+  do_check_eq(observer._itemAddedIndex, 2);
+  txn5.redoTransaction();
+  do_check_eq(observer._itemRemovedId, newbkmk2Id);
+  do_check_eq(observer._itemRemovedFolder, root);
+  do_check_eq(observer._itemRemovedIndex, 2);
+  txn5.undoTransaction();
   do_check_eq(observer._itemAddedParent, root);
   do_check_eq(observer._itemAddedIndex, 2);
 
   // Test creating a separator
   var txn6 = ptSvc.createSeparator(root, 1);
   txn6.doTransaction();
   var sepId = observer._itemAddedId;
   do_check_eq(observer._itemAddedIndex, 1);
   do_check_eq(observer._itemAddedParent, root);
   txn6.undoTransaction();
   do_check_eq(observer._itemRemovedId, sepId);
   do_check_eq(observer._itemRemovedFolder, root);
   do_check_eq(observer._itemRemovedIndex, 1);
+  txn6.redoTransaction();
+  var newSepId = observer._itemAddedId;
+  do_check_eq(observer._itemAddedIndex, 1);
+  do_check_eq(observer._itemAddedParent, root);
+  txn6.undoTransaction();
+  do_check_eq(observer._itemRemovedId, newSepId);
+  do_check_eq(observer._itemRemovedFolder, root);
+  do_check_eq(observer._itemRemovedIndex, 1);
 
   // Test removing a separator
   ptSvc.doTransaction(ptSvc.createSeparator(root, 1));
   var sepId2 = observer._itemAddedId;
   var txn7 = ptSvc.removeItem(sepId2);
   txn7.doTransaction();
   do_check_eq(observer._itemRemovedId, sepId2);
   do_check_eq(observer._itemRemovedFolder, root);
   do_check_eq(observer._itemRemovedIndex, 1);
   txn7.undoTransaction();
   do_check_eq(observer._itemAddedId, sepId2); //New separator created
   do_check_eq(observer._itemAddedParent, root);
   do_check_eq(observer._itemAddedIndex, 1);
+  txn7.redoTransaction();
+  do_check_eq(observer._itemRemovedId, sepId2);
+  do_check_eq(observer._itemRemovedFolder, root);
+  do_check_eq(observer._itemRemovedIndex, 1);
+  txn7.undoTransaction();
+  do_check_eq(observer._itemAddedId, sepId2); //New separator created
+  do_check_eq(observer._itemAddedParent, root);
+  do_check_eq(observer._itemAddedIndex, 1);
 
   // Test editing item title
   var txn8 = ptSvc.editItemTitle(bkmk1Id, "Testing2_mod");
   txn8.doTransaction();
   do_check_eq(observer._itemChangedId, bkmk1Id); 
   do_check_eq(observer._itemChangedProperty, "title");
   do_check_eq(observer._itemChangedValue, "Testing2_mod");
   txn8.undoTransaction();
   do_check_eq(observer._itemChangedId, bkmk1Id); 
   do_check_eq(observer._itemChangedProperty, "title");
   do_check_eq(observer._itemChangedValue, "Testing2");
+  txn8.redoTransaction();
+  do_check_eq(observer._itemChangedId, bkmk1Id); 
+  do_check_eq(observer._itemChangedProperty, "title");
+  do_check_eq(observer._itemChangedValue, "Testing2_mod");
+  txn8.undoTransaction();
+  do_check_eq(observer._itemChangedId, bkmk1Id); 
+  do_check_eq(observer._itemChangedProperty, "title");
+  do_check_eq(observer._itemChangedValue, "Testing2");
 
   // Test editing item uri
   var txn9 = ptSvc.editBookmarkURI(bkmk1Id, uri("http://newuri.com"));
   txn9.doTransaction();
   do_check_eq(observer._itemChangedId, bkmk1Id);
   do_check_eq(observer._itemChangedProperty, "uri");
   do_check_eq(observer._itemChangedValue, "http://newuri.com/");
   txn9.undoTransaction();
   do_check_eq(observer._itemChangedId, bkmk1Id);
   do_check_eq(observer._itemChangedProperty, "uri");
   do_check_eq(observer._itemChangedValue, "http://www.example3.com/");
+  txn9.redoTransaction();
+  do_check_eq(observer._itemChangedId, bkmk1Id);
+  do_check_eq(observer._itemChangedProperty, "uri");
+  do_check_eq(observer._itemChangedValue, "http://newuri.com/");
+  txn9.undoTransaction();
+  do_check_eq(observer._itemChangedId, bkmk1Id);
+  do_check_eq(observer._itemChangedProperty, "uri");
+  do_check_eq(observer._itemChangedValue, "http://www.example3.com/");
   
   // Test edit item description
   var txn10 = ptSvc.editItemDescription(bkmk1Id, "Description1");
   txn10.doTransaction();
   do_check_eq(observer._itemChangedId, bkmk1Id);
   do_check_eq(observer._itemChangedProperty, "bookmarkProperties/description");
 
   // Testing edit keyword
@@ -366,16 +466,24 @@ function run_test() {
   txn17.doTransaction();
   do_check_eq(2, bmsvc.getItemIndex(b1));
   do_check_eq(1, bmsvc.getItemIndex(b2));
   do_check_eq(0, bmsvc.getItemIndex(b3));
   txn17.undoTransaction();
   do_check_eq(0, bmsvc.getItemIndex(b1));
   do_check_eq(1, bmsvc.getItemIndex(b2));
   do_check_eq(2, bmsvc.getItemIndex(b3));
+  txn17.redoTransaction();
+  do_check_eq(2, bmsvc.getItemIndex(b1));
+  do_check_eq(1, bmsvc.getItemIndex(b2));
+  do_check_eq(0, bmsvc.getItemIndex(b3));
+  txn17.undoTransaction();
+  do_check_eq(0, bmsvc.getItemIndex(b1));
+  do_check_eq(1, bmsvc.getItemIndex(b2));
+  do_check_eq(2, bmsvc.getItemIndex(b3));
 
   // editBookmarkMicrosummary
   var tmpMs = mss.createMicrosummary(uri("http://testmicro.com"), 
                                      uri("http://dietrich.ganx4.com/mozilla/test-microsummary.xml"));
   ptSvc.doTransaction(
   ptSvc.createItem(uri("http://dietrich.ganx4.com/mozilla/test-microsummary-content.php"),
                    root, -1, "micro test", null, null, null));
   var bId = (bmsvc.getBookmarkIdsForURI(uri("http://dietrich.ganx4.com/mozilla/test-microsummary-content.php"),{}))[0];
@@ -431,9 +539,81 @@ function run_test() {
   do_check_eq(uneval(tagssvc.getTagsForURI(tagURI, { })), uneval(["bar","foo"]));
   var untagTxn = ptSvc.untagURI(tagURI, ["bar"]);
   untagTxn.doTransaction();
   do_check_eq(uneval(tagssvc.getTagsForURI(tagURI, { })), uneval(["foo"]));
   untagTxn.undoTransaction();
   do_check_eq(uneval(tagssvc.getTagsForURI(tagURI, { })), uneval(["bar","foo"]));
   untagTxn.redoTransaction();
   do_check_eq(uneval(tagssvc.getTagsForURI(tagURI, { })), uneval(["foo"]));
+
+  // Test aggregate removeItem transaction
+  var bkmk1Id = bmsvc.insertBookmark(root, uri("http://www.mozilla.org/"), 0, "Mozilla");
+  var bkmk2Id = bmsvc.insertSeparator(root, 1);
+  var bkmk3Id = bmsvc.createFolder(root, "folder", 2);
+  var bkmk3_1Id = bmsvc.insertBookmark(bkmk3Id, uri("http://www.mozilla.org/"), 0, "Mozilla");
+  var bkmk3_2Id = bmsvc.insertSeparator(bkmk3Id, 1);
+  var bkmk3_3Id = bmsvc.createFolder(bkmk3Id, "folder", 2);
+
+  var transactions = [];
+  transactions.push(ptSvc.removeItem(bkmk1Id));
+  transactions.push(ptSvc.removeItem(bkmk2Id));
+  transactions.push(ptSvc.removeItem(bkmk3Id));
+  var txn = ptSvc.aggregateTransactions("RemoveItems", transactions);
+
+  txn.doTransaction();
+  do_check_eq(bmsvc.getItemIndex(bkmk1Id), -1);
+  do_check_eq(bmsvc.getItemIndex(bkmk2Id), -1);
+  do_check_eq(bmsvc.getItemIndex(bkmk3Id), -1);
+  do_check_eq(bmsvc.getItemIndex(bkmk3_1Id), -1);
+  do_check_eq(bmsvc.getItemIndex(bkmk3_2Id), -1);
+  do_check_eq(bmsvc.getItemIndex(bkmk3_3Id), -1);
+
+  txn.undoTransaction();
+  var newBkmk1Id = bmsvc.getIdForItemAt(root, 0);
+  var newBkmk2Id = bmsvc.getIdForItemAt(root, 1);
+  var newBkmk3Id = bmsvc.getIdForItemAt(root, 2);
+  var newBkmk3_1Id = bmsvc.getIdForItemAt(newBkmk3Id, 0);
+  var newBkmk3_2Id = bmsvc.getIdForItemAt(newBkmk3Id, 1);
+  var newBkmk3_3Id = bmsvc.getIdForItemAt(newBkmk3Id, 2);
+  do_check_eq(bmsvc.getItemType(newBkmk1Id), bmsvc.TYPE_BOOKMARK);
+  do_check_eq(bmsvc.getBookmarkURI(newBkmk1Id).spec, "http://www.mozilla.org/");
+  do_check_eq(bmsvc.getItemType(newBkmk2Id), bmsvc.TYPE_SEPARATOR);
+  do_check_eq(bmsvc.getItemType(newBkmk3Id), bmsvc.TYPE_FOLDER);
+  do_check_eq(bmsvc.getItemTitle(newBkmk3Id), "folder");
+  do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_1Id), newBkmk3Id);
+  do_check_eq(bmsvc.getItemType(newBkmk3_1Id), bmsvc.TYPE_BOOKMARK);
+  do_check_eq(bmsvc.getBookmarkURI(newBkmk3_1Id).spec, "http://www.mozilla.org/");
+  do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_2Id), newBkmk3Id);
+  do_check_eq(bmsvc.getItemType(newBkmk3_2Id), bmsvc.TYPE_SEPARATOR);
+  do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_3Id), newBkmk3Id);
+  do_check_eq(bmsvc.getItemType(newBkmk3_3Id), bmsvc.TYPE_FOLDER);
+  do_check_eq(bmsvc.getItemTitle(newBkmk3_3Id), "folder");
+
+  txn.redoTransaction();
+  do_check_eq(bmsvc.getItemIndex(newBkmk1Id), -1);
+  do_check_eq(bmsvc.getItemIndex(newBkmk2Id), -1);
+  do_check_eq(bmsvc.getItemIndex(newBkmk3Id), -1);
+  do_check_eq(bmsvc.getItemIndex(newBkmk3_1Id), -1);
+  do_check_eq(bmsvc.getItemIndex(newBkmk3_2Id), -1);
+  do_check_eq(bmsvc.getItemIndex(newBkmk3_3Id), -1);
+
+  txn.undoTransaction();
+  newBkmk1Id = bmsvc.getIdForItemAt(root, 0);
+  newBkmk2Id = bmsvc.getIdForItemAt(root, 1);
+  newBkmk3Id = bmsvc.getIdForItemAt(root, 2);
+  newBkmk3_1Id = bmsvc.getIdForItemAt(newBkmk3Id, 0);
+  newBkmk3_2Id = bmsvc.getIdForItemAt(newBkmk3Id, 1);
+  newBkmk3_3Id = bmsvc.getIdForItemAt(newBkmk3Id, 2);
+  do_check_eq(bmsvc.getItemType(newBkmk1Id), bmsvc.TYPE_BOOKMARK);
+  do_check_eq(bmsvc.getBookmarkURI(newBkmk1Id).spec, "http://www.mozilla.org/");
+  do_check_eq(bmsvc.getItemType(newBkmk2Id), bmsvc.TYPE_SEPARATOR);
+  do_check_eq(bmsvc.getItemType(newBkmk3Id), bmsvc.TYPE_FOLDER);
+  do_check_eq(bmsvc.getItemTitle(newBkmk3Id), "folder");
+  do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_1Id), newBkmk3Id);
+  do_check_eq(bmsvc.getItemType(newBkmk3_1Id), bmsvc.TYPE_BOOKMARK);
+  do_check_eq(bmsvc.getBookmarkURI(newBkmk3_1Id).spec, "http://www.mozilla.org/");
+  do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_2Id), newBkmk3Id);
+  do_check_eq(bmsvc.getItemType(newBkmk3_2Id), bmsvc.TYPE_SEPARATOR);
+  do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_3Id), newBkmk3Id);
+  do_check_eq(bmsvc.getItemType(newBkmk3_3Id), bmsvc.TYPE_FOLDER);
+  do_check_eq(bmsvc.getItemTitle(newBkmk3_3Id), "folder");
 }
--- a/browser/components/preferences/permissions.xul
+++ b/browser/components/preferences/permissions.xul
@@ -61,17 +61,17 @@
 
   <keyset>
     <key key="&windowClose.key;" modifiers="accel" oncommand="window.close();"/>
   </keyset>
   
   <vbox class="contentPane" flex="1">
     <description id="permissionsText" control="url"/>
     <separator class="thin"/>
-    <label id="urlLabel" control="url" value="&address.label;"/>
+    <label id="urlLabel" control="url" value="&address.label;" accesskey="&address.accesskey;"/>
     <hbox align="start">
       <textbox id="url" flex="1" 
                oninput="gPermissionManager.onHostInput(event.target);"
                onkeypress="gPermissionManager.onHostKeyPress(event);"/>
     </hbox>
     <hbox pack="end">
       <button id="btnBlock" disabled="true" label="&block.label;" accesskey="&block.accesskey;"
               oncommand="gPermissionManager.addPermission(nsIPermissionManager.DENY_ACTION);"/>
--- a/browser/components/preferences/security.xul
+++ b/browser/components/preferences/security.xul
@@ -92,21 +92,21 @@
         <button id="addonExceptions"
                 label="&addonExceptions.label;"
                 accesskey="&addonExceptions.accesskey;"
                 oncommand="gSecurityPane.showAddonExceptions();"/>
       </hbox>
 
       <separator class="thin"/>
       <checkbox id="tellMaybeAttackSite"
-                label="&tellMaybeAttackSite.label;"
+                label="&tellMaybeAttackSite2.label;"
                 accesskey="&tellMaybeAttackSite.accesskey;"
                 preference="browser.safebrowsing.malware.enabled" />
       <checkbox id="tellMaybeForgery"
-                label="&tellMaybeForgery.label;"
+                label="&tellMaybeForgery2.label;"
                 accesskey="&tellMaybeForgery.accesskey;"
                 preference="browser.safebrowsing.enabled" />
     </groupbox>
 
     <!-- Passwords -->
     <groupbox id="passwordsGroup" orient="vertical">
       <caption label="&passwords.label;"/>
 
--- a/browser/components/preferences/tabs.js
+++ b/browser/components/preferences/tabs.js
@@ -66,31 +66,30 @@ var gTabsPane = {
    * browser.tabs.warnOnOpen
    * - true if the user should be warned if he attempts to open a lot of tabs at
    *   once (e.g. a large folder of bookmarks), false otherwise
    */
 
   /**
    * Determines where a link which opens a new window will open.
    *
-   * @returns 2 if such links should be opened in new windows,
-   *          3 if such links should be opened in new tabs
+   * @returns |true| if such links should be opened in new tabs
    */
   readLinkTarget: function() {
     var openExternal = document.getElementById("browser.link.open_external");
-    return openExternal.value != 2 ? 3 : 2;
+    return openExternal.value != 2;
   },
 
   /**
    * Ensures that pages opened in new windows by web pages and pages opened by
    * external applications both open in the same way (e.g. in a new tab, window,
    * etc.).
    *
    * @returns 2 if such links should be opened in new windows,
    *          3 if such links should be opened in new tabs
    */
   writeLinkTarget: function() {
     var linkTargeting = document.getElementById("linkTargeting");
-    document.getElementById("browser.link.open_newwindow").value = linkTargeting.value;
-    return linkTargeting.value;
+    var linkTarget = linkTargeting.checked ? 3 : 2;
+    document.getElementById("browser.link.open_newwindow").value = linkTarget;
+    return linkTarget;
   }
 };
-
--- a/browser/components/preferences/tabs.xul
+++ b/browser/components/preferences/tabs.xul
@@ -58,32 +58,24 @@
       <preference id="browser.tabs.autoHide"           name="browser.tabs.autoHide"           type="bool" inverted="true"/>
       <preference id="browser.tabs.loadInBackground"   name="browser.tabs.loadInBackground"   type="bool" inverted="true"/>
       <preference id="browser.tabs.warnOnClose"        name="browser.tabs.warnOnClose"        type="bool"/>
       <preference id="browser.tabs.warnOnOpen"         name="browser.tabs.warnOnOpen"         type="bool"/>
     </preferences>
     
     <script type="application/x-javascript" src="chrome://browser/content/preferences/tabs.js"/>
 
-    <vbox id="linksOpenInBox">
-      <label control="linkTargeting">&newPagesIn.label;</label>
-      <radiogroup id="linkTargeting" class="indent"
-                  preference="browser.link.open_external"
-                  onsyncfrompreference="return gTabsPane.readLinkTarget();"
-                  onsynctopreference="return gTabsPane.writeLinkTarget();">
-        <radio label="&inNewWindow.label;" accesskey="&inNewWindow.accesskey;" value="2"/>
-        <radio label="&inNewTab.label;" accesskey="&inNewTab.accesskey;" value="3"/>
-      </radiogroup>
-    </vbox>
-
-    <separator id="tabsSeparator"/>
-
     <!-- XXX flex below is a hack because wrapping checkboxes don't reflow
              properly; see bug 349098 -->
     <vbox id="tabPrefsBox" align="start" flex="1">
+      <checkbox id="linkTargeting" label="&newWindowsAsTabs.label;"
+                accesskey="&newWindowsAsTabs.accesskey;"
+                preference="browser.link.open_external"
+                onsyncfrompreference="return gTabsPane.readLinkTarget();"
+                onsynctopreference="return gTabsPane.writeLinkTarget();"/>
       <checkbox id="warnCloseMultiple" label="&warnCloseMultipleTabs.label;"
                 accesskey="&warnCloseMultipleTabs.accesskey;"
                 preference="browser.tabs.warnOnClose"/>
       <checkbox id="warnOpenMany" label="&warnOpenManyTabs.label;"
                 accesskey="&warnOpenManyTabs.accesskey;"
                 preference="browser.tabs.warnOnOpen"/>
       <checkbox id="showTabBar" label="&showTabBar.label;"
                 accesskey="&showTabBar.accesskey;"
--- a/browser/components/preferences/tests/browser_bug410900.js
+++ b/browser/components/preferences/tests/browser_bug410900.js
@@ -1,12 +1,12 @@
 function test() {
   waitForExplicitFinish();
 
-  // setup a phony hander to ensure the app pane will be populated.
+  // Setup a phony handler to ensure the app pane will be populated.
   var handler = Cc["@mozilla.org/uriloader/web-handler-app;1"].
                 createInstance(Ci.nsIWebHandlerApp);
   handler.name = "App pane alive test";
   handler.uriTemplate = "http://test.mozilla.org/%s";
 
   var extps = Cc["@mozilla.org/uriloader/external-protocol-service;1"].
               getService(Ci.nsIExternalProtocolService);
   var info = extps.getProtocolHandlerInfo("apppanetest");
@@ -18,18 +18,19 @@ function test() {
 
   var obs = Cc["@mozilla.org/observer-service;1"].
             getService(Ci.nsIObserverService);
 
   var observer = {
     observe: function(win, topic, data) {
       if (topic != "app-handler-pane-loaded")
         return;
+
+      obs.removeObserver(observer, "app-handler-pane-loaded");
       runTest(win);
-      obs.removeObserver(observer, "app-handler-pane-loaded");
     }
   };
   obs.addObserver(observer, "app-handler-pane-loaded", false);
 
   openDialog("chrome://browser/content/preferences/preferences.xul", "Preferences",
              "chrome,titlebar,toolbar,centerscreen,dialog=no", "paneApplications");
 }
 
--- a/browser/components/search/Makefile.in
+++ b/browser/components/search/Makefile.in
@@ -42,23 +42,9 @@ srcdir    = @srcdir@
 VPATH     = @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 ifdef ENABLE_TESTS
 DIRS = test
 endif
 
-MODULE = browsersearch
-XPIDL_MODULE = browsersearch
-
-XPIDLSRCS = nsIBrowserSearchService.idl
-
-EXTRA_PP_COMPONENTS = nsSearchService.js \
-	nsSearchSuggestions.js
-
-ifneq (,$(BUILD_OFFICIAL)$(MOZILLA_OFFICIAL))
-DEFINES += -DOFFICIAL_BUILD=1
-endif
-
-DEFINES += -DMOZ_DISTRIBUTION_ID=$(MOZ_DISTRIBUTION_ID)
-
 include $(topsrcdir)/config/rules.mk
--- a/browser/components/sessionstore/test/browser/Makefile.in
+++ b/browser/components/sessionstore/test/browser/Makefile.in
@@ -41,16 +41,17 @@ srcdir		= @srcdir@
 VPATH		= @srcdir@
 relativesrcdir  = browser/components/sessionstore/test/browser 
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _BROWSER_TEST_FILES = \
 	browser_346337.js \
+	browser_346337_sample.html \
 	browser_350525.js \
 	browser_367052.js \
 	browser_393716.js \
 	browser_448741.js \
 	$(NULL)
 
 libs:: $(_BROWSER_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
--- a/browser/components/sessionstore/test/browser/browser_346337.js
+++ b/browser/components/sessionstore/test/browser/browser_346337.js
@@ -33,25 +33,30 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 function test() {
   /** Test for Bug 346337 **/
   
   let fieldList = {
-    "//input[@name='testinput']": Date.now().toString(),
-    "//input[@name='bad name']":  Math.random().toString(),
+    "//input[@name='input']":     Date.now().toString(),
+    "//input[@name='spaced 1']":  Math.random().toString(),
+    "//input[3]":                 "three",
     "//input[@type='checkbox']":  true,
+    "//input[@name='uncheck']":   false,
     "//input[@type='radio'][1]":  false,
     "//input[@type='radio'][2]":  true,
+    "//input[@type='radio'][3]":  false,
     "//select":                   2,
     "//select[@multiple]":        [1, 3],
     "//textarea[1]":              "",
-    "//textarea[3]":              "Some more test\n" + new Date()
+    "//textarea[2]":              "Some text... " + Math.random(),
+    "//textarea[3]":              "Some more text\n" + new Date(),
+    "//input[@type='file']":      "/dev/null"
   };
   
   function getElementByXPath(aTab, aQuery) {
     let doc = aTab.linkedBrowser.contentDocument;
     let xptype = Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE;
     return doc.evaluate(aQuery, doc, null, xptype, null).singleNodeValue;
   }
   
@@ -86,18 +91,19 @@ function test() {
   // test setup
   let tabbrowser = getBrowser();
   waitForExplicitFinish();
   
   // make sure we don't save form data at all (except for tab duplication)
   let privacy_level = gPrefService.getIntPref("browser.sessionstore.privacy_level");
   gPrefService.setIntPref("browser.sessionstore.privacy_level", 2);
   
-  todo(false, "test doesn't run from the harness's http server");
-  let tab = tabbrowser.addTab("https://bugzilla.mozilla.org/attachment.cgi?id=328502");
+  let testURL = "chrome://mochikit/content/browser/" +
+    "browser/components/sessionstore/test/browser/browser_346337_sample.html";
+  let tab = tabbrowser.addTab(testURL);
   tab.linkedBrowser.addEventListener("load", function(aEvent) {
     for (let xpath in fieldList)
       setFormValue(tab, xpath, fieldList[xpath]);
     
     let tab2 = tabbrowser.duplicateTab(tab);
     tab2.linkedBrowser.addEventListener("load", function(aEvent) {
       for (let xpath in fieldList)
         ok(compareFormValue(tab2, xpath, fieldList[xpath]),
new file mode 100644
--- /dev/null
+++ b/browser/components/sessionstore/test/browser/browser_346337_sample.html
@@ -0,0 +1,36 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<title>Test for bug 346337</title>
+
+<h3>Text Fields</h3>
+<input type="text" name="input">
+<input type="text" name="spaced 1">
+<input>
+
+<h3>Checkboxes and Radio buttons</h3>
+<input type="checkbox" name="check"> Check 1
+<input type="checkbox" name="uncheck" checked> Check 2
+<p>
+<input type="radio" name="group" value="1"> Radio 1
+<input type="radio" name="group" value="some"> Radio 2
+<input type="radio" name="group" checked> Radio 3
+
+<h3>Selects</h3>
+<select name="any">  
+  <option value="1"> Select 1  
+  <option value="some"> Select 2 
+  <option>Select 3
+</select>
+<select multiple="multiple">  
+  <option value=1> Multi-select 1
+  <option value=2> Multi-select 2  
+  <option value=3> Multi-select 3
+  <option value=4> Multi-select 4
+</select> 
+
+<h3>Text Areas</h3>
+<textarea name="testarea"></textarea>
+<textarea name="sized one" rows="5" cols="25"></textarea>
+<textarea></textarea>
+
+<h3>File Selector</h3>
+<input type="file">
--- a/browser/components/sidebar/src/nsSidebar.js
+++ b/browser/components/sidebar/src/nsSidebar.js
@@ -147,17 +147,17 @@ function (engineURL, iconURL)
         ! /^(https?|ftp):\/\/.+\.(gif|jpg|jpeg|png|ico)$/i.test(iconURL))
       throw "Unsupported search icon URL.";
   }
   catch(ex)
   {
     debug(ex);
     Components.utils.reportError("Invalid argument passed to window.sidebar.addSearchEngine: " + ex);
     
-    var searchBundle = srGetStrBundle("chrome://browser/locale/search.properties");
+    var searchBundle = srGetStrBundle("chrome://global/locale/search/search.properties");
     var brandBundle = srGetStrBundle("chrome://branding/locale/brand.properties");
     var brandName = brandBundle.GetStringFromName("brandShortName");
     var title = searchBundle.GetStringFromName("error_invalid_engine_title");
     var msg = searchBundle.formatStringFromName("error_invalid_engine_msg",
                                                 [brandName], 1);
     var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
              getService(Components.interfaces.nsIWindowWatcher);
     ww.getNewPrompter(null).alert(title, msg);
--- a/browser/installer/unix/packages-static
+++ b/browser/installer/unix/packages-static
@@ -61,17 +61,16 @@ bin/blocklist.xml
 bin/components/alerts.xpt
 bin/components/accessibility.xpt
 bin/components/appshell.xpt
 bin/components/appstartup.xpt
 bin/components/autocomplete.xpt
 bin/components/autoconfig.xpt
 bin/components/browsercompsbase.xpt
 bin/components/browserplaces.xpt
-bin/components/browsersearch.xpt
 bin/components/browser-feeds.xpt
 bin/components/caps.xpt
 bin/components/chardet.xpt
 bin/components/chrome.xpt
 bin/components/commandhandler.xpt
 bin/components/commandlines.xpt
 bin/components/composer.xpt
 bin/components/content_base.xpt
@@ -162,16 +161,17 @@ bin/components/toolkitremote.xpt
 bin/components/rdf.xpt
 bin/components/satchel.xpt
 bin/components/saxparser.xpt
 bin/components/shistory.xpt
 bin/components/spellchecker.xpt
 bin/components/storage.xpt
 bin/components/profile.xpt
 bin/components/toolkitprofile.xpt
+bin/components/toolkitsearch.xpt
 bin/components/txtsvc.xpt
 bin/components/txmgr.xpt
 bin/components/uconv.xpt
 bin/components/unicharutil.xpt
 bin/components/uriloader.xpt
 bin/components/webBrowser_core.xpt
 bin/components/webbrowserpersist.xpt
 bin/components/webshell_idls.xpt
--- a/browser/installer/windows/Makefile.in
+++ b/browser/installer/windows/Makefile.in
@@ -64,16 +64,17 @@ BRANDING_FILES = \
 	wizHeader.bmp \
 	wizHeaderRTL.bmp \
 	wizWatermark.bmp \
 	$(NULL)
 
 DEFINES += \
 	-DAB_CD=$(AB_CD) \
 	-DPKG_BASENAME=$(PKG_BASENAME) \
+	-DPKG_INST_BASENAME=$(PKG_INST_BASENAME) \
 	-DMOZ_APP_VERSION=$(MOZ_APP_VERSION) \
 	-DMOZ_APP_NAME=$(MOZ_APP_NAME) \
 	-DMOZ_APP_DISPLAYNAME=${MOZ_APP_DISPLAYNAME} \
 	-DMOZILLA_VERSION=${MOZILLA_VERSION} \
 	$(NULL)
 
 include $(topsrcdir)/config/config.mk
 include $(call EXPAND_LOCALE_SRCDIR,toolkit/locales)/installer/windows/charset.mk
--- a/browser/installer/windows/nsis/defines.nsi.in
+++ b/browser/installer/windows/nsis/defines.nsi.in
@@ -1,13 +1,13 @@
 #filter substitution
 !define AppVersion            "@MOZ_APP_VERSION@"
 !define GREVersion            @MOZILLA_VERSION@
 !define AB_CD                 "@AB_CD@"
-!define FileInstallerEXE      "@PKG_BASENAME@.installer.exe"
-!define FileInstallerMSI      "@PKG_BASENAME@.installer.msi"
+!define FileInstallerEXE      "@PKG_INST_BASENAME@.exe"
+!define FileInstallerMSI      "@PKG_INST_BASENAME@.msi"
 !define FileInstallerNETRoot  "@PKG_BASENAME@.net-installer"
 
 !define FileMainEXE           "@MOZ_APP_NAME@.exe"
 !define WindowClass           "FirefoxMessageWindow"
 !define DDEApplication        "Firefox"
 !define AppRegName            "Firefox"
 !define MinUnsupportedVer     "Microsoft Windows 2000"
--- a/browser/installer/windows/packages-static
+++ b/browser/installer/windows/packages-static
@@ -68,17 +68,16 @@ bin\AccessibleMarshal.dll
 bin\components\accessibility.xpt
 bin\components\accessibility-msaa.xpt
 bin\components\appshell.xpt
 bin\components\appstartup.xpt
 bin\components\autocomplete.xpt
 bin\components\autoconfig.xpt
 bin\components\browsercompsbase.xpt
 bin\components\browserplaces.xpt
-bin\components\browsersearch.xpt
 bin\components\browser-feeds.xpt
 bin\components\caps.xpt
 bin\components\chardet.xpt
 bin\components\chrome.xpt
 bin\components\commandhandler.xpt
 bin\components\commandlines.xpt
 bin\components\composer.xpt
 bin\components\content_base.xpt
@@ -166,16 +165,17 @@ bin\components\prefetch.xpt
 bin\components\profile.xpt
 bin\components\proxyObject.xpt
 bin\components\rdf.xpt
 bin\components\satchel.xpt
 bin\components\saxparser.xpt
 bin\components\shistory.xpt
 bin\components\storage.xpt
 bin\components\toolkitprofile.xpt
+bin\components\toolkitsearch.xpt
 bin\components\txtsvc.xpt
 bin\components\txmgr.xpt
 #ifdef MOZ_USE_NATIVE_UCONV
 bin\components\ucnative.xpt
 #endif
 bin\components\uconv.xpt
 bin\components\unicharutil.xpt
 bin\components\uriloader.xpt
--- a/browser/locales/Makefile.in
+++ b/browser/locales/Makefile.in
@@ -69,16 +69,17 @@ PWD := $(shell pwd)
 core_abspath = $(if $(findstring :,$(1)),$(1),$(if $(filter /%,$(1)),$(1),$(PWD)/$(1)))
 
 DEFINES += \
 	-DAB_CD=$(AB_CD) \
 	-DMOZ_LANGPACK_EID=langpack-$(AB_CD)@firefox.mozilla.org \
 	-DMOZ_APP_VERSION=$(MOZ_APP_VERSION) \
 	-DLOCALE_SRCDIR=$(call core_abspath,$(LOCALE_SRCDIR)) \
 	-DPKG_BASENAME=$(PKG_BASENAME) \
+	-DPKG_INST_BASENAME=$(PKG_INST_BASENAME) \
 	$(NULL)
 
 ifndef MOZ_BRANDING_DIRECTORY
 DEFINES += -DMOZ_USE_GENERIC_BRANDING
 endif
 
 ifeq (,$(filter-out pref,$(MOZ_EXTENSIONS)))
 DEFINES += -DEXTENSION_PREF
@@ -187,17 +188,17 @@ MOZ_PKG_MAC_ICON=$(_ABS_DIST)/branding/d
 MOZ_PKG_MAC_RSRC=$(_ABS_DIST)/branding/license.r
 MOZ_PKG_MAC_EXTRA=--symlink "/Applications:/ "
 endif
 
 PACKAGER_NO_LIBS = 1
 include $(topsrcdir)/toolkit/mozapps/installer/packager.mk
 include $(call EXPAND_LOCALE_SRCDIR,toolkit/locales)/installer/windows/charset.mk
 
-repackage-win32-installer: WIN32_INSTALLER_OUT=$(_ABS_DIST)/install/sea/$(PKG_BASENAME).installer.exe
+repackage-win32-installer: WIN32_INSTALLER_OUT=$(_ABS_DIST)/$(PKG_INST_PATH)$(PKG_INST_BASENAME).exe
 repackage-win32-installer: $(WIN32_INSTALLER_IN) $(SUBMAKEFILES)
 ifneq (en-US,$(AB_CD))
 	@echo "Verifying $(AB_CD) installer variable usage"
 	@$(PERL) $(topsrcdir)/toolkit/mozapps/installer/windows/nsis/check-locales.pl $(LOCALE_SRCDIR)/installer
 endif
 	@echo "Repackaging $(WIN32_INSTALLER_IN) into $(WIN32_INSTALLER_OUT)."
 ifdef MOZ_BRANDING_DIRECTORY
 	$(MAKE) -C $(DEPTH)/$(MOZ_BRANDING_DIRECTORY) export
@@ -222,17 +223,17 @@ endif
 	rm -f app.7z
 	cd l10n-stage && \
 	  $(CYGWIN_WRAPPER) 7z a -r -t7z ../app.7z -mx -m0=BCJ2 -m1=LZMA:d24 -m2=LZMA:d19 -m3=LZMA:d19 -mb0:1 -mb0s1:2 -mb0s2:3
 	cat ../installer/windows/l10ngen/7zSD.sfx \
 	    $(topsrcdir)/browser/installer/windows/app.tag \
 	    app.7z > $(WIN32_INSTALLER_OUT)
 	chmod 0755 $(WIN32_INSTALLER_OUT)
 
-repackage-win32-installer-%: WIN32_INSTALLER_IN=$(_ABS_DIST)/install/sea/$(PKG_BASENAME).installer.exe
+repackage-win32-installer-%: WIN32_INSTALLER_IN=$(_ABS_DIST)/$(PKG_INST_PATH)$(PKG_INST_BASENAME).exe
 repackage-win32-installer-%: $(WIN32_INSTALLER_IN)
 	@$(MAKE) repackage-win32-installer AB_CD=$* WIN32_INSTALLER_IN=$(WIN32_INSTALLER_IN)
 
 ifneq (,$(filter mac cocoa,$(MOZ_WIDGET_TOOLKIT)))
 STAGEDIST = $(_ABS_DIST)/l10n-stage/$(MOZ_PKG_APPNAME)/$(_APPNAME)/Contents/MacOS
 else
 STAGEDIST = $(_ABS_DIST)/l10n-stage/$(MOZ_PKG_APPNAME)
 endif
@@ -262,30 +263,32 @@ endif
 	$(RM) -r $(DIST)/xpi-stage/locale-$(AB_CD)/chrome/$(AB_CD)
 	cd $(DIST)/xpi-stage/locale-$(AB_CD) && \
 	  tar $(TAR_CREATE_FLAGS) - * | ( cd $(STAGEDIST) && tar -xf - )
 ifneq (en,$(AB))
 ifneq (,$(filter mac cocoa,$(MOZ_WIDGET_TOOLKIT)))
 	mv $(_ABS_DIST)/l10n-stage/$(MOZ_PKG_APPNAME)/$(_APPNAME)/Contents/Resources/en.lproj $(_ABS_DIST)/l10n-stage/$(MOZ_PKG_APPNAME)/$(_APPNAME)/Contents/Resources/$(AB).lproj
 endif
 endif
+	$(NSINSTALL) -D $(DIST)/l10n-stage/$(PKG_PATH)
 	cd $(DIST)/l10n-stage; \
 	  $(MAKE_PACKAGE)
-	mv -f $(DIST)/l10n-stage/$(PACKAGE) $(DIST)
+	$(NSINSTALL) -D $(DIST)/$(PKG_PATH)
+	mv -f $(DIST)/l10n-stage/$(PACKAGE) $(DIST)/$(PACKAGE)
 
 repackage-zip-%: ZIP_IN=$(_ABS_DIST)/$(PACKAGE)
 repackage-zip-%: $(ZIP_IN)
 	@$(MAKE) repackage-zip AB_CD=$* ZIP_IN=$(ZIP_IN)
 
-langpack-%: LANGPACK_FILE=$(_ABS_DIST)/install/firefox-$(MOZ_APP_VERSION).$(AB_CD).langpack.xpi
+langpack-%: LANGPACK_FILE=$(_ABS_DIST)/$(PKG_LANGPACK_PATH)$(PKG_LANGPACK_BASENAME).xpi
 langpack-%: AB_CD=$*
 langpack-%: XPI_NAME=locale-$*
 langpack-%:
 	@echo "Making langpack $(LANGPACK_FILE)"
-	$(NSINSTALL) -D $(DIST)/install
+	$(NSINSTALL) -D $(DIST)/$(PKG_LANGPACK_PATH)
 	@$(RM) -rf $(DIST)/xpi-stage/locale-$(AB_CD)
 	@$(MAKE) libs-$(AB_CD) USE_EXTENSION_MANIFEST=1
 	$(PERL) $(topsrcdir)/config/preprocessor.pl $(DEFINES) $(ACDEFINES) -I$(call EXPAND_LOCALE_SRCDIR,toolkit/locales)/defines.inc -I$(LOCALE_SRCDIR)/defines.inc $(srcdir)/generic/install.rdf > $(FINAL_TARGET)/install.rdf
 	cd $(DIST)/xpi-stage/locale-$(AB_CD) && \
 	  $(ZIP) -r9D $(LANGPACK_FILE) install.rdf chrome chrome.manifest
 
 # This is a generic target that will make a langpack, repack ZIP (+tarball)
 # builds, and repack an installer if applicable. It is called from the
@@ -330,12 +333,58 @@ endif
 # and for the windows repackages we need the .installer.exe in dist/sea
 wget-en-US:
 ifndef WGET
 	$(error Wget not installed)
 endif
 	@$(WGET) -nv --output-document $(_ABS_DIST)/$(PACKAGE) $(EN_US_BINARY_URL)/$(PACKAGE)
 	@echo "Downloaded $(EN_US_BINARY_URL)/$(PACKAGE) to $(_ABS_DIST)/$(PACKAGE)"
 ifeq ($(OS_ARCH), WINNT)
-	$(NSINSTALL) -D $(_ABS_DIST)/install/sea
-	@$(WGET) -nv --output-document $(_ABS_DIST)/install/sea/$(PKG_BASENAME).installer.exe $(EN_US_BINARY_URL)/$(PKG_BASENAME).installer.exe
-	@echo "Downloaded $(EN_US_BINARY_URL)/$(PKG_BASENAME).installer.exe to $(_ABS_DIST)/install/sea/$(PKG_BASENAME)"
+	$(NSINSTALL) -D $(_ABS_DIST)/$(PKG_INST_PATH)
+	@$(WGET) -nv --output-document $(_ABS_DIST)/$(PKG_INST_PATH)$(PKG_INST_BASENAME).exe $(EN_US_BINARY_URL)/$(PKG_PATH)$(PKG_INST_BASENAME).exe
+	@echo "Downloaded $(EN_US_BINARY_URL)/$(PKG_PATH)$(PKG_INST_BASENAME).exe to $(_ABS_DIST)/$(PKG_INST_PATH)$(PKG_INST_BASENAME)"
+endif
+
+#These make targets call prepare-repackages by setting different UPLOAD_DIR
+prepare-upload-latest-%:
+	@$(MAKE) prepare-repackages-$* UPLOAD_DIR=$(DIST)/upload/latest
+
+prepare-upload-dated-%:
+	@$(MAKE) prepare-repackages-$* UPLOAD_DIR=$(DIST)/upload/`date "+%Y-%m-%d-%H"`-$(MOZ_PKG_APPNAME)$(MOZ_APP_VERSION)-l10n
+
+#Each platform uploads their xpi files to different folders
+ifeq (Linux, $(OS_ARCH))
+XPI_DESTINATION = linux-xpi
+endif
+ifeq (Darwin, $(OS_ARCH))
+XPI_DESTINATION = mac-xpi
+endif
+ifeq (WINNT, $(OS_ARCH))
+XPI_DESTINATION = windows-xpi
 endif
+
+# This target will generate a UPLOAD_DIR folder with
+# l10n repackages in the way that we offer l10n nightlies
+#  1) ./ the binary
+#  2) ./{linux,mac,windows}-xpi/locale.xpi
+prepare-repackages-%:
+ifndef XPI_DESTINATION
+	$(error XPI_DESTINATION not defined; \
+	This is the folder where the xpi files will be moved to)
+endif
+ifndef UPLOAD_DIR
+	$(error UPLOAD_DIR not defined)
+endif
+	$(NSINSTALL) -D $(UPLOAD_DIR)
+	$(NSINSTALL) -D $(UPLOAD_DIR)/$(XPI_DESTINATION)
+# Move the langpack
+	mv $(DIST)/install/firefox-$(MOZ_APP_VERSION).$*.langpack.xpi \
+	   $(UPLOAD_DIR)/$(XPI_DESTINATION)/$*.xpi
+# Move the repackage
+	mv $(DIST)/firefox-$(MOZ_APP_VERSION).$*.* \
+	   $(UPLOAD_DIR)/.
+# Move the windows installer
+ifeq (WINNT, $(OS_ARCH))
+	mv $(DIST)/install/sea/firefox-$(MOZ_APP_VERSION).$*.win32.installer.exe \
+	   $(UPLOAD_DIR)/.
+endif
+# Set the permissions that the folders will have in ftp once uploaded
+	chmod -vR 775 $(UPLOAD_DIR)
--- a/browser/locales/all-locales
+++ b/browser/locales/all-locales
@@ -1,46 +1,61 @@
 af
 ar
+as
 be
+bg
 ca
 cs
+cy
 da
 de
 el
 en-GB
+eo
 es-AR
 es-ES
+et
 eu
 fi
 fr
 fy-NL
 ga-IE
+gl
 gu-IN
 he
+hi-IN
 hu
 id
+is
 it
 ja
 ja-JP-mac
 ka
+kn
 ko
 ku
 lt
 mk
 mn
+mr
 nb-NO
 nl
 nn-NO
+oc
 pa-IN
 pl
 pt-BR
 pt-PT
 ro
 ru
+si
 sk
 sq
 sr
 sv-SE
+ta
+te
+th
 tr
 uk
 zh-CN
 zh-TW
--- a/browser/locales/en-US/chrome/browser/pageInfo.dtd
+++ b/browser/locales/en-US/chrome/browser/pageInfo.dtd
@@ -55,18 +55,18 @@
 <!ENTITY  generalMode           "Render Mode:">
 <!ENTITY  generalSize           "Size:">
 <!ENTITY  generalReferrer       "Referring URL:">
 <!ENTITY  generalSource         "Cache Source:">
 <!ENTITY  generalModified       "Modified:">
 <!ENTITY  generalEncoding       "Encoding:">
 <!ENTITY  generalMetaName       "Name">
 <!ENTITY  generalMetaContent    "Content">
-<!ENTITY  generalSecurityMore   "More">
-<!ENTITY  generalSecurityMore.accesskey "o">
+<!ENTITY  generalSecurityDetails   "Details">
+<!ENTITY  generalSecurityDetails.accesskey "D">
 
 <!ENTITY  mediaTab              "Media">
 <!ENTITY  mediaTab.accesskey    "M">
 <!ENTITY  mediaLocation         "Location:">
 <!ENTITY  mediaText             "Associated Text:">
 <!ENTITY  mediaAltHeader        "Alternate Text">
 <!ENTITY  mediaAddress          "Address">
 <!ENTITY  mediaType             "Type">
--- a/browser/locales/en-US/chrome/browser/preferences/permissions.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/permissions.dtd
@@ -3,16 +3,17 @@
 
 <!ENTITY treehead.sitename.label      "Site">
 <!ENTITY treehead.status.label        "Status">
 <!ENTITY removepermission.label       "Remove Site">
 <!ENTITY removepermission.accesskey   "R">
 <!ENTITY removeallpermissions.label   "Remove All Sites">
 <!ENTITY removeallpermissions.accesskey "e">
 <!ENTITY address.label                "Address of web site:">
+<!ENTITY address.accesskey            "d">
 <!ENTITY block.label                  "Block">
 <!ENTITY block.accesskey              "B">
 <!ENTITY session.label                "Allow for Session">
 <!ENTITY session.accesskey            "S">
 <!ENTITY allow.label                  "Allow">
 <!ENTITY allow.accesskey              "A">
 <!ENTITY windowClose.key              "w">
 
--- a/browser/locales/en-US/chrome/browser/preferences/security.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/security.dtd
@@ -1,23 +1,23 @@
 <!ENTITY  warnAddonInstall.label        "Warn me when sites try to install add-ons">
 <!ENTITY  warnAddonInstall.accesskey    "W">
 
 <!-- LOCALIZATION NOTE (tellMaybeForgery.label, tellMaybeAttackSite.label):
   The methods by which forged (phished) and attack sites will be detected by
   phishing providers will vary from human review to machine-based heuristics to a
   combination of both, so it's important that these strings and
-  useDownloadedList.label convey the meaning "suspected" (and not something like
+  useDownloadedList.label convey the meaning "reported" (and not something like
   "known").
 -->
-<!ENTITY  tellMaybeAttackSite.label     "Tell me if the site I'm visiting is a suspected attack site">
+<!ENTITY  tellMaybeAttackSite2.label     "Block reported attack sites">
 <!ENTITY  tellMaybeAttackSite.accesskey "k">
 
-<!ENTITY  tellMaybeForgery.label     "Tell me if the site I'm visiting is a suspected forgery">
-<!ENTITY  tellMaybeForgery.accesskey "T">
+<!ENTITY  tellMaybeForgery2.label     "Block reported web forgeries">
+<!ENTITY  tellMaybeForgery.accesskey "B">
 
 <!ENTITY  addonExceptions.label         "Exceptions…">
 <!ENTITY  addonExceptions.accesskey     "E">
 
 
 <!ENTITY  passwords.label               "Passwords">
 
 <!ENTITY  rememberPasswords.label       "Remember passwords for sites">
--- a/browser/locales/en-US/chrome/browser/preferences/tabs.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/tabs.dtd
@@ -1,13 +1,10 @@
-<!ENTITY newPagesIn.label             "New pages should be opened in:">
-<!ENTITY inNewWindow.label            "a new window">
-<!ENTITY inNewWindow.accesskey        "w">
-<!ENTITY inNewTab.label               "a new tab">
-<!ENTITY inNewTab.accesskey           "t">
+<!ENTITY newWindowsAsTabs.label       "Open new windows in a new tab instead">
+<!ENTITY newWindowsAsTabs.accesskey   "t">
 
 <!ENTITY warnCloseMultipleTabs.label  "Warn me when closing multiple tabs">
 <!ENTITY warnCloseMultipleTabs.accesskey  "m">
 
 <!ENTITY warnOpenManyTabs.label       "Warn me when opening multiple tabs might slow down &brandShortName;">
 <!ENTITY warnOpenManyTabs.accesskey   "o">
 
 <!ENTITY showTabBar.label             "Always show the tab bar">
--- a/browser/locales/en-US/chrome/browser/search.properties
+++ b/browser/locales/en-US/chrome/browser/search.properties
@@ -1,25 +1,10 @@
 searchtip=Search using %S
 
 cmd_clearHistory=Clear Search History
 cmd_clearHistory_accesskey=C
 
 cmd_showSuggestions=Show Suggestions
 cmd_showSuggestions_accesskey=S
 
-addEngineConfirmTitle=Add Search Engine
-addEngineConfirmation=Add "%S" to the list of engines available in the search bar?\n\nFrom: %S
-addEngineUseNowText=Start &using it right away
-addEngineAddButtonLabel=Add
-
-error_loading_engine_title=Download Error
-# LOCALIZATION NOTE (error_loading_engine_msg2): %1$S = brandShortName, %2$S = location
-error_loading_engine_msg2=%S could not download the search plugin from:\n%S
-error_duplicate_engine_msg=%S could not install the search plugin from "%S" because an engine with the same name already exists.
-
-error_invalid_engine_title=Install Error
-# LOCALIZATION NOTE (error_invalid_engine_msg): %S = brandShortName
-error_invalid_engine_msg=This search engine isn't supported by %S and can't be installed.
-
 cmd_addFoundEngine=Add "%S"
 
-suggestion_label=Suggestions
--- a/browser/locales/en-US/searchplugins/eBay.xml
+++ b/browser/locales/en-US/searchplugins/eBay.xml
@@ -1,17 +1,10 @@
 <SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
 <ShortName>eBay</ShortName>
 <Description>eBay - Online actions</Description>
 <InputEncoding>ISO-8859-1</InputEncoding>
 <Image width="16" height="16">data:image/x-icon;base64,AAABAAEAEBAAAAEACABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAIAAAADAAAAA/wAAAABAAABAQAAAgEAAAMBAAAD/QAAAAIAAAECAAACAgAAAwIAAAP+AAAAAwAAAQMAAAIDAAADAwAAA/8AAAAD/AABA/wAAgP8AAMD/AAD//wAAAABAAEAAQACAAEAAwABAAP8AQAAAQEAAQEBAAIBAQADAQEAA/0BAAACAQABAgEAAgIBAAMCAQAD/gEAAAMBAAEDAQACAwEAAwMBAAP/AQAAA/0AAQP9AAID/QADA/0AA//9AAAAAgABAAIAAgACAAMAAgAD/AIAAAECAAEBAgACAQIAAwECAAP9AgAAAgIAAQICAAICAgADAgIAA/4CAAADAgABAwIAAgMCAAMDAgAD/wIAAAP+AAED/gACA/4AAwP+AAP//gAAAAMAAQADAAIAAwADAAMAA/wDAAABAwABAQMAAgEDAAMBAwAD/QMAAAIDAAECAwACAgMAAwIDAAP+AwAAAwMAAQMDAAIDAwADAwMAA/8DAAAD/wABA/8AAgP/AAMD/wAD//8AAAAD/AEAA/wCAAP8AwAD/AP8A/wAAQP8AQED/AIBA/wDAQP8A/0D/AACA/wBAgP8AgID/AMCA/wD/gP8AAMD/AEDA/wCAwP8AwMD/AP/A/wAA//8AQP//AID//wDA//8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB8fHx8fHx8fHx8fHx8AAB8cGRkUFAcHBx8fBUKfAAAfFBkfHxNHF4cb29vCnwAAHxkZFBQUBx8HG98bwp8fAB8ZGR8UGQcXhxvb28KFXx8fHZkZGRNHBwcfG8jCgoQfAB8fHx8HBx8b29vCnwPCnwAAAB8fBwcfHx8EBB8Dwp8AAAAAHx8fHwAfHx8AHx8fAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAD//wAA//8AAP//AACAAwAAAAMAAAADAAAAAQAAAAAAAAAAAACAAAAA4AAAAPCIAAD//wAA//8AAP//AAA=</Image>
-<Url type="text/html" method="GET" template="http://search.ebay.com/search/search.dll">
-  <Param name="query" value="{searchTerms}"/>
-  <Param name="MfcISAPICommand" value="GetResult"/>
-  <Param name="ht" value="1"/>
-  <Param name="ebaytag1" value="ebayreg"/>
-  <Param name="srchdesc" value="n"/>
-  <Param name="maxRecordsReturned" value="300"/>
-  <Param name="maxRecordsPerPage" value="50"/>
-  <Param name="SortProperty" value="MetaEndSort"/>
+<Url type="text/html" method="GET" template="http://rover.ebay.com/rover/1/711-47294-18009-3/4">
+  <Param name="satitle" value="{searchTerms}"/>
 </Url>
 <SearchForm>http://search.ebay.com/</SearchForm>
 </SearchPlugin>
deleted file mode 100644
--- a/browser/locales/generic/chrome/inspector/contents.rdf
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0"?>
-
-#filter substitution
-
-<RDF:RDF xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
-         xmlns:chrome="http://www.mozilla.org/rdf/chrome#">
-
-  <!-- list all the locales being supplied by this package -->
-  <RDF:Seq about="urn:mozilla:locale:root">
-    <RDF:li resource="urn:mozilla:locale:@AB_CD@"/>
-  </RDF:Seq>
-
-  <!-- locale information -->
-  <RDF:Description about="urn:mozilla:locale:@AB_CD@">
-    <chrome:packages>
-      <RDF:Seq about="urn:mozilla:locale:@AB_CD@:packages">
-        <RDF:li resource="urn:mozilla:locale:@AB_CD@:inspector"/>
-      </RDF:Seq>
-    </chrome:packages>
-  </RDF:Description>
-
-  <!-- Version Information.  State that we work only with major version of this
-       package. -->
-  <RDF:Description about="urn:mozilla:locale:@AB_CD@:inspector"
-                   chrome:localeVersion="@MOZILLA_LOCALE_VERSION@" />
-
-</RDF:RDF>
--- a/browser/modules/Sanitizer.jsm
+++ b/browser/modules/Sanitizer.jsm
@@ -152,35 +152,49 @@ Sanitizer.prototype = {
         // the browser:purge-session-history notification. (like error console)
         return true;
       }
     },
     
     formdata: {
       clear: function ()
       {
-        //Clear undo history of all searchBars
-        var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
-        var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
-        var windows = windowManagerInterface.getEnumerator("navigator:browser");
+        // Clear undo history of all searchBars
+        var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1']
+                                      .getService(Components.interfaces.nsIWindowMediator);
+        var windows = windowManager.getEnumerator("navigator:browser");
         while (windows.hasMoreElements()) {
           var searchBar = windows.getNext().document.getElementById("searchbar");
           if (searchBar) {
             searchBar.value = "";
             searchBar.textbox.editor.transactionManager.clear();
           }
         }
 
         var formHistory = Components.classes["@mozilla.org/satchel/form-history;1"]
                                     .getService(Components.interfaces.nsIFormHistory2);
         formHistory.removeAllEntries();
       },
-      
+
       get canClear()
       {
+        var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1']
+                                      .getService(Components.interfaces.nsIWindowMediator);
+        var windows = windowManager.getEnumerator("navigator:browser");
+        while (windows.hasMoreElements()) {
+          var searchBar = windows.getNext().document.getElementById("searchbar");
+          if (searchBar) {
+            var transactionMgr = searchBar.textbox.editor.transactionManager;
+            if (searchBar.value ||
+                transactionMgr.numberOfUndoItems ||
+                transactionMgr.numberOfRedoItems)
+              return true;
+          }
+        }
+
         var formHistory = Components.classes["@mozilla.org/satchel/form-history;1"]
                                     .getService(Components.interfaces.nsIFormHistory2);
         return formHistory.hasEntries;
       }
     },
     
     downloads: {
       clear: function ()
--- a/browser/themes/gnomestripe/browser/pageInfo.css
+++ b/browser/themes/gnomestripe/browser/pageInfo.css
@@ -121,20 +121,16 @@ textbox.header {
 textbox[disabled] {
   font-style: italic;
 }
 
 /* General Tab */
 #generalPanel > #titletext {
   -moz-margin-start: 5px;
 }
-#metaTags > .groupbox-body {
-  -moz-margin-start: 5px;
-  -moz-margin-end: 1px;
-}
 
 groupbox.collapsable caption .caption-icon { 
   width: 9px;
   height: 9px;
   background-repeat: no-repeat;
   background-position: center;
   -moz-margin-start: 1px;
   -moz-margin-end: 3px;
@@ -150,16 +146,18 @@ groupbox.collapsable[closed="true"] capt
 }
 
 groupbox tree { 
   margin: 0;
   border: none;
 }
 
 groupbox.treebox .groupbox-body { 
+  -moz-margin-start: 5px;
+  -moz-margin-end: 1px;
   padding-top: 0;
 }
 
 #securityBox description { 
   -moz-margin-start: 10px;
 }
 
 #general-security-identity {
deleted file mode 100644
index 786373b1ad673e16e46c113676a4580908ec0dbc..0000000000000000000000000000000000000000
GIT binary patch
literal 0
Hc$@<O00001
deleted file mode 100644
index da9bb88fa1f7134ec3fb495988654b2c5b3374c3..0000000000000000000000000000000000000000
GIT binary patch
literal 0
Hc$@<O00001
new file mode 100644
index 0000000000000000000000000000000000000000..2616e00107084a97bf66d9c07b14c8281f07b485
GIT binary patch
literal 403
zc%17D@N?(olHy`uVBq!ia0vp^tUz4B!3+}NJ#hj^<plVIxc;XjFq3w$1=_1p666=m
z5ENjp=*uMStzl;`?%~SDBOu~v%H`}PDa66&Wg)Ak?9XD8ba{^mQ2i!P7srr_xVQc{
z`3@QI6bD5`nU%@CdGhCf{SxJ?TD|J`3a@Gu2_0t?G;EyF`OyC2sT!qxo3($|Y4Nn4
zaBN>%zqE#@=EQbgnG%=CA1eg@2)s{gy>H`EJ8k6($-gbHwx@Uf{T*Ah^~vq4GWm?g
z_7b<U)+Ro`88t`$pW^9F>zrfNJ)0&U=l0U=ZpxaH^<d6!%RBsXJLGI9e9OF*ykb?B
uL*%r}EsJ!!#2(LhZh7XiM6>+I<I)ek*ur>gr`Q2q&*16m=d#Wzp$PzvsM|mQ
--- a/browser/themes/pinstripe/browser/browser.css
+++ b/browser/themes/pinstripe/browser/browser.css
@@ -42,87 +42,65 @@
  * ***** END LICENSE BLOCK ***** */
 
 @import url("chrome://global/skin/");
 
 @namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");
 @namespace html url("http://www.w3.org/1999/xhtml");
 @namespace svg url("http://www.w3.org/2000/svg");
 
-#main-window {
-  -moz-binding: url("chrome://global/skin/globalBindings.xml#unifiedWindow");
-}
-
 #main-window[chromehidden~="toolbar"][chromehidden~="location"][chromehidden~="directories"] {
   border-top: 1px solid rgba(0,0,0,0.65);
   -moz-appearance: none;
   background-color: #eeeeee;
 }
 
 /* ----- INACTIVE WINDOW ----- */
 
-#main-window:not([active="true"]) > #navigator-toolbox > toolbar {
-  border-top-color: rgba(255,255,255,0.45);
-  border-bottom-color: rgba(0,0,0,0.35);
-  background-color: #cfcfcf;
-}
-
 #main-window:not([active="true"]) > #navigator-toolbox > #nav-bar {
   background-image: url("chrome://global/skin/toolbar/toolbar-background-inactive.png");
 }
 
 #main-window:not([active="true"]) > #navigator-toolbox > #PersonalToolbar {
-  background-image: url("chrome://browser/skin/bookmark_toolbar_background-inactive.png");
+  background-color: -moz-mac-chrome-inactive;
 }
 
 #main-window:not([active="true"]) > #navigator-toolbox > toolbar > toolbaritem,
 #main-window:not([active="true"]) > #navigator-toolbox > toolbar > toolbarbutton,
 #main-window:not([active="true"]) > #browser-bottombox {
   opacity: 0.75;
 }
 
 #main-window:not([active="true"]) > #browser > vbox > #sidebar,
 #main-window:not([active="true"]) > #browser > vbox > sidebarheader { 
   background-color: #e8e8e8;
 }
 
 #main-window:not([active="true"]) .tabbrowser-strip {
-  background-color: #cfcfcf;
+  background-color: #e2e2e2;
 }
 
 #main-window:not([active="true"]) .tabbrowser-tab {
   color: #575757;
 }
 
-#main-window:not([active="true"]) .tabbrowser-tab[selected="true"] > .tab-image-middle,
-#main-window:not([active="true"]) .tabbrowser-tab[selected="true"] > .tab-closebutton,
-#main-window:not([active="true"]) .tabbrowser-tab[selected="true"] > .tab-close-button {
-  background-image: url("chrome://browser/skin/tabbrowser/tab-middle-inactive.png");
-}
-
-#main-window:not([active="true"]) .tabbrowser-tab[selected="true"] > .tab-image-left,
-#main-window:not([active="true"]) .tabbrowser-tab[selected="true"][chromedir="rtl"] > .tab-image-right {
-  background: url("chrome://browser/skin/tabbrowser/tab-left-inactive.png") no-repeat;
-}
-
-#main-window:not([active="true"]) .tabbrowser-tab[selected="true"] > .tab-image-right,
-#main-window:not([active="true"]) .tabbrowser-tab[selected="true"][chromedir="rtl"] > .tab-image-left {
-  background: url("chrome://browser/skin/tabbrowser/tab-right-inactive.png") no-repeat;
+#main-window:not([active="true"]) .tabbrowser-tab[selected="true"] {
+  background-color: -moz-mac-chrome-inactive;
 }
 
 /* ----- SEARCH FIELD ----- */
 
 #wrapper-search-container #searchbar html|*.textbox-input {
   visibility: hidden;
 }
 
 /* ----- BOOKMARK TOOLBAR ----- */
 
 #PersonalToolbar {
-  background: url("chrome://browser/skin/bookmark_toolbar_background.gif") repeat-x center center;
+  background: url("chrome://browser/skin/bookmark_toolbar_background.png") repeat-x center center -moz-mac-chrome-active;
   border-top: 1px solid rgba(255,255,255,0.25);
   border-bottom: 2px solid;
   -moz-border-bottom-colors: rgba(0,0,0,0.35) transparent;
   padding: 2px 0;
 }
 
 
 /* ----- BOOKMARK BUTTONS ----- */	
@@ -1592,18 +1570,16 @@ toolbarbutton.chevron {
 
 
 toolbarbutton.chevron > .toolbarbutton-menu-dropmarker {
   display: none;
 }
 
 #nav-bar {
   background-color: #9e9e9e;
-  border-top: none;
-  border-bottom: 1px solid rgba(0,0,0,0.35);
   background-image: url("chrome://global/skin/toolbar/toolbar-background.gif");
   background-repeat: repeat-x;
   background-position: top right;
   padding: 0 4px;
 }
 
 #nav-bar[collapsed="true"] + toolbar[customindex] {
  border-top: 2px solid;
@@ -1622,17 +1598,17 @@ toolbarbutton.chevron > .toolbarbutton-m
 
 .tab-icon-image {
   width: 16px;
   height: 16px;
   list-style-image: url("chrome://global/skin/tree/item.png");
 }
 
 .tab-icon {
-  margin: 0 0 4px 0;
+  margin: 0 0 3px 0;
   opacity: 0.6;
 }
 
 .tabbrowser-tab:not([selected="true"]):hover .tab-icon,
 .tabbrowser-tab[selected="true"] .tab-icon {
   opacity: 1.0;
 }
 
@@ -1649,27 +1625,30 @@ toolbarbutton.chevron > .toolbarbutton-m
 .tabbrowser-tab[busy] > .tab-icon-image,
 .tabbrowser-tab[busy] > .tab-image-middle > .tab-icon > .tab-icon-image {
  list-style-image: url("chrome://global/skin/icons/loading_16.png") !important; 
 }
 
 .tabbrowser-tab {
   -moz-binding: url("chrome://browser/skin/browser.xml#tabbrowser-tab") !important;
   -moz-appearance: none;
+  -moz-border-radius: 0 0 3px 3px;
   color: #222;
   -moz-box-pack: center;
+  margin: 0 3px 3px 2px;
   padding: 0px;
   border: none !important;
   min-width: 1px !important;
   text-align: center;
-  height: 27px;
+  height: 22px;
 }
 
 .tabbrowser-tab[selected="true"] {
   -moz-user-focus: normal;
+  background-color: -moz-mac-chrome-active;
 }
 
 .tabbrowser-tab[selected="true"]:focus > .tab-image-middle > .tab-text-stack > .tab-text {
   outline: 2px solid #4F8EC9;
   outline-offset: -2px;
   -moz-outline-radius: 3px;
 }
 
@@ -1680,73 +1659,74 @@ toolbarbutton.chevron > .toolbarbutton-m
 
 .tab-image-left,
 .tab-image-right {
   width: 8px;
   margin: 0px;
   padding: 0px;
 }
 
+.tab-image-left,
+.tab-image-right,
+.tabbrowser-tab > .tab-image-middle,
+.tabbrowser-tab > .tab-close-button {
+  margin-bottom: -3px;
+  padding-top: 1px;
+}
+
 .tabbrowser-tab > .tab-image-right,
 .tabbrowser-tab[chromedir="rtl"] > .tab-image-left {
+  margin-right: -3px;
   background: url("chrome://browser/skin/tabbrowser/tab-right.png") no-repeat;
 }
 
 .tabbrowser-tab:not([selected="true"]) > .tab-image-right,
 .tabbrowser-tab:not([selected="true"])[chromedir="rtl"] > .tab-image-left {
   background: url("chrome://browser/skin/tabbrowser/tab-right-bkgnd.png") no-repeat;
 }
 
 .tabbrowser-tab > .tab-image-left,
 .tabbrowser-tab[chromedir="rtl"] > .tab-image-right {
+  margin-left: -2px;
   background: url("chrome://browser/skin/tabbrowser/tab-left.png") no-repeat;
 }
 
 .tabbrowser-tab:not([selected="true"]) > .tab-image-left,
 .tabbrowser-tab:not([selected="true"])[chromedir="rtl"] > .tab-image-right {
   background: url("chrome://browser/skin/tabbrowser/tab-left-bkgnd.png") no-repeat;
 }
 
 .tabbrowser-tab > .tab-image-middle,
-.tabbrowser-tab > .tab-closebutton {
+.tabbrowser-tab > .tab-close-button {
   background: url("chrome://browser/skin/tabbrowser/tab-middle.png") repeat-x;
   -moz-box-pack: center;
 }
 
 .tabbrowser-tab:not([selected="true"]) > .tab-image-middle,
 .tabbrowser-tab:not([selected="true"]) > .tab-close-button {
   background: url("chrome://browser/skin/tabbrowser/tab-middle-bkgnd.png");
 }
 
 .tabbrowser-tab:not([selected="true"]) > .tab-image-middle > .tab-icon > .tab-icon-image  {
   list-style-image: url("chrome://global/skin/tree/item-grayscale.png");
 }
 
-.tabs-closebutton {
-  margin: 0;
-  list-style-image: url("chrome://global/skin/icons/closetab.png") !important;
-}
-
-.tabs-closebutton:hover:active {
-  list-style-image: url("chrome://global/skin/icons/closetab-active.png") !important;
-  border: none !important;
-}
-
 .tabbrowser-strip {
   margin-top: -1px;
   border-bottom: 1px solid #404040;
   background-color: #9B9B9B;
 }
 
 .tabbrowser-tabs {
   border: none;
   -moz-box-pack: center;
   -moz-box-align: center;
   background: url("chrome://browser/skin/tabbrowser/tabbrowser-tabs-bkgnd.png") repeat-x;
-  height: 27px;
+  height: 25px;
+  margin-bottom: 0;
 }
 
 .tabs-left {
   display: -moz-box;
   width: 3px;
 }
 
 .tabbrowser-tabs[overflow="true"] .tabs-left {
@@ -1785,47 +1765,38 @@ tabbrowser > tabbox > tabpanels {
   -moz-margin-end: 0px !important;
   margin-top: 1px;
 }
 
 .tab-close-button {
   list-style-image: url("chrome://global/skin/icons/closetab.png");
   -moz-appearance: none;
   border: none !important;
-  padding: 0 0 4px 0;
+  padding: 0 0 3px 0;
   margin: 0;
   background: inherit;
   cursor: default;
 }
 
 .tab-close-button:hover,
 .tabbrowser-tab[selected="true"] > .tab-close-button:hover {
   list-style-image: url("chrome://global/skin/icons/closetab-hover.png");
 }
 
 .tab-close-button:hover:active,
 .tabbrowser-tab[selected="true"] > .tab-close-button:hover:active {
   list-style-image: url("chrome://global/skin/icons/closetab-active.png");
 }
 
-.tabbrowser-tab > .tab-close-button {
-  background-image: url("chrome://browser/skin/tabbrowser/tab-middle.png");
-  background-repeat: repeat-x;
-}
-
 .tabbrowser-tab[selected="true"] > .tab-close-button {
   /* Make this button focusable so clicking on it will not focus the tab while
      it's getting closed */
   -moz-user-focus: normal;
 }
 
-.tabbrowser-tab:not([selected="true"]) > .tab-close-button {
-  background-image: url("chrome://browser/skin/tabbrowser/tab-middle-bkgnd.png");
-}
-
 .tabbrowser-arrowscrollbox > .scrollbutton-up,
 .tabbrowser-arrowscrollbox > .scrollbutton-down-stack > .scrollbutton-down[chromedir="rtl"] {
   border: 0;
   border-right: 2px solid;
   -moz-border-right-colors: rgba(0,0,0,0.25) rgba(255,255,255,0.15);
   list-style-image: url("chrome://browser/skin/tabbrowser/tab-arrow-start.png");
   -moz-image-region: rect(0px, 7px, 11px, 0px);
   padding: 0;
@@ -1892,18 +1863,17 @@ tabbrowser > tabbox > tabpanels {
 }
 
 .tabs-alltabs-button {
   list-style-image: url("chrome://browser/skin/tabbrowser/alltabs-box-bkgnd-icon.png");
   -moz-border-start: 2px solid;
   -moz-border-left-colors: rgba(0,0,0,0.25) rgba(255,255,255,0.15);
   -moz-border-right-colors: rgba(0,0,0,0.25) rgba(255,255,255,0.15);
   margin: 0;
-  padding-left: 0;
-  padding-right: 0;
+  padding: 2px 0 0 0;
 }
 .tabs-alltabs-button:hover {
   background-color: rgba(0,0,0,0.10);
 }
 .tabs-alltabs-button:hover:active,
 .tabs-alltabs-button[open="true"] {
   background-color: rgba(0,0,0,0.20);
 }
--- a/browser/themes/pinstripe/browser/jar.mn
+++ b/browser/themes/pinstripe/browser/jar.mn
@@ -1,12 +1,11 @@
 classic.jar:
 % skin browser classic/1.0 %skin/classic/browser/
-  skin/classic/browser/bookmark_toolbar_background.gif
-  skin/classic/browser/bookmark_toolbar_background-inactive.png
+  skin/classic/browser/bookmark_toolbar_background.png
   skin/classic/browser/bookmark-open-left.png
   skin/classic/browser/bookmark-open-mid.png
   skin/classic/browser/bookmark-open-right.png
 * skin/classic/browser/browser.css                          (browser.css)
   skin/classic/browser/browser.xml
   skin/classic/browser/contextDialogBackground.png
 * skin/classic/browser/engineManager.css                    (engineManager.css)
   skin/classic/browser/expander-round.png 
@@ -124,26 +123,20 @@ classic.jar:
   skin/classic/browser/tabbrowser/tab-arrow-start-bkgnd-animate.png      (tabbrowser/tab-arrow-start-bkgnd-animate.png)
   skin/classic/browser/tabbrowser/tab-arrow-end.png                      (tabbrowser/tab-arrow-end.png)
   skin/classic/browser/tabbrowser/tab-arrow-end-bkgnd.png                (tabbrowser/tab-arrow-end-bkgnd.png)
   skin/classic/browser/tabbrowser/tab-arrow-end-bkgnd-animate.png        (tabbrowser/tab-arrow-end-bkgnd-animate.png)
   skin/classic/browser/tabbrowser/tabbrowser-tabs-bkgnd.png              (tabbrowser/tabbrowser-tabs-bkgnd.png)
   skin/classic/browser/tabbrowser/tabDragIndicator.png                   (tabbrowser/tabDragIndicator.png)
   skin/classic/browser/tabbrowser/tab-left.png                           (tabbrowser/tab-left.png)
   skin/classic/browser/tabbrowser/tab-left-bkgnd.png                     (tabbrowser/tab-left-bkgnd.png)
-  skin/classic/browser/tabbrowser/tab-left-hover.png                     (tabbrowser/tab-left-hover.png)
-  skin/classic/browser/tabbrowser/tab-left-inactive.png                  (tabbrowser/tab-left-inactive.png)
   skin/classic/browser/tabbrowser/tab-middle.png                         (tabbrowser/tab-middle.png)
   skin/classic/browser/tabbrowser/tab-middle-bkgnd.png                   (tabbrowser/tab-middle-bkgnd.png)
-  skin/classic/browser/tabbrowser/tab-middle-hover.png                   (tabbrowser/tab-middle-hover.png)
-  skin/classic/browser/tabbrowser/tab-middle-inactive.png                (tabbrowser/tab-middle-inactive.png)
   skin/classic/browser/tabbrowser/tab-right.png                          (tabbrowser/tab-right.png)
   skin/classic/browser/tabbrowser/tab-right-bkgnd.png                    (tabbrowser/tab-right-bkgnd.png)
-  skin/classic/browser/tabbrowser/tab-right-hover.png                    (tabbrowser/tab-right-hover.png)
-  skin/classic/browser/tabbrowser/tab-right-inactive.png                 (tabbrowser/tab-right-inactive.png)
   skin/classic/browser/tabbrowser/tabs-bottom-bg.png                     (tabbrowser/tabs-bottom-bg.png)
   skin/classic/browser/urlbar/endcap.png                                 (urlbar/endcap.png)
   skin/classic/browser/urlbar/endcap-rtl.png                             (urlbar/endcap-rtl.png)
   skin/classic/browser/urlbar/endcap-focused.png                         (urlbar/endcap-focused.png)
   skin/classic/browser/urlbar/endcap-focused-rtl.png                     (urlbar/endcap-focused-rtl.png)
   skin/classic/browser/urlbar/startcap.png                               (urlbar/startcap.png)
   skin/classic/browser/urlbar/startcap-rtl.png                           (urlbar/startcap-rtl.png)
   skin/classic/browser/urlbar/startcap-focused.png                       (urlbar/startcap-focused.png)
--- a/browser/themes/pinstripe/browser/pageInfo.css
+++ b/browser/themes/pinstripe/browser/pageInfo.css
@@ -34,37 +34,23 @@
  * 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 ***** */
 
 @import "chrome://global/skin/";
 
-#main-window {
-  -moz-binding: url("chrome://global/skin/globalBindings.xml#unifiedWindow");
-}
-
-#main-window:not([active="true"]) > #topStackBar {
-  background-image: url("chrome://global/skin/toolbar/toolbar-background-inactive.png");
-  background-color: #cfcfcf;
-  border-bottom: 1px solid rgba(0,0,0,0.35);
-}
-
 #main-window:not([active="true"]) > #topStackBar > #viewGroup {
   opacity: 0.7;
 }
 
 #topStackBar {
   display: -moz-box;
-  background-color: #969696;
-  border-bottom: 1px solid #404040;
-  background-image: url("chrome://global/skin/toolbar/toolbar-background.gif");
-  background-repeat: repeat-x;
-  background-position: top right;
+  -moz-appearance: -moz-mac-unified-toolbar;
   padding: 4px 0 8px;
   -moz-box-pack: center;
 }
 
 /* View buttons */
 
 #viewGroup {
   border: 1px solid #404040;
--- a/browser/themes/pinstripe/browser/places/organizer.css
+++ b/browser/themes/pinstripe/browser/places/organizer.css
@@ -1,22 +1,10 @@
-/* Unified toolbar */
-
-#places {
-  -moz-binding: url("chrome://global/skin/globalBindings.xml#unifiedWindow");
-}
-
 /* Inactive Window */
 
-#places:not([active="true"]) > #placesToolbox > #placesToolbar {
-  background-image: url("chrome://global/skin/toolbar/toolbar-background-inactive.png");
-  background-color: #cfcfcf;
-  border-bottom: 1px solid rgba(0,0,0,0.35);
-}
-
 #places:not([active="true"]) > #placesToolbox > #placesToolbar > toolbarbutton,
 #places:not([active="true"]) > #placesToolbox > #placesToolbar > #searchFilter {
   opacity: 0.7;
 }
 
 #places:not([active="true"]) > #placesView > #placesList {
   background-color: #e8e8e8;
 }
@@ -74,21 +62,16 @@
 }
 
 #placesList treechildren::-moz-tree-cell-text(selected) {  
   font-weight: bold !important;
   color: #ffffff !important;
 }
 
 #placesToolbar {
-  background-color: #999;
-  border-bottom: 1px solid #404040;
-  background-image: url("chrome://global/skin/toolbar/toolbar-background.gif");
-  background-repeat: repeat-x;
-  background-position: 3px 0px;
   margin-top: -3px;
   padding: 0 4px;
 }
 
 #placesView {
   border-top: none !important;
 }
 
index 19ae80a16c68b590d431f7a017a7965f946a7ded..a69f8b29c35834d730354a56a9e29cb7570e203f
GIT binary patch
literal 3563
zc$@+24HWW;P)<h;3K|Lk000e1NJLTq001xm001xu1^@s6R|5Hm0000PbVXQnQ*UN;
zcVTj606}DLVr3vnZDD6+Qe|Oed2z{QJOBU<jY&j7RCwCdSq*F)*KwZxzrDL%?%nZt
zBt?oxnX;+cl4u(>oFFNw+C}Obs#BwIQ?!mGI4WGUfL*w5+N8ElK#Zh-5!h||<0J@#
zra^%^KSh-wma8I^+c>sis+1zdvPqFgN|Z?P=l<{Z|8-{XD4pq}B-%x#4lvxuxAVPy
z^WMCfZ}-FlU-}lb5=D_<d@(f5^N`<>Fz>W12R0&v|M^lV%L`DrJ!bA)55Me6R~u#;
zHII7ddIo%}PC?+|7bSg9@2vyrO#=f%r;GX?>bqVc+jlGaW9h+xzTT|^JKinpk8K3s
zkUgLpX$ToZL3<+(gu@}wlF3Ya&!&80)24h|M@NSGu2;x5p6YnEqi0hg)zedmccl(&
z1mBQMTkjy~J%d5}x*edE8e56%i5juA>#-+2pFJ5dj5PIK&nlA5sbX}$9*=GI7(DGU
z_Ou=|dZ}*%yRb*ll4-TQ2SSN%;KIrDdb=Qu{OUtNgW~|+IM3Ra+{nH0uC5nUUCTev
zRoK_BR!+QIQuZ={k;x0y@$9ml?``9(wF41;e4fQt{KzMgo4UTLwY8OollkA@9I70j
zsfIoWj15oCS5BSJ*|{!_GgomnUuYht4fS5s7s7oz3^`%|0}foD2d^+kp)}q&6PKSa
zzP%VaAcvF@L6nAKU6K)LGeB$a0IO#0ot!!!7+H2-CK^v3@;n%=6!LJY>f}Aw9k)$$
zR2D&26lGYHr0t1rS;y6ec(Mb`n)!zlXB&7f{hZN}`g@<jtEGG%rcAqNyY4C5w2pOa
zE=^_xbqFVG_(BNeL>eT$8*CTA_jnMrZt#r3w3pA0ip&C@WBG<NquirkevN7E?Z69s
zmIE$>4rlk>$sL<Lw*Zq<bHM}#wrqmUy(u{K-)xxqER7>%Jl9K?mKH&kc`%X*5C!o(
z59~Qk;HDqm21jPkU4qGm0|U48Aie{B@DBGW-}C!1&c5i{PET%W38Z2c+}KtSBQX%<
zFi5h3R~6?Yf$u|I(GlCW!75k5G;MHe6<}5#65J$+Aw9M?n&>>_ShkU0SQy{kpFc5v
zvJAOg398llPM<|bR&qrciARqeo;LEaRLTe|3b?kvH>!XVOLo766Vh{+=8ykMXa246
zlcfM(S%bgJ(2l$|Z`_keb?Txa;|lwa+r_M@u-YL-+X9@TW2A9_=MKl_aPkaypy7ls
z0VlVCA~0Mm8AN{`z=gfSm!A0SiBn7AyzjA37nYYk^V;#bSK>l(p@yC^#sal$2Pzd4
zzB^{_l+^I3f^lYB_LINaxA@XP%pIG^hb-QQ2Mf97&-`?J?mr@aVXjuQuHdl-lq)qj
za@x8_jYf{D5nVSe>kGS5OE0{4ZutZ=i+Rsuzs|zl;Nog~sE$L*z-eyd)kPIcr$BLM
zpTxC!iJzLj2oI;{U$iXmP)KVxLRx&3icqV<#EG#{mnDpqMeERS_07LXSX$ltJ1>33
za{ZUJwsuXAC62C#4@crhMKPfja`wx+Iu^cswh^KzFZ#KuL)N)5F!4l~7CFr@TpEh)
zQptyM*#|y11|cVVh%iAK&E-oNt8=h-dww4iBICT80xcT;zyzporIdgR7sT;D`gmy{
zVF<f|p)xUf4tDqF9^s|%8C6Sxu0=k8r#{C^aJigx=C|)CK0+A6HpxD|G&NpYT!zI<
z9$cJrVeY&Ovso9;%{Z{Q=tF6F1)_eI4)4CpS;%!gSX$1*3?AB(Z&H^(F7=B+TKwjZ
zYLwRCa}TNoNfN>JgmJ%IHprGRge6&8E<kqXB21jbl*qvu(GUXs;n%GM-QWFjWmyyj
zV4QTus#Z0!B}^Uv{@So`!GaodTV#BOme{YhC}fV~1qar&>><mvv()#ESNH=$D3Rq+
zsa=m{Yn*JzmN2VgW4@yU>$uLKW!dLw@;@GvUeMzmS<+XIOD|HNZQ7??$G(kh3DZJ`
zay1Rl9J`{<m3Ge50-N{MA0l%!_&@x6v@g=WHS04!>r@so)5&Q;jRp7IS`H7Em6gIt
z%%FU_vOJl7{MX7e=+osQ_HSeQ*6#kn_izU;n#BbODWR^gX5cs+REjx_WpiHDlX$AR
zuGy(~Z++<Q;soKF$Xs8|k+VNrxGxwmrCx+hk(uDeT%`{dYF)Gm@UhfUP$ioxb8u6v
zmwy3VCZ<ha23}IrETV$T^P`OCGguqIQ^Og|XCscN;C9u(LtDhmtcDPUhsQ|+9!Q|7
zkuFIN;XL^<lW_+*p95J_Gm_@t#bNrhYBhYIycIDM&AW(_uGk6~@<r&=W+9=jjIMGZ
zLs`jm)@DX#N_{{!EgayX>Iq=E97w!4%6VMo$QR+*;?hbma<bjn^{Ip0Fvf7k_3RN3
z%RgaO9iRoUaHuNwd!G2VXTibeKkNQ*ajDS2w;leoZ}YpQkaWQE?YnKXCCnNJpgmGT
z9bcXJv8G$Q(4k?}OrvUF386pEeETEu@oNa3C-P$FdIn$1Ji0FUzK8Z-;yA8y^k2W;
zzacuk5k7tuc}xh$`h>8tgW4Mf|Hkh;@p)g6lO8Xnsr_LbxGp|^6?wLO%Qi@)w^94R
zM!}X@eM*gY;`((4?TtEc-F$o<*{>L>&3dvMnQb@7da9TDHnRF4t4S#u11V~NFRID)
zc0pY8e_JEZW<s5}1f_#vN|TdYz?xaiG-7(Z5!bCGhI%*ZGe*w<@VpQdAgyZ)EEgA^
zZQ$QV&9wsW{=Gj<`o8x`vs!*iY~M^rG<Y8nqe-yxvrj$vyMHo)WB%vi?>xWQe25RU
z;^SKHHsAyivnL10RH1bK9Y8(~Yxy{;j5>_E9q~FRsi1fDLwnyK@S+F|(<l-@Sk9h-
z@}+6uJQLGAE28}=$~2Rw-%5C%^D)nLZt)olGhRY!oj{7)1su-@czpK&GdB-@Z5agS
z;KFcKe1ADB2-45U0rpY&IEkFP4MG}jx1v%31Cdmc@Zq@rtidi3Uqwc0RxGRqRj?{~
zP^|ah^w>|p3wMB^gz=d&2<SA`3)($o(*d4gwsmn37Z-w3uWuvMb*m8N7K0Gl`%(Bf
z5lzuIUy2$D4BH5Bh^MfjoeStR;>i)7mqAf+btQ(5R)Du~MJ;$-#d2*i=PM#Q0JwY5
zn6%r#QQHr$$gczyBplvH=lEI?)R6Y)!aXAoe<VJRI_6Xhmhbxat44S5P#}lBx_YZu
zmo=^&R4<(buRQYwdiVX#-+un5gSY>(YTMQ)KsGM#I^k#`J@3l@tK$jg1<(}xuYUY5
ze|?Y~peT5gnYpxUnnR94POxC2tCJ=tsue%r=t}uGguQ@||3%aJ`!A=GyWO$O+hx7(
z1PdPAn6yts&JV_`TpR<hH2pGSo*>{`qd$Pj({CQ#I=J&*$Epo@qJfiSO-|IWj*WPn
zmt@UCM6A4W<hx(nw>AqAA0NuI^ia)f!w0ee;Mfp^0!P^hi*l#>em>qLk5m`Wz9U3$
z83aMcbHjp(&~Ewx>*Fvii@=qq&yej}@T=eZy9e(7^dC$YONq4OtHA;WJKzRU1za%M
z8pPE?_SNrw{ekt;=!W_DT3K0g@DO_eL*=<TQw`!6|6rJbP@l`XQp~&HPz<&ZJe}99
z0|6iBc-D-nF9C|_Yg8$QuJZgr7oxay41#Z1+!Z`!6qk#T1GlXQ_B=OTbwZS8TRz`m
zp}=OnN=$qlOoxLS#+xq8!8ZMM*rvT6w5iW@cpw|HZSnlAE<S(=CWW47VwNeq0WALp
zxY%|moG>$y4cWFRV!vb~BX-cnM%xfi;W`DKp{bxvef4`nVB2a3J`^8sk^zccurGn+
zXHgf%u<u~-5NAHagw$P*(2uLAg2<WVz(g|`EAXI=FE?Sa0C8mnjEM7dSy6-M>()Xh
zUs>6{V#R@M$QHYQ@qrNfFnqjOR3Qhd`{vt?iT|+a)?vw8*o}Gs_x$el@KMDCBf1bw
z{73)%H{Wl%^?jrf4;$zRzLIXo(sL!ke)8J!mV=4-!XeAjEb$)8a<+TE*V1m}lOOg~
z;eSV3vQd2RrBCGhJ5%vq)H@=P(0=N>8Kvc{=o3nt9(g7aZv#?lQ{Vp!2WX{LRo<`b
zk={^922yHM-_5uS{F=!diXz>wYmsLn;SkZ*K&g#=e~I_*Bb%Ga0a20V=OjrO76joA
zQ54$3ssgc?28tpF^r8M;Q>MPnNGXn1YZiTtD0rTC5~(d^s%LJb1KfKP=a{C2gSe;f
zJCYb=pWw5}ssqG@JY-e2?O>7eg3l=qGQ4830=I7M<!<N>P=<*a+Ba|)FkD*4I5|Sj
zk=BcjUw^Ui{l{+j8K_pRZ`zLY^hSY*c?z-Ly5SDcC-SAG!t=G7{ZF*A*AlWp+kZsN
zR|$K=9iU%Q=;t5QM{V0Z$rxMLxbbVt3AEiq7{cCg2Yh^e!cc&Gp$yfU3D<I<W;SdQ
z<1_!pI}q@2zn)d_6>!J3Lx}Ap+x5874RL@zp<}^HH>b|^vJu&!Z662RP2@n3CdJDR
zP^jQ4AFEc)U8K}reJ>^(vb~z4|EF~z@Pe;Ttp0P8d(5=#Ou1YerJq(wuvUyjqv~)-
lk%RYv#xB6k5JmqZzyRUDdIn`mBRK#7002ovPDHLkV1iMt>(c-L
--- a/browser/themes/pinstripe/browser/preferences/preferences.css
+++ b/browser/themes/pinstripe/browser/preferences/preferences.css
@@ -34,26 +34,16 @@
 # 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 *****
 */
 
-#BrowserPreferences {
-  -moz-binding: url("chrome://global/skin/globalBindings.xml#unifiedPrefwindow");
-}
-
-#BrowserPreferences:not([active="true"]) > .paneSelector {
-  background-image: url("chrome://global/skin/toolbar/toolbar-background-tall-inactive.png");
-  background-color: #cfcfcf;
-  border-bottom: 1px solid rgba(0,0,0,0.35);
-}
-
 #BrowserPreferences:not([active="true"]) > .paneSelector > radio {
   opacity: 0.7;
 }
 
 .prefWindow-dlgbuttons {
   margin: 0 12px 8px 12px;
 }
 
@@ -64,21 +54,17 @@
 .windowDialog {
   padding: 12px;
   font: -moz-dialog;
 }
 
 .paneSelector {
   list-style-image: url("chrome://browser/skin/preferences/Options.png");
   padding: 0 5px 2px 5px;
-  background-color: #999;
-  border-bottom: 1px solid #404040;
-  background-image: url("chrome://global/skin/toolbar/toolbar-background-tall.png");
-  background-repeat: repeat-x;
-  background-position: top right;
+  -moz-appearance: -moz-mac-unified-toolbar;
   margin: 0;
 }
 
 .paneSelector > radio[pane] {
   -moz-binding: url("chrome://browser/skin/browser.xml#radio-shadow") !important;
 }
 
 .paneSelector radio {
deleted file mode 100755
index 2ed07645bf1de4037889dd7e45ec659ecfdc446c..0000000000000000000000000000000000000000
GIT binary patch
literal 0
Hc$@<O00001
deleted file mode 100644
index 56dbbed45812fea20e23ac1ce4ba3fdfea1ca4f9..0000000000000000000000000000000000000000
GIT binary patch
literal 0
Hc$@<O00001
index 128a879c2635cf2380d04bde9c9c6c98be0c69c6..ab8fb0bdccf67c186cf433a6fe4fd7f163b20f9f
GIT binary patch
literal 318
zc%17D@N?(olHy`uVBq!ia0vp^96&6|!3-p=qvy8+shj|x5ZC|z|1*HWe<T3mGGGJ9
z>hUPU3S7z!jshu_k|4ie2CYbODQ13EHbv2BHf|O(P90exf1U{WU`s(GNACa*ehDUz
zY~FkSfa+sCT^vIy;!4j(^0g=kumprm2`#vPedh1`7a4lhB!0hMs<qPX`$V>YV+}7H
zrJMrhi|D5)y1bqIL|Wnk;|Ye)ugl-PUQ(I8@%yY@Z|C&LB<37>mU`Dmt$(uN?SE4y
YiC<J^4iFFWR0lcG)78&qol`;+060Ql7XSbN
deleted file mode 100755
index b18dbddc8b4e5e325add1169098120b64258c5b9..0000000000000000000000000000000000000000
GIT binary patch
literal 0
Hc$@<O00001
deleted file mode 100644
index 500cabe51d0a8abe6e2e615c0ad66433c537223e..0000000000000000000000000000000000000000
GIT binary patch
literal 0
Hc$@<O00001
index 10b990b483237a571b98aa468496fcd025a7b464..02b8bdb3dcf4713ccb8aa29fd5476b334d99d786
GIT binary patch
literal 161
zc%17D@N?(olHy`uVBq!ia0vp^96&6|!VDz;tuAT<QqloFA+G=b|7U=K|6l;;uJ$aN
z4Wu|rg8YIR6xjmArTmpy*cu!?fPy-nE{-7;aeEI~3o<D1Fkgr`apaz6^}AIJG9uh}
oU;l6CmfN@Ux5yp8f*lJ2Y&1497hk@pAqX<m)78&qol`;+0N08yN&o-=
deleted file mode 100755
index db9d4af3e6a7c3fe83754f1396cb11bbbc6e5a92..0000000000000000000000000000000000000000
GIT binary patch
literal 0
Hc$@<O00001
deleted file mode 100644
index 62063ef3ac1beb0073d97c1c3e9d5a53ce280d43..0000000000000000000000000000000000000000
GIT binary patch
literal 0
Hc$@<O00001
index b2a6b5a47c0c3e0202247a2fd63e79e2279b3b20..7d218171da82206e96a1f2e41e1c5a616dd06829
GIT binary patch
literal 333
zc%17D@N?(olHy`uVBq!ia0vp^96&6|!3-p=qvy8+sr&$+5ZC|z|1*FAgaId!#o=sZ
zmAJV00e^6_1CUZJ3GxeO(2V5d5NBfJQRS54XH(=hWA+Qw4ige{6O7UjwUG94Hj<a%
zw|lRA4yYl+)5S5QA};l;JKqrn9@YR484hEIs{G6E>W>*7id#_8IPahNCXeN&0uxWV
zcco3;cxlFx6OvDP%@)TitFx;6`$#y1`b(HOrN1~*vx~v{YPZvrUEdn^-rx^TEZBQ*
j9~bxh_xvFZht1E(tEn(Q7CjZG26C*YtDnm{r-UW|5%*qG
--- a/browser/themes/winstripe/browser/browser.css
+++ b/browser/themes/winstripe/browser/browser.css
@@ -1804,22 +1804,16 @@ toolbar[mode="text"] > #window-controls 
 }
 
 toolbarbutton.bookmark-item[dragover="true"][open="true"] {
   -moz-appearance: none;
   background: Highlight !important;
   color: HighlightText !important;
 }
 
-/* Bookmark drag and drop styles */
-.bookmark-item[dragover-into="true"] > .menu-iconic-text {
-  background: Highlight !important;
-  color: HighlightText !important;
-}
-
 /* rules for menupopup drop indicators */
 .menupopup-drop-indicator-bar {
   position: relative;
   /* these two margins must together compensate the indicator's height */
   margin-top: -1px;
   margin-bottom: -1px;
 }
 
--- a/build/unix/abs2rel.pl
+++ b/build/unix/abs2rel.pl
@@ -1,10 +1,10 @@
-#!env perl
-
+#!env perl
+
 # ***** 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/
 #
@@ -30,38 +30,38 @@
 # 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 *****
-
-use File::Spec::Unix;
-use strict;
-
-print "Usage: $0 dest_path start_path\n" if ($#ARGV+1 != 2);
-my $finish = my_canonpath(shift);
-my $start = my_canonpath(shift);
-
-my $res = File::Spec::Unix->abs2rel($finish, $start);
-
-#print STDERR "abs2rel($finish,$start) = $res\n";
-print "$res\n";
-
-sub my_canonpath($) {
-    my ($file) = @_;
-    my (@inlist, @outlist, $dir);
-
-    # Do what File::Spec::Unix->no_upwards should do
-    my @inlist = split(/\//, File::Spec::Unix->canonpath($file));
-    foreach $dir (@inlist) {
-	if ($dir eq '..') {
-	    pop @outlist;
-	} else {
-	    push @outlist, $dir;
-	}
-    }
-    $file = join '/',@outlist;
-    return $file;
-}
-
+
+use File::Spec::Unix;
+use strict;
+
+print "Usage: $0 dest_path start_path\n" if ($#ARGV+1 != 2);
+my $finish = my_canonpath(shift);
+my $start = my_canonpath(shift);
+
+my $res = File::Spec::Unix->abs2rel($finish, $start);
+
+#print STDERR "abs2rel($finish,$start) = $res\n";
+print "$res\n";
+
+sub my_canonpath($) {
+    my ($file) = @_;
+    my (@inlist, @outlist, $dir);
+
+    # Do what File::Spec::Unix->no_upwards should do
+    my @inlist = split(/\//, File::Spec::Unix->canonpath($file));
+    foreach $dir (@inlist) {
+	if ($dir eq '..') {
+	    pop @outlist;
+	} else {
+	    push @outlist, $dir;
+	}
+    }
+    $file = join '/',@outlist;
+    return $file;
+}
+
new file mode 100644
--- /dev/null
+++ b/build/wince/shunt/build/vs9/mozce_shunt_static.sln
@@ -0,0 +1,62 @@
+
+Microsoft Visual Studio Solution File, Format Version 10.00
+# Visual Studio 2008
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mozce_shunt_static", "mozce_shunt_static.vcproj", "{082BAB06-D10F-4C57-B123-F84DC06C246D}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Pocket PC 2003 (ARMV4) = Debug|Pocket PC 2003 (ARMV4)
+		Debug|Smartphone 2003 (ARMV4) = Debug|Smartphone 2003 (ARMV4)
+		Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)
+		Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I)
+		Debug|Windows Mobile 6 Professional SDK (ARMV4I) = Debug|Windows Mobile 6 Professional SDK (ARMV4I)
+		Debug|Windows Mobile 6 Standard SDK (ARMV4I) = Debug|Windows Mobile 6 Standard SDK (ARMV4I)
+		Release|Pocket PC 2003 (ARMV4) = Release|Pocket PC 2003 (ARMV4)
+		Release|Smartphone 2003 (ARMV4) = Release|Smartphone 2003 (ARMV4)
+		Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)
+		Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I)
+		Release|Windows Mobile 6 Professional SDK (ARMV4I) = Release|Windows Mobile 6 Professional SDK (ARMV4I)
+		Release|Windows Mobile 6 Standard SDK (ARMV4I) = Release|Windows Mobile 6 Standard SDK (ARMV4I)
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Pocket PC 2003 (ARMV4).ActiveCfg = Debug|Pocket PC 2003 (ARMV4)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Pocket PC 2003 (ARMV4).Build.0 = Debug|Pocket PC 2003 (ARMV4)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Pocket PC 2003 (ARMV4).Deploy.0 = Debug|Pocket PC 2003 (ARMV4)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Smartphone 2003 (ARMV4).ActiveCfg = Debug|Smartphone 2003 (ARMV4)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Smartphone 2003 (ARMV4).Build.0 = Debug|Smartphone 2003 (ARMV4)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Smartphone 2003 (ARMV4).Deploy.0 = Debug|Smartphone 2003 (ARMV4)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Standard SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Standard SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Standard SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Pocket PC 2003 (ARMV4).ActiveCfg = Release|Pocket PC 2003 (ARMV4)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Pocket PC 2003 (ARMV4).Build.0 = Release|Pocket PC 2003 (ARMV4)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Pocket PC 2003 (ARMV4).Deploy.0 = Release|Pocket PC 2003 (ARMV4)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Smartphone 2003 (ARMV4).ActiveCfg = Release|Smartphone 2003 (ARMV4)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Smartphone 2003 (ARMV4).Build.0 = Release|Smartphone 2003 (ARMV4)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Smartphone 2003 (ARMV4).Deploy.0 = Release|Smartphone 2003 (ARMV4)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Standard SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Windows Mobile 6 Standard SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Standard SDK (ARMV4I)
+		{082BAB06-D10F-4C57-B123-F84DC06C246D}.Release|Windows Mobile 6 Standard SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Standard SDK (ARMV4I)
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
new file mode 100644
--- /dev/null
+++ b/build/wince/shunt/build/vs9/mozce_shunt_static.vcproj
@@ -0,0 +1,1261 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9.00"
+	Name="mozce_shunt_static"
+	ProjectGUID="{082BAB06-D10F-4C57-B123-F84DC06C246D}"
+	RootNamespace="mozce_shunt_static"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="131072"
+	>
+	<Platforms>
+		<Platform
+			Name="Pocket PC 2003 (ARMV4)"
+		/>
+		<Platform
+			Name="Smartphone 2003 (ARMV4)"
+		/>
+		<Platform
+			Name="Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
+		/>
+		<Platform
+			Name="Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
+		/>
+		<Platform
+			Name="Windows Mobile 6 Professional SDK (ARMV4I)"
+		/>
+		<Platform
+			Name="Windows Mobile 6 Standard SDK (ARMV4I)"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Pocket PC 2003 (ARMV4)"
+			OutputDirectory="Pocket PC 2003 (ARMV4)\$(ConfigurationName)"
+			IntermediateDirectory="Pocket PC 2003 (ARMV4)\$(ConfigurationName)"
+			ConfigurationType="4"
+			CharacterSet="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="1"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				ExecutionBucket="7"
+				Optimization="0"
+				AdditionalIncludeDirectories="..\..\include"
+				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);_DEBUG;DEBUG;_LIB;$(ARCHFAM);$(_ARCHFAM_);MOZCE_STATIC_BUILD;MOZCE_SHUNT_EXPORTS"
+				MinimalRebuild="true"
+				ExceptionHandling="0"
+				RuntimeLibrary="1"
+				BufferSecurityCheck="false"
+				EnableFunctionLevelLinking="true"
+				TreatWChar_tAsBuiltInType="false"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="_DEBUG;_UNICODE;UNICODE;_WIN32_WCE;UNDER_CE"
+				Culture="1033"
+				AdditionalIncludeDirectories="$(IntDir)"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+				AdditionalOptions=" /subsystem:windowsce,5.01 /machine:THUMB"
+				OutputFile="$(InputDir)/shunt_dbg.lib"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCCodeSignTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+			<DeploymentTool
+				ForceDirty="-1"
+				RemoteDirectory=""
+				RegisterOutput="0"
+				AdditionalFiles=""
+			/>
+			<DebuggerTool
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|Smartphone 2003 (ARMV4)"
+			OutputDirectory="Smartphone 2003 (ARMV4)\$(ConfigurationName)"
+			IntermediateDirectory="Smartphone 2003 (ARMV4)\$(ConfigurationName)"
+			ConfigurationType="4"
+			CharacterSet="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="1"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				ExecutionBucket="7"
+				Optimization="0"
+				AdditionalIncludeDirectories="..\..\include"
+				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);_DEBUG;DEBUG;_LIB;$(ARCHFAM);$(_ARCHFAM_);MOZCE_STATIC_BUILD;MOZCE_SHUNT_EXPORTS"
+				MinimalRebuild="true"
+				ExceptionHandling="0"
+				RuntimeLibrary="1"
+				BufferSecurityCheck="false"
+				EnableFunctionLevelLinking="true"
+				TreatWChar_tAsBuiltInType="false"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="_DEBUG;_UNICODE;UNICODE;_WIN32_WCE;UNDER_CE"
+				Culture="1033"
+				AdditionalIncludeDirectories="$(IntDir)"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+				AdditionalOptions=" /subsystem:windowsce,5.01 /machine:THUMB"
+				OutputFile="$(InputDir)/shunt_dbg.lib"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCCodeSignTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+			<DeploymentTool
+				ForceDirty="-1"
+				RemoteDirectory=""
+				RegisterOutput="0"
+				AdditionalFiles=""
+			/>
+			<DebuggerTool
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
+			OutputDirectory="$(PlatformName)\Debug"
+			IntermediateDirectory="$(PlatformName)\Debug"
+			ConfigurationType="2"
+			CharacterSet="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				ExecutionBucket="7"
+				Optimization="0"
+				AdditionalIncludeDirectories="..\..\include"
+				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);_DEBUG;DEBUG;_LIB;$(ARCHFAM);$(_ARCHFAM_);MOZCE_STATIC_BUILD;MOZCE_SHUNT_EXPORTS"
+				MinimalRebuild="true"
+				ExceptionHandling="0"
+				RuntimeLibrary="1"
+				BufferSecurityCheck="false"
+				EnableFunctionLevelLinking="true"
+				TreatWChar_tAsBuiltInType="false"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="_DEBUG;_UNICODE;UNICODE;_WIN32_WCE;UNDER_CE"
+				Culture="1033"
+				AdditionalIncludeDirectories="$(IntDir)"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalOptions=" /SUBSYSTEM:WINDOWSCE,5.01 /MACHINE:THUMB"
+				OutputFile="$(OutDir)\mozce_shunt.dll"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCCodeSignTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+			<DeploymentTool
+				ForceDirty="-1"
+				RemoteDirectory=""
+				RegisterOutput="0"
+				AdditionalFiles=""
+			/>
+			<DebuggerTool
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
+			OutputDirectory="Windows Mobile 5.0 Smartphone SDK (ARMV4I)\$(ConfigurationName)"
+			IntermediateDirectory="Windows Mobile 5.0 Smartphone SDK (ARMV4I)\$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="1"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				ExecutionBucket="7"
+				Optimization="0"
+				AdditionalIncludeDirectories="..\..\include"
+				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);_DEBUG;DEBUG;_LIB;$(ARCHFAM);$(_ARCHFAM_);MOZCE_STATIC_BUILD;MOZCE_SHUNT_EXPORTS"
+				MinimalRebuild="true"
+				ExceptionHandling="0"
+				RuntimeLibrary="1"
+				BufferSecurityCheck="false"
+				EnableFunctionLevelLinking="true"
+				TreatWChar_tAsBuiltInType="false"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="_DEBUG;_UNICODE;UNICODE;_WIN32_WCE;UNDER_CE"
+				Culture="1033"
+				AdditionalIncludeDirectories="$(IntDir)"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalOptions=" /SUBSYSTEM:WINDOWSCE,5.01 /MACHINE:THUMB"
+				OutputFile="$(OutDir)\mozce_shunt.dll"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCCodeSignTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+			<DeploymentTool
+				ForceDirty="-1"
+				RemoteDirectory=""
+				RegisterOutput="0"
+				AdditionalFiles=""
+			/>
+			<DebuggerTool
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|Windows Mobile 6 Professional SDK (ARMV4I)"
+			OutputDirectory="Windows Mobile 6 Professional SDK (ARMV4I)\$(ConfigurationName)"
+			IntermediateDirectory="Windows Mobile 6 Professional SDK (ARMV4I)\$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="1"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				ExecutionBucket="7"
+				Optimization="0"
+				AdditionalIncludeDirectories="..\..\include"
+				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);_DEBUG;DEBUG;_LIB;$(ARCHFAM);$(_ARCHFAM_);MOZCE_SHUNT_EXPORTS;DEBUG_NSPR_ALL;TIMELINE;API_LOGGING;WINCE_MEMORY_CHECKPOINTING;SHUNT_LOG_ENABLED"
+				MinimalRebuild="true"
+				ExceptionHandling="0"
+				RuntimeLibrary="1"
+				BufferSecurityCheck="false"
+				EnableFunctionLevelLinking="true"
+				TreatWChar_tAsBuiltInType="false"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+				CompileAs="0"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="_DEBUG;_UNICODE;UNICODE;_WIN32_WCE;UNDER_CE"
+				Culture="1033"
+				AdditionalIncludeDirectories="$(IntDir)"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalOptions=" /SUBSYSTEM:WINDOWSCE,5.02"
+				OutputFile="$(OutDir)\mozce_shunt.dll"
+				GenerateDebugInformation="true"
+				ImportLibrary="$(OutDir)\mozce_shunt.lib"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCCodeSignTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy &quot;$(TargetDir)$(TargetName).dll&quot; &quot;$(ProjectDir)&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)$(TargetName).lib&quot; &quot;$(ProjectDir)&quot;&#x0D;&#x0A;"
+			/>
+			<DeploymentTool
+				ForceDirty="-1"
+				RemoteDirectory="\"
+				RegisterOutput="0"
+				AdditionalFiles=""
+			/>
+			<DebuggerTool
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|Windows Mobile 6 Standard SDK (ARMV4I)"
+			OutputDirectory="Windows Mobile 6 Standard SDK (ARMV4I)\$(ConfigurationName)"
+			IntermediateDirectory="Windows Mobile 6 Standard SDK (ARMV4I)\$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="1"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				ExecutionBucket="7"
+				Optimization="0"
+				AdditionalIncludeDirectories="..\..\include"
+				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);_DEBUG;DEBUG;_LIB;$(ARCHFAM);$(_ARCHFAM_);MOZCE_SHUNT_EXPORTS;DEBUG_NSPR_ALL;TIMELINE;API_LOGGING;WINCE_MEMORY_CHECKPOINTING;SHUNT_LOG_ENABLED"
+				MinimalRebuild="true"
+				ExceptionHandling="0"
+				RuntimeLibrary="1"
+				BufferSecurityCheck="false"
+				EnableFunctionLevelLinking="true"
+				TreatWChar_tAsBuiltInType="false"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+				CompileAs="0"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="_DEBUG;_UNICODE;UNICODE;_WIN32_WCE;UNDER_CE"
+				Culture="1033"
+				AdditionalIncludeDirectories="$(IntDir)"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalOptions=" /SUBSYSTEM:WINDOWSCE,5.02"
+				OutputFile="$(OutDir)\mozce_shunt.dll"
+				GenerateDebugInformation="true"
+				ImportLibrary="$(OutDir)\mozce_shunt.lib"
+				TargetMachine="0"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCCodeSignTool"
+				AuthenticodeSignature="false"
+				ProvisionDevice="0"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy &quot;$(TargetDir)$(TargetName).dll&quot; &quot;$(ProjectDir)&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)$(TargetName).lib&quot; &quot;$(ProjectDir)&quot;&#x0D;&#x0A;"
+			/>
+			<DeploymentTool
+				ForceDirty="-1"
+				RemoteDirectory="\"
+				RegisterOutput="0"
+				AdditionalFiles=""
+			/>
+			<DebuggerTool
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Pocket PC 2003 (ARMV4)"
+			OutputDirectory="Pocket PC 2003 (ARMV4)\$(ConfigurationName)"
+			IntermediateDirectory="Pocket PC 2003 (ARMV4)\$(ConfigurationName)"
+			ConfigurationType="4"
+			CharacterSet="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="1"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				ExecutionBucket="7"
+				Optimization="2"
+				AdditionalIncludeDirectories="..\..\include"
+				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);NDEBUG;_LIB;$(ARCHFAM);$(_ARCHFAM_);MOZCE_STATIC_BUILD;MOZCE_SHUNT_EXPORTS"
+				ExceptionHandling="1"
+				RuntimeLibrary="0"
+				BufferSecurityCheck="false"
+				EnableFunctionLevelLinking="true"
+				FloatingPointModel="2"
+				TreatWChar_tAsBuiltInType="false"
+				RuntimeTypeInfo="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+				CompileForArchitecture="0"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="NDEBUG;_UNICODE;UNICODE;_WIN32_WCE;UNDER_CE"
+				Culture="1033"
+				AdditionalIncludeDirectories="$(IntDir)"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+				AdditionalOptions=" /subsystem:windowsce,5.01 /machine:THUMB"
+				OutputFile="$(InputDir)/shunt.lib"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCCodeSignTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+			<DeploymentTool
+				ForceDirty="-1"
+				RemoteDirectory=""
+				RegisterOutput="0"
+				AdditionalFiles=""
+			/>
+			<DebuggerTool
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Smartphone 2003 (ARMV4)"
+			OutputDirectory="Smartphone 2003 (ARMV4)\$(ConfigurationName)"
+			IntermediateDirectory="Smartphone 2003 (ARMV4)\$(ConfigurationName)"
+			ConfigurationType="4"
+			CharacterSet="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="1"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				ExecutionBucket="7"
+				Optimization="2"
+				AdditionalIncludeDirectories="..\..\include"
+				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);NDEBUG;_LIB;$(ARCHFAM);$(_ARCHFAM_);MOZCE_STATIC_BUILD;MOZCE_SHUNT_EXPORTS"
+				ExceptionHandling="1"
+				RuntimeLibrary="0"
+				BufferSecurityCheck="false"
+				EnableFunctionLevelLinking="true"
+				FloatingPointModel="2"
+				TreatWChar_tAsBuiltInType="false"
+				RuntimeTypeInfo="true"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+				CompileForArchitecture="0"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="NDEBUG;_UNICODE;UNICODE;_WIN32_WCE;UNDER_CE"
+				Culture="1033"
+				AdditionalIncludeDirectories="$(IntDir)"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+				AdditionalOptions=" /subsystem:windowsce,5.01 /machine:THUMB"
+				OutputFile="$(InputDir)/shunt.lib"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCCodeSignTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+			<DeploymentTool
+				ForceDirty="-1"
+				RemoteDirectory=""
+				RegisterOutput="0"
+				AdditionalFiles=""
+			/>
+			<DebuggerTool
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
+			OutputDirectory="$(PlatformName)\Release"
+			IntermediateDirectory="$(PlatformName)\Release"
+			ConfigurationType="2"
+			CharacterSet="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				ExecutionBucket="7"
+				Optimization="2"
+				AdditionalIncludeDirectories="..\..\include"
+				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);NDEBUG;_LIB;$(ARCHFAM);$(_ARCHFAM_);MOZCE_STATIC_BUILD;MOZCE_SHUNT_EXPORTS"
+				ExceptionHandling="0"
+				RuntimeLibrary="0"
+				BufferSecurityCheck="false"
+				TreatWChar_tAsBuiltInType="false"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="NDEBUG;_UNICODE;UNICODE;_WIN32_WCE;UNDER_CE"
+				Culture="1033"
+				AdditionalIncludeDirectories="$(IntDir)"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalOptions=" /SUBSYSTEM:WINDOWSCE,5.01 /MACHINE:THUMB"
+				OutputFile="$(OutDir)\mozce_shunt.dll"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCCodeSignTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+			<DeploymentTool
+				ForceDirty="-1"
+				RemoteDirectory=""
+				RegisterOutput="0"
+				AdditionalFiles=""
+			/>
+			<DebuggerTool
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
+			OutputDirectory="Windows Mobile 5.0 Smartphone SDK (ARMV4I)\$(ConfigurationName)"
+			IntermediateDirectory="Windows Mobile 5.0 Smartphone SDK (ARMV4I)\$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="1"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				ExecutionBucket="7"
+				Optimization="2"
+				AdditionalIncludeDirectories="..\..\include"
+				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);NDEBUG;_LIB;$(ARCHFAM);$(_ARCHFAM_);MOZCE_STATIC_BUILD;MOZCE_SHUNT_EXPORTS"
+				ExceptionHandling="0"
+				RuntimeLibrary="0"
+				BufferSecurityCheck="false"
+				TreatWChar_tAsBuiltInType="false"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="NDEBUG;_UNICODE;UNICODE;_WIN32_WCE;UNDER_CE"
+				Culture="1033"
+				AdditionalIncludeDirectories="$(IntDir)"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalOptions=" /SUBSYSTEM:WINDOWSCE,5.01 /MACHINE:THUMB"
+				OutputFile="$(OutDir)\mozce_shunt.dll"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCCodeSignTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+			<DeploymentTool
+				ForceDirty="-1"
+				RemoteDirectory=""
+				RegisterOutput="0"
+				AdditionalFiles=""
+			/>
+			<DebuggerTool
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Windows Mobile 6 Professional SDK (ARMV4I)"
+			OutputDirectory="Windows Mobile 6 Professional SDK (ARMV4I)\$(ConfigurationName)"
+			IntermediateDirectory="Windows Mobile 6 Professional SDK (ARMV4I)\$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+				CommandLine=""
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="1"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				ExecutionBucket="7"
+				Optimization="2"
+				AdditionalIncludeDirectories="..\..\include"
+				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);NDEBUG;_LIB;$(ARCHFAM);$(_ARCHFAM_);MOZCE_SHUNT_EXPORTS"
+				ExceptionHandling="1"
+				RuntimeLibrary="0"
+				BufferSecurityCheck="false"
+				EnableFunctionLevelLinking="true"
+				FloatingPointModel="2"
+				TreatWChar_tAsBuiltInType="false"
+				RuntimeTypeInfo="false"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+				CompileAs="0"
+				CompileForArchitecture="0"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="NDEBUG;_UNICODE;UNICODE;_WIN32_WCE;UNDER_CE"
+				Culture="1033"
+				AdditionalIncludeDirectories="$(IntDir)"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalOptions=" /SUBSYSTEM:WINDOWSCE,5.02"
+				OutputFile="$(OutDir)\mozce_shunt.dll"
+				ImportLibrary="$(OutDir)\mozce_shunt.lib"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCCodeSignTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy &quot;$(TargetDir)$(TargetName).dll&quot; &quot;$(ProjectDir)&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)$(TargetName).lib&quot; &quot;$(ProjectDir)&quot;&#x0D;&#x0A;"
+			/>
+			<DeploymentTool
+				ForceDirty="-1"
+				RemoteDirectory=""
+				RegisterOutput="0"
+				AdditionalFiles=""
+			/>
+			<DebuggerTool
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Windows Mobile 6 Standard SDK (ARMV4I)"
+			OutputDirectory="Windows Mobile 6 Standard SDK (ARMV4I)\$(ConfigurationName)"
+			IntermediateDirectory="Windows Mobile 6 Standard SDK (ARMV4I)\$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+				CommandLine=""
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="1"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				ExecutionBucket="7"
+				Optimization="2"
+				AdditionalIncludeDirectories="..\..\include"
+				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);NDEBUG;_LIB;$(ARCHFAM);$(_ARCHFAM_);MOZCE_SHUNT_EXPORTS"
+				ExceptionHandling="1"
+				RuntimeLibrary="0"
+				BufferSecurityCheck="false"
+				EnableFunctionLevelLinking="true"
+				FloatingPointModel="2"
+				TreatWChar_tAsBuiltInType="false"
+				RuntimeTypeInfo="false"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+				CompileAs="0"
+				CompileForArchitecture="0"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="NDEBUG;_UNICODE;UNICODE;_WIN32_WCE;UNDER_CE"
+				Culture="1033"
+				AdditionalIncludeDirectories="$(IntDir)"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalOptions=" /SUBSYSTEM:WINDOWSCE,5.02"
+				OutputFile="$(OutDir)\mozce_shunt.dll"
+				ImportLibrary="$(OutDir)\mozce_shunt.lib"
+				TargetMachine="0"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCCodeSignTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+				CommandLine="copy &quot;$(TargetDir)$(TargetName).dll&quot; &quot;$(ProjectDir)&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)$(TargetName).lib&quot; &quot;$(ProjectDir)&quot;&#x0D;&#x0A;"
+			/>
+			<DeploymentTool
+				ForceDirty="-1"
+				RemoteDirectory=""
+				RegisterOutput="0"
+				AdditionalFiles=""
+			/>
+			<DebuggerTool
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath="..\..\a2w.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\assert.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\clipboard.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\direct.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\errno.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\io.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\map.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\mbstring.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\mozce_dbg.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\nclog.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\process.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\signal.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\stat.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\stdio.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\stdlib.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\string.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\time.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\w2a.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\win32.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\win32A.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\win32W.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath="..\..\include\crtdbg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\ddeml.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\direct.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\dlgs.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\errno.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\fcntl.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\intshcut.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\io.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\map.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\mbstring.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\mozce_defs.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\mozce_internal.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\mozce_shunt.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\new.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\process.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\rasdlg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\signal.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\time_conversions.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\unistd.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\varargs.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\winresrc.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\winsock2.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\winspool.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\winsvc.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\include\zmouse.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
--- a/build/wince/shunt/include/mozce_defs.h
+++ b/build/wince/shunt/include/mozce_defs.h
@@ -97,26 +97,28 @@
 #define EACCES          13
 #define EFAULT          14
 #define EBUSY           16
 #define EEXIST          17
 #define EXDEV           18
 #define ENODEV          19
 #define ENOTDIR         20
 #define EISDIR          21
+#define EINVAL          22
 #define ENFILE          23
 #define EMFILE          24
 #define ENOTTY          25
 #define EFBIG           27
 #define ENOSPC          28
 #define ESPIPE          29
 #define EROFS           30
 #define EMLINK          31
 #define EPIPE           32
 #define EDOM            33
+#define ERANGE          34
 #define EDEADLK         36
 #ifndef ENAMETOOLONG
 #define ENAMETOOLONG    38
 #endif
 #define ENOLCK          39
 #define ENOSYS          40
 #ifndef ENOTEMPTY
 #define ENOTEMPTY       41
@@ -160,16 +162,19 @@
 // From stdlib.h
 #define _MAX_PATH       MAX_PATH
 
 // From sys/types.h
 typedef int ptrdiff_t;
 typedef long _off_t;
 typedef long off_t;
 
+// Not defined anywhere
+typedef INT_PTR intptr_t; 
+
 // From sys/stat.h
 #if !defined(_STAT_DEFINED)
 #define _STAT_DEFINED
 #define _S_IFDIR    0040000 /* stat, is a directory */
 #define _S_IFREG    0100000 /* stat, is a normal file */
 #define _S_IREAD    0000400 /* stat, can read */
 #define _S_IWRITE   0000200 /* stat, can write */
 #define	_S_IEXEC	0000100
--- a/build/wince/shunt/include/mozce_shunt.h
+++ b/build/wince/shunt/include/mozce_shunt.h
@@ -56,16 +56,17 @@
 #ifndef MOZCE_SHUNT_EXPORTS
 
 #define _mkdir		mkdir
 #define _rmdir		rmdir
 #define _chmod		chmod
 #define _isatty		isatty
 #undef fileno
 #define fileno      (int)_fileno
+#define fstat       (int)_fstat
 #define _mbctolower tolower
 #define _mbsicmp    mbsicmp
 #define _mbsdec     mbsdec
 #define _getpid		getpid
 #define _access		access
 #define	_fdopen		fdopen
 #define _getcwd     getcwd
 #define _open open
@@ -123,16 +124,21 @@
 #define CallWindowProcA            CallWindowProcW
 #define GetWindowLongA             GetWindowLongW
 #define SetWindowLongA             SetWindowLongW
 #define GetMonitorInfoW           GetMonitorInfo
 
 #undef  GetProcAddress
 #define GetProcAddress            GetProcAddressA
 
+#define SHELLEXECUTEINFOW         SHELLEXECUTEINFO
+#define ShellExecuteExW(x)        ShellExecuteEx(x)
+
+#define MapVirtualKeyEx(a,b,c)    MapVirtualKey(a,b)
+
 
 //still need these
 #define GetCurrentDirectory       GetCurrentDirectoryW
 #define OpenSemaphore             OpenSemaphoreW
 #define SetCurrentDirectoryW      SetCurrentDirectoryW
 
 #endif // MOZCE_SHUNT_EXPORTS
 
new file mode 100644
--- /dev/null
+++ b/build/wince/shunt/mozce_dbg.c
@@ -0,0 +1,81 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ *
+ * ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Mozilla CE Shunt Library.
+ *
+ * The Initial Developer of the Original Code is Mozilla Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 2008
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   John Wolfe, 21-July-2008
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "mozce_internal.h"
+
+#include <stdarg.h>
+
+
+#ifndef SHUNT_LOG_ENABLED
+
+void mozce_DebugInit() { };
+void mozce_DebugDeinit() { };
+void mozce_DebugWriteToLog(char *str) { };
+
+#else
+
+#define LOGFILE     "\\Storage Card\\shuntlog.txt"
+
+FILE *gpDebugFile = NULL;
+
+void mozce_DebugInit()
+{
+    if ( NULL == gpDebugFile )
+        gpDebugFile = fopen(LOGFILE, "a+");
+}
+
+void mozce_DebugDeinit()
+{
+    if ( gpDebugFile ) {
+        fclose( gpDebugFile );
+        gpDebugFile = NULL;
+    }
+}
+
+void mozce_DebugWriteToLog(char *str)
+{
+    if ( NULL == gpDebugFile )
+        mozce_DebugInit();
+
+    if ( gpDebugFile ) {
+        fprintf(gpDebugFile, "%s", str);
+        fflush(gpDebugFile);
+    }
+}
+
+#endif
--- a/build/wince/tools/Makefile
+++ b/build/wince/tools/Makefile
@@ -1,19 +1,99 @@
-all:
-	cl vs8ppc2003arm/arm-wince-as.c
-	mv arm-wince-as.exe vs8ppc2003arm
-	cl vs8ppc2003arm/arm-wince-gcc.c
-	mv arm-wince-gcc.exe vs8ppc2003arm
-	cl vs8ppc2003arm/arm-wince-lib.c
-	mv arm-wince-lib.exe vs8ppc2003arm
-	cl vs8ppc2003arm/arm-wince-link.c
-	mv arm-wince-link.exe vs8ppc2003arm
-	rm -f *.obj
-	devenv ../shunt/build/vs8/mozce_shunt_static.sln -Rebuild "Release|Windows Mobile 6 Standard SDK (ARMV4I)"
+#
+# ***** 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 CE Shunt Library.
+#
+# The Initial Developer of the Original Code is Mozilla Corporation.
+# Portions created by the Initial Developer are Copyright (C) 2008
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#	John Wolfe (wolfe@lobo.us)
+#
+# Alternatively, t