Merge from mozilla-central.
authorDavid Anderson <danderson@mozilla.com>
Tue, 17 Jan 2012 14:05:23 -0800
changeset 105583 8e182985f782e8ec3b3872d2c927ba9e63c156b3
parent 105582 0eaa6a95eaee84b3f9a13c00162bb4949a66147b (current diff)
parent 84671 83fa8893f553a214684313a5fe7708de4a8b63b3 (diff)
child 105584 49bc8d35a21ec182c2e0a421bac7045d6049500d
push id1075
push uservporof@mozilla.com
push dateThu, 13 Sep 2012 10:46:49 +0000
treeherderfx-team@f39786e8364d [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone12.0a1
Merge from mozilla-central.
accessible/src/atk/nsAccessibleWrap.cpp
accessible/src/atk/nsApplicationAccessibleWrap.cpp
accessible/src/base/nsAccUtils.cpp
accessible/src/base/nsAccUtils.h
accessible/src/base/nsAccessNode.cpp
accessible/src/base/nsAccessible.cpp
accessible/src/base/nsRootAccessible.h
accessible/src/msaa/nsAccessibleWrap.cpp
accessible/src/xul/Makefile.in
accessible/src/xul/nsXULFormControlAccessible.cpp
accessible/src/xul/nsXULFormControlAccessible.h
accessible/src/xul/nsXULListboxAccessible.cpp
accessible/src/xul/nsXULListboxAccessible.h
accessible/src/xul/nsXULMenuAccessible.cpp
accessible/src/xul/nsXULMenuAccessible.h
accessible/src/xul/nsXULTabAccessible.cpp
accessible/tests/mochitest/events/Makefile.in
accessible/tests/mochitest/tree/Makefile.in
browser/app/profile/firefox.js
browser/base/content/browser.js
browser/base/content/browser.xul
browser/base/content/syncSetup.xul
browser/base/content/tabbrowser.xml
browser/components/migration/src/nsProfileMigrator.cpp
browser/components/migration/src/nsProfileMigrator.h
browser/components/preferences/sync.xul
browser/devtools/styleinspector/StyleInspector.jsm
browser/devtools/webconsole/HUDService.jsm
browser/devtools/webconsole/test/Makefile.in
browser/devtools/webconsole/test/browser_gcli_web.js
browser/locales/en-US/chrome/browser/browser.dtd
browser/locales/en-US/chrome/browser/devtools/styleinspector.properties
build/mobile/devicemanagerADB.py
configure.in
content/base/src/nsGenericElement.cpp
content/base/src/nsPropertyTable.cpp
content/base/src/nsPropertyTable.h
content/base/src/nsRange.cpp
content/base/src/nsRange.h
content/base/src/nsScriptLoader.cpp
content/base/test/Makefile.in
content/base/test/test_bug371576-1.html
content/canvas/src/CustomQS_Canvas2D.h
content/canvas/src/CustomQS_WebGL.h
content/canvas/src/Makefile.in
content/canvas/src/WebGLContext.cpp
content/canvas/src/WebGLContextGL.cpp
content/canvas/src/nsCanvasRenderingContext2DAzure.cpp
content/canvas/test/test_canvas.html
content/html/content/src/nsGenericHTMLElement.cpp
content/html/content/src/nsHTMLDNSPrefetch.cpp
content/html/content/src/nsTextEditorState.cpp
content/html/document/src/ImageDocument.cpp
content/xbl/src/nsXBLDocumentInfo.cpp
content/xul/document/src/nsXULContentSink.cpp
db/sqlite3/src/Makefile.in
docshell/base/nsDocShell.cpp
dom/base/ConsoleAPI.js
dom/base/nsDOMClassInfo.cpp
dom/base/nsDOMWindowUtils.cpp
dom/base/nsFocusManager.cpp
dom/base/nsFocusManager.h
dom/base/nsGlobalWindow.cpp
dom/base/nsJSEnvironment.cpp
dom/indexedDB/IDBObjectStore.cpp
dom/interfaces/base/nsIDOMWindowUtils.idl
dom/interfaces/css/nsIDOMCSS2Properties.idl
dom/plugins/base/nsJSNPRuntime.cpp
dom/plugins/base/nsPluginInstanceOwner.cpp
dom/plugins/ipc/PluginInstanceChild.cpp
dom/workers/Events.cpp
dom/workers/Exceptions.cpp
dom/workers/File.cpp
dom/workers/Location.cpp
dom/workers/Navigator.cpp
dom/workers/WorkerPrivate.cpp
dom/workers/WorkerScope.cpp
dom/workers/XMLHttpRequest.cpp
editor/libeditor/base/nsEditor.cpp
editor/libeditor/base/nsEditor.h
editor/libeditor/base/nsEditorEventListener.cpp
editor/libeditor/base/nsSelectionState.cpp
editor/libeditor/text/nsPlaintextEditor.cpp
editor/libeditor/text/tests/Makefile.in
editor/txtsvc/src/nsTextServicesDocument.cpp
embedding/android/GeckoAppShell.java
embedding/android/Makefile.in
gfx/cairo/cairo/test/Makefile.am
gfx/cairo/cairo/test/Makefile.in
gfx/cairo/cairo/test/README
gfx/cairo/cairo/test/buffer_diff.c
gfx/cairo/cairo/test/buffer_diff.h
gfx/cairo/cairo/test/cairo_test.c
gfx/cairo/cairo/test/cairo_test.h
gfx/cairo/cairo/test/clip_twice-ref.png
gfx/cairo/cairo/test/clip_twice.c
gfx/cairo/cairo/test/coverage-ref.png
gfx/cairo/cairo/test/coverage.c
gfx/cairo/cairo/test/fill_rule-ref.png
gfx/cairo/cairo/test/fill_rule.c
gfx/cairo/cairo/test/imagediff.c
gfx/cairo/cairo/test/leaky_polygon-ref.png
gfx/cairo/cairo/test/leaky_polygon.c
gfx/cairo/cairo/test/line_width-ref.png
gfx/cairo/cairo/test/line_width.c
gfx/cairo/cairo/test/linear_gradient-ref.png
gfx/cairo/cairo/test/linear_gradient.c
gfx/cairo/cairo/test/move_to_show_surface-ref.png
gfx/cairo/cairo/test/move_to_show_surface.c
gfx/cairo/cairo/test/pixman_rotate-ref.png
gfx/cairo/cairo/test/pixman_rotate.c
gfx/cairo/cairo/test/read_png.c
gfx/cairo/cairo/test/read_png.h
gfx/cairo/cairo/test/romedalen.png
gfx/cairo/cairo/test/text_cache_crash.c
gfx/cairo/cairo/test/text_rotate.c
gfx/cairo/cairo/test/write_png.c
gfx/cairo/cairo/test/write_png.h
gfx/cairo/cairo/test/xmalloc.c
gfx/cairo/cairo/test/xmalloc.h
gfx/gl/GLContextProviderEGL.cpp
gfx/layers/basic/BasicLayers.cpp
gfx/layers/opengl/CanvasLayerOGL.cpp
gfx/layers/opengl/CanvasLayerOGL.h
gfx/layers/opengl/ContainerLayerOGL.cpp
gfx/layers/opengl/ImageLayerOGL.cpp
gfx/layers/opengl/ImageLayerOGL.h
gfx/layers/opengl/LayerManagerOGL.cpp
gfx/layers/opengl/LayerManagerOGL.h
gfx/layers/opengl/ThebesLayerOGL.cpp
gfx/layers/opengl/ThebesLayerOGL.h
gfx/thebes/gfxFont.cpp
gfx/thebes/gfxFont.h
gfx/thebes/gfxPlatform.cpp
gfx/thebes/gfxPlatform.h
gfx/thebes/gfxPlatformMac.cpp
gfx/thebes/gfxPlatformMac.h
gfx/thebes/gfxQuartzSurface.cpp
gfx/thebes/gfxQuartzSurface.h
gfx/thebes/gfxWindowsPlatform.cpp
intl/uconv/src/nsCharsetConverterManager.cpp
js/src/Makefile.in
js/src/assembler/wtf/Platform.h
js/src/configure.in
js/src/frontend/BytecodeEmitter.cpp
js/src/frontend/Parser.h
js/src/jit-test/tests/basic/testBug597736.js
js/src/jsapi-tests/testConservativeGC.cpp
js/src/jsapi.cpp
js/src/jsapi.h
js/src/jsclass.h
js/src/jscntxt.h
js/src/jsdate.h
js/src/jsdbgapi.cpp
js/src/jsexn.cpp
js/src/jsfriendapi.cpp
js/src/jsfriendapi.h
js/src/jsfun.cpp
js/src/jsgc.cpp
js/src/jsgc.h
js/src/jsinfer.cpp
js/src/jsinterp.cpp
js/src/jsiter.cpp
js/src/jsnum.cpp
js/src/jsnum.h
js/src/jsobj.cpp
js/src/jsobjinlines.h
js/src/jsopcode.cpp
js/src/jsopcode.h
js/src/jspropertycache.cpp
js/src/jsscript.cpp
js/src/jsstr.cpp
js/src/jsstr.h
js/src/jstypedarray.cpp
js/src/jsutil.h
js/src/jsval.h
js/src/jsxdrapi.h
js/src/methodjit/BaseAssembler.h
js/src/methodjit/Compiler.cpp
js/src/methodjit/FastArithmetic.cpp
js/src/methodjit/FastOps.cpp
js/src/methodjit/MethodJIT.h
js/src/shell/js.cpp
js/xpconnect/shell/xpcshell.cpp
js/xpconnect/src/Makefile.in
js/xpconnect/src/XPCConvert.cpp
js/xpconnect/src/XPCJSRuntime.cpp
js/xpconnect/src/XPCQuickStubs.cpp
js/xpconnect/src/XPCQuickStubs.h
js/xpconnect/src/XPCVariant.cpp
js/xpconnect/src/XPCWrappedJSClass.cpp
js/xpconnect/src/nsXPConnect.cpp
js/xpconnect/src/qsgen.py
js/xpconnect/src/xpcprivate.h
js/xpconnect/wrappers/AccessCheck.cpp
js/xpconnect/wrappers/FilteringWrapper.cpp
js/xpconnect/wrappers/WrapperFactory.cpp
js/xpconnect/wrappers/XrayWrapper.cpp
layout/base/crashtests/crashtests.list
layout/base/nsBidiPresUtils.cpp
layout/base/nsCSSFrameConstructor.cpp
layout/base/nsDocumentViewer.cpp
layout/base/nsIPresShell.h
layout/base/nsLayoutUtils.cpp
layout/base/nsPresContext.cpp
layout/base/nsPresContext.h
layout/base/nsPresShell.cpp
layout/base/nsPresShell.h
layout/base/nsRefreshDriver.cpp
layout/base/nsRefreshDriver.h
layout/base/tests/test_reftests_with_caret.html
layout/forms/nsComboboxControlFrame.cpp
layout/generic/crashtests/crashtests.list
layout/generic/nsBlockFrame.cpp
layout/generic/nsBlockFrame.h
layout/generic/nsFrame.cpp
layout/generic/nsFrameSetFrame.cpp
layout/generic/nsLineLayout.cpp
layout/generic/nsLineLayout.h
layout/generic/nsTextFrameThebes.cpp
layout/reftests/bugs/reftest.list
layout/reftests/canvas/reftest.list
layout/reftests/reftest-sanity/reftest.list
layout/reftests/svg/as-image/reftest.list
layout/reftests/svg/reftest.list
layout/reftests/text/reftest.list
layout/style/nsCSSProps.cpp
layout/style/nsCSSProps.h
layout/style/nsComputedDOMStyle.cpp
layout/style/nsComputedDOMStyle.h
layout/style/nsRuleNode.cpp
layout/style/nsStyleStruct.cpp
layout/style/nsStyleStruct.h
layout/style/test/property_database.js
layout/svg/base/src/nsSVGGeometryFrame.cpp
layout/svg/base/src/nsSVGGeometryFrame.h
layout/svg/base/src/nsSVGGlyphFrame.cpp
layout/svg/base/src/nsSVGGlyphFrame.h
layout/svg/base/src/nsSVGTextFrame.cpp
layout/tables/nsTableCellFrame.cpp
layout/tables/nsTableColFrame.cpp
layout/tables/nsTableColGroupFrame.cpp
layout/tables/nsTableFrame.cpp
layout/tables/nsTableRowFrame.cpp
layout/tables/nsTableRowGroupFrame.cpp
layout/tools/layout-debug/src/nsLayoutDebuggingTools.cpp
layout/tools/reftest/reftest.js
layout/xul/base/src/nsListBoxBodyFrame.cpp
mobile/android/base/AndroidManifest.xml.in
mobile/android/base/GeckoApp.java
mobile/android/base/GeckoAppShell.java
mobile/android/base/Makefile.in
mobile/android/base/resources/drawable-hdpi-v9/ic_menu_bookmark_add.png
mobile/android/base/resources/drawable-hdpi-v9/ic_menu_bookmark_remove.png
mobile/android/base/resources/drawable-hdpi-v9/ic_menu_find_in_page.png
mobile/android/base/resources/drawable-hdpi-v9/ic_menu_forward.png
mobile/android/base/resources/drawable-hdpi-v9/ic_menu_reload.png
mobile/android/base/resources/drawable-hdpi-v9/ic_menu_save_as_pdf.png
mobile/android/base/resources/drawable-hdpi-v9/ic_menu_share.png
mobile/android/base/resources/drawable-mdpi-v9/ic_menu_bookmark_add.png
mobile/android/base/resources/drawable-mdpi-v9/ic_menu_bookmark_remove.png
mobile/android/base/resources/drawable-mdpi-v9/ic_menu_find_in_page.png
mobile/android/base/resources/drawable-mdpi-v9/ic_menu_forward.png
mobile/android/base/resources/drawable-mdpi-v9/ic_menu_reload.png
mobile/android/base/resources/drawable-mdpi-v9/ic_menu_save_as_pdf.png
mobile/android/base/resources/drawable-mdpi-v9/ic_menu_share.png
mobile/android/base/sync/crypto/Utils.java
mobile/android/base/sync/setup/activities/SetupWaitingActivity.java
mobile/xul/app/mobile.js
modules/libjar/nsZipArchive.cpp
modules/libpref/src/init/all.js
netwerk/cache/nsCacheService.cpp
netwerk/protocol/about/nsAboutBloat.cpp
netwerk/protocol/http/HttpChannelParent.cpp
netwerk/protocol/http/HttpChannelParent.h
netwerk/protocol/http/SpdySession.cpp
netwerk/protocol/http/SpdyStream.cpp
netwerk/protocol/http/nsHttpChannel.cpp
services/sync/modules/resource.js
services/sync/modules/rest.js
services/sync/tests/unit/head_http_server.js
toolkit/components/autocomplete/nsAutoCompleteController.cpp
toolkit/components/feeds/nsScriptableUnescapeHTML.cpp
toolkit/components/places/nsNavBookmarks.cpp
toolkit/components/places/nsNavBookmarks.h
toolkit/components/telemetry/Telemetry.cpp
toolkit/components/telemetry/TelemetryHistograms.h
toolkit/content/widgets/videocontrols.xml
toolkit/mozapps/extensions/content/extensions.js
toolkit/mozapps/installer/packager.mk
tools/profiler/sps/platform-macos.cc
uriloader/exthandler/nsExternalHelperAppService.cpp
uriloader/exthandler/nsExternalHelperAppService.h
uriloader/exthandler/nsExternalProtocolHandler.cpp
uriloader/exthandler/nsExternalProtocolHandler.h
view/public/nsIViewManager.h
view/src/nsView.cpp
view/src/nsView.h
view/src/nsViewManager.cpp
view/src/nsViewManager.h
widget/android/AndroidBridge.cpp
widget/android/AndroidBridge.h
widget/android/nsAppShell.cpp
widget/android/nsWindow.cpp
widget/android/nsWindow.h
widget/cocoa/nsChildView.h
widget/cocoa/nsChildView.mm
widget/cocoa/nsCocoaWindow.h
widget/cocoa/nsCocoaWindow.mm
widget/gtk2/nsNativeThemeGTK.cpp
widget/gtk2/nsWindow.cpp
widget/gtk2/nsWindow.h
widget/nsGUIEvent.h
widget/nsIWidget.h
widget/os2/nsWindow.cpp
widget/os2/nsWindow.h
widget/qt/nsWindow.cpp
widget/qt/nsWindow.h
widget/windows/nsClipboard.cpp
widget/windows/nsNativeThemeWin.cpp
widget/windows/nsWindow.cpp
widget/windows/nsWindow.h
widget/windows/nsWindowGfx.cpp
widget/xpwidgets/PuppetWidget.cpp
widget/xpwidgets/PuppetWidget.h
widget/xpwidgets/nsBaseWidget.cpp
widget/xpwidgets/nsBaseWidget.h
xpcom/base/nsCycleCollector.cpp
xpcom/build/nsXPComInit.cpp
xpcom/ds/TimeStamp.h
xpcom/ds/nsCheapSets.h
xpcom/glue/nsCycleCollectionParticipant.h
xpcom/glue/nsISupportsImpl.h
xpcom/io/SpecialSystemDirectory.cpp
xpcom/io/nsLocalFileWin.cpp
xpcom/io/nsLocalFileWin.h
xpcom/threads/nsThread.cpp
xpcom/threads/nsThread.h
xpcom/threads/nsThreadManager.cpp
xpcom/threads/nsThreadUtilsInternal.h
--- a/.gitignore
+++ b/.gitignore
@@ -34,8 +34,14 @@ js/src/configure
 js/src/autom4te.cache
 # SpiderMonkey test result logs
 js/src/tests/results-*.html
 js/src/tests/results-*.txt
 
 # Java HTML5 parser classes
 parser/html/java/htmlparser/
 parser/html/java/javaparser/
+
+# Ignore the files and directory that Eclipse IDE creates
+/.project
+/.cproject
+/.settings/
+
--- a/.hgignore
+++ b/.hgignore
@@ -34,8 +34,14 @@
 # SpiderMonkey test result logs
 ^js/src/tests/results-.*\.(html|txt)$
 
 # Java HTML5 parser classes
 ^parser/html/java/(html|java)parser/
 
 # SVN directories
 \.svn/
+
+# Ignore the files and directory that Eclipse IDE creates
+^\.project$
+^\.cproject$
+^\.settings$
+
--- a/accessible/src/atk/nsAccessibleWrap.cpp
+++ b/accessible/src/atk/nsAccessibleWrap.cpp
@@ -436,23 +436,19 @@ nsAccessibleWrap::CreateMaiInterfaces(vo
     //nsIAccessibleValue
     nsCOMPtr<nsIAccessibleValue> accessInterfaceValue;
     QueryInterface(NS_GET_IID(nsIAccessibleValue),
                    getter_AddRefs(accessInterfaceValue));
     if (accessInterfaceValue) {
        interfacesBits |= 1 << MAI_INTERFACE_VALUE; 
     }
 
-    //nsIAccessibleDocument
-    nsCOMPtr<nsIAccessibleDocument> accessInterfaceDocument;
-    QueryInterface(NS_GET_IID(nsIAccessibleDocument),
-                              getter_AddRefs(accessInterfaceDocument));
-    if (accessInterfaceDocument) {
+    // document accessible
+    if (IsDoc())
         interfacesBits |= 1 << MAI_INTERFACE_DOCUMENT;
-    }
 
     if (IsImageAccessible())
         interfacesBits |= 1 << MAI_INTERFACE_IMAGE;
 
   // HyperLinkAccessible
   if (IsLink())
     interfacesBits |= 1 << MAI_INTERFACE_HYPERLINK_IMPL;
 
--- a/accessible/src/atk/nsApplicationAccessibleWrap.cpp
+++ b/accessible/src/atk/nsApplicationAccessibleWrap.cpp
@@ -891,25 +891,25 @@ PreInit()
     return;
 
   DBusConnection* bus = dbus_bus_get(DBUS_BUS_SESSION, nsnull);
   if (!bus)
     return;
 
   dbus_connection_set_exit_on_disconnect(bus, FALSE);
 
+  static const char* iface = "org.a11y.Status";
+  static const char* member = "IsEnabled";
   DBusMessage *message;
   message = dbus_message_new_method_call("org.a11y.Bus", "/org/a11y/bus",
                                          "org.freedesktop.DBus.Properties",
                                          "Get");
   if (!message)
     goto dbus_done;
 
-  static const char* iface = "org.a11y.Status";
-  static const char* member = "IsEnabled";
   dbus_message_append_args(message, DBUS_TYPE_STRING, &iface,
                            DBUS_TYPE_STRING, &member, DBUS_TYPE_INVALID);
   dbus_connection_send_with_reply(bus, message, &sPendingCall, 1000);
   dbus_message_unref(message);
 
 dbus_done:
   dbus_connection_unref(bus);
 #endif
--- a/accessible/src/atk/nsMaiInterfaceDocument.cpp
+++ b/accessible/src/atk/nsMaiInterfaceDocument.cpp
@@ -32,22 +32,32 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
-#include "nsAccessibleWrap.h"
 #include "nsMaiInterfaceDocument.h"
 
-const char *const kDocTypeName = "W3C-doctype";
-const char *const kDocUrlName = "DocURL";
-const char *const kMimeTypeName = "MimeType";
+#include "nsAccessibleWrap.h"
+#include "nsDocAccessible.h"
+
+static const char* const kDocTypeName = "W3C-doctype";
+static const char* const kDocUrlName = "DocURL";
+static const char* const kMimeTypeName = "MimeType";
+
+// below functions are vfuncs on an ATK  interface so they need to be C call
+extern "C" {
+
+static const gchar* getDocumentLocaleCB(AtkDocument* aDocument);
+static AtkAttributeSet* getDocumentAttributesCB(AtkDocument* aDocument);
+static const gchar* getDocumentAttributeValueCB(AtkDocument* aDocument,
+                                                const gchar* aAttrName);
 
 void
 documentInterfaceInitCB(AtkDocumentIface *aIface)
 {
     NS_ASSERTION(aIface, "Invalid Interface");
     if(!aIface)
         return;
 
@@ -59,101 +69,82 @@ documentInterfaceInitCB(AtkDocumentIface
     aIface->get_document_attributes = getDocumentAttributesCB;
     aIface->get_document_attribute_value = getDocumentAttributeValueCB;
     aIface->get_document_locale = getDocumentLocaleCB;
 }
 
 const gchar *
 getDocumentLocaleCB(AtkDocument *aDocument)
 {
-    nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aDocument));
-    if (!accWrap)
-        return nsnull;
+  nsAccessibleWrap* accWrap = GetAccessibleWrap(ATK_OBJECT(aDocument));
+  if (!accWrap)
+    return nsnull;
 
-    nsCOMPtr<nsIAccessNode> docAccessNode;
-    accWrap->QueryInterface(NS_GET_IID(nsIAccessNode),
-                            getter_AddRefs(docAccessNode));
-    NS_ENSURE_TRUE(docAccessNode, nsnull);
-
-    nsAutoString locale;
-    docAccessNode->GetLanguage(locale);
-    if (locale.IsEmpty()) {
-      return nsnull;
-    }
-    return nsAccessibleWrap::ReturnString(locale);
+  nsAutoString locale;
+  accWrap->GetLanguage(locale);
+  return locale.IsEmpty() ? nsnull : nsAccessibleWrap::ReturnString(locale);
 }
 
 static inline GSList *
 prependToList(GSList *aList, const char *const aName, const nsAutoString &aValue)
 {
+  if (aValue.IsEmpty())
+    return aList;
+
     // libspi will free these
     AtkAttribute *atkAttr = (AtkAttribute *)g_malloc(sizeof(AtkAttribute));
     atkAttr->name = g_strdup(aName);
     atkAttr->value = g_strdup(NS_ConvertUTF16toUTF8(aValue).get());
     return g_slist_prepend(aList, atkAttr);
 }
 
 AtkAttributeSet *
 getDocumentAttributesCB(AtkDocument *aDocument)
 {
-    nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aDocument));
-    if (!accWrap)
-        return nsnull;
+  nsAccessibleWrap* accWrap = GetAccessibleWrap(ATK_OBJECT(aDocument));
+  if (!accWrap || !accWrap->IsDoc())
+    return nsnull;
 
-    nsCOMPtr<nsIAccessibleDocument> accDocument;
-    accWrap->QueryInterface(NS_GET_IID(nsIAccessibleDocument),
-                            getter_AddRefs(accDocument));
-    NS_ENSURE_TRUE(accDocument, nsnull);
-
-    // according to atkobject.h, AtkAttributeSet is a GSList
-    GSList *attributes = nsnull;
+  // according to atkobject.h, AtkAttributeSet is a GSList
+  GSList* attributes = nsnull;
+  nsDocAccessible* document = accWrap->AsDoc();
+  nsAutoString aURL;
+  nsresult rv = document->GetURL(aURL);
+  if (NS_SUCCEEDED(rv))
+    attributes = prependToList(attributes, kDocUrlName, aURL);
 
-    nsAutoString aURL;
-    nsresult rv = accDocument->GetURL(aURL);
-    if (NS_SUCCEEDED(rv)) {
-        attributes = prependToList(attributes, kDocUrlName, aURL);
-    }
-    nsAutoString aW3CDocType;
-    rv = accDocument->GetDocType(aW3CDocType);
-    if (NS_SUCCEEDED(rv)) {
-        attributes = prependToList(attributes, kDocTypeName, aW3CDocType);
-    }
-    nsAutoString aMimeType;
-    rv = accDocument->GetMimeType(aMimeType);
-    if (NS_SUCCEEDED(rv)) {
-        attributes = prependToList(attributes, kMimeTypeName, aMimeType);
-    }
-    
-    return attributes;
+  nsAutoString aW3CDocType;
+  rv = document->GetDocType(aW3CDocType);
+  if (NS_SUCCEEDED(rv))
+    attributes = prependToList(attributes, kDocTypeName, aW3CDocType);
+
+  nsAutoString aMimeType;
+  rv = document->GetMimeType(aMimeType);
+  if (NS_SUCCEEDED(rv))
+    attributes = prependToList(attributes, kMimeTypeName, aMimeType);
+
+  return attributes;
 }
 
 const gchar *
 getDocumentAttributeValueCB(AtkDocument *aDocument,
                             const gchar *aAttrName)
 {
-    nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aDocument));
-    if (!accWrap)
-        return nsnull;
-
-    nsCOMPtr<nsIAccessibleDocument> accDocument;
-    accWrap->QueryInterface(NS_GET_IID(nsIAccessibleDocument),
-                            getter_AddRefs(accDocument));
-    NS_ENSURE_TRUE(accDocument, nsnull);
+  nsAccessibleWrap* accWrap = GetAccessibleWrap(ATK_OBJECT(aDocument));
+  if (!accWrap || !accWrap->IsDoc())
+    return nsnull;
 
-    nsresult rv;
-    nsAutoString attrValue;
-    if (!g_ascii_strcasecmp(aAttrName, kDocTypeName)) {
-        rv = accDocument->GetDocType(attrValue);
-        NS_ENSURE_SUCCESS(rv, nsnull);
-    }
-    else if (!g_ascii_strcasecmp(aAttrName, kDocUrlName)) {
-        rv = accDocument->GetURL(attrValue);
-        NS_ENSURE_SUCCESS(rv, nsnull);
-    }
-    else if (!g_ascii_strcasecmp(aAttrName, kMimeTypeName)) {
-        rv = accDocument->GetMimeType(attrValue);
-        NS_ENSURE_SUCCESS(rv, nsnull);
-    }
-    else {
-        return nsnull;
-    }
-    return nsAccessibleWrap::ReturnString(attrValue);
+  nsDocAccessible* document = accWrap->AsDoc();
+  nsresult rv;
+  nsAutoString attrValue;
+  if (!strcasecmp(aAttrName, kDocTypeName))
+    rv = document->GetDocType(attrValue);
+  else if (!strcasecmp(aAttrName, kDocUrlName))
+    rv = document->GetURL(attrValue);
+  else if (!strcasecmp(aAttrName, kMimeTypeName))
+    rv = document->GetMimeType(attrValue);
+  else
+    return nsnull;
+
+  NS_ENSURE_SUCCESS(rv, nsnull);
+  return attrValue.IsEmpty() ? nsnull : nsAccessibleWrap::ReturnString(attrValue);
 }
+}
--- a/accessible/src/atk/nsMaiInterfaceDocument.h
+++ b/accessible/src/atk/nsMaiInterfaceDocument.h
@@ -36,22 +36,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef __MAI_INTERFACE_DOCUMENT_H__
 #define __MAI_INTERFACE_DOCUMENT_H__
 
 #include "nsMai.h"
-#include "nsIAccessibleDocument.h"
 
 G_BEGIN_DECLS
 
 /* document interface callbacks */
 void documentInterfaceInitCB(AtkDocumentIface *aIface);
-AtkAttributeSet* getDocumentAttributesCB(AtkDocument *aDocument);
-const gchar* getDocumentLocaleCB(AtkDocument *aDocument);
-const gchar* getDocumentAttributeValueCB(AtkDocument *aDocument,
-                                         const gchar *aAttrName);
 
 G_END_DECLS
 
 #endif /* __MAI_INTERFACE_DOCUMENT_H__ */
