Merge mozilla-central to tracemonkey.
authorRobert Sayre <sayrer@gmail.com>
Sun, 04 Apr 2010 14:15:05 -0400
changeset 40455 df40cdde12730b8b6874e7dd2595c3fbaec63248
parent 40454 954e0f3185f7ecab2b2b5fae29085a01c5189ae3 (current diff)
parent 40207 e8daca473796edccc09fcb86706c111f609e1a62 (diff)
child 40456 1942c0b4e1018bb85fc17676c634d6e631662073
child 40791 80fc5dcabaf9713372f15b4cfa60dd492017288b
push idunknown
push userunknown
push dateunknown
milestone1.9.3a4pre
Merge mozilla-central to tracemonkey.
configure.in
content/base/public/nsContentUtils.h
content/canvas/src/nsCanvasRenderingContext2D.cpp
js/src/Makefile.in
js/src/configure.in
js/src/jscpucfg.cpp
js/src/jsnum.cpp
js/src/jstracer.cpp
layout/reftests/bugs/reftest.list
layout/style/nsCSSLoader.h
modules/plugin/base/src/nsNPAPIPlugin.cpp
testing/mochitest/ssltunnel/Makefile.in
toolkit/toolkit-makefiles.sh
toolkit/toolkit-tiers.mk
--- a/browser/base/content/test/browser_sanitize-sitepermissions.js
+++ b/browser/base/content/test/browser_sanitize-sitepermissions.js
@@ -1,18 +1,17 @@
 // Bug 380852 - Delete permission manager entries in Clear Recent History
 
 Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader)
                                            .loadSubScript("chrome://browser/content/sanitize.js");
 
 function test() {
   
   // Add a permission entry
-  var pm = Cc["@mozilla.org/permissionmanager;1"]
-             .getService(Ci.nsIPermissionManager);
+  var pm = Services.perms;
   pm.add(makeURI("http://example.com"), "testing", pm.ALLOW_ACTION);
   
   // Sanity check
   ok(pm.enumerator.hasMoreElements(), "Permission manager should have elements, since we just added one");
   
   // Set up the sanitizer to just clear siteSettings
   let s = new Sanitizer();
   s.ignoreTimespan = false;
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_fastswitch.js
+++ b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_fastswitch.js
@@ -37,18 +37,16 @@
 
 // This test makes sure that users are prevented from toggling the private
 // browsing mode too quickly, hence be proctected from symptoms in bug 526194.
 
 function test() {
   // initialization
   let pb = Cc["@mozilla.org/privatebrowsing;1"].
            getService(Ci.nsIPrivateBrowsingService);
-  let os = Cc["@mozilla.org/observer-service;1"].
-           getService(Ci.nsIObserverService);
   let pbCmd = document.getElementById("Tools:PrivateBrowsing");
   waitForExplicitFinish();
 
   let pass = 1;
   function observer(aSubject, aTopic, aData) {
     switch (aTopic) {
       case "private-browsing":
         setTimeout(function () {
@@ -66,21 +64,21 @@ function test() {
             pb.privateBrowsingEnabled = false;
           }, 100);
         }
         else {
           setTimeout(function () {
             ok(!pbCmd.hasAttribute("disabled"),
                "The private browsing command should be re-enabled after exiting the private browsing mode");
 
-            os.removeObserver(observer, "private-browsing");
-            os.removeObserver(observer, "private-browsing-transition-complete");
+            Services.obs.removeObserver(observer, "private-browsing");
+            Services.obs.removeObserver(observer, "private-browsing-transition-complete");
             finish();
           }, 100);
         }
         break;
     }
   }
-  os.addObserver(observer, "private-browsing", false);
-  os.addObserver(observer, "private-browsing-transition-complete", false);
+  Services.obs.addObserver(observer, "private-browsing", false);
+  Services.obs.addObserver(observer, "private-browsing-transition-complete", false);
 
   pb.privateBrowsingEnabled = true;
 }
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_openlocation.js
+++ b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_openlocation.js
@@ -37,18 +37,16 @@
 
 // This test makes sure that Open Location dialog is usable inside the private browsing
 // mode without leaving any trace of the URLs visited.
 
 function test() {
   // initialization
   let pb = Cc["@mozilla.org/privatebrowsing;1"].
            getService(Ci.nsIPrivateBrowsingService);
-  let ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
-           getService(Ci.nsIWindowWatcher);
   waitForExplicitFinish();
 
   function openLocation(url, autofilled, callback) {
     function observer(aSubject, aTopic, aData) {
       switch (aTopic) {
         case "domwindowopened":
           let dialog = aSubject.QueryInterface(Ci.nsIDOMWindow);
           dialog.addEventListener("load", function () {
@@ -70,22 +68,22 @@ function test() {
               for (let i = 0; i < url.length; ++i)
                 EventUtils.synthesizeKey(url[i], {}, dialog);
               EventUtils.synthesizeKey("VK_RETURN", {}, dialog);
             });
           }, false);
           break;
 
         case "domwindowclosed":
-          ww.unregisterNotification(arguments.callee);
+          Services.ww.unregisterNotification(arguments.callee);
           break;
       }
     }
 
-    ww.registerNotification(observer);
+    Services.ww.registerNotification(observer);
     gPrefService.setIntPref("general.open_location.last_window_choice", 0);
     openDialog("chrome://browser/content/openLocation.xul", "_blank",
                "chrome,titlebar", window);
   }
 
 
   if (gPrefService.prefHasUserValue("general.open_location.last_url"))
     gPrefService.clearUserPref("general.open_location.last_url");
--- a/browser/components/search/test/browser_483086.js
+++ b/browser/components/search/test/browser_483086.js
@@ -29,18 +29,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 ***** */
 let gSS = Services.search;
-let gObs = Cc["@mozilla.org/observer-service;1"].
-           getService(Ci.nsIObserverService);
 
 function test() {
   waitForExplicitFinish();
 
   function observer(aSubject, aTopic, aData) {
     switch (aData) {
       case "engine-added":
         let engine = gSS.getEngineByName("483086a");
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -43,22 +43,23 @@
 @BINPATH@/@DLL_PREFIX@mozjs@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@plc4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@plds4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@xpcom@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@nspr4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@mozalloc@DLL_SUFFIX@
 #ifdef XP_MACOSX
 @BINPATH@/XUL
+@BINPATH@/mozilla-runtime@BIN_SUFFIX@
 #else
 @BINPATH@/@DLL_PREFIX@xul@DLL_SUFFIX@
-#endif
 #ifdef MOZ_IPC
 @BINPATH@/mozilla-runtime@BIN_SUFFIX@
 #endif
+#endif
 #ifdef WINCE
 @BINPATH@/mozce_shunt.dll
 #elifdef XP_WIN32
 #ifndef MOZ_MEMORY
 @BINPATH@/Microsoft.VC80.CRT.manifest
 @BINPATH@/msvcm80.dll
 @BINPATH@/msvcp80.dll
 @BINPATH@/msvcr80.dll
--- a/chrome/test/unit/test_bug519468.js
+++ b/chrome/test/unit/test_bug519468.js
@@ -51,18 +51,19 @@ var locales;
 
 if (systemLocale == "en-US")
   locales = [ "en-US", "fr-FR", "de-DE" ];
 else if (systemLocale == "fr-FR")
   locales = [ "en-US", systemLocale, "de-DE" ];
 else
   locales = [ "en-US", systemLocale, "fr-FR" ];
 
+do_get_profile();
 var workingDir = Cc["@mozilla.org/file/directory_service;1"].
-                 getService(Ci.nsIProperties).get("TmpD", Ci.nsIFile);
+                 getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
 var manifest = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
 manifest.initWithFile(workingDir);
 manifest.append("test_bug519468.manifest");
 manifest.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0600);
 var stream = Cc["@mozilla.org/network/file-output-stream;1"].
              createInstance(Ci.nsIFileOutputStream);
 stream.init(manifest, 0x04 | 0x08 | 0x20, 0600, 0); // write, create, truncate
 locales.slice(0,2).forEach(function(l) write_locale(stream, l, "testmatchos"));
@@ -73,16 +74,17 @@ var MANIFESTS = [
   manifest
 ];
 
 registerManifests(MANIFESTS);
 
 var chromeReg = Cc["@mozilla.org/chrome/chrome-registry;1"]
                 .getService(Ci.nsIXULChromeRegistry)
                 .QueryInterface(Ci.nsIToolkitChromeRegistry);
+chromeReg.checkForNewChrome();
 
 var prefService = Cc["@mozilla.org/preferences-service;1"]
                   .getService(Ci.nsIPrefService)
                   .QueryInterface(Ci.nsIPrefBranch);
 
 function test_locale(aTest) {
   prefService.setBoolPref("intl.locale.matchOS", aTest.matchOS);
   if (aTest.selected)
@@ -111,10 +113,9 @@ function run_test()
   ];
 
   for (var i = 0; i < tests.length; ++ i) {
     var test = tests[i];
     if (!test.package)
       test.package = "testmatchos";
     test_locale(test);
   }
-  manifest.remove(false);
 }
--- a/config/Makefile.in
+++ b/config/Makefile.in
@@ -132,16 +132,36 @@ export::
 		-DMOZ_NATIVE_PNG=$(MOZ_NATIVE_PNG) \
 		-DMOZ_NATIVE_JPEG=$(MOZ_NATIVE_JPEG) \
 		$(srcdir)/system-headers | $(PERL) $(topsrcdir)/nsprpub/config/make-system-wrappers.pl system_wrappers
 	$(INSTALL) system_wrappers $(DIST)
 
 GARBAGE_DIRS += system_wrappers
 endif
 
+ifdef WRAP_STL_INCLUDES
+ifdef GCC_VERSION
+stl_compiler = gcc
+else
+stl_compiler = msvc
+endif
+endif
+
+ifdef stl_compiler
+stl-wrappers-sentinel: $(srcdir)/make-stl-wrappers.py $(srcdir)/$(stl_compiler)-stl-wrapper.template.h $(srcdir)/stl-headers $(GLOBAL_DEPS)
+	$(PYTHON) $(srcdir)/make-stl-wrappers.py stl_wrappers $(stl_compiler) $(srcdir)/$(stl_compiler)-stl-wrapper.template.h $(srcdir)/stl-headers
+	$(PYTHON) $(srcdir)/nsinstall.py stl_wrappers $(DIST)
+	touch stl-wrappers-sentinel
+
+export:: stl-wrappers-sentinel
+
+GARBAGE += stl-wrappers-sentinel
+GARBAGE_DIRS += stl_wrappers
+endif
+
 install::
 	$(SYSINSTALL) $(IFLAGS1) $(DEPTH)/mozilla-config.h $(DESTDIR)$(includedir)
 
 GARBAGE += \
 	$(FINAL_LINK_COMPS) $(FINAL_LINK_LIBS) $(FINAL_LINK_COMP_NAMES) buildid $(srcdir)/*.pyc
 
 ifndef CROSS_COMPILE
 ifdef USE_ELF_DYNSTR_GC
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -113,17 +113,16 @@ MOZ_TRACEVIS    = @MOZ_TRACEVIS@
 DEHYDRA_PATH    = @DEHYDRA_PATH@
 
 MOZ_XPCTOOLS    = @MOZ_XPCTOOLS@
 NS_TRACE_MALLOC = @NS_TRACE_MALLOC@
 USE_ELF_DYNSTR_GC = @USE_ELF_DYNSTR_GC@
 INCREMENTAL_LINKER = @INCREMENTAL_LINKER@
 MACOSX_DEPLOYMENT_TARGET = @MACOSX_DEPLOYMENT_TARGET@
 MOZ_MAIL_NEWS	= @MOZ_MAIL_NEWS@
-MOZ_CALENDAR	= @MOZ_CALENDAR@
 MOZ_PLAINTEXT_EDITOR_ONLY = @MOZ_PLAINTEXT_EDITOR_ONLY@
 BUILD_STATIC_LIBS = @BUILD_STATIC_LIBS@
 MOZ_ENABLE_LIBXUL = @MOZ_ENABLE_LIBXUL@
 ENABLE_TESTS	= @ENABLE_TESTS@
 IBMBIDI = @IBMBIDI@
 MOZ_UNIVERSALCHARDET = @MOZ_UNIVERSALCHARDET@
 ACCESSIBILITY = @ACCESSIBILITY@
 MOZ_VIEW_SOURCE = @MOZ_VIEW_SOURCE@
@@ -354,16 +353,19 @@ CXX_VERSION	= @CXX_VERSION@
 GNU_AS		= @GNU_AS@
 GNU_LD		= @GNU_LD@
 GNU_CC		= @GNU_CC@
 GNU_CXX		= @GNU_CXX@
 HAVE_GCC3_ABI	= @HAVE_GCC3_ABI@
 INTEL_CC	= @INTEL_CC@
 INTEL_CXX	= @INTEL_CXX@
 
+STL_FLAGS		= @STL_FLAGS@
+WRAP_STL_INCLUDES	= @WRAP_STL_INCLUDES@
+
 HOST_CC		= @HOST_CC@
 HOST_CXX	= @HOST_CXX@
 HOST_CFLAGS	= @HOST_CFLAGS@
 HOST_CXXFLAGS	= @HOST_CXXFLAGS@
 HOST_OPTIMIZE_FLAGS = @HOST_OPTIMIZE_FLAGS@
 HOST_NSPR_MDCPUCFG = @HOST_NSPR_MDCPUCFG@
 HOST_AR		= @HOST_AR@
 HOST_AR_FLAGS	= @HOST_AR_FLAGS@
--- a/config/config.mk
+++ b/config/config.mk
@@ -521,17 +521,17 @@ ifeq ($(OS_ARCH),Darwin)
 # Darwin doesn't cross-compile, so just set both types of flags here.
 HOST_CMFLAGS += -fobjc-exceptions
 HOST_CMMFLAGS += -fobjc-exceptions
 OS_COMPILE_CMFLAGS += -fobjc-exceptions
 OS_COMPILE_CMMFLAGS += -fobjc-exceptions
 endif
 
 COMPILE_CFLAGS	= $(VISIBILITY_FLAGS) $(DEFINES) $(INCLUDES) $(DSO_CFLAGS) $(DSO_PIC_CFLAGS) $(CFLAGS) $(RTL_FLAGS) $(OS_COMPILE_CFLAGS)
-COMPILE_CXXFLAGS = $(VISIBILITY_FLAGS) $(DEFINES) $(INCLUDES) $(DSO_CFLAGS) $(DSO_PIC_CFLAGS) $(CXXFLAGS) $(RTL_FLAGS) $(OS_COMPILE_CXXFLAGS)
+COMPILE_CXXFLAGS = $(VISIBILITY_FLAGS) $(STL_FLAGS) $(DEFINES) $(INCLUDES) $(DSO_CFLAGS) $(DSO_PIC_CFLAGS) $(CXXFLAGS) $(RTL_FLAGS) $(OS_COMPILE_CXXFLAGS)
 COMPILE_CMFLAGS = $(OS_COMPILE_CMFLAGS)
 COMPILE_CMMFLAGS = $(OS_COMPILE_CMMFLAGS)
 
 ifndef CROSS_COMPILE
 HOST_CFLAGS += $(RTL_FLAGS)
 endif
 
 #
new file mode 100644
--- /dev/null
+++ b/config/gcc-stl-wrapper.template.h
@@ -0,0 +1,85 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ * vim: sw=2 ts=8 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 Mozilla Code.
+ *
+ * The Initial Developer of the Original Code is
+ *   The Mozilla Foundation
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Chris Jones <jones.chris.g@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 ***** */
+
+#ifndef mozilla_${HEADER}_h
+#define mozilla_${HEADER}_h
+
+#if __EXCEPTIONS
+#  error "STL code can only be used with -fno-exceptions"
+#endif
+
+// See if we're in code that can use mozalloc.  NB: this duplicates
+// code in nscore.h because nscore.h pulls in prtypes.h, and chromium
+// can't build with that being included before base/basictypes.h.
+#if !defined(XPCOM_GLUE) && !defined(NS_NO_XPCOM) && !defined(MOZ_NO_MOZALLOC)
+#  include <new>              // to give mozalloc std::bad_alloc
+#  include <stdlib.h>         // to give mozalloc malloc/free decls
+#  include <string.h>
+#  include "mozilla/mozalloc.h"
+#else
+#  error "STL code can only be used with infallible ::operator new()"
+#endif
+
+#if defined(DEBUG) && !defined(_GLIBCXX_DEBUG)
+// Enable checked iterators and other goodies
+//
+// FIXME/bug 551254: gcc's debug STL implementation requires -frtti.
+// Figure out how to resolve this with -fno-rtti.  Maybe build with
+// -frtti in DEBUG builds?
+//
+//  # define _GLIBCXX_DEBUG 1
+#endif
+
+#pragma GCC visibility push(default)
+#include_next <${HEADER}>
+#pragma GCC visibility pop
+
+// gcc calls a __throw_*() function from bits/functexcept.h when it
+// wants to "throw an exception".  functexcept exists nominally to
+// support -fno-exceptions, but since we'll always use the system
+// libstdc++, and it's compiled with exceptions, then in practice
+// these __throw_*() functions will always throw exceptions (shades of
+// -fshort-wchar).  We don't want that and so define our own inlined
+// __throw_*().
+#ifndef mozilla_functexcept_h
+#  include "mozilla/functexcept.h"
+#endif
+
+#endif  // if mozilla_${HEADER}_h
new file mode 100644
--- /dev/null
+++ b/config/make-stl-wrappers.py
@@ -0,0 +1,87 @@
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is mozilla.org code.
+#
+# The Initial Developer of the Original Code is
+#   The Mozilla Foundation
+# Portions created by the Initial Developer are Copyright (C) 2010
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#   Chris Jones <jones.chris.g@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 *****
+
+import os, re, string, sys
+
+def find_in_path(file, searchpath):
+    for dir in searchpath.split(os.pathsep):
+        f = os.path.join(dir, file)
+        if os.path.exists(f):
+            return f
+    return ''
+
+def header_path(header, compiler):
+    if compiler == 'gcc':
+        # we use include_next on gcc
+        return header
+    elif compiler == 'msvc':
+        return find_in_path(header, os.environ.get('INCLUDE', ''))
+    else:
+        # hope someone notices this ...
+        raise NotImplementedError, compiler
+
+def is_comment(line):
+    return re.match(r'\s*#.*', line)
+
+def main(outdir, compiler, template_file, header_list_file):
+    if not os.path.isdir(outdir):
+        os.mkdir(outdir)
+
+    template = open(template_file, 'r').read()
+    
+    for header in open(header_list_file, 'r'):
+        header = header.rstrip()
+        if 0 == len(header) or is_comment(header):
+            continue
+
+        path = header_path(header, compiler)
+        try:
+            f = open(os.path.join(outdir, header), 'w')
+            f.write(string.Template(template).substitute(HEADER=header,
+                                                         HEADER_PATH=path))
+        finally:
+            f.close()
+
+
+if __name__ == '__main__':
+    if 5 != len(sys.argv):
+        print >>sys.stderr, """Usage:
+  python %s OUT_DIR ('msvc'|'gcc') TEMPLATE_FILE HEADER_LIST_FILE
+"""% (sys.argv[0])
+        sys.exit(1)
+
+    main(*sys.argv[1:])
new file mode 100644
--- /dev/null
+++ b/config/msvc-stl-wrapper.template.h
@@ -0,0 +1,96 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ * vim: sw=2 ts=8 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 Mozilla Code.
+ *
+ * The Initial Developer of the Original Code is
+ *   The Mozilla Foundation
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Chris Jones <jones.chris.g@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 ***** */
+
+#ifndef mozilla_${HEADER}_h
+#define mozilla_${HEADER}_h
+
+#if _HAS_EXCEPTIONS
+#  error "STL code can only be used with -fno-exceptions"
+#endif
+
+// See if we're in code that can use mozalloc.  NB: this duplicates
+// code in nscore.h because nscore.h pulls in prtypes.h, and chromium
+// can't build with that being included before base/basictypes.h.
+#if !defined(XPCOM_GLUE) && !defined(NS_NO_XPCOM) && !defined(MOZ_NO_MOZALLOC)
+#  include <new>              // to give mozalloc std::bad_alloc
+#  include <stdlib.h>         // to give mozalloc malloc/free decls
+#  include <string.h>
+#  include "mozilla/mozalloc.h"
+#else
+#  error "STL code can only be used with infallible ::operator new()"
+#endif
+
+#ifdef DEBUG
+// From
+//   http://msdn.microsoft.com/en-us/library/aa985982%28VS.80%29.aspx
+// and
+//   http://msdn.microsoft.com/en-us/library/aa985965%28VS.80%29.aspx
+// there appear to be two types of STL container checking.  The
+// former is enabled by -D_DEBUG (which is implied by -DDEBUG), and
+// looks to be full generation/mutation checked iterators as done by
+// _GLIBCXX_DEBUG.  The latter appears to just be bounds checking, and
+// is enabled by the following macros.  It appears that the _DEBUG
+// iterators subsume _SECURE_SCL, and the following settings are
+// default anyway, so we'll just leave this commented out.
+//#  define _SECURE_SCL 1
+//#  define _SECURE_SCL_THROWS 0
+#else
+// Note: _SECURE_SCL iterators are on by default in opt builds.  We
+// could leave them on, but since gcc doesn't, we might as well
+// preserve that behavior for perf reasons.  nsTArray is in the same
+// camp as gcc.  Can revisit later.
+//
+// FIXME/bug 551254: because we're not wrapping all the STL headers we
+// use, undefining this here can cause some headers to be built with
+// iterator checking and others not.  Turning this off until we have a
+// better plan.
+//#  undef _SECURE_SCL
+#endif
+
+// We know that code won't be able to catch exceptions, but that's OK
+// because we're not throwing them.
+#pragma warning( push )
+#pragma warning( disable : 4530 )
+
+#include <${HEADER_PATH}>
+
+#pragma warning( pop )
+
+#endif  // if mozilla_${HEADER}_h
new file mode 100644
--- /dev/null
+++ b/config/stl-headers
@@ -0,0 +1,19 @@
+#
+# This file contains a list the of STL headers that have been reviewed
+# for exception safety and approved. See
+#
+#   https://bugzilla.mozilla.org/show_bug.cgi?id=551254
+#
+# At build time, each header listed here is converted into a "wrapper
+# header" that is installed into dist/stl_includes.
+#
+# If you would like to request a new STL header <foo> be added, please
+# file a Core:XPCOM bug with a title like "STL: Review exception
+# safety of <foo> for gcc and MSVC".
+#
+
+# FIXME: these headers haven't been reviewed yet, but we use them
+# unsafely in modules/libpr0n, so we might as well prevent it from
+# throwing exceptions
+algorithm
+vector
--- a/configure.in
+++ b/configure.in
@@ -754,16 +754,19 @@ EOF
         AC_MSG_ERROR([You are targeting Windows version 0x$MOZ_WINSDK_TARGETVER, but your SDK only supports up to version $MOZ_WINSDK_MAXVER. Install and use an updated SDK, or target a lower version using --with-windows-version. See https://developer.mozilla.org/En/Windows_SDK_versions for more details on fixing this.])
     fi
 
     AC_DEFINE_UNQUOTED(MOZ_WINSDK_TARGETVER,0x$MOZ_WINSDK_TARGETVER)
     # Definitions matching sdkddkver.h
     AC_DEFINE_UNQUOTED(MOZ_NTDDI_WS03, 0x05020000)
     AC_DEFINE_UNQUOTED(MOZ_NTDDI_LONGHORN, 0x06000000)
     AC_DEFINE_UNQUOTED(MOZ_NTDDI_WIN7, 0x06010000)
+
+    STL_FLAGS='-D_HAS_EXCEPTIONS=0 -I$(DIST)/stl_wrappers'
+    WRAP_STL_INCLUDES=1
     ;;
 esac
 
 dnl Test breaks icc on OS/2 && MSVC
 if test "$CC" != "icc" -a -z "$_WIN32_MSVC"; then
     AC_PROG_CC_C_O
     if grep "NO_MINUS_C_MINUS_O 1" ./confdefs.h >/dev/null; then
         USING_HCC=1
@@ -802,16 +805,19 @@ AC_SUBST(_MSC_VER)
 
 AC_SUBST(GNU_AS)
 AC_SUBST(GNU_LD)
 AC_SUBST(GNU_CC)
 AC_SUBST(GNU_CXX)
 AC_SUBST(INTEL_CC)
 AC_SUBST(INTEL_CXX)
 
+AC_SUBST(STL_FLAGS)
+AC_SUBST(WRAP_STL_INCLUDES)
+
 dnl ========================================================
 dnl Checks for programs.
 dnl ========================================================
 AC_PROG_INSTALL
 AC_PROG_LN_S
 
 if test -z "$TINDERBOX_SKIP_PERL_VERSION_CHECK"; then
 AC_MSG_CHECKING([for minimum required perl version >= $PERL_VERSION])
@@ -3121,16 +3127,18 @@ EOF
                          fi
                        fi
                        rm -f conftest.{c,S}
                        ])
         if test "$ac_cv_have_visibility_builtin_bug" = "no" -a \
                 "$ac_cv_have_visibility_class_bug" = "no"; then
           VISIBILITY_FLAGS='-I$(DIST)/system_wrappers -include $(topsrcdir)/config/gcc_hidden.h'
           WRAP_SYSTEM_INCLUDES=1
+          STL_FLAGS='-I$(DIST)/stl_wrappers'
+          WRAP_STL_INCLUDES=1
         else
           VISIBILITY_FLAGS='-fvisibility=hidden'
         fi # have visibility pragma bug
       fi   # have visibility pragma
     fi     # have visibility(default) attribute
   fi       # have visibility(hidden) attribute
 fi         # GNU_CC
 
@@ -4971,16 +4979,18 @@ cairo-gtk2-dfb)
         no_x=yes
     fi
     ;;
 
 cairo-qt)
     MOZ_WIDGET_TOOLKIT=qt
     MOZ_ENABLE_QT=1
     MOZ_ENABLE_XREMOTE=1
+    MOZ_WEBGL=1
+    MOZ_WEBGL_GLX=1
     USE_ELF_DYNSTR_GC=
     NS_PRINTING=
 
     AC_DEFINE(MOZ_X11)
     MOZ_X11=1
     USE_FC_FREETYPE=1
 
     TK_CFLAGS='$(MOZ_QT_CFLAGS)'
@@ -5079,20 +5089,20 @@ dnl = QT support
 dnl ========================================================
 if test "$MOZ_ENABLE_QT"
 then
     MOZ_ARG_WITH_STRING(qtdir,
     [  --with-qtdir=\$dir       Specify Qt directory ],
     [ QTDIR=$withval])
 
     if test -z "$QTDIR"; then
-        PKG_CHECK_MODULES(MOZ_QT, QtGui QtNetwork QtCore)
+        PKG_CHECK_MODULES(MOZ_QT, QtGui QtNetwork QtCore QtOpenGL)
         AC_CHECK_PROGS(HOST_MOC, moc, "")
     else
-        MOZ_QT_LIBS="-L$QTDIR/lib/ -lQtGui -lQtNetwork -lQtCore -lQtDBus -lQtXml"
+        MOZ_QT_LIBS="-L$QTDIR/lib/ -lQtGui -lQtNetwork -lQtCore -lQtDBus -lQtXml -lQtOpenGL"
 
         MOZ_QT_CFLAGS="-DQT_SHARED"
         MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include"
         MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/Qt"
         MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtGui"
         MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtCore"
         MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtNetwork"
         MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtDBus"
@@ -5470,19 +5480,16 @@ MOZ_ARG_DISABLE_BOOL(jsd,
 
 dnl ========================================================
 dnl = Disable IPC support for tabs and plugins
 dnl ========================================================
 case "${target}" in
 powerpc-apple-darwin*)
     MOZ_IPC=
     ;;
-i386-apple-darwin*)
-    MOZ_IPC=
-    ;;
 *-wince*)
     MOZ_IPC=
     ;;
 esac
 
 MOZ_ARG_DISABLE_BOOL(ipc,
 [  --disable-ipc           Disable IPC supports for tabs and plugins],
     MOZ_IPC=,
--- a/content/base/public/nsContentUtils.h
+++ b/content/base/public/nsContentUtils.h
@@ -1490,20 +1490,22 @@ public:
   
 
   /**
    * Get the Origin of the passed in nsIPrincipal or nsIURI. If the passed in
    * nsIURI or the URI of the passed in nsIPrincipal does not have a host, the
    * origin is set to 'null'.
    *
    * The ASCII versions return a ASCII strings that are puny-code encoded,
-   * suitable for for example header values. The UTF versions return strings
+   * suitable for, for example, header values. The UTF versions return strings
    * containing international characters.
    *
-   * aPrincipal/aOrigin must not be null.
+   * @pre aPrincipal/aOrigin must not be null.
+   *
+   * @note this should be used for HTML5 origin determination.
    */
   static nsresult GetASCIIOrigin(nsIPrincipal* aPrincipal,
                                  nsCString& aOrigin);
   static nsresult GetASCIIOrigin(nsIURI* aURI, nsCString& aOrigin);
   static nsresult GetUTFOrigin(nsIPrincipal* aPrincipal,
                                nsString& aOrigin);
   static nsresult GetUTFOrigin(nsIURI* aURI, nsString& aOrigin);
 
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -110,18 +110,18 @@ class Loader;
 } // namespace css
 
 namespace dom {
 class Link;
 } // namespace dom
 } // namespace mozilla
 
 #define NS_IDOCUMENT_IID      \
-{ 0x94fb5716, 0xff00, 0x4b97, \
- { 0x90, 0x01, 0x91, 0x65, 0x1a, 0x5f, 0xbe, 0x64 } }
+{ 0x5a428059, 0x4f29, 0x4d7c, \
+ { 0x93, 0xae, 0x7c, 0x68, 0xd6, 0x5a, 0x86, 0x45 } }
 
 // Flag for AddStyleSheet().
 #define NS_STYLESHEET_FROM_CATALOG                (1 << 0)
 
 // Document states
 
 // RTL locale: specific to the XUL localedir attribute
 #define NS_DOCUMENT_STATE_RTL_LOCALE              (1 << 0)
@@ -980,17 +980,17 @@ public:
                                      nsIDOMNodeList** aResult) = 0;
 
   /**
    * Helper for nsIDOMNSDocument::elementFromPoint implementation that allows
    * ignoring the scroll frame and/or avoiding layout flushes.
    *
    * @see nsIDOMWindowUtils::elementFromPoint
    */
-  virtual nsresult ElementFromPointHelper(PRInt32 aX, PRInt32 aY,
+  virtual nsresult ElementFromPointHelper(float aX, float aY,
                                           PRBool aIgnoreRootScrollFrame,
                                           PRBool aFlushLayout,
                                           nsIDOMElement** aReturn) = 0;
 
   /**
    * See FlushSkinBindings on nsBindingManager
    */
   virtual void FlushSkinBindings() = 0;
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -2617,23 +2617,23 @@ nsDocument::GetActiveElement(nsIDOMEleme
     return NS_OK;
   }
 
   // If we couldn't get a BODY, return the root element.
   return GetDocumentElement(aElement);
 }
 
 NS_IMETHODIMP
-nsDocument::ElementFromPoint(PRInt32 aX, PRInt32 aY, nsIDOMElement** aReturn)
+nsDocument::ElementFromPoint(float aX, float aY, nsIDOMElement** aReturn)
 {
   return ElementFromPointHelper(aX, aY, PR_FALSE, PR_TRUE, aReturn);
 }
 
 nsresult
-nsDocument::ElementFromPointHelper(PRInt32 aX, PRInt32 aY,
+nsDocument::ElementFromPointHelper(float aX, float aY,
                                    PRBool aIgnoreRootScrollFrame,
                                    PRBool aFlushLayout,
                                    nsIDOMElement** aReturn)
 {
   NS_ENSURE_ARG_POINTER(aReturn);
   *aReturn = nsnull;
   // As per the the spec, we return null if either coord is negative
   if (!aIgnoreRootScrollFrame && (aX < 0 || aY < 0))
--- a/content/base/src/nsDocument.h
+++ b/content/base/src/nsDocument.h
@@ -868,17 +868,17 @@ public:
   NS_HIDDEN_(void) ClearBoxObjectFor(nsIContent* aContent);
   NS_IMETHOD GetBoxObjectFor(nsIDOMElement* aElement, nsIBoxObject** aResult);
 
   virtual NS_HIDDEN_(nsresult) GetXBLChildNodesFor(nsIContent* aContent,
                                                    nsIDOMNodeList** aResult);
   virtual NS_HIDDEN_(nsresult) GetContentListFor(nsIContent* aContent,
                                                  nsIDOMNodeList** aResult);
 
-  virtual NS_HIDDEN_(nsresult) ElementFromPointHelper(PRInt32 aX, PRInt32 aY,
+  virtual NS_HIDDEN_(nsresult) ElementFromPointHelper(float aX, float aY,
                                                       PRBool aIgnoreRootScrollFrame,
                                                       PRBool aFlushLayout,
                                                       nsIDOMElement** aReturn);
 
   virtual NS_HIDDEN_(void) FlushSkinBindings();
 
   virtual NS_HIDDEN_(nsresult) InitializeFrameLoader(nsFrameLoader* aLoader);
   virtual NS_HIDDEN_(nsresult) FinalizeFrameLoader(nsFrameLoader* aLoader);
--- a/content/base/src/nsXHTMLContentSerializer.cpp
+++ b/content/base/src/nsXHTMLContentSerializer.cpp
@@ -99,23 +99,20 @@ nsXHTMLContentSerializer::~nsXHTMLConten
 NS_IMETHODIMP
 nsXHTMLContentSerializer::Init(PRUint32 aFlags, PRUint32 aWrapColumn,
                               const char* aCharSet, PRBool aIsCopying,
                               PRBool aRewriteEncodingDeclaration)
 {
   // The previous version of the HTML serializer did implicit wrapping
   // when there is no flags, so we keep wrapping in order to keep
   // compatibility with the existing calling code
-  // XXXLJ perhaps we should remove these two default settings later ?
+  // XXXLJ perhaps should we remove this default settings later ?
   if (aFlags & nsIDocumentEncoder::OutputFormatted ) {
       aFlags = aFlags | nsIDocumentEncoder::OutputWrap;
   }
-  else if (!(aFlags & nsIDocumentEncoder::OutputRaw)) {
-      aFlags = aFlags | nsIDocumentEncoder::OutputWrap;
-  }
 
   nsresult rv;
   rv = nsXMLContentSerializer::Init(aFlags, aWrapColumn, aCharSet, aIsCopying, aRewriteEncodingDeclaration);
   NS_ENSURE_SUCCESS(rv, rv);
 
   mRewriteEncodingDeclaration = aRewriteEncodingDeclaration;
   mIsCopying = aIsCopying;
   mIsFirstChildOfOL = PR_FALSE;
@@ -180,17 +177,19 @@ nsXHTMLContentSerializer::AppendText(nsI
   }
   else if (mDoWrap) {
     AppendToStringWrapped(data, aStr);
   }
   else {
     PRInt32 lastNewlineOffset = kNotFound;
     if (HasLongLines(data, lastNewlineOffset)) {
       // We have long lines, rewrap
+      mDoWrap = PR_TRUE;
       AppendToStringWrapped(data, aStr);
+      mDoWrap = PR_FALSE;
     }
     else {
       AppendToStringConvertLF(data, aStr);
     }
   }
 
   return NS_OK;
 }
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -179,16 +179,17 @@ include $(topsrcdir)/config/rules.mk
 		file_htmlserializer_1_links.html \
 		file_htmlserializer_1_noflag.html \
 		file_htmlserializer_1_noformatpre.html \
 		file_htmlserializer_1_raw.html \
 		file_htmlserializer_1_nested_body.html \
 		file_htmlserializer_1_sibling_body.html \
 		file_htmlserializer_1_sibling_body_only_body.html \
 		file_htmlserializer_1_no_body.html \
+		file_htmlserializer_1_wrap.html \
 		test_bug424359-2.html \
 		file_htmlserializer_2.html \
 		test_bug431082.html \
 		file_htmlserializer_2_basic.html \
 		file_htmlserializer_2_enthtml.html \
 		file_htmlserializer_2_entw3c.html \
 		file_htmlserializer_2_latin1.html \
 		test_bug424212.html \
@@ -278,16 +279,17 @@ include $(topsrcdir)/config/rules.mk
 		file_xhtmlserializer_1_links.xhtml \
 		file_xhtmlserializer_1_noflag.xhtml \
 		file_xhtmlserializer_1_noformatpre.xhtml \
 		file_xhtmlserializer_1_raw.xhtml \
 		file_xhtmlserializer_1_nested_body.xhtml \
 		file_xhtmlserializer_1_sibling_body.xhtml \
 		file_xhtmlserializer_1_sibling_body_only_body.xhtml \
 		file_xhtmlserializer_1_no_body.xhtml \
+		file_xhtmlserializer_1_wrap.xhtml \
 		test_bug422403-2.xhtml \
 		file_xhtmlserializer_2.xhtml \
 		file_xhtmlserializer_2_basic.xhtml \
 		file_xhtmlserializer_2_enthtml.xhtml \
 		file_xhtmlserializer_2_entw3c.xhtml \
 		file_xhtmlserializer_2_latin1.xhtml \
 		test_bug500937.html \
 		test_htmlcopyencoder.html \
--- a/content/base/test/file_htmlserializer_1_bodyonly.html
+++ b/content/base/test/file_htmlserializer_1_bodyonly.html
@@ -1,17 +1,15 @@
 <body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script type="text/javascript">
@@ -23,25 +21,23 @@ function nothing() {
 }
 
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.<br>
  Cras quis<br>
  nisi at odio<br>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br>
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros leo ut libero
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc & non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body>
\ No newline at end of file
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body>
\ No newline at end of file
--- a/content/base/test/file_htmlserializer_1_linebreak.html
+++ b/content/base/test/file_htmlserializer_1_linebreak.html
@@ -1,22 +1,19 @@
 <!DOCTYPE html>
-<html><head><meta http-equiv="content-type" content="text/html; 
-charset=UTF-8">
+<html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8">
   <title>Test for html serializer</title>
 
 </head><body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script type="text/javascript">
@@ -28,25 +25,23 @@ function nothing() {
 }
 
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.<br>
  Cras quis<br>
  nisi at odio<br>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br>
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros leo ut libero
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc & non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body></html>
\ No newline at end of file
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body></html>
\ No newline at end of file
--- a/content/base/test/file_htmlserializer_1_links.html
+++ b/content/base/test/file_htmlserializer_1_links.html
@@ -1,23 +1,19 @@
 <!DOCTYPE html>
-<html><head><meta http-equiv="content-type" content="text/html; 
-charset=UTF-8">
+<html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8">
   <title>Test for html serializer</title>
 
 </head><body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a 
-href="http://mochi.test:8888/tests/content/base/test/file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="http://mochi.test:8888/tests/content/base/test/file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script type="text/javascript">
@@ -29,25 +25,23 @@ function nothing() {
 }
 
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.<br>
  Cras quis<br>
  nisi at odio<br>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br>
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros leo ut libero
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc & non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body></html>
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body></html>
--- a/content/base/test/file_htmlserializer_1_nested_body.html
+++ b/content/base/test/file_htmlserializer_1_nested_body.html
@@ -1,22 +1,19 @@
 <!DOCTYPE html>
-<html><head><meta http-equiv="content-type" content="text/html; 
-charset=UTF-8">
+<html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8">
   <title>Test for html serializer</title>
 
 </head><body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script type="text/javascript">
@@ -28,26 +25,23 @@ function nothing() {
 }
 
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.<br>
  Cras quis<br>
  nisi at odio<br>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br>
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros leo ut libero
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc & non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p><body><p>this is
- an other body element</p></body></body></html>
\ No newline at end of file
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p><body><p>this is an other body element</p></body></body></html>
\ No newline at end of file
--- a/content/base/test/file_htmlserializer_1_no_body.html
+++ b/content/base/test/file_htmlserializer_1_no_body.html
@@ -1,6 +1,5 @@
 <!DOCTYPE html>
-<html><head><meta http-equiv="content-type" content="text/html; 
-charset=UTF-8">
+<html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8">
   <title>Test for html serializer</title>
 
 </head></html>
\ No newline at end of file
--- a/content/base/test/file_htmlserializer_1_noflag.html
+++ b/content/base/test/file_htmlserializer_1_noflag.html
@@ -1,22 +1,19 @@
 <!DOCTYPE html>
-<html><head><meta http-equiv="content-type" content="text/html; 
-charset=UTF-8">
+<html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8">
   <title>Test for html serializer</title>
 
 </head><body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script type="text/javascript">
@@ -28,25 +25,23 @@ function nothing() {
 }
 
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.<br>
  Cras quis<br>
  nisi at odio<br>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br>
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros leo ut libero
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc & non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body></html>
\ No newline at end of file
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body></html>
\ No newline at end of file
--- a/content/base/test/file_htmlserializer_1_noformatpre.html
+++ b/content/base/test/file_htmlserializer_1_noformatpre.html
@@ -1,22 +1,19 @@
 <!DOCTYPE html>
-<html><head><meta http-equiv="content-type" content="text/html; 
-charset=UTF-8">
+<html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8">
   <title>Test for html serializer</title>
 
 </head><body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script type="text/javascript">
@@ -28,18 +25,17 @@ function nothing() {
 }
 
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.
 
  Cras quis
 
  nisi at odio
@@ -47,10 +43,9 @@ comments -->
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, 
 
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros leo ut libero
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc & non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body></html>
\ No newline at end of file
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body></html>
\ No newline at end of file
--- a/content/base/test/file_htmlserializer_1_sibling_body.html
+++ b/content/base/test/file_htmlserializer_1_sibling_body.html
@@ -1,22 +1,19 @@
 <!DOCTYPE html>
-<html><head><meta http-equiv="content-type" content="text/html; 
-charset=UTF-8">
+<html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8">
   <title>Test for html serializer</title>
 
 </head><body><p>this is an other body element</p></body><body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script type="text/javascript">
@@ -28,25 +25,23 @@ function nothing() {
 }
 
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.<br>
  Cras quis<br>
  nisi at odio<br>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br>
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros leo ut libero
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc & non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body></html>
\ No newline at end of file
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body></html>
\ No newline at end of file
--- a/content/base/test/file_htmlserializer_1_sibling_body_only_body.html
+++ b/content/base/test/file_htmlserializer_1_sibling_body_only_body.html
@@ -1,17 +1,15 @@
 <body><p>this is an other body element</p></body><body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script type="text/javascript">
@@ -23,25 +21,23 @@ function nothing() {
 }
 
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.<br>
  Cras quis<br>
  nisi at odio<br>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br>
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros leo ut libero
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc & non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body>
\ No newline at end of file
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body>
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/content/base/test/file_htmlserializer_1_wrap.html
@@ -0,0 +1,52 @@
+<!DOCTYPE html>
+<html><head><meta http-equiv="content-type" content="text/html; 
+charset=UTF-8">
+  <title>Test for html serializer</title>
+
+</head><body>
+<p>Hello world</p> <p>
+
+       Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
+adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
+ ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
+ conubia</a> 
+nostra, per inceptos hymenaeos. </p>
+
+
+<ul><li>Nam tellus massa,éàèçù</li><li>
+ fringilla 
+aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
+<div> Duis tristique egestas ligula. Mauris quis felis. </div>
+<script type="text/javascript">
+// a script which does nothing
+
+function nothing() {
+  var hey="hello";
+  var aLongLine="consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere";
+}
+
+var a=3, b=4, c=7;
+// here we test the non-serialization of xml character into javascript content
+var d = a < b && a > c;
+</script>
+
+<ol><li>Fusce
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
+posuere nulla</li><li> Donec tempor.</li></ol>
+Donec sollicitudin tortor 
+<!-- test on 
+comments -->
+<pre>lacinia <em>libero</em> ullamcorper laoreet.<br>
+ Cras quis<br>
+ nisi at odio<br>
+ consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br>
+lacus risus pulvinar ante.
+</pre>
+ut gravida eros leo ut libero
+<p></p>
+<noscript>
+<p>Curabitur consectetuer urna a sem. Nunc & non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
+aliquet lectus. Nunc vitae eros. Class aptent taciti</p></body></html>
\ No newline at end of file
--- a/content/base/test/file_htmlserializer_2_basic.html
+++ b/content/base/test/file_htmlserializer_2_basic.html
@@ -1,16 +1,14 @@
 <!DOCTYPE html>
 <html><head>
-<meta http-equiv="content-type" content="text/html; charset="><title>Test
- for html serializer with entities</title>
+<meta http-equiv="content-type" content="text/html; charset="><title>Test for html serializer with entities</title>
 </head><body>
 
-<p>The basic set is just &nbsp; &amp; &lt; &gt; " for interoperability 
-with older products that don't support α and friends.</p>
+<p>The basic set is just &nbsp; &amp; &lt; &gt; " for interoperability with older products that don't support α and friends.</p>
 
 <p>latin1 ¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ­ ® ¯ ° ± ² ³ ´ 
 µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ
 Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø
 Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê 
 ë ì í î ï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý 
 þ ÿ </p>
 <p>symbols, math.. ƒ Α Β Γ Δ Ε Ζ Η Θ Ι Κ Λ Μ Ν Ξ Ο Π Ρ Σ Τ Υ
--- a/content/base/test/file_htmlserializer_2_enthtml.html
+++ b/content/base/test/file_htmlserializer_2_enthtml.html
@@ -1,16 +1,14 @@
 <!DOCTYPE html>
 <html><head>
-<meta http-equiv="content-type" content="text/html; charset="><title>Test
- for html serializer with entities</title>
+<meta http-equiv="content-type" content="text/html; charset="><title>Test for html serializer with entities</title>
 </head><body>
 
-<p>The basic set is just &nbsp; &amp; &lt; &gt; " for interoperability 
-with older products that don't support &alpha; and friends.</p>
+<p>The basic set is just &nbsp; &amp; &lt; &gt; " for interoperability with older products that don't support &alpha; and friends.</p>
 
 <p>latin1 &iexcl; &cent; &pound; &curren; &yen; &brvbar; &sect; &uml; 
 &copy; &ordf; &laquo; &not; &shy; &reg; &macr; &deg; &plusmn; &sup2; 
 &sup3; &acute; 
 &micro; &para; &middot; &cedil; &sup1; &ordm; &raquo; &frac14; &frac12; 
 &frac34; &iquest; &Agrave; &Aacute; &Acirc; &Atilde; &Auml; &Aring; 
 &AElig;
 &Ccedil; &Egrave; &Eacute; &Ecirc; &Euml; &Igrave; &Iacute; &Icirc; 
--- a/content/base/test/file_htmlserializer_2_entw3c.html
+++ b/content/base/test/file_htmlserializer_2_entw3c.html
@@ -1,16 +1,14 @@
 <!DOCTYPE html>
 <html><head>
-<meta http-equiv="content-type" content="text/html; charset="><title>Test
- for html serializer with entities</title>
+<meta http-equiv="content-type" content="text/html; charset="><title>Test for html serializer with entities</title>
 </head><body>
 
-<p>The basic set is just &nbsp; &amp; &lt; &gt; " for interoperability 
-with older products that don't support &alpha; and friends.</p>
+<p>The basic set is just &nbsp; &amp; &lt; &gt; " for interoperability with older products that don't support &alpha; and friends.</p>
 
 <p>latin1 &iexcl; &cent; &pound; &curren; &yen; &brvbar; &sect; &uml; 
 &copy; &ordf; &laquo; &not; &shy; &reg; &macr; &deg; &plusmn; &sup2; 
 &sup3; &acute; 
 &micro; &para; &middot; &cedil; &sup1; &ordm; &raquo; &frac14; &frac12; 
 &frac34; &iquest; &Agrave; &Aacute; &Acirc; &Atilde; &Auml; &Aring; 
 &AElig;
 &Ccedil; &Egrave; &Eacute; &Ecirc; &Euml; &Igrave; &Iacute; &Icirc; 
--- a/content/base/test/file_htmlserializer_2_latin1.html
+++ b/content/base/test/file_htmlserializer_2_latin1.html
@@ -1,16 +1,14 @@
 <!DOCTYPE html>
 <html><head>
-<meta http-equiv="content-type" content="text/html; charset="><title>Test
- for html serializer with entities</title>
+<meta http-equiv="content-type" content="text/html; charset="><title>Test for html serializer with entities</title>
 </head><body>
 
-<p>The basic set is just &nbsp; &amp; &lt; &gt; " for interoperability 
-with older products that don't support α and friends.</p>
+<p>The basic set is just &nbsp; &amp; &lt; &gt; " for interoperability with older products that don't support α and friends.</p>
 
 <p>latin1 &iexcl; &cent; &pound; &curren; &yen; &brvbar; &sect; &uml; 
 &copy; &ordf; &laquo; &not; &shy; &reg; &macr; &deg; &plusmn; &sup2; 
 &sup3; &acute; 
 &micro; &para; &middot; &cedil; &sup1; &ordm; &raquo; &frac14; &frac12; 
 &frac34; &iquest; &Agrave; &Aacute; &Acirc; &Atilde; &Auml; &Aring; 
 &AElig;
 &Ccedil; &Egrave; &Eacute; &Ecirc; &Euml; &Igrave; &Iacute; &Icirc; 
--- a/content/base/test/file_htmlserializer_ipv6_out.html
+++ b/content/base/test/file_htmlserializer_ipv6_out.html
@@ -1,7 +1,6 @@
 <!DOCTYPE html>
-<html><head><meta http-equiv="Content-Type" content="text/html; 
-charset=UTF-8">
+<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title>Testcase for IPv6 addresses</title>
   </head><body>
     <a href="http://[2001:4860:a003::68]/">Test</a>
   </body></html>
\ No newline at end of file
--- a/content/base/test/file_xhtmlserializer_1_bodyonly.xhtml
+++ b/content/base/test/file_xhtmlserializer_1_bodyonly.xhtml
@@ -1,17 +1,15 @@
 <body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script id="script" type="text/javascript"></script>
@@ -25,36 +23,33 @@ function nothing() {
 }
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 //]]>
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.<br />
  Cras quis<br />
  nisi at odio<br />
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br />
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros <br />leo ut libero
 <!-- empty element: end tag should be generated for backward compatibility with HTML -->
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
-<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> 
-ullamcorper laoreet.<br/>
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
+<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> ullamcorper laoreet.<br/>
  Cras quis<br/>
  nisi at odio<br/>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non 
 urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci 
 luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at 
 pharetra rutrum, <br/>
 lacus risus pulvinar ante.
 </pre>
--- a/content/base/test/file_xhtmlserializer_1_linebreak.xhtml
+++ b/content/base/test/file_xhtmlserializer_1_linebreak.xhtml
@@ -6,20 +6,18 @@
   <title>Test for html serializer</title>
 
 </head>
 <body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script id="script" type="text/javascript"></script>
@@ -33,36 +31,33 @@ function nothing() {
 }
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 //]]>
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.<br />
  Cras quis<br />
  nisi at odio<br />
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br />
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros <br />leo ut libero
 <!-- empty element: end tag should be generated for backward compatibility with HTML -->
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
-<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> 
-ullamcorper laoreet.<br/>
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
+<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> ullamcorper laoreet.<br/>
  Cras quis<br/>
  nisi at odio<br/>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non 
 urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci 
 luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at 
 pharetra rutrum, <br/>
 lacus risus pulvinar ante.
 </pre>
--- a/content/base/test/file_xhtmlserializer_1_links.xhtml
+++ b/content/base/test/file_xhtmlserializer_1_links.xhtml
@@ -6,21 +6,18 @@
   <title>Test for html serializer</title>
 
 </head>
 <body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a 
-href="http://mochi.test:8888/tests/content/base/test/file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="http://mochi.test:8888/tests/content/base/test/file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script id="script" type="text/javascript"></script>
@@ -34,36 +31,33 @@ function nothing() {
 }
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 //]]>
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.<br />
  Cras quis<br />
  nisi at odio<br />
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br />
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros <br />leo ut libero
 <!-- empty element: end tag should be generated for backward compatibility with HTML -->
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
-<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> 
-ullamcorper laoreet.<br/>
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
+<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> ullamcorper laoreet.<br/>
  Cras quis<br/>
  nisi at odio<br/>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non 
 urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci 
 luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at 
 pharetra rutrum, <br/>
 lacus risus pulvinar ante.
 </pre>
--- a/content/base/test/file_xhtmlserializer_1_nested_body.xhtml
+++ b/content/base/test/file_xhtmlserializer_1_nested_body.xhtml
@@ -6,20 +6,18 @@
   <title>Test for html serializer</title>
 
 </head>
 <body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script id="script" type="text/javascript"></script>
@@ -33,36 +31,33 @@ function nothing() {
 }
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 //]]>
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.<br />
  Cras quis<br />
  nisi at odio<br />
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br />
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros <br />leo ut libero
 <!-- empty element: end tag should be generated for backward compatibility with HTML -->
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
-<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> 
-ullamcorper laoreet.<br/>
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
+<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> ullamcorper laoreet.<br/>
  Cras quis<br/>
  nisi at odio<br/>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non 
 urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci 
 luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at 
 pharetra rutrum, <br/>
 lacus risus pulvinar ante.
 </pre>
--- a/content/base/test/file_xhtmlserializer_1_noflag.xhtml
+++ b/content/base/test/file_xhtmlserializer_1_noflag.xhtml
@@ -6,20 +6,18 @@
   <title>Test for html serializer</title>
 
 </head>
 <body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script id="script" type="text/javascript"></script>
@@ -33,36 +31,33 @@ function nothing() {
 }
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 //]]>
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.<br />
  Cras quis<br />
  nisi at odio<br />
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br />
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros <br />leo ut libero
 <!-- empty element: end tag should be generated for backward compatibility with HTML -->
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
-<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> 
-ullamcorper laoreet.<br/>
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
+<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> ullamcorper laoreet.<br/>
  Cras quis<br/>
  nisi at odio<br/>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non 
 urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci 
 luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at 
 pharetra rutrum, <br/>
 lacus risus pulvinar ante.
 </pre>
--- a/content/base/test/file_xhtmlserializer_1_noformatpre.xhtml
+++ b/content/base/test/file_xhtmlserializer_1_noformatpre.xhtml
@@ -6,20 +6,18 @@
   <title>Test for html serializer</title>
 
 </head>
 <body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script id="script" type="text/javascript"></script>
@@ -33,18 +31,17 @@ function nothing() {
 }
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 //]]>
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.
 
  Cras quis
 
  nisi at odio
@@ -53,20 +50,18 @@ comments -->
 
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros <br />leo ut libero
 <!-- empty element: end tag should be generated for backward compatibility with HTML -->
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
-<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> 
-ullamcorper laoreet.<br/>
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
+<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> ullamcorper laoreet.<br/>
  Cras quis<br/>
  nisi at odio<br/>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non 
 urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci 
 luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at 
 pharetra rutrum, <br/>
 lacus risus pulvinar ante.
 </pre>
--- a/content/base/test/file_xhtmlserializer_1_sibling_body.xhtml
+++ b/content/base/test/file_xhtmlserializer_1_sibling_body.xhtml
@@ -6,20 +6,18 @@
   <title>Test for html serializer</title>
 
 </head>
 <body><p>this is an other body element</p></body><body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script id="script" type="text/javascript"></script>
@@ -33,36 +31,33 @@ function nothing() {
 }
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 //]]>
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.<br />
  Cras quis<br />
  nisi at odio<br />
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br />
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros <br />leo ut libero
 <!-- empty element: end tag should be generated for backward compatibility with HTML -->
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
-<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> 
-ullamcorper laoreet.<br/>
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
+<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> ullamcorper laoreet.<br/>
  Cras quis<br/>
  nisi at odio<br/>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non 
 urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci 
 luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at 
 pharetra rutrum, <br/>
 lacus risus pulvinar ante.
 </pre>
--- a/content/base/test/file_xhtmlserializer_1_sibling_body_only_body.xhtml
+++ b/content/base/test/file_xhtmlserializer_1_sibling_body_only_body.xhtml
@@ -1,17 +1,15 @@
 <body><p>this is an other body element</p></body><body>
 <p>Hello world</p> <p>
 
        Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
 adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
-Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
- ad 
-     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
- conubia</a> 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per conubia</a> 
 nostra, per inceptos hymenaeos. </p>
 
 
 <ul><li>Nam tellus massa,éàèçù</li><li>
  fringilla 
 aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
 <div> Duis tristique egestas ligula. Mauris quis felis. </div>
 <script id="script" type="text/javascript"></script>
@@ -25,36 +23,33 @@ function nothing() {
 }
 var a=3, b=4, c=7;
 // here we test the non-serialization of xml character into javascript content
 var d = a < b && a > c;
 //]]>
 </script>
 
 <ol><li>Fusce
- a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
-posuere nulla</li><li> Donec tempor.</li></ol>
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum posuere nulla</li><li> Donec tempor.</li></ol>
 Donec sollicitudin tortor 
 <!-- test on 
 comments -->
 <pre>lacinia <em>libero</em> ullamcorper laoreet.<br />
  Cras quis<br />
  nisi at odio<br />
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br />
 lacus risus pulvinar ante.
 </pre>
 ut gravida eros <br />leo ut libero
 <!-- empty element: end tag should be generated for backward compatibility with HTML -->
 <p></p>
 <noscript>
 <p>Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
-<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
-aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
-<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> 
-ullamcorper laoreet.<br/>
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
+<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> ullamcorper laoreet.<br/>
  Cras quis<br/>
  nisi at odio<br/>
  consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non 
 urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci 
 luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at 
 pharetra rutrum, <br/>
 lacus risus pulvinar ante.
 </pre>
new file mode 100644
--- /dev/null
+++ b/content/base/test/file_xhtmlserializer_1_wrap.xhtml
@@ -0,0 +1,70 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+   <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
+  <title>Test for html serializer</title>
+
+</head>
+<body>
+<p>Hello world</p> <p>
+
+       Lorem ipsum dolor sit amet, <strong>consectetuer</strong> 
+adipiscing elit. Nam eu sapien. Sed viverra lacus. Donec quis ipsum. 
+Nunc cursus aliquet lectus. Nunc vitae eros. Class aptent taciti <span>sociosqu
+ ad 
+     litora</span> torquent <a href="file_htmlserializer_1_result1.html">per
+ conubia</a> 
+nostra, per inceptos hymenaeos. </p>
+
+
+<ul><li>Nam tellus massa,éàèçù</li><li>
+ fringilla 
+aliquam,</li><li> fermentum sit amet,</li><li>posuere ac,</li><li> est.</li></ul>
+<div> Duis tristique egestas ligula. Mauris quis felis. </div>
+<script id="script" type="text/javascript"></script>
+<script type="text/javascript">
+//<![CDATA[
+// a script which does nothing
+
+function nothing() {
+  var hey="hello";
+  var aLongLine="consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere";
+}
+var a=3, b=4, c=7;
+// here we test the non-serialization of xml character into javascript content
+var d = a < b && a > c;
+//]]>
+</script>
+
+<ol><li>Fusce
+ a ipsum</li><li> non lacus posuere aliquet.</li><li> Sed fermentum 
+posuere nulla</li><li> Donec tempor.</li></ol>
+Donec sollicitudin tortor 
+<!-- test on 
+comments -->
+<pre>lacinia <em>libero</em> ullamcorper laoreet.<br />
+ Cras quis<br />
+ nisi at odio<br />
+ consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at pharetra rutrum, <br />
+lacus risus pulvinar ante.
+</pre>
+ut gravida eros <br />leo ut libero
+<!-- empty element: end tag should be generated for backward compatibility with HTML -->
+<p></p>
+<noscript>
+<p>Curabitur consectetuer urna a sem. Nunc non urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci luctus</p></noscript>
+<p>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus 
+aliquet lectus. Nunc vitae eros. Class aptent taciti</p>
+<pre xmlns="http://mozilla.org/ns/foo">lacinia <em>libero</em> 
+ullamcorper laoreet.<br/>
+ Cras quis<br/>
+ nisi at odio<br/>
+ consectetuer molestie. Curabitur consectetuer urna a sem. Nunc non 
+urna. Cras in massa. Vestibulum ante ipsum primis in faucibus orci 
+luctus et ultrices posuere cubilia Curae; Sed sollicitudin, nulla at 
+pharetra rutrum, <br/>
+lacus risus pulvinar ante.
+</pre>
+</body>
+</html>
\ No newline at end of file
--- a/content/base/test/file_xhtmlserializer_2_basic.xhtml
+++ b/content/base/test/file_xhtmlserializer_2_basic.xhtml
@@ -2,18 +2,17 @@
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <meta http-equiv="content-type" content="text/html; charset=" />
   <title>Test for html serializer with entities</title>
 </head>
 <body>
 
-<p>The basic set is just " " &amp; &lt; &gt; " for interoperability with
- older products that don't support α and friends.</p>
+<p>The basic set is just " " &amp; &lt; &gt; " for interoperability with older products that don't support α and friends.</p>
 
 <p>latin1 ¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ­ ® ¯ ° ± ² ³ ´ 
 µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ
 Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø
 Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê 
 ë ì í î ï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý 
 þ ÿ </p>
 <p>symbols, math.. ƒ Α Β Γ Δ Ε Ζ Η Θ Ι Κ Λ Μ Ν Ξ Ο Π Ρ Σ Τ Υ
--- a/content/base/test/file_xhtmlserializer_2_enthtml.xhtml
+++ b/content/base/test/file_xhtmlserializer_2_enthtml.xhtml
@@ -2,18 +2,17 @@
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <meta http-equiv="content-type" content="text/html; charset=" />
   <title>Test for html serializer with entities</title>
 </head>
 <body>
 
-<p>The basic set is just &nbsp; &amp; &lt; &gt; " for interoperability 
-with older products that don't support &alpha; and friends.</p>
+<p>The basic set is just &nbsp; &amp; &lt; &gt; " for interoperability with older products that don't support &alpha; and friends.</p>
 
 <p>latin1 &iexcl; &cent; &pound; &curren; &yen; &brvbar; &sect; &uml; 
 &copy; &ordf; &laquo; &not; &shy; &reg; &macr; &deg; &plusmn; &sup2; 
 &sup3; &acute; 
 &micro; &para; &middot; &cedil; &sup1; &ordm; &raquo; &frac14; &frac12; 
 &frac34; &iquest; &Agrave; &Aacute; &Acirc; &Atilde; &Auml; &Aring; 
 &AElig;
 &Ccedil; &Egrave; &Eacute; &Ecirc; &Euml; &Igrave; &Iacute; &Icirc; 
--- a/content/base/test/file_xhtmlserializer_2_entw3c.xhtml
+++ b/content/base/test/file_xhtmlserializer_2_entw3c.xhtml
@@ -2,18 +2,17 @@
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <meta http-equiv="content-type" content="text/html; charset=" />
   <title>Test for html serializer with entities</title>
 </head>
 <body>
 
-<p>The basic set is just &nbsp; &amp; &lt; &gt; " for interoperability 
-with older products that don't support &alpha; and friends.</p>
+<p>The basic set is just &nbsp; &amp; &lt; &gt; " for interoperability with older products that don't support &alpha; and friends.</p>
 
 <p>latin1 &iexcl; &cent; &pound; &curren; &yen; &brvbar; &sect; &uml; 
 &copy; &ordf; &laquo; &not; &shy; &reg; &macr; &deg; &plusmn; &sup2; 
 &sup3; &acute; 
 &micro; &para; &middot; &cedil; &sup1; &ordm; &raquo; &frac14; &frac12; 
 &frac34; &iquest; &Agrave; &Aacute; &Acirc; &Atilde; &Auml; &Aring; 
 &AElig;
 &Ccedil; &Egrave; &Eacute; &Ecirc; &Euml; &Igrave; &Iacute; &Icirc; 
--- a/content/base/test/file_xhtmlserializer_2_latin1.xhtml
+++ b/content/base/test/file_xhtmlserializer_2_latin1.xhtml
@@ -2,18 +2,17 @@
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <meta http-equiv="content-type" content="text/html; charset=" />
   <title>Test for html serializer with entities</title>
 </head>
 <body>
 
-<p>The basic set is just &nbsp; &amp; &lt; &gt; " for interoperability 
-with older products that don't support α and friends.</p>
+<p>The basic set is just &nbsp; &amp; &lt; &gt; " for interoperability with older products that don't support α and friends.</p>
 
 <p>latin1 &iexcl; &cent; &pound; &curren; &yen; &brvbar; &sect; &uml; 
 &copy; &ordf; &laquo; &not; &shy; &reg; &macr; &deg; &plusmn; &sup2; 
 &sup3; &acute; 
 &micro; &para; &middot; &cedil; &sup1; &ordm; &raquo; &frac14; &frac12; 
 &frac34; &iquest; &Agrave; &Aacute; &Acirc; &Atilde; &Auml; &Aring; 
 &AElig;
 &Ccedil; &Egrave; &Eacute; &Ecirc; &Euml; &Igrave; &Iacute; &Icirc; 
--- a/content/base/test/test_bug422403-1.html
+++ b/content/base/test/test_bug422403-1.html
@@ -81,20 +81,19 @@ function testHtmlSerializer_1 () {
   is(out, expected, "test OutputNoScriptContent");
 
   encoder.init(doc, "application/xhtml+xml", de.OutputLFLineBreak | de.OutputNoFramesContent);
   out = encoder.encodeToString();
   is(out, expected, "test OutputNoFramesContent");
 
 
   //------------ OutputWrap
-  // by default, this flag is set, so we should have the same result as
-  // when there are no flags.
   encoder.init(doc, "application/xhtml+xml", de.OutputLFLineBreak | de.OutputWrap);
   out = encoder.encodeToString();
+  expected = loadFileContent("file_xhtmlserializer_1_wrap.xhtml");
   is(out, expected, "test OutputWrap");
 
   //------------ OutputFormatted
   encoder.init(doc, "application/xhtml+xml", de.OutputLFLineBreak | de.OutputFormatted);
   out = encoder.encodeToString();
   expected = loadFileContent("file_xhtmlserializer_1_format.xhtml");
   is(out, expected, "test OutputFormatted");
 
--- a/content/base/test/test_bug422403-2.xhtml
+++ b/content/base/test/test_bug422403-2.xhtml
@@ -87,99 +87,99 @@ function testHtmlSerializer_1 () {
   var node = document.getElementById('draggable');
 
   var select = window.getSelection();
   select.selectAllChildren(node);  
 
   encoder.init(document, "application/xhtml+xml", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = 'This is a <em xmlns=\"http://www.w3.org/1999/xhtml\">draggable</em> bit of\n text.';
+  expected = 'This is a <em xmlns=\"http://www.w3.org/1999/xhtml\">draggable</em> bit of text.';
   is(out, expected, "test selection");
 
   encoder.init(document, "application/xhtml+xml", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(null);
   encoder.setContainerNode(node);
   out = encoder.encodeToString();
-  expected = 'This is a <em xmlns=\"http://www.w3.org/1999/xhtml\">draggable</em> bit of\n text.';
+  expected = 'This is a <em xmlns=\"http://www.w3.org/1999/xhtml\">draggable</em> bit of text.';
   is(out, expected, "test container node");
 
   encoder.init(document, "application/xhtml+xml", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setNode(node);
   out = encoder.encodeToString();
-  expected = "<div xmlns=\"http://www.w3.org/1999/xhtml\" id=\"draggable\" \nondragstart=\"doDragStartSelection(event)\">This is a <em>draggable</em> \nbit of text.</div>";
+  expected = "<div xmlns=\"http://www.w3.org/1999/xhtml\" id=\"draggable\" ondragstart=\"doDragStartSelection(event)\">This is a <em>draggable</em> bit of text.</div>";
   is(out, expected, "test node");
 
   node = document.getElementById('aList');
 
   var select = window.getSelection();
   select.selectAllChildren(node);  
 
   encoder.init(document, "application/xhtml+xml", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '\n   <li xmlns=\"http://www.w3.org/1999/xhtml\">Lorem ipsum dolor</li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">sit amet, <strong>consectetuer</strong>\n </li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">adipiscing elit</li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">Nam eu sapien. Sed viverra \nlacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. \nClass</li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">aptent taciti</li>\n';
+  expected = '\n   <li xmlns=\"http://www.w3.org/1999/xhtml\">Lorem ipsum dolor</li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">sit amet, <strong>consectetuer</strong> </li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">adipiscing elit</li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">aptent taciti</li>\n';
   is(out, expected, "test list selection");
 
   encoder.init(document, "application/xhtml+xml", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(null);
   encoder.setContainerNode(node);
   out = encoder.encodeToString();
-  expected = '\n   <li xmlns=\"http://www.w3.org/1999/xhtml\">Lorem ipsum dolor</li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">sit amet, <strong>consectetuer</strong>\n </li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">adipiscing elit</li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">Nam eu sapien. Sed viverra \nlacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. \nClass</li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">aptent taciti</li>\n';
+  expected = '\n   <li xmlns=\"http://www.w3.org/1999/xhtml\">Lorem ipsum dolor</li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">sit amet, <strong>consectetuer</strong> </li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">adipiscing elit</li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li xmlns=\"http://www.w3.org/1999/xhtml\">aptent taciti</li>\n';
   is(out, expected, "test list container node");
 
   encoder.init(document, "application/xhtml+xml", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setNode(node);
   out = encoder.encodeToString();
-  expected = "<ol xmlns=\"http://www.w3.org/1999/xhtml\" id=\"aList\">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>";
+  expected = "<ol xmlns=\"http://www.w3.org/1999/xhtml\" id=\"aList\">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>";
   is(out, expected, "test list node");
 
   var liList = node.getElementsByTagName("li");
   var range = document.createRange();
 
   // selection start at the first child of the ol, and end after the element ol
   range.setStart(node, 1);
   range.setEnd(node.parentNode, 2);
   select.removeAllRanges();
   select.addRange(range);
   encoder.init(document, "application/xhtml+xml", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<ol xmlns=\"http://www.w3.org/1999/xhtml\" id="aList"><li>Lorem ipsum \ndolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
+  expected = '<ol xmlns=\"http://www.w3.org/1999/xhtml\" id="aList"><li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   is(out, expected, "test list selection with range: selection start at the first child of the ol, and end after the element ol");
 
   // selection start at the third child of the ol, and end after the element ol
   range.setStart(node, 3);
   range.setEnd(node.parentNode, 2);
   encoder.init(document, "application/xhtml+xml", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<ol xmlns=\"http://www.w3.org/1999/xhtml\" id="aList"><li>sit amet, <strong>consectetuer</strong>\n </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
+  expected = '<ol xmlns=\"http://www.w3.org/1999/xhtml\" id="aList"><li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   is(out, expected, "test list selection with range: selection start at the third child of the ol, and end after the element ol");
 
 
   // selection start at the third child of the ol, and end after the element ol + ol start at the value 5
   range.setStart(node, 3);
   range.setEnd(node.parentNode, 2);
   node.setAttribute("start","5");
   encoder.init(document, "application/xhtml+xml", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<ol xmlns=\"http://www.w3.org/1999/xhtml\" id="aList" start="5"><li>sit \namet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
+  expected = '<ol xmlns=\"http://www.w3.org/1999/xhtml\" id="aList" start="5"><li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   is(out, expected, "test list selection with range: selection start at the third child of the ol, and end after the element ol + ol start at the value 5");
 
 
   // selection contains only some child of the ol
   node.removeAttribute("start");
   range.setStart(node, 3);
   range.setEnd(node, 5);
   encoder.init(document, "application/xhtml+xml", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<li xmlns=\"http://www.w3.org/1999/xhtml\">sit amet, <strong>consectetuer</strong>\n </li>\n  ';
+  expected = '<li xmlns=\"http://www.w3.org/1999/xhtml\">sit amet, <strong>consectetuer</strong> </li>\n  ';
   is(out, expected, "test list selection with range: selection contains only some child of the ol");
 
 
   // test on short attributes
 
   node = document.getElementById('shortattr1');
   encoder.init(document, "application/xhtml+xml",de.OutputSelectionOnly | de.OutputRaw);
   encoder.setNode(node);
--- a/content/base/test/test_bug424359-1.html
+++ b/content/base/test/test_bug424359-1.html
@@ -86,20 +86,19 @@ function testHtmlSerializer_1 () {
   isRoughly(out, expected, "test OutputNoScriptContent");
 
   encoder.init(doc, "text/html", de.OutputLFLineBreak | de.OutputNoFramesContent);
   out = encoder.encodeToString();
   isRoughly(out, expected, "test OutputNoFramesContent");
 
 
   //------------ OutputWrap
-  // by default, this flag is set, so we should have the same result as
-  // when there are no flags.
   encoder.init(doc, "text/html", de.OutputLFLineBreak |de.OutputWrap);
   out = encoder.encodeToString();
+  expected = loadFileContent("file_htmlserializer_1_wrap.html");
   isRoughly(out, expected, "test OutputWrap");
 
   //------------ OutputFormatted
   encoder.init(doc, "text/html", de.OutputLFLineBreak | de.OutputFormatted);
   out = encoder.encodeToString();
   expected = loadFileContent("file_htmlserializer_1_format.html");
   isRoughly(out, expected, "test OutputFormatted");
 
--- a/content/base/test/test_bug424359-2.html
+++ b/content/base/test/test_bug424359-2.html
@@ -106,75 +106,75 @@ function testHtmlSerializer_1 () {
   encoder.setContainerNode(node);
   out = encoder.encodeToString();
   expected = 'This is a <em>draggable</em> bit of text.';
   is(out, expected, "test container node");
 
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setNode(node);
   out = encoder.encodeToString();
-  expected = "<div id=\"draggable\" ondragstart=\"doDragStartSelection(event)\">This is a <em>draggable</em>\n bit of text.</div>";
+  expected = "<div id=\"draggable\" ondragstart=\"doDragStartSelection(event)\">This is a <em>draggable</em> bit of text.</div>";
   is(out, expected, "test node");
 
   node = document.getElementById('aList');
 
   var select = window.getSelection();
   select.selectAllChildren(node);  
 
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n';
+  expected = '\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n';
   is(out, expected, "test list selection");
 
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(null);
   encoder.setContainerNode(node);
   out = encoder.encodeToString();
-  expected = '\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n';
+  expected = '\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n';
   is(out, expected, "test list container node");
 
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setNode(node);
   out = encoder.encodeToString();
-  expected = "<ol id=\"aList\">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>";
+  expected = "<ol id=\"aList\">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>";
   is(out, expected, "test list node");
 
   var liList = node.getElementsByTagName("li");
   var range = document.createRange();
 
   // selection start at the first child of the ol, and end after the element ol
   range.setStart(node, 1);
   range.setEnd(node.parentNode, 2);
   select.removeAllRanges();
   select.addRange(range);
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<ol id="aList"><li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
+  expected = '<ol id="aList"><li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   is(out, expected, "test list selection with range: selection start at the first child of the ol, and end after the element ol");
 
   // selection start at the third child of the ol, and end after the element ol
   range.setStart(node, 3);
   range.setEnd(node.parentNode, 2);
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<ol id="aList"><li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
+  expected = '<ol id="aList"><li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   is(out, expected, "test list selection with range: selection start at the third child of the ol, and end after the element ol");
 
 
   // selection start at the third child of the ol, and end after the element ol + ol start at the value 5
   range.setStart(node, 3);
   range.setEnd(node.parentNode, 2);
   node.setAttribute("start","5");
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<ol start="5" id="aList"><li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
+  expected = '<ol start="5" id="aList"><li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   is(out, expected, "test list selection with range: selection start at the third child of the ol, and end after the element ol + ol start at the value 5");
 
 
   // selection contains only some child of the ol
   node.removeAttribute("start");
   range.setStart(node, 3);
   range.setEnd(node, 5);
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
--- a/content/base/test/test_bug541937.html
+++ b/content/base/test/test_bug541937.html
@@ -85,17 +85,17 @@ function testSerializer () {
   result = result.replace(/\r\n/mg, "\n");
   is(result, expected, "serialization of a link element with no content, inside an xml document");
   
   
   doc = $("testframe").contentDocument;
   encoder.init(doc, "text/html", de.OutputLFLineBreak);
   encoder.setCharset("UTF-8");
   result = encoder.encodeToString();
-  expected = '<html><head><meta http-equiv=\"content-type\" content=\"text/html; \ncharset=UTF-8\">\n  <title>Test</title>\n';
+  expected = '<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n  <title>Test</title>\n';
   expected += '   <link rel=\"Top\" href=\"\"> ';
   expected += ' </head><body>foo \n\n\n  <p>Hello world</p>\n</body></html>';
   is(result, expected, "serialization of a link element with content, inside an html document");
 
   doc = $("testframe2").contentDocument;
   encoder.init(doc, "application/xhtml+xml", de.OutputLFLineBreak);
   encoder.setCharset("UTF-8");
   result = encoder.encodeToString();
--- a/content/base/test/test_copypaste.html
+++ b/content/base/test/test_copypaste.html
@@ -60,17 +60,17 @@ function testCopyPaste () {
   // is the clipboard contain a text/html data ?
   transferable = Components.classes['@mozilla.org/widget/transferable;1']
                            .createInstance(Components.interfaces.nsITransferable);
   transferable.addDataFlavor("text/html");
   clipboard.getData(transferable, 1);
 
   transferable.getTransferData ("text/html", data, {} ) ;
   is (data.value.QueryInterface(Components.interfaces.nsISupportsString).data,
-      "<div id=\"draggable\" title=\"title to have a long HTML line\">This is a <em>draggable</em>\n bit of text.</div>",
+      "<div id=\"draggable\" title=\"title to have a long HTML line\">This is a <em>draggable</em> bit of text.</div>",
       "text/html value in the clipboard");
   
   // let's paste now in the textarea and verify its content
   textarea.focus();
   textarea.QueryInterface(Components.interfaces.nsIDOMNSEditableElement)
           .editor.paste(1);
   is(textarea.value, "This is a draggable bit of text.", "value of the textarea after the paste");
 
--- a/content/base/test/test_htmlcopyencoder.html
+++ b/content/base/test/test_htmlcopyencoder.html
@@ -35,97 +35,97 @@ function testHtmlCopyEncoder () {
   encoder.setContainerNode(node);
   out = encoder.encodeToString();
   expected = 'This is a <em>draggable</em> bit of text.';
   is(out, expected, "test container node ");
 
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setNode(node);
   out = encoder.encodeToString();
-  expected = "<div id=\"draggable\" ondragstart=\"doDragStartSelection(event)\">This is a <em>draggable</em>\n bit of text.</div>";
+  expected = "<div id=\"draggable\" ondragstart=\"doDragStartSelection(event)\">This is a <em>draggable</em> bit of text.</div>";
   is(out, expected, "test node");
 
   var select = window.getSelection();
   select.selectAllChildren(node);
 
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = "<div style=\"display: none;\">\n\n<div id=\"draggable\" ondragstart=\"doDragStartSelection(event)\">This is a <em>draggable</em>\n bit of text.</div>\n\n</div>";
+  expected = "<div style=\"display: none;\">\n\n<div id=\"draggable\" ondragstart=\"doDragStartSelection(event)\">This is a <em>draggable</em> bit of text.</div>\n\n</div>";
   is(out, expected, "test selection");
 
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputAbsoluteLinks | de.OutputEncodeHTMLEntities | de.OutputSelectionOnly | de.OutputRaw);
   encoder.setSelection(select);
   var outContext = {value:''}, outInfo = {value:''};
   out = encoder.encodeToStringWithContext(outContext, outInfo);
   expected = "<div style=\"display: none;\">\n\n<div id=\"draggable\" ondragstart=\"doDragStartSelection(event)\">This is a <em>draggable</em> bit of text.</div>\n\n</div>";
   is(out, expected, "test encodeToStringWithContext with selection ");
 
   node.nextSibling.data="\nfoo bar\n";
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = "<div id=\"draggable\" ondragstart=\"doDragStartSelection(event)\">This is a <em>draggable</em>\n bit of text.</div>";
+  expected = "<div id=\"draggable\" ondragstart=\"doDragStartSelection(event)\">This is a <em>draggable</em> bit of text.</div>";
   is(out, expected, "test selection with additional data");
 
   node = document.getElementById('aList');
 
   var select = window.getSelection();
   select.selectAllChildren(node);
 
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<ol id=\"aList\">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
+  expected = '<ol id=\"aList\">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   is(out, expected, "test list selection");
 
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setContainerNode(node);
   out = encoder.encodeToString();
-  expected = '\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n';
+  expected = '\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n';
   is(out, expected, "test list container node");
 
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setNode(node);
   out = encoder.encodeToString();
-  expected = "<ol id=\"aList\">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>";
+  expected = "<ol id=\"aList\">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>";
   is(out, expected, "test list node");
 
   var liList = node.getElementsByTagName("li");
   var range = document.createRange();
 
   // selection start at the first child of the ol, and end after the element ol
   range.setStart(node, 1);
   range.setEnd(node.parentNode, 2);
   select.removeAllRanges();
   select.addRange(range);
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<ol id="aList">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
+  expected = '<ol id="aList">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   is(out, expected, "test list selection with range: selection start at the first child of the ol, and end after the element ol");
 
   // selection start at the third child of the ol, and end after the element ol
   range.setStart(node, 3);
   range.setEnd(node.parentNode, 2);
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<ol id="aList"><li value=\"2\">sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
+  expected = '<ol id="aList"><li value=\"2\">sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   is(out, expected, "test list selection with range: selection start at the third child of the ol, and end after the element ol");
 
 
   // selection start at the third child of the ol, and end after the element ol + ol start at the value 5
   range.setStart(node, 3);
   range.setEnd(node.parentNode, 2);
   node.setAttribute("start","5");
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<ol start=\"5\" id=\"aList\"><li value=\"6\">sit amet, <strong>consectetuer</strong>\n </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
+  expected = '<ol start=\"5\" id=\"aList\"><li value=\"6\">sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   is(out, expected, "test list selection with range: selection start at the third child of the ol, and end after the element ol + ol start at the value 5");
 
   // selection contains only some child of the ol
   node.removeAttribute("start");
   range.setStart(node, 3);
   range.setEnd(node, 5);
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
@@ -149,17 +149,17 @@ function testHtmlCopyEncoder () {
   out = encoder.encodeToString();
   expected = '<li>sit amet, <strong>consectetuer</strong> </li>\n  ';
   is(out, expected, "test list selection with range: selection contains only some child of the ol + ol start at the value 5");
 
   select.selectAllChildren(node);
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<ol id=\"aList\">\n   <li value=\"8\">Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
+  expected = '<ol id=\"aList\">\n   <li value=\"8\">Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   is(out, expected, "test list selection with a value on a LI");
 
   //test Bug 436703
   node = document.getElementById('aContentEditable');
   select.selectAllChildren(node);
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
--- a/content/base/test/test_htmlcopyencoder.xhtml
+++ b/content/base/test/test_htmlcopyencoder.xhtml
@@ -39,26 +39,26 @@ function testHtmlCopyEncoder () {
 
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setNode(node);
   out = encoder.encodeToString();
   // the attributes are in the reverse order because the XHTML parser parse in the
   // right order but the html serializer serializes in the reverse order
   // (because the html parser stores the attribute in the reverse order,
   // see bug 213347 for reason).
-  expected = "<div ondragstart=\"doDragStartSelection(event)\" id=\"draggable\">This is a <em>draggable</em>\n <br>bit of text.</div>";
+  expected = "<div ondragstart=\"doDragStartSelection(event)\" id=\"draggable\">This is a <em>draggable</em> <br>bit of text.</div>";
   is(out, expected, "test node");
 
   var select = window.getSelection();
   select.selectAllChildren(node);
   
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = "<div style=\"display: none;\">\n\n<div id=\"draggable\" ondragstart=\"doDragStartSelection(event)\">This is a <em>draggable</em>\n <br>bit of text.</div>\n\n</div>";
+  expected = "<div style=\"display: none;\">\n\n<div id=\"draggable\" ondragstart=\"doDragStartSelection(event)\">This is a <em>draggable</em> <br>bit of text.</div>\n\n</div>";
   todo_is(out, expected, "test selection");
 
   node.nextSibling.data="\nfoo bar\n";
   encoder.init(document, "text/html", de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
   expected = "<div id=\"draggable\" ondragstart=\"doDragStartSelection(event)\">This is a <em>draggable</em>\n <br>bit of text.</div>";
   todo_is(out, expected, "test selection with additional data");
@@ -72,57 +72,57 @@ function testHtmlCopyEncoder () {
   encoder.setSelection(select);
   out = encoder.encodeToString();
   expected = '<ol id=\"aList\">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   todo_is(out, expected, "test list selection");
 
   encoder.init(document, "text/html",de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setContainerNode(node);
   out = encoder.encodeToString();
-  expected = '\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n';
+  expected = '\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n';
   is(out, expected, "test list container node");
 
   encoder.init(document, "text/html",de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setNode(node);
   out = encoder.encodeToString();
-  expected = "<ol id=\"aList\">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>";
+  expected = "<ol id=\"aList\">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>";
   is(out, expected, "test list node");
 
   var liList = node.getElementsByTagName("li");
   var range = document.createRange();
 
   // selection start at the first child of the ol, and end after the element ol
   range.setStart(node, 1);
   range.setEnd(node.parentNode, 2);
   select.removeAllRanges();
   select.addRange(range);
   encoder.init(document, "text/html",de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<ol id="aList">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
+  expected = '<ol id="aList">\n   <li>Lorem ipsum dolor</li>\n  <li>sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   todo_is(out, expected, "test list selection with range: selection start at the first child of the ol, and end after the element ol");
 
   // selection start at the third child of the ol, and end after the element ol
   range.setStart(node, 3);
   range.setEnd(node.parentNode, 2);
   encoder.init(document, "text/html",de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<ol id="aList"><li value=\"2\">sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
+  expected = '<ol id="aList"><li value=\"2\">sit amet, <strong>consectetuer</strong> </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   todo_is(out, expected, "test list selection with range: selection start at the third child of the ol, and end after the element ol");
 
 
   // selection start at the third child of the ol, and end after the element ol + ol start at the value 5
   range.setStart(node, 3);
   range.setEnd(node.parentNode, 2);
   node.setAttribute("start","5");
   encoder.init(document, "text/html",de.OutputLFLineBreak | de.OutputSelectionOnly);
   encoder.setSelection(select);
   out = encoder.encodeToString();
-  expected = '<ol start=\"5\" id=\"aList\"><li value=\"6\">sit amet, <strong>consectetuer</strong>\n </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus \naliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
+  expected = '<ol start=\"5\" id=\"aList\"><li value=\"6\">sit amet, <strong>consectetuer</strong>\n </li>\n  <li>adipiscing elit</li>\n  <li>Nam eu sapien. Sed viverra lacus. Donec quis ipsum. Nunc cursus aliquet lectus. Nunc vitae eros. Class</li>\n  <li>aptent taciti</li>\n</ol>';
   todo_is(out, expected, "test list selection with range: selection start at the third child of the ol, and end after the element ol + ol start at the value 5");
 
 
   // selection contains only some child of the ol
   node.removeAttribute("start");
   range.setStart(node, 3);
   range.setEnd(node, 5);
   encoder.init(document, "text/html",de.OutputLFLineBreak | de.OutputSelectionOnly);
--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
@@ -2023,29 +2023,24 @@ nsCanvasRenderingContext2D::SetFont(cons
         nsCOMPtr<nsICSSStyleRule> parentRule;
         rv = CreateFontStyleRule(NS_LITERAL_STRING("10px sans-serif"),
                                  document,
                                  getter_AddRefs(parentRule));
         if (NS_FAILED(rv))
             return rv;
         nsCOMArray<nsIStyleRule> parentRules;
         parentRules.AppendObject(parentRule);
-        parentContext =
-            styleSet->ResolveStyleForRules(nsnull, nsnull,
-                                           nsCSSPseudoElements::ePseudo_NotPseudoElement,
-                                           nsnull, parentRules);
+        parentContext = styleSet->ResolveStyleForRules(nsnull, parentRules);
     }
 
     if (!parentContext)
         return NS_ERROR_FAILURE;
 
     nsRefPtr<nsStyleContext> sc =
-        styleSet->ResolveStyleForRules(parentContext, nsnull,
-                                       nsCSSPseudoElements::ePseudo_NotPseudoElement,
-                                       nsnull, rules);
+        styleSet->ResolveStyleForRules(parentContext, rules);
     if (!sc)
         return NS_ERROR_FAILURE;
     const nsStyleFont* fontStyle = sc->GetStyleFont();
 
     NS_ASSERTION(fontStyle, "Could not obtain font style");
 
     nsIAtom* language = sc->GetStyleVisibility()->mLanguage;
     if (!language) {
--- a/content/html/content/test/test_bug209275.xhtml
+++ b/content/html/content/test/test_bug209275.xhtml
@@ -72,24 +72,29 @@ SimpleTest.waitForExplicitFinish();
 function link123HrefIs(href, testNum) {
   is($('link1').href, href, "link1 test " + testNum);
   is($('link2').href, href, "link2 test " + testNum);
   is($('link3').href, href, "link3 test " + testNum);
 }
 
 var gGen;
 
+function visitedDependentComputedStyle(win, elem, property) {
+  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+  var utils = win.QueryInterface(Components.interfaces.nsIInterfaceRequestor).
+                getInterface(Components.interfaces.nsIDOMWindowUtils);
+  return utils.getVisitedDependentComputedStyle(elem, "", property);
+}
+
 function getColor(elem) {
-  return document.defaultView.getComputedStyle(elem, "").color;
+  return visitedDependentComputedStyle(document.defaultView, elem, "color");
 }
 
 function getFill(elem) {
-  return document.defaultView
-          .getComputedStyle(elem, "")
-          .getPropertyValue("fill");
+  return visitedDependentComputedStyle(document.defaultView, elem, "fill");
 }
 
 function setXlinkHref(elem, href) {
   elem.setAttributeNS("http://www.w3.org/1999/xlink", "href", href);
 }
 
 function continueTest() {
   gGen.next();
--- a/content/html/content/test/test_bug481335.xhtml
+++ b/content/html/content/test/test_bug481335.xhtml
@@ -46,22 +46,28 @@ const visitedColor = "rgb(255, 0, 0)";
 let tests = testIterator();
 function continueTest() {
   tests.next();
 }
 
 function checkLinkColor(aElmId, aExpectedColor, aMessage) {
   // Because link coloring is asynchronous, we wait until we get the right
   // result, or we will time out (resulting in a failure).
-  var getCS = document.defaultView.getComputedStyle;
-  while (getCS($(aElmId), "").color != aExpectedColor) {
+  function getColor() {
+    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+    var utils = document.defaultView.
+                  QueryInterface(Components.interfaces.nsIInterfaceRequestor).
+                  getInterface(Components.interfaces.nsIDOMWindowUtils);
+    return utils.getVisitedDependentComputedStyle($(aElmId), "", "color");
+  }
+  while (getColor() != aExpectedColor) {
     setTimeout(continueTest, 10);
     return false;
   }
-  is(getCS($(aElmId), "").color, aExpectedColor, aMessage);
+  is(getColor(), aExpectedColor, aMessage);
   return true;
 }
 
 function testIterator() {
   // After first load
   $("newparent").appendChild($("t"));
   is($("t").href, "http://www.example.com/" + rand,
      "Unexpected href after move");
--- a/content/html/document/test/Makefile.in
+++ b/content/html/document/test/Makefile.in
@@ -67,16 +67,17 @@ include $(topsrcdir)/config/rules.mk
 		test_bug380383.html \
 		test_bug386495.html \
 		test_bug391777.html \
 		test_bug402680.html \
 		test_bug403868.html \
 		test_bug403868.xhtml \
 		test_bug404320.html \
 		$(warning test_bug435128.html disabled because it takes 60 seconds) \
+		test_bug463104.html \
 		test_bug468353.html \
 		test_form-parsing.html \
 		test_viewport.html \
 		test_documentAll.html \
 		test_bug445004.html \
 		bug445004-inner.js \
 		bug445004-outer-rel.html \
 		bug445004-outer-abs.html \
new file mode 100644
--- /dev/null
+++ b/content/html/document/test/test_bug463104.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+<title>Noninteger coordinates test</title>
+<script type="text/javascript" src="/MochiKit/packed.js"></script>
+<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<div id="a" style="position: fixed; left: 5.5px; top: 5.5px; width: 100px; height: 100px; background: blue"></div>
+<p style="margin-top: 110px">
+<script>
+var a = document.getElementById("a");
+isnot(a, document.elementFromPoint(5, 5), "a shouldn't be found");
+isnot(a, document.elementFromPoint(5.25, 5.25), "a shouldn't be found");
+is(a, document.elementFromPoint(5.5, 5.5), "a should be found");
+is(a, document.elementFromPoint(5.75, 5.75), "a should be found");
+is(a, document.elementFromPoint(6, 6), "a should be found");
+is(a, document.elementFromPoint(105, 105), "a should be found");
+is(a, document.elementFromPoint(105.25, 105.25), "a should be found");
+isnot(a, document.elementFromPoint(105.5, 105.5), "a shouldn't be found");
+isnot(a, document.elementFromPoint(105.75, 105.75), "a shouldn't be found");
+isnot(a, document.elementFromPoint(106, 106), "a shouldn't be found");
+</script>
+</body>
+</html>
--- a/content/media/ogg/nsOggDecoder.cpp
+++ b/content/media/ogg/nsOggDecoder.cpp
@@ -84,24 +84,24 @@ float nsOggDecoder::GetDuration()
   NS_ASSERTION(NS_IsMainThread(), "Should be on main thread.");
   if (mDuration >= 0) {
      return static_cast<float>(mDuration) / 1000.0;
   }
   return std::numeric_limits<float>::quiet_NaN();
 }
 
 nsOggDecoder::nsOggDecoder() :
-  mMonitor("media.decoder"),
   mDecoderPosition(0),
   mPlaybackPosition(0),
   mCurrentTime(0.0),
   mInitialVolume(0.0),
   mRequestedSeekTime(-1.0),
   mDuration(-1),
   mSeekable(PR_TRUE),
+  mMonitor("media.decoder"),
   mPlayState(PLAY_STATE_PAUSED),
   mNextState(PLAY_STATE_PAUSED),
   mResourceLoaded(PR_FALSE),
   mIgnoreProgressData(PR_FALSE)
 {
   MOZ_COUNT_CTOR(nsOggDecoder);
   NS_ASSERTION(NS_IsMainThread(), "Should be on main thread.");
 #ifdef PR_LOGGING
--- a/content/media/ogg/nsOggHacks.h
+++ b/content/media/ogg/nsOggHacks.h
@@ -64,17 +64,17 @@ namespace mozilla {
 
 /**
  * MonitorAutoExit
  * Exit the Monitor when it enters scope, and enters it when it leaves 
  * scope.
  *
  * MUCH PREFERRED to bare calls to Monitor.Exit and Enter.
  */ 
-class NS_COM_GLUE NS_STACK_CLASS MonitorAutoExit
+class MonitorAutoExit
 {
 public:
     /**
      * Constructor
      * The constructor releases the given lock.  The destructor
      * acquires the lock. The lock must be held before constructing
      * this object!
      * 
--- a/content/media/ogg/nsOggPlayStateMachine.cpp
+++ b/content/media/ogg/nsOggPlayStateMachine.cpp
@@ -1016,19 +1016,19 @@ void nsOggPlayStateMachine::RenderVideoF
   unsigned cbCrStride = mInfo.mPicture.width / xSubsample;
   unsigned cbCrHeight = mInfo.mPicture.height / ySubsample;
 
   // Ensure the picture size specified in the headers can be extracted out of
   // the frame we've been supplied without indexing out of bounds.
   PRUint32 picXLimit;
   PRUint32 picYLimit;
   if (!AddOverflow(mInfo.mPicture.x, mInfo.mPicture.width, picXLimit) ||
-      picXLimit > PR_ABS(aData->mBuffer[0].stride) ||
+      picXLimit > PRUint32(PR_ABS(aData->mBuffer[0].stride)) ||
       !AddOverflow(mInfo.mPicture.y, mInfo.mPicture.height, picYLimit) ||
-      picYLimit > PR_ABS(aData->mBuffer[0].height))
+      picYLimit > PRUint32(PR_ABS(aData->mBuffer[0].height)))
   {
     // The specified picture dimensions can't be contained inside the video
     // frame, we'll stomp memory if we try to copy it. Fail.
     return;
   }
 
   unsigned cbCrSize = PR_ABS(aData->mBuffer[0].stride * aData->mBuffer[0].height) +
                       PR_ABS(aData->mBuffer[1].stride * aData->mBuffer[1].height) * 2;
@@ -1044,20 +1044,19 @@ void nsOggPlayStateMachine::RenderVideoF
 
   unsigned char* data = mCbCrBuffer.get();
 
   unsigned char* y = data;
   unsigned char* cb = y + (mInfo.mPicture.width * PR_ABS(aData->mBuffer[0].height));
   unsigned char* cr = cb + (cbCrStride * PR_ABS(aData->mBuffer[1].height));
 
   unsigned char* p = y;
-  unsigned yStride = mInfo.mPicture.width;
   unsigned char* q = aData->mBuffer[0].data + mInfo.mPicture.x +
                      aData->mBuffer[0].stride * mInfo.mPicture.y;
-  for(unsigned i=0; i < mInfo.mPicture.height; ++i) {
+  for(PRInt32 i=0; i < mInfo.mPicture.height; ++i) {
     NS_ASSERTION(q + mInfo.mPicture.width <
                  aData->mBuffer[0].data + aData->mBuffer[0].stride * aData->mBuffer[0].height,
                  "Y read must be in bounds");
     NS_ASSERTION(p + mInfo.mPicture.width < data + mCbCrSize,
                  "Memory copy 1 will stomp");
     memcpy(p, q, mInfo.mPicture.width);
     p += mInfo.mPicture.width;
     q += aData->mBuffer[0].stride;
--- a/content/media/ogg/nsOggReader.h
+++ b/content/media/ogg/nsOggReader.h
@@ -65,31 +65,31 @@ public:
   SoundData(PRInt64 aTime,
             PRInt64 aDuration,
             PRUint32 aSamples,
             float* aData,
             PRUint32 aChannels)
   : mTime(aTime),
     mDuration(aDuration),
     mSamples(aSamples),
-    mAudioData(aData),
-    mChannels(aChannels)
+    mChannels(aChannels),
+    mAudioData(aData)
   {
     MOZ_COUNT_CTOR(SoundData);
   }
 
   SoundData(PRInt64 aDuration,
             PRUint32 aSamples,
             float* aData,
             PRUint32 aChannels)
   : mTime(-1),
     mDuration(aDuration),
     mSamples(aSamples),
-    mAudioData(aData),
-    mChannels(aChannels)
+    mChannels(aChannels),
+    mAudioData(aData)
   {
     MOZ_COUNT_CTOR(SoundData);
   }
 
   ~SoundData()
   {
     MOZ_COUNT_DTOR(SoundData);
   }
--- a/content/smil/nsSMILAnimationFunction.h
+++ b/content/smil/nsSMILAnimationFunction.h
@@ -319,17 +319,16 @@ protected:
   virtual const nsAttrValue* GetAttr(nsIAtom* aAttName) const;
   virtual PRBool             GetAttr(nsIAtom* aAttName,
                                      nsAString& aResult) const;
 
   PRBool   ParseAttr(nsIAtom* aAttName, const nsISMILAttr& aSMILAttr,
                      nsSMILValue& aResult, PRBool& aCanCacheSoFar) const;
   nsresult GetValues(const nsISMILAttr& aSMILAttr,
                      nsSMILValueArray& aResult);
-  void     UpdateValuesArray();
   void     CheckKeyTimes(PRUint32 aNumValues);
   void     CheckKeySplines(PRUint32 aNumValues);
 
   inline PRBool IsToAnimation() const {
     return !HasAttr(nsGkAtoms::values) &&
             HasAttr(nsGkAtoms::to) &&
            !HasAttr(nsGkAtoms::from);
   }
--- a/content/smil/nsSMILCSSProperty.cpp
+++ b/content/smil/nsSMILCSSProperty.cpp
@@ -138,31 +138,32 @@ nsSMILCSSProperty::GetBaseValue() const
 
   // (3) Put cached override style back (if it's non-empty)
   if (overrideDecl && !cachedOverrideStyleVal.IsEmpty()) {
     overrideDecl->SetPropertyValue(mPropID, cachedOverrideStyleVal);
   }
 
   // (4) Populate our nsSMILValue from the computed style
   if (didGetComputedVal) {
-    nsSMILCSSValueType::ValueFromString(mPropID, mElement,
-                                        computedStyleVal, baseValue);
+    nsSMILCSSValueType::ValueFromString(mPropID, mElement, computedStyleVal,
+                                        PR_FALSE, baseValue);
   }
   return baseValue;
 }
 
 nsresult
 nsSMILCSSProperty::ValueFromString(const nsAString& aStr,
                                    const nsISMILAnimationElement* aSrcElement,
                                    nsSMILValue& aValue,
                                    PRBool& aCanCache) const
 {
   NS_ENSURE_TRUE(IsPropertyAnimatable(mPropID), NS_ERROR_FAILURE);
 
-  nsSMILCSSValueType::ValueFromString(mPropID, mElement, aStr, aValue);
+  nsSMILCSSValueType::ValueFromString(mPropID, mElement, aStr,
+                                      PR_FALSE, aValue);
   if (aValue.IsNull()) {
     return NS_ERROR_FAILURE;
   }
 
   // XXXdholbert: For simplicity, just assume that all CSS values have to
   // reparsed every sample. This prevents us from doing the "nothing's changed
   // so don't recompose" optimization (bug 533291) for CSS properties & mapped
   // attributes.  If it ends up being expensive to always recompose those, we
--- a/content/smil/nsSMILCSSValueType.cpp
+++ b/content/smil/nsSMILCSSValueType.cpp
@@ -332,32 +332,33 @@ GetPresContextForElement(nsIContent* aEl
 }
 
 // Helper function to parse a string into a nsStyleAnimation::Value
 static PRBool
 ValueFromStringHelper(nsCSSProperty aPropID,
                       nsIContent* aTargetElement,
                       nsPresContext* aPresContext,
                       const nsAString& aString,
+                      PRBool aUseSVGMode,
                       nsStyleAnimation::Value& aStyleAnimValue)
 {
   // If value is negative, we'll strip off the "-" so the CSS parser won't
   // barf, and then manually make the parsed value negative.
   // (This is a partial solution to let us accept some otherwise out-of-bounds
   // CSS values. Bug 501188 will provide a more complete fix.)
   PRBool isNegative = PR_FALSE;
   PRUint32 subStringBegin = 0;
   PRInt32 absValuePos = nsSMILParserUtils::CheckForNegativeNumber(aString);
   if (absValuePos > 0) {
     isNegative = PR_TRUE;
     subStringBegin = (PRUint32)absValuePos; // Start parsing after '-' sign
   }
   nsDependentSubstring subString(aString, subStringBegin);
-  if (!nsStyleAnimation::ComputeValue(aPropID, aTargetElement,
-                                      subString, aStyleAnimValue)) {
+  if (!nsStyleAnimation::ComputeValue(aPropID, aTargetElement, subString,
+                                      aUseSVGMode, aStyleAnimValue)) {
     return PR_FALSE;
   }
   if (isNegative) {
     InvertSign(aStyleAnimValue);
   }
   
   if (aPropID == eCSSProperty_font_size) {
     // Divide out text-zoom, since SVG is supposed to ignore it
@@ -370,28 +371,29 @@ ValueFromStringHelper(nsCSSProperty aPro
   return PR_TRUE;
 }
 
 // static
 void
 nsSMILCSSValueType::ValueFromString(nsCSSProperty aPropID,
                                     nsIContent* aTargetElement,
                                     const nsAString& aString,
+                                    PRBool aUseSVGMode,
                                     nsSMILValue& aValue)
 {
   NS_ABORT_IF_FALSE(aValue.IsNull(), "Outparam should be null-typed");
   nsPresContext* presContext = GetPresContextForElement(aTargetElement);
   if (!presContext) {
     NS_WARNING("Not parsing animation value; unable to get PresContext");
     return;
   }
 
   nsStyleAnimation::Value parsedValue;
   if (ValueFromStringHelper(aPropID, aTargetElement, presContext,
-                            aString, parsedValue)) {
+                            aString, aUseSVGMode, parsedValue)) {
     sSingleton.Init(aValue);
     aValue.mU.mPtr = new ValueWrapper(aPropID, parsedValue, presContext);
     if (!aValue.mU.mPtr) {
       // Out of memory! Destroy outparam, to leave it as nsSMILNullType,
       // which indicates to our caller that we failed.
       sSingleton.Destroy(aValue);
     }
   }
--- a/content/smil/nsSMILCSSValueType.h
+++ b/content/smil/nsSMILCSSValueType.h
@@ -87,24 +87,28 @@ public:
    *
    * On failure, this method leaves aValue.mType == nsSMILNullType::sSingleton.
    * Otherwise, this method leaves aValue.mType == this class's singleton.
    *
    * @param       aPropID         The property for which we're parsing a value.
    * @param       aTargetElement  The target element to whom the property/value
    *                              setting applies.
    * @param       aString         The string to be parsed as a CSS value.
+   * @param       aUseSVGMode     A flag to indicate whether we should parse
+   *                              |aString| in SVG mode.
    * @param [out] aValue          The nsSMILValue to be populated. Should
    *                              initially be null-typed.
    * @pre  aValue.IsNull()
    * @post aValue.IsNull() || aValue.mType == nsSMILCSSValueType::sSingleton
    */
   static void ValueFromString(nsCSSProperty aPropID,
                               nsIContent* aTargetElement,
-                              const nsAString& aString, nsSMILValue& aValue);
+                              const nsAString& aString,
+                              PRBool aUseSVGMode,
+                              nsSMILValue& aValue);
 
   /**
    * Creates a string representation of the given nsSMILValue.
    *
    * Note: aValue is expected to be of this type (that is, it's expected to
    * have been initialized by nsSMILCSSValueType::sSingleton).  If aValue is a
    * freshly-initialized value, this method will succeed, though the resulting
    * string will be empty.
--- a/content/smil/nsSMILMappedAttribute.cpp
+++ b/content/smil/nsSMILMappedAttribute.cpp
@@ -52,27 +52,48 @@ ReleaseStringBufferPropertyValue(void*  
                                  nsIAtom* aPropertyName, /* unused */
                                  void*    aPropertyValue,
                                  void*    aData          /* unused */)
 {
   nsStringBuffer* buf = static_cast<nsStringBuffer*>(aPropertyValue);
   buf->Release();
 }
 
+
+nsresult
+nsSMILMappedAttribute::ValueFromString(const nsAString& aStr,
+                                       const nsISMILAnimationElement* aSrcElement,
+                                       nsSMILValue& aValue,
+                                       PRBool& aCanCache) const
+{
+  NS_ENSURE_TRUE(IsPropertyAnimatable(mPropID), NS_ERROR_FAILURE);
+
+  nsSMILCSSValueType::ValueFromString(mPropID, mElement, aStr,
+                                      PR_TRUE, aValue);
+  if (aValue.IsNull()) {
+    return NS_ERROR_FAILURE;
+  }
+
+  // XXXdholbert: For simplicity, just assume that all CSS values have to
+  // reparsed every sample. See note in nsSMILCSSProperty::ValueFromString.
+  aCanCache = PR_FALSE;
+  return NS_OK;
+}
+
 nsSMILValue
 nsSMILMappedAttribute::GetBaseValue() const
 {
   nsAutoString baseStringValue;
   nsRefPtr<nsIAtom> attrName = GetAttrNameAtom();
   PRBool success = mElement->GetAttr(kNameSpaceID_None, attrName,
                                      baseStringValue);
   nsSMILValue baseValue;
   if (success) {
-    nsSMILCSSValueType::ValueFromString(mPropID, mElement,
-                                        baseStringValue, baseValue);
+    nsSMILCSSValueType::ValueFromString(mPropID, mElement, baseStringValue,
+                                        PR_TRUE, baseValue);
   } else {
     // Attribute is unset -- use computed value.
     // FIRST: Temporarily clear animated value, to make sure it doesn't pollute
     // the computed value. (We want base value, _without_ animations applied.)
     void* buf = mElement->UnsetProperty(SMIL_MAPPED_ATTR_ANIMVAL,
                                         attrName, nsnull);
     FlushChangesToTargetAttr();
 
--- a/content/smil/nsSMILMappedAttribute.h
+++ b/content/smil/nsSMILMappedAttribute.h
@@ -65,16 +65,20 @@ public:
    * @param  aPropID   The CSS property for the mapped attribute we're
    *                   interested in animating.
    * @param  aElement  The element whose attribute is being animated.
    */
   nsSMILMappedAttribute(nsCSSProperty aPropID, nsIContent* aElement) :
     nsSMILCSSProperty(aPropID, aElement) {}
 
   // nsISMILAttr methods
+  virtual nsresult ValueFromString(const nsAString& aStr,
+                                   const nsISMILAnimationElement* aSrcElement,
+                                   nsSMILValue& aValue,
+                                   PRBool& aCanCache) const;
   virtual nsSMILValue GetBaseValue() const;
   virtual nsresult    SetAnimValue(const nsSMILValue& aValue);
   virtual void        ClearAnimValue();
 
 protected:
   // Helper Methods
   void FlushChangesToTargetAttr() const;
   already_AddRefed<nsIAtom> GetAttrNameAtom() const;
--- a/docshell/test/chrome/bug293235.html
+++ b/docshell/test/chrome/bug293235.html
@@ -1,13 +1,13 @@
 <html>
   <head>
     <title>Bug 293235 page1</title>
     <style type="text/css">
-      a:visited { color: rgb(128, 0, 128); }
-      a:link { color: rgb(0, 0, 128); }
+      a:visited, a.forcevisited.forcevisited { color: rgb(128, 0, 128); }
+      a:link, a.forcelink.forcelink { color: rgb(0, 0, 128); }
       a:focus { color: rgb(128, 0, 0); }
     </style>
   </head>
   <body>
     <a id="link1" href="bug293235_p2.html">This is a test link.</a>
   </body>
 </html>
--- a/docshell/test/chrome/bug293235_window.xul
+++ b/docshell/test/chrome/bug293235_window.xul
@@ -7,16 +7,17 @@
         height="600"
         onload="setTimeout(nextTest,0);"
         title="bug 293235 test">
 
   <script type="application/javascript"
     src=
   "chrome://mochikit/content/chrome/docshell/test/chrome/docshell_helpers.js">
   </script>
+  <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
 
   <script type="application/javascript"><![CDATA[
     const Ci = Components.interfaces;
     const Cc = Components.classes;
     Components.utils.import("resource://gre/modules/NetUtil.jsm");
 
     // Define the generator-iterator for the tests.
     var tests = testIterator();
@@ -69,19 +70,32 @@
       });
       yield;
 
       // Before we go any further, make sure our link has been notified.
       waitForTrue(notified, nextTest);
       yield;
 
       // Now that we've been notified, we can check our link color.
-      is(TestWindow.getWindow().getComputedStyle($("link1"), "").color,
-        "rgb(0, 0, 128)",
-        "link not initially blue");
+      // Since we can't use getComputedStyle() for this because
+      // getComputedStyle lies about styles that result from :visited,
+      // we have to take snapshots.
+      // First, take two reference snapshots.
+      var link1 = $("link1");
+      link1.className = "forcelink";
+      var refLink = snapshotWindow(TestWindow.getWindow());
+      link1.className = "forcevisited";
+      var refVisited = snapshotWindow(TestWindow.getWindow());
+      link1.className = "";
+      function snapshotsEqual(snap1, snap2) {
+        return compareSnapshots(snap1, snap2, true)[0];
+      }
+      ok(!snapshotsEqual(refLink, refVisited), "references should not match");
+      ok(snapshotsEqual(refLink, snapshotWindow(TestWindow.getWindow())),
+         "link should initially be blue");
 
       // Load the page that the link on the previous page points to.
       doPageNavigation({
         uri: getHttpUrl("bug293235_p2.html"),
         onNavComplete: nextTest
       });
       yield;
 
@@ -104,19 +118,18 @@
         expectedEvents: [ { type: "pageshow",
                             persisted: true,
                             title: "Bug 293235 page1" } ],
         onNavComplete: nextTest
       });
       yield;
 
       // Now we can test the link color.
-      is(TestWindow.getWindow().getComputedStyle($("link1"), "").color,
-        "rgb(128, 0, 128)",
-        ":visited link wrong color");
+      ok(snapshotsEqual(refVisited, snapshotWindow(TestWindow.getWindow())),
+         "visited link should be purple");
 
       // Tell the framework the test is finished.  Include the final 'yield'
       // statement to prevent a StopIteration exception from being thrown.
       finish();
       yield;
     }
 
   ]]></script>
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -61,16 +61,17 @@
 
 #include "nsIViewManager.h"
 
 #include "nsIDOMHTMLCanvasElement.h"
 #include "nsICanvasElement.h"
 #include "gfxContext.h"
 #include "gfxImageSurface.h"
 #include "nsLayoutUtils.h"
+#include "nsComputedDOMStyle.h"
 
 #if defined(MOZ_X11) && defined(MOZ_WIDGET_GTK2)
 #include <gdk/gdk.h>
 #include <gdk/gdkx.h>
 #endif
 
 static PRBool IsUniversalXPConnectCapable()
 {
@@ -601,17 +602,17 @@ nsDOMWindowUtils::SendSimpleGestureEvent
     NSAppUnitsToIntPixels(nsPresContext::CSSPixelsToAppUnits(aY) + offset.y,
                           appPerDev);
 
   nsEventStatus status;
   return widget->DispatchEvent(&event, status);
 }
 
 NS_IMETHODIMP
-nsDOMWindowUtils::ElementFromPoint(PRInt32 aX, PRInt32 aY,
+nsDOMWindowUtils::ElementFromPoint(float aX, float aY,
                                    PRBool aIgnoreRootScrollFrame,
                                    PRBool aFlushLayout,
                                    nsIDOMElement** aReturn)
 {
   nsCOMPtr<nsIDocument> doc(do_QueryInterface(mWindow->GetExtantDocument()));
   NS_ENSURE_STATE(doc);
 
   return doc->ElementFromPointHelper(aX, aY, aIgnoreRootScrollFrame, aFlushLayout,
@@ -1219,8 +1220,31 @@ nsDOMWindowUtils::GetClassName(char **aN
 
   // Our argument must be a non-null object.
   if(JSVAL_IS_PRIMITIVE(argv[0]))
     return NS_ERROR_XPC_BAD_CONVERT_JS;
 
   *aName = NS_strdup(JS_GET_CLASS(cx, JSVAL_TO_OBJECT(argv[0]))->name);
   return *aName ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
 }
+
+NS_IMETHODIMP
+nsDOMWindowUtils::GetVisitedDependentComputedStyle(
+                    nsIDOMElement *aElement, const nsAString& aPseudoElement,
+                    const nsAString& aPropertyName, nsAString& aResult)
+{
+  aResult.Truncate();
+
+  if (!IsUniversalXPConnectCapable()) {
+    return NS_ERROR_DOM_SECURITY_ERR;
+  }
+
+  nsCOMPtr<nsIDOMCSSStyleDeclaration> decl;
+  nsresult rv =
+    mWindow->GetComputedStyle(aElement, aPseudoElement, getter_AddRefs(decl));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  static_cast<nsComputedDOMStyle*>(decl.get())->SetExposeVisitedStyle(PR_TRUE);
+  rv = decl->GetPropertyValue(aPropertyName, aResult);
+  static_cast<nsComputedDOMStyle*>(decl.get())->SetExposeVisitedStyle(PR_FALSE);
+
+  return rv;
+}
--- a/dom/interfaces/base/nsIDOMWindowUtils.idl
+++ b/dom/interfaces/base/nsIDOMWindowUtils.idl
@@ -47,17 +47,17 @@
 
 interface nsIDOMNode;
 interface nsIDOMElement;
 interface nsIDOMHTMLCanvasElement;
 interface nsIDOMEvent;
 interface nsITransferable;
 interface nsIQueryContentEventResult;
 
-[scriptable, uuid(00ca8d4f-61f1-4d9c-a7c1-82651b0cf02b)]
+[scriptable, uuid(25ada920-d727-45b6-ac70-847a3aa9c7cf)]
 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.
@@ -293,18 +293,18 @@ interface nsIDOMWindowUtils : nsISupport
   /**
    * Retrieve the element at point aX, aY in the window's document.
    *
    * @param aIgnoreRootScrollFrame whether or not to ignore the root scroll
    *        frame when retrieving the element. If false, this method returns
    *        null for coordinates outside of the viewport.
    * @param aFlushLayout flushes layout if true. Otherwise, no flush occurs.
    */
-  nsIDOMElement elementFromPoint(in long aX,
-                                 in long aY,
+  nsIDOMElement elementFromPoint(in float aX,
+                                 in float aY,
                                  in boolean aIgnoreRootScrollFrame,
                                  in boolean aFlushLayout);
 
   /**
    * Compare the two canvases, returning the number of differing pixels and
    * the maximum difference in a channel.  This will throw an error if
    * the dimensions of the two canvases are different.
    *
@@ -608,9 +608,27 @@ interface nsIDOMWindowUtils : nsISupport
    * @param aReverse If true, the selection set from |aOffset + aLength| to
    *                 |aOffset|.  Otherwise, set from |aOffset| to
    *                 |aOffset + aLength|.
    * @return True, if succeeded.  Otherwise, false.
    */
   boolean sendSelectionSetEvent(in unsigned long aOffset,
                                 in unsigned long aLength,
                                 in boolean aReverse);
+
+  /**
+   * Perform the equivalent of:
+   *   window.getComputedStyle(aElement, aPseudoElement).
+   *     getPropertyValue(aPropertyName)
+   * except that, when the link whose presence in history is allowed to
+   * influence aElement's style is visited, get the value the property
+   * would have if allowed all properties to change as a result of
+   * :visited selectors (except for cases where getComputedStyle uses
+   * data from the frame).
+   *
+   * This is easier to implement than adding our property restrictions
+   * to this API, and is sufficient for the present testing
+   * requirements (which are essentially testing 'color').
+   */
+  AString getVisitedDependentComputedStyle(in nsIDOMElement aElement,
+                                           in AString aPseudoElement,
+                                           in AString aPropertyName);
 };
--- a/dom/interfaces/core/nsIDOMNSDocument.idl
+++ b/dom/interfaces/core/nsIDOMNSDocument.idl
@@ -38,17 +38,17 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "domstubs.idl"
 
 interface nsIBoxObject;
 interface nsIDOMLocation;
 
-[scriptable, uuid(B7E9211B-F29F-4E2D-9762-6BCBC64E5C05)]
+[scriptable, uuid(42c27ca5-6065-42b6-ad9e-b748c1acd250)]
 interface nsIDOMNSDocument : nsISupports
 {
   readonly attribute DOMString      characterSet;
            attribute DOMString      dir;
 
   readonly attribute nsIDOMLocation location;
 
            attribute DOMString      title;
@@ -82,19 +82,19 @@ interface nsIDOMNSDocument : nsISupports
   * the first non-anonymous parent element (that is, the textbox) is returned.
   *
   * This method returns null if either coordinate is negative, or if the
   * specified point lies outside the visible bounds of the document.
   *
   * Callers from XUL documents should wait until the onload event has fired
   * before calling this method.
   *
-  * <a href="http://dev.w3.org/cvsweb/~checkout~/csswg/cssom/Overview.html?content-type=text/html;%20charset=utf-8#documentlayout-elementfrompoint">preliminary spec</a>
+  * See <http://www.w3.org/TR/cssom-view/#the-documentview-interface>
   */
-  nsIDOMElement             elementFromPoint(in long x, in long y);
+  nsIDOMElement             elementFromPoint(in float x, in float y);
 
   /**
    * Release the current mouse capture if it is on an element within this
    * document.
    */
   void releaseCapture();
 
 };
--- a/dom/src/geolocation/nsGeolocation.cpp
+++ b/dom/src/geolocation/nsGeolocation.cpp
@@ -268,17 +268,19 @@ nsGeolocationRequest::Allow()
     PRInt32 tempAge;
     nsresult rv = mOptions->GetMaximumAge(&tempAge);
     if (NS_SUCCEEDED(rv)) {
       if (tempAge >= 0)
         maximumAge = tempAge;
     }
   }
 
-  if (lastPosition && maximumAge > 0 && ( (PR_Now() / PR_USEC_PER_MSEC ) - maximumAge <= cachedPositionTime) ) {
+  if (lastPosition && maximumAge > 0 &&
+      ( (PR_Now() / PR_USEC_PER_MSEC) - maximumAge <=
+        PRTime(cachedPositionTime) )) {
     // okay, we can return a cached position
     mAllowed = PR_TRUE;
     
     // send the cached location
     SendLocation(lastPosition);
   }
 
   PRInt32 timeout;
@@ -917,17 +919,17 @@ nsGeolocation::WatchPosition(nsIDOMGeoPo
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsGeolocation::ClearWatch(PRInt32 aWatchId)
 {
   PRUint32 count = mWatchingCallbacks.Length();
-  if (aWatchId < 0 || count == 0 || aWatchId > count)
+  if (aWatchId < 0 || count == 0 || PRUint32(aWatchId) > count)
     return NS_OK;
 
   mWatchingCallbacks[aWatchId]->MarkCleared();
   return NS_OK;
 }
 
 PRBool
 nsGeolocation::WindowOwnerStillExists()
--- a/dom/tests/mochitest/whatwg/test_bug500328.html
+++ b/dom/tests/mochitest/whatwg/test_bug500328.html
@@ -102,17 +102,21 @@ function noPopStateExpected(msg) {
 }
 
 function popstateExpected(msg) {
   is(gNumPopStates, 1, msg);
   gNumPopStates = 0;
 }
 
 function getColor(elem) {
-  return document.defaultView.getComputedStyle(elem, "").color;
+  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+  var utils = document.defaultView.
+                QueryInterface(Components.interfaces.nsIInterfaceRequestor).
+                getInterface(Components.interfaces.nsIDOMWindowUtils);
+  return utils.getVisitedDependentComputedStyle(elem, "", "color");
 }
 
 function getSHistory(theWindow)
 {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
   const Ci = Components.interfaces;
   var sh = theWindow.QueryInterface(Ci.nsIInterfaceRequestor)
--- a/embedding/components/printingui/src/win/nsPrintDialogUtil.cpp
+++ b/embedding/components/printingui/src/win/nsPrintDialogUtil.cpp
@@ -200,17 +200,16 @@ MapPaperSizeToNativeEnum(LPDEVMODEW aDev
 #ifdef DEBUG_rods
   BOOL doingOrientation = aDevMode->dmFields & DM_ORIENTATION;
   BOOL doingPaperSize   = aDevMode->dmFields & DM_PAPERSIZE;
   BOOL doingPaperLength = aDevMode->dmFields & DM_PAPERLENGTH;
   BOOL doingPaperWidth  = aDevMode->dmFields & DM_PAPERWIDTH;
 #endif
 
   const double kThreshold = 0.05;
-  PRBool foundEnum = PR_FALSE;
   for (PRInt32 i=0;i<kNumPaperSizes;i++) {
     double width  = kPaperSizes[i].mWidth;
     double height = kPaperSizes[i].mHeight;
     if (aW < width+kThreshold && aW > width-kThreshold && 
         aH < height+kThreshold && aH > height-kThreshold) {
       aDevMode->dmPaperSize = kPaperSizes[i].mPaperSize;
       aDevMode->dmFields &= ~DM_PAPERLENGTH;
       aDevMode->dmFields &= ~DM_PAPERWIDTH;
@@ -451,17 +450,17 @@ static void SetRadioOfGroup(HWND aDlg, i
     if (radWnd != NULL) {
       ::SendMessage(radWnd, BM_SETCHECK, (WPARAM)(radioIds[i] == aRadId), (LPARAM)0);
     }
   }
 }
 
 //--------------------------------------------------------
 typedef struct {
-  char * mKeyStr;
+  const char * mKeyStr;
   long   mKeyId;
 } PropKeyInfo;
 
 // These are the control ids used in the dialog and 
 // defined by MS-Windows in commdlg.h
 static PropKeyInfo gAllPropKeys[] = {
     {"printFramesTitleWindows", grp3},
     {"asLaidOutWindows", rad4},
@@ -749,17 +748,16 @@ static UINT CALLBACK PrintHookProc(HWND 
 // NOTE:
 //   This function assumes that aPrintName has already been converted from 
 //   unicode
 //
 static HGLOBAL CreateGlobalDevModeAndInit(LPCWSTR aPrintName, nsIPrintSettings* aPS)
 {
   HGLOBAL hGlobalDevMode = NULL;
 
-  nsresult rv = NS_ERROR_FAILURE;
   HANDLE hPrinter = NULL;
   // const cast kludge for silly Win32 api's
   LPWSTR printName = const_cast<wchar_t*>(aPrintName);
   BOOL status = ::OpenPrinterW(printName, &hPrinter, NULL);
   if (status) {
 
     LPDEVMODEW  pNewDevMode;
     DWORD       dwNeeded, dwRet;
@@ -858,17 +856,16 @@ static PRBool ShouldExtendPrintDialog()
 // Displays the native Print Dialog
 static nsresult 
 ShowNativePrintDialog(HWND              aHWnd,
                       nsIPrintSettings* aPrintSettings)
 {
   //NS_ENSURE_ARG_POINTER(aHWnd);
   NS_ENSURE_ARG_POINTER(aPrintSettings);
 
-  nsresult  rv = NS_ERROR_FAILURE;
   gDialogWasExtended  = PR_FALSE;
 
   HGLOBAL hGlobalDevMode = NULL;
   HGLOBAL hDevNames      = NULL;
 
   // Get the Print Name to be used
   PRUnichar * printerName;
   aPrintSettings->GetPrinterName(&printerName);
@@ -890,23 +887,22 @@ ShowNativePrintDialog(HWND              
   if (!printerName) return NS_ERROR_FAILURE;
 
   // Now create a DEVNAMES struct so the the dialog is initialized correctly.
 
   PRUint32 len = wcslen(printerName);
   hDevNames = (HGLOBAL)::GlobalAlloc(GHND, sizeof(wchar_t) * (len + 1) + 
                                      sizeof(DEVNAMES));
   DEVNAMES* pDevNames = (DEVNAMES*)::GlobalLock(hDevNames);
-  pDevNames->wDriverOffset = sizeof(DEVNAMES);
-  pDevNames->wDeviceOffset = sizeof(DEVNAMES);
-  pDevNames->wOutputOffset = sizeof(DEVNAMES)+len+1;
+  pDevNames->wDriverOffset = sizeof(DEVNAMES)/sizeof(wchar_t);
+  pDevNames->wDeviceOffset = sizeof(DEVNAMES)/sizeof(wchar_t);
+  pDevNames->wOutputOffset = sizeof(DEVNAMES)/sizeof(wchar_t)+len;
   pDevNames->wDefault      = 0;
 
-  wchar_t* device = &(((wchar_t*)pDevNames)[pDevNames->wDeviceOffset]);
-  wcscpy(device, printerName);
+  memcpy(pDevNames+1, printerName, (len + 1) * sizeof(wchar_t));
   ::GlobalUnlock(hDevNames);
 
   // Create a Moveable Memory Object that holds a new DevMode
   // from the Printer Name
   // The PRINTDLG.hDevMode requires that it be a moveable memory object
   // NOTE: We only need to free hGlobalDevMode when the dialog is cancelled
   // When the user prints, it comes back in the printdlg struct and 
   // is used and cleaned up later
--- a/gfx/thebes/src/Makefile.in
+++ b/gfx/thebes/src/Makefile.in
@@ -135,17 +135,17 @@ endif
 EXTRA_DSO_LDOPTS += $(MOZ_PANGO_LIBS) $(ZLIB_LIBS) $(XLDFLAGS) $(XLIBS) $(XEXT_LIBS)
 endif
 
 ifdef MOZ_DFB
 CPPSRCS += gfxDirectFBSurface.cpp
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),qt)
-CPPSRCS += gfxQtPlatform.cpp gfxQPainterSurface.cpp
+CPPSRCS += gfxQtPlatform.cpp gfxQPainterSurface.cpp gfxSharedImageSurface.cpp
 CPPSRCS += gfxXlibSurface.cpp gfxQtNativeRenderer.cpp
 ifdef MOZ_PANGO
 CPPSRCS += gfxPangoFonts.cpp
 else
 CPPSRCS += gfxFT2Fonts.cpp
 endif
 CPPSRCS +=	gfxFT2FontBase.cpp
 CPPSRCS +=	gfxFT2Utils.cpp
new file mode 100644
--- /dev/null
+++ b/ipc/app/fake/Makefile.in
@@ -0,0 +1,46 @@
+# ***** 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 Corporation.
+# Portions created by the Initial Developer are Copyright (C) 2010
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either the GNU General Public License Version 2 or later (the "GPL"), or
+# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+DEPTH		= ../../..
+topsrcdir	= @top_srcdir@
+srcdir		= @srcdir@
+VPATH		= @srcdir@
+
+include $(DEPTH)/config/autoconf.mk
+
+SIMPLE_PROGRAMS	= mozilla-runtime
+
+include $(topsrcdir)/config/rules.mk
new file mode 100644
--- /dev/null
+++ b/ipc/app/fake/mozilla-runtime.cpp
@@ -0,0 +1,45 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: sw=4 ts=4 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 Fake Mozilla Plugin App.
+ *
+ * The Initial Developer of the Original Code is
+ *   Josh Aas <josh@mozilla.com>.
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include <stdio.h>
+
+int main()
+{
+  printf ("All your process are belong to us.\n");
+  return 0;
+}
--- a/js/src/Makefile.in
+++ b/js/src/Makefile.in
@@ -55,17 +55,18 @@ DIRS += editline
 endif
 
 # editline needs to get built before the shell
 ifndef JS_DISABLE_SHELL
 DIRS += shell
 endif
 
 # FIXME: bug 515383 covers getting these working on wince
-ifndef WINCE
+# bug 530688 covers Android
+ifneq (,$(filter-out WINCE ANDROID,$(OS_ARCH)))
 ifdef ENABLE_TESTS
 DIRS += jsapi-tests
 endif
 endif
 
 ifdef ENABLE_TESTS
 DIRS += tests
 endif
--- a/js/src/config/config.mk
+++ b/js/src/config/config.mk
@@ -521,17 +521,17 @@ ifeq ($(OS_ARCH),Darwin)
 # Darwin doesn't cross-compile, so just set both types of flags here.
 HOST_CMFLAGS += -fobjc-exceptions
 HOST_CMMFLAGS += -fobjc-exceptions
 OS_COMPILE_CMFLAGS += -fobjc-exceptions
 OS_COMPILE_CMMFLAGS += -fobjc-exceptions
 endif
 
 COMPILE_CFLAGS	= $(VISIBILITY_FLAGS) $(DEFINES) $(INCLUDES) $(DSO_CFLAGS) $(DSO_PIC_CFLAGS) $(CFLAGS) $(RTL_FLAGS) $(OS_COMPILE_CFLAGS)
-COMPILE_CXXFLAGS = $(VISIBILITY_FLAGS) $(DEFINES) $(INCLUDES) $(DSO_CFLAGS) $(DSO_PIC_CFLAGS) $(CXXFLAGS) $(RTL_FLAGS) $(OS_COMPILE_CXXFLAGS)
+COMPILE_CXXFLAGS = $(VISIBILITY_FLAGS) $(STL_FLAGS) $(DEFINES) $(INCLUDES) $(DSO_CFLAGS) $(DSO_PIC_CFLAGS) $(CXXFLAGS) $(RTL_FLAGS) $(OS_COMPILE_CXXFLAGS)
 COMPILE_CMFLAGS = $(OS_COMPILE_CMFLAGS)
 COMPILE_CMMFLAGS = $(OS_COMPILE_CMMFLAGS)
 
 ifndef CROSS_COMPILE
 HOST_CFLAGS += $(RTL_FLAGS)
 endif
 
 #
--- a/js/src/configure.in
+++ b/js/src/configure.in
@@ -202,16 +202,82 @@ fi
 COMPILE_ENVIRONMENT=1
 MOZ_ARG_ENABLE_BOOL(compile-environment,
 [  --disable-compile-environment
                            Disable compiler/library checks.],
     COMPILE_ENVIRONMENT=1,
     COMPILE_ENVIRONMENT= )
 
 dnl ========================================================
+dnl = Android uses a very custom (hacky) toolchain; we need to do this
+dnl = here, so that the compiler checks can succeed
+dnl ========================================================
+
+MOZ_ARG_WITH_STRING(android-ndk,
+[  --with-android-ndk=DIR
+                           location where the Android NDK can be found],
+    android_ndk=$withval)
+
+MOZ_ARG_WITH_STRING(android-toolchain,
+[  --with-android-toolchain=DIR
+                           location of the android toolchain, default NDK/build/prebuilt/HOST/arm-eabi-4.4.0],
+    android_toolchain=$withval)
+
+MOZ_ARG_WITH_STRING(android-platform,
+[  --with-android-platform=DIR
+                           location of platform dir, default NDK/build/platforms/android-5/arch-arm],
+    android_platform=$withval)
+
+if test "$target" = "arm-android-eabi" ; then
+    if test -z "$android_ndk" ; then
+        AC_MSG_ERROR([You must specify --with-android-ndk=/path/to/ndk when targeting Android.])
+    fi
+
+    if test -z "$android_toolchain" ; then
+        android_toolchain="$android_ndk"/build/prebuilt/`uname -s | tr "[[:upper:]]" "[[:lower:]]"`-x86/arm-eabi-4.4.0
+    fi
+
+    if test -z "$android_platform" ; then
+        android_platform="$android_ndk"/build/platforms/android-5/arch-arm
+    fi
+
+    dnl set up compilers
+    AS="$android_toolchain"/bin/arm-eabi-as
+    CC="$android_toolchain"/bin/arm-eabi-gcc
+    CXX="$android_toolchain"/bin/arm-eabi-g++
+    CPP="$android_toolchain"/bin/arm-eabi-cpp
+    LD="$android_toolchain"/bin/arm-eabi-ld
+    AR="$android_toolchain"/bin/arm-eabi-ar
+    RANLIB="$android_toolchain"/bin/arm-eabi-ranlib
+    STRIP="$android_toolchain"/bin/arm-eabi-strip
+
+    CPPFLAGS="-I$android_platform/usr/include $CPPFLAGS"
+    CFLAGS="-mandroid -I$android_platform/usr/include -msoft-float -fno-short-enums -fno-exceptions -march=armv5te -mthumb-interwork $CFLAGS"
+    CXXFLAGS="-mandroid -std=gnu++0x -I$android_platform/usr/include -msoft-float -fno-short-enums -fno-exceptions -march=armv5te -mthumb-interwork $CXXFLAGS"
+    LDFLAGS="-mandroid -L$android_platform/usr/lib -Wl,-rpath-link=$android_platform/usr/lib --sysroot=$android_platform $LDFLAGS"
+
+    dnl prevent cross compile section from using these flags as host flags
+    if test -z "$HOST_CPPFLAGS" ; then
+        HOST_CPPFLAGS=" "
+    fi
+    if test -z "$HOST_CFLAGS" ; then
+        HOST_CFLAGS=" "
+    fi
+    if test -z "$HOST_CXXFLAGS" ; then
+        HOST_CXXFLAGS=" "
+    fi
+    if test -z "$HOST_LDFLAGS" ; then
+        HOST_LDFLAGS=" "
+    fi
+
+    AC_DEFINE(ANDROID)
+    AC_DEFINE(FORCE_LITTLE_ENDIAN)
+fi
+
+dnl ========================================================
 dnl Checks for compilers.
 dnl ========================================================
 
 dnl AR_FLAGS set here so HOST_AR_FLAGS can be set correctly (see bug 538269)
 AR_FLAGS='cr $@'
 
 if test "$COMPILE_ENVIRONMENT"; then
 
@@ -1201,19 +1267,17 @@ sun4u | sparc*)
     CPU_ARCH=sparc
     ;;
 
 x86_64 | ia64)
     CPU_ARCH="$OS_TEST"
     ;;
 
 arm)
-    if test "$OS_ARCH" = "WINCE"; then
-        CPU_ARCH="$OS_TEST"
-    fi
+    CPU_ARCH=arm
     ;;
 esac
 
 if test -z "$OS_TARGET"; then
     OS_TARGET=$OS_ARCH
 fi
 OS_CONFIG="${OS_TARGET}${OS_RELEASE}"
 
@@ -1245,18 +1309,18 @@ if test "$GNU_CC"; then
     #             be a little bit stricter
     # Warnings slamm took out for now (these were giving more noise than help):
     # -Wbad-function-cast - warns when casting a function to a new return type
     # -Wshadow - removed because it generates more noise than help --pete
     _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wall -W -Wno-unused -Wpointer-arith"
     if test -z "$INTEL_CC"; then
        # Don't use -Wcast-align with ICC
        case "$CPU_ARCH" in
-           # And don't use it on hppa, ia64, sparc, since it's noisy there
-           hppa | ia64 | sparc)
+           # And don't use it on hppa, ia64, sparc, or arm since it's noisy there
+           hppa | ia64 | sparc | arm)
            ;;
            *)
         _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wcast-align"
            ;;
        esac
     fi
 
     dnl Turn pedantic on but disable the warnings for long long
@@ -1308,18 +1372,18 @@ fi
 if test "$GNU_CXX"; then
     # FIXME: Let us build with strict aliasing. bug 414641.
     CXXFLAGS="$CXXFLAGS -fno-strict-aliasing"
     # Turn on GNU specific features
     _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wall -Wpointer-arith -Woverloaded-virtual -Wsynth -Wno-ctor-dtor-privacy -Wno-non-virtual-dtor"
     if test -z "$INTEL_CC"; then
        # Don't use -Wcast-align with ICC
        case "$CPU_ARCH" in
-           # And don't use it on hppa, ia64, sparc, since it's noisy there
-           hppa | ia64 | sparc)
+           # And don't use it on hppa, ia64, sparc, or arm since it's noisy there
+           hppa | ia64 | sparc | arm)
            ;;
            *)
         _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wcast-align"
            ;;
        esac
     fi
 
     _DEFINES_CXXFLAGS='-DMOZILLA_CLIENT -include $(DEPTH)/js-confdefs.h'
@@ -2526,34 +2590,34 @@ x86_64*-*)
 arm*-*)
     AC_DEFINE(AVMPLUS_ARM)
     ;;
 sparc-*)
     AC_DEFINE(AVMPLUS_SPARC)
     ;;
 esac
 
-case "$target_os" in
-linux*)
+case "$target" in
+*-linux*|*-android-eabi)
     AC_DEFINE(AVMPLUS_UNIX)
     AC_DEFINE(AVMPLUS_LINUX)
     ;;
-darwin*)
+*-darwin*)
     AC_DEFINE(AVMPLUS_UNIX)
     ;;
-solaris*)
+*-solaris*)
     AC_DEFINE(AVMPLUS_UNIX)
     ;;
-freebsd*|kfreebsd*)
+*-freebsd*|*-kfreebsd*)
     AC_DEFINE(AVMPLUS_UNIX)
     ;;
-*cygwin*|*mingw*|*mks*|*msvc*|*wince|*winmo)
+*-cygwin*|*-mingw*|*-mks*|*-msvc*|*-wince|*-winmo)
     AC_DEFINE(AVMPLUS_WIN32)
     ;;
-*os2*)
+*-os2*)
     AC_DEFINE(AVMPLUS_OS2)
     ;;
 *)
     AC_MSG_ERROR([Unrecognized nanojit platform. Use --disable-tracejit to build without tracing JIT support.])
 esac
 
 fi # ENABLE_TRACEJIT
 
@@ -3473,35 +3537,56 @@ if test "$GNU_CXX"; then
   _MOZ_EXCEPTIONS_FLAGS_ON=`echo $ac_cv_cxx_exceptions_flags | sed 's|no-||'`
 fi
 
 dnl ========================================================
 dnl Put your C++ language/feature checks below
 dnl ========================================================
 AC_LANG_CPLUSPLUS
 
+ARM_ABI_PREFIX=
 HAVE_GCC3_ABI=
 if test "$GNU_CC"; then
+  if test "$CPU_ARCH" = "arm" ; then
+    AC_CACHE_CHECK(for ARM EABI,
+        ac_cv_gcc_arm_eabi,
+        [AC_TRY_COMPILE([],
+                        [
+#if defined(__ARM_EABI__)
+  return 0;
+#else
+#error Not ARM EABI.
+#endif
+                        ],
+                        ac_cv_gcc_arm_eabi="yes",
+                        ac_cv_gcc_arm_eabi="no")])
+    if test "$ac_cv_gcc_arm_eabi" = "yes"; then
+        ARM_ABI_PREFIX=eabi-
+    else
+        ARM_ABI_PREFIX=oabi-
+    fi
+  fi
+
   AC_CACHE_CHECK(for gcc 3.0 ABI,
       ac_cv_gcc_three_abi,
       [AC_TRY_COMPILE([],
                       [
 #if defined(__GXX_ABI_VERSION) && __GXX_ABI_VERSION >= 100 /* G++ V3 ABI */
   return 0;
 #else
 #error Not gcc3.
 #endif
                       ],
                       ac_cv_gcc_three_abi="yes",
                       ac_cv_gcc_three_abi="no")])
   if test "$ac_cv_gcc_three_abi" = "yes"; then
-      TARGET_COMPILER_ABI="${TARGET_COMPILER_ABI-gcc3}"
+      TARGET_COMPILER_ABI="${TARGET_COMPILER_ABI-${ARM_ABI_PREFIX}gcc3}"
       HAVE_GCC3_ABI=1
   else
-      TARGET_COMPILER_ABI="${TARGET_COMPILER_ABI-gcc2}"
+      TARGET_COMPILER_ABI="${TARGET_COMPILER_ABI-${ARM_ABI_PREFIX}gcc2}"
   fi
 fi
 AC_SUBST(HAVE_GCC3_ABI)
 
 
 AC_CACHE_CHECK(for C++ \"explicit\" keyword,
                ac_cv_cpp_explicit,
                [AC_TRY_COMPILE(class X {
@@ -5094,16 +5179,17 @@ if test "$ACCESSIBILITY" -a "$MOZ_ENABLE
     AC_DEFINE_UNQUOTED(ATK_REV_VERSION, $ATK_REV_VERSION)
 fi
 
 dnl ========================================================
 dnl JavaScript shell
 dnl ========================================================
 
 AC_HAVE_FUNCS(setlocale)
+AC_HAVE_FUNCS(localeconv)
 
 dnl ========================================================
 dnl Use cygwin wrapper for win32 builds, except MSYS/MinGW
 dnl ========================================================
 case "$host_os" in
 mingw*)
     WIN_TOP_SRC=`cd $srcdir; pwd -W`
     ;;
--- a/js/src/jscpucfg.cpp
+++ b/js/src/jscpucfg.cpp
@@ -39,17 +39,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Generate CPU-specific bit-size and similar #defines.
  */
 #include <stdio.h>
 #include <stdlib.h>
 
-#ifdef CROSS_COMPILE
+#if defined(CROSS_COMPILE) && !defined(FORCE_BIG_ENDIAN) && !defined(FORCE_LITTLE_ENDIAN)
 #include <prtypes.h>
 #endif
 
 /************************************************************************/
 
 int main(int argc, char **argv)
 {
     printf("#ifndef js_cpucfg___\n");
@@ -66,20 +66,20 @@ int main(int argc, char **argv)
      */
     printf("#ifdef __LITTLE_ENDIAN__\n");
     printf("#define IS_LITTLE_ENDIAN 1\n");
     printf("#undef  IS_BIG_ENDIAN\n");
     printf("#else\n");
     printf("#undef  IS_LITTLE_ENDIAN\n");
     printf("#define IS_BIG_ENDIAN 1\n");
     printf("#endif\n\n");
-#elif defined(IS_LITTLE_ENDIAN)
+#elif defined(IS_LITTLE_ENDIAN) || defined(FORCE_LITTLE_ENDIAN)
     printf("#define IS_LITTLE_ENDIAN 1\n");
     printf("#undef  IS_BIG_ENDIAN\n\n");
-#elif defined(IS_BIG_ENDIAN)
+#elif defined(IS_BIG_ENDIAN) || defined(FORCE_BIG_ENDIAN)
     printf("#undef  IS_LITTLE_ENDIAN\n");
     printf("#define IS_BIG_ENDIAN 1\n\n");
 #else
 #error "Endianess not defined."
 #endif
 
 #else
 
--- a/js/src/jsnum.cpp
+++ b/js/src/jsnum.cpp
@@ -727,23 +727,29 @@ js_InitRuntimeNumberState(JSContext *cx)
     number_constants[NC_NEGATIVE_INFINITY].dval = js_NegativeInfinity = u.d;
     if (!js_NewDoubleInRootedValue(cx, u.d, &rt->negativeInfinityValue))
         return false;
 
     u.s.hi = 0;
     u.s.lo = 1;
     number_constants[NC_MIN_VALUE].dval = u.d;
 
+#ifndef HAVE_LOCALECONV
+    rt->thousandsSeparator = JS_strdup(cx, "'");
+    rt->decimalSeparator = JS_strdup(cx, ".");
+    rt->numGrouping = JS_strdup(cx, "\3\0");
+#else
     struct lconv *locale = localeconv();
     rt->thousandsSeparator =
         JS_strdup(cx, locale->thousands_sep ? locale->thousands_sep : "'");
     rt->decimalSeparator =
         JS_strdup(cx, locale->decimal_point ? locale->decimal_point : ".");
     rt->numGrouping =
         JS_strdup(cx, locale->grouping ? locale->grouping : "\3\0");
+#endif
 
     return rt->thousandsSeparator && rt->decimalSeparator && rt->numGrouping;
 }
 
 void
 js_TraceRuntimeNumberState(JSTracer *trc)
 {
     JSRuntime *rt = trc->context->runtime;
--- a/js/src/jstracer.cpp
+++ b/js/src/jstracer.cpp
@@ -7272,16 +7272,26 @@ enable_debugger_exceptions()
 
 // Assume ARMv4 by default.
 static unsigned int arm_arch = 4;
 static bool arm_has_vfp = false;
 static bool arm_has_neon = false;
 static bool arm_has_iwmmxt = false;
 static bool arm_tests_initialized = false;
 
+#ifdef ANDROID
+// android doesn't have Elf32_auxv_t defined in elf.h, but it does have /proc/self/auxv
+typedef struct {
+    uint32_t a_type;
+    union {
+       uint32_t a_val;
+    } a_un;
+} Elf32_auxv_t;
+#endif
+
 static void
 arm_read_auxv()
 {
     int fd;
     Elf32_auxv_t aux;
 
     fd = open("/proc/self/auxv", O_RDONLY);
     if (fd > 0) {
--- a/js/src/xpconnect/loader/mozJSComponentLoader.cpp
+++ b/js/src/xpconnect/loader/mozJSComponentLoader.cpp
@@ -187,17 +187,17 @@ Dump(JSContext *cx, JSObject *obj, uintN
     if (!argc)
         return JS_TRUE;
 
     str = JS_ValueToString(cx, argv[0]);
     if (!str)
         return JS_FALSE;
 
     jschar *chars = JS_GetStringChars(str);
-    fputs(NS_ConvertUTF16toUTF8(chars).get(), stderr);
+    fputs(NS_ConvertUTF16toUTF8(reinterpret_cast<const PRUnichar*>(chars)).get(), stderr);
     return JS_TRUE;
 }
 
 static JSBool
 Debug(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
 {
 #ifdef DEBUG
     return Dump(cx, obj, argc, argv, rval);
--- a/layout/base/nsBidi.cpp
+++ b/layout/base/nsBidi.cpp
@@ -165,50 +165,16 @@ static Flags flagO[2]={ DIRPROP_FLAG(LRO
 nsBidi::nsBidi()
 {
   Init();
 
   mMayAllocateText=PR_TRUE;
   mMayAllocateRuns=PR_TRUE;
 }
 
-nsBidi::nsBidi(PRUint32 aMaxLength, PRUint32 aMaxRunCount)
-{
-  Init();
-  nsresult rv = NS_OK;
-
-  /* allocate memory for arrays as requested */
-  if(aMaxLength>0) {
-    if( !GETINITIALDIRPROPSMEMORY(aMaxLength) ||
-        !GETINITIALLEVELSMEMORY(aMaxLength)
-      ) {
-      mMayAllocateText=PR_FALSE;
-      rv = NS_ERROR_OUT_OF_MEMORY;
-    }
-  } else {
-    mMayAllocateText=PR_TRUE;
-  }
-
-  if(aMaxRunCount>0) {
-    if(aMaxRunCount==1) {
-      /* use simpleRuns[] */
-      mRunsSize=sizeof(Run);
-    } else if(!GETINITIALRUNSMEMORY(aMaxRunCount)) {
-      mMayAllocateRuns=PR_FALSE;
-      rv = NS_ERROR_OUT_OF_MEMORY;
-    }
-  } else {
-    mMayAllocateRuns=PR_TRUE;
-  }
-
-  if(NS_FAILED(rv)) {
-    Free();
-  }
-}
-
 nsBidi::~nsBidi()
 {
   Free();
 }
 
 void nsBidi::Init()
 {
   /* reset the object, all pointers NULL, all flags PR_FALSE, all sizes 0 */
--- a/layout/base/nsBidi.h
+++ b/layout/base/nsBidi.h
@@ -438,51 +438,16 @@ public:
    * <code>GetLine()</code>.<p>
    * This object can be reused for as long as it is not destroyed.<p>
    * <code>SetPara()</code> will allocate additional memory for
    * internal structures as necessary.
    *
    */
   nsBidi();
 
-  /** @brief Preallocating constructor
-   * Allocate an <code>nsBidi</code>
-   * object with preallocated memory for internal structures.   This
-   * constructor provides an <code>nsBidi</code> object like
-   * the default constructor, but it also
-   * preallocates memory for internal structures according to the sizings
-   * supplied by the caller.<p> Subsequent functions will not allocate
-   * any more memory, and are thus guaranteed not to fail because of lack
-   * of memory.<p> The preallocation can be limited to some of the
-   * internal memory by setting some values to 0 here. That means that
-   * if, e.g., <code>aMaxRunCount</code> cannot be reasonably
-   * predetermined and should not be set to <code>aMaxLength</code> (the
-   * only failproof value) to avoid wasting memory, then
-   * <code>aMaxRunCount</code> could be set to 0 here and the internal
-   * structures that are associated with it will be allocated on demand,
-   * just like with the default constructor.
-   *
-   * If sufficient memory could not be allocated, no exception is thrown.
-   * Test whether mDirPropsSize == aMaxLength and/or mRunsSize == aMaxRunCount.
-   *
-   * @param aMaxLength is the maximum paragraph or line length that internal memory
-   *      will be preallocated for. An attempt to associate this object with a
-   *      longer text will fail, unless this value is 0, which leaves the allocation
-   *      up to the implementation.
-   *
-   * @param aMaxRunCount is the maximum anticipated number of same-level runs
-   *      that internal memory will be preallocated for. An attempt to access
-   *      visual runs on an object that was not preallocated for as many runs
-   *      as the text was actually resolved to will fail,
-   *      unless this value is 0, which leaves the allocation up to the implementation.<p>
-   *      The number of runs depends on the actual text and maybe anywhere between
-   *      1 and <code>aMaxLength</code>. It is typically small.<p>
-   */
-  nsBidi(PRUint32 aMaxLength, PRUint32 aMaxRunCount);
-
   /** @brief Destructor. */
   virtual ~nsBidi();
 
 
   /**
    * Perform the Unicode Bidi algorithm. It is defined in the
    * <a href="http://www.unicode.org/unicode/reports/tr9/">Unicode Technical Report 9</a>,
    * version 5,
--- a/layout/base/nsBidiPresUtils.cpp
+++ b/layout/base/nsBidiPresUtils.cpp
@@ -1392,26 +1392,16 @@ nsBidiPresUtils::CalculateCharType(PRInt
 
       strongTypeFound = PR_TRUE;
       aCharType = charType;
     }
   }
   aOffset = offset;
 }
 
-nsresult nsBidiPresUtils::GetBidiEngine(nsBidi** aBidiEngine)
-{
-  nsresult rv = NS_ERROR_FAILURE;
-  if (mBidiEngine) {
-    *aBidiEngine = mBidiEngine;
-    rv = NS_OK;
-  }
-  return rv; 
-}
-
 nsresult nsBidiPresUtils::ProcessText(const PRUnichar*       aText,
                                       PRInt32                aLength,
                                       nsBidiDirection        aBaseDirection,
                                       nsPresContext*         aPresContext,
                                       BidiProcessor&         aprocessor,
                                       Mode                   aMode,
                                       nsBidiPositionResolve* aPosResolve,
                                       PRInt32                aPosResolveCount,
--- a/layout/base/nsBidiPresUtils.h
+++ b/layout/base/nsBidiPresUtils.h
@@ -194,21 +194,16 @@ public:
    */
   nsresult FormatUnicodeText(nsPresContext* aPresContext,
                              PRUnichar*      aText,
                              PRInt32&        aTextLength,
                              nsCharType      aCharType,
                              PRBool          aIsOddLevel);
 
   /**
-   * Return our nsBidi object (bidi reordering engine)
-   */
-  nsresult GetBidiEngine(nsBidi** aBidiEngine);
-
-  /**
    * Reorder plain text using the Unicode Bidi algorithm and send it to
    * a rendering context for rendering.
    *
    * @param[in] aText  the string to be rendered (in logical order)
    * @param aLength the number of characters in the string
    * @param aBaseDirection the base direction of the string
    *  NSBIDI_LTR - left-to-right string
    *  NSBIDI_RTL - right-to-left string
--- a/layout/base/nsCSSFrameConstructor.cpp
+++ b/layout/base/nsCSSFrameConstructor.cpp
@@ -7228,18 +7228,18 @@ ApplyRenderingChangeToTree(nsPresContext
     aChange = NS_SubtractHint(aChange, nsChangeHint_RepaintFrame);
     if (!aChange) {
       return;
     }
   }
 
   // If the frame's background is propagated to an ancestor, walk up to
   // that ancestor.
-  const nsStyleBackground *bg;
-  while (!nsCSSRendering::FindBackground(aPresContext, aFrame, &bg)) {
+  nsStyleContext *bgSC;
+  while (!nsCSSRendering::FindBackground(aPresContext, aFrame, &bgSC)) {
     aFrame = aFrame->GetParent();
     NS_ASSERTION(aFrame, "root frame must paint");
   }
 
   nsIViewManager* viewManager = shell->GetViewManager();
 
   // Trigger rendering updates by damaging this frame and any
   // continuations of this frame.
@@ -7647,16 +7647,23 @@ nsCSSFrameConstructor::DoContentStateCha
 
     nsRestyleHint rshint = 
       styleSet->HasStateDependentStyle(presContext, aContent, aStateMask);
       
     if ((aStateMask & NS_EVENT_STATE_HOVER) && rshint != 0) {
       ++mHoverGeneration;
     }
 
+    if (aStateMask & NS_EVENT_STATE_VISITED) {
+      // Exposing information to the page about whether the link is
+      // visited or not isn't really something we can worry about here.
+      // FIXME: We could probably do this a bit better.
+      NS_UpdateHint(hint, nsChangeHint_RepaintFrame);
+    }
+
     PostRestyleEvent(aContent, rshint, hint);
   }
 }
 
 void
 nsCSSFrameConstructor::AttributeWillChange(nsIContent* aContent,
                                            PRInt32 aNameSpaceID,
                                            nsIAtom* aAttribute,
--- a/layout/base/nsCSSRendering.cpp
+++ b/layout/base/nsCSSRendering.cpp
@@ -73,16 +73,17 @@
 #include "nsINameSpaceManager.h"
 #include "nsBlockFrame.h"
 #include "gfxContext.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "gfxPlatform.h"
 #include "gfxImageSurface.h"
 #include "nsStyleStructInlines.h"
 #include "nsCSSFrameConstructor.h"
+#include "nsCSSProps.h"
 
 #include "nsCSSRenderingBorders.h"
 
 /**
  * This is a small wrapper class to encapsulate image drawing that can draw an
  * nsStyleImage image, which may internally be a real image, a sub image, or a
  * CSS gradient.
  *
@@ -537,20 +538,51 @@ ComputePixelRadii(const nscoord *aTwipsR
 }
 
 void
 nsCSSRendering::PaintBorder(nsPresContext* aPresContext,
                             nsIRenderingContext& aRenderingContext,
                             nsIFrame* aForFrame,
                             const nsRect& aDirtyRect,
                             const nsRect& aBorderArea,
-                            const nsStyleBorder& aStyleBorder,
                             nsStyleContext* aStyleContext,
                             PRIntn aSkipSides)
 {
+  nsStyleContext *styleIfVisited = aStyleContext->GetStyleIfVisited();
+  const nsStyleBorder *styleBorder = aStyleContext->GetStyleBorder();
+  // Don't check RelevantLinkVisited here, since we want to take the
+  // same amount of time whether or not it's true.
+  if (!styleIfVisited) {
+    PaintBorderWithStyleBorder(aPresContext, aRenderingContext, aForFrame,
+                               aDirtyRect, aBorderArea, *styleBorder,
+                               aStyleContext, aSkipSides);
+    return;
+  }
+
+  nsStyleBorder newStyleBorder(*styleBorder);
+  NS_FOR_CSS_SIDES(side) {
+    newStyleBorder.SetBorderColor(side,
+      aStyleContext->GetVisitedDependentColor(
+        nsCSSProps::SubpropertyEntryFor(eCSSProperty_border_color)[side]));
+  }
+  PaintBorderWithStyleBorder(aPresContext, aRenderingContext, aForFrame,
+                             aDirtyRect, aBorderArea, newStyleBorder,
+                             aStyleContext, aSkipSides);
+}
+
+void
+nsCSSRendering::PaintBorderWithStyleBorder(nsPresContext* aPresContext,
+                                           nsIRenderingContext& aRenderingContext,
+                                           nsIFrame* aForFrame,
+                                           const nsRect& aDirtyRect,
+                                           const nsRect& aBorderArea,
+                                           const nsStyleBorder& aStyleBorder,
+                                           nsStyleContext* aStyleContext,
+                                           PRIntn aSkipSides)
+{
   nsMargin            border;
   nscoord             twipsRadii[8];
   nsCompatibility     compatMode = aPresContext->CompatibilityMode();
 
   SN("++ PaintBorder");
 
   // Check to see if we have an appearance defined.  If so, we let the theme
   // renderer draw the border.  DO not get the data from aForFrame, since the passed in style context
@@ -570,17 +602,18 @@ nsCSSRendering::PaintBorder(nsPresContex
   
   // Get our style context's color struct.
   const nsStyleColor* ourColor = aStyleContext->GetStyleColor();
 
   // in NavQuirks mode we want to use the parent's context as a starting point
   // for determining the background color
   nsStyleContext* bgContext = nsCSSRendering::FindNonTransparentBackground
     (aStyleContext, compatMode == eCompatibility_NavQuirks ? PR_TRUE : PR_FALSE);
-  const nsStyleBackground* bgColor = bgContext->GetStyleBackground();
+  nscolor bgColor =
+    bgContext->GetVisitedDependentColor(eCSSProperty_background_color);
 
   border = aStyleBorder.GetComputedBorder();
   if ((0 == border.left) && (0 == border.right) &&
       (0 == border.top) && (0 == border.bottom)) {
     // Empty border area
     return;
   }
 
@@ -654,17 +687,17 @@ nsCSSRendering::PaintBorder(nsPresContex
                          ctx,
                          oRect,
                          borderStyles,
                          borderWidths,
                          borderRadii,
                          borderColors,
                          compositeColors,
                          aSkipSides,
-                         bgColor->mBackgroundColor);
+                         bgColor);
   br.DrawBorders();
 
   ctx->Restore();
 
   SN();
 }
 
 static nsRect
@@ -678,39 +711,39 @@ GetOutlineInnerRect(nsIFrame* aFrame)
 }
 
 void
 nsCSSRendering::PaintOutline(nsPresContext* aPresContext,
                              nsIRenderingContext& aRenderingContext,
                              nsIFrame* aForFrame,
                              const nsRect& aDirtyRect,
                              const nsRect& aBorderArea,
-                             const nsStyleBorder& aStyleBorder,
-                             const nsStyleOutline& aOutlineStyle,
                              nsStyleContext* aStyleContext)
 {
   nscoord             twipsRadii[8];
 
   // Get our style context's color struct.
   const nsStyleColor* ourColor = aStyleContext->GetStyleColor();
+  const nsStyleOutline* ourOutline = aStyleContext->GetStyleOutline();
 
   nscoord width;
-  aOutlineStyle.GetOutlineWidth(width);
+  ourOutline->GetOutlineWidth(width);
 
   if (width == 0) {
     // Empty outline
     return;
   }
 
   nsStyleContext* bgContext = nsCSSRendering::FindNonTransparentBackground
     (aStyleContext, PR_FALSE);
-  const nsStyleBackground* bgColor = bgContext->GetStyleBackground();
+  nscolor bgColor =
+    bgContext->GetVisitedDependentColor(eCSSProperty_background_color);
 
   // get the radius for our outline
-  GetBorderRadiusTwips(aOutlineStyle.mOutlineRadius, aBorderArea.width,
+  GetBorderRadiusTwips(ourOutline->mOutlineRadius, aBorderArea.width,
                        twipsRadii);
 
   // When the outline property is set on :-moz-anonymous-block or
   // :-moz-anonyomus-positioned-block pseudo-elements, it inherited that
   // outline from the inline that was broken because it contained a
   // block.  In that case, we don't want a really wide outline if the
   // block inside the inline is narrow, so union the actual contents of
   // the anonymous blocks.
@@ -735,17 +768,17 @@ nsCSSRendering::PaintOutline(nsPresConte
       // the border.
       nsRect r(GetOutlineInnerRect(frameForArea) +
                frameForArea->GetOffsetTo(aForFrame));
       innerRect.UnionRect(innerRect, r);
     }
   }
 
   innerRect += aBorderArea.TopLeft();
-  nscoord offset = aOutlineStyle.mOutlineOffset;
+  nscoord offset = ourOutline->mOutlineOffset;
   innerRect.Inflate(offset, offset);
   // If the dirty rect is completely inside the border area (e.g., only the
   // content is being painted), then we can skip out now
   // XXX this isn't exactly true for rounded borders, where the inside curves may
   // encroach into the content area.  A safer calculation would be to
   // shorten insideRect by the radius one each side before performing this test.
   if (innerRect.Contains(aDirtyRect))
     return;
@@ -760,27 +793,26 @@ nsCSSRendering::PaintOutline(nsPresConte
   gfxRect oRect(RectToGfxRect(outerRect, twipsPerPixel));
 
   // convert the radii
   nsMargin outlineMargin(width, width, width, width);
   gfxCornerSizes outlineRadii;
   ComputePixelRadii(twipsRadii, outerRect, 0, twipsPerPixel,
                     &outlineRadii);
 
-  PRUint8 outlineStyle = aOutlineStyle.GetOutlineStyle();
+  PRUint8 outlineStyle = ourOutline->GetOutlineStyle();
   PRUint8 outlineStyles[4] = { outlineStyle,
                                outlineStyle,
                                outlineStyle,
                                outlineStyle };
 
-  nscolor outlineColor;
-  // PR_FALSE means use the initial color; PR_TRUE means a color was
-  // set.
-  if (!aOutlineStyle.GetOutlineColor(outlineColor))
-    outlineColor = ourColor->mColor;
+  // This handles treating the initial color as 'currentColor'; if we
+  // ever want 'invert' back we'll need to do a bit of work here too.
+  nscolor outlineColor =
+    aStyleContext->GetVisitedDependentColor(eCSSProperty_outline_color);
   nscolor outlineColors[4] = { outlineColor,
                                outlineColor,
                                outlineColor,
                                outlineColor };
 
   // convert the border widths
   gfxFloat outlineWidths[4] = { width / twipsPerPixel,
                                 width / twipsPerPixel,
@@ -795,17 +827,17 @@ nsCSSRendering::PaintOutline(nsPresConte
   nsCSSBorderRenderer br(twipsPerPixel,
                          ctx,
                          oRect,
                          outlineStyles,
                          outlineWidths,
                          outlineRadii,
                          outlineColors,
                          nsnull, 0,
-                         bgColor->mBackgroundColor);
+                         bgColor);
   br.DrawBorders();
 
   ctx->Restore();
 
   SN();
 }
 
 void
@@ -921,16 +953,18 @@ nsCSSRendering::FindNonTransparentBackgr
     context = aContext->GetParent();
   }
   if (!context) {
     context = aContext;
   }
   
   while (context) {
     const nsStyleBackground* bg = context->GetStyleBackground();
+    // No need to call GetVisitedDependentColor because it always uses
+    // this alpha component anyway.
     if (NS_GET_A(bg->mBackgroundColor) > 0)
       break;
 
     const nsStyleDisplay* display = context->GetStyleDisplay();
     if (display->mAppearance)
       break;
 
     nsStyleContext* parent = context->GetParent();
@@ -1017,32 +1051,32 @@ nsCSSRendering::FindBackgroundStyleFrame
  *  + we don't paint the background on the root element, and
  *  + we don't paint the background on the BODY element in *some* cases,
  *    and for SGML-based HTML documents only.
  *
  * |FindBackground| returns true if a background should be painted, and
  * the resulting style context to use for the background information
  * will be filled in to |aBackground|.
  */
-const nsStyleBackground*
+nsStyleContext*
 nsCSSRendering::FindRootFrameBackground(nsIFrame* aForFrame)
 {
-  return FindBackgroundStyleFrame(aForFrame)->GetStyleBackground();
+  return FindBackgroundStyleFrame(aForFrame)->GetStyleContext();
 }
 
 inline PRBool
 FindElementBackground(nsIFrame* aForFrame, nsIFrame* aRootElementFrame,
-                      const nsStyleBackground** aBackground)
+                      nsStyleContext** aBackgroundSC)
 {
   if (aForFrame == aRootElementFrame) {
     // We must have propagated our background to the viewport or canvas. Abort.
     return PR_FALSE;
   }
 
-  *aBackground = aForFrame->GetStyleBackground();
+  *aBackgroundSC = aForFrame->GetStyleContext();
 
   // Return true unless the frame is for a BODY element whose background
   // was propagated to the viewport.
 
   nsIContent* content = aForFrame->GetContent();
   if (!content || content->Tag() != nsGkAtoms::body)
     return PR_TRUE; // not frame for a "body" element
   // It could be a non-HTML "body" element but that's OK, we'd fail the
@@ -1069,25 +1103,25 @@ FindElementBackground(nsIFrame* aForFram
 
   const nsStyleBackground* htmlBG = aRootElementFrame->GetStyleBackground();
   return !htmlBG->IsTransparent();
 }
 
 PRBool
 nsCSSRendering::FindBackground(nsPresContext* aPresContext,
                                nsIFrame* aForFrame,
-                               const nsStyleBackground** aBackground)
+                               nsStyleContext** aBackgroundSC)
 {
   nsIFrame* rootElementFrame =
     aPresContext->PresShell()->FrameConstructor()->GetRootElementStyleFrame();
   if (IsCanvasFrame(aForFrame)) {
-    *aBackground = FindCanvasBackground(aForFrame, rootElementFrame);
+    *aBackgroundSC = FindCanvasBackground(aForFrame, rootElementFrame);
     return PR_TRUE;
   } else {
-    return FindElementBackground(aForFrame, rootElementFrame, aBackground);
+    return FindElementBackground(aForFrame, rootElementFrame, aBackgroundSC);
   }
 }
 
 void
 nsCSSRendering::DidPaint()
 {
   gInlineBGData->Reset();
 }
@@ -1382,37 +1416,37 @@ nsCSSRendering::PaintBackground(nsPresCo
                                 const nsRect& aDirtyRect,
                                 const nsRect& aBorderArea,
                                 PRUint32 aFlags,
                                 nsRect* aBGClipRect)
 {
   NS_PRECONDITION(aForFrame,
                   "Frame is expected to be provided to PaintBackground");
 
-  const nsStyleBackground *background;
-  if (!FindBackground(aPresContext, aForFrame, &background)) {
+  nsStyleContext *sc;
+  if (!FindBackground(aPresContext, aForFrame, &sc)) {
     // We don't want to bail out if moz-appearance is set on a root
     // node. If it has a parent content node, bail because it's not
     // a root, other wise keep going in order to let the theme stuff
     // draw the background. The canvas really should be drawing the
     // bg, but there's no way to hook that up via css.
     if (!aForFrame->GetStyleDisplay()->mAppearance) {
       return;
     }
 
     nsIContent* content = aForFrame->GetContent();
     if (!content || content->GetParent()) {
       return;
     }
 
-    background = aForFrame->GetStyleBackground();
+    sc = aForFrame->GetStyleContext();
   }
 
   PaintBackgroundWithSC(aPresContext, aRenderingContext, aForFrame,
-                        aDirtyRect, aBorderArea, *background,
+                        aDirtyRect, aBorderArea, sc,
                         *aForFrame->GetStyleBorder(), aFlags,
                         aBGClipRect);
 }
 
 static PRBool
 IsOpaqueBorderEdge(const nsStyleBorder& aBorder, PRUint32 aSide)
 {
   if (aBorder.GetActualBorder().side(aSide) == 0)
@@ -1543,58 +1577,60 @@ SetupBackgroundClip(gfxContext *aCtx, PR
     aCtx->NewPath();
     aCtx->RoundedRectangle(bgAreaGfx, clippedRadii, radiiAreOuter);
     aCtx->Clip();
   }
 }
 
 static nscolor
 DetermineBackgroundColorInternal(nsPresContext* aPresContext,
-                                 const nsStyleBackground& aBackground,
+                                 nsStyleContext* aStyleContext,
                                  nsIFrame* aFrame,
                                  PRBool& aDrawBackgroundImage,
                                  PRBool& aDrawBackgroundColor)
 {
   aDrawBackgroundImage = PR_TRUE;
   aDrawBackgroundColor = PR_TRUE;
 
   if (aFrame->HonorPrintBackgroundSettings()) {
     aDrawBackgroundImage = aPresContext->GetBackgroundImageDraw();
     aDrawBackgroundColor = aPresContext->GetBackgroundColorDraw();
   }
 
   nscolor bgColor;
   if (aDrawBackgroundColor) {
-    bgColor = aBackground.mBackgroundColor;
+    bgColor =
+      aStyleContext->GetVisitedDependentColor(eCSSProperty_background_color);
     if (NS_GET_A(bgColor) == 0)
       aDrawBackgroundColor = PR_FALSE;
   } else {
     // If GetBackgroundColorDraw() is false, we are still expected to
     // draw color in the background of any frame that's not completely
     // transparent, but we are expected to use white instead of whatever
     // color was specified.
     bgColor = NS_RGB(255, 255, 255);
-    if (aDrawBackgroundImage || !aBackground.IsTransparent())
+    if (aDrawBackgroundImage ||
+        !aStyleContext->GetStyleBackground()->IsTransparent())
       aDrawBackgroundColor = PR_TRUE;
     else
       bgColor = NS_RGBA(0,0,0,0);
   }
 
   return bgColor;
 }
 
 nscolor
 nsCSSRendering::DetermineBackgroundColor(nsPresContext* aPresContext,
-                                         const nsStyleBackground& aBackground,
+                                         nsStyleContext* aStyleContext,
                                          nsIFrame* aFrame)
 {
   PRBool drawBackgroundImage;
   PRBool drawBackgroundColor;
   return DetermineBackgroundColorInternal(aPresContext,
-                                          aBackground,
+                                          aStyleContext,
                                           aFrame,
                                           drawBackgroundImage,
                                           drawBackgroundColor);
 }
 
 static gfxFloat
 ConvertGradientValueToPixels(const nsStyleCoord& aCoord,
                              gfxFloat aFillLength,
@@ -2057,17 +2093,17 @@ nsCSSRendering::PaintGradient(nsPresCont
 }
 
 void
 nsCSSRendering::PaintBackgroundWithSC(nsPresContext* aPresContext,
                                       nsIRenderingContext& aRenderingContext,
                                       nsIFrame* aForFrame,
                                       const nsRect& aDirtyRect,
                                       const nsRect& aBorderArea,
-                                      const nsStyleBackground& aBackground,
+                                      nsStyleContext* aBackgroundSC,
                                       const nsStyleBorder& aBorder,
                                       PRUint32 aFlags,
                                       nsRect* aBGClipRect)
 {
   NS_PRECONDITION(aForFrame,
                   "Frame is expected to be provided to PaintBackground");
 
   // Check to see if we have an appearance defined.  If so, we let the theme
@@ -2093,17 +2129,17 @@ nsCSSRendering::PaintBackgroundWithSC(ns
   PRBool isCanvasFrame = IsCanvasFrame(aForFrame);
 
   // Determine whether we are drawing background images and/or
   // background colors.
   PRBool drawBackgroundImage;
   PRBool drawBackgroundColor;
 
   nscolor bgColor = DetermineBackgroundColorInternal(aPresContext,
-                                                     aBackground,
+                                                     aBackgroundSC,
                                                      aForFrame,
                                                      drawBackgroundImage,
                                                      drawBackgroundColor);
 
   // At this point, drawBackgroundImage and drawBackgroundColor are
   // true if and only if we are actually supposed to paint an image or
   // color into aDirtyRect, respectively.
   if (!drawBackgroundImage && !drawBackgroundColor)
@@ -2127,16 +2163,17 @@ nsCSSRendering::PaintBackgroundWithSC(ns
   }
   
   // The 'bgClipArea' (used only by the image tiling logic, far below)
   // is the caller-provided aBGClipRect if any, or else the area
   // determined by the value of 'background-clip' in
   // SetupCurrentBackgroundClip.  (Arguably it should be the
   // intersection, but that breaks the table painter -- in particular,
   // taking the intersection breaks reftests/bugs/403249-1[ab].)
+  const nsStyleBackground *bg = aBackgroundSC->GetStyleBackground();
   nsRect bgClipArea, dirtyRect;
   gfxRect dirtyRectGfx;
   PRUint8 currentBackgroundClip;
   PRBool isSolidBorder;
   gfxContextAutoSaveRestore autoSR;
   if (aBGClipRect) {
     bgClipArea = *aBGClipRect;
     SetupDirtyRects(bgClipArea, aDirtyRect, appUnitsPerPixel,
@@ -2145,17 +2182,17 @@ nsCSSRendering::PaintBackgroundWithSC(ns
     // The background is rendered over the 'background-clip' area,
     // which is normally equal to the border area but may be reduced
     // to the padding area by CSS.  Also, if the border is solid, we
     // don't need to draw outside the padding area.  In either case,
     // if the borders are rounded, make sure we use the same inner
     // radii as the border code will.
     // The background-color is drawn based on the bottom
     // background-clip.
-    currentBackgroundClip = aBackground.BottomLayer().mClip;
+    currentBackgroundClip = bg->BottomLayer().mClip;
     isSolidBorder =
       (aFlags & PAINTBG_WILL_PAINT_BORDER) && IsOpaqueBorder(aBorder);
     if (isSolidBorder)
       currentBackgroundClip = NS_STYLE_BG_CLIP_PADDING;
     SetupBackgroundClip(ctx, currentBackgroundClip, aForFrame,
                         aBorderArea, aDirtyRect, haveRoundedCorners,
                         bgRadii, appUnitsPerPixel, &autoSR,
                         &bgClipArea, &dirtyRect, &dirtyRectGfx);
@@ -2175,51 +2212,51 @@ nsCSSRendering::PaintBackgroundWithSC(ns
       ctx->Fill();
     }
     return;
   }
 
   // Ensure we get invalidated for loads of the image.  We need to do
   // this here because this might be the only code that knows about the
   // association of the style data with the frame.
-  aPresContext->SetupBackgroundImageLoaders(aForFrame, &aBackground);
+  aPresContext->SetupBackgroundImageLoaders(aForFrame, bg);
 
   // We can skip painting the background color if a background image is opaque.
   if (drawBackgroundColor &&
-      aBackground.BottomLayer().mRepeat == NS_STYLE_BG_REPEAT_XY &&
-      aBackground.BottomLayer().mImage.IsOpaque())
+      bg->BottomLayer().mRepeat == NS_STYLE_BG_REPEAT_XY &&
+      bg->BottomLayer().mImage.IsOpaque())
     drawBackgroundColor = PR_FALSE;
 
   // The background color is rendered over the entire dirty area,
   // even if the image isn't.
   if (drawBackgroundColor && !isCanvasFrame) {
     if (!dirtyRectGfx.IsEmpty()) {
       ctx->NewPath();
       ctx->Rectangle(dirtyRectGfx, PR_TRUE);
       ctx->Fill();
     }
   }
 
   if (drawBackgroundImage) {
-    NS_FOR_VISIBLE_BACKGROUND_LAYERS_BACK_TO_FRONT(i, &aBackground) {
-      const nsStyleBackground::Layer &layer = aBackground.mLayers[i];
+    NS_FOR_VISIBLE_BACKGROUND_LAYERS_BACK_TO_FRONT(i, bg) {
+      const nsStyleBackground::Layer &layer = bg->mLayers[i];
       if (!aBGClipRect) {
         PRUint8 newBackgroundClip =
           isSolidBorder ? NS_STYLE_BG_CLIP_PADDING : layer.mClip;
         if (currentBackgroundClip != newBackgroundClip) {
           currentBackgroundClip = newBackgroundClip;
           SetupBackgroundClip(ctx, currentBackgroundClip, aForFrame,
                               aBorderArea, aDirtyRect, haveRoundedCorners,
                               bgRadii, appUnitsPerPixel, &autoSR,
                               &bgClipArea, &dirtyRect, &dirtyRectGfx);
         }
       }
       if (!dirtyRectGfx.IsEmpty()) {
         PaintBackgroundLayer(aPresContext, aRenderingContext, aForFrame, aFlags,
-                             dirtyRect, aBorderArea, bgClipArea, aBackground,
+                             dirtyRect, aBorderArea, bgClipArea, *bg,
                              layer);
       }
     }
   }
 }
 
 static inline float
 ScaleDimension(nsStyleBackground::Size::Dimension aDimension,
@@ -3009,16 +3046,18 @@ nsCSSRendering::DrawTableBorderSegment(n
                              aEndBevelSide, aEndBevelOffset);
     }
     else {
       nscoord startBevel = (aStartBevelOffset > 0) 
                             ? RoundFloatToPixel(0.5f * (float)aStartBevelOffset, twipsPerPixel, PR_TRUE) : 0;
       nscoord endBevel =   (aEndBevelOffset > 0) 
                             ? RoundFloatToPixel(0.5f * (float)aEndBevelOffset, twipsPerPixel, PR_TRUE) : 0;
       PRUint8 ridgeGrooveSide = (horizontal) ? NS_SIDE_TOP : NS_SIDE_LEFT;
+      // FIXME: In theory, this should use the visited-dependent
+      // background color, but I don't care.
       aContext.SetColor ( 
         MakeBevelColor(ridgeGrooveSide, ridgeGroove, aBGColor->mBackgroundColor, aBorderColor));
       nsRect rect(aBorder);
       nscoord half;
       if (horizontal) { // top, bottom
         half = RoundFloatToPixel(0.5f * (float)aBorder.height, twipsPerPixel);
         rect.height = half;
         if (NS_SIDE_TOP == aStartBevelSide) {
@@ -3042,16 +3081,18 @@ nsCSSRendering::DrawTableBorderSegment(n
           rect.height -= endBevel;
         }
         DrawSolidBorderSegment(aContext, rect, twipsPerPixel, aStartBevelSide, 
                                startBevel, aEndBevelSide, endBevel);
       }
 
       rect = aBorder;
       ridgeGrooveSide = (NS_SIDE_TOP == ridgeGrooveSide) ? NS_SIDE_BOTTOM : NS_SIDE_RIGHT;
+      // FIXME: In theory, this should use the visited-dependent
+      // background color, but I don't care.
       aContext.SetColor ( 
         MakeBevelColor(ridgeGrooveSide, ridgeGroove, aBGColor->mBackgroundColor, aBorderColor));
       if (horizontal) {
         rect.y = rect.y + half;
         rect.height = aBorder.height - half;
         if (NS_SIDE_BOTTOM == aStartBevelSide) {
           rect.x += startBevel;
           rect.width -= startBevel;
--- a/layout/base/nsCSSRendering.h
+++ b/layout/base/nsCSSRendering.h
@@ -90,35 +90,46 @@ struct nsCSSRendering {
    * Both aDirtyRect and aBorderArea are in the local coordinate space
    * of aForFrame
    */
   static void PaintBorder(nsPresContext* aPresContext,
                           nsIRenderingContext& aRenderingContext,
                           nsIFrame* aForFrame,
                           const nsRect& aDirtyRect,
                           const nsRect& aBorderArea,
-                          const nsStyleBorder& aBorderStyle,
                           nsStyleContext* aStyleContext,
                           PRIntn aSkipSides = 0);
 
   /**
+   * Like PaintBorder, but taking an nsStyleBorder argument instead of
+   * getting it from aStyleContext.
+   */
+  static void PaintBorderWithStyleBorder(nsPresContext* aPresContext,
+                                         nsIRenderingContext& aRenderingContext,
+                                         nsIFrame* aForFrame,
+                                         const nsRect& aDirtyRect,
+                                         const nsRect& aBorderArea,
+                                         const nsStyleBorder& aBorderStyle,
+                                         nsStyleContext* aStyleContext,
+                                         PRIntn aSkipSides = 0);
+
+
+  /**
    * Render the outline for an element using css rendering rules
    * for borders. aSkipSides is a bitmask of the sides to skip
    * when rendering. If 0 then no sides are skipped.
    *
    * Both aDirtyRect and aBorderArea are in the local coordinate space
    * of aForFrame
    */
   static void PaintOutline(nsPresContext* aPresContext,
                           nsIRenderingContext& aRenderingContext,
                           nsIFrame* aForFrame,
                           const nsRect& aDirtyRect,
                           const nsRect& aBorderArea,
-                          const nsStyleBorder& aBorderStyle,
-                          const nsStyleOutline& aOutlineStyle,
                           nsStyleContext* aStyleContext);
 
   /**
    * Render keyboard focus on an element.
    * |aFocusRect| is the outer rectangle of the focused element.
    * Uses a fixed style equivalent to "1px dotted |aColor|".
    * Not used for controls, because the native theme may differ.
    */
@@ -147,54 +158,54 @@ struct nsCSSRendering {
   static nsIFrame* FindBackgroundStyleFrame(nsIFrame* aForFrame);
 
   /**
    * @return PR_TRUE if |aFrame| is a canvas frame, in the CSS sense.
    */
   static PRBool IsCanvasFrame(nsIFrame* aFrame);
 
   /**
-   * Fill in an nsStyleBackground to be used to paint the background
+   * Fill in an aBackgroundSC to be used to paint the background
    * for an element.  This applies the rules for propagating
    * backgrounds between BODY, the root element, and the canvas.
    * @return PR_TRUE if there is some meaningful background.
    */
   static PRBool FindBackground(nsPresContext* aPresContext,
                                nsIFrame* aForFrame,
-                               const nsStyleBackground** aBackground);
+                               nsStyleContext** aBackgroundSC);
 
   /**
    * As FindBackground, but the passed-in frame is known to be a root frame
    * (returned from nsCSSFrameConstructor::GetRootElementStyleFrame())
    * and there is always some meaningful background returned.
    */
-  static const nsStyleBackground* FindRootFrameBackground(nsIFrame* aForFrame);
+  static nsStyleContext* FindRootFrameBackground(nsIFrame* aForFrame);
 
   /**
    * Returns background style information for the canvas.
    *
    * @param aForFrame
    *   the frame used to represent the canvas, in the CSS sense (i.e.
    *   nsCSSRendering::IsCanvasFrame(aForFrame) must be true)
    * @param aRootElementFrame
    *   the frame representing the root element of the document
    * @param aBackground
    *   contains background style information for the canvas on return
    */
-  static const nsStyleBackground*
+  static nsStyleContext*
   FindCanvasBackground(nsIFrame* aForFrame, nsIFrame* aRootElementFrame)
   {
     NS_ABORT_IF_FALSE(IsCanvasFrame(aForFrame), "not a canvas frame");
     if (aRootElementFrame)
       return FindRootFrameBackground(aRootElementFrame);
 
     // This should always give transparent, so we'll fill it in with the
     // default color if needed.  This seems to happen a bit while a page is
     // being loaded.
-    return aForFrame->GetStyleBackground();
+    return aForFrame->GetStyleContext();
   }
 
   /**
    * Find a style context containing a non-transparent background,
    * for various table-related and HR-related backwards-compatibility hacks.
    * This function will also stop if it finds a -moz-appearance value, as
    * the theme may draw a widget as a background.
    *
@@ -205,17 +216,17 @@ struct nsCSSRendering {
   FindNonTransparentBackground(nsStyleContext* aContext,
                                PRBool aStartAtParent = PR_FALSE);
 
   /**
    * Determine the background color to draw taking into account print settings.
    */
   static nscolor
   DetermineBackgroundColor(nsPresContext* aPresContext,
-                           const nsStyleBackground& aBackground,
+                           nsStyleContext* aStyleContext,
                            nsIFrame* aFrame);
 
   /**
    * Render the background for an element using css rendering rules
    * for backgrounds.
    *
    * Both aDirtyRect and aBorderArea are in the local coordinate space
    * of aForFrame
@@ -243,17 +254,17 @@ struct nsCSSRendering {
    * This short-circuits the code that ensures that the root element's
    * background is drawn on the canvas.
    */
   static void PaintBackgroundWithSC(nsPresContext* aPresContext,
                                     nsIRenderingContext& aRenderingContext,
                                     nsIFrame* aForFrame,
                                     const nsRect& aDirtyRect,
                                     const nsRect& aBorderArea,
-                                    const nsStyleBackground& aBackground,
+                                    nsStyleContext *aStyleContext,
                                     const nsStyleBorder& aBorder,
                                     PRUint32 aFlags,
                                     nsRect* aBGClipRect = nsnull);
 
   /**
    * Called by the presShell when painting is finished, so we can clear our
    * inline background data cache.
    */
--- a/layout/base/nsDisplayList.cpp
+++ b/layout/base/nsDisplayList.cpp
@@ -873,23 +873,16 @@ nsDisplayItem* nsDisplayList::RemoveBott
   if (item == mTop) {
     // must have been the only item
     mTop = &mSentinel;
   }
   item->mAbove = nsnull;
   return item;
 }
 
-void nsDisplayList::DeleteBottom() {
-  nsDisplayItem* item = RemoveBottom();
-  if (item) {
-    item->~nsDisplayItem();
-  }
-}
-
 void nsDisplayList::DeleteAll() {
   nsDisplayItem* item;
   while ((item = RemoveBottom()) != nsnull) {
     item->~nsDisplayItem();
   }
 }
 
 nsIFrame* nsDisplayList::HitTest(nsDisplayListBuilder* aBuilder, nsPoint aPt,
@@ -1067,20 +1060,20 @@ static PRBool RoundedRectContainsRect(co
 }
 
 PRBool
 nsDisplayBackground::IsOpaque(nsDisplayListBuilder* aBuilder) {
   // theme background overrides any other background
   if (mIsThemed)
     return PR_FALSE;
 
-  const nsStyleBackground* bg;
-
-  if (!nsCSSRendering::FindBackground(mFrame->PresContext(), mFrame, &bg))
+  nsStyleContext *bgSC;
+  if (!nsCSSRendering::FindBackground(mFrame->PresContext(), mFrame, &bgSC))
     return PR_FALSE;
+  const nsStyleBackground* bg = bgSC->GetStyleBackground();
 
   const nsStyleBackground::Layer& bottomLayer = bg->BottomLayer();
 
   // bottom layer's clip is used for the color
   if (bottomLayer.mClip != NS_STYLE_BG_CLIP_BORDER ||
       nsLayoutUtils::HasNonZeroCorner(mFrame->GetStyleBorder()->mBorderRadius))
     return PR_FALSE;
 
@@ -1093,41 +1086,43 @@ nsDisplayBackground::IsOpaque(nsDisplayL
 }
 
 PRBool
 nsDisplayBackground::IsUniform(nsDisplayListBuilder* aBuilder) {
   // theme background overrides any other background
   if (mIsThemed)
     return PR_FALSE;
 
-  const nsStyleBackground* bg;
+  nsStyleContext *bgSC;
   PRBool hasBG =
-    nsCSSRendering::FindBackground(mFrame->PresContext(), mFrame, &bg);
+    nsCSSRendering::FindBackground(mFrame->PresContext(), mFrame, &bgSC);
   if (!hasBG)
     return PR_TRUE;
+  const nsStyleBackground* bg = bgSC->GetStyleBackground();
   if (bg->BottomLayer().mImage.IsEmpty() &&
       bg->mImageCount == 1 &&
       !nsLayoutUtils::HasNonZeroCorner(mFrame->GetStyleBorder()->mBorderRadius) &&
       bg->BottomLayer().mClip == NS_STYLE_BG_CLIP_BORDER)
     return PR_TRUE;
   return PR_FALSE;
 }
 
 PRBool
 nsDisplayBackground::IsVaryingRelativeToMovingFrame(nsDisplayListBuilder* aBuilder)
 {
   NS_ASSERTION(aBuilder->IsMovingFrame(mFrame),
               "IsVaryingRelativeToMovingFrame called on non-moving frame!");
 
   nsPresContext* presContext = mFrame->PresContext();
-  const nsStyleBackground* bg;
+  nsStyleContext *bgSC;
   PRBool hasBG =
-    nsCSSRendering::FindBackground(presContext, mFrame, &bg);
+    nsCSSRendering::FindBackground(mFrame->PresContext(), mFrame, &bgSC);
   if (!hasBG)
     return PR_FALSE;
+  const nsStyleBackground* bg = bgSC->GetStyleBackground();
   if (!bg->HasFixedBackground())
     return PR_FALSE;
 
   nsIFrame* movingFrame = aBuilder->GetRootMovingFrame();
   // movingFrame is the frame that is going to be moved. It must be equal
   // to mFrame or some ancestor of mFrame, see assertion above.
   // If mFrame is in the same document as movingFrame, then mFrame
   // will move relative to its viewport, which means this display item will
@@ -1168,18 +1163,16 @@ nsDisplayOutline::GetBounds(nsDisplayLis
 void
 nsDisplayOutline::Paint(nsDisplayListBuilder* aBuilder,
                         nsIRenderingContext* aCtx) {
   // TODO join outlines together
   nsPoint offset = aBuilder->ToReferenceFrame(mFrame);
   nsCSSRendering::PaintOutline(mFrame->PresContext(), *aCtx, mFrame,
                                mVisibleRect,
                                nsRect(offset, mFrame->GetSize()),
-                               *mFrame->GetStyleBorder(),
-                               *mFrame->GetStyleOutline(),
                                mFrame->GetStyleContext());
 }
 
 PRBool
 nsDisplayOutline::ComputeVisibility(nsDisplayListBuilder* aBuilder,
                                     nsRegion* aVisibleRegion,
                                     nsRegion* aVisibleRegionBeforeMove) {
   NS_ASSERTION((aVisibleRegionBeforeMove != nsnull) == aBuilder->HasMovingFrames(),
@@ -1246,17 +1239,16 @@ nsDisplayBorder::ComputeVisibility(nsDis
 
 void
 nsDisplayBorder::Paint(nsDisplayListBuilder* aBuilder,
                        nsIRenderingContext* aCtx) {
   nsPoint offset = aBuilder->ToReferenceFrame(mFrame);
   nsCSSRendering::PaintBorder(mFrame->PresContext(), *aCtx, mFrame,
                               mVisibleRect,
                               nsRect(offset, mFrame->GetSize()),
-                              *mFrame->GetStyleBorder(),
                               mFrame->GetStyleContext(),
                               mFrame->GetSkipSides());
 }
 
 // Given a region, compute a conservative approximation to it as a list
 // of rectangles that aren't vertically adjacent (i.e., vertically
 // adjacent or overlapping rectangles are combined).
 // Right now this is only approximate, some vertically overlapping rectangles
--- a/layout/base/nsDisplayList.h
+++ b/layout/base/nsDisplayList.h
@@ -763,20 +763,16 @@ public:
   }
   
   /**
    * Remove an item from the bottom of the list and return it.
    */
   nsDisplayItem* RemoveBottom();
   
   /**
-   * Remove an item from the bottom of the list and call its destructor.
-   */
-  void DeleteBottom();
-  /**
    * Remove all items from the list and call their destructors.
    */
   void DeleteAll();
   
   /**
    * @return the item at the top of the list, or null if the list is empty
    */
   nsDisplayItem* GetTop() const {
--- a/layout/base/nsFrameManager.cpp
+++ b/layout/base/nsFrameManager.cpp
@@ -256,41 +256,16 @@ nsFrameManager::Destroy()
   }
   
   delete mUndisplayedMap;
   mUndisplayedMap = nsnull;
 
   mPresShell = nsnull;
 }
 
-nsIFrame*
-nsFrameManager::GetCanvasFrame()
-{
-  if (mRootFrame) {
-    // walk the children of the root frame looking for a frame with type==canvas
-    // start at the root
-    nsIFrame* childFrame = mRootFrame;
-    while (childFrame) {
-      // get each sibling of the child and check them, startig at the child
-      nsIFrame *siblingFrame = childFrame;
-      while (siblingFrame) {
-        if (siblingFrame->GetType() == nsGkAtoms::canvasFrame) {
-          // this is it
-          return siblingFrame;
-        } else {
-          siblingFrame = siblingFrame->GetNextSibling();
-        }
-      }
-      // move on to the child's child
-      childFrame = childFrame->GetFirstChild(nsnull);
-    }
-  }
-  return nsnull;
-}
-
 //----------------------------------------------------------------------
 
 // Placeholder frame functions
 nsPlaceholderFrame*
 nsFrameManager::GetPlaceholderFrameFor(nsIFrame*  aFrame)
 {
   NS_PRECONDITION(aFrame, "null param unexpected");
 
@@ -487,29 +462,16 @@ nsFrameManager::ClearAllUndisplayedConte
       nsIContent* child = list->GetNodeAt(i);
       if (child->GetParent() != aParentContent) {
         ClearUndisplayedContentIn(child, child->GetParent());
       }
     }
   }
 }
 
-void
-nsFrameManager::ClearUndisplayedContentMap()
-{
-#ifdef DEBUG_UNDISPLAYED_MAP
-  static int i = 0;
-  printf("ClearUndisplayedContentMap(%d)\n", i++);
-#endif
-
-  if (mUndisplayedMap) {
-    mUndisplayedMap->Clear();
-  }
-}
-
 //----------------------------------------------------------------------
 
 nsresult
 nsFrameManager::InsertFrames(nsIFrame*       aParentFrame,
                              nsIAtom*        aListName,
                              nsIFrame*       aPrevFrame,
                              nsFrameList&    aFrameList)
 {
@@ -742,22 +704,18 @@ TryStartingTransition(nsPresContext *aPr
   // currently starting with their start value so we don't start
   // them again for descendants that inherit that value.
   nsCOMPtr<nsIStyleRule> coverRule = 
     aPresContext->TransitionManager()->StyleContextChanged(
       aContent, aOldStyleContext, *aNewStyleContext);
   if (coverRule) {
     nsCOMArray<nsIStyleRule> rules;
     rules.AppendObject(coverRule);
-    *aNewStyleContext = aPresContext->StyleSet()->ResolveStyleForRules(
-                     (*aNewStyleContext)->GetParent(),
-                     (*aNewStyleContext)->GetPseudo(),
-                     (*aNewStyleContext)->GetPseudoType(),
-                     (*aNewStyleContext)->GetRuleNode(),
-                     rules);
+    *aNewStyleContext = aPresContext->StyleSet()->
+                          ResolveStyleByAddingRules(*aNewStyleContext, rules);
   }
 }
 
 nsresult
 nsFrameManager::ReparentStyleContext(nsIFrame* aFrame)
 {
   if (nsGkAtoms::placeholderFrame == aFrame->GetType()) {
     // Also reparent the out-of-flow
--- a/layout/base/nsFrameManager.h
+++ b/layout/base/nsFrameManager.h
@@ -86,22 +86,16 @@ public:
 
   /*
    * After Destroy is called, it is an error to call any FrameManager methods.
    * Destroy should be called when the frame tree managed by the frame
    * manager is no longer being displayed.
    */
   NS_HIDDEN_(void) Destroy();
 
-  /*
-   * Get the canvas frame, searching from the root frame down.
-   * The canvas frame may or may not exist, so this may return null.
-   */
-  NS_HIDDEN_(nsIFrame*) GetCanvasFrame();
-
   // Placeholder frame functions
   NS_HIDDEN_(nsPlaceholderFrame*) GetPlaceholderFrameFor(nsIFrame* aFrame);
   NS_HIDDEN_(nsresult)
     RegisterPlaceholderFrame(nsPlaceholderFrame* aPlaceholderFrame);
 
   NS_HIDDEN_(void)
     UnregisterPlaceholderFrame(nsPlaceholderFrame* aPlaceholderFrame);
 
@@ -111,17 +105,16 @@ public:
   NS_HIDDEN_(nsStyleContext*) GetUndisplayedContent(nsIContent* aContent);
   NS_HIDDEN_(void) SetUndisplayedContent(nsIContent* aContent,
                                          nsStyleContext* aStyleContext);
   NS_HIDDEN_(void) ChangeUndisplayedContent(nsIContent* aContent,
                                             nsStyleContext* aStyleContext);
   NS_HIDDEN_(void) ClearUndisplayedContentIn(nsIContent* aContent,
                                              nsIContent* aParentContent);
   NS_HIDDEN_(void) ClearAllUndisplayedContentIn(nsIContent* aParentContent);
-  NS_HIDDEN_(void) ClearUndisplayedContentMap();
 
   // Functions for manipulating the frame model
   NS_HIDDEN_(nsresult) AppendFrames(nsIFrame*       aParentFrame,
                                     nsIAtom*        aListName,
                                     nsFrameList&    aFrameList)
   {
     return aParentFrame->AppendFrames(aListName, aFrameList);
   }
--- a/layout/base/nsIPresShell.h
+++ b/layout/base/nsIPresShell.h
@@ -736,21 +736,16 @@ public:
    */
   static PRBool GetVerifyReflowEnable();
 
   /**
    * Set the verify-reflow enable flag.
    */
   static void SetVerifyReflowEnable(PRBool aEnabled);
 
-  /**
-   * Get the flags associated with the VerifyReflow debug tool
-   */
-  static PRInt32 GetVerifyReflowFlags();
-
   virtual nsIFrame* GetAbsoluteContainingBlock(nsIFrame* aFrame);
 
 #ifdef MOZ_REFLOW_PERF
   virtual NS_HIDDEN_(void) DumpReflows() = 0;
   virtual NS_HIDDEN_(void) CountReflows(const char * aName, nsIFrame * aFrame) = 0;
   virtual NS_HIDDEN_(void) PaintCount(const char * aName,
                                       nsIRenderingContext* aRenderingContext,
                                       nsPresContext * aPresContext,
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -1755,73 +1755,16 @@ nsLayoutUtils::GetParentOrPlaceholderFor
   if ((aFrame->GetStateBits() & NS_FRAME_OUT_OF_FLOW)
       && !aFrame->GetPrevInFlow()) {
     return aFrameManager->GetPlaceholderFrameFor(aFrame);
   }
   return aFrame->GetParent();
 }
 
 nsIFrame*
-nsLayoutUtils::GetClosestCommonAncestorViaPlaceholders(nsIFrame* aFrame1,
-                                                       nsIFrame* aFrame2,
-                                                       nsIFrame* aKnownCommonAncestorHint)
-{
-  NS_PRECONDITION(aFrame1, "aFrame1 must not be null");
-  NS_PRECONDITION(aFrame2, "aFrame2 must not be null");
-
-  nsPresContext* presContext = aFrame1->PresContext();
-  if (presContext != aFrame2->PresContext()) {
-    // different documents, no common ancestor
-    return nsnull;
-  }
-  nsFrameManager* frameManager = presContext->PresShell()->FrameManager();
-
-  nsAutoTArray<nsIFrame*, 8> frame1Ancestors;
-  nsIFrame* f1;
-  for (f1 = aFrame1; f1 && f1 != aKnownCommonAncestorHint;
-       f1 = GetParentOrPlaceholderFor(frameManager, f1)) {
-    frame1Ancestors.AppendElement(f1);
-  }
-  if (!f1 && aKnownCommonAncestorHint) {
-    // So, it turns out aKnownCommonAncestorHint was not an ancestor of f1. Oops.
-    // Never mind. We can continue as if aKnownCommonAncestorHint was null.
-    aKnownCommonAncestorHint = nsnull;
-  }
-
-  nsAutoTArray<nsIFrame*, 8> frame2Ancestors;
-  nsIFrame* f2;
-  for (f2 = aFrame2; f2 && f2 != aKnownCommonAncestorHint;
-       f2 = GetParentOrPlaceholderFor(frameManager, f2)) {
-    frame2Ancestors.AppendElement(f2);
-  }
-  if (!f2 && aKnownCommonAncestorHint) {
-    // So, it turns out aKnownCommonAncestorHint was not an ancestor of f2.
-    // We need to retry with no common ancestor hint.
-    return GetClosestCommonAncestorViaPlaceholders(aFrame1, aFrame2, nsnull);
-  }
-
-  // now frame1Ancestors and frame2Ancestors give us the parent frame chain
-  // up to aKnownCommonAncestorHint, or if that is null, up to and including
-  // the root frame. We need to walk from the end (i.e., the top of the
-  // frame (sub)tree) down to aFrame1/aFrame2 looking for the first difference.
-  nsIFrame* lastCommonFrame = aKnownCommonAncestorHint;
-  PRInt32 last1 = frame1Ancestors.Length() - 1;
-  PRInt32 last2 = frame2Ancestors.Length() - 1;
-  while (last1 >= 0 && last2 >= 0) {
-    nsIFrame* frame1 = frame1Ancestors.ElementAt(last1);
-    if (frame1 != frame2Ancestors.ElementAt(last2))
-      break;
-    lastCommonFrame = frame1;
-    last1--;
-    last2--;
-  }
-  return lastCommonFrame;
-}
-
-nsIFrame*
 nsLayoutUtils::GetNextContinuationOrSpecialSibling(nsIFrame *aFrame)
 {
   nsIFrame *result = aFrame->GetNextContinuation();
   if (result)
     return result;
 
   if ((aFrame->GetStateBits() & NS_FRAME_IS_SPECIAL) != 0) {
     // We only store the "special sibling" annotation with the first
@@ -3254,21 +3197,22 @@ nsLayoutUtils::GetFrameTransparency(nsIF
   // We need an uninitialized window to be treated as opaque because
   // doing otherwise breaks window display effects on some platforms,
   // specifically Vista. (bug 450322)
   if (aBackgroundFrame->GetType() == nsGkAtoms::viewportFrame &&
       !aBackgroundFrame->GetFirstChild(nsnull)) {
     return eTransparencyOpaque;
   }
 
-  const nsStyleBackground* bg;
+  nsStyleContext* bgSC;
   if (!nsCSSRendering::FindBackground(aBackgroundFrame->PresContext(),
-                                      aBackgroundFrame, &bg)) {
+                                      aBackgroundFrame, &bgSC)) {
     return eTransparencyTransparent;
   }
+  const nsStyleBackground* bg = bgSC->GetStyleBackground();
   if (NS_GET_A(bg->mBackgroundColor) < 255 ||
       // bottom layer's clip is used for the color
       bg->BottomLayer().mClip != NS_STYLE_BG_CLIP_BORDER)
     return eTransparencyTransparent;
   return eTransparencyOpaque;
 }
 
 /* static */ PRBool
--- a/layout/base/nsLayoutUtils.h
+++ b/layout/base/nsLayoutUtils.h
@@ -725,30 +725,16 @@ public:
   /**
    * If aFrame is an out of flow frame, return its placeholder, otherwise
    * return its parent.
    */
   static nsIFrame* GetParentOrPlaceholderFor(nsFrameManager* aFrameManager,
                                              nsIFrame* aFrame);
 
   /**
-   * Find the closest common ancestor of aFrame1 and aFrame2, following
-   * out of flow frames to their placeholders instead of their parents. Returns
-   * nsnull if the frames are in different frame trees.
-   * 
-   * @param aKnownCommonAncestorHint a frame that is believed to be on the
-   * ancestor chain of both aFrame1 and aFrame2. If null, or a frame that is
-   * not in fact on both ancestor chains, then this function will still return
-   * the correct result, but it will be slower.
-   */
-  static nsIFrame*
-  GetClosestCommonAncestorViaPlaceholders(nsIFrame* aFrame1, nsIFrame* aFrame2,
-                                          nsIFrame* aKnownCommonAncestorHint);
-
-  /**
    * Get a frame's next-in-flow, or, if it doesn't have one, its special sibling.
    */
   static nsIFrame*
   GetNextContinuationOrSpecialSibling(nsIFrame *aFrame);
 
   /**
    * Get the first frame in the continuation-plus-special-sibling chain
    * containing aFrame.
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -1087,21 +1087,16 @@ protected:
   PRIntn mContentScrollVPosition;
   PRIntn mContentScrollHPosition;
 
   class nsDelayedEvent
   {
   public:
     virtual ~nsDelayedEvent() {};
     virtual void Dispatch(PresShell* aShell) {}
-    // This is needed only by nsDelayedFocusBlur.
-    virtual PRBool Equals(nsPIDOMEventTarget* aTarget, PRUint32 aEventType)
-    {
-      return PR_FALSE;
-    }
   };
 
   class nsDelayedInputEvent : public nsDelayedEvent
   {
   public:
     virtual void Dispatch(PresShell* aShell)
     {
       if (mEvent && mEvent->widget) {
@@ -1426,26 +1421,16 @@ nsIPresShell::GetVerifyReflowEnable()
 }
 
 void
 nsIPresShell::SetVerifyReflowEnable(PRBool aEnabled)
 {
   gVerifyReflowEnabled = aEnabled;
 }
 
-PRInt32
-nsIPresShell::GetVerifyReflowFlags()
-{
-#ifdef NS_DEBUG
-  return gVerifyReflowFlags;
-#else
-  return 0;
-#endif
-}
-
 /* virtual */ void
 nsIPresShell::AddWeakFrameExternal(nsWeakFrame* aWeakFrame)
 {
   AddWeakFrameInternal(aWeakFrame);
 }
 
 void
 nsIPresShell::AddWeakFrameInternal(nsWeakFrame* aWeakFrame)
@@ -5579,24 +5564,24 @@ nsresult PresShell::AddCanvasBackgroundC
 
 void PresShell::UpdateCanvasBackground()
 {
   // If we have a frame tree and it has style information that
   // specifies the background color of the canvas, update our local
   // cache of that color.
   nsIFrame* rootFrame = FrameConstructor()->GetRootElementStyleFrame();
   if (rootFrame) {
-    const nsStyleBackground* bgStyle =
+    nsStyleContext* bgStyle =
       nsCSSRendering::FindRootFrameBackground(rootFrame);
     // XXX We should really be passing the canvasframe, not the root element
     // style frame but we don't have access to the canvasframe here. It isn't
     // a problem because only a few frames can return something other than true
     // and none of them would be a canvas frame or root element style frame.
     mCanvasBackgroundColor =
-      nsCSSRendering::DetermineBackgroundColor(GetPresContext(), *bgStyle,
+      nsCSSRendering::DetermineBackgroundColor(GetPresContext(), bgStyle,
                                                rootFrame);
   }
 
   // If the root element of the document (ie html) has style 'display: none'
   // then the document's background color does not get drawn; cache the
   // color we actually draw.
   if (!FrameConstructor()->GetRootElementFrame()) {
     mCanvasBackgroundColor = mPresContext->DefaultBackgroundColor();
--- a/layout/forms/nsButtonFrameRenderer.cpp
+++ b/layout/forms/nsButtonFrameRenderer.cpp
@@ -229,29 +229,27 @@ nsButtonFrameRenderer::PaintOutlineAndFo
 
   nsRect rect;
 
   if (mOuterFocusStyle) {
     // ---------- paint the outer focus border -------------
 
     GetButtonOuterFocusRect(aRect, rect);
 
-    const nsStyleBorder* border = mOuterFocusStyle->GetStyleBorder();
     nsCSSRendering::PaintBorder(aPresContext, aRenderingContext, mFrame,
-                                aDirtyRect, rect, *border, mOuterFocusStyle);
+                                aDirtyRect, rect, mOuterFocusStyle);
   }
 
   if (mInnerFocusStyle) { 
     // ---------- paint the inner focus border -------------
 
     GetButtonInnerFocusRect(aRect, rect);
 
-    const nsStyleBorder* border = mInnerFocusStyle->GetStyleBorder();
     nsCSSRendering::PaintBorder(aPresContext, aRenderingContext, mFrame,
-                                aDirtyRect, rect, *border, mInnerFocusStyle);
+                                aDirtyRect, rect, mInnerFocusStyle);
   }
 }
 
 
 void
 nsButtonFrameRenderer::PaintBorderAndBackground(nsPresContext* aPresContext,
           nsIRenderingContext& aRenderingContext,
           const nsRect& aDirtyRect,
@@ -260,24 +258,22 @@ nsButtonFrameRenderer::PaintBorderAndBac
 
 {
   // get the button rect this is inside the focus and outline rects
   nsRect buttonRect;
   GetButtonRect(aRect, buttonRect);
 
   nsStyleContext* context = mFrame->GetStyleContext();
 
-  const nsStyleBorder* border = context->GetStyleBorder();
-
   nsCSSRendering::PaintBackground(aPresContext, aRenderingContext, mFrame,
                                   aDirtyRect, buttonRect, aBGFlags);
   nsCSSRendering::PaintBoxShadowInner(aPresContext, aRenderingContext,
                                       mFrame, buttonRect, aDirtyRect);
   nsCSSRendering::PaintBorder(aPresContext, aRenderingContext, mFrame,
-                              aDirtyRect, buttonRect, *border, context);
+                              aDirtyRect, buttonRect, context);
 }
 
 
 void
 nsButtonFrameRenderer::GetButtonOuterFocusRect(const nsRect& aRect, nsRect& focusRect)
 {
   focusRect = aRect;
 }
@@ -348,30 +344,16 @@ nsButtonFrameRenderer::GetButtonInnerFoc
       NS_NOTYETIMPLEMENTED("percentage padding");
     }
     result += mInnerFocusStyle->GetStyleBorder()->GetActualBorder();
   }
 
   return result;
 }
 
-nsMargin
-nsButtonFrameRenderer::GetButtonOutlineBorderAndPadding()
-{
-  nsMargin borderAndPadding(0,0,0,0);
-  return borderAndPadding;
-}
-
-// gets the full size of our border with all the focus borders
-nsMargin
-nsButtonFrameRenderer::GetFullButtonBorderAndPadding()
-{
-  return GetAddedButtonBorderAndPadding() + GetButtonBorderAndPadding();
-}
-
 // gets all the focus borders and padding that will be added to the regular border
 nsMargin
 nsButtonFrameRenderer::GetAddedButtonBorderAndPadding()
 {
   return GetButtonOuterFocusBorderAndPadding() + GetButtonInnerFocusMargin() + GetButtonInnerFocusBorderAndPadding();
 }
 
 /**
--- a/layout/forms/nsButtonFrameRenderer.h
+++ b/layout/forms/nsButtonFrameRenderer.h
@@ -87,18 +87,16 @@ public:
 
   void GetButtonOuterFocusRect(const nsRect& aRect, nsRect& aResult);
   void GetButtonRect(const nsRect& aRect, nsRect& aResult);
   void GetButtonInnerFocusRect(const nsRect& aRect, nsRect& aResult);
   nsMargin GetButtonOuterFocusBorderAndPadding();
   nsMargin GetButtonBorderAndPadding();
   nsMargin GetButtonInnerFocusMargin();
   nsMargin GetButtonInnerFocusBorderAndPadding();
-  nsMargin GetButtonOutlineBorderAndPadding();
-  nsMargin GetFullButtonBorderAndPadding();
   nsMargin GetAddedButtonBorderAndPadding();
 
   nsStyleContext* GetStyleContext(PRInt32 aIndex) const;
   void SetStyleContext(PRInt32 aIndex, nsStyleContext* aStyleContext);
   void ReResolveStyles(nsPresContext* aPresContext);
 
   nsIFrame* GetFrame();
 
--- a/layout/forms/nsComboboxControlFrame.cpp
+++ b/layout/forms/nsComboboxControlFrame.cpp
@@ -895,27 +895,16 @@ nsComboboxControlFrame::RemoveOption(PRI
   if (!weakThis.IsAlive())
     return NS_OK;
 
   nsListControlFrame* lcf = static_cast<nsListControlFrame*>(mDropdownFrame);
   return lcf->RemoveOption(aIndex);
 }
 
 NS_IMETHODIMP
-nsComboboxControlFrame::GetOptionSelected(PRInt32 aIndex, PRBool* aValue)
-{
-  NS_ASSERTION(mDropdownFrame, "No dropdown frame!");
-
-  nsISelectControlFrame* listFrame = do_QueryFrame(mDropdownFrame);
-  NS_ASSERTION(listFrame, "No list frame!");
-
-  return listFrame->GetOptionSelected(aIndex, aValue);
-}
-
-NS_IMETHODIMP
 nsComboboxControlFrame::OnSetSelectedIndex(PRInt32 aOldIndex, PRInt32 aNewIndex)
 {
   nsAutoScriptBlocker scriptBlocker;
   RedisplayText(aNewIndex);
   NS_ASSERTION(mDropdownFrame, "No dropdown frame!");
   
   nsISelectControlFrame* listFrame = do_QueryFrame(mDropdownFrame);
   NS_ASSERTION(listFrame, "No list frame!");
--- a/layout/forms/nsComboboxControlFrame.h
+++ b/layout/forms/nsComboboxControlFrame.h
@@ -183,17 +183,16 @@ public:
    */
   NS_IMETHOD RedisplaySelectedText();
   virtual PRInt32 UpdateRecentIndex(PRInt32 aIndex);
   virtual void OnContentReset();
 
   // nsISelectControlFrame
   NS_IMETHOD AddOption(PRInt32 index);
   NS_IMETHOD RemoveOption(PRInt32 index);
-  NS_IMETHOD GetOptionSelected(PRInt32 aIndex, PRBool* aValue);
   NS_IMETHOD DoneAddingChildren(PRBool aIsDone);
   NS_IMETHOD OnOptionSelected(PRInt32 aIndex, PRBool aSelected);
   NS_IMETHOD OnSetSelectedIndex(PRInt32 aOldIndex, PRInt32 aNewIndex);
 
   //nsIRollupListener
   /**
    * Hide the dropdown menu and stop capturing mouse events.
    * @note This method might destroy |this|.
--- a/layout/forms/nsFieldSetFrame.cpp
+++ b/layout/forms/nsFieldSetFrame.cpp
@@ -301,55 +301,52 @@ nsFieldSetFrame::PaintBorderBackground(n
     // draw left side
     nsRect clipRect(rect);
     clipRect.width = legendRect.x - rect.x;
     clipRect.height = topBorder;
 
     aRenderingContext.PushState();
     aRenderingContext.SetClipRect(clipRect, nsClipCombine_kIntersect);
     nsCSSRendering::PaintBorder(presContext, aRenderingContext, this,
-                                aDirtyRect, rect, *borderStyle, mStyleContext,
-                                skipSides);
+                                aDirtyRect, rect, mStyleContext, skipSides);
 
     aRenderingContext.PopState();
 
 
     // draw right side
     clipRect = rect;
     clipRect.x = legendRect.XMost();
     clipRect.width = rect.XMost() - legendRect.XMost();
     clipRect.height = topBorder;
 
     aRenderingContext.PushState();
     aRenderingContext.SetClipRect(clipRect, nsClipCombine_kIntersect);
     nsCSSRendering::PaintBorder(presContext, aRenderingContext, this,
-                                aDirtyRect, rect, *borderStyle, mStyleContext,
-                                skipSides);
+                                aDirtyRect, rect, mStyleContext, skipSides);
 
     aRenderingContext.PopState();
 
     
     // draw bottom
     clipRect = rect;
     clipRect.y += topBorder;
     clipRect.height = mRect.height - (yoff + topBorder);
     
     aRenderingContext.PushState();
     aRenderingContext.SetClipRect(clipRect, nsClipCombine_kIntersect);
     nsCSSRendering::PaintBorder(presContext, aRenderingContext, this,
-                                aDirtyRect, rect, *borderStyle, mStyleContext,
-                                skipSides);
+                                aDirtyRect, rect, mStyleContext, skipSides);
 
     aRenderingContext.PopState();
   } else {
 
     nsCSSRendering::PaintBorder(presContext, aRenderingContext, this,
                                 aDirtyRect,
                                 nsRect(aPt, mRect.Size()),
-                                *borderStyle, mStyleContext, skipSides);
+                                mStyleContext, skipSides);
   }
 }
 
 nscoord
 nsFieldSetFrame::GetIntrinsicWidth(nsIRenderingContext* aRenderingContext,
                                    nsLayoutUtils::IntrinsicWidthType aType)
 {
   nscoord legendWidth = 0;
--- a/layout/forms/nsISelectControlFrame.h
+++ b/layout/forms/nsISelectControlFrame.h
@@ -59,21 +59,16 @@ public:
 
   /**
    * Removes the option at index.  The caller must have a live script
    * blocker while calling this method.
    */
   NS_IMETHOD RemoveOption(PRInt32 index) = 0; 
 
   /**
-   * Sets the select state of the option at index
-   */
-  NS_IMETHOD GetOptionSelected(PRInt32 index, PRBool* value) = 0;
-
-  /**
    * Sets whether the parser is done adding children
    * @param aIsDone whether the parser is done adding children
    */
   NS_IMETHOD DoneAddingChildren(PRBool aIsDone) = 0;
 
   /**
    * Notify the frame when an option is selected
    */
--- a/layout/forms/nsListControlFrame.cpp
+++ b/layout/forms/nsListControlFrame.cpp
@@ -1640,24 +1640,16 @@ nsListControlFrame::FireOnChange()
   nsEvent event(PR_TRUE, NS_FORM_CHANGE);
 
   nsCOMPtr<nsIPresShell> presShell = PresContext()->GetPresShell();
   if (presShell) {
     presShell->HandleEventWithTarget(&event, this, nsnull, &status);
   }
 }
 
-// Determine if the specified item in the listbox is selected.
-NS_IMETHODIMP
-nsListControlFrame::GetOptionSelected(PRInt32 aIndex, PRBool* aValue)
-{
-  *aValue = IsContentSelectedByIndex(aIndex);
-  return NS_OK;
-}
-
 NS_IMETHODIMP
 nsListControlFrame::OnSetSelectedIndex(PRInt32 aOldIndex, PRInt32 aNewIndex)
 {
   if (mComboboxFrame) {
     // UpdateRecentIndex with NS_SKIP_NOTIFY_INDEX, so that we won't fire an onchange
     // event for this setting of selectedIndex.
     mComboboxFrame->UpdateRecentIndex(NS_SKIP_NOTIFY_INDEX);
   }
--- a/layout/forms/nsListControlFrame.h
+++ b/layout/forms/nsListControlFrame.h
@@ -183,17 +183,16 @@ public:
    * @note This method might destroy |this|.
    */
   virtual void ComboboxFinish(PRInt32 aIndex);
   virtual void OnContentReset();
 
   // nsISelectControlFrame
   NS_IMETHOD AddOption(PRInt32 index);
   NS_IMETHOD RemoveOption(PRInt32 index);
-  NS_IMETHOD GetOptionSelected(PRInt32 aIndex, PRBool* aValue);
   NS_IMETHOD DoneAddingChildren(PRBool aIsDone);
 
   /**
    * Gets the content (an option) by index and then set it as
    * being selected or not selected.
    */
   NS_IMETHOD OnOptionSelected(PRInt32 aIndex, PRBool aSelected);
   NS_IMETHOD OnSetSelectedIndex(PRInt32 aOldIndex, PRInt32 aNewIndex);
--- a/layout/generic/nsBlockFrame.cpp
+++ b/layout/generic/nsBlockFrame.cpp
@@ -2843,37 +2843,16 @@ nsBlockFrame::ShouldApplyTopMargin(nsBlo
   }
 
   // The line being reflowed is "essentially" the first line in the
   // block. Therefore its top-margin will be collapsed by the
   // generational collapsing logic with its parent (us).
   return PR_FALSE;
 }
 
-nsIFrame*
-nsBlockFrame::GetTopBlockChild(nsPresContext* aPresContext)
-{
-  if (mLines.empty())
-    return nsnull;
-
-  nsLineBox *firstLine = mLines.front();
-  if (firstLine->IsBlock())
-    return firstLine->mFirstChild;
-
-  if (!firstLine->CachedIsEmpty())
-    return nsnull;
-
-  line_iterator secondLine = begin_lines();
-  ++secondLine;
-  if (secondLine == end_lines() || !secondLine->IsBlock())
-    return nsnull;
-
-  return secondLine->mFirstChild;
-}
-
 nsresult
 nsBlockFrame::ReflowBlockFrame(nsBlockReflowState& aState,
                                line_iterator aLine,
                                PRBool* aKeepReflowGoing)
 {
   NS_PRECONDITION(*aKeepReflowGoing, "bad caller");
 
   nsresult rv = NS_OK;
--- a/layout/generic/nsBlockFrame.h
+++ b/layout/generic/nsBlockFrame.h
@@ -266,22 +266,16 @@ public:
 
   /**
    * Determines whether the collapsed margin carried out of the last
    * line includes the margin-top of a line with clearance (in which
    * case we must avoid collapsing that margin with our bottom margin)
    */
   PRBool CheckForCollapsedBottomMarginFromClearanceLine();
 
-  /** return the topmost block child based on y-index.
-    * almost always the first or second line, if there is one.
-    * accounts for lines that hold only compressed white space, etc.
-    */
-  nsIFrame* GetTopBlockChild(nsPresContext *aPresContext);
-
   static nsresult GetCurrentLine(nsBlockReflowState *aState, nsLineBox **aOutCurrentLine);
 
   static PRBool BlockIsMarginRoot(nsIFrame* aBlock);
   static PRBool BlockNeedsFloatManager(nsIFrame* aBlock);
 
   /**
    * Returns whether aFrame is a block frame that will wrap its contents
    * around floats intruding on it from the outside.  (aFrame need not
--- a/layout/generic/nsBulletFrame.cpp
+++ b/layout/generic/nsBulletFrame.cpp
@@ -242,20 +242,18 @@ nsBulletFrame::PaintBullet(nsIRenderingC
         nsLayoutUtils::DrawSingleImage(&aRenderingContext,
              imageCon, nsLayoutUtils::GetGraphicsFilterForFrame(this),
              dest + aPt, aDirtyRect, imgIContainer::FLAG_NONE);
         return;
       }
     }
   }
 
-  const nsStyleColor* myColor = GetStyleColor();
-
   nsCOMPtr<nsIFontMetrics> fm;
-  aRenderingContext.SetColor(myColor->mColor);
+  aRenderingContext.SetColor(GetVisitedDependentColor(eCSSProperty_color));
 
   mTextIsRTL = PR_FALSE;
 
   nsAutoString text;
   switch (listStyleType) {
   case NS_STYLE_LIST_STYLE_NONE:
     break;
 
--- a/layout/generic/nsCanvasFrame.cpp
+++ b/layout/generic/nsCanvasFrame.cpp
@@ -581,18 +581,19 @@ nsCanvasFrame::Reflow(nsPresContext*    
     // frame (which subsumes this special case if defined broadly).  For now,
     // however, this addresses the most common case.  Given that this behavior has
     // long been broken (non-zero percent background-size may be a new instance,
     // but non-zero percent background-position is longstanding), we defer a
     // fully correct fix until later.
     if (nsSize(aDesiredSize.width, aDesiredSize.height) != GetSize()) {
       nsIFrame* rootElementFrame =
         aPresContext->PresShell()->FrameConstructor()->GetRootElementStyleFrame();
-      const nsStyleBackground* bg =
+      nsStyleContext* bgSC =
         nsCSSRendering::FindCanvasBackground(this, rootElementFrame);
+      const nsStyleBackground* bg = bgSC->GetStyleBackground();
       if (!bg->IsTransparent()) {
         NS_FOR_VISIBLE_BACKGROUND_LAYERS_BACK_TO_FRONT(i, bg) {
           const nsStyleBackground::Layer& layer = bg->mLayers[i];
           if (layer.mAttachment == NS_STYLE_BG_ATTACHMENT_FIXED &&
               layer.RenderingMightDependOnFrameSize()) {
             Invalidate(nsRect(nsPoint(0, 0), GetSize()));
             break;
           }
--- a/layout/generic/nsColumnSetFrame.cpp
+++ b/layout/generic/nsColumnSetFrame.cpp
@@ -274,20 +274,20 @@ nsColumnSetFrame::PaintColumnRule(nsIRen
     // Each child frame's position coordinates is actually relative to this nsColumnSetFrame.
     // linePt will be at the top-left edge to paint the line.
     nsPoint edgeOfLeftSibling = leftSibling->GetRect().TopRight() + aPt;
     nsPoint edgeOfRightSibling = rightSibling->GetRect().TopLeft() + aPt;
     nsPoint linePt((edgeOfLeftSibling.x + edgeOfRightSibling.x - ruleWidth) / 2,
                    contentRect.y);
 
     nsRect lineRect(linePt, ruleSize);
-    nsCSSRendering::PaintBorder(presContext, *aCtx, this, aDirtyRect,
-                                lineRect, border, GetStyleContext(),
-                                // Remember, we only have the "left" "border". Skip everything else
-                                (1 << NS_SIDE_TOP | 1 << NS_SIDE_RIGHT | 1 << NS_SIDE_BOTTOM));
+    nsCSSRendering::PaintBorderWithStyleBorder(presContext, *aCtx, this,
+        aDirtyRect, lineRect, border, GetStyleContext(),
+        // Remember, we only have the "left" "border". Skip everything else
+        (1 << NS_SIDE_TOP | 1 << NS_SIDE_RIGHT | 1 << NS_SIDE_BOTTOM));
 
     child = nextSibling;
     nextSibling = nextSibling->GetNextSibling();
   }
 }
 
 NS_IMETHODIMP
 nsColumnSetFrame::SetInitialChildList(nsIAtom*        aListName,
--- a/layout/generic/nsFrame.cpp
+++ b/layout/generic/nsFrame.cpp
@@ -704,26 +704,16 @@ nsIFrame::ApplySkipSides(nsMargin& aMarg
     aMargin.right = 0;
   if (skipSides & (1 << NS_SIDE_BOTTOM))
     aMargin.bottom = 0;
   if (skipSides & (1 << NS_SIDE_LEFT))
     aMargin.left = 0;
 }
 
 nsRect
-nsIFrame::GetMarginRect() const
-{
-  nsMargin m(GetUsedMargin());
-  ApplySkipSides(m);
-  nsRect r(mRect);
-  r.Inflate(m);
-  return r;
-}
-
-nsRect
 nsIFrame::GetPaddingRect() const
 {
   nsMargin b(GetUsedBorder());
   ApplySkipSides(b);
   nsRect r(mRect);
   r.Deflate(b);
   return r;
 }
@@ -1198,26 +1188,16 @@ nsIFrame::OverflowClip(nsDisplayListBuil
                        const nsRect&           aClipRect,
                        PRBool                  aClipBorderBackground,
                        PRBool                  aClipAll)
 {
   nsOverflowClipWrapper wrapper(this, aClipRect, aClipBorderBackground, aClipAll);
   return wrapper.WrapLists(aBuilder, this, aFromSet, aToSet);
 }
 
-nsresult
-nsIFrame::Clip(nsDisplayListBuilder*   aBuilder,
-               const nsDisplayListSet& aFromSet,
-               const nsDisplayListSet& aToSet,
-               const nsRect&           aClipRect)
-{
-  nsAbsPosClipWrapper wrapper(this, aClipRect);
-  return wrapper.WrapLists(aBuilder, this, aFromSet, aToSet);
-}
-
 static nsresult
 BuildDisplayListWithOverflowClip(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
     const nsRect& aDirtyRect, const nsDisplayListSet& aSet,
     const nsRect& aClipRect)
 {
   nsDisplayListCollection set;
   nsresult rv = aFrame->BuildDisplayList(aBuilder, aDirtyRect, set);
   NS_ENSURE_SUCCESS(rv, rv);
@@ -3987,18 +3967,18 @@ nsFrame::CheckInvalidateSizeChange(nsHTM
 {
   nsIFrame::CheckInvalidateSizeChange(mRect, GetOverflowRect(),
       nsSize(aNewDesiredSize.width, aNewDesiredSize.height));
 }
 
 static void
 InvalidateRectForFrameSizeChange(nsIFrame* aFrame, const nsRect& aRect)
 {
-  const nsStyleBackground* bg;
-  if (!nsCSSRendering::FindBackground(aFrame->PresContext(), aFrame, &bg)) {
+  nsStyleContext *bgSC;
+  if (!nsCSSRendering::FindBackground(aFrame->PresContext(), aFrame, &bgSC)) {
     nsIFrame* rootFrame =
       aFrame->PresContext()->PresShell()->FrameManager()->GetRootFrame();
     rootFrame->Invalidate(nsRect(nsPoint(0, 0), rootFrame->GetSize()));
   }
 
   aFrame->Invalidate(aRect);
 }
 
@@ -5999,20 +5979,23 @@ nsIFrame::IsFocusable(PRInt32 *aTabIndex
         // Elements with scrollable view are focusable with script & tabbable
         // Otherwise you couldn't scroll them with keyboard, which is
         // an accessibility issue (e.g. Section 508 rules)
         // However, we don't make them to be focusable with the mouse,
         // because the extra focus outlines are considered unnecessarily ugly.
         // When clicked on, the selection position within the element 
         // will be enough to make them keyboard scrollable.
         nsIScrollableFrame *scrollFrame = do_QueryFrame(this);
-        if (scrollFrame && scrollFrame->GetScrollbarVisibility() != 0) {
-          // Scroll bars will be used for overflow
-          isFocusable = PR_TRUE;
-          tabIndex = 0;
+        if (scrollFrame) {
+          nsMargin margin = scrollFrame->GetActualScrollbarSizes();
+          if (margin.top || margin.right || margin.bottom || margin.left) {
+            // Scroll bars will be used for overflow
+            isFocusable = PR_TRUE;
+            tabIndex = 0;
+          }
         }
       }
     }
   }
 
   if (aTabIndex) {
     *aTabIndex = tabIndex;
   }
--- a/layout/generic/nsFrameList.cpp
+++ b/layout/generic/nsFrameList.cpp
@@ -355,34 +355,16 @@ nsFrameList::ContainsFrame(const nsIFram
     if (frame == aFrame) {
       return PR_TRUE;
     }
     frame = frame->GetNextSibling();
   }
   return PR_FALSE;
 }
 
-PRBool
-nsFrameList::ContainsFrameBefore(const nsIFrame* aFrame, const nsIFrame* aEnd) const
-{
-  NS_PRECONDITION(aFrame, "null ptr");
-
-  nsIFrame* frame = mFirstChild;
-  while (frame) {
-    if (frame == aEnd) {
-      return PR_FALSE;
-    }
-    if (frame == aFrame) {
-      return PR_TRUE;
-    }
-    frame = frame->GetNextSibling();
-  }
-  return PR_FALSE;
-}
-
 PRInt32
 nsFrameList::GetLength() const
 {
   PRInt32 count = 0;
   nsIFrame* frame = mFirstChild;
   while (frame) {
     count++;
     frame = frame->GetNextSibling();
@@ -425,38 +407,16 @@ class CompareByContentOrderComparator
     return aA == aB;
   }
   PRBool LessThan(const nsIFrame* aA, const nsIFrame* aB) const {
     return CompareByContentOrder(aA, aB) < 0;
   }
 };
 
 void
-nsFrameList::SortByContentOrder()
-{
-  if (IsEmpty())
-    return;
-
-  nsAutoTArray<nsIFrame*, 8> array;
-  nsIFrame* f;
-  for (f = mFirstChild; f; f = f->GetNextSibling()) {
-    array.AppendElement(f);
-  }
-  array.Sort(CompareByContentOrderComparator());
-  f = mFirstChild = array.ElementAt(0);
-  for (PRUint32 i = 1; i < array.Length(); ++i) {
-    nsIFrame* ff = array.ElementAt(i);
-    f->SetNextSibling(ff);
-    f = ff;
-  }
-  f->SetNextSibling(nsnull);
-  mLastChild = f;
-}
-
-void
 nsFrameList::ApplySetParent(nsIFrame* aParent) const
 {
   NS_ASSERTION(aParent, "null ptr");
 
   for (nsIFrame* f = FirstChild(); f; f = f->GetNextSibling()) {
     f->SetParent(aParent);
   }
 }
--- a/layout/generic/nsFrameList.h
+++ b/layout/generic/nsFrameList.h
@@ -210,24 +210,16 @@ public:
 
   /**
    * Split this frame list such that all the frames coming after the link
    * pointed to by aLink end up in the returned list, while the frames before
    * that link stay in this list.  After this call, aLink is at end.
    */
   nsFrameList ExtractTail(FrameLinkEnumerator& aLink);
 
-  /**
-   * Sort the frames according to content order so that the first
-   * frame in the list is the first in content order. Frames for
-   * the same content will be ordered so that a prev in flow
-   * comes before its next in flow.
-   */
-  void SortByContentOrder();
-
   nsIFrame* FirstChild() const {
     return mFirstChild;
   }
 
   nsIFrame* LastChild() const {
     return mLastChild;
   }
 
@@ -238,17 +230,16 @@ public:
     return nsnull == mFirstChild;
   }
 
   PRBool NotEmpty() const {
     return nsnull != mFirstChild;
   }
 
   PRBool ContainsFrame(const nsIFrame* aFrame) const;
-  PRBool ContainsFrameBefore(const nsIFrame* aFrame, const nsIFrame* aEnd) const;
 
   PRInt32 GetLength() const;
 
   /**
    * If this frame list has only one frame, return that frame.
    * Otherwise, return null.
    */
   nsIFrame* OnlyChild() const {
--- a/layout/generic/nsFrameSetFrame.cpp
+++ b/layout/generic/nsFrameSetFrame.cpp
@@ -88,26 +88,16 @@ static NS_DEFINE_CID(kLookAndFeelCID, NS
 /*******************************************************************************
  * nsFramesetDrag
  ******************************************************************************/
 nsFramesetDrag::nsFramesetDrag() 
 {
   UnSet();
 }
 
-nsFramesetDrag::nsFramesetDrag(PRBool               aVertical, 
-                               PRInt32              aIndex, 
-                               PRInt32              aChange, 
-                               nsHTMLFramesetFrame* aSource) 
-{
-  mVertical = aVertical;
-  mIndex    = aIndex;
-  mChange   = aChange; 
-  mSource   = aSource;
-}
 void nsFramesetDrag::Reset(PRBool               aVertical, 
                            PRInt32              aIndex, 
                            PRInt32              aChange, 
                            nsHTMLFramesetFrame* aSource) 
 {
   mVertical = aVertical;
   mIndex    = aIndex;
   mChange   = aChange;
--- a/layout/generic/nsFrameSetFrame.h
+++ b/layout/generic/nsFrameSetFrame.h
@@ -82,20 +82,16 @@ enum nsFrameborder {
 struct nsFramesetDrag {
   nsHTMLFramesetFrame* mSource;    // frameset whose border was dragged to cause the resize
   PRInt32              mIndex;     // index of left col or top row of effected area
   PRInt32              mChange;    // pos for left to right or top to bottom, neg otherwise
   PRPackedBool         mVertical;  // vertical if true, otherwise horizontal
   PRPackedBool         mActive;
 
   nsFramesetDrag();
-  nsFramesetDrag(PRBool               aVertical, 
-                 PRInt32              aIndex, 
-                 PRInt32              aChange, 
-                 nsHTMLFramesetFrame* aSource); 
   void Reset(PRBool               aVertical, 
              PRInt32              aIndex, 
              PRInt32              aChange, 
              nsHTMLFramesetFrame* aSource); 
   void UnSet();
 };
 
 /*******************************************************************************
--- a/layout/generic/nsGfxScrollFrame.cpp
+++ b/layout/generic/nsGfxScrollFrame.cpp
@@ -286,20 +286,22 @@ GetScrollbarMetrics(nsBoxLayoutState& aS
                     nsSize* aPref, PRBool aVertical)
 {
   NS_ASSERTION(aState.GetRenderingContext(),
                "Must have rendering context in layout state for size "
                "computations");
   
   if (aMin) {
     *aMin = aBox->GetMinSize(aState);
+    nsBox::AddMargin(aBox, *aMin);
   }
  
   if (aPref) {
     *aPref = aBox->GetPrefSize(aState);
+    nsBox::AddMargin(aBox, *aPref);
   }
 }
 
 /**
  * Assuming that we know the metrics for our wrapped frame and
  * whether the horizontal and/or vertical scrollbars are present,
  * compute the resulting layout and return PR_TRUE if the layout is
  * consistent. If the layout is consistent then we fill in the
@@ -934,24 +936,26 @@ nsMargin nsGfxScrollFrameInner::GetDesir
   NS_ASSERTION(aState && aState->GetRenderingContext(),
                "Must have rendering context in layout state for size "
                "computations");
   
   nsMargin result(0, 0, 0, 0);
 
   if (mVScrollbarBox) {
     nsSize size = mVScrollbarBox->GetPrefSize(*aState);
+    nsBox::AddMargin(mVScrollbarBox, size);
     if (IsScrollbarOnRight())
       result.left = size.width;
     else
       result.right = size.width;
   }
 
   if (mHScrollbarBox) {
     nsSize size = mHScrollbarBox->GetPrefSize(*aState);
+    nsBox::AddMargin(mHScrollbarBox, size);
     // We don't currently support any scripts that would require a scrollbar
     // at the top. (Are there any?)
     result.bottom = size.height;
   }
 
   return result;
 }
 
@@ -1081,22 +1085,24 @@ nsXULScrollFrame::GetPrefSize(nsBoxLayou
 
   nsGfxScrollFrameInner::ScrollbarStyles styles = GetScrollbarStyles();
 
   // scrolled frames don't have their own margins
 
   if (mInner.mVScrollbarBox &&
       styles.mVertical == NS_STYLE_OVERFLOW_SCROLL) {
     nsSize vSize = mInner.mVScrollbarBox->GetPrefSize(aState);
+    nsBox::AddMargin(mInner.mVScrollbarBox, vSize);
     pref.width += vSize.width;
   }
    
   if (mInner.mHScrollbarBox &&
       styles.mHorizontal == NS_STYLE_OVERFLOW_SCROLL) {
     nsSize hSize = mInner.mHScrollbarBox->GetPrefSize(aState);
+    nsBox::AddMargin(mInner.mHScrollbarBox, hSize);
     pref.height += hSize.height;
   }
 
   AddBorderAndPadding(pref);
   PRBool widthSet, heightSet;
   nsIBox::AddCSSPrefSize(this, pref, widthSet, heightSet);
   return pref;
 }
@@ -1110,24 +1116,26 @@ nsXULScrollFrame::GetMinSize(nsBoxLayout
 
   nsSize min = mInner.mScrolledFrame->GetMinSizeForScrollArea(aState);
 
   nsGfxScrollFrameInner::ScrollbarStyles styles = GetScrollbarStyles();
      
   if (mInner.mVScrollbarBox &&
       styles.mVertical == NS_STYLE_OVERFLOW_SCROLL) {
      nsSize vSize = mInner.mVScrollbarBox->GetMinSize(aState);
+     AddMargin(mInner.mVScrollbarBox, vSize);
      min.width += vSize.width;
      if (min.height < vSize.height)
         min.height = vSize.height;
   }
         
   if (mInner.mHScrollbarBox &&
       styles.mHorizontal == NS_STYLE_OVERFLOW_SCROLL) {
      nsSize hSize = mInner.mHScrollbarBox->GetMinSize(aState);
+     AddMargin(mInner.mHScrollbarBox, hSize);
      min.height += hSize.height;
      if (min.width < hSize.width)
         min.width = hSize.width;
   }
 
   AddBorderAndPadding(min);
   PRBool widthSet, heightSet;
   nsIBox::AddCSSMinSize(aState, this, min, widthSet, heightSet);
@@ -2493,16 +2501,17 @@ PRBool
 nsXULScrollFrame::AddRemoveScrollbar(nsBoxLayoutState& aState,
                                      PRBool aOnTop, PRBool aHorizontal, PRBool aAdd)
 {
   if (aHorizontal) {
      if (mInner.mNeverHasHorizontalScrollbar || !mInner.mHScrollbarBox)
        return PR_FALSE;
 
      nsSize hSize = mInner.mHScrollbarBox->GetPrefSize(aState);
+     nsBox::AddMargin(mInner.mHScrollbarBox, hSize);
 
      mInner.SetScrollbarVisibility(mInner.mHScrollbarBox, aAdd);
 
      PRBool hasHorizontalScrollbar;
      PRBool fit = AddRemoveScrollbar(hasHorizontalScrollbar,
                                      mInner.mScrollPort.y,
                                      mInner.mScrollPort.height,
                                      hSize.height, aOnTop, aAdd);
@@ -2511,16 +2520,17 @@ nsXULScrollFrame::AddRemoveScrollbar(nsB
         mInner.SetScrollbarVisibility(mInner.mHScrollbarBox, !aAdd);
 
      return fit;
   } else {
      if (mInner.mNeverHasVerticalScrollbar || !mInner.mVScrollbarBox)
        return PR_FALSE;
 
      nsSize vSize = mInner.mVScrollbarBox->GetPrefSize(aState);
+     nsBox::AddMargin(mInner.mVScrollbarBox, vSize);
 
      mInner.SetScrollbarVisibility(mInner.mVScrollbarBox, aAdd);
 
      PRBool hasVerticalScrollbar;
      PRBool fit = AddRemoveScrollbar(hasVerticalScrollbar,
                                      mInner.mScrollPort.x,
                                      mInner.mScrollPort.width,
                                      vSize.width, aOnTop, aAdd);
@@ -3119,35 +3129,31 @@ nsGfxScrollFrameInner::LayoutScrollbars(
   }
 
   nsPresContext* presContext = mScrolledFrame->PresContext();
   if (mVScrollbarBox) {
     NS_PRECONDITION(mVScrollbarBox->IsBoxFrame(), "Must be a box frame!");
     nsRect vRect(mScrollPort);
     vRect.width = aContentArea.width - mScrollPort.width;
     vRect.x = scrollbarOnLeft ? aContentArea.x : mScrollPort.XMost();
-#ifdef DEBUG
     nsMargin margin;
     mVScrollbarBox->GetMargin(margin);
-    NS_ASSERTION(margin == nsMargin(0,0,0,0), "Scrollbar margin not supported");
-#endif
+    vRect.Deflate(margin);
     AdjustScrollbarRectForResizer(mOuter, presContext, vRect, hasResizer, PR_TRUE);
     LayoutAndInvalidate(aState, mVScrollbarBox, vRect);
   }
 
   if (mHScrollbarBox) {
     NS_PRECONDITION(mHScrollbarBox->IsBoxFrame(), "Must be a box frame!");
     nsRect hRect(mScrollPort);
     hRect.height = aContentArea.height - mScrollPort.height;
     hRect.y = PR_TRUE ? mScrollPort.YMost() : aContentArea.y;
-#ifdef DEBUG
     nsMargin margin;
     mHScrollbarBox->GetMargin(margin);
-    NS_ASSERTION(margin == nsMargin(0,0,0,0), "Scrollbar margin not supported");
-#endif
+    hRect.Deflate(margin);
     AdjustScrollbarRectForResizer(mOuter, presContext, hRect, hasResizer, PR_FALSE);
     LayoutAndInvalidate(aState, mHScrollbarBox, hRect);
   }
 
   // may need to update fixed position children of the viewport,
   // if the client area changed size because of an incremental
   // reflow of a descendant.  (If the outer frame is dirty, the fixed
   // children will be re-laid out anyway)
@@ -3234,28 +3240,21 @@ nsGfxScrollFrameInner::GetScrolledRectIn
     x2 += extraWidth;
   }
   return nsRect(x1, y1, x2 - x1, y2 - y1);
 }
 
 nsMargin
 nsGfxScrollFrameInner::GetActualScrollbarSizes() const
 {
-  nsMargin result(0, 0, 0, 0);
-  if (mVScrollbarBox) {
-    if (IsScrollbarOnRight()) {
-      result.right = mVScrollbarBox->GetRect().width;
-    } else {
-      result.left = mVScrollbarBox->GetRect().width;
-    }
-  }
-  if (mHScrollbarBox) {
-    result.bottom = mHScrollbarBox->GetRect().height;
-  }
-  return result;
+  nsRect r = mOuter->GetPaddingRect() - mOuter->GetPosition();
+
+  return nsMargin(mScrollPort.x - r.x, mScrollPort.y - r.y,
+                  r.XMost() - mScrollPort.XMost(),
+                  r.YMost() - mScrollPort.YMost());
 }
 
 void
 nsGfxScrollFrameInner::SetScrollbarVisibility(nsIBox* aScrollbar, PRBool aVisible)
 {
   if (!aScrollbar)
     return;
 
--- a/layout/generic/nsHTMLContainerFrame.cpp
+++ b/layout/generic/nsHTMLContainerFrame.cpp
@@ -445,17 +445,17 @@ nsHTMLContainerFrame::GetTextDecorations
     // decorations.
     return; 
   }
 
   if (!aIsBlock) {
     aDecorations = this->GetStyleTextReset()->mTextDecoration &
                    NS_STYLE_TEXT_DECORATION_LINES_MASK;
     if (aDecorations) {
-      nscolor color = this->GetStyleColor()->mColor;
+      nscolor color = this->GetVisitedDependentColor(eCSSProperty_color);
       aUnderColor = color;
       aOverColor = color;
       aStrikeColor = color;
     }
   }
   else {
     // We want to ignore a text-decoration from an ancestor frame that
     // is redundant with one from a descendant frame.  This isn't just
@@ -465,17 +465,17 @@ nsHTMLContainerFrame::GetTextDecorations
     // it starts set to all possible decorations.
     PRUint8 decorMask = NS_STYLE_TEXT_DECORATION_LINES_MASK;
 
     // walk tree
     for (nsIFrame* frame = this; frame; frame = frame->GetParent()) {
       PRUint8 decors = frame->GetStyleTextReset()->mTextDecoration & decorMask;
       if (decors) {
         // A *new* text-decoration is found.
-        nscolor color = frame->GetStyleColor()->mColor;
+        nscolor color = frame->GetVisitedDependentColor(eCSSProperty_color);
 
         if (NS_STYLE_TEXT_DECORATION_UNDERLINE & decors) {
           aUnderColor = color;
           decorMask &= ~NS_STYLE_TEXT_DECORATION_UNDERLINE;
           aDecorations |= NS_STYLE_TEXT_DECORATION_UNDERLINE;
         }
         if (NS_STYLE_TEXT_DECORATION_OVERLINE & decors) {
           aOverColor = color;
--- a/layout/generic/nsIFrame.h
+++ b/layout/generic/nsIFrame.h
@@ -717,16 +717,22 @@ public:
     const nsStyle##name_ * GetStyle##name_ () const {                         \
       return static_cast<const nsStyle##name_*>(                              \
                             GetStyleDataExternal(eStyleStruct_##name_));      \
     }
 #endif
   #include "nsStyleStructList.h"
   #undef STYLE_STRUCT
 
+#ifdef _IMPL_NS_LAYOUT
+  /** Also forward GetVisitedDependentColor to the style context */
+  nscolor GetVisitedDependentColor(nsCSSProperty aProperty)
+    { return mStyleContext->GetVisitedDependentColor(aProperty); }
+#endif
+
   /**
    * These methods are to access any additional style contexts that
    * the frame may be holding. These are contexts that are children
    * of the frame's primary context and are NOT used as style contexts
    * for any child frames. These contexts also MUST NOT have any child 
    * contexts whatsoever. If you need to insert style contexts into the
    * style tree, then you should create pseudo element frames to own them
    * The indicies must be consecutive and implementations MUST return an 
@@ -813,21 +819,31 @@ public:
     delete static_cast<nsRect*>(aPropertyValue);
   }
 
   static void DestroyPoint(void* aPropertyValue)
   {
     delete static_cast<nsPoint*>(aPropertyValue);
   }
 
+#ifdef _MSC_VER
+// XXX Workaround MSVC issue by making the static FramePropertyDescriptor
+// non-const.  See bug 555727.
+#define NS_DECLARE_FRAME_PROPERTY(prop, dtor)                   \
+  static const FramePropertyDescriptor* prop() {                \
+    static FramePropertyDescriptor descriptor = { dtor };       \
+    return &descriptor;                                         \
+  }
+#else
 #define NS_DECLARE_FRAME_PROPERTY(prop, dtor)                   \
   static const FramePropertyDescriptor* prop() {                \
     static const FramePropertyDescriptor descriptor = { dtor }; \
     return &descriptor;                                         \
   }
+#endif
 
   NS_DECLARE_FRAME_PROPERTY(IBSplitSpecialSibling, nsnull)
   NS_DECLARE_FRAME_PROPERTY(IBSplitSpecialPrevSibling, nsnull)
 
   NS_DECLARE_FRAME_PROPERTY(ComputedOffsetProperty, DestroyPoint)
 
   NS_DECLARE_FRAME_PROPERTY(OutlineInnerRectProperty, DestroyRect)
   NS_DECLARE_FRAME_PROPERTY(PreEffectsBBoxProperty, DestroyRect)
@@ -877,23 +893,17 @@ public:
    * Apply the result of GetSkipSides() on this frame to an nsMargin by
    * setting to zero any sides that are skipped.
    */
   void ApplySkipSides(nsMargin& aMargin) const;
 
   /**
    * Like the frame's rect (see |GetRect|), which is the border rect,
    * other rectangles of the frame, in app units, relative to the parent.
-   *
-   * Note that GetMarginRect is not meaningful for blocks (anything with
-   * 'display:block', whether block frame or not) because of both the
-   * collapsing and 'auto' issues with GetUsedMargin (on which it
-   * depends).
    */
-  nsRect GetMarginRect() const;
   nsRect GetPaddingRect() const;
   nsRect GetContentRect() const;
 
   /**
    * Get the position of the frame's baseline, relative to the top of
    * the frame (its top border edge).  Only valid when Reflow is not
    * needed and when the frame returned nsHTMLReflowMetrics::
    * ASK_FOR_BASELINE as ascent in its reflow metrics.
@@ -1022,25 +1032,16 @@ public:
    */
   nsresult OverflowClip(nsDisplayListBuilder*   aBuilder,
                         const nsDisplayListSet& aFromSet,
                         const nsDisplayListSet& aToSet,
                         const nsRect&           aClipRect,
                         PRBool                  aClipBorderBackground = PR_FALSE,
                         PRBool                  aClipAll = PR_FALSE);
 
-  /**
-   * Clips the display items of aFromSet, putting the results in aToSet.
-   * All items are clipped.
-   */
-  nsresult Clip(nsDisplayListBuilder* aBuilder,
-                const nsDisplayListSet& aFromSet,
-                const nsDisplayListSet& aToSet,
-                const nsRect& aClipRect);
-
   enum {
     DISPLAY_CHILD_FORCE_PSEUDO_STACKING_CONTEXT = 0x01,
     DISPLAY_CHILD_FORCE_STACKING_CONTEXT = 0x02,
     DISPLAY_CHILD_INLINE = 0x04
   };
   /**
    * Adjusts aDirtyRect for the child's offset, checks that the dirty rect
    * actually intersects the child (or its descendants), calls BuildDisplayList
--- a/layout/generic/nsILineIterator.h
+++ b/layout/generic/nsILineIterator.h
@@ -103,25 +103,16 @@ public:
                      PRUint32* aLineFlags) = 0;
 
   /**
    * Given a frame that's a child of the block, find which line its on
    * and return that line index. Returns -1 if the frame cannot be found.
    */
   virtual PRInt32 FindLineContaining(nsIFrame* aFrame) = 0;
 
-  /**
-   * Given a Y coordinate relative to the block that provided this
-   * line iterator, return the line that contains the Y
-   * coordinate. Returns -1 in aLineNumberResult if the Y coordinate
-   * is above the first line. Returns N (where N is the number of
-   * lines) if the Y coordinate is below the last line.
-   */
-  virtual PRInt32 FindLineAt(nscoord aY) = 0;
-
   // Given a line number and an X coordinate, find the frame on the
   // line that is nearest to the X coordinate. The
   // aXIsBeforeFirstFrame and aXIsAfterLastFrame flags are updated
   // appropriately.
   NS_IMETHOD FindFrameAt(PRInt32 aLineNumber,
                          nscoord aX,
                          nsIFrame** aFrameFound,
                          PRBool* aXIsBeforeFirstFrame,
--- a/layout/generic/nsImageFrame.cpp
+++ b/layout/generic/nsImageFrame.cpp
@@ -1004,18 +1004,19 @@ nsImageFrame::DisplayAltFeedback(nsIRend
   // Make sure we have enough room to actually render the border within
   // our frame bounds
   if ((inner.width < 2 * borderEdgeWidth) || (inner.height < 2 * borderEdgeWidth)) {
     return;
   }
 
   // Paint the border
   nsRecessedBorder recessedBorder(borderEdgeWidth, PresContext());
-  nsCSSRendering::PaintBorder(PresContext(), aRenderingContext, this, inner,
-                              inner, recessedBorder, mStyleContext);
+  nsCSSRendering::PaintBorderWithStyleBorder(PresContext(), aRenderingContext,
+                                             this, inner, inner,
+                                             recessedBorder, mStyleContext);
 
   // Adjust the inner rect to account for the one pixel recessed border,
   // and a six pixel padding on each edge
   inner.Deflate(nsPresContext::CSSPixelsToAppUnits(ICON_PADDING+ALT_BORDER_WIDTH), 
                 nsPresContext::CSSPixelsToAppUnits(ICON_PADDING+ALT_BORDER_WIDTH));
   if (inner.IsEmpty()) {
     return;
   }
--- a/layout/generic/nsImageMap.cpp
+++ b/layout/generic/nsImageMap.cpp
@@ -78,18 +78,16 @@ public:
   virtual void ParseCoords(const nsAString& aSpec);
 
   virtual PRBool IsInside(nscoord x, nscoord y) const = 0;
   virtual void Draw(nsIFrame* aFrame, nsIRenderingContext& aRC) = 0;
   virtual void GetRect(nsIFrame* aFrame, nsRect& aRect) = 0;
 
   void HasFocus(PRBool aHasFocus);
 
-  void GetHREF(nsAString& aHref) const;
-
   nsCOMPtr<nsIContent> mArea;
   nscoord* mCoords;
   PRInt32 mNumCoords;
   PRPackedBool mHasFocus;
 };
 
 Area::Area(nsIContent* aArea)
   : mArea(aArea)
@@ -102,25 +100,16 @@ Area::Area(nsIContent* aArea)
 }
 
 Area::~Area()
 {
   MOZ_COUNT_DTOR(Area);
   delete [] mCoords;
 }
 
-void
-Area::GetHREF(nsAString& aHref) const
-{
-  aHref.Truncate();
-  if (mArea) {
-    mArea->GetAttr(kNameSpaceID_None, nsGkAtoms::href, aHref);
-  }
-}
-
 #include <stdlib.h>
 
 inline PRBool
 is_space(char c)
 {
   return (c == ' ' ||
           c == '\f' ||
           c == '\n' ||
--- a/layout/generic/nsIntervalSet.cpp
+++ b/layout/generic/nsIntervalSet.cpp
@@ -92,27 +92,16 @@ void nsIntervalSet::IncludeInterval(coor
         newInterval->mBegin = NS_MIN(newInterval->mBegin, subsumed->mBegin);
         newInterval->mEnd = NS_MAX(newInterval->mEnd, subsumed->mEnd);
         newInterval->mNext = subsumed->mNext;
         FreeInterval(subsumed);
         subsumed = newInterval->mNext;
     }
 }
 
-PRBool nsIntervalSet::HasPoint(coord_type aPoint) const
-{
-    Interval *current = mList;
-    while (current && current->mBegin <= aPoint) {
-        if (current->mEnd >= aPoint)
-            return PR_TRUE;
-        current = current->mNext;
-    }
-    return PR_FALSE;
-}
-
 PRBool nsIntervalSet::Intersects(coord_type aBegin, coord_type aEnd) const
 {
     Interval *current = mList;
     while (current && current->mBegin <= aEnd) {
         if (current->mEnd >= aBegin)
             return PR_TRUE;
         current = current->mNext;
     }
--- a/layout/generic/nsIntervalSet.h
+++ b/layout/generic/nsIntervalSet.h
@@ -71,21 +71,16 @@ public:
      * Removal of intervals added is not supported because that would
      * require keeping track of the individual intervals that were
      * added (nsIntervalMap should do that).  It would be simple to
      * implement ExcludeInterval if anyone wants it, though.
      */
     void IncludeInterval(coord_type aBegin, coord_type aEnd);
 
     /*
-     * Is the point aPoint contained within the set of intervals?
-     */
-    PRBool HasPoint(coord_type aPoint) const;
-
-    /*
      * Are _some_ points in [aBegin, aEnd] contained within the set
      * of intervals?
      */
     PRBool Intersects(coord_type aBegin, coord_type aEnd) const;
 
     /*
      * Are _all_ points in [aBegin, aEnd] contained within the set
      * of intervals?
--- a/layout/generic/nsLineBox.cpp
+++ b/layout/generic/nsLineBox.cpp
@@ -351,36 +351,16 @@ nsLineBox::DeleteLineList(nsPresContext*
       line->Destroy(shell);
     } while (! aLines.empty());
 #ifdef DEBUG
     NS_ASSERTION(numFrames == 0, "number of frames deleted does not match");
 #endif
   }
 }
 
-nsLineBox*
-nsLineBox::FindLineContaining(nsLineList& aLines, nsIFrame* aFrame,
-                              PRInt32* aFrameIndexInLine)
-{
-  NS_PRECONDITION(aFrameIndexInLine && !aLines.empty() && aFrame, "null ptr");
-  for (nsLineList::iterator line = aLines.begin(),
-                            line_end = aLines.end();
-       line != line_end;
-       ++line)
-  {
-    PRInt32 ix = line->IndexOf(aFrame);
-    if (ix >= 0) {
-      *aFrameIndexInLine = ix;
-      return line;
-    }
-  }
-  *aFrameIndexInLine = -1;
-  return nsnull;
-}
-
 PRBool
 nsLineBox::RFindLineContaining(nsIFrame* aFrame,
                                const nsLineList::iterator& aBegin,
                                nsLineList::iterator& aEnd,
                                nsIFrame* aLastFrameBeforeEnd,
                                PRInt32* aFrameIndexInLine)
 {
   NS_PRECONDITION(aFrame, "null ptr");
@@ -651,33 +631,16 @@ nsLineIterator::FindLineContaining(nsIFr
     if (line->Contains(aFrame)) {
       return lineNumber;
     }
     line = mLines[++lineNumber];
   }
   return -1;
 }
 
-/* virtual */ PRInt32
-nsLineIterator::FindLineAt(nscoord aY)
-{
-  nsLineBox* line = mLines[0];
-  if (!line || (aY < line->mBounds.y)) {
-    return -1;
-  }
-  PRInt32 lineNumber = 0;
-  while (lineNumber != mNumLines) {
-    if ((aY >= line->mBounds.y) && (aY < line->mBounds.YMost())) {
-      return lineNumber;
-    }
-    line = mLines[++lineNumber];
-  }
-  return mNumLines;
-}
-
 #ifdef IBMBIDI
 NS_IMETHODIMP
 nsLineIterator::CheckLineOrder(PRInt32                  aLine,
                                PRBool                   *aIsReordered,
                                nsIFrame                 **aFirstVisual,
                                nsIFrame                 **aLastVisual)
 {
   NS_ASSERTION (aLine >= 0 && aLine < mNumLines, "aLine out of range!");
--- a/layout/generic/nsLineBox.h
+++ b/layout/generic/nsLineBox.h
@@ -429,21 +429,16 @@ public:
 
   nscoord GetHeight() const {
     return mBounds.height;
   }
 
   static void DeleteLineList(nsPresContext* aPresContext, nsLineList& aLines,
                              nsIFrame* aDestructRoot);
 
-  // search from beginning to end
-  // XXX Should switch to API below
-  static nsLineBox* FindLineContaining(nsLineList& aLines, nsIFrame* aFrame,
-                                       PRInt32* aFrameIndexInLine);
-
   // search from end to beginning of [aBegin, aEnd)
   // Returns PR_TRUE if it found the line and PR_FALSE if not.
   // Moves aEnd as it searches so that aEnd points to the resulting line.
   // aLastFrameBeforeEnd is the last frame before aEnd (so if aEnd is
   // the end of the line list, it's just the last frame in the frame
   // list).
   static PRBool RFindLineContaining(nsIFrame* aFrame,
                                     const nsLineList_iterator& aBegin,
@@ -1540,17 +1535,16 @@ public:
   virtual PRInt32 GetNumLines();
   virtual PRBool GetDirection();
   NS_IMETHOD GetLine(PRInt32 aLineNumber,
                      nsIFrame** aFirstFrameOnLine,
                      PRInt32* aNumFramesOnLine,
                      nsRect& aLineBounds,
                      PRUint32* aLineFlags);
   virtual PRInt32 FindLineContaining(nsIFrame* aFrame);
-  virtual PRInt32 FindLineAt(nscoord aY);
   NS_IMETHOD FindFrameAt(PRInt32 aLineNumber,
                          nscoord aX,
                          nsIFrame** aFrameFound,
                          PRBool* aXIsBeforeFirstFrame,
                          PRBool* aXIsAfterLastFrame);
 
   NS_IMETHOD GetNextSiblingOnLine(nsIFrame*& aFrame, PRInt32 aLineNumber);
 #ifdef IBMBIDI
--- a/layout/generic/nsObjectFrame.cpp
+++ b/layout/generic/nsObjectFrame.cpp
@@ -748,19 +748,20 @@ nsObjectFrame::CreateWidget(nscoord aWid
     rpc->RegisterPluginForGeometryUpdates(this);
     rpc->UpdatePluginGeometry(this);
 
     // Here we set the background color for this widget because some plugins will use 
     // the child window background color when painting. If it's not set, it may default to gray
     // Sometimes, a frame doesn't have a background color or is transparent. In this
     // case, walk up the frame tree until we do find a frame with a background color
     for (nsIFrame* frame = this; frame; frame = frame->GetParent()) {
-      const nsStyleBackground* background = frame->GetStyleBackground();
-      if (!background->IsTransparent()) {  // make sure we got an actual color
-        mWidget->SetBackgroundColor(background->mBackgroundColor);
+      nscolor bgcolor =
+        frame->GetVisitedDependentColor(eCSSProperty_background_color);
+      if (NS_GET_A(bgcolor) > 0) {  // make sure we got an actual color
+        mWidget->SetBackgroundColor(bgcolor);
         break;
       }
     }
 
 #ifdef XP_MACOSX
     // Now that we have a widget we want to set the event model before
     // any events are processed.
     nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
--- a/layout/generic/nsTextFrameThebes.cpp
+++ b/layout/generic/nsTextFrameThebes.cpp
@@ -103,17 +103,16 @@
 #include "nsILineIterator.h"
 
 #include "nsIServiceManager.h"
 #ifdef ACCESSIBILITY
 #include "nsIAccessible.h"
 #include "nsIAccessibilityService.h"
 #endif
 #include "nsAutoPtr.h"
-#include "nsStyleSet.h"
 
 #include "nsBidiFrames.h"
 #include "nsBidiPresUtils.h"
 #include "nsBidiUtils.h"
 
 #include "nsIThebesFontMetrics.h"
 #include "gfxFont.h"
 #include "gfxContext.h"
@@ -3001,17 +3000,17 @@ nsTextPaintStyle::EnsureSufficientContra
     return PR_TRUE;
   }
   return PR_FALSE;
 }
 
 nscolor
 nsTextPaintStyle::GetTextColor()
 {
-  nscolor color = mFrame->GetStyleColor()->mColor;
+  nscolor color = mFrame->GetVisitedDependentColor(eCSSProperty_color);
   if (ShouldDarkenColors(mPresContext)) {
     color = DarkenColor(color);
   }
   return color;
 }
 
 PRBool
 nsTextPaintStyle::GetSelectionColors(nscolor* aForeColor,
@@ -3088,21 +3087,21 @@ nsTextPaintStyle::InitCommonColors()
   if (mInitCommonColors)
     return;
 
   nsStyleContext* sc = mFrame->GetStyleContext();
 
   nsStyleContext* bgContext =
     nsCSSRendering::FindNonTransparentBackground(sc);
   NS_ASSERTION(bgContext, "Cannot find NonTransparentBackground.");
-  const nsStyleBackground* bg = bgContext->GetStyleBackground();
+  nscolor bgColor =
+    bgContext->GetVisitedDependentColor(eCSSProperty_background_color);
 
   nscolor defaultBgColor = mPresContext->DefaultBackgroundColor();
-  mFrameBackgroundColor = NS_ComposeColors(defaultBgColor,
-                                           bg->mBackgroundColor);
+  mFrameBackgroundColor = NS_ComposeColors(defaultBgColor, bgColor);
 
   if (bgContext->GetStyleDisplay()->mAppearance) {
     // Assume a native widget has sufficient contrast always
     mSufficientContrast = 0;
     mInitCommonColors = PR_TRUE;
     return;
   }
 
@@ -3162,19 +3161,19 @@ nsTextPaintStyle::InitSelectionColors()
       selectionStatus == nsISelectionController::SELECTION_ON) {
     nsRefPtr<nsStyleContext> sc = nsnull;
     sc = mPresContext->StyleSet()->
       ProbePseudoElementStyle(selectionContent,
                               nsCSSPseudoElements::ePseudo_mozSelection,
                               mFrame->GetStyleContext());
     // Use -moz-selection pseudo class.
     if (sc) {
-      const nsStyleBackground* bg = sc->GetStyleBackground();
-      mSelectionBGColor = bg->mBackgroundColor;
-      mSelectionTextColor = sc->GetStyleColor()->mColor;
+      mSelectionBGColor =
+        sc->GetVisitedDependentColor(eCSSProperty_background_color);
+      mSelectionTextColor = sc->GetVisitedDependentColor(eCSSProperty_color);
       return PR_TRUE;
     }
   }
 
   nsILookAndFeel* look = mPresContext->LookAndFeel();
 
   nscolor selectionBGColor;
   look->GetColor(nsILookAndFeel::eColor_TextSelectBackground,
@@ -3194,18 +3193,18 @@ nsTextPaintStyle::InitSelectionColors()
     mSelectionBGColor = selectionBGColor;
   }
 
   look->GetColor(nsILookAndFeel::eColor_TextSelectForeground,
                  mSelectionTextColor);
 
   // On MacOS X, we don't exchange text color and BG color.
   if (mSelectionTextColor == NS_DONT_CHANGE_COLOR) {
-    mSelectionTextColor = EnsureDifferentColors(mFrame->GetStyleColor()->mColor,
-                                                mSelectionBGColor);
+    nscoord frameColor = mFrame->GetVisitedDependentColor(eCSSProperty_color);
+    mSelectionTextColor = EnsureDifferentColors(frameColor, mSelectionBGColor);
   } else {
     EnsureSufficientContrast(&mSelectionTextColor, &mSelectionBGColor);
   }
   return PR_TRUE;
 }
 
 nsTextPaintStyle::nsSelectionStyle*
 nsTextPaintStyle::GetSelectionStyle(PRInt32 aIndex)
@@ -3999,23 +3998,23 @@ nsTextFrame::GetTextDecorations(nsPresCo
        decorMask && context && context->HasTextDecorations();
        context = context->GetParent()) {
     const nsStyleTextReset* styleText = context->GetStyleTextReset();
     if (!useOverride && 
         (NS_STYLE_TEXT_DECORATION_OVERRIDE_ALL & styleText->mTextDecoration)) {
       // This handles the <a href="blah.html"><font color="green">La 
       // la la</font></a> case. The link underline should be green.
       useOverride = PR_TRUE;
-      overrideColor = context->GetStyleColor()->mColor;
+      overrideColor = context->GetVisitedDependentColor(eCSSProperty_color);
     }
 
     PRUint8 useDecorations = decorMask & styleText->mTextDecoration;
     if (useDecorations) {// a decoration defined here
-      nscolor color = context->GetStyleColor()->mColor;
-  
+      nscolor color = context->GetVisitedDependentColor(eCSSProperty_color);
+
       if (NS_STYLE_TEXT_DECORATION_UNDERLINE & useDecorations) {
         decorations.mUnderColor = useOverride ? overrideColor : color;
         decorMask &= ~NS_STYLE_TEXT_DECORATION_UNDERLINE;
         decorations.mDecorations |= NS_STYLE_TEXT_DECORATION_UNDERLINE;
       }
       if (NS_STYLE_TEXT_DECORATION_OVERLINE & useDecorations) {
         decorations.mOverColor = useOverride ? overrideColor : color;
         decorMask &= ~NS_STYLE_TEXT_DECORATION_OVERLINE;
--- a/layout/mathml/nsIMathMLFrame.h
+++ b/layout/mathml/nsIMathMLFrame.h
@@ -79,19 +79,16 @@ public:
   */
   NS_IMETHOD
   GetBoundingMetrics(nsBoundingMetrics& aBoundingMetrics) = 0;
 
   NS_IMETHOD
   SetBoundingMetrics(const nsBoundingMetrics& aBoundingMetrics) = 0;
 
   NS_IMETHOD
-  GetReference(nsPoint& aReference) = 0;
-
-  NS_IMETHOD
   SetReference(const nsPoint& aReference) = 0;
 
   virtual eMathMLFrameType GetMathMLFrameType() = 0;
 
  /* SUPPORT FOR STRETCHY ELEMENTS */
  /*====================================================================*/
 
  /* Stretch :
@@ -112,40 +109,30 @@ public:
   *        of the frame, on output the size after stretching.
   */
   NS_IMETHOD 
   Stretch(nsIRenderingContext& aRenderingContext,
           nsStretchDirection   aStretchDirection,
           nsBoundingMetrics&   aContainerSize,
           nsHTMLReflowMetrics& aDesiredStretchSize) = 0;
 
- /* GetEmbellishData/SetEmbellishData :
-  * Get/Set the mEmbellishData member variable.
-  */
-
+ /* Get the mEmbellishData member variable. */
+ 
   NS_IMETHOD
   GetEmbellishData(nsEmbellishData& aEmbellishData) = 0;
 
-  NS_IMETHOD
-  SetEmbellishData(const nsEmbellishData& aEmbellishData) = 0;
-
 
  /* SUPPORT FOR SCRIPTING ELEMENTS */
  /*====================================================================*/
 
- /* GetPresentationData/SetPresentationData :
-  * Get/Set the mPresentationData member variable.
-  */
+ /* Get the mPresentationData member variable. */
 
   NS_IMETHOD
   GetPresentationData(nsPresentationData& aPresentationData) = 0;
 
-  NS_IMETHOD
-  SetPresentationData(const nsPresentationData& aPresentationData) = 0;
-
   /* InheritAutomaticData() / TransmitAutomaticData() :
    * There are precise rules governing each MathML frame and its children.
    * Properties such as the scriptlevel or the embellished nature of a frame
    * depend on those rules. Also, certain properties that we use to emulate
    * TeX rendering rules are frame-dependent too. These two methods are meant
    * to be implemented by frame classes that need to assert specific properties
    * within their subtrees.
    *
--- a/layout/mathml/nsMathMLChar.cpp
+++ b/layout/mathml/nsMathMLChar.cpp
@@ -1928,20 +1928,20 @@ private:
   nsStyleContext* mStyleContext;
   nsRect          mRect;
 };
 
 void nsDisplayMathMLCharBackground::Paint(nsDisplayListBuilder* aBuilder,
                                           nsIRenderingContext* aCtx)
 {
   const nsStyleBorder* border = mStyleContext->GetStyleBorder();
-  const nsStyleBackground* backg = mStyleContext->GetStyleBackground();
   nsRect rect(mRect + aBuilder->ToReferenceFrame(mFrame));
   nsCSSRendering::PaintBackgroundWithSC(mFrame->PresContext(), *aCtx, mFrame,
-                                        mVisibleRect, rect, *backg, *border,
+                                        mVisibleRect, rect,
+                                        mStyleContext, *border,
                                         aBuilder->GetBackgroundPaintFlags());
 }
 
 class nsDisplayMathMLCharForeground : public nsDisplayItem {
 public:
   nsDisplayMathMLCharForeground(nsIFrame* aFrame, nsMathMLChar* aChar,
 				PRBool aIsSelected)
     : nsDisplayItem(aFrame), mChar(aChar), mIsSelected(aIsSelected) {
@@ -2003,21 +2003,19 @@ void nsDisplayMathMLCharDebug::Paint(nsD
 {
   // for visual debug
   PRIntn skipSides = 0;
   nsPresContext* presContext = mFrame->PresContext();
   const nsStyleBorder* border = mFrame->GetStyleBorder();
   nsStyleContext* styleContext = mFrame->GetStyleContext();
   nsRect rect = mRect + aBuilder->ToReferenceFrame(mFrame);
   nsCSSRendering::PaintBorder(presContext, *aCtx, mFrame,
-                              mVisibleRect, rect, *border, styleContext,
-                              skipSides);
+                              mVisibleRect, rect, styleContext, skipSides);
   nsCSSRendering::PaintOutline(presContext, *aCtx, mFrame,
-                               mVisibleRect, rect, *border,
-                               *mFrame->GetStyleOutline(), styleContext);
+                               mVisibleRect, rect, styleContext);
 }
 #endif
 
 
 nsresult
 nsMathMLChar::Display(nsDisplayListBuilder*   aBuilder,
                       nsIFrame*               aForFrame,
                       const nsDisplayListSet& aLists,
--- a/layout/mathml/nsMathMLFrame.h
+++ b/layout/mathml/nsMathMLFrame.h
@@ -67,22 +67,16 @@ public:
 
   NS_IMETHOD
   SetBoundingMetrics(const nsBoundingMetrics& aBoundingMetrics) {
     mBoundingMetrics = aBoundingMetrics;
     return NS_OK;
   }
 
   NS_IMETHOD
-  GetReference(nsPoint& aReference) {
-    aReference = mReference;
-    return NS_OK;
-  }
-
-  NS_IMETHOD
   SetReference(const nsPoint& aReference) {
     mReference = aReference;
     return NS_OK;
   }
 
   virtual eMathMLFrameType GetMathMLFrameType();
 
   NS_IMETHOD
@@ -94,36 +88,24 @@ public:
     return NS_OK;
   }
 
   NS_IMETHOD
   GetEmbellishData(nsEmbellishData& aEmbellishData) {
     aEmbellishData = mEmbellishData;
     return NS_OK;
   }
- 
-  NS_IMETHOD
-  SetEmbellishData(const nsEmbellishData& aEmbellishData) {
-    mEmbellishData = aEmbellishData;
-    return NS_OK;
-  }
 
   NS_IMETHOD
   GetPresentationData(nsPresentationData& aPresentationData) {
     aPresentationData = mPresentationData;
     return NS_OK;
   }
 
   NS_IMETHOD
-  SetPresentationData(const nsPresentationData& aPresentationData) {
-    mPresentationData = aPresentationData;
-    return NS_OK;
-  }
-
-  NS_IMETHOD
   InheritAutomaticData(nsIFrame* aParent);
 
   NS_IMETHOD
   TransmitAutomaticData()
   {
     return NS_OK;
   }
 
--- a/layout/reftests/bugs/reftest.list
+++ b/layout/reftests/bugs/reftest.list
@@ -1395,17 +1395,17 @@ fails HTTP(..) == 518172-2b.html 518172-
 == 528096-1.html 528096-1-ref.html
 == 530686-1.html 530686-1-ref.html
 == 531098-1.html 531098-1-ref.html
 == 531371-1.html 531371-1-ref.html
 == 534526-1a.html 534526-1-ref.html
 == 534526-1b.html 534526-1-ref.html
 == 534808-1.html 534808-1-ref.html
 == 534808-2.html 534808-2-ref.html
-== 534919-1.html 534919-1-ref.html
+fails-if(http.oscpu.match(/Mac\x20OS\x20X\x2010\.6$/)) == 534919-1.html 534919-1-ref.html # fails on 10.6, bug 554188
 == 537507-1.xul 537507-1-ref.xul
 == 537507-2.html 537507-2-ref.html
 == 537471-1.html 537471-1-ref.html
 == 538909-1.html 538909-1-ref.html
 == 538935-1.html 538935-1-ref.html
 == 539226-1.html about:blank
 == 539323-1.html 539323-1-ref.html
 == 539323-2.html 539323-2-ref.html
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/border-1-ref.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+
+div { margin: 2px; }
+.unvis { border: medium solid olive; border-top: dashed thin blue; }
+.vis { border: medium solid fuchsia; border-top-style: dashed; border-top-width: thin; border-right-color: silver; }
+
+</style>
+<div class="unvis">unvisited</div>
+<div class="vis">visited</div>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/border-1.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+
+a { text-decoration: none; color: -moz-initial; display: block; margin: 2px; }
+:link { border: medium solid olive; border-top: dashed thin blue; }
+:visited { border: thick dotted fuchsia; border-right: thin double silver; }
+
+</style>
+<a href="unvisited-page.html">unvisited</a>
+<a href="visited-page.html">visited</a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/border-2-ref.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777): default color for 'border'</title>
+<style type="text/css">
+
+div { margin: 2px; }
+.link { color: maroon; border: medium solid maroon; border-top: dashed thin blue; }
+.visited { color: gray; border: medium solid fuchsia; border-top: dashed thin fuchsia; border-right-color: gray; }
+
+</style>
+<div class="link">unvisited</div>
+<div class="visited">visited</div>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/border-2a.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777): implicit default color for 'border'</title>
+<style type="text/css">
+
+a { text-decoration: none; display: block; margin: 2px; }
+:link { color: maroon; border: medium solid; border-top: dashed thin blue; }
+:visited { color: gray; border: thick dotted fuchsia; border-right: thin double; }
+
+</style>
+<a href="unvisited-page.html">unvisited</a>
+<a href="visited-page.html">visited</a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/border-2b.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777): explicit default color for 'border'</title>
+<style type="text/css">
+
+a { text-decoration: none; display: block; margin: 2px; }
+:link { color: maroon; border: medium solid currentColor; border-top: dashed thin blue; }
+:visited { color: gray; border: thick dotted fuchsia; border-right: thin double currentColor; }
+
+</style>
+<a href="unvisited-page.html">unvisited</a>
+<a href="visited-page.html">visited</a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/border-collapse-1-ref.html
@@ -0,0 +1,32 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+
+div.table { display: table; border-collapse: collapse }
+div.row { display: table-row }
+div.link, div.visited { display: table-cell }
+
+.row1 .link { border: medium solid blue }
+.row1 .visited { border: medium solid fuchsia }
+
+.row2 .link { border: thin dotted black }
+.row2 .visited { border: thin dotted red }
+
+.row3 .link { border: 7px double gray }
+.row3 .visited { border: 7px double olive }
+
+</style>
+<div class="table">
+  <div class="row row1">
+    <div class="link">unvisited</div>
+    <div class="visited">visited</div>
+  </div>
+  <div class="row row2">
+    <div class="visited">visited</div>
+    <div class="link">unvisited</div>
+  </div>
+  <div class="row row3">
+    <div class="link">unvisited</div>
+    <div class="visited">visited</div>
+  </div>
+</div>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/border-collapse-1.html
@@ -0,0 +1,32 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+
+div.table { display: table; border-collapse: collapse }
+div.row { display: table-row }
+a { text-decoration: none; color: -moz-initial; display: table-cell }
+
+.row1 :link { border: medium solid blue }
+.row1 :visited { border: thick dashed fuchsia }
+
+.row2 :link { border: thin dotted black }
+.row2 :visited { border: thick hidden rgba(255, 0, 0, 0.5) }
+
+.row3 :link { border: 7px double gray }
+.row3 :visited { border: 4px inset olive }
+
+</style>
+<div class="table">
+  <div class="row row1">
+    <a href="unvisited-page.html">unvisited</a>
+    <a href="visited-page.html">visited</a>
+  </div>
+  <div class="row row2">
+    <a href="visited-page.html">visited</a>
+    <a href="unvisited-page.html">unvisited</a>
+  </div>
+  <div class="row row3">
+    <a href="unvisited-page.html">unvisited</a>
+    <a href="visited-page.html">visited</a>
+  </div>
+</div>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/color-choice-1-ref.html
@@ -0,0 +1,10 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+
+.link { background: rgba(179, 25, 87, 0.72); }
+.visited { background: rgba(28, 215, 119, 0.72); }
+
+</style>
+<span class="link">unvisited</span>
+<span class="visited">visited</span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/color-choice-1.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+
+a { text-decoration: none; color: -moz-initial; }
+:link { background: rgba(179, 25, 87, 0.72); }
+:visited { background: rgba(28, 215, 119, 0.31); }
+
+</style>
+<a href="unvisited-page.html">unvisited</a>
+<a href="visited-page.html">visited</a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/color-on-bullets-1-ref.html
@@ -0,0 +1,18 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+ul, ol, li { margin: 0; padding: 0 }
+li { margin-left: 4em }
+.link { color: rgba(255, 177, 83, 0.8) }
+.visited { color: rgba(128, 99, 12, 0.8) }
+
+</style>
+<ol>
+<li class="link">unvisited</li>
+<li class="visited">visited</li>
+</ol>
+<ul>
+<li class="link">unvisited</li>
+<li class="visited">visited</li>
+</ul>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/color-on-bullets-1.html
@@ -0,0 +1,18 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none; display: list-item; margin-left: 4em }
+:link { color: rgba(255, 177, 83, 0.8) }
+:visited { color: rgba(128, 99, 12, 0.4) }
+
+</style>
+<!-- FIXME: workaround list numbering bug by using ol instead of div -->
+<ol style="list-style-type: decimal; margin: 0; padding: 0">
+<a href="unvisited-page.html">unvisited</a>
+<a href="visited-page.html">visited</a>
+</ol>
+<div style="list-style-type: disc">
+<a href="unvisited-page.html">unvisited</a>
+<a href="visited-page.html">visited</a>
+</div>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/color-on-link-1-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+span { color: fuchsia; }
+</style>
+<span>link</span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/color-on-link-1.html
@@ -0,0 +1,8 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+a { text-decoration: none }
+:link { color: fuchsia; }
+:visited { color: purple; }
+</style>
+<a href="unvisited-page.html">link</a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/color-on-link-before-1.html
@@ -0,0 +1,8 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+a { text-decoration: none }
+:link:before { content: "link"; color: fuchsia; }
+:visited:before { content: "link"; color: purple; }
+</style>
+<a href="unvisited-page.html"></a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/color-on-text-decoration-1-ref.html
@@ -0,0 +1,18 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+
+body > span { text-decoration: underline }
+body > span > span { text-decoration: overline }
+body > span > span > span { text-decoration: line-through }
+
+.link { color: olive }
+.link > span { color: fuchsia }
+.link > span > span { color: black }
+.visited { color: gray }
+.visited > span { color: maroon }
+.visited > span > span { color: purple }
+
+</style>
+<span class="link"><span><span>unvisited</span></span></span>
+<span class="visited"><span><span>visited</span></span></span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/color-on-text-decoration-1.html
@@ -0,0 +1,18 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+
+body > a { text-decoration: underline }
+body > a > span { text-decoration: overline }
+body > a > span > span { text-decoration: line-through }
+
+:link { color: olive }
+:link > span { color: fuchsia }
+:link > span > span { color: black }
+:visited { color: gray }
+:visited > span { color: maroon }
+:visited > span > span { color: purple }
+
+</style>
+<a href="unvisited-page.html"><span><span>unvisited</span></span></a>
+<a href="visited-page.html"><span><span>visited</span></span></a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/color-on-visited-1-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+span { color: purple; }
+</style>
+<span>link</span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/color-on-visited-1.html
@@ -0,0 +1,8 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+a { text-decoration: none }
+:link { color: fuchsia; }
+:visited { color: purple; }
+</style>
+<a href="visited-page.html">link</a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/color-on-visited-before-1.html
@@ -0,0 +1,8 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+a { text-decoration: none }
+:link:before { content: "link"; color: fuchsia; }
+:visited:before { content: "link"; color: purple; }
+</style>
+<a href="visited-page.html"></a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/content-before-1-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+span:before { content: "link"; }
+</style>
+<span></span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/content-color-on-link-before-1-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+span:before { content: "link"; color: fuchsia; }
+</style>
+<span></span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/content-color-on-link-before-1.html
@@ -0,0 +1,8 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+a { text-decoration: none }
+:link:before { content: "link"; color: fuchsia; }
+:visited:before { content: "visited"; color: purple; }
+</style>
+<a href="unvisited-page.html"></a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/content-color-on-visited-before-1-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+span:before { content: "link"; color: purple; }
+</style>
+<span></span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/content-color-on-visited-before-1.html
@@ -0,0 +1,8 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+a { text-decoration: none }
+:link:before { content: "link"; color: fuchsia; }
+:visited:before { content: "visited"; color: purple; }
+</style>
+<a href="visited-page.html"></a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/content-on-link-before-1.html
@@ -0,0 +1,8 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+* { color: -moz-initial; text-decoration: none }
+:link:before { content: "link"; }
+:visited:before { content: "visited"; }
+</style>
+<a href="unvisited-page.html"></a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/content-on-visited-before-1.html
@@ -0,0 +1,8 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+* { color: -moz-initial; text-decoration: none }
+:link:before { content: "link"; }
+:visited:before { content: "visited"; }
+</style>
+<a href="visited-page.html"></a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/first-line-1-ref.html
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML>
+<html lang="en-US">
+<head>
+	<title>:visited and ::first-line (reference)</title>
+</head>
+<body>
+
+<div><span style="color: fuchsia">unvisited</span><br><span style="color: blue">link</span></div>
+<div><span style="color: maroon">visited</span><br><span style="color: purple">link</span></div>
+
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/first-line-1.html
@@ -0,0 +1,22 @@
+<!DOCTYPE HTML>
+<html lang="en-US">
+<head>
+	<title>:visited and ::first-line</title>
+	<style type="text/css">
+	
+	:link, :visited { display: block; text-decoration: none; }
+
+	:link { color: blue }
+	:link::first-line { color: fuchsia; }
+	:visited { color: purple }
+	:visited::first-line { color: maroon; }
+
+	</style>
+</head>
+<body>
+
+<a href="unvisited-page.html">unvisited<br>link</a>
+<a href="visited-page.html">visited<br>link</a>
+
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/inherit-keyword-1-ref.html
@@ -0,0 +1,15 @@
+<!DOCTYPE HTML>
+<!--
+    Intentionally using an HTML reference for an XHTML test, just to
+    mix things up a little. :-)
+  -->
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+span { text-decoration: none; color: olive }
+
+</style>
+<span>unvisited / unvisited</span>
+<span>unvisited / visited</span>
+<span>visited / unvisited</span>
+<span>visited / visited</span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/inherit-keyword-1.xhtml
@@ -0,0 +1,20 @@
+<!DOCTYPE HTML>
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none }
+body > :link { color: olive; }
+body > :visited { color: fuchsia; }
+a > a { color: inherit; }
+
+</style>
+</head>
+<body>
+<a href="unvisited-page.html"><a href="unvisited-page.html">unvisited / unvisited</a></a>
+<a href="unvisited-page.html"><a href="visited-page.html">unvisited / visited</a></a>
+<a href="visited-page.html"><a href="unvisited-page.html">visited / unvisited</a></a>
+<a href="visited-page.html"><a href="visited-page.html">visited / visited</a></a>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/outline-1-ref.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+
+div { margin: 8px; }
+.unvis { outline: medium dotted blue; }
+.vis { outline: medium dotted silver; }
+
+</style>
+<div class="unvis">unvisited</div>
+<div class="vis">visited</div>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/outline-1.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+
+a { text-decoration: none; color: -moz-initial; display: block; margin: 8px; }
+:link { outline: medium dotted blue; }
+:visited { outline: thick dashed silver; }
+
+</style>
+<a href="unvisited-page.html">unvisited</a>
+<a href="visited-page.html">visited</a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/reftest.list
@@ -0,0 +1,4 @@
+# Because coloring of visited links is asynchronous and does not block
+# or fire any events, the tests in this directory are not run through
+# the reftest harness.  Instead, they are run through
+# layout/style/tests/test_visited_reftests.html .
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-adj-sibling-1-ref.html
@@ -0,0 +1,7 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+span { color: olive; }
+</style>
+<span>unvisited</span>
+<span>visited</span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-adj-sibling-1.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none }
+:link + span { color: olive; }
+:visited + span { color: fuchsia; }
+
+</style>
+<a href="unvisited-page.html"></a><span>unvisited</span>
+<a href="visited-page.html"></a><span>visited</span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-adj-sibling-2-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<span style="color: olive">unvisited + unvisited</span>
+<span style="color: fuchsia">unvisited + visited</span>
+<span style="color: olive">visited + unvisited</span>
+<span style="color: fuchsia">visited + visited</span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-adj-sibling-2.html
@@ -0,0 +1,15 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none }
+:link + :link { color: olive; }
+:visited + :link { color: red; }
+:link + :visited { color: fuchsia; }
+:visited + :visited { color: red; }
+
+</style>
+<a href="unvisited-page.html"></a><a href="unvisited-page.html">unvisited + unvisited</a>
+<a href="unvisited-page.html"></a><a href="visited-page.html">unvisited + visited</a>
+<a href="visited-page.html"></a><a href="unvisited-page.html">visited + unvisited</a>
+<a href="visited-page.html"></a><a href="visited-page.html">visited + visited</a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-any-sibling-1-ref.html
@@ -0,0 +1,7 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+div { color: olive; }
+</style>
+<div>unvisited</div>
+<div>visited</div>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-any-sibling-1.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none }
+:link ~ span { color: olive; }
+:visited ~ span { color: fuchsia; }
+
+</style>
+<div><a href="unvisited-page.html"></a><span>unvisited</span></div>
+<div><a href="visited-page.html"></a><span>visited</span></div>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-any-sibling-2-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<div style="color: olive">unvisited + unvisited</div>
+<div style="color: fuchsia">unvisited + visited</div>
+<div style="color: olive">visited + unvisited</div>
+<div style="color: fuchsia">visited + visited</div>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-any-sibling-2.html
@@ -0,0 +1,15 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none }
+:link ~ :link { color: olive; }
+:visited ~ :link { color: red; }
+:link ~ :visited { color: fuchsia; }
+:visited ~ :visited { color: red; }
+
+</style>
+<div><a href="unvisited-page.html"></a><a href="unvisited-page.html">unvisited + unvisited</a></div>
+<div><a href="unvisited-page.html"></a><a href="visited-page.html">unvisited + visited</a></div>
+<div><a href="visited-page.html"></a><a href="unvisited-page.html">visited + unvisited</a></div>
+<div><a href="visited-page.html"></a><a href="visited-page.html">visited + visited</a></div>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-child-1-ref.html
@@ -0,0 +1,4 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<span style="color: olive">unvisited</span>
+<span style="color: fuchsia">visited</span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-child-1.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none }
+:link > span { color: olive; }
+:visited > span { color: fuchsia; }
+
+</style>
+<a href="unvisited-page.html"><span>unvisited</span></a>
+<a href="visited-page.html"><span>visited</span></a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-child-2-ref.xhtml
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML>
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+</head>
+<body>
+<span style="color: olive">unvisited / unvisited</span>
+<span style="color: fuchsia">unvisited / visited</span>
+<span style="color: olive">visited / unvisited</span>
+<span style="color: fuchsia">visited / visited</span>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-child-2.xhtml
@@ -0,0 +1,21 @@
+<!DOCTYPE HTML>
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none }
+:link > :link { color: olive; }
+:visited > :link { color: red; }
+:link > :visited { color: fuchsia; }
+:visited > :visited { color: red; }
+
+</style>
+</head>
+<body>
+<a href="unvisited-page.html"><a href="unvisited-page.html">unvisited / unvisited</a></a>
+<a href="unvisited-page.html"><a href="visited-page.html">unvisited / visited</a></a>
+<a href="visited-page.html"><a href="unvisited-page.html">visited / unvisited</a></a>
+<a href="visited-page.html"><a href="visited-page.html">visited / visited</a></a>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-descendant-1-ref.html
@@ -0,0 +1,4 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<span style="color: olive">unvisited</span>
+<span style="color: fuchsia">visited</span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-descendant-1.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none }
+:link span { color: olive; }
+:visited span { color: fuchsia; }
+
+</style>
+<a href="unvisited-page.html"><span>unvisited</span></a>
+<a href="visited-page.html"><span>visited</span></a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-descendant-2-ref.xhtml
@@ -0,0 +1,36 @@
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+body { color: black }
+span.l { color: olive; background: rgba(0, 255, 255, 0.5); }
+span.v { color: fuchsia; background: rgba(0, 0, 255, 0.5) }
+
+</style>
+</head>
+<body>
+
+<span class="l">unvisited</span> (<span class="l">unvisited</span>)
+<span class="l">unvisited</span> (<span class="v">visited</span>)
+<span class="v">visited</span> (<span class="l">unvisited</span>)
+<span class="v">visited</span> (<span class="v">visited</span>)
+
+<span class="u">unvisited</span> (<span class="l">unvisited</span>)
+<span class="u">unvisited</span> (<span class="v">visited</span>)
+<span class="u">visited</span> (<span class="l">unvisited</span>)
+<span class="u">visited</span> (<span class="v">visited</span>)
+
+<span class="l">unvisited</span> (<span class="l">unvisited</span>)
+<span class="l">unvisited</span> (<span class="l">visited</span>)
+<span class="v">visited</span> (<span class="l">unvisited</span>)
+<span class="v">visited</span> (<span class="l">visited</span>)
+
+<span class="u">unvisited</span> (<span class="u">unvisited</span>)
+<span class="u">unvisited</span> (<span class="u">visited</span>)
+<span class="u">visited</span> (<span class="u">unvisited</span>)
+<span class="u">visited</span> (<span class="u">visited</span>)
+
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/selector-descendant-2.xhtml
@@ -0,0 +1,36 @@
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none; color: black }
+.styled:link span { color: olive; background: rgba(0, 255, 255, 0.5); }
+.styled:visited span { color: fuchsia; background: rgba(0, 0, 255, 0.5) }
+
+</style>
+</head>
+<body>
+
+<a class="styled" href="unvisited-page.html"><span>unvisited</span> (<a class="styled" href="unvisited-page.html"><span>unvisited</span></a>)</a>
+<a class="styled" href="unvisited-page.html"><span>unvisited</span> (<a class="styled" href="visited-page.html"><span>visited</span></a>)</a>
+<a class="styled" href="visited-page.html"><span>visited</span> (<a class="styled" href="unvisited-page.html"><span>unvisited</span></a>)</a>
+<a class="styled" href="visited-page.html"><span>visited</span> (<a class="styled" href="visited-page.html"><span>visited</span></a>)</a>
+
+<a href="unvisited-page.html"><span>unvisited</span> (<a class="styled" href="unvisited-page.html"><span>unvisited</span></a>)</a>
+<a href="unvisited-page.html"><span>unvisited</span> (<a class="styled" href="visited-page.html"><span>visited</span></a>)</a>
+<a href="visited-page.html"><span>visited</span> (<a class="styled" href="unvisited-page.html"><span>unvisited</span></a>)</a>
+<a href="visited-page.html"><span>visited</span> (<a class="styled" href="visited-page.html"><span>visited</span></a>)</a>
+
+<a class="styled" href="unvisited-page.html"><span>unvisited</span> (<a href="unvisited-page.html"><span>unvisited</span></a>)</a>
+<a class="styled" href="unvisited-page.html"><span>unvisited</span> (<a href="visited-page.html"><span>visited</span></a>)</a>
+<a class="styled" href="visited-page.html"><span>visited</span> (<a href="unvisited-page.html"><span>unvisited</span></a>)</a>
+<a class="styled" href="visited-page.html"><span>visited</span> (<a href="visited-page.html"><span>visited</span></a>)</a>
+
+<a href="unvisited-page.html"><span>unvisited</span> (<a href="unvisited-page.html"><span>unvisited</span></a>)</a>
+<a href="unvisited-page.html"><span>unvisited</span> (<a href="visited-page.html"><span>visited</span></a>)</a>
+<a href="visited-page.html"><span>visited</span> (<a href="unvisited-page.html"><span>unvisited</span></a>)</a>
+<a href="visited-page.html"><span>visited</span> (<a href="visited-page.html"><span>visited</span></a>)</a>
+
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/subject-of-selector-1-ref.html
@@ -0,0 +1,4 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<span style="color: olive">unvisited</span>
+<span style="color: fuchsia">visited</span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/subject-of-selector-adj-sibling-1.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none }
+span + :link { color: olive; }
+span + :visited { color: fuchsia; }
+
+</style>
+<span></span><a href="unvisited-page.html">unvisited</a>
+<span></span><a href="visited-page.html">visited</a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/subject-of-selector-any-sibling-1.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none }
+span ~ :link { color: olive; }
+span ~ :visited { color: fuchsia; }
+
+</style>
+<span><span></span><a href="unvisited-page.html">unvisited</a></span>
+<span><span></span><a href="visited-page.html">visited</a></span>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/subject-of-selector-child-1.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none }
+body > :link { color: olive; }
+body > :visited { color: fuchsia; }
+
+</style>
+<a href="unvisited-page.html">unvisited</a>
+<a href="visited-page.html">visited</a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/subject-of-selector-descendant-1.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none }
+body :link { color: olive; }
+body :visited { color: fuchsia; }
+
+</style>
+<a href="unvisited-page.html">unvisited</a>
+<a href="visited-page.html">visited</a>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/subject-of-selector-descendant-2-ref.xhtml
@@ -0,0 +1,33 @@
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+.unstylink { color: blue }
+.unstyvis { color: purple }
+
+.stylink { color: olive; background: rgba(0, 255, 255, 0.5); }
+.styvis { color: fuchsia; background: rgba(0, 0, 255, 0.5) }
+
+</style>
+</head>
+<body>
+
+<span class="stylink">unvisited (<span class="stylink">unvisited</span>)</span>
+<span class="stylink">unvisited (<span class="styvis">visited</span>)</span>
+<span class="styvis">visited (<span class="stylink">unvisited</span>)</span>
+<span class="styvis">visited (<span class="styvis">visited</span>)</span>
+
+<span class="unstylink">unvisited (<span class="stylink">unvisited</span>)</span>
+<span class="unstylink">unvisited (<span class="styvis">visited</span>)</span>
+<span class="unstyvis">visited (<span class="stylink">unvisited</span>)</span>
+<span class="unstyvis">visited (<span class="styvis">visited</span>)</span>
+
+<span class="stylink">unvisited (<span class="unstylink">unvisited</span>)</span>
+<span class="stylink">unvisited (<span class="unstyvis">visited</span>)</span>
+<span class="styvis">visited (<span class="unstylink">unvisited</span>)</span>
+<span class="styvis">visited (<span class="unstyvis">visited</span>)</span>
+
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/subject-of-selector-descendant-2.xhtml
@@ -0,0 +1,33 @@
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style>
+
+a { text-decoration: none }
+:link { color: blue }
+:visited { color: purple }
+body .styled:link { color: olive; background: rgba(0, 255, 255, 0.5); }
+body .styled:visited { color: fuchsia; background: rgba(0, 0, 255, 0.5) }
+
+</style>
+</head>
+<body>
+
+<a class="styled" href="unvisited-page.html">unvisited (<a class="styled" href="unvisited-page.html">unvisited</a>)</a>
+<a class="styled" href="unvisited-page.html">unvisited (<a class="styled" href="visited-page.html">visited</a>)</a>
+<a class="styled" href="visited-page.html">visited (<a class="styled" href="unvisited-page.html">unvisited</a>)</a>
+<a class="styled" href="visited-page.html">visited (<a class="styled" href="visited-page.html">visited</a>)</a>
+
+<a href="unvisited-page.html">unvisited (<a class="styled" href="unvisited-page.html">unvisited</a>)</a>
+<a href="unvisited-page.html">unvisited (<a class="styled" href="visited-page.html">visited</a>)</a>
+<a href="visited-page.html">visited (<a class="styled" href="unvisited-page.html">unvisited</a>)</a>
+<a href="visited-page.html">visited (<a class="styled" href="visited-page.html">visited</a>)</a>
+
+<a class="styled" href="unvisited-page.html">unvisited (<a href="unvisited-page.html">unvisited</a>)</a>
+<a class="styled" href="unvisited-page.html">unvisited (<a href="visited-page.html">visited</a>)</a>
+<a class="styled" href="visited-page.html">visited (<a href="unvisited-page.html">unvisited</a>)</a>
+<a class="styled" href="visited-page.html">visited (<a href="visited-page.html">visited</a>)</a>
+
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/visited-page.html
@@ -0,0 +1,2 @@
+<!DOCTYPE HTML>
+<title>Visited page for tests for privacy restrictions on :visited (Bug 147777)</title>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/width-1-ref.html
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<table>
+  <tr>
+    <td>
+      <div style="width: 100px"></div>
+    </td>
+    <td>
+    text in next cell
+    </td>
+  </tr>
+</table>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/width-on-link-1.html
@@ -0,0 +1,17 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+:link, :visited { display: block }
+:link { width: 100px; }
+:visited { width: 200px; }
+</style>
+<table>
+  <tr>
+    <td>
+      <a href="unvisited-page.html"></a>
+    </td>
+    <td>
+      text in next cell
+    </td>
+  </tr>
+</table>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-visited/width-on-visited-1.html
@@ -0,0 +1,17 @@
+<!DOCTYPE HTML>
+<title>Test for privacy restrictions on :visited (Bug 147777)</title>
+<style type="text/css">
+:link, :visited { display: block }
+:link { width: 100px; }
+:visited { width: 200px; }
+</style>
+<table>
+  <tr>
+    <td>
+      <a href="visited-page.html"></a>
+    </td>
+    <td>
+      text in next cell
+    </td>
+  </tr>
+</table>
--- a/layout/reftests/reftest.list
+++ b/layout/reftests/reftest.list
@@ -57,16 +57,20 @@ include css-namespace/reftest.list
 include css-parsing/reftest.list
 
 # css transitions
 include css-transitions/reftest.list
 
 # css values and units
 include css-valuesandunits/reftest.list
 
+# Reftests in css-visited are run using
+# layout/style/test/test_visited_reftests instead of using the reftest
+# harness.
+
 # columns/
 include columns/reftest.list
 
 # content/
 include ../../content/test/reftest/reftest.list
 
 # counters/
 include counters/reftest.list
--- a/layout/reftests/svg/pseudo-classes-02-ref.svg
+++ b/layout/reftests/svg/pseudo-classes-02-ref.svg
@@ -3,20 +3,20 @@
      http://creativecommons.org/licenses/publicdomain/
 -->
 <svg xmlns="http://www.w3.org/2000/svg" version="1.1"
      xmlns:xlink="http://www.w3.org/1999/xlink">
 
   <title>Reference for pseudo-classes and text/links</title>
 
   <!-- link in text -->
-  <text x="10" y="50" fill="lime" font-size="2em">This should be green</text>
+  <text x="10" y="25" fill="lime" font-size="1em">This should be green</text>
 
   <!-- text in link -->
-  <text x="10" y="100" fill="lime" font-size="2em">This should be green</text>
+  <text x="10" y="50" fill="lime" font-size="1em">This should be green</text>
 
   <!-- link in tspan -->
-  <text x="10" y="150" fill="lime" font-size="2em">This should be green</text>
+  <text x="10" y="75" fill="lime" font-size="1em">This should be green</text>
 
   <!-- tspan in link -->
-  <text x="10" y="200" fill="lime" font-size="2em">This should be green</text>
+  <text x="10" y="100" fill="lime" font-size="1em">This should be green</text>
 
 </svg>
--- a/layout/reftests/svg/pseudo-classes-02.svg
+++ b/layout/reftests/svg/pseudo-classes-02.svg
@@ -1,81 +1,48 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/licenses/publicdomain/
 -->
 <svg xmlns="http://www.w3.org/2000/svg" version="1.1"
-     xmlns:xlink="http://www.w3.org/1999/xlink"
-     class="reftest-wait">
+     xmlns:xlink="http://www.w3.org/1999/xlink">
 
   <title>Testcase for pseudo-classes and text/links</title>
 
   <!-- From https://bugzilla.mozilla.org/show_bug.cgi?id=268135 -->
 
   <style type="text/css">
   <![CDATA[
 
-:root                   { font-size: 2em; }
+:root                   { font-size: 1em; }
 text > a:link           { fill: lime; }
 a:visited > text        { fill: lime; }
 tspan > a:link          { fill: lime; }
 a:visited > tspan       { fill: lime; }
 
   ]]>
   </style>
 
   <!-- link in text -->
-  <text x="10" y="50">
+  <text x="10" y="25">
     <a xlink:href="do-not-visit-me.xxx" fill="red">This should be green</a>
   </text>
 
   <!-- text in link -->
   <a xlink:href="">
-    <text id="t2" x="10" y="100" fill="red">This should be green</text>
+    <text x="10" y="50" fill="red">This should be green</text>
   </a>
 
   <!-- link in tspan -->
   <text>
-    <tspan x="10" y="150">
+    <tspan x="10" y="75">
       <a xlink:href="do-not-visit-me.xxx" fill="red">This should be green</a>
     </tspan>
   </text>
 
   <!-- tspan in link -->
   <text>
     <a xlink:href="">
-      <tspan id="t4" x="10" y="200" fill="red">This should be green</tspan>
+      <tspan x="10" y="100" fill="red">This should be green</tspan>
     </a>
   </text>
 
-  <script type="text/javascript;version=1.7"><![CDATA[
-  let tests = testIterator();
-  function nextTest()
-  {
-    tests.next();
-  }
-
-  function testIterator()
-  {
-    let t2 = document.getElementById("t2");
-    let t4 = document.getElementById("t4");
-    const kExpectedFill = "rgb(0, 255, 0)";
-
-    // Because link coloring is asynchronous, we wait until it is updated.
-    while (getComputedStyle(t2, "").getPropertyValue("fill") != kExpectedFill) {
-      setTimeout(nextTest, 10);
-      yield;
-    }
-    while (getComputedStyle(t4, "").getPropertyValue("fill") != kExpectedFill) {
-      setTimeout(nextTest, 10);
-      yield;
-    }
-
-    // Remove the reftest-wait class so the test harness knows to take the
-    // snapshot.
-    document.documentElement.removeAttribute("class");
-    yield;
-  }
-
-  nextTest();
-  ]]></script>
-
 </svg>
--- a/layout/reftests/svg/reftest.list
+++ b/layout/reftests/svg/reftest.list
@@ -114,17 +114,20 @@ fails == inline-in-xul-basic-01.xul pass
 == opacity-and-gradient-01.svg pass.svg
 == opacity-and-gradient-02.svg opacity-and-gradient-02-ref.svg
 == opacity-and-pattern-01.svg pass.svg
 == path-01.svg path-01-ref.svg
 == pattern-live-01a.svg pattern-live-01-ref.svg
 == pattern-live-01b.svg pattern-live-01-ref.svg
 == pattern-live-01c.svg pattern-live-01-ref.svg
 == pseudo-classes-01.svg pass.svg
-== pseudo-classes-02.svg pseudo-classes-02-ref.svg
+# This test depends on :visited styles (which are asynchronous), so we run
+# it in layout/style/test/test_visited_reftests.html instead of using the
+# reftest harness.
+# == pseudo-classes-02.svg pseudo-classes-02-ref.svg
 == radialGradient-basic-01.svg pass.svg
 == radialGradient-basic-02.svg pass.svg
 == radialGradient-basic-03.svg radialGradient-basic-03-ref.svg
 == rect-01.svg pass.svg
 == rect-02.svg pass.svg
 == rect-03.svg pass.svg
 == rect-with-rx-and-ry-01.svg pass.svg
 == rect-with-rx-or-ry-01.svg rect-with-rx-or-ry-01-ref.svg
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/smil/style/anim-mapped-fontsize-1-from-to-no-no.svg
@@ -0,0 +1,17 @@
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     style="font-size: 2px"
+     class="reftest-wait"
+     onload="go()">
+  <script xlink:href="../smil-grid.js" type="text/javascript"/>
+  <script xlink:href="../smil-util.js" type="text/javascript"/>
+  <script>
+    function go() {
+      var animAttrHash = { "attributeName" : "font-size",
+                           "attributeType" : "XML",
+                           "from"          : "10",
+                           "to"            : "30" };
+      testAnimatedTextGrid("animate", [animAttrHash]);
+    }
+  </script>
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/smil/style/anim-mapped-fontsize-1-from-to-no-px.svg
@@ -0,0 +1,17 @@
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     style="font-size: 2px"
+     class="reftest-wait"
+     onload="go()">
+  <script xlink:href="../smil-grid.js" type="text/javascript"/>
+  <script xlink:href="../smil-util.js" type="text/javascript"/>
+  <script>
+    function go() {
+      var animAttrHash = { "attributeName" : "font-size",
+                           "attributeType" : "XML",
+                           "from"          : "10",
+                           "to"            : "30px" };
+      testAnimatedTextGrid("animate", [animAttrHash]);
+    }
+  </script>
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/smil/style/anim-mapped-fontsize-1-from-to-px-no.svg
@@ -0,0 +1,17 @@
+<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink"
+     style="font-size: 2px"
+     class="reftest-wait"
+     onload="go()">
+  <script xlink:href="../smil-grid.js" type="text/javascript"/>
+  <script xlink:href="../smil-util.js" type="text/javascript"/>
+  <script>
+    function go() {
+      var animAttrHash = { "attributeName" : "font-size",
+                           "attributeType" : "XML",
+                           "from"          : "10px",
+                           "to"            : "30" };
+      testAnimatedTextGrid("animate", [animAttrHash]);
+    }
+  </script>
+</svg>
--- a/layout/reftests/svg/smil/style/reftest.list
+++ b/layout/reftests/svg/smil/style/reftest.list
@@ -67,16 +67,21 @@ fails == anim-css-fillopacity-3-clamp-bi
 
 # 'font' shorthand property
 == anim-css-font-1.svg  anim-css-font-1-ref.svg
 
 # 'font-size' property, from/by/to with pixel values only
 == anim-css-fontsize-1-from-by-px-px.svg    anim-css-fontsize-1-ref.svg
 == anim-css-fontsize-1-from-to-px-px.svg    anim-css-fontsize-1-ref.svg
 
+# 'font-size' mapped attribute (accepts unitless values)
+== anim-mapped-fontsize-1-from-to-no-no.svg anim-css-fontsize-1-ref.svg
+== anim-mapped-fontsize-1-from-to-no-px.svg anim-css-fontsize-1-ref.svg
+== anim-mapped-fontsize-1-from-to-px-no.svg anim-css-fontsize-1-ref.svg
+
 # 'font-size' property, from/by/to with percent values
 == anim-css-fontsize-1-from-by-pct-pct.svg  anim-css-fontsize-1-ref.svg
 == anim-css-fontsize-1-from-by-pct-px.svg   anim-css-fontsize-1-ref.svg
 == anim-css-fontsize-1-from-by-px-pct.svg   anim-css-fontsize-1-ref.svg
 == anim-css-fontsize-1-from-to-pct-pct.svg  anim-css-fontsize-1-ref.svg
 == anim-css-fontsize-1-from-to-pct-px.svg   anim-css-fontsize-1-ref.svg
 == anim-css-fontsize-1-from-to-px-pct.svg   anim-css-fontsize-1-ref.svg
 
new file mode 100644
--- /dev/null
+++ b/layout/style/crashtests/147777-1.html
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML>
+<title>crashtest for NS_ABORT_IF_FALSE during development of 147777</title>
+<style type="text/css">
+:link::before { content: "link: " }
+</style>
+<a href="http://www.example.com/">example</a>
--- a/layout/style/crashtests/crashtests.list
+++ b/layout/style/crashtests/crashtests.list
@@ -1,9 +1,10 @@
 load 105619-1.html
+load 147777-1.html
 load 187671-1.html
 load 192408-1.html
 load 286707-1.html
 load 285727-1.html
 load 317561-1.html
 load 330998-1.html
 load 368175-1.html
 load 379788-1.html
--- a/layout/style/nsCSSDeclaration.cpp
+++ b/layout/style/nsCSSDeclaration.cpp
@@ -113,22 +113,16 @@ nsCSSDeclaration::RemoveProperty(nsCSSPr
     data.ClearProperty(aProperty);
     mOrder.RemoveElement(aProperty);
   }
 
   CompressFrom(&data);
   return NS_OK;
 }
 
-nsresult
-nsCSSDeclaration::AppendComment(const nsAString& aComment)
-{
-  return /* NS_ERROR_NOT_IMPLEMENTED, or not any longer that is */ NS_OK;
-}
-
 PRBool nsCSSDeclaration::AppendValueToString(nsCSSProperty aProperty, nsAString& aResult) const
 {
   nsCSSCompressedDataBlock *data = GetValueIsImportant(aProperty)
                                       ? mImportantData : mData;
   const void *storage = data->StorageFor(aProperty);
   return nsCSSDeclaration::AppendStorageToString(aProperty, storage, aResult);
 }
 
--- a/layout/style/nsCSSDeclaration.h
+++ b/layout/style/nsCSSDeclaration.h
@@ -68,17 +68,16 @@ public:
 
   /**
    * |ValueAppended| must be called to maintain this declaration's
    * |mOrder| whenever a property is parsed into an expanded data block
    * for this declaration.  aProperty must not be a shorthand.
    */
   nsresult ValueAppended(nsCSSProperty aProperty);
 
-  nsresult AppendComment(const nsAString& aComment);
   nsresult RemoveProperty(nsCSSProperty aProperty);
 
   nsresult GetValue(nsCSSProperty aProperty, nsAString& aValue) const;
 
   PRBool HasImportantData() const { return mImportantData != nsnull; }
   PRBool GetValueIsImportant(nsCSSProperty aProperty) const;
   PRBool GetValueIsImportant(const nsAString& aProperty) const;
 
--- a/layout/style/nsCSSLoader.cpp
+++ b/layout/style/nsCSSLoader.cpp
@@ -213,19 +213,19 @@ public:
 
   // mIsLoading is true from the moment we are placed in the loader's
   // "loading datas" table (right after the async channel is opened)
   // to the moment we are removed from said table (due to the load
   // completing or being cancelled).
   PRPackedBool               mIsLoading : 1;
 
   // mIsCancelled is set to true when a sheet load is stopped by
-  // Stop() or StopLoadingSheet().  SheetLoadData::OnStreamComplete()
-  // checks this to avoid parsing sheets that have been cancelled and
-  // such.
+  // Stop() or StopLoadingSheet() (which was removed in Bug 556446).
+  // SheetLoadData::OnStreamComplete() checks this to avoid parsing 
+  // sheets that have been cancelled and such.
   PRPackedBool               mIsCancelled : 1;
 
   // mMustNotify is true if the load data is being loaded async and
   // the original function call that started the load has returned.
   // XXXbz sort our relationship with load/error events!
   PRPackedBool               mMustNotify : 1;
 
   // mWasAlternate is true if the sheet was an alternate when the load data was
@@ -534,24 +534,16 @@ Loader::SetPreferredSheet(const nsAStrin
       --mDatasToNotifyOn;
       LoadSheet(arr[i], eSheetNeedsParser);
     }
   }
 
   return NS_OK;
 }
 
-nsresult
-Loader::GetPreferredSheet(nsAString& aTitle)
-{
-  aTitle.Assign(mPreferredSheet);
-  return NS_OK;
-}
-
-
 static const char kCharsetSym[] = "@charset \"";
 
 static nsresult GetCharsetFromData(const unsigned char* aStyleSheetData,
                                    PRUint32 aDataLength,
                                    nsACString& aCharset)
 {
   aCharset.Truncate();
   if (aDataLength <= sizeof(kCharsetSym) - 1)
@@ -2336,99 +2328,16 @@ Loader::Stop()
   mDatasToNotifyOn += arr.Length();
   for (i = 0; i < arr.Length(); ++i) {
     --mDatasToNotifyOn;
     SheetComplete(arr[i], NS_BINDING_ABORTED);
   }
   return NS_OK;
 }
 
-struct StopLoadingSheetsByURIClosure {
-  StopLoadingSheetsByURIClosure(nsIURI* aURI,
-                                Loader::LoadDataArray& aArray) :
-    uri(aURI), array(aArray)
-  {}
-  
-  nsIURI* uri;
-  Loader::LoadDataArray& array;
-};
-
-static PLDHashOperator
-StopLoadingSheetByURICallback(URIAndPrincipalHashKey* aKey,
-                              SheetLoadData*& aData,
-                              void* aClosure)
-{
-  NS_PRECONDITION(aData, "Must have a data!");
-  NS_PRECONDITION(aClosure, "Must have a loader");
-
-  StopLoadingSheetsByURIClosure* closure =
-    static_cast<StopLoadingSheetsByURIClosure*>(aClosure);
-
-  PRBool equal;
-  if (NS_SUCCEEDED(aData->mURI->Equals(closure->uri, &equal)) &&
-      equal) {
-    aData->mIsLoading = PR_FALSE; // we will handle the removal right here
-    aData->mIsCancelled = PR_TRUE;
-
-    closure->array.AppendElement(aData);
-    return PL_DHASH_REMOVE;
-  }
-
-  return PL_DHASH_NEXT;
-}
-
-nsresult
-Loader::StopLoadingSheet(nsIURI* aURL)
-{
-  NS_ENSURE_TRUE(aURL, NS_ERROR_NULL_POINTER);
-
-  PRUint32 pendingCount =
-    mPendingDatas.IsInitialized() ?  mPendingDatas.Count() : 0;
-  PRUint32 loadingCount =
-    mLoadingDatas.IsInitialized() ? mLoadingDatas.Count() : 0;
-  LoadDataArray arr(pendingCount + loadingCount + mPostedEvents.Length());
-
-  StopLoadingSheetsByURIClosure closure(aURL, arr);
-  if (pendingCount) {
-    mPendingDatas.Enumerate(StopLoadingSheetByURICallback, &closure);
-  }
-  if (loadingCount) {
-    mLoadingDatas.Enumerate(StopLoadingSheetByURICallback, &closure);
-  }
-
-  PRUint32 i;
-  for (i = 0; i < mPostedEvents.Length(); ++i) {
-    SheetLoadData* curData = mPostedEvents[i];
-    PRBool equal;
-    if (curData->mURI && NS_SUCCEEDED(curData->mURI->Equals(aURL, &equal)) &&
-        equal) {
-      curData->mIsCancelled = PR_TRUE;
-      if (arr.AppendElement(curData)) {
-        // SheetComplete() calls Release(), so give this an extra ref.
-        NS_ADDREF(curData);
-      }
-#ifdef DEBUG
-      else {
-        NS_NOTREACHED("We preallocated this memory... shouldn't really fail, "
-                      "except we never check that preallocation succeeds.");
-      }
-#endif
-    }
-  }
-  mPostedEvents.Clear();
-
-  mDatasToNotifyOn += arr.Length();
-  for (i = 0; i < arr.Length(); ++i) {
-    --mDatasToNotifyOn;
-    SheetComplete(arr[i], NS_BINDING_ABORTED);
-  }
-
-  return NS_OK;
-}
-
 PRBool
 Loader::HasPendingLoads()
 {
   return
     (mLoadingDatas.IsInitialized() && mLoadingDatas.Count() != 0) ||
     (mPendingDatas.IsInitialized() && mPendingDatas.Count() != 0) ||
     mPostedEvents.Length() != 0 ||
     mDatasToNotifyOn != 0;
--- a/layout/style/nsCSSLoader.h
+++ b/layout/style/nsCSSLoader.h
@@ -149,17 +149,16 @@ public:
   NS_IMETHOD_(nsrefcnt) Release();
 
   void DropDocumentReference(); // notification that doc is going away
 
   void SetCompatibilityMode(nsCompatibility aCompatMode)
   { mCompatMode = aCompatMode; }
   nsCompatibility GetCompatibilityMode() { return mCompatMode; }
   nsresult SetPreferredSheet(const nsAString& aTitle);
-  nsresult GetPreferredSheet(nsAString& aTitle);
 
   // XXXbz sort out what the deal is with events!  When should they fire?
 
   /**
    * Load an inline style sheet.  If a successful result is returned and
    * *aCompleted is false, then aObserver is guaranteed to be notified
    * asynchronously once the sheet is marked complete.  If an error is
    * returned, or if *aCompleted is true, aObserver will not be notified.  In
@@ -310,20 +309,20 @@ public:
 
   /**
    * Stop loading all sheets.  All nsICSSLoaderObservers involved will be
    * notified with NS_BINDING_ABORTED as the status, possibly synchronously.
    */
   nsresult Stop(void);
 
   /**
-   * Stop loading one sheet.  The nsICSSLoaderObserver involved will be
-   * notified with NS_BINDING_ABORTED as the status, possibly synchronously.
+   * nsresult Loader::StopLoadingSheet(nsIURI* aURL), which notifies the
+   * nsICSSLoaderObserver with NS_BINDING_ABORTED, was removed in Bug 556446. 
+   * It can be found in revision 2c44a32052ad.
    */
-  nsresult StopLoadingSheet(nsIURI* aURL);
 
   /**
    * Whether the loader is enabled or not.
    * When disabled, processing of new styles is disabled and an attempt
    * to do so will fail with a return code of
    * NS_ERROR_NOT_AVAILABLE. Note that this DOES NOT disable
    * currently loading styles or already processed styles.
    */
--- a/layout/style/nsCSSProps.cpp
+++ b/layout/style/nsCSSProps.cpp
@@ -48,16 +48,17 @@
 #include "nsIWidget.h"
 #include "nsThemeConstants.h"  // For system widget appearance types
 
 #include "nsILookAndFeel.h" // for system colors
 
 #include "nsString.h"
 #include "nsReadableUtils.h"
 #include "nsStaticNameTable.h"
+#include "prlog.h" // for PR_STATIC_ASSERT
 
 // required to make the symbol external, so that TestCSSPropertyLookup.cpp can link with it
 extern const char* const kCSSRawProperties[];
 
 // define an array of all CSS properties
 const char* const kCSSRawProperties[] = {
 #define CSS_PROP(name_, id_, method_, flags_, datastruct_, member_, type_,     \
                  kwtable_, stylestruct_, stylestructoffset_, animtype_)        \
@@ -1624,18 +1625,23 @@ static const nsCSSProperty gBorderBottom
   // nsCSSDeclaration.cpp outputs the subproperties in this order.
   // It also depends on the color being third.
   eCSSProperty_border_bottom_width,
   eCSSProperty_border_bottom_style,
   eCSSProperty_border_bottom_color,
   eCSSProperty_UNKNOWN
 };
 
+PR_STATIC_ASSERT(NS_SIDE_TOP == 0);
+PR_STATIC_ASSERT(NS_SIDE_RIGHT == 1);
+PR_STATIC_ASSERT(NS_SIDE_BOTTOM == 2);
+PR_STATIC_ASSERT(NS_SIDE_LEFT == 3);
 static const nsCSSProperty gBorderColorSubpropTable[] = {
   // Code relies on these being in top-right-bottom-left order.
+  // Code relies on these matching the NS_SIDE_* constants.
   eCSSProperty_border_top_color,
   eCSSProperty_border_right_color_value,
   eCSSProperty_border_bottom_color,
   eCSSProperty_border_left_color_value,
   // extras:
   eCSSProperty_border_left_color_ltr_source,
   eCSSProperty_border_left_color_rtl_source,
   eCSSProperty_border_right_color_ltr_source,
--- a/layout/style/nsCSSPseudoClasses.cpp
+++ b/layout/style/nsCSSPseudoClasses.cpp
@@ -62,22 +62,16 @@ static const nsStaticAtom CSSPseudoClass
 };
 
 void nsCSSPseudoClasses::AddRefAtoms()
 {
   NS_RegisterStaticAtoms(CSSPseudoClasses_info,
                          NS_ARRAY_LENGTH(CSSPseudoClasses_info));
 }
 
-PRBool nsCSSPseudoClasses::IsPseudoClass(nsIAtom *aAtom)
-{
-  return nsAtomListUtils::IsMember(aAtom,CSSPseudoClasses_info,
-                                   NS_ARRAY_LENGTH(CSSPseudoClasses_info));
-}
-
 PRBool
 nsCSSPseudoClasses::HasStringArg(nsIAtom* aAtom)
 {
   return aAtom == nsCSSPseudoClasses::lang ||
          aAtom == nsCSSPseudoClasses::mozEmptyExceptChildrenWithLocalname ||
          aAtom == nsCSSPseudoClasses::mozSystemMetric ||
          aAtom == nsCSSPseudoClasses::mozLocaleDir;
 }
--- a/layout/style/nsCSSPseudoClasses.h
+++ b/layout/style/nsCSSPseudoClasses.h
@@ -47,17 +47,16 @@
 // require an atom from this atom list.
 class nsICSSPseudoClass : public nsIAtom {};
 
 class nsCSSPseudoClasses {
 public:
 
   static void AddRefAtoms();
 
-  static PRBool IsPseudoClass(nsIAtom *aAtom);
   static PRBool HasStringArg(nsIAtom* aAtom);
   static PRBool HasNthPairArg(nsIAtom* aAtom);
 
 #define CSS_PSEUDO_CLASS(_name, _value) static nsICSSPseudoClass* _name;
 #include "nsCSSPseudoClassList.h"
 #undef CSS_PSEUDO_CLASS
 
   enum Type {
--- a/layout/style/nsCSSRuleProcessor.cpp
+++ b/layout/style/nsCSSRuleProcessor.cpp
@@ -1108,18 +1108,20 @@ RuleProcessorData::ContentState()
     mContentState = 0;
     if (mPresContext) {
       mPresContext->EventStateManager()->GetContentState(mContent,
                                                          mContentState);
     } else {
       mContentState = mContent->IntrinsicState();
     }
 
-    // If we are not supposed to mark visited links as such, be sure to flip the
-    // bits appropriately.
+    // If we are not supposed to mark visited links as such, be sure to
+    // flip the bits appropriately.  We want to do this here, rather
+    // than in GetContentStateForVisitedHandling, so that we don't
+    // expose that :visited support is disabled to the Web page.
     if ((!gSupportVisitedPseudo ||
         gPrivateBrowsingObserver->InPrivateBrowsing()) &&
         (mContentState & NS_EVENT_STATE_VISITED)) {
       mContentState = (mContentState & ~PRUint32(NS_EVENT_STATE_VISITED)) |
                       NS_EVENT_STATE_UNVISITED;
     }
   }
   return mContentState;
@@ -1133,16 +1135,45 @@ RuleProcessorData::DocumentState()
 
 PRBool
 RuleProcessorData::IsLink()
 {
   PRUint32 state = ContentState();
   return (state & (NS_EVENT_STATE_VISITED | NS_EVENT_STATE_UNVISITED)) != 0;
 }
 
+PRUint32
+RuleProcessorData::GetContentStateForVisitedHandling(
+                     nsRuleWalker::VisitedHandlingType aVisitedHandling,
+                     PRBool aIsRelevantLink)
+{
+  PRUint32 contentState = ContentState();
+  if (contentState & (NS_EVENT_STATE_VISITED | NS_EVENT_STATE_UNVISITED)) {
+    NS_ABORT_IF_FALSE(IsLink(), "IsLink() should match state");
+    contentState &=
+      ~PRUint32(NS_EVENT_STATE_VISITED | NS_EVENT_STATE_UNVISITED);
+    if (aIsRelevantLink) {
+      switch (aVisitedHandling) {
+        case nsRuleWalker::eRelevantLinkUnvisited:
+          contentState |= NS_EVENT_STATE_UNVISITED;
+          break;
+        case nsRuleWalker::eRelevantLinkVisited:
+          contentState |= NS_EVENT_STATE_VISITED;
+          break;
+        case nsRuleWalker::eLinksVisitedOrUnvisited:
+          contentState |= NS_EVENT_STATE_UNVISITED | NS_EVENT_STATE_VISITED;
+          break;
+      }
+    } else {
+      contentState |= NS_EVENT_STATE_UNVISITED;
+    }
+  }
+  return contentState;
+}
+
 PRInt32
 RuleProcessorData::GetNthIndex(PRBool aIsOfType, PRBool aIsFromEnd,
                                PRBool aCheckEdgeOnly)
 {
   NS_ASSERTION(mParentContent, "caller should check mParentContent");
   NS_ASSERTION(!mPreviousSiblingData ||
                mPreviousSiblingData->mContent->IsNodeOfType(nsINode::eELEMENT),
                "Unexpected previous sibling data");
@@ -1210,16 +1241,84 @@ RuleProcessorData::GetNthIndex(PRBool aI
 #ifdef DEBUG
   NS_ASSERTION(!debugMutationGuard.Mutated(0), "Unexpected mutations happened");
 #endif  
 
   slot = result;
   return result;
 }
 
+/**
+ * A |TreeMatchContext| has data about matching a selector (containing
+ * combinators) against a node and the tree that that node is in.  It
+ * contains both input to and output from the matching.
+ */
+struct TreeMatchContext {
+  // Is this matching operation for the creation of a style context?
+  // (If it is, we need to set slow selector bits on nodes indicating
+  // that certain restyling needs to happen.)
+  const PRBool mForStyling;
+
+  // Did this matching operation find a relevant link?  (If so, we'll
+  // need to construct a StyleIfVisited.)
+  PRBool mHaveRelevantLink;
+
+  nsRuleWalker::VisitedHandlingType mVisitedHandling;
+
+  TreeMatchContext(PRBool aForStyling,
+                   nsRuleWalker::VisitedHandlingType aVisitedHandling)
+    : mForStyling(aForStyling)
+    , mHaveRelevantLink(PR_FALSE)
+    , mVisitedHandling(aVisitedHandling)
+  {
+  }
+};
+
+/**
+ * A |NodeMatchContext| has data about matching a selector (without
+ * combinators) against a single node.  It contains only input to the
+ * matching.
+ *
+ * Unlike |RuleProcessorData|, which is similar, a |NodeMatchContext|
+ * can vary depending on the selector matching process.  In other words,
+ * there might be multiple NodeMatchContexts corresponding to a single
+ * node, but only one possible RuleProcessorData.
+ */
+struct NodeMatchContext {
+  // In order to implement nsCSSRuleProcessor::HasStateDependentStyle,
+  // we need to be able to see if a node might match an
+  // event-state-dependent selector for any value of that event state.
+  // So mStateMask contains the states that should NOT be tested.
+  //
+  // NOTE: For |aStateMask| to work correctly, it's important that any
+  // change that changes multiple state bits include all those state
+  // bits in the notification.  Otherwise, if multiple states change but
+  // we do separate notifications then we might determine the style is
+  // not state-dependent when it really is (e.g., determining that a
+  // :hover:active rule no longer matches when both states are unset).
+  const PRInt32 mStateMask;
+
+  // Is this link the unique link whose visitedness can affect the style
+  // of the node being matched?  (That link is the nearest link to the
+  // node being matched that is itself or an ancestor.)
+  //
+  // Always false when TreeMatchContext::mForStyling is false.  (We
+  // could figure it out for SelectorListMatches, but we're starting
+  // from the middle of the selector list when doing
+  // Has{Attribute,State}DependentStyle, so we can't tell.  So when
+  // mForStyling is false, we have to assume we don't know.)
+  const PRBool mIsRelevantLink;
+
+  NodeMatchContext(PRInt32 aStateMask, PRBool aIsRelevantLink)
+    : mStateMask(aStateMask)
+    , mIsRelevantLink(aIsRelevantLink)
+  {
+  }
+};
+
 static PRBool ValueIncludes(const nsSubstring& aValueList,
                             const nsSubstring& aValue,
                             const nsStringComparator& aComparator)
 {
   const PRUnichar *p = aValueList.BeginReading(),
               *p_end = aValueList.EndReading();
 
   while (p < p_end) {
@@ -1307,115 +1406,116 @@ static PRBool AttrMatchesValue(const nsA
       return FindInReadable(aAttrSelector->mValue, aValue, comparator);
     default:
       NS_NOTREACHED("Shouldn't be ending up here");
       return PR_FALSE;
   }
 }
 
 static PRBool NS_FASTCALL
-firstNodeMatches(RuleProcessorData& data, PRBool setNodeFlags,
+firstNodeMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                  nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::firstNode,
                   "Unexpected atom");
   nsIContent *firstNode = nsnull;
   nsIContent *parent = data.mParentContent;
   if (parent) {
-    if (setNodeFlags)
+    if (aTreeMatchContext.mForStyling)
       parent->SetFlags(NODE_HAS_EDGE_CHILD_SELECTOR);
 
     PRInt32 index = -1;
     do {
       firstNode = parent->GetChildAt(++index);
       // stop at first non-comment and non-whitespace node
     } while (firstNode &&
              !IsSignificantChild(firstNode, PR_TRUE, PR_FALSE));
   }
   return (data.mContent == firstNode);
 }
 
 static PRBool NS_FASTCALL
-lastNodeMatches(RuleProcessorData& data, PRBool setNodeFlags,
+lastNodeMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                 nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::lastNode,
                   "Unexpected atom");
   nsIContent *lastNode = nsnull;
   nsIContent *parent = data.mParentContent;
   if (parent) {
-    if (setNodeFlags)
+    if (aTreeMatchContext.mForStyling)
       parent->SetFlags(NODE_HAS_EDGE_CHILD_SELECTOR);
 
     PRUint32 index = parent->GetChildCount();
     do {
       lastNode = parent->GetChildAt(--index);
       // stop at first non-comment and non-whitespace node
     } while (lastNode &&
              !IsSignificantChild(lastNode, PR_TRUE, PR_FALSE));
   }
   return (data.mContent == lastNode);
 }
 
 static inline PRBool
-edgeChildMatches(RuleProcessorData& data, PRBool setNodeFlags,
+edgeChildMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                  PRBool checkFirst, PRBool checkLast)
 {
   nsIContent *parent = data.mParentContent;
   if (!parent) {
     return PR_FALSE;
   }
 
-  if (setNodeFlags)
+  if (aTreeMatchContext.mForStyling)
     parent->SetFlags(NODE_HAS_EDGE_CHILD_SELECTOR);
 
   return (!checkFirst ||
           data.GetNthIndex(PR_FALSE, PR_FALSE, PR_TRUE) == 1) &&
          (!checkLast ||
           data.GetNthIndex(PR_FALSE, PR_TRUE, PR_TRUE) == 1);
 }
 
 static PRBool NS_FASTCALL
-firstChildMatches(RuleProcessorData& data, PRBool setNodeFlags,
+firstChildMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                   nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::firstChild,
                   "Unexpected atom");
-  return edgeChildMatches(data, setNodeFlags, PR_TRUE, PR_FALSE);
+  return edgeChildMatches(data, aTreeMatchContext, PR_TRUE, PR_FALSE);
 }
 
 static PRBool NS_FASTCALL
-lastChildMatches(RuleProcessorData& data, PRBool setNodeFlags,
+lastChildMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                  nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::lastChild,
                   "Unexpected atom");
-  return edgeChildMatches(data, setNodeFlags, PR_FALSE, PR_TRUE);
+  return edgeChildMatches(data, aTreeMatchContext, PR_FALSE, PR_TRUE);
 }
 
 static PRBool NS_FASTCALL
-onlyChildMatches(RuleProcessorData& data, PRBool setNodeFlags,
+onlyChildMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                  nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::onlyChild,
                   "Unexpected atom");
-  return edgeChildMatches(data, setNodeFlags, PR_TRUE, PR_TRUE);
+  return edgeChildMatches(data, aTreeMatchContext, PR_TRUE, PR_TRUE);
 }
 
 static inline PRBool
-nthChildGenericMatches(RuleProcessorData& data, PRBool setNodeFlags,
+nthChildGenericMatches(RuleProcessorData& data,
+                       TreeMatchContext& aTreeMatchContext,
                        nsPseudoClassList* pseudoClass,
                        PRBool isOfType, PRBool isFromEnd)
 {
   nsIContent *parent = data.mParentContent;
   if (!parent) {
     return PR_FALSE;
   }
 
-  if (setNodeFlags) {
+  if (aTreeMatchContext.mForStyling) {
     if (isFromEnd)
       parent->SetFlags(NODE_HAS_SLOW_SELECTOR);
     else
       parent->SetFlags(NODE_HAS_SLOW_SELECTOR_NOAPPEND);
   }
 
   const PRInt32 index = data.GetNthIndex(isOfType, isFromEnd, PR_FALSE);
   if (index <= 0) {
@@ -1434,179 +1534,185 @@ nthChildGenericMatches(RuleProcessorData
   // Integer division in C does truncation (towards 0).  So
   // check that the result is nonnegative, and that there was no
   // truncation.
   const PRInt32 n = (index - b) / a;
   return n >= 0 && (a * n == index - b);
 }
 
 static PRBool NS_FASTCALL
-nthChildMatches(RuleProcessorData& data, PRBool setNodeFlags,
+nthChildMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                 nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::nthChild,
                   "Unexpected atom");
-  return nthChildGenericMatches(data, setNodeFlags, pseudoClass,
+  return nthChildGenericMatches(data, aTreeMatchContext, pseudoClass,
                                 PR_FALSE, PR_FALSE);
 }
 
 static PRBool NS_FASTCALL
-nthLastChildMatches(RuleProcessorData& data, PRBool setNodeFlags,
+nthLastChildMatches(RuleProcessorData& data,
+                    TreeMatchContext& aTreeMatchContext,
                     nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::nthLastChild,
                   "Unexpected atom");
-  return nthChildGenericMatches(data, setNodeFlags, pseudoClass,
+  return nthChildGenericMatches(data, aTreeMatchContext, pseudoClass,
                                 PR_FALSE, PR_TRUE);
 }
 
 static PRBool NS_FASTCALL
-nthOfTypeMatches(RuleProcessorData& data, PRBool setNodeFlags,
+nthOfTypeMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                  nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::nthOfType,
                   "Unexpected atom");
-  return nthChildGenericMatches(data, setNodeFlags, pseudoClass,
+  return nthChildGenericMatches(data, aTreeMatchContext, pseudoClass,
                                 PR_TRUE, PR_FALSE);
 }
 
 static PRBool NS_FASTCALL
-nthLastOfTypeMatches(RuleProcessorData& data, PRBool setNodeFlags,
+nthLastOfTypeMatches(RuleProcessorData& data,
+                     TreeMatchContext& aTreeMatchContext,
                      nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::nthLastOfType,
                   "Unexpected atom");
-  return nthChildGenericMatches(data, setNodeFlags, pseudoClass,
+  return nthChildGenericMatches(data, aTreeMatchContext, pseudoClass,
                                 PR_TRUE, PR_TRUE);
 }
 
 static inline PRBool
-edgeOfTypeMatches(RuleProcessorData& data, PRBool setNodeFlags,
+edgeOfTypeMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                   PRBool checkFirst, PRBool checkLast)
 {
   nsIContent *parent = data.mParentContent;
   if (!parent) {
     return PR_FALSE;
   }
 
-  if (setNodeFlags) {
+  if (aTreeMatchContext.mForStyling) {
     if (checkLast)
       parent->SetFlags(NODE_HAS_SLOW_SELECTOR);
     else
       parent->SetFlags(NODE_HAS_SLOW_SELECTOR_NOAPPEND);
   }
 
   return (!checkFirst ||
           data.GetNthIndex(PR_TRUE, PR_FALSE, PR_TRUE) == 1) &&
          (!checkLast ||
           data.GetNthIndex(PR_TRUE, PR_TRUE, PR_TRUE) == 1);
 }
 
 static PRBool NS_FASTCALL
-firstOfTypeMatches(RuleProcessorData& data, PRBool setNodeFlags,
+firstOfTypeMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                    nsPseudoClassList* pseudoClass)
 { 
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::firstOfType,
                   "Unexpected atom");
-  return edgeOfTypeMatches(data, setNodeFlags, PR_TRUE, PR_FALSE);
+  return edgeOfTypeMatches(data, aTreeMatchContext, PR_TRUE, PR_FALSE);
 }
 
 static PRBool NS_FASTCALL
-lastOfTypeMatches(RuleProcessorData& data, PRBool setNodeFlags,
+lastOfTypeMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                   nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::lastOfType,
                   "Unexpected atom");
-  return edgeOfTypeMatches(data, setNodeFlags, PR_FALSE, PR_TRUE);
+  return edgeOfTypeMatches(data, aTreeMatchContext, PR_FALSE, PR_TRUE);
 }
 
 static PRBool NS_FASTCALL
-onlyOfTypeMatches(RuleProcessorData& data, PRBool setNodeFlags,
+onlyOfTypeMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                   nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::onlyOfType,
                   "Unexpected atom");
-  return edgeOfTypeMatches(data, setNodeFlags, PR_TRUE, PR_TRUE);
+  return edgeOfTypeMatches(data, aTreeMatchContext, PR_TRUE, PR_TRUE);
 }
 
 static inline PRBool
-checkGenericEmptyMatches(RuleProcessorData& data, PRBool setNodeFlags,
+checkGenericEmptyMatches(RuleProcessorData& data,
+                         TreeMatchContext& aTreeMatchContext,
                          PRBool isWhitespaceSignificant)
 {
   nsIContent *child = nsnull;
   nsIContent *element = data.mContent;
   PRInt32 index = -1;
 
-  if (setNodeFlags)
+  if (aTreeMatchContext.mForStyling)
     element->SetFlags(NODE_HAS_EMPTY_SELECTOR);
 
   do {
     child = element->GetChildAt(++index);
     // stop at first non-comment (and non-whitespace for
     // :-moz-only-whitespace) node        
   } while (child && !IsSignificantChild(child, PR_TRUE, isWhitespaceSignificant));
   return (child == nsnull);
 }
 
 static PRBool NS_FASTCALL
-emptyMatches(RuleProcessorData& data, PRBool setNodeFlags,
+emptyMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
              nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::empty,
                   "Unexpected atom");
-  return checkGenericEmptyMatches(data, setNodeFlags, PR_TRUE);
+  return checkGenericEmptyMatches(data, aTreeMatchContext, PR_TRUE);
 }
 
 static PRBool NS_FASTCALL
-mozOnlyWhitespaceMatches(RuleProcessorData& data, PRBool setNodeFlags,
+mozOnlyWhitespaceMatches(RuleProcessorData& data,
+                         TreeMatchContext& aTreeMatchContext,
                          nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::mozOnlyWhitespace,
                   "Unexpected atom");
-  return checkGenericEmptyMatches(data, setNodeFlags, PR_FALSE);
+  return checkGenericEmptyMatches(data, aTreeMatchContext, PR_FALSE);
 }
 
 static PRBool NS_FASTCALL
 mozEmptyExceptChildrenWithLocalnameMatches(RuleProcessorData& data,
-                                           PRBool setNodeFlags,
+                                           TreeMatchContext& aTreeMatchContext,
                                            nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom ==
                     nsCSSPseudoClasses::mozEmptyExceptChildrenWithLocalname,
                   "Unexpected atom");
   NS_ASSERTION(pseudoClass->u.mString, "Must have string!");
   nsIContent *child = nsnull;
   nsIContent *element = data.mContent;
   PRInt32 index = -1;
 
-  if (setNodeFlags)
+  if (aTreeMatchContext.mForStyling)
     element->SetFlags(NODE_HAS_SLOW_SELECTOR);
 
   do {
     child = element->GetChildAt(++index);
   } while (child &&
            (!IsSignificantChild(child, PR_TRUE, PR_FALSE) ||
             (child->GetNameSpaceID() == element->GetNameSpaceID() &&
              child->Tag()->Equals(nsDependentString(pseudoClass->u.mString)))));
   return (child == nsnull);
 }
 
 static PRBool NS_FASTCALL
-mozSystemMetricMatches(RuleProcessorData& data, PRBool setNodeFlags,
+mozSystemMetricMatches(RuleProcessorData& data,
+                       TreeMatchContext& aTreeMatchContext,
                        nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::mozSystemMetric,
                   "Unexpected atom");
   NS_ASSERTION(pseudoClass->u.mString, "Must have string!");
   nsCOMPtr<nsIAtom> metric = do_GetAtom(pseudoClass->u.mString);
   return nsCSSRuleProcessor::HasSystemMetric(metric);
 }
 
 static PRBool NS_FASTCALL
-mozHasHandlerRefMatches(RuleProcessorData& data, PRBool setNodeFlags,
+mozHasHandlerRefMatches(RuleProcessorData& data,
+                        TreeMatchContext& aTreeMatchContext,
                         nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::mozHasHandlerRef,
                   "Unexpected atom");
   nsIContent *child = nsnull;
   nsIContent *element = data.mContent;
   PRInt32 index = -1;
 
@@ -1618,39 +1724,40 @@ mozHasHandlerRefMatches(RuleProcessorDat
                            NS_LITERAL_STRING("pluginurl"), eIgnoreCase)) {
       return PR_TRUE;
     }
   } while (child);
   return PR_FALSE;
 }
 
 static PRBool NS_FASTCALL
-rootMatches(RuleProcessorData& data, PRBool setNodeFlags,
+rootMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
             nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::root,
                   "Unexpected atom");
   return (data.mParentContent == nsnull &&
           data.mContent == data.mContent->GetOwnerDoc()->GetRootContent());
 }
 
 static PRBool NS_FASTCALL
-mozBoundElementMatches(RuleProcessorData& data, PRBool setNodeFlags,
+mozBoundElementMatches(RuleProcessorData& data,
+                       TreeMatchContext& aTreeMatchContext,
                        nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::mozBoundElement,
                   "Unexpected atom");
   // XXXldb How do we know where the selector came from?  And what
   // if there are multiple bindings, and we should be matching the
   // outer one?
   return (data.mScopedRoot == data.mContent);
 }
 
 static PRBool NS_FASTCALL
-langMatches(RuleProcessorData& data, PRBool setNodeFlags,
+langMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
             nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::lang,
                   "Unexpected atom");
   NS_ASSERTION(nsnull != pseudoClass->u.mString, "null lang parameter");
   if (!pseudoClass->u.mString || !*pseudoClass->u.mString) {
     return PR_FALSE;
   }
@@ -1693,92 +1800,97 @@ langMatches(RuleProcessorData& data, PRB
       begin = end + 1;
     }
   }
 
   return PR_FALSE;
 }
 
 static PRBool NS_FASTCALL
-mozIsHTMLMatches(RuleProcessorData& data, PRBool setNodeFlags,
+mozIsHTMLMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                  nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::mozIsHTML,
                   "Unexpected atom");
   return data.mIsHTML;
 }
 
 static PRBool NS_FASTCALL
-mozLocaleDirMatches(RuleProcessorData& data, PRBool setNodeFlags,
+mozLocaleDirMatches(RuleProcessorData& data,
+                    TreeMatchContext& aTreeMatchContext,
                     nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::mozLocaleDir,
                   "Unexpected atom");
 
   PRBool docIsRTL = (data.DocumentState() & NS_DOCUMENT_STATE_RTL_LOCALE) != 0;
 
   nsDependentString dirString(pseudoClass->u.mString);
   NS_ASSERTION(dirString.EqualsLiteral("ltr") || dirString.EqualsLiteral("rtl"),
                "invalid value for -moz-locale-dir");
 
   return dirString.EqualsLiteral("rtl") == docIsRTL;
 }
 
 static PRBool NS_FASTCALL
-mozLWThemeMatches(RuleProcessorData& data, PRBool setNodeFlags,
+mozLWThemeMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                   nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom == nsCSSPseudoClasses::mozLWTheme,
                   "Unexpected atom");
   nsIDocument* doc = data.mContent->GetOwnerDoc();
   return doc && doc->GetDocumentLWTheme() > nsIDocument::Doc_Theme_None;
 }
 
 static PRBool NS_FASTCALL
-mozLWThemeBrightTextMatches(RuleProcessorData& data, PRBool setNodeFlags,
+mozLWThemeBrightTextMatches(RuleProcessorData& data,
+                            TreeMatchContext& aTreeMatchContext,
                             nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom ==
                     nsCSSPseudoClasses::mozLWThemeBrightText,
                   "Unexpected atom");
   nsIDocument* doc = data.mContent->GetOwnerDoc();
   return doc && doc->GetDocumentLWTheme() == nsIDocument::Doc_Theme_Bright;
 }
 
 static PRBool NS_FASTCALL
-mozLWThemeDarkTextMatches(RuleProcessorData& data, PRBool setNodeFlags,
+mozLWThemeDarkTextMatches(RuleProcessorData& data,
+                          TreeMatchContext& aTreeMatchContext,
                           nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom ==
                     nsCSSPseudoClasses::mozLWThemeDarkText,
                   "Unexpected atom");
   nsIDocument* doc = data.mContent->GetOwnerDoc();
   return doc && doc->GetDocumentLWTheme() == nsIDocument::Doc_Theme_Dark;
 }
 
 static PRBool NS_FASTCALL
-mozWindowInactiveMatches(RuleProcessorData& data, PRBool setNodeFlags,
+mozWindowInactiveMatches(RuleProcessorData& data,
+                         TreeMatchContext& aTreeMatchContext,
                          nsPseudoClassList* pseudoClass)
 {
   NS_PRECONDITION(pseudoClass->mAtom ==
                     nsCSSPseudoClasses::mozWindowInactive,
                   "Unexpected atom");
   return (data.DocumentState() & NS_DOCUMENT_STATE_WINDOW_INACTIVE) != 0;
 }
 
 static PRBool NS_FASTCALL
-notPseudoMatches(RuleProcessorData& data, PRBool setNodeFlags,
+notPseudoMatches(RuleProcessorData& data, TreeMatchContext& aTreeMatchContext,
                  nsPseudoClassList* pseudoClass)
 {
   NS_NOTREACHED("Why did this get called?");
   return PR_FALSE;
 }
 
 typedef PRBool
-  (NS_FASTCALL * PseudoClassMatcher)(RuleProcessorData&, PRBool setNodeFlags,
+  (NS_FASTCALL * PseudoClassMatcher)(RuleProcessorData&,
+                                     TreeMatchContext& aTreeMatchContext,
                                      nsPseudoClassList* pseudoClass);
 // Only one of mFunc or mBits will be set; the other will be null or 0
 // respectively.  We could use a union, but then we'd still need to
 // differentiate somehow, eiher with another member in the struct or
 // with a boolean coming from _sowewhere_.
 struct PseudoClassInfo {
   PseudoClassMatcher mFunc;
   PRInt32 mBits;
@@ -1795,39 +1907,36 @@ static const PseudoClassInfo sPseudoClas
   // Add more entries for our fake values to make sure we can't
   // index out of bounds into this array no matter what.
   { nsnull, 0 },
   { nsnull, 0 }
 };
 PR_STATIC_ASSERT(NS_ARRAY_LENGTH(sPseudoClassInfo) >
                    nsCSSPseudoClasses::ePseudoClass_NotPseudoClass);
 
-// NOTE: For |aStateMask| to work correctly, it's important that any change
-// that changes multiple state bits include all those state bits in the
-// notification.  Otherwise, if multiple states change but we do separate
-// notifications then we might determine the style is not state-dependent when
-// it really is (e.g., determining that a :hover:active rule no longer matches
-// when both states are unset).
-
-// If |aForStyling| is false, we shouldn't mark slow-selector bits on nodes.
-
 // |aDependence| has two functions:
 //  * when non-null, it indicates that we're processing a negation,
 //    which is done only when SelectorMatches calls itself recursively
 //  * what it points to should be set to true whenever a test is skipped
 //    because of aStateMask
 static PRBool SelectorMatches(RuleProcessorData &data,
                               nsCSSSelector* aSelector,
-                              PRInt32 aStateMask, // states NOT to test
-                              PRBool aForStyling,
+                              NodeMatchContext& aNodeMatchContext,
+                              TreeMatchContext& aTreeMatchContext,
                               PRBool* const aDependence = nsnull) 
 
 {
   NS_PRECONDITION(!aSelector->IsPseudoElement(),
                   "Pseudo-element snuck into SelectorMatches?");
+  NS_ABORT_IF_FALSE(aTreeMatchContext.mForStyling ||
+                    !aNodeMatchContext.mIsRelevantLink,
+                    "mIsRelevantLink should be set to false when mForStyling "
+                    "is false since we don't know how to set it correctly in "
+                    "Has(Attribute|State)DependentStyle");
+
   // namespace/tag match
   // optimization : bail out early if we can
   if ((kNameSpaceID_Unknown != aSelector->mNameSpace &&
        data.mNameSpaceID != aSelector->mNameSpace))
     return PR_FALSE;
 
   if (aSelector->mLowercaseTag && 
       (data.mIsHTML ? aSelector->mLowercaseTag : aSelector->mCasedTag) !=
@@ -1892,27 +2001,27 @@ static PRBool SelectorMatches(RuleProces
   }
 
   const PRBool isNegated = (aDependence != nsnull);
   // The selectors for which we set node bits are, unfortunately, early
   // in this function (because they're pseudo-classes, which are
   // generally quick to test, and thus earlier).  If they were later,
   // we'd probably avoid setting those bits in more cases where setting
   // them is unnecessary.
-  NS_ASSERTION(aStateMask == 0 || !aForStyling,
-               "aForStyling must be false if we're just testing for "
+  NS_ASSERTION(aNodeMatchContext.mStateMask == 0 ||
+               !aTreeMatchContext.mForStyling,
+               "mForStyling must be false if we're just testing for "
                "state-dependence");
-  const PRBool setNodeFlags = aForStyling;
 
   // test for pseudo class match
   for (nsPseudoClassList* pseudoClass = aSelector->mPseudoClassList;
        pseudoClass; pseudoClass = pseudoClass->mNext) {
     const PseudoClassInfo& info = sPseudoClassInfo[pseudoClass->mType];
     if (info.mFunc) {
-      if (!(*info.mFunc)(data, setNodeFlags, pseudoClass)) {
+      if (!(*info.mFunc)(data, aTreeMatchContext, pseudoClass)) {
         return PR_FALSE;
       }
     } else {
       PRInt32 statesToCheck = info.mBits;
       NS_ABORT_IF_FALSE(statesToCheck != 0, "How did that happen?");
       if ((statesToCheck & (NS_EVENT_STATE_HOVER | NS_EVENT_STATE_ACTIVE)) &&
           data.mCompatMode == eCompatibility_NavQuirks &&
           // global selector (but don't check .class):
@@ -1925,21 +2034,24 @@ static PRBool SelectorMatches(RuleProces
           !isNegated &&
           // important for |IsQuirkEventSensitive|:
           data.mIsHTMLContent && !data.IsLink() &&
           !IsQuirkEventSensitive(data.mContentTag)) {
         // In quirks mode, only make certain elements sensitive to
         // selectors ":hover" and ":active".
         return PR_FALSE;
       } else {
-        if (aStateMask & statesToCheck) {
+        if (aNodeMatchContext.mStateMask & statesToCheck) {
           if (aDependence)
             *aDependence = PR_TRUE;
         } else {
-          if (!(data.ContentState() & statesToCheck)) {
+          PRUint32 contentState = data.GetContentStateForVisitedHandling(
+                                    aTreeMatchContext.mVisitedHandling,
+                                    aNodeMatchContext.mIsRelevantLink);
+          if (!(contentState & statesToCheck)) {
             return PR_FALSE;
           }
         }
       }
     }
   }
 
   PRBool result = PR_TRUE;
@@ -2020,18 +2132,18 @@ static PRBool SelectorMatches(RuleProces
     }
   }
 
   // apply SelectorMatches to the negated selectors in the chain
   if (!isNegated) {
     for (nsCSSSelector *negation = aSelector->mNegations;
          result && negation; negation = negation->mNegations) {
       PRBool dependence = PR_FALSE;
-      result = !SelectorMatches(data, negation, aStateMask,
-                                aForStyling, &dependence);
+      result = !SelectorMatches(data, negation, aNodeMatchContext,
+                                aTreeMatchContext, &dependence);
       // If the selector does match due to the dependence on aStateMask,
       // then we want to keep result true so that the final result of
       // SelectorMatches is true.  Doing so tells StateEnumFunc that
       // there is a dependence on the state.
       result = result || dependence;
     }
   }
   return result;
@@ -2043,17 +2155,18 @@ static PRBool SelectorMatches(RuleProces
 //   ' ', the descendant combinator, is greedy
 //   '~', the indirect adjacent sibling combinator, is greedy
 //   '+' and '>', the direct adjacent sibling and child combinators, are not
 #define NS_IS_GREEDY_OPERATOR(ch) \
   ((ch) == PRUnichar(' ') || (ch) == PRUnichar('~'))
 
 static PRBool SelectorMatchesTree(RuleProcessorData& aPrevData,
                                   nsCSSSelector* aSelector,
-                                  PRBool aForStyling) 
+                                  TreeMatchContext& aTreeMatchContext,
+                                  PRBool aLookForRelevantLink)
 {
   nsCSSSelector* selector = aSelector;
   RuleProcessorData* prevdata = &aPrevData;
   while (selector) { // check compound selectors
     NS_ASSERTION(!selector->mNext ||
                  selector->mNext->mOperator != PRUnichar(0),
                  "compound selector without combinator");
 
@@ -2061,22 +2174,24 @@ static PRBool SelectorMatchesTree(RulePr
     // appropriate content (whether parent or previous sibling), create
     // one.
 
     // for adjacent sibling combinators, the content to test against the
     // selector is the previous sibling *element*
     RuleProcessorData* data;
     if (PRUnichar('+') == selector->mOperator ||
         PRUnichar('~') == selector->mOperator) {
+      // The relevant link must be an ancestor of the node being matched.
+      aLookForRelevantLink = PR_FALSE;
       data = prevdata->mPreviousSiblingData;
       if (!data) {
         nsIContent* content = prevdata->mContent;
         nsIContent* parent = prevdata->mParentContent;
         if (parent) {
-          if (aForStyling)
+          if (aTreeMatchContext.mForStyling)
             parent->SetFlags(NODE_HAS_SLOW_SELECTOR_NOAPPEND);
 
           PRInt32 index = parent->IndexOf(content);
           while (0 <= --index) {
             content = parent->GetChildAt(index);
             if (content->IsNodeOfType(nsINode::eELEMENT)) {
               data = RuleProcessorData::Create(prevdata->mPresContext, content,
                                                prevdata->mRuleWalker,
@@ -2102,17 +2217,29 @@ static PRBool SelectorMatchesTree(RulePr
                                            prevdata->mCompatMode);
           prevdata->mParentData = data;
         }
       }
     }
     if (! data) {
       return PR_FALSE;
     }
-    if (SelectorMatches(*data, selector, 0, aForStyling)) {
+    NodeMatchContext nodeContext(0, aLookForRelevantLink && data->IsLink());
+    if (nodeContext.mIsRelevantLink) {
+      // If we find an ancestor of the matched node that is a link
+      // during the matching process, then it's the relevant link (see
+      // constructor call above).
+      // Since we are still matching against selectors that contain
+      // :visited (they'll just fail), we will always find such a node
+      // during the selector matching process if there is a relevant
+      // link that can influence selector matching.
+      aLookForRelevantLink = PR_FALSE;
+      aTreeMatchContext.mHaveRelevantLink = PR_TRUE;
+    }
+    if (SelectorMatches(*data, selector, nodeContext, aTreeMatchContext)) {
       // to avoid greedy matching, we need to recur if this is a
       // descendant or general sibling combinator and the next
       // combinator is different, but we can make an exception for
       // sibling, then parent, since a sibling's parent is always the
       // same.
       if (NS_IS_GREEDY_OPERATOR(selector->mOperator) &&
           selector->mNext &&
           selector->mNext->mOperator != selector->mOperator &&
@@ -2122,17 +2249,18 @@ static PRBool SelectorMatchesTree(RulePr
 
         // pretend the selector didn't match, and step through content
         // while testing the same selector
 
         // This approach is slightly strange in that when it recurs
         // it tests from the top of the content tree, down.  This
         // doesn't matter much for performance since most selectors
         // don't match.  (If most did, it might be faster...)
-        if (SelectorMatchesTree(*data, selector, aForStyling)) {
+        if (SelectorMatchesTree(*data, selector, aTreeMatchContext,
+                                aLookForRelevantLink)) {
           return PR_TRUE;
         }
       }
       selector = selector->mNext;
     }
     else {
       // for adjacent sibling and child combinators, if we didn't find
       // a match, we're done
@@ -2145,32 +2273,42 @@ static PRBool SelectorMatchesTree(RulePr
   return PR_TRUE; // all the selectors matched.
 }
 
 static void ContentEnumFunc(nsICSSStyleRule* aRule, nsCSSSelector* aSelector,
                             void* aData)
 {
   RuleProcessorData* data = (RuleProcessorData*)aData;
 
-  if (SelectorMatches(*data, aSelector, 0, PR_TRUE)) {
+  TreeMatchContext treeContext(PR_TRUE, data->mRuleWalker->VisitedHandling());
+  NodeMatchContext nodeContext(0, data->IsLink());
+  if (nodeContext.mIsRelevantLink) {
+    treeContext.mHaveRelevantLink = PR_TRUE;
+  }
+  if (SelectorMatches(*data, aSelector, nodeContext, treeContext)) {
     nsCSSSelector *next = aSelector->mNext;
-    if (!next || SelectorMatchesTree(*data, next, PR_TRUE)) {
+    if (!next || SelectorMatchesTree(*data, next, treeContext,
+                                     !nodeContext.mIsRelevantLink)) {
       // for performance, require that every implementation of
       // nsICSSStyleRule return the same pointer for nsIStyleRule (why
       // would anything multiply inherit nsIStyleRule anyway?)
 #ifdef DEBUG
       nsCOMPtr<nsIStyleRule> iRule = do_QueryInterface(aRule);
       NS_ASSERTION(static_cast<nsIStyleRule*>(aRule) == iRule.get(),
                    "Please fix QI so this performance optimization is valid");
 #endif
       aRule->RuleMatched();
       data->mRuleWalker->Forward(static_cast<nsIStyleRule*>(aRule));
       // nsStyleSet will deal with the !important rule
     }
   }
+
+  if (treeContext.mHaveRelevantLink) {
+    data->mRuleWalker->SetHaveRelevantLink();
+  }
 }
 
 NS_IMETHODIMP
 nsCSSRuleProcessor::RulesMatching(ElementRuleProcessorData *aData)
 {
   NS_PRECONDITION(aData->mContent->IsNodeOfType(nsINode::eELEMENT),
                   "content must be element");
 
@@ -2295,19 +2433,23 @@ nsCSSRuleProcessor::HasStateDependentSty
       nsCSSSelector* selector = *iter;
 
       nsRestyleHint possibleChange = IsSiblingOperator(selector->mOperator) ?
         eRestyle_LaterSiblings : eRestyle_Self;
 
       // If hint already includes all the bits of possibleChange,
       // don't bother calling SelectorMatches, since even if it returns false
       // hint won't change.
+      TreeMatchContext treeContext(PR_FALSE,
+                                   nsRuleWalker::eLinksVisitedOrUnvisited);
+      NodeMatchContext nodeContext(aData->mStateMask, PR_FALSE);
       if ((possibleChange & ~hint) &&
-          SelectorMatches(*aData, selector, aData->mStateMask, PR_FALSE) &&
-          SelectorMatchesTree(*aData, selector->mNext, PR_FALSE)) {
+          SelectorMatches(*aData, selector, nodeContext, treeContext) &&
+          SelectorMatchesTree(*aData, selector->mNext, treeContext, PR_FALSE))
+      {
         hint = nsRestyleHint(hint | possibleChange);
       }
     }
   }
   return hint;
 }
 
 PRBool
@@ -2333,19 +2475,22 @@ AttributeEnumFunc(nsCSSSelector* aSelect
   AttributeRuleProcessorData *data = aData->data;
 
   nsRestyleHint possibleChange = IsSiblingOperator(aSelector->mOperator) ?
     eRestyle_LaterSiblings : eRestyle_Self;
 
   // If enumData->change already includes all the bits of possibleChange, don't
   // bother calling SelectorMatches, since even if it returns false
   // enumData->change won't change.
+  TreeMatchContext treeContext(PR_FALSE,
+                               nsRuleWalker::eLinksVisitedOrUnvisited);
+  NodeMatchContext nodeContext(0, PR_FALSE);
   if ((possibleChange & ~(aData->change)) &&
-      SelectorMatches(*data, aSelector, 0, PR_FALSE) &&
-      SelectorMatchesTree(*data, aSelector->mNext, PR_FALSE)) {
+      SelectorMatches(*data, aSelector, nodeContext, treeContext) &&
+      SelectorMatchesTree(*data, aSelector->mNext, treeContext, PR_FALSE)) {
     aData->change = nsRestyleHint(aData->change | possibleChange);
   }
 }
 
 nsRestyleHint
 nsCSSRuleProcessor::HasAttributeDependentStyle(AttributeRuleProcessorData* aData)
 {
   NS_PRECONDITION(aData->mContent->IsNodeOfType(nsINode::eELEMENT),
@@ -2876,19 +3021,22 @@ nsCSSRuleProcessor::RefreshRuleCascade(n
 /* static */ PRBool
 nsCSSRuleProcessor::SelectorListMatches(RuleProcessorData& aData,
                                         nsCSSSelectorList* aSelectorList)
 {
   while (aSelectorList) {
     nsCSSSelector* sel = aSelectorList->mSelectors;
     NS_ASSERTION(sel, "Should have *some* selectors");
     NS_ASSERTION(!sel->IsPseudoElement(), "Shouldn't have been called");
-    if (SelectorMatches(aData, sel, 0, PR_FALSE)) {
+    TreeMatchContext treeContext(PR_FALSE,
+                                 nsRuleWalker::eRelevantLinkUnvisited);
+    NodeMatchContext nodeContext(0, PR_FALSE);
+    if (SelectorMatches(aData, sel, nodeContext, treeContext)) {
       nsCSSSelector* next = sel->mNext;
-      if (!next || SelectorMatchesTree(aData, next, PR_FALSE)) {
+      if (!next || SelectorMatchesTree(aData, next, treeContext, PR_FALSE)) {
         return PR_TRUE;
       }
     }
 
     aSelectorList = aSelectorList->mNext;
   }
 
   return PR_FALSE;
--- a/layout/style/nsCSSStruct.cpp
+++ b/layout/style/nsCSSStruct.cpp
@@ -201,24 +201,16 @@ nsCSSCornerSizes::nsCSSCornerSizes(const
 }
 
 nsCSSCornerSizes::~nsCSSCornerSizes()
 {
   MOZ_COUNT_DTOR(nsCSSCornerSizes);
 }
 
 void
-nsCSSCornerSizes::SetAllCornersTo(const nsCSSValue& aValue)
-{
-  NS_FOR_CSS_FULL_CORNERS(corner) {
-    this->GetFullCorner(corner).SetBothValuesTo(aValue);
-  }
-}
-
-void
 nsCSSCornerSizes::Reset()
 {
   NS_FOR_CSS_FULL_CORNERS(corner) {
     this->GetFullCorner(corner).Reset();
   }
 }
 
 #if NS_CORNER_TOP_LEFT != 0 || NS_CORNER_TOP_RIGHT != 1 || \
--- a/layout/style/nsCSSStruct.h
+++ b/layout/style/nsCSSStruct.h
@@ -201,17 +201,16 @@ struct nsCSSCornerSizes {
   PRBool HasValue() const {
     NS_FOR_CSS_FULL_CORNERS(corner) {
       if (this->GetFullCorner(corner).HasValue())
         return PR_TRUE;
     }
     return PR_FALSE;
   }
 
-  void SetAllCornersTo(const nsCSSValue& aValue);
   void Reset();
 
   nsCSSValuePair mTopLeft;
   nsCSSValuePair mTopRight;
   nsCSSValuePair mBottomRight;
   nsCSSValuePair mBottomLeft;
 
 protected:
--- a/layout/style/nsCSSValue.cpp
+++ b/layout/style/nsCSSValue.cpp
@@ -409,22 +409,16 @@ void nsCSSValue::SetDummyValue()