Merge TM -> JM
authorBrian Hackett <bhackett1024@gmail.com>
Sun, 15 May 2011 11:32:09 -0700
changeset 75056 f9e1445a57f813f1491b8fdbd09b88fbb1f5d6f7
parent 75055 ea96c0f86648997d658ed7c464ec3d246284eb2f (current diff)
parent 69501 599d1c6cba63f738bc441517e5ed2af788d4ca16 (diff)
child 75057 6d27f6e4e07ad311b223627ee023ee88e5152a29
push id2
push userbsmedberg@mozilla.com
push dateFri, 19 Aug 2011 14:38:13 +0000
milestone6.0a1
Merge TM -> JM
accessible/tests/mochitest/test_value.html
accessible/tests/mochitest/test_value.xul
browser/base/content/browser.js
content/events/test/Makefile.in
content/html/document/test/test_bug570376.html
dom/base/nsDOMClassInfo.cpp
dom/base/nsGlobalWindow.cpp
dom/plugins/base/nsIPlugin.idl
intl/locale/public/nsIMacLocale.h
intl/locale/src/mac/nsMacLocale.cpp
intl/locale/src/mac/nsMacLocale.h
js/src/Makefile.in
js/src/config/autoconf.mk.in
js/src/configure.in
js/src/jsapi.cpp
js/src/jsarray.cpp
js/src/jsatom.cpp
js/src/jsbuiltins.cpp
js/src/jscntxt.h
js/src/jsdbgapi.cpp
js/src/jsemit.cpp
js/src/jsexn.cpp
js/src/jsfun.cpp
js/src/jsgc.cpp
js/src/jsgc.h
js/src/jsgcinlines.h
js/src/jsinfer.cpp
js/src/jsinterp.cpp
js/src/jsobj.cpp
js/src/jsobj.h
js/src/json.cpp
js/src/jsopcode.cpp
js/src/jsopcode.h
js/src/jsparse.cpp
js/src/jspropertycache.cpp
js/src/jsstr.cpp
js/src/jsstrinlines.h
js/src/jstracer.cpp
js/src/jstypedarray.cpp
js/src/methodjit/Compiler.cpp
js/src/methodjit/Compiler.h
js/src/methodjit/FastOps.cpp
js/src/methodjit/Logging.cpp
js/src/methodjit/Logging.h
js/src/methodjit/MethodJIT.cpp
js/src/methodjit/MethodJIT.h
js/src/methodjit/StubCalls.cpp
js/src/shell/js.cpp
js/src/tests/manifest.py
js/src/vm/Stack-inl.h
js/src/vm/Stack.h
js/src/xpconnect/shell/xpcshell.cpp
js/src/xpconnect/src/xpcjsruntime.cpp
js/src/xpconnect/wrappers/WrapperFactory.cpp
modules/libpref/src/init/all.js
--- a/accessible/src/base/nsAccessibilityAtomList.h
+++ b/accessible/src/base/nsAccessibilityAtomList.h
@@ -139,16 +139,17 @@ ACCESSIBILITY_ATOM(math, "math")
 ACCESSIBILITY_ATOM(menupopup, "menupopup")     // XUL
 ACCESSIBILITY_ATOM(object, "object")
 ACCESSIBILITY_ATOM(nav, "nav") // HTML landmark
 ACCESSIBILITY_ATOM(ol, "ol")
 ACCESSIBILITY_ATOM(optgroup, "optgroup")
 ACCESSIBILITY_ATOM(option, "option")
 ACCESSIBILITY_ATOM(output, "output")
 ACCESSIBILITY_ATOM(panel, "panel") // XUL
+ACCESSIBILITY_ATOM(progress, "progress")
 ACCESSIBILITY_ATOM(q, "q")
 ACCESSIBILITY_ATOM(select, "select")
 ACCESSIBILITY_ATOM(select1, "select1") // XForms
 ACCESSIBILITY_ATOM(svg, "svg")
 ACCESSIBILITY_ATOM(table, "table")
 ACCESSIBILITY_ATOM(tabpanels, "tabpanels") // XUL
 ACCESSIBILITY_ATOM(tbody, "tbody")
 ACCESSIBILITY_ATOM(td, "td")
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -1427,17 +1427,17 @@ nsAccessibilityService::CreateAccessible
       break;
 
     case nsIAccessibleProvider::XULPane:
       accessible = new nsEnumRoleAccessible(aContent, aWeakShell,
                                             nsIAccessibleRole::ROLE_PANE);
       break;
 
     case nsIAccessibleProvider::XULProgressMeter:
-      accessible = new nsXULProgressMeterAccessible(aContent, aWeakShell);
+      accessible = new XULProgressMeterAccessible(aContent, aWeakShell);
       break;
 
     case nsIAccessibleProvider::XULStatusBar:
       accessible = new nsXULStatusBarAccessible(aContent, aWeakShell);
       break;
 
     case nsIAccessibleProvider::XULScale:
       accessible = new nsXULSliderAccessible(aContent, aWeakShell);
@@ -1686,16 +1686,23 @@ nsAccessibilityService::CreateHTMLAccess
   }
 
   if (tag == nsAccessibilityAtoms::output) {
     nsAccessible* accessible = new nsHTMLOutputAccessible(aContent, aWeakShell);
     NS_IF_ADDREF(accessible);
     return accessible;
   }
 
+  if (tag == nsAccessibilityAtoms::progress) {
+    nsAccessible* accessible =
+      new HTMLProgressMeterAccessible(aContent, aWeakShell);
+    NS_IF_ADDREF(accessible);
+    return accessible;
+  }
+
   return nsnull;
  }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsIAccessibilityService (DON'T put methods here)
 
 nsAccessible*
 nsAccessibilityService::AddNativeRootAccessible(void* aAtkAccessible)
--- a/accessible/src/base/nsFormControlAccessible.cpp
+++ b/accessible/src/base/nsFormControlAccessible.cpp
@@ -40,16 +40,153 @@
 // NOTE: alphabetically ordered
 #include "nsFormControlAccessible.h"
 #include "nsIDOMHTMLFormElement.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIDOMXULElement.h"
 #include "nsIDOMXULControlElement.h"
 
 ////////////////////////////////////////////////////////////////////////////////
+// ProgressMeterAccessible
+////////////////////////////////////////////////////////////////////////////////
+
+template class ProgressMeterAccessible<1>;
+template class ProgressMeterAccessible<100>;
+
+////////////////////////////////////////////////////////////////////////////////
+// nsISupports
+
+template<int Max>
+NS_IMPL_ADDREF_INHERITED(ProgressMeterAccessible<Max>, nsFormControlAccessible)
+
+template<int Max>
+NS_IMPL_RELEASE_INHERITED(ProgressMeterAccessible<Max>, nsFormControlAccessible)
+
+template<int Max>
+NS_IMPL_QUERY_INTERFACE_INHERITED1(ProgressMeterAccessible<Max>,
+                                   nsFormControlAccessible,
+                                   nsIAccessibleValue)
+
+////////////////////////////////////////////////////////////////////////////////
+// nsAccessible
+
+template<int Max>
+PRUint32
+ProgressMeterAccessible<Max>::NativeRole()
+{
+  return nsIAccessibleRole::ROLE_PROGRESSBAR;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+// nsIAccessibleValue
+
+template<int Max>
+NS_IMETHODIMP
+ProgressMeterAccessible<Max>::GetValue(nsAString& aValue)
+{
+  nsresult rv = nsFormControlAccessible::GetValue(aValue);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  if (!aValue.IsEmpty())
+    return NS_OK;
+
+  double maxValue = 0;
+  rv = GetMaximumValue(&maxValue);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  double curValue = 0;
+  rv = GetCurrentValue(&curValue);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  // Treat the current value bigger than maximum as 100%.
+  double percentValue = (curValue < maxValue) ?
+    (curValue / maxValue) * 100 : 100;
+
+  nsAutoString value;
+  value.AppendFloat(percentValue); // AppendFloat isn't available on nsAString
+  value.AppendLiteral("%");
+  aValue = value;
+  return NS_OK;
+}
+
+template<int Max>
+NS_IMETHODIMP
+ProgressMeterAccessible<Max>::GetMaximumValue(double* aMaximumValue)
+{
+  nsresult rv = nsFormControlAccessible::GetMaximumValue(aMaximumValue);
+  if (rv != NS_OK_NO_ARIA_VALUE)
+    return rv;
+
+  nsAutoString value;
+  if (mContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::max, value)) {
+    PRInt32 result = NS_OK;
+    *aMaximumValue = value.ToDouble(&result);
+    return result;
+  }
+
+  *aMaximumValue = Max;
+  return NS_OK;
+}
+
+template<int Max>
+NS_IMETHODIMP
+ProgressMeterAccessible<Max>::GetMinimumValue(double* aMinimumValue)
+{
+  nsresult rv = nsFormControlAccessible::GetMinimumValue(aMinimumValue);
+  if (rv != NS_OK_NO_ARIA_VALUE)
+    return rv;
+
+  *aMinimumValue = 0;
+  return NS_OK;
+}
+
+template<int Max>
+NS_IMETHODIMP
+ProgressMeterAccessible<Max>::GetMinimumIncrement(double* aMinimumIncrement)
+{
+  nsresult rv = nsFormControlAccessible::GetMinimumIncrement(aMinimumIncrement);
+  if (rv != NS_OK_NO_ARIA_VALUE)
+    return rv;
+
+  *aMinimumIncrement = 0;
+  return NS_OK;
+}
+
+template<int Max>
+NS_IMETHODIMP
+ProgressMeterAccessible<Max>::GetCurrentValue(double* aCurrentValue)
+{
+  nsresult rv = nsFormControlAccessible::GetCurrentValue(aCurrentValue);
+  if (rv != NS_OK_NO_ARIA_VALUE)
+    return rv;
+
+  nsAutoString attrValue;
+  mContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::value, attrValue);
+
+  // Return zero value if there is no attribute or its value is empty.
+  if (attrValue.IsEmpty())
+    return NS_OK;
+
+  PRInt32 error = NS_OK;
+  double value = attrValue.ToDouble(&error);
+  if (NS_FAILED(error))
+    return NS_OK; // Zero value because of wrong markup.
+
+  *aCurrentValue = value;
+  return NS_OK;
+}
+
+template<int Max>
+NS_IMETHODIMP
+ProgressMeterAccessible<Max>::SetCurrentValue(double aValue)
+{
+  return NS_ERROR_FAILURE; // Progress meters are readonly.
+}
+
+////////////////////////////////////////////////////////////////////////////////
 // nsRadioButtonAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsRadioButtonAccessible::
   nsRadioButtonAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsFormControlAccessible(aContent, aShell)
 {
 }
--- a/accessible/src/base/nsFormControlAccessible.h
+++ b/accessible/src/base/nsFormControlAccessible.h
@@ -39,16 +39,38 @@
 #ifndef _nsFormControlAccessible_H_
 #define _nsFormControlAccessible_H_
 
 #include "nsBaseWidgetAccessible.h"
 
 typedef nsLeafAccessible nsFormControlAccessible;
 
 /**
+  * Generic class used for progress meters.
+  */
+template<int Max>
+class ProgressMeterAccessible: public nsFormControlAccessible
+{
+public:
+  ProgressMeterAccessible(nsIContent* aContent, nsIWeakReference* aShell) :
+    nsFormControlAccessible(aContent, aShell)
+  {
+  }
+
+  NS_DECL_ISUPPORTS_INHERITED
+  NS_DECL_NSIACCESSIBLEVALUE
+
+  // nsIAccessible
+  NS_IMETHOD GetValue(nsAString &aValue);
+
+  // nsAccessible
+  virtual PRUint32 NativeRole();
+};
+
+/**
   * Generic class used for radio buttons.
   */
 class nsRadioButtonAccessible : public nsFormControlAccessible
 {
 
 public:
   nsRadioButtonAccessible(nsIContent *aContent, nsIWeakReference *aShell);
 
--- a/accessible/src/html/nsHTMLFormControlAccessible.h
+++ b/accessible/src/html/nsHTMLFormControlAccessible.h
@@ -38,16 +38,21 @@
 
 #ifndef _nsHTMLFormControlAccessible_H_
 #define _nsHTMLFormControlAccessible_H_
 
 #include "nsFormControlAccessible.h"
 #include "nsHyperTextAccessibleWrap.h"
 
 /**
+ * Accessible for HTML progress element.
+ */
+typedef ProgressMeterAccessible<1> HTMLProgressMeterAccessible;
+
+/**
  * Accessible for HTML input@type="checkbox".
  */
 class nsHTMLCheckboxAccessible : public nsFormControlAccessible
 {
 
 public:
   enum { eAction_Click = 0 };
 
--- a/accessible/src/msaa/nsAccessNodeWrap.cpp
+++ b/accessible/src/msaa/nsAccessNodeWrap.cpp
@@ -62,17 +62,16 @@
 /// the accessible library and cached methods
 HINSTANCE nsAccessNodeWrap::gmAccLib = nsnull;
 HINSTANCE nsAccessNodeWrap::gmUserLib = nsnull;
 LPFNACCESSIBLEOBJECTFROMWINDOW nsAccessNodeWrap::gmAccessibleObjectFromWindow = nsnull;
 LPFNLRESULTFROMOBJECT nsAccessNodeWrap::gmLresultFromObject = NULL;
 LPFNNOTIFYWINEVENT nsAccessNodeWrap::gmNotifyWinEvent = nsnull;
 LPFNGETGUITHREADINFO nsAccessNodeWrap::gmGetGUIThreadInfo = nsnull;
 
-PRBool nsAccessNodeWrap::gIsEnumVariantSupportDisabled = 0;
 // Used to determine whether an IAccessible2 compatible screen reader is loaded.
 PRBool nsAccessNodeWrap::gIsIA2Disabled = PR_FALSE;
 
 AccTextChangeEvent* nsAccessNodeWrap::gTextEvent = nsnull;
 
 // Pref to disallow CtrlTab preview functionality if JAWS or Window-Eyes are
 // running.
 #define CTRLTAB_DISALLOW_FOR_SCREEN_READERS_PREF "browser.ctrlTab.disallowForScreenReaders"
@@ -592,21 +591,16 @@ nsAccessNodeWrap::get_localInterface(
   *localInterface = static_cast<nsIAccessNode*>(this);
   NS_ADDREF_THIS();
 } __except(FilterA11yExceptions(::GetExceptionCode(), GetExceptionInformation())) { }
   return S_OK;
 }
  
 void nsAccessNodeWrap::InitAccessibility()
 {
-  nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID));
-  if (prefBranch) {
-    prefBranch->GetBoolPref("accessibility.disableenumvariant", &gIsEnumVariantSupportDisabled);
-  }
-
   if (!gmUserLib) {
     gmUserLib =::LoadLibraryW(L"USER32.DLL");
   }
 
   if (gmUserLib) {
     if (!gmNotifyWinEvent)
       gmNotifyWinEvent = (LPFNNOTIFYWINEVENT)GetProcAddress(gmUserLib,"NotifyWinEvent");
     if (!gmGetGUIThreadInfo)
--- a/accessible/src/msaa/nsAccessNodeWrap.h
+++ b/accessible/src/msaa/nsAccessNodeWrap.h
@@ -180,18 +180,16 @@ protected:
   /**
    * Return ISimpleDOMNode instance for existing accessible object or
    * creates new nsAccessNode instance if the accessible doesn't exist.
    *
    * @note ISimpleDOMNode is returned addrefed
    */
   ISimpleDOMNode *MakeAccessNode(nsINode *aNode);
 
-    static PRBool gIsEnumVariantSupportDisabled;
-
     /**
      * Used to determine whether an IAccessible2 compatible screen reader is
      * loaded. Currently used for JAWS versions older than 8.0.2173.
      */
      static PRBool gIsIA2Disabled;
 
     /**
      * It is used in nsHyperTextAccessibleWrap for IA2::newText/oldText
--- a/accessible/src/msaa/nsAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsAccessibleWrap.cpp
@@ -114,17 +114,17 @@ NS_IMPL_ISUPPORTS_INHERITED0(nsAccessibl
 // Microsoft COM QueryInterface
 STDMETHODIMP nsAccessibleWrap::QueryInterface(REFIID iid, void** ppv)
 {
 __try {
   *ppv = NULL;
 
   if (IID_IUnknown == iid || IID_IDispatch == iid || IID_IAccessible == iid)
     *ppv = static_cast<IAccessible*>(this);
-  else if (IID_IEnumVARIANT == iid && !gIsEnumVariantSupportDisabled) {
+  else if (IID_IEnumVARIANT == iid) {
     long numChildren;
     get_accChildCount(&numChildren);
     if (numChildren > 0)  // Don't support this interface for leaf elements
       *ppv = static_cast<IEnumVARIANT*>(this);
   } else if (IID_IServiceProvider == iid)
     *ppv = static_cast<IServiceProvider*>(this);
   else if (IID_IAccessible2 == iid && !gIsIA2Disabled)
     *ppv = static_cast<IAccessible2*>(this);
--- a/accessible/src/xul/nsXULFormControlAccessible.cpp
+++ b/accessible/src/xul/nsXULFormControlAccessible.cpp
@@ -459,149 +459,16 @@ nsXULGroupboxAccessible::GetRelationByTy
       }
     }
   }
 
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsXULProgressMeterAccessible
-////////////////////////////////////////////////////////////////////////////////
-
-nsXULProgressMeterAccessible::
-  nsXULProgressMeterAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
-  nsFormControlAccessible(aContent, aShell)
-{
-}
-
-NS_IMPL_ISUPPORTS_INHERITED1(nsXULProgressMeterAccessible,
-                             nsFormControlAccessible,
-                             nsIAccessibleValue)
-
-// nsAccessible
-
-PRUint32
-nsXULProgressMeterAccessible::NativeRole()
-{
-  return nsIAccessibleRole::ROLE_PROGRESSBAR;
-}
-
-// nsIAccessibleValue
-
-NS_IMETHODIMP
-nsXULProgressMeterAccessible::GetValue(nsAString& aValue)
-{
-  nsresult rv = nsFormControlAccessible::GetValue(aValue);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  if (!aValue.IsEmpty())
-    return NS_OK;
-
-  double maxValue = 0;
-  rv = GetMaximumValue(&maxValue);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  if (maxValue != 1) {
-    double curValue = 0;
-    rv = GetCurrentValue(&curValue);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    double percentValue = (curValue / maxValue) * 100;
-    nsAutoString value;
-    value.AppendFloat(percentValue); // AppendFloat isn't available on nsAString
-    value.AppendLiteral("%");
-    aValue = value;
-    return NS_OK;
-  }
-
-  mContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::value, aValue);
-  if (aValue.IsEmpty())
-    aValue.AppendLiteral("0");  // Empty value for progress meter = 0%
-
-  aValue.AppendLiteral("%");
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsXULProgressMeterAccessible::GetMaximumValue(double *aMaximumValue)
-{
-  nsresult rv = nsFormControlAccessible::GetMaximumValue(aMaximumValue);
-  if (rv != NS_OK_NO_ARIA_VALUE)
-    return rv;
-
-  nsAutoString value;
-  if (mContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::max, value)) {
-    PRInt32 result = NS_OK;
-    *aMaximumValue = value.ToDouble(&result);
-    return result;
-  }
-
-  *aMaximumValue = 1; // 100% = 1;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsXULProgressMeterAccessible::GetMinimumValue(double *aMinimumValue)
-{
-  nsresult rv = nsFormControlAccessible::GetMinimumValue(aMinimumValue);
-  if (rv != NS_OK_NO_ARIA_VALUE)
-    return rv;
-
-  *aMinimumValue = 0;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsXULProgressMeterAccessible::GetMinimumIncrement(double *aMinimumIncrement)
-{
-  nsresult rv = nsFormControlAccessible::GetMinimumIncrement(aMinimumIncrement);
-  if (rv != NS_OK_NO_ARIA_VALUE)
-    return rv;
-
-  *aMinimumIncrement = 0;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsXULProgressMeterAccessible::GetCurrentValue(double *aCurrentValue)
-{
-  nsresult rv = nsFormControlAccessible::GetCurrentValue(aCurrentValue);
-  if (rv != NS_OK_NO_ARIA_VALUE)
-    return rv;
-
-  nsAutoString attrValue;
-  mContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::value, attrValue);
-
-  // Return zero value if there is no attribute or its value is empty.
-  if (attrValue.IsEmpty())
-    return NS_OK;
-
-  PRInt32 error = NS_OK;
-  double value = attrValue.ToDouble(&error);
-  if (NS_FAILED(error))
-    return NS_OK; // Zero value because of wrong markup.
-
-  // If no max value then value is between 0 and 1 (refer to GetMaximumValue()
-  // method where max value is assumed to be equal to 1 in this case).
-  if (!mContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::max))
-    value /= 100;
-
-  *aCurrentValue = value;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsXULProgressMeterAccessible::SetCurrentValue(double aValue)
-{
-  return NS_ERROR_FAILURE; // Progress meters are readonly!
-}
-
-
-////////////////////////////////////////////////////////////////////////////////
 // nsXULRadioButtonAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULRadioButtonAccessible::
   nsXULRadioButtonAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsRadioButtonAccessible(aContent, aShell)
 {
 }
--- a/accessible/src/xul/nsXULFormControlAccessible.h
+++ b/accessible/src/xul/nsXULFormControlAccessible.h
@@ -42,16 +42,21 @@
 
 // NOTE: alphabetically ordered
 #include "nsAccessibleWrap.h"
 #include "nsFormControlAccessible.h"
 #include "nsXULMenuAccessible.h"
 #include "nsHyperTextAccessibleWrap.h"
 
 /**
+ * Used for XUL progressmeter element.
+ */
+typedef ProgressMeterAccessible<100> XULProgressMeterAccessible;
+
+/**
  * Used for XUL button.
  *
  * @note  Don't inherit from nsFormControlAccessible - it doesn't allow children
  *         and a button can have a dropmarker child.
  */
 class nsXULButtonAccessible : public nsAccessibleWrap
 {
 public:
@@ -134,32 +139,16 @@ public:
                                nsIAccessibleRelation **aRelation);
 
   // nsAccessible
   virtual PRUint32 NativeRole();
   virtual nsresult GetNameInternal(nsAString& aName);
 };
 
 /**
- * Used for XUL progressmeter element.
- */
-class nsXULProgressMeterAccessible : public nsFormControlAccessible
-{
-  NS_DECL_ISUPPORTS_INHERITED
-  NS_DECL_NSIACCESSIBLEVALUE
-
-public:
-  nsXULProgressMeterAccessible(nsIContent *aContent, nsIWeakReference *aShell);
-  NS_IMETHOD GetValue(nsAString &aValue);
-
-  // nsAccessible
-  virtual PRUint32 NativeRole();
-};
-
-/**
  * Used for XUL radio element (radio button).
  */
 class nsXULRadioButtonAccessible : public nsRadioButtonAccessible
 {
 
 public:
   nsXULRadioButtonAccessible(nsIContent *aContent, nsIWeakReference *aShell);
 
--- a/accessible/tests/mochitest/Makefile.in
+++ b/accessible/tests/mochitest/Makefile.in
@@ -52,16 +52,17 @@ DIRS	= \
   name \
   relations \
   selectable \
   states \
   table \
   text \
   tree \
   treeupdate \
+  value \
   $(null)
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES =\
 		formimage.png \
 		letters.gif \
@@ -104,18 +105,16 @@ include $(topsrcdir)/config/rules.mk
 		test_nsIAccessibleImage.html \
 		test_nsIAccessNode_utils.html \
 		test_nsOuterDocAccessible.html \
 		test_role_nsHyperTextAcc.html \
 		test_takeFocus.html \
 		test_text_caret.html \
 		test_textboxes.html \
 		test_textboxes.xul \
-		test_value.html \
-		test_value.xul \
 		testTextboxes.js \
 		text.js \
 		treeview.css \
 		treeview.js \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/a11y/$(relativesrcdir)
--- a/accessible/tests/mochitest/events.js
+++ b/accessible/tests/mochitest/events.js
@@ -828,16 +828,20 @@ function synthHomeKey(aNodeOrID, aChecke
  * Focus invoker.
  */
 function synthFocus(aNodeOrID, aCheckerOrEventSeq, aEventType)
 {
   this.__proto__ = new synthAction(aNodeOrID, aCheckerOrEventSeq, aEventType);
 
   this.invoke = function synthFocus_invoke()
   {
+    if (this.DOMNode instanceof Components.interfaces.nsIDOMNSEditableElement ||
+        this.DOMNode instanceof Components.interfaces.nsIDOMXULTextBoxElement) {
+      this.DOMNode.selectionStart = this.DOMNode.selectionEnd = this.DOMNode.value.length;
+    }
     this.DOMNode.focus();
   }
 
   this.getID = function synthFocus_getID() 
   { 
     return prettyName(aNodeOrID) + " focus";
   }
 }
--- a/accessible/tests/mochitest/text/Makefile.in
+++ b/accessible/tests/mochitest/text/Makefile.in
@@ -45,15 +45,15 @@ relativesrcdir  = accessible/text
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES = \
 		doc.html \
 		test_doc.html \
 		test_hypertext.html \
 		test_passwords.html \
-	$(warning test_singleline.html disabled due to bug 652459) \
-	$(warning test_whitespaces.html disabled due to bug 652459) \
+		test_singleline.html \
+		test_whitespaces.html \
 		test_words.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/a11y/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/value/Makefile.in
@@ -0,0 +1,55 @@
+#
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is mozilla.org code.
+#
+# The Initial Developer of the Original Code is
+# Mozilla Foundation.
+# Portions created by the Initial Developer are Copyright (C) 2011
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#   Alexander Surkov <surkov.alexander@gmail.com> (original author)
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either of the GNU General Public License Version 2 or later (the "GPL"),
+# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+DEPTH		= ../../../..
+topsrcdir	= @top_srcdir@
+srcdir		= @srcdir@
+VPATH		= @srcdir@
+relativesrcdir  = accessible/value
+
+include $(DEPTH)/config/autoconf.mk
+include $(topsrcdir)/config/rules.mk
+
+_TEST_FILES =\
+		test_general.html \
+		test_progress.html \
+		test_progress.xul \
+		$(NULL)
+
+libs:: $(_TEST_FILES)
+	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/a11y/$(relativesrcdir)
rename from accessible/tests/mochitest/test_value.html
rename to accessible/tests/mochitest/value/test_general.html
--- a/accessible/tests/mochitest/test_value.html
+++ b/accessible/tests/mochitest/value/test_general.html
@@ -17,34 +17,34 @@
   </style>
 
   <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="common.js"></script>
+          src="../common.js"></script>
 
   <script type="application/javascript"
-          src="chrome://mochikit/content/chrome-harness.js"/>
+	  src="chrome://mochikit/content/chrome-harness.js"></script>
 
   <script type="application/javascript">
     function doTest()
     {
       function testValue(aID, aValue)
       {
         var acc = getAccessible(aID);
         if (!acc)
           return;
         is(acc.value, aValue, "Wrong value for " + aID + "!");
       }
 
       var rootDir = getRootDirectory(window.location.href);
-      var href = rootDir.path + "foo";
+      var href = getRootDirectory(window.location.href) + "foo";
 
       // roles that can't live as nsHTMLLinkAccessibles
       testValue("aria_menuitem_link", "");
       testValue("aria_button_link", "");
       testValue("aria_checkbox_link", "");
       testValue("aria_application_link", "");
 
       // roles that can live as nsHTMLLinkAccessibles
@@ -63,23 +63,28 @@
 
 <body>
 
   <a target="_blank"
      href="https://bugzilla.mozilla.org/show_bug.cgi?id=494807"
      title="Do not expose a11y info specific to hyperlinks when role is overridden using ARIA">
     Mozilla Bug 494807
   </a><br />
+  <p id="display"></p>
+  <div id="content" style="display: none">
+  </div>
+  <pre id="test">
+  </pre>
 
   <a id="aria_menuitem_link" role="menuitem" href="foo">menuitem</a>
   <a id="aria_button_link" role="button" href="foo">button</a>
   <a id="aria_checkbox_link" role="checkbox" href="foo">checkbox</a>
 
   <!-- landmark links -->
   <a id="aria_application_link" role="application" href="foo">app</a>
   <a id="aria_main_link" role="main" href="foo">main</a>
   <a id="aria_navigation_link" role="navigation" href="foo">nav</a>
-  
+
   <!-- strange edge case: please don't do this in the wild -->
   <a id="aria_link_link" role="link" href="foo">link</a>
 
 </body>
 </html>
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/value/test_progress.html
@@ -0,0 +1,63 @@
+<html>
+
+<head>
+  <title>nsIAccessible value testing for progress element</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="../common.js"></script>
+  <script type="application/javascript"
+          src="../value.js"></script>
+
+  <script type="application/javascript"
+          src="chrome://mochikit/content/chrome-harness.js"></script>
+
+  <script type="application/javascript">
+    function doTest()
+    {
+      // HTML5 progress element tests
+      testValue("pr_indeterminate", "0%", 0, 0, 1, 0);
+      testValue("pr_zero", "0%", 0, 0, 1, 0);
+      testValue("pr_zeropointfive", "50%", 0.5, 0, 1, 0);
+      testValue("pr_one", "100%", 1, 0, 1, 0);
+      testValue("pr_42", "100%", 42, 0, 1, 0);
+      testValue("pr_21", "50%", 21, 0, 42, 0);
+
+      SimpleTest.finish();
+    }
+
+    SimpleTest.waitForExplicitFinish();
+    addA11yLoadEvent(doTest);
+  </script>
+
+</head>
+
+<body>
+
+  <a target="_blank"
+     href="https://bugzilla.mozilla.org/show_bug.cgi?id=559773"
+     title="make HTML5 progress element accessible">
+    Mozilla Bug 559773
+  </a><br />
+  <p id="display"></p>
+  <div id="content" style="display: none">
+  </div>
+  <pre id="test">
+  </pre>
+
+  <!-- HTML5 progress element -->
+  <progress id="pr_indeterminate">this will be read by legacy browsers</progress>
+  <progress id="pr_zero" value="0">this will be read by legacy browsers</progress>
+  <progress id="pr_zeropointfive" value="0.5">this will be read by legacy browsers</progress>
+  <progress id="pr_one" value="1">this will be read by legacy browsers</progress>
+  <progress id="pr_42" value="42">this will be read by legacy browsers</progress>
+  <progress id="pr_21" value="21" max="42">this will be read by legacy browsers</progress>
+</body>
+</html>
rename from accessible/tests/mochitest/test_value.xul
rename to accessible/tests/mochitest/value/test_progress.xul
--- a/accessible/tests/mochitest/test_value.xul
+++ b/accessible/tests/mochitest/value/test_progress.xul
@@ -7,28 +7,28 @@
         title="XUL progressmeter tests">
 
   <script type="application/javascript" 
           src="chrome://mochikit/content/MochiKit/packed.js" />
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
 
   <script type="application/javascript"
-          src="common.js" />
+          src="../common.js" />
   <script type="application/javascript"
-          src="value.js" />
+          src="../value.js" />
 
   <script type="application/javascript">
   <![CDATA[
     function doTest()
     {
       // progressmeter
-      testValue("pm1", "50%", .5, 0, 1, 0);
+      testValue("pm1", "50%", 50, 0, 100, 0);
       testValue("pm2", "50%", 500, 0, 1000, 0);
-      testValue("pm3", "0%", 0, 0, 1, 0);
+      testValue("pm3", "0%", 0, 0, 100, 0);
 
       // scale
       testValue("sc1", "500", 500, 0, 1000, 10);
       testValue("sc2", "", 0, 0, 0, 0);
 
       // aria progressbar
       testValue("ariapb1", "500", 500, 0, 1000, 0);
       testValue("ariapb2", "", 0, 0, 0, 0);
--- a/browser/app/Makefile.in
+++ b/browser/app/Makefile.in
@@ -72,16 +72,23 @@ ifdef MOZ_SOURCE_STAMP
 DEFINES += -DMOZ_SOURCE_STAMP="$(MOZ_SOURCE_STAMP)"
 endif
 
 SOURCE_REPO := $(shell hg -R $(topsrcdir) showconfig paths.default 2>/dev/null | sed -e "s/^ssh:/http:/")
 ifdef SOURCE_REPO
 DEFINES += -DMOZ_SOURCE_REPO="$(SOURCE_REPO)"
 endif
 
+DEFINES += -DMOZ_APP_BASENAME="$(MOZ_APP_BASENAME)" \
+           -DMOZ_APP_VENDOR="$(MOZ_APP_VENDOR)"
+
+ifdef MOZ_APP_PROFILE
+DEFINES += -DMOZ_APP_PROFILE="$(MOZ_APP_PROFILE)"
+endif
+
 LIBS += $(JEMALLOC_LIBS)
 
 ifdef LIBXUL_SDK
 include $(topsrcdir)/config/rules.mk
 else
 # Build a binary bootstrapping with XRE_main
 
 ifneq (,$(filter OS2 WINNT,$(OS_ARCH)))
--- a/browser/app/application.ini
+++ b/browser/app/application.ini
@@ -32,19 +32,22 @@
 ; 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 *****
 
 #filter substitution
 [App]
-Vendor=Mozilla
-Name=Firefox
+Vendor=@MOZ_APP_VENDOR@
+Name=@MOZ_APP_BASENAME@
 Version=@APP_VERSION@
+#ifdef MOZ_APP_PROFILE
+Profile=@MOZ_APP_PROFILE@
+#endif
 BuildID=@GRE_BUILDID@
 #ifdef MOZ_SOURCE_REPO
 SourceRepository=@MOZ_SOURCE_REPO@
 #endif
 #ifdef MOZ_SOURCE_STAMP
 SourceStamp=@MOZ_SOURCE_STAMP@
 #endif
 ID={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
--- a/browser/base/content/browser-menubar.inc
+++ b/browser/base/content/browser-menubar.inc
@@ -531,17 +531,17 @@
                         label="&syncSyncNowItem.label;"
                         accesskey="&syncSyncNowItem.accesskey;"
                         observes="sync-syncnow-state"
                         oncommand="gSyncUI.doSync(event);"/>
 #endif
               <menuseparator id="devToolsSeparator"/>
               <menu id="webDeveloperMenu"
                     label="&webDeveloperMenu.label;"
-                    accesskey="webDeveloperMenu.accesskey;">
+                    accesskey="&webDeveloperMenu.accesskey;">
                 <menupopup id="menuWebDeveloperPopup">
                   <menuitem id="webConsole"
                             label="&webConsoleCmd.label;"
                             accesskey="&webConsoleCmd.accesskey;"
                             key="key_webConsole"
                             oncommand="HUDConsoleUI.toggleHUD();"/>
                   <menuitem id="menu_pageinspect"
                             type="checkbox"
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -6887,17 +6887,17 @@ var gPluginHandler = {
                                          popup     : null,
                                          callback  : showPluginsMissing
                                       }],
                             },
 #ifdef XP_MACOSX
       "npapi-carbon-event-model-failure" : {
                                              barID    : "carbon-failure-plugins",
                                              iconURL  : "chrome://mozapps/skin/plugins/notifyPluginGeneric.png",
-                                             message  : gNavigatorBundle.getString("carbonFailurePluginsMessage.title"),
+                                             message  : gNavigatorBundle.getString("carbonFailurePluginsMessage.message"),
                                              buttons: [{
                                                          label     : gNavigatorBundle.getString("carbonFailurePluginsMessage.restartButton.label"),
                                                          accessKey : gNavigatorBundle.getString("carbonFailurePluginsMessage.restartButton.accesskey"),
                                                          popup     : null,
                                                          callback  : carbonFailurePluginsRestartBrowser
                                                       }],
                             }
 #endif
--- a/browser/base/content/tabview/groupitems.js
+++ b/browser/base/content/tabview/groupitems.js
@@ -734,32 +734,32 @@ GroupItem.prototype = Utils.extend(new I
 
     this._cancelFadeAwayUndoButtonTimer();
     this.hidden = false;
     this.$undoContainer.remove();
     this.$undoContainer = null;
     this.droppable(true);
     this.setTrenches(this.bounds);
 
-    UI.setActive(this);
-
     iQ(this.container).show().animate({
       "-moz-transform": "scale(1)",
       "opacity": 1
     }, {
       duration: 170,
       complete: function() {
         self._children.forEach(function(child) {
           iQ(child.container).show();
         });
+
+        UI.setActive(self);
+        self._sendToSubscribers("groupShown", { groupItemId: self.id });
       }
     });
 
     GroupItems.updateGroupCloseButtons();
-    self._sendToSubscribers("groupShown", { groupItemId: self.id });
   },
 
   // ----------
   // Function: closeHidden
   // Removes the group item, its children and its container.
   closeHidden: function GroupItem_closeHidden() {
     let self = this;
 
--- a/browser/base/content/test/tabview/Makefile.in
+++ b/browser/base/content/test/tabview/Makefile.in
@@ -95,19 +95,20 @@ include $(topsrcdir)/config/rules.mk
                  browser_tabview_bug616967.js \
                  browser_tabview_bug618816.js \
                  browser_tabview_bug618828.js \
                  browser_tabview_bug619937.js \
                  browser_tabview_bug622835.js \
                  browser_tabview_bug622872.js \
                  browser_tabview_bug623768.js \
                  browser_tabview_bug624265.js \
-                 browser_tabview_bug624931.js \
+                 browser_tabview_bug624692.js \
                  browser_tabview_bug624727.js \
                  browser_tabview_bug624847.js \
+                 browser_tabview_bug624931.js \
                  browser_tabview_bug624953.js \
                  browser_tabview_bug625269.js \
                  browser_tabview_bug625424.js \
                  browser_tabview_bug625666.js \
                  browser_tabview_bug626368.js \
                  browser_tabview_bug626525.js \
                  browser_tabview_bug626791.js \
                  browser_tabview_bug627288.js \
@@ -130,16 +131,17 @@ include $(topsrcdir)/config/rules.mk
                  browser_tabview_bug641802.js \
                  browser_tabview_bug642793.js \
                  browser_tabview_bug644097.js \
                  browser_tabview_bug645653.js \
                  browser_tabview_bug648882.js \
                  browser_tabview_bug649006.js \
                  browser_tabview_bug649307.js \
                  browser_tabview_bug651311.js \
+                 browser_tabview_bug654941.js \
                  browser_tabview_dragdrop.js \
                  browser_tabview_exit_button.js \
                  browser_tabview_expander.js \
                  browser_tabview_firstrun_pref.js \
                  browser_tabview_group.js \
                  browser_tabview_launch.js \
                  browser_tabview_multiwindow_search.js \
                  browser_tabview_orphaned_tabs.js \
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/tabview/browser_tabview_bug624692.js
@@ -0,0 +1,25 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function test() {
+  waitForExplicitFinish();
+
+  newWindowWithTabView(function (win) {
+    registerCleanupFunction(function () win.close());
+
+    let cw = win.TabView.getContentWindow();
+    let groupItem = cw.GroupItems.groupItems[0];
+    let tabItem = groupItem.getChild(0);
+
+    hideGroupItem(groupItem, function () {
+      unhideGroupItem(groupItem, function () {
+        let bounds = tabItem.getBounds();
+        groupItem.arrange({immediately: true});
+        ok(bounds.equals(tabItem.getBounds()),
+           "tabItem bounds were correct after unhiding the groupItem");
+
+        finish();
+      });
+    });
+  });
+}
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/tabview/browser_tabview_bug654941.js
@@ -0,0 +1,33 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function test() {
+  waitForExplicitFinish();
+
+  let compareCanvasSize = function (prefix, width, height, tabItem) {
+    let canvas = tabItem.$canvas[0];
+    is(canvas.width, width, prefix + ": canvas widths are equal (" + width + "px)");
+    is(canvas.height, height, prefix + ": canvas heights are equal (" + height + "px)");
+  };
+
+  newWindowWithTabView(function (win) {
+    registerCleanupFunction(function () win.close());
+
+    let cw = win.TabView.getContentWindow();
+    let groupItem = cw.GroupItems.groupItems[0];
+    let tabItem = groupItem.getChild(0);
+
+    afterAllTabItemsUpdated(function () {
+      let {width, height} = tabItem.$canvas[0];
+
+      hideGroupItem(groupItem, function () {
+        compareCanvasSize("hidden", width, height, tabItem);
+
+        unhideGroupItem(groupItem, function () {
+          compareCanvasSize("unhidden", width, height, tabItem);
+          finish();
+        });
+      });
+    }, win);
+  });
+}
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -215,16 +215,27 @@
             range = document.createRange();
             range.setStart(textNode, startRest);
             range.setEnd(textNode, value.length);
             selection.addRange(range);
           }
         ]]></body>
       </method>
 
+      <method name="_clearFormatting">
+        <body><![CDATA[
+          if (!this._formattingEnabled)
+            return;
+
+          let controller = this.editor.selectionController;
+          let selection = controller.getSelection(controller.SELECTION_URLSECONDARY);
+          selection.removeAllRanges();
+        ]]></body>
+      </method>
+
       <method name="handleRevert">
         <body><![CDATA[
           var isScrolling = this.popupOpen;
 
           gBrowser.userTypedValue = null;
 
           // don't revert to last valid url unless page is NOT loading
           // and user is NOT key-scrolling through autocomplete list
@@ -434,16 +445,17 @@
           let url = browserDragAndDrop.drop(aEvent, { })
 
           // The URL bar automatically handles inputs with newline characters,
           // so we can get away with treating text/x-moz-url flavours as text/plain.
           if (url) {
             aEvent.preventDefault();
             this.value = url;
             SetPageProxyState("invalid");
+            this.focus();
             try {
               urlSecurityCheck(this.value,
                                gBrowser.contentPrincipal,
                                Ci.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL);
             } catch (ex) {
               return;
             }
             this.handleCommand();
@@ -639,16 +651,17 @@
           this._numNoActionsKeys--;
           if (this._numNoActionsKeys == 0)
             this._clearNoActions();
         }
       ]]></handler>
 
       <handler event="blur"><![CDATA[
         this._clearNoActions();
+        this.formatValue();
       ]]></handler>
 
       <handler event="draggesture" phase="capturing"><![CDATA[
         // TODO: This should use dragstart but editor code is still using
         //       the old drag & drop APIs, so we have to handle draggesture.
         //       This can be changed once editor code is updated to the new API.
         //       See bug 499008 for details.
 
@@ -673,16 +686,17 @@
         dt.setData("text/html", htmlString);
 
         dt.effectAllowed = "copyLink";
         event.stopPropagation();
       ]]></handler>
 
       <handler event="focus" phase="capturing"><![CDATA[
         this._hideURLTooltip();
+        this._clearFormatting();
       ]]></handler>
 
       <handler event="dragover" phase="capturing" action="this.onDragOver(event, this);"/>
       <handler event="drop" phase="capturing" action="this.onDrop(event, this);"/>
       <handler event="select"><![CDATA[
         if (!Cc["@mozilla.org/widget/clipboard;1"]
                .getService(Ci.nsIClipboard)
                .supportsSelectionClipboard())
--- a/browser/components/feeds/src/FeedConverter.js
+++ b/browser/components/feeds/src/FeedConverter.js
@@ -541,62 +541,41 @@ GenericProtocolHandler.prototype = {
     return this._http.defaultPort;
   },
   
   allowPort: function GPH_allowPort(port, scheme) {
     return this._http.allowPort(port, scheme);
   },
   
   newURI: function GPH_newURI(spec, originalCharset, baseURI) {
-    // See bug 408599 - feed URIs can be either standard URLs of the form
-    // feed://example.com, in which case the real protocol is http, or nested
-    // URIs of the form feed:realscheme:. When realscheme is either http or
-    // https, we deal with the way that creates a standard URL with the
-    // realscheme as the host by unmangling in newChannel; for others, we fail
-    // rather than let it wind up loading something like www.realscheme.com//foo
+    // Feed URIs can be either nested URIs of the form feed:realURI (in which
+    // case we create a nested URI for the realURI) or feed://example.com, in
+    // which case we create a nested URI for the real protocol which is http.
+
+    var scheme = this._scheme + ":";
+    if (spec.substr(0, scheme.length) != scheme)
+      throw Components.results.NS_ERROR_MALFORMED_URI;
 
-    const feedSlashes = "feed://";
-    const feedHttpSlashes = "feed:http://";
-    const feedHttpsSlashes = "feed:https://";
-    const NS_ERROR_MALFORMED_URI = 0x804B000A;
-
-    if (spec.substr(0, feedSlashes.length) != feedSlashes &&
-        spec.substr(0, feedHttpSlashes.length) != feedHttpSlashes &&
-        spec.substr(0, feedHttpsSlashes.length) != feedHttpsSlashes)
-      throw NS_ERROR_MALFORMED_URI;
-
-    var uri = 
-        Cc["@mozilla.org/network/standard-url;1"].
-        createInstance(Ci.nsIStandardURL);
-    uri.init(Ci.nsIStandardURL.URLTYPE_STANDARD, 80, spec, originalCharset,
-             baseURI);
+    var prefix = spec.substr(scheme.length, 2) == "//" ? "http:" : "";
+    var inner = Cc["@mozilla.org/network/io-service;1"].
+                getService(Ci.nsIIOService).newURI(spec.replace(scheme, prefix),
+                                                   originalCharset, baseURI);
+    var uri = Cc["@mozilla.org/network/util;1"].
+              getService(Ci.nsINetUtil).newSimpleNestedURI(inner);
+    uri.spec = inner.spec.replace(prefix, scheme);
     return uri;
   },
   
   newChannel: function GPH_newChannel(aUri) {
-    var ios = 
-        Cc["@mozilla.org/network/io-service;1"].
-        getService(Ci.nsIIOService);
-    // feed: URIs either start feed://, in which case the real scheme is http:
-    // or feed:http(s)://, (which by now we've changed to feed://realscheme//)
-    var feedSpec = aUri.spec;
-    const httpsChunk = "feed://https//";
-    const httpChunk = "feed://http//";
-    if (feedSpec.substr(0, httpsChunk.length) == httpsChunk)
-      feedSpec = "https://" + feedSpec.substr(httpsChunk.length);
-    else if (feedSpec.substr(0, httpChunk.length) == httpChunk)
-      feedSpec = "http://" + feedSpec.substr(httpChunk.length);
-    else
-      feedSpec = feedSpec.replace(/^feed/, "http");
-
-    var uri = ios.newURI(feedSpec, aUri.originCharset, null);
-    var channel =
-      ios.newChannelFromURI(uri, null).QueryInterface(Ci.nsIHttpChannel);
-    // Set this so we know this is supposed to be a feed
-    channel.setRequestHeader("X-Moz-Is-Feed", "1", false);
+    var inner = aUri.QueryInterface(Ci.nsINestedURI).innerURI;
+    var channel = Cc["@mozilla.org/network/io-service;1"].
+                  getService(Ci.nsIIOService).newChannelFromURI(inner, null);
+    if (channel instanceof Components.interfaces.nsIHttpChannel)
+      // Set this so we know this is supposed to be a feed
+      channel.setRequestHeader("X-Moz-Is-Feed", "1", false);
     channel.originalURI = aUri;
     return channel;
   },
   
   QueryInterface: function GPH_QueryInterface(iid) {
     if (iid.equals(Ci.nsIProtocolHandler) ||
         iid.equals(Ci.nsISupports))
       return this;
--- a/browser/components/feeds/test/unit/test_355473.js
+++ b/browser/components/feeds/test/unit/test_355473.js
@@ -18,32 +18,12 @@ function run_test() {
   do_check_true(httpFeedURI.equals(httpChannel.originalURI));
   do_check_true(httpsFeedURI.equals(httpsChannel.originalURI));
 
   // actually using the horrible mess that's a feed: URI is suicidal
   do_check_true(httpURI.equals(feedChannel.URI));
   do_check_true(httpURI.equals(httpChannel.URI));
   do_check_true(httpsURI.equals(httpsChannel.URI));
 
-  // trying to create a feed URI with something non-http(s) as the inner URL
-  // should fail, until someone fixes bug 408599
-  try {
-    var dataFeedURI = ios.newURI("feed:data:text/xml,<rss/>", null, null);
-    do_throw("Not reached");
-  } catch (e if (e instanceof Ci.nsIException &&
-                 e.result == NS_ERROR_MALFORMED_URI)) {
-    // do nothing
-  }
-  try {
-    var ftpFeedURI = ios.newURI("feed:ftp://example.com/feed.xml", null, null);
-    do_throw("Not reached");
-  } catch (e if (e instanceof Ci.nsIException &&
-                 e.result == NS_ERROR_MALFORMED_URI)) {
-    // do nothing
-  }
-  try {
-    var fileFeedURI = ios.newURI("feed:file:///var/feed.xml", null, null);
-    do_throw("Not reached");
-  } catch (e if (e instanceof Ci.nsIException &&
-                 e.result == NS_ERROR_MALFORMED_URI)) {
-    // do nothing
-  }
+  var dataFeedURI = ios.newURI("feed:data:text/xml,<rss/>", null, null);
+  var ftpFeedURI = ios.newURI("feed:ftp://example.com/feed.xml", null, null);
+  var fileFeedURI = ios.newURI("feed:file:///var/feed.xml", null, null);
 }
--- a/browser/components/places/content/editBookmarkOverlay.js
+++ b/browser/components/places/content/editBookmarkOverlay.js
@@ -798,30 +798,50 @@ var gEditItemOverlay = {
   },
 
   _rebuildTagsSelectorList: function EIO__rebuildTagsSelectorList() {
     var tagsSelector = this._element("tagsSelector");
     var tagsSelectorRow = this._element("tagsSelectorRow");
     if (tagsSelectorRow.collapsed)
       return;
 
+    // Save the current scroll position and restore it after the rebuild.
+    let firstIndex = tagsSelector.getIndexOfFirstVisibleRow();
+    let selectedIndex = tagsSelector.selectedIndex;
+    let selectedTag = selectedIndex >= 0 ? tagsSelector.selectedItem.label
+                                         : null;
+
     while (tagsSelector.hasChildNodes())
       tagsSelector.removeChild(tagsSelector.lastChild);
 
     var tagsInField = this._getTagsArrayFromTagField();
     var allTags = PlacesUtils.tagging.allTags;
     for (var i = 0; i < allTags.length; i++) {
       var tag = allTags[i];
       var elt = document.createElement("listitem");
       elt.setAttribute("type", "checkbox");
       elt.setAttribute("label", tag);
       if (tagsInField.indexOf(tag) != -1)
         elt.setAttribute("checked", "true");
+      tagsSelector.appendChild(elt);
+      if (selectedTag === tag)
+        selectedIndex = tagsSelector.getIndexOfItem(elt);
+    }
 
-      tagsSelector.appendChild(elt);
+    // Restore position.
+    // The listbox allows to scroll only if the required offset doesn't
+    // overflow its capacity, thus need to adjust the index for removals.
+    firstIndex =
+      Math.min(firstIndex,
+               tagsSelector.itemCount - tagsSelector.getNumberOfVisibleRows());
+    tagsSelector.scrollToIndex(firstIndex);
+    if (selectedIndex >= 0 && tagsSelector.itemCount > 0) {
+      selectedIndex = Math.min(selectedIndex, tagsSelector.itemCount - 1);
+      tagsSelector.selectedIndex = selectedIndex;
+      tagsSelector.ensureIndexIsVisible(selectedIndex);
     }
   },
 
   toggleTagsSelector: function EIO_toggleTagsSelector() {
     var tagsSelector = this._element("tagsSelector");
     var tagsSelectorRow = this._element("tagsSelectorRow");
     var expander = this._element("tagsSelectorExpander");
     if (tagsSelectorRow.collapsed) {
--- a/browser/components/places/tests/chrome/Makefile.in
+++ b/browser/components/places/tests/chrome/Makefile.in
@@ -47,12 +47,13 @@ include $(topsrcdir)/config/rules.mk
 	test_treeview_date.xul \
 	test_bug485100-change-case-loses-tag.xul \
 	test_bug427633_no_newfolder_if_noip.xul \
 	test_0_multiple_left_pane.xul \
 	test_0_bug510634.xul \
 	test_bug549192.xul \
 	test_bug549491.xul \
 	test_editBookmarkOverlay_tags_liveUpdate.xul \
+	test_bug631374_tags_selector_scroll.xul \
 	$(NULL)
 
 libs:: $(_CHROME_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/chrome/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/browser/components/places/tests/chrome/test_bug631374_tags_selector_scroll.xul
@@ -0,0 +1,156 @@
+<?xml version="1.0"?>
+
+<!-- Any copyright is dedicated to the Public Domain.
+     http://creativecommons.org/publicdomain/zero/1.0/ -->
+
+<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
+<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
+                 type="text/css"?>
+
+<?xml-stylesheet href="chrome://browser/skin/places/editBookmarkOverlay.css"?>
+<?xml-stylesheet href="chrome://browser/content/places/places.css"?>
+<?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
+
+<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
+<?xul-overlay href="chrome://browser/content/places/editBookmarkOverlay.xul"?>
+
+<!DOCTYPE window [
+  <!ENTITY % editBookmarkOverlayDTD SYSTEM "chrome://browser/locale/places/editBookmarkOverlay.dtd">
+  %editBookmarkOverlayDTD;
+]>
+
+<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+        title="Bug 631374 - Editing tags in the selector scrolls up the listbox"
+        onload="runTest();">
+
+  <script type="application/javascript"
+          src="chrome://mochikit/content/MochiKit/packed.js" />
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
+  <script type="application/javascript"
+          src="chrome://browser/content/places/editBookmarkOverlay.js"/>
+
+  <body xmlns="http://www.w3.org/1999/xhtml" />
+
+  <vbox id="editBookmarkPanelContent"/>
+
+  <script type="application/javascript">
+  <![CDATA[
+
+     /**
+      * This test checks that editing tags doesn't scroll the tags selector
+      * listbox to wrong positions.
+      */
+
+    function runTest() {
+      SimpleTest.waitForExplicitFinish();
+
+      Components.utils.import("resource://gre/modules/NetUtil.jsm");
+
+      let tags = ["a", "b", "c", "d", "e", "f", "g",
+                  "h", "i", "l", "m", "n", "o", "p"];
+
+      // Add a bookmark and tag it.
+      let uri1 = NetUtil.newURI("http://www1.mozilla.org/");
+      let id1 = PlacesUtils.bookmarks.insertBookmark(
+        PlacesUtils.toolbarFolderId, uri1,
+        PlacesUtils.bookmarks.DEFAULT_INDEX, "mozilla"
+      );
+      PlacesUtils.tagging.tagURI(uri1, tags);
+
+      // Add a second bookmark so that tags won't disappear when unchecked.
+      let uri2 = NetUtil.newURI("http://www2.mozilla.org/");
+      let id2 = PlacesUtils.bookmarks.insertBookmark(
+        PlacesUtils.toolbarFolderId, uri2,
+        PlacesUtils.bookmarks.DEFAULT_INDEX, "mozilla"
+      );
+      PlacesUtils.tagging.tagURI(uri2, tags);
+
+      // Init panel.
+      ok(gEditItemOverlay, "gEditItemOverlay is in context");
+      gEditItemOverlay.initPanel(id1);
+      ok(gEditItemOverlay._initialized, "gEditItemOverlay is initialized");
+
+      // Wait for the tags selector to be open.
+      let tagsSelectorRow = document.getElementById("editBMPanel_tagsSelectorRow");
+      tagsSelectorRow.addEventListener("DOMAttrModified", function (event) {
+        tagsSelectorRow.removeEventListener("DOMAttrModified", arguments.callee, false);
+        SimpleTest.executeSoon(function () {
+          let tagsSelector = document.getElementById("editBMPanel_tagsSelector");
+
+          // Go by two so there is some untouched tag in the middle.
+          for (let i = 8; i < tags.length; i += 2) {
+            tagsSelector.selectedIndex = i;
+            let listItem = tagsSelector.selectedItem;
+            SimpleTest.isnot(listItem, null, "Valid listItem found");
+
+            tagsSelector.ensureElementIsVisible(listItem);
+            let visibleIndex = tagsSelector.getIndexOfFirstVisibleRow();
+
+            SimpleTest.ok(listItem.checked, "Item is checked " + i);
+            let selectedTag = listItem.label;
+
+            // Uncheck the tag.
+            listItem.checked = false;
+            SimpleTest.is(visibleIndex,
+                          tagsSelector.getIndexOfFirstVisibleRow(),
+                          "Scroll position did not change");
+
+            // The listbox is rebuilt, so we have to get the new element.
+            let newItem = tagsSelector.selectedItem;
+            SimpleTest.isnot(newItem, null, "Valid new listItem found");
+            SimpleTest.ok(!newItem.checked, "New listItem is unchecked " + i);
+            SimpleTest.is(newItem.label, selectedTag,
+                          "Correct tag is still selected");
+
+            // Check the tag.
+            newItem.checked = true;
+            SimpleTest.is(visibleIndex,
+                          tagsSelector.getIndexOfFirstVisibleRow(),
+                          "Scroll position did not change");
+          }
+
+          // Remove the second bookmark, then nuke some of the tags.
+          PlacesUtils.bookmarks.removeItem(id2);
+
+          // Doing this backwords tests more interesting paths.
+          for (let i = tags.length - 1; i >= 0 ; i -= 2) {
+            tagsSelector.selectedIndex = i;
+            let listItem = tagsSelector.selectedItem;
+            SimpleTest.isnot(listItem, null, "Valid listItem found");
+
+            tagsSelector.ensureElementIsVisible(listItem);
+            let visibleIndex = tagsSelector.getIndexOfFirstVisibleRow();
+
+            SimpleTest.ok(listItem.checked, "Item is checked " + i);
+            let selectedTag = listItem.label;
+
+            // Uncheck the tag.
+            listItem.checked = false;
+            SimpleTest.is(tagsSelector.getIndexOfFirstVisibleRow(),
+                          Math.max(visibleIndex -1, 0),
+                          "Scroll position is correct");
+
+            // The listbox is rebuilt, so we have to get the new element.
+            let newItem = tagsSelector.selectedItem;
+            SimpleTest.isnot(newItem, null, "Valid new listItem found");
+            SimpleTest.ok(newItem.checked, "New listItem is checked " + i);
+            SimpleTest.is(tagsSelector.selectedItem.label,
+                          tags[Math.min(i + 1, tags.length - 2)],
+                          "The next tag is now selected");
+          }
+
+          // Cleanup.
+          PlacesUtils.bookmarks.removeItem(id1);
+
+          SimpleTest.finish();
+        });
+      }, false);
+
+      // Open the tags selector.
+      document.getElementById("editBMPanel_tagsSelectorExpander").doCommand();
+    }
+  ]]>
+  </script>
+
+</window>
--- a/browser/components/sessionstore/content/aboutSessionRestore.js
+++ b/browser/components/sessionstore/content/aboutSessionRestore.js
@@ -177,18 +177,20 @@ function onListClick(aEvent) {
     // on a tab's title.
 #ifdef XP_MACOSX
     let accelKey = aEvent.metaKey;
 #else
     let accelKey = aEvent.ctrlKey;
 #endif
     if ((aEvent.button == 1 || aEvent.button == 0 && aEvent.detail == 2 || accelKey) &&
         col.value.id == "title" &&
-        !treeView.isContainer(row.value))
+        !treeView.isContainer(row.value)) {
       restoreSingleTab(row.value, aEvent.shiftKey);
+      aEvent.stopPropagation();
+    }
     else if (col.value.id == "restore")
       toggleRowChecked(row.value);
   }
 }
 
 function onListKeyDown(aEvent) {
   switch (aEvent.keyCode)
   {
--- a/browser/components/sessionstore/src/nsSessionStore.js
+++ b/browser/components/sessionstore/src/nsSessionStore.js
@@ -766,46 +766,51 @@ SessionStoreService.prototype = {
           closedWindowState = this._closedWindows[i];
           closedWindowIndex = i;
           break;
         }
       }
 
       if (closedWindowState) {
         let newWindowState;
-#ifdef XP_MACOSX
-        // We want to split the window up into pinned tabs and unpinned tabs.
-        // Pinned tabs should be restored. If there are any remaining tabs,
-        // they should be added back to _closedWindows.
-        // We'll cheat a little bit and reuse _prepDataForDeferredRestore
-        // even though it wasn't built exactly for this.
-        let [appTabsState, normalTabsState] =
-          this._prepDataForDeferredRestore(JSON.stringify({ windows: [closedWindowState] }));
-
-        // These are our pinned tabs, which we should restore
-        if (appTabsState.windows.length) {
-          newWindowState = appTabsState.windows[0];
-          delete newWindowState.__lastSessionWindowID;
+#ifndef XP_MACOSX
+        if (!this._doResumeSession()) {
+#endif
+          // We want to split the window up into pinned tabs and unpinned tabs.
+          // Pinned tabs should be restored. If there are any remaining tabs,
+          // they should be added back to _closedWindows.
+          // We'll cheat a little bit and reuse _prepDataForDeferredRestore
+          // even though it wasn't built exactly for this.
+          let [appTabsState, normalTabsState] =
+            this._prepDataForDeferredRestore(JSON.stringify({ windows: [closedWindowState] }));
+
+          // These are our pinned tabs, which we should restore
+          if (appTabsState.windows.length) {
+            newWindowState = appTabsState.windows[0];
+            delete newWindowState.__lastSessionWindowID;
+          }
+
+          // In case there were no unpinned tabs, remove the window from _closedWindows
+          if (!normalTabsState.windows.length) {
+            this._closedWindows.splice(closedWindowIndex, 1);
+          }
+          // Or update _closedWindows with the modified state
+          else {
+            delete normalTabsState.windows[0].__lastSessionWindowID;
+            this._closedWindows[closedWindowIndex] = normalTabsState.windows[0];
+          }
+#ifndef XP_MACOSX
         }
-
-        // In case there were no unpinned tabs, remove the window from _closedWindows
-        if (!normalTabsState.windows.length) {
+        else {
+          // If we're just restoring the window, make sure it gets removed from
+          // _closedWindows.
           this._closedWindows.splice(closedWindowIndex, 1);
+          newWindowState = closedWindowState;
+          delete newWindowState.hidden;
         }
-        // Or update _closedWindows with the modified state
-        else {
-          delete normalTabsState.windows[0].__lastSessionWindowID;
-          this._closedWindows[closedWindowIndex] = normalTabsState.windows[0];
-        }
-#else
-        // If we're just restoring the window, make sure it gets removed from
-        // _closedWindows.
-        this._closedWindows.splice(closedWindowIndex, 1);
-        newWindowState = closedWindowState;
-        delete newWindowState.hidden;
 #endif
         if (newWindowState) {
           // Ensure that the window state isn't hidden
           this._restoreCount = 1;
           let state = { windows: [newWindowState] };
           this.restoreWindow(aWindow, state, this._isCmdLineEmpty(aWindow, state));
         }
       }
--- a/browser/components/sessionstore/test/browser/browser_580512.js
+++ b/browser/components/sessionstore/test/browser/browser_580512.js
@@ -16,24 +16,17 @@ function test() {
 }
 
 function closeFirstWin(win) {
   win.gBrowser.pinTab(win.gBrowser.tabs[0]);
   win.gBrowser.pinTab(win.gBrowser.tabs[1]);
   win.BrowserTryToCloseWindow();
   ok(win.closed, "window closed");
 
-
-  // The second check will be platform dependent. After bug 592833, Win/Linux
-  // will restore all tabs from the last close window while OSX will just
-  // reopen pinned tabs.
-  let expectedURIs = URIS_PINNED.concat(URIS_NORMAL_B);
-  if (!navigator.platform.match(/Mac/))
-    expectedURIs = expectedURIs.concat(URIS_NORMAL_A);
-  openWinWithCb(checkSecondWin, URIS_NORMAL_B, expectedURIs);
+  openWinWithCb(checkSecondWin, URIS_NORMAL_B, URIS_PINNED.concat(URIS_NORMAL_B));
 }
 
 function checkSecondWin(win) {
   is(win.gBrowser.browsers[0].currentURI.spec, URIS_PINNED[0], "first pinned tab restored");
   is(win.gBrowser.browsers[1].currentURI.spec, URIS_PINNED[1], "second pinned tab restored");
   ok(win.gBrowser.tabs[0].pinned, "first pinned tab is still pinned");
   ok(win.gBrowser.tabs[1].pinned, "second pinned tab is still pinned");
   win.close();
--- a/browser/components/sessionstore/test/browser/head.js
+++ b/browser/components/sessionstore/test/browser/head.js
@@ -40,66 +40,95 @@ const SS_SVC = Cc["@mozilla.org/browser/
 
 // This assumes that tests will at least have some state/entries
 function waitForBrowserState(aState, aSetStateCallback) {
   let windows = [window];
   let tabsRestored = 0;
   let expectedTabsRestored = 0;
   let expectedWindows = aState.windows.length;
   let windowsOpen = 1;
+  let listening = false;
+  let windowObserving = false;
 
   aState.windows.forEach(function(winState) expectedTabsRestored += winState.tabs.length);
 
   function onSSTabRestored(aEvent) {
     if (++tabsRestored == expectedTabsRestored) {
       // Remove the event listener from each window
       windows.forEach(function(win) {
         win.gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, true);
       });
+      listening = false;
       info("running " + aSetStateCallback.name);
       executeSoon(aSetStateCallback);
     }
   }
 
   // Used to add our listener to further windows so we can catch SSTabRestored
   // coming from them when creating a multi-window state.
   function windowObserver(aSubject, aTopic, aData) {
     if (aTopic == "domwindowopened") {
       let newWindow = aSubject.QueryInterface(Ci.nsIDOMWindow);
       newWindow.addEventListener("load", function() {
         newWindow.removeEventListener("load", arguments.callee, false);
 
-        if (++windowsOpen == expectedWindows)
+        if (++windowsOpen == expectedWindows) {
           Services.ww.unregisterNotification(windowObserver);
+          windowObserving = false;
+        }
 
         // Track this window so we can remove the progress listener later
         windows.push(newWindow);
         // Add the progress listener
         newWindow.gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, true);
       }, false);
     }
   }
 
   // We only want to register the notification if we expect more than 1 window
-  if (expectedWindows > 1)
+  if (expectedWindows > 1) {
+    registerCleanupFunction(function() {
+      if (windowObserving) {
+        Services.ww.unregisterNotification(windowObserver);
+      }
+    });
+    windowObserving = true;
     Services.ww.registerNotification(windowObserver);
+  }
 
+  registerCleanupFunction(function() {
+    if (listening) {
+      windows.forEach(function(win) {
+        win.gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, true);
+      });
+    }
+  });
   // Add the event listener for this window as well.
+  listening = true;
   gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, true);
 
   // Finally, call setBrowserState
   SS_SVC.setBrowserState(JSON.stringify(aState));
 }
 
 // waitForSaveState waits for a state write but not necessarily for the state to
 // turn dirty.
 function waitForSaveState(aSaveStateCallback) {
   let topic = "sessionstore-state-write";
-  Services.obs.addObserver(function() {
-    Services.obs.removeObserver(arguments.callee, topic, false);
+  let observing = false;
+  function observer(aSubject, aTopic, aData) {
+    Services.obs.removeObserver(observer, topic, false);
+    observing = false;
     executeSoon(aSaveStateCallback);
-  }, topic, false);
+  }
+  registerCleanupFunction(function() {
+    if (observing) {
+      Services.obs.removeObserver(observer, topic, false);
+    }
+  });
+  observing = true;
+  Services.obs.addObserver(observer, topic, false);
 };
 
 var gUniqueCounter = 0;
 function r() {
   return Date.now() + "-" + (++gUniqueCounter);
 }
--- a/browser/components/shell/src/nsGNOMEShellService.cpp
+++ b/browser/components/shell/src/nsGNOMEShellService.cpp
@@ -41,16 +41,17 @@
 #include "nsILocalFile.h"
 #include "nsIProperties.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsIPrefService.h"
 #include "prenv.h"
 #include "nsStringAPI.h"
 #include "nsIGConfService.h"
 #include "nsIGIOService.h"
+#include "nsIGSettingsService.h"
 #include "nsIStringBundle.h"
 #include "nsIOutputStream.h"
 #include "nsIProcess.h"
 #include "nsNetUtil.h"
 #include "nsIDOMHTMLImageElement.h"
 #include "nsIImageLoadingContent.h"
 #include "imgIRequest.h"
 #include "imgIContainer.h"
@@ -96,29 +97,37 @@ static const char kDocumentIconPath[] = 
 // GConf registry key constants
 #define DG_BACKGROUND "/desktop/gnome/background"
 
 static const char kDesktopImageKey[] = DG_BACKGROUND "/picture_filename";
 static const char kDesktopOptionsKey[] = DG_BACKGROUND "/picture_options";
 static const char kDesktopDrawBGKey[] = DG_BACKGROUND "/draw_background";
 static const char kDesktopColorKey[] = DG_BACKGROUND "/primary_color";
 
+static const char kDesktopBGSchema[] = "org.gnome.desktop.background";
+static const char kDesktopImageGSKey[] = "picture-uri";
+static const char kDesktopOptionGSKey[] = "picture-options";
+static const char kDesktopDrawBGGSKey[] = "draw-background";
+static const char kDesktopColorGSKey[] = "primary-color";
+
 nsresult
 nsGNOMEShellService::Init()
 {
   nsresult rv;
 
-  // GConf or GIO _must_ be available, or we do not allow
+  // GConf, GSettings or GIO _must_ be available, or we do not allow
   // CreateInstance to succeed.
 
   nsCOMPtr<nsIGConfService> gconf = do_GetService(NS_GCONFSERVICE_CONTRACTID);
   nsCOMPtr<nsIGIOService> giovfs =
     do_GetService(NS_GIOSERVICE_CONTRACTID);
+  nsCOMPtr<nsIGSettingsService> gsettings =
+    do_GetService(NS_GSETTINGSSERVICE_CONTRACTID);
 
-  if (!gconf && !giovfs)
+  if (!gconf && !giovfs && !gsettings)
     return NS_ERROR_NOT_AVAILABLE;
 
   // Check G_BROKEN_FILENAMES.  If it's set, then filenames in glib use
   // the locale encoding.  If it's not set, they use UTF-8.
   mUseLocaleFilenames = PR_GetEnv("G_BROKEN_FILENAMES") != nsnull;
 
   if (GetAppPathFromLauncher())
     return NS_OK;
@@ -407,16 +416,25 @@ nsGNOMEShellService::SetDesktopBackgroun
   nsCOMPtr<imgIRequest> request;
   rv = imageContent->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
                                 getter_AddRefs(request));
   if (!request) return rv;
   nsCOMPtr<imgIContainer> container;
   rv = request->GetImage(getter_AddRefs(container));
   if (!container) return rv;
 
+  // Set desktop wallpaper filling style
+  nsCAutoString options;
+  if (aPosition == BACKGROUND_TILE)
+    options.Assign("wallpaper");
+  else if (aPosition == BACKGROUND_STRETCH)
+    options.Assign("stretched");
+  else
+    options.Assign("centered");
+
   // Write the background file to the home directory.
   nsCAutoString filePath(PR_GetEnv("HOME"));
 
   // get the product brand name from localized strings
   nsString brandName;
   nsCID bundleCID = NS_STRINGBUNDLESERVICE_CID;
   nsCOMPtr<nsIStringBundleService> bundleService(do_GetService(bundleCID));
   if (bundleService) {
@@ -432,29 +450,48 @@ nsGNOMEShellService::SetDesktopBackgroun
 
   // build the file name
   filePath.Append('/');
   filePath.Append(NS_ConvertUTF16toUTF8(brandName));
   filePath.Append("_wallpaper.png");
 
   // write the image to a file in the home dir
   rv = WriteImage(filePath, container);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  // Try GSettings first. If we don't have GSettings or the right schema, fall back
+  // to using GConf instead. Note that if GSettings works ok, the changes get
+  // mirrored to GConf by the gsettings->gconf bridge in gnome-settings-daemon
+  nsCOMPtr<nsIGSettingsService> gsettings = 
+    do_GetService(NS_GSETTINGSSERVICE_CONTRACTID);
+  if (gsettings) {
+    nsCOMPtr<nsIGSettingsCollection> background_settings;
+    gsettings->GetCollectionForSchema(
+      NS_LITERAL_CSTRING(kDesktopBGSchema), getter_AddRefs(background_settings));
+    if (background_settings) {
+      gchar *file_uri = g_filename_to_uri(filePath.get(), NULL, NULL);
+      if (!file_uri)
+         return NS_ERROR_FAILURE;
+
+      background_settings->SetString(NS_LITERAL_CSTRING(kDesktopOptionGSKey),
+                                     options);
+
+      background_settings->SetString(NS_LITERAL_CSTRING(kDesktopImageGSKey),
+                                     nsDependentCString(file_uri));
+      g_free(file_uri);
+      background_settings->SetBoolean(NS_LITERAL_CSTRING(kDesktopDrawBGGSKey),
+                                      PR_TRUE);
+      return rv;
+    }
+  }
 
   // if the file was written successfully, set it as the system wallpaper
   nsCOMPtr<nsIGConfService> gconf = do_GetService(NS_GCONFSERVICE_CONTRACTID);
 
   if (gconf) {
-    nsCAutoString options;
-    if (aPosition == BACKGROUND_TILE)
-      options.Assign("wallpaper");
-    else if (aPosition == BACKGROUND_STRETCH)
-      options.Assign("stretched");
-    else
-      options.Assign("centered");
-
     gconf->SetString(NS_LITERAL_CSTRING(kDesktopOptionsKey), options);
 
     // Set the image to an empty string first to force a refresh
     // (since we could be writing a new image on top of an existing
     // Firefox_wallpaper.png and nautilus doesn't monitor the file for changes)
     gconf->SetString(NS_LITERAL_CSTRING(kDesktopImageKey),
                      EmptyCString());
 
@@ -466,21 +503,34 @@ nsGNOMEShellService::SetDesktopBackgroun
 }
 
 #define COLOR_16_TO_8_BIT(_c) ((_c) >> 8)
 #define COLOR_8_TO_16_BIT(_c) ((_c) << 8 | (_c))
 
 NS_IMETHODIMP
 nsGNOMEShellService::GetDesktopBackgroundColor(PRUint32 *aColor)
 {
-  nsCOMPtr<nsIGConfService> gconf = do_GetService(NS_GCONFSERVICE_CONTRACTID);
-
+  nsCOMPtr<nsIGSettingsService> gsettings = 
+    do_GetService(NS_GSETTINGSSERVICE_CONTRACTID);
+  nsCOMPtr<nsIGSettingsCollection> background_settings;
   nsCAutoString background;
-  if (gconf) {
-    gconf->GetString(NS_LITERAL_CSTRING(kDesktopColorKey), background);
+
+  if (gsettings) {
+    gsettings->GetCollectionForSchema(
+      NS_LITERAL_CSTRING(kDesktopBGSchema), getter_AddRefs(background_settings));
+    if (background_settings) {
+      background_settings->GetString(NS_LITERAL_CSTRING(kDesktopColorGSKey),
+                                     background);
+    }
+  }
+
+  if (!background_settings) {
+    nsCOMPtr<nsIGConfService> gconf = do_GetService(NS_GCONFSERVICE_CONTRACTID);
+    if (gconf)
+      gconf->GetString(NS_LITERAL_CSTRING(kDesktopColorKey), background);
   }
 
   if (background.IsEmpty()) {
     *aColor = 0;
     return NS_OK;
   }
 
   GdkColor color;
@@ -508,22 +558,35 @@ ColorToCString(PRUint32 aColor, nsCStrin
 
   PR_snprintf(buf, 14, "#%04x%04x%04x", red, green, blue);
 }
 
 NS_IMETHODIMP
 nsGNOMEShellService::SetDesktopBackgroundColor(PRUint32 aColor)
 {
   NS_ASSERTION(aColor <= 0xffffff, "aColor has extra bits");
+  nsCAutoString colorString;
+  ColorToCString(aColor, colorString);
+
+  nsCOMPtr<nsIGSettingsService> gsettings =
+    do_GetService(NS_GSETTINGSSERVICE_CONTRACTID);
+  if (gsettings) {
+    nsCOMPtr<nsIGSettingsCollection> background_settings;
+    gsettings->GetCollectionForSchema(
+      NS_LITERAL_CSTRING(kDesktopBGSchema), getter_AddRefs(background_settings));
+    if (background_settings) {
+      background_settings->SetString(NS_LITERAL_CSTRING(kDesktopColorGSKey),
+                                     colorString);
+      return NS_OK;
+    }
+  }
+
   nsCOMPtr<nsIGConfService> gconf = do_GetService(NS_GCONFSERVICE_CONTRACTID);
 
   if (gconf) {
-    nsCAutoString colorString;
-    ColorToCString(aColor, colorString);
-
     gconf->SetString(NS_LITERAL_CSTRING(kDesktopColorKey), colorString);
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsGNOMEShellService::OpenApplication(PRInt32 aApplication)
--- a/browser/confvars.sh
+++ b/browser/confvars.sh
@@ -31,17 +31,18 @@
 # use your version of this file under the terms of the MPL, indicate your
 # decision by deleting the provisions above and replace them with the notice
 # and other provisions required by the GPL or the LGPL. If you do not delete
 # the provisions above, a recipient may use your version of this file under
 # the terms of any one of the MPL, the GPL or the LGPL.
 #
 # ***** END LICENSE BLOCK *****
 
-MOZ_APP_NAME=firefox
+MOZ_APP_BASENAME=Firefox
+MOZ_APP_VENDOR=Mozilla
 MOZ_UPDATER=1
 MOZ_PHOENIX=1
 
 MOZ_ENABLE_LIBXUL=1
 MOZ_CHROME_FILE_FORMAT=omni
 MOZ_STATIC_BUILD_UNSUPPORTED=1
 # always enabled for form history
 MOZ_MORKREADER=1
--- a/browser/installer/Makefile.in
+++ b/browser/installer/Makefile.in
@@ -118,17 +118,17 @@ INSTALL_SDK = 1
 endif
 
 ifneq (1_,$(if $(CROSS_COMPILE),1,0)_$(UNIVERSAL_BINARY))
 ifdef RUN_TEST_PROGRAM
 _ABS_RUN_TEST_PROGRAM = $(call core_abspath,$(RUN_TEST_PROGRAM))
 endif
 
 GENERATE_CACHE = \
-  $(_ABS_RUN_TEST_PROGRAM) $(_ABS_DIST)/bin/xpcshell$(BIN_SUFFIX) -g "$$PWD" -f $(topsrcdir)/browser/installer/precompile_cache.js -e 'populate_startupcache("omni.jar", "startupCache.zip");' && \
+  $(_ABS_RUN_TEST_PROGRAM) $(LIBXUL_DIST)/bin/xpcshell$(BIN_SUFFIX) -g "$$PWD" -f $(topsrcdir)/browser/installer/precompile_cache.js -e 'populate_startupcache("omni.jar", "startupCache.zip");' && \
   rm -rf jsloader && \
   $(UNZIP) startupCache.zip && \
   rm startupCache.zip && \
   find jsloader | xargs touch -t 201001010000 && \
   $(ZIP) -r9mX omni.jar jsloader
 endif
 
 include $(topsrcdir)/toolkit/mozapps/installer/packager.mk
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -379,16 +379,18 @@
 @BINPATH@/components/nsINIProcessor.manifest
 @BINPATH@/components/nsINIProcessor.js
 @BINPATH@/components/nsPrompter.manifest
 @BINPATH@/components/nsPrompter.js
 #ifdef MOZ_SERVICES_SYNC
 @BINPATH@/components/SyncComponents.manifest
 @BINPATH@/components/Weave.js
 #endif
+@BINPATH@/components/TelemetryPing.js
+@BINPATH@/components/TelemetryPing.manifest
 
 ; Modules
 @BINPATH@/modules/*
 
 ; Safe Browsing
 @BINPATH@/components/nsSafebrowsingApplication.manifest
 @BINPATH@/components/nsSafebrowsingApplication.js
 @BINPATH@/components/nsURLClassifier.manifest
--- a/browser/locales/Makefile.in
+++ b/browser/locales/Makefile.in
@@ -182,17 +182,17 @@ install:: $(addsuffix .xml,$(SEARCH_PLUG
 
 
 libs-%:
 	$(NSINSTALL) -D $(DIST)/install
 	@$(MAKE) -C ../../toolkit/locales libs-$* BOTH_MANIFESTS=1
 	@$(MAKE) -C ../../services/sync/locales AB_CD=$* XPI_NAME=locale-$* BOTH_MANIFESTS=1
 	@$(MAKE) -C ../../extensions/spellcheck/locales AB_CD=$* XPI_NAME=locale-$* BOTH_MANIFESTS=1
 	@$(MAKE) -C ../../intl/locales AB_CD=$* XPI_NAME=locale-$* BOTH_MANIFESTS=1
-	@$(MAKE) libs AB_CD=$* XPI_NAME=locale-$* PREF_DIR=defaults/pref BOTH_MANIFESTS=1
+	@$(MAKE) libs AB_CD=$* XPI_NAME=locale-$* PREF_DIR=$(PREF_DIR) BOTH_MANIFESTS=1
 	@$(MAKE) -C $(DEPTH)/$(MOZ_BRANDING_DIRECTORY)/locales AB_CD=$* XPI_NAME=locale-$* BOTH_MANIFESTS=1
 
 
 repackage-win32-installer: WIN32_INSTALLER_OUT=$(_ABS_DIST)/$(PKG_INST_PATH)$(PKG_INST_BASENAME).exe
 repackage-win32-installer: $(call ESCAPE_SPACE,$(WIN32_INSTALLER_IN)) $(SUBMAKEFILES) libs-$(AB_CD)
 	@echo "Repackaging $(WIN32_INSTALLER_IN) into $(WIN32_INSTALLER_OUT)."
 	$(MAKE) -C $(DEPTH)/$(MOZ_BRANDING_DIRECTORY) export
 	$(MAKE) -C ../installer/windows CONFIG_DIR=l10ngen l10ngen/setup.exe l10ngen/7zSD.sfx
--- a/browser/locales/en-US/chrome/browser/browser.dtd
+++ b/browser/locales/en-US/chrome/browser/browser.dtd
@@ -200,17 +200,17 @@ can reach it easily. -->
   -  and evaluating bits of JavaScript code for the purposes of function
   -  prototyping, experimentation and convenient scripting.
   -
   -  It's quite possible that you won't have a good analogue for the word
   -  "Scratchpad" in your locale. You should feel free to find a close
   -  approximation to it or choose a word (or words) that means
   -  "simple discardable text editor". -->
 <!ENTITY scratchpad.label             "Scratchpad">
-<!ENTITY scratchpad.accesskey         "r">
+<!ENTITY scratchpad.accesskey         "s">
 <!ENTITY scratchpad.keycode           "VK_F4">
 <!ENTITY scratchpad.keytext           "F4">
 
 <!ENTITY inspectPanelTitle.label      "HTML">
 <!ENTITY inspectButton.label          "Inspect">
 <!ENTITY inspectButton.accesskey      "I">
 <!ENTITY inspectNextButton.label      "Next">
 <!ENTITY inspectNextButton.accesskey  "N">
--- a/browser/locales/en-US/chrome/browser/browser.properties
+++ b/browser/locales/en-US/chrome/browser/browser.properties
@@ -107,17 +107,17 @@ blockedpluginsMessage.infoButton.accessk
 blockedpluginsMessage.searchButton.label=Update Plugins…
 blockedpluginsMessage.searchButton.accesskey=U
 crashedpluginsMessage.title=The %S plugin has crashed.
 crashedpluginsMessage.reloadButton.label=Reload page
 crashedpluginsMessage.reloadButton.accesskey=R
 crashedpluginsMessage.submitButton.label=Submit a crash report
 crashedpluginsMessage.submitButton.accesskey=S
 crashedpluginsMessage.learnMore=Learn More…
-carbonFailurePluginsMessage.title=This page requires a plugin that can only run in 32-bit mode
+carbonFailurePluginsMessage.message=This page asks to use a plugin that can only run in 32-bit mode
 carbonFailurePluginsMessage.restartButton.label=Restart in 32-bit mode
 carbonFailurePluginsMessage.restartButton.accesskey=R
 
 # Sanitize
 # LOCALIZATION NOTE (sanitizeDialog2.everything.title): When "Time range to
 # clear" is set to "Everything", the Clear Recent History dialog's title is
 # changed to this.  See UI mockup and comment 11 at bug 480169 -->
 sanitizeDialog2.everything.title=Clear All History
--- a/browser/locales/en-US/chrome/browser/places/places.dtd
+++ b/browser/locales/en-US/chrome/browser/places/places.dtd
@@ -1,22 +1,19 @@
 <!-- LOCALIZATION NOTE (places.library.title): use "Library", "Archive" or "Repository" -->
 <!ENTITY places.library.title  "Library">
 <!ENTITY places.library.width  "700">
 <!ENTITY places.library.height "500">
 <!ENTITY organize.label        "Organize">
 <!ENTITY organize.accesskey    "O">
 <!ENTITY organize.tooltip      "Organize your bookmarks">
 
-<!ENTITY file.accesskey                 "F">
 <!ENTITY file.close.label               "Close">
 <!ENTITY file.close.accesskey           "C">
 <!ENTITY cmd.close.key                  "w">
-<!ENTITY edit.label                     "Edit">
-<!ENTITY edit.accesskey                 "E">
 <!ENTITY views.label                    "Views">
 <!ENTITY views.accesskey                "V">
 <!ENTITY views.tooltip                  "Change your view">
 <!ENTITY view.columns.label             "Show Columns">
 <!ENTITY view.columns.accesskey         "C">
 <!ENTITY view.sort.label                "Sort">
 <!ENTITY view.sort.accesskey            "S">
 <!ENTITY view.unsorted.label            "Unsorted">
@@ -106,27 +103,24 @@
 <!ENTITY saveSearch.accesskey                      "S">
 
 <!ENTITY cmd.find.key  "f">
 
 <!ENTITY maintenance.label      "Import and Backup">
 <!ENTITY maintenance.accesskey  "I">
 <!ENTITY maintenance.tooltip    "Import and backup your bookmarks">
 
-<!ENTITY backCmd.label       "Back">
 <!ENTITY backButton.tooltip  "Go back">
 
-<!ENTITY forwardCmd.label       "Forward">
 <!ENTITY forwardButton.tooltip  "Go forward">
 
 <!ENTITY detailsPane.more.label "More">
 <!ENTITY detailsPane.more.accesskey "e">
 <!ENTITY detailsPane.less.label "Less">
 <!ENTITY detailsPane.less.accesskey "e">
-<!ENTITY detailsPane.noPreviewAvailable.label "Preview">
 <!ENTITY detailsPane.selectAnItemText.description "Select an item to view and edit its properties">
 
 <!ENTITY find.label               "Search:">
 <!ENTITY find.accesskey           "S">
 <!ENTITY view.label               "View">
 <!ENTITY view.accesskey           "w">
 <!ENTITY byDate.label             "By Date">
 <!ENTITY byDate.accesskey         "D">
--- a/browser/locales/en-US/chrome/browser/places/places.properties
+++ b/browser/locales/en-US/chrome/browser/places/places.properties
@@ -1,11 +1,8 @@
-deleteHost=Delete all from %S
-deleteDomain=Delete entire domain %S
-
 load-js-data-url-error=For security reasons, javascript or data urls cannot be loaded from the history window or sidebar.
 noTitle=(no title)
 
 bookmarksMenuEmptyFolder=(Empty)
 
 bookmarksBackupTitle=Bookmarks backup filename
 
 bookmarksRestoreAlertTitle=Revert Bookmarks
--- a/browser/themes/winstripe/browser/browser-aero.css
+++ b/browser/themes/winstripe/browser/browser-aero.css
@@ -83,16 +83,20 @@
     -moz-margin-end: 3px;
   }
 
   #main-window {
     -moz-appearance: -moz-win-borderless-glass;
     background: transparent;
   }
 
+  #appcontent {
+    -moz-appearance: -moz-win-exclude-glass;
+  }
+
   #main-window[chromemargin^="0,"][sizemode=normal] #navigator-toolbox {
     margin-top: -7px;
   }
 
   /* Artificially draw window borders that are covered by lwtheme, see bug 591930. */
   #main-window[sizemode="normal"] > #titlebar > #titlebar-content:-moz-lwtheme {
     border-top: 2px solid;
     -moz-border-top-colors: @glassActiveBorderColor@ rgba(255,255,255,.6);
--- a/build/mobile/devicemanager-run-test.py
+++ b/build/mobile/devicemanager-run-test.py
@@ -30,20 +30,20 @@
 # 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 *****
 
 import devicemanager
+import devicemanagerUtils
 import sys
 import os
 
-
 def main():
     ip_addr = os.environ.get("DEVICE_IP")
     port = os.environ.get("DEVICE_PORT")
     gre_path = os.environ.get("REMOTE_GRE_PATH").replace('\\','/')
 
     if ip_addr == None:
         print "Error: please define the environment variable DEVICE_IP before running this test"
         sys.exit(1)
@@ -51,17 +51,17 @@ def main():
     if port == None:
         print "Error: please define the environment variable DEVICE_PORT before running this test"
         sys.exit(1)
 
     if gre_path == None:
         print "Error: please define the environment variable REMOTE_GRE_PATH before running this test"
         sys.exit(1)
 
-    dm = devicemanager.DeviceManager(ip_addr, int(port))
+    dm = devicemanagerUtils.getDeviceManager(ip_addr, int(port))
     if len(sys.argv) < 2:
         print "usage python devicemanager-run-test.py <test program> [args1 [arg2..]]"
         sys.exit(1)
 
     cmd = sys.argv[1]
     args = ' '
     if len(sys.argv) > 2:
         args = ' ' + ' '.join(sys.argv[2:])
--- a/build/mobile/devicemanager.py
+++ b/build/mobile/devicemanager.py
@@ -32,26 +32,21 @@
 # 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 *****
 
+import time
+import hashlib
 import socket
-import SocketServer
-import time, datetime
 import os
 import re
-import hashlib
-import subprocess
-from threading import Thread
-import traceback
-import sys
 
 class FileError(Exception):
   " Signifies an error which occurs while doing a file operation."
 
   def __init__(self, msg = ''):
     self.msg = msg
 
   def __str__(self):
@@ -63,490 +58,118 @@ class DMError(Exception):
   def __init__(self, msg= ''):
     self.msg = msg
 
   def __str__(self):
     return self.msg
 
 
 class DeviceManager:
-  host = ''
-  port = 0
-  debug = 2 
-  retries = 0
-  tempRoot = os.getcwd()
-  base_prompt = '$>'
-  base_prompt_re = '\$\>'
-  prompt_sep = '\x00'
-  prompt_regex = '.*(' + base_prompt_re + prompt_sep + ')'
-  agentErrorRE = re.compile('^##AGENT-WARNING##.*')
-
-  # TODO: member variable to indicate error conditions.
-  # This should be set to a standard error from the errno module.
-  # So, for example, when an error occurs because of a missing file/directory,
-  # before returning, the function would do something like 'self.error = errno.ENOENT'.
-  # The error would be set where appropriate--so sendCMD() could set socket errors,
-  # pushFile() and other file-related commands could set filesystem errors, etc.
-
-  def __init__(self, host, port = 20701, retrylimit = 5):
-    self.host = host
-    self.port = port
-    self.retrylimit = retrylimit
-    self.retries = 0
-    self._sock = None
-    self.getDeviceRoot()
-
-  def cmdNeedsResponse(self, cmd):
-    """ Not all commands need a response from the agent:
-        * if the cmd matches the pushRE then it is the first half of push
-          and therefore we want to wait until the second half before looking
-          for a response
-        * rebt obviously doesn't get a response
-        * uninstall performs a reboot to ensure starting in a clean state and
-          so also doesn't look for a response
-    """
-    noResponseCmds = [re.compile('^push .*$'),
-                      re.compile('^rebt'),
-                      re.compile('^uninst .*$'),
-                      re.compile('^pull .*$')]
-
-    for c in noResponseCmds:
-      if (c.match(cmd)):
-        return False
-    
-    # If the command is not in our list, then it gets a response
-    return True
-
-  def shouldCmdCloseSocket(self, cmd):
-    """ Some commands need to close the socket after they are sent:
-    * push
-    * rebt
-    * uninst
-    * quit
-    """
-    
-    socketClosingCmds = [re.compile('^push .*$'),
-                         re.compile('^quit.*'),
-                         re.compile('^rebt.*'),
-                         re.compile('^uninst .*$')]
-
-    for c in socketClosingCmds:
-      if (c.match(cmd)):
-        return True
-
-    return False
-
-  # convenience function to enable checks for agent errors
-  def verifySendCMD(self, cmdline, newline = True):
-    return self.sendCMD(cmdline, newline, False)
-
-
-  #
-  # create a wrapper for sendCMD that loops up to self.retrylimit iterations.
-  # this allows us to move the retry logic outside of the _doCMD() to make it 
-  # easier for debugging in the future.
-  # note that since cmdline is a list of commands, they will all be retried if
-  # one fails.  this is necessary in particular for pushFile(), where we don't want
-  # to accidentally send extra data if a failure occurs during data transmission.
-  #
-  def sendCMD(self, cmdline, newline = True, ignoreAgentErrors = True):
-    done = False
-    while (not done):
-      retVal = self._doCMD(cmdline, newline)
-      if (retVal is None):
-        self.retries += 1
-      else:
-        self.retries = 0
-        if ignoreAgentErrors == False:
-          if (self.agentErrorRE.match(retVal)):
-            raise DMError("error on the agent executing '%s'" % cmdline)
-        return retVal
-
-      if (self.retries >= self.retrylimit):
-        done = True
-
-    raise DMError("unable to connect to %s after %s attempts" % (self.host, self.retrylimit))        
-
-  def _doCMD(self, cmdline, newline = True):
-    promptre = re.compile(self.prompt_regex + '$')
-    data = ""
-    shouldCloseSocket = False
-    recvGuard = 1000
-
-    if (self._sock == None):
-      try:
-        if (self.debug >= 1):
-          print "reconnecting socket"
-        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-      except:
-        self._sock = None
-        if (self.debug >= 2):
-          print "unable to create socket"
-        return None
-      
-      try:
-        self._sock.connect((self.host, int(self.port)))
-        self._sock.recv(1024)
-      except:
-        self._sock.close()
-        self._sock = None
-        if (self.debug >= 2):
-          print "unable to connect socket"
-        return None
-    
-    for cmd in cmdline:
-      if newline: cmd += '\r\n'
-      
-      try:
-        numbytes = self._sock.send(cmd)
-        if (numbytes != len(cmd)):
-          print "ERROR: our cmd was " + str(len(cmd)) + " bytes and we only sent " + str(numbytes)
-          return None
-        if (self.debug >= 4): print "send cmd: " + str(cmd)
-      except:
-        self._sock.close()
-        self._sock = None
-        return None
-      
-      # Check if the command should close the socket
-      shouldCloseSocket = self.shouldCmdCloseSocket(cmd)
-
-      # Handle responses from commands
-      if (self.cmdNeedsResponse(cmd)):
-        found = False
-        loopguard = 0
-
-        while (found == False and (loopguard < recvGuard)):
-          temp = ''
-          if (self.debug >= 4): print "recv'ing..."
-
-          # Get our response
-          try:
-            temp = self._sock.recv(1024)
-            if (self.debug >= 4): print "response: " + str(temp)
-          except:
-            self._sock.close()
-            self._sock = None
-            return None
-
-          # If something goes wrong in the agent it will send back a string that
-          # starts with '##AGENT-ERROR##'
-          if (self.agentErrorRE.match(temp)):
-            data = temp
-            break
-
-          lines = temp.split('\n')
-
-          for line in lines:
-            if (promptre.match(line)):
-              found = True
-          data += temp
-
-          # If we violently lose the connection to the device, this loop tends to spin,
-          # this guard prevents that
-          if (temp == ''):
-            loopguard += 1
-
-    if (shouldCloseSocket == True):
-      try:
-        self._sock.close()
-        self._sock = None
-      except:
-        self._sock = None
-        return None
-
-    return data
-  
-  # internal function
-  # take a data blob and strip instances of the prompt '$>\x00'
-  def stripPrompt(self, data):
-    promptre = re.compile(self.prompt_regex + '.*')
-    retVal = []
-    lines = data.split('\n')
-    for line in lines:
-      try:
-        while (promptre.match(line)):
-          pieces = line.split(self.prompt_sep)
-          index = pieces.index('$>')
-          pieces.pop(index)
-          line = self.prompt_sep.join(pieces)
-      except(ValueError):
-        pass
-      retVal.append(line)
-
-    return '\n'.join(retVal)
-  
-
   # external function
   # returns:
   #  success: True
   #  failure: False
   def pushFile(self, localname, destname):
-    if (os.name == "nt"):
-      destname = destname.replace('\\', '/')
-
-    if (self.debug >= 3): print "in push file with: " + localname + ", and: " + destname
-    if (self.validateFile(destname, localname) == True):
-      if (self.debug >= 3): print "files are validated"
-      return True
-
-    if self.mkDirs(destname) == None:
-      print "unable to make dirs: " + destname
-      return False
-
-    if (self.debug >= 3): print "sending: push " + destname
-    
-    filesize = os.path.getsize(localname)
-    f = open(localname, 'rb')
-    data = f.read()
-    f.close()
+    assert 0 == 1
+    return False
 
-    try:
-      retVal = self.verifySendCMD(['push ' + destname + ' ' + str(filesize) + '\r\n', data], newline = False)
-    except(DMError):
-      retVal = False
-  
-    if (self.debug >= 3): print "push returned: " + str(retVal)
-
-    validated = False
-    if (retVal):
-      retline = self.stripPrompt(retVal).strip() 
-      if (retline == None):
-        # Then we failed to get back a hash from agent, try manual validation
-        validated = self.validateFile(destname, localname)
-      else:
-        # Then we obtained a hash from push
-        localHash = self.getLocalHash(localname)
-        if (str(localHash) == str(retline)):
-          validated = True
-    else:
-      # We got nothing back from sendCMD, try manual validation
-      validated = self.validateFile(destname, localname)
-
-    if (validated):
-      if (self.debug >= 3): print "Push File Validated!"
-      return True
-    else:
-      if (self.debug >= 2): print "Push File Failed to Validate!"
-      return False
-  
   # external function
   # returns:
   #  success: directory name
   #  failure: None
   def mkDir(self, name):
-    if (self.dirExists(name)):
-      return name
-    else:
-      try:
-        retVal = self.verifySendCMD(['mkdr ' + name])
-      except(DMError):
-        retVal = None
-      return retVal
+      assert 0 == 1
+      return None
 
   # make directory structure on the device
   # external function
   # returns:
   #  success: directory structure that we created
   #  failure: None
   def mkDirs(self, filename):
-    parts = filename.split('/')
-    name = ""
-    for part in parts:
-      if (part == parts[-1]): break
-      if (part != ""):
-        name += '/' + part
-        if (self.mkDir(name) == None):
-          print "failed making directory: " + str(name)
-          return None
-    return name
+      assert 0 == 1
+      return None
 
   # push localDir from host to remoteDir on the device
   # external function
   # returns:
   #  success: remoteDir
   #  failure: None
   def pushDir(self, localDir, remoteDir):
-    if (self.debug >= 2): print "pushing directory: %s to %s" % (localDir, remoteDir)
-    for root, dirs, files in os.walk(localDir):
-      parts = root.split(localDir)
-      for file in files:
-        remoteRoot = remoteDir + '/' + parts[1]
-        remoteName = remoteRoot + '/' + file
-        if (parts[1] == ""): remoteRoot = remoteDir
-        if (self.pushFile(os.path.join(root, file), remoteName) == False):
-          # retry once
-          self.removeFile(remoteName)
-          if (self.pushFile(os.path.join(root, file), remoteName) == False):
-            return None
-    return remoteDir
+    assert 0 == 1
+    return None
 
   # external function
   # returns:
   #  success: True
   #  failure: False
   def dirExists(self, dirname):
-    match = ".*" + dirname + "$"
-    dirre = re.compile(match)
-    try:
-      data = self.verifySendCMD(['cd ' + dirname, 'cwd'])
-    except(DMError):
-      return False
-
-    retVal = self.stripPrompt(data)
-    data = retVal.split('\n')
-    found = False
-    for d in data:
-      if (dirre.match(d)): 
-        found = True
-
-    return found
+    assert 0 == 1
+    return False
 
   # Because we always have / style paths we make this a lot easier with some
   # assumptions
   # external function
   # returns:
   #  success: True
   #  failure: False
   def fileExists(self, filepath):
-    s = filepath.split('/')
-    containingpath = '/'.join(s[:-1])
-    listfiles = self.listFiles(containingpath)
-    for f in listfiles:
-      if (f == s[-1]):
-        return True
+    assert 0 == 1
     return False
 
   # list files on the device, requires cd to directory first
   # external function
   # returns:
   #  success: array of filenames, ['file1', 'file2', ...]
   #  failure: []
   def listFiles(self, rootdir):
-    rootdir = rootdir.rstrip('/')
-    if (self.dirExists(rootdir) == False):
-      return []
-    try:
-      data = self.verifySendCMD(['cd ' + rootdir, 'ls'])
-    except(DMError):
-      return []
-
-    retVal = self.stripPrompt(data)
-    files = filter(lambda x: x, retVal.split('\n'))
-    if len(files) == 1 and files[0] == '<empty>':
-      # special case on the agent: empty directories return just the string "<empty>"
-      return []
-    return files
+    assert 0 == 1
+    return []
 
   # external function
   # returns:
   #  success: output of telnet, i.e. "removing file: /mnt/sdcard/tests/test.txt"
   #  failure: None
   def removeFile(self, filename):
-    if (self.debug>= 2): print "removing file: " + filename
-    try:
-      retVal = self.verifySendCMD(['rm ' + filename])
-    except(DMError):
-      return None
+    assert 0 == 1
+    return False
 
-    return retVal
-  
   # does a recursive delete of directory on the device: rm -Rf remoteDir
   # external function
   # returns:
   #  success: output of telnet, i.e. "removing file: /mnt/sdcard/tests/test.txt"
   #  failure: None
   def removeDir(self, remoteDir):
-    try:
-      retVal = self.verifySendCMD(['rmdr ' + remoteDir])
-    except(DMError):
-      return None
-
-    return retVal
+    assert 0 == 1
+    return None
 
   # external function
   # returns:
   #  success: array of process tuples
   #  failure: []
   def getProcessList(self):
-    try:
-      data = self.verifySendCMD(['ps'])
-    except DMError:
-      return []
-
-    retVal = self.stripPrompt(data)
-    lines = retVal.split('\n')
-    files = []
-    for line in lines:
-      if (line.strip() != ''):
-        pidproc = line.strip().split()
-        if (len(pidproc) == 2):
-          files += [[pidproc[0], pidproc[1]]]
-        elif (len(pidproc) == 3):
-          #android returns <userID> <procID> <procName>
-          files += [[pidproc[1], pidproc[2], pidproc[0]]]     
-    return files
+    assert 0 == 1
+    return []
 
   # external function
   # returns:
   #  success: pid
   #  failure: None
   def fireProcess(self, appname, failIfRunning=False):
-    if (not appname):
-      if (self.debug >= 1): print "WARNING: fireProcess called with no command to run"
-      return None
-
-    if (self.debug >= 2): print "FIRE PROC: '" + appname + "'"
-
-    if (self.processExist(appname) != None):
-      print "WARNING: process %s appears to be running already\n" % appname
-      if (failIfRunning):
-        return None
-    
-    try:
-      data = self.verifySendCMD(['exec ' + appname])
-    except(DMError):
-      return None
-
-    # wait up to 30 seconds for process to start up
-    timeslept = 0
-    while (timeslept <= 30):
-      process = self.processExist(appname)
-      if (process is not None):
-        break
-      time.sleep(3)
-      timeslept += 3
-
-    if (self.debug >= 4): print "got pid: %s for process: %s" % (process, appname)
-    return process
+    assert 0 == 1
+    return None
 
   # external function
   # returns:
   #  success: output filename
   #  failure: None
   def launchProcess(self, cmd, outputFile = "process.txt", cwd = '', env = '', failIfRunning=False):
-    if not cmd:
-      if (self.debug >= 1): print "WARNING: launchProcess called without command to run"
-      return None
+    assert 0 == 1
+    return None
 
-    cmdline = subprocess.list2cmdline(cmd)
-    if (outputFile == "process.txt" or outputFile == None):
-      outputFile = self.getDeviceRoot();
-      if outputFile is None:
-        return None
-      outputFile += "/process.txt"
-      cmdline += " > " + outputFile
-    
-    # Prepend our env to the command 
-    cmdline = '%s %s' % (self.formatEnvString(env), cmdline)
-
-    if self.fireProcess(cmdline, failIfRunning) is None:
-      return None
-    return outputFile
-  
   # loops until 'process' has exited or 'timeout' seconds is reached
   # loop sleeps for 'interval' seconds between iterations
   # external function
   # returns:
   #  success: [file contents, None]
   #  failure: [None, None]
   def communicate(self, process, timeout = 600, interval = 5):
     timed_out = True
@@ -597,271 +220,83 @@ class DeviceManager:
         break
     return pid
 
   # external function
   # returns:
   #  success: output from testagent
   #  failure: None
   def killProcess(self, appname):
-    try:
-      data = self.verifySendCMD(['kill ' + appname])
-    except(DMError):
-      return None
-
-    return data
-
-  # external function
-  # returns:
-  #  success: tmpdir, string
-  #  failure: None
-  def getTempDir(self):
-    try:
-      data = self.verifySendCMD(['tmpd'])
-    except(DMError):
-      return None
-
-    return self.stripPrompt(data).strip('\n')
+    assert 0 == 1
+    return None
 
   # external function
   # returns:
   #  success: filecontents
   #  failure: None
   def catFile(self, remoteFile):
-    try:
-      data = self.verifySendCMD(['cat ' + remoteFile])
-    except(DMError):
-      return None
+    assert 0 == 1
+    return None
 
-    return self.stripPrompt(data)
-  
   # external function
   # returns:
   #  success: output of pullfile, string
   #  failure: None
   def pullFile(self, remoteFile):
-    """Returns contents of remoteFile using the "pull" command.
-    The "pull" command is different from other commands in that DeviceManager
-    has to read a certain number of bytes instead of just reading to the
-    next prompt.  This is more robust than the "cat" command, which will be
-    confused if the prompt string exists within the file being catted.
-    However it means we can't use the response-handling logic in sendCMD().
-    """
-    
-    def err(error_msg):
-        err_str = 'error returned from pull: %s' % error_msg
-        print err_str
-        self._sock = None
-        raise FileError(err_str) 
-
-    # FIXME: We could possibly move these socket-reading functions up to
-    # the class level if we wanted to refactor sendCMD().  For now they are
-    # only used to pull files.
-    
-    def uread(to_recv, error_msg):
-      """ unbuffered read """
-      try:
-        data = self._sock.recv(to_recv)
-        if not data:
-          err(error_msg)
-          return None
-        return data
-      except:
-        err(error_msg)
-        return None
-
-    def read_until_char(c, buffer, error_msg):
-      """ read until 'c' is found; buffer rest """
-      while not '\n' in buffer:
-        data = uread(1024, error_msg)
-        if data == None:
-          err(error_msg)
-          return ('', '', '')
-        buffer += data
-      return buffer.partition(c)
-
-    def read_exact(total_to_recv, buffer, error_msg):
-      """ read exact number of 'total_to_recv' bytes """
-      while len(buffer) < total_to_recv:
-        to_recv = min(total_to_recv - len(buffer), 1024)
-        data = uread(to_recv, error_msg)
-        if data == None:
-          return None
-        buffer += data
-      return buffer
-
-    prompt = self.base_prompt + self.prompt_sep
-    buffer = ''
-    
-    # expected return value:
-    # <filename>,<filesize>\n<filedata>
-    # or, if error,
-    # <filename>,-1\n<error message>
-    try:
-      data = self.verifySendCMD(['pull ' + remoteFile])
-    except(DMError):
-      return None
-
-    # read metadata; buffer the rest
-    metadata, sep, buffer = read_until_char('\n', buffer, 'could not find metadata')
-    if not metadata:
-      return None
-    if self.debug >= 3:
-      print 'metadata: %s' % metadata
-
-    filename, sep, filesizestr = metadata.partition(',')
-    if sep == '':
-      err('could not find file size in returned metadata')
-      return None
-    try:
-        filesize = int(filesizestr)
-    except ValueError:
-      err('invalid file size in returned metadata')
-      return None
-
-    if filesize == -1:
-      # read error message
-      error_str, sep, buffer = read_until_char('\n', buffer, 'could not find error message')
-      if not error_str:
-        return None
-      # prompt should follow
-      read_exact(len(prompt), buffer, 'could not find prompt')
-      print 'DeviceManager: error pulling file: %s' % error_str
-      return None
-
-    # read file data
-    total_to_recv = filesize + len(prompt)
-    buffer = read_exact(total_to_recv, buffer, 'could not get all file data')
-    if buffer == None:
-      return None
-    if buffer[-len(prompt):] != prompt:
-      err('no prompt found after file data--DeviceManager may be out of sync with agent')
-      return buffer
-    return buffer[:-len(prompt)]
+    assert 0 == 1
+    return None
 
   # copy file from device (remoteFile) to host (localFile)
   # external function
   # returns:
   #  success: output of pullfile, string
   #  failure: None
   def getFile(self, remoteFile, localFile = ''):
-    if localFile == '':
-      localFile = os.path.join(self.tempRoot, "temp.txt")
-  
-    retVal = self.pullFile(remoteFile)
-    if (retVal is None):
-      return None
-
-    fhandle = open(localFile, 'wb')
-    fhandle.write(retVal)
-    fhandle.close()
-    if not self.validateFile(remoteFile, localFile):
-      print 'failed to validate file when downloading %s!' % remoteFile
-      return None
-    return retVal
+    assert 0 == 1
+    return None
 
   # copy directory structure from device (remoteDir) to host (localDir)
   # external function
   # checkDir exists so that we don't create local directories if the
   # remote directory doesn't exist but also so that we don't call isDir
   # twice when recursing.
   # returns:
   #  success: list of files, string
   #  failure: None
   def getDirectory(self, remoteDir, localDir, checkDir=True):
-    if (self.debug >= 2): print "getting files in '" + remoteDir + "'"
-    if checkDir:
-      try:
-        is_dir = self.isDir(remoteDir)
-      except FileError:
-        return None
-      if not is_dir:
-        return None
-        
-    filelist = self.listFiles(remoteDir)
-    if (self.debug >= 3): print filelist
-    if not os.path.exists(localDir):
-      os.makedirs(localDir)
-
-    for f in filelist:
-      if f == '.' or f == '..':
-        continue
-      remotePath = remoteDir + '/' + f
-      localPath = os.path.join(localDir, f)
-      try:
-        is_dir = self.isDir(remotePath)
-      except FileError:
-        print 'isdir failed on file "%s"; continuing anyway...' % remotePath
-        continue
-      if is_dir:
-        if (self.getDirectory(remotePath, localPath, False) == None):
-          print 'failed to get directory "%s"' % remotePath
-          return None
-      else:
-        # It's sometimes acceptable to have getFile() return None, such as
-        # when the agent encounters broken symlinks.
-        # FIXME: This should be improved so we know when a file transfer really
-        # failed.
-        if self.getFile(remotePath, localPath) == None:
-          print 'failed to get file "%s"; continuing anyway...' % remotePath 
-    return filelist
+    assert 0 == 1
+    return None
 
   # external function
   # returns:
   #  success: True
   #  failure: False
   #  Throws a FileError exception when null (invalid dir/filename)
   def isDir(self, remotePath):
-    try:
-      data = self.verifySendCMD(['isdir ' + remotePath])
-    except(DMError):
-      # normally there should be no error here; a nonexistent file/directory will
-      # return the string "<filename>: No such file or directory".
-      # However, I've seen AGENT-WARNING returned before. 
-      return False
-
-    retVal = self.stripPrompt(data).strip()
-    if not retVal:
-      raise FileError('isdir returned null')
-    return retVal == 'TRUE'
+    assert 0 == 1
+    return False
 
   # true/false check if the two files have the same md5 sum
   # external function
   # returns:
   #  success: True
   #  failure: False
   def validateFile(self, remoteFile, localFile):
-    remoteHash = self.getRemoteHash(remoteFile)
-    localHash = self.getLocalHash(localFile)
-
-    if (remoteHash == None):
-      return False
+    assert 0 == 1
+    return False
 
-    if (remoteHash == localHash):
-      return True
-
-    return False
-  
   # return the md5 sum of a remote file
   # internal function
   # returns:
   #  success: MD5 hash for given filename
   #  failure: None
   def getRemoteHash(self, filename):
-    try:
-      data = self.verifySendCMD(['hash ' + filename])
-    except(DMError):
-      return None
+    assert 0 == 1
+    return None
 
-    retVal = self.stripPrompt(data)
-    if (retVal != None):
-      retVal = retVal.strip('\n')
-    if (self.debug >= 3): print "remote hash returned: '" + retVal + "'"
-    return retVal
-    
   # return the md5 sum of a file on the host
   # internal function
   # returns:
   #  success: MD5 hash for given filename
   #  failure: None
   def getLocalHash(self, filename):
     file = open(filename, 'rb')
     if (file == None):
@@ -877,17 +312,16 @@ class DeviceManager:
       if not data:
         break
       mdsum.update(data)
 
     file.close()
     hexval = mdsum.hexdigest()
     if (self.debug >= 3): print "local hash returned: '" + hexval + "'"
     return hexval
-
   # Gets the device root for the testing area on the device
   # For all devices we will use / type slashes and depend on the device-agent
   # to sort those out.  The agent will return us the device location where we
   # should store things, we will then create our /tests structure relative to
   # that returned path.
   # Structure on the device is as follows:
   # /tests
   #       /<fennec>|<firefox>  --> approot
@@ -896,28 +330,18 @@ class DeviceManager:
   #       /reftest
   #       /mochitest
   #
   # external function
   # returns:
   #  success: path for device root
   #  failure: None
   def getDeviceRoot(self):
-    try:
-      data = self.verifySendCMD(['testroot'])
-    except:
-      return None
-  
-    deviceRoot = self.stripPrompt(data).strip('\n') + '/tests'
-
-    if (not self.dirExists(deviceRoot)):
-      if (self.mkDir(deviceRoot) == None):
-        return None
-
-    return deviceRoot
+    assert 0 == 1
+    return None
 
   # Either we will have /tests/fennec or /tests/firefox but we will never have
   # both.  Return the one that exists
   # TODO: ensure we can support org.mozilla.firefox
   # external function
   # returns:
   #  success: path for app root
   #  failure: None
@@ -929,16 +353,20 @@ class DeviceManager:
     if (self.dirExists(devroot + '/fennec')):
       return devroot + '/fennec'
     elif (self.dirExists(devroot + '/firefox')):
       return devroot + '/firefox'
     elif (self.dirExsts('/data/data/org.mozilla.fennec')):
       return 'org.mozilla.fennec'
     elif (self.dirExists('/data/data/org.mozilla.firefox')):
       return 'org.mozilla.firefox'
+    elif (self.dirExists('/data/data/org.mozilla.fennec_aurora')):
+      return 'org.mozilla.fennec_aurora'
+    elif (self.dirExists('/data/data/org.mozilla.firefox_beta')):
+      return 'org.mozilla.firefox_beta'
 
     # Failure (either not installed or not a recognized platform)
     return None
 
   # Gets the directory location on the device for a specific test type
   # Type is one of: xpcshell|reftest|mochitest
   # external function
   # returns:
@@ -968,73 +396,25 @@ class DeviceManager:
     # TODO: make this real
     return 0
 
   # external function
   # returns:
   #  success: output of unzip command
   #  failure: None
   def unpackFile(self, filename):
-    devroot = self.getDeviceRoot()
-    if (devroot == None):
-      return None
-
-    dir = ''
-    parts = filename.split('/')
-    if (len(parts) > 1):
-      if self.fileExists(filename):
-        dir = '/'.join(parts[:-1])
-    elif self.fileExists('/' + filename):
-      dir = '/' + filename
-    elif self.fileExists(devroot + '/' + filename):
-      dir = devroot + '/' + filename
-    else:
-      return None
-
-    try:
-      data = self.verifySendCMD(['cd ' + dir, 'unzp ' + filename])
-    except(DMError):
-      return None
-
-    return data
+    return None
 
   # external function
   # returns:
   #  success: status from test agent
   #  failure: None
   def reboot(self, ipAddr=None, port=30000):
-    cmd = 'rebt'   
-
-    if (self.debug > 3): print "INFO: sending rebt command"
-    callbacksvrstatus = None    
-
-    if (ipAddr is not None):
-    #create update.info file:
-      try:
-        destname = '/data/data/com.mozilla.SUTAgentAndroid/files/update.info'
-        data = "%s,%s\rrebooting\r" % (ipAddr, port)
-        self.verifySendCMD(['push ' + destname + ' ' + str(len(data)) + '\r\n', data], newline = False)
-      except(DMError):
-        return None
-
-      ip, port = self.getCallbackIpAndPort(ipAddr, port)
-      cmd += " %s %s" % (ip, port)
-      # Set up our callback server
-      callbacksvr = callbackServer(ip, port, self.debug)
-
-    try:
-      status = self.verifySendCMD([cmd])
-    except(DMError):
-      return None
-
-    if (ipAddr is not None):
-      status = callbacksvr.disconnect()
-
-    if (self.debug > 3): print "INFO: rebt- got status back: " + str(status)
-    return status
+    assert 0 == 1
+    return None
 
   # validate localDir from host to remoteDir on the device
   # external function
   # returns:
   #  success: True
   #  failure: False
   def validateDir(self, localDir, remoteDir):
     if (self.debug >= 2): print "validating directory: " + localDir + " to " + remoteDir
@@ -1060,288 +440,52 @@ class DeviceManager:
   # process - list of running processes (same as ps)
   # disk - total, free, available bytes on disk
   # power - power status (charge, battery temp)
   # all - all of them - or call it with no parameters to get all the information
   # returns:
   #   success: dict of info strings by directive name
   #   failure: {}
   def getInfo(self, directive=None):
-    data = None
-    result = {}
-    collapseSpaces = re.compile('  +')
-
-    directives = ['os', 'id','uptime','systime','screen','memory','process',
-                  'disk','power']
-    if (directive in directives):
-      directives = [directive]
-
-    for d in directives:
-      data = self.verifySendCMD(['info ' + d])
-      if (data is None):
-        continue
-      data = self.stripPrompt(data)
-      data = collapseSpaces.sub(' ', data)
-      result[d] = data.split('\n')
+    assert 0 == 1
+    return {}
 
-    # Get rid of any 0 length members of the arrays
-    for k, v in result.iteritems():
-      result[k] = filter(lambda x: x != '', result[k])
-    
-    # Format the process output
-    if 'process' in result:
-      proclist = []
-      for l in result['process']:
-        if l:
-          proclist.append(l.split('\t'))
-      result['process'] = proclist
-
-    if (self.debug >= 3): print "results: " + str(result)
-    return result
-
-  """
-  Installs the application onto the device
-  Application bundle - path to the application bundle on the device
-  Destination - destination directory of where application should be
-                installed to (optional)
-  Returns None for success, or output if known failure
-  """
   # external function
   # returns:
   #  success: output from agent for inst command
   #  failure: None
   def installApp(self, appBundlePath, destPath=None):
-    cmd = 'inst ' + appBundlePath
-    if destPath:
-      cmd += ' ' + destPath
-    try:
-      data = self.verifySendCMD([cmd])
-    except(DMError):
-      return None
-
-    f = re.compile('Failure')
-    for line in data.split():
-      if (f.match(line)):
-        return data
+    assert 0 == 1
     return None
 
-  """
-  Uninstalls the named application from device and causes a reboot.
-  Takes an optional argument of installation path - the path to where the application
-  was installed.
-  Returns True, but it doesn't mean anything other than the command was sent,
-  the reboot happens and we don't know if this succeeds or not.
-  """
   # external function
   # returns:
   #  success: True
   #  failure: None
   def uninstallAppAndReboot(self, appName, installPath=None):
-    cmd = 'uninst ' + appName
-    if installPath:
-      cmd += ' ' + installPath
-    try:
-      data = self.verifySendCMD([cmd])
-    except(DMError):
-      return None
-
-    if (self.debug > 3): print "uninstallAppAndReboot: " + str(data)
-    return True
+    assert 0 == 1
+    return None
 
-  """
-  Updates the application on the device.
-  Application bundle - path to the application bundle on the device
-  Process name of application - used to end the process if the applicaiton is
-                                currently running
-  Destination - Destination directory to where the application should be
-                installed (optional)
-  ipAddr - IP address to await a callback ping to let us know that the device has updated
-           properly - defaults to current IP.
-  port - port to await a callback ping to let us know that the device has updated properly
-         defaults to 30000, and counts up from there if it finds a conflict
-  Returns True if succeeds, False if not
-  """
   # external function
   # returns:
   #  success: text status from command or callback server
   #  failure: None
   def updateApp(self, appBundlePath, processName=None, destPath=None, ipAddr=None, port=30000):
-    status = None
-    cmd = 'updt '
-    if (processName == None):
-      # Then we pass '' for processName
-      cmd += "'' " + appBundlePath
-    else:
-      cmd += processName + ' ' + appBundlePath
-
-    if (destPath):
-      cmd += " " + destPath
-
-    if (ipAddr is not None):
-      ip, port = self.getCallbackIpAndPort(ipAddr, port)
-      cmd += " %s %s" % (ip, port)
-      # Set up our callback server
-      callbacksvr = callbackServer(ip, port, self.debug)
+    assert 0 == 1
+    return None
 
-    if (self.debug >= 3): print "INFO: updateApp using command: " + str(cmd)
-
-    try:
-      status = self.verifySendCMD([cmd])
-    except(DMError):
-      return None
-
-    if ipAddr is not None:
-      status = callbacksvr.disconnect()
-
-    if (self.debug >= 3): print "INFO: updateApp: got status back: " + str(status)
-
-    return status
-
-  """
-    return the current time on the device
-  """
   # external function
   # returns:
   #  success: time in ms
   #  failure: None
   def getCurrentTime(self):
-    try:
-      data = self.verifySendCMD(['clok'])
-    except(DMError):
-      return None
-
-    return self.stripPrompt(data).strip('\n')
-
-  """
-    Connect the ipaddress and port for a callback ping.  Defaults to current IP address
-    And ports starting at 30000.
-    NOTE: the detection for current IP address only works on Linux!
-  """
-  def getCallbackIpAndPort(self, aIp, aPort):
-    ip = aIp
-    nettools = NetworkTools()
-    if (ip == None):
-      ip = nettools.getLanIp()
-    if (aPort != None):
-      port = nettools.findOpenPort(ip, aPort)
-    else:
-      port = nettools.findOpenPort(ip, 30000)
-    return ip, port
-
-  """
-    Returns a properly formatted env string for the agent.
-    Input - env, which is either None, '', or a dict
-    Output - a quoted string of the form: '"envvar1=val1,envvar2=val2..."'
-    If env is None or '' return '' (empty quoted string)
-  """
-  def formatEnvString(self, env):
-    if (env == None or env == ''):
-      return ''
-
-    retVal = '"%s"' % ','.join(map(lambda x: '%s=%s' % (x[0], x[1]), env.iteritems()))
-    if (retVal == '""'):
-      return ''
-
-    return retVal
-
-  """
-    adjust the screen resolution on the device, REBOOT REQUIRED
-    NOTE: this only works on a tegra ATM
-    success: True
-    failure: False
-
-    supported resolutions: 640x480, 800x600, 1024x768, 1152x864, 1200x1024, 1440x900, 1680x1050, 1920x1080
-  """
-  def adjustResolution(self, width=1680, height=1050, type='hdmi'):
-    if self.getInfo('os')['os'][0].split()[0] != 'harmony-eng':
-      if (self.debug >= 2): print "WARNING: unable to adjust screen resolution on non Tegra device"
-      return False
-
-    results = self.getInfo('screen')
-    parts = results['screen'][0].split(':')
-    if (self.debug >= 3): print "INFO: we have a current resolution of %s, %s" % (parts[1].split()[0], parts[2].split()[0])
-
-    #verify screen type is valid, and set it to the proper value (https://bugzilla.mozilla.org/show_bug.cgi?id=632895#c4)
-    screentype = -1
-    if (type == 'hdmi'):
-      screentype = 5
-    elif (type == 'vga' or type == 'crt'):
-      screentype = 3
-    else:
-      return False
+    assert 0 == 1
+    return None
 
-    #verify we have numbers
-    if not (isinstance(width, int) and isinstance(height, int)):
-      return False
 
-    if (width < 100 or width > 9999):
-      return False
-
-    if (height < 100 or height > 9999):
-      return False
-
-    if (self.debug >= 3): print "INFO: adjusting screen resolution to %s, %s and rebooting" % (width, height)
-    try:
-      self.verifySendCMD(["exec setprop persist.tegra.dpy%s.mode.width %s" % (screentype, width)])
-      self.verifySendCMD(["exec setprop persist.tegra.dpy%s.mode.height %s" % (screentype, height)])
-    except(DMError):
-      return False
-
-    return True
-
-gCallbackData = ''
-
-class myServer(SocketServer.TCPServer):
-  allow_reuse_address = True
-
-class callbackServer():
-  def __init__(self, ip, port, debuglevel):
-    global gCallbackData
-    if (debuglevel >= 1): print "DEBUG: gCallbackData is: %s on port: %s" % (gCallbackData, port)
-    gCallbackData = ''
-    self.ip = ip
-    self.port = port
-    self.connected = False
-    self.debug = debuglevel
-    if (self.debug >= 3): print "Creating server with " + str(ip) + ":" + str(port)
-    self.server = myServer((ip, port), self.myhandler)
-    self.server_thread = Thread(target=self.server.serve_forever) 
-    self.server_thread.setDaemon(True)
-    self.server_thread.start()
-
-  def disconnect(self, step = 60, timeout = 600):
-    t = 0
-    if (self.debug >= 3): print "Calling disconnect on callback server"
-    while t < timeout:
-      if (gCallbackData):
-        # Got the data back
-        if (self.debug >= 3): print "Got data back from agent: " + str(gCallbackData)
-        break
-      else:
-        if (self.debug >= 0): print '.',
-      time.sleep(step)
-      t += step
-
-    try:
-      if (self.debug >= 3): print "Shutting down server now"
-      self.server.shutdown()
-    except:
-      if (self.debug >= 1): print "Unable to shutdown callback server - check for a connection on port: " + str(self.port)
-
-    #sleep 1 additional step to ensure not only we are online, but all our services are online
-    time.sleep(step)
-    return gCallbackData
-
-  class myhandler(SocketServer.BaseRequestHandler):
-    def handle(self):
-      global gCallbackData
-      gCallbackData = self.request.recv(1024)
-      #print "Callback Handler got data: " + str(gCallbackData)
-      self.request.send("OK")
-  
 class NetworkTools:
   def __init__(self):
     pass
 
   # Utilities to get the local ip address
   def getInterfaceIp(self, ifname):
     if os.name != "nt":
       import fcntl
new file mode 100644
--- /dev/null
+++ b/build/mobile/devicemanagerADB.py
@@ -0,0 +1,439 @@
+import subprocess
+from devicemanager import DeviceManager, DMError
+import re
+
+class DeviceManagerADB(DeviceManager):
+
+  def __init__(self, host = None, port = 20701, retrylimit = 5):
+    self.host = host
+    self.port = port
+    self.retrylimit = retrylimit
+    self.retries = 0
+    self._sock = None
+    self.getDeviceRoot()
+    try:
+      # a test to see if we have root privs
+      self.checkCmd(["shell", "ls", "/sbin"])
+    except:
+      try:
+        self.checkCmd(["root"])
+      except:
+        print "restarting as root failed"
+
+  # external function
+  # returns:
+  #  success: True
+  #  failure: False
+  def pushFile(self, localname, destname):
+    try:
+      self.checkCmd(["push", localname, destname])
+      self.chmodDir(destname)
+      return True
+    except:
+      return False
+
+  # external function
+  # returns:
+  #  success: directory name
+  #  failure: None
+  def mkDir(self, name):
+    try:
+      self.checkCmd(["shell", "mkdir", name])
+      return name
+    except:
+      return None
+
+  # make directory structure on the device
+  # external function
+  # returns:
+  #  success: directory structure that we created
+  #  failure: None
+  def mkDirs(self, filename):
+    self.checkCmd(["shell", "mkdir", "-p ", name])
+    return filename
+
+  # push localDir from host to remoteDir on the device
+  # external function
+  # returns:
+  #  success: remoteDir
+  #  failure: None
+  def pushDir(self, localDir, remoteDir):
+    try:
+      self.checkCmd(["push", localDir, remoteDir])
+      self.chmodDir(remoteDir)
+      return True
+    except:
+      print "pushing " + localDir + " to " + remoteDir + " failed"
+      return False
+
+  # external function
+  # returns:
+  #  success: True
+  #  failure: False
+  def dirExists(self, dirname):
+    try:
+      self.checkCmd(["shell", "ls", dirname])
+      return True
+    except:
+      return False
+
+  # Because we always have / style paths we make this a lot easier with some
+  # assumptions
+  # external function
+  # returns:
+  #  success: True
+  #  failure: False
+  def fileExists(self, filepath):
+    self.checkCmd(["shell", "ls", filepath])
+    return True
+
+  def removeFile(self, filename):
+    return self.runCmd(["shell", "rm", filename]).stdout.read()
+
+  # does a recursive delete of directory on the device: rm -Rf remoteDir
+  # external function
+  # returns:
+  #  success: output of telnet, i.e. "removing file: /mnt/sdcard/tests/test.txt"
+  #  failure: None
+  def removeSingleDir(self, remoteDir):
+    return self.runCmd(["shell", "rmdir", remoteDir]).stdout.read()
+
+  # does a recursive delete of directory on the device: rm -Rf remoteDir
+  # external function
+  # returns:
+  #  success: output of telnet, i.e. "removing file: /mnt/sdcard/tests/test.txt"
+  #  failure: None
+  def removeDir(self, remoteDir):
+      out = ""
+      if (self.isDir(remoteDir)):
+          files = self.listFiles(remoteDir.strip())
+          for f in files:
+              if (self.isDir(remoteDir.strip() + "/" + f.strip())):
+                  out += self.removeDir(remoteDir.strip() + "/" + f.strip())
+              else:
+                  out += self.removeFile(remoteDir.strip())
+          out += self.removeSingleDir(remoteDir)
+      else:
+          out += self.removeFile(remoteDir.strip())
+      return out
+
+  def isDir(self, remotePath):
+      p = self.runCmd(["shell", "ls", remotePath])
+      data = p.stdout.readlines()
+      if (len(data) == 0):
+          return True
+      if (len(data) == 1):
+          if (data[0] == remotePath):
+              return False
+          if (data[0].find("No such file or directory") != -1):
+              return False
+          if (data[0].find("Not a directory") != -1):
+              return False
+      return True
+
+  def listFiles(self, rootdir):
+      p = self.runCmd(["shell", "ls", rootdir])
+      data = p.stdout.readlines()
+      if (len(data) == 1):
+          if (data[0] == rootdir):
+              return []
+          if (data[0].find("No such file or directory") != -1):
+              return []
+          if (data[0].find("Not a directory") != -1):
+              return []
+      return data
+
+  # external function
+  # returns:
+  #  success: array of process tuples
+  #  failure: []
+  def getProcessList(self):
+    p = self.runCmd(["shell", "ps"])
+      # first line is the headers
+    p.stdout.readline()
+    proc = p.stdout.readline()
+    ret = []
+    while (proc):
+      els = proc.split()
+      ret.append(list([els[1], els[len(els) - 1], els[0]]))
+      proc =  p.stdout.readline()
+    return ret
+
+  # external function
+  # returns:
+  #  success: pid
+  #  failure: None
+  def fireProcess(self, appname, failIfRunning=False):
+    return self.runCmd(["shell", appname]).pid
+
+  # external function
+  # returns:
+  #  success: output filename
+  #  failure: None
+  def launchProcess(self, cmd, outputFile = "process.txt", cwd = '', env = '', failIfRunning=False):
+    acmd = ["shell", "am","start"]
+    cmd = ' '.join(cmd)
+    i = cmd.find(" ")
+    acmd.append("-n")
+    acmd.append(cmd[0:i] + "/.App")
+    acmd.append("--es")
+    acmd.append("args")
+    acmd.append(cmd[i:])
+    print acmd
+    self.checkCmd(acmd)
+    return outputFile;
+
+  # external function
+  # returns:
+  #  success: output from testagent
+  #  failure: None
+  def killProcess(self, appname):
+    procs = self.getProcessList()
+    for proc in procs:
+      if (proc[1] == appname):
+        p = self.runCmd(["shell", "ps"])
+        return p.stdout.read()
+      return None
+
+  # external function
+  # returns:
+  #  success: filecontents
+  #  failure: None
+  def catFile(self, remoteFile):
+    #p = self.runCmd(["shell", "cat", remoteFile])
+    #return p.stdout.read()
+    return self.getFile(remoteFile)
+
+  # external function
+  # returns:
+  #  success: output of pullfile, string
+  #  failure: None
+  def pullFile(self, remoteFile):
+    #return self.catFile(remoteFile)
+    return self.getFile(remoteFile)
+
+  # copy file from device (remoteFile) to host (localFile)
+  # external function
+  # returns:
+  #  success: output of pullfile, string
+  #  failure: None
+  def getFile(self, remoteFile, localFile = 'tmpfile_dm_adb'):
+    try:
+      self.checkCmd(["pull",  remoteFile, localFile])
+      f = open(localFile)
+      ret = f.read()
+      f.close()
+      return ret;      
+    except:
+      return None
+
+  # copy directory structure from device (remoteDir) to host (localDir)
+  # external function
+  # checkDir exists so that we don't create local directories if the
+  # remote directory doesn't exist but also so that we don't call isDir
+  # twice when recursing.
+  # returns:
+  #  success: list of files, string
+  #  failure: None
+  def getDirectory(self, remoteDir, localDir, checkDir=True):
+    ret = []
+    p = self.runCmd(["pull", remoteDir, localDir])
+    p.stderr.readline()
+    line = p.stderr.readline()
+    while (line):
+      els = line.split()
+      f = els[len(els) - 1]
+      i = f.find(localDir)
+      if (i != -1):
+        if (localDir[len(localDir) - 1] != '/'):
+          i = i + 1
+        f = f[i + len(localDir):]
+      i = f.find("/")
+      if (i > 0):
+        f = f[0:i]
+      ret.append(f)
+      line =  p.stderr.readline()
+    #the last line is a summary
+    ret.pop(len(ret) - 1)
+    return ret
+
+
+
+  # true/false check if the two files have the same md5 sum
+  # external function
+  # returns:
+  #  success: True
+  #  failure: False
+  def validateFile(self, remoteFile, localFile):
+    return self.getRemoteHash(remoteFile) == self.getLocalHash(localFile)
+
+  # return the md5 sum of a remote file
+  # internal function
+  # returns:
+  #  success: MD5 hash for given filename
+  #  failure: None
+  def getRemoteHash(self, filename):
+    data = p = self.runCmd(["shell", "ls", "-l", filename]).stdout.read()
+    return data.split()[3]
+
+  def getLocalHash(self, filename):
+    data = p = subprocess.Popen(["ls", "-l", filename], stdout=subprocess.PIPE).stdout.read()
+    return data.split()[4]
+
+  # Gets the device root for the testing area on the device
+  # For all devices we will use / type slashes and depend on the device-agent
+  # to sort those out.  The agent will return us the device location where we
+  # should store things, we will then create our /tests structure relative to
+  # that returned path.
+  # Structure on the device is as follows:
+  # /tests
+  #       /<fennec>|<firefox>  --> approot
+  #       /profile
+  #       /xpcshell
+  #       /reftest
+  #       /mochitest
+  #
+  # external function
+  # returns:
+  #  success: path for device root
+  #  failure: None
+  def getDeviceRoot(self):
+    if (not self.dirExists("/data/local/tests")):
+      self.mkDir("/data/local/tests")
+    return "/data/local/tests"
+
+  # Either we will have /tests/fennec or /tests/firefox but we will never have
+  # both.  Return the one that exists
+  # TODO: ensure we can support org.mozilla.firefox
+  # external function
+  # returns:
+  #  success: path for app root
+  #  failure: None
+  def getAppRoot(self):
+    devroot = self.getDeviceRoot()
+    if (devroot == None):
+      return None
+
+    if (self.dirExists(devroot + '/fennec')):
+      return devroot + '/fennec'
+    elif (self.dirExists(devroot + '/firefox')):
+      return devroot + '/firefox'
+    elif (self.dirExsts('/data/data/org.mozilla.fennec')):
+      return 'org.mozilla.fennec'
+    elif (self.dirExists('/data/data/org.mozilla.firefox')):
+      return 'org.mozilla.firefox'
+
+    # Failure (either not installed or not a recognized platform)
+    return None
+
+  # Gets the directory location on the device for a specific test type
+  # Type is one of: xpcshell|reftest|mochitest
+  # external function
+  # returns:
+  #  success: path for test root
+  #  failure: None
+  def getTestRoot(self, type):
+    devroot = self.getDeviceRoot()
+    if (devroot == None):
+      return None
+
+    if (re.search('xpcshell', type, re.I)):
+      self.testRoot = devroot + '/xpcshell'
+    elif (re.search('?(i)reftest', type)):
+      self.testRoot = devroot + '/reftest'
+    elif (re.search('?(i)mochitest', type)):
+      self.testRoot = devroot + '/mochitest'
+    return self.testRoot
+
+
+  # external function
+  # returns:
+  #  success: status from test agent
+  #  failure: None
+  def reboot(self, wait = False):
+    ret = self.runCmd(["reboot"]).stdout.read()
+    if (not wait):
+      return "Success"
+    countdown = 40
+    while (countdown > 0):
+      countdown
+      try:
+        self.checkCmd(["wait-for-device", "shell", "ls", "/sbin"])
+        return ret
+      except:
+        try:
+          self.checkCmd(["root"])
+        except:
+          time.sleep(1)
+          print "couldn't get root"
+    return "Success"
+
+  # external function
+  # returns:
+  #  success: text status from command or callback server
+  #  failure: None
+  def updateApp(self, appBundlePath, processName=None, destPath=None, ipAddr=None, port=30000):
+    return self.runCmd(["install", "-r", appBundlePath]).stdout.read()
+    
+  # Returns information about the device:
+  # Directive indicates the information you want to get, your choices are:
+  # os - name of the os
+  # id - unique id of the device
+  # uptime - uptime of the device
+  # systime - system time of the device
+  # screen - screen resolution
+  # memory - memory stats
+  # process - list of running processes (same as ps)
+  # disk - total, free, available bytes on disk
+  # power - power status (charge, battery temp)
+  # all - all of them - or call it with no parameters to get all the information
+  # returns:
+  #   success: dict of info strings by directive name
+  #   failure: {}
+  def getInfo(self, directive="all"):
+    ret = {}
+    if (directive == "id" or directive == "all"):
+      ret["id"] = self.runCmd(["get-serialno"]).stdout.read()
+    if (directive == "os" or directive == "all"):
+      ret["os"] = self.runCmd(["shell", "getprop", "ro.build.display.id"]).stdout.read()
+    if (directive == "uptime" or directive == "all"):
+      utime = self.runCmd(["shell", "uptime"]).stdout.read()
+      if (not utime):
+        raise DMError("error getting uptime")
+      utime = utime[9:]
+      hours = utime[0:utime.find(":")]
+      utime = utime[utime[1:].find(":") + 2:]
+      minutes = utime[0:utime.find(":")]
+      utime = utime[utime[1:].find(":") +  2:]
+      seconds = utime[0:utime.find(",")]
+      ret["uptime"] = ["0 days " + hours + " hours " + minutes + " minutes " + seconds + " seconds"]
+    if (directive == "process" or directive == "all"):
+      ret["process"] = self.runCmd(["shell", "ps"]).stdout.read()
+    if (directive == "systime" or directive == "all"):
+      ret["systime"] = self.runCmd(["shell", "date"]).stdout.read()
+    print ret
+    return ret
+
+  def runCmd(self, args):
+    args.insert(0, "adb")
+    return subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+
+  def checkCmd(self, args):
+    args.insert(0, "adb")
+    return subprocess.check_call(args)
+
+  def chmodDir(self, remoteDir):
+    print "called chmodDir"
+    if (self.isDir(remoteDir)):
+      files = self.listFiles(remoteDir.strip())
+      for f in files:
+        if (self.isDir(remoteDir.strip() + "/" + f.strip())):
+          self.chmodDir(remoteDir.strip() + "/" + f.strip())
+        else:
+          self.checkCmd(["shell", "chmod", "777", remoteDir.strip()])
+          print "chmod " + remoteDir.strip()
+      self.checkCmd(["shell", "chmod", "777", remoteDir])
+      print "chmod " + remoteDir
+    else:
+      self.checkCmd(["shell", "chmod", "777", remoteDir.strip()])
+      print "chmod " + remoteDir
copy from build/mobile/devicemanager.py
copy to build/mobile/devicemanagerSUT.py
--- a/build/mobile/devicemanager.py
+++ b/build/mobile/devicemanagerSUT.py
@@ -42,37 +42,19 @@ import SocketServer
 import time, datetime
 import os
 import re
 import hashlib
 import subprocess
 from threading import Thread
 import traceback
 import sys
-
-class FileError(Exception):
-  " Signifies an error which occurs while doing a file operation."
-
-  def __init__(self, msg = ''):
-    self.msg = msg
-
-  def __str__(self):
-    return self.msg
+from devicemanager import DeviceManager, DMError, FileError, NetworkTools
 
-class DMError(Exception):
-  "generic devicemanager exception."
-
-  def __init__(self, msg= ''):
-    self.msg = msg
-
-  def __str__(self):
-    return self.msg
-
-
-class DeviceManager:
+class DeviceManagerSUT(DeviceManager):
   host = ''
   port = 0
   debug = 2 
   retries = 0
   tempRoot = os.getcwd()
   base_prompt = '$>'
   base_prompt_re = '\$\>'
   prompt_sep = '\x00'
@@ -537,38 +519,16 @@ class DeviceManager:
     
     # Prepend our env to the command 
     cmdline = '%s %s' % (self.formatEnvString(env), cmdline)
 
     if self.fireProcess(cmdline, failIfRunning) is None:
       return None
     return outputFile
   
-  # loops until 'process' has exited or 'timeout' seconds is reached
-  # loop sleeps for 'interval' seconds between iterations
-  # external function
-  # returns:
-  #  success: [file contents, None]
-  #  failure: [None, None]
-  def communicate(self, process, timeout = 600, interval = 5):
-    timed_out = True
-    if (timeout > 0):
-      total_time = 0
-      while total_time < timeout:
-        time.sleep(interval)
-        if self.processExist(process) == None:
-          timed_out = False
-          break
-        total_time += interval
-
-    if (timed_out == True):
-      return [None, None]
-
-    return [self.getFile(process, "temp.txt"), None]
-
   # iterates process list and returns pid if exists, otherwise None
   # external function
   # returns:
   #  success: pid
   #  failure: None
   def processExist(self, appname):
     pid = None
 
@@ -812,17 +772,16 @@ class DeviceManager:
   def isDir(self, remotePath):
     try:
       data = self.verifySendCMD(['isdir ' + remotePath])
     except(DMError):
       # normally there should be no error here; a nonexistent file/directory will
       # return the string "<filename>: No such file or directory".
       # However, I've seen AGENT-WARNING returned before. 
       return False
-
     retVal = self.stripPrompt(data).strip()
     if not retVal:
       raise FileError('isdir returned null')
     return retVal == 'TRUE'
 
   # true/false check if the two files have the same md5 sum
   # external function
   # returns:
@@ -852,42 +811,16 @@ class DeviceManager:
       return None
 
     retVal = self.stripPrompt(data)
     if (retVal != None):
       retVal = retVal.strip('\n')
     if (self.debug >= 3): print "remote hash returned: '" + retVal + "'"
     return retVal
     
-  # return the md5 sum of a file on the host
-  # internal function
-  # returns:
-  #  success: MD5 hash for given filename
-  #  failure: None
-  def getLocalHash(self, filename):
-    file = open(filename, 'rb')
-    if (file == None):
-      return None
-
-    try:
-      mdsum = hashlib.md5()
-    except:
-      return None
-
-    while 1:
-      data = file.read(1024)
-      if not data:
-        break
-      mdsum.update(data)
-
-    file.close()
-    hexval = mdsum.hexdigest()
-    if (self.debug >= 3): print "local hash returned: '" + hexval + "'"
-    return hexval
-
   # Gets the device root for the testing area on the device
   # For all devices we will use / type slashes and depend on the device-agent
   # to sort those out.  The agent will return us the device location where we
   # should store things, we will then create our /tests structure relative to
   # that returned path.
   # Structure on the device is as follows:
   # /tests
   #       /<fennec>|<firefox>  --> approot
@@ -909,70 +842,16 @@ class DeviceManager:
     deviceRoot = self.stripPrompt(data).strip('\n') + '/tests'
 
     if (not self.dirExists(deviceRoot)):
       if (self.mkDir(deviceRoot) == None):
         return None
 
     return deviceRoot
 
-  # Either we will have /tests/fennec or /tests/firefox but we will never have
-  # both.  Return the one that exists
-  # TODO: ensure we can support org.mozilla.firefox
-  # external function
-  # returns:
-  #  success: path for app root
-  #  failure: None
-  def getAppRoot(self):
-    devroot = self.getDeviceRoot()
-    if (devroot == None):
-      return None
-
-    if (self.dirExists(devroot + '/fennec')):
-      return devroot + '/fennec'
-    elif (self.dirExists(devroot + '/firefox')):
-      return devroot + '/firefox'
-    elif (self.dirExsts('/data/data/org.mozilla.fennec')):
-      return 'org.mozilla.fennec'
-    elif (self.dirExists('/data/data/org.mozilla.firefox')):
-      return 'org.mozilla.firefox'
-
-    # Failure (either not installed or not a recognized platform)
-    return None
-
-  # Gets the directory location on the device for a specific test type
-  # Type is one of: xpcshell|reftest|mochitest
-  # external function
-  # returns:
-  #  success: path for test root
-  #  failure: None
-  def getTestRoot(self, type):
-    devroot = self.getDeviceRoot()
-    if (devroot == None):
-      return None
-
-    if (re.search('xpcshell', type, re.I)):
-      self.testRoot = devroot + '/xpcshell'
-    elif (re.search('?(i)reftest', type)):
-      self.testRoot = devroot + '/reftest'
-    elif (re.search('?(i)mochitest', type)):
-      self.testRoot = devroot + '/mochitest'
-    return self.testRoot
-
-  # Sends a specific process ID a signal code and action.
-  # For Example: SIGINT and SIGDFL to process x
-  def signal(self, processID, signalType, signalAction):
-    # currently not implemented in device agent - todo
-    pass
-
-  # Get a return code from process ending -- needs support on device-agent
-  def getReturnCode(self, processID):
-    # TODO: make this real
-    return 0
-
   # external function
   # returns:
   #  success: output of unzip command
   #  failure: None
   def unpackFile(self, filename):
     devroot = self.getDeviceRoot()
     if (devroot == None):
       return None
@@ -1026,34 +905,16 @@ class DeviceManager:
       return None
 
     if (ipAddr is not None):
       status = callbacksvr.disconnect()
 
     if (self.debug > 3): print "INFO: rebt- got status back: " + str(status)
     return status
 
-  # validate localDir from host to remoteDir on the device
-  # external function
-  # returns:
-  #  success: True
-  #  failure: False
-  def validateDir(self, localDir, remoteDir):
-    if (self.debug >= 2): print "validating directory: " + localDir + " to " + remoteDir
-    for root, dirs, files in os.walk(localDir):
-      parts = root.split(localDir)
-      for file in files:
-        remoteRoot = remoteDir + '/' + parts[1]
-        remoteRoot = remoteRoot.replace('/', '/')
-        if (parts[1] == ""): remoteRoot = remoteDir
-        remoteName = remoteRoot + '/' + file
-        if (self.validateFile(remoteName, os.path.join(root, file)) <> True):
-            return False
-    return True
-
   # Returns information about the device:
   # Directive indicates the information you want to get, your choices are:
   # os - name of the os
   # id - unique id of the device
   # uptime - uptime of the device
   # systime - system time of the device
   # screen - screen resolution
   # memory - memory stats
@@ -1210,16 +1071,44 @@ class DeviceManager:
 
     return self.stripPrompt(data).strip('\n')
 
   """
     Connect the ipaddress and port for a callback ping.  Defaults to current IP address
     And ports starting at 30000.
     NOTE: the detection for current IP address only works on Linux!
   """
+  # external function
+  # returns:
+  #  success: output of unzip command
+  #  failure: None
+  def unpackFile(self, filename):
+    devroot = self.getDeviceRoot()
+    if (devroot == None):
+      return None
+
+    dir = ''
+    parts = filename.split('/')
+    if (len(parts) > 1):
+      if self.fileExists(filename):
+        dir = '/'.join(parts[:-1])
+    elif self.fileExists('/' + filename):
+      dir = '/' + filename
+    elif self.fileExists(devroot + '/' + filename):
+      dir = devroot + '/' + filename
+    else:
+      return None
+
+    try:
+      data = self.verifySendCMD(['cd ' + dir, 'unzp ' + filename])
+    except(DMError):
+      return None
+
+    return data
+
   def getCallbackIpAndPort(self, aIp, aPort):
     ip = aIp
     nettools = NetworkTools()
     if (ip == None):
       ip = nettools.getLanIp()
     if (aPort != None):
       port = nettools.findOpenPort(ip, aPort)
     else:
@@ -1332,63 +1221,8 @@ class callbackServer():
 
   class myhandler(SocketServer.BaseRequestHandler):
     def handle(self):
       global gCallbackData
       gCallbackData = self.request.recv(1024)
       #print "Callback Handler got data: " + str(gCallbackData)
       self.request.send("OK")
   
-class NetworkTools:
-  def __init__(self):
-    pass
-
-  # Utilities to get the local ip address
-  def getInterfaceIp(self, ifname):
-    if os.name != "nt":
-      import fcntl
-      import struct
-      s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
-      return socket.inet_ntoa(fcntl.ioctl(
-                              s.fileno(),
-                              0x8915,  # SIOCGIFADDR
-                              struct.pack('256s', ifname[:15])
-                              )[20:24])
-    else:
-      return None
-
-  def getLanIp(self):
-    ip = socket.gethostbyname(socket.gethostname())
-    if ip.startswith("127.") and os.name != "nt":
-      interfaces = ["eth0","eth1","eth2","wlan0","wlan1","wifi0","ath0","ath1","ppp0"]
-      for ifname in interfaces:
-        try:
-          ip = self.getInterfaceIp(ifname)
-          break;
-        except IOError:
-          pass
-    return ip
-
-  # Gets an open port starting with the seed by incrementing by 1 each time
-  def findOpenPort(self, ip, seed):
-    try:
-      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-      s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
-      connected = False
-      if isinstance(seed, basestring):
-        seed = int(seed)
-      maxportnum = seed + 5000 # We will try at most 5000 ports to find an open one
-      while not connected:
-        try:
-          s.bind((ip, seed))
-          connected = True
-          s.close()
-          break
-        except:          
-          if seed > maxportnum:
-            print "Could not find open port after checking 5000 ports"
-          raise
-        seed += 1
-    except:
-      print "Socket error trying to find open port"
-        
-    return seed
-
--- a/caps/src/nsScriptSecurityManager.cpp
+++ b/caps/src/nsScriptSecurityManager.cpp
@@ -2629,16 +2629,21 @@ nsScriptSecurityManager::IsCapabilityEna
             return NS_OK;
 
         // Now see if the capability is enabled.
         void *annotation = JS_GetFrameAnnotation(cx, fp);
         rv = principal->IsCapabilityEnabled(capability, annotation, result);
         if (NS_FAILED(rv)) return rv;
         if (*result)
             return NS_OK;
+
+        // Capabilities do not extend to calls into C/C++ and then back into
+        // the JS engine via JS_EvaluateScript or similar APIs.
+        if (JS_IsGlobalFrame(cx, fp))
+            break;
     } while ((fp = JS_FrameIterator(cx, &fp)) != nsnull);
 
     if (!previousPrincipal)
     {
         // No principals on the stack, all native code.  Allow
         // execution if the subject principal is the system principal.
 
         return SubjectPrincipalIsSystem(result);
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -45,16 +45,19 @@ target          = @target@
 ac_configure_args = @ac_configure_args@
 BUILD_MODULES	= @BUILD_MODULES@
 MOZILLA_VERSION = @MOZILLA_VERSION@
 FIREFOX_VERSION	= @FIREFOX_VERSION@
 
 MOZ_BUILD_APP = @MOZ_BUILD_APP@
 MOZ_APP_NAME	= @MOZ_APP_NAME@
 MOZ_APP_DISPLAYNAME = @MOZ_APP_DISPLAYNAME@
+MOZ_APP_BASENAME = @MOZ_APP_BASENAME@
+MOZ_APP_VENDOR = @MOZ_APP_VENDOR@
+MOZ_APP_PROFILE = @MOZ_APP_PROFILE@
 MOZ_APP_UA_NAME = @MOZ_APP_UA_NAME@
 MOZ_APP_VERSION = @MOZ_APP_VERSION@
 MOZ_UA_FIREFOX_VERSION = @FIREFOX_VERSION@
 MOZ_UA_BUILDID = @MOZ_UA_BUILDID@
 
 MOZ_PKG_SPECIAL = @MOZ_PKG_SPECIAL@
 
 prefix		= @prefix@
old mode 100755
new mode 100644
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -151,44 +151,44 @@ testxpcsrcdir = $(topsrcdir)/testing/xpc
 # Execute all tests in the $(XPCSHELL_TESTS) directories.
 # See also testsuite-targets.mk 'xpcshell-tests' target for global execution.
 xpcshell-tests:
 	$(PYTHON) -u $(topsrcdir)/config/pythonpath.py \
 	  -I$(topsrcdir)/build \
 	  $(testxpcsrcdir)/runxpcshelltests.py \
 	  --symbols-path=$(DIST)/crashreporter-symbols \
 	  $(EXTRA_TEST_ARGS) \
-	  $(DIST)/bin/xpcshell \
+	  $(LIBXUL_DIST)/bin/xpcshell \
 	  $(foreach dir,$(XPCSHELL_TESTS),$(testxpcobjdir)/$(relativesrcdir)/$(dir))
 
 # Execute a single test, specified in $(SOLO_FILE), but don't automatically
 # start the test. Instead, present the xpcshell prompt so the user can
 # attach a debugger and then start the test.
 check-interactive:
 	$(PYTHON) -u $(topsrcdir)/config/pythonpath.py \
 	  -I$(topsrcdir)/build \
 	  $(testxpcsrcdir)/runxpcshelltests.py \
 	  --symbols-path=$(DIST)/crashreporter-symbols \
 	  --test-path=$(SOLO_FILE) \
 	  --profile-name=$(MOZ_APP_NAME) \
 	  --interactive \
-	  $(DIST)/bin/xpcshell \
+	  $(LIBXUL_DIST)/bin/xpcshell \
 	  $(foreach dir,$(XPCSHELL_TESTS),$(testxpcobjdir)/$(relativesrcdir)/$(dir))
 
 # Execute a single test, specified in $(SOLO_FILE)
 check-one:
 	$(PYTHON) -u $(topsrcdir)/config/pythonpath.py \
 	  -I$(topsrcdir)/build \
 	  $(testxpcsrcdir)/runxpcshelltests.py \
 	  --symbols-path=$(DIST)/crashreporter-symbols \
 	  --test-path=$(SOLO_FILE) \
 	  --profile-name=$(MOZ_APP_NAME) \
 	  --verbose \
 	  $(EXTRA_TEST_ARGS) \
-	  $(DIST)/bin/xpcshell \
+	  $(LIBXUL_DIST)/bin/xpcshell \
 	  $(foreach dir,$(XPCSHELL_TESTS),$(testxpcobjdir)/$(relativesrcdir)/$(dir))
 
 endif # XPCSHELL_TESTS
 
 ifdef CPP_UNIT_TESTS
 
 # Compile the tests to $(DIST)/bin.  Make lots of niceties available by default
 # through TestHarness.h, by modifying the list of includes and the libs against
--- a/configure.in
+++ b/configure.in
@@ -8136,17 +8136,17 @@ if test -n "$ENABLE_SHARED_JS"; then
   MOZ_JS_LIBS=$MOZ_JS_SHARED_LIBS
 else
   MOZ_JS_LIBS=$MOZ_JS_STATIC_LIBS
   AC_DEFINE(MOZ_STATIC_JS)
 fi
 AC_SUBST(JS_SHARED_LIBRARY)
 
 if test -n "$MOZ_STATIC_BUILD_UNSUPPORTED" -a -n "$BUILD_STATIC_LIBS"; then
-  AC_MSG_ERROR([--enable-static is not supported for building $MOZ_APP_NAME.])
+  AC_MSG_ERROR([--enable-static is not supported for building $MOZ_BUILD_APP.])
 fi
 
 if test -n "$MOZ_ENABLE_LIBXUL" -a -n "$BUILD_STATIC_LIBS"; then
   AC_MSG_ERROR([--enable-libxul is not compatible with --enable-static])
 fi
 
 AC_SUBST(LIBXUL_LIBS)
 XPCOM_LIBS="$LIBXUL_LIBS"
@@ -8839,18 +8839,43 @@ AC_SUBST(USE_DEPENDENT_LIBS)
 
 AC_SUBST(MOZ_BUILD_ROOT)
 AC_SUBST(MOZ_OS2_TOOLS)
 
 AC_SUBST(MOZ_POST_DSO_LIB_COMMAND)
 AC_SUBST(MOZ_POST_PROGRAM_COMMAND)
 AC_SUBST(MOZ_TIMELINE)
 
+# The following variables are available to branding and application
+# configuration ($BRANDING/configure.sh and $APPLICATION/confvars.sh):
+# - MOZ_APP_VENDOR: Used for application.ini's "Vendor" field, which also
+# impacts profile location and user-visible fields.
+# - MOZ_APP_BASENAME: Typically stays consistent for multiple branded
+# versions of a given application (e.g. Aurora and Firefox both use
+# "Firefox"), but may vary for full rebrandings (e.g. Iceweasel). Used
+# for application.ini's "Name" field, which controls profile location in
+# the absence of a "Profile" field (see below), and various system
+# integration hooks (Unix remoting, Windows MessageWindow name, etc.)
+# - MOZ_APP_DISPLAYNAME: Used in user-visible fields (DLL properties,
+# Mac Bundle name, Updater, Installer), it is typically used for nightly
+# builds (e.g. Aurora for Firefox).
+# - MOZ_APP_NAME: Used for e.g. the binary program file name. If not set,
+# defaults to a lowercase form of MOZ_APP_BASENAME.
+# - MOZ_APP_PROFILE: When set, used for application.ini's
+# "Profile" field, which controls profile location.
+
+if test -z "$MOZ_APP_NAME"; then
+   MOZ_APP_NAME=`echo $MOZ_APP_BASENAME | tr A-Z a-z`
+fi
+
 AC_SUBST(MOZ_APP_NAME)
 AC_SUBST(MOZ_APP_DISPLAYNAME)
+AC_SUBST(MOZ_APP_BASENAME)
+AC_SUBST(MOZ_APP_VENDOR)
+AC_SUBST(MOZ_APP_PROFILE)
 AC_DEFINE_UNQUOTED(MOZ_APP_UA_NAME, "$MOZ_APP_UA_NAME")
 AC_SUBST(MOZ_APP_UA_NAME)
 AC_DEFINE_UNQUOTED(MOZ_APP_UA_VERSION, "$MOZ_APP_VERSION")
 AC_SUBST(MOZ_APP_VERSION)
 AC_DEFINE_UNQUOTED(MOZ_UA_FIREFOX_VERSION, "$FIREFOX_VERSION")
 AC_SUBST(MOZ_UA_FIREFOX_VERSION)
 AC_SUBST(FIREFOX_VERSION)
 AC_DEFINE_UNQUOTED(MOZ_UA_BUILDID, "$MOZ_UA_BUILDID")
--- a/content/base/src/nsContentSink.cpp
+++ b/content/base/src/nsContentSink.cpp
@@ -701,30 +701,32 @@ nsContentSink::ProcessLinkHeader(nsICont
           }
         }
       }
     }
 
     if (endCh == kCommaCh) {
       // hit a comma, process what we've got so far
 
+      href.Trim(" \t\n\r\f"); // trim HTML5 whitespace
       if (!href.IsEmpty() && !rel.IsEmpty()) {
         rv = ProcessLink(aElement, href, rel, title, type, media);
       }
 
       href.Truncate();
       rel.Truncate();
       title.Truncate();
       type.Truncate();
       media.Truncate();
     }
 
     start = ++end;
   }
 
+  href.Trim(" \t\n\r\f"); // trim HTML5 whitespace
   if (!href.IsEmpty() && !rel.IsEmpty()) {
     rv = ProcessLink(aElement, href, rel, title, type, media);
   }
 
   return rv;
 }
 
 
--- a/content/base/src/nsContentSink.h
+++ b/content/base/src/nsContentSink.h
@@ -249,16 +249,18 @@ protected:
                                        nsIURI **aManifestURI,
                                        CacheSelectionAction *aAction);
 
 public:
   // Searches for the offline cache manifest attribute and calls one
   // of the above defined methods to select the document's application
   // cache, let it be associated with the document and eventually
   // schedule the cache update process.
+  // This method MUST be called with the empty string as the argument
+  // when there is no manifest attribute!
   void ProcessOfflineManifest(const nsAString& aManifestSpec);
 
   // Extracts the manifest attribute from the element if it is the root 
   // element and calls the above method.
   void ProcessOfflineManifest(nsIContent *aElement);
 
 protected:
   // Tries to scroll to the URI's named anchor. Once we've successfully
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -2714,38 +2714,26 @@ nsDocument::GetReferrer(nsAString& aRefe
 
 NS_IMETHODIMP
 nsDocument::GetActiveElement(nsIDOMElement **aElement)
 {
   *aElement = nsnull;
 
   // Get the focused element.
   nsCOMPtr<nsPIDOMWindow> window = GetWindow();
-  if (!window) {
-    return NS_ERROR_NOT_AVAILABLE;
-  }
-
-  nsIFocusManager* fm = nsFocusManager::GetFocusManager();
-  if (!fm)
-    return NS_ERROR_NOT_AVAILABLE;
-
-  nsCOMPtr<nsPIDOMWindow> focusedWindow;
-  nsIContent* focusedContent =
-    nsFocusManager::GetFocusedDescendant(window, PR_FALSE, getter_AddRefs(focusedWindow));
-
-  // an element in this document is focused, so return it
-  if (focusedContent) {
+  if (window) {
+    nsCOMPtr<nsPIDOMWindow> focusedWindow;
+    nsIContent* focusedContent =
+      nsFocusManager::GetFocusedDescendant(window, PR_FALSE,
+                                           getter_AddRefs(focusedWindow));
     // be safe and make sure the element is from this document
-    if (focusedContent->GetOwnerDoc() != this) {
-      NS_WARNING("Focused element found from another document");
-      return NS_ERROR_FAILURE;
-    }
-
-    CallQueryInterface(focusedContent, aElement);
-    return NS_OK;
+    if (focusedContent && focusedContent->GetOwnerDoc() == this) {
+      CallQueryInterface(focusedContent, aElement);
+      return NS_OK;
+    }
   }
 
   // No focused element anywhere in this document.  Try to get the BODY.
   nsCOMPtr<nsIDOMHTMLDocument> htmlDoc =
     do_QueryInterface(static_cast<nsIDocument*>(this));
   if (htmlDoc) {
     nsCOMPtr<nsIDOMHTMLElement> bodyElement;
     htmlDoc->GetBody(getter_AddRefs(bodyElement));
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -857,16 +857,41 @@ nsFrameLoader::Show(PRInt32 marginWidth,
   if (mHideCalled) {
     mHideCalled = PR_FALSE;
     Hide();
     return PR_FALSE;
   }
   return PR_TRUE;
 }
 
+void
+nsFrameLoader::MarginsChanged(PRUint32 aMarginWidth,
+                              PRUint32 aMarginHeight)
+{
+  // We assume that the margins are always zero for remote frames.
+  if (mRemoteFrame)
+    return;
+
+  // If there's no docshell, we're probably not up and running yet.
+  // nsFrameLoader::Show() will take care of setting the right
+  // margins.
+  if (!mDocShell)
+    return;
+
+  // Set the margins
+  mDocShell->SetMarginWidth(aMarginWidth);
+  mDocShell->SetMarginHeight(aMarginHeight);
+
+  // Trigger a restyle if there's a prescontext
+  nsRefPtr<nsPresContext> presContext;
+  mDocShell->GetPresContext(getter_AddRefs(presContext));
+  if (presContext)
+    presContext->RebuildAllStyleData(nsChangeHint(0));
+}
+
 bool
 nsFrameLoader::ShowRemoteFrame(const nsIntSize& size)
 {
   NS_ASSERTION(mRemoteFrame, "ShowRemote only makes sense on remote frames.");
 
   if (!mRemoteBrowser) {
     TryRemoteBrowser();
 
--- a/content/base/src/nsFrameLoader.h
+++ b/content/base/src/nsFrameLoader.h
@@ -203,16 +203,21 @@ public:
    * Called from the layout frame associated with this frame loader;
    * this notifies us to hook up with the widget and view.
    */
   PRBool Show(PRInt32 marginWidth, PRInt32 marginHeight,
               PRInt32 scrollbarPrefX, PRInt32 scrollbarPrefY,
               nsSubDocumentFrame* frame);
 
   /**
+   * Called when the margin properties of the containing frame are changed.
+   */
+  void MarginsChanged(PRUint32 aMarginWidth, PRUint32 aMarginHeight);
+
+  /**
    * Called from the layout frame associated with this frame loader, when
    * the frame is being torn down; this notifies us that out widget and view
    * are going away and we should unhook from them.
    */
   void Hide();
 
   nsresult CloneForStatic(nsIFrameLoader* aOriginal);
 
--- a/content/base/src/nsFrameMessageManager.cpp
+++ b/content/base/src/nsFrameMessageManager.cpp
@@ -44,16 +44,18 @@
 #include "jsapi.h"
 #include "jsarray.h"
 #include "jsinterp.h"
 #include "nsJSUtils.h"
 #include "nsNetUtil.h"
 #include "nsScriptLoader.h"
 #include "nsIJSContextStack.h"
 #include "nsIXULRuntime.h"
+#include "nsIScriptError.h"
+#include "nsIConsoleService.h"
 
 static PRBool
 IsChromeProcess()
 {
   nsCOMPtr<nsIXULRuntime> rt = do_GetService("@mozilla.org/xre/runtime;1");
   if (!rt)
     return PR_TRUE;
 
@@ -438,17 +440,18 @@ nsFrameMessageManager::ReceiveMessage(ns
         argv.set(OBJECT_TO_JSVAL(param));
 
         {
           JSAutoEnterCompartment tac;
 
           JSObject* thisObject = JSVAL_TO_OBJECT(thisValue);
 
           if (!tac.enter(ctx, thisObject) ||
-              !JS_WrapValue(ctx, argv.jsval_addr()))
+              !JS_WrapValue(ctx, argv.jsval_addr()) ||
+              !JS_WrapValue(ctx, &funval))
             return NS_ERROR_UNEXPECTED;
 
           JS_CallFunctionValue(ctx, thisObject,
                                funval, 1, argv.jsval_addr(), &rval);
           if (aJSONRetVal) {
             nsString json;
             if (JS_TryJSON(ctx, &rval) &&
                 JS_Stringify(ctx, &rval, nsnull, JSVAL_NULL,
@@ -527,16 +530,63 @@ NS_NewGlobalMessageManager(nsIChromeFram
                                                         nsnull,
                                                         nsnull,
                                                         nsnull,
                                                         PR_TRUE);
   NS_ENSURE_TRUE(mm, NS_ERROR_OUT_OF_MEMORY);
   return CallQueryInterface(mm, aResult);
 }
 
+void
+ContentScriptErrorReporter(JSContext* aCx,
+                           const char* aMessage,
+                           JSErrorReport* aReport)
+{
+  nsresult rv;
+  nsCOMPtr<nsIScriptError> scriptError =
+      do_CreateInstance(NS_SCRIPTERROR_CONTRACTID, &rv);
+  if (NS_FAILED(rv)) {
+    return;
+  }
+  nsAutoString message, filename, line;
+  PRUint32 lineNumber, columnNumber, flags, errorNumber;
+
+  if (aReport) {
+    if (aReport->ucmessage) {
+      message.Assign(reinterpret_cast<const PRUnichar*>(aReport->ucmessage));
+    }
+    filename.AssignWithConversion(aReport->filename);
+    line.Assign(reinterpret_cast<const PRUnichar*>(aReport->uclinebuf));
+    lineNumber = aReport->lineno;
+    columnNumber = aReport->uctokenptr - aReport->uclinebuf;
+    flags = aReport->flags;
+    errorNumber = aReport->errorNumber;
+  } else {
+    lineNumber = columnNumber = errorNumber = 0;
+    flags = nsIScriptError::errorFlag | nsIScriptError::exceptionFlag;
+  }
+
+  if (message.IsEmpty()) {
+    message.AssignWithConversion(aMessage);
+  }
+
+  rv = scriptError->Init(message.get(), filename.get(), line.get(),
+                         lineNumber, columnNumber, flags,
+                         "Message manager content script");
+  if (NS_FAILED(rv)) {
+    return;
+  }
+
+  nsCOMPtr<nsIConsoleService> consoleService =
+      do_GetService(NS_CONSOLESERVICE_CONTRACTID);
+  if (consoleService) {
+    (void) consoleService->LogMessage(scriptError);
+  }
+}
+
 nsDataHashtable<nsStringHashKey, nsFrameScriptExecutorJSObjectHolder*>*
   nsFrameScriptExecutor::sCachedScripts = nsnull;
 nsRefPtr<nsScriptCacheCleaner> nsFrameScriptExecutor::sScriptCacheCleaner;
 
 void
 nsFrameScriptExecutor::DidCreateCx()
 {
   NS_ASSERTION(mCx, "Should have mCx!");
@@ -610,17 +660,17 @@ nsFrameScriptExecutor::LoadFrameScriptIn
     nsContentUtils::ThreadJSContextStack()->Push(mCx);
     {
       // Need to scope JSAutoRequest to happen after Push but before Pop,
       // at least for now. See bug 584673.
       JSAutoRequest ar(mCx);
       JSObject* global = nsnull;
       mGlobal->GetJSObject(&global);
       if (global) {
-        JS_ExecuteScript(mCx, global, holder->mObject, nsnull);
+        (void) JS_ExecuteScript(mCx, global, holder->mObject, nsnull);
       }
     }
     JSContext* unused;
     nsContentUtils::ThreadJSContextStack()->Pop(&unused);
     return;
   }
 
   nsCString url = NS_ConvertUTF16toUTF8(aURL);
@@ -678,17 +728,17 @@ nsFrameScriptExecutor::LoadFrameScriptIn
           if (!scheme.EqualsLiteral("data")) {
             nsFrameScriptExecutorJSObjectHolder* holder =
               new nsFrameScriptExecutorJSObjectHolder(scriptObj);
             // Root the object also for caching.
             JS_AddNamedObjectRoot(mCx, &(holder->mObject),
                                   "Cached message manager script");
             sCachedScripts->Put(aURL, holder);
           }
-          JS_ExecuteScript(mCx, global, scriptObj, nsnull);
+          (void) JS_ExecuteScript(mCx, global, scriptObj, nsnull);
         }
         //XXX Argh, JSPrincipals are manually refcounted!
         JSPRINCIPALS_DROP(mCx, jsprin);
       }
     } 
     JSContext* unused;
     nsContentUtils::ThreadJSContextStack()->Pop(&unused);
   }
--- a/content/base/src/nsFrameMessageManager.h
+++ b/content/base/src/nsFrameMessageManager.h
@@ -175,16 +175,21 @@ protected:
   void* mCallbackData;
   JSContext* mContext;
   nsTArray<nsString> mPendingScripts;
 public:
   static nsFrameMessageManager* sParentProcessManager;
   static nsFrameMessageManager* sChildProcessManager;
 };
 
+void
+ContentScriptErrorReporter(JSContext* aCx,
+                           const char* aMessage,
+                           JSErrorReport* aReport);
+
 class nsScriptCacheCleaner;
 
 struct nsFrameScriptExecutorJSObjectHolder
 {
   nsFrameScriptExecutorJSObjectHolder(JSObject* aObject) : mObject(aObject)
   { MOZ_COUNT_CTOR(nsFrameScriptExecutorJSObjectHolder); }
   ~nsFrameScriptExecutorJSObjectHolder()
   { MOZ_COUNT_DTOR(nsFrameScriptExecutorJSObjectHolder); }
--- a/content/base/src/nsInProcessTabChildGlobal.cpp
+++ b/content/base/src/nsInProcessTabChildGlobal.cpp
@@ -294,16 +294,17 @@ nsInProcessTabChildGlobal::InitTabChildG
   nsContentUtils::XPConnect()->SetSecurityManagerForJSContext(cx, nsContentUtils::GetSecurityManager(), 0);
   nsContentUtils::GetSecurityManager()->GetSystemPrincipal(getter_AddRefs(mPrincipal));
 
   JS_SetNativeStackQuota(cx, 128 * sizeof(size_t) * 1024);
   JS_SetScriptStackQuota(cx, 25 * sizeof(size_t) * 1024 * 1024);
 
   JS_SetOptions(cx, JS_GetOptions(cx) | JSOPTION_JIT | JSOPTION_ANONFUNFIX | JSOPTION_PRIVATE_IS_NSISUPPORTS);
   JS_SetVersion(cx, JSVERSION_LATEST);
+  JS_SetErrorReporter(cx, ContentScriptErrorReporter);
 
   xpc_LocalizeContext(cx);
 
   JSAutoRequest ar(cx);
   nsIXPConnect* xpc = nsContentUtils::XPConnect();
   const PRUint32 flags = nsIXPConnect::INIT_JS_STANDARD_CLASSES |
                          /*nsIXPConnect::OMIT_COMPONENTS_OBJECT ?  |*/
                          nsIXPConnect::FLAG_SYSTEM_GLOBAL_OBJECT;
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -472,16 +472,20 @@ include $(topsrcdir)/config/rules.mk
 		test_bug631615.html \
 		test_bug558431.html \
 		file_bug558431.html \
 		file_bug558431.html^headers^ \
 		test_bug604592.html \
 		test_bug628938.html \
 		test_bug626262.html \
 		test_plugin_freezing.html \
+		test_bug638112.html \
+		bug638112-response.txt \
+		bug638112.sjs \
+		test_bug656283.html \
 		$(NULL)
 
 # This test fails on the Mac for some reason
 ifneq (,$(filter gtk2 windows,$(MOZ_WIDGET_TOOLKIT)))
 _TEST_FILES2 += 	test_copyimage.html \
 		$(NULL)
 endif
 
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..9ce788da792d9a02133cb7b2bb857152469c5ace
GIT binary patch
literal 247
zc$`I!T?)c55QGI^B#<+>2e4}D4;b*FsHmtQ7<><PZ3A{w>Q>Y%cv5d+6{Pbx%r`SD
zWA;7ORS@<Eu%@#wGRw{r94uXfsAOL_eoHa8j2cW@cAyIGY*7J9fg0*?tW^lhosr^b
zi-(3Njxpz8L9stMN~D;1Vx-#9kUU*p`&*=hQ(ZMmu|dp(=;ChG8oLaA$<t8>GJBtn
lC*hAFjK2>x)Y-brJn}DzckZQ}U8Inr{c1ISYBn2xeE{I$N9F(k
new file mode 100644
--- /dev/null
+++ b/content/base/test/bug638112.sjs
@@ -0,0 +1,26 @@
+function getInputStream(path)
+{
+  var file = Components.classes["@mozilla.org/file/directory_service;1"].
+                        getService(Components.interfaces.nsIProperties).
+                        get("CurWorkD", Components.interfaces.nsILocalFile);
+  var fis  = Components.classes['@mozilla.org/network/file-input-stream;1'].
+                        createInstance(Components.interfaces.nsIFileInputStream);
+  var split = path.split("/");
+  for(var i = 0; i < split.length; ++i) {
+    file.append(split[i]);
+  }
+  fis.init(file, -1, -1, false);
+  return fis;
+}
+
+
+
+function handleRequest(request, response)
+{
+  var inputStream = getInputStream("tests/content/base/test/bug638112-response.txt")
+  response.seizePower();
+  response.bodyOutputStream.writeFrom(inputStream,
+                                      inputStream.available());
+  response.finish();
+  inputStream.close();
+}
--- a/content/base/test/test_bug503473.html
+++ b/content/base/test/test_bug503473.html
@@ -12,32 +12,23 @@ https://bugzilla.mozilla.org/show_bug.cg
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=503473">Mozilla Bug 503473</a>
 <p id="display"></p>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 503473 **/
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-          .getService(Components.interfaces.nsIPrefBranch);
-var gOriginalHtml5Pref = prefs.getBoolPref("html5.parser.enable");
-prefs.setBoolPref("html5.parser.enable", true);
-
 SimpleTest.waitForExplicitFinish();
 
 function done() {
   var iframe = document.getElementById("iframe");
   var divs = iframe.contentWindow.document.getElementsByTagName("div").length;
   is(divs, 0, "Div wasn't blown away.")
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  prefs.setBoolPref("html5.parser.enable", gOriginalHtml5Pref);
-
   SimpleTest.finish();
 }
 
 </script>
 </pre>
 <div id="content" style="display: none">
   <iframe id='iframe' src="file_bug503473-frame.sjs">
   </iframe>
--- a/content/base/test/test_bug527896.html
+++ b/content/base/test/test_bug527896.html
@@ -15,22 +15,16 @@ https://bugzilla.mozilla.org/show_bug.cg
 <div id="content" style="display: none">
   <iframe></iframe>
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 527896 **/
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-          .getService(Components.interfaces.nsIPrefBranch);
-var gOriginalHtml5Pref = prefs.getBoolPref("html5.parser.enable");
-prefs.setBoolPref("html5.parser.enable", true);
-
 SimpleTest.waitForExplicitFinish();
 
 var docWrittenSrcExecuted = false;
 var scriptInsertedSrcExecuted = false;
 
 // the iframe test runs with the HTML5 parser
 
 var iframe = document.getElementsByTagName('iframe')[0];
@@ -53,20 +47,15 @@ div.appendChild(script); // this shouldn
 script.setAttribute("src", "data:text/javascript,scriptInsertedSrcExecuted = true;");
 
 todo(false, "Add SVG tests after bug 528442.");
 
 function done() {
   ok(docWrittenSrcExecuted, "document.written src didn't execute");
   ok(scriptInsertedSrcExecuted, "script-inserted src didn't execute");
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-            .getService(Components.interfaces.nsIPrefBranch);
-  prefs.setBoolPref("html5.parser.enable", gOriginalHtml5Pref);
-
   SimpleTest.finish();
 }
 
 </script>
 </pre>
 </body>
 </html>
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_bug638112.html
@@ -0,0 +1,41 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=638112
+-->
+<head>
+  <title>Test for Bug 638112</title>
+  <script type="text/javascript" src="/MochiKit/packed.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=638112">Mozilla Bug 638112</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+</div>
+<pre id="test">
+<script type="text/javascript">
+
+/** Test for Bug 638112 **/
+
+function run_test() {
+  var req = new XMLHttpRequest();
+  req.open("GET", "bug638112.sjs", false);
+  req.send(null);
+  var statusText = req.statusText;
+
+  is(statusText, "Information Sans-Autorit", "");
+
+  SimpleTest.finish();
+}
+
+
+SimpleTest.waitForExplicitFinish();
+
+addLoadEvent(run_test);
+
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_bug656283.html
@@ -0,0 +1,60 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=656283
+-->
+<head>
+  <title>Test for Bug 656283</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body onload="test()">
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=656283">Mozilla Bug 656283</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 656283 **/
+
+SimpleTest.waitForExplicitFinish();
+
+var ifr;
+function test() {
+  // First a test with data documents.
+  var d = document.implementation.createHTMLDocument("");
+  is(d.activeElement, d.body, "Active element should be body by default! (1)");
+ 
+
+  ifr = document.getElementById("ifr");
+  ifr.onload = test2;
+  ifr.src = "data:text/html,1";
+}
+
+var firstDoc;
+function test2() {
+  firstDoc = ifr.contentDocument;
+  is(firstDoc.activeElement, firstDoc.body,
+     "Active element should be body by default! (2)");
+  ifr.onload = test3;
+  ifr.src = "data:text/html,<input>";
+}
+
+function test3() {
+  ifr.contentDocument.getElementsByTagName("input")[0].focus();
+  is(firstDoc.activeElement, firstDoc.body,
+     "Active element should be body by default! (3)");
+  ifr.parentNode.removeChild(ifr);
+  is(firstDoc.activeElement, firstDoc.body,
+     "Active element should be body by default! (4)");
+  SimpleTest.finish();
+}
+
+</script>
+</pre>
+<iframe id="ifr"></irame>
+</body>
+</html>
--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
@@ -167,18 +167,21 @@ static PRBool FloatValidate (double f1, 
 /* Memory reporter stuff */
 static nsIMemoryReporter *gCanvasMemoryReporter = nsnull;
 static PRInt64 gCanvasMemoryUsed = 0;
 
 static PRInt64 GetCanvasMemoryUsed(void *) {
     return gCanvasMemoryUsed;
 }
 
+// This isn't "heap-used/content/canvas/2d-pixel-bytes" because the pixels of a
+// canvas may not be stored on the heap. And if they are, they will be tracked
+// by the underlying surface implementations.  See bug 655638 for details.
 NS_MEMORY_REPORTER_IMPLEMENT(CanvasMemory,
-                             "heap-used/content/canvas/2d-pixel-bytes",
+                             "canvas-2d-pixel-bytes",
                              "Memory used by 2D canvases. Each canvas "
                              "requires (width * height * 4) bytes.",
                              GetCanvasMemoryUsed,
                              NULL)
 
 static void
 CopyContext(gfxContext* dest, gfxContext* src)
 {
--- a/content/events/public/nsIPrivateDOMEvent.h
+++ b/content/events/public/nsIPrivateDOMEvent.h
@@ -139,9 +139,11 @@ nsresult
 NS_NewDOMAnimationEvent(nsIDOMEvent** aInstancePtrResult, nsPresContext* aPresContext, class nsAnimationEvent* aEvent);
 #endif
 nsresult
 NS_NewDOMCloseEvent(nsIDOMEvent** aInstancePtrResult, nsPresContext* aPresContext, class nsEvent* aEvent);
 nsresult
 NS_NewDOMMozTouchEvent(nsIDOMEvent** aInstancePtrResult, nsPresContext* aPresContext, class nsMozTouchEvent* aEvent);
 nsresult
 NS_NewDOMTouchEvent(nsIDOMEvent** aInstancePtrResult, nsPresContext* aPresContext, class nsInputEvent *aEvent);
+nsresult
+NS_NewDOMCustomEvent(nsIDOMEvent** aInstancePtrResult, nsPresContext* aPresContext, nsEvent* aEvent);
 #endif // nsIPrivateDOMEvent_h__
--- a/content/events/src/Makefile.in
+++ b/content/events/src/Makefile.in
@@ -87,16 +87,17 @@ CPPSRCS		= \
 		nsDOMMozTouchEvent.cpp \
 		nsDOMEventTargetHelper.cpp \
 		nsDOMScrollAreaEvent.cpp \
 		nsDOMTransitionEvent.cpp \
 		nsDOMPopStateEvent.cpp \
 		nsDOMHashChangeEvent.cpp \
 		nsDOMCloseEvent.cpp \
 		nsDOMTouchEvent.cpp \
+		nsDOMCustomEvent.cpp \
 		$(NULL)
 
 ifdef MOZ_CSS_ANIMATIONS
 CPPSRCS		+= nsDOMAnimationEvent.cpp 
 endif
 
 # we don't want the shared lib, but we want to force the creation of a static lib.
 FORCE_STATIC_LIB = 1
new file mode 100644
--- /dev/null
+++ b/content/events/src/nsDOMCustomEvent.cpp
@@ -0,0 +1,88 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is the Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Olli Pettay <Olli.Pettay@helsinki.fi> (Original Author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of the GNU General Public License Version 2 or later (the "GPL"),
+ * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "nsDOMCustomEvent.h"
+#include "nsContentUtils.h"
+
+NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMCustomEvent)
+
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsDOMCustomEvent, nsDOMEvent)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDetail)
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsDOMCustomEvent, nsDOMEvent)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mDetail)
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+DOMCI_DATA(CustomEvent, nsDOMCustomEvent)
+
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsDOMCustomEvent)
+  NS_INTERFACE_MAP_ENTRY(nsIDOMCustomEvent)
+  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(CustomEvent)
+NS_INTERFACE_MAP_END_INHERITING(nsDOMEvent)
+
+NS_IMPL_ADDREF_INHERITED(nsDOMCustomEvent, nsDOMEvent)
+NS_IMPL_RELEASE_INHERITED(nsDOMCustomEvent, nsDOMEvent)
+
+NS_IMETHODIMP
+nsDOMCustomEvent::GetDetail(nsIVariant** aDetail)
+{
+  NS_IF_ADDREF(*aDetail = mDetail);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsDOMCustomEvent::InitCustomEvent(const nsAString& aType,
+                                  PRBool aCanBubble,
+                                  PRBool aCancelable,
+                                  nsIVariant* aDetail)
+{
+  nsresult rv = nsDOMEvent::InitEvent(aType, aCanBubble, aCancelable);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  mDetail = aDetail;
+  return NS_OK;
+}
+
+nsresult
+NS_NewDOMCustomEvent(nsIDOMEvent** aInstancePtrResult,
+                     nsPresContext* aPresContext,
+                     nsEvent* aEvent) 
+{
+  nsDOMCustomEvent* e = new nsDOMCustomEvent(aPresContext, aEvent);
+  return CallQueryInterface(e, aInstancePtrResult);
+}
new file mode 100644
--- /dev/null
+++ b/content/events/src/nsDOMCustomEvent.h
@@ -0,0 +1,66 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License
+ * Version 1.1 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is the Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Olli Pettay <Olli.Pettay@helsinki.fi> (Original Author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef nsDOMCustomEvent_h__
+#define nsDOMCustomEvent_h__
+
+#include "nsIDOMCustomEvent.h"
+#include "nsDOMEvent.h"
+#include "nsCycleCollectionParticipant.h"
+
+class nsDOMCustomEvent : public nsDOMEvent,
+                         public nsIDOMCustomEvent
+{
+public:
+  nsDOMCustomEvent(nsPresContext* aPresContext, nsEvent* aEvent)
+    : nsDOMEvent(aPresContext, aEvent)
+  {
+  }
+                     
+  NS_DECL_ISUPPORTS_INHERITED
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsDOMCustomEvent, nsDOMEvent)
+
+  NS_DECL_NSIDOMCUSTOMEVENT
+
+  // Forward to base class
+  NS_FORWARD_TO_NSDOMEVENT
+
+private:
+  nsCOMPtr<nsIVariant> mDetail;
+};
+
+#endif // nsDOMCustomEvent_h__
--- a/content/events/src/nsEventDispatcher.cpp
+++ b/content/events/src/nsEventDispatcher.cpp
@@ -873,11 +873,13 @@ nsEventDispatcher::CreateEvent(nsPresCon
     return NS_NewDOMAudioAvailableEvent(aDOMEvent, aPresContext, nsnull);
   if (aEventType.LowerCaseEqualsLiteral("closeevent"))
     return NS_NewDOMCloseEvent(aDOMEvent, aPresContext, nsnull);
   if (aEventType.LowerCaseEqualsLiteral("touchevent") &&
       nsDOMTouchEvent::PrefEnabled())
     return NS_NewDOMTouchEvent(aDOMEvent, aPresContext, nsnull);
   if (aEventType.LowerCaseEqualsLiteral("hashchangeevent"))
     return NS_NewDOMHashChangeEvent(aDOMEvent, aPresContext, nsnull);
+  if (aEventType.LowerCaseEqualsLiteral("customevent"))
+    return NS_NewDOMCustomEvent(aDOMEvent, aPresContext, nsnull);
 
   return NS_ERROR_DOM_NOT_SUPPORTED_ERR;
 }
--- a/content/events/test/Makefile.in
+++ b/content/events/test/Makefile.in
@@ -67,16 +67,17 @@ include $(topsrcdir)/config/rules.mk
 		test_bug368835.html \
 		test_bug379120.html \
 		test_bug391568.xhtml \
 		test_bug402089.html \
 		test_bug405632.html \
 		test_bug409604.html \
 		test_bug412567.html \
 		test_bug426082.html \
+		test_bug427537.html \
 		test_bug443985.html \
 		test_bug447736.html \
 		test_bug450876.html \
 		test_bug456273.html \
 		test_bug457672.html \
 		test_bug428988.html \
 		bug457672.html \
 		test_draggableprop.html \
new file mode 100644
--- /dev/null
+++ b/content/events/test/test_bug427537.html
@@ -0,0 +1,58 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=427537
+-->
+<head>
+  <title>Test for Bug 427537</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=427537">Mozilla Bug 427537</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 427537 **/
+
+var e = document.createEvent("CustomEvent");
+ok(e, "Should have custom event!");
+
+// Test initCustomEvent and also cycle collection handling by
+// passing reference to the event as 'detail' parameter.
+e.initCustomEvent("foobar", true, true, e);
+
+var didCallListener = false;
+document.addEventListener("foobar",
+  function(evt) {
+    didCallListener = true;
+    is(evt.type, "foobar", "Should get 'foobar' event!");
+    is(evt.detail, evt, ".detail should point to the event itself.");
+    ok(e.bubbles, "Event should bubble!");
+    ok(e.cancelable, "Event should be cancelable.");
+  }, true);
+
+document.dispatchEvent(e);
+ok(didCallListener, "Should have called listener!");
+
+e = document.createEvent("CustomEvent");
+e.initCustomEvent("foobar", true, true, 1);
+is(e.detail, 1, "Detail should be 1.");
+
+e = document.createEvent("CustomEvent");
+e.initCustomEvent("foobar", true, true, "test");
+is(e.detail, "test", "Detail should be 'test'.");
+
+e = document.createEvent("CustomEvent");
+e.initCustomEvent("foobar", true, true, true);
+is(e.detail, true, "Detail should be true.");
+
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/html/content/reftests/649134-1.html
@@ -0,0 +1,31 @@
+<!DOCTYPE HTML>
+<html><head>
+    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+    <title>Testcase for bug </title>
+<link rel="stylesheet" type="text/css" href="" />
+<!--
+        #foo {
+            /* This doesn't get evaluated */
+            color: red;
+        }
+        #ie {
+            border: 5px solid red;
+        }
+        #ie {
+            display: block;
+        }
+        #moz {
+            color: blue;
+            /* display: none; */
+        }
+-->
+
+</head>
+<body>
+
+<p id="foo">foo</p>
+<p id="ie">ie</p>
+<p id="moz">moz</p>
+
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/html/content/reftests/649134-2.html
@@ -0,0 +1,31 @@
+<!DOCTYPE HTML>
+<html><head>
+    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+    <title>Testcase for bug </title>
+<link rel="stylesheet" type="text/css" href=" 	" />
+<!--
+        #foo {
+            /* This doesn't get evaluated */
+            color: red;
+        }
+        #ie {
+            border: 5px solid red;
+        }
+        #ie {
+            display: block;
+        }
+        #moz {
+            color: blue;
+            /* display: none; */
+        }
+-->
+
+</head>
+<body>
+
+<p id="foo">foo</p>
+<p id="ie">ie</p>
+<p id="moz">moz</p>
+
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/html/content/reftests/649134-ref.html
@@ -0,0 +1,13 @@
+<!DOCTYPE HTML>
+<html><head>
+    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+    <title>Testcase for bug </title>
+</head>
+<body>
+
+<p id="foo">foo</p>
+<p id="ie">ie</p>
+<p id="moz">moz</p>
+
+</body>
+</html>
--- a/content/html/content/reftests/reftest.list
+++ b/content/html/content/reftests/reftest.list
@@ -16,16 +16,19 @@ include autofocus/reftest.list
 == 560059-video-dimensions.html 560059-video-dimensions-ref.html
 == 573322-quirks.html 573322-quirks-ref.html
 == 573322-no-quirks.html 573322-no-quirks-ref.html
 == 596455-1a.html 596455-ref-1.html
 == 596455-1b.html 596455-ref-1.html
 == 596455-2a.html 596455-ref-2.html
 == 596455-2b.html 596455-ref-2.html
 == 610935.html 610935-ref.html
+== 649134-1.html 649134-ref.html
+== 649134-2.html 649134-ref.html
+
 == hidden-1a.html hidden-1-ref.html
 == hidden-1b.html hidden-1-ref.html
 == hidden-1c.html hidden-1-ref.html
 == hidden-1d.html hidden-1-ref.html
 == hidden-1e.html hidden-1-ref.html
 == hidden-1f.html hidden-1-ref.html
 == hidden-1g.html hidden-1-ref.html
 == hidden-2.svg hidden-2-ref.svg
--- a/content/html/content/src/nsHTMLLinkElement.cpp
+++ b/content/html/content/src/nsHTMLLinkElement.cpp
@@ -384,16 +384,22 @@ nsHTMLLinkElement::GetHrefURI() const
 {
   return GetHrefURIForAnchors();
 }
 
 already_AddRefed<nsIURI>
 nsHTMLLinkElement::GetStyleSheetURL(PRBool* aIsInline)
 {
   *aIsInline = PR_FALSE;
+  nsAutoString href;
+  GetAttr(kNameSpaceID_None, nsGkAtoms::href, href);
+  href.Trim(" \t\n\r\f"); // trim HTML5 whitespace
+  if (href.IsEmpty()) {
+    return nsnull;
+  }
   return Link::GetURI();
 }
 
 void
 nsHTMLLinkElement::GetStyleSheetInfo(nsAString& aTitle,
                                      nsAString& aType,
                                      nsAString& aMedia,
                                      PRBool* aIsAlternate)
--- a/content/html/content/src/nsHTMLMediaElement.cpp
+++ b/content/html/content/src/nsHTMLMediaElement.cpp
@@ -1950,17 +1950,19 @@ void nsHTMLMediaElement::MetadataLoaded(
   mRate = aRate;
   ChangeReadyState(nsIDOMHTMLMediaElement::HAVE_METADATA);
   DispatchAsyncEvent(NS_LITERAL_STRING("durationchange"));
   DispatchAsyncEvent(NS_LITERAL_STRING("loadedmetadata"));
 }
 
 void nsHTMLMediaElement::FirstFrameLoaded(PRBool aResourceFullyLoaded)
 {
-  ChangeReadyState(nsIDOMHTMLMediaElement::HAVE_CURRENT_DATA);
+  ChangeReadyState(aResourceFullyLoaded ?
+    nsIDOMHTMLMediaElement::HAVE_ENOUGH_DATA :
+    nsIDOMHTMLMediaElement::HAVE_CURRENT_DATA);
   ChangeDelayLoadStatus(PR_FALSE);
 
   NS_ASSERTION(!mSuspendedAfterFirstFrame, "Should not have already suspended");
 
   if (mDecoder && mAllowSuspendAfterFirstFrame && mPaused &&
       !aResourceFullyLoaded &&
       !HasAttr(kNameSpaceID_None, nsGkAtoms::autoplay) &&
       mPreloadAction == nsHTMLMediaElement::PRELOAD_METADATA) {
@@ -2227,16 +2229,19 @@ ImageContainer* nsHTMLMediaElement::GetI
     return nsnull;
 
   nsRefPtr<LayerManager> manager =
     nsContentUtils::PersistentLayerManagerForDocument(GetOwnerDoc());
   if (!manager)
     return nsnull;
 
   mImageContainer = manager->CreateImageContainer();
+  if (manager->IsCompositingCheap()) {
+    mImageContainer->SetDelayedConversion(PR_TRUE);
+  }
   return mImageContainer;
 }
 
 nsresult nsHTMLMediaElement::DispatchAudioAvailableEvent(float* aFrameBuffer,
                                                          PRUint32 aFrameBufferLength,
                                                          float aTime)
 {
   // Auto manage the memory for the frame buffer. If we fail and return
--- a/content/html/content/test/Makefile.in
+++ b/content/html/content/test/Makefile.in
@@ -37,16 +37,27 @@
 
 DEPTH          = ../../../..
 topsrcdir      = @top_srcdir@
 srcdir         = @srcdir@
 VPATH          = @srcdir@
 relativesrcdir = content/html/content/test
 
 include $(DEPTH)/config/autoconf.mk
+
+ifdef ENABLE_TESTS
+# This extra subdirectory is needed due to the nature of this test.
+# With the bug, the test loads the base URL of the bug649134/file_*.sjs
+# files, and the mochitest server responds with the contents of index.html if
+# it exists in that case, which we use to detect failure.
+# We can't have index.html in this directory because it would prevent
+# running the tests here.
+DIRS		+= bug649134
+endif
+
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES = \
 		test_hidden.html \
 		test_bug589.html \
 		test_bug691.html \
 		nnc_lockup.gif \
 		test_bug694.html \
@@ -258,12 +269,13 @@ include $(topsrcdir)/config/rules.mk
 		test_bug636336.html \
 		test_bug630889.html \
 		test_bug610212.html \
 		test_bug633058.html \
 		test_bug641219.html \
 		test_bug643051.html \
 		test_bug583514.html \
 		test_bug514437.html \
+		test_bug649134.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/bug649134/Makefile.in
@@ -0,0 +1,50 @@
+#
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is mozilla.org code.
+#
+# The Initial Developer of the Original Code is
+# Mozilla Foundation.
+# Portions created by the Initial Developer are Copyright (C) 2011
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either of the GNU General Public License Version 2 or later (the "GPL"),
+# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+DEPTH          = ../../../../..
+topsrcdir      = @top_srcdir@
+srcdir         = @srcdir@
+VPATH          = @srcdir@
+relativesrcdir = content/html/content/test/bug649134
+
+include $(DEPTH)/config/autoconf.mk
+include $(topsrcdir)/config/rules.mk
+
+_TEST_FILES = file_bug649134-1.sjs file_bug649134-2.sjs index.html
+
+libs:: $(_TEST_FILES)
+	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/bug649134/file_bug649134-1.sjs
@@ -0,0 +1,12 @@
+function handleRequest(request, response)
+{
+  response.seizePower();
+  var r = 'HTTP/1.1 200 OK\r\n' +
+          'Content-Type: text/html\r\n' +
+          'Link: <		\014>; rel="stylesheet"\r\n' +
+          '\r\n' +
+          '<!-- selector {} body {display:none;} --><body>PASS</body>\r\n';
+  response.bodyOutputStream.write(r, r.length);
+  response.bodyOutputStream.flush();
+  response.finish();
+}
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/bug649134/file_bug649134-2.sjs
@@ -0,0 +1,12 @@
+function handleRequest(request, response)
+{
+  response.seizePower();
+  var r = 'HTTP/1.1 200 OK\r\n' +
+          'Content-Type: text/html\r\n' +
+          'Link: <		\014>; rel="stylesheet",\r\n' +
+          '\r\n' +
+          '<!-- selector {} body {display:none;} --><body>PASS</body>\r\n';
+  response.bodyOutputStream.write(r, r.length);
+  response.bodyOutputStream.flush();
+  response.finish();
+}
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/bug649134/index.html
@@ -0,0 +1,3 @@
+body {
+    display:none;
+}
--- a/content/html/content/test/test_bug389797.html
+++ b/content/html/content/test/test_bug389797.html
@@ -19,20 +19,16 @@ https://bugzilla.mozilla.org/show_bug.cg
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 389797 **/
 var allTags = [];
 var classInfos = {};
 var interfaces = {};
 var interfacesNonClassinfo = {};
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-            .getService(Components.interfaces.nsIPrefBranch);
-
 function getClassName(tag) {
   return "HTML" + classInfos[tag] + "Element";
 }
 
 function HTML_TAG(aTagName, aImplClass) {
   allTags.push(aTagName);
   classInfos[aTagName] = aImplClass;
   interfaces[aTagName] =
@@ -174,24 +170,17 @@ HTML_TAG("iframe", "IFrame", [ "nsIDOMNS
                              [ "nsIFrameLoaderOwner" ]);
 HTML_TAG("image", "Span");
 HTML_TAG("img", "Image", [], [ "imgIDecoderObserver",
                                "nsIImageLoadingContent" ]);
 HTML_TAG("input", "Input", [], [ "imgIDecoderObserver",
                                  "nsIImageLoadingContent",
                                  "nsIDOMNSEditableElement" ]);
 HTML_TAG("ins", "Ins", [ "nsIDOMHTMLModElement" ]);
-
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-if (prefs.getBoolPref("html5.parser.enable")) {
-  HTML_TAG("isindex", ""); // HTMLElement
-} else {
-  HTML_TAG("isindex", "IsIndex");
-}
-
+HTML_TAG("isindex", ""); // HTMLElement
 HTML_TAG("kbd", ""); // HTMLElement
 HTML_TAG("keygen", "Span");
 HTML_TAG("label", "Label");
 HTML_TAG("legend", "Legend");
 HTML_TAG("li", "LI");
 HTML_TAG("link", "Link", [ "nsIDOMLinkStyle" ]);
 HTML_TAG("listing", ""); // HTMLElement
 HTML_TAG("map", "Map");
--- a/content/html/content/test/test_bug555567.html
+++ b/content/html/content/test/test_bug555567.html
@@ -21,30 +21,23 @@ https://bugzilla.mozilla.org/show_bug.cg
   <legend id="c"></legend>
 </div>
 <pre id="test">
 <p id="display"></p>
 <script type="application/javascript">
 
 /** Test for Bug 555567 **/
 
-// This test works only with html5 parser.
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-            .getService(Components.interfaces.nsIPrefBranch);
+var a = document.getElementById('a');
+var b = document.getElementById('b');
+var c = document.getElementById('c');
 
-if (prefs.getBoolPref("html5.parser.enable")) {
-  var a = document.getElementById('a');
-  var b = document.getElementById('b');
-  var c = document.getElementById('c');
-
-  isnot(a.form, null,
-    "First legend element should have a not null form IDL attribute");
-  is(b.form, null,
-    "Second legend element should have a null form IDL attribute");
-  is(c.form, null,
-    "Third legend element should have a null form IDL attribute");
-}
+isnot(a.form, null,
+  "First legend element should have a not null form IDL attribute");
+is(b.form, null,
+  "Second legend element should have a null form IDL attribute");
+is(c.form, null,
+  "Third legend element should have a null form IDL attribute");
 
 </script>
 </pre>
 </body>
 </html>
--- a/content/html/content/test/test_bug562932.html
+++ b/content/html/content/test/test_bug562932.html
@@ -33,23 +33,16 @@ https://bugzilla.mozilla.org/show_bug.cg
   <label id='l13' for=''><input></label>
   <!-- <label id='l14'> is created in script -->
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 562932 **/
 
-// Check if we are using the html5 parser
-// because some tests will fail otherwise.
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-var gHtml5Parser = Components.classes["@mozilla.org/preferences-service;1"]
-                   .getService(Components.interfaces.nsIPrefBranch)
-                   .getBoolPref("html5.parser.enable");
-
 function checkControl(aLabelId, aElementId, aMsg)
 {
   var element = null;
 
   if (aElementId != null) {
     element = document.getElementById(aElementId);
   }
 
@@ -59,26 +52,22 @@ function checkControl(aLabelId, aElement
 ok('control' in document.createElement('label'),
    "label element should have a control IDL attribute");
 
 checkControl('l1', 'i1', "label control should be the first form element");
 checkControl('l2', 'i2', "label control should be the first form element");
 checkControl('l3', null, "label control should be null when there is no child");
 checkControl('l4a', null, "label control should be null when there is no \
              labelable form element child");
-if (gHtml5Parser) {
-  checkControl('l4b', 'i3', "label control should be the first labelable element \
-               in tree order");
-}
+checkControl('l4b', 'i3', "label control should be the first labelable element \
+             in tree order");
 checkControl('l4c', 'i3', "label control should be the first labelable element \
              in tree order");
-if (gHtml5Parser) {
-  checkControl('l4d', 'i3b', "label control should be the first labelable element \
-               in tree order");
-}
+checkControl('l4d', 'i3b', "label control should be the first labelable element \
+             in tree order");
 checkControl('l4e', 'i3b', "label control should be the first labelable element \
              in tree order");
 checkControl('l5', 'i1', "label control should be the id in @for");
 checkControl('l6', null,
              "label control should be null if the id in @for is not valid");
 checkControl('l7', null,
              "label control should be null if the id in @for is not valid");
 checkControl('l8', null,
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug649134.html
@@ -0,0 +1,55 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=649134
+-->
+<head>
+  <title>Test for Bug 649134</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=649134">Mozilla Bug 649134</a>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 649134 **/
+SimpleTest.waitForExplicitFinish();
+
+var calls = 0;
+function finish() {
+  if (++calls == 4)
+    SimpleTest.finish();
+}
+function verifyNoLoad(iframe) {
+  ok(iframe.contentDocument.body.offsetHeight > 0,
+     "HTTP Link stylesheet was ignored " + iframe.src);
+  finish();
+}
+var verifyLoadCalls = 0;
+function verifyLoad(iframe) {
+  if (++verifyLoadCalls == 2) {
+    ok(indexContent == iframe.contentDocument.body.innerHTML,
+       "bug649134/ loads bug649134/index.html " + iframe.src);
+  }
+  finish();
+}
+function indexLoad(iframe) {
+  indexContent = iframe.contentDocument.body.innerHTML;
+  verifyLoad(iframe);
+}
+
+</script>
+</pre>
+<p id="display">
+<!-- Note: the extra sub-directory is needed for the test, see bug 649134 comment 14 -->
+<iframe onload="verifyNoLoad(this);" src="bug649134/file_bug649134-1.sjs"></iframe>
+<iframe onload="verifyNoLoad(this);" src="bug649134/file_bug649134-2.sjs"></iframe>
+<iframe onload="verifyLoad(this);" src="bug649134/"></iframe> <!-- verify that mochitest server loads index.html -->
+<iframe onload="indexLoad(this);" src="bug649134/index.html"></iframe>
+</p>
+</body>
+</html>
--- a/content/html/document/test/Makefile.in
+++ b/content/html/document/test/Makefile.in
@@ -97,17 +97,16 @@ include $(topsrcdir)/config/rules.mk
 		test_bug482659.html \
 		test_bug486741.html \
 		test_bug489532.html \
 		test_bug497242.xhtml \
 		test_bug499092.html \
 		bug499092.xml \
 		bug499092.html \
 		test_bug512367.html \
-		test_bug570376.html \
 		test_bug571981.html \
 		$(NULL)
 
 ifneq (mobile,$(MOZ_BUILD_APP))
 _BROWSER_TEST_FILES = \
 		browser_bug592641.js \
 		bug592641_img.jpg \
 		$(NULL)
--- a/content/html/document/test/test_bug255820.html
+++ b/content/html/document/test/test_bug255820.html
@@ -64,21 +64,16 @@ function f3Continue() {
                  'is(doc.defaultView.getComputedStyle(doc.body, "").color, ' +
                  '   "rgb(0, 180, 0)",' +
                  '   "Wrong color after reload");' +
                  "charsetTestFinished('f1', this.contentDocument, 'UTF-8')");
   $("f3").contentWindow.location.reload();
 }
 
 function runTest() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-    .getService(Components.interfaces.nsIPrefBranch);
-  var html5enabled = prefs.getBoolPref("html5.parser.enable");
-
   var doc = $("f1").contentDocument;
   is(doc.characterSet, "UTF-8",
      "Unexpected initial character set for first frame");
   doc.open();
   doc.write('<html></html>');
   doc.close();
   is(doc.characterSet, "UTF-8",
      "Unexpected character set for first frame after write");
@@ -95,27 +90,20 @@ function runTest() {
   str += '<script src="data:application/javascript,"><'+'/script>';
   str += '<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">';
   str += '</head><body>';
   str += '</body></html>';
   doc.write(str);
   doc.close();
   is(doc.characterSet, "UTF-8",
      "Unexpected character set for second frame after write");
-  if (html5enabled) {
-    $("f2").
-      setAttribute("onload",
-        "charsetTestFinished('f2', this.contentDocument, 'UTF-8');" +
-        "f2Continue()");
-  } else {
-    $("f2").
-      setAttribute("onload",
-        "charsetTestFinished('f2', this.contentDocument, 'us-ascii');" +
-        "f2Continue()");
-  }
+  $("f2").
+    setAttribute("onload",
+      "charsetTestFinished('f2', this.contentDocument, 'UTF-8');" +
+      "f2Continue()");
 
   doc = $("f3").contentDocument;
   is(doc.characterSet, "UTF-8",
      "Unexpected initial character set for first frame");
   doc.open();
   var str = '<html><head>';
   str += '<style>body { color: rgb(255, 0, 0) }</style>';
   str += '<link type="text/css" rel="stylesheet" href="data:text/css, body { color: rgb(0, 180, 0) }">';
deleted file mode 100644
--- a/content/html/document/test/test_bug570376.html
+++ /dev/null
@@ -1,44 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=570376
--->
-<head>
-  <title>Test for Bug 570376</title>
-  <script type="application/javascript" src="/MochiKit/packed.js"></script>
-  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=570376">Mozilla Bug 570376</a>
-<p id="display">
-  <iframe id="testiframe"></iframe>
-</p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-<script type="application/javascript">
-
-/** Test for Bug 570376
-    Don't crash loading <form><legend> with the html5 parser preffed off.
- **/
-
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-                      .getService(Components.interfaces.nsIPrefBranch);
-var gOriginalHtml5Pref = prefs.getBoolPref("html5.parser.enable");
-prefs.setBoolPref("html5.parser.enable", false);
-
-$("testiframe").onload = function () {
-  ok(true, "Shouldn't crash loading a form containing a legend with the html5 parser preffed off");
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-                        .getService(Components.interfaces.nsIPrefBranch);
-  prefs.setBoolPref("html5.parser.enable", gOriginalHtml5Pref);
-}
-$("testiframe").src = "data:text/html,<form><legend>";
-
-</script>
-</pre>
-</body>
-</html>
--- a/content/media/nsBuiltinDecoderStateMachine.cpp
+++ b/content/media/nsBuiltinDecoderStateMachine.cpp
@@ -1543,17 +1543,17 @@ void nsBuiltinDecoderStateMachine::Advan
         mState == DECODER_STATE_COMPLETED) {
       mDecoder->GetReentrantMonitor().Wait();
     }
   }
 }
 
 void nsBuiltinDecoderStateMachine::Wait(PRInt64 aUsecs) {
   mDecoder->GetReentrantMonitor().AssertCurrentThreadIn();
-  TimeStamp end = TimeStamp::Now() + UsecsToDuration(aUsecs);
+  TimeStamp end = TimeStamp::Now() + UsecsToDuration(PR_MAX(USECS_PER_MS, aUsecs));
   TimeStamp now;
   while ((now = TimeStamp::Now()) < end &&
          mState != DECODER_STATE_SHUTDOWN &&
          mState != DECODER_STATE_SEEKING)
   {
     PRInt64 ms = static_cast<PRInt64>(NS_round((end - now).ToSeconds() * 1000));
     if (ms == 0 || ms > PR_UINT32_MAX) {
       break;
--- a/content/media/nsBuiltinDecoderStateMachine.h
+++ b/content/media/nsBuiltinDecoderStateMachine.h
@@ -282,19 +282,20 @@ protected:
   PRBool HasFutureAudio() const;
 
   // Returns PR_TRUE if we recently exited "quick buffering" mode.
   PRBool JustExitedQuickBuffering();
 
   // Waits on the decoder ReentrantMonitor for aUsecs microseconds. If the decoder
   // monitor is awoken by a Notify() call, we'll continue waiting, unless
   // we've moved into shutdown state. This enables us to ensure that we
-  // wait for a specified time, and that the myriad of Notify()s we do an
-  // the decoder monitor don't cause the audio thread to be starved. The
-  // decoder monitor must be locked.
+  // wait for a specified time, and that the myriad of Notify()s we do on
+  // the decoder monitor don't cause the audio thread to be starved. aUsecs
+  // values of less than 1 millisecond are rounded up to 1 millisecond
+  // (see bug 651023). The decoder monitor must be held.
   void Wait(PRInt64 aUsecs);
 
   // Dispatches an asynchronous event to update the media element's ready state.
   void UpdateReadyState();
 
   // Resets playback timing data. Called when we seek, on the state machine
   // thread.
   void ResetPlayback();
--- a/content/media/test/test_bug495300.html
+++ b/content/media/test/test_bug495300.html
@@ -10,50 +10,49 @@ https://bugzilla.mozilla.org/show_bug.cg
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
   <script type="text/javascript" src="manifest.js"></script>
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=495300">Mozilla Bug 495300</a>
 <pre id="test">
 <script class="testbody" type="text/javascript">
-var testsWaiting = 0;
+
+var manager = new MediaTestManager;
+
+function filename(uri) {
+  return uri.substr(uri.lastIndexOf("/")+1);
+}
 
 function mediaEnded(event) {
-  ok(true, "Got expected 'ended' event: " + event.target.currentSrc);
+  ok(true, "Got expected 'ended' event: " + filename(event.target.currentSrc));
 
   if (event.target._expectedDuration)
     ok(Math.abs(event.target.currentTime - event.target._expectedDuration) < 0.1,
-       "currentTime equals duration: " + event.target.currentSrc);
+       "currentTime equals duration: " + filename(event.target.currentSrc));
 
-  if (--testsWaiting == 0)
-    SimpleTest.finish();
+  manager.finished(event.target.token);
 }
 
-for (var i = 0; i < gSeekTests.length; ++i) {
-  var test = gSeekTests[i];
+function startTest(test, token) {
   var elemType = /^audio/.test(test.type) ? "audio" : "video";
   var v1 = document.createElement(elemType);
-  if (!v1.canPlayType(test.type))
-    continue;
 
   v1.src = test.name;
   if (test.duration) {
     v1._expectedDuration = test.duration;
   }
   v1.addEventListener("loadedmetadata", function (event) {
     event.target.currentTime = event.target.duration;
   }, false);
   v1.addEventListener("ended", mediaEnded, false);
   v1.load();
 
-  ++testsWaiting;
+  v1.token = token;
+  manager.started(token);
 }
 
-if (testsWaiting == 0) {
-  todo(false, "Can't play anything");
-} else {
-  SimpleTest.waitForExplicitFinish();
-}
+manager.runTests(gSeekTests, startTest);
+
 </script>
 </pre>
 </body>
 </html>
--- a/content/smil/nsSMILAnimationController.cpp
+++ b/content/smil/nsSMILAnimationController.cpp
@@ -89,16 +89,18 @@ nsSMILAnimationController::~nsSMILAnimat
 }
 
 void
 nsSMILAnimationController::Disconnect()
 {
   NS_ABORT_IF_FALSE(mDocument, "disconnecting when we weren't connected...?");
   NS_ABORT_IF_FALSE(mRefCnt.get() == 1,
                     "Expecting to disconnect when doc is sole remaining owner");
+  NS_ABORT_IF_FALSE(mPauseState & nsSMILTimeContainer::PAUSE_PAGEHIDE,
+                    "Expecting to be paused for pagehide before disconnect");
 
   StopSampling(GetRefreshDriver());
 
   mDocument = nsnull; // (raw pointer)
 }
 
 //----------------------------------------------------------------------
 // nsSMILTimeContainer methods:
--- a/db/mork/src/morkConfig.h
+++ b/db/mork/src/morkConfig.h
@@ -45,18 +45,16 @@
 // } %%%%% end debug mode options in Mork %%%%%
 
 #ifdef MORK_DEBUG
 #define MORK_MAX_CODE_COMPILE 1
 #endif
 
 // { %%%%% begin platform defs peculiar to Mork %%%%%
 
-//#define XP_MAC 1
-
 #ifdef XP_MACOSX
 #define MORK_MAC 1
 #endif
 
 #ifdef XP_OS2
 #define MORK_OS2 1
 #endif
 
--- a/db/sqlite3/src/Makefile.in
+++ b/db/sqlite3/src/Makefile.in
@@ -47,17 +47,17 @@ include $(DEPTH)/config/autoconf.mk
 
 MODULE           = sqlite3
 LIBRARY_NAME     = mozsqlite3
 SHORT_LIBNAME    = mozsqlt3
 FORCE_SHARED_LIB = 1
 VISIBILITY_FLAGS =
 LIB_IS_C_ONLY    = 1
 
-ifeq (,$(filter-out WINNT WINCE,$(OS_ARCH)))
+ifeq ($(OS_ARCH),WINNT)
 ifndef GNU_CC
 DEFFILE = $(CURDIR)/sqlite-processed.def
 RCFILE  = sqlite.rc
 RESFILE = sqlite.res
 
 GARBAGE += \
   sqlite-version.h \
   $(DEFFILE) \
@@ -130,16 +130,21 @@ NO_PROFILE_GUIDED_OPTIMIZE = 1
 endif
 
 ifeq ($(OS_ARCH),OS2)
 ifdef MOZ_OS2_HIGH_MEMORY
 DEFINES += -DOS2_HIGH_MEMORY
 endif
 endif
 
+ifeq ($(OS_TARGET),Android)
+# default to user readable only to fit Android security model
+DEFINES += -DSQLITE_DEFAULT_FILE_PERMISSIONS=0600
+endif
+
 include $(topsrcdir)/config/rules.mk
 
 # next line allows use of MOZ_OBJDIR in .mozconfig with older gcc on BeOS, maybe others
 LOCAL_INCLUDES += -I$(srcdir)
 
 ifeq ($(OS_ARCH),OS2)
 ADD_TO_DEF_FILE = $(PYTHON) $(topsrcdir)/config/Preprocessor.py $(DEFINES) \
        $(srcdir)/sqlite.def | sed -e '1,/^EXPORTS$$/ d' -e 's,sqlite3,_\0,' \
--- a/docshell/base/nsDefaultURIFixup.cpp
+++ b/docshell/base/nsDefaultURIFixup.cpp
@@ -812,26 +812,16 @@ const char * nsDefaultURIFixup::GetFileS
   }
 
   return mFsCharset.get();
 }
 
 const char * nsDefaultURIFixup::GetCharsetForUrlBar()
 {
   const char *charset = GetFileSystemCharset();
-#ifdef XP_MAC
-  // check for "x-mac-" prefix
-  if ((strlen(charset) >= 6) && charset[0] == 'x' && charset[2] == 'm')
-  {
-    if (!strcmp("x-mac-roman", charset))
-      return "ISO-8859-1";
-    // we can do more x-mac-xxxx mapping here
-    // or somewhere in intl code like nsIPlatformCharset.
-  }
-#endif
   return charset;
 }
 
 nsresult nsDefaultURIFixup::KeywordURIFixup(const nsACString & aURIString, 
                                             nsIURI** aURI)
 {
     // These are keyword formatted strings
     // "what is mozilla"
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -6470,16 +6470,20 @@ nsDocShell::CreateAboutBlankContentViewe
 
     mSavingOldViewer = aTryToSaveOldPresentation && 
                        CanSavePresentation(LOAD_NORMAL, nsnull, nsnull);
 
     // Make sure to blow away our mLoadingURI just in case.  No loads
     // from inside this pagehide.
     mLoadingURI = nsnull;
     
+    // Stop any in-progress loading, so that we don't accidentally trigger any
+    // PageShow notifications from Embed() interrupting our loading below.
+    Stop();
+
     // Notify the current document that it is about to be unloaded!!
     //
     // It is important to fire the unload() notification *before* any state
     // is changed within the DocShell - otherwise, javascript will get the
     // wrong information :-(
     //
     (void) FirePageHideNotification(!mSavingOldViewer);
   }
@@ -8002,38 +8006,47 @@ nsDocShell::InternalLoad(nsIURI * aURI,
     {
         PRBool inherits;
         // One more twist: Don't inherit the owner for external loads.
         if (aLoadType != LOAD_NORMAL_EXTERNAL && !owner &&
             (aFlags & INTERNAL_LOAD_FLAGS_INHERIT_OWNER) &&
             NS_SUCCEEDED(URIInheritsSecurityContext(aURI, &inherits)) &&
             inherits) {
 
-            // Don't allow loads that would inherit our security context
-            // if this document came from an unsafe channel.
+            owner = GetInheritedPrincipal(PR_TRUE);
+        }
+    }
+
+    // Don't allow loads that would inherit our security context
+    // if this document came from an unsafe channel.
+    {
+        PRBool willInherit;
+        // This condition needs to match the one in DoChannelLoad.
+        // Except we reverse the rv check to be safe in case
+        // URIInheritsSecurityContext fails here and succeeds there.
+        rv = URIInheritsSecurityContext(aURI, &willInherit);
+        if (NS_FAILED(rv) || willInherit || IsAboutBlank(aURI)) {
             nsCOMPtr<nsIDocShellTreeItem> treeItem = this;
             do {
                 nsCOMPtr<nsIDocShell> itemDocShell =
                     do_QueryInterface(treeItem);
                 PRBool isUnsafe;
                 if (itemDocShell &&
                     NS_SUCCEEDED(itemDocShell->GetChannelIsUnsafe(&isUnsafe)) &&
                     isUnsafe) {
                     return NS_ERROR_DOM_SECURITY_ERR;
                 }
 
                 nsCOMPtr<nsIDocShellTreeItem> parent;
                 treeItem->GetSameTypeParent(getter_AddRefs(parent));
                 parent.swap(treeItem);
             } while (treeItem);
-
-            owner = GetInheritedPrincipal(PR_TRUE);
-        }
-    }
-
+        }
+    }
+    
     //
     // Resolve the window target before going any further...
     // If the load has been targeted to another DocShell, then transfer the
     // load to it...
     //
     if (aWindowTarget && *aWindowTarget) {
         // We've already done our owner-inheriting.  Mask out that bit, so we
         // don't try inheriting an owner from the target window if we came up
@@ -8832,16 +8845,18 @@ nsDocShell::DoURILoad(nsIURI * aURI,
     //      (Currently chrome URIs set the owner when they are created!
     //      So setting a NULL owner would be bad!)
     //
     // If this code ever changes, change nsObjectLoadingContent::LoadObject
     // accordingly.
     PRBool inherit;
     // We expect URIInheritsSecurityContext to return success for an
     // about:blank URI, so don't call IsAboutBlank() if this call fails.
+    // This condition needs to match the one in InternalLoad where
+    // we're checking for things that will use the owner.
     rv = URIInheritsSecurityContext(aURI, &inherit);
     if (NS_SUCCEEDED(rv) && (inherit || IsAboutBlank(aURI))) {
         channel->SetOwner(aOwner);
     }
 
     //
     // file: uri special-casing
     //
--- a/docshell/base/nsIMarkupDocumentViewer.idl
+++ b/docshell/base/nsIMarkupDocumentViewer.idl
@@ -47,17 +47,17 @@
  * for a markup document - HTML or XML
  */
 
 #include "nsISupports.idl"
 
 interface nsIDOMNode;
 
 
-[scriptable, uuid(19187542-1f4d-46e1-9b2d-d5de02dace85)]
+[scriptable, uuid(00d3454c-e125-4cce-bfec-adfbf0975e05)]
 interface nsIMarkupDocumentViewer : nsISupports
 {
 
 	/*
 	Scrolls to a given DOM content node. 
 	*/
 	void scrollToNode(in nsIDOMNode node);
 
@@ -138,27 +138,20 @@ interface nsIMarkupDocumentViewer : nsIS
    * bidiSupport: whether to use platform bidi support or Mozilla's bidi support
    *              1 - Use Mozilla's bidi support
    *              2 - Use the platform bidi support
    *              3 - Disable bidi support
    */
   attribute octet bidiSupport;
 
   /**
-   * bidiCharacterSet: whether to force the user's character set
-   *                   1 - use the document character set
-   *                   2 - use the character set chosen by the user
-   */
-  attribute octet bidiCharacterSet;  
-  
-  /**
    * Use this attribute to access all the Bidi options in one operation
    */
   attribute PRUint32 bidiOptions;
 };
 
-[scriptable, uuid(cadfcad1-5570-4dac-b5a2-cd1ea751fe29)]
+[scriptable, uuid(83b28afd-75a7-4d13-9265-625e36861f04)]
 interface nsIMarkupDocumentViewer_MOZILLA_2_0_BRANCH : nsIMarkupDocumentViewer
 {
 	/** The minimum font size  */
 	attribute long minFontSize;
 
 };
index 86b9c8c0964e8012b94bc1d965b296aae512a6de..a6e9a68a8514fb48f89a2eedf8b86a6854ca4d0c
GIT binary patch
literal 1113
zc$^FHW@Zs#U}E54Flbn87n-|s%{B%Gh8RW$1|9|(hQz$&jQpZvy^NCFoX`+X24?B_
z1HK?!TEWf0$nq7a45*udVeSNPzC#8)F5hiir}8Q&DzP{<+_`g9wasmc3YS~!?aPxs
zL~fR;w)vcr^YoHr&dfC{83N{%<eZSdHDTR~&1(YEnavK`vBlpEZzv4#c#yNU<x;1s
z<Ln<1+TKpp4|l)Vm}qw@`qhUj552CJbGI*yZ#gmVvQnF|zxvNQBj;Eju1_n%&c5Ap
z>&>>)r7sPVWq2wDnm->B^XQT^t({o&gIOymNuTxA+z;JfGv_z+&%gE2`={*>FY~Ly
z0YJZVF@S(nQ@*)qPu5j8poiSReivoPOe;#vO-1s1@k1MT5Du+iVfe}@!e9fEv9rlY
zO-!-l<x)_vDakC!NwtIOv(bledAV%#p-OC$@>427N{dUAiZfDka*Ba$n*xxC4Mdkh
zW{Ry+N@7W(E`+b7P+XJ@5wR*sttin4S*Zi!mKNnGK-Ab2Cl_TFl-QML=B4D9>lGvx
zrRJ5usr>9z4Rs_F)irJOp&FDxPPNg8h}&UxN>(wdL$VUf5+S;+@K^`erLL)DmsN~v
zi;X@s6l}nru?v7FK$iB!b_Z(?oSF!Xkkbs11Xz@sR+L(tfrx|`*#~?<7%c(n_WANP
z83?p~SG(6((yZnc`}%_L4x^6@Q~NTNF9gk7w0*lny0QKH)78#mv8zvPGRxYn$<^e1
zTI-YXrwq?^uNRf@#6~E{R95Wv*ELc}D_wi+`vbYH7P0TPXXl!Hk^Iv-Cz#K~>>}%m
zlV6Ydhh8w;82Ul~-qf3`?@T^3#bc$)=j1ORo=vYxd8}kUV`<Hzqc*(t0p5&Ea?H4L
zmIOG}0htU-8bK`7e8vjNXJ}ponJCVTE4}hEz(7OeA0UaEdRZZ<H?#s`49sDeA&ziZ
eLt`To16ugALc$-zVXSN*UCcoE8c0VlgLnY6{&S!J
--- a/docshell/test/test_bug369814.html
+++ b/docshell/test/test_bug369814.html
@@ -10,38 +10,36 @@ https://bugzilla.mozilla.org/show_bug.cg
   <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=384014">Mozilla Bug 369814</a>
 
 <p>
 
-<iframe id="testFrame"></iframe>
-
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /** Tests for Bug 369814 **/
 
 SimpleTest.waitForExplicitFinish();
 
 // Because child scripts won't be able to run to tell us they're done,
-// we need to just wait for them.  Wait this amount of time before checking
-// the results.
-const gLoadTimeout = 3000;
+// we need to just wait for them.  Wait this many event loop spins before
+// checking the results.
+const gLoadEventLoopCount = 100;
 
 var Ci = Components.interfaces;
 
 var gCurrentTest;
 var gTargetWindow;
 var gNumPokes;
 var gPrefValue;
 
-var gTestFrame = document.getElementById('testFrame');
+var gTestFrame;
 
 /**
  * Called by documents loaded from jar files to indicate that they can access
  * this document.
  */
 function poke(description) {
   ok(false, gCurrentTest['name'] + ": got unexpected poke: " + description);
   gNumPokes++;
@@ -65,66 +63,88 @@ function loadTestTarget(callback)
 function closeTestTarget()
 {
   gTargetWindow.close();
   gTargetWindow = null;
 }
 
 function loadErrorTest(test)
 {
-  gTestFrame.src = test['url'];
-
-  // Give the frame a chance to fail at loading
-  setTimeout(function() {
+  // Give the frame a chance to fail at loading.
+  // How do detect failure to load?  Error pages don't fire load
+  // events.  But we can load another page before the error page and
+  // then use its unload handler to know when the error page is just
+  // about loaded; at that point a single trip through the event loop
+  // should do the trick.
+  loadEvent(gTestFrame, function() {
+      gTestFrame.src = test['url'];
+    });
+  gTestFrame.unloading = function() {
+    gTestFrame.unloading = null;
+    // Go out to the event loop once so that unload processing finishes and
+    // the new document is set up.
+    setTimeout(function() {
       // XXX: There doesn't seem to be a reliable check for "got an error,"
       // but reaching in to an error document will throw an exception
       var errorPage;
       try {
         var item = gTestFrame.contentDocument.getElementById(gCurrentTest['data-iframe']);
         errorPage = false;
       } catch (e) {
         errorPage = true;
       }
       ok(errorPage, gCurrentTest["name"] + ": should block a suspicious JAR load.");
 
       finishTest();
-    }, gLoadTimeout);
+    }, 0);
+  }
+  var unloadDetector = "data:text/html,<script>window.onunload = function() { frameElement.unloading(); }</" + "script>";
+  gTestFrame.src = unloadDetector;
 }
 
 function iframeTest(test) {
   gTestFrame.src = test['url'];
   loadEvent(gTestFrame, function() {
       finishTest();
     });
 }
 
+
+function hitEventLoop(func, times) {
+  if (times > 0) {
+    SimpleTest.executeSoon(function() { hitEventLoop(func, times-1); });
+  } else {
+    SimpleTest.executeSoon(func);
+  }
+}
+
 function refreshTest(test) {
   gTestFrame.src = test['url'];
   loadEvent(gTestFrame, function() {
       // Wait for the frame to try and refresh
       // XXX: a "blocked redirect" signal would be needed to get rid of
       // this timeout.
-      setTimeout(function() {
+      hitEventLoop(function() {
           finishTest();
-        }, gLoadTimeout);
+        }, gLoadEventLoopCount);
     });
 }
 
 function anchorTest(test) {
   loadTestTarget(function() {
       gTestFrame.src = test['url'];
       loadEvent(gTestFrame, function() {
         sendMouseEvent({type:'click'}, 'target', gTestFrame.contentWindow);
         sendMouseEvent({type:'click'}, 'notarget', gTestFrame.contentWindow);
 
         // Give the clicks a chance to load
-        setTimeout(function() {
+        hitEventLoop(function() {
             closeTestTarget();
             finishTest();
-          }, gLoadTimeout);
+          }, gLoadEventLoopCount);
         });
     });
 }
 
 var gTests = [
   { "name" : "iframes.html loaded from non-jar type, pref disabled",
     "url" : "jar:http://mochi.test:8888/tests/docshell/test/bug369814.zip!/iframes.html",
     "pref" : false,
@@ -172,16 +192,24 @@ function runNextTest()
     getService(Components.interfaces.nsIPrefBranch);
 
   if (gNextTest < gTests.length) {
     gCurrentTest = gTests[gNextTest++];
     gNumPokes = 0;
 
     prefs.setBoolPref("network.jar.open-unsafe-types", gCurrentTest['pref']);
 
+    // Create a new frame each time, so our restictions on loads in a
+    // jar:-loaded iframe don't interfere with the test.
+    if (gTestFrame) {
+      document.body.removeChild(gTestFrame);
+    }
+    gTestFrame = document.createElement("iframe");
+    document.body.insertBefore(gTestFrame, $("test"));
+
     gCurrentTest['func'](gCurrentTest);
   } else {
     // Put back the pref value we had at test start
     prefs.setBoolPref("network.jar.open-unsafe-types", gPrefValue);
     SimpleTest.finish();
   }
 }
 
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -66,17 +66,17 @@
 #include "nsUnicharUtils.h"
 #include "xptcall.h"
 #include "prprf.h"
 #include "nsTArray.h"
 #include "nsCSSValue.h"
 #include "nsIRunnable.h"
 #include "nsThreadUtils.h"
 #include "nsDOMEventTargetWrapperCache.h"
-#include "xpcpublic.h"
+#include "xpcprivate.h"
 
 // General helper includes
 #include "nsGlobalWindow.h"
 #include "nsHistory.h"
 #include "nsIContent.h"
 #include "nsIAttribute.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
@@ -506,16 +506,17 @@
 #include "mozilla/dom/indexedDB/IDBKeyRange.h"
 #include "mozilla/dom/indexedDB/IDBIndex.h"
 #include "nsIIDBDatabaseException.h"
 #include "nsIDOMEventException.h"
 
 #include "nsIDOMMediaQueryList.h"
 
 #include "nsDOMTouchEvent.h"
+#include "nsIDOMCustomEvent.h"
 
 using namespace mozilla::dom;
 
 static NS_DEFINE_CID(kDOMSOF_CID, NS_DOM_SCRIPT_OBJECT_FACTORY_CID);
 
 static const char kDOMStringBundleURL[] =
   "chrome://global/locale/dom/dom.properties";
 
@@ -1511,16 +1512,18 @@ static nsDOMClassInfoData sClassInfoData
   NS_DEFINE_CLASSINFO_DATA(MozCSSKeyframeRule, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(MozCSSKeyframesRule, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
 #endif
 
   NS_DEFINE_CLASSINFO_DATA(MediaQueryList, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
+  NS_DEFINE_CLASSINFO_DATA(CustomEvent, nsDOMGenericSH,
+                           DOM_DEFAULT_SCRIPTABLE_FLAGS)
 };
 
 // Objects that should be constructable through |new Name();|
 struct nsContractIDMapData
 {
   PRInt32 mDOMClassInfoID;
   const char *mContractID;
 };
@@ -1559,17 +1562,16 @@ static const nsConstructorFuncMapData kC
 
 nsIXPConnect *nsDOMClassInfo::sXPConnect = nsnull;
 nsIScriptSecurityManager *nsDOMClassInfo::sSecMan = nsnull;
 PRBool nsDOMClassInfo::sIsInitialized = PR_FALSE;
 PRBool nsDOMClassInfo::sDisableDocumentAllSupport = PR_FALSE;
 PRBool nsDOMClassInfo::sDisableGlobalScopePollutionSupport = PR_FALSE;
 
 
-jsid nsDOMClassInfo::sTop_id             = JSID_VOID;
 jsid nsDOMClassInfo::sParent_id          = JSID_VOID;
 jsid nsDOMClassInfo::sScrollbars_id      = JSID_VOID;
 jsid nsDOMClassInfo::sLocation_id        = JSID_VOID;
 jsid nsDOMClassInfo::sConstructor_id     = JSID_VOID;
 jsid nsDOMClassInfo::s_content_id        = JSID_VOID;
 jsid nsDOMClassInfo::sContent_id         = JSID_VOID;
 jsid nsDOMClassInfo::sMenubar_id         = JSID_VOID;
 jsid nsDOMClassInfo::sToolbar_id         = JSID_VOID;
@@ -1894,17 +1896,16 @@ nsDOMClassInfo::DefineStaticJSVals(JSCon
 #define SET_JSID_TO_STRING(_id, _cx, _str)                                    \
   if (JSString *str = ::JS_InternString(_cx, _str))                           \
       _id = INTERNED_STRING_TO_JSID(str);                                     \
   else                                                                        \
       return NS_ERROR_OUT_OF_MEMORY;
 
   JSAutoRequest ar(cx);
 
-  SET_JSID_TO_STRING(sTop_id,             cx, "top");
   SET_JSID_TO_STRING(sParent_id,          cx, "parent");
   SET_JSID_TO_STRING(sScrollbars_id,      cx, "scrollbars");
   SET_JSID_TO_STRING(sLocation_id,        cx, "location");
   SET_JSID_TO_STRING(sConstructor_id,     cx, "constructor");
   SET_JSID_TO_STRING(s_content_id,        cx, "_content");
   SET_JSID_TO_STRING(sContent_id,         cx, "content");
   SET_JSID_TO_STRING(sMenubar_id,         cx, "menubar");
   SET_JSID_TO_STRING(sToolbar_id,         cx, "toolbar");
@@ -4334,16 +4335,21 @@ nsDOMClassInfo::Init()
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMMozCSSKeyframesRule)
   DOM_CLASSINFO_MAP_END
 #endif
 
   DOM_CLASSINFO_MAP_BEGIN(MediaQueryList, nsIDOMMediaQueryList)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMMediaQueryList)
   DOM_CLASSINFO_MAP_END
 
+  DOM_CLASSINFO_MAP_BEGIN(CustomEvent, nsIDOMCustomEvent)
+    DOM_CLASSINFO_MAP_ENTRY(nsIDOMCustomEvent)
+    DOM_CLASSINFO_EVENT_MAP_ENTRIES
+  DOM_CLASSINFO_MAP_END
+
 #ifdef NS_DEBUG
   {
     PRUint32 i = NS_ARRAY_LENGTH(sClassInfoData);
 
     if (i != eDOMClassInfoIDCount) {
       NS_ERROR("The number of items in sClassInfoData doesn't match the "
                "number of nsIDOMClassInfo ID's, this is bad! Fix it!");
 
@@ -5017,17 +5023,16 @@ nsDOMClassInfo::ShutDown()
   if (sClassInfoData[0].u.mConstructorFptr) {
     PRUint32 i;
 
     for (i = 0; i < eDOMClassInfoIDCount; i++) {
       NS_IF_RELEASE(sClassInfoData[i].mCachedClassInfo);
     }
   }
 
-  sTop_id             = JSID_VOID;
   sParent_id          = JSID_VOID;
   sScrollbars_id      = JSID_VOID;
   sLocation_id        = JSID_VOID;
   sConstructor_id     = JSID_VOID;
   s_content_id        = JSID_VOID;
   sContent_id         = JSID_VOID;
   sMenubar_id         = JSID_VOID;
   sToolbar_id         = JSID_VOID;
@@ -8009,17 +8014,17 @@ nsElementSH::PostCreate(nsIXPConnectWrap
   PRBool ok = GetBindingURL(element, doc, &bindingURL);
   NS_ENSURE_TRUE(ok, NS_ERROR_FAILURE);
 
   if (!bindingURL) {
     // No binding, nothing left to do here.
     return NS_OK;
   }
 
-  nsCOMPtr<nsIURI> uri = bindingURL->mURI;
+  nsCOMPtr<nsIURI> uri = bindingURL->GetURI();
   nsCOMPtr<nsIPrincipal> principal = bindingURL->mOriginPrincipal;
 
   // We have a binding that must be installed.
   PRBool dummy;
 
   nsCOMPtr<nsIXBLService> xblService(do_GetService("@mozilla.org/xbl;1"));
   NS_ENSURE_TRUE(xblService, NS_ERROR_NOT_AVAILABLE);
 
@@ -10187,22 +10192,21 @@ nsStringArraySH::GetProperty(nsIXPConnec
 
   nsresult rv = GetStringAt(GetNative(wrapper, obj), n, val);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // XXX: Null strings?
 
   JSAutoRequest ar(cx);
 
-  JSString *str =
-    ::JS_NewUCStringCopyN(cx, reinterpret_cast<const jschar *>(val.get()),
-                          val.Length());
-  NS_ENSURE_TRUE(str, NS_ERROR_OUT_OF_MEMORY);
-
-  *vp = STRING_TO_JSVAL(str);
+  nsStringBuffer* sharedBuffer = nsnull;
+  *vp = XPCStringConvert::ReadableToJSVal(cx, val, &sharedBuffer);
+  if (sharedBuffer) {
+    val.ForgetSharedBuffer();
+  }
 
   return NS_SUCCESS_I_DID_SOMETHING;
 }
 
 
 // History helper
 
 NS_IMETHODIMP
--- a/dom/base/nsDOMClassInfo.h
+++ b/dom/base/nsDOMClassInfo.h
@@ -197,18 +197,17 @@ protected:
   // Checks if id is a number and returns the number, if aIsNumber is
   // non-null it's set to true if the id is a number and false if it's
   // not a number. If id is not a number this method returns -1
   static PRInt32 GetArrayIndexFromId(JSContext *cx, jsid id,
                                      PRBool *aIsNumber = nsnull);
 
   static inline PRBool IsReadonlyReplaceable(jsid id)
   {
-    return (id == sTop_id          ||
-            id == sParent_id       ||
+    return (id == sParent_id       ||
             id == sScrollbars_id   ||
             id == sContent_id      ||
             id == sMenubar_id      ||
             id == sToolbar_id      ||
             id == sLocationbar_id  ||
             id == sPersonalbar_id  ||
             id == sStatusbar_id    ||
             id == sControllers_id  ||
@@ -241,17 +240,16 @@ protected:
   // nsIXPCScriptable code
   static nsresult DefineStaticJSVals(JSContext *cx);
 
   static PRBool sIsInitialized;
   static PRBool sDisableDocumentAllSupport;
   static PRBool sDisableGlobalScopePollutionSupport;
 
 public:
-  static jsid sTop_id;
   static jsid sParent_id;
   static jsid sScrollbars_id;
   static jsid sLocation_id;
   static jsid sConstructor_id;
   static jsid s_content_id;
   static jsid sContent_id;
   static jsid sMenubar_id;
   static jsid sToolbar_id;
--- a/dom/base/nsDOMClassInfoClasses.h
+++ b/dom/base/nsDOMClassInfoClasses.h
@@ -518,8 +518,9 @@ DOMCI_CLASS(TouchList)
 DOMCI_CLASS(TouchEvent)
 
 #ifdef MOZ_CSS_ANIMATIONS
 DOMCI_CLASS(MozCSSKeyframeRule)
 DOMCI_CLASS(MozCSSKeyframesRule)
 #endif
 
 DOMCI_CLASS(MediaQueryList)
+DOMCI_CLASS(CustomEvent)
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -813,17 +813,17 @@ nsGlobalWindow::nsGlobalWindow(nsGlobalW
     mIsPopupSpam(PR_FALSE),
     mBlockScriptedClosingFlag(PR_FALSE),
     mFireOfflineStatusChangeEventOnThaw(PR_FALSE),
     mCreatingInnerWindow(PR_FALSE),
     mIsChrome(PR_FALSE),
     mCleanMessageManager(PR_FALSE),
     mNeedsFocus(PR_TRUE),
     mHasFocus(PR_FALSE),
-#if defined(XP_MAC) || defined(XP_MACOSX)
+#if defined(XP_MACOSX)
     mShowAccelerators(PR_FALSE),
     mShowFocusRings(PR_FALSE),
 #else
     mShowAccelerators(PR_TRUE),
     mShowFocusRings(PR_TRUE),
 #endif
     mShowFocusRingForContent(PR_FALSE),
     mFocusByKeyOccurred(PR_FALSE),
@@ -4086,17 +4086,17 @@ nsGlobalWindow::CheckSecurityLeftAndTop(
       winWidth  = DevToCSSIntPixels(winWidth);
       winHeight = DevToCSSIntPixels(winHeight);
 
       // Get the screen dimensions
       // XXX This should use nsIScreenManager once it's fully fleshed out.
       screen->GetAvailLeft(&screenLeft);
       screen->GetAvailWidth(&screenWidth);
       screen->GetAvailHeight(&screenHeight);
-#if defined(XP_MAC) || defined(XP_MACOSX)
+#if defined(XP_MACOSX)
       /* The mac's coordinate system is different from the assumed Windows'
          system. It offsets by the height of the menubar so that a window
          placed at (0,0) will be entirely visible. Unfortunately that
          correction is made elsewhere (in Widget) and the meaning of
          the Avail... coordinates is overloaded. Here we allow a window
          to be placed at (0,0) because it does make sense to do so.
       */
       screen->GetTop(&screenTop);
@@ -4426,17 +4426,17 @@ NS_IMETHODIMP
 nsGlobalWindow::Dump(const nsAString& aStr)
 {
   if (!DOMWindowDumpEnabled()) {
     return NS_OK;
   }
 
   char *cstr = ToNewUTF8String(aStr);
 
-#if defined(XP_MAC) || defined(XP_MACOSX)
+#if defined(XP_MACOSX)
   // have to convert \r to \n so that printing to the console works
   char *c = cstr, *cEnd = cstr + strlen(cstr);
   while (c < cEnd) {
     if (*c == '\r')
       *c = '\n';
     c++;
   }
 #endif
--- a/dom/interfaces/events/Makefile.in
+++ b/dom/interfaces/events/Makefile.in
@@ -85,16 +85,17 @@ XPIDLSRCS =					\
 	nsIDOMDeviceOrientationEvent.idl			\
 	nsIDOMScrollAreaEvent.idl		\
 	nsIDOMTransitionEvent.idl		\
 	nsIDOMPopStateEvent.idl			\
 	nsIDOMCloseEvent.idl			\
 	nsIDOMEventException.idl		\
 	nsIDOMTouchEvent.idl			\
 	nsIDOMHashChangeEvent.idl		\
+	nsIDOMCustomEvent.idl			\
 	$(NULL)
 
 ifdef MOZ_CSS_ANIMATIONS
 XPIDLSRCS +=					\
 	nsIDOMAnimationEvent.idl		\
 	$(NULL)
 endif
 
new file mode 100644
--- /dev/null
+++ b/dom/interfaces/events/nsIDOMCustomEvent.idl
@@ -0,0 +1,51 @@
+/* vim: set shiftwidth=2 tabstop=8 autoindent cindent expandtab: */
+/* ***** 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 nsIDOMCustomEvent.
+ *
+ * The Initial Developer of the Original Code is the Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Olli Pettay <Olli.Pettay@helsinki.fi> (Original Author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "nsIDOMEvent.idl"
+interface nsIVariant;
+
+[scriptable, uuid(e93f84c5-e72f-4429-b797-f0c28d87890f)]
+interface nsIDOMCustomEvent : nsIDOMEvent
+{
+
+  readonly attribute nsIVariant detail;
+
+  void initCustomEvent(in DOMString  typeArg, 
+                       in boolean    canBubbleArg, 
+                       in boolean    cancelableArg, 
+                       in nsIVariant detailArg);
+};
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -843,16 +843,17 @@ TabChild::InitTabChildGlobal()
   nsContentUtils::XPConnect()->SetSecurityManagerForJSContext(cx, nsContentUtils::GetSecurityManager(), 0);
   nsContentUtils::GetSecurityManager()->GetSystemPrincipal(getter_AddRefs(mPrincipal));
 
   JS_SetNativeStackQuota(cx, 128 * sizeof(size_t) * 1024);
   JS_SetScriptStackQuota(cx, 25 * sizeof(size_t) * 1024 * 1024);
 
   JS_SetOptions(cx, JS_GetOptions(cx) | JSOPTION_JIT | JSOPTION_ANONFUNFIX | JSOPTION_PRIVATE_IS_NSISUPPORTS);
   JS_SetVersion(cx, JSVERSION_LATEST);
+  JS_SetErrorReporter(cx, ContentScriptErrorReporter);
 
   xpc_LocalizeContext(cx);
 
   JSAutoRequest ar(cx);
   nsIXPConnect* xpc = nsContentUtils::XPConnect();
   const PRUint32 flags = nsIXPConnect::INIT_JS_STANDARD_CLASSES |
                          /*nsIXPConnect::OMIT_COMPONENTS_OBJECT ?  |*/
                          nsIXPConnect::FLAG_SYSTEM_GLOBAL_OBJECT;
--- a/dom/plugins/base/Makefile.in
+++ b/dom/plugins/base/Makefile.in
@@ -49,17 +49,16 @@ IS_COMPONENT    = 1
 MODULE_NAME	= nsPluginModule
 GRE_MODULE	= 1
 LIBXUL_LIBRARY = 1
 
 EXPORTS_NAMESPACES = mozilla
 
 XPIDLSRCS = \
   nsIHTTPHeaderListener.idl \
-  nsIPlugin.idl \
   nsIPluginDocument.idl \
   nsIPluginHost.idl \
   nsIPluginInputStream.idl \
   nsIPluginInstance.idl \
   nsIPluginInstanceOwner.idl \
   nsIPluginStreamInfo.idl \
   nsIPluginStreamListener.idl \
   nsIPluginTag.idl \
@@ -89,17 +88,17 @@ CPPSRCS		= \
 		nsPluginStreamListenerPeer.cpp \
 		nsPluginHost.cpp \
 		nsPluginModule.cpp \
 		nsJSNPRuntime.cpp \
 		nsPluginTags.cpp \
 		PluginPRLibrary.cpp \
 		$(NULL)
 
-ifneq (,$(filter WINNT WINCE,$(OS_ARCH)))
+ifeq ($(OS_ARCH),WINNT)
 	CPPSRCS += nsPluginsDirWin.cpp
 	CPPSRCS += nsPluginNativeWindowWin.cpp
 	CPPSRCS += nsPluginDirServiceProvider.cpp
 	LOCAL_INCLUDES += -I$(topsrcdir)/xpcom/base
 else
 ifeq ($(MOZ_WIDGET_TOOLKIT),os2)
 	CPPSRCS += nsPluginsDirOS2.cpp
 	CPPSRCS += nsPluginNativeWindowOS2.cpp
deleted file mode 100644
--- a/dom/plugins/base/nsIPlugin.idl
+++ /dev/null
@@ -1,69 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either 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 "nsISupports.idl"
-#include "nspluginroot.idl"
-
-%{C++
-#include "npapi.h"
-
-#define MOZ_PLUGIN_CONTRACTID \
-  "@mozilla.org/plugin/plugin;1"
-%}
-
-interface nsIPluginInstance;
-
-[uuid(94C32FEA-5C50-49D3-9D3D-9047CD342777)]
-interface nsIPlugin : nsISupports
-{
-  /**
-   * Creates a new plugin instance, based on a MIME type. This
-   * allows different impelementations to be created depending on
-   * the specified MIME type.
-   */
-  void createPluginInstance(out nsIPluginInstance aResult);
-
-  /**
-   * Called when the browser is done with the plugin factory, or when
-   * the plugin is disabled by the user.
-   *
-   * (Corresponds to NPP_Shutdown.)
-   *
-   * @result - NS_OK if this operation was successful
-   */
-  void shutdown();
-};
--- a/dom/plugins/base/nsIPluginHost.idl
+++ b/dom/plugins/base/nsIPluginHost.idl
@@ -50,26 +50,25 @@
 #include "nsNetUtil.h"
 #endif
 #include "prlink.h"  // for PRLibrary
 
 #define MOZ_PLUGIN_HOST_CONTRACTID \
   "@mozilla.org/plugin/host;1"
 %}
 
-interface nsIPlugin;
 interface nsIURI;
 interface nsIDOMPlugin;
 interface nsIChannel;
 interface nsIPluginStreamListener;
 
 [ptr] native PRLibraryPtr(PRLibrary);
 [ptr] native nsPluginNativeWindowPtr(nsPluginNativeWindow);
 
-[scriptable, uuid(0BB66261-4114-4D73-8DFC-C3CA997E6817)]
+[scriptable, uuid(FB2E7827-1E7D-4DCC-93A8-94098A4B588D)]
 interface nsIPluginHost : nsISupports
 {
   [noscript] void init();
 
   [noscript] void destroy();
 
   [noscript] void loadPlugins();
 
@@ -77,18 +76,16 @@ interface nsIPluginHost : nsISupports
    * Causes the plugins directory to be searched again for new plugin 
    * libraries.
    *
    * @param reloadPages - indicates whether currently visible pages should 
    * also be reloaded
    */
   void reloadPlugins(in boolean reloadPages);
 
-  [noscript] nsIPlugin getPlugin(in string aMimeType);
-
   /**
    * Instantiate an embedded plugin for an existing channel. The caller is
    * responsible for opening the channel. It may or may not be already opened
    * when this function is called.
    */
   [noscript] nsIStreamListener instantiatePluginForChannel(in nsIChannel aChannel, in nsIPluginInstanceOwner aOwner);
 
   [noscript] void setUpPluginInstance(in string aMimeType, in nsIURI aURL, in nsIPluginInstanceOwner aOwner);
--- a/dom/plugins/base/nsIPluginInstanceOwner.idl
+++ b/dom/plugins/base/nsIPluginInstanceOwner.idl
@@ -32,17 +32,16 @@
  * 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 "nsISupports.idl"
 #include "nspluginroot.idl"
-#include "nsIPlugin.idl"
 #include "nsIInputStream.idl"
 
 interface nsIPluginInstance;
 interface nsIDocument;
 
 %{C++
 #include "npapi.h"
 class nsPluginEvent;
--- a/dom/plugins/base/nsNPAPIPlugin.cpp
+++ b/dom/plugins/base/nsNPAPIPlugin.cpp
@@ -228,17 +228,17 @@ static void CheckClassInitialized()
   if (!sPluginThreadAsyncCallLock)
     sPluginThreadAsyncCallLock = new Mutex("nsNPAPIPlugin.sPluginThreadAsyncCallLock");
 
   initialized = PR_TRUE;
 
   NPN_PLUGIN_LOG(PLUGIN_LOG_NORMAL,("NPN callbacks initialized\n"));
 }
 
-NS_IMPL_ISUPPORTS1(nsNPAPIPlugin, nsIPlugin)
+NS_IMPL_ISUPPORTS0(nsNPAPIPlugin)
 
 nsNPAPIPlugin::nsNPAPIPlugin()
 {
   memset((void*)&mPluginFuncs, 0, sizeof(mPluginFuncs));
   mPluginFuncs.size = sizeof(mPluginFuncs);
   mPluginFuncs.version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;
 
   mLibrary = nsnull;
@@ -529,17 +529,17 @@ nsNPAPIPlugin::GetLibrary()
 }
 
 NPPluginFuncs*
 nsNPAPIPlugin::PluginFuncs()
 {
   return &mPluginFuncs;
 }
 
-NS_IMETHODIMP
+nsresult
 nsNPAPIPlugin::CreatePluginInstance(nsIPluginInstance **aResult)
 {
   if (!aResult)
     return NS_ERROR_NULL_POINTER;
 
   *aResult = NULL;
 
   nsRefPtr<nsNPAPIPluginInstance> inst = new nsNPAPIPluginInstance(this);
@@ -620,17 +620,17 @@ MakeNewNPAPIStreamInternal(NPP npp, cons
   if (listener) {
     // SetCallNotify(bDoNotify) here, see comment above.
     static_cast<nsNPAPIPluginStreamListener*>(listener.get())->SetCallNotify(bDoNotify);
   }
 
   return NPERR_NO_ERROR;
 }
 
-#if defined(MOZ_MEMORY_WINDOWS) && !defined(MOZ_MEMORY_WINCE)
+#if defined(MOZ_MEMORY_WINDOWS)
 extern "C" size_t malloc_usable_size(const void *ptr);
 #endif
 
 namespace {
 
 static char *gNPPException;
 
 // A little helper class used to wrap up plugin manager streams (that is,
@@ -733,17 +733,17 @@ doGetIdentifier(JSContext *cx, const NPU
                                        utf16name.Length());
 
   if (!str)
     return NULL;
 
   return StringToNPIdentifier(str);
 }
 
-#if defined(MOZ_MEMORY_WINDOWS) && !defined(MOZ_MEMORY_WINCE)
+#if defined(MOZ_MEMORY_WINDOWS)
 BOOL
 InHeap(HANDLE hHeap, LPVOID lpMem)
 {
   BOOL success = FALSE;
   PROCESS_HEAP_ENTRY he;
   he.lpData = NULL;
   while (HeapWalk(hHeap, &he) != 0) {
     if (he.lpData == lpMem) {
@@ -1914,17 +1914,17 @@ void NP_CALLBACK
   case NPVariantType_Int32 :
   case NPVariantType_Double :
     break;
   case NPVariantType_String :
     {
       const NPString *s = &NPVARIANT_TO_STRING(*variant);
 
       if (s->UTF8Characters) {
-#if defined(MOZ_MEMORY_WINDOWS) && !defined(MOZ_MEMORY_WINCE)
+#if defined(MOZ_MEMORY_WINDOWS)
         if (malloc_usable_size((void *)s->UTF8Characters) != 0) {
           PR_Free((void *)s->UTF8Characters);
         } else {
           void *p = (void *)s->UTF8Characters;
           DWORD nheaps = 0;
           nsAutoTArray<HANDLE, 50> heaps;
           nheaps = GetProcessHeaps(0, heaps.Elements());
           heaps.AppendElements(nheaps);
@@ -2220,54 +2220,21 @@ NPError NP_CALLBACK
   }
 
   case NPNVsupportsUpdatedCocoaTextInputBool: {
     *(NPBool*)result = true;
     return NPERR_NO_ERROR;
   }
 #endif
 
-  // we no longer hand out any XPCOM objects, except on WINCE,
-  // where it's needed for the ActiveX shunt that makes Flash
-  // work until we get an NPAPI plugin there.
-#ifdef WINCE
-  case NPNVDOMWindow: {
-    nsNPAPIPluginInstance *inst = (nsNPAPIPluginInstance *)npp->ndata;
-    NS_ENSURE_TRUE(inst, NPERR_GENERIC_ERROR);
-
-    nsIDOMWindow *domWindow = inst->GetDOMWindow().get();
-
-    if (domWindow) {
-      // Pass over ownership of domWindow to the caller.
-      (*(nsIDOMWindow**)result) = domWindow;
-      return NPERR_NO_ERROR;
-    }
-
-    return NPERR_GENERIC_ERROR;
-  }
-
-  case NPNVDOMElement: {
-    nsNPAPIPluginInstance *inst = (nsNPAPIPluginInstance *) npp->ndata;
-    NS_ENSURE_TRUE(inst, NPERR_GENERIC_ERROR);
-
-    nsCOMPtr<nsIDOMElement> e;
-    inst->GetDOMElement(getter_AddRefs(e));
-    if (e) {
-      NS_ADDREF(*(nsIDOMElement**)result = e.get());
-      return NPERR_NO_ERROR;
-    }
-
-    return NPERR_GENERIC_ERROR;
-  }
-#else
+  // we no longer hand out any XPCOM objects
   case NPNVDOMElement:
     // fall through
   case NPNVDOMWindow:
     // fall through
-#endif /* WINCE */
   case NPNVserviceManager:
     // old XPCOM objects, no longer supported, but null out the out
     // param to avoid crashing plugins that still try to use this.
     *(nsISupports**)result = nsnull;
     // fall through
   default:
     return NPERR_GENERIC_ERROR;
   }
--- a/dom/plugins/base/nsNPAPIPlugin.h
+++ b/dom/plugins/base/nsNPAPIPlugin.h
@@ -33,17 +33,16 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef nsNPAPIPlugin_h_
 #define nsNPAPIPlugin_h_
 
-#include "nsIPlugin.h"
 #include "prlink.h"
 #include "npfunctions.h"
 #include "nsPluginHost.h"
 
 #include "jsapi.h"
 
 #include "mozilla/PluginLibrary.h"
 
@@ -67,27 +66,26 @@
 #define NS_NPAPIPLUGIN_CALLBACK(_type, _name) _type (* _name)
 #endif
 
 typedef NS_NPAPIPLUGIN_CALLBACK(NPError, NP_GETENTRYPOINTS) (NPPluginFuncs* pCallbacks);
 typedef NS_NPAPIPLUGIN_CALLBACK(NPError, NP_PLUGININIT) (const NPNetscapeFuncs* pCallbacks);
 typedef NS_NPAPIPLUGIN_CALLBACK(NPError, NP_PLUGINUNIXINIT) (const NPNetscapeFuncs* pCallbacks, NPPluginFuncs* fCallbacks);
 typedef NS_NPAPIPLUGIN_CALLBACK(NPError, NP_PLUGINSHUTDOWN) ();
 
-class nsNPAPIPlugin : public nsIPlugin
+class nsNPAPIPlugin : public nsISupports
 {
 private:
   typedef mozilla::PluginLibrary PluginLibrary;
 
 public:
   nsNPAPIPlugin();
   virtual ~nsNPAPIPlugin();
 
   NS_DECL_ISUPPORTS
-  NS_DECL_NSIPLUGIN
 
   // Constructs and initializes an nsNPAPIPlugin object. A NULL file path
   // will prevent this from calling NP_Initialize.
   static nsresult CreatePlugin(nsPluginTag *aPluginTag, nsNPAPIPlugin** aResult);
 
   PluginLibrary* GetLibrary();
   // PluginFuncs() can't fail but results are only valid if GetLibrary() succeeds
   NPPluginFuncs* PluginFuncs();
@@ -100,16 +98,19 @@ public:
   // crashes and is no longer usable. pluginDumpID/browserDumpID are
   // the IDs of respective minidumps that were written, or empty if no
   // minidump was written.
   void PluginCrashed(const nsAString& pluginDumpID,
                      const nsAString& browserDumpID);
   
   static PRBool RunPluginOOP(const nsPluginTag *aPluginTag);
 
+  nsresult CreatePluginInstance(nsIPluginInstance **aResult);
+  nsresult Shutdown();
+
 protected:
   NPPluginFuncs mPluginFuncs;
   PluginLibrary* mLibrary;
 };
 
 namespace mozilla {
 namespace plugins {
 namespace parent {
--- a/dom/plugins/base/nsPluginDirServiceProvider.cpp
+++ b/dom/plugins/base/nsPluginDirServiceProvider.cpp
@@ -84,22 +84,17 @@ GetFileVersion(LPCWSTR szFile, verBlock 
   DWORD             dwHandle;
   LPVOID            lpData;
   LPVOID            lpBuffer;
   VS_FIXEDFILEINFO  *lpBuffer2;
 
   ClearVersion(vbVersion);
   if (FileExists(szFile)) {
     bRv    = TRUE;
-#ifdef WINCE
-    // WinCe takes a non const file path string, while desktop take a const
-    LPWSTR lpFilepath = const_cast<LPWSTR>(szFile);
-#else
     LPCWSTR lpFilepath = szFile;
-#endif
     dwLen  = GetFileVersionInfoSizeW(lpFilepath, &dwHandle);
     lpData = (LPVOID)malloc(dwLen);
     uLen   = 0;
 
     if (lpData && GetFileVersionInfoW(lpFilepath, dwHandle, dwLen, lpData) != 0) {
       if (VerQueryValueW(lpData, L"\\", &lpBuffer, &uLen) != 0) {
         lpBuffer2 = (VS_FIXEDFILEINFO *)lpBuffer;
 
--- a/dom/plugins/base/nsPluginHost.cpp
+++ b/dom/plugins/base/nsPluginHost.cpp
@@ -44,17 +44,16 @@
 #include "nsPluginHost.h"
 
 #include <stdio.h>
 #include "prio.h"
 #include "prmem.h"
 #include "nsIComponentManager.h"
 #include "nsNPAPIPlugin.h"
 #include "nsNPAPIPluginStreamListener.h"
-#include "nsIPlugin.h"
 #include "nsNPAPIPluginInstance.h"
 #include "nsIPluginStreamListener.h"
 #include "nsIHTTPHeaderListener.h"
 #include "nsIHttpHeaderVisitor.h"
 #include "nsIObserverService.h"
 #include "nsIHttpProtocolHandler.h"
 #include "nsIHttpChannel.h"
 #include "nsIHttpChannelInternal.h"
@@ -1318,22 +1317,22 @@ nsPluginHost::TrySetUpPluginInstance(con
     }
   }
   else {
     mimetype = aMimeType;
   }
 
   NS_ASSERTION(pluginTag, "Must have plugin tag here!");
 
-  nsCOMPtr<nsIPlugin> plugin;
+  nsRefPtr<nsNPAPIPlugin> plugin;
   GetPlugin(mimetype, getter_AddRefs(plugin));
 
   nsCOMPtr<nsIPluginInstance> instance;
   if (plugin) {
-#if defined(XP_WIN) && !defined(WINCE)
+#if defined(XP_WIN)
     static BOOL firstJavaPlugin = FALSE;
     BOOL restoreOrigDir = FALSE;
     WCHAR origDir[_MAX_PATH];
     if (pluginTag->mIsJavaPlugin && !firstJavaPlugin) {
       DWORD dw = GetCurrentDirectoryW(_MAX_PATH, origDir);
       NS_ASSERTION(dw <= _MAX_PATH, "Failed to obtain the current directory, which may lead to incorrect class loading");
       nsCOMPtr<nsIFile> binDirectory;
       rv = NS_GetSpecialDirectory(NS_XPCOM_CURRENT_PROCESS_DIR,
@@ -1344,17 +1343,17 @@ nsPluginHost::TrySetUpPluginInstance(con
         binDirectory->GetPath(path);
         restoreOrigDir = SetCurrentDirectoryW(path.get());
       }
     }
 #endif
 
     rv = plugin->CreatePluginInstance(getter_AddRefs(instance));
 
-#if defined(XP_WIN) && !defined(WINCE)
+#if defined(XP_WIN)
     if (!firstJavaPlugin && restoreOrigDir) {
       BOOL bCheck = SetCurrentDirectoryW(origDir);
       NS_ASSERTION(bCheck, "Error restoring directory");
       firstJavaPlugin = TRUE;
     }
 #endif
   }
 
@@ -1449,21 +1448,19 @@ nsPluginHost::IsPluginEnabledForExtensio
 class DOMMimeTypeImpl : public nsIDOMMimeType {
 public:
   NS_DECL_ISUPPORTS
 
   DOMMimeTypeImpl(nsPluginTag* aTag, PRUint32 aMimeTypeIndex)
   {
     if (!aTag)
       return;
-    CopyUTF8toUTF16(aTag->mMimeDescriptionArray[aMimeTypeIndex], mDescription);
-    if (aTag->mExtensionsArray)
-      CopyUTF8toUTF16(aTag->mExtensionsArray[aMimeTypeIndex], mSuffixes);
-    if (aTag->mMimeTypeArray)
-      CopyUTF8toUTF16(aTag->mMimeTypeArray[aMimeTypeIndex], mType);
+    CopyUTF8toUTF16(aTag->mMimeDescriptions[aMimeTypeIndex], mDescription);
+    CopyUTF8toUTF16(aTag->mExtensions[aMimeTypeIndex], mSuffixes);
+    CopyUTF8toUTF16(aTag->mMimeTypes[aMimeTypeIndex], mType);
   }
 
   virtual ~DOMMimeTypeImpl() {
   }
 
   NS_METHOD GetDescription(nsAString& aDescription)
   {
     aDescription.Assign(mDescription);
@@ -1538,32 +1535,32 @@ public:
   NS_METHOD GetName(nsAString& aName)
   {
     CopyUTF8toUTF16(mPluginTag.mName, aName);
     return NS_OK;
   }
 
   NS_METHOD GetLength(PRUint32* aLength)
   {
-    *aLength = mPluginTag.mVariants;
+    *aLength = mPluginTag.mMimeTypes.Length();
     return NS_OK;
   }
 
   NS_METHOD Item(PRUint32 aIndex, nsIDOMMimeType** aReturn)
   {
     nsIDOMMimeType* mimeType = new DOMMimeTypeImpl(&mPluginTag, aIndex);
     NS_IF_ADDREF(mimeType);
     *aReturn = mimeType;
     return NS_OK;
   }
 
   NS_METHOD NamedItem(const nsAString& aName, nsIDOMMimeType** aReturn)
   {
-    for (int i = mPluginTag.mVariants - 1; i >= 0; --i) {
-      if (aName.Equals(NS_ConvertUTF8toUTF16(mPluginTag.mMimeTypeArray[i])))
+    for (int i = mPluginTag.mMimeTypes.Length() - 1; i >= 0; --i) {
+      if (aName.Equals(NS_ConvertUTF8toUTF16(mPluginTag.mMimeTypes[i])))
         return Item(i, aReturn);
     }
     return NS_OK;
   }
 
 private:
   nsPluginTag mPluginTag;
 };
@@ -1645,59 +1642,52 @@ nsPluginHost::FindPluginForType(const ch
     return nsnull;
   }
 
   LoadPlugins();
 
   nsPluginTag *plugin = mPlugins;
   while (plugin) {
     if (!aCheckEnabled || plugin->IsEnabled()) {
-      PRInt32 mimeCount = plugin->mVariants;
+      PRInt32 mimeCount = plugin->mMimeTypes.Length();
       for (PRInt32 i = 0; i < mimeCount; i++) {
-        if (plugin->mMimeTypeArray[i] &&
-            (0 == PL_strcasecmp(plugin->mMimeTypeArray[i], aMimeType))) {
+        if (0 == PL_strcasecmp(plugin->mMimeTypes[i].get(), aMimeType)) {
           return plugin;
         }
       }
     }
     plugin = plugin->mNext;
   }
 
   return nsnull;
 }
 
 nsPluginTag*
 nsPluginHost::FindPluginEnabledForExtension(const char* aExtension,
                                             const char*& aMimeType)
 {
-  nsPluginTag *plugins = nsnull;
-  PRInt32     variants, cnt;
+  if (!aExtension) {
+    return nsnull;
+  }
 
   LoadPlugins();
 
-  // if we have a mimetype passed in, search the mPlugins linked
-  // list for a match
-  if (aExtension) {
-    plugins = mPlugins;
-    while (plugins) {
-      variants = plugins->mVariants;
-      if (plugins->mExtensionsArray) {
-        for (cnt = 0; cnt < variants; cnt++) {
-          // mExtensionsArray[cnt] is a list of extensions separated
-          // by commas
-          if (plugins->IsEnabled() &&
-              0 == CompareExtensions(plugins->mExtensionsArray[cnt], aExtension)) {
-            aMimeType = plugins->mMimeTypeArray[cnt];
-            return plugins;
-          }
+  nsPluginTag *plugin = mPlugins;
+  while (plugin) {
+    if (plugin->IsEnabled()) {
+      PRInt32 variants = plugin->mExtensions.Length();
+      for (PRInt32 i = 0; i < variants; i++) {
+        // mExtensionsArray[cnt] is a list of extensions separated by commas
+        if (0 == CompareExtensions(plugin->mExtensions[i].get(), aExtension)) {
+          aMimeType = plugin->mMimeTypes[i].get();
+          return plugin;
         }
       }
-
-      plugins = plugins->mNext;
     }
+    plugin = plugin->mNext;
   }
 
   return nsnull;
 }
 
 static nsresult CreateNPAPIPlugin(nsPluginTag *aPluginTag,
                                   nsNPAPIPlugin **aOutNPAPIPlugin)
 {
@@ -1730,17 +1720,17 @@ nsresult nsPluginHost::EnsurePluginLoade
     if (NS_FAILED(rv)) {
       return rv;
     }
     plugin->mEntryPoint = entrypoint;
   }
   return NS_OK;
 }
 
-NS_IMETHODIMP nsPluginHost::GetPlugin(const char *aMimeType, nsIPlugin** aPlugin)
+nsresult nsPluginHost::GetPlugin(const char *aMimeType, nsNPAPIPlugin** aPlugin)
 {
   nsresult rv = NS_ERROR_FAILURE;
   *aPlugin = NULL;
 
   if (!aMimeType)
     return NS_ERROR_ILLEGAL_VALUE;
 
   // If plugins haven't been scanned yet, do so now
@@ -2674,62 +2664,62 @@ nsPluginHost::WritePluginInfo()
     for (nsPluginTag *tag = taglist[i]; tag; tag=tag->mNext) {
       // from mCachedPlugins list write down only unwanted plugins
       if ((taglist[i] == mCachedPlugins) && !tag->HasFlag(NS_PLUGIN_FLAG_UNWANTED))
         continue;
       // store each plugin info into the registry
       // filename & fullpath are on separate line
       // because they can contain field delimiter char
       PR_fprintf(fd, "%s%c%c\n%s%c%c\n%s%c%c\n",
-        (!tag->mFileName.IsEmpty() ? tag->mFileName.get() : ""),
+        (tag->mFileName.get()),
         PLUGIN_REGISTRY_FIELD_DELIMITER,
         PLUGIN_REGISTRY_END_OF_LINE_MARKER,
-        (!tag->mFullPath.IsEmpty() ? tag->mFullPath.get() : ""),
+        (tag->mFullPath.get()),
         PLUGIN_REGISTRY_FIELD_DELIMITER,
         PLUGIN_REGISTRY_END_OF_LINE_MARKER,
-        (!tag->mVersion.IsEmpty() ? tag->mVersion.get() : ""),
+        (tag->mVersion.get()),
         PLUGIN_REGISTRY_FIELD_DELIMITER,
         PLUGIN_REGISTRY_END_OF_LINE_MARKER);
 
       // lastModifiedTimeStamp|canUnload|tag->mFlags
       PR_fprintf(fd, "%lld%c%d%c%lu%c%c\n",
         tag->mLastModifiedTime,
         PLUGIN_REGISTRY_FIELD_DELIMITER,
         tag->mCanUnloadLibrary,
         PLUGIN_REGISTRY_FIELD_DELIMITER,
         tag->Flags(),
         PLUGIN_REGISTRY_FIELD_DELIMITER,
         PLUGIN_REGISTRY_END_OF_LINE_MARKER);
 
       //description, name & mtypecount are on separate line
       PR_fprintf(fd, "%s%c%c\n%s%c%c\n%d\n",
-        (!tag->mDescription.IsEmpty() ? tag->mDescription.get() : ""),
+        (tag->mDescription.get()),
         PLUGIN_REGISTRY_FIELD_DELIMITER,
         PLUGIN_REGISTRY_END_OF_LINE_MARKER,
-        (!tag->mName.IsEmpty() ? tag->mName.get() : ""),
+        (tag->mName.get()),
         PLUGIN_REGISTRY_FIELD_DELIMITER,
         PLUGIN_REGISTRY_END_OF_LINE_MARKER,
-        tag->mVariants + (tag->mIsNPRuntimeEnabledJavaPlugin ? 1 : 0));
+        tag->mMimeTypes.Length() + (tag->mIsNPRuntimeEnabledJavaPlugin ? 1 : 0));
 
       // Add in each mimetype this plugin supports
-      for (int i=0; i<tag->mVariants; i++) {
+      for (PRUint32 i = 0; i < tag->mMimeTypes.Length(); i++) {
         PR_fprintf(fd, "%d%c%s%c%s%c%s%c%c\n",
           i,PLUGIN_REGISTRY_FIELD_DELIMITER,
-          (tag->mMimeTypeArray && tag->mMimeTypeArray[i] ? tag->mMimeTypeArray[i] : ""),
+          (tag->mMimeTypes[i].get()),
           PLUGIN_REGISTRY_FIELD_DELIMITER,
-          (!tag->mMimeDescriptionArray[i].IsEmpty() ? tag->mMimeDescriptionArray[i].get() : ""),
+          (tag->mMimeDescriptions[i].get()),
           PLUGIN_REGISTRY_FIELD_DELIMITER,
-          (tag->mExtensionsArray && tag->mExtensionsArray[i] ? tag->mExtensionsArray[i] : ""),
+          (tag->mExtensions[i].get()),
           PLUGIN_REGISTRY_FIELD_DELIMITER,
           PLUGIN_REGISTRY_END_OF_LINE_MARKER);
       }
 
       if (tag->mIsNPRuntimeEnabledJavaPlugin) {
         PR_fprintf(fd, "%d%c%s%c%s%c%s%c%c\n",
-          tag->mVariants, PLUGIN_REGISTRY_FIELD_DELIMITER,
+          tag->mMimeTypes.Length(), PLUGIN_REGISTRY_FIELD_DELIMITER,
           "application/x-java-vm-npruntime",
           PLUGIN_REGISTRY_FIELD_DELIMITER,
           "",
           PLUGIN_REGISTRY_FIELD_DELIMITER,
           "",
           PLUGIN_REGISTRY_FIELD_DELIMITER,
           PLUGIN_REGISTRY_END_OF_LINE_MARKER);
       }
--- a/dom/plugins/base/nsPluginHost.h
+++ b/dom/plugins/base/nsPluginHost.h
@@ -41,17 +41,16 @@
 
 #include "nsIPluginHost.h"
 #include "nsIObserver.h"
 #include "nsCOMPtr.h"
 #include "prlink.h"
 #include "prclist.h"
 #include "npapi.h"
 #include "nsNPAPIPluginInstance.h"
-#include "nsIPlugin.h"
 #include "nsIPluginTag.h"
 #include "nsPluginsDir.h"
 #include "nsPluginDirServiceProvider.h"
 #include "nsAutoPtr.h"
 #include "nsWeakPtr.h"
 #include "nsIPrompt.h"
 #include "nsISupportsArray.h"
 #include "nsIPrefBranch.h"
@@ -173,16 +172,18 @@ public:
   nsresult InstantiateFullPagePlugin(const char *aMimeType,
                                      nsIURI* aURI,
                                      nsIPluginInstanceOwner *aOwner,
                                      nsIStreamListener **aStreamListener);
 
   // Does not accept NULL and should never fail.
   nsPluginTag* TagForPlugin(nsNPAPIPlugin* aPlugin);
 
+  nsresult GetPlugin(const char *aMimeType, nsNPAPIPlugin** aPlugin);
+
 private:
   nsresult
   TrySetUpPluginInstance(const char *aMimeType, nsIURI *aURL, nsIPluginInstanceOwner *aOwner);
 
   nsresult
   NewEmbeddedPluginStreamListener(nsIURI* aURL, nsIPluginInstanceOwner *aOwner,
                                   nsNPAPIPluginInstance* aInstance,
                                   nsIStreamListener** aListener);
--- a/dom/plugins/base/nsPluginNativeWindowWin.cpp
+++ b/dom/plugins/base/nsPluginNativeWindowWin.cpp
@@ -141,20 +141,18 @@ typedef enum {
 class nsPluginNativeWindowWin : public nsPluginNativeWindow {
 public: 
   nsPluginNativeWindowWin();
   virtual ~nsPluginNativeWindowWin();
 
   virtual nsresult CallSetWindow(nsCOMPtr<nsIPluginInstance> &aPluginInstance);
 
 private:
-#ifndef WINCE
   nsresult SubclassAndAssociateWindow();
   nsresult UndoSubclassAndAssociateWindow();
-#endif
 
 public:
   // locals
   WNDPROC GetPrevWindowProc();
   void SetPrevWindowProc(WNDPROC proc) { mPluginWinProc = proc; }
   WNDPROC GetWindowProc();
   PluginWindowEvent * GetPluginWindowEvent(HWND aWnd,
                                            UINT aMsg,
@@ -283,17 +281,16 @@ static LRESULT CALLBACK PluginWndProcInt
       }
 
       // fall through
     case WM_KEYUP:
       enablePopups = PR_TRUE;
 
       break;
 
-#ifndef WINCE
     case WM_MOUSEACTIVATE: {
       // If a child window of this plug-in is already focused,
       // don't focus the parent to avoid focus dance. We'll 
       // receive a follow up WM_SETFOCUS which will notify
       // the appropriate window anyway.
       HWND focusedWnd = ::GetFocus();
       if (!::IsChild((HWND)win->window, focusedWnd)) {
         // Notify the dom / focus manager the plugin has focus when one of
@@ -327,17 +324,16 @@ static LRESULT CALLBACK PluginWndProcInt
       WNDPROC prevWndProc = win->GetPrevWindowProc();
       if (prevWndProc && !sInPreviousMessageDispatch) {
         sInPreviousMessageDispatch = PR_TRUE;
         ::CallWindowProc(prevWndProc, hWnd, msg, wParam, lParam);
         sInPreviousMessageDispatch = PR_FALSE;
       }
       break;
     }
-#endif
   }
 
   // Macromedia Flash plugin may flood the message queue with some special messages
   // (WM_USER+1) causing 100% CPU consumption and GUI freeze, see mozilla bug 132759;
   // we can prevent this from happening by delaying the processing such messages;
   if (win->mPluginType == nsPluginType_Flash) {
     if (ProcessFlashMessageDelayed(win, inst, hWnd, msg, wParam, lParam))
       return TRUE;
@@ -648,18 +644,16 @@ nsresult nsPluginNativeWindowWin::CallSe
         mPluginType = nsPluginType_Real;
       else if (!strcmp(mimetype, "application/pdf"))
         mPluginType = nsPluginType_PDF;
       else
         mPluginType = nsPluginType_Other;
     }
   }
 
-  // WINCE does not subclass windows.  See bug 300011 for the details.
-#ifndef WINCE
   if (window) {
     // grab the widget procedure before the plug-in does a subclass in
     // setwindow. We'll use this in PluginWndProc for forwarding focus
     // events to the widget.
     WNDPROC currentWndProc =
       (WNDPROC)::GetWindowLongPtr((HWND)window, GWLP_WNDPROC);
     if (!mPrevWinProc && currentWndProc != PluginWndProc)
       mPrevWinProc = currentWndProc;
@@ -670,34 +664,29 @@ nsresult nsPluginNativeWindowWin::CallSe
       HWND parent = ::GetParent((HWND)window);
       if (mParentWnd != parent) {
         NS_ASSERTION(!mParentWnd, "Plugin's parent window changed");
         mParentWnd = parent;
         mParentProc = ::GetWindowLongPtr(mParentWnd, GWLP_WNDPROC);
       }
     }
   }
-#endif
 
   nsPluginNativeWindow::CallSetWindow(aPluginInstance);
 
-#ifndef WINCE
   SubclassAndAssociateWindow();
 
   if (window && mPluginType == nsPluginType_Flash &&
       !GetPropW((HWND)window, L"PluginInstanceParentProperty")) {
     HookSetWindowLongPtr();
   }
-#endif
 
   return NS_OK;
 }
 
-#ifndef WINCE
-
 nsresult nsPluginNativeWindowWin::SubclassAndAssociateWindow()
 {
   if (type != NPWindowTypeWindow || !window)
     return NS_ERROR_FAILURE;
 
   HWND hWnd = (HWND)window;
 
   // check if we need to subclass
@@ -769,17 +758,16 @@ nsresult nsPluginNativeWindowWin::UndoSu
   if (mPluginType == nsPluginType_PDF && mParentWnd) {
     ::SetWindowLongPtr(mParentWnd, GWLP_WNDPROC, mParentProc);
     mParentWnd = NULL;
     mParentProc = 0;
   }
 
   return NS_OK;
 }
-#endif // WINCE
 
 nsresult PLUG_NewPluginNativeWindow(nsPluginNativeWindow ** aPluginNativeWindow)
 {
   NS_ENSURE_ARG_POINTER(aPluginNativeWindow);
 
   *aPluginNativeWindow = new nsPluginNativeWindowWin();
 
   return *aPluginNativeWindow ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
--- a/dom/plugins/base/nsPluginSafety.h
+++ b/dom/plugins/base/nsPluginSafety.h
@@ -39,17 +39,17 @@
 #define nsPluginSafety_h_
 
 #include "npapi.h"
 #include "nsIPluginHost.h"
 #include "nsIPrefBranch.h"
 #include "nsIPrefService.h"
 #include <prinrval.h>
 
-#if defined(XP_WIN) && !defined(WINCE)
+#if defined(XP_WIN)
 #define CALL_SAFETY_ON
 #endif
 
 void NS_NotifyPluginCall(PRIntervalTime);
 
 #ifdef CALL_SAFETY_ON
 
 extern PRBool gSkipPluginSafeCalls;
--- a/dom/plugins/base/nsPluginTags.cpp
+++ b/dom/plugins/base/nsPluginTags.cpp
@@ -71,135 +71,116 @@ inline char* new_str(const char* str)
 }
 
 /* nsPluginTag */
 
 nsPluginTag::nsPluginTag(nsPluginTag* aPluginTag)
 : mPluginHost(nsnull),
 mName(aPluginTag->mName),
 mDescription(aPluginTag->mDescription),
-mVariants(aPluginTag->mVariants),
-mMimeTypeArray(nsnull),
-mMimeDescriptionArray(aPluginTag->mMimeDescriptionArray),
-mExtensionsArray(nsnull),
+mMimeTypes(aPluginTag->mMimeTypes),
+mMimeDescriptions(aPluginTag->mMimeDescriptions),
+mExtensions(aPluginTag->mExtensions),
 mLibrary(nsnull),
 mCanUnloadLibrary(PR_TRUE),
 mIsJavaPlugin(aPluginTag->mIsJavaPlugin),
 mIsNPRuntimeEnabledJavaPlugin(aPluginTag->mIsNPRuntimeEnabledJavaPlugin),
 mIsFlashPlugin(aPluginTag->mIsFlashPlugin),
 mFileName(aPluginTag->mFileName),
 mFullPath(aPluginTag->mFullPath),
 mVersion(aPluginTag->mVersion),
 mLastModifiedTime(0),
 mFlags(NS_PLUGIN_FLAG_ENABLED)
 {
-  if (aPluginTag->mMimeTypeArray != nsnull) {
-    mMimeTypeArray = new char*[mVariants];
-    for (int i = 0; i < mVariants; i++)
-      mMimeTypeArray[i] = new_str(aPluginTag->mMimeTypeArray[i]);
-  }
-  
-  if (aPluginTag->mExtensionsArray != nsnull) {
-    mExtensionsArray = new char*[mVariants];
-    for (int i = 0; i < mVariants; i++)
-      mExtensionsArray[i] = new_str(aPluginTag->mExtensionsArray[i]);
-  }
 }
 
 nsPluginTag::nsPluginTag(nsPluginInfo* aPluginInfo)
 : mPluginHost(nsnull),
 mName(aPluginInfo->fName),
 mDescription(aPluginInfo->fDescription),
-mVariants(aPluginInfo->fVariantCount),
-mMimeTypeArray(nsnull),
-mExtensionsArray(nsnull),
 mLibrary(nsnull),
 #ifdef XP_MACOSX
 mCanUnloadLibrary(PR_FALSE),
 #else
 mCanUnloadLibrary(PR_TRUE),
 #endif
 mIsJavaPlugin(PR_FALSE),
 mIsNPRuntimeEnabledJavaPlugin(PR_FALSE),
 mIsFlashPlugin(PR_FALSE),
 mFileName(aPluginInfo->fFileName),
 mFullPath(aPluginInfo->fFullPath),
 mVersion(aPluginInfo->fVersion),
 mLastModifiedTime(0),
 mFlags(NS_PLUGIN_FLAG_ENABLED)
 {
-  PRInt32 javaSentinelVariant = -1;
+  if (!aPluginInfo->fMimeTypeArray) {
+    return;
+  }
 
-  if (aPluginInfo->fMimeTypeArray) {
-    mMimeTypeArray = new char*[mVariants];
-    for (int i = 0; i < mVariants; i++) {
-      char* currentMIMEType = aPluginInfo->fMimeTypeArray[i];
-      if (!currentMIMEType) {
-        continue;
-      }
-
+  for (PRUint32 i = 0; i < aPluginInfo->fVariantCount; i++) {
+    // First fill in the MIME types.
+    char* currentMIMEType = aPluginInfo->fMimeTypeArray[i];
+    if (currentMIMEType) {
       if (mIsJavaPlugin) {
         if (strcmp(currentMIMEType, "application/x-java-vm-npruntime") == 0) {
           // This "magic MIME type" should not be exposed, but is just a signal
           // to the browser that this is new-style java.
-          // Remove it and its associated MIME description from our arrays.
+          // Don't add it or its associated information to our arrays.
           mIsNPRuntimeEnabledJavaPlugin = PR_TRUE;
-          javaSentinelVariant = i;
+          continue;
         }
       }
-
-      mMimeTypeArray[i] = new_str(currentMIMEType);
-
-      if (nsPluginHost::IsJavaMIMEType(mMimeTypeArray[i])) {
+      mMimeTypes.AppendElement(nsCString(currentMIMEType));
+      if (nsPluginHost::IsJavaMIMEType(currentMIMEType)) {
         mIsJavaPlugin = PR_TRUE;
       }
       else if (strcmp(currentMIMEType, "application/x-shockwave-flash") == 0) {
         mIsFlashPlugin = PR_TRUE;
       }
+    } else {
+      continue;
     }
-  }
 
-  if (aPluginInfo->fMimeDescriptionArray) {
-    for (int i = 0; i < mVariants; i++) {
+    // Now fill in the MIME descriptions.
+    if (aPluginInfo->fMimeDescriptionArray &&
+        aPluginInfo->fMimeDescriptionArray[i]) {
       // we should cut off the list of suffixes which the mime
       // description string may have, see bug 53895
       // it is usually in form "some description (*.sf1, *.sf2)"
       // so we can search for the opening round bracket
       char cur = '\0';
       char pre = '\0';
       char * p = PL_strrchr(aPluginInfo->fMimeDescriptionArray[i], '(');
       if (p && (p != aPluginInfo->fMimeDescriptionArray[i])) {
         if ((p - 1) && *(p - 1) == ' ') {
           pre = *(p - 1);
           *(p - 1) = '\0';
         } else {
           cur = *p;
           *p = '\0';
         }
-        
       }
-      mMimeDescriptionArray.AppendElement(
-                                          aPluginInfo->fMimeDescriptionArray[i]);
+      mMimeDescriptions.AppendElement(nsCString(aPluginInfo->fMimeDescriptionArray[i]));
       // restore the original string
       if (cur != '\0')
         *p = cur;
       if (pre != '\0')
-        *(p - 1) = pre;
+        *(p - 1) = pre;      
+    } else {
+      mMimeDescriptions.AppendElement(nsCString());
     }
-  } else {
-    mMimeDescriptionArray.SetLength(mVariants);
+
+    // Now fill in the extensions.
+    if (aPluginInfo->fExtensionArray &&
+        aPluginInfo->fExtensionArray[i]) {
+      mExtensions.AppendElement(nsCString(aPluginInfo->fExtensionArray[i]));
+    } else {
+      mExtensions.AppendElement(nsCString());
+    }
   }
-  
-  if (aPluginInfo->fExtensionArray != nsnull) {
-    mExtensionsArray = new char*[mVariants];
-    for (int i = 0; i < mVariants; i++)
-      mExtensionsArray[i] = new_str(aPluginInfo->fExtensionArray[i]);
-  }
-  
-  RemoveJavaSentinel(javaSentinelVariant);
 
   EnsureMembersAreUTF8();
 }
 
 nsPluginTag::nsPluginTag(const char* aName,
                          const char* aDescription,
                          const char* aFileName,
                          const char* aFullPath,
@@ -209,75 +190,47 @@ nsPluginTag::nsPluginTag(const char* aNa
                          const char* const* aExtensions,
                          PRInt32 aVariants,
                          PRInt64 aLastModifiedTime,
                          PRBool aCanUnload,
                          PRBool aArgsAreUTF8)
 : mPluginHost(nsnull),
 mName(aName),
 mDescription(aDescription),
-mVariants(aVariants),
-mMimeTypeArray(nsnull),
-mExtensionsArray(nsnull),
 mLibrary(nsnull),
 mCanUnloadLibrary(aCanUnload),
 mIsJavaPlugin(PR_FALSE),
 mIsNPRuntimeEnabledJavaPlugin(PR_FALSE),
 mFileName(aFileName),
 mFullPath(aFullPath),
 mVersion(aVersion),
 mLastModifiedTime(aLastModifiedTime),
 mFlags(0) // Caller will read in our flags from cache
 {
-  PRInt32 javaSentinelVariant = -1;
-
-  if (aVariants) {
-    mMimeTypeArray        = new char*[mVariants];
-    mExtensionsArray      = new char*[mVariants];
-    
-    for (PRInt32 i = 0; i < aVariants; ++i) {
-      if (mIsJavaPlugin && aMimeTypes[i] &&
-          strcmp(aMimeTypes[i], "application/x-java-vm-npruntime") == 0) {
-        mIsNPRuntimeEnabledJavaPlugin = PR_TRUE;
-        javaSentinelVariant = i;
-      }
-      
-      mMimeTypeArray[i]        = new_str(aMimeTypes[i]);
-      mMimeDescriptionArray.AppendElement(aMimeDescriptions[i]);
-      mExtensionsArray[i]      = new_str(aExtensions[i]);
-      if (nsPluginHost::IsJavaMIMEType(mMimeTypeArray[i]))
-        mIsJavaPlugin = PR_TRUE;
+  for (PRInt32 i = 0; i < aVariants; i++) {
+    if (mIsJavaPlugin && aMimeTypes[i] &&
+        strcmp(aMimeTypes[i], "application/x-java-vm-npruntime") == 0) {
+      mIsNPRuntimeEnabledJavaPlugin = PR_TRUE;
+      continue;
+    }
+    mMimeTypes.AppendElement(nsCString(aMimeTypes[i]));
+    mMimeDescriptions.AppendElement(nsCString(aMimeDescriptions[i]));
+    mExtensions.AppendElement(nsCString(aExtensions[i]));
+    if (nsPluginHost::IsJavaMIMEType(mMimeTypes[i].get())) {
+      mIsJavaPlugin = PR_TRUE;
     }
   }
 
-  RemoveJavaSentinel(javaSentinelVariant);
-
   if (!aArgsAreUTF8)
     EnsureMembersAreUTF8();
 }
 
 nsPluginTag::~nsPluginTag()
 {
   NS_ASSERTION(!mNext, "Risk of exhausting the stack space, bug 486349");
-  
-  if (mMimeTypeArray) {
-    for (int i = 0; i < mVariants; i++)
-      delete[] mMimeTypeArray[i];
-    
-    delete[] (mMimeTypeArray);
-    mMimeTypeArray = nsnull;
-  }
-  
-  if (mExtensionsArray) {
-    for (int i = 0; i < mVariants; i++)
-      delete[] mExtensionsArray[i];
-    
-    delete[] (mExtensionsArray);
-    mExtensionsArray = nsnull;
-  }
 }
 
 NS_IMPL_ISUPPORTS1(nsPluginTag, nsIPluginTag)
 
 static nsresult ConvertToUTF8(nsIUnicodeDecoder *aUnicodeDecoder,
                               nsAFlatCString& aString)
 {
   PRInt32 numberOfBytes = aString.Length();
@@ -329,18 +282,18 @@ nsresult nsPluginTag::EnsureMembersAreUT
   rv = pcs->GetCharset(kPlatformCharsetSel_PlainTextInFile, charset);
   NS_ENSURE_SUCCESS(rv, rv);
   if (!charset.LowerCaseEqualsLiteral("utf-8")) {
     rv = ccm->GetUnicodeDecoderRaw(charset.get(), getter_AddRefs(decoder));
     NS_ENSURE_SUCCESS(rv, rv);
     
     ConvertToUTF8(decoder, mName);
     ConvertToUTF8(decoder, mDescription);
-    for (PRUint32 i = 0; i < mMimeDescriptionArray.Length(); ++i) {
-      ConvertToUTF8(decoder, mMimeDescriptionArray[i]);
+    for (PRUint32 i = 0; i < mMimeDescriptions.Length(); ++i) {
+      ConvertToUTF8(decoder, mMimeDescriptions[i]);
     }
   }
   return NS_OK;
 #endif
 }
 
 void nsPluginTag::SetHost(nsPluginHost * aHost)
 {
@@ -425,19 +378,16 @@ nsPluginTag::SetBlocklisted(PRBool aBloc
   mPluginHost->UpdatePluginInfo(nsnull);
   return NS_OK;
 }
 
 void
 nsPluginTag::RegisterWithCategoryManager(PRBool aOverrideInternalTypes,
                                          nsPluginTag::nsRegisterType aType)
 {
-  if (!mMimeTypeArray)
-    return;
-  
   PLUGIN_LOG(PLUGIN_LOG_NORMAL,
              ("nsPluginTag::RegisterWithCategoryManager plugin=%s, removing = %s\n",
               mFileName.get(), aType == ePluginUnregister ? "yes" : "no"));
   
   nsCOMPtr<nsICategoryManager> catMan = do_GetService(NS_CATEGORYMANAGER_CONTRACTID);
   if (!catMan)
     return;
   
@@ -459,51 +409,50 @@ nsPluginTag::RegisterWithCategoryManager
   if (aType != ePluginUnregister) {
     psvc->GetCharPref("plugin.disable_full_page_plugin_for_types", getter_Copies(overrideTypes));
     overrideTypesFormatted.Assign(',');
     overrideTypesFormatted += overrideTypes;
     overrideTypesFormatted.Append(',');
   }
   
   nsACString::const_iterator start, end;
-  for (int i = 0; i < mVariants; i++) {
+  for (PRUint32 i = 0; i < mMimeTypes.Length(); i++) {
     if (aType == ePluginUnregister) {
       nsXPIDLCString value;
       if (NS_SUCCEEDED(catMan->GetCategoryEntry("Gecko-Content-Viewers",
-                                                mMimeTypeArray[i],
+                                                mMimeTypes[i].get(),
                                                 getter_Copies(value)))) {
         // Only delete the entry if a plugin registered for it
         if (strcmp(value, contractId) == 0) {
           catMan->DeleteCategoryEntry("Gecko-Content-Viewers",
-                                      mMimeTypeArray[i],
+                                      mMimeTypes[i].get(),
                                       PR_TRUE);
         }
       }
     } else {
       overrideTypesFormatted.BeginReading(start);
       overrideTypesFormatted.EndReading(end);
       
-      nsDependentCString mimeType(mMimeTypeArray[i]);
       nsCAutoString commaSeparated; 
       commaSeparated.Assign(',');
-      commaSeparated += mimeType;
+      commaSeparated += mMimeTypes[i];
       commaSeparated.Append(',');
       if (!FindInReadable(commaSeparated, start, end)) {
         catMan->AddCategoryEntry("Gecko-Content-Viewers",
-                                 mMimeTypeArray[i],
+                                 mMimeTypes[i].get(),
                                  contractId,
                                  PR_FALSE, /* persist: broken by bug 193031 */
                                  aOverrideInternalTypes, /* replace if we're told to */
                                  nsnull);
       }
     }
     
     PLUGIN_LOG(PLUGIN_LOG_NOISY,
                ("nsPluginTag::RegisterWithCategoryManager mime=%s, plugin=%s\n",
-                mMimeTypeArray[i], mFileName.get()));
+                mMimeTypes[i].get(), mFileName.get()));
   }
 }
 
 void nsPluginTag::Mark(PRUint32 mask)
 {
   PRBool wasEnabled = IsEnabled();
   mFlags |= mask;
   // Update entries in the category manager if necessary.
@@ -544,25 +493,26 @@ PRBool nsPluginTag::IsEnabled()
 }
 
 PRBool nsPluginTag::Equals(nsPluginTag *aPluginTag)
 {
   NS_ENSURE_TRUE(aPluginTag, PR_FALSE);
   
   if ((!mName.Equals(aPluginTag->mName)) ||
       (!mDescription.Equals(aPluginTag->mDescription)) ||
-      (mVariants != aPluginTag->mVariants))
+      (mMimeTypes.Length() != aPluginTag->mMimeTypes.Length())) {
     return PR_FALSE;
-  
-  if (mVariants && mMimeTypeArray && aPluginTag->mMimeTypeArray) {
-    for (PRInt32 i = 0; i < mVariants; i++) {
-      if (PL_strcmp(mMimeTypeArray[i], aPluginTag->mMimeTypeArray[i]) != 0)
-        return PR_FALSE;
+  }
+
+  for (PRUint32 i = 0; i < mMimeTypes.Length(); i++) {
+    if (!mMimeTypes[i].Equals(aPluginTag->mMimeTypes[i])) {
+      return PR_FALSE;
     }
   }
+
   return PR_TRUE;
 }
 
 void nsPluginTag::TryUnloadPlugin()
 {
   if (mEntryPoint) {
     mEntryPoint->Shutdown();
     mEntryPoint = nsnull;
@@ -581,38 +531,8 @@ void nsPluginTag::TryUnloadPlugin()
   mLibrary = nsnull;
   
   // Remove mime types added to the category manager
   // only if we were made 'active' by setting the host
   if (mPluginHost) {
     RegisterWithCategoryManager(PR_FALSE, nsPluginTag::ePluginUnregister);
   }
 }
-
-void
-nsPluginTag::RemoveJavaSentinel(PRInt32 sentinelIndex)
-{
-  if (sentinelIndex == -1)
-    return;
-
-  delete[] mMimeTypeArray[sentinelIndex];
-  mMimeDescriptionArray.RemoveElementAt(sentinelIndex);
-  if (mExtensionsArray)
-    delete[] mExtensionsArray[sentinelIndex];
-
-  // Move the subsequent entries in the arrays.
-  if (mVariants > sentinelIndex + 1) {
-    memmove(mMimeTypeArray + sentinelIndex,
-            mMimeTypeArray + sentinelIndex + 1,
-            (mVariants - sentinelIndex - 1) * sizeof(mMimeTypeArray[0]));
-
-    if (mExtensionsArray) {
-      memmove(mExtensionsArray + sentinelIndex,
-              mExtensionsArray + sentinelIndex + 1,
-              (mVariants - sentinelIndex - 1) * sizeof(mExtensionsArray[0]));
-    }
-  }
-  --mVariants;
-
-  mMimeTypeArray[mVariants] = NULL;
-  if (mExtensionsArray)
-    mExtensionsArray[mVariants] = NULL;
-}
--- a/dom/plugins/base/nsPluginTags.h
+++ b/dom/plugins/base/nsPluginTags.h
@@ -40,17 +40,16 @@
 #define nsPluginTags_h_
 
 #include "nscore.h"
 #include "prtypes.h"
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsCOMArray.h"
 #include "nsIPluginTag.h"
-#include "nsIPlugin.h"
 #include "nsNPAPIPluginInstance.h"
 #include "nsISupportsArray.h"
 
 class nsPluginHost;
 struct PRLibrary;
 struct nsPluginInfo;
 
 // Remember that flags are written out to pluginreg.dat, be careful
@@ -95,30 +94,24 @@ public:
   void Mark(PRUint32 mask);
   void UnMark(PRUint32 mask);
   PRBool HasFlag(PRUint32 flag);
   PRUint32 Flags();
   PRBool Equals(nsPluginTag* aPluginTag);
   PRBool IsEnabled();
   void RegisterWithCategoryManager(PRBool aOverrideInternalTypes,
                                    nsRegisterType aType = ePluginRegister);
-
-  // Remove the MIME/description/extension entry associated with the magic Java sentinel
-  // which informs us that the Java plugin is NPAPI-enabled. If sentinelIndex is -1, no
-  // action will be performed.
-  void RemoveJavaSentinel(PRInt32 sentinelIndex);
   
   nsRefPtr<nsPluginTag> mNext;
   nsPluginHost *mPluginHost;
   nsCString     mName; // UTF-8
   nsCString     mDescription; // UTF-8
-  PRInt32       mVariants;
-  char          **mMimeTypeArray;
-  nsTArray<nsCString> mMimeDescriptionArray; // UTF-8
-  char          **mExtensionsArray;
+  nsTArray<nsCString> mMimeTypes; // UTF-8
+  nsTArray<nsCString> mMimeDescriptions; // UTF-8
+  nsTArray<nsCString> mExtensions; // UTF-8
   PRLibrary     *mLibrary;
   nsRefPtr<nsNPAPIPlugin> mEntryPoint;
   PRPackedBool  mCanUnloadLibrary;
   PRPackedBool  mIsJavaPlugin;
   PRPackedBool  mIsNPRuntimeEnabledJavaPlugin;
   PRPackedBool  mIsFlashPlugin;
   nsCString     mFileName; // UTF-8
   nsCString     mFullPath; // UTF-8
--- a/dom/plugins/base/nsPluginsDirWin.cpp
+++ b/dom/plugins/base/nsPluginsDirWin.cpp
@@ -270,17 +270,16 @@ nsresult nsPluginFile::LoadPlugin(PRLibr
 {
   nsCOMPtr<nsILocalFile> plugin = do_QueryInterface(mPlugin);
 
   if (!plugin)
     return NS_ERROR_NULL_POINTER;
 
   PRBool protectCurrentDirectory = PR_TRUE;
 
-#ifndef WINCE
   nsAutoString pluginFolderPath;
   plugin->GetPath(pluginFolderPath);
 
   PRInt32 idx = pluginFolderPath.RFindChar('\\');
   if (kNotFound == idx)
     return NS_ERROR_FILE_INVALID_PATH;
 
   if (Substring(pluginFolderPath, idx).LowerCaseEqualsLiteral("\\np32dsw.dll")) {
@@ -293,36 +292,33 @@ nsresult nsPluginFile::LoadPlugin(PRLibr
   WCHAR aOrigDir[MAX_PATH + 1];
   DWORD dwCheck = GetCurrentDirectoryW(MAX_PATH, aOrigDir);
   NS_ASSERTION(dwCheck <= MAX_PATH + 1, "Error in Loading plugin");
 
   if (dwCheck <= MAX_PATH + 1) {
     restoreOrigDir = SetCurrentDirectoryW(pluginFolderPath.get());
     NS_ASSERTION(restoreOrigDir, "Error in Loading plugin");
   }
-#endif
 
   if (protectCurrentDirectory) {
     mozilla::NS_SetDllDirectory(NULL);
   }
 
   nsresult rv = plugin->Load(outLibrary);
   if (NS_FAILED(rv))
       *outLibrary = NULL;
 
   if (protectCurrentDirectory) {
     mozilla::NS_SetDllDirectory(L"");
   }
 
-#ifndef WINCE    
   if (restoreOrigDir) {
     BOOL bCheck = SetCurrentDirectoryW(aOrigDir);
     NS_ASSERTION(bCheck, "Error in Loading plugin");
   }
-#endif
 
   return rv;
 }
 
 /**
  * Obtains all of the information currently available for this plugin.
  */
 nsresult nsPluginFile::GetPluginInfo(nsPluginInfo& info, PRLibrary **outLibrary)
@@ -342,22 +338,17 @@ nsresult nsPluginFile::GetPluginInfo(nsP
 
   if (!CanLoadPlugin(fullPath.get()))
     return NS_ERROR_FAILURE;
 
   nsAutoString fileName;
   if (NS_FAILED(rv = mPlugin->GetLeafName(fileName)))
     return rv;
 
-#ifdef WINCE
-    // WinCe takes a non const file path string, while desktop take a const
-  LPWSTR lpFilepath = const_cast<LPWSTR>(fullPath.get());
-#else
   LPCWSTR lpFilepath = fullPath.get();
-#endif
 
   versionsize = ::GetFileVersionInfoSizeW(lpFilepath, &zerome);
 
   if (versionsize > 0)
     verbuf = PR_Malloc(versionsize);
   if (!verbuf)
     return NS_ERROR_OUT_OF_MEMORY;
 
--- a/dom/plugins/ipc/PluginInstanceChild.cpp
+++ b/dom/plugins/ipc/PluginInstanceChild.cpp
@@ -1977,18 +1977,22 @@ PluginInstanceChild::FlashThrottleMessag
 #endif // OS_WIN
 
 bool
 PluginInstanceChild::AnswerSetPluginFocus()
 {
     PR_LOG(gPluginLog, PR_LOG_DEBUG, ("%s", FULLFUNCTION));
 
 #if defined(OS_WIN)
-    // Parent is letting us know something set focus to the plugin.
-    if (::GetFocus() == mPluginWindowHWND)
+    // Parent is letting us know the dom set focus to the plugin. Note,
+    // focus can change during transit in certain edge cases, for example
+    // when a button click brings up a full screen window. Since we send
+    // this in response to a WM_SETFOCUS event on our parent, the parent
+    // should have focus when we receive this. If not, ignore the call.
+    if (::GetFocus() == mPluginWindowHWND || ::GetFocus() != mPluginParentHWND)
         return true;
     ::SetFocus(mPluginWindowHWND);
     return true;
 #else
     NS_NOTREACHED("PluginInstanceChild::AnswerSetPluginFocus not implemented!");
     return false;
 #endif
 }
--- a/dom/tests/mochitest/bugs/Makefile.in
+++ b/dom/tests/mochitest/bugs/Makefile.in
@@ -133,14 +133,15 @@ include $(topsrcdir)/config/rules.mk
 		file_bug593174_2.html \
 		test_bug612267.html \
 		test_bug617296.html \
 		test_bug620947.html \
 		test_bug622361.html \
 		test_bug633133.html \
 		test_bug642026.html \
 		test_bug648465.html \
+		test_bug654137.html \
 		test_window_bar.html \
 		file_window_bar.html \
 		$(NULL)
 
 libs:: 	$(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/bugs/test_bug654137.html
@@ -0,0 +1,26 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=654137
+-->
+<head>
+  <title>Test for Bug 654137</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=654137">Mozilla Bug 654137</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+</div>
+<pre id="test">
+<script type="application/javascript">
+/** Test for Bug 654137 **/
+var prev = window.top;
+top = "Fail";
+is(top, prev, "top should not have been replaced");
+</script>
+</pre>
+</body>
+</html>
--- a/editor/composer/src/nsComposerCommands.cpp
+++ b/editor/composer/src/nsComposerCommands.cpp
@@ -81,21 +81,16 @@ nsresult SetTextProperty(nsIEditor *aEdi
 
 nsBaseComposerCommand::nsBaseComposerCommand()
 {
 }
 
 NS_IMPL_ISUPPORTS1(nsBaseComposerCommand, nsIControllerCommand)
 
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
-
 nsBaseStateUpdatingCommand::nsBaseStateUpdatingCommand(const char* aTagName)
 : nsBaseComposerCommand()
 , mTagName(aTagName)
 {
 }
 
 nsBaseStateUpdatingCommand::~nsBaseStateUpdatingCommand()
 {
@@ -192,20 +187,16 @@ nsPasteNoFormattingCommand::GetCommandSt
 
   PRBool enabled = PR_FALSE;
   nsresult rv = IsCommandEnabled(aCommandName, refCon, &enabled);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return aParams->SetBooleanValue(STATE_ENABLED, enabled);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 nsStyleUpdatingCommand::nsStyleUpdatingCommand(const char* aTagName)
 : nsBaseStateUpdatingCommand(aTagName)
 {
 }
 
 nsresult
 nsStyleUpdatingCommand::GetCurrentState(nsIEditor *aEditor, 
                                         const char* aTagName,
@@ -288,19 +279,16 @@ nsStyleUpdatingCommand::ToggleState(nsIE
     if (NS_SUCCEEDED(rv))
       rv = SetTextProperty(aEditor,tagName.get(), nsnull, nsnull);
 
     aEditor->EndTransaction();
   }
 
   return rv;
 }
-#ifdef XP_MAC
-#pragma mark -
-#endif
 
 nsListCommand::nsListCommand(const char* aTagName)
 : nsBaseStateUpdatingCommand(aTagName)
 {
 }
 
 nsresult
 nsListCommand::GetCurrentState(nsIEditor *aEditor, const char* aTagName,
@@ -346,20 +334,16 @@ nsListCommand::ToggleState(nsIEditor *aE
   else
   {
     rv = editor->MakeOrChangeList(listType, PR_FALSE, EmptyString());
   }
   
   return rv;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 nsListItemCommand::nsListItemCommand(const char* aTagName)
 : nsBaseStateUpdatingCommand(aTagName)
 {
 }
 
 nsresult
 nsListItemCommand::GetCurrentState(nsIEditor *aEditor, const char* aTagName,
                                    nsICommandParams *aParams)
@@ -430,20 +414,16 @@ nsListItemCommand::ToggleState(nsIEditor
     //    but we currently don't use this for non DL lists anyway.
     // Problem: won't this replace any current block paragraph style?
     rv = htmlEditor->SetParagraphFormat(itemType);
   }
     
   return rv;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 NS_IMETHODIMP
 nsRemoveListCommand::IsCommandEnabled(const char * aCommandName,
                                       nsISupports *refCon,
                                       PRBool *outCmdEnabled)
 {
   nsCOMPtr<nsIEditor> editor = do_QueryInterface(refCon);
   if (editor)
   {
@@ -492,20 +472,16 @@ nsRemoveListCommand::GetCommandStatePara
                                            nsICommandParams *aParams, 
                                            nsISupports *refCon)
 {
   PRBool outCmdEnabled = PR_FALSE;
   IsCommandEnabled(aCommandName, refCon, &outCmdEnabled);
   return aParams->SetBooleanValue(STATE_ENABLED,outCmdEnabled);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 NS_IMETHODIMP
 nsIndentCommand::IsCommandEnabled(const char * aCommandName,
                                   nsISupports *refCon, PRBool *outCmdEnabled)
 {
   nsCOMPtr<nsIHTMLEditor> editor = do_QueryInterface(refCon);
   *outCmdEnabled = editor ? PR_TRUE : PR_FALSE;
   return NS_OK;
 }
@@ -588,21 +564,16 @@ nsOutdentCommand::GetCommandStateParams(
                                         nsICommandParams *aParams,
                                         nsISupports *refCon)
 {
   PRBool outCmdEnabled = PR_FALSE;
   IsCommandEnabled(aCommandName, refCon, &outCmdEnabled);
   return aParams->SetBooleanValue(STATE_ENABLED,outCmdEnabled);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
-
 nsMultiStateCommand::nsMultiStateCommand()
 : nsBaseComposerCommand()
 {
 }
 
 nsMultiStateCommand::~nsMultiStateCommand()
 {
 }
@@ -668,20 +639,16 @@ nsMultiStateCommand::GetCommandStatePara
   nsresult rv = NS_OK;
   if (editor)
   {
       rv = GetCurrentState(editor, aParams);
   }
   return rv;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 nsParagraphStateCommand::nsParagraphStateCommand()
 : nsMultiStateCommand()
 {
 }
 
 nsresult
 nsParagraphStateCommand::GetCurrentState(nsIEditor *aEditor,
                                          nsICommandParams *aParams)
@@ -710,20 +677,16 @@ nsParagraphStateCommand::SetState(nsIEdi
 {
   NS_ASSERTION(aEditor, "Need an editor here");
   nsCOMPtr<nsIHTMLEditor> htmlEditor = do_QueryInterface(aEditor);
   NS_ENSURE_TRUE(htmlEditor, NS_ERROR_FAILURE);
 
   return htmlEditor->SetParagraphFormat(newState);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 nsFontFaceStateCommand::nsFontFaceStateCommand()
 : nsMultiStateCommand()
 {
 }
 
 nsresult
 nsFontFaceStateCommand::GetCurrentState(nsIEditor *aEditor,
                                         nsICommandParams *aParams)
@@ -774,20 +737,16 @@ nsFontFaceStateCommand::SetState(nsIEdit
       rv = htmlEditor->SetInlineProperty(fontAtom, NS_LITERAL_STRING("face"),
                                          newState);
     }
   }
   
   return rv;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 nsFontSizeStateCommand::nsFontSizeStateCommand()
   : nsMultiStateCommand()
 {
 }
 
 //  nsCAutoString tOutStateString;
 //  tOutStateString.AssignWithConversion(outStateString);
 nsresult
@@ -854,19 +813,16 @@ nsFontSizeStateCommand::SetState(nsIEdit
     // set the size
     rv = htmlEditor->SetInlineProperty(fontAtom, NS_LITERAL_STRING("size"),
                                        newState);
   }
 
   return rv;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
 nsFontColorStateCommand::nsFontColorStateCommand()
 : nsMultiStateCommand()
 {
 }
 
 nsresult
 nsFontColorStateCommand::GetCurrentState(nsIEditor *aEditor,
                                          nsICommandParams *aParams)
@@ -904,20 +860,16 @@ nsFontColorStateCommand::SetState(nsIEdi
   } else {
     rv = htmlEditor->SetInlineProperty(fontAtom, NS_LITERAL_STRING("color"), 
                                        newState);
   }
   
   return rv;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 nsHighlightColorStateCommand::nsHighlightColorStateCommand()
 : nsMultiStateCommand()
 {
 }
 
 nsresult
 nsHighlightColorStateCommand::GetCurrentState(nsIEditor *aEditor,
                                               nsICommandParams *aParams)
@@ -966,20 +918,16 @@ nsHighlightColorStateCommand::IsCommandE
                                                PRBool *outCmdEnabled)
 {
   nsCOMPtr<nsIHTMLEditor> htmlEditor = do_QueryInterface(refCon);
   *outCmdEnabled = htmlEditor ? PR_TRUE : PR_FALSE;
   return NS_OK;
 }
 
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 nsBackgroundColorStateCommand::nsBackgroundColorStateCommand()
 : nsMultiStateCommand()
 {
 }
 
 nsresult
 nsBackgroundColorStateCommand::GetCurrentState(nsIEditor *aEditor,
                                                nsICommandParams *aParams)
@@ -1008,20 +956,16 @@ nsBackgroundColorStateCommand::SetState(
   NS_ASSERTION(aEditor, "Need an editor here");
   
   nsCOMPtr<nsIHTMLEditor> htmlEditor = do_QueryInterface(aEditor);
   NS_ENSURE_TRUE(htmlEditor, NS_ERROR_FAILURE);
 
   return htmlEditor->SetBackgroundColor(newState);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 nsAlignCommand::nsAlignCommand()
 : nsMultiStateCommand()
 {
 }
 
 nsresult
 nsAlignCommand::GetCurrentState(nsIEditor *aEditor, nsICommandParams *aParams)
 {
@@ -1069,22 +1013,16 @@ nsAlignCommand::SetState(nsIEditor *aEdi
   NS_ASSERTION(aEditor, "Need an editor here");
   
   nsCOMPtr<nsIHTMLEditor> htmlEditor = do_QueryInterface(aEditor);
   NS_ENSURE_TRUE(htmlEditor, NS_ERROR_FAILURE);
 
   return htmlEditor->Align(newState);
 }
 
-
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
-
 nsAbsolutePositioningCommand::nsAbsolutePositioningCommand()
 : nsBaseStateUpdatingCommand("")
 {
 }
 
 NS_IMETHODIMP
 nsAbsolutePositioningCommand::IsCommandEnabled(const char * aCommandName,
                                                nsISupports *aCommandRefCon,
@@ -1146,20 +1084,16 @@ nsAbsolutePositioningCommand::ToggleStat
   }
   else {
     rv = htmlEditor->AbsolutePositionSelection(PR_TRUE);
   }
   return rv;
 }
 
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 NS_IMETHODIMP
 nsDecreaseZIndexCommand::IsCommandEnabled(const char * aCommandName,
                                           nsISupports *refCon,
                                           PRBool *outCmdEnabled)
 {
   nsCOMPtr<nsIHTMLAbsPosEditor> htmlEditor = do_QueryInterface(refCon);
   NS_ENSURE_TRUE(htmlEditor, NS_ERROR_FAILURE);
 
@@ -1207,20 +1141,16 @@ nsDecreaseZIndexCommand::GetCommandState
 
   PRBool enabled = PR_FALSE;
   nsresult rv = IsCommandEnabled(aCommandName, refCon, &enabled);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return aParams->SetBooleanValue(STATE_ENABLED, enabled);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 NS_IMETHODIMP
 nsIncreaseZIndexCommand::IsCommandEnabled(const char * aCommandName,
                                           nsISupports *refCon,
                                           PRBool *outCmdEnabled)
 {
   nsCOMPtr<nsIHTMLAbsPosEditor> htmlEditor = do_QueryInterface(refCon);
   NS_ENSURE_TRUE(htmlEditor, NS_ERROR_FAILURE);
 
@@ -1261,20 +1191,16 @@ nsIncreaseZIndexCommand::GetCommandState
 
   PRBool enabled = PR_FALSE;
   nsresult rv = IsCommandEnabled(aCommandName, refCon, &enabled);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return aParams->SetBooleanValue(STATE_ENABLED, enabled);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 
 NS_IMETHODIMP
 nsRemoveStylesCommand::IsCommandEnabled(const char * aCommandName,
                                         nsISupports *refCon,
                                         PRBool *outCmdEnabled)
 {
   nsCOMPtr<nsIEditor> editor = do_QueryInterface(refCon);
   // test if we have any styles?
@@ -1312,20 +1238,16 @@ nsRemoveStylesCommand::GetCommandStatePa
                                              nsICommandParams *aParams,
                                              nsISupports *refCon)
 {
   PRBool outCmdEnabled = PR_FALSE;
   IsCommandEnabled(aCommandName, refCon, &outCmdEnabled);
   return aParams->SetBooleanValue(STATE_ENABLED,outCmdEnabled);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 NS_IMETHODIMP
 nsIncreaseFontSizeCommand::IsCommandEnabled(const char * aCommandName,
                                             nsISupports *refCon,
                                             PRBool *outCmdEnabled)
 {
   nsCOMPtr<nsIEditor> editor = do_QueryInterface(refCon);
   // test if we have any styles?
   *outCmdEnabled = editor ? PR_TRUE : PR_FALSE;
@@ -1361,20 +1283,16 @@ nsIncreaseFontSizeCommand::GetCommandSta
                                                  nsICommandParams *aParams,
                                                  nsISupports *refCon)
 {
   PRBool outCmdEnabled = PR_FALSE;
   IsCommandEnabled(aCommandName, refCon, &outCmdEnabled);
   return aParams->SetBooleanValue(STATE_ENABLED,outCmdEnabled);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 NS_IMETHODIMP
 nsDecreaseFontSizeCommand::IsCommandEnabled(const char * aCommandName,
                                             nsISupports *refCon,
                                             PRBool *outCmdEnabled)
 {
   nsCOMPtr<nsIEditor> editor = do_QueryInterface(refCon);
   // test if we are at min size?
   *outCmdEnabled = editor ? PR_TRUE : PR_FALSE;
@@ -1410,20 +1328,16 @@ nsDecreaseFontSizeCommand::GetCommandSta
                                                  nsICommandParams *aParams,
                                                  nsISupports *refCon)
 {
   PRBool outCmdEnabled = PR_FALSE;
   IsCommandEnabled(aCommandName, refCon, &outCmdEnabled);
   return aParams->SetBooleanValue(STATE_ENABLED,outCmdEnabled);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 NS_IMETHODIMP
 nsInsertHTMLCommand::IsCommandEnabled(const char * aCommandName,
                                       nsISupports *refCon,
                                       PRBool *outCmdEnabled)
 {
   NS_ENSURE_ARG_POINTER(outCmdEnabled);
   nsCOMPtr<nsIHTMLEditor> editor = do_QueryInterface(refCon);
   *outCmdEnabled = editor ? PR_TRUE : PR_FALSE;
@@ -1467,20 +1381,16 @@ nsInsertHTMLCommand::GetCommandStatePara
   NS_ENSURE_ARG_POINTER(aParams);
   NS_ENSURE_ARG_POINTER(refCon);
 
   PRBool outCmdEnabled = PR_FALSE;
   IsCommandEnabled(aCommandName, refCon, &outCmdEnabled);
   return aParams->SetBooleanValue(STATE_ENABLED, outCmdEnabled);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 NS_IMPL_ISUPPORTS_INHERITED0(nsInsertTagCommand, nsBaseComposerCommand)
 
 nsInsertTagCommand::nsInsertTagCommand(const char* aTagName)
 : nsBaseComposerCommand()
 , mTagName(aTagName)
 {
 }
 
@@ -1579,19 +1489,16 @@ nsInsertTagCommand::GetCommandStateParam
   NS_ENSURE_ARG_POINTER(aParams);
   NS_ENSURE_ARG_POINTER(refCon);
 
   PRBool outCmdEnabled = PR_FALSE;
   IsCommandEnabled(aCommandName, refCon, &outCmdEnabled);
   return aParams->SetBooleanValue(STATE_ENABLED, outCmdEnabled);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
 
 /****************************/
 //HELPER METHODS
 /****************************/
 
 nsresult
 GetListState(nsIEditor *aEditor, PRBool *aMixed, PRUnichar **_retval)
 {
--- a/editor/composer/src/nsComposerDocumentCommands.cpp
+++ b/editor/composer/src/nsComposerDocumentCommands.cpp
@@ -443,20 +443,16 @@ nsSetDocumentStateCommand::GetCommandSta
  *
  *  5. Use GetCommandStateParams() to obtain state information
  *     e.g., any creation state codes when creating an editor are 
  *     supplied for "obs_documentCreated" command in the 
  *     "state_data" param's value
  *
  */
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 NS_IMETHODIMP
 nsDocumentStateCommand::IsCommandEnabled(const char* aCommandName,
                                          nsISupports *refCon,
                                          PRBool *outCmdEnabled)
 {
   NS_ENSURE_ARG_POINTER(outCmdEnabled);
   // Always return false to discourage callers from using DoCommand()
   *outCmdEnabled = PR_FALSE;
--- a/editor/composer/src/nsEditingSession.cpp
+++ b/editor/composer/src/nsEditingSession.cpp
@@ -636,20 +636,16 @@ nsEditingSession::GetEditorForWindow(nsI
   nsCOMPtr<nsIEditorDocShell> editorDocShell;
   nsresult rv = GetEditorDocShellFromWindow(aWindow,
                                             getter_AddRefs(editorDocShell));
   NS_ENSURE_SUCCESS(rv, rv);  
   
   return editorDocShell->GetEditor(outEditor);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 /*---------------------------------------------------------------------------
 
   OnStateChange
 
 ----------------------------------------------------------------------------*/
 NS_IMETHODIMP
 nsEditingSession::OnStateChange(nsIWebProgress *aWebProgress,
                                 nsIRequest *aRequest,
@@ -889,21 +885,16 @@ NS_IMETHODIMP
 nsEditingSession::OnSecurityChange(nsIWebProgress *aWebProgress,
                                    nsIRequest *aRequest, PRUint32 state)
 {
     NS_NOTREACHED("notification excluded in AddProgressListener(...)");
     return NS_OK;
 }
 
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
-
 /*---------------------------------------------------------------------------
 
   IsProgressForTargetDocument
 
   Check that this notification is for our document.
 ----------------------------------------------------------------------------*/
 
 PRBool
@@ -1144,21 +1135,16 @@ nsEditingSession::EndPageLoad(nsIWebProg
 #if 0
   // Shouldn't we do this when we want to edit sub-frames?
   return MakeWindowEditable(domWindow, "html", PR_FALSE, mInteractive);
 #else
   return NS_OK;
 #endif
 }
 
-
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 /*---------------------------------------------------------------------------
 
   GetDocShellFromWindow
 
   Utility method. This will always return nsnull if no docShell is found.
 ----------------------------------------------------------------------------*/
 nsIDocShell *
 nsEditingSession::GetDocShellFromWindow(nsIDOMWindow *aWindow)
--- a/editor/libeditor/base/nsEditor.cpp
+++ b/editor/libeditor/base/nsEditor.cpp
@@ -210,22 +210,16 @@ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(
  NS_INTERFACE_MAP_ENTRY(nsIEditorIMESupport)
  NS_INTERFACE_MAP_ENTRY(nsIEditor)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIEditor)
 NS_INTERFACE_MAP_END
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsEditor)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsEditor)
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  nsIEditorMethods 
-#pragma mark -
-#endif
-
 
 NS_IMETHODIMP
 nsEditor::Init(nsIDOMDocument *aDoc, nsIContent *aRoot, nsISelectionController *aSelCon, PRUint32 aFlags)
 {
   NS_PRECONDITION(aDoc, "bad arg");
   if (!aDoc)
     return NS_ERROR_NULL_POINTER;
 
@@ -1334,22 +1328,16 @@ NS_IMETHODIMP nsEditor::SyncRealTimeSpel
 
 NS_IMETHODIMP nsEditor::SetSpellcheckUserOverride(PRBool enable)
 {
   mSpellcheckCheckboxState = enable ? eTriTrue : eTriFalse;
 
   return SyncRealTimeSpell();
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  main node manipulation routines 
-#pragma mark -
-#endif
-
 NS_IMETHODIMP nsEditor::CreateNode(const nsAString& aTag,
                                    nsIDOMNode *    aParent,
                                    PRInt32         aPosition,
                                    nsIDOMNode **   aNewNode)
 {
   PRInt32 i;
 
   nsAutoRules beginRulesSniffing(this, kOpCreateNode, nsIEditor::eNext);
@@ -1697,21 +1685,16 @@ nsEditor::MoveNode(nsIDOMNode *aNode, ns
   }
 
   // put aNode in new parent
   res = DeleteNode(aNode);
   NS_ENSURE_SUCCESS(res, res);
   return InsertNode(aNode, aParent, aOffset);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  editor observer maintainance
-#pragma mark -
-#endif
 
 NS_IMETHODIMP
 nsEditor::AddEditorObserver(nsIEditorObserver *aObserver)
 {
   // we don't keep ownership of the observers.  They must
   // remove themselves as observers before they are destroyed.
   
   NS_ENSURE_TRUE(aObserver, NS_ERROR_NULL_POINTER);
@@ -1739,21 +1722,16 @@ nsEditor::RemoveEditorObserver(nsIEditor
 }
 
 void nsEditor::NotifyEditorObservers(void)
 {
   for (PRInt32 i = 0; i < mEditorObservers.Count(); i++)
     mEditorObservers[i]->EditAction();
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  action listener maintainance
-#pragma mark -
-#endif
 
 NS_IMETHODIMP
 nsEditor::AddEditActionListener(nsIEditActionListener *aListener)
 {
   NS_ENSURE_TRUE(aListener, NS_ERROR_NULL_POINTER);
 
   // Make sure the listener isn't already on the list
   if (mActionListeners.IndexOf(aListener) == -1) 
@@ -1773,23 +1751,16 @@ nsEditor::RemoveEditActionListener(nsIEd
 
   if (!mActionListeners.RemoveObject(aListener))
     return NS_ERROR_FAILURE;
 
   return NS_OK;
 }
 
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  docstate listener maintainance
-#pragma mark -
-#endif
-
-
 NS_IMETHODIMP
 nsEditor::AddDocumentStateListener(nsIDocumentStateListener *aListener)
 {
   NS_ENSURE_TRUE(aListener, NS_ERROR_NULL_POINTER);
 
   if (mDocStateListeners.IndexOf(aListener) == -1)
   {
     if (!mDocStateListeners.AppendObject(aListener))
@@ -1807,22 +1778,16 @@ nsEditor::RemoveDocumentStateListener(ns
 
   if (!mDocStateListeners.RemoveObject(aListener))
     return NS_ERROR_FAILURE;
 
   return NS_OK;
 }
 
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  misc 
-#pragma mark -
-#endif
-
 NS_IMETHODIMP nsEditor::OutputToString(const nsAString& aFormatType,
                                        PRUint32 aFlags,
                                        nsAString& aOutputString)
 {
   // these should be implemented by derived classes.
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
@@ -1868,21 +1833,16 @@ NS_IMETHODIMP
 nsEditor::DebugUnitTests(PRInt32 *outNumTests, PRInt32 *outNumTestsFailed)
 {
 #ifdef DEBUG
   NS_NOTREACHED("This should never get called. Overridden by subclasses");
 #endif
   return NS_OK;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  support for selection preservation
-#pragma mark -
-#endif
 
 PRBool   
 nsEditor::ArePreservingSelection()
 {
   return !(mSavedSel.IsEmpty());
 }
 
 nsresult 
@@ -1905,22 +1865,16 @@ nsEditor::RestorePreservedSelection(nsIS
 void     
 nsEditor::StopPreservingSelection()
 {
   mRangeUpdater.DropSelectionState(mSavedSel);
   mSavedSel.MakeEmpty();
 }
 
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  IME event handlers 
-#pragma mark -
-#endif
-
 nsresult
 nsEditor::BeginIMEComposition()
 {
   mInIMEMode = PR_TRUE;
   if (mPhonetic) {
     mPhonetic->Truncate(0);
   }
   return NS_OK;
@@ -1956,42 +1910,28 @@ nsEditor::EndIMEComposition()
 
   // notify editor observers of action
   NotifyEditorObservers();
 
   return rv;
 }
 
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  nsIPhonetic
-#pragma mark -
-#endif
-
-
 NS_IMETHODIMP
 nsEditor::GetPhonetic(nsAString& aPhonetic)
 {
   if (mPhonetic)
     aPhonetic = *mPhonetic;
   else
     aPhonetic.Truncate(0);
 
   return NS_OK;
 }
 
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  nsIEditorIMESupport 
-#pragma mark -
-#endif
-
-
 static nsresult
 GetEditorContentWindow(nsIDOMElement *aRoot, nsIWidget **aResult)
 {
   NS_ENSURE_TRUE(aRoot && aResult, NS_ERROR_NULL_POINTER);
 
   *aResult = 0;
 
   nsCOMPtr<nsIContent> content = do_QueryInterface(aRoot);
@@ -2030,17 +1970,17 @@ NS_IMETHODIMP
 nsEditor::ForceCompositionEnd()
 {
 
 // We can test mInIMEMode and do some optimization for Mac and Window
 // Howerver, since UNIX support over-the-spot, we cannot rely on that 
 // flag for Unix.
 // We should use nsILookAndFeel to resolve this
 
-#if defined(XP_MAC) || defined(XP_MACOSX) || defined(XP_WIN) || defined(XP_OS2)
+#if defined(XP_MACOSX) || defined(XP_WIN) || defined(XP_OS2)
   // XXXmnakano see bug 558976, ResetInputState() has two meaning which are
   // "commit the composition" and "cursor is moved".  This method name is
   // "ForceCompositionEnd", so, ResetInputState() should be used only for the
   // former here.  However, ResetInputState() is also used for the latter here
   // because even if we don't have composition, we call ResetInputState() on
   // Linux.  Currently, nsGtkIMModule can know the timing of the cursor move,
   // so, the latter meaning should be gone and we should remove this #if.
   if(! mInIMEMode)
@@ -2099,24 +2039,19 @@ nsEditor::GetPreferredIMEState(PRUint32 
 NS_IMETHODIMP
 nsEditor::GetComposing(PRBool* aResult)
 {
   NS_ENSURE_ARG_POINTER(aResult);
   *aResult = IsIMEComposing();
   return NS_OK;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  public nsEditor methods 
-#pragma mark -
-#endif
+
 /* Non-interface, public methods */
 
-
 NS_IMETHODIMP
 nsEditor::GetRootElement(nsIDOMElement **aRootElement)
 {
   NS_ENSURE_ARG_POINTER(aRootElement);
   NS_ENSURE_TRUE(mRootElement, NS_ERROR_NOT_AVAILABLE);
   *aRootElement = mRootElement;
   NS_ADDREF(*aRootElement);
   return NS_OK;
@@ -2269,21 +2204,16 @@ nsEditor::CloneAttributes(nsIDOMNode *aD
           }
         }        
       }
     }
   }
   return result;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  Protected and static methods 
-#pragma mark -
-#endif
 
 NS_IMETHODIMP nsEditor::ScrollSelectionIntoView(PRBool aScrollToAnchor)
 {
   nsCOMPtr<nsISelectionController> selCon;
   if (NS_SUCCEEDED(GetSelectionController(getter_AddRefs(selCon))) && selCon)
   {
     PRInt16 region = nsISelectionController::SELECTION_FOCUS_REGION;
 
@@ -2756,21 +2686,16 @@ NS_IMETHODIMP nsEditor::CreateTxnForJoin
   }
 
   return rv;
 }
 
 
 // END nsEditor core implementation
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  nsEditor public static helper methods 
-#pragma mark -
-#endif
 
 // BEGIN nsEditor public helper methods
 
 nsresult
 nsEditor::SplitNodeImpl(nsIDOMNode * aExistingRightNode,
                         PRInt32      aOffset,
                         nsIDOMNode*  aNewLeftNode,
                         nsIDOMNode*  aParent)
@@ -4266,23 +4191,16 @@ nsresult nsEditor::EndUpdateViewBatch()
 
 PRBool 
 nsEditor::GetShouldTxnSetSelection()
 {
   return mShouldTxnSetSelection;
 }
 
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  protected nsEditor methods 
-#pragma mark -
-#endif
-
-
 NS_IMETHODIMP 
 nsEditor::DeleteSelectionImpl(nsIEditor::EDirection aAction)
 {
   nsCOMPtr<nsISelection>selection;
   nsresult res = GetSelection(getter_AddRefs(selection));
   NS_ENSURE_SUCCESS(res, res);
   nsRefPtr<EditAggregateTxn> txn;
   nsCOMPtr<nsIDOMNode> deleteNode;
--- a/editor/libeditor/base/nsEditorCommands.cpp
+++ b/editor/libeditor/base/nsEditorCommands.cpp
@@ -55,20 +55,16 @@
 
 
 nsBaseEditorCommand::nsBaseEditorCommand()
 {
 }
 
 NS_IMPL_ISUPPORTS1(nsBaseEditorCommand, nsIControllerCommand)
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 
 NS_IMETHODIMP
 nsUndoCommand::IsCommandEnabled(const char * aCommandName, 
                                 nsISupports *aCommandRefCon, 
                                 PRBool *outCmdEnabled)
 {
   NS_ENSURE_ARG_POINTER(outCmdEnabled);
   nsCOMPtr<nsIEditor> editor = do_QueryInterface(aCommandRefCon);
@@ -785,19 +781,16 @@ nsSelectionMoveCommands::GetCommandState
                                                nsICommandParams *aParams,
                                                nsISupports *aCommandRefCon)
 {
   PRBool canUndo;
   IsCommandEnabled(aCommandName, aCommandRefCon, &canUndo);
   return aParams->SetBooleanValue(STATE_ENABLED,canUndo);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
 
 NS_IMETHODIMP
 nsInsertPlaintextCommand::IsCommandEnabled(const char * aCommandName,
                                            nsISupports *refCon, 
                                            PRBool *outCmdEnabled)
 {
   NS_ENSURE_ARG_POINTER(outCmdEnabled);
   nsCOMPtr<nsIEditor> editor = do_QueryInterface(refCon);
@@ -845,20 +838,16 @@ nsInsertPlaintextCommand::GetCommandStat
   NS_ENSURE_ARG_POINTER(aParams);
 
   PRBool outCmdEnabled = PR_FALSE;
   IsCommandEnabled(aCommandName, refCon, &outCmdEnabled);
   return aParams->SetBooleanValue(STATE_ENABLED, outCmdEnabled);
 }
 
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 NS_IMETHODIMP
 nsPasteQuotationCommand::IsCommandEnabled(const char * aCommandName,
                                           nsISupports *refCon,
                                           PRBool *outCmdEnabled)
 {
   NS_ENSURE_ARG_POINTER(outCmdEnabled);
 
   nsCOMPtr<nsIEditor> editor = do_QueryInterface(refCon);
--- a/editor/libeditor/base/nsStyleSheetTxns.cpp
+++ b/editor/libeditor/base/nsStyleSheetTxns.cpp
@@ -123,20 +123,16 @@ AddStyleSheetTxn::UndoTransaction()
 
 NS_IMETHODIMP
 AddStyleSheetTxn::GetTxnDescription(nsAString& aString)
 {
   aString.AssignLiteral("AddStyleSheetTxn");
   return NS_OK;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 
 RemoveStyleSheetTxn::RemoveStyleSheetTxn()
 :  EditTxn()
 ,  mEditor(NULL)
 {
 }
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(RemoveStyleSheetTxn)
--- a/editor/libeditor/html/nsHTMLDataTransfer.cpp
+++ b/editor/libeditor/html/nsHTMLDataTransfer.cpp
@@ -1565,17 +1565,17 @@ NS_IMETHODIMP nsHTMLEditor::InsertFromDr
       PRBool userWantsCopy = PR_FALSE;
 
       nsCOMPtr<nsIDOMNSUIEvent> nsuiEvent(do_QueryInterface(aDropEvent));
       NS_ENSURE_TRUE(nsuiEvent, NS_ERROR_FAILURE);
 
       nsCOMPtr<nsIDOMMouseEvent> mouseEvent(do_QueryInterface(aDropEvent));
       if (mouseEvent)
 
-#if defined(XP_MAC) || defined(XP_MACOSX)
+#if defined(XP_MACOSX)
         mouseEvent->GetAltKey(&userWantsCopy);
 #else
         mouseEvent->GetCtrlKey(&userWantsCopy);
 #endif
 
       // Current doc is destination
       nsCOMPtr<nsIDOMDocument>destdomdoc; 
       rv = GetDocument(getter_AddRefs(destdomdoc)); 
--- a/editor/libeditor/html/nsHTMLEditRules.cpp
+++ b/editor/libeditor/html/nsHTMLEditRules.cpp
@@ -35,21 +35,16 @@
  * 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 ***** */
 
-/* build on macs with low memory */
-#if defined(XP_MAC) && defined(MOZ_MAC_LOWMEM)
-#pragma optimization_level 1
-#endif
-
 #include "nsHTMLEditRules.h"
 
 #include "nsEditor.h"
 #include "nsTextEditUtils.h"
 #include "nsHTMLEditUtils.h"
 #include "nsHTMLCSSUtils.h"
 #include "nsHTMLEditor.h"
 
@@ -8396,22 +8391,16 @@ nsHTMLEditRules::InsertMozBRIfNeeded(nsI
   NS_ENSURE_SUCCESS(res, res);
   if (isEmpty)
   {
     res = CreateMozBR(aNode, 0, address_of(brNode));
   }
   return res;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  nsIEditActionListener methods 
-#pragma mark -
-#endif
-
 NS_IMETHODIMP 
 nsHTMLEditRules::WillCreateNode(const nsAString& aTag, nsIDOMNode *aParent, PRInt32 aPosition)
 {
   return NS_OK;  
 }
 
 NS_IMETHODIMP 
 nsHTMLEditRules::DidCreateNode(const nsAString& aTag, 
--- a/editor/libeditor/html/nsHTMLEditor.cpp
+++ b/editor/libeditor/html/nsHTMLEditor.cpp
@@ -1388,22 +1388,16 @@ nsHTMLEditor::GetIsDocumentEditable(PRBo
   return NS_OK;
 }
 
 PRBool nsHTMLEditor::IsModifiable()
 {
   return !IsReadonly();
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  nsIHTMLEditor methods 
-#pragma mark -
-#endif
-
 NS_IMETHODIMP
 nsHTMLEditor::UpdateBaseURL()
 {
   nsCOMPtr<nsIDOMDocument> domDoc;
   GetDocument(getter_AddRefs(domDoc));
   NS_ENSURE_TRUE(domDoc, NS_ERROR_FAILURE);
 
   // Look for an HTML <base> tag
@@ -3479,21 +3473,16 @@ nsHTMLEditor::GetLinkedObjects(nsISuppor
       }
       iter->Next();
     }
   }
 
   return NS_OK;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  nsIEditorStyleSheets methods 
-#pragma mark -
-#endif
 
 NS_IMETHODIMP
 nsHTMLEditor::AddStyleSheet(const nsAString &aURL)
 {
   // Enable existing sheet if already loaded.
   if (EnableExistingStyleSheet(aURL))
     return NS_OK;
 
@@ -3805,22 +3794,16 @@ nsHTMLEditor::GetEmbeddedObjects(nsISupp
       iter->Next();
     }
   }
 
   return res;
 }
 
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  nsIEditor overrides 
-#pragma mark -
-#endif
-
 NS_IMETHODIMP nsHTMLEditor::DeleteNode(nsIDOMNode * aNode)
 {
   // do nothing if the node is read-only
   if (!IsModifiableNode(aNode) && !IsMozEditorBogusNode(aNode)) {
     return NS_ERROR_FAILURE;
   }
 
   nsCOMPtr<nsIDOMNode> selectAllNode = FindUserSelectAllNode(aNode);
@@ -3858,22 +3841,16 @@ NS_IMETHODIMP nsHTMLEditor::InsertTextIm
   // do nothing if the node is read-only
   if (!IsModifiableNode(*aInOutNode)) {
     return NS_ERROR_FAILURE;
   }
 
   return nsEditor::InsertTextImpl(aStringToInsert, aInOutNode, aInOutOffset, aDoc);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  nsStubMutationObserver overrides 
-#pragma mark -
-#endif
-
 void
 nsHTMLEditor::ContentAppended(nsIDocument *aDocument, nsIContent* aContainer,
                               nsIContent* aFirstNewContent,
                               PRInt32 /* unused */)
 {
   ContentInserted(aDocument, aContainer, aFirstNewContent, 0);
 }
 
@@ -3917,21 +3894,16 @@ nsHTMLEditor::ContentRemoved(nsIDocument
     if (node && IsMozEditorBogusNode(node)) {
       // Ignore removal of the bogus node
       return;
     }
     mRules->DocumentModified();
   }
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  support utils
-#pragma mark -
-#endif
 
 /* This routine examines aNode and it's ancestors looking for any node which has the
    -moz-user-select: all style lit.  Return the highest such ancestor.  */
 nsCOMPtr<nsIDOMNode> nsHTMLEditor::FindUserSelectAllNode(nsIDOMNode *aNode)
 {
   nsCOMPtr<nsIDOMNode> resultNode;  // starts out empty
   nsCOMPtr<nsIDOMNode> node = aNode;
   nsIDOMElement *root = GetRoot();
@@ -4066,22 +4038,16 @@ nsHTMLEditor::DebugUnitTests(PRInt32 *ou
   tester->Run(this, outNumTests, outNumTestsFailed);
   delete tester;
   return NS_OK;
 #else
   return NS_ERROR_NOT_IMPLEMENTED;
 #endif
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  StyleSheet utils 
-#pragma mark -
-#endif
-
 
 NS_IMETHODIMP 
 nsHTMLEditor::StyleSheetLoaded(nsCSSStyleSheet* aSheet, PRBool aWasAlternate,
                                nsresult aStatus)
 {
   nsresult rv = NS_OK;
   nsAutoEditBatch batchIt(this);
 
@@ -4109,22 +4075,16 @@ nsHTMLEditor::StyleSheetLoaded(nsCSSStyl
         AddNewStyleSheetToList(mLastStyleSheetURL, aSheet);
       }
     }
   }
 
   return NS_OK;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  nsEditor overrides 
-#pragma mark -
-#endif
-
 
 /** All editor operations which alter the doc should be prefaced
  *  with a call to StartOperation, naming the action and direction */
 NS_IMETHODIMP
 nsHTMLEditor::StartOperation(PRInt32 opID, nsIEditor::EDirection aDirection)
 {
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> kungFuDeathGrip(mRules);
@@ -4260,22 +4220,16 @@ nsHTMLEditor::SelectAll()
 
   nsCOMPtr<nsIDOMNode> rootElement = do_QueryInterface(rootContent, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return selection->SelectAllChildren(rootElement);
 }
 
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  Random methods 
-#pragma mark -
-#endif
-
 // this will NOT find aAttribute unless aAttribute has a non-null value
 // so singleton attributes like <Table border> will not be matched!
 void nsHTMLEditor::IsTextPropertySetByContent(nsIDOMNode        *aNode,
                                               nsIAtom           *aProperty, 
                                               const nsAString   *aAttribute, 
                                               const nsAString   *aValue, 
                                               PRBool            &aIsSet,
                                               nsIDOMNode       **aStyleNode,
@@ -4335,19 +4289,16 @@ void nsHTMLEditor::IsTextPropertySetByCo
       node = temp;
     }
     else {
       node = nsnull;
     }
   }
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
 
 //================================================================
 // HTML Editor methods
 //
 // Note: Table Editing methods are implemented in nsTableEditor.cpp
 //
 
 
@@ -4442,19 +4393,16 @@ nsHTMLEditor::GetEnclosingTable(nsIDOMNo
     tmp = GetBlockNodeParent(node);
     if (!tmp) break;
     if (nsHTMLEditUtils::IsTable(tmp)) tbl = tmp;
     node = tmp;
   }
   return tbl;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
 
 #ifdef PRE_NODE_IN_BODY
 nsCOMPtr<nsIDOMElement> nsHTMLEditor::FindPreElement()
 {
   nsCOMPtr<nsIDOMDocument> domdoc;
   nsEditor::GetDocument(getter_AddRefs(domdoc));
   NS_ENSURE_TRUE(domdoc, 0);
 
@@ -4547,19 +4495,16 @@ NS_IMETHODIMP
 nsHTMLEditor::SetSelectionAtDocumentStart(nsISelection *aSelection)
 {
   nsIDOMElement *rootElement = GetRoot();  
   NS_ENSURE_TRUE(rootElement, NS_ERROR_NULL_POINTER);
 
   return aSelection->Collapse(rootElement,0);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
 
 ///////////////////////////////////////////////////////////////////////////
 // RemoveBlockContainer: remove inNode, reparenting it's children into their
 //                  the parent of inNode.  In addition, INSERT ANY BR's NEEDED
 //                  TO PRESERVE IDENTITY OF REMOVED BLOCK.
 //
 nsresult
 nsHTMLEditor::RemoveBlockContainer(nsIDOMNode *inNode)
--- a/editor/libeditor/html/nsHTMLEditorEventListener.cpp
+++ b/editor/libeditor/html/nsHTMLEditorEventListener.cpp
@@ -131,17 +131,17 @@ nsHTMLEditorEventListener::MouseDown(nsI
   //XXX This should be easier to do!
   // But eDOMEvents_contextmenu and NS_CONTEXTMENU is not exposed in any event interface :-(
   PRUint16 buttonNumber;
   nsresult res = mouseEvent->GetButton(&buttonNumber);
   NS_ENSURE_SUCCESS(res, res);
 
   PRBool isContextClick;
 
-#if defined(XP_MAC) || defined(XP_MACOSX)
+#if defined(XP_MACOSX)
   // Ctrl+Click for context menu
   res = mouseEvent->GetCtrlKey(&isContextClick);
   NS_ENSURE_SUCCESS(res, res);
 #else
   // Right mouse button for Windows, UNIX
   isContextClick = buttonNumber == 2;
 #endif
   
--- a/editor/libeditor/text/nsPlaintextEditor.cpp
+++ b/editor/libeditor/text/nsPlaintextEditor.cpp
@@ -413,22 +413,16 @@ nsPlaintextEditor::HandleKeyPressEvent(n
     // we don't PreventDefault() here or keybindings like control-x won't work
     return NS_OK;
   }
   aKeyEvent->PreventDefault();
   nsAutoString str(nativeKeyEvent->charCode);
   return TypedText(str, eTypedText);
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  nsIHTMLEditor methods 
-#pragma mark -
-#endif
-
 /* This routine is needed to provide a bottleneck for typing for logging
    purposes.  Can't use HandleKeyPress() (above) for that since it takes
    a nsIDOMKeyEvent* parameter.  So instead we pass enough info through
    to TypedText() to determine what action to take, but without passing
    an event.
    */
 NS_IMETHODIMP nsPlaintextEditor::TypedText(const nsAString& aString,
                                       PRInt32 aAction)
@@ -1202,22 +1196,16 @@ nsPlaintextEditor::GetNewlineHandling(PR
 NS_IMETHODIMP 
 nsPlaintextEditor::SetNewlineHandling(PRInt32 aNewlineHandling)
 {
   mNewlineHandling = aNewlineHandling;
   
   return NS_OK;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  nsIEditor overrides 
-#pragma mark -
-#endif
-
 NS_IMETHODIMP 
 nsPlaintextEditor::Undo(PRUint32 aCount)
 {
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> kungFuDeathGrip(mRules);
 
   FireTrustedInputEvent trusted(this);
 
@@ -1452,23 +1440,16 @@ nsPlaintextEditor::OutputToStream(nsIOut
   rv = GetAndInitDocEncoder(aFormatType, aFlags, aCharset,
                             getter_AddRefs(encoder));
 
   NS_ENSURE_SUCCESS(rv, rv);
 
   return encoder->EncodeToStream(aOutputStream);
 }
 
-
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  nsIEditorMailSupport overrides 
-#pragma mark -
-#endif
-
 NS_IMETHODIMP
 nsPlaintextEditor::InsertTextWithQuotations(const nsAString &aStringToInsert)
 {
   return InsertText(aStringToInsert);
 }
 
 NS_IMETHODIMP
 nsPlaintextEditor::PasteAsQuotation(PRInt32 aSelectionType)
@@ -1668,23 +1649,16 @@ nsPlaintextEditor::StripCites()
 NS_IMETHODIMP
 nsPlaintextEditor::GetEmbeddedObjects(nsISupportsArray** aNodeList)
 {
   *aNodeList = 0;
   return NS_OK;
 }
 
 
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  nsEditor overrides 
-#pragma mark -
-#endif
-
-
 /** All editor operations which alter the doc should be prefaced
  *  with a call to StartOperation, naming the action and direction */
 NS_IMETHODIMP
 nsPlaintextEditor::StartOperation(PRInt32 opID, nsIEditor::EDirection aDirection)
 {
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> kungFuDeathGrip(mRules);
 
@@ -1736,23 +1710,16 @@ nsPlaintextEditor::SelectEntireDocument(
 already_AddRefed<nsPIDOMEventTarget>
 nsPlaintextEditor::GetPIDOMEventTarget()
 {
   NS_IF_ADDREF(mEventTarget);
   return mEventTarget.get();
 }
 
 
-
-#ifdef XP_MAC
-#pragma mark -
-#pragma mark  Random methods 
-#pragma mark -
-#endif
-
 nsresult
 nsPlaintextEditor::SetAttributeOrEquivalent(nsIDOMElement * aElement,
                                             const nsAString & aAttribute,
                                             const nsAString & aValue,
                                             PRBool aSuppressTransaction)
 {
   return nsEditor::SetAttribute(aElement, aAttribute, aValue);
 }
--- a/editor/libeditor/text/nsTextEditRules.cpp
+++ b/editor/libeditor/text/nsTextEditRules.cpp
@@ -632,17 +632,19 @@ nsTextEditRules::WillInsertText(PRInt32 
   *aHandled = PR_TRUE;
 
   // handle docs with a max length
   // NOTE, this function copies inString into outString for us.
   PRBool truncated = PR_FALSE;
   nsresult res = TruncateInsertionIfNeeded(aSelection, inString, outString,
                                            aMaxLength, &truncated);
   NS_ENSURE_SUCCESS(res, res);
-  if (truncated && outString->IsEmpty()) {
+  // If we're exceeding the maxlength when composing IME, we need to clean up
+  // the composing text, so we shouldn't return early.
+  if (truncated && outString->IsEmpty() && aAction != kInsertTextIME) {
     *aCancel = PR_TRUE;
     return NS_OK;
   }
   
   PRUint32 start = 0;
   PRUint32 end = 0;  
 
   // handle password field docs
--- a/editor/libeditor/text/tests/test_bug596333.html
+++ b/editor/libeditor/text/tests/test_bug596333.html
@@ -39,16 +39,17 @@ function getSpellCheckSelection() {
   return selcon.getSelection(selcon.SELECTION_SPELLCHECK);
 }
 
 function append(str) {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
   var edit = document.getElementById("edit");
   edit.focus();
+  edit.selectionStart = edit.selectionEnd = edit.value.length;
   var editor = getEditor();
 
   for (var i = 0; i < str.length; ++i) {
     synthesizeKey(str[i], {});
   }
 }
 
 function paste(str) {
--- a/editor/txtsvc/src/nsTextServicesDocument.cpp
+++ b/editor/txtsvc/src/nsTextServicesDocument.cpp
@@ -3816,21 +3816,17 @@ nsTextServicesDocument::NodeHasOffsetEnt
 
   *aHasEntry   = PR_FALSE;
   *aEntryIndex = -1;
 
   return NS_OK;
 }
 
 // Spellchecker code has this. See bug 211343
-#ifdef XP_MAC
-#define IS_NBSP_CHAR(c) (((unsigned char)0xca)==(c))
-#else
 #define IS_NBSP_CHAR(c) (((unsigned char)0xa0)==(c))
-#endif
 
 nsresult
 nsTextServicesDocument::FindWordBounds(nsTArray<OffsetEntry*> *aOffsetTable,
                                        nsString *aBlockStr,
                                        nsIDOMNode *aNode,
                                        PRInt32 aNodeOffset,
                                        nsIDOMNode **aWordStartNode,
                                        PRInt32 *aWordStartOffset,
--- a/embedding/android/AndroidManifest.xml.in
+++ b/embedding/android/AndroidManifest.xml.in
@@ -1,16 +1,16 @@
 #filter substitution
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="@ANDROID_PACKAGE_NAME@"
       android:installLocation="auto"
       android:versionCode="@ANDROID_VERSION_CODE@"
       android:versionName="@MOZ_APP_VERSION@"
-      android:sharedUserId="@ANDROID_PACKAGE_NAME@.sharedID">
+      android:sharedUserId="@MOZ_ANDROID_SHARED_ID@">
     <uses-sdk android:minSdkVersion="5"
               android:targetSdkVersion="5"/>
 
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
     <uses-permission android:name="android.permission.INTERNET"/>
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
     <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
@@ -43,16 +43,17 @@
                 <data android:scheme="https" />
                 <data android:scheme="about" />
                 <data android:scheme="javascript" />
             </intent-filter>
             <intent-filter>
                 <action android:name="android.intent.action.VIEW" />
                 <category android:name="android.intent.category.BROWSABLE" />
                 <category android:name="android.intent.category.DEFAULT" />
+                <data android:scheme="file" />
                 <data android:scheme="http" />
                 <data android:scheme="https" />
                 <data android:mimeType="text/html"/>
                 <data android:mimeType="text/plain"/>
                 <data android:mimeType="application/xhtml+xml"/>
             </intent-filter>
             <intent-filter>
                 <action android:name="android.intent.action.WEB_SEARCH" />
--- a/embedding/android/GeckoApp.java
+++ b/embedding/android/GeckoApp.java
@@ -201,16 +201,20 @@ abstract public class GeckoApp
         mainLayout.addView(surfaceView,
                            new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,
                                                         FrameLayout.LayoutParams.FILL_PARENT));
 
         setContentView(mainLayout,
                        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                                                   ViewGroup.LayoutParams.FILL_PARENT));
 
+        mConnectivityFilter = new IntentFilter();
+        mConnectivityFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
+        mConnectivityReceiver = new GeckoConnectivityReceiver();
+
         if (!checkAndSetLaunchState(LaunchState.PreLaunch,
                                     LaunchState.Launching))
             return;
 
         checkAndLaunchUpdate();
         mLibLoadThread = new Thread(new Runnable() {
             public void run() {
                 // At some point while loading the gecko libs our default locale gets set
@@ -250,20 +254,16 @@ abstract public class GeckoApp
                                                            int id)
                                        {
                                            GeckoApp.this.finish();
                                            System.exit(0);
                                        }
                                    })
                 .show();
         }
-
-        mConnectivityFilter = new IntentFilter();
-        mConnectivityFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
-        mConnectivityReceiver = new GeckoConnectivityReceiver();
     }
 
     boolean IsNewInstall() {
         File appIni = new File(sGREDir, "application.ini");
         return !appIni.exists();
     }
 
     boolean IsUnsupportedDevice() {
--- a/embedding/android/Makefile.in
+++ b/embedding/android/Makefile.in
@@ -69,17 +69,17 @@ MIN_CPU_VERSION=5
 endif
 
 ifeq (,$(ANDROID_VERSION_CODE))
 ANDROID_VERSION_CODE=$(shell $(PYTHON) $(topsrcdir)/toolkit/xre/make-platformini.py --print-buildid | cut -c1-10)
 endif
 
 DEFINES += \
   -DANDROID_PACKAGE_NAME=$(ANDROID_PACKAGE_NAME) \
-  -DMOZ_APP_DISPLAYNAME=$(MOZ_APP_DISPLAYNAME) \
+  -DMOZ_APP_DISPLAYNAME="$(MOZ_APP_DISPLAYNAME)" \
   -DMOZ_APP_NAME=$(MOZ_APP_NAME) \
   -DMOZ_APP_VERSION=$(MOZ_APP_VERSION) \
   -DMOZ_CHILD_PROCESS_NAME=$(MOZ_CHILD_PROCESS_NAME) \
   -DMOZ_MIN_CPU_VERSION=$(MIN_CPU_VERSION) \
   -DMOZ_CRASHREPORTER=$(MOZ_CRASHREPORTER) \
   -DANDROID_VERSION_CODE=$(ANDROID_VERSION_CODE) \
   $(NULL)
 
@@ -93,19 +93,25 @@ GARBAGE += \
   $(NULL)
 
 GARBAGE_DIRS += classes res
 
 # Bug 567884 - Need a way to find appropriate icons during packaging
 ifeq ($(MOZ_APP_NAME),fennec)
 ICON_PATH = $(topsrcdir)/$(MOZ_BRANDING_DIRECTORY)/content/fennec_48x48.png
 ICON_PATH_HDPI = $(topsrcdir)/$(MOZ_BRANDING_DIRECTORY)/content/fennec_72x72.png
+ifeq (,$(MOZ_OFFICIAL_BRANDING))
+DEFINES += -DMOZ_ANDROID_SHARED_ID="org.mozilla.fennec.sharedID"
+else
+DEFINES += -DMOZ_ANDROID_SHARED_ID="org.mozilla.firefox.sharedID"
+endif
 else
 ICON_PATH = $(topsrcdir)/$(MOZ_BRANDING_DIRECTORY)/content/icon48.png
 ICON_PATH_HDPI = $(topsrcdir)/$(MOZ_BRANDING_DIRECTORY)/content/icon64.png
+DEFINES += -DMOZ_ANDROID_SHARED_ID="$(ANDROID_PACKAGE_NAME).sharedID"
 endif
 
 RES_LAYOUT = \
   res/layout/notification_progress.xml \
   res/layout/notification_progress_text.xml \
   res/layout/notification_icon_text.xml \
   $(NULL)
 
--- a/embedding/browser/webBrowser/nsDocShellTreeOwner.cpp
+++ b/embedding/browser/webBrowser/nsDocShellTreeOwner.cpp
@@ -1022,21 +1022,16 @@ nsDocShellTreeOwner::GetOwnerRequestor()
     req = mOwnerRequestor;
     NS_ADDREF(mOwnerRequestor);
   }
 
   return req;
 }
 
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
-
 ///////////////////////////////////////////////////////////////////////////////
 // DefaultTooltipTextProvider
 
 class DefaultTooltipTextProvider : public nsITooltipTextProvider
 {
 public:
     DefaultTooltipTextProvider();
 
@@ -1646,22 +1641,16 @@ ChromeTooltipListener::sAutoHideCallback
   if ( self )
     self->HideTooltip();
 
   // NOTE: |aTimer| and |self->mAutoHideTimer| are invalid after calling ClosePopup();
   
 } // sAutoHideCallback
 
 
-
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
-
 NS_IMPL_ADDREF(ChromeContextMenuListener)
 NS_IMPL_RELEASE(ChromeContextMenuListener)
 
 NS_INTERFACE_MAP_BEGIN(ChromeContextMenuListener)
     NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMContextMenuListener)
     NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsIDOMEventListener, nsIDOMContextMenuListener)
     NS_INTERFACE_MAP_ENTRY(nsIDOMContextMenuListener)
 NS_INTERFACE_MAP_END
--- a/embedding/components/commandhandler/src/nsCommandManager.cpp
+++ b/embedding/components/commandhandler/src/nsCommandManager.cpp
@@ -270,20 +270,16 @@ nsCommandManager::DoCommand(const char *
   nsCOMPtr<nsICommandController>  commandController = do_QueryInterface(controller);
   if (commandController && aCommandParams)
     rv = commandController->DoCommandWithParams(aCommandName, aCommandParams);
   else
     rv = controller->DoCommand(aCommandName);
   return rv;
 }
 
-#ifdef XP_MAC
-#pragma mark -
-#endif
-
 nsresult
 nsCommandManager::IsCallerChrome(PRBool *is_caller_chrome)
 {
   *is_caller_chrome = PR_FALSE;
   nsresult rv = NS_OK;
   nsCOMPtr<nsIScriptSecurityManager> secMan = 
       do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
   if (NS_FAILED(rv))
--- a/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.cpp
+++ b/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.cpp
@@ -210,22 +210,17 @@ struct CleanupData
     // catch files that turn into dirs or vice versa.
     PRPackedBool mIsDirectory;
 };
 
 // Maximum file length constant. The max file name length is
 // volume / server dependent but it is difficult to obtain
 // that information. Instead this constant is a reasonable value that
 // modern systems should able to cope with.
-
-#ifdef XP_MAC
-const PRUint32 kDefaultMaxFilenameLength = 31;
-#else
 const PRUint32 kDefaultMaxFilenameLength = 64;
-#endif
 
 // Default flags for persistence
 const PRUint32 kDefaultPersistFlags = 
     nsIWebBrowserPersist::PERSIST_FLAGS_NO_CONVERSION |
     nsIWebBrowserPersist::PERSIST_FLAGS_REPLACE_EXISTING_FILES;
 
 // String bundle where error messages come from
 const char *kWebBrowserPersistStringBundle =
--- a/extensions/pref/autoconfig/src/nsReadConfig.cpp
+++ b/extensions/pref/autoconfig/src/nsReadConfig.cpp
@@ -275,20 +275,17 @@ nsresult nsReadConfig::openAndEvaluateJS
 
     nsCOMPtr<nsIInputStream> inStr;
     if (isBinDir) {
         nsCOMPtr<nsIFile> jsFile;
         rv = NS_GetSpecialDirectory(NS_XPCOM_CURRENT_PROCESS_DIR, 
                                     getter_AddRefs(jsFile));
         if (NS_FAILED(rv)) 
             return rv;
-        
-#ifdef XP_MAC
-        jsFile->AppendNative(NS_LITERAL_CSTRING("Essential Files"));
-#endif
+
         rv = jsFile->AppendNative(nsDependentCString(aFileName));
         if (NS_FAILED(rv)) 
             return rv;
 
         rv = NS_NewLocalFileInputStream(getter_AddRefs(inStr), jsFile);
         if (NS_FAILED(rv)) 
             return rv;
 
--- a/gfx/harfbuzz/src/hb-ot-layout.cc
+++ b/gfx/harfbuzz/src/hb-ot-layout.cc
@@ -478,46 +478,26 @@ hb_ot_layout_position_lookup   (hb_font_
 
 void
 hb_ot_layout_position_finish (hb_face_t *face, hb_buffer_t *buffer)
 {
   /* force diacritics to have zero width */
   unsigned int count = buffer->len;
   if (hb_ot_layout_has_glyph_classes (face)) {
     const GDEF& gdef = _get_gdef (face);
-    if (buffer->props.direction == HB_DIRECTION_RTL) {
-      for (unsigned int i = 1; i < count; i++) {
-        if (gdef.get_glyph_class (buffer->info[i].codepoint) == GDEF::MarkGlyph) {
-          buffer->pos[i].x_advance = 0;
-        }
-      }
-    } else {
-      for (unsigned int i = 1; i < count; i++) {
-        if (gdef.get_glyph_class (buffer->info[i].codepoint) == GDEF::MarkGlyph) {
-          hb_glyph_position_t& pos = buffer->pos[i];
-          pos.x_offset -= pos.x_advance;
-          pos.x_advance = 0;
-        }
+    for (unsigned int i = 1; i < count; i++) {
+      if (gdef.get_glyph_class (buffer->info[i].codepoint) == GDEF::MarkGlyph) {
+        buffer->pos[i].x_advance = 0;
       }
     }
   } else {
     /* no GDEF classes available, so use General Category as a fallback */
-    if (buffer->props.direction == HB_DIRECTION_RTL) {
-      for (unsigned int i = 1; i < count; i++) {
-        if (buffer->info[i].general_category() == HB_CATEGORY_NON_SPACING_MARK) {
-          buffer->pos[i].x_advance = 0;
-        }
-      }
-    } else {
-      for (unsigned int i = 1; i < count; i++) {
-        if (buffer->info[i].general_category() == HB_CATEGORY_NON_SPACING_MARK) {
-          hb_glyph_position_t& pos = buffer->pos[i];
-          pos.x_offset -= pos.x_advance;
-          pos.x_advance = 0;
-        }
+    for (unsigned int i = 1; i < count; i++) {
+      if (buffer->info[i].general_category() == HB_CATEGORY_NON_SPACING_MARK) {
+        buffer->pos[i].x_advance = 0;
       }
     }
   }
 
   GPOS::position_finish (buffer);
 }
 
 
--- a/gfx/layers/ImageLayers.h
+++ b/gfx/layers/ImageLayers.h
@@ -158,16 +158,22 @@ public:
    * Can be called on any thread. This method takes mReentrantMonitor
    * when accessing thread-shared state.
    * 
    * The Image data must not be modified after this method is called!
    */
   virtual void SetCurrentImage(Image* aImage) = 0;
 
   /**
+   * Ask any PlanarYCbCr images created by this container to delay
+   * YUV -> RGB conversion until draw time. See PlanarYCbCrImage::SetDelayedConversion.
+   */
+  virtual void SetDelayedConversion(PRBool aDelayed) {}
+
+  /**
    * Get the current Image.
    * This has to add a reference since otherwise there are race conditions
    * where the current image is destroyed before the caller can add
    * a reference.
    * Can be called on any thread. This method takes mReentrantMonitor
    * when accessing thread-shared state.
    * Implementations must call CurrentImageChanged() while holding
    * mReentrantMonitor.
@@ -410,16 +416,28 @@ public:
   /**
    * This makes a copy of the data buffers.
    * XXX Eventually we will change this to not make a copy of the data,
    * Right now it doesn't matter because the BasicLayer implementation
    * does YCbCr conversion here anyway.
    */
   virtual void SetData(const Data& aData) = 0;
 
+  /**
+   * Ask this Image to not convert YUV to RGB during SetData, and make
+   * the original data available through GetData. This is optional,
+   * and not all PlanarYCbCrImages will support it.
+   */
+  virtual void SetDelayedConversion(PRBool aDelayed) { }
+
+  /**
+   * Grab the original YUV data. This is optional.
+   */
+  virtual const Data* GetData() { return nsnull; }
+
 protected:
   PlanarYCbCrImage(void* aImplData) : Image(aImplData, PLANAR_YCBCR) {}
 };
 
 /**
  * Currently, the data in a CairoImage surface is treated as being in the
  * device output color space.
  */
--- a/gfx/layers/basic/BasicImages.cpp
+++ b/gfx/layers/basic/BasicImages.cpp
@@ -110,62 +110,125 @@ class BasicPlanarYCbCrImage : public Pla
 public:
    /** 
     * aScaleHint is a size that the image is expected to be rendered at.
     * This is a hint for image backends to optimize scaling.
     */
   BasicPlanarYCbCrImage(const gfxIntSize& aScaleHint) :
     PlanarYCbCrImage(static_cast<BasicImageImplData*>(this)),
     mScaleHint(aScaleHint),
-    mOffscreenFormat(gfxASurface::ImageFormatUnknown)
+    mOffscreenFormat(gfxASurface::ImageFormatUnknown),
+    mDelayedConversion(PR_FALSE)
     {}
 
   virtual void SetData(const Data& aData);
+  virtual void SetDelayedConversion(PRBool aDelayed) { mDelayedConversion = aDelayed; }
 
   virtual already_AddRefed<gfxASurface> GetAsSurface();
 
+  const Data* GetData() { return &mData; }
+
   void SetOffscreenFormat(gfxImageFormat aFormat) { mOffscreenFormat = aFormat; }
   gfxImageFormat GetOffscreenFormat() { return mOffscreenFormat; }
 
 protected:
   nsAutoArrayPtr<PRUint8>              mBuffer;
   nsCountedRef<nsMainThreadSurfaceRef> mSurface;
   gfxIntSize                           mScaleHint;
   PRInt32                              mStride;
   gfxImageFormat                       mOffscreenFormat;
+  Data                                 mData;
+  PRUint32                             mBufferSize;
+  PRPackedBool                         mDelayedConversion;
 };
 
 void
 BasicPlanarYCbCrImage::SetData(const Data& aData)
 {
   // Do some sanity checks to prevent integer overflow
   if (aData.mYSize.width > 16384 || aData.mYSize.height > 16384) {
     NS_ERROR("Illegal width or height");
     return;
   }
-
-  gfxASurface::gfxImageFormat format = GetOffscreenFormat();
-
+  
   gfx::YUVType type = gfx::YV12;
+  int width_shift = 0;
+  int height_shift = 0;
   if (aData.mYSize.width == aData.mCbCrSize.width &&
       aData.mYSize.height == aData.mCbCrSize.height) {
     type = gfx::Y