--- a/accessible/src/atk/nsMaiInterfaceHypertext.cpp
+++ b/accessible/src/atk/nsMaiInterfaceHypertext.cpp
@@ -33,17 +33,16 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsMaiInterfaceHypertext.h"
-#include "nsIAccessibleDocument.h"
 #include "nsHyperTextAccessible.h"
 
 void
 hypertextInterfaceInitCB(AtkHypertextIface *aIface)
 {
     g_return_if_fail(aIface != NULL);
 
     aIface->get_link = getLinkCB;
--- a/accessible/src/base/nsAccUtils.cpp
+++ b/accessible/src/base/nsAccUtils.cpp
@@ -603,25 +603,22 @@ nsAccUtils::GetLiveAttrValue(PRUint32 aR
   return false;
 }
 
 #ifdef DEBUG_A11Y
 
 bool
 nsAccUtils::IsTextInterfaceSupportCorrect(nsAccessible *aAccessible)
 {
+  // Don't test for accessible docs, it makes us create accessibles too
+  // early and fire mutation events before we need to
+  if (aAccessible->IsDoc())
+    return true;
+
   bool foundText = false;
-  
-  nsCOMPtr<nsIAccessibleDocument> accDoc = do_QueryObject(aAccessible);
-  if (accDoc) {
-    // Don't test for accessible docs, it makes us create accessibles too
-    // early and fire mutation events before we need to
-    return true;
-  }
-
   PRInt32 childCount = aAccessible->GetChildCount();
   for (PRint32 childIdx = 0; childIdx < childCount; childIdx++) {
     nsAccessible *child = GetChildAt(childIdx);
     if (IsText(child)) {
       foundText = true;
       break;
     }
   }
--- a/accessible/src/base/nsAccUtils.h
+++ b/accessible/src/base/nsAccUtils.h
@@ -36,17 +36,16 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef nsAccUtils_h_
 #define nsAccUtils_h_
 
 #include "nsIAccessible.h"
 #include "nsIAccessNode.h"
-#include "nsIAccessibleDocument.h"
 #include "nsIAccessibleRole.h"
 #include "nsIAccessibleText.h"
 #include "nsIAccessibleTable.h"
 
 #include "nsARIAMap.h"
 #include "nsAccessibilityService.h"
 #include "nsCoreUtils.h"
 
--- a/accessible/src/base/nsAccessNode.cpp
+++ b/accessible/src/base/nsAccessNode.cpp
@@ -42,17 +42,16 @@
 
 #include "nsAccCache.h"
 #include "nsAccUtils.h"
 #include "nsCoreUtils.h"
 
 #include "nsHashtable.h"
 #include "nsAccessibilityService.h"
 #include "nsApplicationAccessibleWrap.h"
-#include "nsIAccessibleDocument.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocument.h"
 #include "nsIDOMCSSPrimitiveValue.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMHTMLElement.h"
 #include "nsIDOMWindow.h"
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -1001,17 +1001,17 @@ nsIFrame* nsAccessible::GetBoundsFrame()
 /* void removeSelection (); */
 NS_IMETHODIMP nsAccessible::SetSelected(bool aSelect)
 {
   // Add or remove selection
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   if (State() & states::SELECTABLE) {
-    nsCOMPtr<nsIAccessible> multiSelect =
+    nsAccessible* multiSelect =
       nsAccUtils::GetMultiSelectableContainer(mContent);
     if (!multiSelect) {
       return aSelect ? TakeFocus() : NS_ERROR_FAILURE;
     }
 
     if (mRoleMapEntry) {
       if (aSelect) {
         return mContent->SetAttr(kNameSpaceID_None,
@@ -1029,22 +1029,21 @@ NS_IMETHODIMP nsAccessible::SetSelected(
 /* void takeSelection (); */
 NS_IMETHODIMP nsAccessible::TakeSelection()
 {
   // Select only this item
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   if (State() & states::SELECTABLE) {
-    nsCOMPtr<nsIAccessible> multiSelect =
+    nsAccessible* multiSelect =
       nsAccUtils::GetMultiSelectableContainer(mContent);
-    if (multiSelect) {
-      nsCOMPtr<nsIAccessibleSelectable> selectable = do_QueryInterface(multiSelect);
-      selectable->ClearSelection();
-    }
+    if (multiSelect)
+      multiSelect->ClearSelection();
+
     return SetSelected(true);
   }
 
   return NS_ERROR_FAILURE;
 }
 
 NS_IMETHODIMP
 nsAccessible::TakeFocus()
--- a/accessible/src/base/nsRootAccessible.h
+++ b/accessible/src/base/nsRootAccessible.h
@@ -36,17 +36,16 @@
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _nsRootAccessible_H_
 #define _nsRootAccessible_H_
 
 #include "nsCaretAccessible.h"
 #include "nsDocAccessibleWrap.h"
 
-#include "nsIAccessibleDocument.h"
 #ifdef MOZ_XUL
 #include "nsXULTreeAccessible.h"
 #endif
 
 #include "nsHashtable.h"
 #include "nsCaretAccessible.h"
 #include "nsIDocument.h"
 #include "nsIDOMEventListener.h"
--- a/accessible/src/msaa/nsAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsAccessibleWrap.cpp
@@ -43,17 +43,16 @@
 #include "nsCoreUtils.h"
 #include "nsWinUtils.h"
 #include "Relation.h"
 #include "Role.h"
 #include "States.h"
 
 #include "ia2AccessibleRelation.h"
 
-#include "nsIAccessibleDocument.h"
 #include "nsIAccessibleEvent.h"
 #include "nsIAccessibleRelation.h"
 #include "nsIAccessibleWin32Object.h"
 
 #include "Accessible2_i.c"
 #include "AccessibleStates.h"
 
 #include "nsIMutableArray.h"
--- a/accessible/src/xul/Makefile.in
+++ b/accessible/src/xul/Makefile.in
@@ -45,16 +45,17 @@ include $(DEPTH)/config/autoconf.mk
 
 MODULE = accessibility
 LIBRARY_NAME = accessibility_xul_s
 LIBXUL_LIBRARY = 1
 
 
 
 CPPSRCS = \
+  XULSelectControlAccessible.cpp \
   nsXULAlertAccessible.cpp \
   nsXULColorPickerAccessible.cpp \
   nsXULComboboxAccessible.cpp \
   nsXULFormControlAccessible.cpp \
   nsXULListboxAccessible.cpp \
   nsXULMenuAccessible.cpp \
   nsXULSliderAccessible.cpp \
   nsXULTabAccessible.cpp \
new file mode 100644
--- /dev/null
+++ b/accessible/src/xul/XULSelectControlAccessible.cpp
@@ -0,0 +1,309 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2012
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Jignesh Kakadiya (jigneshhk1992@gmail.com)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of the GNU General Public License Version 2 or later (the "GPL"),
+ * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "XULSelectControlAccessible.h"
+
+#include "nsAccessibilityService.h"
+#include "nsDocAccessible.h"
+
+#include "nsIDOMXULContainerElement.h"
+#include "nsIDOMXULSelectCntrlItemEl.h"
+#include "nsIDOMXULMultSelectCntrlEl.h"
+#include "nsIDOMKeyEvent.h"
+#include "nsIDOMElement.h"
+#include "nsIDOMXULElement.h"
+#include "nsIMutableArray.h"
+#include "nsIServiceManager.h"
+
+#include "mozilla/dom/Element.h"
+
+using namespace mozilla;
+using namespace mozilla::a11y;
+
+////////////////////////////////////////////////////////////////////////////////
+// XULSelectControlAccessible
+////////////////////////////////////////////////////////////////////////////////
+
+XULSelectControlAccessible::
+  XULSelectControlAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
+  nsAccessibleWrap(aContent, aShell)
+{
+  mSelectControl = do_QueryInterface(aContent);
+}
+
+////////////////////////////////////////////////////////////////////////////////
+// XULSelectControlAccessible: nsAccessNode
+
+void
+XULSelectControlAccessible::Shutdown()
+{
+  mSelectControl = nsnull;
+  nsAccessibleWrap::Shutdown();
+}
+
+////////////////////////////////////////////////////////////////////////////////
+// XULSelectControlAccessible: SelectAccessible
+
+bool
+XULSelectControlAccessible::IsSelect()
+{
+  return !!mSelectControl;
+}
+
+// Interface methods
+already_AddRefed<nsIArray>
+XULSelectControlAccessible::SelectedItems()
+{
+  nsCOMPtr<nsIMutableArray> selectedItems =
+    do_CreateInstance(NS_ARRAY_CONTRACTID);
+  if (!selectedItems)
+    return nsnull;
+
+  // For XUL multi-select control
+  nsCOMPtr<nsIDOMXULMultiSelectControlElement> xulMultiSelect =
+    do_QueryInterface(mSelectControl);
+  if (xulMultiSelect) {
+    PRInt32 length = 0;
+    xulMultiSelect->GetSelectedCount(&length);
+    for (PRInt32 index = 0; index < length; index++) {
+      nsCOMPtr<nsIDOMXULSelectControlItemElement> itemElm;
+      xulMultiSelect->GetSelectedItem(index, getter_AddRefs(itemElm));
+      nsCOMPtr<nsINode> itemNode(do_QueryInterface(itemElm));
+      nsAccessible* item =
+        GetAccService()->GetAccessibleInWeakShell(itemNode, mWeakShell);
+      if (item)
+        selectedItems->AppendElement(static_cast<nsIAccessible*>(item),
+                                     false);
+    }
+  } else {  // Single select?
+      nsCOMPtr<nsIDOMXULSelectControlItemElement> itemElm;
+      mSelectControl->GetSelectedItem(getter_AddRefs(itemElm));
+      nsCOMPtr<nsINode> itemNode(do_QueryInterface(itemElm));
+      if(itemNode) {
+        nsAccessible* item =
+          GetAccService()->GetAccessibleInWeakShell(itemNode, mWeakShell);
+        if (item)
+          selectedItems->AppendElement(static_cast<nsIAccessible*>(item),
+                                     false);
+      }
+    }
+
+  nsIMutableArray* items = nsnull;
+  selectedItems.forget(&items);
+  return items;
+}
+
+nsAccessible*
+XULSelectControlAccessible::GetSelectedItem(PRUint32 aIndex)
+{
+  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
+    do_QueryInterface(mSelectControl);
+
+  nsCOMPtr<nsIDOMXULSelectControlItemElement> itemElm;
+  if (multiSelectControl)
+    multiSelectControl->GetSelectedItem(aIndex, getter_AddRefs(itemElm));
+  else if (aIndex == 0)
+    mSelectControl->GetSelectedItem(getter_AddRefs(itemElm));
+
+  nsCOMPtr<nsINode> itemNode(do_QueryInterface(itemElm));
+  return itemNode ?
+    GetAccService()->GetAccessibleInWeakShell(itemNode, mWeakShell) : nsnull;
+}
+
+PRUint32
+XULSelectControlAccessible::SelectedItemCount()
+{
+  // For XUL multi-select control
+  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
+    do_QueryInterface(mSelectControl);
+  if (multiSelectControl) {
+    PRInt32 count = 0;
+    multiSelectControl->GetSelectedCount(&count);
+    return count;
+  }
+
+  // For XUL single-select control/menulist
+  PRInt32 index;
+  mSelectControl->GetSelectedIndex(&index);
+  return (index >= 0) ? 1 : 0;
+}
+
+bool
+XULSelectControlAccessible::AddItemToSelection(PRUint32 aIndex)
+{
+  nsAccessible* item = GetChildAt(aIndex);
+  if (!item)
+    return false;
+
+  nsCOMPtr<nsIDOMXULSelectControlItemElement> itemElm =
+    do_QueryInterface(item->GetContent());
+  if (!itemElm)
+    return false;
+
+  bool isItemSelected = false;
+  itemElm->GetSelected(&isItemSelected);
+  if (isItemSelected)
+    return true;
+
+  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
+    do_QueryInterface(mSelectControl);
+
+  if (multiSelectControl)
+    multiSelectControl->AddItemToSelection(itemElm);
+  else
+    mSelectControl->SetSelectedItem(itemElm);
+
+  return true;
+}
+
+bool
+XULSelectControlAccessible::RemoveItemFromSelection(PRUint32 aIndex)
+{
+  nsAccessible* item = GetChildAt(aIndex);
+  if (!item)
+    return false;
+
+  nsCOMPtr<nsIDOMXULSelectControlItemElement> itemElm =
+      do_QueryInterface(item->GetContent());
+  if (!itemElm)
+    return false;
+
+  bool isItemSelected = false;
+  itemElm->GetSelected(&isItemSelected);
+  if (!isItemSelected)
+    return true;
+
+  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
+    do_QueryInterface(mSelectControl);
+
+  if (multiSelectControl)
+    multiSelectControl->RemoveItemFromSelection(itemElm);
+  else
+    mSelectControl->SetSelectedItem(nsnull);
+
+  return true;
+}
+
+bool
+XULSelectControlAccessible::IsItemSelected(PRUint32 aIndex)
+{
+  nsAccessible* item = GetChildAt(aIndex);
+  if (!item)
+    return false;
+
+  nsCOMPtr<nsIDOMXULSelectControlItemElement> itemElm =
+    do_QueryInterface(item->GetContent());
+  if (!itemElm)
+    return false;
+
+  bool isItemSelected = false;
+  itemElm->GetSelected(&isItemSelected);
+  return isItemSelected;
+}
+
+bool
+XULSelectControlAccessible::UnselectAll()
+{
+  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
+    do_QueryInterface(mSelectControl);
+  multiSelectControl ?
+    multiSelectControl->ClearSelection() : mSelectControl->SetSelectedIndex(-1);
+
+  return true;
+}
+
+bool
+XULSelectControlAccessible::SelectAll()
+{
+  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
+    do_QueryInterface(mSelectControl);
+  if (multiSelectControl) {
+    multiSelectControl->SelectAll();
+    return true;
+  }
+
+  // otherwise, don't support this method
+  return false;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+// XULSelectControlAccessible: Widgets
+
+nsAccessible*
+XULSelectControlAccessible::CurrentItem()
+{
+  if (!mSelectControl)
+    return nsnull;
+
+  nsCOMPtr<nsIDOMXULSelectControlItemElement> currentItemElm;
+  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
+    do_QueryInterface(mSelectControl);
+  if (multiSelectControl)
+    multiSelectControl->GetCurrentItem(getter_AddRefs(currentItemElm));
+  else
+    mSelectControl->GetSelectedItem(getter_AddRefs(currentItemElm));
+
+  nsCOMPtr<nsINode> DOMNode;
+  if (currentItemElm)
+    DOMNode = do_QueryInterface(currentItemElm);
+
+  if (DOMNode) {
+    nsDocAccessible* document = GetDocAccessible();
+    if (document)
+      return document->GetAccessible(DOMNode);
+  }
+
+  return nsnull;
+}
+
+void
+XULSelectControlAccessible::SetCurrentItem(nsAccessible* aItem)
+{
+  if (!mSelectControl)
+    return;
+
+  nsCOMPtr<nsIDOMXULSelectControlItemElement> itemElm =
+    do_QueryInterface(aItem->GetContent());
+  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
+    do_QueryInterface(mSelectControl);
+  if (multiSelectControl)
+    multiSelectControl->SetCurrentItem(itemElm);
+  else
+    mSelectControl->SetSelectedItem(itemElm);
+}
new file mode 100644
--- /dev/null
+++ b/accessible/src/xul/XULSelectControlAccessible.h
@@ -0,0 +1,80 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2012
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Jignesh Kakadiya (jigneshhk1992@gmail.com)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of the GNU General Public License Version 2 or later (the "GPL"),
+ * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef _XULSelectControlAccessible_H_
+#define _XULSelectControlAccessible_H_
+
+#include "nsAccessibleWrap.h"
+#include "nsIDOMXULSelectCntrlEl.h"
+
+/**
+ * The basic implementation of accessible selection for XUL select controls.
+ */
+class XULSelectControlAccessible : public nsAccessibleWrap
+{
+public:
+  XULSelectControlAccessible(nsIContent *aContent, nsIWeakReference *aShell);
+  virtual ~XULSelectControlAccessible() {}
+
+  // nsAccessNode
+  virtual void Shutdown();
+
+  // SelectAccessible
+  virtual bool IsSelect();
+  virtual already_AddRefed<nsIArray> SelectedItems();
+  virtual PRUint32 SelectedItemCount();
+  virtual nsAccessible* GetSelectedItem(PRUint32 aIndex);
+  virtual bool IsItemSelected(PRUint32 aIndex);
+  virtual bool AddItemToSelection(PRUint32 aIndex);
+  virtual bool RemoveItemFromSelection(PRUint32 aIndex);
+  virtual bool SelectAll();
+  virtual bool UnselectAll();
+
+  // Widgets
+  virtual nsAccessible* CurrentItem();
+  virtual void SetCurrentItem(nsAccessible* aItem);
+
+protected:
+  // nsIDOMXULMultiSelectControlElement inherits from this, so we'll always have
+  // one of these if the widget is valid and not defunct
+  nsCOMPtr<nsIDOMXULSelectControlElement> mSelectControl;
+};
+
+#endif
+
--- a/accessible/src/xul/nsXULFormControlAccessible.cpp
+++ b/accessible/src/xul/nsXULFormControlAccessible.cpp
@@ -554,17 +554,17 @@ nsXULRadioButtonAccessible::ContainerWid
   *   focus whereas the Buttons do not. So we only have an accessible object for
   *   this for the purpose of getting the proper RadioButton. Need this here to 
   *   avoid circular reference problems when navigating the accessible tree and
   *   for getting to the radiobuttons.
   */
 
 nsXULRadioGroupAccessible::
   nsXULRadioGroupAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
-  nsXULSelectableAccessible(aContent, aShell)
+  XULSelectControlAccessible(aContent, aShell)
 { 
 }
 
 role
 nsXULRadioGroupAccessible::NativeRole()
 {
   return roles::GROUPING;
 }
--- a/accessible/src/xul/nsXULFormControlAccessible.h
+++ b/accessible/src/xul/nsXULFormControlAccessible.h
@@ -38,18 +38,18 @@
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _nsXULFormControlAccessible_H_
 #define _nsXULFormControlAccessible_H_
 
 // NOTE: alphabetically ordered
 #include "nsAccessibleWrap.h"
 #include "nsFormControlAccessible.h"
-#include "nsXULMenuAccessible.h"
 #include "nsHyperTextAccessibleWrap.h"
+#include "XULSelectControlAccessible.h"
 
 /**
  * Used for XUL progressmeter element.
  */
 typedef ProgressMeterAccessible<100> XULProgressMeterAccessible;
 
 /**
  * Used for XUL button.
@@ -168,17 +168,17 @@ public:
 
   // Widgets
   virtual nsAccessible* ContainerWidget() const;
 };
 
 /**
  * Used for XUL radiogroup element.
  */
-class nsXULRadioGroupAccessible : public nsXULSelectableAccessible
+class nsXULRadioGroupAccessible : public XULSelectControlAccessible
 {
 public:
   nsXULRadioGroupAccessible(nsIContent *aContent, nsIWeakReference *aShell);
 
   // nsAccessible
   virtual mozilla::a11y::role NativeRole();
   virtual PRUint64 NativeState();
 
@@ -279,10 +279,10 @@ protected:
   // nsHyperTextAccessible
   virtual already_AddRefed<nsFrameSelection> FrameSelection();
 
   // nsXULTextFieldAccessible
   already_AddRefed<nsIContent> GetInputField() const;
 };
 
 
-#endif  
+#endif
 
--- a/accessible/src/xul/nsXULListboxAccessible.cpp
+++ b/accessible/src/xul/nsXULListboxAccessible.cpp
@@ -128,34 +128,34 @@ nsXULColumnItemAccessible::DoAction(PRUi
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULListboxAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULListboxAccessible::
   nsXULListboxAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
-  nsXULSelectableAccessible(aContent, aShell)
+  XULSelectControlAccessible(aContent, aShell)
 {
   nsIContent* parentContent = mContent->GetParent();
   if (parentContent) {
     nsCOMPtr<nsIAutoCompletePopup> autoCompletePopupElm =
       do_QueryInterface(parentContent);
     if (autoCompletePopupElm)
       mFlags |= eAutoCompletePopupAccessible;
   }
 }
 
-NS_IMPL_ADDREF_INHERITED(nsXULListboxAccessible, nsXULSelectableAccessible)
-NS_IMPL_RELEASE_INHERITED(nsXULListboxAccessible, nsXULSelectableAccessible)
+NS_IMPL_ADDREF_INHERITED(nsXULListboxAccessible, XULSelectControlAccessible)
+NS_IMPL_RELEASE_INHERITED(nsXULListboxAccessible, XULSelectControlAccessible)
 
 nsresult
 nsXULListboxAccessible::QueryInterface(REFNSIID aIID, void** aInstancePtr)
 {
-  nsresult rv = nsXULSelectableAccessible::QueryInterface(aIID, aInstancePtr);
+  nsresult rv = XULSelectControlAccessible::QueryInterface(aIID, aInstancePtr);
   if (*aInstancePtr)
     return rv;
 
   if (aIID.Equals(NS_GET_IID(nsIAccessibleTable)) && IsMulticolumn()) {
     *aInstancePtr = static_cast<nsIAccessibleTable*>(this);
     NS_ADDREF_THIS();
     return NS_OK;
   }
--- a/accessible/src/xul/nsXULListboxAccessible.h
+++ b/accessible/src/xul/nsXULListboxAccessible.h
@@ -40,16 +40,17 @@
 #ifndef __nsXULListboxAccessible_h__
 #define __nsXULListboxAccessible_h__
 
 #include "nsIAccessibleTable.h"
 
 #include "nsCOMPtr.h"
 #include "nsXULMenuAccessible.h"
 #include "nsBaseWidgetAccessible.h"
+#include "XULSelectControlAccessible.h"
 
 class nsIWeakReference;
 
 /**
  * nsXULColumnsAccessible are accessible for list and tree columns elements
  * (xul:treecols and xul:listcols).
  */
 class nsXULColumnsAccessible : public nsAccessibleWrap
@@ -83,17 +84,17 @@ public:
   virtual PRUint8 ActionCount();
 
   enum { eAction_Click = 0 };
 };
 
 /*
  * A class the represents the XUL Listbox widget.
  */
-class nsXULListboxAccessible : public nsXULSelectableAccessible,
+class nsXULListboxAccessible : public XULSelectControlAccessible,
                                public nsIAccessibleTable
 {
 public:
   nsXULListboxAccessible(nsIContent *aContent, nsIWeakReference *aShell);
   virtual ~nsXULListboxAccessible() {}
 
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_NSIACCESSIBLETABLE
--- a/accessible/src/xul/nsXULMenuAccessible.cpp
+++ b/accessible/src/xul/nsXULMenuAccessible.cpp
@@ -62,269 +62,16 @@
 #include "mozilla/Preferences.h"
 #include "mozilla/LookAndFeel.h"
 #include "mozilla/dom/Element.h"
 
 using namespace mozilla;
 using namespace mozilla::a11y;
 
 ////////////////////////////////////////////////////////////////////////////////
-// nsXULSelectableAccessible
-////////////////////////////////////////////////////////////////////////////////
-
-nsXULSelectableAccessible::
-  nsXULSelectableAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
-  nsAccessibleWrap(aContent, aShell)
-{
-  mSelectControl = do_QueryInterface(aContent);
-}
-
-////////////////////////////////////////////////////////////////////////////////
-// nsXULSelectableAccessible: nsAccessNode
-
-void
-nsXULSelectableAccessible::Shutdown()
-{
-  mSelectControl = nsnull;
-  nsAccessibleWrap::Shutdown();
-}
-
-////////////////////////////////////////////////////////////////////////////////
-// nsXULSelectableAccessible: SelectAccessible
-
-bool
-nsXULSelectableAccessible::IsSelect()
-{
-  return !!mSelectControl;
-}
-
-// Interface methods
-already_AddRefed<nsIArray>
-nsXULSelectableAccessible::SelectedItems()
-{
-  nsCOMPtr<nsIMutableArray> selectedItems =
-    do_CreateInstance(NS_ARRAY_CONTRACTID);
-  if (!selectedItems)
-    return nsnull;
-
-  // For XUL multi-select control
-  nsCOMPtr<nsIDOMXULMultiSelectControlElement> xulMultiSelect =
-    do_QueryInterface(mSelectControl);
-  if (xulMultiSelect) {
-    PRInt32 length = 0;
-    xulMultiSelect->GetSelectedCount(&length);
-    for (PRInt32 index = 0; index < length; index++) {
-      nsCOMPtr<nsIDOMXULSelectControlItemElement> itemElm;
-      xulMultiSelect->GetSelectedItem(index, getter_AddRefs(itemElm));
-      nsCOMPtr<nsINode> itemNode(do_QueryInterface(itemElm));
-      nsAccessible* item =
-        GetAccService()->GetAccessibleInWeakShell(itemNode, mWeakShell);
-      if (item)
-        selectedItems->AppendElement(static_cast<nsIAccessible*>(item),
-                                     false);
-    }
-  }
-  else {  // Single select?
-    nsCOMPtr<nsIDOMXULSelectControlItemElement> itemElm;
-    mSelectControl->GetSelectedItem(getter_AddRefs(itemElm));
-    nsCOMPtr<nsINode> itemNode(do_QueryInterface(itemElm));
-    if(itemNode) {
-      nsAccessible* item =
-        GetAccService()->GetAccessibleInWeakShell(itemNode, mWeakShell);
-      if (item)
-        selectedItems->AppendElement(static_cast<nsIAccessible*>(item),
-                                     false);
-    }
-  }
-
-  nsIMutableArray* items = nsnull;
-  selectedItems.forget(&items);
-  return items;
-}
-
-nsAccessible*
-nsXULSelectableAccessible::GetSelectedItem(PRUint32 aIndex)
-{
-  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
-    do_QueryInterface(mSelectControl);
-
-  nsCOMPtr<nsIDOMXULSelectControlItemElement> itemElm;
-  if (multiSelectControl)
-    multiSelectControl->GetSelectedItem(aIndex, getter_AddRefs(itemElm));
-  else if (aIndex == 0)
-    mSelectControl->GetSelectedItem(getter_AddRefs(itemElm));
-
-  nsCOMPtr<nsINode> itemNode(do_QueryInterface(itemElm));
-  return itemNode ?
-    GetAccService()->GetAccessibleInWeakShell(itemNode, mWeakShell) : nsnull;
-}
-
-PRUint32
-nsXULSelectableAccessible::SelectedItemCount()
-{
-  // For XUL multi-select control
-  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
-    do_QueryInterface(mSelectControl);
-  if (multiSelectControl) {
-    PRInt32 count = 0;
-    multiSelectControl->GetSelectedCount(&count);
-    return count;
-  }
-
-  // For XUL single-select control/menulist
-  PRInt32 index;
-  mSelectControl->GetSelectedIndex(&index);
-  return (index >= 0) ? 1 : 0;
-}
-
-bool
-nsXULSelectableAccessible::AddItemToSelection(PRUint32 aIndex)
-{
-  nsAccessible* item = GetChildAt(aIndex);
-  if (!item)
-    return false;
-
-  nsCOMPtr<nsIDOMXULSelectControlItemElement> itemElm =
-    do_QueryInterface(item->GetContent());
-  if (!itemElm)
-    return false;
-
-  bool isItemSelected = false;
-  itemElm->GetSelected(&isItemSelected);
-  if (isItemSelected)
-    return true;
-
-  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
-    do_QueryInterface(mSelectControl);
-
-  if (multiSelectControl)
-    multiSelectControl->AddItemToSelection(itemElm);
-  else
-    mSelectControl->SetSelectedItem(itemElm);
-
-  return true;
-}
-
-bool
-nsXULSelectableAccessible::RemoveItemFromSelection(PRUint32 aIndex)
-{
-  nsAccessible* item = GetChildAt(aIndex);
-  if (!item)
-    return false;
-
-  nsCOMPtr<nsIDOMXULSelectControlItemElement> itemElm =
-      do_QueryInterface(item->GetContent());
-  if (!itemElm)
-    return false;
-
-  bool isItemSelected = false;
-  itemElm->GetSelected(&isItemSelected);
-  if (!isItemSelected)
-    return true;
-
-  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
-    do_QueryInterface(mSelectControl);
-
-  if (multiSelectControl)
-    multiSelectControl->RemoveItemFromSelection(itemElm);
-  else
-    mSelectControl->SetSelectedItem(nsnull);
-
-  return true;
-}
-
-bool
-nsXULSelectableAccessible::IsItemSelected(PRUint32 aIndex)
-{
-  nsAccessible* item = GetChildAt(aIndex);
-  if (!item)
-    return false;
-
-  nsCOMPtr<nsIDOMXULSelectControlItemElement> itemElm =
-    do_QueryInterface(item->GetContent());
-  if (!itemElm)
-    return false;
-
-  bool isItemSelected = false;
-  itemElm->GetSelected(&isItemSelected);
-  return isItemSelected;
-}
-
-bool
-nsXULSelectableAccessible::UnselectAll()
-{
-  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
-    do_QueryInterface(mSelectControl);
-  multiSelectControl ?
-    multiSelectControl->ClearSelection() : mSelectControl->SetSelectedIndex(-1);
-
-  return true;
-}
-
-bool
-nsXULSelectableAccessible::SelectAll()
-{
-  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
-    do_QueryInterface(mSelectControl);
-  if (multiSelectControl) {
-    multiSelectControl->SelectAll();
-    return true;
-  }
-
-  // otherwise, don't support this method
-  return false;
-}
-
-////////////////////////////////////////////////////////////////////////////////
-// nsXULSelectableAccessible: Widgets
-
-nsAccessible*
-nsXULSelectableAccessible::CurrentItem()
-{
-  if (!mSelectControl)
-    return nsnull;
-
-  nsCOMPtr<nsIDOMXULSelectControlItemElement> currentItemElm;
-  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
-    do_QueryInterface(mSelectControl);
-  if (multiSelectControl)
-    multiSelectControl->GetCurrentItem(getter_AddRefs(currentItemElm));
-  else
-    mSelectControl->GetSelectedItem(getter_AddRefs(currentItemElm));
-
-  nsCOMPtr<nsINode> DOMNode;
-  if (currentItemElm)
-    DOMNode = do_QueryInterface(currentItemElm);
-
-  if (DOMNode) {
-    nsDocAccessible* document = GetDocAccessible();
-    if (document)
-      return document->GetAccessible(DOMNode);
-  }
-
-  return nsnull;
-}
-
-void
-nsXULSelectableAccessible::SetCurrentItem(nsAccessible* aItem)
-{
-  if (!mSelectControl)
-    return;
-
-  nsCOMPtr<nsIDOMXULSelectControlItemElement> itemElm =
-    do_QueryInterface(aItem->GetContent());
-  nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
-    do_QueryInterface(mSelectControl);
-  if (multiSelectControl)
-    multiSelectControl->SetCurrentItem(itemElm);
-  else
-    mSelectControl->SetSelectedItem(itemElm);
-}
-
-////////////////////////////////////////////////////////////////////////////////
 // nsXULMenuitemAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULMenuitemAccessible::
   nsXULMenuitemAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
 }
@@ -703,17 +450,17 @@ nsXULMenuSeparatorAccessible::ActionCoun
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULMenupopupAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULMenupopupAccessible::
   nsXULMenupopupAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
-  nsXULSelectableAccessible(aContent, aShell)
+  XULSelectControlAccessible(aContent, aShell)
 {
   nsMenuPopupFrame* menuPopupFrame = do_QueryFrame(GetFrame());
   if (menuPopupFrame && menuPopupFrame->IsMenu())
     mFlags |= eMenuPopupAccessible;
 
   // May be the anonymous <menupopup> inside <menulist> (a combobox)
   mSelectControl = do_QueryInterface(mContent->GetParent());
 }
--- a/accessible/src/xul/nsXULMenuAccessible.h
+++ b/accessible/src/xul/nsXULMenuAccessible.h
@@ -36,49 +36,17 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _nsXULMenuAccessible_H_
 #define _nsXULMenuAccessible_H_
 
 #include "nsAccessibleWrap.h"
 #include "nsIDOMXULSelectCntrlEl.h"
-
-/**
- * The basic implementation of SelectAccessible for XUL select controls.
- */
-class nsXULSelectableAccessible : public nsAccessibleWrap
-{
-public:
-  nsXULSelectableAccessible(nsIContent *aContent, nsIWeakReference *aShell);
-  virtual ~nsXULSelectableAccessible() {}
-
-  // nsAccessNode
-  virtual void Shutdown();
-
-  // SelectAccessible
-  virtual bool IsSelect();
-  virtual already_AddRefed<nsIArray> SelectedItems();
-  virtual PRUint32 SelectedItemCount();
-  virtual nsAccessible* GetSelectedItem(PRUint32 aIndex);
-  virtual bool IsItemSelected(PRUint32 aIndex);
-  virtual bool AddItemToSelection(PRUint32 aIndex);
-  virtual bool RemoveItemFromSelection(PRUint32 aIndex);
-  virtual bool SelectAll();
-  virtual bool UnselectAll();
-
-  // Widgets
-  virtual nsAccessible* CurrentItem();
-  virtual void SetCurrentItem(nsAccessible* aItem);
-
-protected:
-  // nsIDOMXULMultiSelectControlElement inherits from this, so we'll always have
-  // one of these if the widget is valid and not defunct
-  nsCOMPtr<nsIDOMXULSelectControlElement> mSelectControl;
-};
+#include "XULSelectControlAccessible.h"
 
 /**
  * Used for XUL menu, menuitem elements.
  */
 class nsXULMenuitemAccessible : public nsAccessibleWrap
 {
 public:
   enum { eAction_Click = 0 };
@@ -131,17 +99,17 @@ public:
   // ActionAccessible
   virtual PRUint8 ActionCount();
 };
 
 
 /**
  * Used for XUL menupopup and panel.
  */
-class nsXULMenupopupAccessible : public nsXULSelectableAccessible
+class nsXULMenupopupAccessible : public XULSelectControlAccessible
 {
 public:
   nsXULMenupopupAccessible(nsIContent *aContent, nsIWeakReference *aShell);
 
   // nsAccessible
   virtual nsresult GetNameInternal(nsAString& aName);
   virtual mozilla::a11y::role NativeRole();
   virtual PRUint64 NativeState();
@@ -169,9 +137,9 @@ public:
 
   // Widget
   virtual bool IsActiveWidget() const;
   virtual bool AreItemsOperable() const;
   virtual nsAccessible* CurrentItem();
   virtual void SetCurrentItem(nsAccessible* aItem);
 };
 
-#endif  
+#endif
--- a/accessible/src/xul/nsXULTabAccessible.cpp
+++ b/accessible/src/xul/nsXULTabAccessible.cpp
@@ -174,17 +174,17 @@ nsXULTabAccessible::GetPositionAndSizeIn
 
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTabsAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULTabsAccessible::
   nsXULTabsAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
-  nsXULSelectableAccessible(aContent, aShell)
+  XULSelectControlAccessible(aContent, aShell)
 {
 }
 
 role
 nsXULTabsAccessible::NativeRole()
 {
   return roles::PAGETABLIST;
 }
--- a/accessible/src/xul/nsXULTabAccessible.h
+++ b/accessible/src/xul/nsXULTabAccessible.h
@@ -37,16 +37,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _nsXULTabAccessible_H_
 #define _nsXULTabAccessible_H_
 
 // NOTE: alphabetically ordered
 #include "nsBaseWidgetAccessible.h"
 #include "nsXULMenuAccessible.h"
+#include "XULSelectControlAccessible.h"
 
 /**
  * An individual tab, xul:tab element.
  */
 class nsXULTabAccessible : public nsAccessibleWrap
 {
 public:
   enum { eAction_Switch = 0 };
@@ -67,17 +68,17 @@ public:
   // ActionAccessible
   virtual PRUint8 ActionCount();
 };
 
 
 /**
  * A container of tab objects, xul:tabs element.
  */
-class nsXULTabsAccessible : public nsXULSelectableAccessible
+class nsXULTabsAccessible : public XULSelectControlAccessible
 {
 public:
   nsXULTabsAccessible(nsIContent *aContent, nsIWeakReference *aShell);
 
   // nsIAccessible
   NS_IMETHOD GetValue(nsAString& _retval);
 
   // nsAccessible
--- a/accessible/tests/mochitest/events/Makefile.in
+++ b/accessible/tests/mochitest/events/Makefile.in
@@ -40,32 +40,32 @@ DEPTH		= ../../../..
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 relativesrcdir  = accessible/events
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
+# test_docload.xul, docload_wnd.xul, test_scroll.xul disabled for misusing <tabbrowser> (bug 715857)
+
 _TEST_FILES =\
 		docload_wnd.html \
-		docload_wnd.xul \
 		focus.html \
 		scroll.html \
 		test_aria_alert.html \
 		test_aria_menu.html \
 		test_aria_objattr.html \
 		test_aria_statechange.html \
 		test_attrs.html \
 		test_caretmove.html \
 		test_caretmove.xul \
 		test_coalescence.html \
 		test_contextmenu.html \
 		test_docload.html \
-		test_docload.xul \
 		test_dragndrop.html \
 		test_flush.html \
 		test_focus_aria_activedescendant.html \
 		test_focus_autocomplete.xul \
 		test_focus_browserui.xul \
 		test_focus_contextmenu.xul \
 		test_focus_controls.html \
 		test_focus_dialog.html \
@@ -76,17 +76,16 @@ include $(topsrcdir)/config/rules.mk
 		test_focus_menu.xul \
 		test_focus_name.html \
 		test_focus_selects.html \
 		test_focus_tabbox.xul \
 		test_focus_tree.xul \
 		test_menu.xul \
 		test_mutation.html \
 		test_mutation.xhtml \
-		test_scroll.xul \
 		test_selection_aria.html \
 		test_selection.html \
 		test_selection.xul \
 		test_statechange.html \
 		test_text_alg.html \
 		test_text.html \
 		test_textattrchange.html \
 		test_tree.xul \
--- a/accessible/tests/mochitest/events/test_focus_browserui.xul
+++ b/accessible/tests/mochitest/events/test_focus_browserui.xul
@@ -17,16 +17,18 @@
           src="../role.js"></script>
   <script type="application/javascript"
           src="../states.js"></script>
   <script type="application/javascript"
           src="../events.js"></script>
 
   <script type="application/javascript">
   <![CDATA[
+    Components.utils.import("resource://gre/modules/Services.jsm");
+
     ////////////////////////////////////////////////////////////////////////////
     // Helpers
 
     function tabBrowser()
     {
       return gBrowserWnd.gBrowser;
     }
 
@@ -92,18 +94,18 @@
     // Testing
 
     var gInputDocURI = "data:text/html,<html><input id='input'></html>";
     var gButtonDocURI = "data:text/html,<html><input id='input' type='button' value='button'></html>";
 
     var gBrowserWnd = null;
     function loadBrowser()
     {
-      gBrowserWnd = window.openDialog("chrome://browser/content/", "_blank",
-                                      "chrome,all,dialog=no", gInputDocURI);
+      gBrowserWnd = window.openDialog(Services.prefs.getCharPref("browser.chromeURL"),
+                                      "_blank", "chrome,all,dialog=no", gInputDocURI);
 
       addA11yLoadEvent(startTests, gBrowserWnd);
     }
 
     function startTests()
     {
       // Wait for tab load.
       var browser = gBrowserWnd.gBrowser.selectedBrowser;
--- a/accessible/tests/mochitest/name/Makefile.in
+++ b/accessible/tests/mochitest/name/Makefile.in
@@ -40,26 +40,26 @@ DEPTH		= ../../../..
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 relativesrcdir  = accessible/name
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
+# test_nsRootAcc.xul, nsRootAcc_wnd.xul disabled for misusing <tabbrowser> (bug 715857)
+
 _TEST_FILES =\
 		general.css \
 		general.xbl \
 		markup.js \
-		nsRootAcc_wnd.xul \
 		test_button.html \
 		test_general.html \
 		test_general.xul \
 		test_link.html \
 		test_list.html \
 		test_markup.html \
-		test_nsRootAcc.xul \
 		test_tree.xul \
 		markuprules.xml \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/a11y/$(relativesrcdir)
--- a/accessible/tests/mochitest/relations/Makefile.in
+++ b/accessible/tests/mochitest/relations/Makefile.in
@@ -40,18 +40,19 @@ DEPTH		= ../../../..
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 relativesrcdir  = accessible/relations
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
+# test_tabbrowser.xul disabled for misusing <tabbrowser> (bug 715857)
+
 _TEST_FILES =\
 		test_general.html \
 		test_general.xul \
-		test_tabbrowser.xul \
 		test_tree.xul \
 		test_update.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/a11y/$(relativesrcdir)
--- a/accessible/tests/mochitest/tree/Makefile.in
+++ b/accessible/tests/mochitest/tree/Makefile.in
@@ -40,16 +40,18 @@ DEPTH		= ../../../..
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 relativesrcdir  = accessible/tree
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
+# test_tabbrowser.xul disabled for misusing <tabbrowser> (bug 715857)
+
 _TEST_FILES =\
 		dockids.html \
 	$(warning test_applicationacc.xul temporarily disabled, see bug 561508) \
 		test_aria_globals.html \
 		test_aria_imgmap.html \
 		test_aria_presentation.html \
 		test_button.xul \
 		test_canvas.html \
@@ -65,17 +67,16 @@ include $(topsrcdir)/config/rules.mk
 		test_iframe.html \
 		test_img.html \
 		test_invalidationlist.html \
 		test_list.html \
 		test_map.html \
 		test_media.html \
 		test_select.html \
 		test_tabbox.xul \
-		test_tabbrowser.xul \
 		test_table.html \
 		test_tree.xul \
 		test_txtcntr.html \
 		test_txtctrl.html \
 		test_txtctrl.xul \
 		wnd.xul \
 		$(NULL)
 
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -232,17 +232,17 @@ pref("lightweightThemes.update.enabled",
 pref("keyword.enabled", true);
 // Override the default keyword.URL. Empty value means
 // "use the search service's default engine"
 pref("keyword.URL", "");
 
 pref("general.useragent.locale", "@AB_CD@");
 pref("general.skins.selectedSkin", "classic/1.0");
 
-pref("general.smoothScroll", false);
+pref("general.smoothScroll", true);
 #ifdef UNIX_BUT_NOT_MAC
 pref("general.autoScroll", false);
 #else
 pref("general.autoScroll", true);
 #endif
 
 // Whether or not the application should check at startup each time if it 
 // is the default browser.
@@ -867,17 +867,17 @@ pref("browser.zoom.siteSpecific", true);
 
 // Whether or not to update background tabs to the current zoom level.
 pref("browser.zoom.updateBackgroundTabs", true);
 
 // The breakpad report server to link to in about:crashes
 pref("breakpad.reportURL", "http://crash-stats.mozilla.com/report/index/");
 
 // base URL for web-based support pages
-pref("app.support.baseURL", "http://support.mozilla.com/1/firefox/%VERSION%/%OS%/%LOCALE%/");
+pref("app.support.baseURL", "http://support.mozilla.org/1/firefox/%VERSION%/%OS%/%LOCALE%/");
 
 // Name of alternate about: page for certificate errors (when undefined, defaults to about:neterror)
 pref("security.alternate_certificate_error_page", "certerror");
 
 // Whether to start the private browsing mode at application startup
 pref("browser.privatebrowsing.autostart", false);
 
 // Whether we should skip prompting before starting the private browsing mode
@@ -1028,19 +1028,16 @@ pref("devtools.inspector.enabled", true)
 pref("devtools.inspector.htmlHeight", 112);
 
 // Enable the style inspector
 pref("devtools.styleinspector.enabled", true);
 
 // Enable the Tilt inspector
 pref("devtools.tilt.enabled", true);
 
-// Enable the Tilt inspector even if WebGL capabilities are not detected
-pref("devtools.tilt.force-enabled", false);
-
 // Enable the rules view
 pref("devtools.ruleview.enabled", true);
 
 // Enable the Scratchpad tool.
 pref("devtools.scratchpad.enabled", true);
 
 // Enable the Style Editor.
 pref("devtools.styleeditor.enabled", true);
--- a/browser/base/content/browser-appmenu.inc
+++ b/browser/base/content/browser-appmenu.inc
@@ -336,16 +336,23 @@
                       command="Browser:ShowAllHistory"
                       key="showAllHistoryKb"/>
             <menuseparator/>
             <menuitem id="appmenu_sanitizeHistory"
                       label="&clearRecentHistory.label;"
                       key="key_sanitize"
                       command="Tools:Sanitize"/>
             <menuseparator class="hide-if-empty-places-result"/>
+#ifdef MOZ_SERVICES_SYNC
+            <menuitem id="appmenu_sync-tabs"
+                      class="syncTabsMenuItem"
+                      label="&syncTabsMenu.label;"
+                      oncommand="BrowserOpenSyncTabs();"
+                      disabled="true"/>
+#endif
             <menuitem id="appmenu_restoreLastSession"
                       class="restoreLastSession"
                       label="&historyRestoreLastSession.label;"
                       oncommand="restoreLastSession();"
                       disabled="true"/>
             <menu id="appmenu_recentlyClosedTabsMenu"
                   class="recentlyClosedTabsMenu"
                   label="&historyUndoMenu.label;"
--- a/browser/base/content/browser-syncui.js
+++ b/browser/base/content/browser-syncui.js
@@ -85,26 +85,18 @@ let gSyncUI = {
     if (gBrowser) {
       this._obs.push("weave:notification:added");
     }
 
     this._obs.forEach(function(topic) {
       Services.obs.addObserver(this, topic, true);
     }, this);
 
-    // Find the alltabs-popup, only if there is a gBrowser
-    if (gBrowser) {
-      let popup = document.getElementById("alltabs-popup");
-      if (popup) {
-        popup.addEventListener(
-          "popupshowing", this.alltabsPopupShowing.bind(this), true);
-      }
-
-      if (Weave.Notifications.notifications.length)
-        this.initNotifications();
+    if (gBrowser && Weave.Notifications.notifications.length) {
+      this.initNotifications();
     }
     this.updateUI();
   },
 
   initNotifications: function SUI_initNotifications() {
     const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
     let notificationbox = document.createElementNS(XULNS, "notificationbox");
     notificationbox.id = "sync-notifications";
@@ -144,44 +136,16 @@ let gSyncUI = {
       return;
 
     button.removeAttribute("status");
     this._updateLastSyncTime();
     if (needsSetup)
       button.removeAttribute("tooltiptext");
   },
 
-  alltabsPopupShowing: function(event) {
-    // Should we show the menu item?
-    //XXXphilikon We should remove the check for isLoggedIn here and have
-    //            about:sync-tabs auto-login (bug 583344)
-    if (!Weave.Service.isLoggedIn || !Weave.Engines.get("tabs").enabled)
-      return;
-
-    let label = this._stringBundle.GetStringFromName("tabs.fromOtherComputers.label");
-
-    let popup = document.getElementById("alltabs-popup");
-    if (!popup)
-      return;
-
-    let menuitem = document.createElement("menuitem");
-    menuitem.setAttribute("id", "sync-tabs-menuitem");
-    menuitem.setAttribute("label", label);
-    menuitem.setAttribute("class", "alltabs-item");
-    menuitem.setAttribute("oncommand", "BrowserOpenSyncTabs();");
-
-    // Fake the tab object on the menu entries, so that we don't have to worry
-    // about removing them ourselves. They will just get cleaned up by popup
-    // binding.
-    menuitem.tab = { "linkedBrowser": { "currentURI": { "spec": label } } };
-
-    let sep = document.getElementById("alltabs-popup-separator");
-    popup.insertBefore(menuitem, sep);
-  },
-
 
   // Functions called by observers
   onActivityStart: function SUI_onActivityStart() {
     if (!gBrowser)
       return;
 
     let button = document.getElementById("sync-button");
     if (!button)
--- a/browser/base/content/browser.css
+++ b/browser/base/content/browser.css
@@ -474,16 +474,17 @@ browser[tabmodalPromptShowing] {
 /* Status panel */
 
 statuspanel {
   -moz-binding: url("chrome://browser/content/tabbrowser.xml#statuspanel");
   position: fixed;
   margin-top: -3em;
   left: 0;
   max-width: 50%;
+  pointer-events: none;
 }
 
 statuspanel:-moz-locale-dir(ltr)[mirror],
 statuspanel:-moz-locale-dir(rtl):not([mirror]) {
   left: auto;
   right: 0;
 }
 
@@ -500,17 +501,16 @@ statuspanel[type=status] {
 statuspanel[type=overLink] {
   -moz-transition: opacity 120ms ease-out;
   direction: ltr;
 }
 
 statuspanel[inactive] {
   -moz-transition: none;
   opacity: 0;
-  pointer-events: none;
 }
 
 statuspanel[inactive][previoustype=overLink] {
   -moz-transition: opacity 200ms ease-out;
 }
 
 .statuspanel-inner {
   height: 3em;
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -1696,16 +1696,22 @@ function delayedStartup(isLoadingBlank, 
 
 #ifdef MOZ_SERVICES_SYNC
   // initialize the sync UI
   gSyncUI.init();
 #endif
 
   TabView.init();
 
+  setUrlAndSearchBarWidthForConditionalForwardButton();
+  window.addEventListener("resize", function resizeHandler(event) {
+    if (event.target == window)
+      setUrlAndSearchBarWidthForConditionalForwardButton();
+  });
+
   // Enable Inspector?
   let enabled = gPrefService.getBoolPref("devtools.inspector.enabled");
   if (enabled) {
     document.getElementById("menu_pageinspect").hidden = false;
     document.getElementById("Tools:Inspect").removeAttribute("disabled");
 #ifdef MENUBAR_CAN_AUTOHIDE
     document.getElementById("appmenu_pageInspect").hidden = false;
 #endif
@@ -1746,16 +1752,19 @@ function delayedStartup(isLoadingBlank, 
   // If the user (or the locale) hasn't enabled the top-level "Character
   // Encoding" menu via the "browser.menu.showCharacterEncoding" preference,
   // hide it.
   if ("true" != gPrefService.getComplexValue("browser.menu.showCharacterEncoding",
                                              Ci.nsIPrefLocalizedString).data)
     document.getElementById("appmenu_charsetMenu").hidden = true;
 #endif
 
+  window.addEventListener("mousemove", MousePosTracker, false);
+  window.addEventListener("dragover", MousePosTracker, false);
+
   Services.obs.notifyObservers(window, "browser-delayed-startup-finished", "");
 }
 
 function BrowserShutdown() {
   // In certain scenarios it's possible for unload to be fired before onload,
   // (e.g. if the window is being closed after browser.js loads but before the
   // load completes). In that case, there's nothing to do here.
   if (!gStartupRan)
@@ -2602,16 +2611,34 @@ function UpdateUrlbarSearchSplitterState
       splitter.setAttribute("resizeafter", "flex");
       splitter.className = "chromeclass-toolbar-additional";
     }
     urlbar.parentNode.insertBefore(splitter, ibefore);
   } else if (splitter)
     splitter.parentNode.removeChild(splitter);
 }
 
+function setUrlAndSearchBarWidthForConditionalForwardButton() {
+  // Workaround for bug 694084: Showing/hiding the conditional forward button resizes
+  // the search bar when the url/search bar splitter hasn't been used.
+  var urlbarContainer = document.getElementById("urlbar-container");
+  var searchbarContainer = document.getElementById("search-container");
+  if (!urlbarContainer ||
+      !searchbarContainer ||
+      urlbarContainer.hasAttribute("width") ||
+      searchbarContainer.hasAttribute("width") ||
+      urlbarContainer.parentNode != searchbarContainer.parentNode)
+    return;
+  urlbarContainer.style.width = searchbarContainer.style.width = "";
+  var urlbarWidth = urlbarContainer.clientWidth;
+  var searchbarWidth = searchbarContainer.clientWidth;
+  urlbarContainer.style.width = urlbarWidth + "px";
+  searchbarContainer.style.width = searchbarWidth + "px";
+}
+
 function UpdatePageProxyState()
 {
   if (gURLBar && gURLBar.value != gLastValidURLStr)
     SetPageProxyState("invalid");
 }
 
 function SetPageProxyState(aState)
 {
@@ -3727,16 +3754,17 @@ function BrowserToolboxCustomizeDone(aTo
 
   PlacesToolbarHelper.customizeDone();
   BookmarksMenuButton.customizeDone();
 
   // The url bar splitter state is dependent on whether stop/reload
   // and the location bar are combined, so we need this ordering
   CombinedStopReload.init();
   UpdateUrlbarSearchSplitterState();
+  setUrlAndSearchBarWidthForConditionalForwardButton();
 
   // Update the urlbar
   if (gURLBar) {
     URLBarSetURI();
     XULBrowserWindow.asyncUpdateUI();
     PlacesStarButton.updateState();
   }
 
@@ -3902,23 +3930,20 @@ var FullScreen = {
       this._shouldAnimate = !document.mozFullScreen;
       this.mouseoverToggle(false);
 
       // Autohide prefs
       gPrefService.addObserver("browser.fullscreen", this, false);
     }
     else {
       // The user may quit fullscreen during an animation
-      window.mozCancelAnimationFrame(this._animationHandle);
-      this._animationHandle = 0;
-      clearTimeout(this._animationTimeout);
+      this._cancelAnimation();
       gNavToolbox.style.marginTop = "";
       if (this._isChromeCollapsed)
         this.mouseoverToggle(true);
-      this._isAnimating = false;
       // This is needed if they use the context menu to quit fullscreen
       this._isPopupOpen = false;
 
       this.cleanup();
     }
   },
 
   exitDomFullScreen : function(e) {
@@ -3969,20 +3994,17 @@ var FullScreen = {
     gBrowser.tabContainer.addEventListener("TabClose", this.exitDomFullScreen);
     gBrowser.tabContainer.addEventListener("TabSelect", this.exitDomFullScreen);
 
     // Exit DOM full-screen mode when the browser window loses focus (ALT+TAB, etc).
     window.addEventListener("deactivate", this.exitDomFullScreen, true);
 
     // Cancel any "hide the toolbar" animation which is in progress, and make
     // the toolbar hide immediately.
-    clearInterval(this._animationInterval);
-    clearTimeout(this._animationTimeout);
-    this._isAnimating = false;
-    this._shouldAnimate = false;
+    this._cancelAnimation();
     this.mouseoverToggle(false);
 
     // If there's a full-screen toggler, remove its listeners, so that mouseover
     // the top of the screen will not cause the toolbar to re-appear.
     let fullScrToggler = document.getElementById("fullscr-toggler");
     if (fullScrToggler) {
       fullScrToggler.removeEventListener("mouseover", this._expandCallback, false);
       fullScrToggler.removeEventListener("dragenter", this._expandCallback, false);
@@ -4117,29 +4139,34 @@ var FullScreen = {
   sample: function (timeStamp) {
     const duration = 1500;
     const timePassed = timeStamp - this._animateStartTime;
     const pos = timePassed >= duration ? 1 :
                 1 - Math.pow(1 - timePassed / duration, 4);
 
     if (pos >= 1) {
       // We've animated enough
-      window.mozCancelAnimationFrame(this._animationHandle);
+      this._cancelAnimation();
       gNavToolbox.style.marginTop = "";
-      this._animationHandle = 0;
-      this._isAnimating = false;
-      this._shouldAnimate = false; // Just to make sure
       this.mouseoverToggle(false);
       return;
     }
 
     gNavToolbox.style.marginTop = (gNavToolbox.boxObject.height * pos * -1) + "px";
     this._animationHandle = window.mozRequestAnimationFrame(this);
   },
 
+  _cancelAnimation: function() {
+    window.mozCancelAnimationFrame(this._animationHandle);
+    this._animationHandle = 0;
+    clearTimeout(this._animationTimeout);
+    this._isAnimating = false;
+    this._shouldAnimate = false;
+  },
+
   cancelWarning: function(event) {
     if (!this.warningBox) {
       return;
     }
     if (this.onWarningHidden) {
       this.warningBox.removeEventListener("transitionend", this.onWarningHidden, false);
       this.onWarningHidden = null;
     }
@@ -5455,17 +5482,17 @@ function updateAppButtonDisplay() {
     !gInPrintPreviewMode &&
     window.menubar.visible &&
     document.getElementById("toolbar-menubar").getAttribute("autohide") == "true";
 
 #ifdef CAN_DRAW_IN_TITLEBAR
   document.getElementById("titlebar").hidden = !displayAppButton;
 
   if (displayAppButton)
-    document.documentElement.setAttribute("chromemargin", "0,-1,-1,-1");
+    document.documentElement.setAttribute("chromemargin", "0,2,2,2");
   else
     document.documentElement.removeAttribute("chromemargin");
 
   TabsInTitlebar.allowedBy("drawing-in-titlebar", displayAppButton);
 #else
   document.getElementById("appmenu-toolbar-button").hidden =
     !displayAppButton;
 #endif
@@ -9051,15 +9078,78 @@ XPCOMUtils.defineLazyGetter(window, "gSh
   let sysInfo = Components.classes["@mozilla.org/system-info;1"]
                           .getService(Components.interfaces.nsIPropertyBag2);
   return parseFloat(sysInfo.getProperty("version")) < 6;
 #else
   return false;
 #endif
 });
 
+
+var MousePosTracker = {
+  _listeners: [],
+  _x: 0,
+  _y: 0,
+  get _windowUtils() {
+    delete this._windowUtils;
+    return this._windowUtils = window.getInterface(Ci.nsIDOMWindowUtils);
+  },
+
+  addListener: function (listener) {
+    if (this._listeners.indexOf(listener) >= 0)
+      return;
+
+    listener._hover = false;
+    this._listeners.push(listener);
+
+    this._callListener(listener);
+  },
+
+  removeListener: function (listener) {
+    var index = this._listeners.indexOf(listener);
+    if (index < 0)
+      return;
+
+    this._listeners.splice(index, 1);
+  },
+
+  handleEvent: function (event) {
+    var screenPixelsPerCSSPixel = this._windowUtils.screenPixelsPerCSSPixel;
+    this._x = event.screenX / screenPixelsPerCSSPixel - window.mozInnerScreenX;
+    this._y = event.screenY / screenPixelsPerCSSPixel - window.mozInnerScreenY;
+
+    this._listeners.forEach(function (listener) {
+      try {
+        this._callListener(listener);
+      } catch (e) {
+        Cu.reportError(e);
+      }
+    }, this);
+  },
+
+  _callListener: function (listener) {
+    let rect = listener.getMouseTargetRect();
+    let hover = this._x >= rect.left &&
+                this._x <= rect.right &&
+                this._y >= rect.top &&
+                this._y <= rect.bottom;
+
+    if (hover == listener._hover)
+      return;
+
+    listener._hover = hover;
+
+    if (hover) {
+      if (listener.onMouseEnter)
+        listener.onMouseEnter();
+    } else {
+      if (listener.onMouseLeave)
+        listener.onMouseLeave();
+    }
+  }
+};
 function focusNextFrame(event) {
   let fm = Cc["@mozilla.org/focus-manager;1"].getService(Ci.nsIFocusManager);
   let dir = event.shiftKey ? fm.MOVEFOCUS_BACKWARDDOC : fm.MOVEFOCUS_FORWARDDOC;
   let element = fm.moveFocus(window, null, dir, fm.FLAG_BYKEY);
   if (element.ownerDocument == document)
     focusAndSelectUrlBar();
 }
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -1009,18 +1009,18 @@
                          command="Inspector:Inspect"/>
           <arrowscrollbox id="inspector-breadcrumbs"
                           flex="1" orient="horizontal"
                           clicktoscroll="true"/>
           <hbox id="inspector-tools">
             <toolbarbutton id="inspector-3D-button"
                            class="devtools-toolbarbutton"
                            hidden="true"
-                           label="&inspect3DButton.label;"
-                           accesskey="&inspect3DButton.accesskey;"
+                           label="&inspect3DViewButton.label;"
+                           accesskey="&inspect3DViewButton.accesskey;"
                            command="Inspector:Tilt"/>
             <toolbarbutton id="inspector-style-button"
                            class="devtools-toolbarbutton"
                            label="&inspectStyleButton.label;"
                            accesskey="&inspectStyleButton.accesskey;"
                            command="Inspector:Sidebar"/>
             <!-- registered tools go here -->
           </hbox>
--- a/browser/base/content/syncSetup.xul
+++ b/browser/base/content/syncSetup.xul
@@ -403,16 +403,20 @@
                  accesskey="&syncComputerName.accesskey;"
                  control="syncComputerName"/>
           <textbox id="syncComputerName" flex="1"
                    onchange="gSyncUtils.changeName(this)"/>
         </row>
         <row>
           <label value="&syncMy.label;" />
           <vbox>
+            <checkbox label="&engine.addons.label;"
+                      accesskey="&engine.addons.accesskey;"
+                      id="engine.addons"
+                      checked="true"/>
             <checkbox label="&engine.bookmarks.label;"
                       accesskey="&engine.bookmarks.accesskey;"
                       id="engine.bookmarks"
                       checked="true"/>
             <checkbox label="&engine.passwords.label;"
                       accesskey="&engine.passwords.accesskey;"
                       id="engine.passwords"
                       checked="true"/>
@@ -423,20 +427,16 @@
             <checkbox label="&engine.history.label;"
                       accesskey="&engine.history.accesskey;"
                       id="engine.history"
                       checked="true"/>
             <checkbox label="&engine.tabs.label;"
                       accesskey="&engine.tabs.accesskey;"
                       id="engine.tabs"
                       checked="true"/>
-            <checkbox label="&engine.addons.label;"
-                      accesskey="&engine.addons.accesskey;"
-                      id="engine.addons"
-                      checked="true"/>
           </vbox>
         </row>
       </rows>
     </grid>
     </groupbox>
 
     <groupbox id="mergeOptions">
       <radiogroup id="mergeChoiceRadio" pack="start">
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -2842,21 +2842,19 @@
           let visible = this.visible;
 
           document.getElementById("menu_closeWindow").hidden = !visible;
           document.getElementById("menu_close").setAttribute("label",
             this.tabbrowser.mStringBundle.getString(visible ? "tabs.closeTab" : "tabs.close"));
 
           goSetCommandEnabled("cmd_ToggleTabsOnTop", visible);
 
-          if (window.TabsOnTop)
-            TabsOnTop.syncUI();
-
-          if (window.TabsInTitlebar)
-            TabsInTitlebar.allowedBy("tabs-visible", visible);
+          TabsOnTop.syncUI();
+
+          TabsInTitlebar.allowedBy("tabs-visible", visible);
         ]]></body>
       </method>
 
       <method name="updateVisibility">
         <body><![CDATA[
           if (this.childNodes.length - this.tabbrowser._removingTabs.length == 1)
             this.visible = window.toolbar.visible &&
                            !Services.prefs.getBoolPref("browser.tabs.autoHide");
@@ -4002,20 +4000,23 @@
                    flex="1"
                    crop="end"/>
       </xul:hbox>
     </content>
 
     <implementation implements="nsIDOMEventListener">
       <constructor><![CDATA[
         window.addEventListener("findbaropen", this, false);
+        window.addEventListener("resize", this, false);
       ]]></constructor>
 
       <destructor><![CDATA[
         window.removeEventListener("findbaropen", this, false);
+        window.removeEventListener("resize", this, false);
+        MousePosTracker.removeListener(this);
       ]]></destructor>
 
       <property name="label">
         <setter><![CDATA[
           if (!this.label) {
             if (window.gFindBarInitialized && !window.gFindBar.hidden)
               this.setAttribute("mirror", "true");
             else
@@ -4024,45 +4025,87 @@
 
           this.style.minWidth = this.getAttribute("type") == "status" &&
                                 this.getAttribute("previoustype") == "status"
                                   ? getComputedStyle(this).width : "";
 
           if (val) {
             this.setAttribute("label", val);
             this.removeAttribute("inactive");
+            this._calcMouseTargetRect();
+            MousePosTracker.addListener(this);
           } else {
             this.setAttribute("inactive", "true");
+            MousePosTracker.removeListener(this);
           }
 
           return val;
         ]]></setter>
         <getter>
           return this.hasAttribute("inactive") ? "" : this.getAttribute("label");
         </getter>
       </property>
 
+      <method name="getMouseTargetRect">
+        <body><![CDATA[
+          return this._mouseTargetRect;
+        ]]></body>
+      </method>
+
+      <method name="onMouseEnter">
+        <body>
+          this._mirror();
+        </body>
+      </method>
+
+      <method name="onMouseLeave">
+        <body>
+          this._mirror();
+        </body>
+      </method>
+
       <method name="handleEvent">
         <parameter name="event"/>
         <body><![CDATA[
-          if (event.type == "findbaropen" &&
-              this.label)
-            this.setAttribute("mirror", "true");
+          if (!this.label)
+            return;
+
+          switch (event.type) {
+            case "findbaropen":
+              this.setAttribute("mirror", "true");
+              this._calcMouseTargetRect();
+              break;
+            case "resize":
+              this._calcMouseTargetRect();
+              break;
+          }
+        ]]></body>
+      </method>
+
+      <method name="_calcMouseTargetRect">
+        <body><![CDATA[
+          let alignRight = (window.gFindBarInitialized && !window.gFindBar.hidden);
+
+          if (getComputedStyle(document.documentElement).direction == "rtl")
+            alighRight = !alignRight;
+
+          let rect = this.getBoundingClientRect();
+          this._mouseTargetRect = {
+            top:    rect.top,
+            bottom: rect.bottom,
+            left:   alignRight ? window.innerWidth - rect.width : 0,
+            right:  alignRight ? window.innerWidth : rect.width
+          };
         ]]></body>
       </method>
 
       <method name="_mirror">
         <body>
           if (this.hasAttribute("mirror"))
             this.removeAttribute("mirror");
           else
             this.setAttribute("mirror", "true");
         </body>
       </method>
     </implementation>
-
-    <handlers>
-      <handler event="mouseover" action="this._mirror();"/>
-      <handler event="dragover" action="this._mirror();"/>
-    </handlers>
   </binding>
 
 </bindings>
--- a/browser/components/build/nsModule.cpp
+++ b/browser/components/build/nsModule.cpp
@@ -44,17 +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
 
-#include "nsProfileMigrator.h"
 #if defined(XP_WIN) && !defined(__MINGW32__)
 #include "nsIEProfileMigrator.h"
 #elif defined(XP_MACOSX)
 #include "nsSafariProfileMigrator.h"
 #endif
 
 #include "rdf.h"
 #include "nsFeedSniffer.h"
@@ -72,17 +71,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
 
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsProfileMigrator)
 #if defined(XP_WIN) && !defined(__MINGW32__)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsIEProfileMigrator)
 #elif defined(XP_MACOSX)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsSafariProfileMigrator)
 #endif
 
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsFeedSniffer)
 
@@ -91,17 +89,16 @@ NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsPr
 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);
-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);
 #endif
 NS_DEFINE_NAMED_CID(NS_PRIVATE_BROWSING_SERVICE_WRAPPER_CID);
 
@@ -109,17 +106,16 @@ static const mozilla::Module::CIDEntry k
     { &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 },
-    { &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 },
 #endif
     { &kNS_PRIVATE_BROWSING_SERVICE_WRAPPER_CID, false, NULL, nsPrivateBrowsingServiceWrapperConstructor },
     { NULL }
@@ -143,17 +139,16 @@ static const mozilla::Module::ContractID
     { 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 },
     { NS_ABOUT_MODULE_CONTRACTID_PREFIX "sync-progress", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
 #endif
     { NS_ABOUT_MODULE_CONTRACTID_PREFIX "home", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
     { NS_ABOUT_MODULE_CONTRACTID_PREFIX "permissions", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
-    { 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 },
 #endif
     { NS_PRIVATE_BROWSING_SERVICE_CONTRACTID, &kNS_PRIVATE_BROWSING_SERVICE_WRAPPER_CID },
     { NULL }
--- a/browser/components/migration/src/BrowserProfileMigrators.manifest
+++ b/browser/components/migration/src/BrowserProfileMigrators.manifest
@@ -1,4 +1,6 @@
-component {4cec1de4-1671-4fc3-a53e-6c539dc77a26} ChromeProfileMigrator.js
-contract @mozilla.org/profile/migrator;1?app=browser&type=chrome {4cec1de4-1671-4fc3-a53e-6c539dc77a26}
-component {91185366-ba97-4438-acba-48deaca63386} FirefoxProfileMigrator.js
-contract @mozilla.org/profile/migrator;1?app=browser&type=firefox {91185366-ba97-4438-acba-48deaca63386}
+component {6F8BB968-C14F-4D6F-9733-6C6737B35DCE} ProfileMigrator.js
+contract @mozilla.org/toolkit/profile-migrator;1 {6F8BB968-C14F-4D6F-9733-6C6737B35DCE}
+component {4cec1de4-1671-4fc3-a53e-6c539dc77a26} ChromeProfileMigrator.js
+contract @mozilla.org/profile/migrator;1?app=browser&type=chrome {4cec1de4-1671-4fc3-a53e-6c539dc77a26}
+component {91185366-ba97-4438-acba-48deaca63386} FirefoxProfileMigrator.js
+contract @mozilla.org/profile/migrator;1?app=browser&type=firefox {91185366-ba97-4438-acba-48deaca63386}
--- a/browser/components/migration/src/Makefile.in
+++ b/browser/components/migration/src/Makefile.in
@@ -44,31 +44,31 @@ include $(DEPTH)/config/autoconf.mk
 MODULE		= migration
 LIBRARY_NAME	= migration_s
 FORCE_STATIC_LIB = 1
 ifndef MOZ_MEMORY
 USE_STATIC_LIBS = 1
 endif
 
 
-CPPSRCS  = nsProfileMigrator.cpp \
-           nsBrowserProfileMigratorUtils.cpp \
+CPPSRCS  = nsBrowserProfileMigratorUtils.cpp \
            $(NULL)
 
 ifeq ($(OS_ARCH)_$(GNU_CXX),WINNT_)
 CPPSRCS += nsIEProfileMigrator.cpp \
            $(NULL)
 endif
 
 ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT))
 CPPSRCS += nsSafariProfileMigrator.cpp \
            $(NULL)
 endif            
 
 EXTRA_PP_COMPONENTS = \
+  ProfileMigrator.js \
   ChromeProfileMigrator.js \
   FirefoxProfileMigrator.js \
   $(NULL)
 
 EXTRA_COMPONENTS = \
 	BrowserProfileMigrators.manifest \
 	$(NULL)
 
new file mode 100644
--- /dev/null
+++ b/browser/components/migration/src/ProfileMigrator.js
@@ -0,0 +1,141 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const Cc = Components.classes;
+const Ci = Components.interfaces;
+const Cu = Components.utils;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/FileUtils.jsm");
+
+function ProfileMigrator() {
+}
+
+ProfileMigrator.prototype = {
+  migrate: function PM_migrate(aStartup) {
+    // By opening the wizard with a supplied migrator, it will automatically
+    // migrate from it.
+    let [key, migrator] = this._getDefaultMigrator();
+    if (!key)
+        return;
+
+    let params = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
+    params.appendElement(this._toCString(key), false);
+    params.appendElement(migrator, false);
+    params.appendElement(aStartup, false);
+
+    Services.ww.openWindow(null,
+                           "chrome://browser/content/migration/migration.xul",
+                           "_blank",
+                           "chrome,dialog,modal,centerscreen,titlebar",
+                           params);
+  },
+
+  _toCString: function PM__toCString(aStr) {
+    let cstr = Cc["@mozilla.org/supports-cstring;1"].
+               createInstance(Ci.nsISupportsCString);
+    cstr.data = aStr;
+    return cstr;
+  },
+
+  _getMigratorIfSourceExists: function PM__getMigratorIfSourceExists(aKey) {
+    let cid = "@mozilla.org/profile/migrator;1?app=browser&type=" + aKey;
+    let migrator = Cc[cid].createInstance(Ci.nsIBrowserProfileMigrator);
+    if (migrator.sourceExists)
+      return migrator;
+    return null;
+  },
+
+  // We don't yet support checking for the default browser on all platforms,
+  // needless to say we don't have migrators for all browsers.  Thus, for each
+  // platform, there's a fallback list of migrators used in these cases.
+  _PLATFORM_FALLBACK_LIST:
+#ifdef XP_WIN
+     ["ie", "chrome", /* safari */],
+#elifdef XP_MACOSX
+     ["safari", "chrome"],
+#else
+     ["chrome"],
+#endif
+
+  _getDefaultMigrator: function PM__getDefaultMigrator() {
+    let migratorsOrdered = Array.slice(this._PLATFORM_FALLBACK_LIST);
+    let defaultBrowser = "";
+#ifdef XP_WIN
+    try {
+      const REG_KEY = "SOFTWARE\\Classes\\HTTP\\shell\\open\\command";
+      let regKey = Cc["@mozilla.org/windows-registry-key;1"].
+                   createInstance(Ci.nsIWindowsRegKey);
+      regKey.open(regKey.ROOT_KEY_LOCAL_MACHINE, REG_KEY,
+                  regKey.ACCESS_READ);
+      let value = regKey.readStringValue("").toLowerCase();      
+      let pathMatches = value.match(/^"?(.+?\.exe)"?/);
+      if (!pathMatches) {
+        throw new Error("Could not extract path from " +
+                        REG_KEY + "(" + value + ")");
+      }
+ 
+      // We want to find out what the default browser is but the path in and of
+      // itself isn't enough.  Why? Because sometimes on Windows paths get
+      // truncated like so: C:\PROGRA~1\MOZILL~2\MOZILL~1.EXE.  How do we know
+      // what product that is? Mozilla's file objects do nothing to 'normalize'
+      // the path so we need to attain an actual product descriptor from the
+      // file somehow, and in this case it means getting the "InternalName"
+      // field of the file's VERSIONINFO resource. 
+      //
+      // In the file's resource segment there is a VERSIONINFO section that is
+      // laid out like this:
+      //
+      // VERSIONINFO
+      //   StringFileInfo
+      //     <TranslationID>
+      //       InternalName           "iexplore"
+      //   VarFileInfo
+      //     Translation              <TranslationID>
+      //
+      // By Querying the VERSIONINFO section for its Tranlations, we can find
+      // out where the InternalName lives (A file can have more than one
+      // translation of its VERSIONINFO segment, but we just assume the first
+      // one).
+      let file = FileUtils.File(pathMatches[1])
+                          .QueryInterface(Ci.nsILocalFileWin);
+      switch (file.getVersionInfoField("InternalName").toLowerCase()) {
+        case "iexplore":
+          defaultBrowser = "ie";
+          break;
+        case "chrome":
+          defaultBrowser = "chrome";
+          break;
+      }
+    }
+    catch (ex) {
+      Cu.reportError("Could not retrieve default browser: " + ex);
+    }
+#endif
+
+    // If we found the default browser and we have support for that browser,
+    // make sure to check it before any other browser, by moving it to the head
+    // of the array.
+    if (defaultBrowser)
+      migratorsOrdered.sort(function(a, b) b == defaultBrowser ? 1 : 0);
+
+    for (let i = 0; i < migratorsOrdered.length; i++) {
+      let migrator = this._getMigratorIfSourceExists(migratorsOrdered[i]);
+      if (migrator)
+        return [migratorsOrdered[i], migrator];
+    }
+
+    return ["", null];
+  },
+
+  QueryInterface: XPCOMUtils.generateQI([Ci.nsIProfileMigrator]),
+  classDescription: "Profile Migrator",
+  contractID: "@mozilla.org/toolkit/profile-migrator;1",
+  classID: Components.ID("6F8BB968-C14F-4D6F-9733-6C6737B35DCE")
+};
+
+let NSGetFactory = XPCOMUtils.generateNSGetFactory([ProfileMigrator]);
deleted file mode 100644
--- a/browser/components/migration/src/nsProfileMigrator.cpp
+++ /dev/null
@@ -1,252 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is The Browser Profile Migrator.
- *
- * The Initial Developer of the Original Code is Ben Goodger.
- * Portions created by the Initial Developer are Copyright (C) 2004
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Ben Goodger <ben@bengoodger.com>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#include "nsProfileMigrator.h"
-
-#include "nsIBrowserProfileMigrator.h"
-#include "nsIComponentManager.h"
-#include "nsIDOMWindow.h"
-#include "nsILocalFile.h"
-#include "nsIObserverService.h"
-#include "nsIProperties.h"
-#include "nsIServiceManager.h"
-#include "nsISupportsPrimitives.h"
-#include "nsIMutableArray.h"
-#include "nsIToolkitProfile.h"
-#include "nsIToolkitProfileService.h"
-#include "nsIWindowWatcher.h"
-
-#include "nsCOMPtr.h"
-#include "nsBrowserCompsCID.h"
-#include "nsComponentManagerUtils.h"
-#include "nsDirectoryServiceDefs.h"
-#include "nsServiceManagerUtils.h"
-
-#include "nsStringAPI.h"
-#include "nsUnicharUtils.h"
-#ifdef XP_WIN
-#include <windows.h>
-#include "nsIWindowsRegKey.h"
-#include "nsILocalFileWin.h"
-#else
-#include <limits.h>
-#endif
-
-#include "nsAutoPtr.h"
-
-///////////////////////////////////////////////////////////////////////////////
-// nsIProfileMigrator
-
-#define MIGRATION_WIZARD_FE_URL "chrome://browser/content/migration/migration.xul"
-#define MIGRATION_WIZARD_FE_FEATURES "chrome,dialog,modal,centerscreen,titlebar"
-
-NS_IMETHODIMP
-nsProfileMigrator::Migrate(nsIProfileStartup* aStartup)
-{
-  nsresult rv;
-
-  nsCAutoString key;
-  nsCOMPtr<nsIBrowserProfileMigrator> bpm;
-
-  rv = GetDefaultBrowserMigratorKey(key, bpm);
-  if (NS_FAILED(rv)) return rv;
-
-  if (!bpm) {
-    nsCAutoString contractID(NS_BROWSERPROFILEMIGRATOR_CONTRACTID_PREFIX);
-    contractID.Append(key);
-
-    bpm = do_CreateInstance(contractID.get());
-    if (!bpm) return NS_ERROR_FAILURE;
-  }
-
-  bool sourceExists;
-  bpm->GetSourceExists(&sourceExists);
-  if (!sourceExists) {
-#ifdef XP_WIN
-    // The "Default Browser" key in the registry was set to a browser for which
-    // no profile data exists. On Windows, this means the Default Browser settings
-    // in the registry are bad, and we should just fall back to IE in this case.
-    bpm = do_CreateInstance(NS_BROWSERPROFILEMIGRATOR_CONTRACTID_PREFIX "ie");
-#else
-    return NS_ERROR_FAILURE;
-#endif
-  }
-
-  nsCOMPtr<nsISupportsCString> cstr
-    (do_CreateInstance("@mozilla.org/supports-cstring;1"));
-  if (!cstr) return NS_ERROR_OUT_OF_MEMORY;
-  cstr->SetData(key);
-
-  // By opening the Migration FE with a supplied bpm, it will automatically
-  // migrate from it. 
-  nsCOMPtr<nsIWindowWatcher> ww(do_GetService(NS_WINDOWWATCHER_CONTRACTID));
-  nsCOMPtr<nsIMutableArray> params = do_CreateInstance(NS_ARRAY_CONTRACTID);
-  if (!ww || !params) return NS_ERROR_FAILURE;
-
-  params->AppendElement(cstr, false);
-  params->AppendElement(bpm, false);
-  params->AppendElement(aStartup, false);
-
-  nsCOMPtr<nsIDOMWindow> migrateWizard;
-  return ww->OpenWindow(nsnull, 
-                        MIGRATION_WIZARD_FE_URL,
-                        "_blank",
-                        MIGRATION_WIZARD_FE_FEATURES,
-                        params,
-                        getter_AddRefs(migrateWizard));
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// nsProfileMigrator
-
-NS_IMPL_ISUPPORTS1(nsProfileMigrator, nsIProfileMigrator)
-
-#ifdef XP_WIN
-
-#define INTERNAL_NAME_IEXPLORE        "iexplore"
-#define INTERNAL_NAME_MOZILLA_SUITE   "apprunner"
-#define INTERNAL_NAME_CHROME          "chrome"
-#define INTERNAL_NAME_FIREFOX         "firefox"
-#endif
-
-nsresult
-nsProfileMigrator::GetDefaultBrowserMigratorKey(nsACString& aKey,
-                                                nsCOMPtr<nsIBrowserProfileMigrator>& bpm)
-{
-#if XP_WIN
-
-  nsCOMPtr<nsIWindowsRegKey> regKey = 
-    do_CreateInstance("@mozilla.org/windows-registry-key;1");
-  if (!regKey)
-    return NS_ERROR_FAILURE;
-
-  NS_NAMED_LITERAL_STRING(kCommandKey,
-                          "SOFTWARE\\Classes\\HTTP\\shell\\open\\command");
-
-  if (NS_FAILED(regKey->Open(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE,
-                             kCommandKey, nsIWindowsRegKey::ACCESS_READ)))
-    return NS_ERROR_FAILURE;
-
-  nsAutoString value;
-  if (NS_FAILED(regKey->ReadStringValue(EmptyString(), value)))
-    return NS_ERROR_FAILURE;
-
-  PRInt32 len = value.Find(NS_LITERAL_STRING(".exe"), CaseInsensitiveCompare);
-  if (len == -1)
-    return NS_ERROR_FAILURE;
-
-  // Move past ".exe"
-  len += 4;
-
-  PRUint32 start = 0;
-  // skip an opening quotation mark if present
-  if (value.get()[1] != ':') {
-    start = 1;
-    --len;
-  }
-
-  const nsDependentSubstring filePath(Substring(value, start, len)); 
-
-  // We want to find out what the default browser is but the path in and of itself
-  // isn't enough. Why? Because sometimes on Windows paths get truncated like so:
-  // C:\PROGRA~1\MOZILL~2\MOZILL~1.EXE
-  // How do we know what product that is? Mozilla or Mozilla Firebird? etc. Mozilla's
-  // file objects do nothing to 'normalize' the path so we need to attain an actual
-  // product descriptor from the file somehow, and in this case it means getting
-  // the "InternalName" field of the file's VERSIONINFO resource. 
-  //
-  // In the file's resource segment there is a VERSIONINFO section that is laid 
-  // out like this:
-  //
-  // VERSIONINFO
-  //   StringFileInfo
-  //     <TranslationID>
-  //       InternalName           "iexplore"
-  //   VarFileInfo
-  //     Translation              <TranslationID>
-  //
-  // By Querying the VERSIONINFO section for its Tranlations, we can find out where
-  // the InternalName lives. (A file can have more than one translation of its 
-  // VERSIONINFO segment, but we just assume the first one). 
-
-  nsCOMPtr<nsILocalFile> lf;
-  NS_NewLocalFile(filePath, true, getter_AddRefs(lf));
-  if (!lf)
-    return NS_ERROR_FAILURE;
-
-  nsCOMPtr<nsILocalFileWin> lfw = do_QueryInterface(lf); 
-  if (!lfw)
-    return NS_ERROR_FAILURE;
-
-  nsAutoString internalName;
-  if (NS_FAILED(lfw->GetVersionInfoField("InternalName", internalName)))
-    return NS_ERROR_FAILURE;
-
-  if (internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_IEXPLORE)) {
-    aKey = "ie";
-    return NS_OK;
-  }
-  else if (internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_CHROME)) {
-    aKey = "chrome";
-    return NS_OK;
-  }
-  else if (internalName.LowerCaseEqualsLiteral(INTERNAL_NAME_FIREFOX)) {
-    aKey = "firefox";
-    return NS_OK;
-  }
-
-#else
-  bool exists = false;
-#define CHECK_MIGRATOR(browser) do {\
-  bpm = do_CreateInstance(NS_BROWSERPROFILEMIGRATOR_CONTRACTID_PREFIX browser);\
-  if (bpm)\
-    bpm->GetSourceExists(&exists);\
-  if (exists) {\
-    aKey = browser;\
-    return NS_OK;\
-  }} while(0)
-
-#if defined(XP_MACOSX)
-  CHECK_MIGRATOR("safari");
-#endif
-  CHECK_MIGRATOR("chrome");
-  CHECK_MIGRATOR("firefox");
-
-#undef CHECK_MIGRATOR
-#endif
-  return NS_ERROR_FAILURE;
-}
deleted file mode 100644
--- a/browser/components/migration/src/nsProfileMigrator.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is The Browser Profile Migrator.
- *
- * The Initial Developer of the Original Code is Ben Goodger.
- * Portions created by the Initial Developer are Copyright (C) 2004
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Ben Goodger <ben@bengoodger.com>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
- 
-#ifndef profilemigrator___h___
-#define profilemigrator___h___
-
-#include "nsIBrowserProfileMigrator.h"
-#include "nsIProfileMigrator.h"
-#include "nsCOMPtr.h"
-
-#define NS_FIREFOX_PROFILEMIGRATOR_CID \
-{ 0x4ca3c946, 0x5408, 0x49f0, { 0x9e, 0xca, 0x3a, 0x97, 0xd5, 0xc6, 0x77, 0x50 } }
-
-class nsProfileMigrator : public nsIProfileMigrator
-{
-public:
-  NS_DECL_NSIPROFILEMIGRATOR
-  NS_DECL_ISUPPORTS
-
-  nsProfileMigrator() { }
-
-protected:
-  ~nsProfileMigrator() { }
-
-  nsresult GetDefaultBrowserMigratorKey(nsACString& key,
-                                        nsCOMPtr<nsIBrowserProfileMigrator>& bpm);
-};
-
-#endif
-
--- a/browser/components/preferences/sync.xul
+++ b/browser/components/preferences/sync.xul
@@ -52,22 +52,22 @@
          xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
          xmlns:html="http://www.w3.org/1999/xhtml">
 
   <prefpane id="paneSync"
             helpTopic="prefs-weave"
             onpaneload="gSyncPane.init()">
 
     <preferences>
+      <preference id="engine.addons"    name="services.sync.engine.addons"    type="bool"/>
       <preference id="engine.bookmarks" name="services.sync.engine.bookmarks" type="bool"/>
       <preference id="engine.history"   name="services.sync.engine.history"   type="bool"/>
       <preference id="engine.tabs"      name="services.sync.engine.tabs"      type="bool"/>
       <preference id="engine.prefs"     name="services.sync.engine.prefs"     type="bool"/>
       <preference id="engine.passwords" name="services.sync.engine.passwords" type="bool"/>
-      <preference id="engine.addons"    name="services.sync.engine.addons"    type="bool"/>
     </preferences>
 
 
     <script type="application/javascript"
             src="chrome://browser/content/preferences/sync.js"/>
     <script type="application/javascript"
             src="chrome://browser/content/syncUtils.js"/>
 
@@ -124,16 +124,21 @@
             </hbox>
 
             <vbox>
               <label value="&syncMy.label;" />
               <richlistbox id="syncEnginesList"
                            orient="vertical"
                            onselect="if (this.selectedCount) this.clearSelection();">
                 <richlistitem>
+                  <checkbox label="&engine.addons.label;"
+                            accesskey="&engine.addons.accesskey;"
+                            preference="engine.addons"/>
+                </richlistitem>
+                <richlistitem>
                   <checkbox label="&engine.bookmarks.label;"
                             accesskey="&engine.bookmarks.accesskey;"
                             preference="engine.bookmarks"/>
                 </richlistitem>
                 <richlistitem>
                   <checkbox label="&engine.passwords.label;"
                             accesskey="&engine.passwords.accesskey;"
                             preference="engine.passwords"/>
@@ -148,21 +153,16 @@
                             accesskey="&engine.history.accesskey;"
                             preference="engine.history"/>
                 </richlistitem>
                 <richlistitem>
                   <checkbox label="&engine.tabs.label;"
                             accesskey="&engine.tabs.accesskey;"
                             preference="engine.tabs"/>
                 </richlistitem>
-                <richlistitem>
-                  <checkbox label="&engine.addons.label;"
-                            accesskey="&engine.addons.accesskey;"
-                            preference="engine.addons"/>
-                </richlistitem>
               </richlistbox>
             </vbox>
           </groupbox>
 
           <groupbox class="syncGroupBox">
             <grid>
               <columns>
                 <column/>
--- a/browser/devtools/sourceeditor/orion/mozilla.css
+++ b/browser/devtools/sourceeditor/orion/mozilla.css
@@ -3,16 +3,17 @@
 
 .viewContainer {
   background: #cddae5; /* This will be seen as the continuation of the ruler */
   font-family: monospace;
   font-size: inherit; /* inherit browser's default monospace font size */
 }
 
 .view {
+  color: black; /* Default text color */
   background: #f0f0ff; /* Background of the editor */
   padding-left: 0;
 }
 
 .readonly > .view {
   background: #f0f0ff;
 }
 
--- a/browser/devtools/styleeditor/StyleEditor.jsm
+++ b/browser/devtools/styleeditor/StyleEditor.jsm
@@ -746,80 +746,38 @@ StyleEditor.prototype = {
   /**
    * Load source from the HTTP cache.
    *
    * @param string aHref
    *        URL for the stylesheet.
    */
   _loadSourceFromCache: function SE__loadSourceFromCache(aHref)
   {
-    try {
-      let cacheService = Cc["@mozilla.org/network/cache-service;1"]
-                           .getService(Ci.nsICacheService);
-      let session = cacheService.createSession("HTTP", Ci.nsICache.STORE_ANYWHERE, true);
-      session.doomEntriesIfExpired = false;
-      session.asyncOpenCacheEntry(aHref, Ci.nsICache.ACCESS_READ, {
-        onCacheEntryAvailable: this._onCacheEntryAvailable.bind(this)
-      });
-    } catch (ex) {
-      this._signalError(LOAD_ERROR);
-    }
-  },
-
-   /**
-    * The nsICacheListener.onCacheEntryAvailable method implementation used when
-    * the style sheet source is loaded from the browser cache.
-    *
-    * @param nsICacheEntryDescriptor aEntry
-    * @param nsCacheAccessMode aMode
-    * @param integer aStatus
-    */
-  _onCacheEntryAvailable: function SE__onCacheEntryAvailable(aEntry, aMode, aStatus)
-  {
-    if (!Components.isSuccessCode(aStatus)) {
-      return this._signalError(LOAD_ERROR);
-    }
-
-    let stream = aEntry.openInputStream(0);
+    let channel = Services.io.newChannel(aHref, null, null);
     let chunks = [];
     let streamListener = { // nsIStreamListener inherits nsIRequestObserver
       onStartRequest: function (aRequest, aContext, aStatusCode) {
-      },
+        if (!Components.isSuccessCode(aStatusCode)) {
+          return this._signalError(LOAD_ERROR);
+        }
+      }.bind(this),
       onDataAvailable: function (aRequest, aContext, aStream, aOffset, aCount) {
         chunks.push(NetUtil.readInputStreamToString(aStream, aCount));
       },
       onStopRequest: function (aRequest, aContext, aStatusCode) {
+        if (!Components.isSuccessCode(aStatusCode)) {
+          return this._signalError(LOAD_ERROR);
+        }
+
         this._onSourceLoad(chunks.join(""));
-      }.bind(this),
+      }.bind(this)
     };
 
-    let head = aEntry.getMetaDataElement("response-head");
-    if (/^Content-Encoding:\s*gzip/mi.test(head)) {
-      let converter = Cc["@mozilla.org/streamconv;1?from=gzip&to=uncompressed"]
-                        .createInstance(Ci.nsIStreamConverter);
-      converter.asyncConvertData("gzip", "uncompressed", streamListener, null);
-      streamListener = converter; // proxy original listener via converter
-    }
-
-    try {
-      streamListener.onStartRequest(null, null);
-      while (stream.available()) {
-        streamListener.onDataAvailable(null, null, stream, 0, stream.available());
-      }
-      streamListener.onStopRequest(null, null, 0);
-    } catch (ex) {
-      this._signalError(LOAD_ERROR);
-    } finally {
-      try {
-        stream.close();
-      } catch (ex) {
-        // swallow (some stream implementations can auto-close at eos)
-      }
-      aEntry.close();
-    }
+    channel.loadFlags = channel.LOAD_FROM_CACHE;
+    channel.asyncOpen(streamListener, null);
   },
 
   /**
    * Called when source has been loaded.
    *
    * @param string aSourceText
    */
   _onSourceLoad: function SE__onSourceLoad(aSourceText)
--- a/browser/devtools/styleinspector/CssRuleView.jsm
+++ b/browser/devtools/styleinspector/CssRuleView.jsm
@@ -1137,17 +1137,18 @@ TextPropertyEditor.prototype = {
  *    {function} start:
  *       Will be called when the inplace editor is initialized.
  *    {function} change:
  *       Will be called when the text input changes.  Will be called
  *       with the current value of the text input.
  *    {function} done:
  *       Called when input is committed or blurred.  Called with
  *       current value and a boolean telling the caller whether to
- *       commit the change.
+ *       commit the change.  This function is called after the editor
+ *       has been torn down.
  *    {string} advanceChars:
  *       If any characters in advanceChars are typed, focus will advance
  *       to the next element.
  */
 function editableField(aOptions)
 {
   aOptions.element.addEventListener("focus", function() {
     new InplaceEditor(aOptions);
@@ -1281,21 +1282,21 @@ InplaceEditor.prototype = {
   },
 
   /**
    * Handle loss of focus by calling the client's done handler and
    * clearing out.
    */
   _onBlur: function InplaceEditor_onBlur(aEvent)
   {
+    let val = this.input.value.trim();
+    this._clear();
     if (this.done) {
-      this.done(this.cancelled ? this.initial : this.input.value.trim(),
-                !this.cancelled);
+      this.done(this.cancelled ? this.initial : val, !this.cancelled);
     }
-    this._clear();
   },
 
   _onKeyPress: function InplaceEditor_onKeyPress(aEvent)
   {
     let prevent = false;
     if (aEvent.charCode in this._advanceCharCodes
        || aEvent.keyCode === Ci.nsIDOMKeyEvent.DOM_VK_RETURN) {
       // Focus the next element, triggering a blur which
--- a/browser/devtools/styleinspector/StyleInspector.jsm
+++ b/browser/devtools/styleinspector/StyleInspector.jsm
@@ -76,19 +76,19 @@ StyleInspector.prototype = {
 
     // Were we invoked from the Highlighter?
     if (this.IUI) {
       this.openDocked = true;
       let isOpen = this.isOpen.bind(this);
 
       this.registrationObject = {
         id: "styleinspector",
-        label: this.l10n("style.highlighter.button.label1"),
+        label: this.l10n("style.highlighter.button.label2"),
         tooltiptext: this.l10n("style.highlighter.button.tooltip"),
-        accesskey: this.l10n("style.highlighter.accesskey1"),
+        accesskey: this.l10n("style.highlighter.accesskey2"),
         context: this,
         get isOpen() isOpen(),
         onSelect: this.selectNode,
         onChanged: this.updateNode,
         show: this.open,
         hide: this.close,
         dim: this.dimTool,
         panel: null,
--- a/browser/devtools/styleinspector/styleinspector.css
+++ b/browser/devtools/styleinspector/styleinspector.css
@@ -37,8 +37,12 @@
 
 .ruleview {
   overflow: auto;
 }
 
 .ruleview-computedlist:not(.styleinspector-open) {
   display: none;
 }
+
+.ruleview-code {
+  direction: ltr;
+}
--- a/browser/devtools/tilt/Tilt.jsm
+++ b/browser/devtools/tilt/Tilt.jsm
@@ -266,17 +266,17 @@ Tilt.prototype = {
   },
 
   /**
    * Returns true if this tool is enabled.
    */
   get enabled()
   {
     return (TiltVisualizer.Prefs.enabled &&
-           (TiltVisualizer.Prefs.forceEnabled || TiltGL.isWebGLSupported()));
+           (TiltGL.isWebGLForceEnabled() || TiltGL.isWebGLSupported()));
   },
 
   /**
    * Gets the ID of the current window object to identify the visualizer.
    */
   get currentWindowId()
   {
     let gBrowser = this.chromeWindow.gBrowser;
--- a/browser/devtools/tilt/TiltGL.jsm
+++ b/browser/devtools/tilt/TiltGL.jsm
@@ -32,25 +32,26 @@
  * 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 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 *****/
 
-/*global Components, TiltMath, TiltUtils, mat4 */
+/*global Components, Services, TiltMath, TiltUtils, mat4 */
 "use strict";
 
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 const Cu = Components.utils;
 
 const WEBGL_CONTEXT_NAME = "experimental-webgl";
 
+Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource:///modules/devtools/TiltMath.jsm");
 Cu.import("resource:///modules/devtools/TiltUtils.jsm");
 
 let EXPORTED_SYMBOLS = ["TiltGL"];
 
 /**
  * Module containing thin wrappers around low-level WebGL functions.
  */
@@ -1549,16 +1550,21 @@ TiltGL.ColorShader = {
     "uniform vec4 fill;",
 
     "void main() {",
     "    gl_FragColor = fill;",
     "}"
   ].join("\n")
 };
 
+TiltGL.isWebGLForceEnabled = function TGL_isWebGLForceEnabled()
+{
+  return Services.prefs.getBoolPref("webgl.force-enabled");
+};
+
 /**
  * Tests if the WebGL OpenGL or Angle renderer is available using the
  * GfxInfo service.
  *
  * @return {Boolean} true if WebGL is available
  */
 TiltGL.isWebGLSupported = function TGL_isWebGLSupported()
 {
--- a/browser/devtools/tilt/TiltVisualizer.jsm
+++ b/browser/devtools/tilt/TiltVisualizer.jsm
@@ -1544,38 +1544,23 @@ TiltVisualizer.Prefs = {
 
   set enabled(value)
   {
     TiltUtils.Preferences.set("enabled", "boolean", value);
     this._enabled = value;
   },
 
   /**
-   * Specifies if Tilt should be enabled even if WebGL may not be available.
-   */
-  get forceEnabled()
-  {
-    return this._forceEnabled;
-  },
-
-  set forceEnabled(value)
-  {
-    TiltUtils.Preferences.set("force-enabled", "boolean", value);
-    this._forceEnabled = value;
-  },
-
-  /**
    * Loads the preferences.
    */
   load: function TVC_load()
   {
     let prefs = TiltUtils.Preferences;
 
     TiltVisualizer.Prefs._enabled = prefs.get("enabled", "boolean");
-    TiltVisualizer.Prefs._forceEnabled = prefs.get("force-enabled", "boolean");
   }
 };
 
 /**
  * A custom visualization shader.
  *
  * @param {Attribute} vertexPosition: the vertex position
  * @param {Attribute} vertexTexCoord: texture coordinates used by the sampler
--- a/browser/devtools/tilt/test/Makefile.in
+++ b/browser/devtools/tilt/test/Makefile.in
@@ -46,16 +46,17 @@ include $(topsrcdir)/config/rules.mk
 
 _BROWSER_TEST_FILES = \
 	head.js \
 	browser_tilt_01_lazy_getter.js \
 	browser_tilt_02_notifications.js \
 	browser_tilt_03_tab_switch.js \
 	browser_tilt_04_initialization.js \
 	browser_tilt_05_destruction-esc.js \
+	browser_tilt_05_destruction-url.js \
 	browser_tilt_05_destruction.js \
 	browser_tilt_arcball.js \
 	browser_tilt_controller.js \
 	browser_tilt_gl01.js \
 	browser_tilt_gl02.js \
 	browser_tilt_gl03.js \
 	browser_tilt_gl04.js \
 	browser_tilt_gl05.js \
--- a/browser/devtools/tilt/test/browser_tilt_04_initialization.js
+++ b/browser/devtools/tilt/test/browser_tilt_04_initialization.js
@@ -26,21 +26,16 @@ function test() {
       "The unique window identifiers should match for the same window.");
 
     createTilt({
       onInspectorOpen: function() {
         initialActiveElement = document.activeElement;
 
         is(Tilt.visualizers[id], null,
           "A instance of the visualizer shouldn't be initialized yet.");
-
-        is(typeof TiltVisualizer.Prefs.enabled, "boolean",
-          "The 'enabled' pref should have been loaded by now.");
-        is(typeof TiltVisualizer.Prefs.forceEnabled, "boolean",
-          "The 'force-enabled' pref should have been loaded by now.");
       },
       onTiltOpen: function(instance)
       {
         is(document.activeElement, instance.presenter.canvas,
           "The visualizer canvas should be focused on initialization.");
 
         ok(Tilt.visualizers[id] instanceof TiltVisualizer,
           "A new instance of the visualizer wasn't created properly.");
new file mode 100644
--- /dev/null
+++ b/browser/devtools/tilt/test/browser_tilt_05_destruction-url.js
@@ -0,0 +1,41 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/*global ok, is, info, waitForExplicitFinish, finish, gBrowser */
+/*global isTiltEnabled, isWebGLSupported, createTab, createTilt */
+/*global Services, EventUtils, Tilt, TiltUtils, InspectorUI, TILT_DESTROYED */
+"use strict";
+
+function test() {
+  if (!isTiltEnabled()) {
+    info("Skipping destruction test because Tilt isn't enabled.");
+    return;
+  }
+  if (!isWebGLSupported()) {
+    info("Skipping destruction test because WebGL isn't supported.");
+    return;
+  }
+
+  waitForExplicitFinish();
+
+  createTab(function() {
+    createTilt({
+      onTiltOpen: function()
+      {
+        Services.obs.addObserver(cleanup, TILT_DESTROYED, false);
+        window.content.location = "about:mozilla";
+      }
+    });
+  });
+}
+
+function cleanup() {
+  let id = TiltUtils.getWindowId(gBrowser.selectedBrowser.contentWindow);
+
+  is(Tilt.visualizers[id], null,
+    "The current instance of the visualizer wasn't destroyed properly.");
+
+  Services.obs.removeObserver(cleanup, TILT_DESTROYED);
+  gBrowser.removeCurrentTab();
+  finish();
+}
--- a/browser/devtools/webconsole/HUDService.jsm
+++ b/browser/devtools/webconsole/HUDService.jsm
@@ -114,22 +114,39 @@ XPCOMUtils.defineLazyGetter(this, "Autoc
     Cu.import("resource:///modules/AutocompletePopup.jsm", obj);
   }
   catch (err) {
     Cu.reportError(err);
   }
   return obj.AutocompletePopup;
 });
 
+XPCOMUtils.defineLazyGetter(this, "ScratchpadManager", function () {
+  var obj = {};
+  try {
+    Cu.import("resource:///modules/devtools/scratchpad-manager.jsm", obj);
+  }
+  catch (err) {
+    Cu.reportError(err);
+  }
+  return obj.ScratchpadManager;
+});
+
 XPCOMUtils.defineLazyGetter(this, "namesAndValuesOf", function () {
   var obj = {};
   Cu.import("resource:///modules/PropertyPanel.jsm", obj);
   return obj.namesAndValuesOf;
 });
 
+XPCOMUtils.defineLazyGetter(this, "gConsoleStorage", function () {
+  let obj = {};
+  Cu.import("resource://gre/modules/ConsoleAPIStorage.jsm", obj);
+  return obj.ConsoleAPIStorage;
+});
+
 function LogFactory(aMessagePrefix)
 {
   function log(aMessage) {
     var _msg = aMessagePrefix + " " + aMessage + "\n";
     dump(_msg);
   }
   return log;
 }
@@ -1410,16 +1427,28 @@ HUD_SERVICE.prototype =
    * @returns integer
    */
   getWindowId: function HS_getWindowId(aWindow)
   {
     return aWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils).outerWindowID;
   },
 
   /**
+   * Gets the ID of the inner window of this DOM window
+   *
+   * @param nsIDOMWindow aWindow
+   * @returns integer
+   */
+  getInnerWindowId: function HS_getInnerWindowId(aWindow)
+  {
+    return aWindow.QueryInterface(Ci.nsIInterfaceRequestor).
+           getInterface(Ci.nsIDOMWindowUtils).currentInnerWindowID;
+  },
+
+  /**
    * Gets the top level content window that has an outer window with
    * the given ID or returns null if no such content window exists
    *
    * @param integer aId
    * @returns nsIDOMWindow
    */
   getWindowByWindowId: function HS_getWindowByWindowId(aId)
   {
@@ -2140,17 +2169,18 @@ HUD_SERVICE.prototype =
     let node = ConsoleUtils.createMessageNode(hud.outputNode.ownerDocument,
                                               CATEGORY_WEBDEV,
                                               LEVELS[level],
                                               body,
                                               aHUDId,
                                               sourceURL,
                                               sourceLine,
                                               clipboardText,
-                                              level);
+                                              level,
+                                              aMessage.timeStamp);
 
     // Make the node bring up the property panel, to allow the user to inspect
     // the stack trace.
     if (level == "trace") {
       node._stacktrace = args;
 
       let linkNode = node.querySelector(".webconsole-msg-body");
       linkNode.classList.add("hud-clickable");
@@ -2207,28 +2237,48 @@ HUD_SERVICE.prototype =
                                               SEVERITY_WARNING, message,
                                               aHUDId);
     ConsoleUtils.outputMessageNode(node, aHUDId);
   },
 
   /**
    * Reports an error in the page source, either JavaScript or CSS.
    *
-   * @param number aCategory
-   *        The category of the message; either CATEGORY_CSS or CATEGORY_JS.
    * @param nsIScriptError aScriptError
    *        The error message to report.
    * @return void
    */
-  reportPageError: function HS_reportPageError(aCategory, aScriptError)
-  {
-    if (aCategory != CATEGORY_CSS && aCategory != CATEGORY_JS) {
-      throw Components.Exception("Unsupported category (must be one of CSS " +
-                                 "or JS)", Cr.NS_ERROR_INVALID_ARG,
-                                 Components.stack.caller);
+  reportPageError: function HS_reportPageError(aScriptError)
+  {
+    if (!aScriptError.outerWindowID) {
+      return;
+    }
+
+    let category;
+
+    switch (aScriptError.category) {
+      // We ignore chrome-originating errors as we only care about content.
+      case "XPConnect JavaScript":
+      case "component javascript":
+      case "chrome javascript":
+      case "chrome registration":
+      case "XBL":
+      case "XBL Prototype Handler":
+      case "XBL Content Sink":
+      case "xbl javascript":
+        return;
+
+      case "CSS Parser":
+      case "CSS Loader":
+        category = CATEGORY_CSS;
+        break;
+
+      default:
+        category = CATEGORY_JS;
+        break;
     }
 
     // Warnings and legacy strict errors become warnings; other types become
     // errors.
     let severity = SEVERITY_ERROR;
     if ((aScriptError.flags & aScriptError.warningFlag) ||
         (aScriptError.flags & aScriptError.strictFlag)) {
       severity = SEVERITY_WARNING;
@@ -2237,22 +2287,24 @@ HUD_SERVICE.prototype =
     let window = HUDService.getWindowByWindowId(aScriptError.outerWindowID);
     if (window) {
       let hudId = HUDService.getHudIdByWindow(window.top);
       if (hudId) {
         let outputNode = this.hudReferences[hudId].outputNode;
         let chromeDocument = outputNode.ownerDocument;
 
         let node = ConsoleUtils.createMessageNode(chromeDocument,
-                                                  aCategory,
+                                                  category,
                                                   severity,
                                                   aScriptError.errorMessage,
                                                   hudId,
                                                   aScriptError.sourceName,
-                                                  aScriptError.lineNumber);
+                                                  aScriptError.lineNumber,
+                                                  null, null,
+                                                  aScriptError.timeStamp);
 
         ConsoleUtils.outputMessageNode(node, hudId);
       }
     }
   },
 
   /**
    * Register a Gecko app's specialized ApplicationHooks object
@@ -2890,29 +2942,31 @@ HUD_SERVICE.prototype =
       }
     }
 
     let hud;
     // If there is no HUD for this tab create a new one.
     if (!hudNode) {
       // get nBox object and call new HUD
       let config = { parentNode: nBox,
-                     contentWindow: aContentWindow
+                     contentWindow: aContentWindow.top
                    };
 
       hud = new HeadsUpDisplay(config);
 
       HUDService.registerHUDReference(hud);
       let windowId = this.getWindowId(aContentWindow.top);
       this.windowIds[windowId] = hudId;
 
       hud.progressListener = new ConsoleProgressListener(hudId);
 
       _browser.webProgress.addProgressListener(hud.progressListener,
         Ci.nsIWebProgress.NOTIFY_STATE_ALL);
+
+      hud.displayCachedConsoleMessages();
     }
     else {
       hud = this.hudReferences[hudId];
       if (aContentWindow == aContentWindow.top) {
         // TODO: name change?? doesn't actually re-attach the console
         hud.reattachConsole(aContentWindow);
       }
     }
@@ -3572,16 +3626,68 @@ HeadsUpDisplay.prototype = {
       }
     }
     else {
       throw new Error("Unsupported Gecko Application");
     }
   },
 
   /**
+   * Display cached messages that may have been collected before the UI is
+   * displayed.
+   *
+   * @returns void
+   */
+  displayCachedConsoleMessages: function HUD_displayCachedConsoleMessages()
+  {
+    let innerWindowId = HUDService.getInnerWindowId(this.contentWindow);
+
+    let messages = gConsoleStorage.getEvents(innerWindowId);
+
+    let errors = {};
+    Services.console.getMessageArray(errors, {});
+
+    // Filter the errors to find only those we should display.
+    let filteredErrors = (errors.value || []).filter(function(aError) {
+      return aError instanceof Ci.nsIScriptError &&
+             aError.innerWindowID == innerWindowId;
+    }, this);
+
+    messages.push.apply(messages, filteredErrors);
+    messages.sort(function(a, b) { return a.timeStamp - b.timeStamp; });
+
+    // Turn off scrolling for the moment.
+    ConsoleUtils.scroll = false;
+    this.outputNode.hidden = true;
+
+    // Display all messages.
+    messages.forEach(function(aMessage) {
+      if (aMessage instanceof Ci.nsIScriptError) {
+        HUDService.reportPageError(aMessage);
+      }
+      else {
+        // In this case the cached message is a console message generated
+        // by the ConsoleAPI, not an nsIScriptError
+        HUDService.logConsoleAPIMessage(this.hudId, aMessage);
+      }
+    }, this);
+
+    this.outputNode.hidden = false;
+    ConsoleUtils.scroll = true;
+
+    // Scroll to bottom.
+    let numChildren = this.outputNode.childNodes.length;
+    if (numChildren && this.outputNode.clientHeight) {
+      // We also check the clientHeight to force a reflow, otherwise
+      // ensureIndexIsVisible() does not work after outputNode.hidden = false.
+      this.outputNode.ensureIndexIsVisible(numChildren - 1);
+    }
+  },
+
+  /**
    * Re-attaches a console when the contentWindow is recreated
    *
    * @param nsIDOMWindow aContentWindow
    * @returns void
    */
   reattachConsole: function HUD_reattachConsole(aContentWindow)
   {
     this.contentWindow = aContentWindow;
@@ -4003,17 +4109,17 @@ HeadsUpDisplay.prototype = {
    * @return void
    */
   makeClearConsoleButton: function HUD_makeClearConsoleButton(aToolbar)
   {
     let hudId = this.hudId;
     function HUD_clearButton_onCommand() {
       let hud = HUDService.getHudReferenceById(hudId);
       if (hud.jsterm) {
-        hud.jsterm.clearOutput();
+        hud.jsterm.clearOutput(true);
       }
       if (hud.gcliterm) {
         hud.gcliterm.clearOutput();
       }
     }
 
     let clearButton = this.makeXULNode("toolbarbutton");
     clearButton.setAttribute("label", this.getStr("btnClear"));
@@ -4521,17 +4627,17 @@ function JSTermHelper(aJSTerm)
   });
 
   /**
    * Clears the output of the JSTerm.
    */
   aJSTerm.sandbox.clear = function JSTH_clear()
   {
     aJSTerm.helperEvaluated = true;
-    aJSTerm.clearOutput();
+    aJSTerm.clearOutput(true);
   };
 
   /**
    * Returns the result of Object.keys(aObject).
    *
    * @param object aObject
    *        Object to return the property names from.
    * @returns array of string
@@ -5113,17 +5219,24 @@ JSTerm.prototype = {
     let type = aResult === null ? "null" : typeof aResult;
     if (type == "object" && aResult.constructor && aResult.constructor.name) {
       type = aResult.constructor.name;
     }
 
     return type.toLowerCase();
   },
 
-  clearOutput: function JST_clearOutput()
+  /**
+   * Clear the Web Console output.
+   *
+   * @param boolean aClearStorage
+   *        True if you want to clear the console messages storage associated to
+   *        this Web Console.
+   */
+  clearOutput: function JST_clearOutput(aClearStorage)
   {
     let hud = HUDService.getHudReferenceById(this.hudId);
     hud.cssNodes = {};
 
     let node = hud.outputNode;
     while (node.firstChild) {
       if (node.firstChild.classList &&
           node.firstChild.classList.contains("webconsole-msg-inspector")) {
@@ -5131,16 +5244,21 @@ JSTerm.prototype = {
       }
       else {
         hud.outputNode.removeChild(node.firstChild);
       }
     }
 
     hud.HUDBox.lastTimestamp = 0;
     hud.groupDepth = 0;
+
+    if (aClearStorage) {
+      let windowId = HUDService.getInnerWindowId(hud.contentWindow);
+      gConsoleStorage.clearEvents(windowId);
+    }
   },
 
   /**
    * Updates the size of the input field (command line) to fit its contents.
    *
    * @returns void
    */
   resizeInput: function JST_resizeInput()
@@ -5661,16 +5779,21 @@ FirefoxApplicationHooks.prototype = {
 //////////////////////////////////////////////////////////////////////////////
 
 /**
  * ConsoleUtils: a collection of globally used functions
  *
  */
 
 ConsoleUtils = {
+  /**
+   * Flag to turn on and off scrolling.
+   */
+  scroll: true,
+
   supString: function ConsoleUtils_supString(aString)
   {
     let str = Cc["@mozilla.org/supports-string;1"].
       createInstance(Ci.nsISupportsString);
     str.data = aString;
     return str;
   },
 
@@ -5704,16 +5827,20 @@ ConsoleUtils = {
    * Scrolls a node so that it's visible in its containing XUL "scrollbox"
    * element.
    *
    * @param nsIDOMNode aNode
    *        The node to make visible.
    * @returns void
    */
   scrollToVisible: function ConsoleUtils_scrollToVisible(aNode) {
+    if (!this.scroll) {
+      return;
+    }
+
     // Find the enclosing richlistbox node.
     let richListBoxNode = aNode.parentNode;
     while (richListBoxNode.tagName != "richlistbox") {
       richListBoxNode = richListBoxNode.parentNode;
     }
 
     // Use the scroll box object interface to ensure the element is visible.
     let boxObject = richListBoxNode.scrollBoxObject;
@@ -5741,24 +5868,28 @@ ConsoleUtils = {
    *        The line number on which the error occurred. If zero or omitted,
    *        there is no line number associated with this message.
    * @param string aClipboardText [optional]
    *        The text that should be copied to the clipboard when this node is
    *        copied. If omitted, defaults to the body text. If `aBody` is not
    *        a string, then the clipboard text must be supplied.
    * @param number aLevel [optional]
    *        The level of the console API message.
+   * @param number aTimeStamp [optional]
+   *        The timestamp to use for this message node. If omitted, the current
+   *        date and time is used.
    * @return nsIDOMNode
    *         The message node: a XUL richlistitem ready to be inserted into
    *         the Web Console output node.
    */
   createMessageNode:
   function ConsoleUtils_createMessageNode(aDocument, aCategory, aSeverity,
                                           aBody, aHUDId, aSourceURL,
-                                          aSourceLine, aClipboardText, aLevel) {
+                                          aSourceLine, aClipboardText, aLevel,
+                                          aTimeStamp) {
     if (typeof aBody != "string" && aClipboardText == null && aBody.innerText) {
       aClipboardText = aBody.innerText;
     }
 
     // Make the icon container, which is a vertical box. Its purpose is to
     // ensure that the icon stays anchored at the top of the message even for
     // long multi-line messages.
     let iconContainer = aDocument.createElementNS(XUL_NS, "vbox");
@@ -5808,17 +5939,17 @@ ConsoleUtils = {
     let repeatNode = aDocument.createElementNS(XUL_NS, "label");
     repeatNode.setAttribute("value", "1");
     repeatNode.classList.add("webconsole-msg-repeat");
     repeatContainer.appendChild(repeatNode);
 
     // Create the timestamp.
     let timestampNode = aDocument.createElementNS(XUL_NS, "label");
     timestampNode.classList.add("webconsole-timestamp");
-    let timestamp = ConsoleUtils.timestamp();
+    let timestamp = aTimeStamp || ConsoleUtils.timestamp();
     let timestampString = ConsoleUtils.timestampString(timestamp);
     timestampNode.setAttribute("value", timestampString);
 
     // Create the source location (e.g. www.example.com:6) that sits on the
     // right side of the message, if applicable.
     let locationNode;
     if (aSourceURL) {
       locationNode = this.createLocationNode(aDocument, aSourceURL,
@@ -6514,58 +6645,32 @@ CommandController.prototype = {
 HUDConsoleObserver = {
   QueryInterface: XPCOMUtils.generateQI(
     [Ci.nsIObserver]
   ),
 
   init: function HCO_init()
   {
     Services.console.registerListener(this);
-    Services.obs.addObserver(this, "xpcom-shutdown", false);
+    Services.obs.addObserver(this, "quit-application-granted", false);
   },
 
   uninit: function HCO_uninit()
   {
     Services.console.unregisterListener(this);
-    Services.obs.removeObserver(this, "xpcom-shutdown");
+    Services.obs.removeObserver(this, "quit-application-granted");
   },
 
   observe: function HCO_observe(aSubject, aTopic, aData)
   {
-    if (aTopic == "xpcom-shutdown") {
+    if (aTopic == "quit-application-granted") {
       this.uninit();
-      return;
-    }
-
-    if (!(aSubject instanceof Ci.nsIScriptError) ||
-        !aSubject.outerWindowID) {
-      return;
-    }
-
-    switch (aSubject.category) {
-      // We ignore chrome-originating errors as we only
-      // care about content.
-      case "XPConnect JavaScript":
-      case "component javascript":
-      case "chrome javascript":
-      case "chrome registration":
-      case "XBL":
-      case "XBL Prototype Handler":
-      case "XBL Content Sink":
-      case "xbl javascript":
-        return;
-
-      case "CSS Parser":
-      case "CSS Loader":
-        HUDService.reportPageError(CATEGORY_CSS, aSubject);
-        return;
-
-      default:
-        HUDService.reportPageError(CATEGORY_JS, aSubject);
-        return;
+    }
+    else if (aSubject instanceof Ci.nsIScriptError) {
+      HUDService.reportPageError(aSubject);
     }
   }
 };
 
 /**
  * A WebProgressListener that listens for location changes, to update HUDService
  * state information on page navigation.
  *
@@ -6670,31 +6775,24 @@ function appName()
   let name = APP_ID_TABLE[APP_ID];
 
   if (name){
     return name;
   }
   throw new Error("appName: UNSUPPORTED APPLICATION UUID");
 }
 
-///////////////////////////////////////////////////////////////////////////
-// HUDService (exported symbol)
-///////////////////////////////////////////////////////////////////////////
-
-try {
-  // start the HUDService
-  // This is in a try block because we want to kill everything if
-  // *any* of this fails
-  var HUDService = new HUD_SERVICE();
-}
-catch (ex) {
-  Cu.reportError("HUDService failed initialization.\n" + ex);
-  // TODO: kill anything that may have started up
-  // see bug 568665
-}
+XPCOMUtils.defineLazyGetter(this, "HUDService", function () {
+  try {
+    return new HUD_SERVICE();
+  }
+  catch (ex) {
+    Cu.reportError(ex);
+  }
+});
 
 ///////////////////////////////////////////////////////////////////////////
 // GcliTerm
 ///////////////////////////////////////////////////////////////////////////
 
 /**
  * Some commands need customization - this is how we get at them.
  */
@@ -6727,29 +6825,44 @@ function GcliTerm(aContentWindow, aHudId
   this.hintNode = aHintNode;
 
   this.createUI();
   this.createSandbox();
 
   this.show = this.show.bind(this);
   this.hide = this.hide.bind(this);
 
+  // Allow GCLI:Inputter to decide how and when to open a scratchpad window
+  let scratchpad = {
+    shouldActivate: function Scratchpad_shouldActivate(aEvent) {
+      return aEvent.shiftKey &&
+          aEvent.keyCode === Ci.nsIDOMKeyEvent.DOM_VK_RETURN;
+    },
+    activate: function Scratchpad_activate(aValue) {
+      aValue = aValue.replace(/^\s*{\s*/, '');
+      ScratchpadManager.openScratchpad({ text: aValue });
+      return true;
+    },
+    linkText: stringBundle.GetStringFromName('scratchpad.linkText')
+  };
+
   this.opts = {
     environment: { hudId: this.hudId },
     chromeDocument: this.document,
     contentDocument: aContentWindow.document,
     jsEnvironment: {
       globalObject: unwrap(aContentWindow),
       evalFunction: this.evalInSandbox.bind(this)
     },
     inputElement: this.inputNode,
     completeElement: this.completeNode,
     inputBackgroundElement: this.inputStack,
     hintElement: this.hintNode,
     consoleWrap: aConsoleWrap,
+    scratchpad: scratchpad,
     gcliTerm: this
   };
 
   gcli._internal.commandOutputManager.addListener(this.onCommandOutput, this);
   gcli._internal.createView(this.opts);
 
   if (!commandExports) {
     commandExports = loadCommands();
--- a/browser/devtools/webconsole/gcli.jsm
+++ b/browser/devtools/webconsole/gcli.jsm
@@ -5319,17 +5319,18 @@ function getManTemplateData(command, con
 
 define('gcli/ui/domtemplate', ['require', 'exports', 'module' ], function(require, exports, module) {
 
   var obj = {};
   Components.utils.import('resource:///modules/devtools/Templater.jsm', obj);
   exports.template = obj.template;
 
 });
-define("text!gcli/commands/help.css", [], void 0);
+define("text!gcli/commands/help.css", [], "");
+
 define("text!gcli/commands/help_intro.html", [], "\n" +
   "<h2>${l10n.introHeader}</h2>\n" +
   "\n" +
   "<p>\n" +
   "</p>\n" +
   "");
 
 define("text!gcli/commands/help_list.html", [], "\n" +
@@ -5410,17 +5411,18 @@ function Console(options) {
 
   this.inputter = new Inputter({
     document: options.chromeDocument,
     requisition: options.requisition,
     inputElement: options.inputElement,
     completeElement: options.completeElement,
     completionPrompt: '',
     backgroundElement: options.backgroundElement,
-    focusManager: this.focusManager
+    focusManager: this.focusManager,
+    scratchpad: options.scratchpad
   });
 
   this.menu = new CommandMenu({
     document: options.chromeDocument,
     requisition: options.requisition,
     menuClass: 'gcliterm-menu'
   });
   this.hintElement.appendChild(this.menu.element);
@@ -5561,34 +5563,36 @@ exports.Console = Console;
 
 });
 /*
  * Copyright 2009-2011 Mozilla Foundation and contributors
  * Licensed under the New BSD license. See LICENSE.txt or:
  * http://opensource.org/licenses/BSD-3-Clause
  */
 
-define('gcli/ui/inputter', ['require', 'exports', 'module' , 'gcli/util', 'gcli/types', 'gcli/history', 'text!gcli/ui/inputter.css'], function(require, exports, module) {
+define('gcli/ui/inputter', ['require', 'exports', 'module' , 'gcli/util', 'gcli/l10n', 'gcli/types', 'gcli/history', 'text!gcli/ui/inputter.css'], function(require, exports, module) {
 var cliView = exports;
 
 
 var KeyEvent = require('gcli/util').event.KeyEvent;
 var dom = require('gcli/util').dom;
+var l10n = require('gcli/l10n');
 
 var Status = require('gcli/types').Status;
 var History = require('gcli/history').History;
 
 var inputterCss = require('text!gcli/ui/inputter.css');
 
 
 /**
  * A wrapper to take care of the functions concerning an input element
  */
 function Inputter(options) {
   this.requisition = options.requisition;
+  this.scratchpad = options.scratchpad;
 
   // Suss out where the input element is
   this.element = options.inputElement || 'gcli-input';
   if (typeof this.element === 'string') {
     this.document = options.document || document;
     var name = this.element;
     this.element = this.document.getElementById(name);
     if (!this.element) {
@@ -5860,16 +5864,24 @@ Inputter.prototype.onKeyDown = function(
     }
   }
 };
 
 /**
  * The main keyboard processing loop
  */
 Inputter.prototype.onKeyUp = function(ev) {
+  // Give the scratchpad (if enabled) a chance to activate
+  if (this.scratchpad && this.scratchpad.shouldActivate(ev)) {
+    if (this.scratchpad.activate(this.element.value)) {
+      this._setInputInternal('', true);
+    }
+    return;
+  }
+
   // RETURN does a special exec/highlight thing
   if (ev.keyCode === KeyEvent.DOM_VK_RETURN) {
     var worst = this.requisition.getStatus();
     // Deny RETURN unless the command might work
     if (worst === Status.VALID) {
       this._scrollingThroughHistory = false;
       this.history.add(this.element.value);
       this.requisition.exec();
@@ -5958,16 +5970,21 @@ Inputter.prototype.getInputState = funct
 
   // Workaround for potential XUL bug 676520 where textbox gives incorrect
   // values for its content
   if (input.typed == null) {
     input = { typed: '', cursor: { start: 0, end: 0 } };
     console.log('fixing input.typed=""', input);
   }
 
+  // Workaround for a Bug 717268 (which is really a jsdom bug)
+  if (input.cursor.start == null) {
+    input.cursor.start = 0;
+  }
+
   return input;
 };
 
 cliView.Inputter = Inputter;
 
 
 /**
  * Completer is an 'input-like' element that sits  an input element annotating
@@ -5981,16 +5998,17 @@ cliView.Inputter = Inputter;
  * - completionPrompt (optional) The prompt - defaults to '\u00bb'
  *   (double greater-than, a.k.a right guillemet). The prompt is used directly
  *   in a TextNode, so HTML entities are not allowed.
  */
 function Completer(options) {
   this.document = options.document || document;
   this.requisition = options.requisition;
   this.elementCreated = false;
+  this.scratchpad = options.scratchpad;
 
   this.element = options.completeElement || 'gcli-row-complete';
   if (typeof this.element === 'string') {
     var name = this.element;
     this.element = this.document.getElementById(name);
 
     if (!this.element) {
       this.elementCreated = true;
@@ -6074,16 +6092,21 @@ Completer.prototype.decorate = function(
     this.resizer();
   }
 };
 
 /**
  * Ensure that the completion element is the same size and the inputter element
  */
 Completer.prototype.resizer = function() {
+  // Remove this when jsdom does getBoundingClientRect(). See Bug 717269
+  if (!this.inputter.element.getBoundingClientRect) {
+    return;
+  }
+
   var rect = this.inputter.element.getBoundingClientRect();
   // -4 to line up with 1px of padding and border, top and bottom
   var height = rect.bottom - rect.top - 4;
 
   this.element.style.top = rect.top + 'px';
   this.element.style.height = height + 'px';
   this.element.style.lineHeight = height + 'px';
   this.element.style.left = rect.left + 'px';
@@ -6118,16 +6141,17 @@ Completer.prototype.update = function(in
   // which is complex due to a need to merge spans.
   // Bug 707131 questions if we couldn't simplify this to use a template.
   //
   // <span class="gcli-prompt">${completionPrompt}</span>
   // ${appendMarkupStatus()}
   // ${prefix}
   // <span class="gcli-in-ontab">${contents}</span>
   // <span class="gcli-in-closebrace" if="${unclosedJs}">}<span>
+  // <div class="gcli-in-scratchlink">${scratchLink}</div>
 
   var document = this.element.ownerDocument;
   var prompt = dom.createElement(document, 'span');
   prompt.classList.add('gcli-prompt');
   prompt.appendChild(document.createTextNode(this.completionPrompt + ' '));
   this.element.appendChild(prompt);
 
   if (input.typed.length > 0) {
@@ -6161,24 +6185,34 @@ Completer.prototype.update = function(in
     suffix.classList.add('gcli-in-ontab');
     suffix.appendChild(document.createTextNode(contents));
     this.element.appendChild(suffix);
   }
 
   // Add a grey '}' to the end of the command line when we've opened
   // with a { but haven't closed it
   var command = this.requisition.commandAssignment.getValue();
-  var unclosedJs = command && command.name === '{' &&
+  var isJsCommand = (command && command.name === '{');
+  var isUnclosedJs = isJsCommand &&
           this.requisition.getAssignment(0).getArg().suffix.indexOf('}') === -1;
-  if (unclosedJs) {
+  if (isUnclosedJs) {
     var close = dom.createElement(document, 'span');
     close.classList.add('gcli-in-closebrace');
     close.appendChild(document.createTextNode(' }'));
     this.element.appendChild(close);
   }
+
+  // Create a scratchpad link if it's a JS command and we have a function to
+  // actually perform the request
+  if (isJsCommand && this.scratchpad) {
+    var hint = dom.createElement(document, 'div');
+    hint.classList.add('gcli-in-scratchlink');
+    hint.appendChild(document.createTextNode(this.scratchpad.linkText));
+    this.element.appendChild(hint);
+  }
 };
 
 /**
  * Mark-up an array of Status values with spans
  */
 Completer.prototype.appendMarkupStatus = function(element, scores, input) {
   if (scores.length === 0) {
     return;
@@ -6281,17 +6315,18 @@ History.prototype.backward = function() 
   if (this._current < this._buffer.length - 1) {
     this._current++;
   }
   return this._buffer[this._current];
 };
 
 exports.History = History;
 
-});define("text!gcli/ui/inputter.css", [], void 0);
+});define("text!gcli/ui/inputter.css", [], "");
+
 /*
  * Copyright 2009-2011 Mozilla Foundation and contributors
  * Licensed under the New BSD license. See LICENSE.txt or:
  * http://opensource.org/licenses/BSD-3-Clause
  */
 
 define('gcli/ui/arg_fetch', ['require', 'exports', 'module' , 'gcli/util', 'gcli/types', 'gcli/ui/field', 'gcli/ui/domtemplate', 'text!gcli/ui/arg_fetch.css', 'text!gcli/ui/arg_fetch.html'], function(require, exports, module) {
 var argFetch = exports;
@@ -7414,31 +7449,33 @@ CommandMenu.prototype.onCommandChange = 
     this.hide();
   }
 };
 
 exports.CommandMenu = CommandMenu;
 
 
 });
-define("text!gcli/ui/menu.css", [], void 0);
+define("text!gcli/ui/menu.css", [], "");
+
 define("text!gcli/ui/menu.html", [], "\n" +
   "<table class=\"gcli-menu-template\" aria-live=\"polite\">\n" +
   "  <tr class=\"gcli-menu-option\" foreach=\"item in ${items}\"\n" +
   "      onclick=\"${onItemClick}\" title=\"${item.manual || ''}\">\n" +
   "    <td class=\"gcli-menu-name\">${item.name}</td>\n" +
   "    <td class=\"gcli-menu-desc\">${item.description}</td>\n" +
   "  </tr>\n" +
   "  <tr if=\"${error}\">\n" +
   "    <td class=\"gcli-menu-error\" colspan=\"2\">${error}</td>\n" +
   "  </tr>\n" +
   "</table>\n" +
   "");
 
-define("text!gcli/ui/arg_fetch.css", [], void 0);
+define("text!gcli/ui/arg_fetch.css", [], "");
+
 define("text!gcli/ui/arg_fetch.html", [], "\n" +
   "<!--\n" +
   "Template for an Assignment.\n" +
   "Evaluated each time the commandAssignment changes\n" +
   "-->\n" +
   "<div class=\"gcli-af-template\" aria-live=\"polite\">\n" +
   "  <div>\n" +
   "    <div class=\"gcli-af-cmddesc\">\n" +
--- a/browser/devtools/webconsole/test/Makefile.in
+++ b/browser/devtools/webconsole/test/Makefile.in
@@ -145,16 +145,17 @@ include $(topsrcdir)/config/rules.mk
 	browser_webconsole_bug_704295.js \
 	browser_gcli_inspect.js \
 	browser_gcli_integrate.js \
 	browser_gcli_require.js \
 	browser_gcli_web.js \
 	browser_webconsole_bug_658368_time_methods.js \
 	browser_webconsole_bug_622303_persistent_filters.js \
 	browser_webconsole_window_zombie.js \
+	browser_cached_messages.js \
 	head.js \
 	$(NULL)
 
 _BROWSER_TEST_PAGES = \
 	test-console.html \
 	test-network.html \
 	test-network-request.html \
 	test-mutation.html \
@@ -217,15 +218,16 @@ include $(topsrcdir)/config/rules.mk
 	test-bug-585956-console-trace.html \
 	test-bug-644419-log-limits.html \
 	test-bug-632275-getters.html \
 	test-bug-646025-console-file-location.html \
 	test-bug-678816-content.js \
 	test-file-location.js \
 	browser_gcli_inspect.html \
 	test-bug-658368-time-methods.html \
+	test-webconsole-error-observer.html \
 	$(NULL)
 
 libs:: $(_BROWSER_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
 
 libs:: $(_BROWSER_TEST_PAGES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/browser/devtools/webconsole/test/browser_cached_messages.js
@@ -0,0 +1,83 @@
+/* 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 DevTools test code.
+ *
+ * The Initial Developer of the Original Code is Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   David Dahl <ddahl@mozilla.com>
+ *   Mihai Sucan <mihai.sucan@gmail.com>
+ *
+ * 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 ***** */
+
+const TEST_URI = "http://example.com/browser/browser/devtools/webconsole/test/test-webconsole-error-observer.html";
+
+function test()
+{
+  waitForExplicitFinish();
+
+  expectUncaughtException();
+
+  gBrowser.selectedTab = gBrowser.addTab(TEST_URI);
+
+  gBrowser.selectedBrowser.addEventListener("load", function onLoad() {
+    gBrowser.selectedBrowser.removeEventListener("load", onLoad, true);
+    testOpenUI(true);
+  }, true);
+}
+
+function testOpenUI(aTestReopen)
+{
+  // test to see if the messages are
+  // displayed when the console UI is opened
+
+  HUDService.activateHUDForContext(gBrowser.selectedTab);
+  let hudId = HUDService.getHudIdByWindow(content);
+  let hud = HUDService.getHudReferenceById(hudId);
+
+  testLogEntry(hud.outputNode, "log Bazzle",
+               "Find a console log entry from before console UI is opened",
+               false, null);
+
+  testLogEntry(hud.outputNode, "error Bazzle",
+               "Find a console error entry from before console UI is opened",
+               false, null);
+
+  testLogEntry(hud.outputNode, "bazBug611032", "Found the JavaScript error");
+  testLogEntry(hud.outputNode, "cssColorBug611032", "Found the CSS error");
+
+  HUDService.deactivateHUDForContext(gBrowser.selectedTab);
+
+  if (aTestReopen) {
+    HUDService.deactivateHUDForContext(gBrowser.selectedTab);
+    executeSoon(testOpenUI);
+  } else {
+    executeSoon(finish);
+  }
+}
--- a/browser/devtools/webconsole/test/browser_gcli_web.js
+++ b/browser/devtools/webconsole/test/browser_gcli_web.js
@@ -49,39 +49,83 @@ var define = obj.gcli._internal.define;
 var console = obj.gcli._internal.console;
 var Node = Components.interfaces.nsIDOMNode;
 /*
  * Copyright 2009-2011 Mozilla Foundation and contributors
  * Licensed under the New BSD license. See LICENSE.txt or:
  * http://opensource.org/licenses/BSD-3-Clause
  */
 
-define('gclitest/suite', ['require', 'exports', 'module' , 'gcli/index', 'test/examiner', 'gclitest/testTokenize', 'gclitest/testSplit', 'gclitest/testCli', 'gclitest/testExec', 'gclitest/testKeyboard', 'gclitest/testHistory', 'gclitest/testRequire', 'gclitest/testJs'], function(require, exports, module) {
+define('gclitest/index', ['require', 'exports', 'module' , 'gclitest/suite', 'gcli/types/javascript'], function(require, exports, module) {
+
+  var examiner = require('gclitest/suite').examiner;
+  var javascript = require('gcli/types/javascript');
+
+  /**
+   * Run the tests defined in the test suite
+   * @param options How the tests are run. Properties include:
+   * - window: The browser window object to run the tests against
+   * - useFakeWindow: Use a test subset and a fake DOM to avoid a real document
+   * - detailedResultLog: console.log test passes and failures in more detail
+   */
+  exports.run = function(options) {
+    options = options || {};
+
+    if (options.useFakeWindow) {
+      // A minimum fake dom to get us through the JS tests
+      var doc = { title: 'Fake DOM' };
+      var fakeWindow = {
+        window: { document: doc },
+        document: doc
+      };
+
+      options.window = fakeWindow;
+    }
+
+    if (options.window) {
+      javascript.setGlobalObject(options.window);
+    }
+
+    examiner.run(options);
+
+    if (options.detailedResultLog) {
+      examiner.log();
+    }
+    else {
+      console.log('Completed test suite');
+    }
+  };
+});
+/*
+ * Copyright 2009-2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE.txt or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+define('gclitest/suite', ['require', 'exports', 'module' , 'gcli/index', 'test/examiner', 'gclitest/testTokenize', 'gclitest/testSplit', 'gclitest/testCli', 'gclitest/testExec', 'gclitest/testKeyboard', 'gclitest/testScratchpad', 'gclitest/testHistory', 'gclitest/testRequire', 'gclitest/testJs'], function(require, exports, module) {
 
   // We need to make sure GCLI is initialized before we begin testing it
   require('gcli/index');
 
   var examiner = require('test/examiner');
 
   // It's tempting to want to unify these strings and make addSuite() do the
   // call to require(), however that breaks the build system which looks for
   // the strings passed to require
   examiner.addSuite('gclitest/testTokenize', require('gclitest/testTokenize'));
   examiner.addSuite('gclitest/testSplit', require('gclitest/testSplit'));
   examiner.addSuite('gclitest/testCli', require('gclitest/testCli'));
   examiner.addSuite('gclitest/testExec', require('gclitest/testExec'));
   examiner.addSuite('gclitest/testKeyboard', require('gclitest/testKeyboard'));
+  examiner.addSuite('gclitest/testScratchpad', require('gclitest/testScratchpad'));
   examiner.addSuite('gclitest/testHistory', require('gclitest/testHistory'));
   examiner.addSuite('gclitest/testRequire', require('gclitest/testRequire'));
   examiner.addSuite('gclitest/testJs', require('gclitest/testJs'));
 
-  examiner.run();
-  console.log('Completed test suite');
-  // examiner.log();
-
+  exports.examiner = examiner;
 });
 /*
  * Copyright 2009-2011 Mozilla Foundation and contributors
  * Licensed under the New BSD license. See LICENSE.txt or:
  * http://opensource.org/licenses/BSD-3-Clause
  */
 
 define('test/examiner', ['require', 'exports', 'module' ], function(require, exports, module) {
@@ -114,46 +158,46 @@ var stati = {
  */
 examiner.addSuite = function(name, suite) {
   examiner.suites[name] = new Suite(name, suite);
 };
 
 /**
  * Run all the tests synchronously
  */
-examiner.run = function() {
+examiner.run = function(options) {
   Object.keys(examiner.suites).forEach(function(suiteName) {
     var suite = examiner.suites[suiteName];
-    suite.run();
+    suite.run(options);
   }.bind(this));
   return examiner.suites;
 };
 
 /**
  * Run all the tests asynchronously
  */
-examiner.runAsync = function(callback) {
-  this.runAsyncInternal(0, callback);
+examiner.runAsync = function(options, callback) {
+  this.runAsyncInternal(0, options, callback);
 };
 
 /**
  * Run all the test suits asynchronously
  */
-examiner.runAsyncInternal = function(i, callback) {
+examiner.runAsyncInternal = function(i, options, callback) {
   if (i >= Object.keys(examiner.suites).length) {
     if (typeof callback === 'function') {
       callback();
     }
     return;
   }
 
   var suiteName = Object.keys(examiner.suites)[i];
-  examiner.suites[suiteName].runAsync(function() {
+  examiner.suites[suiteName].runAsync(options, function() {
     setTimeout(function() {
-      examiner.runAsyncInternal(i + 1, callback);
+      examiner.runAsyncInternal(i + 1, options, callback);
     }.bind(this), delay);
   }.bind(this));
 };
 
 /**
  *
  */
 examiner.reportToText = function() {
@@ -217,65 +261,65 @@ function Suite(suiteName, suite) {
       this.tests[testName] = test;
     }
   }.bind(this));
 }
 
 /**
  * Run all the tests in this suite synchronously
  */
-Suite.prototype.run = function() {
+Suite.prototype.run = function(options) {
   if (typeof this.suite.setup == "function") {
-    this.suite.setup();
+    this.suite.setup(options);
   }
 
   Object.keys(this.tests).forEach(function(testName) {
     var test = this.tests[testName];
-    test.run();
+    test.run(options);
   }.bind(this));
 
   if (typeof this.suite.shutdown == "function") {
-    this.suite.shutdown();
+    this.suite.shutdown(options);
   }
 };
 
 /**
  * Run all the tests in this suite asynchronously
  */
-Suite.prototype.runAsync = function(callback) {
+Suite.prototype.runAsync = function(options, callback) {
   if (typeof this.suite.setup == "function") {
     this.suite.setup();
   }
 
-  this.runAsyncInternal(0, function() {
+  this.runAsyncInternal(0, options, function() {
     if (typeof this.suite.shutdown == "function") {
       this.suite.shutdown();
     }
 
     if (typeof callback === 'function') {
       callback();
     }
   }.bind(this));
 };
 
 /**
  * Function used by the async runners that can handle async recursion.
  */
-Suite.prototype.runAsyncInternal = function(i, callback) {
+Suite.prototype.runAsyncInternal = function(i, options, callback) {
   if (i >= Object.keys(this.tests).length) {
     if (typeof callback === 'function') {
       callback();
     }
     return;
   }
 
   var testName = Object.keys(this.tests)[i];
-  this.tests[testName].runAsync(function() {
+  this.tests[testName].runAsync(options, function() {
     setTimeout(function() {
-      this.runAsyncInternal(i + 1, callback);
+      this.runAsyncInternal(i + 1, options, callback);
     }.bind(this), delay);
   }.bind(this));
 };
 
 /**
  * Create a JSON object suitable for serialization
  */
 Suite.prototype.toRemote = function() {
@@ -299,23 +343,23 @@ function Test(suite, name, func) {
 
   this.messages = [];
   this.status = stati.notrun;
 }
 
 /**
  * Run just a single test
  */
-Test.prototype.run = function() {
+Test.prototype.run = function(options) {
   currentTest = this;
   this.status = stati.executing;
   this.messages = [];
 
   try {
-    this.func.apply(this.suite);
+    this.func.apply(this.suite, [ options ]);
   }
   catch (ex) {
     this.status = stati.fail;
     this.messages.push('' + ex);
     console.error(ex);
     if (ex.stack) {
       console.error(ex.stack);
     }
@@ -326,17 +370,17 @@ Test.prototype.run = function() {
   }
 
   currentTest = null;
 };
 
 /**
  * Run all the tests in this suite asynchronously
  */
-Test.prototype.runAsync = function(callback) {
+Test.prototype.runAsync = function(options, callback) {
   setTimeout(function() {
     this.run();
     if (typeof callback === 'function') {
       callback();
     }
   }.bind(this), delay);
 };
 
@@ -1505,24 +1549,28 @@ function check(initial, action, after) {
     case KEY_DOWNS_TO:
       assignment.decrement();
       break;
   }
 
   test.is(after, requisition.toString(), initial + ' + ' + action + ' -> ' + after);
 }
 
-exports.testComplete = function() {
+exports.testComplete = function(options) {
   check('tsela', COMPLETES_TO, 'tselarr ');
   check('tsn di', COMPLETES_TO, 'tsn dif ');
   check('tsg a', COMPLETES_TO, 'tsg aaa ');
 
   check('{ wind', COMPLETES_TO, '{ window');
   check('{ window.docum', COMPLETES_TO, '{ window.document');
-  check('{ window.document.titl', COMPLETES_TO, '{ window.document.title ');
+
+  // Bug 717228: This fails under node
+  if (!options.isNode) {
+    check('{ window.document.titl', COMPLETES_TO, '{ window.document.title ');
+  }
 };
 
 exports.testIncrDecr = function() {
   check('tsu -70', KEY_UPS_TO, 'tsu -5');
   check('tsu -7', KEY_UPS_TO, 'tsu -5');
   check('tsu -6', KEY_UPS_TO, 'tsu -5');
   check('tsu -5', KEY_UPS_TO, 'tsu -3');
   check('tsu -4', KEY_UPS_TO, 'tsu -3');
@@ -1574,16 +1622,69 @@ exports.testIncrDecr = function() {
 
 });
 /*
  * Copyright 2009-2011 Mozilla Foundation and contributors
  * Licensed under the New BSD license. See LICENSE.txt or:
  * http://opensource.org/licenses/BSD-3-Clause
  */
 
+define('gclitest/testScratchpad', ['require', 'exports', 'module' , 'test/assert'], function(require, exports, module) {
+
+
+var test = require('test/assert');
+
+var origScratchpad;
+
+exports.setup = function(options) {
+  if (options.inputter) {
+    origScratchpad = options.inputter.scratchpad;
+    options.inputter.scratchpad = stubScratchpad;
+  }
+};
+
+exports.shutdown = function(options) {
+  if (options.inputter) {
+    options.inputter.scratchpad = origScratchpad;
+  }
+};
+
+var stubScratchpad = {
+  shouldActivate: function(ev) {
+    return true;
+  },
+  activatedCount: 0,
+  linkText: 'scratchpad.linkText'
+};
+stubScratchpad.activate = function(value) {
+  stubScratchpad.activatedCount++;
+  return true;
+};
+
+
+exports.testActivate = function(options) {
+  if (options.inputter) {
+    var ev = {};
+    stubScratchpad.activatedCount = 0;
+    options.inputter.onKeyUp(ev);
+    test.is(1, stubScratchpad.activatedCount, 'scratchpad is activated');
+  }
+  else {
+    console.log('Skipping scratchpad tests');
+  }
+};
+
+
+});
+/*
+ * Copyright 2009-2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE.txt or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
 define('gclitest/testHistory', ['require', 'exports', 'module' , 'test/assert', 'gcli/history'], function(require, exports, module) {
 
 var test = require('test/assert');
 var History = require('gcli/history').History;
 
 exports.setup = function() {
 };
 
@@ -1823,16 +1924,21 @@ function check(expStatuses, expStatus, e
       expPredict.forEach(function(p) {
         contains = predictionsHas(p);
         test.ok(contains, 'missing prediction ' + p);
       });
     }
     else if (typeof expPredict === 'number') {
       contains = true;
       test.is(assign.getPredictions().length, expPredict, 'prediction count');
+      if (assign.getPredictions().length !== expPredict) {
+        assign.getPredictions().forEach(function(prediction) {
+          console.log('actual prediction: ', prediction);
+        });
+      }
     }
     else {
       contains = predictionsHas(expPredict);
       test.ok(contains, 'missing prediction ' + expPredict);
     }
 
     if (!contains) {
       console.log('Predictions: ' + assign.getPredictions().map(function(p) {
@@ -1851,17 +1957,17 @@ exports.testBasic = function() {
 
   input('{ w');
   check('VVI', Status.ERROR, 'w', 'window');
 
   input('{ windo');
   check('VVIIIII', Status.ERROR, 'windo', 'window');
 
   input('{ window');
-  check('VVVVVVVV', Status.VALID, 'window', 0);
+  check('VVVVVVVV', Status.VALID, 'window');
 
   input('{ window.d');
   check('VVIIIIIIII', Status.ERROR, 'window.d', 'window.document');
 
   input('{ window.document.title');
   check('VVVVVVVVVVVVVVVVVVVVVVV', Status.VALID, 'window.document.title', 0);
 
   input('{ d');
@@ -1893,39 +1999,43 @@ exports.testBasic = function() {
   input('{ donteval.xxx');
   check('VVVVVVVVVVVVVV', Status.VALID, 'donteval.xxx', 0);
 };
 
 
 });
 
 function undefine() {
+  delete define.modules['gclitest/index'];
   delete define.modules['gclitest/suite'];
   delete define.modules['test/examiner'];
   delete define.modules['gclitest/testTokenize'];
   delete define.modules['test/assert'];
   delete define.modules['gclitest/testSplit'];
   delete define.modules['gclitest/commands'];
   delete define.modules['gclitest/testCli'];
   delete define.modules['gclitest/testExec'];
   delete define.modules['gclitest/testKeyboard'];
+  delete define.modules['gclitest/testScratchpad'];
   delete define.modules['gclitest/testHistory'];
   delete define.modules['gclitest/testRequire'];
   delete define.modules['gclitest/requirable'];
   delete define.modules['gclitest/testJs'];
 
+  delete define.globalDomain.modules['gclitest/index'];
   delete define.globalDomain.modules['gclitest/suite'];
   delete define.globalDomain.modules['test/examiner'];
   delete define.globalDomain.modules['gclitest/testTokenize'];
   delete define.globalDomain.modules['test/assert'];
   delete define.globalDomain.modules['gclitest/testSplit'];
   delete define.globalDomain.modules['gclitest/commands'];
   delete define.globalDomain.modules['gclitest/testCli'];
   delete define.globalDomain.modules['gclitest/testExec'];
   delete define.globalDomain.modules['gclitest/testKeyboard'];
+  delete define.globalDomain.modules['gclitest/testScratchpad'];
   delete define.globalDomain.modules['gclitest/testHistory'];
   delete define.globalDomain.modules['gclitest/testRequire'];
   delete define.globalDomain.modules['gclitest/requirable'];
   delete define.globalDomain.modules['gclitest/testJs'];
 }
 
 registerCleanupFunction(function() {
   Services.prefs.clearUserPref("devtools.gcli.enable");
@@ -1943,22 +2053,30 @@ function test() {
 }
 
 function onLoad() {
   browser.removeEventListener("DOMContentLoaded", onLoad, false);
   var failed = false;
 
   try {
     openConsole();
-    define.globalDomain.require("gclitest/index");
+
+    var gcliterm = HUDService.getHudByWindow(content).gcliterm;
+
+    var gclitest = define.globalDomain.require("gclitest/index");
+    gclitest.run({
+      window: gcliterm.document.defaultView,
+      inputter: gcliterm.opts.console.inputter,
+      requisition: gcliterm.opts.requistion
+    });
   }
   catch (ex) {
     failed = ex;
-    console.error('Test Failure', ex);
-    ok(false, '' + ex);
+    console.error("Test Failure", ex);
+    ok(false, "" + ex);
   }
   finally {
     closeConsole();
     finish();
   }
 
   if (failed) {
     throw failed;
--- a/browser/devtools/webconsole/test/browser_webconsole_bug_611795.js
+++ b/browser/devtools/webconsole/test/browser_webconsole_bug_611795.js
@@ -43,12 +43,15 @@ registerCleanupFunction(function() {
 function test()
 {
   Services.prefs.setBoolPref("devtools.gcli.enable", false);
   addTab(TEST_URI);
   browser.addEventListener("load", function() {
     browser.removeEventListener("load", arguments.callee, true);
 
     openConsole();
+    // Clear cached messages that are shown once the Web Console opens.
+    HUDService.getHudByWindow(content).jsterm.clearOutput(true);
+
     browser.addEventListener("load", onContentLoaded, true);
     content.location.reload();
   }, true);
 }
--- a/browser/devtools/webconsole/test/browser_webconsole_notifications.js
+++ b/browser/devtools/webconsole/test/browser_webconsole_notifications.js
@@ -14,63 +14,61 @@
  *
  * The Original Code is DevTools test code.
  *
  * The Initial Developer of the Original Code is Mozilla Foundation.
  * Portions created by the Initial Developer are Copyright (C) 2010
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
- *  David Dahl <ddahl@mozilla.com>
+ *   David Dahl <ddahl@mozilla.com>
+ *   Mihai Sucan <mihai.sucan@gmail.com>
  *
  * 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 ***** */
 
-const TEST_URI = "http://example.com/browser/browser/devtools/webconsole/test//test-console.html";
+const TEST_URI = "data:text/html,<p>Web Console test for notifications";
 
 function test() {
   observer.init();
   addTab(TEST_URI);
-  browser.addEventListener("DOMContentLoaded", onLoad, false);
+  browser.addEventListener("load", onLoad, true);
 }
 
 function webConsoleCreated(aID)
 {
   Services.obs.removeObserver(observer, "web-console-created");
-  executeSoon(function (){
-    ok(HUDService.hudReferences[aID], "We have a hud reference");
-    let console = browser.contentWindow.wrappedJSObject.console;
-    console.log("adding a log message");
-  });
+  ok(HUDService.hudReferences[aID], "We have a hud reference");
+  content.wrappedJSObject.console.log("adding a log message");
 }
 
 function webConsoleDestroyed(aID)
 {
   Services.obs.removeObserver(observer, "web-console-destroyed");
   ok(!HUDService.hudReferences[aID], "We do not have a hud reference");
-  finishTest();
+  executeSoon(finishTest);
 }
 
 function webConsoleMessage(aID, aNodeID)
 {
   Services.obs.removeObserver(observer, "web-console-message-created");
   ok(aID, "we have a console ID");
-  ok(typeof aNodeID == 'string', "message node id is not null");
-  closeConsole();
+  is(typeof aNodeID, "string", "message node id is a string");
+  executeSoon(closeConsole);
 }
 
 let observer = {
 
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]),
 
   observe: function observe(aSubject, aTopic, aData)
   {
@@ -95,11 +93,11 @@ let observer = {
   {
     Services.obs.addObserver(this, "web-console-created", false);
     Services.obs.addObserver(this, "web-console-destroyed", false);
     Services.obs.addObserver(this, "web-console-message-created", false);
   }
 };
 
 function onLoad() {
-  browser.removeEventListener("DOMContentLoaded", onLoad, false);
+  browser.removeEventListener("load", onLoad, true);
   openConsole();
 }
new file mode 100644
--- /dev/null
+++ b/browser/devtools/webconsole/test/test-webconsole-error-observer.html
@@ -0,0 +1,24 @@
+<!DOCTYPE HTML>
+<html dir="ltr" xml:lang="en-US" lang="en-US">
+  <head>
+    <title>WebConsoleErrorObserver test - bug 611032</title>
+    <!-- Any copyright is dedicated to the Public Domain.
+         http://creativecommons.org/publicdomain/zero/1.0/ -->
+    <script type="text/javascript">
+      console.log("log Bazzle");
+      console.info("info Bazzle");
+      console.warn("warn Bazzle");
+      console.error("error Bazzle");
+
+      var foo = {};
+      foo.bazBug611032();
+    </script>
+    <style type="text/css">
+      .foo { color: cssColorBug611032; }
+    </style>
+  </head>
+  <body>
+    <h1>WebConsoleErrorObserver test</h1>
+  </body>
+</html>
+
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -129,17 +129,16 @@
 @BINPATH@/components/content_htmldoc.xpt
 @BINPATH@/components/content_html.xpt
 @BINPATH@/components/content_xslt.xpt
 @BINPATH@/components/content_xtf.xpt
 @BINPATH@/components/cookie.xpt
 @BINPATH@/components/directory.xpt
 @BINPATH@/components/docshell.xpt
 @BINPATH@/components/dom.xpt
-@BINPATH@/components/dom_apps.xpt
 @BINPATH@/components/dom_base.xpt
 #ifdef MOZ_B2G_RIL
 @BINPATH@/components/dom_telephony.xpt
 @BINPATH@/components/dom_wifi.xpt
 @BINPATH@/components/dom_system_b2g.xpt
 #endif
 @BINPATH@/components/dom_battery.xpt
 @BINPATH@/components/dom_canvas.xpt
@@ -384,18 +383,16 @@
 @BINPATH@/components/nsPrompter.manifest
 @BINPATH@/components/nsPrompter.js
 #ifdef MOZ_SERVICES_SYNC
 @BINPATH@/components/SyncComponents.manifest
 @BINPATH@/components/Weave.js
 #endif
 @BINPATH@/components/TelemetryPing.js
 @BINPATH@/components/TelemetryPing.manifest
-@BINPATH@/components/Webapps.js
-@BINPATH@/components/Webapps.manifest
 
 ; Modules
 @BINPATH@/modules/*
 
 ; Safe Browsing
 @BINPATH@/components/nsSafebrowsingApplication.manifest
 @BINPATH@/components/nsSafebrowsingApplication.js
 @BINPATH@/components/nsURLClassifier.manifest
--- a/browser/locales/en-US/chrome/browser/browser.dtd
+++ b/browser/locales/en-US/chrome/browser/browser.dtd
@@ -212,18 +212,23 @@ can reach it easily. -->
 <!ENTITY scratchpad.accesskey         "s">
 <!ENTITY scratchpad.keycode           "VK_F4">
 <!ENTITY scratchpad.keytext           "F4">
 
 <!ENTITY inspectPanelTitle.label        "HTML">
 <!ENTITY inspectButton.label            "Inspect">
 <!ENTITY inspectButton.accesskey        "I">
 <!ENTITY inspectCloseButton.tooltiptext "Close Inspector">
-<!ENTITY inspect3DButton.label        "3D">
-<!ENTITY inspect3DButton.accesskey    "M">
+
+<!-- LOCALIZATION NOTE (inspect3DViewButton.label): This button shows an
+  -  alternate view for the Inspector, creating a 3D visualization of the
+  -  webpage. -->
+<!ENTITY inspect3DViewButton.label     "3D View">
+<!ENTITY inspect3DViewButton.accesskey "W">
+
 <!ENTITY inspectStyleButton.label     "Style">
 <!ENTITY inspectStyleButton.accesskey "S">
 
 <!-- LOCALIZATION NOTE (styleeditor.label): This menu item label appears
   -  in the Tools menu. -->
 <!ENTITY styleeditor.label            "Style Editor">
 <!ENTITY styleeditor.accesskey        "y">
 <!ENTITY styleeditor.keycode          "VK_F7">
--- a/browser/locales/en-US/chrome/browser/devtools/gcli.properties
+++ b/browser/locales/en-US/chrome/browser/devtools/gcli.properties
@@ -15,17 +15,17 @@ canonDescNone=(No description)
 # of JavaScript like traditional developer tool command lines. This describes
 # the '{' command.
 cliEvalJavascript=Enter JavaScript directly
 
 # LOCALIZATION NOTE (fieldSelectionSelect): When a command has a parameter
 # that has a number of pre-defined options the user interface presents these
 # in a drop-down menu, where the first 'option' is an indicator that a
 # selection should be made. This string describes that first option.
-fieldSelectionSelect=Select a %S …
+fieldSelectionSelect=Select a %S…
 
 # LOCALIZATION NOTE (fieldArrayAdd): When a command has a parameter that can
 # be repeated a number of times (e.g. like the 'cat a.txt b.txt' command) the
 # user interface presents buttons to add and remove arguments. This string is
 # used to add arguments.
 fieldArrayAdd=Add
 
 # LOCALIZATION NOTE (fieldArrayDel): When a command has a parameter that can
--- a/browser/locales/en-US/chrome/browser/devtools/styleinspector.properties
+++ b/browser/locales/en-US/chrome/browser/devtools/styleinspector.properties
@@ -28,18 +28,19 @@ rule.sourceElement=element
 
 # LOCALIZATION NOTE (rule.inheritedSource): Shown for CSS rules
 # that were inherited from a parent node.  Will be passed a node
 # identifier and a source location.
 # e.g "Inherited from body#bodyID (styles.css:20)"
 rule.inheritedSource=Inherited from %S (%S)
 
 # LOCALIZATION NOTE (style.highlighter.button): These strings are used inside
-# sidebar of the Highlighter for the style inspector button
-style.highlighter.button.label1=Properties
-style.highlighter.accesskey1=P
-style.highlighter.button.tooltip=Inspect element styles
+# sidebar of the Highlighter for the style inspector button.
+# "Computed" refers to the Computed Style of the element.
+style.highlighter.button.label2=Computed
+style.highlighter.accesskey2=C
+style.highlighter.button.tooltip=Inspect element computed styles
 
 # LOCALIZATION NOTE (helpLinkTitle): For each style property
 # the user can hover it and get a help link button which allows one to
 # quickly jump to the documentation from the Mozilla Developer Network site.
 # This is the link title shown in the hover tooltip.
 helpLinkTitle=Read the documentation for this property
--- a/browser/locales/en-US/chrome/browser/devtools/webconsole.properties
+++ b/browser/locales/en-US/chrome/browser/devtools/webconsole.properties
@@ -141,16 +141,21 @@ webConsolePositionBelow=Below
 webConsolePositionWindow=Window
 
 # LOCALIZATION NOTE (webConsoleWindowTitleAndURL): The Web Console floating
 # panel title, followed by the web page URL.
 # For RTL languages you need to set the LRM in the string to give the URL
 # the correct direction.
 webConsoleWindowTitleAndURL=Web Console - %S
 
+# LOCALIZATION NOTE (scratchpad.linkText):
+# The text used in the right hand side of the web console command line when
+# Javascript is being entered, to indicate how to jump into scratchpad mode
+scratchpad.linkText=Shift+RETURN - Open in Scratchpad
+
 # LOCALIZATION NOTE (Autocomplete.label):
 # The autocomplete popup panel label/title.
 Autocomplete.label=Autocomplete popup
 
 # LOCALIZATION NOTE (stacktrace.anonymousFunction):
 # This string is used to display JavaScript functions that have no given name -
 # they are said to be anonymous. See stacktrace.outputMessage.
 stacktrace.anonymousFunction=<anonymous>
--- a/browser/themes/gnomestripe/browser.css
+++ b/browser/themes/gnomestripe/browser.css
@@ -1998,16 +1998,20 @@ panel[dimmed="true"] {
   -moz-border-start: 1px solid #242b33;
   min-width: 0;
   width: 3px;
   background-color: transparent;
   -moz-margin-end: -3px;
   position: relative;
 }
 
+#devtools-sidebar-box {
+  background-color: -moz-Field;
+}
+
 /* Highlighter - toolbar resizers */
 
 .inspector-resizer {
   -moz-appearance: none;
   cursor: n-resize;
 }
 
 #inspector-top-resizer {
--- a/browser/themes/gnomestripe/devtools/csshtmltree.css
+++ b/browser/themes/gnomestripe/devtools/csshtmltree.css
@@ -229,20 +229,16 @@
   width: 8px;
   height: 8px;
   background: url("chrome://browser/skin/devtools/arrows.png") 24px 0;
   cursor: pointer;
   -moz-margin-start: 2px;
   -moz-margin-end: 5px;
 }
 
-.ruleview-expander:-moz-locale-dir(rtl) {
-  background-position: 16px 0;
-}
-
 .ruleview-expander.styleinspector-open {
   background-position: 8px 0;
 }
 
 .ruleview-newproperty {
   /* (enable checkbox width: 12px) + (expander width: 15px) */
   -moz-margin-start: 27px;
 }
--- a/browser/themes/gnomestripe/devtools/gcli.css
+++ b/browser/themes/gnomestripe/devtools/gcli.css
@@ -168,31 +168,29 @@
 .gcli-out-shortcut {
   font-family: "DejaVu Sans Mono", monospace;
 }
 
 /* From: $GCLI/lib/gcli/ui/arg_fetch.css */
 
 .gcli-argfetch {
   width: 100%;
-  box-sizing: border-box;
   -moz-box-sizing: border-box;
 }
 
 .gcli-af-cmddesc {
   font-weight: bold;
   text-align: center;
   margin-bottom: 5px;
   padding: 3px 10px 0;
 }
 
 .gcli-af-params {
   padding: 0 10px;
   width: 100%;
-  box-sizing: border-box;
   -moz-box-sizing: border-box;
 }
 
 .gcli-af-paramname {
   text-align: right;
   font-size: 90%;
 }
 
@@ -302,16 +300,23 @@
   color: #999;
 }
 
 .gcli-prompt {
   color: #66F;
   font-weight: bold;
 }
 
+.gcli-in-scratchlink {
+  float: right;
+  font-size: 85%;
+  color: #888;
+  padding-right: 10px;
+}
+
 /* From: $GCLI/lib/gcli/commands/help.css */
 
 .gcli-help-name {
   text-align: end;
 }
 
 .gcli-help-arrow {
   font-size: 70%;
--- a/browser/themes/pinstripe/browser.css
+++ b/browser/themes/pinstripe/browser.css
@@ -2735,16 +2735,20 @@ panel[dimmed="true"] {
   -moz-border-start: 1px solid #242b33;
   min-width: 0;
   width: 3px;
   background-color: transparent;
   -moz-margin-end: -3px;
   position: relative;
 }
 
+#devtools-sidebar-box {
+  background-color: -moz-Field;
+}
+
 /* Highlighter - toolbar resizers */
 
 .inspector-resizer {
   -moz-appearance: none;
   cursor: n-resize;
 }
 
 #inspector-top-resizer {
--- a/browser/themes/pinstripe/devtools/csshtmltree.css
+++ b/browser/themes/pinstripe/devtools/csshtmltree.css
@@ -231,20 +231,16 @@
   width: 8px;
   height: 8px;
   background: url("chrome://browser/skin/devtools/arrows.png") 24px 0;
   cursor: pointer;
   -moz-margin-start: 2px;
   -moz-margin-end: 5px;
 }
 
-.ruleview-expander:-moz-locale-dir(rtl) {
-  background-position: 16px 0;
-}
-
 .ruleview-expander.styleinspector-open {
   background-position: 8px 0;
 }
 
 .ruleview-newproperty {
   /* (enable checkbox width: 12px) + (expander width: 15px) */
   -moz-margin-start: 27px;
 }
--- a/browser/themes/pinstripe/devtools/gcli.css
+++ b/browser/themes/pinstripe/devtools/gcli.css
@@ -172,31 +172,29 @@
 .gcli-out-shortcut {
   font-family: Menlo, Monaco, monospace;
 }
 
 /* From: $GCLI/lib/gcli/ui/arg_fetch.css */
 
 .gcli-argfetch {
   width: 100%;
-  box-sizing: border-box;
   -moz-box-sizing: border-box;
 }
 
 .gcli-af-cmddesc {
   font-weight: bold;
   text-align: center;
   margin-bottom: 5px;
   padding: 3px 10px 0;
 }
 
 .gcli-af-params {
   padding: 0 10px;
   width: 100%;
-  box-sizing: border-box;
   -moz-box-sizing: border-box;
 }
 
 .gcli-af-paramname {
   text-align: right;
   font-size: 90%;
 }
 
@@ -306,16 +304,23 @@
   color: #999;
 }
 
 .gcli-prompt {
   color: #66F;
   font-weight: bold;
 }
 
+.gcli-in-scratchlink {
+  float: right;
+  font-size: 85%;
+  color: #888;
+  padding-right: 10px;
+}
+
 /* From: $GCLI/lib/gcli/commands/help.css */
 
 .gcli-help-name {
   text-align: end;
 }
 
 .gcli-help-arrow {
   font-size: 70%;
--- a/browser/themes/winstripe/browser.css
+++ b/browser/themes/winstripe/browser.css
@@ -2678,16 +2678,20 @@ panel[dimmed="true"] {
   -moz-border-start: 1px solid #242b33;
   min-width: 0;
   width: 3px;
   background-color: transparent;
   -moz-margin-end: -3px;
   position: relative;
 }
 
+#devtools-sidebar-box {
+  background-color: -moz-Field;
+}
+
 /* Highlighter - toolbar resizers */
 
 .inspector-resizer {
   -moz-appearance: none;
   cursor: n-resize;
 }
 
 #inspector-top-resizer {
--- a/browser/themes/winstripe/devtools/common.css
+++ b/browser/themes/winstripe/devtools/common.css
@@ -69,17 +69,17 @@
 
 .devtools-toolbarbutton[checked] {
   border-color: hsla(211,68%,6%,.6);
   background: -moz-linear-gradient(hsla(211,68%,6%,.1), hsla(211,68%,6%,.2));
   box-shadow: 0 1px 3px hsla(211,68%,6%,.5) inset, 0 0 0 1px hsla(209,29%,72%,.1), 0 1px 0 hsla(210,16%,76%,.1);
   color: hsl(200,100%,60%) !important;
 }
 
-.devtools-toolbarbutton:[checked]:hover:active {
+.devtools-toolbarbutton[checked]:hover:active {
   background-color: hsla(211,68%,6%,.2);
 }
 
 /* Search input */
 
 .devtools-searchinput {
   -moz-appearance: none;
   margin: 0 3px;
--- a/browser/themes/winstripe/devtools/csshtmltree.css
+++ b/browser/themes/winstripe/devtools/csshtmltree.css
@@ -229,20 +229,16 @@
   width: 8px;
   height: 8px;
   background: url("chrome://browser/skin/devtools/arrows.png") 24px 0;
   cursor: pointer;
   -moz-margin-start: 2px;
   -moz-margin-end: 5px;
 }
 
-.ruleview-expander:-moz-locale-dir(rtl) {
-  background-position: 16px 0;
-}
-
 .ruleview-expander.styleinspector-open {
   background-position: 8px 0;
 }
 
 .ruleview-newproperty {
   /* (enable checkbox width: 12px) + (expander width: 15px) */
   -moz-margin-start: 27px;
 }
--- a/browser/themes/winstripe/devtools/gcli.css
+++ b/browser/themes/winstripe/devtools/gcli.css
@@ -168,31 +168,29 @@
 .gcli-out-shortcut {
   font-family: Consolas, Inconsolata, "Courier New", monospace;
 }
 
 /* From: $GCLI/lib/gcli/ui/arg_fetch.css */
 
 .gcli-argfetch {
   width: 100%;
-  box-sizing: border-box;
   -moz-box-sizing: border-box;
 }
 
 .gcli-af-cmddesc {
   font-weight: bold;
   text-align: center;
   margin-bottom: 5px;
   padding: 3px 10px 0;
 }
 
 .gcli-af-params {
   padding: 0 10px;
   width: 100%;
-  box-sizing: border-box;
   -moz-box-sizing: border-box;
 }
 
 .gcli-af-paramname {
   text-align: right;
   font-size: 90%;
 }
 
@@ -302,16 +300,23 @@
   color: #999;
 }
 
 .gcli-prompt {
   color: #66F;
   font-weight: bold;
 }
 
+.gcli-in-scratchlink {
+  float: right;
+  font-size: 85%;
+  color: #888;
+  padding-right: 10px;
+}
+
 /* From: $GCLI/lib/gcli/commands/help.css */
 
 .gcli-help-name {
   text-align: end;
 }
 
 .gcli-help-arrow {
   font-size: 70%;
--- a/build/checksums.py
+++ b/build/checksums.py
@@ -31,16 +31,18 @@
 # use your version of this file under the terms of the MPL, indicate your
 # decision by deleting the provisions above and replace them with the notice
 # and other provisions required by the GPL or the LGPL. If you do not delete
 # the provisions above, a recipient may use your version of this file under
 # the terms of any one of the MPL, the GPL or the LGPL.
 #
 # ***** END LICENSE BLOCK *****
 
+from __future__ import with_statement
+
 from optparse import OptionParser
 import logging
 import os
 try:
     import hashlib
 except:
     hashlib = None
 
@@ -52,75 +54,74 @@ def digest_file(filename, digest, chunk_
     work, the None object will be returned instead.  The size of blocks
     that this function will read from the file object it opens based on
     'filename' can be specified by 'chunk_size', which defaults to 1K'''
     assert not os.path.isdir(filename), 'this function only works with files'
     logger = logging.getLogger('checksums.py')
     if hashlib is not None:
         logger.debug('Creating new %s object' % digest)
         h = hashlib.new(digest)
-        f = open(filename, "rb")
-        while True:
-            data = f.read(chunk_size)
-            if not data:
-                logger.debug('Finished reading in file')
-                break
-            h.update(data)
-        f.close()
+        with open(filename, 'rb') as f:
+            while True:
+                data = f.read(chunk_size)
+                if not data:
+                    logger.debug('Finished reading in file')
+                    break
+                h.update(data)
         hash = h.hexdigest()
         logger.debug('Hash for %s is %s' % (filename, hash))
         return hash
     else:
         # In this case we could subprocess.Popen and .communicate with
         # sha1sum or md5sum
         logger.warn('The python module for hashlib is missing!')
         return None
 
 
-def process_files(files, output_filename, digest, strip):
+def process_files(files, output_filename, digests, strip):
     '''This function takes a list of file names, 'files'.  It will then
     compute the checksum for each of the files by opening the files.
     Once each file is read and its checksum is computed, this function
     will write the information to the file specified by 'output_filename'.
     The path written in the output file will have anything specified by 'strip'
     removed from the path.  The output file is closed before returning nothing
-    The algorithm to compute checksums with can be specified by 'digest' 
-    and needs to be a valid OpenSSL algorithm.
+    The algorithm to compute checksums with can be specified by 'digests' 
+    and needs to be a list of valid OpenSSL algorithms.
 
     The output file is written in the format:
         <hash> <algorithm> <filesize> <filepath>
     Example:
         d1fa09a<snip>e4220 sha1 14250744 firefox-4.0b6pre.en-US.mac64.dmg
     '''
 
     logger = logging.getLogger('checksums.py')
     if os.path.exists(output_filename):
         logger.debug('Overwriting existing checksums file "%s"' %
                      output_filename)
     else:
         logger.debug('Creating a new checksums file "%s"' % output_filename)
-    output = open(output_filename, 'w+')
-    for file in files:
-        if os.path.isdir(file):
-            logger.warn('%s is a directory, skipping' % file)
-        else:
-            hash = digest_file(file, digest)
-            if hash is None:
-                logger.warn('Unable to generate a hash for %s. ' +
-                            'Using NOHASH as fallback' % file)
-                hash = 'NOHASH'
-            if file.startswith(strip):
-                short_file = file[len(strip):]
-                short_file = short_file.lstrip('/')
+    with open(output_filename, 'w+') as output:
+        for file in files:
+            if os.path.isdir(file):
+                logger.warn('%s is a directory, skipping' % file)
             else:
-                short_file = file
-            print >>output, '%s %s %s %s' % (hash, digest,
-                                             os.path.getsize(file),
-                                             short_file)
-    output.close()
+                for digest in digests:
+                    hash = digest_file(file, digest)
+                    if hash is None:
+                        logger.warn('Unable to generate a hash for %s. ' +
+                                    'Skipping.' % file)
+                        continue
+                    if file.startswith(strip):
+                        short_file = file[len(strip):]
+                        short_file = short_file.lstrip('/')
+                    else:
+                        short_file = file
+                    print >>output, '%s %s %s %s' % (hash, digest,
+                                                     os.path.getsize(file),
+                                                     short_file)
 
 def setup_logging(level=logging.DEBUG):
     '''This function sets up the logging module using a speficiable logging
     module logging level.  The default log level is DEBUG.
 
     The output is in the format:
         <level> - <message>
     Example:
@@ -136,17 +137,17 @@ def setup_logging(level=logging.DEBUG):
     logger.addHandler(handler)
 
 def main():
     '''This is a main function that parses arguments, sets up logging
     and generates a checksum file'''
     # Parse command line arguments
     parser = OptionParser()
     parser.add_option('-d', '--digest', help='checksum algorithm to use',
-                      action='store', dest='digest', default='sha1')
+                      action='append', dest='digests')
     parser.add_option('-o', '--output', help='output file to use',
                       action='store', dest='outfile', default='checksums')
     parser.add_option('-v', '--verbose',
                       help='Be noisy (takes precedence over quiet)',
                       action='store_true', dest='verbose', default=False)
     parser.add_option('-q', '--quiet', help='Be quiet', action='store_true',
                       dest='quiet', default=False)
     parser.add_option('-s', '--strip',
@@ -162,26 +163,29 @@ def main():
     else:
         loglevel = logging.INFO
 
     #Set up logging
     setup_logging(loglevel)
     logger = logging.getLogger('checksums.py')
 
     # Validate the digest type to use
+    if not options.digests:
+        options.digests = ['sha1']
     try:
-        hashlib.new(options.digest)
+        for digest in options.digests:
+            hashlib.new(digest)
     except ValueError, ve:
         logger.error('Could not create a "%s" hash object (%s)' %
-                     (options.digest, ve.args[0]))
+                     (digest, ve.args[0]))
         exit(1)
 
     # Validate the files to checksum
     files = []
     for i in args:
         if os.path.exists(i):
             files.append(i)
         else:
             logger.info('File "%s" was not found on the filesystem' % i)
-    process_files(files, options.outfile, options.digest, options.strip)
+    process_files(files, options.outfile, options.digests, options.strip)
 
 if __name__ == '__main__':
     main()
--- a/build/mobile/devicemanagerADB.py
+++ b/build/mobile/devicemanagerADB.py
@@ -573,17 +573,17 @@ class DeviceManagerADB(DeviceManager):
     else:
       self.checkCmdAs(["shell", "chmod", "777", remoteDir.strip()])
       print "chmod " + remoteDir.strip()
 
   def verifyADB(self):
     # Check to see if adb itself can be executed.
     try:
       self.runCmd(["version"])
-    except Exception as (ex):
+    except:
       print "unable to execute ADB: ensure Android SDK is installed and adb is in your $PATH"
     
   def isCpAvailable(self):
     # Some Android systems may not have a cp command installed,
     # or it may not be executable by the user. 
     data = self.runCmd(["shell", "cp"]).stdout.read()
     if (re.search('Usage', data)):
       return True
--- a/build/mobile/remoteautomation.py
+++ b/build/mobile/remoteautomation.py
@@ -151,17 +151,20 @@ class RemoteAutomation(Automation):
     class RProcess(object):
         # device manager process
         dm = None
         def __init__(self, dm, cmd, stdout = None, stderr = None, env = None, cwd = '.'):
             self.dm = dm
             self.stdoutlen = 0
             self.proc = dm.launchProcess(cmd, stdout, cwd, env, True)
             if (self.proc is None):
-              raise Exception("unable to launch process")
+              if cmd[0] == 'am':
+                self.proc = stdout
+              else:
+                raise Exception("unable to launch process")
             exepath = cmd[0]
             name = exepath.split('/')[-1]
             self.procName = name
 
             # Setting timeout at 1 hour since on a remote device this takes much longer
             self.timeout = 3600
             time.sleep(15)
 
--- a/build/unix/gnu-ld-scripts/components-mapfile
+++ b/build/unix/gnu-ld-scripts/components-mapfile
@@ -1,6 +1,7 @@
 {
    global:
 		NSModule;
 		NSGetModule;
+		__RLD_MAP;
    local: *;
 };
--- a/build/unix/gnu-ld-scripts/components-version-script
+++ b/build/unix/gnu-ld-scripts/components-version-script
@@ -1,6 +1,7 @@
 EXPORTED {
    global:
 		NSModule;
 		NSGetModule;
+		__RLD_MAP;
    local: *;
 };
--- a/configure.in
+++ b/configure.in
@@ -2531,17 +2531,17 @@ ia64*-hpux*)
         CXXFLAGS="$CXXFLAGS -mms-bitfields"
         DSO_LDOPTS='-shared'
         MKSHLIB='$(CXX) $(DSO_LDOPTS) -o $@'
         MKCSHLIB='$(CC) $(DSO_LDOPTS) -o $@'
         RC='$(WINDRES)'
         # Use temp file for windres (bug 213281)
         RCFLAGS='-O coff --use-temp-file'
         # mingw doesn't require kernel32, user32, and advapi32 explicitly
-        LIBS="$LIBS -luuid -lgdi32 -lwinmm -lwsock32"
+        LIBS="$LIBS -luuid -lgdi32 -lwinmm -lwsock32 -luserenv"
         MOZ_FIX_LINK_PATHS=
         DYNAMIC_XPCOM_LIBS='-L$(LIBXUL_DIST)/lib -lxpcom -lxpcom_core -lmozalloc'
         XPCOM_FROZEN_LDOPTS='-L$(LIBXUL_DIST)/lib -lxpcom -lmozalloc'
         DLL_PREFIX=
         IMPORT_LIB_SUFFIX=dll.a
         GCC_VERSION=`$CC -v 2>&1 | awk '/^gcc version/ { print $3 }'`
     else
         TARGET_COMPILER_ABI=msvc
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -4268,25 +4268,31 @@ static const char* kNSURIs[] = {
   " (RDF)",
   " (XUL)",
   " (SVG)",
   " (XML Events)"
 };
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsGenericElement)
   if (NS_UNLIKELY(cb.WantDebugInfo())) {
-    char name[72];
+    char name[512];
     PRUint32 nsid = tmp->GetNameSpaceID();
     nsAtomCString localName(tmp->NodeInfo()->NameAtom());
+    nsCAutoString uri;
+    if (tmp->OwnerDoc()->GetDocumentURI()) {
+      tmp->OwnerDoc()->GetDocumentURI()->GetSpec(uri);
+    }
+
     if (nsid < ArrayLength(kNSURIs)) {
-      PR_snprintf(name, sizeof(name), "nsGenericElement%s %s", kNSURIs[nsid],
-                  localName.get());
+      PR_snprintf(name, sizeof(name), "nsGenericElement%s %s %s", kNSURIs[nsid],
+                  localName.get(), uri.get());
     }
     else {
-      PR_snprintf(name, sizeof(name), "nsGenericElement %s", localName.get());
+      PR_snprintf(name, sizeof(name), "nsGenericElement %s %s",
+                  localName.get(), uri.get());
     }
     cb.DescribeRefCountedNode(tmp->mRefCnt.get(), sizeof(nsGenericElement),
                               name);
   }
   else {
     NS_IMPL_CYCLE_COLLECTION_DESCRIBE(nsGenericElement, tmp->mRefCnt.get())
   }
 
--- a/content/base/src/nsPropertyTable.cpp
+++ b/content/base/src/nsPropertyTable.cpp
@@ -156,16 +156,43 @@ nsPropertyTable::Enumerate(nsPropertyOwn
       (PL_DHashTableOperate(&prop->mObjectValueMap, aObject, PL_DHASH_LOOKUP));
     if (PL_DHASH_ENTRY_IS_BUSY(entry)) {
       aCallback(const_cast<void*>(aObject.get()), prop->mName, entry->value,
                  aData);
     }
   }
 }
 
+struct PropertyEnumeratorData
+{
+  nsIAtom* mName;
+  NSPropertyFunc mCallBack;
+  void* mData;
+};
+
+static PLDHashOperator
+PropertyEnumerator(PLDHashTable* aTable, PLDHashEntryHdr* aHdr,
+                   PRUint32 aNumber, void* aArg)
+{
+  PropertyListMapEntry* entry = static_cast<PropertyListMapEntry*>(aHdr);
+  PropertyEnumeratorData* data = static_cast<PropertyEnumeratorData*>(aArg);
+  data->mCallBack(const_cast<void*>(entry->key), data->mName, entry->value,
+                  data->mData);
+  return PL_DHASH_NEXT;
+}
+
+void
+nsPropertyTable::EnumerateAll(NSPropertyFunc aCallBack, void* aData)
+{
+  for (PropertyList* prop = mPropertyList; prop; prop = prop->mNext) {
+    PropertyEnumeratorData data = { prop->mName, aCallBack, aData };
+    PL_DHashTableEnumerate(&prop->mObjectValueMap, PropertyEnumerator, &data);
+  }
+}
+
 void*
 nsPropertyTable::GetPropertyInternal(nsPropertyOwner aObject,
                                      nsIAtom    *aPropertyName,
                                      bool        aRemove,
                                      nsresult   *aResult)
 {
   NS_PRECONDITION(aPropertyName && aObject, "unexpected null param");
   nsresult rv = NS_PROPTABLE_PROP_NOT_THERE;
--- a/content/base/src/nsPropertyTable.h
+++ b/content/base/src/nsPropertyTable.h
@@ -177,16 +177,23 @@ class nsPropertyTable
    * Enumerate the properties for object |aObject|.
    * For every property |aCallback| will be called with as arguments |aObject|,
    * the property name, the property value and |aData|.
    */
   NS_HIDDEN_(void) Enumerate(nsPropertyOwner aObject,
                              NSPropertyFunc aCallback, void *aData);
 
   /**
+   * Enumerate all the properties.
+   * For every property |aCallback| will be called with arguments the owner,
+   * the property name, the property value and |aData|.
+   */
+  NS_HIDDEN_(void) EnumerateAll(NSPropertyFunc aCallback, void *aData);
+
+  /**
    * Deletes all of the properties for all objects in the property
    * table, calling the destructor function for each property.
    */
   NS_HIDDEN_(void) DeleteAllProperties();
 
   nsPropertyTable() : mPropertyList(nsnull) {}  
   ~nsPropertyTable() {
     DeleteAllProperties();
--- a/content/base/src/nsRange.cpp
+++ b/content/base/src/nsRange.cpp
@@ -287,16 +287,50 @@ nsRangeUtils::CompareNodeToRange(nsICont
 nsRange::~nsRange() 
 {
   NS_ASSERTION(!IsInSelection(), "deleting nsRange that is in use");
 
   // we want the side effects (releases and list removals)
   DoSetRange(nsnull, 0, nsnull, 0, nsnull);
 } 
 
+/* static */
+nsresult
+nsRange::CreateRange(nsIDOMNode* aStartParent, PRInt32 aStartOffset,
+                     nsIDOMNode* aEndParent, PRInt32 aEndOffset,
+                     nsRange** aRange)
+{
+  MOZ_ASSERT(aRange);
+  *aRange = NULL;
+
+  nsRefPtr<nsRange> range = new nsRange();
+
+  nsresult rv = range->SetStart(aStartParent, aStartOffset);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  rv = range->SetEnd(aEndParent, aEndOffset);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  range.forget(aRange);
+  return NS_OK;
+}
+
+/* static */
+nsresult
+nsRange::CreateRange(nsIDOMNode* aStartParent, PRInt32 aStartOffset,
+                     nsIDOMNode* aEndParent, PRInt32 aEndOffset,
+                     nsIDOMRange** aRange)
+{
+  nsRefPtr<nsRange> range;
+  nsresult rv = nsRange::CreateRange(aStartParent, aStartOffset, aEndParent,
+                                     aEndOffset, getter_AddRefs(range));
+  range.forget(aRange);
+  return rv;
+}
+
 /******************************************************
  * nsISupports
  ******************************************************/
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsRange)
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsRange)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsRange)
--- a/content/base/src/nsRange.h
+++ b/content/base/src/nsRange.h
@@ -61,16 +61,23 @@ public:
     , mEndOffset(0)
     , mIsPositioned(false)
     , mIsDetached(false)
     , mMaySpanAnonymousSubtrees(false)
     , mInSelection(false)
   {}
   virtual ~nsRange();
 
+  static nsresult CreateRange(nsIDOMNode* aStartParent, PRInt32 aStartOffset,
+                              nsIDOMNode* aEndParent, PRInt32 aEndOffset,
+                              nsRange** aRange);
+  static nsresult CreateRange(nsIDOMNode* aStartParent, PRInt32 aStartOffset,
+                              nsIDOMNode* aEndParent, PRInt32 aEndOffset,
+                              nsIDOMRange** aRange);
+
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsRange, nsIDOMRange)
 
   // nsIDOMRange interface
   NS_DECL_NSIDOMRANGE
   
   nsINode* GetRoot() const
   {
--- a/content/base/src/nsScriptLoader.cpp
+++ b/content/base/src/nsScriptLoader.cpp
@@ -36,17 +36,18 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * A class that handles loading and evaluation of <script> elements.
  */
 
-#include "jscntxt.h"
+#include "jsapi.h"
+#include "jsfriendapi.h"
 #include "nsScriptLoader.h"
 #include "nsParserUtils.h"
 #include "nsICharsetConverterManager.h"
 #include "nsIUnicodeDecoder.h"
 #include "nsIContent.h"
 #include "mozilla/dom/Element.h"
 #include "nsGkAtoms.h"
 #include "nsNetUtil.h"
@@ -493,17 +494,17 @@ nsScriptLoader::ProcessScriptElement(nsI
         if (rv != NS_ERROR_INVALID_ARG)
           return false;
       } else {
         if (value.Length() == 1 && value[0] == '1')
           // This means that we need to set JSOPTION_XML in the JS options.
           // We re-use our knowledge of the implementation to reuse
           // JSVERSION_HAS_XML as a safe version flag.
           // If version has JSVERSION_UNKNOWN (-1), then this is still OK.
-          version |= js::VersionFlags::HAS_XML;
+          version = js::VersionSetXML(JSVersion(version), true);
       }
     }
   } else {
     // no 'type=' element
     // "language" is a deprecated attribute of HTML, so we check it only for
     // HTML script elements.
     if (scriptContent->IsHTML()) {
       scriptContent->GetAttr(kNameSpaceID_None, nsGkAtoms::language, language);
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -111,17 +111,16 @@ include $(topsrcdir)/config/rules.mk
 		test_bug357450_svg.xhtml \
 		test_bug357509.html \
 		test_bug358660.html \
 		test_bug362391.xhtml \
 		test_bug364092.xhtml \
 		test_bug364413.xhtml \
 		test_bug366946.html \
 		test_bug367164.html \
-		test_bug371576-1.html \
 		test_bug371576-2.html \
 		test_bug371576-3.html \
 		test_bug371576-4.html \
 		test_bug371576-5.html \
 		test_bug372086.html \
 		test_bug372964.html \
 		test_bug372964-2.html \
 		test_bug373181.xhtml \
deleted file mode 100644
--- a/content/base/test/test_bug371576-1.html
+++ /dev/null
@@ -1,32 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=371576
--->
-<head id="head">
-  <title>Test for Bug 371576</title>
-  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>        
-  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=371576">Mozilla Bug 371576</a>
-<p id="display"></p>
-<div id="content" style="display: none">
-  
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-  var result = "A";
-  var scrElem= document.createElement('script');
-  scrElem.setAttribute('src','data:text/javascript,result+="C";$("content").innerHTML="--";result+="D";');
-  $("head").appendChild(scrElem);
-  result += "B";
-
-</script>
-<script>result += "E"</script>
-<script>result += "F"</script>
-<script>is(result, "ABCDEF", "Wrong order of execution");</script>
-</pre>
-</body>
-</html>
--- a/content/canvas/src/Makefile.in
+++ b/content/canvas/src/Makefile.in
@@ -35,16 +35,18 @@
 #
 # ***** END LICENSE BLOCK *****
 
 DEPTH		= ../../..
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
+FAIL_ON_WARNINGS = 1
+
 include $(DEPTH)/config/autoconf.mk
 
 MODULE		= content
 LIBRARY_NAME	= gkconcvs_s
 LIBXUL_LIBRARY  = 1
 
 EXPORTS = \
 	CustomQS_Canvas2D.h \
@@ -55,18 +57,16 @@ CPPSRCS	= \
 	CanvasImageCache.cpp \
 	CanvasUtils.cpp \
 	nsCanvasRenderingContext2D.cpp \
 	nsCanvasRenderingContext2DAzure.cpp \
 	DocumentRendererParent.cpp \
 	DocumentRendererChild.cpp \
 	$(NULL)
 
-# Canvas 3D Pieces
-
 ifdef MOZ_WEBGL
 
 CPPSRCS += \
 	WebGLContext.cpp \
 	WebGLContextGL.cpp \
 	WebGLContextUtils.cpp \
 	WebGLContextValidate.cpp \
 	WebGLExtensionStandardDerivatives.cpp \
--- a/content/canvas/src/WebGLContext.cpp
+++ b/content/canvas/src/WebGLContext.cpp
@@ -496,19 +496,19 @@ WebGLContext::SetDimensions(PRInt32 widt
     // know if creating the new context will succeed.
     DestroyResourcesAndContext();
 
     // Get some prefs for some preferred/overriden things
     NS_ENSURE_TRUE(Preferences::GetRootBranch(), NS_ERROR_FAILURE);
 
     bool forceOSMesa =
         Preferences::GetBool("webgl.force_osmesa", false);
+#ifdef XP_WIN
     bool preferEGL =
         Preferences::GetBool("webgl.prefer-egl", false);
-#ifdef XP_WIN
     bool preferOpenGL =
         Preferences::GetBool("webgl.prefer-native-gl", false);
 #endif
     bool forceEnabled =
         Preferences::GetBool("webgl.force-enabled", false);
     bool disabled =
         Preferences::GetBool("webgl.disabled", false);
     bool verbose =
@@ -561,43 +561,52 @@ WebGLContext::SetDimensions(PRInt32 widt
         gfxInfo &&
         NS_SUCCEEDED(gfxInfo->GetFeatureStatus(nsIGfxInfo::FEATURE_WEBGL_MSAA, &status))) {
         if (status == nsIGfxInfo::FEATURE_NO_INFO || forceMSAA) {
             PRUint32 msaaLevel = Preferences::GetUint("webgl.msaa-level", 2);
             format.samples = msaaLevel*msaaLevel;
         }
     }
 
+#ifdef XP_WIN
     if (PR_GetEnv("MOZ_WEBGL_PREFER_EGL")) {
         preferEGL = true;
     }
+#endif
 
     // Ask GfxInfo about what we should use
     bool useOpenGL = true;
+
+#ifdef XP_WIN
     bool useANGLE = true;
+#endif
 
     if (gfxInfo && !forceEnabled) {
         if (NS_SUCCEEDED(gfxInfo->GetFeatureStatus(nsIGfxInfo::FEATURE_WEBGL_OPENGL, &status))) {
             if (status != nsIGfxInfo::FEATURE_NO_INFO) {
                 useOpenGL = false;
             }
         }
+#ifdef XP_WIN
         if (NS_SUCCEEDED(gfxInfo->GetFeatureStatus(nsIGfxInfo::FEATURE_WEBGL_ANGLE, &status))) {
             if (status != nsIGfxInfo::FEATURE_NO_INFO) {
                 useANGLE = false;
             }
         }
+#endif
     }
 
+#ifdef XP_WIN
     // allow forcing GL and not EGL/ANGLE
     if (PR_GetEnv("MOZ_WEBGL_FORCE_OPENGL")) {
         preferEGL = false;
         useANGLE = false;
         useOpenGL = true;
     }
+#endif
 
     // if we're forcing osmesa, do it first
     if (forceOSMesa) {
         gl = gl::GLContextProviderOSMesa::CreateOffscreen(gfxIntSize(width, height), format);
         if (!gl || !InitAndValidateGL()) {
             LogMessage("OSMesa forced, but creating context failed -- aborting!");
             return NS_ERROR_FAILURE;
         }
@@ -609,45 +618,42 @@ WebGLContext::SetDimensions(PRInt32 widt
     if (!gl && (preferEGL || useANGLE) && !preferOpenGL) {
         gl = gl::GLContextProviderEGL::CreateOffscreen(gfxIntSize(width, height), format);
         if (gl) {
             if (InitAndValidateGL()) {
                 if (useANGLE) {
                     gl->SetFlushGuaranteesResolve(true);
                 }
             } else {
-                gl = nsnull;
+                LogMessage("Error during ANGLE OpenGL ES initialization");
+                return NS_ERROR_FAILURE;
             }
         }
     }
-
-    // if it failed, then try the default provider, whatever that is
-    if (!gl && useOpenGL) {
-        gl = gl::GLContextProvider::CreateOffscreen(gfxIntSize(width, height), format);
-        if (gl && !InitAndValidateGL()) {
-            gl = nsnull;
-        }
-    }
-#else
-    // other platforms just use whatever the default is
-    if (!gl && useOpenGL) {
-        gl = gl::GLContextProvider::CreateOffscreen(gfxIntSize(width, height), format);
-        if (gl && !InitAndValidateGL()) {
-            gl = nsnull;
-        }
-    }
 #endif
 
+    // try the default provider, whatever that is
+    if (!gl && useOpenGL) {
+        gl = gl::GLContextProvider::CreateOffscreen(gfxIntSize(width, height), format);
+        if (gl && !InitAndValidateGL()) {
+            LogMessage("Error during OpenGL initialization");
+            return NS_ERROR_FAILURE;
+        }
+    }
+
     // finally, try OSMesa
     if (!gl) {
         gl = gl::GLContextProviderOSMesa::CreateOffscreen(gfxIntSize(width, height), format);
-        if (!gl || !InitAndValidateGL()) {
-            gl = nsnull;
-        } else {
-            LogMessage("Using software rendering via OSMesa (THIS WILL BE SLOW)");
+        if (gl) {
+            if (!InitAndValidateGL()) {
+                LogMessage("Error during OSMesa initialization");
+                return NS_ERROR_FAILURE;
+            } else {
+                LogMessage("Using software rendering via OSMesa (THIS WILL BE SLOW)");
+            }
         }
     }
 
     if (!gl) {
         LogMessage("Can't get a usable WebGL context");
         return NS_ERROR_FAILURE;
     }
 
@@ -1013,20 +1019,22 @@ void
 WebGLContext::ForceClearFramebufferWithDefaultValues(PRUint32 mask, const nsIntRect& viewportRect)
 {
     MakeContextCurrent();
 
     bool initializeColorBuffer = 0 != (mask & LOCAL_GL_COLOR_BUFFER_BIT);
     bool initializeDepthBuffer = 0 != (mask & LOCAL_GL_DEPTH_BUFFER_BIT);
     bool initializeStencilBuffer = 0 != (mask & LOCAL_GL_STENCIL_BUFFER_BIT);
 
+    // fun GL fact: no need to worry about the viewport here, glViewport is just setting up a coordinates transformation,
+    // it doesn't affect glClear at all
+
     // prepare GL state for clearing
     gl->fDisable(LOCAL_GL_SCISSOR_TEST);
     gl->fDisable(LOCAL_GL_DITHER);
-    gl->PushViewportRect(viewportRect);
 
     if (initializeColorBuffer) {
         gl->fColorMask(1, 1, 1, 1);
         gl->fClearColor(0.f, 0.f, 0.f, 0.f);
     }
 
     if (initializeDepthBuffer) {
         gl->fDepthMask(1);
@@ -1059,18 +1067,16 @@ WebGLContext::ForceClearFramebufferWithD
     }
 
     if (initializeStencilBuffer) {
         gl->fStencilMaskSeparate(LOCAL_GL_FRONT, mStencilWriteMaskFront);
         gl->fStencilMaskSeparate(LOCAL_GL_BACK, mStencilWriteMaskBack);
         gl->fClearStencil(mStencilClearValue);
     }
 
-    gl->PopViewportRect();
-
     if (mDitherEnabled)
         gl->fEnable(LOCAL_GL_DITHER);
     else
         gl->fDisable(LOCAL_GL_DITHER);
 
     if (mScissorTestEnabled)
         gl->fEnable(LOCAL_GL_SCISSOR_TEST);
     else
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -1444,17 +1444,17 @@ WebGLContext::UndoFakeVertexAttrib0()
         return;
 
     gl->fBindBuffer(LOCAL_GL_ARRAY_BUFFER, mAttribBuffers[0].buf ? mAttribBuffers[0].buf->GLName() : 0);
     gl->fVertexAttribPointer(0,
                              mAttribBuffers[0].size,
                              mAttribBuffers[0].type,
                              mAttribBuffers[0].normalized,
                              mAttribBuffers[0].stride,
-                             (const GLvoid *) mAttribBuffers[0].byteOffset);
+                             reinterpret_cast<const GLvoid *>(mAttribBuffers[0].byteOffset));
 
     gl->fBindBuffer(LOCAL_GL_ARRAY_BUFFER, mBoundArrayBuffer ? mBoundArrayBuffer->GLName() : 0);
 }
 
 bool
 WebGLContext::NeedFakeBlack()
 {
     // handle this case first, it's the generic case
@@ -1703,17 +1703,17 @@ WebGLContext::DrawElements(WebGLenum mod
         EnsureBackbufferClearedAsNeeded();
     }
 
     BindFakeBlackTextures();
     if (!DoFakeVertexAttrib0(checked_maxIndexPlusOne.value()))
         return NS_OK;
 
     SetupRobustnessTimer();
-    gl->fDrawElements(mode, count, type, (GLvoid*) (byteOffset));
+    gl->fDrawElements(mode, count, type, reinterpret_cast<GLvoid*>(byteOffset));
 
     UndoFakeVertexAttrib0();
     UnbindFakeBlackTextures();
 
     mBackbufferClearingStatus = BackbufferClearingStatus::HasBeenDrawnTo;
     Invalidate();
 
     return NS_OK;
@@ -4695,17 +4695,17 @@ WebGLContext::VertexAttribPointer(WebGLu
     vd.byteOffset = byteOffset;
     vd.type = type;
     vd.normalized = normalized;
 
     MakeContextCurrent();
 
     gl->fVertexAttribPointer(index, size, type, normalized,
                              stride,
-                             (void*) (byteOffset));
+                             reinterpret_cast<void*>(byteOffset));
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::TexImage2D(PRInt32)
 {
     if (!IsContextStable())
--- a/content/canvas/src/nsCanvasRenderingContext2DAzure.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2DAzure.cpp
@@ -3076,18 +3076,16 @@ struct NS_STACK_CLASS nsCanvasBidiProces
       if (mOp == nsCanvasRenderingContext2DAzure::TEXT_DRAW_OPERATION_FILL) {
         nsCanvasRenderingContext2DAzure::AdjustedTarget(mCtx)->
           FillGlyphs(scaledFont, buffer,
                       nsCanvasRenderingContext2DAzure::GeneralPattern().
                         ForStyle(mCtx, nsCanvasRenderingContext2DAzure::STYLE_FILL, mCtx->mTarget),
                       DrawOptions(mState->globalAlpha, mCtx->UsedOperation()));
       } else if (mOp == nsCanvasRenderingContext2DAzure::TEXT_DRAW_OPERATION_STROKE) {
         RefPtr<Path> path = scaledFont->GetPathForGlyphs(buffer, mCtx->mTarget);
-            
-        Matrix oldTransform = mCtx->mTarget->GetTransform();
 
         const ContextState& state = *mState;
         nsCanvasRenderingContext2DAzure::AdjustedTarget(mCtx)->
           Stroke(path, nsCanvasRenderingContext2DAzure::GeneralPattern().
                     ForStyle(mCtx, nsCanvasRenderingContext2DAzure::STYLE_STROKE, mCtx->mTarget),
                   StrokeOptions(state.lineWidth, state.lineJoin,
                                 state.lineCap, state.miterLimit,
                                 state.dash.Length(),
--- a/content/events/test/test_bug350471.xul
+++ b/content/events/test/test_bug350471.xul
@@ -17,18 +17,16 @@ https://bugzilla.mozilla.org/show_bug.cg
 <div id="content" style="display: none">
 </div>
 </body>
 
 <script class="testbody" type="application/javascript;version=1.7"><![CDATA[
 
 /** Test for Bug 350471 **/
 
-// This test depends on general.smoothScroll being off.
-
 const minLineHeight = 10, maxLineHeight = 20;
 
 function between(x, min, max) (min <= max) ? (min <= x && x <= max) : (max <= x && x <= min);
 function isbetween(x, min, max, msg) ok(between(x, min, max), msg + " - Expected " + min + " to " + max + ", got " + x);
 
 function testEventDispatching(aWin) {
   function helper(aAxis, aDelta, aKind, aShiftKey, aCtrlKey, aAltKey, aMetaKey) {
     let expectedEvents = [];
@@ -223,28 +221,28 @@ function testDefaultHandling(aWin, andTh
 function initPrefs()
 {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   var prefSvc = Components.classes["@mozilla.org/preferences-service;1"].
                   getService(Components.interfaces.nsIPrefBranch2);
   // Disables the app level scroll acceleration
   prefSvc.setIntPref("mousewheel.acceleration.start", -1);
   prefSvc.setBoolPref("mousewheel.system_scroll_override_on_root_content.enabled", false);
+  prefSvc.setBoolPref("general.smoothScroll", false);
 }
 
 function clearPrefs()
 {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   var prefSvc = Components.classes["@mozilla.org/preferences-service;1"].
                   getService(Components.interfaces.nsIPrefBranch2);
 
-  if (prefSvc.prefHasUserValue("mousewheel.acceleration.start"))
-    prefSvc.clearUserPref("mousewheel.acceleration.start");
-  if (prefSvc.prefHasUserValue("mousewheel.system_scroll_override_on_root_content.enabled"))
-    prefSvc.clearUserPref("mousewheel.system_scroll_override_on_root_content.enabled");
+  prefSvc.clearUserPref("mousewheel.acceleration.start");
+  prefSvc.clearUserPref("mousewheel.system_scroll_override_on_root_content.enabled");
+  prefSvc.clearUserPref("general.smoothScroll");
 }
 
 window.onload = function () {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
   let win = window.open('data:application/vnd.mozilla.xul+xml,<?xml version="1.0"?><?xml-stylesheet href="chrome://global/skin" type="text/css"?><window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"><vbox style="height: 150px; background: cyan; overflow: auto;" id="scrollbox"><hbox style="height: 8000px;"><vbox style="width: 8000px;"/></hbox></vbox></window>', '_blank', 'chrome,width=400,height=200');
   win.onload = function() {
     setTimeout(function() {
--- a/content/events/test/test_bug574663.html
+++ b/content/events/test/test_bug574663.html
@@ -15,18 +15,16 @@ https://bugzilla.mozilla.org/show_bug.cg
 <div id="content" style="display: none">
 
 </div>
 <pre id="test">
 <script type="application/javascript;version=1.7">
 
 /** Test for Bug 574663 **/
 
-// This test depends on general.smoothScroll being off.
-
 function sendTouchpadScrollMotion(scrollbox, direction, ctrl, momentum) {
   var win = scrollbox.ownerDocument.defaultView;
   let event = {
     'type': "DOMMouseScroll",
     'axis': "vertical",
     'delta': direction,
     'hasPixels': true,
     'ctrlKey': ctrl,
@@ -102,35 +100,34 @@ function runTest() {
   }, win);
 }
 
 function initPrefs()
 {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   var prefSvc = Components.classes["@mozilla.org/preferences-service;1"].
                   getService(Components.interfaces.nsIPrefBranch2);
+  prefSvc.setBoolPref("general.smoothScroll", false);
   // Disables the app level scroll acceleration
   prefSvc.setIntPref("mousewheel.acceleration.start", -1);
   prefSvc.setBoolPref("mousewheel.system_scroll_override_on_root_content.enabled", false);
   // Enable zooming for ctrl-scrolling
   prefSvc.setIntPref("mousewheel.withcontrolkey.action", 3);
 }
 
 function clearPrefs()
 {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   var prefSvc = Components.classes["@mozilla.org/preferences-service;1"].
                   getService(Components.interfaces.nsIPrefBranch2);
 
-  if (prefSvc.prefHasUserValue("mousewheel.acceleration.start"))
-    prefSvc.clearUserPref("mousewheel.acceleration.start");
-  if (prefSvc.prefHasUserValue("mousewheel.system_scroll_override_on_root_content.enabled"))
-    prefSvc.clearUserPref("mousewheel.system_scroll_override_on_root_content.enabled");
-  if (prefSvc.prefHasUserValue("mousewheel.withcontrolkey.action"))
-    prefSvc.clearUserPref("mousewheel.withcontrolkey.action");
+  prefSvc.clearUserPref("general.smoothScroll");
+  prefSvc.clearUserPref("mousewheel.acceleration.start");
+  prefSvc.clearUserPref("mousewheel.system_scroll_override_on_root_content.enabled");
+  prefSvc.clearUserPref("mousewheel.withcontrolkey.action");
 }
 
 window.onload = function () {
   initPrefs();
   SimpleTest.executeSoon(runTest);
 }
 
 SimpleTest.waitForExplicitFinish();
--- a/content/html/content/src/Makefile.in
+++ b/content/html/content/src/Makefile.in
@@ -144,12 +144,11 @@ INCLUDES	+= \
 		-I$(srcdir)/../../../../layout/tables \
 		-I$(srcdir)/../../../../layout/xul/base/src \
 		-I$(srcdir)/../../../../layout/generic \
 		-I$(srcdir)/../../../../dom/base \
 		-I$(srcdir)/../../../../editor/libeditor/base \
 		-I$(srcdir)/../../../../editor/libeditor/text \
 		-I$(srcdir) \
 		-I$(topsrcdir)/xpcom/ds \
-		-I$(srcdir)/../../../../js/xpconnect/src \
 		$(NULL)
 
 DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -498,17 +498,18 @@ nsGenericHTMLElement::GetOffsetRect(nsRe
   nsIFrame* frame = GetStyledFrame();
   if (!frame) {
     return;
   }
 
   nsIFrame* parent = frame->GetParent();
   nsPoint origin(0, 0);
 
-  if (parent && parent->GetType() == nsGkAtoms::tableOuterFrame) {
+  if (parent && parent->GetType() == nsGkAtoms::tableOuterFrame &&
+      frame->GetType() == nsGkAtoms::tableFrame) {
     origin = parent->GetPositionIgnoringScrolling();
     parent = parent->GetParent();
   }
 
   Element* docElement = GetCurrentDoc()->GetRootElement();
   nsIContent* content = frame->GetContent();
 
   if (content && (content->IsHTML(nsGkAtoms::body) || content == docElement)) {
--- a/content/html/content/src/nsHTMLDNSPrefetch.cpp
+++ b/content/html/content/src/nsHTMLDNSPrefetch.cpp
@@ -135,27 +135,16 @@ nsHTMLDNSPrefetch::IsAllowed (nsIDocumen
 {
   // There is no need to do prefetch on non UI scenarios such as XMLHttpRequest.
   return aDocument->IsDNSPrefetchAllowed() && aDocument->GetWindow();
 }
 
 nsresult
 nsHTMLDNSPrefetch::Prefetch(Link *aElement, PRUint16 flags)
 {
-  if (IsNeckoChild()) {
-    // Instead of transporting the Link object to the other process
-    // we are using the hostname based function here, too. Compared to the 
-    // IPC the performance hit should be negligible.
-    nsAutoString hostname;
-    nsresult rv = aElement->GetHostname(hostname);
-    NS_ENSURE_SUCCESS(rv,rv);
-
-    return Prefetch(hostname, flags);
-  }
-
   if (!(sInitialized && sPrefetches && sDNSService && sDNSListener))
     return NS_ERROR_NOT_AVAILABLE;
 
   return sPrefetches->Add(flags, aElement);
 }
 
 nsresult
 nsHTMLDNSPrefetch::PrefetchLow(Link *aElement)
@@ -294,21 +283,26 @@ nsHTMLDNSPrefetch::nsDeferrals::SubmitQu
     nsCOMPtr<nsIContent> content = do_QueryReferent(mEntries[mTail].mElement);
     if (content) {
       nsCOMPtr<Link> link = do_QueryInterface(content);
       nsCOMPtr<nsIURI> hrefURI(link ? link->GetURI() : nsnull);
       if (hrefURI)
         hrefURI->GetAsciiHost(hostName);
 
       if (!hostName.IsEmpty()) {
-        nsCOMPtr<nsICancelable> tmpOutstanding;
+        if (IsNeckoChild()) {
+          gNeckoChild->SendHTMLDNSPrefetch(NS_ConvertUTF8toUTF16(hostName),
+                                           mEntries[mTail].mFlags);
+        } else {
+          nsCOMPtr<nsICancelable> tmpOutstanding;
 
-        sDNSService->AsyncResolve(hostName, 
+          sDNSService->AsyncResolve(hostName, 
                                   mEntries[mTail].mFlags | nsIDNSService::RESOLVE_SPECULATE,
                                   sDNSListener, nsnull, getter_AddRefs(tmpOutstanding));
+        }
       }
     }
     
     mEntries[mTail].mElement = nsnull;
     mTail = (mTail + 1) & sMaxDeferredMask;
   }
   
   if (mTimerArmed) {
--- a/content/html/content/src/nsTextEditorState.cpp
+++ b/content/html/content/src/nsTextEditorState.cpp
@@ -1155,20 +1155,16 @@ nsTextEditorState::PrepareEditor(const n
   if (IsSingleLineTextControl())
     editorFlags |= nsIPlaintextEditor::eEditorSingleLineMask;
   if (IsPasswordTextControl())
     editorFlags |= nsIPlaintextEditor::eEditorPasswordMask;
 
   // All nsTextControlFrames are widgets
   editorFlags |= nsIPlaintextEditor::eEditorWidgetMask;
 
-  // Use async reflow and painting for text widgets to improve
-  // performance.
-  editorFlags |= nsIPlaintextEditor::eEditorUseAsyncUpdatesMask;
-  
   // Spell check is diabled at creation time. It is enabled once
   // the editor comes into focus.
   editorFlags |= nsIPlaintextEditor::eEditorSkipSpellCheck;
 
   bool shouldInitializeEditor = false;
   nsCOMPtr<nsIEditor> newEditor; // the editor that we might create
   nsresult rv = NS_OK;
   if (!mEditor) {
@@ -1309,22 +1305,17 @@ nsTextEditorState::PrepareEditor(const n
   }
 
   // If we have a default value, insert it under the div we created
   // above, but be sure to use the editor so that '*' characters get
   // displayed for password fields, etc. SetValue() will call the
   // editor for us.
 
   if (!defaultValue.IsEmpty()) {
-    // Avoid causing reentrant painting and reflowing by telling the editor
-    // that we don't want it to force immediate view refreshes or force
-    // immediate reflows during any editor calls.
-
-    rv = newEditor->SetFlags(editorFlags |
-                             nsIPlaintextEditor::eEditorUseAsyncUpdatesMask);
+    rv = newEditor->SetFlags(editorFlags);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // Now call SetValue() which will make the necessary editor calls to set
     // the default value.  Make sure to turn off undo before setting the default
     // value, and turn it back on afterwards. This will make sure we can't undo
     // past the default value.
 
     rv = newEditor->EnableUndo(false);
@@ -1832,17 +1823,16 @@ nsTextEditorState::SetValue(const nsAStr
 
         // get the flags, remove readonly and disabled, set the value,
         // restore flags
         PRUint32 flags, savedFlags;
         mEditor->GetFlags(&savedFlags);
         flags = savedFlags;
         flags &= ~(nsIPlaintextEditor::eEditorDisabledMask);
         flags &= ~(nsIPlaintextEditor::eEditorReadonlyMask);
-        flags |= nsIPlaintextEditor::eEditorUseAsyncUpdatesMask;
         flags |= nsIPlaintextEditor::eEditorDontEchoPassword;
         mEditor->SetFlags(flags);
 
         mTextListener->SettingValue(true);
 
         // Also don't enforce max-length here
         PRInt32 savedMaxLength;
         plaintextEditor->GetMaxTextLength(&savedMaxLength);
--- a/content/html/content/test/Makefile.in
+++ b/content/html/content/test/Makefile.in
@@ -277,16 +277,17 @@ include $(topsrcdir)/config/rules.mk
 		test_bug617528.html \
 		test_bug660959-1.html \
 		test_bug660959-2.html \
 		test_bug660959-3.html \
 		test_checked.html \
 		test_bug677658.html \
 		test_bug677463.html \
 		test_bug682886.html \
+		test_bug717819.html \
 		file_fullscreen-api.html \
 		file_fullscreen-api-keys.html \
 		test_fullscreen-api.html \
 		file_fullscreen-plugins.html \
 		file_fullscreen-denied.html \
 		file_fullscreen-denied-inner.html \
 		file_fullscreen-hidden.html \
 		file_fullscreen-navigation.html \
--- a/content/html/content/test/test_bug375003-1.html
+++ b/content/html/content/test/test_bug375003-1.html
@@ -71,18 +71,17 @@ function run_test() {
    t3('tr7'  ,[0,0,39,24],[9,9,39,24],[0,0,39,22],'table7');
    t3('span8' ,[0,0,20,20],[26,37,20,20],[0,0,20,20],'table7');
    t3('table7',[7,7,43,54],[10,319,57,68],[0,0,57,50],'body');
    t3('div7',[10,10,-1,68],[0,309,-1,88],[0,0,-1,70],'body');
 
    t3('span9' ,[0,0,20,20],[1,1,20,20],[0,0,20,20],'td9');
    t3('td9'   ,[1,1,22,22],[15,15,24,24],[0,0,24,24],'table9');
    t3('tr9'  ,[0,0,24,24],[15,15,24,24],[0,0,24,22],'table9');
-   // t3('span10' ,[0,0,20,20],[3,30,20,20],[0,0,20,20],'table9');
-   t3('span10' ,[0,0,20,20],[27,450,20,20],[0,0,20,20],'body');  // bug: 'body' should be 'table9'
+   t3('span10' ,[0,0,20,20],[17,43,20,20],[0,0,20,20],'table9');
    t3('table9',[13,13,28,34],[10,407,54,60],[0,0,54,50],'body');
    t3('div9',[10,10,-1,0],[0,397,-1,20],[0,0,-1,70],'body');
 
    t3('span11' ,[0,0,20,20],[1,1,20,20],[0,0,20,20],'td11');
    t3('td11'   ,[0,0,22,22],[2,2,22,22],[0,0,22,22],'table11');
    t3('tr11'  ,[0,0,22,22],[2,2,22,22],[0,0,22,22],'table11');
    t3('span12' ,[0,0,20,20],[28,454,20,20],[0,0,20,20],'body');
    t3('table11',[0,0,26,30],[10,427,26,30],[0,0,26,50],'body');
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug717819.html
@@ -0,0 +1,37 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=717819
+-->
+<head>
+  <title>Test for Bug 717819</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=717819">Mozilla Bug 717819</a>
+<p id="display"></p>
+<div id="content">
+  <table style="position: relative; top: 100px;">
+    <tr>
+      <td>
+        <div id="test" style="position: absolute; top: 50px;"></div>
+      </td>
+    </tr>
+  </table>
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 717819 **/
+var div = document.getElementById("test");
+is(div.offsetTop, 50, "The offsetTop must be calculated correctly");
+is(div.offsetParent, document.querySelector("table"),
+   "The offset should be calculated off of the correct parent");
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/html/document/src/ImageDocument.cpp
+++ b/content/html/document/src/ImageDocument.cpp
@@ -608,41 +608,16 @@ ImageDocument::HandleEvent(nsIDOMEvent* 
       }
       mShouldResize = false;
       RestoreImageTo(x, y);
     }
     else if (mImageIsOverflowing) {
       ShrinkToFit();
     }
   }
-  else if (eventType.EqualsLiteral("keypress")) {
-    nsCOMPtr<nsIDOMKeyEvent> keyEvent = do_QueryInterface(aEvent);
-    PRUint32 charCode;
-    bool ctrlKey, metaKey, altKey;
-    keyEvent->GetCharCode(&charCode);
-    keyEvent->GetCtrlKey(&ctrlKey);
-    keyEvent->GetMetaKey(&metaKey);
-    keyEvent->GetAltKey(&altKey);
-    // plus key
-    if (charCode == 0x2B && !ctrlKey && !metaKey && !altKey) {
-      mShouldResize = false;
-      if (mImageIsResized) {
-        ResetZoomLevel();
-        RestoreImage();
-      }
-    }
-    // minus key
-    else if (charCode == 0x2D && !ctrlKey && !metaKey && !altKey) {
-      mShouldResize = true;
-      if (mImageIsOverflowing) {
-        ResetZoomLevel();
-        ShrinkToFit();
-      }
-    }
-  }
 
   return NS_OK;
 }
 
 nsresult
 ImageDocument::CreateSyntheticDocument()
 {
   // Synthesize an html document that refers to the image
--- a/content/xbl/src/Makefile.in
+++ b/content/xbl/src/Makefile.in
@@ -85,12 +85,11 @@ LOCAL_INCLUDES	= \
 		-I$(srcdir)/../../html/document/src \
 		-I$(srcdir)/../../xml/document/src \
 		-I$(srcdir)/../../xul/content/src \
 		-I$(srcdir)/../../xul/document/src \
 		-I$(srcdir)/../../events/src \
 		-I$(srcdir)/../../../layout/style \
 		-I$(srcdir)/../../../dom/base \
 		-I$(topsrcdir)/xpcom/ds \
-		-I$(srcdir)/../../../js/xpconnect/src \
 		$(NULL)
 
 DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/xbl/src/nsXBLDocumentInfo.cpp
+++ b/content/xbl/src/nsXBLDocumentInfo.cpp
@@ -53,16 +53,17 @@
 #include "nsIPrincipal.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsContentUtils.h"
 #include "nsDOMJSUtils.h"
 #include "mozilla/Services.h"
 #include "xpcpublic.h"
 #include "mozilla/scache/StartupCache.h"
 #include "mozilla/scache/StartupCacheUtils.h"
+#include "nsCCUncollectableMarker.h"
 
 using namespace mozilla::scache;
 
 static const char kXBLCachePrefix[] = "xblcache";
 
 static NS_DEFINE_CID(kDOMScriptObjectFactoryCID, NS_DOM_SCRIPT_OBJECT_FACTORY_CID);
 
 // An XBLDocumentInfo object has a special context associated with it which we can use to pre-compile 
@@ -299,17 +300,17 @@ nsXBLDocGlobalObject::EnsureScriptEnviro
 {
   if (aLangID != nsIProgrammingLanguage::JAVASCRIPT) {
     NS_WARNING("XBL still JS only");
     return NS_ERROR_INVALID_ARG;
   }
   if (mScriptContext)
     return NS_OK; // already initialized for this lang
   nsCOMPtr<nsIDOMScriptObjectFactory> factory = do_GetService(kDOMScriptObjectFactoryCID);
-  NS_ENSURE_TRUE(factory, nsnull);
+  NS_ENSURE_TRUE(factory, NS_OK);
 
   nsresult rv;
 
   nsCOMPtr<nsIScriptRuntime> scriptRuntime;
   rv = NS_GetScriptRuntimeByID(aLangID, getter_AddRefs(scriptRuntime));
   NS_ENSURE_SUCCESS(rv, rv);
   nsCOMPtr<nsIScriptContext> newCtx = scriptRuntime->CreateContext();
   rv = SetScriptContext(aLangID, newCtx);
@@ -322,17 +323,17 @@ nsXBLDocGlobalObject::EnsureScriptEnviro
   // why - see bug 339647)
   JS_SetErrorReporter(cx, XBL_ProtoErrorReporter);
 
   nsIPrincipal *principal = GetPrincipal();
   JSCompartment *compartment;
 
   rv = xpc_CreateGlobalObject(cx, &gSharedGlobalClass, principal, nsnull,
                               false, &mJSObject, &compartment);
-  NS_ENSURE_SUCCESS(rv, nsnull);
+  NS_ENSURE_SUCCESS(rv, NS_OK);
 
   ::JS_SetGlobalObject(cx, mJSObject);
 
   // Add an owning reference from JS back to us. This'll be
   // released when the JSObject is finalized.
   ::JS_SetPrivate(cx, mJSObject, this);
   NS_ADDREF(this);
   return NS_OK;
@@ -461,16 +462,21 @@ NS_IMPL_CYCLE_COLLECTION_CLASS(nsXBLDocu
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsXBLDocumentInfo)
   if (tmp->mBindingTable) {
     tmp->mBindingTable->Enumerate(UnlinkProtoJSObjects, nsnull);
   }
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDocument)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mGlobalObject)
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsXBLDocumentInfo)
+  if (tmp->mDocument &&
+      nsCCUncollectableMarker::InGeneration(cb, tmp->mDocument->GetMarkedCCGeneration())) {
+    NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
+    return NS_SUCCESS_INTERRUPTED_TRAVERSE;
+  }
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mDocument)
   if (tmp->mBindingTable) {
     tmp->mBindingTable->Enumerate(TraverseProtos, &cb);
   }
   cb.NoteXPCOMChild(static_cast<nsIScriptGlobalObject*>(tmp->mGlobalObject));
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsXBLDocumentInfo)
--- a/content/xul/document/src/nsXULContentSink.cpp
+++ b/content/xul/document/src/nsXULContentSink.cpp
@@ -42,17 +42,18 @@
 /*
  * An implementation for a Gecko-style content sink that knows how
  * to build a content model (the "prototype" document) from XUL.
  *
  * For more information on XUL,
  * see http://developer.mozilla.org/en/docs/XUL
  */
 
-#include "jscntxt.h"  // for JSVERSION_HAS_XML
+#include "jsapi.h"
+#include "jsfriendapi.h"
 #include "nsXULContentSink.h"
 #include "nsCOMPtr.h"
 #include "nsForwardReference.h"
 #include "nsIContentSink.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMEventListener.h"
 #include "nsIDOMHTMLFormElement.h"
 #include "nsIDOMXULDocument.h"
@@ -1055,40 +1056,40 @@ XULContentSinkImpl::OpenScript(const PRU
             }
           }
           // Some js specifics yet to be abstracted.
           if (langID == nsIProgrammingLanguage::JAVASCRIPT) {
               // By default scripts in XUL documents have E4X turned on. We use
               // our implementation knowledge to reuse JSVERSION_HAS_XML as a
               // safe version flag. This is still OK if version is
               // JSVERSION_UNKNOWN (-1),
-              version |= js::VersionFlags::HAS_XML;
+              version = js::VersionSetXML(JSVersion(version), true);
 
               nsAutoString value;
               rv = parser.GetParameter("e4x", value);
               if (NS_FAILED(rv)) {
                   if (rv != NS_ERROR_INVALID_ARG)
                       return rv;
               } else {
                   if (value.Length() == 1 && value[0] == '0')
-                    version &= ~js::VersionFlags::HAS_XML;
+                    version = js::VersionSetXML(JSVersion(version), false);
               }
           }
       }
       else if (key.EqualsLiteral("language")) {
           // Language is deprecated, and the impl in nsScriptLoader ignores the
           // various version strings anyway.  So we make no attempt to support
           // languages other than JS for language=
           nsAutoString lang(aAttributes[1]);
           if (nsParserUtils::IsJavaScriptLanguage(lang, &version)) {
               langID = nsIProgrammingLanguage::JAVASCRIPT;
 
               // Even when JS version < 1.6 is specified, E4X is
               // turned on in XUL.
-              version |= js::VersionFlags::HAS_XML;
+              version = js::VersionSetXML(JSVersion(version), true);
           }
       }
       aAttributes += 2;
   }
   // Not all script languages have a "sandbox" concept.  At time of
   // writing, Python is the only other language, and it does not.
   // For such languages, neither any inline script nor remote script are
   // safe to execute from untrusted sources.
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -4727,18 +4727,17 @@ nsDocShell::Repaint(bool aForce)
 {
     nsCOMPtr<nsIPresShell> presShell;
     GetPresShell(getter_AddRefs(presShell));
     NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
 
     nsIViewManager* viewManager = presShell->GetViewManager();
     NS_ENSURE_TRUE(viewManager, NS_ERROR_FAILURE);
 
-    // what about aForce ?
-    NS_ENSURE_SUCCESS(viewManager->UpdateAllViews(0), NS_ERROR_FAILURE);
+    NS_ENSURE_SUCCESS(viewManager->InvalidateAllViews(), NS_ERROR_FAILURE);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDocShell::GetParentWidget(nsIWidget ** parentWidget)
 {
     NS_ENSURE_ARG_POINTER(parentWidget);
 
@@ -7319,17 +7318,17 @@ nsDocShell::RestoreFromHistory()
 
         newVM = shell->GetViewManager();
         if (newVM) {
             // When we insert the root view above the resulting invalidate is
             // dropped because painting is suppressed in the presshell until we
             // call Thaw. So we issue the invalidate here.
             newRootView = newVM->GetRootView();
             if (newRootView) {
-                newVM->UpdateView(newRootView, NS_VMREFRESH_NO_SYNC);
+                newVM->InvalidateView(newRootView);
             }
         }
     }
 
     return privWin->FireDelayedDOMEvents();
 }
 
 NS_IMETHODIMP
--- a/docshell/test/navigation/test_bug430723.html
+++ b/docshell/test/navigation/test_bug430723.html
@@ -38,17 +38,19 @@ var gTallBlueBoxURI = "data:text/html;ch
 // </div></body></html>
 
 
 window.onload = runTest;
 
 var testWindow;
 var testNum = 0;
 
+var smoothScrollPref = "general.smoothScroll";
 function runTest() {
+  SpecialPowers.setBoolPref(smoothScrollPref, false);
   testWindow = window.open(gTallRedBoxURI, "testWindow", "width=300,height=300,location=yes,scrollbars=yes");
 }
 
 var nextTest =function() {
   testNum++;
   switch (testNum) {
     case 1: setTimeout(step1, 0); break;
     case 2: setTimeout(step2, 0); break;
@@ -117,16 +119,17 @@ var step3 =function() {
      "Page1Again: Ensure scroll pane at top before we scroll.");  
   testWindow.addEventListener("scroll", function () {
     testWindow.removeEventListener("scroll", arguments.callee, true);
 
     isnot(testWindow.document.body.scrollTop, 0,
           "Page2Again: Ensure we can still scroll.");  
 
     testWindow.close();
+    SpecialPowers.clearUserPref(smoothScrollPref);
     window.SimpleTest.finish();
   }, true);
   sendKey('DOWN', testWindow);
 }
 
 SimpleTest.waitForExplicitFinish();
 
 //]]>
--- a/dom/base/ConsoleAPI.js
+++ b/dom/base/ConsoleAPI.js
@@ -197,17 +197,18 @@ ConsoleAPI.prototype = {
     let frame = stack[1];
     let consoleEvent = {
       ID: aOuterWindowID,
       innerID: aInnerWindowID,
       level: aLevel,
       filename: frame.filename,
       lineNumber: frame.lineNumber,
       functionName: frame.functionName,
-      arguments: aArguments
+      arguments: aArguments,
+      timeStamp: Date.now(),
     };
 
     consoleEvent.wrappedJSObject = consoleEvent;
 
     ConsoleAPIStorage.recordEvent(aInnerWindowID, consoleEvent);
 
     Services.obs.notifyObservers(consoleEvent,
                                  "console-api-log-event", aOuterWindowID);
--- a/dom/base/ConsoleAPIStorage.jsm
+++ b/dom/base/ConsoleAPIStorage.jsm
@@ -116,17 +116,17 @@ var ConsoleAPIStorage = {
    * @param string aId
    *        The inner window ID for which you want to get the array of cached
    *        events.
    * @returns array
    *          The array of cached events for the given window.
    */
   getEvents: function CS_getEvents(aId)
   {
-    return _consoleStorage[aId] || [];
+    return (_consoleStorage[aId] || []).slice(0);
   },
 
   /**
    * Record an event associated with the given window ID.
    *
    * @param string aWindowID
    *        The ID of the inner window for which the event occurred.
    * @param object aEvent
--- a/dom/base/Makefile.in
+++ b/dom/base/Makefile.in
@@ -47,24 +47,28 @@ LIBRARY_NAME	= jsdombase_s
 LIBXUL_LIBRARY	= 1
 FORCE_STATIC_LIB = 1
 
 EXTRA_PP_COMPONENTS = \
 		ConsoleAPI.js \
 		ConsoleAPI.manifest \
 		$(NULL)
 
+EXTRA_JS_MODULES = ConsoleAPIStorage.jsm \
+		$(NULL)
+
+ifeq (gonk,$(MOZ_WIDGET_TOOLKIT))
 EXTRA_COMPONENTS = \
 	        Webapps.js \
 	        Webapps.manifest \
 		$(NULL)
 
-EXTRA_JS_MODULES = ConsoleAPIStorage.jsm \
-                Webapps.jsm \
+EXTRA_JS_MODULES += Webapps.jsm \
 		$(NULL)
+endif
 
 XPIDLSRCS = \
   nsIEntropyCollector.idl \
   nsIScriptChannel.idl \
   $(NULL)
 
 EXPORTS = \
   nsDOMCID.h \
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -37,18 +37,18 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "mozilla/Util.h"
 
 // JavaScript includes
 #include "jsapi.h"
+#include "jsfriendapi.h"
 #include "jsprvtd.h"    // we are using private JS typedefs...
-#include "jscntxt.h"
 #include "jsdbgapi.h"
 #include "WrapperFactory.h"
 #include "AccessCheck.h"
 
 #include "xpcprivate.h"
 #include "XPCWrapper.h"
 
 #include "nscore.h"
@@ -5380,17 +5380,17 @@ nsWindowSH::GetProperty(nsIXPConnectWrap
         // the window, so no need to wrap it again).
 
         return NS_SUCCESS_I_DID_SOMETHING;
       }
     }
   }
 
   if (id == sWrappedJSObject_id &&
-      xpc::AccessCheck::isChrome(cx->compartment)) {
+      xpc::AccessCheck::isChrome(js::GetContextCompartment(cx))) {
     obj = JS_ObjectToOuterObject(cx, obj);
     *vp = OBJECT_TO_JSVAL(obj);
     return NS_SUCCESS_I_DID_SOMETHING;
   }
 
   return NS_OK;
 }
 
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -757,37 +757,16 @@ nsDOMWindowUtils::CycleCollect(nsICycleC
   }
 #endif
 
   nsJSContext::CycleCollectNow(aListener);
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMWindowUtils::ProcessUpdates()
-{
-  nsPresContext* presContext = GetPresContext();
-  if (!presContext)
-    return NS_ERROR_UNEXPECTED;
-
-  nsIPresShell* shell = presContext->GetPresShell();
-  if (!shell)
-    return NS_ERROR_UNEXPECTED;
-
-  nsIViewManager *viewManager = shell->GetViewManager();
-  if (!viewManager)
-    return NS_ERROR_UNEXPECTED;
-  
-  nsIViewManager::UpdateViewBatch batch;
-  batch.BeginUpdateViewBatch(viewManager);
-  batch.EndUpdateViewBatch(NS_VMREFRESH_IMMEDIATE);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
 nsDOMWindowUtils::SendSimpleGestureEvent(const nsAString& aType,
                                          float aX,
                                          float aY,
                                          PRUint32 aDirection,
                                          PRFloat64 aDelta,
                                          PRInt32 aModifiers)
 {
   if (!IsUniversalXPConnectCapable()) {
--- a/dom/base/nsFocusManager.cpp
+++ b/dom/base/nsFocusManager.cpp
@@ -156,21 +156,23 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mFocusedContent)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mFirstBlurEvent)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mFirstFocusEvent)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mWindowBeingLowered)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 nsFocusManager* nsFocusManager::sInstance = nsnull;
 bool nsFocusManager::sMouseFocusesFormControl = false;
+bool nsFocusManager::sTestMode = false;
 
 static const char* kObservedPrefs[] = {
   "accessibility.browsewithcaret",
   "accessibility.tabfocus_applies_to_xul",
   "accessibility.mouse_focuses_formcontrol",
+  "focusmanager.testmode",
   NULL
 };
 
 nsFocusManager::nsFocusManager()
 { }
 
 nsFocusManager::~nsFocusManager()
 {
@@ -193,16 +195,18 @@ nsFocusManager::Init()
 
   nsIContent::sTabFocusModelAppliesToXUL =
     Preferences::GetBool("accessibility.tabfocus_applies_to_xul",
                          nsIContent::sTabFocusModelAppliesToXUL);
 
   sMouseFocusesFormControl =
     Preferences::GetBool("accessibility.mouse_focuses_formcontrol", false);
 
+  sTestMode = Preferences::GetBool("focusmanager.testmode", false);
+
   Preferences::AddWeakObservers(fm, kObservedPrefs);
 
   nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
   if (obs) {
     obs->AddObserver(fm, "xpcom-shutdown", true);
   }
 
   return NS_OK;
@@ -230,16 +234,19 @@ nsFocusManager::Observe(nsISupports *aSu
         Preferences::GetBool("accessibility.tabfocus_applies_to_xul",
                              nsIContent::sTabFocusModelAppliesToXUL);
     }
     else if (data.EqualsLiteral("accessibility.mouse_focuses_formcontrol")) {
       sMouseFocusesFormControl =
         Preferences::GetBool("accessibility.mouse_focuses_formcontrol",
                              false);
     }
+    else if (data.EqualsLiteral("focusmanager.testmode")) {
+      sTestMode = Preferences::GetBool("focusmanager.testmode", false);
+    }
   } else if (!nsCRT::strcmp(aTopic, "xpcom-shutdown")) {
     mActiveWindow = nsnull;
     mFocusedWindow = nsnull;
     mFocusedContent = nsnull;
     mFirstBlurEvent = nsnull;
     mFirstFocusEvent = nsnull;
     mWindowBeingLowered = nsnull;
     mDelayedBlurFocusEvents.Clear();
@@ -1059,17 +1066,17 @@ nsFocusManager::NotifyFocusStateChange(n
     aContent->AsElement()->RemoveStates(eventState);
   }
 }
 
 // static
 void
 nsFocusManager::EnsureCurrentWidgetFocused()
 {
-  if (!mFocusedWindow)
+  if (!mFocusedWindow || sTestMode)
     return;
 
   // get the main child widget for the focused window and ensure that the
   // platform knows that this widget is focused.
   nsCOMPtr<nsIDocShell> docShell = mFocusedWindow->GetDocShell();
   if (docShell) {
     nsCOMPtr<nsIPresShell> presShell;
     docShell->GetPresShell(getter_AddRefs(presShell));
@@ -1565,17 +1572,17 @@ nsFocusManager::Blur(nsPIDOMWindow* aWin
 
     // if an object/plug-in/remote browser is being blurred, move the system focus
     // to the parent window, otherwise events will still get fired at the plugin.
     // But don't do this if we are blurring due to the window being lowered,
     // otherwise, the parent window can get raised again.
     if (mActiveWindow) {
       nsIFrame* contentFrame = content->GetPrimaryFrame();
       nsIObjectFrame* objectFrame = do_QueryFrame(contentFrame);
-      if (aAdjustWidgets && objectFrame) {
+      if (aAdjustWidgets && objectFrame && !sTestMode) {
         // note that the presshell's widget is being retrieved here, not the one
         // for the object frame.
         nsIViewManager* vm = presShell->GetViewManager();
         if (vm) {
           nsCOMPtr<nsIWidget> widget;
           vm->GetRootWidget(getter_AddRefs(widget));
           if (widget)
             widget->SetFocus(false);
@@ -1739,17 +1746,17 @@ nsFocusManager::Focus(nsPIDOMWindow* aWi
   // own widget and is either already focused or is about to be focused.
   nsCOMPtr<nsIWidget> objectFrameWidget;
   if (aContent) {
     nsIFrame* contentFrame = aContent->GetPrimaryFrame();
     nsIObjectFrame* objectFrame = do_QueryFrame(contentFrame);
     if (objectFrame)
       objectFrameWidget = objectFrame->GetWidget();
   }
-  if (aAdjustWidgets && !objectFrameWidget) {
+  if (aAdjustWidgets && !objectFrameWidget && !sTestMode) {
     nsIViewManager* vm = presShell->GetViewManager();
     if (vm) {
       nsCOMPtr<nsIWidget> widget;
       vm->GetRootWidget(getter_AddRefs(widget));
       if (widget)
         widget->SetFocus(false);
     }
   }
@@ -1786,17 +1793,17 @@ nsFocusManager::Focus(nsPIDOMWindow* aWi
         ScrollIntoView(presShell, aContent, aFlags);
 
       NotifyFocusStateChange(aContent, aWindow->ShouldShowFocusRing(), true);
 
       // if this is an object/plug-in/remote browser, focus its widget.  Note that we might
       // no longer be in the same document, due to the events we fired above when
       // aIsNewDocument.
       if (presShell->GetDocument() == aContent->GetDocument()) {
-        if (aAdjustWidgets && objectFrameWidget)
+        if (aAdjustWidgets && objectFrameWidget && !sTestMode)
           objectFrameWidget->SetFocus(false);
 
         // if the object being focused is a remote browser, activate remote content
         TabParent* remote = GetRemoteForContent(aContent);
         if (remote) {
           remote->Activate();
 #ifdef DEBUG_FOCUS
           printf("*Remote browser activated\n");
@@ -1828,17 +1835,18 @@ nsFocusManager::Focus(nsPIDOMWindow* aWi
       }
     }
   }
   else {
     // If the window focus event (fired above when aIsNewDocument) caused
     // the plugin not to be focusable, update the system focus by focusing
     // the root widget.
     if (aAdjustWidgets && objectFrameWidget &&
-        mFocusedWindow == aWindow && mFocusedContent == nsnull) {
+        mFocusedWindow == aWindow && mFocusedContent == nsnull &&
+        !sTestMode) {
       nsIViewManager* vm = presShell->GetViewManager();
       if (vm) {
         nsCOMPtr<nsIWidget> widget;
         vm->GetRootWidget(getter_AddRefs(widget));
         if (widget)
           widget->SetFocus(false);
       }
     }
@@ -1960,16 +1968,25 @@ nsFocusManager::ScrollIntoView(nsIPresSh
 void
 nsFocusManager::RaiseWindow(nsPIDOMWindow* aWindow)
 {
   // don't raise windows that are already raised or are in the process of
   // being lowered
   if (!aWindow || aWindow == mActiveWindow || aWindow == mWindowBeingLowered)
     return;
 
+  if (sTestMode) {
+    // In test mode, emulate the existing window being lowered and the new
+    // window being raised.
+    if (mActiveWindow)
+      WindowLowered(mActiveWindow);
+    WindowRaised(aWindow);
+    return;
+  }
+
 #if defined(XP_WIN) || defined(XP_OS2)
   // Windows would rather we focus the child widget, otherwise, the toplevel
   // widget will always end up being focused. Fortunately, focusing the child
   // widget will also have the effect of raising the window this widget is in.
   // But on other platforms, we can just focus the toplevel widget to raise
   // the window.
   nsCOMPtr<nsPIDOMWindow> childWindow;
   GetFocusedDescendant(aWindow, true, getter_AddRefs(childWindow));
--- a/dom/base/nsFocusManager.h
+++ b/dom/base/nsFocusManager.h
@@ -522,16 +522,18 @@ private:
   // A document which is handling a mouse button down event.
   // When a mouse down event process is finished, ESM sets focus to the target
   // content.  Therefore, while DOM event handlers are handling mouse down
   // events, the handlers should be able to steal focus from any elements even
   // if focus is in chrome content.  So, if this isn't NULL and the caller
   // can access the document node, the caller should succeed in moving focus.
   nsCOMPtr<nsIDocument> mMouseDownEventHandlingDocument;
 
+  static bool sTestMode;
+
   // the single focus manager
   static nsFocusManager* sInstance;
 };
 
 nsresult
 NS_NewFocusManager(nsIFocusManager** aResult);
 
 #endif
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -252,18 +252,16 @@
 #include "mozilla/Telemetry.h"
 #include "nsLocation.h"
 #include "nsWrapperCacheInlines.h"
 
 #ifdef ANDROID
 #include <android/log.h>
 #endif
 
-#include "jscntxt.h" // cx->runtime->structuredCloneCallbacks
-
 #ifdef PR_LOGGING
 static PRLogModuleInfo* gDOMLeakPRLog;
 #endif
 
 static const char kStorageEnabled[] = "dom.storage.enabled";
 
 using namespace mozilla;
 using namespace mozilla::dom;
@@ -1401,18 +1399,19 @@ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(
 NS_INTERFACE_MAP_END
 
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsGlobalWindow)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsGlobalWindow)
 
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsGlobalWindow)
-  if (tmp->mDoc && nsCCUncollectableMarker::InGeneration(
-                     cb, tmp->mDoc->GetMarkedCCGeneration())) {
+  if ((tmp->mDoc && nsCCUncollectableMarker::InGeneration(
+                      cb, tmp->mDoc->GetMarkedCCGeneration())) ||
+      (nsCCUncollectableMarker::sGeneration && tmp->IsBlack())) {
     return NS_SUCCESS_INTERRUPTED_TRAVERSE;
   }
 
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mContext)
 
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mControllers)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mArguments)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mArgumentsLast)
@@ -6026,17 +6025,17 @@ PostMessageReadStructuredClone(JSContext
                                                     getter_AddRefs(wrapper)))) {
           return JSVAL_TO_OBJECT(val);
         }
       }
     }
   }
 
   const JSStructuredCloneCallbacks* runtimeCallbacks =
-    cx->runtime->structuredCloneCallbacks;
+    js::GetContextStructuredCloneCallbacks(cx);
 
   if (runtimeCallbacks) {
     return runtimeCallbacks->read(cx, reader, tag, data, nsnull);
   }
 
   return JS_FALSE;
 }
 
@@ -6066,17 +6065,17 @@ PostMessageWriteStructuredClone(JSContex
 
     if (scTag)
       return JS_WriteUint32Pair(writer, scTag, 0) &&
              JS_WriteBytes(writer, &supports, sizeof(supports)) &&
              scInfo->event->StoreISupports(supports);
   }
 
   const JSStructuredCloneCallbacks* runtimeCallbacks =
-    cx->runtime->structuredCloneCallbacks;
+    js::GetContextStructuredCloneCallbacks(cx);
 
   if (runtimeCallbacks) {
     return runtimeCallbacks->write(cx, writer, obj, nsnull);
   }
 
   return JS_FALSE;
 }
 
@@ -9176,16 +9175,18 @@ nsGlobalWindow::RunTimeout(nsTimeout *aT
   dummy_timeout.AddRef();
   dummy_timeout.AddRef();
 
   last_insertion_point = mTimeoutInsertionPoint;
   // If we ever start setting mTimeoutInsertionPoint to a non-dummy timeout,
   // the logic in ResetTimersForNonBackgroundWindow will need to change.
   mTimeoutInsertionPoint = &dummy_timeout;
 
+  Telemetry::AutoCounter<Telemetry::DOM_TIMERS_FIRED_PER_NATIVE_TIMEOUT> timeoutsRan;
+
   for (timeout = FirstTimeout();
        timeout != &dummy_timeout && !IsFrozen();
        timeout = nextTimeout) {
     nextTimeout = timeout->Next();
 
     if (timeout->mFiringDepth != firingDepth) {
       // We skip the timeout since it's on the list to run at another
       // depth.
@@ -9227,16 +9228,17 @@ nsGlobalWindow::RunTimeout(nsTimeout *aT
       // we'll fire the timeouts that are due at that point.
       continue;
     }
 
     // This timeout is good to run
     nsTimeout *last_running_timeout = mRunningTimeout;
     mRunningTimeout = timeout;
     timeout->mRunning = true;
+    ++timeoutsRan;
 
     // Push this timeout's popup control state, which should only be
     // eabled the first time a timeout fires that was created while
     // popups were enabled and with a delay less than
     // "dom.disable_open_click_delay".
     nsAutoPopupStatePusher popupStatePusher(timeout->mPopupState);
 
     // Clear the timeout's popup state, if any, to prevent interval
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -32,17 +32,16 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
-#include "jscntxt.h"
 #include "nsJSEnvironment.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIScriptObjectPrincipal.h"
 #include "nsIDOMChromeWindow.h"
 #include "nsPIDOMWindow.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsDOMCID.h"
 #include "nsIServiceManager.h"
@@ -707,18 +706,17 @@ nsJSContext::DOMOperationCallback(JSCont
   // If we get here we're most likely executing an infinite loop in JS,
   // we'll tell the user about this and we'll give the user the option
   // of stopping the execution of the script.
   nsCOMPtr<nsIPrompt> prompt = GetPromptFromContext(ctx);
   NS_ENSURE_TRUE(prompt, JS_FALSE);
 
   // Check if we should offer the option to debug
   JSStackFrame* fp = ::JS_GetScriptedCaller(cx, NULL);
-  bool debugPossible = (fp != nsnull && cx->debugHooks &&
-                          cx->debugHooks->debuggerHandler != nsnull);
+  bool debugPossible = fp && js::CanCallContextDebugHandler(cx);
 #ifdef MOZ_JSDEBUGGER
   // Get the debugger service if necessary.
   if (debugPossible) {
     bool jsds_IsOn = false;
     const char jsdServiceCtrID[] = "@mozilla.org/js/jsd/debugger-service;1";
     nsCOMPtr<jsdIExecutionHook> jsdHook;
     nsCOMPtr<jsdIDebuggerService> jsds = do_GetService(jsdServiceCtrID, &rv);
 
@@ -837,20 +835,17 @@ nsJSContext::DOMOperationCallback(JSCont
     }
 
     ctx->mOperationCallbackTime = PR_Now();
     return JS_TRUE;
   }
   else if ((buttonPressed == 2) && debugPossible) {
     // Debug the script
     jsval rval;
-    switch(cx->debugHooks->debuggerHandler(cx, script, ::JS_GetFramePC(cx, fp),
-                                           &rval,
-                                           cx->debugHooks->
-                                           debuggerHandlerData)) {
+    switch (js::CallContextDebugHandler(cx, script, JS_GetFramePC(cx, fp), &rval)) {
       case JSTRAP_RETURN:
         JS_SetFrameReturnValue(cx, fp, rval);
         return JS_TRUE;
       case JSTRAP_ERROR:
         JS_ClearPendingException(cx);
         return JS_FALSE;
       case JSTRAP_THROW:
         JS_SetPendingException(cx, rval);
@@ -1126,17 +1121,17 @@ nsJSContext::DestroyJSContext()
   mContext = nsnull;
 }
 
 // QueryInterface implementation for nsJSContext
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsJSContext)
 NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsJSContext)
 NS_IMPL_CYCLE_COLLECTION_TRACE_END
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsJSContext)
-  NS_ASSERTION(!tmp->mContext || tmp->mContext->outstandingRequests == 0,
+  NS_ASSERTION(!tmp->mContext || js::GetContextOutstandingRequests(tmp->mContext) == 0,
                "Trying to unlink a context with outstanding requests.");
   tmp->mIsInitialized = false;
   tmp->mGCOnDestruction = false;
   tmp->DestroyJSContext();
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mGlobalObjectRef)
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsJSContext)
   NS_IMPL_CYCLE_COLLECTION_DESCRIBE(nsJSContext, tmp->GetCCRefcnt())
@@ -1156,17 +1151,17 @@ NS_INTERFACE_MAP_END
 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsJSContext)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsJSContext)
 
 nsrefcnt
 nsJSContext::GetCCRefcnt()
 {
   nsrefcnt refcnt = mRefCnt.get();
   if (NS_LIKELY(mContext))
-    refcnt += mContext->outstandingRequests;
+    refcnt += js::GetContextOutstandingRequests(mContext);
   return refcnt;
 }
 
 nsresult
 nsJSContext::EvaluateStringWithValue(const nsAString& aScript,
                                      JSObject* aScopeObject,
                                      nsIPrincipal *aPrincipal,
                                      const char *aURL,
--- a/dom/indexedDB/IDBObjectStore.cpp
+++ b/dom/indexedDB/IDBObjectStore.cpp
@@ -36,17 +36,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "IDBObjectStore.h"
 
 #include "nsIJSContextStack.h"
 
-#include "jsclone.h"
+#include "jsfriendapi.h"
 #include "mozilla/dom/StructuredCloneTags.h"
 #include "mozilla/storage.h"
 #include "nsCharSeparatedTokenizer.h"
 #include "nsContentUtils.h"
 #include "nsDOMClassInfo.h"
 #include "nsDOMFile.h"
 #include "nsDOMLists.h"
 #include "nsEventDispatcher.h"
@@ -1018,17 +1018,17 @@ IDBObjectStore::StructuredCloneReadCallb
       NS_WARNING("Failed to wrap native!");
       return nsnull;
     }
 
     return JSVAL_TO_OBJECT(wrappedFile);
   }
 
   const JSStructuredCloneCallbacks* runtimeCallbacks =
-    aCx->runtime->structuredCloneCallbacks;
+    js::GetContextStructuredCloneCallbacks(aCx);
 
   if (runtimeCallbacks) {
     return runtimeCallbacks->read(aCx, aReader, aTag, aData, nsnull);
   }
 
   return nsnull;
 }
 
@@ -1099,17 +1099,17 @@ IDBObjectStore::StructuredCloneWriteCall
       cloneWriteInfo->mBlobs.AppendElement(blob);
 
       return true;
     }
   }
 
   // try using the runtime callbacks
   const JSStructuredCloneCallbacks* runtimeCallbacks =
-    aCx->runtime->structuredCloneCallbacks;
+    js::GetContextStructuredCloneCallbacks(aCx);
   if (runtimeCallbacks) {
     return runtimeCallbacks->write(aCx, aWriter, aObj, nsnull);
   }
 
   return false;
 }
 
 nsresult
--- a/dom/indexedDB/Key.cpp
+++ b/dom/indexedDB/Key.cpp
@@ -34,17 +34,17 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "Key.h"
 #include "nsIStreamBufferAccess.h"
-#include "jsdate.h"
+#include "jsfriendapi.h"
 #include "nsAlgorithm.h"
 #include "nsContentUtils.h"
 #include "nsJSUtils.h"
 #include "xpcpublic.h"
 
 USING_INDEXEDDB_NAMESPACE
 
 /*
--- a/dom/interfaces/base/nsIDOMWindowUtils.idl
+++ b/dom/interfaces/base/nsIDOMWindowUtils.idl
@@ -64,17 +64,17 @@ interface nsIDOMHTMLCanvasElement;
 interface nsIDOMEvent;
 interface nsITransferable;
 interface nsIQueryContentEventResult;
 interface nsIDOMWindow;
 interface nsIDOMBlob;
 interface nsIDOMFile;
 interface nsIFile;
 
-[scriptable, uuid(15fcceb0-37ea-11e1-b86c-0800200c9a66)]
+[scriptable, uuid(b9c1f815-c2f2-4607-a060-6a8566581927)]
 interface nsIDOMWindowUtils : nsISupports {
 
   /**
    * Image animation mode of the window. When this attribute's value
    * is changed, the implementation should set all images in the window
    * to the given value. That is, when set to kDontAnimMode, all images
    * will stop animating. The attribute's value must be one of the
    * animationMode values from imgIContainer.
@@ -373,22 +373,16 @@ interface nsIDOMWindowUtils : nsISupport
    * privileges in non-debug builds. Available to all callers in debug builds.
    *
    * @param aListener listener that receives information about the CC graph
    *                  (see @mozilla.org/cycle-collector-logger;1 for a logger
    *                   component)
    */
   void cycleCollect([optional] in nsICycleCollectorListener aListener);
 
-  /**
-   * Force processing of any queued paints
-   */
-
-  void processUpdates();
-
   /** Synthesize a simple gesture event for a window. The event types
    *  supported are: MozSwipeGesture, MozMagnifyGestureStart,
    *  MozMagnifyGestureUpdate, MozMagnifyGesture, MozRotateGestureStart,
    *  MozRotateGestureUpdate, MozRotateGesture, MozPressTapGesture, and
    *  MozTapGesture.
    *
    * Cannot be accessed from unprivileged context (not
    * content-accessible) Will throw a DOM security error if called
--- a/dom/interfaces/css/nsIDOMCSS2Properties.idl
+++ b/dom/interfaces/css/nsIDOMCSS2Properties.idl
@@ -615,16 +615,19 @@ interface nsIDOMCSS2Properties : nsISupp
 
            /* CSS3 properties */
            attribute DOMString        opacity;
                                         // raises(DOMException) on setting
 
            attribute DOMString        outlineOffset;
                                         // raises(DOMException) on setting
 
+           attribute DOMString        MozTextAlignLast;
+                                        // raises(DOMException) on setting
+
            /* Mozilla extensions */
            attribute DOMString        overflowX;
                                         // raises(DOMException) on setting
 
            attribute DOMString        overflowY;
                                         // raises(DOMException) on setting
 
            attribute DOMString        imeMode;
--- a/dom/plugins/base/android/ANPSurface.cpp
+++ b/dom/plugins/base/android/ANPSurface.cpp
@@ -161,27 +161,27 @@ static int bytesPerPixel(int32_t format)
     default: return -1;
   }
 }
 
 static bool init() {
   if (gSurfaceFunctions.initialized)
     return true;
 
-  void* handle = dlopen("/system/lib/libsurfaceflinger_client.so", RTLD_LAZY);
+  void* handle = dlopen("libsurfaceflinger_client.so", RTLD_LAZY);
 
   if (!handle) {
     LOG("Failed to open libsurfaceflinger_client.so");
     return false;
   }
 
   gSurfaceFunctions.lock = (int (*)(void*, SurfaceInfo*, void*))dlsym(handle, "_ZN7android7Surface4lockEPNS0_11SurfaceInfoEPNS_6RegionEb");
   gSurfaceFunctions.unlockAndPost = (int (*)(void*))dlsym(handle, "_ZN7android7Surface13unlockAndPostEv");
 
-  handle = dlopen("/system/lib/libui.so", RTLD_LAZY);
+  handle = dlopen("libui.so", RTLD_LAZY);
   if (!handle) {
     LOG("Failed to open libui.so");
     return false;
   }
 
   gSurfaceFunctions.regionConstructor = (void* (*)(void*))dlsym(handle, "_ZN7android6RegionC1Ev");
   gSurfaceFunctions.setRegion = (void (*)(void*, ARect const&))dlsym(handle, "_ZN7android6Region3setERKNS_4RectE");
 
--- a/dom/plugins/base/nsJSNPRuntime.cpp
+++ b/dom/plugins/base/nsJSNPRuntime.cpp
@@ -34,18 +34,16 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "base/basictypes.h"
 
 #include "jsapi.h"
-// FIXME(bug 332648): Give me a real API please!
-#include "jscntxt.h"
 #include "jsfriendapi.h"
 
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsJSNPRuntime.h"
 #include "nsNPAPIPlugin.h"
 #include "nsNPAPIPluginInstance.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIScriptContext.h"
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -616,18 +616,17 @@ NS_IMETHODIMP nsPluginInstanceOwner::Inv
   }
 
 #ifndef XP_MACOSX
   // Windowed plugins should not be calling NPN_InvalidateRect, but
   // Silverlight does and expects it to "work"
   if (mWidget) {
     mWidget->Invalidate(nsIntRect(invalidRect->left, invalidRect->top,
                                   invalidRect->right - invalidRect->left,
-                                  invalidRect->bottom - invalidRect->top),
-                        false);
+                                  invalidRect->bottom - invalidRect->top));
     return NS_OK;
   }
 #endif
 
   nsPresContext* presContext = mObjectFrame->PresContext();
   nsRect rect(presContext->DevPixelsToAppUnits(invalidRect->left),
               presContext->DevPixelsToAppUnits(invalidRect->top),
               presContext->DevPixelsToAppUnits(invalidRect->right - invalidRect->left),
@@ -649,22 +648,16 @@ NS_IMETHODIMP nsPluginInstanceOwner::Inv
 
 NS_IMETHODIMP nsPluginInstanceOwner::InvalidateRegion(NPRegion invalidRegion)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 NS_IMETHODIMP nsPluginInstanceOwner::ForceRedraw()
 {
-  NS_ENSURE_TRUE(mObjectFrame, NS_ERROR_NULL_POINTER);
-  nsIView* view = mObjectFrame->GetView();
-  if (view) {
-    return view->GetViewManager()->Composite();
-  }
-
   return NS_OK;
 }
 
 NS_IMETHODIMP nsPluginInstanceOwner::GetNetscapeWindow(void *value)
 {
   if (!mObjectFrame) {
     NS_WARNING("plugin owner has no owner in getting doc's window handle");
     return NS_ERROR_FAILURE;
--- a/dom/plugins/ipc/PluginInstanceChild.cpp
+++ b/dom/plugins/ipc/PluginInstanceChild.cpp
@@ -2575,17 +2575,17 @@ PluginInstanceChild::MaybeCreatePlatform
             return true;
         }
 #endif
         // For image layer surface we should always create helper surface
         createHelperSurface = true;
         // Check if we can create helper surface with non-default visual
         visual = gfxXlibSurface::FindVisual(screen,
             static_cast<gfxImageSurface*>(mCurrentSurface.get())->Format());
-        if (visual && defaultVisual != visual && !supportNonDefaultVisual) {
+        if (!visual || (defaultVisual != visual && !supportNonDefaultVisual)) {
             visual = defaultVisual;
             mDoAlphaExtraction = mIsTransparent;
         }
     }
 
     if (createHelperSurface) {
         if (!visual) {
             NS_ERROR("Need X falback surface, but visual failed");
--- a/dom/sms/src/SmsMessage.cpp
+++ b/dom/sms/src/SmsMessage.cpp
@@ -34,17 +34,17 @@
  * 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 "SmsMessage.h"
 #include "nsIDOMClassInfo.h"
 #include "jsapi.h" // For OBJECT_TO_JSVAL and JS_NewDateObjectMsec
-#include "jsdate.h" // For js_DateGetMsecSinceEpoch
+#include "jsfriendapi.h" // For js_DateGetMsecSinceEpoch
 #include "Constants.h"
 
 DOMCI_DATA(MozSmsMessage, mozilla::dom::sms::SmsMessage)
 
 namespace mozilla {
 namespace dom {
 namespace sms {
 
--- a/dom/wifi/libcutils.js
+++ b/dom/wifi/libcutils.js
@@ -1,13 +1,13 @@
 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
 
 "use strict";
 
 let libcutils = (function () {
-  let library = ctypes.open("/system/lib/libcutils.so");
+  let library = ctypes.open("libcutils.so");
 
   return {
     property_get: library.declare("property_get", ctypes.default_abi, ctypes.int, ctypes.char.ptr, ctypes.char.ptr, ctypes.char.ptr),
     property_set: library.declare("property_set", ctypes.default_abi, ctypes.int, ctypes.char.ptr, ctypes.char.ptr)
   };
 })();
--- a/dom/wifi/libhardware_legacy.js
+++ b/dom/wifi/libhardware_legacy.js
@@ -1,15 +1,15 @@
 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
 
 "use strict";
 
 let libhardware_legacy = (function () {
-  let library = ctypes.open("/system/lib/libhardware_legacy.so");
+  let library = ctypes.open("libhardware_legacy.so");
 
   return {
     // Load wifi driver, 0 on success, < 0 on failure.
     load_driver: library.declare("wifi_load_driver", ctypes.default_abi, ctypes.int),
 
     // Unload wifi driver, 0 on success, < 0 on failure.
     unload_driver: library.declare("wifi_unload_driver", ctypes.default_abi, ctypes.int),
 
--- a/dom/wifi/libnetutils.js
+++ b/dom/wifi/libnetutils.js
@@ -1,15 +1,15 @@
 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
 
 "use strict";
 
 let libnetutils = (function () {
-  let library = ctypes.open("/system/lib/libnetutils.so");
+  let library = ctypes.open("libnetutils.so");
 
   return {
     ifc_enable: library.declare("ifc_enable", ctypes.default_abi, ctypes.int, ctypes.char.ptr),
     ifc_disable: library.declare("ifc_disable", ctypes.default_abi, ctypes.int, ctypes.char.ptr),
     ifc_add_host_route: library.declare("ifc_add_host_route", ctypes.default_abi, ctypes.int, ctypes.char.ptr, ctypes.int),
     ifc_remove_host_routes: library.declare("ifc_remove_host_routes", ctypes.default_abi, ctypes.int, ctypes.char.ptr),
     ifc_set_default_route: library.declare("ifc_set_default_route", ctypes.default_abi, ctypes.int, ctypes.char.ptr, ctypes.int),
     ifc_get_default_route: library.declare("ifc_get_default_route", ctypes.default_abi, ctypes.int, ctypes.char.ptr),
--- a/dom/wifi/nsWifiWorker.js
+++ b/dom/wifi/nsWifiWorker.js
@@ -46,16 +46,23 @@ Cu.import("resource://gre/modules/XPCOMU
 
 const DEBUG = true; // set to false to suppress debug messages
 
 const WIFIWORKER_CONTRACTID = "@mozilla.org/wifi/worker;1";
 const WIFIWORKER_CID        = Components.ID("{a14e8977-d259-433a-a88d-58dd44657e5b}");
 
 const WIFIWORKER_WORKER     = "resource://gre/modules/network_worker.js";
 
+// A note about errors and error handling in this file:
+// The libraries that we use in this file are intended for C code. For
+// C code, it is natural to return -1 for errors and 0 for success.
+// Therefore, the code that interacts directly with the worker uses this
+// convention (note: command functions do get boolean results since the
+// command always succeeds and we do a string/boolean check for the
+// expected results).
 var WifiManager = (function() {
   var controlWorker = new ChromeWorker(WIFIWORKER_WORKER);
   var eventWorker = new ChromeWorker(WIFIWORKER_WORKER);
 
   // Callbacks to invoke when a reply arrives from the controlWorker.
   var controlCallbacks = Object.create(null);
   var idgen = 0;
 
@@ -501,16 +508,47 @@ var WifiManager = (function() {
     retryTimer = null;
     notify("supplicantlost");
   }
 
   manager.start = function() {
     connectToSupplicant(connectCallback);
   }
 
+  function onconnected() {
+    runDhcp(manager.ifname, function (data) {
+      if (!data) {
+        debug("DHCP failed to run");
+        return;
+      }
+      setProperty("net.dns1", ipToString(data.dns1), function(ok) {
+        if (!ok) {
+          debug("Unable to set net.dns1");
+          return;
+        }
+        setProperty("net.dns2", ipToString(data.dns2), function(ok) {
+          if (!ok) {
+            debug("Unable to set net.dns2");
+            return;
+          }
+          getProperty("net.dnschange", "0", function(value) {
+            if (value === null) {
+              debug("Unable to get net.dnschange");
+              return;
+            }
+            setProperty("net.dnschange", String(Number(value) + 1), function(ok) {
+              if (!ok)
+                debug("Unable to set net.dnschange");
+            });
+          });
+        });
+      });
+    });
+  }
+
   var supplicantStatesMap = ["DISCONNECTED", "INACTIVE", "SCANNING", "ASSOCIATING",
                              "FOUR_WAY_HANDSHAKE", "GROUP_HANDSHAKE", "COMPLETED",
                              "DORMANT", "UNINITIALIZED"];
   var driverEventMap = { STOPPED: "driverstopped", STARTED: "driverstarted", HANGED: "driverhung" };
 
   // handle events sent to us by the event worker
   function handleEvent(event) {
     debug("Event coming in: " + event);
@@ -564,16 +602,17 @@ var WifiManager = (function() {
       notify("statechange", { state: "DISCONNECTED" });
       return true;
     }
     if (eventData.indexOf("CTRL-EVENT-CONNECTED") === 0) {
       // Format: CTRL-EVENT-CONNECTED - Connection to 00:1e:58:ec:d5:6d completed (reauth) [id=1 id_str=]
       var bssid = eventData.split(" ")[4];
       var id = eventData.substr(eventData.indexOf("id=")).split(" ")[0];
       notify("statechange", { state: "CONNECTED", BSSID: bssid, id: id });
+      onconnected();
       return true;
     }
     if (eventData.indexOf("CTRL-EVENT-SCAN-RESULTS") === 0) {
       debug("Notifying of scn results available");
       notify("scanresultsavailable");
       return true;
     }
     // unknown event
@@ -586,22 +625,47 @@ var WifiManager = (function() {
   // Public interface of the wifi service
   manager.setWifiEnabled = function(enable, callback) {
     var targetState = enable ? "ENABLED" : "DISABLED";
     if (enable == targetState)
       return true;
     if (enable && airplaneMode)
       return false;
     if (enable) {
-      loadDriver(function (ok) {
-        (ok === 0) ? startSupplicant(callback) : callback(-1);
+      loadDriver(function (status) {
+        if (status < 0) {
+          callback(status);
+          return;
+        }
+        startSupplicant(function (status) {