Merge TM -> JM
authorBrian Hackett <bhackett1024@gmail.com>
Thu, 28 Apr 2011 13:02:47 -0700
changeset 74205 02c4a0f752f34165ed948246e84d19fc71ba071d
parent 74204 c03780e2597b7bc122ecad6aff2d11f7877378c1 (current diff)
parent 68874 881c06ebc5eead0674ff38b67d14a18b005d0079 (diff)
child 74206 e0cb191ba87392ce670a053719c26865c1180269
push idunknown
push userunknown
push dateunknown
milestone6.0a1
Merge TM -> JM
accessible/tests/mochitest/tree/test_colorpicker.xul
accessible/tests/mochitest/tree/test_menu.xul
browser/base/content/browser.js
browser/themes/gnomestripe/browser/urlbar-favicon-glow.png
browser/themes/pinstripe/browser/urlbar-favicon-glow.png
browser/themes/winstripe/browser/urlbar-favicon-glow.png
build/package/wince/make_wince_cab.py
build/util.py
build/wince/shunt/Makefile.in
build/wince/shunt/environment.cpp
build/wince/shunt/include/direct.h
build/wince/shunt/include/environment.h
build/wince/shunt/include/errno.h
build/wince/shunt/include/fcntl.h
build/wince/shunt/include/io.h
build/wince/shunt/include/mbstring.h
build/wince/shunt/include/mozce_shunt.h
build/wince/shunt/include/process.h
build/wince/shunt/include/signal.h
build/wince/shunt/include/stdlib.h.in
build/wince/shunt/include/sys/Makefile.in
build/wince/shunt/include/sys/stat.h
build/wince/shunt/include/sys/types.h
build/wince/shunt/include/windows.h.in
build/wince/shunt/include/ymath.h.in
build/wince/shunt/memory.cpp
build/wince/shunt/mozce_shunt.def.in
build/wince/shunt/shunt.cpp
build/wince/shunt/time.cpp
build/wince/shunt/time_conversions.h
build/wince/tools/Makefile
build/wince/tools/Makefile.in
build/wince/tools/arm-wince-as.c
build/wince/tools/arm-wince-gcc.c
build/wince/tools/arm-wince-lib.c
build/wince/tools/arm-wince-link.c
build/wince/tools/arm-wince-res.c
build/wince/tools/linkargs.c
build/wince/tools/linkargs.h
build/wince/tools/toolspath.c
build/wince/tools/toolspath.h
content/base/public/nsIContentUtils.h
content/events/public/nsIEventStateManager.h
content/events/test/Makefile.in
content/html/content/reftests/409604-1-ref.html
content/html/content/reftests/409604-1.html
content/html/content/reftests/583514-1-ref.html
content/html/content/reftests/583514-1.html
content/html/content/reftests/583514-2-ref.html
content/html/content/reftests/583514-2.html
content/xslt/public/nsIXSLTProcessorObsolete.idl
dom/base/nsDOMClassInfo.cpp
dom/base/nsGlobalWindow.cpp
dom/interfaces/core/nsIDOMDOMConfiguration.idl
gfx/src/nsIDeviceContext.h
gfx/src/nsIFontMetrics.h
gfx/src/nsIRenderingContext.h
gfx/src/nsIThebesFontMetrics.h
gfx/src/nsThebesDeviceContext.cpp
gfx/src/nsThebesDeviceContext.h
gfx/src/nsThebesFontMetrics.cpp
gfx/src/nsThebesFontMetrics.h
gfx/src/nsThebesRenderingContext.cpp
gfx/src/nsThebesRenderingContext.h
intl/uconv/src/nsUConvDll.cpp
intl/uconv/src/nsUConvDll.h
intl/uconv/src/nsUCvMinDll.h
js/src/GlobalObject.cpp
js/src/Makefile.in
js/src/assembler/assembler/X86Assembler.h
js/src/config/autoconf.mk.in
js/src/configure.in
js/src/jit-test/tests/basic/bug618853.js
js/src/jit-test/tests/basic/bug619338.js
js/src/jit-test/tests/basic/bug630865-1.js
js/src/jit-test/tests/basic/bug630865-2.js
js/src/jit-test/tests/basic/bug630865-3.js
js/src/jit-test/tests/basic/bug630865-4.js
js/src/jit-test/tests/basic/bug643249.js
js/src/jsanalyze.cpp
js/src/jsapi-tests/Makefile.in
js/src/jsapi-tests/testConservativeGC.cpp
js/src/jsapi.cpp
js/src/jsapi.h
js/src/jsarray.cpp
js/src/jscntxt.cpp
js/src/jscntxt.h
js/src/jscntxtinlines.h
js/src/jscompartment.cpp
js/src/jscompartment.h
js/src/jsdate.cpp
js/src/jsdbgapi.cpp
js/src/jsemit.cpp
js/src/jsexn.cpp
js/src/jsfun.cpp
js/src/jsfun.h
js/src/jsgc.cpp
js/src/jsgc.h
js/src/jsgcinlines.h
js/src/jsgcmark.cpp
js/src/jsinfer.cpp
js/src/jsinferinlines.h
js/src/jsinterp.cpp
js/src/jsinterp.h
js/src/jsinterpinlines.h
js/src/jsiter.cpp
js/src/jsmath.cpp
js/src/jsnum.cpp
js/src/jsobj.cpp
js/src/jsobj.h
js/src/jsobjinlines.h
js/src/json.cpp
js/src/jsopcode.cpp
js/src/jsparse.cpp
js/src/jsparse.h
js/src/jspropertycache.cpp
js/src/jsproxy.cpp
js/src/jsreflect.cpp
js/src/jsregexp.cpp
js/src/jsregexpinlines.h
js/src/jsscope.cpp
js/src/jsscope.h
js/src/jsscopeinlines.h
js/src/jsscript.cpp
js/src/jsscript.h
js/src/jsscriptinlines.h
js/src/jsstr.cpp
js/src/jsstrinlines.h
js/src/jstracer.cpp
js/src/jstracer.h
js/src/jsvalue.h
js/src/jswrapper.cpp
js/src/jswrapper.h
js/src/jsxml.cpp
js/src/methodjit/BaseAssembler.h
js/src/methodjit/Compiler.cpp
js/src/methodjit/Compiler.h
js/src/methodjit/FastOps.cpp
js/src/methodjit/FrameState-inl.h
js/src/methodjit/FrameState.cpp
js/src/methodjit/FrameState.h
js/src/methodjit/InlineFrameAssembler.h
js/src/methodjit/InvokeHelpers.cpp
js/src/methodjit/MachineRegs.h
js/src/methodjit/MethodJIT.cpp
js/src/methodjit/MethodJIT.h
js/src/methodjit/MonoIC.cpp
js/src/methodjit/MonoIC.h
js/src/methodjit/PolyIC.cpp
js/src/methodjit/PolyIC.h
js/src/methodjit/PunboxAssembler.h
js/src/methodjit/RematInfo.h
js/src/methodjit/Retcon.cpp
js/src/methodjit/Retcon.h
js/src/methodjit/StubCalls.cpp
js/src/methodjit/StubCalls.h
js/src/methodjit/StubCompiler.cpp
js/src/methodjit/StubCompiler.h
js/src/methodjit/TrampolineCompiler.cpp
js/src/methodjit/TrampolineSUNWX86.s
js/src/shell/js.cpp
js/src/tests/js1_8_5/regress/jstests.list
js/src/tracejit/Writer.cpp
js/src/tracejit/Writer.h
js/src/vm/Stack-inl.h
js/src/vm/Stack.cpp
js/src/vm/Stack.h
js/src/xpconnect/loader/mozJSLoaderConstructors.h
js/src/xpconnect/shell/xpcshell.cpp
js/src/xpconnect/src/xpcdebug.cpp
js/src/xpconnect/src/xpcwrappednative.cpp
js/src/xpconnect/wrappers/WrapperFactory.cpp
layout/base/tests/test_bug370436.html
layout/base/tests/test_bug420499.xul
mobile/installer/wince/Makefile.in
mobile/installer/wince/Setup.cpp
mobile/installer/wince/Setup.def
modules/libpref/src/init/all.js
other-licenses/branding/firefox/LICENSE
other-licenses/branding/firefox/Makefile.in
other-licenses/branding/firefox/background.png
other-licenses/branding/firefox/branding.nsi
other-licenses/branding/firefox/configure.sh
other-licenses/branding/firefox/content/Makefile.in
other-licenses/branding/firefox/content/about-logo.png
other-licenses/branding/firefox/content/about-wordmark.png
other-licenses/branding/firefox/content/about.png
other-licenses/branding/firefox/content/icon48.png
other-licenses/branding/firefox/content/icon64.png
other-licenses/branding/firefox/content/jar.mn
other-licenses/branding/firefox/default16.png
other-licenses/branding/firefox/default22.png
other-licenses/branding/firefox/default24.png
other-licenses/branding/firefox/default256.png
other-licenses/branding/firefox/default32.png
other-licenses/branding/firefox/default48.png
other-licenses/branding/firefox/disk.icns
other-licenses/branding/firefox/document-os2.ico
other-licenses/branding/firefox/document.icns
other-licenses/branding/firefox/document.ico
other-licenses/branding/firefox/document.png
other-licenses/branding/firefox/dsstore
other-licenses/branding/firefox/firefox-os2.ico
other-licenses/branding/firefox/firefox.icns
other-licenses/branding/firefox/firefox.ico
other-licenses/branding/firefox/locales/Makefile.in
other-licenses/branding/firefox/locales/browserconfig.properties
other-licenses/branding/firefox/locales/en-US/brand.dtd
other-licenses/branding/firefox/locales/en-US/brand.properties
other-licenses/branding/firefox/locales/jar.mn
other-licenses/branding/firefox/mozicon128.png
other-licenses/branding/firefox/pref/firefox-branding.js
other-licenses/branding/firefox/splash.bmp
other-licenses/branding/firefox/wizHeader.bmp
other-licenses/branding/firefox/wizHeaderRTL.bmp
other-licenses/branding/firefox/wizWatermark.bmp
testing/mochitest/tests/SimpleTest/tests/Makefile.in
testing/mochitest/tests/SimpleTest/tests/test_synthesizeDragStart.xul
testing/mochitest/tests/SimpleTest/tests/test_synthesizeDrop.xul
toolkit/components/console/hudservice/tests/browser/test-bug-595934-dom-events-external.html
toolkit/components/console/hudservice/tests/browser/test-bug-595934-dom-events-external.js
widget/src/windows/nsClipboardCE.cpp
widget/src/windows/nsClipboardCE.h
widget/src/windows/nsWindowCE.cpp
widget/src/windows/nsWindowCE.h
xpcom/tests/xptinfo/Makefile.in
xpcom/tests/xptinfo/xptiITestInterface.idl
xpcom/tests/xptinfo/xptunit/test_jar_xptloading.js
xpcom/typelib/xpt/tools/xpt_dump.c
xpcom/typelib/xpt/tools/xpt_link.c
--- a/Makefile.in
+++ b/Makefile.in
@@ -83,21 +83,16 @@ include $(topsrcdir)/config/config.mk
 
 GARBAGE_DIRS += dist _javagen _profile _tests staticlib
 DIST_GARBAGE = config.cache config.log config.status config-defs.h \
    config/autoconf.mk \
    unallmakefiles mozilla-config.h \
    netwerk/necko-config.h xpcom/xpcom-config.h xpcom/xpcom-private.h \
    $(topsrcdir)/.mozconfig.mk $(topsrcdir)/.mozconfig.out
 
-ifdef WINCE
-check::
-	$(PYTHON) $(topsrcdir)/build/mobile/devicemanager-utils.py copy $(DIST)/bin
-endif
-
 default alldep all:: $(topsrcdir)/configure config.status
 	$(RM) -r $(DIST)/sdk
 	$(RM) -r $(DIST)/include
 	$(RM) -r $(DIST)/private
 	$(RM) -r $(DIST)/public
 	$(RM) -r $(DIST)/bin/components
 	$(RM) -r _tests
 
@@ -190,31 +185,16 @@ endif
 	$(NSINSTALL) -D $(DIST)/$(PKG_PATH)
 	cd $(DIST)/crashreporter-symbols && \
           zip -r9D "../$(PKG_PATH)$(SYMBOL_FULL_ARCHIVE_BASENAME).zip" .
 	cd $(DIST)/crashreporter-symbols && \
 	grep "sym" $(SYMBOL_INDEX_NAME) > $(SYMBOL_INDEX_NAME).tmp && \
 	  mv $(SYMBOL_INDEX_NAME).tmp $(SYMBOL_INDEX_NAME)
 	cd $(DIST)/crashreporter-symbols && \
           zip -r9D "../$(PKG_PATH)$(SYMBOL_ARCHIVE_BASENAME).zip" . -i "*.sym" -i "*.txt"
-else
-ifdef WINCE
-ifdef SYMBOLSTORE_PATH
-	echo building symbol store with symstore.exe
-	$(RM) -r $(DIST)/symbols
-	$(RM) "$(DIST)/$(SYMBOL_ARCHIVE_BASENAME).zip"
-	$(NSINSTALL) -D $(DIST)/symbols
-	$(SYMBOLSTORE_PATH) add -r -f "$(subst /,\,$(shell pwd -W))\*.PDB" \
-	  -s $(DIST)/symbols/ -t "$(MOZ_PKG_APPNAME)" -v "$(MOZ_PKG_VERSION)"
-	echo packing symbols
-	$(NSINSTALL) -D $(DIST)/$(PKG_PATH)
-	cd $(DIST)/symbols && \
-	  zip -r9D "../$(PKG_PATH)$(SYMBOL_ARCHIVE_BASENAME).zip" .
-endif # SYMBOLSTORE_PATH
-endif # WINCE
 endif # MOZ_CRASHREPORTER
 
 uploadsymbols:
 ifdef MOZ_CRASHREPORTER
 	$(SHELL) $(topsrcdir)/toolkit/crashreporter/tools/upload_symbols.sh "$(DIST)/$(PKG_PATH)$(SYMBOL_FULL_ARCHIVE_BASENAME).zip"
 endif
 
 # defined in package-name.mk
--- a/accessible/src/atk/nsAccessNodeWrap.cpp
+++ b/accessible/src/atk/nsAccessNodeWrap.cpp
@@ -33,16 +33,19 @@
  * 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 "nsAccessNodeWrap.h"
 #include "nsApplicationAccessibleWrap.h"
+#include "nsMaiInterfaceText.h"
+
+PRBool nsAccessNodeWrap::gHaveNewTextSignals = PR_FALSE;
 
 /* For documentation of the accessibility architecture, 
  * see http://lxr.mozilla.org/seamonkey/source/accessible/accessible-docs.html
  */
 
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessNodeWrap
@@ -63,15 +66,16 @@ nsAccessNodeWrap::
 //-----------------------------------------------------
 nsAccessNodeWrap::~nsAccessNodeWrap()
 {
 }
 
 void nsAccessNodeWrap::InitAccessibility()
 {
   nsAccessNode::InitXPAccessibility();
+  gHaveNewTextSignals = g_signal_lookup("text-insert", ATK_TYPE_TEXT);
 }
 
 void nsAccessNodeWrap::ShutdownAccessibility()
 {
   nsAccessNode::ShutdownXPAccessibility();
 }
 
--- a/accessible/src/atk/nsAccessNodeWrap.h
+++ b/accessible/src/atk/nsAccessNodeWrap.h
@@ -48,11 +48,18 @@
 class nsAccessNodeWrap :  public nsAccessNode
 {
 public: // construction, destruction
     nsAccessNodeWrap(nsIContent *aContent, nsIWeakReference *aShell);
     virtual ~nsAccessNodeWrap();
 
     static void InitAccessibility();
     static void ShutdownAccessibility();
+
+    /*
+     * do we have text-remove and text-insert signals if not we need to use
+     * text-changed see nsAccessibleWrap::FireAtkTextChangedEvent() and
+     * bug 619002
+     */
+    static PRBool gHaveNewTextSignals;
 };
 
 #endif
--- a/accessible/src/atk/nsAccessibleWrap.cpp
+++ b/accessible/src/atk/nsAccessibleWrap.cpp
@@ -1356,24 +1356,37 @@ nsAccessibleWrap::FireAtkTextChangedEven
     MAI_LOG_DEBUG(("\n\nReceived: EVENT_TEXT_REMOVED/INSERTED\n"));
 
     AccTextChangeEvent* event = downcast_accEvent(aEvent);
     NS_ENSURE_TRUE(event, NS_ERROR_FAILURE);
 
     PRInt32 start = event->GetStartOffset();
     PRUint32 length = event->GetLength();
     PRBool isInserted = event->IsTextInserted();
-
     PRBool isFromUserInput = aEvent->IsFromUserInput();
+    char* signal_name = nsnull;
 
-    char *signal_name = g_strconcat(isInserted ? "text_changed::insert" : "text_changed::delete",
-                                    isFromUserInput ? "" : kNonUserInputEvent, NULL);
-    g_signal_emit_by_name(aObject, signal_name, start, length);
-    g_free (signal_name);
+    if (gHaveNewTextSignals) {
+        nsAutoString text;
+        event->GetModifiedText(text);
+        signal_name = g_strconcat(isInserted ? "text-insert" : "text-remove",
+                                  isFromUserInput ? "" : "::system", NULL);
+        g_signal_emit_by_name(aObject, signal_name, start, length,
+                              NS_ConvertUTF16toUTF8(text).get());
+    } else {
+        // XXX remove this code and the gHaveNewTextSignals check when we can
+        // stop supporting old atk since it doesn't really work anyway
+        // see bug 619002
+        signal_name = g_strconcat(isInserted ? "text_changed::insert" :
+                                  "text_changed::delete",
+                                  isFromUserInput ? "" : kNonUserInputEvent, NULL);
+        g_signal_emit_by_name(aObject, signal_name, start, length);
+    }
 
+    g_free(signal_name);
     return NS_OK;
 }
 
 nsresult
 nsAccessibleWrap::FireAtkShowHideEvent(AccEvent* aEvent,
                                        AtkObject *aObject, PRBool aIsAdded)
 {
     if (aIsAdded)
--- a/accessible/src/base/AccEvent.cpp
+++ b/accessible/src/base/AccEvent.cpp
@@ -45,17 +45,17 @@
 #include "nsDocAccessible.h"
 #include "nsIAccessibleText.h"
 #ifdef MOZ_XUL
 #include "nsXULTreeAccessible.h"
 #endif
 #include "nsAccEvent.h"
 
 #include "nsIDOMDocument.h"
-#include "nsIEventStateManager.h"
+#include "nsEventStateManager.h"
 #include "nsIServiceManager.h"
 #ifdef MOZ_XUL
 #include "nsIDOMXULMultSelectCntrlEl.h"
 #endif
 
 ////////////////////////////////////////////////////////////////////////////////
 // AccEvent
 ////////////////////////////////////////////////////////////////////////////////
@@ -198,17 +198,17 @@ AccEvent::CaptureIsFromUserInput(EIsFrom
     return;
 
   nsIPresShell *presShell = nsCoreUtils::GetPresShellFor(targetNode);
   if (!presShell) {
     NS_NOTREACHED("Threre should always be an pres shell for an event");
     return;
   }
 
-  nsIEventStateManager *esm = presShell->GetPresContext()->EventStateManager();
+  nsEventStateManager *esm = presShell->GetPresContext()->EventStateManager();
   if (!esm) {
     NS_NOTREACHED("There should always be an ESM for an event");
     return;
   }
 
   mIsFromUserInput = esm->IsHandlingUserInputExternal();
 }
 
--- a/accessible/src/base/nsAccessibilityAtomList.h
+++ b/accessible/src/base/nsAccessibilityAtomList.h
@@ -59,17 +59,16 @@
 ACCESSIBILITY_ATOM(button, "button")
 ACCESSIBILITY_ATOM(checkbox, "checkbox")
 ACCESSIBILITY_ATOM(col, "col")
 ACCESSIBILITY_ATOM(_empty, "")
 ACCESSIBILITY_ATOM(_false, "false")
 ACCESSIBILITY_ATOM(image, "image")
 ACCESSIBILITY_ATOM(menu, "menu")
 ACCESSIBILITY_ATOM(menuButton, "menu-button")
-ACCESSIBILITY_ATOM(menugenerated, "menugenerated")
 ACCESSIBILITY_ATOM(multiple, "multiple")
 ACCESSIBILITY_ATOM(open, "open")
 ACCESSIBILITY_ATOM(password, "password")
 ACCESSIBILITY_ATOM(radio, "radio")
 ACCESSIBILITY_ATOM(reset, "reset")
 ACCESSIBILITY_ATOM(row, "row")
 ACCESSIBILITY_ATOM(submit, "submit")
 ACCESSIBILITY_ATOM(_true, "true")
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -70,17 +70,17 @@
 #include "nsIObserverService.h"
 #include "nsIPluginInstance.h"
 #include "nsISupportsUtils.h"
 #include "nsObjectFrame.h"
 #include "nsOuterDocAccessible.h"
 #include "nsRootAccessibleWrap.h"
 #include "nsTextFragment.h"
 #include "mozilla/Services.h"
-#include "nsIEventStateManager.h"
+#include "nsEventStates.h"
 
 #ifdef MOZ_XUL
 #include "nsXULAlertAccessible.h"
 #include "nsXULColorPickerAccessible.h"
 #include "nsXULComboboxAccessible.h"
 #include "nsXULFormControlAccessible.h"
 #include "nsXULListboxAccessibleWrap.h"
 #include "nsXULMenuAccessibleWrap.h"
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -94,17 +94,17 @@
 #include "nsIURI.h"
 #include "nsArrayUtils.h"
 #include "nsIMutableArray.h"
 #include "nsIObserverService.h"
 #include "nsIServiceManager.h"
 #include "nsWhitespaceTokenizer.h"
 #include "nsAttrName.h"
 #include "nsNetUtil.h"
-#include "nsIEventStateManager.h"
+#include "nsEventStates.h"
 
 #ifdef NS_DEBUG
 #include "nsIDOMCharacterData.h"
 #endif
 
 #include "mozilla/unused.h"
 
 
--- a/accessible/src/base/nsCoreUtils.cpp
+++ b/accessible/src/base/nsCoreUtils.cpp
@@ -55,17 +55,17 @@
 #include "nsIDOMWindowInternal.h"
 #include "nsIDOMXULElement.h"
 #include "nsIDocShell.h"
 #include "nsIContentViewer.h"
 #include "nsIEventListenerManager.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 #include "nsIScrollableFrame.h"
-#include "nsIEventStateManager.h"
+#include "nsEventStateManager.h"
 #include "nsISelection2.h"
 #include "nsISelectionController.h"
 #include "nsPIDOMWindow.h"
 #include "nsGUIEvent.h"
 #include "nsIView.h"
 
 #include "nsContentCID.h"
 #include "nsComponentManagerUtils.h"
@@ -201,39 +201,37 @@ nsCoreUtils::DispatchMouseEvent(PRUint32
 PRUint32
 nsCoreUtils::GetAccessKeyFor(nsIContent *aContent)
 {
   if (!aContent)
     return 0;
 
   // Accesskeys are registered by @accesskey attribute only. At first check
   // whether it is presented on the given element to avoid the slow
-  // nsIEventStateManager::GetRegisteredAccessKey() method.
+  // nsEventStateManager::GetRegisteredAccessKey() method.
   if (!aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::accesskey))
     return 0;
 
   nsCOMPtr<nsIDocument> doc = aContent->GetOwnerDoc();
   if (!doc)
     return 0;
 
   nsCOMPtr<nsIPresShell> presShell = doc->GetShell();
   if (!presShell)
     return 0;
 
   nsPresContext *presContext = presShell->GetPresContext();
   if (!presContext)
     return 0;
 
-  nsIEventStateManager *esm = presContext->EventStateManager();
+  nsEventStateManager *esm = presContext->EventStateManager();
   if (!esm)
     return 0;
 
-  PRUint32 key = 0;
-  esm->GetRegisteredAccessKey(aContent, &key);
-  return key;
+  return esm->GetRegisteredAccessKey(aContent);
 }
 
 nsIContent *
 nsCoreUtils::GetDOMElementFor(nsIContent *aContent)
 {
   if (aContent->IsElement())
     return aContent;
 
@@ -756,57 +754,16 @@ nsCoreUtils::IsColumnHidden(nsITreeColum
 {
   nsCOMPtr<nsIDOMElement> element;
   aColumn->GetElement(getter_AddRefs(element));
   nsCOMPtr<nsIContent> content = do_QueryInterface(element);
   return content->AttrValueIs(kNameSpaceID_None, nsAccessibilityAtoms::hidden,
                               nsAccessibilityAtoms::_true, eCaseMatters);
 }
 
-void
-nsCoreUtils::GeneratePopupTree(nsIContent *aContent, PRBool aIsAnon)
-{
-  // Set menugenerated="true" on the menupopup node to generate the sub-menu
-  // items if they have not been generated.
-
-  nsCOMPtr<nsIDOMNodeList> list;
-  if (aIsAnon) {    
-    nsIDocument* document = aContent->GetCurrentDoc();
-    if (document)
-      document->GetXBLChildNodesFor(aContent, getter_AddRefs(list));
-
-  } else {
-    list = aContent->GetChildNodesList();
-  }
-
-  PRUint32 length = 0;
-  if (!list || NS_FAILED(list->GetLength(&length)))
-    return;
-
-  for (PRUint32 idx = 0; idx < length; idx++) {
-    nsCOMPtr<nsIDOMNode> childNode;
-    list->Item(idx, getter_AddRefs(childNode));
-    nsCOMPtr<nsIContent> child(do_QueryInterface(childNode));
-
-    PRBool isPopup = child->NodeInfo()->Equals(nsAccessibilityAtoms::menupopup,
-                                               kNameSpaceID_XUL) ||
-                     child->NodeInfo()->Equals(nsAccessibilityAtoms::panel,
-                                               kNameSpaceID_XUL);
-    if (isPopup && !child->AttrValueIs(kNameSpaceID_None,
-                                       nsAccessibilityAtoms::menugenerated,
-                                       nsAccessibilityAtoms::_true,
-                                       eCaseMatters)) {
-
-      child->SetAttr(kNameSpaceID_None, nsAccessibilityAtoms::menugenerated,
-                     NS_LITERAL_STRING("true"), PR_TRUE);
-      return;
-    }
-  }
-}
-
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessibleDOMStringList
 ////////////////////////////////////////////////////////////////////////////////
 
 NS_IMPL_ISUPPORTS1(nsAccessibleDOMStringList, nsIDOMDOMStringList)
 
 NS_IMETHODIMP
--- a/accessible/src/base/nsCoreUtils.h
+++ b/accessible/src/base/nsCoreUtils.h
@@ -105,17 +105,17 @@ public:
    */
   static void DispatchMouseEvent(PRUint32 aEventType, PRInt32 aX, PRInt32 aY,
                                  nsIContent *aContent, nsIFrame *aFrame,
                                  nsIPresShell *aPresShell,
                                  nsIWidget *aRootWidget);
 
   /**
    * Return an accesskey registered on the given element by
-   * nsIEventStateManager or 0 if there is no registered accesskey.
+   * nsEventStateManager or 0 if there is no registered accesskey.
    *
    * @param aContent - the given element.
    */
   static PRUint32 GetAccessKeyFor(nsIContent *aContent);
 
   /**
    * Return DOM element related with the given node, i.e.
    * a) itself if it is DOM element
@@ -362,26 +362,16 @@ public:
   /**
    * Return true if the given node is table header element.
    */
   static PRBool IsHTMLTableHeader(nsIContent *aContent)
   {
     return aContent->NodeInfo()->Equals(nsAccessibilityAtoms::th) ||
       aContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::scope);
   }
-
-  /**
-   * Generates frames for popup subtree.
-   *
-   * @param aContent [in] DOM node containing the menupopup element as a child
-   * @param aIsAnon  [in] specifies whether popup should be searched inside of
-   *                  anonymous or explicit content
-   */
-  static void GeneratePopupTree(nsIContent *aContent,
-                                PRBool aIsAnon = PR_FALSE);
 };
 
 
 /**
  * nsIDOMDOMStringList implementation.
  */
 class nsAccessibleDOMStringList : public nsIDOMDOMStringList
 {
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -56,17 +56,17 @@
 #include "nsIDOMDocumentType.h"
 #include "nsIDOMNSDocument.h"
 #include "nsIDOMNSHTMLDocument.h"
 #include "nsIDOMXULDocument.h"
 #include "nsIDOMMutationEvent.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDOMXULPopupElement.h"
 #include "nsIEditingSession.h"
-#include "nsIEventStateManager.h"
+#include "nsEventStateManager.h"
 #include "nsIFrame.h"
 #include "nsHTMLSelectAccessible.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsINameSpaceManager.h"
 #include "nsIPresShell.h"
 #include "nsIServiceManager.h"
 #include "nsIViewManager.h"
 #include "nsIScrollableFrame.h"
--- a/accessible/src/base/nsOuterDocAccessible.cpp
+++ b/accessible/src/base/nsOuterDocAccessible.cpp
@@ -84,17 +84,17 @@ nsOuterDocAccessible::GetChildAtPoint(PR
   if (aX < docX || aX >= docX + docWidth || aY < docY || aY >= docY + docHeight)
     return nsnull;
 
   // Always return the inner doc as direct child accessible unless bounds
   // outside of it.
   nsAccessible* child = GetChildAt(0);
   NS_ENSURE_TRUE(child, nsnull);
 
-  if (aWhichChild = eDeepestChild)
+  if (aWhichChild == eDeepestChild)
     return child->GetChildAtPoint(aX, aY, eDeepestChild);
   return child;
 }
 
 nsresult
 nsOuterDocAccessible::GetAttributesInternal(nsIPersistentProperties *aAttributes)
 {
   nsAutoString tag;
--- a/accessible/src/base/nsTextAttrs.cpp
+++ b/accessible/src/base/nsTextAttrs.cpp
@@ -39,17 +39,17 @@
 #include "nsTextAttrs.h"
 
 #include "nsAccUtils.h"
 #include "nsCoreUtils.h"
 #include "nsHyperTextAccessibleWrap.h"
 
 #include "gfxFont.h"
 #include "gfxUserFontSet.h"
-#include "nsIThebesFontMetrics.h"
+#include "nsFontMetrics.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // Constants and structures
 
 /**
  * Item of the gCSSTextAttrsMap map.
  */
 struct nsCSSTextAttrMapItem
@@ -461,17 +461,17 @@ nsFontSizeTextAttr::Format(const nscoord
   //
   // Note: according to IA2, "The conversion doesn't have to be exact.
   // The intent is to give the user a feel for the size of the text."
   // 
   // ATK does not specify a unit and will likely follow IA2 here.
   //
   // XXX todo: consider sharing this code with layout module? (bug 474621)
   float px =
-    NSAppUnitsToFloatPixels(aValue, nsIDeviceContext::AppUnitsPerCSSPixel());
+    NSAppUnitsToFloatPixels(aValue, nsDeviceContext::AppUnitsPerCSSPixel());
   // Each pt is 4/3 of a CSS pixel.
   int pts = NS_lround(px*3/4);
 
   nsAutoString value;
   value.AppendInt(pts);
   value.Append(NS_LITERAL_STRING("pt"));
   aFormattedValue = value;
 }
@@ -527,23 +527,22 @@ nsFontWeightTextAttr::GetFontWeight(nsIF
 {
   // nsFont::width isn't suitable here because it's necessary to expose real
   // value of font weight (used font might not have some font weight values).
   nsStyleFont* styleFont =
     (nsStyleFont*)(aFrame->GetStyleDataExternal(eStyleStruct_Font));
 
   gfxUserFontSet *fs = aFrame->PresContext()->GetUserFontSet();
 
-  nsCOMPtr<nsIFontMetrics> fm;
+  nsRefPtr<nsFontMetrics> fm;
   aFrame->PresContext()->DeviceContext()->
     GetMetricsFor(styleFont->mFont, aFrame->GetStyleVisibility()->mLanguage,
                   fs, *getter_AddRefs(fm));
 
-  nsCOMPtr<nsIThebesFontMetrics> tfm = do_QueryInterface(fm);
-  gfxFontGroup *fontGroup = tfm->GetThebesFontGroup();
+  gfxFontGroup *fontGroup = fm->GetThebesFontGroup();
   gfxFont *font = fontGroup->GetFontAt(0);
 
   // When there doesn't exist a bold font in the family and so the rendering of
   // a non-bold font face is changed so that the user sees what looks like a
   // bold font, i.e. synthetic bolding is used. IsSyntheticBold method is only
   // needed on Mac, but it is "safe" to use on all platforms.  (For non-Mac
   // platforms it always return false.)
   if (font->IsSyntheticBold())
--- a/accessible/src/base/nsTextAttrs.h
+++ b/accessible/src/base/nsTextAttrs.h
@@ -332,17 +332,17 @@ private:
   /**
    * Return font size for the given frame.
    *
    * @param aFrame      [in] the given frame to query font-size
    * @return            font size
    */
    nscoord GetFontSize(nsIFrame *aFrame);
 
-  nsIDeviceContext *mDC;
+  nsDeviceContext *mDC;
 };
 
 
 /**
  * Class is used for the work with "font-weight" text attribute in
  * nsTextAttrsMgr class.
  */
 class nsFontWeightTextAttr : public nsTextAttr<PRInt32>
--- a/accessible/src/html/nsHTMLFormControlAccessible.cpp
+++ b/accessible/src/html/nsHTMLFormControlAccessible.cpp
@@ -417,16 +417,19 @@ nsHTMLTextFieldAccessible::GetNameIntern
   // text inputs and textareas might have useful placeholder text
   mContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::placeholder, aName);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP nsHTMLTextFieldAccessible::GetValue(nsAString& _retval)
 {
+  if (IsDefunct())
+    return NS_ERROR_FAILURE;
+
   if (NativeState() & states::PROTECTED)    // Don't return password text!
     return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIDOMHTMLTextAreaElement> textArea(do_QueryInterface(mContent));
   if (textArea) {
     return textArea->GetValue(_retval);
   }
   
--- a/accessible/src/html/nsHTMLLinkAccessible.cpp
+++ b/accessible/src/html/nsHTMLLinkAccessible.cpp
@@ -37,17 +37,17 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsHTMLLinkAccessible.h"
 
 #include "States.h"
 #include "nsCoreUtils.h"
 
-#include "nsIEventStateManager.h"
+#include "nsEventStates.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLLinkAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLLinkAccessible::
   nsHTMLLinkAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsHyperTextAccessibleWrap(aContent, aShell)
--- a/accessible/src/html/nsHyperTextAccessible.cpp
+++ b/accessible/src/html/nsHyperTextAccessible.cpp
@@ -53,17 +53,16 @@
 #include "nsPIDOMWindow.h"        
 #include "nsIDOMDocumentView.h"
 #include "nsIDOMRange.h"
 #include "nsIDOMNSRange.h"
 #include "nsIDOMWindowInternal.h"
 #include "nsIDOMXULDocument.h"
 #include "nsIEditingSession.h"
 #include "nsIEditor.h"
-#include "nsIFontMetrics.h"
 #include "nsIFrame.h"
 #include "nsFrameSelection.h"
 #include "nsILineIterator.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIPlaintextEditor.h"
 #include "nsIScrollableFrame.h"
 #include "nsISelection2.h"
 #include "nsISelectionPrivate.h"
@@ -306,17 +305,17 @@ nsHyperTextAccessible::GetPosAndText(PRI
     return nsnull;
   }
 
   nsIFrame *startFrame = nsnull;
   if (aEndFrame) {
     *aEndFrame = nsnull;
   }
   if (aBoundsRect) {
-    aBoundsRect->Empty();
+    aBoundsRect->SetEmpty();
   }
   if (aStartAcc)
     *aStartAcc = nsnull;
   if (aEndAcc)
     *aEndAcc = nsnull;
 
   nsIntRect unionRect;
   nsAccessible *lastAccessible = nsnull;
--- a/accessible/src/msaa/nsTextAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsTextAccessibleWrap.cpp
@@ -31,29 +31,24 @@
  * 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 ***** */
 
-// NOTE: alphabetically ordered
 #include "nsTextAccessibleWrap.h"
 #include "ISimpleDOMText_i.c"
 
 #include "nsCoreUtils.h"
 #include "nsDocAccessible.h"
-
-#include "nsIThebesFontMetrics.h"
 #include "nsIFrame.h"
+#include "nsFontMetrics.h"
 #include "nsPresContext.h"
-#include "nsIPresShell.h"
-#include "nsIRenderingContext.h"
-#include "nsIComponentManager.h"
 
 #include "gfxFont.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsTextAccessibleWrap Accessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsTextAccessibleWrap::
@@ -255,26 +250,24 @@ STDMETHODIMP nsTextAccessibleWrap::get_f
 __try {
   *aFontFamily = NULL;
 
   nsIFrame* frame = GetFrame();
   if (!frame) {
     return E_FAIL;
   }
 
-  nsCOMPtr<nsIFontMetrics> fm;
+  nsRefPtr<nsFontMetrics> fm;
   frame->PresContext()->DeviceContext()->
     GetMetricsFor(frame->GetStyleFont()->mFont,
                   frame->GetStyleVisibility()->mLanguage,
                   frame->PresContext()->GetUserFontSet(),
                   *getter_AddRefs(fm));
 
-  nsCOMPtr<nsIThebesFontMetrics> tfm = do_QueryInterface(fm);
-  const nsString& name = tfm->GetThebesFontGroup()->GetFontAt(0)->GetName();
-
+  const nsString& name = fm->GetThebesFontGroup()->GetFontAt(0)->GetName();
   if (name.IsEmpty())
     return S_FALSE;
 
   *aFontFamily = ::SysAllocStringLen(name.get(), name.Length());
   if (!*aFontFamily)
     return E_OUTOFMEMORY;
 
 } __except(FilterA11yExceptions(::GetExceptionCode(),
--- a/accessible/src/msaa/nsTextAccessibleWrap.h
+++ b/accessible/src/msaa/nsTextAccessibleWrap.h
@@ -39,17 +39,17 @@
 #ifndef _nsTextAccessibleWrap_H_
 #define _nsTextAccessibleWrap_H_
 
 #include "nsTextAccessible.h"
 #include "ISimpleDOMText.h"
 #include "nsRect.h"
 
 class nsIFrame;
-class nsIRenderingContext;
+class nsRenderingContext;
 
 class nsTextAccessibleWrap : public nsTextAccessible, 
                              public ISimpleDOMText
 {
 public:
   nsTextAccessibleWrap(nsIContent *aContent, nsIWeakReference *aShell);
   virtual ~nsTextAccessibleWrap() {}
 
--- a/accessible/src/xul/nsXULColorPickerAccessible.cpp
+++ b/accessible/src/xul/nsXULColorPickerAccessible.cpp
@@ -112,29 +112,16 @@ nsXULColorPickerTileAccessible::NativeSt
 
 nsXULColorPickerAccessible::
   nsXULColorPickerAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsXULColorPickerTileAccessible(aContent, aShell)
 {
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsXULColorPickerAccessible: nsAccessNode
-
-PRBool
-nsXULColorPickerAccessible::Init()
-{
-  if (!nsXULColorPickerTileAccessible::Init())
-    return PR_FALSE;
-
-  nsCoreUtils::GeneratePopupTree(mContent, PR_TRUE);
-  return PR_TRUE;
-}
-
-////////////////////////////////////////////////////////////////////////////////
 // nsXULColorPickerAccessible: nsAccessible
 
 PRUint64
 nsXULColorPickerAccessible::NativeState()
 {
   // Possible states: focused, focusable, unavailable(disabled).
 
   // get focus and disable status from base class
--- a/accessible/src/xul/nsXULColorPickerAccessible.h
+++ b/accessible/src/xul/nsXULColorPickerAccessible.h
@@ -63,19 +63,16 @@ public:
 /**
  * Used for colorpicker button (xul:colorpicker@type="button").
  */
 class nsXULColorPickerAccessible : public nsXULColorPickerTileAccessible
 {
 public:
   nsXULColorPickerAccessible(nsIContent *aContent, nsIWeakReference *aShell);
 
-  // nsAccessNode
-  virtual PRBool Init();
-
   // nsAccessible
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
 
 protected:
 
   // nsAccessible
   virtual void CacheChildren();
--- a/accessible/src/xul/nsXULComboboxAccessible.cpp
+++ b/accessible/src/xul/nsXULComboboxAccessible.cpp
@@ -52,26 +52,16 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULComboboxAccessible::
   nsXULComboboxAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
 }
 
-PRBool
-nsXULComboboxAccessible::Init()
-{
-  if (!nsAccessibleWrap::Init())
-    return PR_FALSE;
-
-  nsCoreUtils::GeneratePopupTree(mContent);
-  return PR_TRUE;
-}
-
 PRUint32
 nsXULComboboxAccessible::NativeRole()
 {
   if (mContent->AttrValueIs(kNameSpaceID_None, nsAccessibilityAtoms::type,
                             nsAccessibilityAtoms::autocomplete, eIgnoreCase))
     return nsIAccessibleRole::ROLE_AUTOCOMPLETE;
   return nsIAccessibleRole::ROLE_COMBOBOX;
 }
--- a/accessible/src/xul/nsXULComboboxAccessible.h
+++ b/accessible/src/xul/nsXULComboboxAccessible.h
@@ -55,18 +55,15 @@ public:
 
   // nsIAccessible
   NS_IMETHOD GetValue(nsAString& aValue);
   NS_IMETHOD GetDescription(nsAString& aDescription);
   NS_IMETHOD DoAction(PRUint8 aIndex);
   NS_IMETHOD GetNumActions(PRUint8 *aNumActions);
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
 
-  // nsAccessNode
-  virtual PRBool Init();
-
   // nsAccessible
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
   virtual PRBool GetAllowsAnonChildAccessibles();
 };
 
 #endif
--- a/accessible/src/xul/nsXULFormControlAccessible.cpp
+++ b/accessible/src/xul/nsXULFormControlAccessible.cpp
@@ -105,31 +105,16 @@ nsXULButtonAccessible::DoAction(PRUint8 
   if (aIndex != 0)
     return NS_ERROR_INVALID_ARG;
 
   DoCommand();
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsXULButtonAccessible: nsAccessNode
-
-PRBool
-nsXULButtonAccessible::Init()
-{
-  if (!nsAccessibleWrap::Init())
-    return PR_FALSE;
-
-  if (ContainsMenu())
-    nsCoreUtils::GeneratePopupTree(mContent);
-
-  return PR_TRUE;
-}
-
-////////////////////////////////////////////////////////////////////////////////
 // nsXULButtonAccessible: nsAccessible
 
 PRUint32
 nsXULButtonAccessible::NativeRole()
 {
   return nsIAccessibleRole::ROLE_PUSHBUTTON;
 }
 
--- a/accessible/src/xul/nsXULFormControlAccessible.h
+++ b/accessible/src/xul/nsXULFormControlAccessible.h
@@ -61,19 +61,16 @@ public:
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIAccessible
   NS_IMETHOD GetNumActions(PRUint8 *_retval);
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
   NS_IMETHOD DoAction(PRUint8 index);
 
-  // nsAccessNode
-  virtual PRBool Init();
-
   // nsAccessible
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
 
 protected:
 
   // nsAccessible
   virtual void CacheChildren();
--- a/accessible/src/xul/nsXULMenuAccessible.cpp
+++ b/accessible/src/xul/nsXULMenuAccessible.cpp
@@ -275,26 +275,16 @@ nsXULSelectableAccessible::SelectAll()
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULMenuitemAccessible::
   nsXULMenuitemAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
 }
 
-PRBool
-nsXULMenuitemAccessible::Init()
-{
-  if (!nsAccessibleWrap::Init())
-    return PR_FALSE;
-
-  nsCoreUtils::GeneratePopupTree(mContent);
-  return PR_TRUE;
-}
-
 PRUint64
 nsXULMenuitemAccessible::NativeState()
 {
   PRUint64 state = nsAccessible::NativeState();
 
   // Focused?
   if (mContent->HasAttr(kNameSpaceID_None,
                         nsAccessibilityAtoms::_moz_menuactive))
@@ -406,17 +396,17 @@ nsXULMenuitemAccessible::GetKeyboardShor
 {
   aAccessKey.Truncate();
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   static PRInt32 gMenuAccesskeyModifier = -1;  // magic value of -1 indicates unitialized state
 
   // We do not use nsCoreUtils::GetAccesskeyFor() because accesskeys for
-  // menu are't registered by nsIEventStateManager.
+  // menu are't registered by nsEventStateManager.
   nsAutoString accesskey;
   mContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::accesskey,
                     accesskey);
   if (accesskey.IsEmpty())
     return NS_OK;
 
   nsAccessible* parentAcc = GetParent();
   if (parentAcc) {
--- a/accessible/src/xul/nsXULMenuAccessible.h
+++ b/accessible/src/xul/nsXULMenuAccessible.h
@@ -84,19 +84,16 @@ public:
   // nsIAccessible
   NS_IMETHOD GetDescription(nsAString& aDescription);
   NS_IMETHOD GetKeyboardShortcut(nsAString& _retval);
   NS_IMETHOD GetDefaultKeyBinding(nsAString& aKeyBinding);
   NS_IMETHOD DoAction(PRUint8 index);
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
   NS_IMETHOD GetNumActions(PRUint8 *_retval);
 
-  // nsAccessNode
-  virtual PRBool Init();
-
   // nsAccessible
   virtual nsresult GetNameInternal(nsAString& aName);
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
   virtual PRInt32 GetLevelInternal();
   virtual void GetPositionAndSizeInternal(PRInt32 *aPosInSet,
                                           PRInt32 *aSetSize);
 
--- a/accessible/tests/mochitest/actions/test_general.xul
+++ b/accessible/tests/mochitest/actions/test_general.xul
@@ -24,17 +24,22 @@
   <script type="application/javascript">
   <![CDATA[
     function doTest()
     {
       var actionsArray = [
         {
           ID: "menu",
           actionName: "click",
-          events: CLICK_EVENTS
+          events: CLICK_EVENTS,
+          // Wait for focus event, it guarantees us the submenu tree is created,
+          // that's necessary for next test.
+          eventSeq: [
+            new invokerChecker(EVENT_FOCUS, getNode("menu"))
+          ]
         },
         {
           ID: "submenu",
           actionName: "click",
           events: CLICK_EVENTS
         },
         {
           ID: "menuitem",
--- a/accessible/tests/mochitest/tree/Makefile.in
+++ b/accessible/tests/mochitest/tree/Makefile.in
@@ -46,31 +46,29 @@ include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES =\
 		dockids.html \
 	$(warning test_applicationacc.xul temporarily disabled, see bug 561508) \
 		test_aria_globals.html \
 		test_aria_imgmap.html \
 		test_button.xul \
-		test_colorpicker.xul \
 		test_combobox.xul \
 		test_cssoverflow.html \
 		test_dochierarchy.html \
 		test_dockids.html \
 		test_filectrl.html \
 		test_formctrl.html \
 		test_formctrl.xul \
 		test_gencontent.html \
 		test_groupbox.xul \
 		test_iframe.html \
 		test_img.html \
 		test_list.html \
 		test_media.html \
-		test_menu.xul \
 		test_select.html \
 		test_tabbox.xul \
 		test_tabbrowser.xul \
 		test_table.html \
 		test_tree.xul \
 		test_txtcntr.html \
 		test_txtctrl.html \
 		test_txtctrl.xul \
--- a/accessible/tests/mochitest/tree/test_button.xul
+++ b/accessible/tests/mochitest/tree/test_button.xul
@@ -19,132 +19,34 @@
   <script type="application/javascript">
   <![CDATA[
     ////////////////////////////////////////////////////////////////////////////
     // Test
 
     function doTest()
     {
       //////////////////////////////////////////////////////////////////////////
-      // button1
+      // button
 
       var accTree = {
         role: ROLE_PUSHBUTTON,
         name: "hello",
         children: [ ]
       };
       testAccessibleTree("button1", accTree);
 
       //////////////////////////////////////////////////////////////////////////
-      // button2
-
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button2", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button3
-
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          },
-          {
-            role: ROLE_PUSHBUTTON,
-            children: [
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button3", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button4
+      // toolbarbutton
 
       var accTree = {
         role: ROLE_PUSHBUTTON,
         name: "hello",
         children: [ ]
       };
-      testAccessibleTree("button4", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button5
-
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button5", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button6
-
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          },
-          {
-            role: ROLE_PUSHBUTTON,
-            children: [
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button6", accTree);
+      testAccessibleTree("button2", accTree);
 
       SimpleTest.finish()
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   ]]>
   </script>
@@ -160,39 +62,14 @@
       <div id="content" style="display: none">
       </div>
       <pre id="test">
       </pre>
     </body>
 
     <vbox flex="1">
       <button id="button1" label="hello"/>
-      <button id="button2" type="menu" label="hello">
-        <menupopup>
-          <menuitem label="menuitem"/>
-          <menuitem label="menuitem"/>
-        </menupopup>
-      </button>
-      <button id="button3" type="menu-button" label="hello">
-        <menupopup>
-          <menuitem label="menuitem"/>
-          <menuitem label="menuitem"/>
-        </menupopup>
-      </button>
-
-      <toolbarbutton id="button4" label="hello"/>
-      <toolbarbutton id="button5" type="menu" label="hello">
-        <menupopup>
-          <menuitem label="menuitem"/>
-          <menuitem label="menuitem"/>
-        </menupopup>
-      </toolbarbutton>
-      <toolbarbutton id="button6" type="menu-button" label="hello">
-        <menupopup>
-          <menuitem label="menuitem"/>
-          <menuitem label="menuitem"/>
-        </menupopup>
-      </toolbarbutton>
+      <toolbarbutton id="button2" label="hello"/>
     </vbox>
   </hbox>
 
 </window>
 
deleted file mode 100644
--- a/accessible/tests/mochitest/tree/test_menu.xul
+++ /dev/null
@@ -1,86 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
-                 type="text/css"?>
-
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
-        title="Accessible XUL menu hierarchy tests">
-
-  <script type="application/javascript" 
-          src="chrome://mochikit/content/MochiKit/packed.js" />
-  <script type="application/javascript"
-          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
-
-  <script type="application/javascript"
-          src="../common.js" />
-  <script type="application/javascript"
-          src="../role.js" />
-
-  <script type="application/javascript">
-  <![CDATA[
-    ////////////////////////////////////////////////////////////////////////////
-    // Test
-
-    function doTest()
-    {
-      if (LINUX || SOLARIS) {
-        // XXX: bug 527646
-
-        todo(false, "Failure on Linux and Solaris.");
-        SimpleTest.finish();
-        return;
-      }
-
-      var accTree = {
-        role: ROLE_PARENT_MENUITEM,
-        name: "menu",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("menu", accTree);
-
-      SimpleTest.finish();
-    }
-
-    SimpleTest.waitForExplicitFinish();
-    addA11yLoadEvent(doTest);
-  ]]>
-  </script>
-
-  <hbox flex="1" style="overflow: auto;">
-    <body xmlns="http://www.w3.org/1999/xhtml">
-      <a target="_blank"
-         href="https://bugzilla.mozilla.org/show_bug.cgi?id=249292"
-         title="Ensure accessible children for toolbarbutton types 'menu' and 'menu-button'">
-        Mozilla Bug 249292
-      </a><br/>
-      <p id="display"></p>
-      <div id="content" style="display: none">
-      </div>
-      <pre id="test">
-      </pre>
-    </body>
-
-    <vbox flex="1">
-      <menu id="menu" label="menu">
-        <menupopup>
-          <menuitem label="menuitem"/>
-          <menuitem label="menuitem"/>
-        </menupopup>
-      </menu>
-    </vbox>
-  </hbox>
-
-</window>
-
--- a/accessible/tests/mochitest/treeupdate/Makefile.in
+++ b/accessible/tests/mochitest/treeupdate/Makefile.in
@@ -42,21 +42,24 @@ srcdir		= @srcdir@
 VPATH		= @srcdir@
 relativesrcdir  = accessible/treeupdate
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES =\
 		test_ariadialog.html \
+		test_colorpicker.xul \
+		test_contextmenu.xul \
 		test_doc.html \
 		test_gencontent.html \
 		test_list_editabledoc.html \
 		test_list.html \
 		test_menu.xul \
+		test_menubutton.xul \
 		test_recreation.html \
 		test_select.html \
 		test_textleaf.html \
 		test_visibility.html \
 		test_whitespace.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
rename from accessible/tests/mochitest/tree/test_colorpicker.xul
rename to accessible/tests/mochitest/treeupdate/test_colorpicker.xul
--- a/accessible/tests/mochitest/tree/test_colorpicker.xul
+++ b/accessible/tests/mochitest/treeupdate/test_colorpicker.xul
@@ -10,60 +10,137 @@
           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" />
   <script type="application/javascript"
           src="../role.js" />
+  <script type="application/javascript"
+          src="../events.js" />
 
   <script type="application/javascript">
   <![CDATA[
     ////////////////////////////////////////////////////////////////////////////
     // Test
 
+    function openColorpicker(aColorpickerID)
+    {
+      this.node = getNode(aColorpickerID);
+
+      this.eventSeq = [];
+
+      var it = new colorButtonIterator(this.node);
+      for (var btnNode = it.next(); btnNode = it.next(); btnNode)
+        this.eventSeq.push(new invokerChecker(EVENT_SHOW, btnNode));
+
+      var popupNode = getPopupNode(this.node);
+      this.eventSeq.push(new invokerChecker(EVENT_REORDER, popupNode));
+
+      this.invoke = function openColorpicker_invoke()
+      {
+        var tree =
+          { BUTTONDROPDOWNGRID: [
+            { ALERT: [ ] }
+          ] };
+        testAccessibleTree(this.node, tree);
+
+        this.node.showPopup();
+      }
+
+      this.finalCheck = function openColorpicker_finalCheck()
+      {
+        var tree =
+          { BUTTONDROPDOWNGRID: [
+            { ALERT: [ ] }
+          ] };
+
+        var colorButtons = tree.BUTTONDROPDOWNGRID[0].ALERT;
+        var it = new colorButtonIterator(this.node);
+        while (it.next()) {
+          var obj = { PUSHBUTTON: [ ] };
+          colorButtons.push(obj);
+        }
+
+        testAccessibleTree(this.node, tree);
+      }
+
+      this.getID = function openColorpicker_getID()
+      {
+        return "open colorpicker " + prettyName(aColorpickerID);
+      }
+    }
+
+    function getPopupNode(aColorpickerNode)
+    {
+      return aColorpickerNode.mPicker.parentNode;
+    }
+
+    function colorButtonIterator(aColorpickerNode)
+    {
+      this.container = aColorpickerNode.mPicker.mBox;
+      this.group = this.container.firstChild;
+      this.item = null;
+
+      this.next = function colorButtonIterator_next()
+      {
+        if (!this.group)
+          return null;
+
+        if (!this.item) {
+          this.item = this.group.firstChild;
+          return this.item;
+        }
+
+        if (this.item.nextSibling) {
+          this.item = this.item.nextSibling;
+          return this.item;
+        }
+
+        if (this.group.nextSibling) {
+          this.group = this.group.nextSibling;
+          this.item = this.group.firstChild;
+          return this.item;
+        }
+
+        this.group = null;
+        this.item = null;
+        return null;
+      }
+    }
+
+    //gA11yEventDumpToConsole = true; // debug stuff
+
+    var gQueue = null;
     function doTest()
     {
-      //////////////////////////////////////////////////////////////////////////
-      // button1
-
-      var accTree = {
-        role: ROLE_BUTTONDROPDOWNGRID,
-        children: [
-          {
-            role: ROLE_ALERT,
-            children: [ ]
-          }
-        ]
-      };
-
-      var colorButtons = accTree.children[0].children;
-      for (var idx = 0; idx < 70; idx++) {
-        var obj = { role: ROLE_PUSHBUTTON };
-        colorButtons.push(obj);
-      }
-
-      testAccessibleTree("colorpicker", accTree);
-
-      SimpleTest.finish()
+      gQueue = new eventQueue();
+      gQueue.push(new openColorpicker("colorpicker"));
+      gQueue.invoke(); // Will call SimpleTest.finish()
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   ]]>
   </script>
 
   <hbox flex="1" style="overflow: auto;">
     <body xmlns="http://www.w3.org/1999/xhtml">
       <a target="_blank"
          href="https://bugzilla.mozilla.org/show_bug.cgi?id=249292"
          title="Ensure accessible children for toolbarbutton types 'menu' and 'menu-button'">
         Mozilla Bug 249292
-      </a><br/>
+      </a>
+      <a target="_blank"
+         href="https://bugzilla.mozilla.org/show_bug.cgi?id=630486"
+         title="Don't force accessible creation for popup children.">
+        Mozilla Bug 630486
+      </a>
+      <br/>
       <p id="display"></p>
       <div id="content" style="display: none">
       </div>
       <pre id="test">
       </pre>
     </body>
 
     <vbox flex="1">
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/treeupdate/test_contextmenu.xul
@@ -0,0 +1,321 @@
+<?xml version="1.0"?>
+<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
+<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
+                 type="text/css"?>
+
+<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+        title="menu tree and events">
+
+  <script type="application/javascript" 
+          src="chrome://mochikit/content/MochiKit/packed.js" />
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
+
+  <script type="application/javascript"
+          src="../common.js" />
+  <script type="application/javascript"
+          src="../events.js" />
+  <script type="application/javascript"
+          src="../role.js" />
+
+  <script type="application/javascript">
+  <![CDATA[
+
+    function openMenu(aID, aTree)
+    {
+      this.eventSeq = [
+        new invokerChecker(EVENT_MENUPOPUP_START, getNode(aID))
+      ];
+
+      this.invoke = function openMenu_invoke()
+      {
+        var button = getNode("button");
+        getNode(aID).openPopup(button, "after_start", 0, 0, true, false);
+      }
+
+      this.finalCheck = function openMenu_finalCheck(aEvent)
+      {
+        testAccessibleTree(aID, aTree);
+      }
+
+      this.getID = function openMenu_getID()
+      {
+        return "open menu " + prettyName(aID);
+      }
+    }
+
+    function selectNextMenuItem(aID)
+    {
+      this.eventSeq = [
+        new invokerChecker(EVENT_FOCUS, getNode(aID))
+      ];
+
+      this.invoke = function selectMenuItem_invoke()
+      {
+        synthesizeKey("VK_DOWN", { });
+      }
+
+      this.getID = function selectMenuItem_getID()
+      {
+        return "select menuitem " + prettyName(aID);
+      }
+    }
+    
+    function openSubMenu(aSubMenuID, aItemID, aMenuID, aTree)
+    {
+      this.eventSeq = [
+        new invokerChecker(EVENT_FOCUS, getNode(aItemID)),
+      ];
+
+      this.invoke = function openSubMenu_invoke()
+      {
+        synthesizeKey("VK_ENTER", { });
+      }
+
+      this.finalCheck = function openSubMenu_finalCheck(aEvent)
+      {
+        testAccessibleTree(aMenuID, aTree);
+      }
+
+      this.getID = function openSubMenu_getID()
+      {
+        return "open submenu " + prettyName(aSubMenuID) + " focusing item " + prettyName(aItemID);
+      }
+    }
+
+    function closeSubMenu(aSubMenuID, aItemID)
+    {
+      this.eventSeq = [
+        new invokerChecker(EVENT_FOCUS, getNode(aItemID)),
+      ];
+
+      this.invoke = function closeSubMenu_invoke()
+      {
+        synthesizeKey("VK_ESCAPE", { });
+      }
+
+      this.getID = function closeSubMenu_getID()
+      {
+        return "close submenu " + prettyName(aSubMenuID) + " focusing item " + prettyName(aItemID);
+      }
+    }
+
+    function closeMenu(aID)
+    {
+      this.eventSeq = [
+        new invokerChecker(EVENT_MENUPOPUP_END, getNode(aID))
+      ];
+
+      this.invoke = function closeMenu_invoke()
+      {
+        synthesizeKey("VK_ESCAPE", { });
+      }
+
+      this.getID = function closeMenu_getID()
+      {
+        return "close menu " + prettyName(aID);
+      }
+    }
+
+    //gA11yEventDumpID = "eventdump";
+    //gA11yEventDumpToConsole = true;
+
+    var gQueue = null;
+    var gContextTree = {};
+
+    // Linux and Windows menu trees discrepancy: bug 527646.
+
+    /**
+     * Return the context menu tree before submenus were open.
+     */
+    function getMenuTree1()
+    {
+      if (LINUX || SOLARIS) {
+        var tree = {
+          role: ROLE_MENUPOPUP,
+          children: [
+            {
+              name: "item0",
+              role: ROLE_MENUITEM,
+              children: []
+            },
+            {
+              name: "item1",
+              role: ROLE_MENUITEM,
+              children: []
+            },
+            {
+              name: "item2",
+              role: ROLE_PARENT_MENUITEM,
+              children: [ ]
+            }
+          ]
+        };
+        return tree;
+      }
+
+      // Windows
+      var tree = {
+        role: ROLE_MENUPOPUP,
+        children: [
+          {
+            name: "item0",
+            role: ROLE_MENUITEM,
+            children: []
+          },
+          {
+            name: "item1",
+            role: ROLE_MENUITEM,
+            children: []
+          },
+          {
+            name: "item2",
+            role: ROLE_PARENT_MENUITEM,
+            children: [
+              {
+                name: "item2",
+                role: ROLE_MENUPOPUP,
+                children: [ ]
+              }
+            ]
+          }
+        ]
+      };
+      return tree;
+    }
+
+    /**
+     * Return context menu tree when submenu was open.
+     */
+    function getMenuTree2()
+    {
+      var tree = getMenuTree1();
+      if (LINUX || SOLARIS) {
+        var submenuTree =
+        {
+          name: "item2.0",
+          role: ROLE_PARENT_MENUITEM,
+          children: [ ]
+        };
+        tree.children[2].children.push(submenuTree);
+        return tree;
+      }
+
+      // Windows
+      var submenuTree =
+      {
+        name: "item2.0",
+        role: ROLE_PARENT_MENUITEM,
+        children: [
+          {
+            name: "item2.0",
+            role: ROLE_MENUPOPUP,
+            children: [ ]
+          }
+        ]
+      };
+
+      tree.children[2].children[0].children.push(submenuTree);
+      return tree;
+    }
+
+    /**
+     * Return context menu tree when subsub menu was open.
+     */
+    function getMenuTree3()
+    {
+      var tree = getMenuTree2();
+      var subsubmenuTree =
+      {
+        name: "item2.0.0",
+        role: ROLE_MENUITEM,
+        children: []
+      };
+
+      if (LINUX || SOLARIS)
+        tree.children[2].children[0].\(subsubmenuTree);
+      else
+        tree.children[2].children[0].children[0].children[0].children.push(subsubmenuTree);
+
+      return tree;
+    }
+
+
+    function doTests()
+    {
+      gQueue = new eventQueue();
+
+      // Check initial empty tree
+      testAccessibleTree("context", { MENUPOPUP: [] });
+
+      // Open context menu and check that menu item accesibles are created.
+      gQueue.push(new openMenu("context", getMenuTree1()));
+
+      // Select items and check focus event on them.
+      gQueue.push(new selectNextMenuItem("item0"));
+      gQueue.push(new selectNextMenuItem("item1"));
+      gQueue.push(new selectNextMenuItem("item2"));
+
+      // Open sub menu and check menu accessible tree and focus event.
+      gQueue.push(new openSubMenu("submenu2", "item2.0",
+                                  "context", getMenuTree2()));
+      gQueue.push(new openSubMenu("submenu2.0", "item2.0.0",
+                                  "context", getMenuTree3()));
+
+      // Close submenus and check that focus goes to parent.
+      gQueue.push(new closeSubMenu("submenu2.0", "item2.0"));
+      gQueue.push(new closeSubMenu("submenu2", "item2"));
+
+      gQueue.push(new closeMenu("context"));
+
+      gQueue.invoke(); // Will call SimpleTest.finish();
+    }
+
+    SimpleTest.waitForExplicitFinish();
+    addA11yLoadEvent(doTests);
+  ]]>
+  </script>
+
+  <hbox flex="1" style="overflow: auto;">
+  <body xmlns="http://www.w3.org/1999/xhtml">
+    <a target="_blank"
+       href="https://bugzilla.mozilla.org/show_bug.cgi?id=630194"
+       title="Update accessible tree when opening the menu popup">
+      Mozilla Bug 630194
+    </a>
+    <a target="_blank"
+       href="https://bugzilla.mozilla.org/show_bug.cgi?id=630486"
+       title="Don't force accessible creation for popup children.">
+      Mozilla Bug 630486
+    </a>
+  <p id="display"></p>
+    <div id="content" style="display: none">
+    </div>
+    <pre id="test">
+    </pre>
+  </body>
+
+    <vbox flex="1">
+
+      <menupopup id="context">
+        <menuitem id="item0" label="item0"/>
+        <menuitem id="item1" label="item1"/>
+        <menu id="item2" label="item2">
+          <menupopup id="submenu2">
+            <menu id="item2.0" label="item2.0">
+              <menupopup id="submenu2.0">
+                <menuitem id="item2.0.0" label="item2.0.0"/>
+              </menupopup>
+            </menu>
+          </menupopup>
+        </menu>
+      </menupopup>
+
+      <button context="context" id="button">btn</button>
+
+      <vbox id="eventdump" role="log"/>
+    </vbox>
+  </hbox>
+</window>
--- a/accessible/tests/mochitest/treeupdate/test_menu.xul
+++ b/accessible/tests/mochitest/treeupdate/test_menu.xul
@@ -1,277 +1,130 @@
 <?xml version="1.0"?>
 <?xml-stylesheet href="chrome://global/skin" type="text/css"?>
 <?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
                  type="text/css"?>
 
 <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
-        title="menu tree and events">
+        title="Accessible XUL menu hierarchy tests">
 
   <script type="application/javascript" 
           src="chrome://mochikit/content/MochiKit/packed.js" />
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
-  <script type="application/javascript"
-          src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
 
   <script type="application/javascript"
           src="../common.js" />
   <script type="application/javascript"
-          src="../events.js" />
+          src="../role.js" />
   <script type="application/javascript"
-          src="../role.js" />
+          src="../events.js" />
 
   <script type="application/javascript">
   <![CDATA[
-    function openMenu(aID, aTree)
+    ////////////////////////////////////////////////////////////////////////////
+    // Invokers
+
+    function openMenu(aID)
     {
+      this.menuNode = getNode(aID),
+
       this.eventSeq = [
-        new invokerChecker(EVENT_MENUPOPUP_START, getNode(aID))
+        new invokerChecker(EVENT_FOCUS, this.menuNode)
       ];
 
       this.invoke = function openMenu_invoke()
       {
-        var button = getNode("button");
-        getNode(aID).openPopup(button, "after_start", 0, 0, true, false);
+        var tree;
+        if (LINUX || SOLARIS) {
+          tree =
+            { PARENT_MENUITEM: [ ] };
+
+        } else {
+          tree =
+            { PARENT_MENUITEM: [
+              { MENUPOPUP: [ ] }
+            ] };
+        }
+        testAccessibleTree(aID, tree);
+
+        // Show menu.
+        this.menuNode.open = true;
       }
 
-      this.finalCheck = function openMenu_finalCheck(aEvent)
+      this.finalCheck = function openMenu_finalCheck()
       {
-        testAccessibleTree(aID, aTree);
+        var tree;
+        if (LINUX || SOLARIS) {
+          tree =
+            { PARENT_MENUITEM: [
+              { MENUITEM: [ ] },
+              { MENUITEM: [ ] }
+            ] };
+
+        } else {
+          tree =
+            { PARENT_MENUITEM: [
+              { MENUPOPUP: [
+                { MENUITEM: [ ] },
+                { MENUITEM: [ ] }
+              ] }
+            ] };
+        }
+        testAccessibleTree(aID, tree);
       }
 
       this.getID = function openMenu_getID()
       {
         return "open menu " + prettyName(aID);
       }
     }
 
-    function selectNextMenuItem(aID)
-    {
-      this.eventSeq = [
-        new invokerChecker(EVENT_FOCUS, getNode(aID))
-      ];
-
-      this.invoke = function selectMenuItem_invoke()
-      {
-        synthesizeKey("VK_DOWN", { });
-      }
-
-      this.getID = function selectMenuItem_getID()
-      {
-        return "select menuitem " + prettyName(aID);
-      }
-    }
-    
-    function openSubMenu(aSubMenuID, aItemID)
-    {
-      this.eventSeq = [
-        new invokerChecker(EVENT_FOCUS, getNode(aItemID)),
-      ];
-
-      this.invoke = function openSubMenu_invoke()
-      {
-        synthesizeKey("VK_ENTER", { });
-      }
-
-      this.finalCheck = function openSubMenu_finalCheck(aEvent)
-      {
-        getAccessible(aItemID);
-      }
-
-      this.getID = function openSubMenu_getID()
-      {
-        return "open submenu " + prettyName(aSubMenuID) + " focusing item " + prettyName(aItemID);
-      }
-    }
-
-    function closeSubMenu(aSubMenuID, aItemID)
-    {
-      this.eventSeq = [
-        new invokerChecker(EVENT_FOCUS, getNode(aItemID)),
-      ];
-
-      this.invoke = function closeSubMenu_invoke()
-      {
-        synthesizeKey("VK_ESCAPE", { });
-      }
-
-      this.getID = function closeSubMenu_getID()
-      {
-        return "close submenu " + prettyName(aSubMenuID) + " focusing item " + prettyName(aItemID);
-      }
-    }
-
-    function closeMenu(aID)
-    {
-      this.eventSeq = [
-        new invokerChecker(EVENT_MENUPOPUP_END, getNode(aID))
-      ];
-
-      this.invoke = function closeMenu_invoke()
-      {
-        synthesizeKey("VK_ESCAPE", { });
-      }
-
-      this.getID = function closeMenu_getID()
-      {
-        return "close menu " + prettyName(aID);
-      }
-    }
-
-    //gA11yEventDumpID = "eventdump";
-    //gA11yEventDumpToConsole = true;
+    ////////////////////////////////////////////////////////////////////////////
+    // Test
 
     var gQueue = null;
-    var gContextTree = {};
-
-    // bug 527646
-    if (LINUX || SOLARIS) {
-      gContextTree = {
-        role: ROLE_MENUPOPUP,
-        children: [
-          {
-            name: "item0",
-            role: ROLE_MENUITEM,
-            children: []
-          },
-          {
-            name: "item1",
-            role: ROLE_MENUITEM,
-            children: []
-          },
-          {
-            name: "item2",
-            role: ROLE_PARENT_MENUITEM,
-            children: [
-              {
-                name: "item2.0",
-                role: ROLE_PARENT_MENUITEM,
-                children: [
-                  { 
-                    name: "item2.0.0",
-                    role: ROLE_MENUITEM,
-                    children: []
-                  }
-                ]
-              }
-            ]
-          }
-        ]
-      };
-    } else {
-      gContextTree = {
-        role: ROLE_MENUPOPUP,
-        children: [
-          {
-            name: "item0",
-            role: ROLE_MENUITEM,
-            children: []
-          },
-          {
-            name: "item1",
-            role: ROLE_MENUITEM,
-            children: []
-          },
-          {
-            name: "item2",
-            role: ROLE_PARENT_MENUITEM,
-            children: [
-              {
-                name: "item2",
-                role: ROLE_MENUPOPUP,
-                children: [
-                  {
-                    name: "item2.0",
-                    role: ROLE_PARENT_MENUITEM,
-                    children: [
-                      { 
-                        name: "item2.0",
-                        role: ROLE_MENUPOPUP,
-                        children: [
-                          { 
-                            name: "item2.0.0",
-                            role: ROLE_MENUITEM,
-                            children: []
-                          }
-                        ]
-                      }
-                    ]
-                  }
-                ]
-              }
-            ]
-          }
-        ]
-      };
-    }
-
-
-    function doTests()
+    function doTest()
     {
       gQueue = new eventQueue();
-
-      // Check initial empty tree
-      testAccessibleTree("context", { MENUPOPUP: [] });
-
-      // Open context menu and check that menu item accesibles are created.
-      gQueue.push(new openMenu("context", gContextTree));
-
-      // Select items and check focus event on them.
-      gQueue.push(new selectNextMenuItem("item0"));
-      gQueue.push(new selectNextMenuItem("item1"));
-      gQueue.push(new selectNextMenuItem("item2"));
-
-      // Open sub menu and check menu item accessibles and focus event.
-      gQueue.push(new openSubMenu("submenu2", "item2.0"));
-      gQueue.push(new openSubMenu("submenu2.0", "item2.0.0"));
-
-      // Close submenus and check that focus goes to parent.
-      gQueue.push(new closeSubMenu("submenu2.0", "item2.0"));
-      gQueue.push(new closeSubMenu("submenu2", "item2"));
-
-      gQueue.push(new closeMenu("context"));
-
+      gQueue.push(new openMenu("menu"));
       gQueue.invoke(); // Will call SimpleTest.finish();
     }
 
     SimpleTest.waitForExplicitFinish();
-    addA11yLoadEvent(doTests);
+    addA11yLoadEvent(doTest);
   ]]>
   </script>
 
   <hbox flex="1" style="overflow: auto;">
-  <body xmlns="http://www.w3.org/1999/xhtml">
-    <a target="_blank"
-       href="https://bugzilla.mozilla.org/show_bug.cgi?id=630194"
-       title="Update accessible tree when opening the menu popup">
-      Mozilla Bug 630194
-    </a>
-  <p id="display"></p>
-    <div id="content" style="display: none">
-    </div>
-    <pre id="test">
-    </pre>
-  </body>
+    <body xmlns="http://www.w3.org/1999/xhtml">
+      <a target="_blank"
+         href="https://bugzilla.mozilla.org/show_bug.cgi?id=249292"
+         title="Ensure accessible children for toolbarbutton types 'menu' and 'menu-button'">
+        Mozilla Bug 249292
+      </a>
+      <a target="_blank"
+         href="https://bugzilla.mozilla.org/show_bug.cgi?id=630486"
+         title="Don't force accessible creation for popup children.">
+        Mozilla Bug 630486
+      </a>
+      <br/>
+      <p id="display"></p>
+      <div id="content" style="display: none">
+      </div>
+      <pre id="test">
+      </pre>
+    </body>
 
     <vbox flex="1">
-
-      <menupopup id="context">
-        <menuitem id="item0" label="item0"/>
-        <menuitem id="item1" label="item1"/>
-        <menu id="item2" label="item2">
-          <menupopup id="submenu2">
-            <menu id="item2.0" label="item2.0">
-              <menupopup id="submenu2.0">
-                <menuitem id="item2.0.0" label="item2.0.0"/>
-              </menupopup>
-            </menu>
+      <menubar>
+        <menu id="menu" label="menu">
+          <menupopup>
+            <menuitem label="menuitem"/>
+            <menuitem label="menuitem"/>
           </menupopup>
         </menu>
-      </menupopup>
-
-      <button context="context" id="button">btn</button>
-
-      <vbox id="eventdump" role="log"/>
+      </menubar>
     </vbox>
   </hbox>
+
 </window>
+
copy from accessible/tests/mochitest/tree/test_button.xul
copy to accessible/tests/mochitest/treeupdate/test_menubutton.xul
--- a/accessible/tests/mochitest/tree/test_button.xul
+++ b/accessible/tests/mochitest/treeupdate/test_menubutton.xul
@@ -10,187 +10,168 @@
           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" />
   <script type="application/javascript"
           src="../role.js" />
+  <script type="application/javascript"
+          src="../events.js" />
 
   <script type="application/javascript">
   <![CDATA[
+
     ////////////////////////////////////////////////////////////////////////////
-    // Test
+    // Invokers
+
+    function openMenu(aButtonID)
+    {
+      this.buttonNode = getNode(aButtonID);
+      this.menupoupNode = this.buttonNode.firstChild;
+
+      this.eventSeq = [
+        new invokerChecker(EVENT_REORDER, this.menupoupNode)
+      ];
+
+      this.invoke = function openMenu_invoke()
+      {
+        var tree =
+          { PUSHBUTTON: [
+            { MENUPOPUP: [ ] }
+          ] };
+        testAccessibleTree(this.buttonNode, tree);
+
+        this.buttonNode.open = true;
+      }
+
+      this.finalCheck = function openMenu_finalCheck()
+      {
+        var tree =
+          { PUSHBUTTON: [
+            { MENUPOPUP: [
+              { MENUITEM: [ ] },
+              { MENUITEM: [ ] }
+            ] }
+          ] };
+        testAccessibleTree(this.buttonNode, tree);
+      }
+
+      this.getID = function openMenu_getID()
+      {
+        return "open menu for button " + prettyName(aButtonID);
+      }
+    }
+
+    function openMenuButton(aButtonID)
+    {
+      this.buttonNode = getNode(aButtonID);
+      this.menupoupNode = this.buttonNode.firstChild;
+
+      this.eventSeq = [
+        new invokerChecker(EVENT_REORDER, this.menupoupNode)
+      ];
+
+      this.invoke = function openMenu_invoke()
+      {
+        var tree =
+          { PUSHBUTTON: [
+            { MENUPOPUP: [ ] },
+            { PUSHBUTTON: [ ] }
+          ] };
+        testAccessibleTree(this.buttonNode, tree);
+
+        this.buttonNode.open = true;
+      }
+
+      this.finalCheck = function openMenu_finalCheck()
+      {
+        var tree =
+          { PUSHBUTTON: [
+            { MENUPOPUP: [
+              { MENUITEM: [ ] },
+              { MENUITEM: [ ] }
+            ] },
+            { PUSHBUTTON: [ ] }
+          ] };
+        testAccessibleTree(this.buttonNode, tree);
+      }
+
+      this.getID = function openMenu_getID()
+      {
+        return "open menu for menu button " + prettyName(aButtonID);
+      }
+    }
+
+    ////////////////////////////////////////////////////////////////////////////
+    // Do test
+
+    gA11yEventDumpToConsole = true; // debug stuff
+
+    var gQueue = null;
 
     function doTest()
     {
-      //////////////////////////////////////////////////////////////////////////
-      // button1
-
-      var accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [ ]
-      };
-      testAccessibleTree("button1", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button2
-
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button2", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button3
-
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          },
-          {
-            role: ROLE_PUSHBUTTON,
-            children: [
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button3", accTree);
+      gQueue = new eventQueue();
 
-      //////////////////////////////////////////////////////////////////////////
-      // button4
-
-      var accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [ ]
-      };
-      testAccessibleTree("button4", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button5
+      gQueue.push(new openMenu("button1"));
+      gQueue.push(new openMenuButton("button2"));
+      gQueue.push(new openMenu("button3"));
+      gQueue.push(new openMenuButton("button4"));
 
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button5", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // button6
-
-      accTree = {
-        role: ROLE_PUSHBUTTON,
-        name: "hello",
-        children: [
-          {
-            role: ROLE_MENUPOPUP,
-            children: [
-              {
-                role: ROLE_MENUITEM
-              },
-              {
-                role: ROLE_MENUITEM
-              }
-            ]
-          },
-          {
-            role: ROLE_PUSHBUTTON,
-            children: [
-            ]
-          }
-        ]
-      };
-      testAccessibleTree("button6", accTree);
-
-      SimpleTest.finish()
+      gQueue.invoke(); // SimpleTest.finish()
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   ]]>
   </script>
 
   <hbox flex="1" style="overflow: auto;">
     <body xmlns="http://www.w3.org/1999/xhtml">
       <a target="_blank"
          href="https://bugzilla.mozilla.org/show_bug.cgi?id=249292"
          title="Ensure accessible children for toolbarbutton types 'menu' and 'menu-button'">
         Mozilla Bug 249292
-      </a><br/>
+      </a>
+      <a target="_blank"
+         href="https://bugzilla.mozilla.org/show_bug.cgi?id=630486"
+         title="Don't force accessible creation for popup children.">
+        Mozilla Bug 630486
+      </a>
+      <br/>
       <p id="display"></p>
       <div id="content" style="display: none">
       </div>
       <pre id="test">
       </pre>
     </body>
 
     <vbox flex="1">
-      <button id="button1" label="hello"/>
-      <button id="button2" type="menu" label="hello">
+      <button id="button1" type="menu" label="hello">
         <menupopup>
           <menuitem label="menuitem"/>
           <menuitem label="menuitem"/>
         </menupopup>
       </button>
-      <button id="button3" type="menu-button" label="hello">
+      <button id="button2" type="menu-button" label="hello">
         <menupopup>
           <menuitem label="menuitem"/>
           <menuitem label="menuitem"/>
         </menupopup>
       </button>
 
-      <toolbarbutton id="button4" label="hello"/>
-      <toolbarbutton id="button5" type="menu" label="hello">
+      <toolbarbutton id="button3" type="menu" label="hello">
         <menupopup>
           <menuitem label="menuitem"/>
           <menuitem label="menuitem"/>
         </menupopup>
       </toolbarbutton>
-      <toolbarbutton id="button6" type="menu-button" label="hello">
+      <toolbarbutton id="button4" type="menu-button" label="hello">
         <menupopup>
           <menuitem label="menuitem"/>
           <menuitem label="menuitem"/>
         </menupopup>
       </toolbarbutton>
     </vbox>
   </hbox>
 
--- a/allmakefiles.sh
+++ b/allmakefiles.sh
@@ -70,27 +70,16 @@ config/mkdepend/Makefile
 config/nspr/Makefile
 config/doxygen.cfg
 config/expandlibs_config.py
 config/tests/src-simple/Makefile
 probes/Makefile
 extensions/Makefile
 "
 
-if [ "$WINCE" ]; then
-  add_makefiles "
-    build/wince/tools/Makefile
-    build/wince/shunt/Makefile
-    build/wince/shunt/include/windows.h
-    build/wince/shunt/include/ymath.h
-    build/wince/shunt/include/stdlib.h
-    build/wince/shunt/include/sys/Makefile
-  "
-fi
-
 if [ "$MOZ_MEMORY" -a "$LIBXUL_SDK" = "" ]; then
   add_makefiles "
     memory/jemalloc/Makefile
   "
 fi
 
 #
 # Application-specific makefiles
--- a/browser/app/Makefile.in
+++ b/browser/app/Makefile.in
@@ -79,17 +79,17 @@ endif
 
 LIBS += $(JEMALLOC_LIBS)
 
 ifdef LIBXUL_SDK
 include $(topsrcdir)/config/rules.mk
 else
 # Build a binary bootstrapping with XRE_main
 
-ifneq (,$(filter OS2 WINCE WINNT,$(OS_ARCH)))
+ifneq (,$(filter OS2 WINNT,$(OS_ARCH)))
 PROGRAM = $(MOZ_APP_NAME)$(BIN_SUFFIX)
 else
 PROGRAM = $(MOZ_APP_NAME)-bin$(BIN_SUFFIX)
 endif
 
 CPPSRCS = nsBrowserApp.cpp
 
 LOCAL_INCLUDES += -I$(topsrcdir)/toolkit/xre
@@ -156,26 +156,18 @@ endif
 # shouldn't get 755 perms need $(IFLAGS1) for either way of calling nsinstall.
 NSDISTMODE = copy
 
 include $(topsrcdir)/config/config.mk
 
 ifdef _MSC_VER
 # Always enter a Windows program through wmain, whether or not we're
 # a console application.
-ifdef WINCE
-WIN32_EXE_LDFLAGS += -ENTRY:mainWCRTStartup
-else
 WIN32_EXE_LDFLAGS += -ENTRY:wmainCRTStartup
 endif
-endif
-
-ifdef WINCE
-EXTRA_DSO_LDOPTS += $(call EXPAND_LIBNAME,corelibc)
-endif
 
 ifdef BUILD_STATIC_LIBS
 include $(topsrcdir)/config/static-config.mk
 
 EXTRA_DEPS	+= \
 	$(STATIC_EXTRA_DEPS) \
 	$(NULL)
 DEFINES		+= $(STATIC_DEFINES)
@@ -184,17 +176,17 @@ EXTRA_DSO_LIBS	+= $(STATIC_EXTRA_DSO_LIB
 EXTRA_LIBS	+= $(STATIC_EXTRA_LIBS)
 endif
 
 ifeq ($(OS_ARCH),WINNT)
 OS_LIBS += $(call EXPAND_LIBNAME,comctl32 comdlg32 uuid shell32 ole32 oleaut32 version winspool)
 OS_LIBS += $(call EXPAND_LIBNAME,usp10 msimg32)
 endif
 
-ifneq (,$(filter WINNT WINCE,$(OS_ARCH)))
+ifeq ($(OS_ARCH),WINNT)
 RCINCLUDE = splash.rc
 ifndef GNU_CC
 RCFLAGS += -DMOZ_PHOENIX -I$(srcdir)
 else
 RCFLAGS += -DMOZ_PHOENIX --include-dir $(srcdir)
 endif
 ifdef BUILD_STATIC_LIBS
 RCFLAGS += -DMOZ_STATIC_BUILD
@@ -243,17 +235,17 @@ ifndef GNU_CC
 LDFLAGS += /HEAP:0x40000
 ifeq ($(OS_TEST),x86_64)
 # set stack to 2MB on x64 build.  See bug 582910
 LDFLAGS += -STACK:2097152
 endif
 endif
 endif
 
-ifneq (,$(filter-out OS2 WINNT WINCE,$(OS_ARCH)))
+ifneq (,$(filter-out OS2 WINNT,$(OS_ARCH)))
 
 $(MOZ_APP_NAME):: $(topsrcdir)/build/unix/mozilla.in $(GLOBAL_DEPS)
 	cat $< | sed -e "s|%MOZAPPDIR%|$(installdir)|" \
 		-e "s|%MOZ_APP_DISPLAYNAME%|$(MOZ_APP_DISPLAYNAME)|" > $@
 	chmod +x $@
 
 libs:: $(MOZ_APP_NAME)
 	$(INSTALL) $< $(DIST)/bin
@@ -285,23 +277,16 @@ endif
 
 ifdef MOZ_SPLASHSCREEN
 ifeq ($(MOZ_WIDGET_TOOLKIT),windows)
 libs::
 	$(INSTALL) $(IFLAGS1) $(DIST)/branding/splash.bmp $(DIST)/bin
 endif
 endif
 
-ifdef WINCE
-ifdef MOZ_FASTSTART
-libs::
-	cp -f $(DIST)/bin/faststartstub.exe $(DIST)/bin/$(MOZ_APP_NAME)faststart.exe
-endif
-endif
-
 libs:: $(srcdir)/profile/prefs.js
 	$(INSTALL) $(IFLAGS1) $^ $(DIST)/bin/defaults/profile
 
 libs:: $(srcdir)/blocklist.xml
 	$(INSTALL) $(IFLAGS1) $^ $(DIST)/bin
 
 ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT))
 
--- a/browser/app/macbuild/Contents/Info.plist.in
+++ b/browser/app/macbuild/Contents/Info.plist.in
@@ -24,16 +24,38 @@
 				<string>HTML</string>
 			</array>
 			<key>CFBundleTypeRole</key>
 			<string>Viewer</string>
 		</dict>
 		<dict>
 			<key>CFBundleTypeExtensions</key>
 			<array>
+				<string>svg</string>
+			</array>
+			<key>CFBundleTypeIconFile</key>
+			<string>document.icns</string>
+			<key>CFBundleTypeMIMETypes</key>
+			<array>
+				<string>image/svg+xml</string>
+			</array>
+			<key>CFBundleTypeName</key>
+			<string>SVG document</string>
+			<key>CFBundleTypeOSTypes</key>
+			<array>
+				<string>TEXT</string>
+			</array>
+			<key>CFBundleTypeRole</key>
+			<string>Viewer</string>
+			<key>NSDocumentClass</key>
+			<string>BrowserDocument</string>
+		</dict>
+		<dict>
+			<key>CFBundleTypeExtensions</key>
+			<array>
 			    <string>text</string>
 				<string>txt</string>
 				<string>js</string>
 				<string>log</string>
 				<string>css</string>
 				<string>xul</string>
 				<string>rdf</string>
 			</array>
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -303,22 +303,17 @@ pref("browser.urlbar.default.behavior", 
 // Number of milliseconds to wait for the http headers (and thus
 // the Content-Disposition filename) before giving up and falling back to 
 // picking a filename without that info in hand so that the user sees some
 // feedback from their action.
 pref("browser.download.saveLinkAsFilenameTimeout", 1000);
 
 pref("browser.download.useDownloadDir", true);
 
-#ifdef WINCE
-pref("browser.download.folderList", 2);
-pref("browser.download.dir", "\\Storage Card");
-#else
 pref("browser.download.folderList", 1);
-#endif
 pref("browser.download.manager.showAlertOnComplete", true);
 pref("browser.download.manager.showAlertInterval", 2000);
 pref("browser.download.manager.retention", 2);
 pref("browser.download.manager.showWhenStarting", true);
 pref("browser.download.manager.closeWhenDone", false);
 pref("browser.download.manager.focusWhenStarting", false);
 pref("browser.download.manager.flashCount", 2);
 pref("browser.download.manager.addToRecentDocs", true);
@@ -366,21 +361,17 @@ pref("browser.sessionhistory.max_entries
 pref("browser.link.open_newwindow", 3);
 
 // 0: no restrictions - divert everything
 // 1: don't divert window.open at all
 // 2: don't divert window.open with features
 pref("browser.link.open_newwindow.restriction", 2);
 
 // Tabbed browser
-#ifndef WINCE
 pref("browser.tabs.autoHide", false);
-#else
-pref("browser.tabs.autoHide", true);
-#endif
 pref("browser.tabs.closeWindowWithLastTab", true);
 pref("browser.tabs.insertRelatedAfterCurrent", true);
 pref("browser.tabs.warnOnClose", true);
 pref("browser.tabs.warnOnOpen", true);
 pref("browser.tabs.maxOpenBeforeWarn", 15);
 pref("browser.tabs.loadInBackground", true);
 pref("browser.tabs.opentabfor.middleclick", true);
 pref("browser.tabs.loadDivertedInBackground", false);
@@ -420,21 +411,16 @@ pref("browser.bookmarks.max_backups",   
 
 // Scripts & Windows prefs
 pref("dom.disable_open_during_load",              true);
 pref("javascript.options.showInConsole",          true);
 #ifdef DEBUG
 pref("general.warnOnAboutConfig",                 false);
 #endif
 
-#ifdef WINCE
-// Set the threshold higher to avoid some slow script warnings
-pref("dom.max_script_run_time",                   20);
-#endif
-
 // This is the pref to control the location bar, change this to true to 
 // force this - this makes the origin of popup windows more obvious to avoid
 // spoofing. We would rather not do it by default because it affects UE for web
 // applications, but without it there isn't a really good way to prevent chrome
 // spoofing, see bug 337344
 pref("dom.disable_window_open_feature.location",  true);
 // prevent JS from setting status messages
 pref("dom.disable_window_status_change",          true);
@@ -770,21 +756,17 @@ pref("browser.EULA.version", 3);
 pref("browser.rights.version", 3);
 pref("browser.rights.3.shown", false);
 
 #ifdef DEBUG
 // Don't show the about:rights notification in debug builds.
 pref("browser.rights.override", true);
 #endif
 
-#ifdef WINCE
-pref("browser.sessionstore.resume_from_crash", false);
-#else
 pref("browser.sessionstore.resume_from_crash", true);
-#endif
 pref("browser.sessionstore.resume_session_once", false);
 
 // minimal interval between two save operations in milliseconds
 pref("browser.sessionstore.interval", 15000);
 // maximum amount of POSTDATA to be saved in bytes per history entry (-1 = all of it)
 // (NB: POSTDATA will be saved either entirely or not at all)
 pref("browser.sessionstore.postdata", 0);
 // on which sites to save text data, POSTDATA and cookies
@@ -894,82 +876,48 @@ pref("browser.privatebrowsing.dont_promp
 // Don't try to alter this pref, it'll be reset the next time you use the
 // bookmarking dialog
 pref("browser.bookmarks.editDialog.firstEditField", "namePicker");
 
 // base url for the wifi geolocation network provider
 pref("geo.wifi.uri", "https://www.google.com/loc/json");
 pref("geo.wifi.protocol", 0);
 
-#ifdef WINCE
-
-// tweak awesomebar -- increase the delay until a search happens.
-pref("browser.urlbar.delay", 250);
-
-// disable safe browsing, due to perf hit
-pref("browser.safebrowsing.enabled", false);
-pref("browser.safebrowsing.malware.enabled", false);
-
-// don't check for default browser
-pref("browser.shell.checkDefaultBrowser", false);
-
-// disable bfcache for memory
-pref("browser.sessionhistory.max_total_viewers", 0);
-
-pref("browser.sessionhistory.optimize_eviction", false);
-
-// tweak default content sink prefs
-pref("content.sink.interactive_deflect_count", 10); /* default 0 */
-pref("content.sink.perf_deflect_count", 50); /* default 200 */
-pref("content.sink.interactive_parse_time", 5000); /* default 3000 */
-pref("content.sink.perf_parse_time", 150000); /* default 360000 */
-pref("content.sink.pending_event_mode", 0); /* default 1 */
-pref("content.sink.event_probe_rate", 1); /* default 1 */
-pref("content.sink.interactive_time", 750000); /* default 750000 */
-pref("content.sink.initial_perf_time", 500000); /* default 2000000 */
-pref("content.sink.enable_perf_mode", 0); /* default 0; 0 == switch, 1 == stay interactive, 2 == stay perf */
-
-// Write sessionstore.js less often
-pref("browser.sessionstore.interval", 60000);
-
-#endif /* WINCE */
-
 // Whether to use a panel that looks like an OS X sheet for customization
 #ifdef XP_MACOSX
 pref("toolbar.customization.usesheet", true);
 #else
 pref("toolbar.customization.usesheet", false);
 #endif
 
 // The default for this pref reflects whether the build is capable of IPC.
 // (Turning it on in a no-IPC build will have no effect.)
 #ifdef XP_MACOSX
 // i386 ipc preferences
 pref("dom.ipc.plugins.enabled.i386", false);
 pref("dom.ipc.plugins.enabled.i386.flash player.plugin", true);
 pref("dom.ipc.plugins.enabled.i386.javaplugin2_npapi.plugin", true);
+pref("dom.ipc.plugins.enabled.i386.javaappletplugin.plugin", true);
 // x86_64 ipc preferences
 pref("dom.ipc.plugins.enabled.x86_64", true);
 #else
 pref("dom.ipc.plugins.enabled", true);
 #endif
 
 #ifdef XP_WIN
-#ifndef WINCE
 pref("browser.taskbar.previews.enable", false);
 pref("browser.taskbar.previews.max", 20);
 pref("browser.taskbar.previews.cachetime", 5);
 pref("browser.taskbar.lists.enabled", true);
 pref("browser.taskbar.lists.frequent.enabled", true);
 pref("browser.taskbar.lists.recent.enabled", false);
 pref("browser.taskbar.lists.maxListItemCount", 7);
 pref("browser.taskbar.lists.tasks.enabled", true);
 pref("browser.taskbar.lists.refreshInSeconds", 120);
 #endif
-#endif
 
 #ifdef MOZ_SERVICES_SYNC
 // The sync engines to use.
 pref("services.sync.registerEngines", "Bookmarks,Form,History,Password,Prefs,Tab");
 // Preferences to be synced by default
 pref("services.sync.prefs.sync.accessibility.blockautorefresh", true);
 pref("services.sync.prefs.sync.accessibility.browsewithcaret", true);
 pref("services.sync.prefs.sync.accessibility.typeaheadfind", true);
--- a/browser/base/Makefile.in
+++ b/browser/base/Makefile.in
@@ -57,34 +57,31 @@ EXTRA_JS_MODULES = \
 	content/openLocationLastURL.jsm \
 	content/NetworkPrioritizer.jsm \
 	content/domplate.jsm \
 	content/stylePanel.jsm \
 	$(NULL)
 
 include $(topsrcdir)/config/rules.mk
 
-PRE_RELEASE_SUFFIX := $(shell $(PYTHON) $(topsrcdir)/config/printprereleasesuffix.py \
-                        $(shell cat $(srcdir)/../config/version.txt))
+PRE_RELEASE_SUFFIX := ""
 
 DEFINES += \
 	-DMOZ_APP_VERSION=$(MOZ_APP_VERSION) \
 	-DAPP_LICENSE_BLOCK=$(abs_srcdir)/content/overrides/app-license.html \
 	-DPRE_RELEASE_SUFFIX="$(PRE_RELEASE_SUFFIX)" \
 	$(NULL)
 
 ifneq (,$(filter windows gtk2 cocoa, $(MOZ_WIDGET_TOOLKIT)))
 DEFINES += -DHAVE_SHELL_SERVICE=1
 endif
 
 ifneq (,$(filter windows cocoa gtk2, $(MOZ_WIDGET_TOOLKIT)))
-ifneq ($(OS_ARCH),WINCE)
 DEFINES += -DCONTEXT_COPY_IMAGE_CONTENTS=1
 endif
-endif
 
 ifneq (,$(filter windows, $(MOZ_WIDGET_TOOLKIT)))
 DEFINES += -DCAN_DRAW_IN_TITLEBAR=1
 endif
 
 ifneq (,$(filter windows gtk2, $(MOZ_WIDGET_TOOLKIT)))
 DEFINES += -DMENUBAR_CAN_AUTOHIDE=1
 endif
--- a/browser/base/content/aboutDialog.css
+++ b/browser/base/content/aboutDialog.css
@@ -1,69 +1,26 @@
 #aboutDialog {
   width: 620px;
 }
 
-/* Official branding has Firefox logo on the left side of the window. 
-   Nightly/aurora branding has background image applied to entire window. */
-%ifdef MOZ_OFFICIAL_BRANDING
-#clientBox {
-  background-color: #F7F7F7;
-  color: #222222;
-}
-%else
-#aboutDialogContainer {
-  background-image: url("chrome://branding/content/about-background.png");
-  background-repeat: no-repeat;
-  background-color: #000;
-  color: #fff;
-}
-
-.text-link {
-  color: #fff !important;
-}
-%endif
-
-%ifdef MOZ_OFFICIAL_BRANDING
-#leftBox {
-  background-image: url("chrome://branding/content/about-logo.png");
-  background-repeat: no-repeat;
-  /* min-width and min-height create room for the logo */
-  min-width: 210px;
-  min-height: 210px;
-  margin-top:20px;
-  -moz-margin-start: 30px;
-}
-%endif
-
 #rightBox {
   background-image: url("chrome://branding/content/about-wordmark.png");
   background-repeat: no-repeat;
   /* padding-top creates room for the wordmark */
   padding-top: 38px;
   margin-top:20px;
-%ifdef MOZ_OFFICIAL_BRANDING
-  margin-left: 30px;
-  margin-right: 30px;
-%else 
-  /* this margin prevents text from overlapping the planet image */
-  margin-left: 280px;
-  margin-right: 20px;
-%endif
 }
 
 #rightBox:-moz-locale-dir(rtl) {
   background-position: 100% 0;
 }
 
 #bottomBox {
   padding: 15px 10px 0;
-%ifndef MOZ_OFFICIAL_BRANDING
-  background-color: rgba(0,0,0,.7);
-%endif
 }
 
 #version {
   margin-top: 10px;
   -moz-margin-start: 0;
 }
 
 #distribution,
@@ -82,17 +39,16 @@
 
 #updateButton,
 #updateDeck > hbox > label {
   -moz-margin-start: 0;
   -moz-padding-start: 0;
 }
 
 #updateDeck > hbox > label:not([class="text-link"]) {
-  color: #909090;
   font-style:italic;
 }
 
 .update-throbber {
   width: 16px;
   min-height: 16px;
   -moz-margin-end: 3px;
   list-style-image: url("chrome://global/skin/icons/loading_16.png");
@@ -106,44 +62,36 @@
 }
 
 .bottom-link,
 .bottom-link:focus {
   text-align: center;
   margin: 0 40px;
 }
 
-/* we assume trademark text only appears in offical builds */
-%ifdef MOZ_OFFICIAL_BRANDING
-#trademark {
-  font-size: xx-small;
-  text-align: center;
-  color: #999999;
-  margin-top: 10px;
-  margin-bottom: 10px;
-}
-%endif
-
 #currentChannel {
   margin: 0;
   padding: 0;
   font-weight: bold;
 }
 
 #channelSelector {
   margin-top: 10px;
 }
 
+#channelSelectorStart {
+  -moz-margin-start: 0;
+}
+
 #channelMenulist {
   margin: 0;
 }
 
 .channel-description {
   margin: 10px 0;
-  text-align: center;
 }
 
 #detailsBox,
 #channelSelector,
 .channel-description {
   -moz-transition: opacity 250ms;
 }
 
--- a/browser/base/content/aboutDialog.js
+++ b/browser/base/content/aboutDialog.js
@@ -60,19 +60,19 @@ function init(aEvent)
       distroIdField.value = distroId + " - " + distroVersion;
       distroIdField.style.display = "block";
     }
   }
   catch (e) {
     // Pref is unset
   }
 
-  // Include the build ID if this is a "pre" (i.e. non-release) build
+  // Include the build ID if this is an "a#" (nightly or aurora) build
   let version = Services.appinfo.version;
-  if (version.indexOf("pre") != -1) {
+  if (/a\d+$/.test(version)) {
     let buildID = Services.appinfo.appBuildID;
     let buildDate = buildID.slice(0,4) + "-" + buildID.slice(4,6) + "-" + buildID.slice(6,8);
     document.getElementById("version").value += " (" + buildDate + ")";
   }
 
 #ifdef MOZ_OFFICIAL_BRANDING
   // Hide the Charlton trademark attribution for non-en-US/en-GB
   // DO NOT REMOVE without consulting people involved with bug 616193
--- a/browser/base/content/aboutDialog.xul
+++ b/browser/base/content/aboutDialog.xul
@@ -36,16 +36,17 @@
 # and other provisions required by the LGPL or the GPL. 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 ***** -->
 
 <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/content/aboutDialog.css" type="text/css"?>
+<?xml-stylesheet href="chrome://branding/content/aboutDialog.css" type="text/css"?>
 
 <!DOCTYPE window [
 <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd" >
 %brandDTD;
 <!ENTITY % aboutDialogDTD SYSTEM "chrome://browser/locale/aboutDialog.dtd" >
 %aboutDialogDTD;
 ]>
 
@@ -122,18 +123,18 @@
               &community.start2;<label class="text-link" href="http://www.mozilla.org/">&community.mozillaLink;</label>&community.middle2;<label class="text-link" href="about:credits">&community.creditsLink;</label>&community.end2;
             </description>
             <description class="text-blurb">
               &contribute.start;<label class="text-link" href="http://www.mozilla.org/contribute/">&contribute.getInvolvedLink;</label>&contribute.end;
             </description>
           </vbox>
 
           <vbox id="channelSelector">
-            <hbox pack="center" align="center">
-              <label>&channel.selector.start;</label>
+            <hbox pack="start" align="center">
+              <label id="channelSelectorStart">&channel.selector.start;</label>
               <menulist id="channelMenulist" onselect="gChannelSelector.selectChannel(this.selectedItem);">
                 <menupopup>
                   <menuitem id="releaseMenuitem" label="Release" value="release"/>
                   <menuitem id="betaMenuitem" label="Beta" value="beta"/>
                   <menuseparator/>
                   <menuitem id="auroraMenuitem" label="Aurora" value="aurora"/>
                 </menupopup>
               </menulist>
@@ -141,19 +142,24 @@
             </hbox>
 
             <deck id="channelDescriptionDeck" selectedIndex="0">
               <description id="releaseDescription" class="channel-description">&channel.release.description;</description>
               <description id="betaDescription" class="channel-description">&channel.beta.description;</description>
               <description id="auroraDescription" class="channel-description">&channel.aurora.description;</description>
             </deck>
 
-            <hbox id="channelSelectorButtons" pack="center">
+            <hbox id="channelSelectorButtons" pack="end">
+#ifdef XP_UNIX
+              <button oncommand="gChannelSelector.cancel();" label="&channel.selector.cancelButton;"/>
+              <button oncommand="gChannelSelector.apply();" label="&channel.selector.applyButton;"/>
+#else
               <button oncommand="gChannelSelector.apply();" label="&channel.selector.applyButton;"/>
               <button oncommand="gChannelSelector.cancel();" label="&channel.selector.cancelButton;"/>
+#endif
             </hbox>
           </vbox>
         </deck>
       </vbox>
     </hbox>
     <vbox id="bottomBox">
       <hbox pack="center">
         <label class="text-link bottom-link" href="about:license">&bottomLinks.license;</label>
--- a/browser/base/content/browser-menubar.inc
+++ b/browser/base/content/browser-menubar.inc
@@ -86,17 +86,16 @@
                           accesskey="&savePageCmd.accesskey;"
                           key="key_savePage"
                           command="Browser:SavePage"/>
                 <menuitem id="menu_sendLink"
                           label="&sendPageCmd.label;"
                           accesskey="&sendPageCmd.accesskey;"
                           command="Browser:SendLink"/>
                 <menuseparator/>
-#ifndef WINCE
                 <menuitem id="menu_printSetup"
                           label="&printSetupCmd.label;"
                           accesskey="&printSetupCmd.accesskey;"
                           command="cmd_pageSetup"/>
 #ifndef XP_MACOSX
                 <menuitem id="menu_printPreview"
                           label="&printPreviewCmd.label;"
                           accesskey="&printPreviewCmd.accesskey;"
@@ -110,17 +109,16 @@
                 <menuseparator/>
                 <menuitem id="menu_import"
                           label="&import.label;"
                           accesskey="&import.accesskey;"
                           oncommand="BrowserImport();"/>
 #ifndef XP_MACOSX
                 <menuseparator/>
 #endif
-#endif
                 <menuitem id="goOfflineMenuitem"
                           label="&goOfflineCmd.label;"
                           accesskey="&goOfflineCmd.accesskey;"
                           type="checkbox"
                           observes="workOfflineMenuitemState"
                           oncommand="BrowserOffline.toggleOfflineStatus();"/>
                 <menuitem id="menu_FileQuitItem"
 #ifdef XP_WIN
--- a/browser/base/content/browser-sets.inc
+++ b/browser/base/content/browser-sets.inc
@@ -351,17 +351,19 @@
     <key id="key_sanitize" command="Tools:Sanitize" keycode="VK_DELETE" modifiers="accel,shift"/>
 #ifdef XP_MACOSX
     <key id="key_sanitize_mac" command="Tools:Sanitize" keycode="VK_BACK" modifiers="accel,shift"/>
 #endif
 #ifdef XP_UNIX
     <key id="key_quitApplication" key="&quitApplicationCmdMac.key;" command="cmd_quitApplication" modifiers="accel"/>
 #endif
 
+#ifdef FULL_BROWSER_WINDOW
     <key id="key_undoCloseTab" command="History:UndoCloseTab" key="&tabCmd.commandkey;" modifiers="accel,shift"/>
+#endif
     <key id="key_undoCloseWindow" command="History:UndoCloseWindow" key="&newNavigatorCmd.key;" modifiers="accel,shift"/>
 
 #ifdef XP_GNOME
 #define NUM_SELECT_TAB_MODIFIER alt
 #else
 #define NUM_SELECT_TAB_MODIFIER accel
 #endif
 
--- a/browser/base/content/browser-tabview.js
+++ b/browser/base/content/browser-tabview.js
@@ -33,19 +33,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 *****
 
 let TabView = {
   _deck: null,
+  _iframe: null,
   _window: null,
   _firstUseExperienced: false,
   _browserKeyHandlerInitialized: false,
+  _isFrameLoading: false,
+  _initFrameCallbacks: [],
   VISIBILITY_IDENTIFIER: "tabview-visibility",
 
   // ----------
   get windowTitle() {
     delete this.windowTitle;
     let brandBundle = document.getElementById("bundle_brand");
     let brandShortName = brandBundle.getString("brandShortName");
     let title = gNavigatorBundle.getFormattedString("tabView2.title", [brandShortName]);
@@ -122,76 +125,91 @@ let TabView = {
         "TabShow", this._tabShowEventListener, true);
     }
   },
 
   // ----------
   // Creates the frame and calls the callback once it's loaded. 
   // If the frame already exists, calls the callback immediately. 
   _initFrame: function TabView__initFrame(callback) {
+    let hasCallback = typeof callback == "function";
+
     if (this._window) {
-      if (typeof callback == "function")
+      if (hasCallback)
         callback();
-    } else {
-      // ___ find the deck
-      this._deck = document.getElementById("tab-view-deck");
+      return;
+    }
+
+    if (hasCallback)
+      this._initFrameCallbacks.push(callback);
+
+    if (this._isFrameLoading)
+      return;
+
+    this._isFrameLoading = true;
+
+    // ___ find the deck
+    this._deck = document.getElementById("tab-view-deck");
 
-      // ___ create the frame
-      let iframe = document.createElement("iframe");
-      iframe.id = "tab-view";
-      iframe.setAttribute("transparent", "true");
-      iframe.flex = 1;
+    // ___ create the frame
+    this._iframe = document.createElement("iframe");
+    this._iframe.id = "tab-view";
+    this._iframe.setAttribute("transparent", "true");
+    this._iframe.flex = 1;
 
-      if (typeof callback == "function")
-        window.addEventListener("tabviewframeinitialized", callback, false);
+    let self = this;
 
-      iframe.setAttribute("src", "chrome://browser/content/tabview.html");
-      this._deck.appendChild(iframe);
-      this._window = iframe.contentWindow;
+    window.addEventListener("tabviewframeinitialized", function onInit() {
+      window.removeEventListener("tabviewframeinitialized", onInit, false);
 
-      if (this._tabShowEventListener) {
+      self._isFrameLoading = false;
+      self._window = self._iframe.contentWindow;
+      self._setBrowserKeyHandlers();
+
+      if (self._tabShowEventListener) {
         gBrowser.tabContainer.removeEventListener(
-          "TabShow", this._tabShowEventListener, true);
-        this._tabShowEventListener = null;
+          "TabShow", self._tabShowEventListener, true);
+        self._tabShowEventListener = null;
       }
 
-      this._setBrowserKeyHandlers();
-    }
+      self._initFrameCallbacks.forEach(function (cb) cb());
+      self._initFrameCallbacks = [];
+    }, false);
+
+    this._iframe.setAttribute("src", "chrome://browser/content/tabview.html");
+    this._deck.appendChild(this._iframe);
   },
 
   // ----------
   getContentWindow: function TabView_getContentWindow() {
     return this._window;
   },
 
   // ----------
-  isVisible: function() {
-    return (this._deck ? this._deck.selectedIndex == 1 : false);
+  isVisible: function TabView_isVisible() {
+    return (this._deck ? this._deck.selectedPanel == this._iframe : false);
   },
 
   // ----------
   show: function() {
     if (this.isVisible())
       return;
-    
+
+    let self = this;
     this._initFrame(function() {
-      let event = document.createEvent("Events");
-      event.initEvent("tabviewshow", false, false);
-      dispatchEvent(event);
+      self._window.UI.showTabView(true);
     });
   },
 
   // ----------
   hide: function() {
     if (!this.isVisible())
       return;
 
-    let event = document.createEvent("Events");
-    event.initEvent("tabviewhide", false, false);
-    dispatchEvent(event);
+    this._window.UI.exit();
   },
 
   // ----------
   toggle: function() {
     if (this.isVisible())
       this.hide();
     else 
       this.show();
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -183,34 +183,32 @@ let gInitialPages = [
 #include browser-tabview.js
 
 #ifdef MOZ_SERVICES_SYNC
 #include browser-syncui.js
 #endif
 
 XPCOMUtils.defineLazyGetter(this, "Win7Features", function () {
 #ifdef XP_WIN
-#ifndef WINCE
   const WINTASKBAR_CONTRACTID = "@mozilla.org/windows-taskbar;1";
   if (WINTASKBAR_CONTRACTID in Cc &&
       Cc[WINTASKBAR_CONTRACTID].getService(Ci.nsIWinTaskbar).available) {
     let temp = {};
     Cu.import("resource://gre/modules/WindowsPreviewPerTab.jsm", temp);
     let AeroPeek = temp.AeroPeek;
     return {
       onOpenWindow: function () {
         AeroPeek.onOpenWindow(window);
       },
       onCloseWindow: function () {
         AeroPeek.onCloseWindow(window);
       }
     };
   }
 #endif
-#endif
   return null;
 });
 
 #ifdef MOZ_CRASHREPORTER
 XPCOMUtils.defineLazyServiceGetter(this, "gCrashReporter",
                                    "@mozilla.org/xre/app-info;1",
                                    "nsICrashReporter");
 #endif
@@ -3291,26 +3289,25 @@ const BrowserSearch = {
     if (window.location.href != getBrowserURL()) {
       var win = getTopWin();
       if (win) {
         // If there's an open browser window, it should handle this command
         win.focus()
         win.BrowserSearch.webSearch();
       } else {
         // If there are no open browser windows, open a new one
-
-        // This needs to be in a timeout so that we don't end up refocused
-        // in the url bar
-        function webSearchCallback() {
-          setTimeout(BrowserSearch.webSearch, 0);
+        function observer(subject, topic, data) {
+          if (subject == win) {
+            BrowserSearch.webSearch();
+            Services.obs.removeObserver(observer, "browser-delayed-startup-finished");
+          }
         }
-
         win = window.openDialog("chrome://browser/content/", "_blank",
                                 "chrome,all,dialog=no", "about:blank");
-        win.addEventListener("load", webSearchCallback, false);
+        Services.obs.addObserver(observer, "browser-delayed-startup-finished", false); 
       }
       return;
     }
 #endif
     var searchBar = this.searchBar;
     if (searchBar && window.fullScreen)
       FullScreen.mouseoverToggle(true);
 
@@ -4029,26 +4026,29 @@ var FullScreen = {
     }
 
     // In tabs-on-top mode, move window controls to the tab bar,
     // and in tabs-on-bottom mode, move them back to the navigation toolbar.
     // When there is a chance the tab bar may be collapsed, put window
     // controls on nav bar.
     var fullscreenflex = document.getElementById("fullscreenflex");
     var fullscreenctls = document.getElementById("window-controls");
-    var ctlsOnTabbar = TabsOnTop.enabled &&
-                       !gPrefService.getBoolPref("browser.tabs.autoHide");
-    if (fullscreenctls.parentNode.id == "nav-bar" && ctlsOnTabbar) {
+    var navbar = document.getElementById("nav-bar");
+    var ctlsOnTabbar = window.toolbar.visible &&
+                       (navbar.collapsed ||
+                          (TabsOnTop.enabled &&
+                           !gPrefService.getBoolPref("browser.tabs.autoHide")));
+    if (fullscreenctls.parentNode == navbar && ctlsOnTabbar) {
       document.getElementById("TabsToolbar").appendChild(fullscreenctls);
       // we don't need this space in tabs-on-top mode, so prevent it from 
       // being shown
       fullscreenflex.removeAttribute("fullscreencontrol");
     }
     else if (fullscreenctls.parentNode.id == "TabsToolbar" && !ctlsOnTabbar) {
-      document.getElementById("nav-bar").appendChild(fullscreenctls);
+      navbar.appendChild(fullscreenctls);
       fullscreenflex.setAttribute("fullscreencontrol", "true");
     }
 
     var controls = document.getElementsByAttribute("fullscreencontrol", "true");
     for (var i = 0; i < controls.length; ++i)
       controls[i].hidden = aShow;
   }
 };
@@ -5552,17 +5552,17 @@ function handleLinkClick(event, href, li
 
 function middleMousePaste(event) {
   let clipboard = readFromClipboard();
   if (!clipboard)
     return;
 
   // Strip embedded newlines and surrounding whitespace, to match the URL
   // bar's behavior (stripsurroundingwhitespace)
-  clipboard.replace(/\s*\n\s*/g, "");
+  clipboard = clipboard.replace(/\s*\n\s*/g, "");
 
   let url = getShortcutOrURI(clipboard);
   try {
     makeURI(url);
   } catch (ex) {
     // Not a valid URI.
     return;
   }
@@ -7789,17 +7789,17 @@ var gIdentityHandler = {
     var urlString = value + "\n" + content.document.title;
     var htmlString = "<a href=\"" + value + "\">" + value + "</a>";
 
     var dt = event.dataTransfer;
     dt.setData("text/x-moz-url", urlString);
     dt.setData("text/uri-list", value);
     dt.setData("text/plain", value);
     dt.setData("text/html", htmlString);
-    dt.addElement(event.currentTarget);
+    dt.setDragImage(gProxyFavIcon, 16, 16);
   }
 };
 
 let DownloadMonitorPanel = {
   //////////////////////////////////////////////////////////////////////////////
   //// DownloadMonitorPanel Member Variables
 
   _panel: null,
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -102,17 +102,19 @@
 <script type="application/javascript" src="chrome://browser/content/safebrowsing/sb-loader.js"/>
 #endif
 <script type="application/javascript" src="chrome://global/content/contentAreaUtils.js"/>
 
 <script type="application/javascript" src="chrome://browser/content/places/editBookmarkOverlay.js"/>
 
 # All sets except for popupsets (commands, keys, stringbundles and broadcasters) *must* go into the
 # browser-sets.inc file for sharing with hiddenWindow.xul.
+#define FULL_BROWSER_WINDOW
 #include browser-sets.inc
+#undef FULL_BROWSER_WINDOW
 
   <popupset id="mainPopupSet">
     <menupopup id="tabContextMenu"
                onpopupshowing="if (event.target == this) TabContextMenu.updateContextMenu(this);"
                onpopuphidden="if (event.target == this) TabContextMenu.contextTab = null;">
       <menuitem id="context_reloadTab" label="&reloadTab.label;" accesskey="&reloadTab.accesskey;"
                 oncommand="gBrowser.reloadTab(TabContextMenu.contextTab);"/>
       <menuseparator/>
@@ -456,25 +458,21 @@
         <toolbarbutton class="titlebar-button" id="titlebar-close" command="cmd_closeWindow"/>
       </hbox>
     </hbox>
   </hbox>
 </vbox>
 #endif
 
 <deck flex="1" id="tab-view-deck">
-<vbox flex="1">
+<vbox flex="1" id="browser-panel">
 
   <toolbox id="navigator-toolbox"
            defaultmode="icons" mode="icons"
-#ifdef WINCE
-           defaulticonsize="small" iconsize="small"
-#else
            iconsize="large"
-#endif
            tabsontop="true"
            persist="tabsontop">
     <!-- Menu -->
     <toolbar type="menubar" id="toolbar-menubar" class="chromeclass-menubar" customizable="true"
              defaultset="menubar-items"
              mode="icons" iconsize="small" defaulticonsize="small"
              lockiconsize="true"
 #ifdef MENUBAR_CAN_AUTOHIDE
@@ -492,23 +490,18 @@
       <hbox class="titlebar-placeholder" type="appmenu-button" ordinal="0"/>
       <hbox class="titlebar-placeholder" type="caption-buttons" ordinal="1000"/>
 #endif
     </toolbar>
 
     <toolbar id="nav-bar" class="toolbar-primary chromeclass-toolbar"
              toolbarname="&navbarCmd.label;" accesskey="&navbarCmd.accesskey;"
              fullscreentoolbar="true" mode="icons" customizable="true"
-#ifdef WINCE
-             iconsize="small" defaulticonsize="small"
-             defaultset="unified-back-forward-button,urlbar-container,reload-button,stop-button,search-container,home-button,bookmarks-menu-button-container,navigator-throbber,fullscreenflex,window-controls"
-#else
              iconsize="large"
              defaultset="unified-back-forward-button,urlbar-container,reload-button,stop-button,search-container,home-button,bookmarks-menu-button-container,fullscreenflex,window-controls"
-#endif
              context="toolbar-context-menu">
 
       <toolbaritem id="unified-back-forward-button" class="chromeclass-toolbar-additional"
                    context="backForwardMenu" removable="true"
                    title="&backForwardItem.title;">
         <toolbarbutton id="back-button" class="toolbarbutton-1"
                        label="&backCmd.label;"
                        command="Browser:BackOrBackDuplicate"
--- a/browser/base/content/openLocationLastURL.jsm
+++ b/browser/base/content/openLocationLastURL.jsm
@@ -91,13 +91,12 @@ let gOpenLocationLastURL = {
     else {
       let str = Components.classes["@mozilla.org/supports-string;1"]
                           .createInstance(Components.interfaces.nsISupportsString);
       str.data = val;
       prefSvc.setComplexValue(LAST_URL_PREF, nsISupportsString, str);
     }
   },
   reset: function() {
-    if (prefSvc.prefHasUserValue(LAST_URL_PREF))
-        prefSvc.clearUserPref(LAST_URL_PREF);
+    prefSvc.clearUserPref(LAST_URL_PREF);
     gOpenLocationLastURLData = "";
   }
 };
--- a/browser/base/content/pageinfo/security.js
+++ b/browser/base/content/pageinfo/security.js
@@ -369,10 +369,12 @@ function previousVisitCount(host, endTim
   // Search for visits to this host before today
   var query = historyService.getNewQuery();
   query.endTimeReference = query.TIME_RELATIVE_TODAY;
   query.endTime = 0;
   query.domain = host;
 
   var result = historyService.executeQuery(query, options);
   result.root.containerOpen = true;
-  return result.root.childCount;
+  var cc = result.root.childCount;
+  result.root.containerOpen = false;
+  return cc;
 }
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -352,48 +352,44 @@
           <![CDATA[
             const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
             let browser = (aBrowser || this.mCurrentBrowser);
             let stack = browser.parentNode;
             let self = this;
 
             let promptBox = {
               appendPrompt : function(args, onCloseCallback) {
-                let count = browser.getAttribute("tabmodalPromptShowing");
-                if (count)
-                    count = parseInt(count) + 1;
-                else
-                    count = 1;
-                browser.setAttribute("tabmodalPromptShowing", count);
-
                 let newPrompt = document.createElementNS(XUL_NS, "tabmodalprompt");
                 stack.appendChild(newPrompt);
+                browser.setAttribute("tabmodalPromptShowing", true);
+
                 newPrompt.clientTop; // style flush to assure binding is attached
 
                 let tab = self._getTabForContentWindow(browser.contentWindow);
                 newPrompt.init(args, tab, onCloseCallback);
                 return newPrompt;
               },
 
               removePrompt : function(aPrompt) {
-                let count = parseInt(browser.getAttribute("tabmodalPromptShowing"));
-                count--;
-                if (count)
-                    browser.setAttribute("tabmodalPromptShowing", count);
-                else
-                    browser.removeAttribute("tabmodalPromptShowing");
                 stack.removeChild(aPrompt);
+
+                let prompts = this.listPrompts();
+                if (prompts.length) {
+                  let prompt = prompts[prompts.length - 1];
+                  prompt.Dialog.setDefaultFocus();
+                } else {
+                  browser.removeAttribute("tabmodalPromptShowing");
+                  browser.focus();
+                }
               },
 
               listPrompts : function(aPrompt) {
-                let prompts = [];
                 let els = stack.getElementsByTagNameNS(XUL_NS, "tabmodalprompt");
                 // NodeList --> real JS array
-                for (let i = 0; i < els.length; i++)
-                  prompts.push(els[i]);
+                let prompts = Array.slice(els);
                 return prompts;
               },
             };
 
             return promptBox;
           ]]>
         </body>
       </method>
@@ -809,31 +805,31 @@
                             aBrowser.currentURI);
                 if (uri.scheme == "about")
                   newTitle = uri.spec + sep + newTitle;
                 else
                   newTitle = uri.prePath + sep + newTitle;
               }
             } catch (e) {}
 
-            if (window.TabView) {
+            if ("TabView" in window) {
               let groupName = TabView.getActiveGroupName();
               if (groupName)
                 newTitle = groupName + sep + newTitle;
             }
 
             return newTitle;
           ]]>
         </body>
       </method>
 
       <method name="updateTitlebar">
         <body>
           <![CDATA[
-            if (window.TabView && TabView.isVisible()) {
+            if ("TabView" in window && TabView.isVisible()) {
               // ToDo: this will be removed when we gain ability to draw to the menu bar.
               // Bug 586175
               this.ownerDocument.title = TabView.windowTitle;
             }
             else {
               this.ownerDocument.title = this.getWindowTitleForBrowser(this.mCurrentBrowser);
             }
           ]]>
@@ -947,16 +943,26 @@
               event.initEvent("TabSelect", true, false);
               this.mCurrentTab.dispatchEvent(event);
 
               this._tabAttrModified(oldTab);
               this._tabAttrModified(this.mCurrentTab);
 
               // Adjust focus
               do {
+
+                // If there's a tabmodal prompt showing, focus it.
+                if (newBrowser.hasAttribute("tabmodalPromptShowing")) {
+                  let XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
+                  let prompts = newBrowser.parentNode.getElementsByTagNameNS(XUL_NS, "tabmodalprompt");
+                  let prompt = prompts[prompts.length - 1];
+                  prompt.Dialog.setDefaultFocus();
+                  break;
+                }
+
                 // Focus the location bar if it was previously focused for that tab.
                 // In full screen mode, only bother making the location bar visible
                 // if the tab is a blank one.
                 oldBrowser._urlbarFocused = (gURLBar && gURLBar.focused);
                 if (newBrowser._urlbarFocused && gURLBar) {
                   if (!window.fullScreen) {
                     gURLBar.focus();
                     break;
@@ -1266,17 +1272,17 @@
             // Add the Message and the Browser to the box
             var notificationbox = document.createElementNS(
                                     "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul",
                                     "notificationbox");
             notificationbox.setAttribute("flex", "1");
             notificationbox.appendChild(stack);
 
             var position = this.tabs.length - 1;
-            var uniqueId = "panel" + Math.floor(Date.now()) + position;
+            var uniqueId = "panel" + Date.now() + position;
             notificationbox.id = uniqueId;
             t.linkedPanel = uniqueId;
             t.linkedBrowser = b;
             t._tPos = position;
             if (t.previousSibling.selected)
               t.setAttribute("afterselected", true);
 
             // NB: this appendChild call causes us to run constructors for the
--- a/browser/base/content/tabview/groupitems.js
+++ b/browser/base/content/tabview/groupitems.js
@@ -161,18 +161,20 @@ function GroupItem(listOfEls, options) {
     .appendTo($container);
 
   // ___ Title
   this.$titleContainer = iQ('.title-container', this.$titlebar);
   this.$title = iQ('.name', this.$titlebar);
   this.$titleShield = iQ('.title-shield', this.$titlebar);
   this.setTitle(options.title);
 
-  var handleKeyDown = function(e) {
-    if (e.which == 13 || e.which == 27) { // return & escape
+  var handleKeyPress = function (e) {
+    if (e.keyCode == KeyEvent.DOM_VK_ESCAPE ||
+        e.keyCode == KeyEvent.DOM_VK_RETURN ||
+        e.keyCode == KeyEvent.DOM_VK_ENTER) {
       (self.$title)[0].blur();
       self.$title
         .addClass("transparentBorder")
         .one("mouseout", function() {
           self.$title.removeClass("transparentBorder");
         });
       e.stopPropagation();
       e.preventDefault();
@@ -199,17 +201,17 @@ function GroupItem(listOfEls, options) {
       if (!self._titleFocused) {
         (self.$title)[0].select();
         self._titleFocused = true;
       }
     })
     .mousedown(function(e) {
       e.stopPropagation();
     })
-    .keydown(handleKeyDown)
+    .keypress(handleKeyPress)
     .keyup(handleKeyUp);
 
   this.$titleShield
     .mousedown(function(e) {
       self.lastMouseDownTarget = (Utils.isLeftClick(e) ? e.target : null);
     })
     .mouseup(function(e) {
       var same = (e.target == self.lastMouseDownTarget);
@@ -1142,17 +1144,19 @@ GroupItem.prototype = Utils.extend(new I
   
   // ----------
   // Handles error event for loading app tab's fav icon.
   _onAppTabError : function(event) {
     iQ(".appTabIcon", this.$appTabTray).each(function(icon) {
       let $icon = iQ(icon);
       if ($icon.data("xulTab") == event.target) {
         $icon.attr("src", Utils.defaultFaviconURL);
+        return false;
       }
+      return true;
     });
   },
 
   // ----------
   // Adds the given xul:tab as an app tab in this group's apptab tray
   //
   // Parameters:
   //   options - change how the app tab is added.
@@ -1188,19 +1192,20 @@ GroupItem.prototype = Utils.extend(new I
 
   // ----------
   // Removes the given xul:tab as an app tab in this group's apptab tray
   removeAppTab: function GroupItem_removeAppTab(xulTab) {
     // remove the icon
     iQ(".appTabIcon", this.$appTabTray).each(function(icon) {
       let $icon = iQ(icon);
       if ($icon.data("xulTab") != xulTab)
-        return;
+        return true;
         
       $icon.remove();
+      return false;
     });
     
     // adjust the tray
     this.adjustAppTabTray(true);
 
     xulTab.removeEventListener("error", this._onAppTabError, false);
   },
 
@@ -1210,27 +1215,28 @@ GroupItem.prototype = Utils.extend(new I
     let self = this;
 
     let elements = iQ(".appTabIcon", this.$appTabTray);
     let length = elements.length;
 
     elements.each(function(icon) {
       let $icon = iQ(icon);
       if ($icon.data("xulTab") != xulTab)
-        return;
+        return true;
 
       let targetIndex = xulTab._tPos;
 
       $icon.remove();
       if (targetIndex < (length - 1))
         self.$appTabTray[0].insertBefore(
           icon,
         iQ(".appTabIcon:nth-child(" + (targetIndex + 1) + ")", self.$appTabTray)[0]);
       else
         $icon.appendTo(self.$appTabTray);
+      return false;
     });
   },
 
   // ----------
   // Function: hideExpandControl
   // Hide the control which expands a stacked groupItem into a quick-look view.
   hideExpandControl: function GroupItem_hideExpandControl() {
     this.$expander.hide();
@@ -1663,23 +1669,22 @@ GroupItem.prototype = Utils.extend(new I
   // ----------
   // Function: _addHandlers
   // Helper routine for the constructor; adds various event handlers to the container.
   _addHandlers: function GroupItem__addHandlers(container) {
     let self = this;
 
     // Create new tab and zoom in on it after a double click
     container.mousedown(function(e) {
-      if (!Utils.isLeftClick(e))
+      if (!Utils.isLeftClick(e) || self.$titlebar[0] == e.target || 
+          self.$titlebar.contains(e.target)) {
+        self._lastClick = 0;
+        self._lastClickPositions = null;
         return;
-
-      // clicking in the title bar shouldn't create new tabs
-      if (self.$titlebar[0] == e.target || self.$titlebar.contains(e.target))
-        return;
-
+      }
       if (Date.now() - self._lastClick <= UI.DBLCLICK_INTERVAL &&
           (self._lastClickPositions.x - UI.DBLCLICK_OFFSET) <= e.clientX &&
           (self._lastClickPositions.x + UI.DBLCLICK_OFFSET) >= e.clientX &&
           (self._lastClickPositions.y - UI.DBLCLICK_OFFSET) <= e.clientY &&
           (self._lastClickPositions.y + UI.DBLCLICK_OFFSET) >= e.clientY) {
         self.newTab();
         self._lastClick = 0;
         self._lastClickPositions = null;
@@ -1783,17 +1788,22 @@ GroupItem.prototype = Utils.extend(new I
   // ----------
   // Function: setResizable
   // Sets whether the groupItem is resizable and updates the UI accordingly.
   setResizable: function GroupItem_setResizable(value, immediately) {
     var self = this;
 
     this.resizeOptions.minWidth = GroupItems.minGroupWidth;
     this.resizeOptions.minHeight = GroupItems.minGroupHeight;
-    this.resizeOptions.start = function () self._unfreezeItemSize();
+
+    let start = this.resizeOptions.start;
+    this.resizeOptions.start = function (event) {
+      start.call(self, event);
+      self._unfreezeItemSize();
+    }
 
     if (value) {
       immediately ? this.$resizer.show() : this.$resizer.fadeIn();
       this.resizable(true);
     } else {
       immediately ? this.$resizer.hide() : this.$resizer.fadeOut();
       this.resizable(false);
     }
@@ -2028,20 +2038,21 @@ let GroupItems = {
     if (xulTab.ownerDocument.defaultView != gWindow || !xulTab.pinned)
       return;
 
     let iconUrl = xulTab.image || Utils.defaultFaviconURL;
     this.groupItems.forEach(function(groupItem) {
       iQ(".appTabIcon", groupItem.$appTabTray).each(function(icon) {
         let $icon = iQ(icon);
         if ($icon.data("xulTab") != xulTab)
-          return;
+          return true;
 
         if (iconUrl != $icon.attr("src"))
           $icon.attr("src", iconUrl);
+        return false;
       });
     });
   },  
 
   // ----------
   // Function: addAppTab
   // Adds the given xul:tab to the app tab tray in all groups
   addAppTab: function GroupItems_addAppTab(xulTab) {
--- a/browser/base/content/tabview/iq.js
+++ b/browser/base/content/tabview/iq.js
@@ -212,19 +212,17 @@ iQClass.prototype = {
   // ----------
   // Function: each
   // Execute a callback for every element in the matched set.
   each: function iQClass_each(callback) {
     if (typeof callback != "function") {
       Utils.assert(false, "each's argument must be a function");
       return null;
     }
-    for (let i = 0; this[i] != null; i++) {
-      callback(this[i]);
-    }
+    for (let i = 0; this[i] != null && callback(this[i]) !== false; i++) {}
     return this;
   },
 
   // ----------
   // Function: addClass
   // Adds the given class(es) to the receiver.
   addClass: function iQClass_addClass(value) {
     Utils.assertThrow(typeof value == "string" && value,
--- a/browser/base/content/tabview/items.js
+++ b/browser/base/content/tabview/items.js
@@ -656,17 +656,17 @@ Item.prototype = {
       };
 
       // ___ mouseup
       var handleMouseUp = function(e) {
         iQ(gWindow)
           .unbind('mousemove', handleMouseMove)
           .unbind('mouseup', handleMouseUp);
 
-        if (dropTarget) {
+        if (startSent && dropTarget) {
           var dropOptions = dropTarget.dropOptions;
           if (dropOptions && typeof dropOptions.drop == "function")
             dropOptions.drop.apply(dropTarget, [e]);
         }
 
         if (startSent && typeof self.dragOptions.stop == "function")
           self.dragOptions.stop.apply(self, [e]);
 
--- a/browser/base/content/tabview/search.js
+++ b/browser/base/content/tabview/search.js
@@ -127,17 +127,17 @@ var TabUtils = {
   // Function: _nameOfTab
   // Given a <TabItem> or a <xul:tab> returns the tab's name.
   nameOf: function TabUtils_nameOfTab(tab) {
     // We can have two types of tabs: A <TabItem> or a <xul:tab>
     // because we have to deal with both tabs represented inside
     // of active Panoramas as well as for windows in which
     // Panorama has yet to be activated. We uses object sniffing to
     // determine the type of tab and then returns its name.     
-    return tab.label != undefined ? tab.label : tab.$tabTitle[0].innerHTML;
+    return tab.label != undefined ? tab.label : tab.$tabTitle[0].textContent;
   },
   
   // ---------
   // Function: URLOf
   // Given a <TabItem> or a <xul:tab> returns the URL of tab
   URLOf: function TabUtils_URLOf(tab) {
     // Convert a <TabItem> to <xul:tab>
     if(tab.tab != undefined)
--- a/browser/base/content/tabview/tabview.css
+++ b/browser/base/content/tabview/tabview.css
@@ -8,16 +8,17 @@ html {
 }
 
 body {
   padding: 0px;
   margin: 0 auto;
 }
 
 #content {
+  overflow: -moz-hidden-unscrollable;
   position: absolute;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
 }
 
 #bg {
--- a/browser/base/content/tabview/tabview.js
+++ b/browser/base/content/tabview/tabview.js
@@ -28,16 +28,17 @@ XPCOMUtils.defineLazyGetter(this, "gNetU
   Cu.import("resource://gre/modules/NetUtil.jsm", obj);
   return obj.NetUtil;
 });
 
 var gWindow = window.parent;
 var gBrowser = gWindow.gBrowser;
 var gTabView = gWindow.TabView;
 var gTabViewDeck = gWindow.document.getElementById("tab-view-deck");
+var gBrowserPanel = gWindow.document.getElementById("browser-panel");
 var gTabViewFrame = gWindow.document.getElementById("tab-view");
 
 # NB: Certain files need to evaluate before others
 
 #include iq.js
 #include storage.js
 #include items.js
 #include groupitems.js
--- a/browser/base/content/tabview/ui.js
+++ b/browser/base/content/tabview/ui.js
@@ -158,21 +158,16 @@ let UI = {
       this._initPageDirection();
 
       // ___ storage
       Storage.init();
       let data = Storage.readUIData(gWindow);
       this._storageSanity(data);
       this._pageBounds = data.pageBounds;
 
-      // ___ hook into the browser
-      gWindow.addEventListener("tabviewshow", function() {
-        self.showTabView(true);
-      }, false);
-
       // ___ currentTab
       this._currentTab = gBrowser.selectedTab;
 
       // ___ exit button
       iQ("#exit-button").click(function() {
         self.exit();
         self.blurAll();
       });
@@ -183,58 +178,59 @@ let UI = {
         if (iQ(":focus").length > 0) {
           iQ(":focus").each(function(element) {
             // don't fire blur event if the same input element is clicked.
             if (e.target != element && element.nodeName == "INPUT")
               element.blur();
           });
         }
         if (e.originalTarget.id == "content") {
-          // Create an orphan tab on double click
-          if (Date.now() - self._lastClick <= self.DBLCLICK_INTERVAL && 
-              (self._lastClickPositions.x - self.DBLCLICK_OFFSET) <= e.clientX &&
-              (self._lastClickPositions.x + self.DBLCLICK_OFFSET) >= e.clientX &&
-              (self._lastClickPositions.y - self.DBLCLICK_OFFSET) <= e.clientY &&
-              (self._lastClickPositions.y + self.DBLCLICK_OFFSET) >= e.clientY) {
-            GroupItems.setActiveGroupItem(null);
-            TabItems.creatingNewOrphanTab = true;
-
-            let newTab = 
-              gBrowser.loadOneTab("about:blank", { inBackground: true });
-
-            let box = 
-              new Rect(e.clientX - Math.floor(TabItems.tabWidth/2),
-                       e.clientY - Math.floor(TabItems.tabHeight/2),
-                       TabItems.tabWidth, TabItems.tabHeight);
-            newTab._tabViewTabItem.setBounds(box, true);
-            newTab._tabViewTabItem.pushAway(true);
-            UI.setActiveTab(newTab._tabViewTabItem);
-
-            TabItems.creatingNewOrphanTab = false;
-            newTab._tabViewTabItem.zoomIn(true);
-
+          if (!Utils.isLeftClick(e)) {
             self._lastClick = 0;
             self._lastClickPositions = null;
-            gTabView.firstUseExperienced = true;
           } else {
-            self._lastClick = Date.now();
-            self._lastClickPositions = new Point(e.clientX, e.clientY);
-            self._createGroupItemOnDrag(e);
+            // Create an orphan tab on double click
+            if (Date.now() - self._lastClick <= self.DBLCLICK_INTERVAL && 
+                (self._lastClickPositions.x - self.DBLCLICK_OFFSET) <= e.clientX &&
+                (self._lastClickPositions.x + self.DBLCLICK_OFFSET) >= e.clientX &&
+                (self._lastClickPositions.y - self.DBLCLICK_OFFSET) <= e.clientY &&
+                (self._lastClickPositions.y + self.DBLCLICK_OFFSET) >= e.clientY) {
+              GroupItems.setActiveGroupItem(null);
+              TabItems.creatingNewOrphanTab = true;
+
+              let newTab =
+                gBrowser.loadOneTab("about:blank", { inBackground: true });
+
+              let box =
+                new Rect(e.clientX - Math.floor(TabItems.tabWidth/2),
+                         e.clientY - Math.floor(TabItems.tabHeight/2),
+                         TabItems.tabWidth, TabItems.tabHeight);
+              newTab._tabViewTabItem.setBounds(box, true);
+              newTab._tabViewTabItem.pushAway(true);
+              UI.setActiveTab(newTab._tabViewTabItem);
+
+              TabItems.creatingNewOrphanTab = false;
+              newTab._tabViewTabItem.zoomIn(true);
+
+              self._lastClick = 0;
+              self._lastClickPositions = null;
+              gTabView.firstUseExperienced = true;
+            } else {
+              self._lastClick = Date.now();
+              self._lastClickPositions = new Point(e.clientX, e.clientY);
+              self._createGroupItemOnDrag(e);
+            }
           }
         }
       });
 
       iQ(window).bind("unload", function() {
         self.uninit();
       });
 
-      gWindow.addEventListener("tabviewhide", function() {
-        self.exit();
-      }, false);
-
       // ___ setup key handlers
       this._setTabViewFrameKeyHandlers();
 
       // ___ add tab action handlers
       this._addTabActionHandlers();
 
       // ___ groups
       GroupItems.init();
@@ -420,17 +416,17 @@ let UI = {
   getActiveOrphanTab: function UI_getActiveOrphanTab() {
     return (this._activeTab && !this._activeTab.parent) ? this._activeTab : null;
   },
 
   // ----------
   // Function: isTabViewVisible
   // Returns true if the TabView UI is currently shown.
   isTabViewVisible: function UI_isTabViewVisible() {
-    return gTabViewDeck.selectedIndex == 1;
+    return gTabViewDeck.selectedPanel == gTabViewFrame;
   },
 
   // ---------
   // Function: _initPageDirection
   // Initializes the page base direction
   _initPageDirection: function UI__initPageDirection() {
     let chromeReg = Cc["@mozilla.org/chrome/chrome-registry;1"].
                     getService(Ci.nsIXULChromeRegistry);
@@ -459,17 +455,17 @@ let UI = {
       groupItem.reorderTabItemsBasedOnTabOrder();
     });
     this._reorderTabItemsOnShow = [];
 
 #ifdef XP_WIN
     // Restore the full height when showing TabView
     gTabViewFrame.style.marginTop = "";
 #endif
-    gTabViewDeck.selectedIndex = 1;
+    gTabViewDeck.selectedPanel = gTabViewFrame;
     gWindow.TabsInTitlebar.allowedBy("tabview-open", false);
     gTabViewFrame.contentWindow.focus();
 
     gBrowser.updateTitlebar();
 #ifdef XP_MACOSX
     this.setTitlebarColors(true);
 #endif
     let event = document.createEvent("Events");
@@ -541,17 +537,17 @@ let UI = {
     this._reorderTabsOnHide = [];
 
 #ifdef XP_WIN
     // Push the top of TabView frame to behind the tabbrowser, so glass can show
     // XXX bug 586679: avoid shrinking the iframe and squishing iframe contents
     // as well as avoiding the flash of black as we animate out
     gTabViewFrame.style.marginTop = gBrowser.boxObject.y + "px";
 #endif
-    gTabViewDeck.selectedIndex = 0;
+    gTabViewDeck.selectedPanel = gBrowserPanel;
     gWindow.TabsInTitlebar.allowedBy("tabview-open", true);
     gBrowser.contentWindow.focus();
 
     gBrowser.updateTitlebar();
 #ifdef XP_MACOSX
     this.setTitlebarColors(false);
 #endif
     Storage.saveVisibilityData(gWindow, "false");
--- a/browser/base/content/test/browser_bug553455.js
+++ b/browser/base/content/test/browser_bug553455.js
@@ -700,98 +700,16 @@ function test_renotify_installed() {
   var triggers = encodeURIComponent(JSON.stringify({
     "XPI": "unsigned.xpi"
   }));
   gBrowser.selectedTab = gBrowser.addTab();
   gBrowser.loadURI(TESTROOT + "installtrigger.html?" + triggers);
 },
 
 function test_cancel_restart() {
-  // If the XPI is already cached then the HTTP observer won't see the request
-  var cacheService = Cc["@mozilla.org/network/cache-service;1"].
-                     getService(Ci.nsICacheService);
-  try {
-    cacheService.evictEntries(Components.interfaces.nsICache.STORE_ANYWHERE);
-  } catch(ex) {}
-
-  // Must be registered before any request starts
-  var observerService = Cc["@mozilla.org/network/http-activity-distributor;1"].
-                        getService(Ci.nsIHttpActivityDistributor);
-  observerService.addObserver({
-    observeActivity: function(aChannel, aType, aSubtype, aTimestamp, aSizeData,
-                              aStringData) {
-      aChannel.QueryInterface(Ci.nsIChannel);
-
-      // Wait for the first event for the download
-      if (aChannel.URI.spec != TESTROOT + "unsigned.xpi" ||
-        aType != Ci.nsIHttpActivityObserver.ACTIVITY_TYPE_HTTP_TRANSACTION ||
-        aSubtype != Ci.nsIHttpActivityObserver.ACTIVITY_SUBTYPE_REQUEST_HEADER)
-        return;
-
-      observerService.removeObserver(this);
-
-      info("Replacing channel");
-      aChannel.QueryInterface(Ci.nsITraceableChannel);
-      var listener = aChannel.setNewListener({
-        onStartRequest: function(aRequest, aContext) {
-          listener.onStartRequest(aRequest, aContext);
-        },
-
-        onDataAvailable: function(aRequest, aContext, aInputStream, aOffset, aCount) {
-          listener.onDataAvailable(aRequest, aContext, aInputStream, aOffset, aCount);
-        },
-
-        onStopRequest: function(aRequest, aContext, aStatusCode) {
-          listener.onStopRequest(aRequest, aContext, aStatusCode);
-
-          // Request should have been cancelled
-          is(aStatusCode, Components.results.NS_BINDING_ABORTED, "Should have seen a cancelled request");
-
-          // Notification should have changed to cancelled
-          let notification = PopupNotifications.panel.childNodes[0];
-          is(notification.id, "addon-install-cancelled-notification", "Should have seen the cancelled notification");
-
-          // Wait for the install confirmation dialog
-          wait_for_install_dialog(function(aWindow) {
-            // Wait for the complete notification
-            wait_for_notification(function(aPanel) {
-              let notification = aPanel.childNodes[0];
-              is(notification.id, "addon-install-complete-notification", "Should have seen the install complete");
-              is(notification.button.label, "Restart Now", "Should have seen the right button");
-              is(notification.getAttribute("label"),
-                 "XPI Test will be installed after you restart " + gApp + ".",
-                 "Should have seen the right message");
-
-              AddonManager.getAllInstalls(function(aInstalls) {
-                is(aInstalls.length, 1, "Should be one pending install");
-                aInstalls[0].cancel();
-
-                Services.perms.remove("example.com", "install");
-                wait_for_notification_close(runNextTest);
-                gBrowser.removeTab(gBrowser.selectedTab);
-              });
-            });
-
-            aWindow.document.documentElement.acceptDialog();
-          });
-
-          // Restart the download
-          info("Restarting download");
-          EventUtils.synthesizeMouse(notification.button, 20, 10, {});
-
-          // Should be back to a progress notification
-          ok(PopupNotifications.isPanelOpen, "Notification should still be open");
-          is(PopupNotifications.panel.childNodes.length, 1, "Should be only one notification");
-          notification = PopupNotifications.panel.childNodes[0];
-          is(notification.id, "addon-progress-notification", "Should have seen the progress notification");
-        }
-      });
-    }
-  });
-
   // Wait for the progress notification
   wait_for_notification(function(aPanel) {
     let notification = aPanel.childNodes[0];
     is(notification.id, "addon-progress-notification", "Should have seen the progress notification");
 
     // Close the notification
     let anchor = document.getElementById("addons-notification-icon");
     EventUtils.synthesizeMouseAtCenter(anchor, {});
@@ -801,18 +719,54 @@ function test_cancel_restart() {
     ok(PopupNotifications.isPanelOpen, "Notification should still be open");
     is(PopupNotifications.panel.childNodes.length, 1, "Should be only one notification");
     isnot(notification, aPanel.childNodes[0], "Should have reconstructed the notification UI");
     notification = aPanel.childNodes[0];
     is(notification.id, "addon-progress-notification", "Should have seen the progress notification");
     let button = document.getAnonymousElementByAttribute(notification, "anonid", "cancel");
 
     // Cancel the download
-    info("Cancelling download");
     EventUtils.synthesizeMouse(button, 2, 2, {});
+
+    // Notification should have changed to cancelled
+    notification = aPanel.childNodes[0];
+    is(notification.id, "addon-install-cancelled-notification", "Should have seen the cancelled notification");
+
+    // Wait for the install confirmation dialog
+    wait_for_install_dialog(function(aWindow) {
+      // Wait for the complete notification
+      wait_for_notification(function(aPanel) {
+        let notification = aPanel.childNodes[0];
+        is(notification.id, "addon-install-complete-notification", "Should have seen the install complete");
+        is(notification.button.label, "Restart Now", "Should have seen the right button");
+        is(notification.getAttribute("label"),
+           "XPI Test will be installed after you restart " + gApp + ".",
+           "Should have seen the right message");
+
+        AddonManager.getAllInstalls(function(aInstalls) {
+          is(aInstalls.length, 1, "Should be one pending install");
+          aInstalls[0].cancel();
+
+          Services.perms.remove("example.com", "install");
+          wait_for_notification_close(runNextTest);
+          gBrowser.removeTab(gBrowser.selectedTab);
+        });
+      });
+
+      aWindow.document.documentElement.acceptDialog();
+    });
+
+    // Restart the download
+    EventUtils.synthesizeMouse(notification.button, 20, 10, {});
+
+    // Should be back to a progress notification
+    ok(PopupNotifications.isPanelOpen, "Notification should still be open");
+    is(PopupNotifications.panel.childNodes.length, 1, "Should be only one notification");
+    notification = aPanel.childNodes[0];
+    is(notification.id, "addon-progress-notification", "Should have seen the progress notification");
   });
 
   var pm = Services.perms;
   pm.add(makeURI("http://example.com/"), "install", pm.ALLOW_ACTION);
 
   var triggers = encodeURIComponent(JSON.stringify({
     "XPI": "unsigned.xpi"
   }));
--- a/browser/base/content/test/browser_inspector_domPanel.js
+++ b/browser/base/content/test/browser_inspector_domPanel.js
@@ -60,35 +60,35 @@ function createDocument()
   doc.title = "Inspector DOM Test";
   Services.obs.addObserver(runDOMTests, "inspector-opened", false);
   InspectorUI.openInspectorUI();
 }
 
 function nodeGenerator()
 {
   let body = doc.body;
-  newProperty = "rand" + Math.floor(Date.now());
+  newProperty = "rand" + Date.now();
   body[newProperty] = Math.round(Math.random() * 100);
   InspectorUI.inspectNode(body);
   yield;
 
   let h1 = doc.querySelector("h1");
-  newProperty = "rand2" + Math.floor(Date.now());
+  newProperty = "rand2" + Date.now();
   h1[newProperty] = "test" + Math.random();
   InspectorUI.inspectNode(h1);
   yield;
 
   let first = doc.getElementById("first");
-  newProperty = "rand3" + Math.floor(Date.now());
+  newProperty = "rand3" + Date.now();
   first[newProperty] = null;
   InspectorUI.inspectNode(first);
   yield;
 
   let closing = doc.getElementById("closing");
-  newProperty = "bazbaz" + Math.floor(Date.now());
+  newProperty = "bazbaz" + Date.now();
   closing[newProperty] = false;
   InspectorUI.inspectNode(closing);
   yield;
 }
 
 function runDOMTests()
 {
   InspectorUI._log("runDOMtests");
--- a/browser/base/content/test/tabview/Makefile.in
+++ b/browser/base/content/test/tabview/Makefile.in
@@ -125,16 +125,19 @@ include $(topsrcdir)/config/rules.mk
                  browser_tabview_bug634085.js \
                  browser_tabview_bug634158.js \
                  browser_tabview_bug634672.js \
                  browser_tabview_bug635696.js \
                  browser_tabview_bug640765.js \
                  browser_tabview_bug641802.js \
                  browser_tabview_bug644097.js \
                  browser_tabview_bug645653.js \
+                 browser_tabview_bug649006.js \
+                 browser_tabview_bug649307.js \
+                 browser_tabview_bug651311.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 \
--- a/browser/base/content/test/tabview/browser_tabview_bug595436.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug595436.js
@@ -1,67 +1,54 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 function test() {
-  waitForExplicitFinish();
-  
-  window.addEventListener('tabviewshown', onTabViewWindowLoaded, false);
-  TabView.toggle();
-}
+  let cw, search, searchButton;
+
+  let assertSearchIsEnabled = function () {
+    isnot(search.style.display, "none", "search is enabled");
+  }
 
-function onTabViewWindowLoaded() {
-  window.removeEventListener('tabviewshown', onTabViewWindowLoaded, false);
-  
-  let contentWindow = document.getElementById('tab-view').contentWindow;
-  let search = contentWindow.document.getElementById('search');
-  let searchButton = contentWindow.document.getElementById('searchbutton');
-  
-  let isSearchEnabled = function () {
-    return 'none' != search.style.display;
+  let assertSearchIsDisabled = function () {
+    is(search.style.display, "none", "search is disabled");
   }
-  
-  let assertSearchIsEnabled = function () {
-    ok(isSearchEnabled(), 'search is enabled');
-  }
-  
-  let assertSearchIsDisabled = function () {
-    ok(!isSearchEnabled(), 'search is disabled');
-  }
-  
+
   let testSearchInitiatedByKeyPress = function () {
-    EventUtils.synthesizeKey('a', {});
+    EventUtils.synthesizeKey("a", {}, cw);
     assertSearchIsEnabled();
-    
-    EventUtils.synthesizeKey('VK_BACK_SPACE', {});
+
+    EventUtils.synthesizeKey("VK_BACK_SPACE", {}, cw);
     assertSearchIsDisabled();
   }
-  
+
   let testSearchInitiatedByMouseClick = function () {
-    EventUtils.sendMouseEvent({type: 'mousedown'}, searchButton, contentWindow);
+    EventUtils.sendMouseEvent({type: "mousedown"}, searchButton, cw);
     assertSearchIsEnabled();
-    
-    EventUtils.synthesizeKey('a', {});
-    EventUtils.synthesizeKey('VK_BACK_SPACE', {});
-    EventUtils.synthesizeKey('VK_BACK_SPACE', {});
+
+    EventUtils.synthesizeKey("a", {}, cw);
+    EventUtils.synthesizeKey("VK_BACK_SPACE", {}, cw);
+    EventUtils.synthesizeKey("VK_BACK_SPACE", {}, cw);
     assertSearchIsEnabled();
-    
-    EventUtils.synthesizeKey('VK_ESCAPE', {});
+
+    EventUtils.synthesizeKey("VK_ESCAPE", {}, cw);
     assertSearchIsDisabled();
   }
-  
-  let finishTest = function () {
-    let onTabViewHidden = function () {
-      window.removeEventListener('tabviewhidden', onTabViewHidden, false);
+
+  waitForExplicitFinish();
+
+  newWindowWithTabView(function (win) {
+    registerCleanupFunction(function () win.close());
+
+    cw = win.TabView.getContentWindow();
+    search = cw.document.getElementById("search");
+    searchButton = cw.document.getElementById("searchbutton");
+
+    SimpleTest.waitForFocus(function () {
+      assertSearchIsDisabled();
+
+      testSearchInitiatedByKeyPress();
+      testSearchInitiatedByMouseClick();
+
       finish();
-    }
-    
-    window.addEventListener('tabviewhidden', onTabViewHidden, false);
-    TabView.hide();
-  }
-  
-  assertSearchIsDisabled();
-  
-  testSearchInitiatedByKeyPress();
-  testSearchInitiatedByMouseClick();
-  
-  finishTest();
+    }, cw);
+  });
 }
--- a/browser/base/content/test/tabview/browser_tabview_bug595560.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug595560.js
@@ -20,18 +20,20 @@ function test() {
   }
   browser.addEventListener("load", onLoad, true);
 }
 
 function onTabViewWindowLoaded() {
   window.removeEventListener("tabviewshown", onTabViewWindowLoaded, false);
   ok(TabView.isVisible(), "Tab View is visible");
 
-  let contentWindow = document.getElementById("tab-view").contentWindow;
-  testOne(contentWindow);
+  afterAllTabItemsUpdated(function() { 
+    let contentWindow = document.getElementById("tab-view").contentWindow;
+    testOne(contentWindow);
+  });
 }
 
 function testOne(contentWindow) {
   onSearchEnabledAndDisabled(contentWindow, function() {
     testTwo(contentWindow); 
   });
   // press cmd/ctrl F
   EventUtils.synthesizeKey("f", { accelKey: true });
--- a/browser/base/content/test/tabview/browser_tabview_bug597248.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug597248.js
@@ -29,17 +29,17 @@ function setupTwo(win) {
 
   let tabItems = contentWindow.TabItems.getItems();
   is(tabItems.length, 3, "There should be 3 tab items before closing");
 
   let numTabsToSave = tabItems.length;
 
   // force all canvases to update, and hook in imageData save detection
   tabItems.forEach(function(tabItem) {
-    contentWindow.TabItems._update(tabItem.tab);
+    contentWindow.TabItems.update(tabItem.tab);
     tabItem.addSubscriber(tabItem, "savedCachedImageData", function(item) {
       item.removeSubscriber(item, "savedCachedImageData");
       --numTabsToSave;
     });
   });
 
   // after the window is closed, restore it.
   let xulWindowDestory = function() {
@@ -65,18 +65,17 @@ function setupTwo(win) {
         newTabThree = restoredWin.gBrowser.tabs[2];
         restoredWin.gBrowser.addTabsProgressListener(gTabsProgressListener);
 
         // execute code when the frame is initialized
         let onTabViewFrameInitialized = function() {
           restoredWin.removeEventListener(
             "tabviewframeinitialized", onTabViewFrameInitialized, false);
 
-          let restoredContentWindow =
-            restoredWin.document.getElementById("tab-view").contentWindow;
+          let restoredContentWindow = restoredWin.TabView.getContentWindow();
           // prevent TabItems._update being called before checking cached images
           restoredContentWindow.TabItems._pauseUpdateForTest = true;
 
           let nextStep = function() {
             // since we are not sure whether the frame is initialized first or two tabs
             // compete loading first so we need this.
             if (restoredNewTabTwoLoaded && restoredNewTabThreeLoaded)
               updateAndCheck();
@@ -129,18 +128,17 @@ let gTabsProgressListener = {
           updateAndCheck();
       }
     }
   }
 };
 
 function updateAndCheck() {
   // force all canvas to update
-  let contentWindow = 
-    restoredWin.document.getElementById("tab-view").contentWindow;
+  let contentWindow = restoredWin.TabView.getContentWindow();
 
   contentWindow.TabItems._pauseUpdateForTest = false;
 
   let tabItems = contentWindow.TabItems.getItems();
   tabItems.forEach(function(tabItem) {
     contentWindow.TabItems._update(tabItem.tab);
     ok(!tabItem.isShowingCachedData(),
       "Tab item is not showing cached data anymore. " +
--- a/browser/base/content/test/tabview/browser_tabview_bug602432.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug602432.js
@@ -1,72 +1,45 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 function test() {
-  waitForExplicitFinish();
-  newWindowWithTabView(onTabViewWindowLoaded);
-}
-
-let contentWindow = null;
-
-function onTabViewWindowLoaded(win) {
-  ok(win.TabView.isVisible(), "Tab View is visible");
-
-  contentWindow = win.TabView.getContentWindow();
-
-  // Preparation
-  //
-  let numTabs = 10;
-  let groupItem = createGroupItemWithBlankTabs(win, 150, 150, 100,
-    numTabs, false);
-
-  // Ensure that group is stacked
-  ok(groupItem.isStacked(), "Group item is stacked");
+  let checkUpdateTimes = function (groupItem) {
+    let children = groupItem.getChildren();
+    let earliestUpdateTime = children.shift()._testLastTabUpdateTime;
 
-  // Force updates to be deferred
-  contentWindow.TabItems.pausePainting();
-  let children = groupItem.getChildren();
-  is(children.length, numTabs, "Correct number of tabitems created");
-   
-  let leftToUpdate = numTabs;
-  let testFunc = function(tabItem) {
-    tabItem.removeSubscriber(tabItem, "updated");
-    if (--leftToUpdate>0)
-      return;
-    // Now that everything is updated, compare update times.
-    // All tabs in the group should have updated AFTER the first one.
-    let earliest = children[0]._lastTabUpdateTime;
-    for (let c=1; c<children.length; ++c)
-      ok(earliest <= children[c]._lastTabUpdateTime,
-        "Stacked group item update ("+children[c]._lastTabUpdateTime+") > first item ("+earliest+")");
-    shutDown(win, groupItem);
-  };
-
-  for (let c=0; c<children.length; ++c) {
-    let tabItem = children[c];
-    tabItem.addSubscriber(tabItem, "updated", testFunc);
-    contentWindow.TabItems.update(tabItem.tab);
+    children.forEach(function (tabItem) {
+      let updateTime = tabItem._testLastTabUpdateTime;
+      ok(earliestUpdateTime <= updateTime, "Stacked group item update (" +
+         updateTime + ") > first item (" + earliestUpdateTime + ")");
+    });
   }
 
-  // Let the update queue start again
-  contentWindow.TabItems.resumePainting();
-}
+  waitForExplicitFinish();
+
+  newWindowWithTabView(function (win) {
+    registerCleanupFunction(function () win.close());
+
+    let numTabsToUpdate = 10;
+    let groupItem = createGroupItemWithBlankTabs(win, 150, 150, 100, numTabsToUpdate, false);
+    ok(groupItem.isStacked(), "groupItem is stacked");
+
+    let cw = win.TabView.getContentWindow();
+    cw.TabItems.pausePainting();
 
-function shutDown(win, groupItem) {
-  // Shut down
-  let groupItemCount = contentWindow.GroupItems.groupItems.length;
-  closeGroupItem(groupItem, function() {
-    // check the number of groups.
-    is(contentWindow.GroupItems.groupItems.length, --groupItemCount,
-       "The number of groups is decreased by 1");
-    let onTabViewHidden = function() {
-      win.removeEventListener("tabviewhidden", onTabViewHidden, false);
-      // assert that we're no longer in tab view
-      ok(!TabView.isVisible(), "Tab View is hidden");
-      win.close();
-      ok(win.closed, "new window is closed");
-      finish();
-    };
-    win.addEventListener("tabviewhidden", onTabViewHidden, false);
-    win.TabView.toggle();
+    groupItem.getChildren().forEach(function (tabItem) {
+      tabItem.addSubscriber(tabItem, "updated", function () {
+        tabItem.removeSubscriber(tabItem, "updated");
+        tabItem._testLastTabUpdateTime = tabItem._lastTabUpdateTime;
+
+        if (--numTabsToUpdate)
+          return;
+
+        checkUpdateTimes(groupItem);
+        finish();
+      });
+
+      cw.TabItems.update(tabItem.tab);
+    });
+
+    cw.TabItems.resumePainting();
   });
 }
--- a/browser/base/content/test/tabview/browser_tabview_bug604098.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug604098.js
@@ -1,87 +1,64 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 let originalTab;
 let orphanedTab;
 let contentWindow;
+let contentElement;
 
 function test() {
   waitForExplicitFinish();
 
-  window.addEventListener("tabviewshown", onTabViewWindowLoaded, false);
-  TabView.show();
-}
-
-function onTabViewWindowLoaded() {
-  window.removeEventListener("tabviewshown", onTabViewWindowLoaded, false);
-
-  contentWindow = document.getElementById("tab-view").contentWindow;
-  originalTab = gBrowser.visibleTabs[0];
-
-  test1();
+  showTabView(function() {
+    contentWindow = TabView.getContentWindow();
+    contentElement = contentWindow.document.getElementById("content");
+    originalTab = gBrowser.visibleTabs[0];
+    test1();
+  });
 }
 
 function test1() {
   is(contentWindow.GroupItems.getOrphanedTabs().length, 0, "No orphaned tabs");
 
-  let onTabViewHidden = function() {
-    window.removeEventListener("tabviewhidden", onTabViewHidden, false);
-
-    let onTabViewShown = function() {
-      window.removeEventListener("tabviewshown", onTabViewShown, false);
-
-      is(contentWindow.GroupItems.getOrphanedTabs().length, 1, 
+  whenTabViewIsHidden(function() {
+    showTabView(function() {
+      is(contentWindow.GroupItems.getOrphanedTabs().length, 1,
          "An orphaned tab is created");
       orphanedTab = contentWindow.GroupItems.getOrphanedTabs()[0].tab;
 
       test2();
-    };
-    window.addEventListener("tabviewshown", onTabViewShown, false);
-    TabView.show();
-  };
-  window.addEventListener("tabviewhidden", onTabViewHidden, false);
+    });
+  });
 
   // first click
-  EventUtils.sendMouseEvent(
-    { type: "mousedown" }, contentWindow.document.getElementById("content"), 
-    contentWindow);
-  EventUtils.sendMouseEvent(
-    { type: "mouseup" }, contentWindow.document.getElementById("content"), 
-    contentWindow);
+  mouseClick(contentElement, 0);
   // second click
-  EventUtils.sendMouseEvent(
-    { type: "mousedown" }, contentWindow.document.getElementById("content"), 
-    contentWindow);
-  EventUtils.sendMouseEvent(
-    { type: "mouseup" }, contentWindow.document.getElementById("content"), 
-    contentWindow);
+  mouseClick(contentElement, 0);
 }
 
 function test2() {
   let groupItem = createEmptyGroupItem(contentWindow, 300, 300, 200);
   is(groupItem.getChildren().length, 0, "The group is empty");
 
-  let onTabViewHidden = function() {
-    window.removeEventListener("tabviewhidden", onTabViewHidden, false);
+  hideTabView(function() {
+    is(groupItem.getChildren().length, 1, "A tab is created inside the group");
 
-    is(groupItem.getChildren().length, 1, "A tab is created inside the group");
-    
     gBrowser.selectedTab = originalTab;
     gBrowser.removeTab(orphanedTab);
     gBrowser.removeTab(groupItem.getChildren()[0].tab);
 
     finish();
-  };
-  window.addEventListener("tabviewhidden", onTabViewHidden, false);
+  });
 
   // first click
-  EventUtils.sendMouseEvent(
-    { type: "mousedown" }, groupItem.container, contentWindow);
-  EventUtils.sendMouseEvent(
-    { type: "mouseup" }, groupItem.container, contentWindow);
+  mouseClick(groupItem.container, 0);
   // second click
-  EventUtils.sendMouseEvent(
-    { type: "mousedown" }, groupItem.container, contentWindow);
+  mouseClick(groupItem.container, 0);
+}
+
+function mouseClick(targetElement, buttonCode) {
   EventUtils.sendMouseEvent(
-    { type: "mouseup" }, groupItem.container, contentWindow);
+    { type: "mousedown", button: buttonCode }, targetElement, contentWindow);
+  EventUtils.sendMouseEvent(
+    { type: "mouseup", button: buttonCode }, targetElement, contentWindow);
 }
--- a/browser/base/content/test/tabview/browser_tabview_bug612470.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug612470.js
@@ -1,76 +1,48 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Tests that groups behave properly when closing all tabs but app tabs.
 
-let appTab, contentWindow;
-let originalGroup, originalGroupTab, newGroup, newGroupTab;
+function test() {
+  let cw, win, groupItem;
+
+  let onLoad = function (tvwin) {
+    win = tvwin;
+    registerCleanupFunction(function () win.close());
+    win.gBrowser.pinTab(win.gBrowser.tabs[0]);
+    win.gBrowser.loadOneTab("about:blank", {inBackground: true});
+  };
+
+  let onShow = function () {
+    cw = win.TabView.getContentWindow();
+    is(cw.GroupItems.groupItems.length, 1, "There's only one group");
+
+    groupItem = createEmptyGroupItem(cw, 200, 200, 20);
+    cw.GroupItems.setActiveGroupItem(groupItem);
+
+    executeSoon(function () hideTabView(onHide, win));
+  };
 
-function test() {
+  let onHide = function () {
+    let tab = win.gBrowser.loadOneTab("about:blank", {inBackground: true});
+    is(groupItem.getChildren().length, 1, "One tab is in the new group");
+
+    executeSoon(function () {
+      is(win.gBrowser.visibleTabs.length, 2, "There are two tabs displayed");
+      win.gBrowser.removeTab(tab);
+
+      is(groupItem.getChildren().length, 0, "No tabs are in the new group");
+      is(win.gBrowser.visibleTabs.length, 1, "There is one tab displayed");
+      is(cw.GroupItems.groupItems.length, 2, "There are two groups still");
+
+      showTabView(function () {
+        is(cw.GroupItems.groupItems.length, 1, "There is now only one group");
+        waitForFocus(finish);
+      }, win);
+    });
+  };
+
   waitForExplicitFinish();
 
-  appTab = gBrowser.selectedTab;
-  gBrowser.pinTab(appTab);
-  originalGroupTab = gBrowser.addTab();
-
-  addEventListener("tabviewshown", createGroup, false);
-  TabView.toggle();
-}
-
-function createGroup() {
-  removeEventListener("tabviewshown", createGroup, false);
-
-  contentWindow = document.getElementById("tab-view").contentWindow;
-  is(contentWindow.GroupItems.groupItems.length, 1, "There's only one group");
-
-  originalGroup = contentWindow.GroupItems.groupItems[0];
-
-  // Create a new group.
-  let box = new contentWindow.Rect(20, 400, 300, 300);
-  newGroup = new contentWindow.GroupItem([], { bounds: box });
-
-  contentWindow.GroupItems.setActiveGroupItem(newGroup);
-
-  addEventListener("tabviewhidden", addTab, false);
-  TabView.toggle();
-}
-
-function addTab() {
-  removeEventListener("tabviewhidden", addTab, false);
-
-  newGroupTab = gBrowser.addTab();
-  is(newGroup.getChildren().length, 1, "One tab is in the new group");
-  executeSoon(removeTab);
+  newWindowWithTabView(onShow, onLoad);
 }
-
-function removeTab() {
-  is(gBrowser.visibleTabs.length, 2, "There are two tabs displayed");
-  gBrowser.removeTab(newGroupTab);
-
-  is(newGroup.getChildren().length, 0, "No tabs are in the new group");
-  is(gBrowser.visibleTabs.length, 1, "There is one tab displayed");
-  is(contentWindow.GroupItems.groupItems.length, 2,
-     "There are two groups still");
-
-  addEventListener("tabviewshown", checkForRemovedGroup, false);
-  TabView.toggle();
-}
-
-function checkForRemovedGroup() {
-  removeEventListener("tabviewshown", checkForRemovedGroup, false);
-
-  is(contentWindow.GroupItems.groupItems.length, 1,
-     "There is now only one group");
-
-  addEventListener("tabviewhidden", finishTest, false);
-  TabView.toggle();
-}
-
-function finishTest() {
-  removeEventListener("tabviewhidden", finishTest, false);
-
-  gBrowser.removeTab(originalGroupTab);
-  gBrowser.unpinTab(appTab);
-  finish();
-}
-
--- a/browser/base/content/test/tabview/browser_tabview_bug626791.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug626791.js
@@ -15,20 +15,16 @@ function test() {
           prefix + ": panorama button should be in the toolbar");
   }
 
   let assertToolbarButtonNotExists = function () {
     is(getToolbar().currentSet.indexOf("tabview-button"), -1,
        prefix + ": panorama button should not be in the toolbar");
   }
 
-  let assertNumberOfGroups = function (num) {
-    is(cw.GroupItems.groupItems.length, num, prefix + ': there are ' + num + ' groups');
-  }
-
   let assertNumberOfTabs = function (num) {
     is(win.gBrowser.tabs.length, num, prefix + ': there are ' + num + ' tabs');
   }
 
   let removeToolbarButton = function () {
     let toolbar = getToolbar();
     let currentSet = toolbar.currentSet.split(",");
     let buttonId = "tabview-button";
@@ -86,17 +82,17 @@ function test() {
     EventUtils.synthesizeMouse(body, width - 10, height - 10, {}, cw);
     EventUtils.synthesizeMouse(body, width - 10, height - 10, {}, cw);
 
     whenTabViewIsHidden(function () {
       assertNumberOfTabs(2);
       assertToolbarButtonExists();
 
       next();
-    });
+    }, win);
   }
 
   let testDragToCreateOrphan = function (tab) {
     if (!tab) {
       let tab = win.gBrowser.loadOneTab('about:blank', {inBackground: true});
       afterAllTabsLoaded(function () testDragToCreateOrphan(tab), win);
       return;
     }
@@ -119,60 +115,65 @@ function test() {
     assertToolbarButtonExists();
     next();
   }
 
   let testReAddingAfterRemoval = function () {
     prefix = 're-adding-after-removal';
     assertToolbarButtonNotExists();
 
-    TabView.firstUseExperienced = true;
+    win.TabView.firstUseExperienced = true;
+    assertToolbarButtonExists();
     removeToolbarButton();
+    assertToolbarButtonNotExists();
+
+    win.close();
 
-    TabView.firstUseExperienced = true;
-    TabView._addToolbarButton();
-
-    assertToolbarButtonNotExists();
-    next();
+    newWindowWithTabView(function (newWin) {
+      win = newWin;
+      win.TabView.firstUseExperienced = true;
+      assertToolbarButtonNotExists();
+      next();
+    });
   }
 
   let tests = [testNameGroup, testDragToCreateGroup, testCreateOrphan,
                testDragToCreateOrphan, testReAddingAfterRemoval];
 
   let next = function () {
     let test = tests.shift();
 
-    if (win)
-      win.close();
-
     if (!test) {
       finish();
       return;
     }
 
-    newWindowWithTabView(
-      function (newWin) {
-        cw = win.TabView.getContentWindow();
-        let groupItem = cw.GroupItems.groupItems[0];
-        groupItem.setSize(200, 200, true);
-        groupItem.setUserSize();
+    if (win)
+      win.close();
+
+    TabView.firstUseExperienced = false;
 
+    let onLoad = function (newWin) {
+      win = newWin;
+      removeToolbarButton();
+    }
+
+    let onShow = function () {
+      cw = win.TabView.getContentWindow();
+
+      let groupItem = cw.GroupItems.groupItems[0];
+      groupItem.setSize(200, 200, true);
+      groupItem.setUserSize();
+
+      SimpleTest.waitForFocus(function () {
         assertToolbarButtonNotExists();
         test();
-      },
-      function(newWin) {
-        win = newWin;
-        removeToolbarButton();
-        TabView.firstUseExperienced = false;
-        TabView.init();
-      }
-    );
+      }, cw);
+    }
+
+    newWindowWithTabView(onShow, onLoad);
   }
 
   waitForExplicitFinish();
-
-  registerCleanupFunction(function () {
-    if (win && !win.closed)
-      win.close();
-  });
+  registerCleanupFunction(function () win && win.close());
 
   next();
 }
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/tabview/browser_tabview_bug649006.js
@@ -0,0 +1,94 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+let contentWindow;
+let contentElement;
+let groupItem;
+
+function test() {
+  waitForExplicitFinish();
+
+  registerCleanupFunction(function () {
+    hideTabView(function () {});
+  });
+
+  showTabView(function() {
+    contentWindow = TabView.getContentWindow();
+    contentElement = contentWindow.document.getElementById("content");
+    test1();
+  });
+}
+
+function test1() {
+  is(gBrowser.tabs.length, 1, 
+     "Total number of tabs is 1 before right button double click");
+  // first click
+  mouseClick(contentElement, 2);
+  // second click
+  mouseClick(contentElement, 2);
+
+  is(gBrowser.tabs.length, 1, 
+     "Total number of tabs is 1 after right button double click");
+  test2();
+}
+
+
+function test2() {
+  is(gBrowser.tabs.length, 1, 
+     "Total number of tabs is 1 before left, right and left mouse clicks");
+
+  // first click
+  mouseClick(contentElement, 0);
+  // second click
+  mouseClick(contentElement, 2);
+  // third click
+  mouseClick(contentElement, 0);
+
+  is(gBrowser.tabs.length, 1, 
+     "Total number of tabs is 1 before left, right and left mouse clicks");
+  test3();
+}
+
+function test3() {
+  ok(contentWindow.GroupItems.groupItems.length, 1, "Only one group item exists");
+  groupItem = contentWindow.GroupItems.groupItems[0];
+
+  is(groupItem.getChildren().length, 1, 
+     "The number of tab items in the group is 1 before right button double click");
+
+  // first click
+  mouseClick(groupItem.container, 2);
+  // second click
+  mouseClick(groupItem.container, 2);
+
+  is(groupItem.getChildren().length, 1, 
+     "The number of tab items in the group is 1 after right button double click");
+  test4();
+}
+
+function test4() {
+  is(groupItem.getChildren().length, 1, 
+     "The number of tab items in the group is 1 before left, right, left mouse clicks");
+
+  // first click
+  mouseClick(groupItem.container, 0);
+  // second click
+  mouseClick(groupItem.container, 2);
+  // third click
+  mouseClick(groupItem.container, 0);
+
+  is(groupItem.getChildren().length, 1, 
+     "The number of tab items in the group is 1 before left, right, left mouse clicks");
+
+  hideTabView(function() {
+    is(gBrowser.tabs.length, 1, "Total number of tabs is 1 after all tests");
+    finish();
+  });
+}
+
+function mouseClick(targetElement, buttonCode) {
+  EventUtils.sendMouseEvent(
+    { type: "mousedown", button: buttonCode }, targetElement, contentWindow);
+  EventUtils.sendMouseEvent(
+    { type: "mouseup", button: buttonCode }, targetElement, contentWindow);
+}
+
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/tabview/browser_tabview_bug649307.js
@@ -0,0 +1,43 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function test() {
+  waitForExplicitFinish();
+
+  newWindowWithTabView(function (win) {
+    let cw = win.TabView.getContentWindow();
+
+    registerCleanupFunction(function () {
+      cw.gPrefBranch.clearUserPref("animate_zoom");
+      win.close();
+    });
+
+    cw.gPrefBranch.setBoolPref("animate_zoom", false);
+
+    let groupItem = cw.GroupItems.groupItems[0];
+    let shield = groupItem.$titleShield[0];
+    let keys = ["RETURN", "ENTER", "ESCAPE"];
+
+    ok(win.TabView.isVisible(), "tabview is visible");
+
+    let simulateKeyPress = function () {
+      let key = keys.shift();
+
+      if (!key) {
+        ok(win.TabView.isVisible(), "tabview is still visible");
+        finish();
+        return;
+      }
+
+      EventUtils.synthesizeMouseAtCenter(shield, {}, cw);
+      EventUtils.synthesizeKey("VK_" + key, {}, cw);
+
+      executeSoon(function () {
+        ok(win.TabView.isVisible(), "tabview is still visible [" + key + "]");
+        simulateKeyPress();
+      });
+    }
+
+    SimpleTest.waitForFocus(simulateKeyPress, cw);
+  });
+}
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/tabview/browser_tabview_bug651311.js
@@ -0,0 +1,38 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+function test() {
+  waitForExplicitFinish();
+
+  let callCount = 0;
+
+  newWindow(function (win) {
+    registerCleanupFunction(function () win.close());
+
+    win.TabView._initFrame(function () {
+      is(callCount++, 0, "call count is zero");
+      ok(win.TabView.getContentWindow().UI, "content window is loaded");
+    });
+
+    win.TabView._initFrame(function () {
+      is(callCount++, 1, "call count is one");
+      ok(win.TabView.getContentWindow().UI, "content window is loaded");
+    });
+
+    win.TabView._initFrame(function () {
+      is(callCount, 2, "call count is two");
+      ok(win.TabView.getContentWindow().UI, "content window is loaded");
+      finish();
+    });
+  });
+}
+
+function newWindow(callback) {
+  let opts = "chrome,all,dialog=no,height=800,width=800";
+  let win = window.openDialog(getBrowserURL(), "_blank", opts);
+
+  win.addEventListener("load", function onLoad() {
+    win.removeEventListener("load", onLoad, false);
+    callback(win);
+  }, false);
+}
--- a/browser/base/content/test/tabview/browser_tabview_rtl.js
+++ b/browser/base/content/test/tabview/browser_tabview_rtl.js
@@ -1,61 +1,46 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
-let tabViewShownCount = 0;
-
 // ----------
 function test() {
   waitForExplicitFinish();
 
   // verify initial state
   ok(!TabView.isVisible(), "Tab View starts hidden");
 
-  // use the Tab View button to launch it for the first time
-  window.addEventListener("tabviewshown", onTabViewLoadedAndShown("ltr"), false);
-  toggleTabView();
-}
-
-function toggleTabView() {
-  let tabViewCommand = document.getElementById("Browser:ToggleTabView");
-  tabViewCommand.doCommand();
+  showTabView(onTabViewLoadedAndShown("ltr"));
 }
 
 // ----------
 function onTabViewLoadedAndShown(dir) {
   return function() {
-    window.removeEventListener("tabviewshown", arguments.callee, false);
     ok(TabView.isVisible(), "Tab View is visible.");
 
     let contentWindow = document.getElementById("tab-view").contentWindow;
     let contentDocument = contentWindow.document;
     is(contentDocument.documentElement.getAttribute("dir"), dir,
        "The direction should be set to " + dir.toUpperCase());
 
     // kick off the series
-    window.addEventListener("tabviewhidden", onTabViewHidden(dir), false);
-    TabView.toggle();
+    hideTabView(onTabViewHidden(dir));
   };
 }
 
 // ---------- 
 function onTabViewHidden(dir) {
   return function() {
-    window.removeEventListener("tabviewhidden", arguments.callee, false);
     ok(!TabView.isVisible(), "Tab View is hidden.");
 
     if (dir == "ltr") {
       // Switch to RTL mode
       Services.prefs.setCharPref("intl.uidirection.en-US", "rtl");
 
-      // use the Tab View button to launch it for the second time
-      window.addEventListener("tabviewshown", onTabViewLoadedAndShown("rtl"), false);
-      toggleTabView();
+      showTabView(onTabViewLoadedAndShown("rtl"));
     } else {
       // Switch to LTR mode
       Services.prefs.clearUserPref("intl.uidirection.en-US");
 
       finish();
     }
   };
 }
-
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -59,17 +59,17 @@
           <xul:image class="autocomplete-icon" allowevents="true"/>
         </children>
         <xul:hbox anonid="textbox-input-box"
                   class="textbox-input-box urlbar-input-box"
                   flex="1" xbl:inherits="tooltiptext=inputtooltiptext">
           <children/>
           <html:input anonid="input"
                       class="autocomplete-textbox urlbar-input textbox-input uri-element-right-align"
-                      flex="1" allowevents="true"
+                      allowevents="true"
                       xbl:inherits="tooltiptext=inputtooltiptext,onfocus,onblur,value,type,maxlength,disabled,size,readonly,placeholder,tabindex,accesskey"/>
         </xul:hbox>
         <children includes="hbox"/>
       </xul:hbox>
       <xul:dropmarker anonid="historydropmarker"
                       class="autocomplete-history-dropmarker urlbar-history-dropmarker"
                       allowevents="true"
                       xbl:inherits="open,enablehistory,parentfocused=focused"/>
new file mode 100644
--- /dev/null
+++ b/browser/branding/aurora/content/aboutDialog.css
@@ -0,0 +1,20 @@
+#aboutDialogContainer {
+  background-image: url("chrome://branding/content/about-background.png");
+  background-repeat: no-repeat;
+  background-color: #000;
+  color: #fff;
+}
+
+.text-link {
+  color: #fff !important;
+}
+
+#rightBox {
+  /* this margin prevents text from overlapping the planet image */
+  margin-left: 280px;
+  margin-right: 20px;
+}
+
+#bottomBox {
+  background-color: rgba(0,0,0,.7);
+}
--- a/browser/branding/aurora/content/jar.mn
+++ b/browser/branding/aurora/content/jar.mn
@@ -3,8 +3,9 @@ browser.jar:
   content/branding/about.png                     (about.png)
   content/branding/about-background.png          (about-background.png)
   content/branding/about-logo.png                (about-logo.png)
   content/branding/about-wordmark.png            (about-wordmark.png)
   content/branding/icon48.png                    (icon48.png)
   content/branding/icon64.png                    (icon64.png)
   content/branding/icon128.png                   (../mozicon128.png)
   content/branding/icon16.png                    (../default16.png)
+  content/branding/aboutDialog.css               (aboutDialog.css)
new file mode 100644
--- /dev/null
+++ b/browser/branding/nightly/content/aboutDialog.css
@@ -0,0 +1,20 @@
+#aboutDialogContainer {
+  background-image: url("chrome://branding/content/about-background.png");
+  background-repeat: no-repeat;
+  background-color: #000;
+  color: #fff;
+}
+
+.text-link {
+  color: #fff !important;
+}
+
+#rightBox {
+  /* this margin prevents text from overlapping the planet image */
+  margin-left: 280px;
+  margin-right: 20px;
+}
+
+#bottomBox {
+  background-color: rgba(0,0,0,.7);
+}
--- a/browser/branding/nightly/content/jar.mn
+++ b/browser/branding/nightly/content/jar.mn
@@ -3,8 +3,9 @@ browser.jar:
   content/branding/about.png                     (about.png)
   content/branding/about-background.png          (about-background.png)
   content/branding/about-logo.png                (about-logo.png)
   content/branding/about-wordmark.png            (about-wordmark.png)
   content/branding/icon48.png                    (icon48.png)
   content/branding/icon64.png                    (icon64.png)
   content/branding/icon128.png                   (../mozicon128.png)
   content/branding/icon16.png                    (../default16.png)
+  content/branding/aboutDialog.css               (aboutDialog.css)
rename from other-licenses/branding/firefox/LICENSE
rename to browser/branding/official/LICENSE
rename from other-licenses/branding/firefox/Makefile.in
rename to browser/branding/official/Makefile.in
rename from other-licenses/branding/firefox/background.png
rename to browser/branding/official/background.png
rename from other-licenses/branding/firefox/branding.nsi
rename to browser/branding/official/branding.nsi
rename from other-licenses/branding/firefox/configure.sh
rename to browser/branding/official/configure.sh
rename from other-licenses/branding/firefox/content/Makefile.in
rename to browser/branding/official/content/Makefile.in
rename from other-licenses/branding/firefox/content/about-logo.png
rename to browser/branding/official/content/about-logo.png
rename from other-licenses/branding/firefox/content/about-wordmark.png
rename to browser/branding/official/content/about-wordmark.png
rename from other-licenses/branding/firefox/content/about.png
rename to browser/branding/official/content/about.png
new file mode 100644
--- /dev/null
+++ b/browser/branding/official/content/aboutDialog.css
@@ -0,0 +1,31 @@
+#clientBox {
+  background-color: #F7F7F7;
+  color: #222222;
+}
+
+#leftBox {
+  background-image: url("chrome://branding/content/about-logo.png");
+  background-repeat: no-repeat;
+  /* min-width and min-height create room for the logo */
+  min-width: 210px;
+  min-height: 210px;
+  margin-top:20px;
+  -moz-margin-start: 30px;
+}
+
+#rightBox {
+  margin-left: 30px;
+  margin-right: 30px;
+}
+
+#updateDeck > hbox > label:not([class="text-link"]) {
+  color: #909090;
+}
+
+#trademark {
+  font-size: xx-small;
+  text-align: center;
+  color: #999999;
+  margin-top: 10px;
+  margin-bottom: 10px;
+}
rename from other-licenses/branding/firefox/content/icon48.png
rename to browser/branding/official/content/icon48.png
rename from other-licenses/branding/firefox/content/icon64.png
rename to browser/branding/official/content/icon64.png
rename from other-licenses/branding/firefox/content/jar.mn
rename to browser/branding/official/content/jar.mn
--- a/other-licenses/branding/firefox/content/jar.mn
+++ b/browser/branding/official/content/jar.mn
@@ -2,8 +2,9 @@ browser.jar:
 % content branding %content/branding/ contentaccessible=yes
   content/branding/about.png                     (about.png)
   content/branding/about-logo.png                (about-logo.png)
   content/branding/about-wordmark.png            (about-wordmark.png)
   content/branding/icon48.png                    (icon48.png)
   content/branding/icon64.png                    (icon64.png)
   content/branding/icon128.png                   (../mozicon128.png)
   content/branding/icon16.png                    (../default16.png)
+  content/branding/aboutDialog.css               (aboutDialog.css)
rename from other-licenses/branding/firefox/default16.png
rename to browser/branding/official/default16.png
rename from other-licenses/branding/firefox/default22.png
rename to browser/branding/official/default22.png
rename from other-licenses/branding/firefox/default24.png
rename to browser/branding/official/default24.png
rename from other-licenses/branding/firefox/default256.png
rename to browser/branding/official/default256.png
rename from other-licenses/branding/firefox/default32.png
rename to browser/branding/official/default32.png
rename from other-licenses/branding/firefox/default48.png
rename to browser/branding/official/default48.png
rename from other-licenses/branding/firefox/disk.icns
rename to browser/branding/official/disk.icns
rename from other-licenses/branding/firefox/document-os2.ico
rename to browser/branding/official/document-os2.ico
rename from other-licenses/branding/firefox/document.icns
rename to browser/branding/official/document.icns
rename from other-licenses/branding/firefox/document.ico
rename to browser/branding/official/document.ico
rename from other-licenses/branding/firefox/document.png
rename to browser/branding/official/document.png
rename from other-licenses/branding/firefox/dsstore
rename to browser/branding/official/dsstore
rename from other-licenses/branding/firefox/firefox-os2.ico
rename to browser/branding/official/firefox-os2.ico
rename from other-licenses/branding/firefox/firefox.icns
rename to browser/branding/official/firefox.icns
rename from other-licenses/branding/firefox/firefox.ico
rename to browser/branding/official/firefox.ico
rename from other-licenses/branding/firefox/locales/Makefile.in
rename to browser/branding/official/locales/Makefile.in
--- a/other-licenses/branding/firefox/locales/Makefile.in
+++ b/browser/branding/official/locales/Makefile.in
@@ -33,15 +33,15 @@
 # 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 = other-licenses/branding/firefox/locales
+relativesrcdir = browser/branding/official/locales
 
 include $(DEPTH)/config/autoconf.mk
 
 DEFINES += -DAB_CD=$(AB_CD)
 
 include $(topsrcdir)/config/rules.mk
rename from other-licenses/branding/firefox/locales/browserconfig.properties
rename to browser/branding/official/locales/browserconfig.properties
rename from other-licenses/branding/firefox/locales/en-US/brand.dtd
rename to browser/branding/official/locales/en-US/brand.dtd
rename from other-licenses/branding/firefox/locales/en-US/brand.properties
rename to browser/branding/official/locales/en-US/brand.properties
rename from other-licenses/branding/firefox/locales/jar.mn
rename to browser/branding/official/locales/jar.mn
rename from other-licenses/branding/firefox/mozicon128.png
rename to browser/branding/official/mozicon128.png
rename from other-licenses/branding/firefox/pref/firefox-branding.js
rename to browser/branding/official/pref/firefox-branding.js
rename from other-licenses/branding/firefox/splash.bmp
rename to browser/branding/official/splash.bmp
rename from other-licenses/branding/firefox/wizHeader.bmp
rename to browser/branding/official/wizHeader.bmp
rename from other-licenses/branding/firefox/wizHeaderRTL.bmp
rename to browser/branding/official/wizHeaderRTL.bmp
rename from other-licenses/branding/firefox/wizWatermark.bmp
rename to browser/branding/official/wizWatermark.bmp
new file mode 100644
--- /dev/null
+++ b/browser/branding/unofficial/content/aboutDialog.css
@@ -0,0 +1,20 @@
+#aboutDialogContainer {
+  background-image: url("chrome://branding/content/about-background.png");
+  background-repeat: no-repeat;
+  background-color: #000;
+  color: #fff;
+}
+
+.text-link {
+  color: #fff !important;
+}
+
+#rightBox {
+  /* this margin prevents text from overlapping the planet image */
+  margin-left: 280px;
+  margin-right: 20px;
+}
+
+#bottomBox {
+  background-color: rgba(0,0,0,.7);
+}
--- a/browser/branding/unofficial/content/jar.mn
+++ b/browser/branding/unofficial/content/jar.mn
@@ -3,8 +3,9 @@ browser.jar:
   content/branding/about.png                     (about.png)
   content/branding/about-background.png          (about-background.png)
   content/branding/about-logo.png                (about-logo.png)
   content/branding/about-wordmark.png            (about-wordmark.png)
   content/branding/icon48.png                    (icon48.png)
   content/branding/icon64.png                    (icon64.png)
   content/branding/icon128.png                   (../mozicon128.png)
   content/branding/icon16.png                    (../default16.png)
+  content/branding/aboutDialog.css               (aboutDialog.css)
--- a/browser/components/Makefile.in
+++ b/browser/components/Makefile.in
@@ -65,27 +65,22 @@ PARALLEL_DIRS = \
   feeds \
   places \
   preferences \
   privatebrowsing \
   search \
   sessionstore \
   shell \
   sidebar \
+  migration \
   $(NULL)
 
-ifndef WINCE
-PARALLEL_DIRS += migration
-endif
-
 ifeq ($(MOZ_WIDGET_TOOLKIT),windows) 
-ifndef WINCE
 PARALLEL_DIRS += wintaskbar
 endif
-endif
 
 ifdef MOZ_SAFE_BROWSING
 PARALLEL_DIRS += safebrowsing
 endif
 
 ifdef ENABLE_TESTS
 DIRS += test
 endif
--- a/browser/components/build/Makefile.in
+++ b/browser/components/build/Makefile.in
@@ -49,23 +49,20 @@ SHARED_LIBRARY_LIBS = \
 	$(NULL)
 
 ifneq (,$(filter windows cocoa gtk2, $(MOZ_WIDGET_TOOLKIT)))
 SHARED_LIBRARY_LIBS += ../shell/src/$(LIB_PREFIX)shellservice_s.$(LIB_SUFFIX)
 endif
 
 EXTRA_DSO_LDOPTS += $(call EXPAND_LIBNAME_PATH,unicharutil_external_s,$(LIBXUL_DIST)/lib)
 
-# migration requires mozreg, which doesn't build on WINCE; only include
-# it on non-CE
-ifndef WINCE
+# migration requires mozreg
 LOCAL_INCLUDES += -I$(srcdir)/../migration/src
 SHARED_LIBRARY_LIBS += ../migration/src/$(LIB_PREFIX)migration_s.$(LIB_SUFFIX)
 EXTRA_DSO_LDOPTS += $(LIBXUL_DIST)/lib/$(LIB_PREFIX)mozreg_s.$(LIB_SUFFIX)
-endif
 
 # This has to come after the above chunk, because mozreg_s has dependencies on
 # stuff in MOZ_COMPONENT_LIBS.
 EXTRA_DSO_LDOPTS += \
 	$(LIBXUL_DIST)/lib/$(LIB_PREFIX)xpcomglue_s.$(LIB_SUFFIX) \
 	$(MOZ_COMPONENT_LIBS) \
 	$(NULL)
 
--- a/browser/components/build/nsModule.cpp
+++ b/browser/components/build/nsModule.cpp
@@ -44,18 +44,16 @@
 #if defined(XP_WIN)
 #include "nsWindowsShellService.h"
 #elif defined(XP_MACOSX)
 #include "nsMacShellService.h"
 #elif defined(MOZ_WIDGET_GTK2)
 #include "nsGNOMEShellService.h"
 #endif
 
-#ifndef WINCE
-
 #include "nsProfileMigrator.h"
 #include "nsDogbertProfileMigrator.h"
 #if !defined(XP_OS2)
 #include "nsOperaProfileMigrator.h"
 #endif
 #include "nsPhoenixProfileMigrator.h"
 #include "nsSeamonkeyProfileMigrator.h"
 #if defined(XP_WIN) && !defined(__MINGW32__)
@@ -63,18 +61,16 @@
 #elif defined(XP_MACOSX)
 #include "nsSafariProfileMigrator.h"
 #include "nsOmniWebProfileMigrator.h"
 #include "nsMacIEProfileMigrator.h"
 #include "nsCaminoProfileMigrator.h"
 #include "nsICabProfileMigrator.h"
 #endif
 
-#endif // WINCE
-
 #include "rdf.h"
 #include "nsFeedSniffer.h"
 #include "AboutRedirector.h"
 #include "nsIAboutModule.h"
 
 #include "nsPrivateBrowsingServiceWrapper.h"
 #include "nsNetCID.h"
 
@@ -86,18 +82,16 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(Directory
 #if defined(XP_WIN)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsWindowsShellService)
 #elif defined(XP_MACOSX)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsMacShellService)
 #elif defined(MOZ_WIDGET_GTK2)
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsGNOMEShellService, Init)
 #endif
 
-#ifndef WINCE
-
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsDogbertProfileMigrator)
 #if !defined(XP_OS2)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsOperaProfileMigrator)
 #endif
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsPhoenixProfileMigrator)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsProfileMigrator)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsSeamonkeyProfileMigrator)
 #if defined(XP_WIN) && !defined(__MINGW32__)
@@ -105,31 +99,28 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(nsIEProfi
 #elif defined(XP_MACOSX)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsSafariProfileMigrator)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsOmniWebProfileMigrator)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsMacIEProfileMigrator)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsCaminoProfileMigrator)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsICabProfileMigrator)
 #endif
 
-#endif
-
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsFeedSniffer)
 
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsPrivateBrowsingServiceWrapper, Init)
 
 NS_DEFINE_NAMED_CID(NS_BROWSERDIRECTORYPROVIDER_CID);
 #if defined(XP_WIN)
 NS_DEFINE_NAMED_CID(NS_SHELLSERVICE_CID);
 #elif defined(MOZ_WIDGET_GTK2)
 NS_DEFINE_NAMED_CID(NS_SHELLSERVICE_CID);
 #endif
 NS_DEFINE_NAMED_CID(NS_FEEDSNIFFER_CID);
 NS_DEFINE_NAMED_CID(NS_BROWSER_ABOUT_REDIRECTOR_CID);
-#ifndef WINCE
 NS_DEFINE_NAMED_CID(NS_FIREFOX_PROFILEMIGRATOR_CID);
 #if defined(XP_WIN) && !defined(__MINGW32__)
 NS_DEFINE_NAMED_CID(NS_WINIEPROFILEMIGRATOR_CID);
 #elif defined(XP_MACOSX)
 NS_DEFINE_NAMED_CID(NS_SHELLSERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_SAFARIPROFILEMIGRATOR_CID);
 NS_DEFINE_NAMED_CID(NS_MACIEPROFILEMIGRATOR_CID);
 NS_DEFINE_NAMED_CID(NS_OMNIWEBPROFILEMIGRATOR_CID);
@@ -137,29 +128,27 @@ NS_DEFINE_NAMED_CID(NS_CAMINOPROFILEMIGR
 NS_DEFINE_NAMED_CID(NS_ICABPROFILEMIGRATOR_CID);
 #endif
 #if !defined(XP_OS2)
 NS_DEFINE_NAMED_CID(NS_OPERAPROFILEMIGRATOR_CID);
 #endif
 NS_DEFINE_NAMED_CID(NS_DOGBERTPROFILEMIGRATOR_CID);
 NS_DEFINE_NAMED_CID(NS_PHOENIXPROFILEMIGRATOR_CID);
 NS_DEFINE_NAMED_CID(NS_SEAMONKEYPROFILEMIGRATOR_CID);
-#endif /* WINCE */
 NS_DEFINE_NAMED_CID(NS_PRIVATE_BROWSING_SERVICE_WRAPPER_CID);
 
 static const mozilla::Module::CIDEntry kBrowserCIDs[] = {
     { &kNS_BROWSERDIRECTORYPROVIDER_CID, false, NULL, DirectoryProviderConstructor },
 #if defined(XP_WIN)
     { &kNS_SHELLSERVICE_CID, false, NULL, nsWindowsShellServiceConstructor },
 #elif defined(MOZ_WIDGET_GTK2)
     { &kNS_SHELLSERVICE_CID, false, NULL, nsGNOMEShellServiceConstructor },
 #endif
     { &kNS_FEEDSNIFFER_CID, false, NULL, nsFeedSnifferConstructor },
     { &kNS_BROWSER_ABOUT_REDIRECTOR_CID, false, NULL, AboutRedirector::Create },
-#ifndef WINCE
     { &kNS_FIREFOX_PROFILEMIGRATOR_CID, false, NULL, nsProfileMigratorConstructor },
 #if defined(XP_WIN) && !defined(__MINGW32__)
     { &kNS_WINIEPROFILEMIGRATOR_CID, false, NULL, nsIEProfileMigratorConstructor },
 #elif defined(XP_MACOSX)
     { &kNS_SHELLSERVICE_CID, false, NULL, nsMacShellServiceConstructor },
     { &kNS_SAFARIPROFILEMIGRATOR_CID, false, NULL, nsSafariProfileMigratorConstructor },
     { &kNS_MACIEPROFILEMIGRATOR_CID, false, NULL, nsMacIEProfileMigratorConstructor },
     { &kNS_OMNIWEBPROFILEMIGRATOR_CID, false, NULL, nsOmniWebProfileMigratorConstructor },
@@ -167,17 +156,16 @@ static const mozilla::Module::CIDEntry k
     { &kNS_ICABPROFILEMIGRATOR_CID, false, NULL, nsICabProfileMigratorConstructor },
 #endif
 #if !defined(XP_OS2)
     { &kNS_OPERAPROFILEMIGRATOR_CID, false, NULL, nsOperaProfileMigratorConstructor },
 #endif
     { &kNS_DOGBERTPROFILEMIGRATOR_CID, false, NULL, nsDogbertProfileMigratorConstructor },
     { &kNS_PHOENIXPROFILEMIGRATOR_CID, false, NULL, nsPhoenixProfileMigratorConstructor },
     { &kNS_SEAMONKEYPROFILEMIGRATOR_CID, false, NULL, nsSeamonkeyProfileMigratorConstructor },
-#endif /* WINCE */
     { &kNS_PRIVATE_BROWSING_SERVICE_WRAPPER_CID, false, NULL, nsPrivateBrowsingServiceWrapperConstructor },
     { NULL }
 };
 
 static const mozilla::Module::ContractIDEntry kBrowserContracts[] = {
     { NS_BROWSERDIRECTORYPROVIDER_CONTRACTID, &kNS_BROWSERDIRECTORYPROVIDER_CID },
 #if defined(XP_WIN)
     { NS_SHELLSERVICE_CONTRACTID, &kNS_SHELLSERVICE_CID },
@@ -193,17 +181,16 @@ static const mozilla::Module::ContractID
     { NS_ABOUT_MODULE_CONTRACTID_PREFIX "privatebrowsing", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
     { NS_ABOUT_MODULE_CONTRACTID_PREFIX "rights", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
     { NS_ABOUT_MODULE_CONTRACTID_PREFIX "robots", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
     { NS_ABOUT_MODULE_CONTRACTID_PREFIX "sessionrestore", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
 #ifdef MOZ_SERVICES_SYNC
     { NS_ABOUT_MODULE_CONTRACTID_PREFIX "sync-tabs", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
 #endif
     { NS_ABOUT_MODULE_CONTRACTID_PREFIX "home", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
-#ifndef WINCE
     { NS_PROFILEMIGRATOR_CONTRACTID, &kNS_FIREFOX_PROFILEMIGRATOR_CID },
 #if defined(XP_WIN) && !defined(__MINGW32__)
     { NS_BROWSERPROFILEMIGRATOR_CONTRACTID_PREFIX "ie", &kNS_WINIEPROFILEMIGRATOR_CID },
 #elif defined(XP_MACOSX)
     { NS_SHELLSERVICE_CONTRACTID, &kNS_SHELLSERVICE_CID },
     { NS_BROWSERPROFILEMIGRATOR_CONTRACTID_PREFIX "safari", &kNS_SAFARIPROFILEMIGRATOR_CID },
     { NS_BROWSERPROFILEMIGRATOR_CONTRACTID_PREFIX "macie", &kNS_MACIEPROFILEMIGRATOR_CID },
     { NS_BROWSERPROFILEMIGRATOR_CONTRACTID_PREFIX "omniweb", &kNS_OMNIWEBPROFILEMIGRATOR_CID },
@@ -211,17 +198,16 @@ static const mozilla::Module::ContractID
     { NS_BROWSERPROFILEMIGRATOR_CONTRACTID_PREFIX "icab", &kNS_ICABPROFILEMIGRATOR_CID },
 #endif
 #if !defined(XP_OS2)
     { NS_BROWSERPROFILEMIGRATOR_CONTRACTID_PREFIX "opera", &kNS_OPERAPROFILEMIGRATOR_CID },
 #endif
     { NS_BROWSERPROFILEMIGRATOR_CONTRACTID_PREFIX "dogbert", &kNS_DOGBERTPROFILEMIGRATOR_CID },
     { NS_BROWSERPROFILEMIGRATOR_CONTRACTID_PREFIX "phoenix", &kNS_PHOENIXPROFILEMIGRATOR_CID },
     { NS_BROWSERPROFILEMIGRATOR_CONTRACTID_PREFIX "seamonkey", &kNS_SEAMONKEYPROFILEMIGRATOR_CID },
-#endif /* WINCE */
     { NS_PRIVATE_BROWSING_SERVICE_CONTRACTID, &kNS_PRIVATE_BROWSING_SERVICE_WRAPPER_CID },
     { NULL }
 };
 
 static const mozilla::Module::CategoryEntry kBrowserCategories[] = {
     { XPCOM_DIRECTORY_PROVIDER_CATEGORY, "browser-directory-provider", NS_BROWSERDIRECTORYPROVIDER_CONTRACTID },
     { NS_CONTENT_SNIFFER_CATEGORY, "Feed Sniffer", NS_FEEDSNIFFER_CONTRACTID },
     { NULL }
--- a/browser/components/feeds/content/subscribe.xml
+++ b/browser/components/feeds/content/subscribe.xml
@@ -44,17 +44,17 @@
           xmlns="http://www.mozilla.org/xbl"
           xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
   <binding id="feedreaderUI">
     <content>
       <xul:vbox>
         <xul:hbox align="center">
           <xul:description anonid="subscribeUsingDescription" class="subscribeUsingDescription"/>
           <xul:menulist anonid="handlersMenuList" class="handlersMenuList" aria-labelledby="subscribeUsingDescription">
-            <xul:menupopup menugenerated="true" anonid="handlersMenuPopup" class="handlersMenuPopup">
+            <xul:menupopup anonid="handlersMenuPopup" class="handlersMenuPopup">
               <xul:menuitem anonid="liveBookmarksMenuItem" label="&feedLiveBookmarks;" class="menuitem-iconic liveBookmarksMenuItem" image="chrome://browser/skin/page-livemarks.png" selected="true"/>
               <xul:menuseparator/>
             </xul:menupopup>
           </xul:menulist>
         </xul:hbox>
         <xul:hbox>
           <xul:checkbox anonid="alwaysUse" class="alwaysUse" checked="false"/>
         </xul:hbox>
--- a/browser/components/migration/content/migration.js
+++ b/browser/components/migration/content/migration.js
@@ -452,20 +452,17 @@ var MigrationWizard = {
         if (this._newHomePage) {
           try {
             // set homepage properly
             var prefSvc = Components.classes["@mozilla.org/preferences-service;1"]
                                     .getService(Components.interfaces.nsIPrefService);
             var prefBranch = prefSvc.getBranch(null);
 
             if (this._newHomePage == "DEFAULT") {
-              try {
-                prefBranch.clearUserPref("browser.startup.homepage");
-              }
-              catch (e) { }
+              prefBranch.clearUserPref("browser.startup.homepage");
             }
             else {
               var str = Components.classes["@mozilla.org/supports-string;1"]
                                 .createInstance(Components.interfaces.nsISupportsString);
               str.data = this._newHomePage;
               prefBranch.setComplexValue("browser.startup.homepage",
                                          Components.interfaces.nsISupportsString,
                                          str);
--- a/browser/components/nsBrowserGlue.js
+++ b/browser/components/nsBrowserGlue.js
@@ -256,16 +256,24 @@ BrowserGlue.prototype = {
       case "browser-glue-test": // used by tests
         if (data == "post-update-notification") {
           if (Services.prefs.prefHasUserValue("app.update.postupdate"))
             this._showUpdateNotification();
         }
         else if (data == "force-ui-migration") {
           this._migrateUI();
         }
+        else if (data == "force-distribution-customization") {
+          this._distributionCustomizer.applyPrefDefaults();
+          this._distributionCustomizer.applyCustomizations();
+          // To apply distribution bookmarks use "places-init-complete".
+        }
+        else if (data == "force-places-init") {
+          this._initPlaces();
+        }
         break;
     }
   }, 
 
   // initialization (called on application startup) 
   _init: function BG__init() {
     let os = Services.obs;
     os.addObserver(this, "xpcom-shutdown", false);
@@ -357,45 +365,29 @@ BrowserGlue.prototype = {
     }
 
     Services.obs.notifyObservers(null, "browser-ui-startup-complete", "");
   },
 
   // the first browser window has finished initializing
   _onFirstWindowLoaded: function BG__onFirstWindowLoaded() {
 #ifdef XP_WIN
-#ifndef WINCE
     // For windows seven, initialize the jump list module.
     const WINTASKBAR_CONTRACTID = "@mozilla.org/windows-taskbar;1";
     if (WINTASKBAR_CONTRACTID in Cc &&
         Cc[WINTASKBAR_CONTRACTID].getService(Ci.nsIWinTaskbar).available) {
       let temp = {};
       Cu.import("resource://gre/modules/WindowsJumpLists.jsm", temp);
       temp.WinTaskbarJumpList.startup();
     }
 #endif
-#endif
   },
 
   // profile shutdown handler (contains profile cleanup routines)
   _onProfileShutdown: function BG__onProfileShutdown() {
-#ifdef MOZ_UPDATER
-#ifdef WINCE
-    // If there's a pending update, clear cache to free up disk space.
-    try {
-      let um = Cc["@mozilla.org/updates/update-manager;1"].
-               getService(Ci.nsIUpdateManager);
-      if (um.activeUpdate && um.activeUpdate.state == "pending") {
-        let cacheService = Cc["@mozilla.org/network/cache-service;1"].
-                           getService(Ci.nsICacheService);
-        cacheService.evictEntries(Ci.nsICache.STORE_ANYWHERE);
-      }
-    } catch (e) { }
-#endif
-#endif
     this._shutdownPlaces();
     this._sanitizer.onShutdown();
   },
 
   // Browser startup complete. All initial windows have opened.
   _onBrowserStartup: function BG__onBrowserStartup() {
     // Show about:rights notification, if needed.
     if (this._shouldShowRights())
--- a/browser/components/places/content/history-panel.js
+++ b/browser/components/places/content/history-panel.js
@@ -79,38 +79,38 @@ function searchHistory(aInput)
   const NHQO = Ci.nsINavHistoryQueryOptions;
   var sortingMode;
   var resultType;
 
   switch (gHistoryGrouping) {
     case "visited":
       resultType = NHQO.RESULTS_AS_URI;
       sortingMode = NHQO.SORT_BY_VISITCOUNT_DESCENDING;
-      break; 
+      break;
     case "lastvisited":
       resultType = NHQO.RESULTS_AS_URI;
       sortingMode = NHQO.SORT_BY_DATE_DESCENDING;
-      break; 
+      break;
     case "dayandsite":
       resultType = NHQO.RESULTS_AS_DATE_SITE_QUERY;
       break;
     case "site":
       resultType = NHQO.RESULTS_AS_SITE_QUERY;
       sortingMode = NHQO.SORT_BY_TITLE_ASCENDING;
       break;
     case "day":
     default:
       resultType = NHQO.RESULTS_AS_DATE_QUERY;
       break;
   }
 
   if (aInput) {
     query.searchTerms = aInput;
     if (gHistoryGrouping != "visited" && gHistoryGrouping != "lastvisited") {
-      sortingMode = NHQO.SORT_BY_TITLE_ASCENDING;
+      sortingMode = NHQO.SORT_BY_FRECENCY_DESCENDING;
       resultType = NHQO.RESULTS_AS_URI;
     }
   }
 
   options.sortingMode = sortingMode;
   options.resultType = resultType;
 
   // call load() on the tree manually
--- a/browser/components/places/tests/browser/browser_410196_paste_into_tags.js
+++ b/browser/components/places/tests/browser/browser_410196_paste_into_tags.js
@@ -34,18 +34,20 @@ function onLibraryReady() {
   ok(PlacesUIUtils, "PlacesUIUtils in scope");
 
   PlacesOrganizer = gLibrary.PlacesOrganizer;
   ok(PlacesOrganizer, "Places organizer in scope");
 
   tests.makeHistVisit();
   tests.makeTag();
   tests.focusTag();
-  tests.copyHistNode();
-  tests.waitForClipboard();
+  waitForClipboard(function(aData) !!aData,
+                   tests.copyHistNode,
+                   onClipboardReady,
+                   PlacesUtils.TYPE_X_MOZ_PLACE);
 }
 
 function onClipboardReady() {
   tests.pasteToTag();
   tests.historyNode();
   tests.checkForBookmarkInUI();
 
   gLibrary.close();
@@ -109,34 +111,16 @@ let tests = {
     this.histNode = PlacesOrganizer._content.view.nodeForTreeIndex(0);
     PlacesOrganizer._content.selectNode(this.histNode);
     is(this.histNode.uri, MOZURISPEC,
        "historyNode exists: " + this.histNode.uri);
     // copy the history node
     PlacesOrganizer._content.controller.copy();
   },
 
-  waitForClipboard: function (){
-    try {
-      let xferable = Cc["@mozilla.org/widget/transferable;1"].
-                     createInstance(Ci.nsITransferable);
-      xferable.addDataFlavor(PlacesUtils.TYPE_X_MOZ_PLACE);
-      let clipboard = Cc["@mozilla.org/widget/clipboard;1"].
-                      getService(Ci.nsIClipboard);
-      clipboard.getData(xferable, Ci.nsIClipboard.kGlobalClipboard);
-      let data = { }, type = { };
-      xferable.getAnyTransferData(type, data, { });
-      // Data is in the clipboard
-      onClipboardReady();
-    } catch (ex) {
-      // check again after 100ms.
-      setTimeout(arguments.callee, 100);
-    }
-  },
-
   pasteToTag: function (){
     // paste history node into tag
     this.focusTag(true);
   },
 
   historyNode: function (){
     // re-focus the history again
     PlacesOrganizer.selectLeftPaneQuery("History");
--- a/browser/components/places/tests/browser/browser_423515.js
+++ b/browser/components/places/tests/browser/browser_423515.js
@@ -232,19 +232,21 @@ function test() {
       readOnlyFolder.QueryInterface(Ci.nsINavHistoryContainerResultNode);
       readOnlyFolder.containerOpen = true;
       var childFolder = readOnlyFolder.getChild(0);
 
       is(PlacesControllerDragHelper.canMoveContainer(childFolder.itemId),
          false, "cannot move a child of a read-only folder");
       is(PlacesControllerDragHelper.canMoveNode(childFolder),
          false, "cannot move a child node of a read-only folder node");
+      readOnlyFolder.containerOpen = false;
     }
   });
 
   tests.forEach(function(aTest) {
     PlacesUtils.bookmarks.removeFolderChildren(rootId);
     aTest.populate();
     aTest.validate();
   });
 
+  rootNode.containerOpen = false;
   PlacesUtils.bookmarks.removeItem(rootId);
 }
--- a/browser/components/places/tests/browser/browser_425884.js
+++ b/browser/components/places/tests/browser/browser_425884.js
@@ -73,16 +73,18 @@ function test() {
   validate(folderANode);
   is(testRootNode.childCount, 1, "create test folder");
 
   // copy it, using the front-end helper functions
   var serializedNode = PlacesUtils.wrapNode(folderANode, PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER);
   var rawNode = PlacesUtils.unwrapNodes(serializedNode, PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER).shift();
   // confirm serialization
   ok(rawNode.type, "confirm json node");
+  folderANode.containerOpen = false;
+
   var transaction = PlacesUIUtils.makeTransaction(rawNode,
                                                   PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER,
                                                   testRootId,
                                                   -1,
                                                   true);
   ok(transaction, "create transaction");
   PlacesUIUtils.ptm.doTransaction(transaction);
   // confirm copy
--- a/browser/components/places/tests/unit/test_browserGlue_distribution.js
+++ b/browser/components/places/tests/unit/test_browserGlue_distribution.js
@@ -1,154 +1,97 @@
-/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* ***** 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 Places Unit Test code.
- *
- * The Initial Developer of the Original Code is Mozilla Foundation.
- * Portions created by the Initial Developer are Copyright (C) 2009
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Marco Bonardo <mak77@bonardo.net>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * 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 ***** */
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
- * Tests that nsBrowserGlue does not overwrite bookmarks imported from the
- * migrators.  They usually run before nsBrowserGlue, so if we find any
- * bookmark on init, we should not try to import.
+ * Tests that nsBrowserGlue correctly imports bookmarks from distribution.ini.
  */
 
 const PREF_SMART_BOOKMARKS_VERSION = "browser.places.smartBookmarksVersion";
 const PREF_BMPROCESSED = "distribution.516444.bookmarksProcessed";
 const PREF_DISTRIBUTION_ID = "distribution.id";
 
-const TOPIC_FINAL_UI_STARTUP = "final-ui-startup";
+const TOPICDATA_DISTRIBUTION_CUSTOMIZATION = "force-distribution-customization";
 const TOPIC_CUSTOMIZATION_COMPLETE = "distribution-customization-complete";
+const TOPIC_BROWSERGLUE_TEST = "browser-glue-test";
 
-function run_test() {
-  // This is needed but we still have to investigate the reason, could just be
-  // we try to act too late in the game, moving our shutdown earlier will help.
-  let hs = Cc["@mozilla.org/browser/nav-history-service;1"].
-         getService(Ci.nsINavHistoryService);
-  // TODO: re-enable when bug 523936 is fixed.
-  return;
-
+function run_test()
+{
   do_test_pending();
 
   // Copy distribution.ini file to our app dir.
   let distroDir = Services.dirsvc.get("XCurProcD", Ci.nsIFile);
   distroDir.append("distribution");
   let iniFile = distroDir.clone();
   iniFile.append("distribution.ini");
   if (iniFile.exists()) {
     iniFile.remove(false);
     print("distribution.ini already exists, did some test forget to cleanup?");
   }
-
   let testDistributionFile = gTestDir.clone();
   testDistributionFile.append("distribution.ini");
   testDistributionFile.copyTo(distroDir, "distribution.ini");
   do_check_true(testDistributionFile.exists());
 
   // Disable Smart Bookmarks creation.
-  let ps = Cc["@mozilla.org/preferences-service;1"].
-           getService(Ci.nsIPrefBranch);
-  ps.setIntPref(PREF_SMART_BOOKMARKS_VERSION, -1);
-  // Avoid migrateUI, we are just simulating a partial startup.
-  ps.setIntPref("browser.migration.version", 4);
+  Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, -1);
 
-  // Initialize Places through the History Service.
-  let hs = Cc["@mozilla.org/browser/nav-history-service;1"].
-           getService(Ci.nsINavHistoryService);
-  // Check a new database has been created.
-  // nsBrowserGlue will use databaseStatus to manage initialization.
-  do_check_eq(hs.databaseStatus, hs.DATABASE_STATUS_CREATE);
-
-  // Initialize nsBrowserGlue.
-  let bg = Cc["@mozilla.org/browser/browserglue;1"].
-           getService(Ci.nsIBrowserGlue);
+  // Initialize Places through the History Service and check that a new
+  // database has been created.
+  do_check_eq(PlacesUtils.history.databaseStatus,
+              PlacesUtils.history.DATABASE_STATUS_CREATE);
 
-  let os = Cc["@mozilla.org/observer-service;1"].
-           getService(Ci.nsIObserverService);
-  let observer = {
-    observe: function(aSubject, aTopic, aData) {
-      os.removeObserver(this, PlacesUtils.TOPIC_INIT_COMPLETE);
+  // Force distribution.
+  Cc["@mozilla.org/browser/browserglue;1"].
+  getService(Ci.nsIObserver).observe(null,
+                                     TOPIC_BROWSERGLUE_TEST,
+                                     TOPICDATA_DISTRIBUTION_CUSTOMIZATION);
 
-      // Simulate browser startup.
-      bg.QueryInterface(Ci.nsIObserver).observe(null,
-                                                TOPIC_FINAL_UI_STARTUP,
-                                                null);
-      // Test will continue on customization complete notification.
-      let cObserver = {
-        observe: function(aSubject, aTopic, aData) {
-          os.removeObserver(this, TOPIC_CUSTOMIZATION_COMPLETE);
-          do_execute_soon(continue_test);
-        }
-      }
-      os.addObserver(cObserver, TOPIC_CUSTOMIZATION_COMPLETE, false);
-    }
-  }
-  os.addObserver(observer, PlacesUtils.TOPIC_INIT_COMPLETE, false);
+  // Test will continue on customization complete notification.
+  Services.obs.addObserver(function(aSubject, aTopic, aData) {
+    Services.obs.removeObserver(arguments.callee,
+                                TOPIC_CUSTOMIZATION_COMPLETE,
+                                false);
+    do_execute_soon(onCustomizationComplete);
+  }, TOPIC_CUSTOMIZATION_COMPLETE, false);
 }
 
-function continue_test() {
-  let bs = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
-           getService(Ci.nsINavBookmarksService);
-
-  dump_table("moz_bookmarks");
-
+function onCustomizationComplete()
+{
   // Check the custom bookmarks exist on menu.
-  let menuItemId = bs.getIdForItemAt(bs.bookmarksMenuFolder, 0);
+  let menuItemId =
+    PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.bookmarksMenuFolderId, 0);
   do_check_neq(menuItemId, -1);
-  do_check_eq(bs.getItemTitle(menuItemId), "Menu Link Before");
-  menuItemId = bs.getIdForItemAt(bs.bookmarksMenuFolder, 1 + DEFAULT_BOOKMARKS_ON_MENU);
+  do_check_eq(PlacesUtils.bookmarks.getItemTitle(menuItemId),
+              "Menu Link Before");
+  menuItemId =
+    PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.bookmarksMenuFolderId,
+                                         1 + DEFAULT_BOOKMARKS_ON_MENU);
   do_check_neq(menuItemId, -1);
-  do_check_eq(bs.getItemTitle(menuItemId), "Menu Link After");
+  do_check_eq(PlacesUtils.bookmarks.getItemTitle(menuItemId),
+              "Menu Link After");
 
   // Check the custom bookmarks exist on toolbar.
-  let toolbarItemId = bs.getIdForItemAt(bs.toolbarFolder, 0);
+  let toolbarItemId =
+    PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId, 0);
   do_check_neq(toolbarItemId, -1);
-  do_check_eq(bs.getItemTitle(toolbarItemId), "Toolbar Link Before");
-  toolbarItemId = bs.getIdForItemAt(bs.toolbarFolder, 1 + DEFAULT_BOOKMARKS_ON_TOOLBAR);
+  do_check_eq(PlacesUtils.bookmarks.getItemTitle(toolbarItemId),
+              "Toolbar Link Before");
+  toolbarItemId =
+    PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId,
+                                         1 + DEFAULT_BOOKMARKS_ON_TOOLBAR);
   do_check_neq(toolbarItemId, -1);
-  do_check_eq(bs.getItemTitle(toolbarItemId), "Toolbar Link After");
+  do_check_eq(PlacesUtils.bookmarks.getItemTitle(toolbarItemId),
+              "Toolbar Link After");
 
   // Check the bmprocessed pref has been created.
-  let ps = Cc["@mozilla.org/preferences-service;1"].
-           getService(Ci.nsIPrefBranch);
-  do_check_true(ps.getBoolPref(PREF_BMPROCESSED));
+  do_check_true(Services.prefs.getBoolPref(PREF_BMPROCESSED));
 
   // Check distribution prefs have been created.
-  do_check_eq(ps.getCharPref(PREF_DISTRIBUTION_ID), "516444");
+  do_check_eq(Services.prefs.getCharPref(PREF_DISTRIBUTION_ID), "516444");
 
   do_test_finished();
 }
 
 do_register_cleanup(function() {
   // Remove the distribution file, even if the test failed, otherwise all
   // next tests will import it.
   let iniFile = Services.dirsvc.get("XCurProcD", Ci.nsIFile);
--- a/browser/components/places/tests/unit/test_browserGlue_migrate.js
+++ b/browser/components/places/tests/unit/test_browserGlue_migrate.js
@@ -1,121 +1,86 @@
-/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* ***** 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 Places Unit Test code.
- *
- * The Initial Developer of the Original Code is Mozilla Foundation.
- * Portions created by the Initial Developer are Copyright (C) 2009
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Marco Bonardo <mak77@bonardo.net>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * 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 ***** */
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Tests that nsBrowserGlue does not overwrite bookmarks imported from the
  * migrators.  They usually run before nsBrowserGlue, so if we find any
  * bookmark on init, we should not try to import.
  */
 
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "bs",
-                                   "@mozilla.org/browser/nav-bookmarks-service;1",
-                                   "nsINavBookmarksService");
-XPCOMUtils.defineLazyServiceGetter(this, "anno",
-                                   "@mozilla.org/browser/annotation-service;1",
-                                   "nsIAnnotationService");
-
-let bookmarksObserver = {
-  onBeginUpdateBatch: function() {},
-  onEndUpdateBatch: function() {
-    let itemId = bs.getIdForItemAt(bs.toolbarFolder, 0);
-    do_check_neq(itemId, -1);
-    if (anno.itemHasAnnotation(itemId, "Places/SmartBookmark"))
-      continue_test();
-  },
-  onItemAdded: function() {},
-  onBeforeItemRemoved: function(id) {},
-  onItemRemoved: function(id, folder, index, itemType) {},
-  onItemChanged: function() {},
-  onItemVisited: function(id, visitID, time) {},
-  onItemMoved: function() {},
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver])
-};
-
 const PREF_SMART_BOOKMARKS_VERSION = "browser.places.smartBookmarksVersion";
 
 function run_test() {
   do_test_pending();
 
   // Create our bookmarks.html copying bookmarks.glue.html to the profile
-  // folder.  It will be ignored.
+  // folder.  It should be ignored.
   create_bookmarks_html("bookmarks.glue.html");
 
   // Remove current database file.
   let db = gProfD.clone();
   db.append("places.sqlite");
   if (db.exists()) {
     db.remove(false);
     do_check_false(db.exists());
   }
 
-  // Initialize Places through the History Service.
-  let hs = Cc["@mozilla.org/browser/nav-history-service;1"].
-           getService(Ci.nsINavHistoryService);
-  // Check a new database has been created.
-  // nsBrowserGlue uses databaseStatus to manage initialization.
-  do_check_eq(hs.databaseStatus, hs.DATABASE_STATUS_CREATE);
+  // Initialize Places through the History Service and check that a new
+  // database has been created.
+  do_check_eq(PlacesUtils.history.databaseStatus,
+              PlacesUtils.history.DATABASE_STATUS_CREATE);
 
   // A migrator would run before nsBrowserGlue, so we mimic that behavior
   // adding a bookmark.
-  bs.insertBookmark(bs.bookmarksMenuFolder, uri("http://mozilla.org/"),
-                    bs.DEFAULT_INDEX, "migrated");
+  PlacesUtils.bookmarks.insertBookmark(PlacesUtils.bookmarks.bookmarksMenuFolder, uri("http://mozilla.org/"),
+                    PlacesUtils.bookmarks.DEFAULT_INDEX, "migrated");
 
   // Initialize nsBrowserGlue.
   let bg = Cc["@mozilla.org/browser/browserglue;1"].
            getService(Ci.nsIBrowserGlue);
 
+  let bookmarksObserver = {
+    onBeginUpdateBatch: function() {},
+    onEndUpdateBatch: function() {
+      // Check if the currently finished batch created the smart bookmarks.
+      let itemId =
+        PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId, 0);
+      do_check_neq(itemId, -1);
+      if (PlacesUtils.annotations
+                     .itemHasAnnotation(itemId, "Places/SmartBookmark")) {
+        do_execute_soon(onSmartBookmarksCreation);
+      }
+    },
+    onItemAdded: function() {},
+    onBeforeItemRemoved: function(id) {},
+    onItemRemoved: function(id, folder, index, itemType) {},
+    onItemChanged: function() {},
+    onItemVisited: function(id, visitID, time) {},
+    onItemMoved: function() {},
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver])
+  };
   // The test will continue once import has finished and smart bookmarks
   // have been created.
-  bs.addObserver(bookmarksObserver, false);
+  PlacesUtils.bookmarks.addObserver(bookmarksObserver, false);
 }
 
-function continue_test() {
+function onSmartBookmarksCreation() {
   // Check the created bookmarks still exist.
-  let itemId = bs.getIdForItemAt(bs.bookmarksMenuFolder, SMART_BOOKMARKS_ON_MENU);
-  do_check_eq(bs.getItemTitle(itemId), "migrated");
+  let itemId =
+    PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.bookmarksMenuFolderId,
+                                         SMART_BOOKMARKS_ON_MENU);
+  do_check_eq(PlacesUtils.bookmarks.getItemTitle(itemId), "migrated");
 
   // Check that we have not imported any new bookmark.
-  do_check_eq(bs.getIdForItemAt(bs.bookmarksMenuFolder, SMART_BOOKMARKS_ON_MENU + 1), -1);
-  do_check_eq(bs.getIdForItemAt(bs.toolbarFolder, SMART_BOOKMARKS_ON_MENU), -1);
+  itemId =
+    PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.bookmarksMenuFolderId,
+                                         SMART_BOOKMARKS_ON_MENU + 1)
+  do_check_eq(itemId, -1);
+  itemId =
+    PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId,
+                                         SMART_BOOKMARKS_ON_MENU)
+  do_check_eq(itemId, -1);
 
   remove_bookmarks_html();
 
   do_test_finished();
 }
--- a/browser/components/places/tests/unit/test_browserGlue_prefs.js
+++ b/browser/components/places/tests/unit/test_browserGlue_prefs.js
@@ -1,287 +1,265 @@
-/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* ***** 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 Places Unit Test code.
- *
- * The Initial Developer of the Original Code is Mozilla Foundation.
- * Portions created by the Initial Developer are Copyright (C) 2009
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Marco Bonardo <mak77@bonardo.net>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * 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 ***** */
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Tests that nsBrowserGlue is correctly interpreting the preferences settable
  * by the user or by other components.
  */
 
-/** Bug 539067
- * Test is disabled due to random failures and timeouts, see run_test.
- * This is commented out to avoid leaks.
-// Initialize browserGlue.
-let bg = Cc["@mozilla.org/browser/browserglue;1"].
-         getService(Ci.nsIBrowserGlue);
-*/
-
-// Initialize Places through Bookmarks Service.
-let bs = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
-         getService(Ci.nsINavBookmarksService);
-
-// Get other services.
-let ps = Cc["@mozilla.org/preferences-service;1"].
-         getService(Ci.nsIPrefBranch);
-let os = Cc["@mozilla.org/observer-service;1"].
-         getService(Ci.nsIObserverService);
-
 const PREF_IMPORT_BOOKMARKS_HTML = "browser.places.importBookmarksHTML";
 const PREF_RESTORE_DEFAULT_BOOKMARKS = "browser.bookmarks.restore_default_bookmarks";
 const PREF_SMART_BOOKMARKS_VERSION = "browser.places.smartBookmarksVersion";
 const PREF_AUTO_EXPORT_HTML = "browser.bookmarks.autoExportHTML";
 
-let tests = [];
-//------------------------------------------------------------------------------
+const TOPIC_BROWSERGLUE_TEST = "browser-glue-test";
+const TOPICDATA_FORCE_PLACES_INIT = "force-places-init";
+
+let bg = Cc["@mozilla.org/browser/browserglue;1"].
+         getService(Ci.nsIBrowserGlue);
+
+let gTests = [
+
+  // This test must be the first one.
+  function test_checkPreferences() {
+    // Initialize Places through the History Service and check that a new
+    // database has been created.
+    do_check_eq(PlacesUtils.history.databaseStatus,
+                PlacesUtils.history.DATABASE_STATUS_CREATE);
+
+    // Wait for Places init notification.
+    Services.obs.addObserver(function(aSubject, aTopic, aData) {
+      Services.obs.removeObserver(arguments.callee,
+                                  PlacesUtils.TOPIC_INIT_COMPLETE);
+      do_execute_soon(function () {
+        // Ensure preferences status.
+        do_check_false(Services.prefs.getBoolPref(PREF_AUTO_EXPORT_HTML));
 
-tests.push({
-  description: "Import from bookmarks.html if importBookmarksHTML is true.",
-  exec: function() {
+        try {
+          do_check_false(Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
+          do_throw("importBookmarksHTML pref should not exist");
+        }
+        catch(ex) {}
+
+        try {
+          do_check_false(Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS));
+          do_throw("importBookmarksHTML pref should not exist");
+        }
+        catch(ex) {}
+
+        run_next_test();
+      });
+    }, PlacesUtils.TOPIC_INIT_COMPLETE, false);
+  },
+
+  function test_import()
+  {
+    do_log_info("Import from bookmarks.html if importBookmarksHTML is true.");
+
+    remove_all_bookmarks();
     // Sanity check: we should not have any bookmark on the toolbar.
-    do_check_eq(bs.getIdForItemAt(bs.toolbarFolder, 0), -1);
+    let itemId =
+      PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId, 0);
+    do_check_eq(itemId, -1);
 
     // Set preferences.
-    ps.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
-
-    // Force nsBrowserGlue::_initPlaces().
-    print("Simulate Places init");
-    bg.QueryInterface(Ci.nsIObserver).observe(null,
-                                              PlacesUtils.TOPIC_INIT_COMPLETE,
-                                              null);
-    // Check bookmarks.html has been imported, and a smart bookmark has been
-    // created.
-    let itemId = bs.getIdForItemAt(bs.toolbarFolder,
-                                   SMART_BOOKMARKS_ON_TOOLBAR);
-    do_check_eq(bs.getItemTitle(itemId), "example");
-    // Check preferences have been reverted.
-    do_check_false(ps.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
-
-    next_test();
-  }
-});
-
-//------------------------------------------------------------------------------
-
-tests.push({
-  description: "import from bookmarks.html, but don't create smart bookmarks if they are disabled",
-  exec: function() {
-    // Sanity check: we should not have any bookmark on the toolbar.
-    do_check_eq(bs.getIdForItemAt(bs.toolbarFolder, 0), -1);
-
-    // Set preferences.
-    ps.setIntPref(PREF_SMART_BOOKMARKS_VERSION, -1);
-    ps.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
+    Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
 
     // Force nsBrowserGlue::_initPlaces().
     print("Simulate Places init");
     bg.QueryInterface(Ci.nsIObserver).observe(null,
-                                              PlacesUtils.TOPIC_INIT_COMPLETE,
-                                              null);
+                                              TOPIC_BROWSERGLUE_TEST,
+                                              TOPICDATA_FORCE_PLACES_INIT);
+
+    // Check bookmarks.html has been imported, and a smart bookmark has been
+    // created.
+    itemId = PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId,
+                                                  SMART_BOOKMARKS_ON_TOOLBAR);
+    do_check_eq(PlacesUtils.bookmarks.getItemTitle(itemId), "example");
+    // Check preferences have been reverted.
+    do_check_false(Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
+
+    run_next_test();
+  },
+
+  function test_import_noSmartBookmarks()
+  {
+    do_log_info("import from bookmarks.html, but don't create smart bookmarks \
+                 if they are disabled");
+
+    remove_all_bookmarks();
+    // Sanity check: we should not have any bookmark on the toolbar.
+    let itemId =
+      PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId, 0);
+    do_check_eq(itemId, -1);
+
+    // Set preferences.
+    Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, -1);
+    Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
+
+    // Force nsBrowserGlue::_initPlaces().
+    print("Simulate Places init");
+    bg.QueryInterface(Ci.nsIObserver).observe(null,
+                                              TOPIC_BROWSERGLUE_TEST,
+                                              TOPICDATA_FORCE_PLACES_INIT);
+
     // Check bookmarks.html has been imported, but smart bookmarks have not
     // been created.
-    let itemId = bs.getIdForItemAt(bs.toolbarFolder, 0);
-    do_check_eq(bs.getItemTitle(itemId), "example");
+    itemId =
+      PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId, 0);
+    do_check_eq(PlacesUtils.bookmarks.getItemTitle(itemId), "example");
     // Check preferences have been reverted.
-    do_check_false(ps.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
-
-    next_test();
-  }
-});
+    do_check_false(Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
 
-//------------------------------------------------------------------------------
-
-tests.push({
-  description: "Import from bookmarks.html, but don't create smart bookmarks if autoExportHTML is true and they are at latest version",
-  exec: function() {
-    // Sanity check: we should not have any bookmark on the toolbar.
-    do_check_eq(bs.getIdForItemAt(bs.toolbarFolder, 0), -1);
-    // Set preferences.
-    ps.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 999);
-    ps.setBoolPref(PREF_AUTO_EXPORT_HTML, true);
-    ps.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
+    run_next_test();
+  },
 
-    // Force nsBrowserGlue::_initPlaces()
-    print("Simulate Places init");
-    bg.QueryInterface(Ci.nsIObserver).observe(null,
-                                              PlacesUtils.TOPIC_INIT_COMPLETE,
-                                              null);
-    // Check bookmarks.html has been imported, but smart bookmarks have not
-    // been created.
-    let itemId = bs.getIdForItemAt(bs.toolbarFolder, 0);
-    do_check_eq(bs.getItemTitle(itemId), "example");
-    do_check_false(ps.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
-    // Check preferences have been reverted.
-    ps.setBoolPref(PREF_AUTO_EXPORT_HTML, false);
+  function test_import_autoExport_updatedSmartBookmarks()
+  {
+    do_log_info("Import from bookmarks.html, but don't create smart bookmarks \
+                 if autoExportHTML is true and they are at latest version");
 
-    next_test();
-  }
-});
-
-//------------------------------------------------------------------------------
+    remove_all_bookmarks();
+    // Sanity check: we should not have any bookmark on the toolbar.
+    let itemId =
+      PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId, 0);
+    do_check_eq(itemId, -1);
 
-tests.push({
-  description: "Import from bookmarks.html, and create smart bookmarks if autoExportHTML is true and they are not at latest version.",
-  exec: function() {
-    // Sanity check: we should not have any bookmark on the toolbar.
-    do_check_eq(bs.getIdForItemAt(bs.toolbarFolder, 0), -1);
     // Set preferences.
-    ps.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 0);
-    ps.setBoolPref(PREF_AUTO_EXPORT_HTML, true);
-    ps.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
+    Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 999);
+    Services.prefs.setBoolPref(PREF_AUTO_EXPORT_HTML, true);
+    Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
 
     // Force nsBrowserGlue::_initPlaces()
     print("Simulate Places init");
     bg.QueryInterface(Ci.nsIObserver).observe(null,
-                                              PlacesUtils.TOPIC_INIT_COMPLETE,
-                                              null);
+                                              TOPIC_BROWSERGLUE_TEST,
+                                              TOPICDATA_FORCE_PLACES_INIT);
+
     // Check bookmarks.html has been imported, but smart bookmarks have not
     // been created.
-    let itemId = bs.getIdForItemAt(bs.toolbarFolder, SMART_BOOKMARKS_ON_TOOLBAR);
-    do_check_eq(bs.getItemTitle(itemId), "example");
-    do_check_false(ps.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
+    itemId =
+      PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId, 0);
+    do_check_eq(PlacesUtils.bookmarks.getItemTitle(itemId), "example");
+    do_check_false(Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
     // Check preferences have been reverted.
-    ps.setBoolPref(PREF_AUTO_EXPORT_HTML, false);
+    Services.prefs.setBoolPref(PREF_AUTO_EXPORT_HTML, false);
 
-    next_test();
-  }
-});
-
-//------------------------------------------------------------------------------
-tests.push({
-  description: "restore from default bookmarks.html if restore_default_bookmarks is true.",
-  exec: function() {
-    // Sanity check: we should not have any bookmark on the toolbar.
-    do_check_eq(bs.getIdForItemAt(bs.toolbarFolder, 0), -1);
-    // Set preferences.
-    ps.setBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS, true);
+    run_next_test();
+  },
 
-    // Force nsBrowserGlue::_initPlaces()
-    print("Simulate Places init");
-    bg.QueryInterface(Ci.nsIObserver).observe(null,
-                                              PlacesUtils.TOPIC_INIT_COMPLETE,
-                                              null);
-    // Check bookmarks.html has been restored.
-    let itemId = bs.getIdForItemAt(bs.toolbarFolder, SMART_BOOKMARKS_ON_TOOLBAR + 1);
-    do_check_true(itemId > 0);
-    // Check preferences have been reverted.
-    do_check_false(ps.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS));
+  function test_import_autoExport_oldSmartBookmarks()
+  {
+    do_log_info("Import from bookmarks.html, and create smart bookmarks if \
+                 autoExportHTML is true and they are not at latest version.");
 
-    next_test();
-  }
-});
-
-//------------------------------------------------------------------------------
+    remove_all_bookmarks();
+    // Sanity check: we should not have any bookmark on the toolbar.
+    let itemId =
+      PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId, 0);
+    do_check_eq(itemId, -1);
 
-tests.push({
-  description: "setting both importBookmarksHTML and restore_default_bookmarks should restore defaults.",
-  exec: function() {
-    // Sanity check: we should not have any bookmark on the toolbar.
-    do_check_eq(bs.getIdForItemAt(bs.toolbarFolder, 0), -1);
     // Set preferences.
-    ps.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
-    ps.setBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS, true);
+    Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 0);
+    Services.prefs.setBoolPref(PREF_AUTO_EXPORT_HTML, true);
+    Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
 
     // Force nsBrowserGlue::_initPlaces()
     print("Simulate Places init");
     bg.QueryInterface(Ci.nsIObserver).observe(null,
-                                              PlacesUtils.TOPIC_INIT_COMPLETE,
-                                              null);
+                                              TOPIC_BROWSERGLUE_TEST,
+                                              TOPICDATA_FORCE_PLACES_INIT);
+
+    // Check bookmarks.html has been imported, but smart bookmarks have not
+    // been created.
+    itemId =
+      PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId,
+                                           SMART_BOOKMARKS_ON_TOOLBAR);
+    do_check_eq(PlacesUtils.bookmarks.getItemTitle(itemId), "example");
+    do_check_false(Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
+    // Check preferences have been reverted.
+    Services.prefs.setBoolPref(PREF_AUTO_EXPORT_HTML, false);
+
+    run_next_test();
+  },
+
+  function test_restore()
+  {
+    do_log_info("restore from default bookmarks.html if \
+                 restore_default_bookmarks is true.");
+
+    remove_all_bookmarks();
+    // Sanity check: we should not have any bookmark on the toolbar.
+    let itemId =
+      PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId, 0);
+    do_check_eq(itemId, -1);
+
+    // Set preferences.
+    Services.prefs.setBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS, true);
+
+    // Force nsBrowserGlue::_initPlaces()
+    print("Simulate Places init");
+    bg.QueryInterface(Ci.nsIObserver).observe(null,
+                                              TOPIC_BROWSERGLUE_TEST,
+                                              TOPICDATA_FORCE_PLACES_INIT);
+
     // Check bookmarks.html has been restored.
-    let itemId = bs.getIdForItemAt(bs.toolbarFolder, SMART_BOOKMARKS_ON_TOOLBAR + 1);
+    itemId =
+      PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId,
+                                           SMART_BOOKMARKS_ON_TOOLBAR + 1);
     do_check_true(itemId > 0);
     // Check preferences have been reverted.
-    do_check_false(ps.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS));
-    do_check_false(ps.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
+    do_check_false(Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS));
+
+    run_next_test();
+  },
+
+  function test_restore_import()
+  {
+    do_log_info("setting both importBookmarksHTML and \
+                 restore_default_bookmarks should restore defaults.");
+
+    remove_all_bookmarks();
+    // Sanity check: we should not have any bookmark on the toolbar.
+    let itemId =
+      PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId, 0);
+    do_check_eq(itemId, -1);
 
-    do_test_finished();
+    // Set preferences.
+    Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true);
+    Services.prefs.setBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS, true);
+
+    // Force nsBrowserGlue::_initPlaces()
+    print("Simulate Places init");
+    bg.QueryInterface(Ci.nsIObserver).observe(null,
+                                              TOPIC_BROWSERGLUE_TEST,
+                                              TOPICDATA_FORCE_PLACES_INIT);
+
+    // Check bookmarks.html has been restored.
+    itemId =
+      PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.toolbarFolderId,
+                                           SMART_BOOKMARKS_ON_TOOLBAR + 1);
+    do_check_true(itemId > 0);
+    // Check preferences have been reverted.
+    do_check_false(Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS));
+    do_check_false(Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
+
+    run_next_test();
   }
-});
 
-//------------------------------------------------------------------------------
+];
 
-function finish_test() {
-  // Clean up database from all bookmarks.
+do_register_cleanup(function () {
   remove_all_bookmarks();
   remove_bookmarks_html();
   remove_all_JSON_backups();
+});
 
-  do_test_finished();
-}
-var testIndex = 0;
-function next_test() {
-  // Clean up database from all bookmarks.
-  remove_all_bookmarks();
-  // nsBrowserGlue stops observing topics after first notification,
-  // so we add back the observer to test additional runs.
-  os.addObserver(bg.QueryInterface(Ci.nsIObserver),
-                 PlacesUtils.TOPIC_INIT_COMPLETE, false);
-  os.addObserver(bg.QueryInterface(Ci.nsIObserver),
-                 PlacesUtils.TOPIC_DATABASE_LOCKED, false);
-  // Execute next test.
-  let test = tests.shift();
-  print("\nTEST " + (++testIndex) + ": " + test.description);
-  test.exec();
-}
-function run_test() {
-  // Bug 539067: disabled due to random failures and timeouts.
-  return;
-
-  do_test_pending();
-  // Enqueue test, so it will consume the default places-init-complete
-  // notification created at Places init.
-  do_timeout(0, start_tests);
-}
-
-function start_tests() {
-  // Clean up database from all bookmarks.
-  remove_all_bookmarks();
-
-  // Ensure preferences status.
-  do_check_false(ps.getBoolPref(PREF_AUTO_EXPORT_HTML));
-  try {
-  do_check_false(ps.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML));
-    do_throw("importBookmarksHTML pref should not exist");
-  }
-  catch(ex) {}
-  do_check_false(ps.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS));
-
+function run_test()
+{
   // Create our bookmarks.html from bookmarks.glue.html.
   create_bookmarks_html("bookmarks.glue.html");
   // Create our JSON backup from bookmarks.glue.json.
   create_JSON_backup("bookmarks.glue.json");
-  // Kick-off tests.
-  next_test();
+
+  run_next_test();
 }
--- a/browser/components/places/tests/unit/test_placesTxn.js
+++ b/browser/components/places/tests/unit/test_placesTxn.js
@@ -95,21 +95,16 @@ var observer = {
   }
 };
 bmsvc.addObserver(observer, false);
 
 // index at which items should begin
 var bmStartIndex = 0;
 
 // main
-
-function time() {
-    return (new Date()).getTime();
-}
-
 function run_test() {
   // get bookmarks root index
   var root = bmsvc.bookmarksMenuFolder;
 
   //Test creating a folder with a description
   const TEST_DESCRIPTION = "this is my test description";
   var annos = [{ name: PlacesUIUtils.DESCRIPTION_ANNO,
                  type: annosvc.TYPE_STRING,
@@ -537,17 +532,17 @@ function run_test() {
   // Test generic page annotation
   var pageAnnoObj = { name: "testAnno/testInt",
                       type: Ci.nsIAnnotationService.TYPE_INT32,
                       flags: 0,
                       value: 123,
                       expires: Ci.nsIAnnotationService.EXPIRE_NEVER };
   var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
            getService(Ci.nsINavHistoryService);
-  hs.addVisit(uri("http://www.mozilla.org/"), time() * 1000, null,
+  hs.addVisit(uri("http://www.mozilla.org/"), Date.now() * 1000, null,
               hs.TRANSITION_TYPED, false, 0);
   var genPageAnnoTxn = ptSvc.setPageAnnotation(uri("http://www.mozilla.org/"), pageAnnoObj);
   genPageAnnoTxn.doTransaction();
   do_check_true(annosvc.pageHasAnnotation(uri("http://www.mozilla.org/"), "testAnno/testInt"));
   genPageAnnoTxn.undoTransaction();
   do_check_false(annosvc.pageHasAnnotation(uri("http://www.mozilla.org/"), "testAnno/testInt"));
   genPageAnnoTxn.redoTransaction();
   do_check_true(annosvc.pageHasAnnotation(uri("http://www.mozilla.org/"), "testAnno/testInt"));
@@ -612,26 +607,26 @@ function run_test() {
   postDataTxn.doTransaction();
   do_check_true(annosvc.itemHasAnnotation(postDataId, POST_DATA_ANNO))
   do_check_eq(annosvc.getItemAnnotation(postDataId, POST_DATA_ANNO), postData);
   postDataTxn.undoTransaction();
   do_check_false(annosvc.itemHasAnnotation(postDataId, POST_DATA_ANNO))
 
   // Test editing item date added
   var oldAdded = bmsvc.getItemDateAdded(bkmk1Id);
-  var newAdded = time();
+  var newAdded = Date.now();
   var eidaTxn = ptSvc.editItemDateAdded(bkmk1Id, newAdded);
   eidaTxn.doTransaction();
   do_check_eq(newAdded, bmsvc.getItemDateAdded(bkmk1Id));
   eidaTxn.undoTransaction();
   do_check_eq(oldAdded, bmsvc.getItemDateAdded(bkmk1Id));
 
   // Test editing item last modified 
   var oldModified = bmsvc.getItemLastModified(bkmk1Id);
-  var newModified = time();
+  var newModified = Date.now();
   var eilmTxn = ptSvc.editItemLastModified(bkmk1Id, newModified);
   eilmTxn.doTransaction();
   do_check_eq(newModified, bmsvc.getItemLastModified(bkmk1Id));
   eilmTxn.undoTransaction();
   do_check_eq(oldModified, bmsvc.getItemLastModified(bkmk1Id));
 
   // Test tagURI/untagURI
   var tagURI = uri("http://foo.tld");
@@ -729,17 +724,17 @@ function run_test() {
   do_check_eq(bmsvc.getItemType(newBkmk3_3Id), bmsvc.TYPE_FOLDER);
   do_check_eq(bmsvc.getItemTitle(newBkmk3_3Id), "folder");
   // Check last added back item id.
   // Notice items are restored in reverse order.
   do_check_eq(observer._itemAddedId, newBkmk1Id);
 
   // Test creating an item with child transactions.
   var childTxns = [];
-  var newDateAdded = time() - 20000;
+  var newDateAdded = Date.now() - 20000;
   childTxns.push(ptSvc.editItemDateAdded(null, newDateAdded));
   var itemChildAnnoObj = { name: "testAnno/testInt",
                            type: Ci.nsIAnnotationService.TYPE_INT32,
                            flags: 0,
                            value: 123,
                            expires: Ci.nsIAnnotationService.EXPIRE_NEVER };
   childTxns.push(ptSvc.setItemAnnotation(null, itemChildAnnoObj));
   var itemWChildTxn = ptSvc.createItem(uri("http://www.example.com"), root,
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_opendir.js
+++ b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_opendir.js
@@ -49,18 +49,17 @@ function test() {
   let file = dir2.clone();
   file.append("pbtest.file");
   file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0600);
 
   const kPrefName = "browser.open.lastDir";
 
   function setupCleanSlate() {
     gLastOpenDirectory.reset();
-    if (gPrefService.prefHasUserValue(kPrefName))
-        gPrefService.clearUserPref(kPrefName);
+    gPrefService.clearUserPref(kPrefName);
   }
 
   setupCleanSlate();
 
   // Test 1: general workflow test
 
   // initial checks
   ok(!gLastOpenDirectory.path,
--- a/browser/components/search/content/search.xml
+++ b/browser/components/search/content/search.xml
@@ -518,21 +518,18 @@
         this.focus();
         this.select();
       ]]></handler>
 
       <handler event="popupshowing" action="this.rebuildPopupDynamic();"/>
 
       <handler event="DOMMouseScroll"
                phase="capturing"
-#ifdef XP_MACOSX
-               action="if (event.metaKey) this.selectEngine(event, (event.detail > 0));"/>
-#else
-               action="if (event.ctrlKey) this.selectEngine(event, (event.detail > 0));"/>
-#endif
+               modifiers="accel"
+               action="this.selectEngine(event, (event.detail > 0));"/>
     </handlers>
   </binding>
 
   <binding id="searchbar-textbox"
       extends="chrome://global/content/bindings/autocomplete.xml#autocomplete">
     <implementation implements="nsIObserver">
       <constructor><![CDATA[
         if (document.getBindingParent(this).parentNode.parentNode.localName ==
--- a/browser/components/sessionstore/src/nsSessionStore.js
+++ b/browser/components/sessionstore/src/nsSessionStore.js
@@ -708,17 +708,17 @@ SessionStoreService.prototype = {
       return;
 
     // ignore non-browser windows and windows opened while shutting down
     if (aWindow.document.documentElement.getAttribute("windowtype") != "navigator:browser" ||
         this._loadState == STATE_QUITTING)
       return;
 
     // assign it a unique identifier (timestamp)
-    aWindow.__SSi = "window" + Math.floor(Date.now());
+    aWindow.__SSi = "window" + Date.now();
 
     // and create its data object
     this._windows[aWindow.__SSi] = { tabs: [], selected: 0, _closedTabs: [] };
     if (!this._isWindowLoaded(aWindow))
       this._windows[aWindow.__SSi]._restoring = true;
     if (!aWindow.toolbar.visible)
       this._windows[aWindow.__SSi].isPopup = true;
     
@@ -838,17 +838,17 @@ SessionStoreService.prototype = {
    * @param aWindow
    *        Window reference
    */
   onClose: function sss_onClose(aWindow) {
     // this window was about to be restored - conserve its original data, if any
     let isFullyLoaded = this._isWindowLoaded(aWindow);
     if (!isFullyLoaded) {
       if (!aWindow.__SSi)
-        aWindow.__SSi = "window" + Math.floor(Date.now());
+        aWindow.__SSi = "window" + Date.now();
       this._windows[aWindow.__SSi] = this._statesToRestore[aWindow.__SS_restoreID];
       delete this._statesToRestore[aWindow.__SS_restoreID];
       delete aWindow.__SS_restoreID;
     }
     
     // ignore windows not tracked by SessionStore
     if (!aWindow.__SSi || !this._windows[aWindow.__SSi]) {
       return;
@@ -2850,32 +2850,39 @@ SessionStoreService.prototype = {
 
     // Remove the history listener, since we no longer need it once we start restoring
     this._removeSHistoryListener(aTab);
 
     let activeIndex = (tabData.index || tabData.entries.length) - 1;
     if (activeIndex >= tabData.entries.length)
       activeIndex = tabData.entries.length - 1;
 
-    // Reset currentURI.
+    // Reset currentURI.  This creates a new session history entry with a new
+    // doc identifier, so we need to explicitly save and restore the old doc
+    // identifier (corresponding to the SHEntry at activeIndex) below.
     browser.webNavigation.setCurrentURI(this._getURIFromString("about:blank"));
 
     // Attach data that will be restored on "load" event, after tab is restored.
     if (activeIndex > -1) {
+      let curSHEntry = browser.webNavigation.sessionHistory.
+                       getEntryAtIndex(activeIndex, false).
+                       QueryInterface(Ci.nsISHEntry);
+
       // restore those aspects of the currently active documents which are not
       // preserved in the plain history entries (mainly scroll state and text data)
       browser.__SS_restore_data = tabData.entries[activeIndex] || {};
       browser.__SS_restore_pageStyle = tabData.pageStyle || "";
       browser.__SS_restore_tab = aTab;
+      browser.__SS_restore_docIdentifier = curSHEntry.docIdentifier;
 
       didStartLoad = true;
       try {
         // In order to work around certain issues in session history, we need to
         // force session history to update its internal index and call reload
-        // instead of gotoIndex. c.f. bug 597315
+        // instead of gotoIndex. See bug 597315.
         browser.webNavigation.sessionHistory.getEntryAtIndex(activeIndex, true);
         browser.webNavigation.sessionHistory.
           QueryInterface(Ci.nsISHistory_2_0_BRANCH).reloadCurrentEntry();
       }
       catch (ex) {
         // ignore page load errors
         aTab.removeAttribute("busy");
         didStartLoad = false;
@@ -2976,17 +2983,17 @@ SessionStoreService.prototype = {
       shEntry.cacheKey = cacheKey;
     }
 
     if (aEntry.ID) {
       // get a new unique ID for this frame (since the one from the last
       // start might already be in use)
       var id = aIdMap[aEntry.ID] || 0;
       if (!id) {
-        for (id = Math.floor(Date.now()); id in aIdMap.used; id++);
+        for (id = Date.now(); id in aIdMap.used; id++);
         aIdMap[aEntry.ID] = id;
         aIdMap.used[id] = true;
       }
       shEntry.ID = id;
     }
 
     if (aEntry.docshellID)
       shEntry.docshellID = aEntry.docshellID;
@@ -3158,22 +3165,29 @@ SessionStoreService.prototype = {
     // don't restore text data and scrolling state if the user has navigated
     // away before the loading completed (except for in-page navigation)
     if (hasExpectedURL(aEvent.originalTarget, aBrowser.__SS_restore_data.url)) {
       var content = aEvent.originalTarget.defaultView;
       restoreTextDataAndScrolling(content, aBrowser.__SS_restore_data, "");
       aBrowser.markupDocumentViewer.authorStyleDisabled = selectedPageStyle == "_nostyle";
     }
 
+    if (aBrowser.__SS_restore_docIdentifier) {
+      let sh = aBrowser.webNavigation.sessionHistory;
+      sh.getEntryAtIndex(sh.index, false).QueryInterface(Ci.nsISHEntry).
+         docIdentifier = aBrowser.__SS_restore_docIdentifier;
+    }
+
     // notify the tabbrowser that this document has been completely restored
     this._sendTabRestoredNotification(aBrowser.__SS_restore_tab);
 
     delete aBrowser.__SS_restore_data;
     delete aBrowser.__SS_restore_pageStyle;
     delete aBrowser.__SS_restore_tab;
+    delete aBrowser.__SS_restore_docIdentifier;
   },
 
   /**
    * Restore visibility and dimension features to a window
    * @param aWindow
    *        Window reference
    * @param aWinData
    *        Object containing session data for the window
@@ -3746,17 +3760,17 @@ SessionStoreService.prototype = {
         // - _closedTabs
         // - extData
         // - isPopup
         // - hidden
 
         // Assign a unique ID to correlate the window to be opened with the
         // remaining data
         window.__lastSessionWindowID = pinnedWindowState.__lastSessionWindowID
-                                     = "" + Math.floor(Date.now()) + Math.random();
+                                     = "" + Date.now() + Math.random();
 
         // Extract the cookies that belong with each pinned tab
         this._splitCookiesFromWindow(window, pinnedWindowState);
 
         // Actually add this window to our defaultState
         defaultState.windows.push(pinnedWindowState);
         // Remove the window from the state if it doesn't have any tabs
         if (!window.tabs.length) {
--- a/browser/components/sessionstore/test/browser/browser_248970_b.js
+++ b/browser/components/sessionstore/test/browser/browser_248970_b.js
@@ -46,17 +46,17 @@ function test() {
   }
 
   var file = Components.classes["@mozilla.org/file/directory_service;1"]
              .getService(Components.interfaces.nsIProperties)
              .get("TmpD", Components.interfaces.nsIFile);
   filePath = file.path;
 
   let fieldList = {
-    "//input[@name='input']":     Math.floor(Date.now()).toString(),
+    "//input[@name='input']":     Date.now().toString(),
     "//input[@name='spaced 1']":  Math.random().toString(),
     "//input[3]":                 "three",
     "//input[@type='checkbox']":  true,
     "//input[@name='uncheck']":   false,
     "//input[@type='radio'][1]":  false,
     "//input[@type='radio'][2]":  true,
     "//input[@type='radio'][3]":  false,
     "//select":                   2,
--- a/browser/components/sessionstore/test/browser/browser_345898.js
+++ b/browser/components/sessionstore/test/browser/browser_345898.js
@@ -73,13 +73,13 @@ function test() {
   ok(test(function() ss.getWindowValue({}, "")),
      "Invalid window for getWindowValue throws");
   ok(test(function() ss.getWindowValue({}, "")),
      "Invalid window for getWindowValue throws");
   ok(test(function() ss.getWindowValue({}, "", "")),
      "Invalid window for setWindowValue throws");
   ok(test(function() ss.deleteWindowValue({}, "")),
      "Invalid window for deleteWindowValue throws");
-  ok(test(function() ss.deleteWindowValue(window, Math.floor(Date.now()).toString())),
+  ok(test(function() ss.deleteWindowValue(window, Date.now().toString())),
      "Nonexistent value for deleteWindowValue throws");
-  ok(test(function() ss.deleteTabValue(gBrowser.selectedTab, Math.floor(Date.now()).toString())),
+  ok(test(function() ss.deleteTabValue(gBrowser.selectedTab, Date.now().toString())),
      "Nonexistent value for deleteTabValue throws");
 }
--- a/browser/components/sessionstore/test/browser/browser_346337.js
+++ b/browser/components/sessionstore/test/browser/browser_346337.js
@@ -46,17 +46,17 @@ function test() {
   file = Components.classes["@mozilla.org/file/directory_service;1"]
              .getService(Components.interfaces.nsIProperties)
              .get("TmpD", Components.interfaces.nsILocalFile);
   file.append("346337_test2.file");
   file.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0666);
   filePath2 = file.path;
   
   let fieldList = {
-    "//input[@name='input']":     Math.floor(Date.now()).toString(),
+    "//input[@name='input']":     Date.now().toString(),
     "//input[@name='spaced 1']":  Math.random().toString(),
     "//input[3]":                 "three",
     "//input[@type='checkbox']":  true,
     "//input[@name='uncheck']":   false,
     "//input[@type='radio'][1]":  false,
     "//input[@type='radio'][2]":  true,
     "//input[@type='radio'][3]":  false,
     "//select":                   2,
--- a/browser/components/sessionstore/test/browser/browser_350525.js
+++ b/browser/components/sessionstore/test/browser/browser_350525.js
@@ -19,17 +19,17 @@ function test() {
   
   // service
   let ss = test(function() ssComponent.getService(Ci.nsISessionStore));
   ok(ss, "reference the sessionstore service");
   
   ////////////////////////////
   // setWindowValue, et al. //
   ////////////////////////////
-  let key = "Unique name: " + Math.floor(Date.now());
+  let key = "Unique name: " + Date.now();
   let value = "Unique value: " + Math.random();
   
   // test adding
   ok(test(function() ss.setWindowValue(window, key, value)), "set a window value");
   
   // test retrieving
   is(ss.getWindowValue(window, key), value, "stored window value matches original");
   
@@ -38,17 +38,17 @@ function test() {
   
   // value should not exist post-delete
   is(ss.getWindowValue(window, key), "", "window value was deleted");
   
   /////////////////////////
   // setTabValue, et al. //
   /////////////////////////
   key = "Unique name: " + Math.random();
-  value = "Unique value: " + Math.floor(Date.now());
+  value = "Unique value: " + Date.now();
   let tab = tabbrowser.addTab();
   tab.linkedBrowser.stop();
   
   // test adding
   ok(test(function() ss.setTabValue(tab, key, value)), "store a tab value");
   
   // test retrieving
   is(ss.getTabValue(tab, key), value, "stored tab value match original");
--- a/browser/components/sessionstore/test/browser/browser_393716.js
+++ b/browser/components/sessionstore/test/browser/browser_393716.js
@@ -8,17 +8,17 @@ function test() {
   catch (ex) { }
   ok(ss, "SessionStore service is available");
   let tabbrowser = gBrowser;
   waitForExplicitFinish();
   
   /////////////////
   // getTabState //
   /////////////////
-  let key = "Unique key: " + Math.floor(Date.now());
+  let key = "Unique key: " + Date.now();
   let value = "Unique value: " + Math.random();
   let testURL = "about:config";
   
   // create a new tab
   let tab = tabbrowser.addTab(testURL);
   ss.setTabValue(tab, key, value);
   tab.linkedBrowser.addEventListener("load", function(aEvent) {
     this.removeEventListener("load", arguments.callee, true);
@@ -39,17 +39,17 @@ function test() {
     tabbrowser.removeTab(tab);
   }, true);
   
   //////////////////////////////////
   // setTabState and duplicateTab //
   //////////////////////////////////
   let key2 = "key2";
   let value2 = "Value " + Math.random();
-  let value3 = "Another value: " + Math.floor(Date.now());
+  let value3 = "Another value: " + Date.now();
   let state = { entries: [{ url: testURL }], extData: { key2: value2 } };
   
   // create a new tab
   let tab2 = tabbrowser.addTab();
   // set the tab's state
   ss.setTabState(tab2, JSON.stringify(state));
   tab2.linkedBrowser.addEventListener("load", function(aEvent) {
     this.removeEventListener("load", arguments.callee, true);
--- a/browser/components/sessionstore/test/browser/browser_394759.js
+++ b/browser/components/sessionstore/test/browser/browser_394759.js
@@ -55,17 +55,17 @@ function test() {
   let ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
   let pb = Cc["@mozilla.org/privatebrowsing;1"].getService(Ci.nsIPrivateBrowsingService);
   waitForExplicitFinish();
   
   function test_basic(callback) {
   
     let testURL = "about:config";
     let uniqueKey = "bug 394759";
-    let uniqueValue = "unik" + Math.floor(Date.now());
+    let uniqueValue = "unik" + Date.now();
     let uniqueText = "pi != " + Math.random();
   
   
     // make sure that the next closed window will increase getClosedWindowCount
     let max_windows_undo = gPrefService.getIntPref("browser.sessionstore.max_windows_undo");
     gPrefService.setIntPref("browser.sessionstore.max_windows_undo", max_windows_undo + 1);
     let closedWindowCount = ss.getClosedWindowCount();
   
--- a/browser/components/sessionstore/test/browser/browser_394759_privatebrowsing.js
+++ b/browser/components/sessionstore/test/browser/browser_394759_privatebrowsing.js
@@ -100,17 +100,17 @@ function continue_test() {
   ok(!pb.privateBrowsingEnabled, "Private Browsing is disabled");
   let ss = Cc["@mozilla.org/browser/sessionstore;1"].
            getService(Ci.nsISessionStore);
 
   let closedWindowCount = ss.getClosedWindowCount();
   is(closedWindowCount, 0, "Correctly set window count");
 
   // Prevent VM timers issues, cache now and increment it manually.
-  let now = Math.floor(Date.now());
+  let now = Date.now();
   const TESTS = [
     { url: "about:config",
       key: "bug 394759 Non-PB",
       value: "uniq" + (++now) },
     { url: "about:mozilla",
       key: "bug 394759 PB",
       value: "uniq" + (++now) },
   ];
--- a/browser/components/sessionstore/test/browser/browser_448741.js
+++ b/browser/components/sessionstore/test/browser/browser_448741.js
@@ -37,17 +37,17 @@
 function test() {
   /** Test for Bug 448741 **/
 
   // test setup
   let ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
   waitForExplicitFinish();
 
   let uniqueName = "bug 448741";
-  let uniqueValue = "as good as unique: " + Math.floor(Date.now());
+  let uniqueValue = "as good as unique: " + Date.now();
 
   // set a unique value on a new, blank tab
   var tab = gBrowser.addTab();
   tab.linkedBrowser.stop();
   ss.setTabValue(tab, uniqueName, uniqueValue);
   let valueWasCleaned = false;
 
   // prevent our value from being written to disk
--- a/browser/components/sessionstore/test/browser/browser_459906.js
+++ b/browser/components/sessionstore/test/browser/browser_459906.js
@@ -36,17 +36,17 @@
 
 function test() {
   /** Test for Bug 459906 **/
 
   waitForExplicitFinish();
 
   let testURL = "http://mochi.test:8888/browser/" +
     "browser/components/sessionstore/test/browser/browser_459906_sample.html";
-  let uniqueValue = "<b>Unique:</b> " + Math.floor(Date.now());
+  let uniqueValue = "<b>Unique:</b> " + Date.now();
 
   var frameCount = 0;
   let tab = gBrowser.addTab(testURL);
   tab.linkedBrowser.addEventListener("load", function(aEvent) {
     // wait for all frames to load completely
     if (frameCount++ < 2)
       return;
     tab.linkedBrowser.removeEventListener("load", arguments.callee, true);
--- a/browser/components/sessionstore/test/browser/browser_465215.js
+++ b/browser/components/sessionstore/test/browser/browser_465215.js
@@ -36,17 +36,17 @@
 
 function test() {
   /** Test for Bug 465215 **/
   
   let ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
   waitForExplicitFinish();
   
   let uniqueName = "bug 465215";
-  let uniqueValue1 = "as good as unique: " + Math.floor(Date.now());
+  let uniqueValue1 = "as good as unique: " + Date.now();
   let uniqueValue2 = "as good as unique: " + Math.random();
   
   // set a unique value on a new, blank tab
   let tab1 = gBrowser.addTab();
   tab1.linkedBrowser.addEventListener("load", function() {
     tab1.linkedBrowser.removeEventListener("load", arguments.callee, true);
     ss.setTabValue(tab1, uniqueName, uniqueValue1);
     
--- a/browser/components/sessionstore/test/browser/browser_465223.js
+++ b/browser/components/sessionstore/test/browser/browser_465223.js
@@ -49,17 +49,17 @@ function test() {
   is(browserWindowsCount(), 1, "Only one browser window should be open initially");
   
   // test setup
   let ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
   waitForExplicitFinish();
   
   let uniqueKey1 = "bug 465223.1";
   let uniqueKey2 = "bug 465223.2";
-  let uniqueValue1 = "unik" + Math.floor(Date.now());
+  let uniqueValue1 = "unik" + Date.now();
   let uniqueValue2 = "pi != " + Math.random();
   
   // open a window and set a value on it
   let newWin = openDialog(location, "_blank", "chrome,all,dialog=no");
   newWin.addEventListener("load", function(aEvent) {
     ss.setWindowValue(newWin, uniqueKey1, uniqueValue1);
     
     let newState = { windows: [{ tabs:[{ entries: [] }], extData: {} }] };
--- a/browser/components/sessionstore/test/browser/browser_476161.js
+++ b/browser/components/sessionstore/test/browser/browser_476161.js
@@ -42,17 +42,17 @@ function test() {
   let testURL = "http://mochi.test:8888/browser/" +
     "browser/components/sessionstore/test/browser/browser_476161_sample.html";
   let tab = gBrowser.addTab(testURL);
   tab.linkedBrowser.addEventListener("load", function(aEvent) {
     tab.linkedBrowser.removeEventListener("load", arguments.callee, true);
     let doc = tab.linkedBrowser.contentDocument;
     
     doc.getElementById("modify1").value += Math.random();
-    doc.getElementById("modify2").value += " " + Math.floor(Date.now());
+    doc.getElementById("modify2").value += " " + Date.now();
     
     let tab2 = gBrowser.duplicateTab(tab);
     tab2.linkedBrowser.addEventListener("load", function(aEvent) {
       tab2.linkedBrowser.removeEventListener("load", arguments.callee, true);
       let doc = tab2.linkedBrowser.contentDocument;
       let changed = doc.getElementById("changed").textContent.trim().split();
       
       is(changed.sort().join(" "), "modify1 modify2",
--- a/browser/components/sessionstore/test/browser/browser_477657.js
+++ b/browser/components/sessionstore/test/browser/browser_477657.js
@@ -62,17 +62,17 @@ function test() {
       _closedTabs: [{
         state: { entries: [{ url: "about:" }]},
         title: "About:"
       }],
       sizemode: "maximized"
     }] };
     
     let uniqueKey = "bug 477657";
-    let uniqueValue = "unik" + Math.floor(Date.now());
+    let uniqueValue = "unik" + Date.now();
   
     ss.setWindowValue(newWin, uniqueKey, uniqueValue);
     is(ss.getWindowValue(newWin, uniqueKey), uniqueValue,
        "window value was set before the window was overwritten");
     ss.setWindowState(newWin, JSON.stringify(newState), true);
     
     // use setTimeout(..., 0) to mirror sss_restoreWindowFeatures
     setTimeout(function() {
--- a/browser/components/sessionstore/test/browser/browser_480893.js
+++ b/browser/components/sessionstore/test/browser/browser_480893.js
@@ -72,19 +72,16 @@ function test() {
         browser.addEventListener("load", function(aEvent) {
           browser.removeEventListener("load", arguments.callee, true);
           let doc = browser.contentDocument;
 
           is(doc.URL, homepage, "loaded page is the homepage");
 
           // close tab, restore default values and finish the test
           gBrowser.removeTab(tab);
-          // we need this if-statement because if there is no user set value, 
-          // clearUserPref throws a uncatched exception and finish is not called
-          if (gPrefService.prefHasUserValue("browser.startup.page"))
-            gPrefService.clearUserPref("browser.startup.page");
+          gPrefService.clearUserPref("browser.startup.page");
           gPrefService.clearUserPref("browser.startup.homepage");
           finish();
         }, true);
       }, true);
     }, true);
   }, true);
 }
--- a/browser/components/sessionstore/test/browser/browser_500328.js
+++ b/browser/components/sessionstore/test/browser/browser_500328.js
@@ -39,21 +39,25 @@ function checkState(tab) {
   // from the popState event are as we expect them to be.
   //
   // We also add a node to the document's body when after going back and make
   // sure it's still there after we go forward -- this is to test that the two
   // history entries correspond to the same document.
 
   let popStateCount = 0;
 
-  let handler = function(aEvent) {
+  tab.linkedBrowser.addEventListener('popstate', function(aEvent) {
     let contentWindow = tab.linkedBrowser.contentWindow;
     if (popStateCount == 0) {
       popStateCount++;
-      //ok(aEvent.state, "Event should have a state property.");
+
+      is(tab.linkedBrowser.contentWindow.testState, 'foo',
+         'testState after going back');
+
+      ok(aEvent.state, "Event should have a state property.");
       is(JSON.stringify(tab.linkedBrowser.contentWindow.history.state), JSON.stringify({obj1:1}),
          "first popstate object.");
 
       // Add a node with id "new-elem" to the document.
       let doc = contentWindow.document;
       ok(!doc.getElementById("new-elem"),
          "doc shouldn't contain new-elem before we add it.");
       let elem = doc.createElement("div");
@@ -73,25 +77,26 @@ function checkState(tab) {
       let doc = contentWindow.document;
       let newElem = doc.getElementById("new-elem");
       ok(newElem, "doc should contain new-elem.");
       newElem.parentNode.removeChild(newElem);
       ok(!doc.getElementById("new-elem"), "new-elem should be removed.");
 
       // Clean up after ourselves and finish the test.
       tab.linkedBrowser.removeEventListener("popstate", arguments.callee, true);
-      tab.linkedBrowser.removeEventListener("load", arguments.callee, true);
       gBrowser.removeTab(tab);
       finish();
     }
-  };
+  }, true);
 
-  tab.linkedBrowser.addEventListener("load", handler, true);
-  tab.linkedBrowser.addEventListener("popstate", handler, true);
+  // Set some state in the page's window.  When we go back(), the page should
+  // be retrieved from bfcache, and this state should still be there.
+  tab.linkedBrowser.contentWindow.testState = 'foo';
 
+  // Now go back.  This should trigger the popstate event handler above.
   tab.linkedBrowser.contentWindow.history.back();
 }
 
 function test() {
   // Tests session restore functionality of history.pushState and
   // history.replaceState().  (Bug 500328)
 
   let ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
@@ -114,26 +119,30 @@ function test() {
       // After these push/replaceState calls, the window should have three
       // history entries:
       //   testURL (state object: null)      <-- oldest
       //   testURL (state object: {obj1:1})
       //   page2   (state object: {obj3:3})  <-- newest
       let contentWindow = tab.linkedBrowser.contentWindow;
       let history = contentWindow.history;
       history.pushState({obj1:1}, "title-obj1");
-      history.pushState({obj2:2}, "title-obj2", "?foo");
+      history.pushState({obj2:2}, "title-obj2", "page2");
       history.replaceState({obj3:3}, "title-obj3");
 
       let state = ss.getTabState(tab);
+      gBrowser.removeTab(tab);
 
-      // In order to make sure that setWindowState actually modifies the
-      // window's state, we modify the state here.  checkState will fail if
-      // this change isn't overwritten by setWindowState.
-      history.replaceState({should_be_overwritten:true}, "title-overwritten");
+      // Restore the state into a new tab.  Things don't work well when we
+      // restore into the old tab, but that's not a real use case anyway.
+      let tab2 = gBrowser.addTab("about:blank");
+      ss.setTabState(tab2, state, true);
 
-      // Restore the state and make sure it looks right, after giving the event
-      // loop a chance to flush.
-      ss.setTabState(tab, state, true);
-      executeSoon(function() { checkState(tab); });
+      // Run checkState() once the tab finishes loading its restored state.
+      tab2.linkedBrowser.addEventListener("load", function() {
+        tab2.linkedBrowser.removeEventListener("load", arguments.callee, true);
+        SimpleTest.executeSoon(function() {
+          checkState(tab2);
+        });
+      }, true);
 
     }, true);
   }, true);
 }
--- a/browser/components/sessionstore/test/browser/browser_524745.js
+++ b/browser/components/sessionstore/test/browser/browser_524745.js
@@ -47,17 +47,17 @@ function browserWindowsCount() {
 
 function test() {
   /** Test for Bug 524745 **/
   is(browserWindowsCount(), 1, "Only one browser window should be open initially");
 
   let ss = Cc["@mozilla.org/browser/sessionstore;1"].
            getService(Ci.nsISessionStore);
   let uniqKey = "bug524745";
-  let uniqVal = Math.floor(Date.now());
+  let uniqVal = Date.now();
 
   waitForExplicitFinish();
 
   let window_B = openDialog(location, "_blank", "chrome,all,dialog=no");
   window_B.addEventListener("load", function(aEvent) {
     window_B.removeEventListener("load", arguments.callee, false);
 
       waitForFocus(function() {
--- a/browser/components/sessionstore/test/browser/browser_586068-cascaded_restore.js
+++ b/browser/components/sessionstore/test/browser/browser_586068-cascaded_restore.js
@@ -755,11 +755,8 @@ function countTabs() {
         needsRestore++;
       else
         wasRestored++;
     }
   }
   return [needsRestore, isRestoring, wasRestored];
 }
 
-function r() {
-  return "" + Math.floor(Date.now()) + Math.random();
-}
--- a/browser/components/sessionstore/test/browser/browser_590268.js
+++ b/browser/components/sessionstore/test/browser/browser_590268.js
@@ -1,10 +1,9 @@
 /* ***** 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,
@@ -166,13 +165,8 @@ function test() {
 
   // Add the event listeners
   gBrowser.tabContainer.addEventListener("SSTabRestoring", onSSTabRestoring, false);
   gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, true);
   gBrowser.tabContainer.addEventListener("TabOpen", onTabOpen, false);
   // Restore state
   ss.setBrowserState(JSON.stringify(state));
 }
-
-// Helper function to create a random value
-function r() {
-  return "" + Math.floor(Date.now()) + Math.random();
-}
--- a/browser/components/sessionstore/test/browser/browser_600545.js
+++ b/browser/components/sessionstore/test/browser/browser_600545.js
@@ -45,64 +45,16 @@ function test() {
   waitForExplicitFinish();
   testBug600545();
 }
 
 function testBug600545() {
   // Set the pref to false to cause non-app tabs to be stripped out on a save
   Services.prefs.setBoolPref("browser.sessionstore.resume_from_crash", false);
 
-  // Need to wait for SessionStore's saveState function to be called
-  // so that non-pinned tabs will be stripped from non-active window
-  function waitForSaveState(aSaveStateCallback) {
-    let topic = "sessionstore-state-write";
-    Services.obs.addObserver(function() {
-      Services.obs.removeObserver(arguments.callee, topic, false);
-      executeSoon(aSaveStateCallback);
-    }, topic, false);
-  };
-
-  // Need to wait for all tabs to be restored before reading browser state
-  function waitForBrowserState(aState, aSetStateCallback) {
-    let tabsRestored = 0;
-    let expectedTabs = getStateTabCount(aState);
-
-    // We know that there are only 2 windows total, so just be specific
-    let newWin;
-
-    // Used to determine when tabs have been restored
-    function onTabRestored(aEvent) {
-      if (++tabsRestored == expectedTabs) {
-        gBrowser.tabContainer.removeEventListener("SSTabRestored", onTabRestored, true);
-        newWin.gBrowser.tabContainer.removeEventListener("SSTabRestored", onTabRestored, true);
-        executeSoon(aSetStateCallback);
-      }
-    }
-
-    // We also want to catch the 2nd window, so we need to observe domwindowopened
-    function windowObserver(aSubject, aTopic, aData) {
-      let theWin = aSubject.QueryInterface(Ci.nsIDOMWindow);
-      if (aTopic == "domwindowopened") {
-        theWin.addEventListener("load", function() {
-          theWin.removeEventListener("load", arguments.callee, false);
-
-          // So we can remove the event listener in onTabRestored
-          newWin = theWin;
-
-          Services.ww.unregisterNotification(windowObserver);
-          theWin.gBrowser.tabContainer.addEventListener("SSTabRestored", onTabRestored, true);
-        }, false);
-      }
-    }
-
-    Services.ww.registerNotification(windowObserver);
-    gBrowser.tabContainer.addEventListener("SSTabRestored", onTabRestored, true);
-    ss.setBrowserState(JSON.stringify(aState));
-  }
-
   // This tests the following use case:
   // When multiple windows are open and browser.sessionstore.resume_from_crash
   // preference is false, tab session data for non-active window is stripped for
   // non-pinned tabs.  This occurs after "sessionstore-state-write" fires which
   // will only fire in this case if there is at least one pinned tab.
   let state = { windows: [
     {
       tabs: [
@@ -119,16 +71,18 @@ function testBug600545() {
         { entries: [{ url: "http://example.com#5" }] },
         { entries: [{ url: "http://example.com#6" }] }
       ],
       selected: 3
     }
   ] };
 
   waitForBrowserState(state, function() {
+    // Need to wait for SessionStore's saveState function to be called
+    // so that non-pinned tabs will be stripped from non-active window
     waitForSaveState(function () {
       let expectedNumberOfTabs = getStateTabCount(state);
       let retrievedState = JSON.parse(ss.getBrowserState());
       let actualNumberOfTabs = getStateTabCount(retrievedState);
 
       is(actualNumberOfTabs, expectedNumberOfTabs,
         "Number of tabs in retreived session data, matches number of tabs set.");
 
--- a/browser/components/sessionstore/test/browser/browser_607016.js
+++ b/browser/components/sessionstore/test/browser/browser_607016.js
@@ -143,12 +143,8 @@ function test() {
 
     cleanup();
   }
 
   window.gBrowser.addTabsProgressListener(progressListener);
   ss.setBrowserState(JSON.stringify(state));
 }
 
-// Helper function to create a random value
-function r() {
-  return "" + Math.floor(Date.now()) + Math.random();
-}
--- a/browser/components/sessionstore/test/browser/browser_618151.js
+++ b/browser/components/sessionstore/test/browser/browser_618151.js
@@ -75,29 +75,16 @@ function runNextTest() {
     waitForBrowserState(testState, currentTest);
   }
   else {
     ss.setBrowserState(stateBackup);
     executeSoon(finish);
   }
 }
 
-// helper, works only for single window
-function waitForBrowserState(aState, aSetStateCallback) {
-  let tabsRestored = 0;
-  gBrowser.tabContainer.addEventListener("SSTabRestored", function() {
-    if (++tabsRestored == aState.windows[0].tabs.length) {
-      gBrowser.tabContainer.removeEventListener("SSTabRestored", arguments.callee, true);
-      executeSoon(aSetStateCallback);
-    }
-  }, true);
-  ss.setBrowserState(JSON.stringify(aState));
-}
-
-
 function test_setup() {
   function onSSTabRestored(aEvent) {
     gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, false);
     runNextTest();
   }
 
   gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, false);
   ss.setTabState(gBrowser.tabs[1], JSON.stringify({
--- a/browser/components/sessionstore/test/browser/head.js
+++ b/browser/components/sessionstore/test/browser/head.js
@@ -94,11 +94,12 @@ function waitForBrowserState(aState, aSe
 function waitForSaveState(aSaveStateCallback) {
   let topic = "sessionstore-state-write";
   Services.obs.addObserver(function() {
     Services.obs.removeObserver(arguments.callee, topic, false);
     executeSoon(aSaveStateCallback);
   }, topic, false);
 };
 
+var gUniqueCounter = 0;
 function r() {
-  return Math.floor(Date.now()) + Math.random();
+  return Date.now() + "-" + (++gUniqueCounter);
 }
--- a/browser/components/shell/content/setDesktopBackground.xul
+++ b/browser/components/shell/content/setDesktopBackground.xul
@@ -72,19 +72,17 @@
     <hbox align="center">
       <label value="&position.label;"/>
       <menulist id="menuPosition"
                 label="&position.label;" 
                 oncommand="gSetBackground.updatePosition();">
         <menupopup>
           <menuitem label="&center.label;"  value="CENTER"/>
           <menuitem label="&tile.label;"    value="TILE"/>
-#ifndef WINCE
           <menuitem label="&stretch.label;" value="STRETCH"/>
-#endif
         </menupopup>
       </menulist>
       <spacer flex="1"/>
       <label value="&color.label;"/>
       <colorpicker id="desktopColor"
                    type="button" 
                    onchange="gSetBackground.updateColor(this.color);"/> 
     </hbox>
--- a/browser/components/shell/public/Makefile.in
+++ b/browser/components/shell/public/Makefile.in
@@ -42,17 +42,17 @@ VPATH   = @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE = shellservice
 XPIDL_MODULE  = shellservice
 
 XPIDLSRCS = nsIShellService.idl
 
-ifneq (,$(filter WINCE WINNT,$(OS_ARCH)))
+ifeq ($(OS_ARCH),WINNT)
 XPIDLSRCS += nsIWindowsShellService.idl
 endif
 
 ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT))
 XPIDLSRCS += nsIMacShellService.idl
 endif
 
 include $(topsrcdir)/config/rules.mk
--- a/browser/components/shell/src/Makefile.in
+++ b/browser/components/shell/src/Makefile.in
@@ -45,17 +45,17 @@ include $(DEPTH)/config/autoconf.mk
 MODULE = shellservice
 FORCE_STATIC_LIB = 1
 FORCE_USE_PIC = 1
 ifndef MOZ_MEMORY
 USE_STATIC_LIBS = 1
 endif
 
 
-ifneq (,$(filter WINCE WINNT,$(OS_ARCH)))
+ifeq ($(OS_ARCH),WINNT)
 CPPSRCS = nsWindowsShellService.cpp
 else
 ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT))
 CPPSRCS = nsMacShellService.cpp
 else
 ifeq ($(MOZ_WIDGET_TOOLKIT), gtk2)
 CPPSRCS = nsGNOMEShellService.cpp
 endif
--- a/browser/components/shell/src/nsGNOMEShellService.cpp
+++ b/browser/components/shell/src/nsGNOMEShellService.cpp
@@ -101,30 +101,33 @@ static const char kDesktopOptionsKey[] =
 static const char kDesktopDrawBGKey[] = DG_BACKGROUND "/draw_background";
 static const char kDesktopColorKey[] = DG_BACKGROUND "/primary_color";
 
 nsresult
 nsGNOMEShellService::Init()
 {
   nsresult rv;
 
-  // GConf _must_ be available, or we do not allow
+  // GConf 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);
 
-  if (!gconf)
+  if (!gconf && !giovfs)
     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;
+
   nsCOMPtr<nsIProperties> dirSvc
     (do_GetService("@mozilla.org/file/directory_service;1"));
   NS_ENSURE_TRUE(dirSvc, NS_ERROR_NOT_AVAILABLE);
 
   nsCOMPtr<nsILocalFile> appPath;
   rv = dirSvc->Get(NS_XPCOM_CURRENT_PROCESS_DIR, NS_GET_IID(nsILocalFile),
                    getter_AddRefs(appPath));
   NS_ENSURE_SUCCESS(rv, rv);
@@ -133,16 +136,44 @@ nsGNOMEShellService::Init()
   NS_ENSURE_SUCCESS(rv, rv);
 
   return appPath->GetNativePath(mAppPath);
 }
 
 NS_IMPL_ISUPPORTS1(nsGNOMEShellService, nsIShellService)
 
 PRBool
+nsGNOMEShellService::GetAppPathFromLauncher()
+{
+  gchar *tmp;
+
+  const char *launcher = PR_GetEnv("MOZ_APP_LAUNCHER");
+  if (!launcher)
+    return PR_FALSE;
+
+  if (g_path_is_absolute(launcher)) {
+    mAppPath = launcher;
+    tmp = g_path_get_basename(launcher);
+    gchar *fullpath = g_find_program_in_path(tmp);
+    if (fullpath && mAppPath.Equals(fullpath))
+      mAppIsInPath = PR_TRUE;
+    g_free(fullpath);
+  } else {
+    tmp = g_find_program_in_path(launcher);
+    if (!tmp)
+      return PR_FALSE;
+    mAppPath = tmp;
+    mAppIsInPath = PR_TRUE;
+  }
+
+  g_free(tmp);
+  return PR_TRUE;
+}
+
+PRBool
 nsGNOMEShellService::KeyMatchesAppName(const char *aKeyValue) const
 {
 
   gchar *commandPath;
   if (mUseLocaleFilenames) {
     gchar *nativePath = g_filename_from_utf8(aKeyValue, -1, NULL, NULL, NULL);
     if (!nativePath) {
       NS_ERROR("Error converting path to filesystem encoding");
@@ -158,50 +189,77 @@ nsGNOMEShellService::KeyMatchesAppName(c
   if (!commandPath)
     return PR_FALSE;
 
   PRBool matches = mAppPath.Equals(commandPath);
   g_free(commandPath);
   return matches;
 }
 
+PRBool
+nsGNOMEShellService::CheckHandlerMatchesAppName(const nsACString &handler) const
+{
+  gint argc;
+  gchar **argv;
+  nsCAutoString command(handler);
+
+  // The string will be something of the form: [/path/to/]browser "%s"
+  // We want to remove all of the parameters and get just the binary name.
+
+  if (g_shell_parse_argv(command.get(), &argc, &argv, NULL) && argc > 0) {
+    command.Assign(argv[0]);
+    g_strfreev(argv);
+  }
+
+  if (!KeyMatchesAppName(command.get()))
+    return PR_FALSE; // the handler is set to another app
+
+  return PR_TRUE;
+}
+
 NS_IMETHODIMP
 nsGNOMEShellService::IsDefaultBrowser(PRBool aStartupCheck,
                                       PRBool* aIsDefaultBrowser)
 {
   *aIsDefaultBrowser = PR_FALSE;
   if (aStartupCheck)
     mCheckedThisSession = PR_TRUE;
 
   nsCOMPtr<nsIGConfService> gconf = do_GetService(NS_GCONFSERVICE_CONTRACTID);
+  nsCOMPtr<nsIGIOService> giovfs = do_GetService(NS_GIOSERVICE_CONTRACTID);
 
   PRBool enabled;
   nsCAutoString handler;
+  nsCOMPtr<nsIGIOMimeApp> gioApp;
 
   for (unsigned int i = 0; i < NS_ARRAY_LENGTH(appProtocols); ++i) {
     if (!appProtocols[i].essential)
       continue;
 
-    handler.Truncate();
-    gconf->GetAppForProtocol(nsDependentCString(appProtocols[i].name),
-                             &enabled, handler);
-
-    // The string will be something of the form: [/path/to/]browser "%s"
-    // We want to remove all of the parameters and get just the binary name.
+    if (gconf) {
+      handler.Truncate();
+      gconf->GetAppForProtocol(nsDependentCString(appProtocols[i].name),
+                               &enabled, handler);
 
-    gint argc;
-    gchar **argv;
-
-    if (g_shell_parse_argv(handler.get(), &argc, &argv, NULL) && argc > 0) {
-      handler.Assign(argv[0]);
-      g_strfreev(argv);
+      if (!CheckHandlerMatchesAppName(handler) || !enabled)
+        return NS_OK; // the handler is disabled or set to another app
     }
 
-    if (!KeyMatchesAppName(handler.get()) || !enabled)
-      return NS_OK; // the handler is disabled or set to another app
+    if (giovfs) {
+      handler.Truncate();
+      giovfs->GetAppForURIScheme(nsDependentCString(appProtocols[i].name),
+                                 getter_AddRefs(gioApp));
+      if (!gioApp)
+        return NS_OK;
+
+      gioApp->GetCommand(handler);
+
+      if (!CheckHandlerMatchesAppName(handler))
+        return NS_OK; // the handler is set to another app
+    }
   }
 
   *aIsDefaultBrowser = PR_TRUE;
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -209,34 +267,40 @@ nsGNOMEShellService::SetDefaultBrowser(P
                                        PRBool aForAllUsers)
 {
 #ifdef DEBUG
   if (aForAllUsers)
     NS_WARNING("Setting the default browser for all users is not yet supported");
 #endif
 
   nsCOMPtr<nsIGConfService> gconf = do_GetService(NS_GCONFSERVICE_CONTRACTID);
+  nsCOMPtr<nsIGIOService> giovfs = do_GetService(NS_GIOSERVICE_CONTRACTID);
   if (gconf) {
-    nsCAutoString appKeyValue(mAppPath);
-    appKeyValue.Append(" \"%s\"");
+    nsCAutoString appKeyValue;
+    if (mAppIsInPath) {
+      // mAppPath is in the users path, so use only the basename as the launcher
+      gchar *tmp = g_path_get_basename(mAppPath.get());
+      appKeyValue = tmp;
+      g_free(tmp);
+    } else {
+      appKeyValue = mAppPath;
+    }
+
+    appKeyValue.AppendLiteral(" %s");
+
     for (unsigned int i = 0; i < NS_ARRAY_LENGTH(appProtocols); ++i) {
       if (appProtocols[i].essential || aClaimAllTypes) {
         gconf->SetAppForProtocol(nsDependentCString(appProtocols[i].name),
                                  appKeyValue);
       }
     }
   }
 
-  // set handler for .html and xhtml files and MIME types:
-  if (aClaimAllTypes) {
+  if (giovfs) {
     nsresult rv;
-    nsCOMPtr<nsIGIOService> giovfs =
-      do_GetService(NS_GIOSERVICE_CONTRACTID, &rv);
-    NS_ENSURE_SUCCESS(rv, NS_OK);
-
     nsCOMPtr<nsIStringBundleService> bundleService =
       do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsCOMPtr<nsIStringBundle> brandBundle;
     rv = bundleService->CreateBundle(BRAND_PROPERTIES, getter_AddRefs(brandBundle));
     NS_ENSURE_SUCCESS(rv, rv);
 
@@ -249,20 +313,30 @@ nsGNOMEShellService::SetDefaultBrowser(P
     // use brandShortName as the application id.
     NS_ConvertUTF16toUTF8 id(brandShortName);
     nsCOMPtr<nsIGIOMimeApp> appInfo;
     rv = giovfs->CreateAppFromCommand(mAppPath,
                                       id,
                                       getter_AddRefs(appInfo));
     NS_ENSURE_SUCCESS(rv, rv);
 
-    // Add mime types for html, xhtml extension and set app to just created appinfo.
-    for (unsigned int i = 0; i < NS_ARRAY_LENGTH(appTypes); ++i) {
-      appInfo->SetAsDefaultForMimeType(nsDependentCString(appTypes[i].mimeType));
-      appInfo->SetAsDefaultForFileExtensions(nsDependentCString(appTypes[i].extensions));
+    // set handler for the protocols
+    for (unsigned int i = 0; i < NS_ARRAY_LENGTH(appProtocols); ++i) {
+      if (appProtocols[i].essential || aClaimAllTypes) {
+        appInfo->SetAsDefaultForURIScheme(nsDependentCString(appProtocols[i].name));
+      }
+    }
+
+    // set handler for .html and xhtml files and MIME types:
+    if (aClaimAllTypes) {
+      // Add mime types for html, xhtml extension and set app to just created appinfo.
+      for (unsigned int i = 0; i < NS_ARRAY_LENGTH(appTypes); ++i) {
+        appInfo->SetAsDefaultForMimeType(nsDependentCString(appTypes[i].mimeType));
+        appInfo->SetAsDefaultForFileExtensions(nsDependentCString(appTypes[i].extensions));
+      }
     }
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsGNOMEShellService::GetShouldCheckDefaultBrowser(PRBool* aResult)
@@ -362,48 +436,52 @@ nsGNOMEShellService::SetDesktopBackgroun
   filePath.Append("_wallpaper.png");
 
   // write the image to a file in the home dir
   rv = WriteImage(filePath, container);
 
   // if the file was written successfully, set it as the system wallpaper
   nsCOMPtr<nsIGConfService> gconf = do_GetService(NS_GCONFSERVICE_CONTRACTID);
 
-  nsCAutoString options;
-  if (aPosition == BACKGROUND_TILE)
-    options.Assign("wallpaper");
-  else if (aPosition == BACKGROUND_STRETCH)
-    options.Assign("stretched");
-  else
-    options.Assign("centered");
+  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);
+    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());
+    // 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());
 
-  gconf->SetString(NS_LITERAL_CSTRING(kDesktopImageKey), filePath);
-  gconf->SetBool(NS_LITERAL_CSTRING(kDesktopDrawBGKey), PR_TRUE);
+    gconf->SetString(NS_LITERAL_CSTRING(kDesktopImageKey), filePath);
+    gconf->SetBool(NS_LITERAL_CSTRING(kDesktopDrawBGKey), PR_TRUE);
+  }
 
   return rv;
 }
 
 #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);
 
   nsCAutoString background;
-  gconf->GetString(NS_LITERAL_CSTRING(kDesktopColorKey), background);
+  if (gconf) {
+    gconf->GetString(NS_LITERAL_CSTRING(kDesktopColorKey), background);
+  }
 
   if (background.IsEmpty()) {
     *aColor = 0;
     return NS_OK;
   }
 
   GdkColor color;
   gboolean success = gdk_color_parse(background.get(), &color);
@@ -432,36 +510,48 @@ ColorToCString(PRUint32 aColor, nsCStrin
 }
 
 NS_IMETHODIMP
 nsGNOMEShellService::SetDesktopBackgroundColor(PRUint32 aColor)
 {
   NS_ASSERTION(aColor <= 0xffffff, "aColor has extra bits");
   nsCOMPtr<nsIGConfService> gconf = do_GetService(NS_GCONFSERVICE_CONTRACTID);
 
-  nsCAutoString colorString;
-  ColorToCString(aColor, colorString);
+  if (gconf) {
+    nsCAutoString colorString;
+    ColorToCString(aColor, colorString);
 
-  gconf->SetString(NS_LITERAL_CSTRING(kDesktopColorKey), colorString);
+    gconf->SetString(NS_LITERAL_CSTRING(kDesktopColorKey), colorString);
+  }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsGNOMEShellService::OpenApplication(PRInt32 aApplication)
 {
   nsCAutoString scheme;
   if (aApplication == APPLICATION_MAIL)
     scheme.Assign("mailto");
   else if (aApplication == APPLICATION_NEWS)
     scheme.Assign("news");
   else
     return NS_ERROR_NOT_AVAILABLE;
 
+  nsCOMPtr<nsIGIOService> giovfs = do_GetService(NS_GIOSERVICE_CONTRACTID);
+  if (giovfs) {
+    nsCOMPtr<nsIGIOMimeApp> gioApp;
+    giovfs->GetAppForURIScheme(scheme, getter_AddRefs(gioApp));
+    if (gioApp)
+      return gioApp->Launch(EmptyCString());
+  }
+
   nsCOMPtr<nsIGConfService> gconf = do_GetService(NS_GCONFSERVICE_CONTRACTID);
+  if (!gconf)
+    return NS_ERROR_FAILURE;
 
   PRBool enabled;
   nsCAutoString appCommand;
   gconf->GetAppForProtocol(scheme, &enabled, appCommand);
 
   if (!enabled)
     return NS_ERROR_FAILURE;
 
--- a/browser/components/shell/src/nsGNOMEShellService.h
+++ b/browser/components/shell/src/nsGNOMEShellService.h
@@ -38,26 +38,29 @@
 #define nsgnomeshellservice_h____
 
 #include "nsIShellService.h"
 #include "nsStringAPI.h"
 
 class nsGNOMEShellService : public nsIShellService
 {
 public:
-  nsGNOMEShellService() : mCheckedThisSession(PR_FALSE) { }
+  nsGNOMEShellService() : mCheckedThisSession(PR_FALSE), mAppIsInPath(PR_FALSE) { }
 
   NS_DECL_ISUPPORTS
   NS_DECL_NSISHELLSERVICE
 
   nsresult Init() NS_HIDDEN;
 
 private:
   ~nsGNOMEShellService() {}
 
   NS_HIDDEN_(PRBool) KeyMatchesAppName(const char *aKeyValue) const;
+  NS_HIDDEN_(PRBool) CheckHandlerMatchesAppName(const nsACString& handler) const;
 
+  NS_HIDDEN_(PRBool) GetAppPathFromLauncher();
   PRPackedBool mCheckedThisSession;
   PRPackedBool mUseLocaleFilenames;
   nsCString    mAppPath;
+  PRPackedBool mAppIsInPath;
 };
 
 #endif // nsgnomeshellservice_h____
--- a/browser/components/shell/src/nsWindowsShellService.cpp
+++ b/browser/components/shell/src/nsWindowsShellService.cpp
@@ -86,21 +86,17 @@
 #define REG_SUCCEEDED(val) \
   (val == ERROR_SUCCESS)
 
 #define REG_FAILED(val) \
   (val != ERROR_SUCCESS)
 
 #define NS_TASKBAR_CONTRACTID "@mozilla.org/windows-taskbar;1"
 
-#ifndef WINCE
 NS_IMPL_ISUPPORTS2(nsWindowsShellService, nsIWindowsShellService, nsIShellService)
-#else
-NS_IMPL_ISUPPORTS1(nsWindowsShellService, nsIShellService)
-#endif
 
 static nsresult
 OpenKeyForReading(HKEY aKeyRoot, const nsAString& aKeyName, HKEY* aKey)
 {
   const nsString &flatName = PromiseFlatString(aKeyName);
 
   DWORD res = ::RegOpenKeyExW(aKeyRoot, flatName.get(), 0, KEY_READ, aKey);
   switch (res) {
@@ -110,43 +106,16 @@ OpenKeyForReading(HKEY aKeyRoot, const n
     return NS_ERROR_FILE_ACCESS_DENIED;
   case ERROR_FILE_NOT_FOUND:
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   return NS_OK;
 }
 
-#ifdef WINCE
-static nsresult
-OpenKeyForWriting(HKEY aStartKey, const nsAString& aKeyName, HKEY* aKey)
-{
-  const nsString &flatName = PromiseFlatString(aKeyName);
-
-  DWORD dwDisp = 0;
-  DWORD res = ::RegCreateKeyExW(aStartKey, flatName.get(), 0, NULL,
-                                0, KEY_READ | KEY_WRITE, NULL, aKey,
-                                &dwDisp);
-  switch (res) {
-  case ERROR_SUCCESS:
-    break;
-  case ERROR_ACCESS_DENIED:
-    return NS_ERROR_FILE_ACCESS_DENIED;
-  case ERROR_FILE_NOT_FOUND:
-    res = ::RegCreateKeyExW(aStartKey, flatName.get(), 0, NULL,
-                            0, KEY_READ | KEY_WRITE, NULL, aKey,
-                            NULL);
-    if (res != ERROR_SUCCESS)
-      return NS_ERROR_FILE_ACCESS_DENIED;
-  }
-
-  return NS_OK;
-}
-#endif
-
 ///////////////////////////////////////////////////////////////////////////////
 // Default Browser Registry Settings
 //
 // The setting of these values are made by an external binary since writing
 // these values may require elevation.
 //
 // - File Extension Mappings
 //   -----------------------
@@ -212,73 +181,47 @@ OpenKeyForWriting(HKEY aStartKey, const 
 //
 
 typedef struct {
   char* keyName;
   char* valueName;
   char* valueData;
 } SETTING;
 
-#ifndef WINCE
 #define APP_REG_NAME L"Firefox"
 #define CLS_HTML "FirefoxHTML"
 #define CLS_URL "FirefoxURL"
 #define CPL_DESKTOP L"Control Panel\\Desktop"
 #define VAL_OPEN "\"%APPPATH%\" -requestPending -osint -url \"%1\""
 #define VAL_FILE_ICON "%APPPATH%,1"
-#else
-#define CPL_DESKTOP L"ControlPanel\\Desktop"
-#define VAL_OPEN "\"%APPPATH%\" -osint -url \"%1\""
-#define VAL_FILE_ICON "%APPPATH%,-2"
-#endif
-
 #define DI "\\DefaultIcon"
 #define SOP "\\shell\\open\\command"
 
-
 #define MAKE_KEY_NAME1(PREFIX, MID) \
   PREFIX MID
 
 // The DefaultIcon registry key value should never be used when checking if
 // Firefox is the default browser for file handlers since other applications
 // (e.g. MS Office) may modify the DefaultIcon registry key value to add Icon
 // Handlers. see http://msdn2.microsoft.com/en-us/library/aa969357.aspx for
 // more info.
 static SETTING gSettings[] = {
-#ifndef WINCE
   // File Handler Class
   { MAKE_KEY_NAME1(CLS_HTML, SOP), "", VAL_OPEN },
 
   // Protocol Handler Class - for Vista and above
   { MAKE_KEY_NAME1(CLS_URL, SOP), "", VAL_OPEN },
-#else
-  { MAKE_KEY_NAME1("FTP", DI), "", VAL_FILE_ICON },
-  { MAKE_KEY_NAME1("FTP", SOP), "", VAL_OPEN },
-
-  // File handlers for Windows CE
-  { MAKE_KEY_NAME1("bmpfile", DI), "", VAL_FILE_ICON },
-  { MAKE_KEY_NAME1("bmpfile", SOP), "", VAL_OPEN },
-  { MAKE_KEY_NAME1("giffile", DI), "", VAL_FILE_ICON },
-  { MAKE_KEY_NAME1("giffile", SOP), "", VAL_OPEN },
-  { MAKE_KEY_NAME1("jpegfile", DI), "", VAL_FILE_ICON },
-  { MAKE_KEY_NAME1("jpegfile", SOP), "", VAL_OPEN },
-  { MAKE_KEY_NAME1("pngfile", DI), "", VAL_FILE_ICON },
-  { MAKE_KEY_NAME1("pngfile", SOP), "", VAL_OPEN },
-  { MAKE_KEY_NAME1("htmlfile", DI), "", VAL_FILE_ICON },
-  { MAKE_KEY_NAME1("htmlfile", SOP), "", VAL_OPEN },
-#endif
 
   // Protocol Handlers
   { MAKE_KEY_NAME1("HTTP", DI),    "", VAL_FILE_ICON },
   { MAKE_KEY_NAME1("HTTP", SOP),   "", VAL_OPEN },
   { MAKE_KEY_NAME1("HTTPS", DI),   "", VAL_FILE_ICON },
   { MAKE_KEY_NAME1("HTTPS", SOP),  "", VAL_OPEN }
 };
 
-#if !defined(WINCE)
 nsresult
 GetHelperPath(nsAutoString& aPath)
 {
   nsresult rv;
   nsCOMPtr<nsIProperties> directoryService = 
     do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -308,22 +251,20 @@ LaunchHelper(nsAutoString& aPath)
 
   if (!ok)
     return NS_ERROR_FAILURE;
 
   CloseHandle(pi.hProcess);
   CloseHandle(pi.hThread);
   return NS_OK;
 }
-#endif // !defined(WINCE)
 
 NS_IMETHODIMP
 nsWindowsShellService::ShortcutMaintenance()
 {
-#if !defined(WINCE)
   nsresult rv;
 
   // Launch helper.exe so it can update the application user model ids on
   // shortcuts in the user's taskbar and start menu. This keeps older pinned
   // shortcuts grouped correctly after major updates. Note, we also do this
   // through the upgrade installer script, however, this is the only place we
   // have a chance to trap links created by users who do control the install/
   // update process of the browser.
@@ -383,23 +324,18 @@ nsWindowsShellService::ShortcutMaintenan
 
   nsAutoString appHelperPath;
   if (NS_FAILED(GetHelperPath(appHelperPath)))
     return NS_ERROR_UNEXPECTED;
 
   appHelperPath.AppendLiteral(" /UpdateShortcutAppUserModelIds");
 
   return LaunchHelper(appHelperPath);
-#else
-  NS_NOTREACHED("ShortcutMaintenance not implemented on wince!");
-  return NS_OK;
-#endif // !defined(WINCE)
 }
 
-#ifndef WINCE
 PRBool
 nsWindowsShellService::IsDefaultBrowserVista(PRBool* aIsDefaultBrowser)
 {
 #if MOZ_WINSDK_TARGETVER >= MOZ_NTDDI_LONGHORN
   IApplicationAssociationRegistration* pAAR;
   
   HRESULT hr = CoCreateInstance(CLSID_ApplicationAssociationRegistration,
                                 NULL,
@@ -413,17 +349,16 @@ nsWindowsShellService::IsDefaultBrowserV
                                     aIsDefaultBrowser);
 
     pAAR->Release();
     return PR_TRUE;
   }
 #endif  
   return PR_FALSE;
 }
-#endif
 
 NS_IMETHODIMP
 nsWindowsShellService::IsDefaultBrowser(PRBool aStartupCheck,
                                         PRBool* aIsDefaultBrowser)
 {
   // If this is the first browser window, maintain internal state that we've
   // checked this session (so that subsequent window opens don't show the 
   // default browser dialog).
@@ -434,22 +369,20 @@ nsWindowsShellService::IsDefaultBrowser(
   SETTING* end = gSettings + sizeof(gSettings)/sizeof(SETTING);
 
   *aIsDefaultBrowser = PR_TRUE;
 
   PRUnichar exePath[MAX_BUF];
   if (!::GetModuleFileNameW(0, exePath, MAX_BUF))
     return NS_ERROR_FAILURE;
 
-#ifndef WINCE
   // Convert the path to a long path since GetModuleFileNameW returns the path
   // that was used to launch Firefox which is not necessarily a long path.
   if (!::GetLongPathNameW(exePath, exePath, MAX_BUF))
     return NS_ERROR_FAILURE;
-#endif
 
   nsAutoString appLongPath(exePath);
 
   nsresult rv;
   PRUnichar currValue[MAX_BUF];
   for (settings = gSettings; settings < end; ++settings) {
     NS_ConvertUTF8toUTF16 dataLongPath(settings->valueData);
     NS_ConvertUTF8toUTF16 key(settings->keyName);
@@ -473,126 +406,40 @@ nsWindowsShellService::IsDefaultBrowser(
     if (REG_FAILED(res) ||
         !dataLongPath.Equals(currValue, CaseInsensitiveCompare)) {
       // Key wasn't set, or was set to something other than our registry entry
       *aIsDefaultBrowser = PR_FALSE;
       return NS_OK;
     }
   }
 
-#ifndef WINCE
   // Only check if Firefox is the default browser on Vista if the previous
   // checks show that Firefox is the default browser.
   if (*aIsDefaultBrowser)
     IsDefaultBrowserVista(aIsDefaultBrowser);
-#endif
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsWindowsShellService::SetDefaultBrowser(PRBool aClaimAllTypes, PRBool aForAllUsers)
 {
-#ifndef WINCE
   nsAutoString appHelperPath;
   if (NS_FAILED(GetHelperPath(appHelperPath)))
     return NS_ERROR_FAILURE;
 
   if (aForAllUsers) {
     appHelperPath.AppendLiteral(" /SetAsDefaultAppGlobal");
   } else {
     appHelperPath.AppendLiteral(" /SetAsDefaultAppUser");
   }
 
   return LaunchHelper(appHelperPath);
-#else
-  SETTING* settings;
-  SETTING* end = gSettings + sizeof(gSettings)/sizeof(SETTING);
-
-  PRUnichar exePath[MAX_BUF];
-  if (!::GetModuleFileNameW(0, exePath, MAX_BUF))
-    return NS_ERROR_FAILURE;
-
-  nsAutoString appLongPath(exePath);
-
-  // The .png registry key isn't present by default so also add Content Type.
-  SetRegKey(NS_LITERAL_STRING(".png"), EmptyString(),
-            NS_LITERAL_STRING("pngfile"));
-  SetRegKey(NS_LITERAL_STRING(".png"), NS_LITERAL_STRING("Content Type"),
-            NS_LITERAL_STRING("image/png"));
-
-  // Set these keys to their default value for a clean install in case another
-  // app has changed these keys.
-  SetRegKey(NS_LITERAL_STRING(".htm"), EmptyString(),
-            NS_LITERAL_STRING("htmlfile"));
-  SetRegKey(NS_LITERAL_STRING(".html"), EmptyString(),
-            NS_LITERAL_STRING("htmlfile"));
-  SetRegKey(NS_LITERAL_STRING(".bmp"), EmptyString(),
-            NS_LITERAL_STRING("bmpfile"));
-  SetRegKey(NS_LITERAL_STRING(".gif"), EmptyString(),
-            NS_LITERAL_STRING("giffile"));
-  SetRegKey(NS_LITERAL_STRING(".jpe"), EmptyString(),
-            NS_LITERAL_STRING("jpegfile"));
-  SetRegKey(NS_LITERAL_STRING(".jpg"), EmptyString(),
-            NS_LITERAL_STRING("jpegfile"));
-  SetRegKey(NS_LITERAL_STRING(".jpeg"), EmptyString(),
-            NS_LITERAL_STRING("jpegfile"));
-
-  for (settings = gSettings; settings < end; ++settings) {
-    NS_ConvertUTF8toUTF16 dataLongPath(settings->valueData);
-    NS_ConvertUTF8toUTF16 key(settings->keyName);
-    NS_ConvertUTF8toUTF16 value(settings->valueName);
-    PRInt32 offset = dataLongPath.Find("%APPPATH%");
-    dataLongPath.Replace(offset, 9, appLongPath);
-    SetRegKey(key, value, dataLongPath);
-  }
-  // On Windows CE RegFlushKey can negatively impact performance if there are a
-  // lot of pending writes to the HKEY_CLASSES_ROOT registry hive but it is
-  // necessary to save the values in the case where the user performs a hard
-  // power off of the device.
-  ::RegFlushKey(HKEY_CLASSES_ROOT);
-#endif
-
-  return NS_OK;
 }
 
-#ifdef WINCE
-void
-nsWindowsShellService::SetRegKey(const nsString& aKeyName,
-                                 const nsString& aValueName,
-                                 const nsString& aValue)
-{
-  PRUnichar buf[MAX_BUF];
-  DWORD len = sizeof buf;
-
-  HKEY theKey;
-  nsresult rv = OpenKeyForWriting(HKEY_CLASSES_ROOT, aKeyName, &theKey);
-  if (NS_FAILED(rv))
-    return;
-
-  // Get the current value.
-  DWORD res = ::RegQueryValueExW(theKey, PromiseFlatString(aValueName).get(),
-                                 NULL, NULL, (LPBYTE)buf, &len);
-
-  // Set the new value if it doesn't exist or it is different than the current
-  // value.
-  nsAutoString current(buf);
-  if (REG_FAILED(res) || !current.Equals(aValue)) {
-    const nsString &flatValue = PromiseFlatString(aValue);
-
-    ::RegSetValueExW(theKey, PromiseFlatString(aValueName).get(),
-                     0, REG_SZ, (const BYTE *)flatValue.get(),
-                     (flatValue.Length() + 1) * sizeof(PRUnichar));
-  }
-
-  // Close the key we opened.
-  ::RegCloseKey(theKey);
-}
-#endif
-
 NS_IMETHODIMP
 nsWindowsShellService::GetShouldCheckDefaultBrowser(PRBool* aResult)
 {
   // If we've already checked, the browser has been started and this is a 
   // new window open, and we don't want to check again.
   if (mCheckedThisSession) {
     *aResult = PR_FALSE;
     return NS_OK;
@@ -763,17 +610,16 @@ nsWindowsShellService::SetDesktopBackgro
      PRBool result = PR_FALSE;
      DWORD  dwDisp = 0;
      HKEY   key;
      // Try to create/open a subkey under HKCU.
      DWORD res = ::RegCreateKeyExW(HKEY_CURRENT_USER, CPL_DESKTOP,
                                    0, NULL, REG_OPTION_NON_VOLATILE,
                                    KEY_WRITE, NULL, &key, &dwDisp);
     if (REG_SUCCEEDED(res)) {
-#ifndef WINCE
       PRUnichar tile[2], style[2];
       switch (aPosition) {
         case BACKGROUND_TILE:
           tile[0] = '1';
           style[0] = '1';
           break;
         case BACKGROUND_CENTER:
           tile[0] = '0';
@@ -790,35 +636,19 @@ nsWindowsShellService::SetDesktopBackgro
       // The size is always 3 unicode characters.
       PRInt32 size = 3 * sizeof(PRUnichar);
       ::RegSetValueExW(key, L"TileWallpaper",
                        0, REG_SZ, (const BYTE *)tile, size);
       ::RegSetValueExW(key, L"WallpaperStyle",
                        0, REG_SZ, (const BYTE *)style, size);
       ::SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (PVOID)path.get(),
                               SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
-#else
-      DWORD tile = (aPosition == BACKGROUND_TILE);
-      ::RegSetValueExW(key, L"Tile",
-                       0, REG_DWORD, (const BYTE *)&tile, sizeof(DWORD));
-      // On WinCE SPI_SETDESKWALLPAPER isn't available, so set the registry
-      // entry ourselves and then broadcast UI change
-      PRInt32 size = (path.Length() + 1) * sizeof(PRUnichar);
-      ::RegSetValueExW(key, L"Wallpaper",
-                       0, REG_SZ, (const BYTE *)path.get(), size);
-      ::SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, NULL, 0);
-#endif
 
       // Close the key we opened.
       ::RegCloseKey(key);
-
-#ifdef WINCE
-      // Ensure that the writes are flushed in case of hard reboot
-      ::RegFlushKey(HKEY_CURRENT_USER);
-#endif
     }
   }
   return rv;
 }
 
 NS_IMETHODIMP
 nsWindowsShellService::OpenApplication(PRInt32 aApplication)
 {
@@ -934,19 +764,16 @@ nsWindowsShellService::SetDesktopBackgro
   int aParameters[2] = { COLOR_BACKGROUND, COLOR_DESKTOP };
   BYTE r = (aColor >> 16);
   BYTE g = (aColor << 16) >> 24;
   BYTE b = (aColor << 24) >> 24;
   COLORREF colors[2] = { RGB(r,g,b), RGB(r,g,b) };
 
   ::SetSysColors(sizeof(aParameters) / sizeof(int), aParameters, colors);
 
-  // SetSysColors is persisting across sessions on Windows CE, so no need to
-  // write to registry
-#ifndef WINCE
   PRBool result = PR_FALSE;
   DWORD  dwDisp = 0;
   HKEY   key;
   // Try to create/open a subkey under HKCU.
   DWORD rv = ::RegCreateKeyExW(HKEY_CURRENT_USER,
                                L"Control Panel\\Colors", 0, NULL,
                                REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL,
                                &key, &dwDisp);
@@ -958,21 +785,19 @@ nsWindowsShellService::SetDesktopBackgro
 
     ::RegSetValueExW(key, L"Background",
                      0, REG_SZ, (const BYTE *)backColor.get(),
                      (backColor.Length() + 1) * sizeof(PRUnichar));
   }
   
   // Close the key we opened.
   ::RegCloseKey(key);
-#endif
   return NS_OK;
 }
 
-#ifndef WINCE
 NS_IMETHODIMP
 nsWindowsShellService::GetUnreadMailCount(PRUint32* aCount)
 {
   *aCount = 0;
 
   HKEY accountKey;
   if (GetMailAccountKey(&accountKey)) {
     DWORD type, unreadCount;
@@ -1022,17 +847,16 @@ nsWindowsShellService::GetMailAccountKey
       break;
   }
   while (1);
 
   // Close the key we opened.
   ::RegCloseKey(mailKey);
   return PR_FALSE;
 }
-#endif
 
 NS_IMETHODIMP
 nsWindowsShellService::OpenApplicationWithURI(nsILocalFile* aApplication,
                                               const nsACString& aURI)
 {
   nsresult rv;
   nsCOMPtr<nsIProcess> process = 
     do_CreateInstance("@mozilla.org/process/util;1", &rv);
--- a/browser/components/shell/src/nsWindowsShellService.h
+++ b/browser/components/shell/src/nsWindowsShellService.h
@@ -41,40 +41,28 @@
 
 #include "nscore.h"
 #include "nsStringAPI.h"
 #include "nsIWindowsShellService.h"
 
 #include <windows.h>
 #include <ole2.h>
 
-#ifndef WINCE
 class nsWindowsShellService : public nsIWindowsShellService
-#else
-class nsWindowsShellService : public nsIShellService
-#endif
 {
 public:
   nsWindowsShellService() : mCheckedThisSession(PR_FALSE) {}; 
   virtual ~nsWindowsShellService() {};
 
   NS_DECL_ISUPPORTS
   NS_DECL_NSISHELLSERVICE
-#ifndef WINCE
   NS_DECL_NSIWINDOWSSHELLSERVICE
-#endif
 
 protected:
-#ifndef WINCE
   PRBool    IsDefaultBrowserVista(PRBool* aIsDefaultBrowser);
 
   PRBool    GetMailAccountKey(HKEY* aResult);
-#else
-  void      SetRegKey(const nsString& aKeyName,
-                      const nsString& aValueName,
-                      const nsString& aValue);
-#endif
 
 private:
   PRBool    mCheckedThisSession;
 };
 
 #endif // nswindowsshellservice_h____
--- a/browser/confvars.sh
+++ b/browser/confvars.sh
@@ -45,10 +45,12 @@ MOZ_CHROME_FILE_FORMAT=omni
 MOZ_STATIC_BUILD_UNSUPPORTED=1
 # always enabled for form history
 MOZ_MORKREADER=1
 MOZ_SAFE_BROWSING=1
 MOZ_SERVICES_SYNC=1
 MOZ_APP_VERSION=$FIREFOX_VERSION
 MOZ_EXTENSIONS_DEFAULT=" gnomevfs"
 # MOZ_APP_DISPLAYNAME will be set by branding/configure.sh
+# Changing either of these values requires a clobber to ensure correct results,
+# because branding dependencies are broken.
 MOZ_BRANDING_DIRECTORY=browser/branding/nightly
-MOZ_OFFICIAL_BRANDING_DIRECTORY=other-licenses/branding/firefox