merging from cvs-trunk-mirror
authoredward.lee@engineering.uiuc.edu
Mon, 06 Aug 2007 16:03:20 -0700
changeset 4326 c9881a28179f534f5eb7089b73cdff1ee5ff2ec5
parent 4325 395f0c24c13d9dd640f4bf2187969d046434ca11 (current diff)
parent 4324 d39aec14c3e20e2b6e86ce9a14552374356775bd (diff)
child 4493 1d2af7f2f34d4f14ad12a679389252e6eaabcea5
push id1
push userbsmedberg@mozilla.com
push dateThu, 20 Mar 2008 16:49:24 +0000
treeherdermozilla-central@61007906a1f8 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone1.9a8pre
merging from cvs-trunk-mirror
build/unix/mozilla-js.pc.in
build/unix/mozilla-nspr.pc.in
build/unix/mozilla-nss.pc.in
build/unix/mozilla-plugin.pc.in
build/unix/mozilla-xpcom.pc.in
client.mk
config/autoconf.mk.in
config/rules.mk
configure.in
content/xslt/src/base/txTokenizer.h
gfx/cairo/cairo/src/cairo-font.c
gfx/cairo/cairo/src/cairo-pdf-test.h
gfx/cairo/cairo/src/cairo-ps-test.h
gfx/cairo/cairo/src/cairo-scaled-font-test.h
gfx/cairo/cairo/src/cairo-svg-test.h
gfx/cairo/cairo/src/cairo-xlib-test.h
gfx/cairo/fbcompose-bandaid.patch
gfx/cairo/libpixman/src/fbcompose.c
gfx/cairo/libpixman/src/fbedge.c
gfx/cairo/libpixman/src/fbedgeimp.h
gfx/cairo/libpixman/src/fbmmx.c
gfx/cairo/libpixman/src/fbmmx.h
gfx/cairo/libpixman/src/fbpict.c
gfx/cairo/libpixman/src/fbpict.h
gfx/cairo/libpixman/src/fbtrap.c
gfx/cairo/libpixman/src/icblt.c
gfx/cairo/libpixman/src/icbltone.c
gfx/cairo/libpixman/src/iccolor.c
gfx/cairo/libpixman/src/icformat.c
gfx/cairo/libpixman/src/icimage.c
gfx/cairo/libpixman/src/icimage.h
gfx/cairo/libpixman/src/icint.h
gfx/cairo/libpixman/src/icpixels.c
gfx/cairo/libpixman/src/icrect.c
gfx/cairo/libpixman/src/icrop.h
gfx/cairo/libpixman/src/icstipple.c
gfx/cairo/libpixman/src/ictransform.c
gfx/cairo/libpixman/src/ictrap.c
gfx/cairo/libpixman/src/ictri.c
gfx/cairo/libpixman/src/icutil.c
gfx/cairo/libpixman/src/pixman-xserver-compat.h
gfx/cairo/libpixman/src/pixregion.c
gfx/cairo/libpixman/src/pixregionint.h
gfx/cairo/libpixman/src/renderedge.c
gfx/cairo/libpixman/src/renderedge.h
gfx/cairo/quartz-glyph-rounding.patch
js/src/js.cpp
js/src/jsapi.cpp
js/src/jsarray.cpp
js/src/jsatom.cpp
js/src/jsbool.cpp
js/src/jscntxt.cpp
js/src/jsdate.cpp
js/src/jsdbgapi.cpp
js/src/jsemit.cpp
js/src/jsexn.cpp
js/src/jsfun.cpp
js/src/jsgc.cpp
js/src/jsinterp.cpp
js/src/jsiter.cpp
js/src/jsmath.cpp
js/src/jsnum.cpp
js/src/jsobj.cpp
js/src/jsopcode.cpp
js/src/jsparse.cpp
js/src/jsregexp.cpp
js/src/jsscan.cpp
js/src/jsscript.cpp
js/src/jsstr.cpp
js/src/jsxml.cpp
js/tests/js1_5/extensions/regress-363258.js
js/tests/js1_7/geniter/regress-387871.js
js/tests/js1_7/geniter/regress-390918.js
js/tests/js1_8/genexps/regress-347739.js
js/tests/js1_8/genexps/regress-349012-01.js
js/tests/js1_8/genexps/regress-349331.js
layout/reftests/bugs/379349-1-ref.xhtml
layout/reftests/bugs/379349-1a.xhtml
layout/reftests/bugs/379349-1b.xhtml
layout/reftests/bugs/379349-1c.xhtml
layout/reftests/bugs/379349-2-ref.xhtml
layout/reftests/bugs/379349-2a.xhtml
layout/reftests/bugs/379349-2b.xhtml
layout/reftests/bugs/379349-3-ref.xhtml
layout/reftests/bugs/379349-3a.xhtml
layout/reftests/bugs/379349-3b.xhtml
layout/reftests/bugs/386470-1-ref.html
layout/reftests/bugs/386470-1a.html
layout/reftests/bugs/386470-1b.html
layout/reftests/bugs/386470-1c.html
layout/reftests/svg/style-property-not-on-script-element-01.svg
parser/htmlparser/tests/mochitest/bug379025.txt
profile/build/Makefile.in
profile/build/nsProfileFactory.cpp
profile/build/profile.pkg
profile/defaults/Makefile.in
profile/defaults/bookmarks.html
profile/defaults/chrome/Makefile.in
profile/defaults/chrome/userChrome-example.css
profile/defaults/chrome/userContent-example.css
profile/defaults/localstore.rdf
profile/defaults/mimeTypes.rdf
profile/defaults/panels.rdf
profile/defaults/profiledef.pkg
profile/defaults/search.rdf
profile/pref-migrator/Makefile.in
profile/pref-migrator/public/Makefile.in
profile/pref-migrator/public/idl/guid_list.txt
profile/pref-migrator/public/idl/prefm.idl
profile/pref-migrator/public/nsIPrefMigration.idl
profile/pref-migrator/public/nsIPrefMigrationProgress.idl
profile/pref-migrator/resources/Makefile.in
profile/pref-migrator/resources/content/profileMigrationProgress.js
profile/pref-migrator/resources/content/profileMigrationProgress.xul
profile/pref-migrator/resources/jar.mn
profile/pref-migrator/resources/locale/en-US/profileMigrationProgress.dtd
profile/public/nsIProfileInternal.idl
profile/public/nsIProfileStartupListener.idl
profile/public/nsISessionRoaming.idl
profile/resources/Makefile.in
profile/resources/content/createProfileWizard.js
profile/resources/content/createProfileWizard.xul
profile/resources/content/migrateAllProfile.xul
profile/resources/content/profileManager.js
profile/resources/content/profileSelection.js
profile/resources/content/profileSelection.xul
profile/resources/content/selectLang.js
profile/resources/content/selectLang.xul
profile/resources/jar.mn
profile/resources/locale/en-US/createProfileWizard.dtd
profile/resources/locale/en-US/migrateAllProfile.dtd
profile/resources/locale/en-US/migration.properties
profile/resources/locale/en-US/profileManager.properties
profile/resources/locale/en-US/profileManagerMigrateAll.dtd
profile/resources/locale/en-US/profileSelection.dtd
profile/resources/locale/en-US/selectLang.dtd
profile/src/Makefile.in
profile/src/nsProfile.cpp
profile/src/nsProfile.h
profile/src/nsProfileAccess.cpp
profile/src/nsProfileAccess.h
testing/performance/talos/base_profile/prefs.js
testing/performance/talos/ffprofile_linux.py
testing/performance/talos/utils.py
toolkit/components/places/public/nsIRemoteContainer.idl
toolkit/content/tests/chrome/widget_progressmeter.xul
toolkit/crashreporter/client/crashreporter.ico
toolkit/crashreporter/client/crashreporter.rc
toolkit/crashreporter/google-breakpad/AUTHORS
toolkit/crashreporter/google-breakpad/COPYING
toolkit/crashreporter/google-breakpad/ChangeLog
toolkit/crashreporter/google-breakpad/INSTALL
toolkit/crashreporter/google-breakpad/Makefile.am
toolkit/crashreporter/google-breakpad/Makefile.in
toolkit/crashreporter/google-breakpad/NEWS
toolkit/crashreporter/google-breakpad/README
toolkit/crashreporter/google-breakpad/aclocal.m4
toolkit/crashreporter/google-breakpad/autotools/config.guess
toolkit/crashreporter/google-breakpad/autotools/config.sub
toolkit/crashreporter/google-breakpad/autotools/depcomp
toolkit/crashreporter/google-breakpad/autotools/install-sh
toolkit/crashreporter/google-breakpad/autotools/ltmain.sh
toolkit/crashreporter/google-breakpad/autotools/missing
toolkit/crashreporter/google-breakpad/configure
toolkit/crashreporter/google-breakpad/configure.ac
toolkit/crashreporter/google-breakpad/src/client/minidump_file_writer-inl.h
toolkit/crashreporter/google-breakpad/src/client/minidump_file_writer.cc
toolkit/crashreporter/google-breakpad/src/client/minidump_file_writer.h
toolkit/crashreporter/google-breakpad/src/client/windows/Makefile.in
toolkit/crashreporter/google-breakpad/src/client/windows/handler/Makefile.in
toolkit/crashreporter/google-breakpad/src/client/windows/handler/exception_handler.cc
toolkit/crashreporter/google-breakpad/src/client/windows/handler/exception_handler.h
toolkit/crashreporter/google-breakpad/src/client/windows/handler/exception_handler.vcproj
toolkit/crashreporter/google-breakpad/src/client/windows/sender/Makefile.in
toolkit/crashreporter/google-breakpad/src/client/windows/sender/crash_report_sender.cc
toolkit/crashreporter/google-breakpad/src/client/windows/sender/crash_report_sender.h
toolkit/crashreporter/google-breakpad/src/client/windows/sender/crash_report_sender.vcproj
toolkit/crashreporter/google-breakpad/src/common/windows/Makefile.in
toolkit/crashreporter/google-breakpad/src/common/windows/guid_string.cc
toolkit/crashreporter/google-breakpad/src/common/windows/guid_string.h
toolkit/crashreporter/google-breakpad/src/common/windows/http_upload.cc
toolkit/crashreporter/google-breakpad/src/common/windows/http_upload.h
toolkit/crashreporter/google-breakpad/src/common/windows/pdb_source_line_writer.cc
toolkit/crashreporter/google-breakpad/src/common/windows/pdb_source_line_writer.h
toolkit/crashreporter/google-breakpad/src/common/windows/string_utils-inl.h
toolkit/crashreporter/google-breakpad/src/config.h.in
toolkit/crashreporter/google-breakpad/src/processor/address_map-inl.h
toolkit/crashreporter/google-breakpad/src/processor/address_map.h
toolkit/crashreporter/google-breakpad/src/processor/address_map_unittest.cc
toolkit/crashreporter/google-breakpad/src/processor/call_stack.cc
toolkit/crashreporter/google-breakpad/src/processor/contained_range_map-inl.h
toolkit/crashreporter/google-breakpad/src/processor/contained_range_map.h
toolkit/crashreporter/google-breakpad/src/processor/contained_range_map_unittest.cc
toolkit/crashreporter/google-breakpad/src/processor/linked_ptr.h
toolkit/crashreporter/google-breakpad/src/processor/minidump.cc
toolkit/crashreporter/google-breakpad/src/processor/minidump_dump.cc
toolkit/crashreporter/google-breakpad/src/processor/minidump_dump_test
toolkit/crashreporter/google-breakpad/src/processor/minidump_processor.cc
toolkit/crashreporter/google-breakpad/src/processor/minidump_processor_unittest.cc
toolkit/crashreporter/google-breakpad/src/processor/minidump_stackwalk.cc
toolkit/crashreporter/google-breakpad/src/processor/minidump_stackwalk_machine_readable_test
toolkit/crashreporter/google-breakpad/src/processor/minidump_stackwalk_test
toolkit/crashreporter/google-breakpad/src/processor/pathname_stripper.cc
toolkit/crashreporter/google-breakpad/src/processor/pathname_stripper.h
toolkit/crashreporter/google-breakpad/src/processor/pathname_stripper_unittest.cc
toolkit/crashreporter/google-breakpad/src/processor/postfix_evaluator-inl.h
toolkit/crashreporter/google-breakpad/src/processor/postfix_evaluator.h
toolkit/crashreporter/google-breakpad/src/processor/postfix_evaluator_unittest.cc
toolkit/crashreporter/google-breakpad/src/processor/process_state.cc
toolkit/crashreporter/google-breakpad/src/processor/range_map-inl.h
toolkit/crashreporter/google-breakpad/src/processor/range_map.h
toolkit/crashreporter/google-breakpad/src/processor/range_map_unittest.cc
toolkit/crashreporter/google-breakpad/src/processor/scoped_ptr.h
toolkit/crashreporter/google-breakpad/src/processor/simple_symbol_supplier.cc
toolkit/crashreporter/google-breakpad/src/processor/simple_symbol_supplier.h
toolkit/crashreporter/google-breakpad/src/processor/stack_frame_info.h
toolkit/crashreporter/google-breakpad/src/processor/stackwalker.cc
toolkit/crashreporter/google-breakpad/src/processor/stackwalker_ppc.cc
toolkit/crashreporter/google-breakpad/src/processor/stackwalker_ppc.h
toolkit/crashreporter/google-breakpad/src/processor/stackwalker_selftest.cc
toolkit/crashreporter/google-breakpad/src/processor/stackwalker_x86.cc
toolkit/crashreporter/google-breakpad/src/processor/stackwalker_x86.h
toolkit/crashreporter/google-breakpad/src/processor/testdata/minidump2.dmp
toolkit/crashreporter/google-breakpad/src/processor/testdata/minidump2.dump.out
toolkit/crashreporter/google-breakpad/src/processor/testdata/minidump2.stackwalk.out
toolkit/crashreporter/google-breakpad/src/processor/testdata/module1.out
toolkit/crashreporter/google-breakpad/src/processor/testdata/module2.out
toolkit/crashreporter/google-breakpad/src/processor/testdata/module3_bad.out
toolkit/crashreporter/google-breakpad/src/processor/testdata/symbols/kernel32.pdb/BCE8785C57B44245A669896B6A19B9542/kernel32.sym
toolkit/crashreporter/google-breakpad/src/processor/testdata/test_app.cc
toolkit/crashreporter/google-breakpad/src/tools/windows/dump_syms/dump_syms.cc
toolkit/crashreporter/google-breakpad/src/tools/windows/dump_syms/dump_syms.vcproj
toolkit/crashreporter/google-breakpad/src/tools/windows/dump_syms/run_regtest.sh
toolkit/crashreporter/google-breakpad/src/tools/windows/dump_syms/testdata/dump_syms_regtest.pdb
toolkit/crashreporter/google-breakpad/src/tools/windows/symupload/symupload.cc
toolkit/crashreporter/google-breakpad/src/tools/windows/symupload/symupload.vcproj
toolkit/crashreporter/nsExceptionHandler.cpp
toolkit/crashreporter/tools/symbolstore.py
toolkit/crashreporter/tools/upload_symbols.sh
toolkit/crashreporter/tools/win32/dump_syms.exe
uriloader/exthandler/nsHandlerService.js
uriloader/exthandler/nsIHandlerService.idl
uriloader/exthandler/tests/Makefile.in
uriloader/exthandler/tests/unit/head_handlerService.js
uriloader/exthandler/tests/unit/tail_handlerService.js
uriloader/exthandler/tests/unit/test_handlerService.js
xpcom/base/nsCycleCollectionParticipant.cpp
xpcom/base/nsCycleCollectionParticipant.h
xpfe/components/killAll/Makefile.in
xpfe/components/killAll/nsKillAll.js
xpfe/components/urlwidget/Makefile.in
xpfe/components/urlwidget/nsIUrlWidget.idl
xpfe/components/urlwidget/nsUrlWidget.cpp
xpfe/components/urlwidget/nsUrlWidget.h
xpinstall/standalone/makefile.win
xpinstall/standalone/nsSimpleNotifier.cpp
xpinstall/standalone/nsSimpleNotifier.h
xpinstall/standalone/standalone.cpp
--- a/.hgtags
+++ b/.hgtags
@@ -1,2 +1,3 @@
 df7a3c8ffeeaba229067efee5a20e21dae0dd877 MOZILLA_1_9_a4_BASE
 4209e16b58411750ac73f761023e46b76b793e2c MOZILLA_1_9_a6_BASE
+66a5c7bce7ee86a820d3c0d54fa07cb719be751c MOZILLA_1_9_a7_BASE
--- a/Makefile.in
+++ b/Makefile.in
@@ -77,21 +77,16 @@ DIST_GARBAGE = config.cache config.log c
    $(topsrcdir)/.mozconfig.mk $(topsrcdir)/.mozconfig.out 
 
 # Build pseudo-external modules first when export is explicitly called
 export::
 	$(RM) -rf $(DIST)/sdk
 	$(MAKE) -C config export
 	$(MAKE) tier_nspr
 
-install::
-ifdef MOZ_LDAP_XPCOM
-	$(MAKE) -C directory/c-sdk real_install DESTDIR=$(DESTDIR) libdir=$(mozappdir) includedir=$(includedir)/ldap
-endif
-
 include $(topsrcdir)/config/rules.mk
 
 # After we build tier toolkit, go back and build the tools from previous dirs
 tier_toolkit::
 	$(MAKE) tools_tier_js
 	$(MAKE) tools_tier_xpcom
 	$(MAKE) tools_tier_necko
 	$(MAKE) tools_tier_gecko
--- a/accessible/build/Makefile.in
+++ b/accessible/build/Makefile.in
@@ -74,16 +74,17 @@ SHARED_LIBRARY_LIBS += ../src/xul/$(LIB_
 endif
 
 ifndef DISABLE_XFORMS_HOOKS
 SHARED_LIBRARY_LIBS += ../src/xforms/$(LIB_PREFIX)accessibility_xforms_s.$(LIB_SUFFIX)
 endif
 
 EXTRA_DSO_LIBS = \
 	gkgfx \
+	thebes \
 	$(NULL)
 
 EXTRA_DSO_LDOPTS =           \
 	$(LIBS_DIR)              \
 	$(EXTRA_DSO_LIBS)        \
 	$(MOZ_UNICHARUTIL_LIBS)  \
 	$(MOZ_COMPONENT_LIBS)    \
 	$(NULL)
--- a/accessible/public/nsIAccessibleProvider.idl
+++ b/accessible/public/nsIAccessibleProvider.idl
@@ -40,17 +40,17 @@
 
 #include "nsISupports.idl"
 
 /**
  * nsIAccessibleProvider interface is used to link element and accessible
    object. For that XBL binding of element should implement the interface.
  */
 
-[scriptable, uuid(7250d0f0-732d-4981-b73e-dd5d71b16183)]
+[scriptable, uuid(3f7f9194-c625-4a85-8148-6d92d34897fa)]
 interface nsIAccessibleProvider : nsISupports
 {
   /**
    * Constants set of common use.
    */
 
   /** For elements that spawn a new document. For example now it is used by
     <xul:iframe>, <xul:browser> and <xul:editor>. */
@@ -64,47 +64,49 @@ interface nsIAccessibleProvider : nsISup
   const long XULButton = 0x00001002;
   const long XULCheckbox = 0x00001003;
   const long XULColorPicker = 0x00001004;
   const long XULColorPickerTile = 0x00001005;
   const long XULCombobox = 0x00001006;
   const long XULDropmarker = 0x00001007;
   const long XULGroupbox = 0x00001008;
   const long XULImage = 0x00001009;
-  const long XULLink = 0x00001010;
-  const long XULListbox = 0x00001011;
-  const long XULListitem = 0x00001012;
-  const long XULMenubar = 0x00001013;
-  const long XULMenuitem = 0x00001014;
-  const long XULMenupopup = 0x00001015;
-  const long XULMenuSeparator = 0x00001016;
-  const long XULProgressMeter = 0x00001017;
-  const long XULStatusBar = 0x00001018;
-  const long XULRadioButton = 0x00001019;
-  const long XULRadioGroup = 0x00001020;
+  const long XULLink = 0x0000100A;
+  const long XULListbox = 0x0000100B;
+  const long XULListitem = 0x0000100C;
+  const long XULMenubar = 0x0000100D;
+  const long XULMenuitem = 0x0000100E;
+  const long XULMenupopup = 0x0000100F;
+  const long XULMenuSeparator = 0x00001010;
+  const long XULProgressMeter = 0x00001011;
+  const long XULScale = 0x00001012;
+  const long XULStatusBar = 0x00001013;
+  const long XULRadioButton = 0x00001014;
+  const long XULRadioGroup = 0x00001015;
 
   /** The single tab in a dialog or tabbrowser/editor interface */
-  const long XULTab = 0x00001021;
+  const long XULTab = 0x00001016;
 
   /** A combination of a tabs object and a tabpanels object */
-  const long XULTabBox = 0x00001022;
+  const long XULTabBox = 0x00001017;
 
   /** The collection of tab objects, useable in the TabBox and independant of
    as well */
-  const long XULTabs = 0x00001023;
+  const long XULTabs = 0x00001018;
 
-  const long XULText             = 0x00001024;
-  const long XULTextBox          = 0x00001025;
-  const long XULTree             = 0x00001026;
-  const long XULTreeColumns      = 0x00001027;
-  const long XULTreeColumnitem   = 0x00001028;
-  const long XULToolbar          = 0x00001029;
-  const long XULToolbarSeparator = 0x00001030;
-  const long XULTooltip          = 0x00001031;
-  const long XULToolbarButton    = 0x00001032;
+  const long XULText             = 0x00001019;
+  const long XULTextBox          = 0x0000101A;
+  const long XULThumb            = 0x0000101B;
+  const long XULTree             = 0x0000101C;
+  const long XULTreeColumns      = 0x0000101D;
+  const long XULTreeColumnitem   = 0x0000101E;
+  const long XULToolbar          = 0x0000101F;
+  const long XULToolbarSeparator = 0x00001020;
+  const long XULTooltip          = 0x00001021;
+  const long XULToolbarButton    = 0x00001022;
 
 
   /**
    * Constants set is used by XForms elements.
    */
 
   /** Used for xforms elements that provide accessible object for itself as
    * well for anonymous content. This property are used for upload,
--- a/accessible/public/nsIAccessibleRole.idl
+++ b/accessible/public/nsIAccessibleRole.idl
@@ -39,17 +39,17 @@
 #include "nsISupports.idl"
 
 /**
  * Defines cross platform (Gecko) roles.
  *
  * @note - When adding a new role, be sure to also add it to nsRoleMap.h for
  *         each platform.
  */
-[scriptable, uuid(d6d73bc4-0fe9-46a1-a8dd-6d93b041e54b)]
+[scriptable, uuid(31685b85-36a3-448c-99ed-b034a198e303)]
 interface nsIAccessibleRole : nsISupports
 {
   /**
    * Used when accessible hans't strong defined role.
    */
   const unsigned long ROLE_NOTHING = 0;
 
   /**
@@ -739,14 +739,19 @@ interface nsIAccessibleRole : nsISupport
   const unsigned long ROLE_COMBOBOX_LIST = 114;
 
   /**
    * A item of list that is shown by combobox;
    */
   const unsigned long ROLE_COMBOBOX_LISTITEM = 115;
 
   /**
+   * An image map -- has child links representing the areas
+   */
+  const unsigned long ROLE_IMAGE_MAP = 116;
+  
+  /**
    * It's not role actually. This contanst is important to help ensure
    * nsRoleMap's are synchronized.
    */
-  const unsigned long ROLE_LAST_ENTRY = 116;
+  const unsigned long ROLE_LAST_ENTRY = 117;
 };
 
--- a/accessible/public/nsPIAccessible.idl
+++ b/accessible/public/nsPIAccessible.idl
@@ -36,17 +36,17 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsISupports.idl"
 
 interface nsIAccessible;
 interface nsIAccessibleEvent;
 
-[uuid(817ae493-b238-4fbc-a623-d20ed81eebcd)]
+[uuid(03932812-53d1-4dc7-965d-6b6ad8a872b1)]
 interface nsPIAccessible : nsISupports
 {
   /**
    * Set accessible parent.
    */
   void setParent(in nsIAccessible aAccParent);
 
   /**
@@ -95,11 +95,12 @@ interface nsPIAccessible : nsISupports
    * Assert if child not in parent's cache.
    */
   void testChildCache(in nsIAccessible aCachedChild);
 
   /**
    * Returns text of accessible if accessible has text role otherwise empty
    * string.
    */
-  AString getContentText();
+  void appendTextTo(out AString aString, in unsigned long aStartOffset,
+                    in unsigned long aLength);
 };
 
--- a/accessible/src/atk/nsAccessibleWrap.cpp
+++ b/accessible/src/atk/nsAccessibleWrap.cpp
@@ -422,93 +422,95 @@ nsAccessibleWrap::CreateMaiInterfaces(vo
     PRUint8 actionCount = 0;
     nsresult rv = GetNumActions(&actionCount);
     if (NS_SUCCEEDED(rv) && actionCount > 0) {
        interfacesBits |= 1 << MAI_INTERFACE_ACTION; 
     }
 
     PRUint32 accRole;
     GetRole(&accRole);
-
+  
     //nsIAccessibleText
     nsCOMPtr<nsIAccessibleText> accessInterfaceText;
     QueryInterface(NS_GET_IID(nsIAccessibleText),
                    getter_AddRefs(accessInterfaceText));
     if (accessInterfaceText) {
         interfacesBits |= 1 << MAI_INTERFACE_TEXT;
     }
 
     //nsIAccessibleEditableText
     nsCOMPtr<nsIAccessibleEditableText> accessInterfaceEditableText;
     QueryInterface(NS_GET_IID(nsIAccessibleEditableText),
                    getter_AddRefs(accessInterfaceEditableText));
     if (accessInterfaceEditableText) {
         interfacesBits |= 1 << MAI_INTERFACE_EDITABLE_TEXT;
     }
 
-    //nsIAccessibleSelection
-    nsCOMPtr<nsIAccessibleSelectable> accessInterfaceSelection;
-    QueryInterface(NS_GET_IID(nsIAccessibleSelectable),
-                   getter_AddRefs(accessInterfaceSelection));
-    if (accessInterfaceSelection) {
-        interfacesBits |= 1 << MAI_INTERFACE_SELECTION;
-    }
-
     //nsIAccessibleValue
     nsCOMPtr<nsIAccessibleValue> accessInterfaceValue;
     QueryInterface(NS_GET_IID(nsIAccessibleValue),
                    getter_AddRefs(accessInterfaceValue));
     if (accessInterfaceValue) {
        interfacesBits |= 1 << MAI_INTERFACE_VALUE; 
     }
 
-    //nsIAccessibleHypertext
-    PRInt32 linkCount = 0;
-    nsCOMPtr<nsIAccessibleHyperText> accessInterfaceHypertext;
-    QueryInterface(NS_GET_IID(nsIAccessibleHyperText),
-                   getter_AddRefs(accessInterfaceHypertext));
-    if (accessInterfaceHypertext) {
-        nsresult rv = accessInterfaceHypertext->GetLinks(&linkCount);
-        if (NS_SUCCEEDED(rv) && (linkCount > 0)) {
-            interfacesBits |= 1 << MAI_INTERFACE_HYPERTEXT;
-        }
-    }
-
-    //nsIAccessibleHyperLink
-    nsCOMPtr<nsIAccessibleHyperLink> accessInterfaceHyperlink;
-    QueryInterface(NS_GET_IID(nsIAccessibleHyperLink),
-                   getter_AddRefs(accessInterfaceHyperlink));
-    if (accessInterfaceHyperlink) {
-       interfacesBits |= 1 << MAI_INTERFACE_HYPERLINK_IMPL;
-    }
-
-    //nsIAccessibleTable
-    nsCOMPtr<nsIAccessibleTable> accessInterfaceTable;
-    QueryInterface(NS_GET_IID(nsIAccessibleTable),
-                   getter_AddRefs(accessInterfaceTable));
-    if (accessInterfaceTable) {
-        interfacesBits |= 1 << MAI_INTERFACE_TABLE;
-    }
-
     //nsIAccessibleDocument
     nsCOMPtr<nsIAccessibleDocument> accessInterfaceDocument;
     QueryInterface(NS_GET_IID(nsIAccessibleDocument),
                               getter_AddRefs(accessInterfaceDocument));
     if (accessInterfaceDocument) {
         interfacesBits |= 1 << MAI_INTERFACE_DOCUMENT;
     }
 
     //nsIAccessibleImage
     nsCOMPtr<nsIAccessibleImage> accessInterfaceImage;
     QueryInterface(NS_GET_IID(nsIAccessibleImage),
                               getter_AddRefs(accessInterfaceImage));
     if (accessInterfaceImage) {
         interfacesBits |= 1 << MAI_INTERFACE_IMAGE;
     }
 
+    //nsIAccessibleHyperLink
+    nsCOMPtr<nsIAccessibleHyperLink> accessInterfaceHyperlink;
+    QueryInterface(NS_GET_IID(nsIAccessibleHyperLink),
+                   getter_AddRefs(accessInterfaceHyperlink));
+    if (accessInterfaceHyperlink) {
+       interfacesBits |= 1 << MAI_INTERFACE_HYPERLINK_IMPL;
+    }
+
+    if (!MustPrune(this)) {  // These interfaces require children
+      //nsIAccessibleHypertext
+      PRInt32 linkCount = 0;
+      nsCOMPtr<nsIAccessibleHyperText> accessInterfaceHypertext;
+      QueryInterface(NS_GET_IID(nsIAccessibleHyperText),
+                     getter_AddRefs(accessInterfaceHypertext));
+      if (accessInterfaceHypertext) {
+          nsresult rv = accessInterfaceHypertext->GetLinks(&linkCount);
+          if (NS_SUCCEEDED(rv) && (linkCount > 0)) {
+              interfacesBits |= 1 << MAI_INTERFACE_HYPERTEXT;
+          }
+      }
+
+      //nsIAccessibleTable
+      nsCOMPtr<nsIAccessibleTable> accessInterfaceTable;
+      QueryInterface(NS_GET_IID(nsIAccessibleTable),
+                     getter_AddRefs(accessInterfaceTable));
+      if (accessInterfaceTable) {
+          interfacesBits |= 1 << MAI_INTERFACE_TABLE;
+      }
+      
+      //nsIAccessibleSelection
+      nsCOMPtr<nsIAccessibleSelectable> accessInterfaceSelection;
+      QueryInterface(NS_GET_IID(nsIAccessibleSelectable),
+                     getter_AddRefs(accessInterfaceSelection));
+      if (accessInterfaceSelection) {
+          interfacesBits |= 1 << MAI_INTERFACE_SELECTION;
+      }
+    }
+
     return interfacesBits;
 }
 
 static GType
 GetMaiAtkType(PRUint16 interfacesBits)
 {
     GType type;
     static const GTypeInfo tinfo = {
@@ -867,17 +869,17 @@ getParentCB(AtkObject *aAtkObj)
     }
     return aAtkObj->accessible_parent;
 }
 
 gint
 getChildCountCB(AtkObject *aAtkObj)
 {
     nsAccessibleWrap *accWrap = GetAccessibleWrap(aAtkObj);
-    if (!accWrap) {
+    if (!accWrap || nsAccessibleWrap::MustPrune(accWrap)) {
         return 0;
     }
 
     PRInt32 count = 0;
     nsCOMPtr<nsIAccessibleHyperText> hyperText;
     accWrap->QueryInterface(NS_GET_IID(nsIAccessibleHyperText), getter_AddRefs(hyperText));
     if (hyperText) {
         // If HyperText, then number of links matches number of children
@@ -901,17 +903,17 @@ refChildCB(AtkObject *aAtkObj, gint aChi
       return nsnull;
     }
 
     // XXX Fix this so it is not O(n^2) to walk through the children!
     // Either we can cache the last accessed child so that we can just GetNextSibling()
     // or we should cache an array of children in each nsAccessible
     // (instead of mNextSibling on the children)
     nsAccessibleWrap *accWrap = GetAccessibleWrap(aAtkObj);
-    if (!accWrap) {
+    if (!accWrap || nsAccessibleWrap::MustPrune(accWrap)) {
         return nsnull;
     }
 
     nsresult rv;
     nsCOMPtr<nsIAccessible> accChild;
     nsCOMPtr<nsIAccessibleHyperText> hyperText;
     accWrap->QueryInterface(NS_GET_IID(nsIAccessibleHyperText), getter_AddRefs(hyperText));
     if (hyperText) {
@@ -1546,8 +1548,13 @@ nsAccessibleWrap::FireAtkShowHideEvent(n
                           "children_changed::remove",
                           indexInParent,
                           aObject,
                           NULL);
 
     return NS_OK;
 }
 
+PRBool nsAccessibleWrap::MustPrune(nsIAccessible *aAccessible)
+{
+  PRUint32 role = Role(aAccessible);
+  return role == nsIAccessibleRole::ROLE_GRAPHIC;
+}
--- a/accessible/src/atk/nsAccessibleWrap.h
+++ b/accessible/src/atk/nsAccessibleWrap.h
@@ -110,16 +110,19 @@ public:
     void SetMaiHyperlink(MaiHyperlink* aMaiHyperlink);
 
     static const char * ReturnString(nsAString &aString) {
       static nsCString returnedString;
       returnedString = NS_ConvertUTF16toUTF8(aString);
       return returnedString.get();
     }
 
+    // Should this accessible be allowed to have any ATK children
+    static PRBool MustPrune(nsIAccessible *aAccessible);
+
 protected:
     nsresult FireAtkStateChangeEvent(nsIAccessibleEvent *aEvent,
                                      AtkObject *aObject);
     nsresult FireAtkTextChangedEvent(nsIAccessibleEvent *aEvent,
                                      AtkObject *aObject);
     nsresult FireAtkPropChangedEvent(nsIAccessibleEvent *aEvent,
                                      AtkObject *aObject);
     nsresult FireAtkShowHideEvent(nsIAccessibleEvent *aEvent,
--- a/accessible/src/atk/nsMaiInterfaceComponent.cpp
+++ b/accessible/src/atk/nsMaiInterfaceComponent.cpp
@@ -64,17 +64,17 @@ componentInterfaceInitCB(AtkComponentIfa
 }
 
 AtkObject *
 refAccessibleAtPointCB(AtkComponent *aComponent,
                        gint aAccX, gint aAccY,
                        AtkCoordType aCoordType)
 {
     nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aComponent));
-    if (!accWrap)
+    if (!accWrap || nsAccessibleWrap::MustPrune(accWrap))
         return nsnull;
 
     // or ATK_XY_SCREEN  what is definition this in nsIAccessible ???
     if (aCoordType == ATK_XY_WINDOW) {
         /* deal with the coord type */
     }
 
     nsCOMPtr<nsIAccessible> pointAcc;
--- a/accessible/src/atk/nsRoleMap.h
+++ b/accessible/src/atk/nsRoleMap.h
@@ -157,11 +157,12 @@ static const PRUint32 atkRoleMap[] = {
     ATK_ROLE_REDUNDANT_OBJECT,    // nsIAccessibleRole::ROLE_REDUNDANT_OBJECT     108
     ATK_ROLE_FORM,                // nsIAccessibleRole::ROLE_FORM                 109
     ATK_ROLE_INPUT_METHOD_WINDOW, // nsIAccessibleRole::ROLE_IME                  110
     ATK_ROLE_APPLICATION,         // nsIAccessibleRole::ROLE_APP_ROOT             111
     ATK_ROLE_MENU,                // nsIAccessibleRole::ROLE_PARENT_MENUITEM      112
     ATK_ROLE_CALENDAR,            // nsIAccessibleRole::ROLE_CALENDAR             113
     ATK_ROLE_MENU,                // nsIAccessibleRole::ROLE_COMBOBOX_LIST        114
     ATK_ROLE_MENU_ITEM,           // nsIAccessibleRole::ROLE_COMBOBOX_LISTITEM    115
+    ATK_ROLE_IMAGE,               // nsIAccessibleRole::ROLE_IMAGE_MAP            116
     kROLE_ATK_LAST_ENTRY          // nsIAccessibleRole::ROLE_LAST_ENTRY
 };
 
--- a/accessible/src/base/nsARIAMap.cpp
+++ b/accessible/src/base/nsARIAMap.cpp
@@ -56,17 +56,17 @@
  *  There are no nsIAccessibleRole enums for the following landmark roles:
  *    banner, contentinfo, main, navigation, note, search, secondary, seealso, breadcrumbs
  */ 
 
 static const nsStateMapEntry kEndEntry = {0, 0, 0};  // To fill in array of state mappings
 
 nsRoleMapEntry nsARIAMap::gWAIRoleMap[] = 
 {
-  {"alert", nsIAccessibleRole::ROLE_ALERT, eNameOkFromChildren, eNoValue, kNoReqStates, kEndEntry},
+  {"alert", nsIAccessibleRole::ROLE_ALERT, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"alertdialog", nsIAccessibleRole::ROLE_ALERT, eNameOkFromChildren, eNoValue, kNoReqStates, kEndEntry},
   {"application", nsIAccessibleRole::ROLE_APPLICATION, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"button", nsIAccessibleRole::ROLE_PUSHBUTTON, eNameOkFromChildren, eNoValue, kNoReqStates,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {"pressed", kBoolState, nsIAccessibleStates::STATE_PRESSED}, kEndEntry},
   {"checkbox", nsIAccessibleRole::ROLE_CHECKBUTTON, eNameOkFromChildren, eNoValue, nsIAccessibleStates::STATE_CHECKABLE,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {"checked", kBoolState, nsIAccessibleStates::STATE_CHECKED},
@@ -76,36 +76,37 @@ nsRoleMapEntry nsARIAMap::gWAIRoleMap[] 
             {"checked", kBoolState, nsIAccessibleStates::STATE_CHECKED},
             {"checked", "mixed", nsIAccessibleStates::STATE_MIXED},
             {"readonly", kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"columnheader", nsIAccessibleRole::ROLE_COLUMNHEADER, eNameOkFromChildren, eNoValue, kNoReqStates,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {"selected", kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
             {"selected", "false", nsIAccessibleStates::STATE_SELECTABLE},
             {"readonly", kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
-  {"combobox", nsIAccessibleRole::ROLE_COMBOBOX, eNameLabelOrTitle, eHasValueMinMax, kNoReqStates,
+  {"combobox", nsIAccessibleRole::ROLE_COMBOBOX, eNameLabelOrTitle, eHasValueMinMax, nsIAccessibleStates::STATE_COLLAPSED,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {"readonly", kBoolState, nsIAccessibleStates::STATE_READONLY},
-            {"expanded", kBoolState, nsIAccessibleStates::STATE_EXPANDED},
-            {"multiselectable", kBoolState, nsIAccessibleStates::STATE_MULTISELECTABLE | nsIAccessibleStates::STATE_EXTSELECTABLE}, kEndEntry},
+            {"expanded", kBoolState, nsIAccessibleStates::STATE_EXPANDED}, kEndEntry},
   {"description", nsIAccessibleRole::ROLE_TEXT_CONTAINER, eNameOkFromChildren, eNoValue, kNoReqStates, kEndEntry},
   {"dialog", nsIAccessibleRole::ROLE_DIALOG, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"document", nsIAccessibleRole::ROLE_DOCUMENT, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"grid", nsIAccessibleRole::ROLE_TABLE, eNameLabelOrTitle, eNoValue, nsIAccessibleStates::STATE_FOCUSABLE,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {"multiselectable", kBoolState, nsIAccessibleStates::STATE_MULTISELECTABLE | nsIAccessibleStates::STATE_EXTSELECTABLE},
             {"readonly", kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"gridcell", nsIAccessibleRole::ROLE_CELL, eNameOkFromChildren, eNoValue, kNoReqStates,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {"expanded", kBoolState, nsIAccessibleStates::STATE_EXPANDED},
             {"expanded", "false", nsIAccessibleStates::STATE_COLLAPSED},
             {"selected", kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
             {"selected", "false", nsIAccessibleStates::STATE_SELECTABLE},
             {"readonly", kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"group", nsIAccessibleRole::ROLE_GROUPING, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
+  {"heading", nsIAccessibleRole::ROLE_HEADING, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
+  {"img", nsIAccessibleRole::ROLE_GRAPHIC, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"label", nsIAccessibleRole::ROLE_LABEL, eNameOkFromChildren, eNoValue, kNoReqStates, kEndEntry},
   {"link", nsIAccessibleRole::ROLE_LINK, eNameOkFromChildren, eNoValue, nsIAccessibleStates::STATE_LINKED,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
   {"list", nsIAccessibleRole::ROLE_LIST, eNameLabelOrTitle, eNoValue, kNoReqStates,
             {"readonly", kBoolState, nsIAccessibleStates::STATE_READONLY},
             {"multiselectable", kBoolState, nsIAccessibleStates::STATE_MULTISELECTABLE | nsIAccessibleStates::STATE_EXTSELECTABLE}, kEndEntry},
   {"listbox", nsIAccessibleRole::ROLE_LIST, eNameLabelOrTitle, eNoValue, kNoReqStates,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
@@ -139,48 +140,51 @@ nsRoleMapEntry nsARIAMap::gWAIRoleMap[] 
             {"checked", "false", nsIAccessibleStates::STATE_CHECKABLE}, kEndEntry},
   {"progressbar", nsIAccessibleRole::ROLE_PROGRESSBAR, eNameLabelOrTitle, eHasValueMinMax, nsIAccessibleStates::STATE_READONLY,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
   {"radio", nsIAccessibleRole::ROLE_RADIOBUTTON, eNameOkFromChildren, eNoValue, kNoReqStates,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {"checked", kBoolState, nsIAccessibleStates::STATE_CHECKED}, kEndEntry},
   {"radiogroup", nsIAccessibleRole::ROLE_GROUPING, eNameLabelOrTitle, eNoValue, kNoReqStates,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
+  {"region", nsIAccessibleRole::ROLE_PANE, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"row", nsIAccessibleRole::ROLE_ROW, eNameOkFromChildren, eNoValue, kNoReqStates,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {"selected", kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
             {"selected", "false", nsIAccessibleStates::STATE_SELECTABLE},
             {"expanded", kBoolState, nsIAccessibleStates::STATE_EXPANDED},
             {"expanded", "false", nsIAccessibleStates::STATE_COLLAPSED}, kEndEntry},
   {"rowheader", nsIAccessibleRole::ROLE_ROWHEADER, eNameOkFromChildren, eNoValue, kNoReqStates,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {"selected", kBoolState, nsIAccessibleStates::STATE_SELECTED | nsIAccessibleStates::STATE_SELECTABLE},
             {"selected", "false", nsIAccessibleStates::STATE_SELECTABLE},
             {"readonly", kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"secret", nsIAccessibleRole::ROLE_PASSWORD_TEXT, eNameLabelOrTitle, eNoValue, nsIAccessibleStates::STATE_PROTECTED,
             // Manually map EXT_STATE_SINGLE_LINE and EXT_STATE_MULTI_LINE FROM aaa:multiline
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
+  {"section", nsIAccessibleRole::ROLE_SECTION, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"separator", nsIAccessibleRole::ROLE_SEPARATOR, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"slider", nsIAccessibleRole::ROLE_SLIDER, eNameLabelOrTitle, eHasValueMinMax, kNoReqStates,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {"readonly", kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"spinbutton", nsIAccessibleRole::ROLE_SPINBUTTON, eNameLabelOrTitle, eHasValueMinMax, kNoReqStates,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {"readonly", kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"status", nsIAccessibleRole::ROLE_STATUSBAR, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"tab", nsIAccessibleRole::ROLE_PAGETAB, eNameOkFromChildren, eNoValue, kNoReqStates,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
   {"tablist", nsIAccessibleRole::ROLE_PAGETABLIST, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
   {"tabpanel", nsIAccessibleRole::ROLE_PROPERTYPAGE, eNameLabelOrTitle, eNoValue, kNoReqStates, kEndEntry},
-  {"textbox", nsIAccessibleRole::ROLE_ENTRY, eNameLabelOrTitle, eHasValueMinMax, kNoReqStates,
+  {"textbox", nsIAccessibleRole::ROLE_ENTRY, eNameLabelOrTitle, eNoValue, kNoReqStates,
             // Manually map EXT_STATE_SINGLE_LINE and EXT_STATE_MULTI_LINE FROM aaa:multiline
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {"readonly", kBoolState, nsIAccessibleStates::STATE_READONLY}, kEndEntry},
   {"toolbar", nsIAccessibleRole::ROLE_TOOLBAR, eNameLabelOrTitle, eNoValue, kNoReqStates,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE}, kEndEntry},
+  {"tooltip", nsIAccessibleRole::ROLE_TOOLTIP, eNameOkFromChildren, eNoValue, kNoReqStates, kEndEntry},
   {"tree", nsIAccessibleRole::ROLE_OUTLINE, eNameLabelOrTitle, eNoValue, kNoReqStates,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {"readonly", kBoolState, nsIAccessibleStates::STATE_READONLY},
             {"multiselectable", kBoolState, nsIAccessibleStates::STATE_MULTISELECTABLE | nsIAccessibleStates::STATE_EXTSELECTABLE}, kEndEntry},
   {"treegrid", nsIAccessibleRole::ROLE_TREE_TABLE, eNameLabelOrTitle, eNoValue, kNoReqStates,
             {"disabled", kBoolState, nsIAccessibleStates::STATE_UNAVAILABLE},
             {"readonly", kBoolState, nsIAccessibleStates::STATE_READONLY},
             {"multiselectable", kBoolState, nsIAccessibleStates::STATE_MULTISELECTABLE | nsIAccessibleStates::STATE_EXTSELECTABLE}, kEndEntry},
--- a/accessible/src/base/nsAccessibilityAtomList.h
+++ b/accessible/src/base/nsAccessibilityAtomList.h
@@ -150,49 +150,64 @@ ACCESSIBILITY_ATOM(owns, "owns")
   // Alphabetical list of attributes
 ACCESSIBILITY_ATOM(acceltext, "acceltext")
 ACCESSIBILITY_ATOM(accesskey, "accesskey")
 ACCESSIBILITY_ATOM(alt, "alt")
 ACCESSIBILITY_ATOM(anonid, "anonid") // Used for ID's in XBL
 ACCESSIBILITY_ATOM(autocomplete, "autocomplete") // Used as attribute value too
 ACCESSIBILITY_ATOM(control, "control")
 ACCESSIBILITY_ATOM(cycles, "cycles") // used for XUL cycler attribute
+ACCESSIBILITY_ATOM(curpos, "curpos") // XUL
 ACCESSIBILITY_ATOM(data, "data")
 ACCESSIBILITY_ATOM(disabled, "disabled")
+ACCESSIBILITY_ATOM(droppable, "droppable")   // XUL combo box
 ACCESSIBILITY_ATOM(editable, "editable")
 ACCESSIBILITY_ATOM(_for, "for")
+ACCESSIBILITY_ATOM(hidden, "hidden")   // XUL tree columns
 ACCESSIBILITY_ATOM(href, "href")
 ACCESSIBILITY_ATOM(id, "id")
+ACCESSIBILITY_ATOM(increment, "increment") // XUL
 ACCESSIBILITY_ATOM(lang, "lang")
+ACCESSIBILITY_ATOM(maxpos, "maxpos") // XUL
+ACCESSIBILITY_ATOM(minpos, "minpos") // XUL
 ACCESSIBILITY_ATOM(multiline, "multiline")
 ACCESSIBILITY_ATOM(name, "name")
 ACCESSIBILITY_ATOM(onclick, "onclick")
 ACCESSIBILITY_ATOM(readonly, "readonly")
 ACCESSIBILITY_ATOM(src, "src")
 ACCESSIBILITY_ATOM(summary, "summary")
 ACCESSIBILITY_ATOM(tabindex, "tabindex")
 ACCESSIBILITY_ATOM(title, "title")
 ACCESSIBILITY_ATOM(tooltiptext, "tooltiptext")
 ACCESSIBILITY_ATOM(type, "type")
 ACCESSIBILITY_ATOM(value, "value")
 
   // ARIA (DHTML accessibility) attributes
+ACCESSIBILITY_ATOM(atomic, "atomic")
+ACCESSIBILITY_ATOM(busy, "busy")
+ACCESSIBILITY_ATOM(channel, "channel")
 ACCESSIBILITY_ATOM(activedescendant, "activedescendant")
 ACCESSIBILITY_ATOM(checked, "checked")
-ACCESSIBILITY_ATOM(droppable, "droppable")
+ACCESSIBILITY_ATOM(datatype, "datatype")
+ACCESSIBILITY_ATOM(dropeffect, "dropeffect")
 ACCESSIBILITY_ATOM(expanded, "expanded")
+ACCESSIBILITY_ATOM(grab, "grab")
+ACCESSIBILITY_ATOM(haspopup, "haspopup")
 ACCESSIBILITY_ATOM(invalid, "invalid")
 ACCESSIBILITY_ATOM(level, "level")
+ACCESSIBILITY_ATOM(live, "live")
 ACCESSIBILITY_ATOM(multiselectable, "multiselectable")
 ACCESSIBILITY_ATOM(posinset, "posinset")
+ACCESSIBILITY_ATOM(pressed, "pressed")
+ACCESSIBILITY_ATOM(relevant, "relevant")
 ACCESSIBILITY_ATOM(required, "required")
 ACCESSIBILITY_ATOM(role, "role")
+ACCESSIBILITY_ATOM(secret, "secret")
 ACCESSIBILITY_ATOM(selected, "selected")
 ACCESSIBILITY_ATOM(setsize, "setsize")
 ACCESSIBILITY_ATOM(valuenow, "valuenow")    // For DHTML widget values
 ACCESSIBILITY_ATOM(valuemin, "valuemin")
 ACCESSIBILITY_ATOM(valuemax, "valuemax")
-ACCESSIBILITY_ATOM(hidden, "hidden")
 
   // misc atoms
 // a form property used to obtain the default label
 // of an HTML button from the button frame
 ACCESSIBILITY_ATOM(defaultLabel, "defaultLabel")
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -82,16 +82,17 @@
 #include "nsDocShellLoadTypes.h"
 
 #ifdef MOZ_XUL
 #include "nsXULAlertAccessible.h"
 #include "nsXULColorPickerAccessible.h"
 #include "nsXULFormControlAccessible.h"
 #include "nsXULMenuAccessibleWrap.h"
 #include "nsXULSelectAccessible.h"
+#include "nsXULSliderAccessible.h"
 #include "nsXULTabAccessible.h"
 #include "nsXULTextAccessible.h"
 #include "nsXULTreeAccessibleWrap.h"
 #endif
 
 // For native window support for object/embed/applet tags
 #ifdef XP_WIN
 #include "nsHTMLWin32ObjectAccessible.h"
@@ -1401,16 +1402,27 @@ NS_IMETHODIMP nsAccessibilityService::Ge
   // of some property that makes this object interesting
   // We don't do this for <body>, <html>, <window>, <dialog> etc. which 
   // correspond to the doc accessible and will be created in any case
   if (!newAcc && content->Tag() != nsAccessibilityAtoms::body && content->GetParent() && 
       (content->IsFocusable() ||
       (isHTML && nsAccUtils::HasListener(content, NS_LITERAL_STRING("click"))) ||
        content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::describedby) ||
        content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::labelledby) ||
+       content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::flowto) ||
+       content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::controls) ||
+       content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::atomic) ||
+       content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::busy) ||
+       content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::channel) ||
+       content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::datatype) ||
+       content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::dropeffect) ||
+       content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::grab) ||
+       content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::haspopup) ||
+       content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::live) ||
+       content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::relevant) ||
        content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::required) ||
        content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::invalid) ||
        !role.IsEmpty())) {
     // This content is focusable or has an interesting dynamic content accessibility property.
     // If it's interesting we need it in the accessibility hierarchy so that events or
     // other accessibles can point to it, or so that it can hold a state, etc.
     if (isHTML) {
       // Interesting HTML container which may have selectable text and/or embedded objects
@@ -1597,16 +1609,19 @@ nsresult nsAccessibilityService::GetAcce
       *aAccessible = new nsXULMenuSeparatorAccessible(aNode, weakShell);
       break;
     case nsIAccessibleProvider::XULProgressMeter:
       *aAccessible = new nsXULProgressMeterAccessible(aNode, weakShell);
       break;
     case nsIAccessibleProvider::XULStatusBar:
       *aAccessible = new nsXULStatusBarAccessible(aNode, weakShell);
       break;
+    case nsIAccessibleProvider::XULScale:
+      *aAccessible = new nsXULSliderAccessible(aNode, weakShell);
+      break;
     case nsIAccessibleProvider::XULRadioButton:
       *aAccessible = new nsXULRadioButtonAccessible(aNode, weakShell);
       break;
     case nsIAccessibleProvider::XULRadioGroup:
       *aAccessible = new nsXULRadioGroupAccessible(aNode, weakShell);
       break;
     case nsIAccessibleProvider::XULTab:
       *aAccessible = new nsXULTabAccessible(aNode, weakShell);
@@ -1618,16 +1633,19 @@ nsresult nsAccessibilityService::GetAcce
       *aAccessible = new nsXULTabsAccessible(aNode, weakShell);
       break;
     case nsIAccessibleProvider::XULText:
       *aAccessible = new nsXULTextAccessible(aNode, weakShell);
       break;
     case nsIAccessibleProvider::XULTextBox:
       *aAccessible = new nsXULTextFieldAccessible(aNode, weakShell);
       break;
+    case nsIAccessibleProvider::XULThumb:
+      *aAccessible = new nsXULThumbAccessible(aNode, weakShell);
+      break;
     case nsIAccessibleProvider::XULTree:
       *aAccessible = new nsXULTreeAccessibleWrap(aNode, weakShell);
       break;
     case nsIAccessibleProvider::XULTreeColumns:
       *aAccessible = new nsXULTreeColumnsAccessibleWrap(aNode, weakShell);
       break;
     case nsIAccessibleProvider::XULTreeColumnitem:
       *aAccessible = new nsXULTreeColumnitemAccessible(aNode, weakShell);
--- a/accessible/src/base/nsAccessibilityService.h
+++ b/accessible/src/base/nsAccessibilityService.h
@@ -163,17 +163,18 @@ static const char kRoleNames[][20] = {
   "section",             //ROLE_SECTION
   "redundant object",    //ROLE_REDUNDANT_OBJECT
   "form",                //ROLE_FORM
   "ime",                 //ROLE_IME
   "app root",            //ROLE_APP_ROOT
   "parent menuitem",     //ROLE_PARENT_MENUITEM
   "calendar",            //ROLE_CALENDAR
   "combobox list",       //ROLE_COMBOBOX_LIST
-  "combobox listitem"    //ROLE_COMBOBOX_LISTITEM
+  "combobox listitem",   //ROLE_COMBOBOX_LISTITEM
+  "image map"            //ROLE_IMAGE_MAP
 };
 
 class nsAccessibilityService : public nsIAccessibilityService, 
                                public nsIObserver,
                                public nsIWebProgressListener,
                                public nsSupportsWeakReference
 {
 public:
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -577,16 +577,28 @@ NS_IMETHODIMP nsAccessible::Shutdown()
   }
 
   return nsAccessNodeWrap::Shutdown();
 }
 
 NS_IMETHODIMP nsAccessible::InvalidateChildren()
 {
   // Document has transformed, reset our invalid children and child count
+
+  // Reset the sibling pointers, they will be set up again the next time
+  // CacheChildren() is called.
+  // Note: we don't want to start creating accessibles at this point,
+  // so don't use GetNextSibling() here. (bug 387252)
+  nsAccessible* child = static_cast<nsAccessible*>(mFirstChild);
+  while (child && child->mNextSibling != DEAD_END_ACCESSIBLE) {
+    nsIAccessible *next = child->mNextSibling;
+    child->mNextSibling = nsnull;
+    child = static_cast<nsAccessible*>(next);
+  }
+
   mAccChildCount = eChildCountUninitialized;
   mFirstChild = nsnull;
   return NS_OK;
 }
 
 NS_IMETHODIMP nsAccessible::GetParent(nsIAccessible **  aParent)
 {
   nsresult rv = GetCachedParent(aParent);
@@ -1444,16 +1456,20 @@ nsresult nsAccessible::AppendNameFromAcc
                                                    PRBool aFromValue)
 {
   nsAutoString textEquivalent, value;
 
   nsCOMPtr<nsIDOMNode> domNode(do_QueryInterface(aContent));
   nsCOMPtr<nsIAccessible> accessible;
   if (domNode == mDOMNode) {
     accessible = this;
+    if (!aFromValue) {
+      // prevent recursive call GetName()
+      return NS_OK;
+    }
   }
   else {
     nsCOMPtr<nsIAccessibilityService> accService =
       do_GetService("@mozilla.org/accessibilityService;1");
     NS_ENSURE_TRUE(accService, NS_ERROR_FAILURE);
     accService->GetAccessibleInWeakShell(domNode, mWeakShell, getter_AddRefs(accessible));
   }
   if (accessible) {
@@ -1502,22 +1518,23 @@ nsresult nsAccessible::AppendFlatStringF
           isHTMLBlock = PR_TRUE;
           if (!aFlatString->IsEmpty()) {
             aFlatString->Append(PRUnichar(' '));
           }
         }
       }
     }
     if (aContent->TextLength() > 0) {
-      nsAutoString text;
-      aContent->AppendTextTo(text);
-      if (!text.IsEmpty())
-        aFlatString->Append(text);
-      if (isHTMLBlock && !aFlatString->IsEmpty())
+      nsIFrame *frame = shell->GetPrimaryFrameFor(aContent);
+      NS_ENSURE_TRUE(frame, NS_ERROR_FAILURE);
+      nsresult rv = frame->GetRenderedText(aFlatString);
+      NS_ENSURE_SUCCESS(rv, rv);
+      if (isHTMLBlock && !aFlatString->IsEmpty()) {
         aFlatString->Append(PRUnichar(' '));
+      }
     }
     return NS_OK;
   }
 
   nsAutoString textEquivalent;
   if (!aContent->IsNodeOfType(nsINode::eHTML)) {
     if (aContent->IsNodeOfType(nsINode::eXUL)) {
       nsCOMPtr<nsIPresShell> shell = GetPresShell();
@@ -2025,16 +2042,44 @@ nsAccessible::FireAccessibleEvent(nsIAcc
 
   return obsService->NotifyObservers(aEvent, NS_ACCESSIBLE_EVENT_TOPIC, nsnull);
 }
 
 NS_IMETHODIMP nsAccessible::GetFinalRole(PRUint32 *aRole)
 {
   if (mRoleMapEntry) {
     *aRole = mRoleMapEntry->role;
+
+    // These unfortunate exceptions don't fit into the ARIA table
+    // This is where the nsIAccessible role depends on both the role and ARIA state
+    if (*aRole == nsIAccessibleRole::ROLE_ENTRY) {
+      nsCOMPtr<nsIContent> content = do_QueryInterface(mDOMNode);
+      if (content && 
+          content->AttrValueIs(kNameSpaceID_WAIProperties , nsAccessibilityAtoms::secret,
+                               nsAccessibilityAtoms::_true, eCaseMatters)) {
+        // For entry field with aaa:secret="true"
+        *aRole = nsIAccessibleRole::ROLE_PASSWORD_TEXT;
+      }
+    }
+    else if (*aRole == nsIAccessibleRole::ROLE_PUSHBUTTON) {
+      nsCOMPtr<nsIContent> content = do_QueryInterface(mDOMNode);
+      if (content) {
+        if (content->HasAttr(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::pressed)) {
+          // For aaa:pressed="false" or aaa:pressed="true"
+          // For simplicity, any pressed attribute indicates it's a toggle button
+          *aRole = nsIAccessibleRole::ROLE_TOGGLE_BUTTON;
+        }
+        else if (content->AttrValueIs(kNameSpaceID_WAIProperties, nsAccessibilityAtoms::haspopup,
+                                      nsAccessibilityAtoms::_true, eCaseMatters)) {
+          // For button with aaa:haspopup="true"
+          *aRole = nsIAccessibleRole::ROLE_BUTTONMENU;
+        }
+      }
+    }
+  
     if (*aRole != nsIAccessibleRole::ROLE_NOTHING) {
       return NS_OK;
     }
   }
   return mDOMNode ? GetRole(aRole) : NS_ERROR_FAILURE;  // Node already shut down
 }
 
 NS_IMETHODIMP
@@ -2067,16 +2112,17 @@ nsAccessible::GetAttributes(nsIPersisten
     }
 
     char *ariaProperties[] = { "live", "channel", "atomic", "relevant", "datatype", "level",
                                "posinset", "setsize", "sort", "grab", "dropeffect"};
 
     for (PRUint32 index = 0; index < NS_ARRAY_LENGTH(ariaProperties); index ++) {
       nsAutoString value;
       nsCOMPtr<nsIAtom> attr = do_GetAtom(ariaProperties[index]);
+      NS_ENSURE_TRUE(attr, NS_ERROR_OUT_OF_MEMORY);
       if (content->GetAttr(kNameSpaceID_WAIProperties, attr, value)) {
         ToLowerCase(value);
         attributes->SetStringProperty(nsDependentCString(ariaProperties[index]), value, oldValueUnused);    
       }
     }
   }
 
   if (!nsAccUtils::HasAccGroupAttrs(attributes)) {
@@ -2213,16 +2259,17 @@ PRBool nsAccessible::MappedAttrState(nsI
 {
   // Return true if we should continue
   if (!aStateMapEntry->attributeName) {
     return PR_FALSE;  // Stop looking -- no more states
   }
 
   nsAutoString attribValue;
   nsCOMPtr<nsIAtom> attribAtom = do_GetAtom(aStateMapEntry->attributeName); // XXX put atoms directly in entry
+  NS_ENSURE_TRUE(attribAtom, NS_ERROR_OUT_OF_MEMORY);
   if (aContent->GetAttr(kNameSpaceID_WAIProperties, attribAtom, attribValue)) {
     if (aStateMapEntry->attributeValue == kBoolState) {
       // No attribute value map specified in state map entry indicates state cleared
       if (attribValue.EqualsLiteral("false")) {
         return *aStateInOut &= ~aStateMapEntry->state;
       }
       return *aStateInOut |= aStateMapEntry->state;
     }
@@ -2244,19 +2291,28 @@ nsAccessible::GetFinalState(PRUint32 *aS
 
   // Set additional states which presence depends on another states.
   if (aExtraState) {
     if (!(*aState & nsIAccessibleStates::STATE_UNAVAILABLE)) {
       *aExtraState |= nsIAccessibleStates::EXT_STATE_ENABLED |
                       nsIAccessibleStates::EXT_STATE_SENSITIVE;
     }
 
-    if (*aState & (nsIAccessibleStates::STATE_COLLAPSED |
-                   nsIAccessibleStates::STATE_EXPANDED)) {
+    const PRUint32 kExpandCollapseStates =
+      nsIAccessibleStates::STATE_COLLAPSED | nsIAccessibleStates::STATE_EXPANDED;
+    if (*aState & kExpandCollapseStates) {
       *aExtraState |= nsIAccessibleStates::EXT_STATE_EXPANDABLE;
+      if ((*aState & kExpandCollapseStates) == kExpandCollapseStates) {
+        // Cannot be both expanded and collapsed -- this happens 
+        // in ARIA expanded combobox because of limitation of nsARIAMap
+        // XXX Perhaps we will be able to make this less hacky if 
+        // we support extended states in nsARIAMap, e.g. derive
+        // COLLAPSED from EXPANDABLE && !EXPANDED
+        *aExtraState &= ~nsIAccessibleStates::STATE_COLLAPSED;
+      } 
     }
   }
 
   // Apply ARIA states to be sure accessible states will be overriden.
   return GetARIAState(aState);
 }
 
 nsresult
@@ -2319,120 +2375,78 @@ NS_IMETHODIMP nsAccessible::GetValue(nsA
     if (content && content->GetAttr(kNameSpaceID_WAIProperties,
                                     nsAccessibilityAtoms::valuenow, aValue)) {
       return NS_OK;
     }
   }
   return NS_OK;
 }
 
-NS_IMETHODIMP nsAccessible::GetMaximumValue(double *aMaximumValue)
+// nsIAccessibleValue
+NS_IMETHODIMP
+nsAccessible::GetMaximumValue(double *aMaximumValue)
 {
-  *aMaximumValue = 0;
-  if (!mDOMNode) {
-    return NS_ERROR_FAILURE;  // Node already shut down
-  }
-  if (mRoleMapEntry) {
-    if (mRoleMapEntry->valueRule == eNoValue) {
-      return NS_OK;
-    }
-    nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
-    nsAutoString valueMax;
-    if (content && content->GetAttr(kNameSpaceID_WAIProperties,
-                                    nsAccessibilityAtoms::valuemax, valueMax) &&
-        valueMax.IsEmpty() == PR_FALSE) {
-      *aMaximumValue = PR_strtod(NS_LossyConvertUTF16toASCII(valueMax).get(), nsnull);
-      return NS_OK;
-    }
-  }
-  return NS_ERROR_FAILURE; // No maximum
+  return GetAttrValue(kNameSpaceID_WAIProperties,
+                      nsAccessibilityAtoms::valuemax, aMaximumValue);
 }
 
-NS_IMETHODIMP nsAccessible::GetMinimumValue(double *aMinimumValue)
+NS_IMETHODIMP
+nsAccessible::GetMinimumValue(double *aMinimumValue)
 {
-  *aMinimumValue = 0;
-  if (!mDOMNode) {
-    return NS_ERROR_FAILURE;  // Node already shut down
-  }
-  if (mRoleMapEntry) {
-    if (mRoleMapEntry->valueRule == eNoValue) {
-      return NS_OK;
-    }
-    nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
-    nsAutoString valueMin;
-    if (content && content->GetAttr(kNameSpaceID_WAIProperties,
-                                    nsAccessibilityAtoms::valuemin, valueMin) &&
-        valueMin.IsEmpty() == PR_FALSE) {
-      *aMinimumValue = PR_strtod(NS_LossyConvertUTF16toASCII(valueMin).get(), nsnull);
-      return NS_OK;
-    }
-  }
-  return NS_ERROR_FAILURE; // No minimum
+  return GetAttrValue(kNameSpaceID_WAIProperties,
+                      nsAccessibilityAtoms::valuemin, aMinimumValue);
 }
 
-NS_IMETHODIMP nsAccessible::GetMinimumIncrement(double *aMinIncrement)
+NS_IMETHODIMP
+nsAccessible::GetMinimumIncrement(double *aMinIncrement)
 {
+  NS_ENSURE_ARG_POINTER(aMinIncrement);
   *aMinIncrement = 0;
-  return NS_ERROR_NOT_IMPLEMENTED; // No mimimum increment in dynamic content spec right now
+
+  // No mimimum increment in dynamic content spec right now
+  return NS_OK_NO_ARIA_VALUE;
 }
 
-NS_IMETHODIMP nsAccessible::GetCurrentValue(double *aValue)
+NS_IMETHODIMP
+nsAccessible::GetCurrentValue(double *aValue)
 {
-  *aValue = 0;
-  if (!mDOMNode) {
-    return NS_ERROR_FAILURE;  // Node already shut down
-  }
-  if (mRoleMapEntry) {
-    if (mRoleMapEntry->valueRule == eNoValue) {
-      return NS_OK;
-    }
-    nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
-    nsAutoString value;
-    if (content && content->GetAttr(kNameSpaceID_WAIProperties,
-                                    nsAccessibilityAtoms::valuenow, value) &&
-        value.IsEmpty() == PR_FALSE) {
-      *aValue = PR_strtod(NS_LossyConvertUTF16toASCII(value).get(), nsnull);
-      return NS_OK;
-    }
-  }
-  return NS_ERROR_FAILURE; // No value
+  return GetAttrValue(kNameSpaceID_WAIProperties,
+                      nsAccessibilityAtoms::valuenow, aValue);
 }
 
-NS_IMETHODIMP nsAccessible::SetCurrentValue(double aValue)
+NS_IMETHODIMP
+nsAccessible::SetCurrentValue(double aValue)
 {
-  if (!mDOMNode) {
+  if (!mDOMNode)
     return NS_ERROR_FAILURE;  // Node already shut down
-  }
-  if (mRoleMapEntry) {
-    if (mRoleMapEntry->valueRule == eNoValue) {
-      return NS_OK;
-    }
-    const PRUint32 kValueCannotChange = nsIAccessibleStates::STATE_READONLY |
-                                        nsIAccessibleStates::STATE_UNAVAILABLE;
-
-    if (State(this) & kValueCannotChange) {
-      return NS_ERROR_FAILURE;
-    }
-    double minValue;
-    if (NS_SUCCEEDED(GetMinimumValue(&minValue)) && aValue < minValue) {
-      return NS_ERROR_INVALID_ARG;
-    }
-    double maxValue;
-    if (NS_SUCCEEDED(GetMaximumValue(&maxValue)) && aValue > maxValue) {
-      return NS_ERROR_INVALID_ARG;
-    }
-    nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
-    if (content) {
-      nsAutoString newValue;
-      newValue.AppendFloat(aValue);
-      return content->SetAttr(kNameSpaceID_WAIProperties,
-                              nsAccessibilityAtoms::valuenow, newValue, PR_TRUE);
-    }
-  }
-  return NS_ERROR_FAILURE; // Not in a role that can accept value
+
+  if (!mRoleMapEntry || mRoleMapEntry->valueRule == eNoValue)
+    return NS_OK_NO_ARIA_VALUE;
+
+  const PRUint32 kValueCannotChange = nsIAccessibleStates::STATE_READONLY |
+                                      nsIAccessibleStates::STATE_UNAVAILABLE;
+
+  if (State(this) & kValueCannotChange)
+    return NS_ERROR_FAILURE;
+
+  double minValue = 0;
+  if (NS_SUCCEEDED(GetMinimumValue(&minValue)) && aValue < minValue)
+    return NS_ERROR_INVALID_ARG;
+
+  double maxValue = 0;
+  if (NS_SUCCEEDED(GetMaximumValue(&maxValue)) && aValue > maxValue)
+    return NS_ERROR_INVALID_ARG;
+
+  nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
+  NS_ENSURE_STATE(content);
+
+  nsAutoString newValue;
+  newValue.AppendFloat(aValue);
+  return content->SetAttr(kNameSpaceID_WAIProperties,
+                          nsAccessibilityAtoms::valuenow, newValue, PR_TRUE);
 }
 
 /* void setName (in DOMString name); */
 NS_IMETHODIMP nsAccessible::SetName(const nsAString& name)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
@@ -3130,28 +3144,44 @@ nsresult nsAccessible::GetLinkOffset(PRI
   return NS_ERROR_FAILURE;
 }
 
 PRInt32 nsAccessible::TextLength(nsIAccessible *aAccessible)
 {
   if (!IsText(aAccessible))
     return 1;
 
+  nsCOMPtr<nsPIAccessNode> pAccNode(do_QueryInterface(aAccessible));
+  NS_ASSERTION(pAccNode, "QI to nsPIAccessNode failed");
+
+  nsIFrame *frame = pAccNode->GetFrame();
+  if (frame) { // Optimal way to get the text length -- no string copy
+    nsIContent *content = frame->GetContent();
+    if (content) {
+      PRUint32 length;
+      nsresult rv = nsHyperTextAccessible::ContentToRenderedOffset(frame, content->TextLength(), &length);
+      return NS_SUCCEEDED(rv) ? length : -1;
+    }
+  }
+
+  // For list bullets (or anything other accessible which would compute its own text
+  // They don't have their own frame.
+  // XXX In the future, list bullets may have frame and anon content, so 
+  // we should be able to remove this at that point
   nsCOMPtr<nsPIAccessible> pAcc(do_QueryInterface(aAccessible));
-  NS_ENSURE_TRUE(pAcc, NS_ERROR_FAILURE);
+  NS_ASSERTION(pAcc, "QI to nsPIAccessible failed");
 
   nsAutoString text;
-  pAcc->GetContentText(text);
+  pAcc->AppendTextTo(text, 0, PR_UINT32_MAX); // Get all the text
   return text.Length();
 }
 
 NS_IMETHODIMP
-nsAccessible::GetContentText(nsAString& aText)
+nsAccessible::AppendTextTo(nsAString& aText, PRUint32 aStartOffset, PRUint32 aLength)
 {
-  aText.Truncate();
   return NS_OK;
 }
 
 already_AddRefed<nsIAccessible>
 nsAccessible::GetFirstAvailableAccessible(nsIDOMNode *aStartNode, PRBool aRequireLeaf)
 {
   nsIAccessibilityService *accService = GetAccService();
   nsCOMPtr<nsIAccessible> accessible;
@@ -3214,8 +3244,33 @@ PRBool nsAccessible::CheckVisibilityInPa
       }
     }
 
     document = parentDoc;
   }
 
   return PR_TRUE;
 }
+
+nsresult
+nsAccessible::GetAttrValue(PRUint32 aNameSpaceID, nsIAtom *aName,
+                           double *aValue)
+{
+  NS_ENSURE_ARG_POINTER(aValue);
+  *aValue = 0;
+
+  if (!mDOMNode)
+    return NS_ERROR_FAILURE;  // Node already shut down
+
+ if (!mRoleMapEntry || mRoleMapEntry->valueRule == eNoValue)
+    return NS_OK_NO_ARIA_VALUE;
+
+  nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
+  NS_ENSURE_STATE(content);
+
+  PRInt32 result = NS_OK;
+  nsAutoString value;
+  if (content->GetAttr(aNameSpaceID, aName, value) && !value.IsEmpty())
+    *aValue = value.ToFloat(&result);
+
+  return result;
+}
+
--- a/accessible/src/base/nsAccessible.h
+++ b/accessible/src/base/nsAccessible.h
@@ -62,16 +62,19 @@
 struct nsRect;
 class nsIContent;
 class nsIFrame;
 class nsIPresShell;
 class nsIDOMNode;
 class nsIAtom;
 class nsIView;
 
+#define NS_OK_NO_ARIA_VALUE \
+NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_GENERAL, 0x21)
+
 // When mNextSibling is set to this, it indicates there ar eno more siblings
 #define DEAD_END_ACCESSIBLE static_cast<nsIAccessible*>((void*)1)
 
 // Saves a data member -- if child count equals this value we haven't
 // cached children or child count yet
 enum { eChildCountUninitialized = -1 };
 
 class nsAccessibleDOMStringList : public nsIDOMDOMStringList
@@ -144,17 +147,17 @@ public:
   static PRBool IsTextInterfaceSupportCorrect(nsIAccessible *aAccessible);
 #endif
 
   static PRBool IsCorrectFrameType(nsIFrame* aFrame, nsIAtom* aAtom);
   static PRUint32 State(nsIAccessible *aAcc) { PRUint32 state; aAcc->GetFinalState(&state, nsnull); return state; }
   static PRUint32 Role(nsIAccessible *aAcc) { PRUint32 role; aAcc->GetFinalRole(&role); return role; }
   static PRBool IsText(nsIAccessible *aAcc) { PRUint32 role = Role(aAcc); return role == nsIAccessibleRole::ROLE_TEXT_LEAF || role == nsIAccessibleRole::ROLE_STATICTEXT; }
   static PRBool IsEmbeddedObject(nsIAccessible *aAcc) { PRUint32 role = Role(aAcc); return role != nsIAccessibleRole::ROLE_TEXT_LEAF && role != nsIAccessibleRole::ROLE_WHITESPACE && role != nsIAccessibleRole::ROLE_STATICTEXT; }
-  static PRInt32 TextLength(nsIAccessible *aAccessible);
+  static PRInt32 TextLength(nsIAccessible *aAccessible); // Returns -1 on failure
   static PRBool IsLeaf(nsIAccessible *aAcc) { PRInt32 numChildren; aAcc->GetChildCount(&numChildren); return numChildren > 0; }
   static PRBool IsNodeRelevant(nsIDOMNode *aNode); // Is node something that could have an attached accessible
   
   already_AddRefed<nsIAccessible> GetParent() {
     nsIAccessible *parent = nsnull;
     GetParent(&parent);
     return parent;
   }
@@ -270,16 +273,27 @@ protected:
 
   // For accessibles that have actions
   static void DoCommandCallback(nsITimer *aTimer, void *aClosure);
   nsresult DoCommand(nsIContent *aContent = nsnull);
 
   // Check the visibility across both parent content and chrome
   PRBool CheckVisibilityInParentChain(nsIDocument* aDocument, nsIView* aView);
 
+  /**
+   * Get numeric value of the given attribute.
+   *
+   * @param aNameSpaceID - namespace ID of the attribute
+   * @param aName - name of the attribute
+   * @param aValue - value of the attribute
+   *
+   * @return - NS_OK_NO_ARIA_VALUE if there is no setted ARIA attribute
+   */
+  nsresult GetAttrValue(PRUint32 aNameSpaceID, nsIAtom *aName, double *aValue);
+
   // Data Members
   nsCOMPtr<nsIAccessible> mParent;
   nsIAccessible *mFirstChild, *mNextSibling;
   nsRoleMapEntry *mRoleMapEntry; // Non-null indicates author-supplied role; possibly state & value as well
   PRInt32 mAccChildCount;
 };
 
 
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -209,18 +209,21 @@ nsDocAccessible::GetDescription(nsAStrin
 }
 
 NS_IMETHODIMP
 nsDocAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // nsAccessible::GetState() always fail for document accessible.
   nsAccessible::GetState(aState, aExtraState);
 
+#ifdef MOZ_XUL
   nsCOMPtr<nsIXULDocument> xulDoc(do_QueryInterface(mDocument));
-  if (!xulDoc) {
+  if (!xulDoc)
+#endif
+  {
     // XXX Need to invent better check to see if doc is focusable,
     // which it should be if it is scrollable. A XUL document could be focusable.
     // See bug 376803.
     *aState |= nsIAccessibleStates::STATE_FOCUSABLE;
   }
 
   if (!mIsContentLoaded) {
     *aState |= nsIAccessibleStates::STATE_BUSY;
@@ -392,18 +395,16 @@ NS_IMETHODIMP nsDocAccessible::GetDocume
   }
 
   return NS_ERROR_FAILURE;
 }
 
 void nsDocAccessible::SetEditor(nsIEditor* aEditor)
 {
   mEditor = aEditor;
-  if (mEditor)
-    mEditor->AddEditActionListener(this);
 }
 
 void nsDocAccessible::CheckForEditor()
 {
   if (mEditor) {
     return;  // Already have editor, don't need to check
   }
   if (!mDocument) {
@@ -525,20 +526,17 @@ NS_IMETHODIMP nsDocAccessible::Shutdown(
 {
   if (!mWeakShell) {
     return NS_OK;  // Already shutdown
   }
 
   nsCOMPtr<nsIDocShellTreeItem> treeItem = GetDocShellTreeItemFor(mDOMNode);
   ShutdownChildDocuments(treeItem);
 
-  if (mEditor) {
-    mEditor->RemoveEditActionListener(this);
-    mEditor = nsnull;
-  }
+  mEditor = nsnull;
 
   if (mDocLoadTimer) {
     mDocLoadTimer->Cancel();
     mDocLoadTimer = nsnull;
   }
 
   RemoveEventListeners();
 
@@ -1118,24 +1116,35 @@ nsDocAccessible::ARIAAttributeChanged(ns
     }
   }
 }
 
 void nsDocAccessible::ContentAppended(nsIDocument *aDocument,
                                       nsIContent* aContainer,
                                       PRInt32 aNewIndexInContainer)
 {
-  // InvalidateCacheSubtree will not fire the EVENT_SHOW for the new node
-  // unless an accessible can be created for the passed in node, which it
-  // can't do unless the node is visible. The right thing happens there so
-  // no need for an extra visibility check here.
+  if (!mIsContentLoaded || !mDocument) {
+    if (mAccessNodeCache.Count() <= 1) {
+      // See comments in nsDocAccessible::InvalidateCacheSubtree
+      InvalidateChildren();
+    }
+    return;
+  }
+
   PRUint32 childCount = aContainer->GetChildCount();
   for (PRUint32 index = aNewIndexInContainer; index < childCount; index ++) {
-    InvalidateCacheSubtree(aContainer->GetChildAt(index),
-                           nsIAccessibleEvent::EVENT_SHOW);
+    nsCOMPtr<nsIContent> child(aContainer->GetChildAt(index));
+
+    FireTextChangedEventOnDOMNodeInserted(child, aContainer, index);
+
+    // InvalidateCacheSubtree will not fire the EVENT_SHOW for the new node
+    // unless an accessible can be created for the passed in node, which it
+    // can't do unless the node is visible. The right thing happens there so
+    // no need for an extra visibility check here.
+    InvalidateCacheSubtree(child, nsIAccessibleEvent::EVENT_SHOW);
   }
 }
 
 void nsDocAccessible::ContentStatesChanged(nsIDocument* aDocument,
                                            nsIContent* aContent1,
                                            nsIContent* aContent2,
                                            PRInt32 aStateMask)
 {
@@ -1146,42 +1155,211 @@ void nsDocAccessible::ContentStatesChang
   nsHTMLSelectOptionAccessible::SelectionChangedIfOption(aContent1);
   nsHTMLSelectOptionAccessible::SelectionChangedIfOption(aContent2);
 }
 
 void nsDocAccessible::CharacterDataChanged(nsIDocument *aDocument,
                                            nsIContent* aContent,
                                            CharacterDataChangeInfo* aInfo)
 {
-  // XXX fire text change events here? See bug 377891
+  FireTextChangedEventOnDOMCharacterDataModified(aContent, aInfo);
 }
 
 void
 nsDocAccessible::ContentInserted(nsIDocument *aDocument, nsIContent* aContainer,
                                  nsIContent* aChild, PRInt32 aIndexInContainer)
 {
+  FireTextChangedEventOnDOMNodeInserted(aChild, aContainer, aIndexInContainer);
+
   // InvalidateCacheSubtree will not fire the EVENT_SHOW for the new node
   // unless an accessible can be created for the passed in node, which it
   // can't do unless the node is visible. The right thing happens there so
   // no need for an extra visibility check here.
   InvalidateCacheSubtree(aChild, nsIAccessibleEvent::EVENT_SHOW);
 }
 
 void
 nsDocAccessible::ContentRemoved(nsIDocument *aDocument, nsIContent* aContainer,
                                 nsIContent* aChild, PRInt32 aIndexInContainer)
 {
+  FireTextChangedEventOnDOMNodeRemoved(aChild, aContainer, aIndexInContainer);
+
+  // Invalidate the subtree of the removed element.
   InvalidateCacheSubtree(aChild, nsIAccessibleEvent::EVENT_HIDE);
 }
 
 void
 nsDocAccessible::ParentChainChanged(nsIContent *aContent)
 {
 }
 
+void
+nsDocAccessible::FireTextChangedEventOnDOMCharacterDataModified(nsIContent *aContent,
+                                                                CharacterDataChangeInfo* aInfo)
+{
+  if (!mIsContentLoaded || !mDocument) {
+    return;
+  }
+
+  nsCOMPtr<nsIDOMNode> node(do_QueryInterface(aContent));
+  if (!node)
+    return;
+
+  nsCOMPtr<nsIAccessible> accessible;
+  nsresult rv = GetAccessibleInParentChain(node, getter_AddRefs(accessible));
+  if (NS_FAILED(rv) || !accessible)
+    return;
+
+  nsRefPtr<nsHyperTextAccessible> textAccessible;
+  rv = accessible->QueryInterface(NS_GET_IID(nsHyperTextAccessible),
+                                  getter_AddRefs(textAccessible));
+  if (NS_FAILED(rv) || !textAccessible)
+    return;
+
+  PRInt32 start = aInfo->mChangeStart;
+  PRUint32 end = aInfo->mChangeEnd;
+  PRInt32 length = end - start;
+  PRUint32 replaceLen = aInfo->mReplaceLength;
+
+  PRInt32 offset = 0;
+  rv = textAccessible->DOMPointToHypertextOffset(node, start, &offset);
+  if (NS_FAILED(rv))
+    return;
+
+  // Text has been removed.
+  if (length > 0) {
+    nsCOMPtr<nsIAccessibleTextChangeEvent> event =
+      new nsAccTextChangeEvent(accessible, offset, length, PR_FALSE);
+    textAccessible->FireAccessibleEvent(event);
+  }
+
+  // Text has been added.
+  if (replaceLen) {
+    nsCOMPtr<nsIAccessibleTextChangeEvent> event =
+      new nsAccTextChangeEvent(accessible, offset, replaceLen, PR_TRUE);
+    textAccessible->FireAccessibleEvent(event);
+  }
+}
+
+void
+nsDocAccessible::FireTextChangedEventOnDOMNodeInserted(nsIContent *aChild,
+                                                       nsIContent *aContainer,
+                                                       PRInt32 aIndexInContainer)
+{
+  if (!mIsContentLoaded || !mDocument) {
+    return;
+  }
+
+  nsCOMPtr<nsIDOMNode> node(do_QueryInterface(aChild));
+  if (!node)
+    return;
+
+  nsCOMPtr<nsIAccessible> accessible;
+  nsresult rv = GetAccessibleInParentChain(node, getter_AddRefs(accessible));
+  if (NS_FAILED(rv) || !accessible)
+    return;
+
+  nsRefPtr<nsHyperTextAccessible> textAccessible;
+  rv = accessible->QueryInterface(NS_GET_IID(nsHyperTextAccessible),
+                                  getter_AddRefs(textAccessible));
+  if (NS_FAILED(rv) || !textAccessible)
+    return;
+
+  PRUint32 length = 1;
+  if (aChild && aChild->IsNodeOfType(nsINode::eTEXT)) {
+    length = aChild->TextLength();
+    if (!length)
+      return;
+  } else {
+    // Don't fire event for the first html:br in an editor.
+    nsCOMPtr<nsIEditor> editor;
+    textAccessible->GetAssociatedEditor(getter_AddRefs(editor));
+    if (editor) {
+      PRBool isEmpty = PR_FALSE;
+      editor->GetDocumentIsEmpty(&isEmpty);
+      if (isEmpty)
+        return;
+    }
+  }
+
+  nsCOMPtr<nsIDOMNode> parentNode(do_QueryInterface(aContainer));
+  if (!parentNode)
+    return;
+
+  PRInt32 offset = 0;
+  rv = textAccessible->DOMPointToHypertextOffset(parentNode, aIndexInContainer, &offset);
+  if (NS_FAILED(rv))
+    return;
+
+  nsCOMPtr<nsIAccessibleTextChangeEvent> event =
+    new nsAccTextChangeEvent(accessible, offset, length, PR_TRUE);
+  if (!event)
+    return;
+
+  textAccessible->FireAccessibleEvent(event);
+}
+
+void
+nsDocAccessible::FireTextChangedEventOnDOMNodeRemoved(nsIContent *aChild,
+                                                      nsIContent *aContainer,
+                                                      PRInt32 aIndexInContainer)
+{
+  if (!mIsContentLoaded || !mDocument) {
+    return;
+  }
+
+  nsCOMPtr<nsIDOMNode> node(do_QueryInterface(aChild));
+  if (!node)
+    return;
+
+  nsCOMPtr<nsIAccessible> accessible;
+  nsresult rv = GetAccessibleInParentChain(node, getter_AddRefs(accessible));
+  if (NS_FAILED(rv) || !accessible)
+    return;
+
+  nsRefPtr<nsHyperTextAccessible> textAccessible;
+  rv = accessible->QueryInterface(NS_GET_IID(nsHyperTextAccessible),
+                                  getter_AddRefs(textAccessible));
+  if (NS_FAILED(rv) || !textAccessible)
+    return;
+
+  PRUint32 length = 1;
+  if (aChild && aChild->IsNodeOfType(nsINode::eTEXT)) {
+    length = aChild->TextLength();
+    if (!length)
+      return;
+  } else {
+    // Don't fire event for the last html:br in an editor.
+    nsCOMPtr<nsIEditor> editor;
+    textAccessible->GetAssociatedEditor(getter_AddRefs(editor));
+    if (editor) {
+      PRBool isEmpty = PR_FALSE;
+      editor->GetDocumentIsEmpty(&isEmpty);
+      if (isEmpty)
+        return;
+    }
+  }
+
+  nsCOMPtr<nsIDOMNode> parentNode(do_QueryInterface(aContainer));
+  if (!parentNode)
+    return;
+
+  PRInt32 offset = 0;
+  rv = textAccessible->DOMPointToHypertextOffset(parentNode, aIndexInContainer, &offset);
+  if (NS_FAILED(rv))
+    return;
+
+  nsCOMPtr<nsIAccessibleTextChangeEvent> event =
+    new nsAccTextChangeEvent(accessible, offset, length, PR_FALSE);
+  if (!event)
+    return;
+
+  textAccessible->FireAccessibleEvent(event);
+}
+
 nsresult nsDocAccessible::FireDelayedToolkitEvent(PRUint32 aEvent,
                                                   nsIDOMNode *aDOMNode,
                                                   void *aData,
                                                   PRBool aAllowDupes)
 {
   nsCOMPtr<nsIAccessibleEvent> event = new nsAccEvent(aEvent, aDOMNode, aData);
   NS_ENSURE_TRUE(event, NS_ERROR_OUT_OF_MEMORY);
 
--- a/accessible/src/base/nsDocAccessible.h
+++ b/accessible/src/base/nsDocAccessible.h
@@ -130,16 +130,37 @@ class nsDocAccessible : public nsHyperTe
     /**
      * Fires accessible events when ARIA attribute is chaned.
      *
      * @param aContent - node that attribute is changed for
      * @param aAttribute - changed attribute
      */
     void ARIAAttributeChanged(nsIContent* aContent, nsIAtom* aAttribute);
 
+    /**
+     * Fire text changed event for charackter data changed.
+     */
+    void FireTextChangedEventOnDOMCharacterDataModified(nsIContent *aContent,
+                                                        CharacterDataChangeInfo* aInfo);
+    /**
+     * Fire text changed event for the inserted element if it is inside a text
+     * accessible.
+     */
+    void FireTextChangedEventOnDOMNodeInserted(nsIContent *aChild,
+                                               nsIContent *aContainer,
+                                               PRInt32 aIndexInContainer);
+
+    /**
+     * Fire text changed event for the removed element if it is inside a text
+     * accessible.
+     */
+    void FireTextChangedEventOnDOMNodeRemoved(nsIContent *aChild,
+                                              nsIContent *aContainer,
+                                              PRInt32 aIndexInContainer);
+
     nsAccessNodeHashtable mAccessNodeCache;
     void *mWnd;
     nsCOMPtr<nsIDocument> mDocument;
     nsCOMPtr<nsITimer> mScrollWatchTimer;
     nsCOMPtr<nsITimer> mFireEventTimer;
     PRUint16 mScrollPositionChangedTicks; // Used for tracking scroll events
     PRPackedBool mIsContentLoaded;
     nsCOMArray<nsIAccessibleEvent> mEventsToFire;
--- a/accessible/src/base/nsRootAccessible.cpp
+++ b/accessible/src/base/nsRootAccessible.cpp
@@ -801,23 +801,22 @@ nsresult nsRootAccessible::HandleEventWi
   else if (eventType.EqualsLiteral("DOMMenuItemActive")) {
     if (!treeItemAccessible) {
       nsCOMPtr<nsPIAccessNode> menuAccessNode = do_QueryInterface(accessible);
       NS_ENSURE_TRUE(menuAccessNode, NS_ERROR_FAILURE);
       nsIFrame* menuFrame = menuAccessNode->GetFrame();
       NS_ENSURE_TRUE(menuFrame, NS_ERROR_FAILURE);
       nsIMenuFrame* imenuFrame;
       CallQueryInterface(menuFrame, &imenuFrame);
-      NS_ENSURE_TRUE(imenuFrame, NS_ERROR_FAILURE);
-      if (imenuFrame->IsOnMenuBar()) {
-        if (!imenuFrame->IsOnActiveMenuBar()) {
-          // It is a top level menuitem. Only fire a focus event when the menu bar
-          // is active.
-          return NS_OK;
-        }
+      // QI failed for nsIMenuFrame means it's not on menu bar
+      if (imenuFrame && imenuFrame->IsOnMenuBar() &&
+                       !imenuFrame->IsOnActiveMenuBar()) {
+        // It is a top level menuitem. Only fire a focus event when the menu bar
+        // is active.
+        return NS_OK;
       } else {
         nsCOMPtr<nsIAccessible> containerAccessible;
         accessible->GetParent(getter_AddRefs(containerAccessible));
         NS_ENSURE_TRUE(containerAccessible, NS_ERROR_FAILURE);
         // It is not top level menuitem
         // Only fire focus event if it is not inside collapsed popup
         if (State(containerAccessible) & nsIAccessibleStates::STATE_COLLAPSED)
           return NS_OK;
--- a/accessible/src/base/nsTextAccessible.cpp
+++ b/accessible/src/base/nsTextAccessible.cpp
@@ -84,21 +84,16 @@ NS_IMETHODIMP nsTextAccessible::GetLastC
   */
 NS_IMETHODIMP nsTextAccessible::GetChildCount(PRInt32 *_retval)
 {
   *_retval = 0;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsTextAccessible::GetContentText(nsAString& aText)
+nsTextAccessible::AppendTextTo(nsAString& aText, PRUint32 aStartOffset, PRUint32 aLength)
 {
-  nsresult rv = nsLinkableAccessible::GetContentText(aText);
-  NS_ENSURE_SUCCESS(rv, rv);
-
   nsIFrame *frame = GetFrame();
-  if (!frame)
-    return NS_OK;
+  NS_ENSURE_TRUE(frame, NS_ERROR_FAILURE);
 
-  frame->GetContent()->AppendTextTo(aText);
-  return NS_OK;
+  return frame->GetRenderedText(&aText, nsnull, nsnull, aStartOffset, aLength);
 }
 
--- a/accessible/src/base/nsTextAccessible.h
+++ b/accessible/src/base/nsTextAccessible.h
@@ -55,14 +55,14 @@ public:
 
   // nsIAccessible
   NS_IMETHOD GetRole(PRUint32 *_retval); 
   NS_IMETHOD GetFirstChild(nsIAccessible **_retval);
   NS_IMETHOD GetLastChild(nsIAccessible **_retval);
   NS_IMETHOD GetChildCount(PRInt32 *_retval);
 
   // nsPIAccessible
-  NS_IMETHOD GetContentText(nsAString& aText);
+  NS_IMETHOD AppendTextTo(nsAString& aText, PRUint32 aStartOffset, PRUint32 aLength);
 };
 
 
 #endif
 
--- a/accessible/src/html/Makefile.in
+++ b/accessible/src/html/Makefile.in
@@ -49,23 +49,26 @@ LIBXUL_LIBRARY = 1
 
 REQUIRES	= content \
 		  docshell \
 		  dom \
 		  editor \
 		  gfx \
 		  imglib2 \
 		  intl \
+		  js \
 		  layout \
 		  locale \
 		  necko \
 		  string \
+		  thebes \
 		  webshell \
 		  widget \
 		  xpcom \
+		  xpconnect \
 		  $(NULL)
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),gtk2)
 REQUIRES += editor
 endif
 
 CPPSRCS = \
   nsHTMLAreaAccessible.cpp \
--- a/accessible/src/html/nsHTMLFormControlAccessible.cpp
+++ b/accessible/src/html/nsHTMLFormControlAccessible.cpp
@@ -46,16 +46,19 @@
 #include "nsIDOMNSEditableElement.h"
 #include "nsIDOMNSHTMLButtonElement.h"
 #include "nsIDOMHTMLFormElement.h"
 #include "nsIDOMHTMLLegendElement.h"
 #include "nsIDOMHTMLTextAreaElement.h"
 #include "nsIFrame.h"
 #include "nsINameSpaceManager.h"
 #include "nsISelectionController.h"
+#include "jsapi.h"
+#include "nsIJSContextStack.h"
+#include "nsIServiceManager.h"
 #include "nsITextControlFrame.h"
 
 // --- checkbox -----
 
 nsHTMLCheckboxAccessible::nsHTMLCheckboxAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell):
 nsFormControlAccessible(aNode, aShell)
 { 
 }
@@ -281,18 +284,17 @@ NS_IMETHODIMP nsHTMLButtonAccessible::Ge
       // Use HTML label or DHTML accessibility's labelledby attribute for name
       GetHTMLName(name, PR_FALSE);
     }
     if (name.IsEmpty()) {
       // Use the button's (default) label if nothing else works
       nsIFrame* frame = GetFrame();
       if (frame) {
         nsIFormControlFrame* fcFrame;
-        frame->QueryInterface(NS_GET_IID(nsIFormControlFrame),
-                              (void**) &fcFrame);
+        CallQueryInterface(frame, &fcFrame);
         if (fcFrame)
           fcFrame->GetFormProperty(nsAccessibilityAtoms::defaultLabel, name);
       }
     }
     if (name.IsEmpty() &&
         !content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::title,
                           name) &&
         !content->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::src,
@@ -376,20 +378,17 @@ NS_IMPL_ISUPPORTS_INHERITED1(nsHTMLTextF
 NS_IMETHODIMP nsHTMLTextFieldAccessible::Init()
 {
   CheckForEditor();
   return nsHyperTextAccessibleWrap::Init();
 }
 
 NS_IMETHODIMP nsHTMLTextFieldAccessible::Shutdown()
 {
-  if (mEditor) {
-    mEditor->RemoveEditActionListener(this);
-    mEditor = nsnull;
-  }
+  mEditor = nsnull;
   return nsHyperTextAccessibleWrap::Shutdown();
 }
 
 NS_IMETHODIMP nsHTMLTextFieldAccessible::GetRole(PRUint32 *aRole)
 {
   *aRole = nsIAccessibleRole::ROLE_ENTRY;
   nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
   if (content &&
@@ -541,32 +540,43 @@ NS_IMETHODIMP nsHTMLTextFieldAccessible:
     return NS_ERROR_FAILURE;
   }
   return NS_ERROR_INVALID_ARG;
 }
 
 void nsHTMLTextFieldAccessible::SetEditor(nsIEditor* aEditor)
 {
   mEditor = aEditor;
-  if (mEditor)
-    mEditor->AddEditActionListener(this);
 }
 
 void nsHTMLTextFieldAccessible::CheckForEditor()
 {
   nsCOMPtr<nsIDOMNSEditableElement> editableElt(do_QueryInterface(mDOMNode));
   if (!editableElt) {
     return;
   }
 
+  // nsGenericHTMLElement::GetEditor has a security check.
+  // Make sure we're not restricted by the permissions of
+  // whatever script is currently running.
+  nsCOMPtr<nsIJSContextStack> stack =
+    do_GetService("@mozilla.org/js/xpc/ContextStack;1");
+  PRBool pushed = stack && NS_SUCCEEDED(stack->Push(nsnull));
+
   nsCOMPtr<nsIEditor> editor;
   nsresult rv = editableElt->GetEditor(getter_AddRefs(editor));
   if (NS_SUCCEEDED(rv)) {
     SetEditor(editor);
   }
+
+  if (pushed) {
+    JSContext* cx;
+    stack->Pop(&cx);
+    NS_ASSERTION(!cx, "context should be null");
+  }
 }
 
 // --- groupbox  -----
 
 /*
  * The HTML for this is <fieldset> <legend>box-title</legend> form elements </fieldset> 
  */
 
--- a/accessible/src/html/nsHTMLImageAccessible.cpp
+++ b/accessible/src/html/nsHTMLImageAccessible.cpp
@@ -139,17 +139,20 @@ NS_IMETHODIMP nsHTMLImageAccessible::Get
   }
 
   return NS_OK;
 }
 
 /* wstring getRole (); */
 NS_IMETHODIMP nsHTMLImageAccessible::GetRole(PRUint32 *_retval)
 {
-  *_retval = nsIAccessibleRole::ROLE_GRAPHIC;
+  PRInt32 numChildren;
+  GetChildCount(&numChildren);
+  *_retval = (numChildren > 0) ? nsIAccessibleRole::ROLE_IMAGE_MAP :
+                                 nsIAccessibleRole::ROLE_GRAPHIC;
   return NS_OK;
 }
 
 
 already_AddRefed<nsIAccessible>
 nsHTMLImageAccessible::GetAreaAccessible(PRInt32 aAreaNum)
 {
   if (!mMapElement)
--- a/accessible/src/html/nsHTMLTextAccessible.cpp
+++ b/accessible/src/html/nsHTMLTextAccessible.cpp
@@ -51,34 +51,17 @@
 nsHTMLTextAccessible::nsHTMLTextAccessible(nsIDOMNode* aDomNode, nsIWeakReference* aShell):
 nsTextAccessibleWrap(aDomNode, aShell)
 { 
 }
 
 NS_IMETHODIMP nsHTMLTextAccessible::GetName(nsAString& aName)
 {
   aName.Truncate();
-  if (!mDOMNode) {
-    return NS_ERROR_FAILURE;
-  }
-
-  nsIFrame *frame = GetFrame();
-  NS_ENSURE_TRUE(frame, NS_ERROR_FAILURE);
-
-  nsAutoString name;
-  nsresult rv = mDOMNode->GetNodeValue(name);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  if (!frame->GetStyleText()->WhiteSpaceIsSignificant()) {
-    // Replace \r\n\t in markup with space unless in this is preformatted text
-    // where those characters are significant
-    name.ReplaceChar("\r\n\t", ' ');
-  }
-  aName = name;
-  return rv;
+  return AppendTextTo(aName, 0, PR_UINT32_MAX);
 }
 
 NS_IMETHODIMP nsHTMLTextAccessible::GetRole(PRUint32 *aRole)
 {
   nsIFrame *frame = GetFrame();
   NS_ENSURE_TRUE(frame, NS_ERROR_NULL_POINTER);
 
   if (frame->IsGeneratedContentFrame()) {
@@ -362,19 +345,24 @@ nsHTMLListBulletAccessible::SetParent(ns
 NS_IMETHODIMP
 nsHTMLListBulletAccessible::GetParent(nsIAccessible **aParentAccessible)
 {
   NS_IF_ADDREF(*aParentAccessible = mWeakParent);
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsHTMLListBulletAccessible::GetContentText(nsAString& aText)
+nsHTMLListBulletAccessible::AppendTextTo(nsAString& aText, PRUint32 aStartOffset,
+                                         PRUint32 aLength)
 {
-  aText = mBulletText;
+  PRUint32 maxLength = mBulletText.Length() - aStartOffset;
+  if (aLength > maxLength) {
+    aLength = maxLength;
+  }
+  aText += nsDependentSubstring(mBulletText, aStartOffset, aLength);
   return NS_OK;
 }
 
 // nsHTMLListAccessible
 
 NS_IMETHODIMP
 nsHTMLListAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
--- a/accessible/src/html/nsHTMLTextAccessible.h
+++ b/accessible/src/html/nsHTMLTextAccessible.h
@@ -106,17 +106,17 @@ public:
 
   // Don't cache via unique ID -- bullet accessible shares the same dom node as
   // this LI accessible. Also, don't cache via mParent/SetParent(), prevent
   // circular reference since li holds onto us.
   NS_IMETHOD SetParent(nsIAccessible *aParentAccessible);
   NS_IMETHOD GetParent(nsIAccessible **aParentAccessible);
 
   // nsPIAccessible
-  NS_IMETHOD GetContentText(nsAString& aText);
+  NS_IMETHOD AppendTextTo(nsAString& aText, PRUint32 aStartOffset, PRUint32 aLength);
 
 protected:
   // XXX: Ideally we'd get the bullet text directly from the bullet frame via
   // nsBulletFrame::GetListItemText(), but we'd need an interface for getting
   // text from contentless anonymous frames. Perhaps something like
   // nsIAnonymousFrame::GetText() ? However, in practice storing the bullet text
   // here should not be a problem if we invalidate the right parts of
   // the accessibility cache when mutation events occur.
--- a/accessible/src/html/nsHyperTextAccessible.cpp
+++ b/accessible/src/html/nsHyperTextAccessible.cpp
@@ -51,30 +51,37 @@
 #include "nsIDOMRange.h"
 #include "nsIDOMWindowInternal.h"
 #include "nsIDOMXULDocument.h"
 #include "nsIFontMetrics.h"
 #include "nsIFrame.h"
 #include "nsIPlaintextEditor.h"
 #include "nsIServiceManager.h"
 #include "nsTextFragment.h"
+#include "gfxSkipChars.h"
 
 static NS_DEFINE_IID(kRangeCID, NS_RANGE_CID);
 
 // ------------
 // nsHyperTextAccessible
 // ------------
 
 NS_IMPL_ADDREF_INHERITED(nsHyperTextAccessible, nsAccessible)
 NS_IMPL_RELEASE_INHERITED(nsHyperTextAccessible, nsAccessible)
 
 nsresult nsHyperTextAccessible::QueryInterface(REFNSIID aIID, void** aInstancePtr)
 {
   *aInstancePtr = nsnull;
 
+  if (aIID.Equals(NS_GET_IID(nsHyperTextAccessible))) {
+    *aInstancePtr = static_cast<nsHyperTextAccessible*>(this);
+    NS_ADDREF_THIS();
+    return NS_OK;
+  }
+
   nsCOMPtr<nsIDOMXULDocument> xulDoc(do_QueryInterface(mDOMNode));
   if (mDOMNode && !xulDoc) {
     // We need XUL doc check for now because for now nsDocAccessible must inherit from nsHyperTextAccessible
     // in order for HTML document accessibles to get support for these interfaces
     // However at some point we may push <body> to implement the interfaces and
     // return nsDocAccessible to inherit from nsAccessibleWrap
     if (aIID.Equals(NS_GET_IID(nsIAccessibleText))) {
       // If |this| contains any children
@@ -227,23 +234,34 @@ void nsHyperTextAccessible::CacheChildre
       walker.GetNextSibling();
       privatePrevAccessible->SetNextSibling(walker.mState.accessible);
     }
     mAccChildCount = childCount;
   }
 }
 
 // Substring must be entirely within the same text node
-nsIntRect nsHyperTextAccessible::GetBoundsForString(nsIFrame *aFrame, PRInt32 aStartOffset, PRInt32 aLength)
+nsIntRect nsHyperTextAccessible::GetBoundsForString(nsIFrame *aFrame, PRInt32 aStartContentOffset,
+                                                    PRInt32 aEndContentOffset)
 {
   nsIntRect screenRect;
+  NS_ENSURE_TRUE(aFrame, screenRect);
+
+  PRUint32 startRenderedOFfset, endRenderedOFfset;
+  nsresult rv = ContentToRenderedOffset(aFrame, aStartContentOffset, &startRenderedOFfset);
+  NS_ENSURE_SUCCESS(rv, screenRect);
+  rv = ContentToRenderedOffset(aFrame, aEndContentOffset, &endRenderedOFfset);
+  NS_ENSURE_SUCCESS(rv, screenRect);
+
   nsIFrame *frame;
-  PRInt32 startOffsetInFrame;
-  nsresult rv = aFrame->GetChildFrameContainingOffset(aStartOffset, PR_FALSE,
-                                                      &startOffsetInFrame, &frame);
+  PRInt32 startRenderedOFfsetInFrame;
+  // Get the right frame continuation -- not really a child, but a sibling of
+  // the primary frame passed in
+  rv = aFrame->GetChildFrameContainingOffset(startRenderedOFfset, PR_FALSE,
+                                             &startRenderedOFfsetInFrame, &frame);
   NS_ENSURE_SUCCESS(rv, screenRect);
 
   nsCOMPtr<nsIPresShell> shell = GetPresShell();
   NS_ENSURE_TRUE(shell, screenRect);
 
   nsCOMPtr<nsIRenderingContext> rc;
   shell->CreateRenderingContext(frame, getter_AddRefs(rc));
   NS_ENSURE_TRUE(rc, screenRect);
@@ -251,47 +269,47 @@ nsIntRect nsHyperTextAccessible::GetBoun
   const nsStyleFont *font = frame->GetStyleFont();
   const nsStyleVisibility *visibility = frame->GetStyleVisibility();
 
   rv = rc->SetFont(font->mFont, visibility->mLangGroup);
   NS_ENSURE_SUCCESS(rv, screenRect);
 
   nsPresContext *context = shell->GetPresContext();
 
-  while (frame && aLength > 0) {
+  while (frame && startRenderedOFfset < endRenderedOFfset) {
     // Start with this frame's screen rect, which we will 
     // shrink based on the substring we care about within it.
     // We will then add that frame to the total screenRect we
     // are returning.
     nsIntRect frameScreenRect = frame->GetScreenRectExternal();
 
     // Get the length of the substring in this frame that we want the bounds for
     PRInt32 startFrameTextOffset, endFrameTextOffset;
     frame->GetOffsets(startFrameTextOffset, endFrameTextOffset);
     PRInt32 frameTotalTextLength = endFrameTextOffset - startFrameTextOffset;
-    PRInt32 frameSubStringLength = PR_MIN(frameTotalTextLength - startOffsetInFrame, aLength);
+    PRInt32 seekLength = endRenderedOFfset - startRenderedOFfset;
+    PRInt32 frameSubStringLength = PR_MIN(frameTotalTextLength - startRenderedOFfsetInFrame, seekLength);
 
     // Add the point where the string starts to the frameScreenRect
     nsPoint frameTextStartPoint;
-    rv = frame->GetPointFromOffset(context, rc, aStartOffset, &frameTextStartPoint);
+    rv = frame->GetPointFromOffset(context, rc, startRenderedOFfset, &frameTextStartPoint);
     NS_ENSURE_SUCCESS(rv, nsRect());   
     frameScreenRect.x += context->AppUnitsToDevPixels(frameTextStartPoint.x);
 
     // Use the point for the end offset to calculate the width
     nsPoint frameTextEndPoint;
-    rv = frame->GetPointFromOffset(context, rc, aStartOffset + frameSubStringLength, &frameTextEndPoint);
+    rv = frame->GetPointFromOffset(context, rc, startRenderedOFfset + frameSubStringLength, &frameTextEndPoint);
     NS_ENSURE_SUCCESS(rv, nsRect());   
     frameScreenRect.width = context->AppUnitsToDevPixels(frameTextEndPoint.x - frameTextStartPoint.x);
 
     screenRect.UnionRect(frameScreenRect, screenRect);
 
     // Get ready to loop back for next frame continuation
-    aStartOffset += frameSubStringLength;
-    startOffsetInFrame = 0;
-    aLength -= frameSubStringLength;
+    startRenderedOFfset += frameSubStringLength;
+    startRenderedOFfsetInFrame = 0;
     frame = frame->GetNextContinuation();
   }
 
   return screenRect;
 }
 
 /*
  * Gets the specified text.
@@ -320,75 +338,80 @@ nsIFrame* nsHyperTextAccessible::GetPosA
   }
   if (aBoundsRect) {
     aBoundsRect->Empty();
   }
 
   nsIntRect unionRect;
   nsCOMPtr<nsIAccessible> accessible;
 
+  gfxSkipChars skipChars;
+  gfxSkipCharsIterator iter;
+
   // Loop through children and collect valid offsets, text and bounds
   // depending on what we need for out parameters
   while (NextChild(accessible)) {
     nsCOMPtr<nsPIAccessNode> accessNode(do_QueryInterface(accessible));
     nsIFrame *frame = accessNode->GetFrame();
     if (!frame) {
       continue;
     }
     if (IsText(accessible)) {
-      nsCOMPtr<nsPIAccessible> pAcc(do_QueryInterface(accessible));
-      nsAutoString newText;
-      pAcc->GetContentText(newText);
-
-      PRInt32 substringEndOffset = newText.Length();
+      // We only need info up to rendered offset -- that is what we're converting to content offset
+      PRInt32 substringEndOffset;
+      nsresult rv = frame->GetRenderedText(nsnull, &skipChars, &iter);
+      PRUint32 ourRenderedStart = iter.GetSkippedOffset();
+      PRInt32 ourContentStart = iter.GetOriginalOffset();
+      if (NS_SUCCEEDED(rv)) {
+        substringEndOffset = iter.ConvertOriginalToSkipped(skipChars.GetOriginalCharCount() + ourContentStart) -
+                    ourRenderedStart;
+      }
+      else {
+        // XXX for non-textframe text like list bullets, should go away after list bullet rewrite
+        substringEndOffset = TextLength(accessible);
+      }
       if (startOffset < substringEndOffset) {
         // Our start is within this substring
-        // XXX Can we somehow optimize further by getting the nsTextFragment
-        // and use CopyTo to a PRUnichar buffer to copy it directly to
-        // the string?
-
         if (startOffset > 0 || endOffset < substringEndOffset) {
-          // XXX the Substring operation is efficient, but does the 
-          // reassignment to the original nsAutoString cause a copy?
+          // We don't want the whole string for this accessible
+          // Get out the continuing text frame with this offset
           PRInt32 outStartLineUnused;
-          frame->GetChildFrameContainingOffset(startOffset, PR_TRUE, &outStartLineUnused, &frame);
-          if (endOffset < substringEndOffset) {
-            // Don't take entire substring: stop before the end
-            substringEndOffset = endOffset;
-          }
-          if (aText) {
-            newText = Substring(newText, startOffset,
-                                substringEndOffset - startOffset);
-          }
+          PRInt32 contentOffset = iter.ConvertSkippedToOriginal(startOffset) + ourRenderedStart - ourContentStart;
+          frame->GetChildFrameContainingOffset(contentOffset, PR_TRUE, &outStartLineUnused, &frame);
           if (aEndFrame) {
             *aEndFrame = frame; // We ended in the current frame
           }
+          if (substringEndOffset > endOffset) {
+            // Need to stop before the end of the available text
+            substringEndOffset = endOffset;
+          }
           aEndOffset = endOffset;
         }
         if (aText) {
-          if (!frame->GetStyleText()->WhiteSpaceIsSignificant()) {
-            // Replace \r\n\t in markup with space unless in this is
-            // preformatted text  where those characters are significant
-            newText.ReplaceChar("\r\n\t", ' ');
-          }
-          *aText += newText;
+          nsCOMPtr<nsPIAccessible> pAcc(do_QueryInterface(accessible));
+          pAcc->AppendTextTo(*aText, startOffset, substringEndOffset - startOffset);
         }
-        if (aBoundsRect) {
+        if (aBoundsRect) {    // Caller wants the bounds of the text
           aBoundsRect->UnionRect(*aBoundsRect, GetBoundsForString(frame, startOffset,
-                                                                  substringEndOffset - startOffset));
+                                 substringEndOffset));
         }
         if (!startFrame) {
           startFrame = frame;
           aStartOffset = startOffset;
         }
+        // We already started copying in this accessible's string,
+        // for the next accessible we'll start at offset 0
         startOffset = 0;
       }
       else {
+        // We have not found the start position yet, get the new startOffset
+        // that is relative to next accessible
         startOffset -= substringEndOffset;
       }
+      // The endOffset needs to be relative to the new startOffset
       endOffset -= substringEndOffset;
     }
     else {
       // Embedded object, append marker
       // XXX Append \n for <br>'s
       if (startOffset >= 1) {
         -- startOffset;
       }
@@ -437,74 +460,88 @@ NS_IMETHODIMP nsHyperTextAccessible::Get
   *aCharacterCount = 0;
   if (!mDOMNode) {
     return NS_ERROR_FAILURE;
   }
 
   nsCOMPtr<nsIAccessible> accessible;
 
   while (NextChild(accessible)) {
-    *aCharacterCount += TextLength(accessible);
+    PRInt32 textLength = TextLength(accessible);
+    NS_ENSURE_TRUE(textLength >= 0, nsnull);
+    *aCharacterCount += textLength;
   }
   return NS_OK;
 }
 
 /*
  * Gets the specified character.
  */
 NS_IMETHODIMP nsHyperTextAccessible::GetCharacterAtOffset(PRInt32 aOffset, PRUnichar *aCharacter)
 {
   if (!mDOMNode) {
     return NS_ERROR_FAILURE;
   }
   nsAutoString text;
   nsresult rv = GetText(aOffset, aOffset + 1, text);
   NS_ENSURE_SUCCESS(rv, rv);
+  if (text.IsEmpty()) {
+    return NS_ERROR_FAILURE;
+  }
   *aCharacter = text.First();
   return NS_OK;
 }
 
-nsresult nsHyperTextAccessible::DOMPointToOffset(nsIDOMNode* aNode, PRInt32 aNodeOffset, PRInt32* aResult,
-                                                 nsIAccessible **aFinalAccessible)
+nsresult nsHyperTextAccessible::DOMPointToHypertextOffset(nsIDOMNode* aNode, PRInt32 aNodeOffset,
+                                                          PRInt32* aHyperTextOffset,
+                                                          nsIAccessible **aFinalAccessible)
 {
   // Turn a DOM Node and offset into an offset into this hypertext.
   // On failure, return null. On success, return the DOM node which contains the offset.
-  NS_ENSURE_ARG_POINTER(aResult);
-  *aResult = 0;
+  NS_ENSURE_ARG_POINTER(aHyperTextOffset);
+  *aHyperTextOffset = 0;
   NS_ENSURE_ARG_POINTER(aNode);
   NS_ENSURE_TRUE(aNodeOffset >= 0, NS_ERROR_INVALID_ARG);
   if (aFinalAccessible) {
     *aFinalAccessible = nsnull;
   }
 
-  PRInt32 addTextOffset = 0;
+  PRUint32 addTextOffset = 0;
   nsCOMPtr<nsIDOMNode> findNode;
 
   unsigned short nodeType;
   aNode->GetNodeType(&nodeType);
   if (nodeType == nsIDOMNode::TEXT_NODE) {
     // For text nodes, aNodeOffset comes in as a character offset
     // Text offset will be added at the end, if we find the offset in this hypertext
-    addTextOffset = aNodeOffset;
+    // We want the "skipped" offset into the text (rendered text without the extra whitespace)
+    nsCOMPtr<nsIContent> content = do_QueryInterface(aNode);
+    NS_ASSERTION(content, "No nsIContent for dom node");
+    nsCOMPtr<nsIPresShell> presShell = GetPresShell();
+    NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
+    nsIFrame *frame = presShell->GetPrimaryFrameFor(content);
+    NS_ENSURE_TRUE(frame, NS_ERROR_FAILURE);
+    nsresult rv = ContentToRenderedOffset(frame, aNodeOffset, &addTextOffset);
+    NS_ENSURE_SUCCESS(rv, rv);
     // Get the child node and 
     findNode = aNode;
   }
   else {
     // For non-text nodes, aNodeOffset comes in as a child node index
     nsCOMPtr<nsIContent> parentContent(do_QueryInterface(aNode));
     // Should not happen, but better to protect against crash if doc node is somehow passed in
     NS_ENSURE_TRUE(parentContent, NS_ERROR_FAILURE);
     // findNode could be null if aNodeOffset == # of child nodes, which means one of two things:
     // 1) we're at the end of the children, keep findNode = null, so that we get the last possible offset
     // 2) there are no children, use parentContent for the node to find. In this case parentContent can't be
     //    the nsIAccessibleText, because an accesible text must have children
      
     findNode = do_QueryInterface(parentContent->GetChildAt(aNodeOffset));
     if (!findNode && !aNodeOffset) {
-      NS_ASSERTION(!SameCOMIdentity(parentContent, mDOMNode), "Cannot find child for DOMPointToOffset search");
+      NS_ASSERTION(!SameCOMIdentity(parentContent, mDOMNode), "Cannot find child for DOMPointToHypertextOffset search");
       findNode = do_QueryInterface(parentContent); // Case #2: there are no children
     }
   }
 
   // Get accessible for this findNode, or if that node isn't accessible, use the
   // accessible for the next DOM node which has one (based on forward depth first search)
   nsCOMPtr<nsIAccessible> descendantAccessible;
   if (findNode) {
@@ -532,22 +569,24 @@ nsresult nsHyperTextAccessible::DOMPoint
   }  
 
   // Loop through, adding offsets until we reach childAccessible
   // If childAccessible is null we will end up adding up the entire length of
   // the hypertext, which is good -- it just means our offset node
   // came after the last accessible child's node
   nsCOMPtr<nsIAccessible> accessible;
   while (NextChild(accessible) && accessible != childAccessible) {
-    *aResult += TextLength(accessible);
+    PRInt32 textLength = TextLength(accessible);
+    NS_ENSURE_TRUE(textLength >= 0, nsnull);
+    *aHyperTextOffset += textLength;
   }
   if (accessible) {
-    *aResult += addTextOffset;
+    *aHyperTextOffset += addTextOffset;
     NS_ASSERTION(accessible == childAccessible, "These should be equal whenever we exit loop and accessible != nsnull");
-    if (aFinalAccessible && (NextChild(accessible) || addTextOffset < TextLength(childAccessible))) {  
+    if (aFinalAccessible && (NextChild(accessible) || static_cast<PRInt32>(addTextOffset) < TextLength(childAccessible))) {  
       // If not at end of last text node, we will return the accessible we were in
       NS_ADDREF(*aFinalAccessible = childAccessible);
     }
   }
   return NS_OK;
 }
 
 PRInt32 nsHyperTextAccessible::GetRelativeOffset(nsIPresShell *aPresShell, nsIFrame *aFromFrame, PRInt32 aFromOffset,
@@ -560,43 +599,48 @@ PRInt32 nsHyperTextAccessible::GetRelati
 
   EWordMovementType wordMovementType = aNeedsStart ? eStartWord : eEndWord;
   if (aAmount == eSelectLine) {
     aAmount = (aDirection == eDirNext) ? eSelectEndLine : eSelectBeginLine;
   }
 
   // Ask layout for the new node and offset, after moving the appropriate amount
   nsPeekOffsetStruct pos;
-  pos.SetData(aAmount, aDirection, aFromOffset, 0, kIsJumpLinesOk,
-              kIsScrollViewAStop, kIsKeyboardSelect, kIsVisualBidi,
+
+  PRInt32 contentOffset;
+  nsresult rv = RenderedToContentOffset(aFromFrame, aFromOffset, &contentOffset);
+  NS_ENSURE_SUCCESS(rv, -1);
+
+  pos.SetData(aAmount, aDirection, contentOffset,
+              0, kIsJumpLinesOk, kIsScrollViewAStop, kIsKeyboardSelect, kIsVisualBidi,
               wordMovementType);
-  nsresult rv = aFromFrame->PeekOffset(&pos);
+  rv = aFromFrame->PeekOffset(&pos);
   if (NS_FAILED(rv)) {
     if (aDirection == eDirPrevious) {
       // Use passed-in frame as starting point in failure case for now,
       // this is a hack to deal with starting on a list bullet frame,
       // which fails in PeekOffset() because the line iterator doesn't see it.
       // XXX Need to look at our overall handling of list bullets, which are an odd case
       pos.mResultContent = aFromFrame->GetContent();
       PRInt32 endOffsetUnused;
       aFromFrame->GetOffsets(pos.mContentOffset, endOffsetUnused);
     }
     else {
-      return rv;
+      return -1;
     }
   }
 
   // Turn the resulting node and offset into a hyperTextOffset
   PRInt32 hyperTextOffset;
   nsCOMPtr<nsIDOMNode> resultNode = do_QueryInterface(pos.mResultContent);
   NS_ENSURE_TRUE(resultNode, -1);
 
   nsCOMPtr<nsIAccessible> finalAccessible;
-  rv = DOMPointToOffset(resultNode, pos.mContentOffset, &hyperTextOffset, getter_AddRefs(finalAccessible));
-  // If finalAccessible == nsnull, then DOMPointToOffset() searched through the hypertext
+  rv = DOMPointToHypertextOffset(resultNode, pos.mContentOffset, &hyperTextOffset, getter_AddRefs(finalAccessible));
+  // If finalAccessible == nsnull, then DOMPointToHypertextOffset() searched through the hypertext
   // children without finding the node/offset position
   NS_ENSURE_SUCCESS(rv, -1);
 
   if (!finalAccessible && aDirection == eDirPrevious) {
     // If we reached the end during search, this means we didn't find the DOM point
     // and we're actually at the start of the paragraph
     hyperTextOffset = 0;
   }  
@@ -702,17 +746,21 @@ nsresult nsHyperTextAccessible::GetTextH
     {
       // XXX We should merge identically formatted frames
       // XXX deal with static text case
       // XXX deal with boundary type
       nsIContent *textContent = startFrame->GetContent();
       // If not text, then it's represented by an embedded object char 
       // (length of 1)
       // XXX did this mean to check for eTEXT?
+      // XXX This is completely wrong, needs to be reimplemented
       PRInt32 textLength = textContent ? textContent->TextLength() : 1;
+      if (textLength < 0) {
+        return NS_ERROR_FAILURE;
+      }
       *aStartOffset = aOffset - startOffset;
       *aEndOffset = *aStartOffset + textLength;
       startOffset = *aStartOffset;
       endOffset = *aEndOffset;
       return GetText(startOffset, endOffset, aText);
     }
   default:  // Note, sentence support is deprecated and falls through to here
     return NS_ERROR_INVALID_ARG;
@@ -801,16 +849,17 @@ NS_IMETHODIMP nsHyperTextAccessible::Get
   if (!mDOMNode) {
     return NS_ERROR_FAILURE;
   }
 
   nsCOMPtr<nsIAccessible> accessible;
   
   while (NextChild(accessible)) {
     PRInt32 length = TextLength(accessible);
+    NS_ENSURE_TRUE(length >= 0, NS_ERROR_FAILURE);
     if (*aRangeStartOffset + length > aOffset) {
       *aRangeEndOffset = *aRangeStartOffset + length;
       NS_ADDREF(*aAccessibleWithAttrs = accessible);
       return NS_OK;
     }
     *aRangeStartOffset += length;
   }
 
@@ -982,24 +1031,29 @@ nsHyperTextAccessible::GetOffsetAtPoint(
       nsSize frameSize = frame->GetSize();
       if (pointInFrame.x < frameSize.width && pointInFrame.y < frameSize.height) {
         // Finished
         if (IsText(accessible)) {
           nsIFrame::ContentOffsets contentOffsets = frame->GetContentOffsetsFromPointExternal(pointInFrame, PR_TRUE);
           if (contentOffsets.IsNull() || contentOffsets.content != content) {
             return NS_OK; // Not found, will return -1
           }
-          offset += contentOffsets.offset;
+          PRUint32 addToOffset;
+          nsresult rv = ContentToRenderedOffset(frame, contentOffsets.offset, &addToOffset);
+          NS_ENSURE_SUCCESS(rv, rv);
+          offset += addToOffset;
         }
         *aOffset = offset;
         return NS_OK;
       }
       frame = frame->GetNextContinuation();
     }
-    offset += TextLength(accessible);
+    PRInt32 textLength = TextLength(accessible);
+    NS_ENSURE_TRUE(textLength >= 0, NS_ERROR_FAILURE);
+    offset += textLength;
   }
 
   return NS_OK; // Not found, will return -1
 }
 
 // ------- nsIAccessibleHyperText ---------------
 NS_IMETHODIMP nsHyperTextAccessible::GetLinks(PRInt32 *aLinks)
 {
@@ -1048,17 +1102,19 @@ NS_IMETHODIMP nsHyperTextAccessible::Get
   }
 
   nsCOMPtr<nsIAccessible> accessible;
 
   while (NextChild(accessible) && characterCount <= aCharIndex) {
     PRUint32 role = Role(accessible);
     if (role == nsIAccessibleRole::ROLE_TEXT_LEAF ||
         role == nsIAccessibleRole::ROLE_STATICTEXT) {
-      characterCount += TextLength(accessible);
+      PRInt32 textLength = TextLength(accessible);
+      NS_ENSURE_TRUE(textLength >= 0, NS_ERROR_FAILURE);
+      characterCount += textLength;
     }
     else {
       if (characterCount ++ == aCharIndex) {
         *aLinkIndex = linkIndex;
         break;
       }
       if (role != nsIAccessibleRole::ROLE_WHITESPACE) {
         ++ linkIndex;
@@ -1141,214 +1197,16 @@ nsHyperTextAccessible::GetAssociatedEdit
 
   nsCOMPtr<nsIEditor> editor(GetEditor());
   NS_IF_ADDREF(*aEditor = editor);
 
   return NS_OK;
 }
 
 /**
-  * nsIEditActionListener impl.
-  */
-NS_IMETHODIMP nsHyperTextAccessible::WillCreateNode(const nsAString& aTag,
-                                                    nsIDOMNode *aParent, PRInt32 aPosition)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::DidCreateNode(const nsAString& aTag, nsIDOMNode *aNode,
-                                                   nsIDOMNode *aParent, PRInt32 aPosition, nsresult aResult)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::WillInsertNode(nsIDOMNode *aNode, nsIDOMNode *aParent,
-                                                    PRInt32 aPosition)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::DidInsertNode(nsIDOMNode *aNode, nsIDOMNode *aParent,
-                                                   PRInt32 aPosition, nsresult aResult)
-{
-  InvalidateChildren();
-
-  PRInt32 start;
-  PRUint32 length = 1;
-  PRBool isInserted = PR_TRUE;
-
-  nsCOMPtr<nsIContent> content(do_QueryInterface(aNode));
-  if (content && content->IsNodeOfType(nsINode::eTEXT)) {
-    length = content->TextLength();
-    if (!length)
-      return NS_OK;
-  }
-  else {
-    // Don't fire event for the first br
-    nsCOMPtr<nsIEditor> editor = GetEditor();
-    if (editor) {
-      PRBool isEmpty;
-      editor->GetDocumentIsEmpty(&isEmpty);
-      if (isEmpty) {
-        return NS_OK;
-      }
-    }
-  }
-
-  nsCOMPtr<nsIDOMNode> parentNode;
-  aNode->GetParentNode(getter_AddRefs(parentNode));
-  if (NS_FAILED(DOMPointToOffset(parentNode, aPosition, &start)))
-    return NS_OK;
-
-  nsCOMPtr<nsIAccessibleTextChangeEvent> event =
-    new nsAccTextChangeEvent(this, start, length, isInserted);
-  NS_ENSURE_TRUE(event, NS_ERROR_OUT_OF_MEMORY);
-
-  return FireAccessibleEvent(event);
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::WillDeleteNode(nsIDOMNode *aChild)
-{
-  PRInt32 start;
-  PRUint32 length = 1;
-  PRBool isInserted = PR_FALSE;
-
-  nsCOMPtr<nsIContent> content(do_QueryInterface(aChild));
-  if (content && content->IsNodeOfType(nsINode::eTEXT)) {
-    length = content->TextLength();
-    if (!length)
-      return NS_OK;
-  }
-  else {
-    // Don't fire event for the last br
-    nsCOMPtr<nsIEditor> editor = GetEditor();
-    if (editor) {
-      PRBool isEmpty;
-      editor->GetDocumentIsEmpty(&isEmpty);
-      if (isEmpty) {
-        return NS_OK;
-      }
-    }
-  }
-
-  nsCOMPtr<nsIDOMNode> parentNode;
-  aChild->GetParentNode(getter_AddRefs(parentNode));
-  nsCOMPtr<nsIContent> parentContent(do_QueryInterface(parentNode));
-  NS_ENSURE_TRUE(parentContent, NS_ERROR_FAILURE);
-  nsCOMPtr<nsIContent> childContent(do_QueryInterface(aChild));
-  NS_ENSURE_TRUE(childContent, NS_ERROR_FAILURE);
-  if (NS_FAILED(DOMPointToOffset(parentNode, parentContent->IndexOf(childContent), &start)))
-    return NS_OK;
-
-  nsCOMPtr<nsIAccessibleTextChangeEvent> event =
-    new nsAccTextChangeEvent(this, start, length, isInserted);
-  NS_ENSURE_TRUE(event, NS_ERROR_OUT_OF_MEMORY);
-
-  return FireAccessibleEvent(event);
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::DidDeleteNode(nsIDOMNode *aChild, nsresult aResult)
-{
-  return InvalidateChildren();
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::WillSplitNode(nsIDOMNode *aExistingRightNode, PRInt32 aOffset)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::DidSplitNode(nsIDOMNode *aExistingRightNode, PRInt32 aOffset,
-                                                  nsIDOMNode *aNewLeftNode, nsresult aResult)
-{
-  return InvalidateChildren();
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::WillJoinNodes(nsIDOMNode *aLeftNode,
-                                                   nsIDOMNode *aRightNode, nsIDOMNode *aParent)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::DidJoinNodes(nsIDOMNode *aLeftNode, nsIDOMNode *aRightNode,
-                                                  nsIDOMNode *aParent, nsresult aResult)
-{
-  return InvalidateChildren();
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::WillInsertText(nsIDOMCharacterData *aTextNode,
-                                                    PRInt32 aOffset, const nsAString& aString)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::DidInsertText(nsIDOMCharacterData *aTextNode, PRInt32 aOffset,
-                                                   const nsAString& aString, nsresult aResult)
-{
-  PRInt32 start;
-  PRUint32 length = aString.Length();
-  PRBool isInserted = PR_TRUE;
-
-  if (NS_FAILED(DOMPointToOffset(aTextNode, aOffset, &start)))
-    return NS_OK;
-
-  nsCOMPtr<nsIAccessibleTextChangeEvent> event =
-    new nsAccTextChangeEvent(this, start, length, isInserted);
-  NS_ENSURE_TRUE(event, NS_ERROR_OUT_OF_MEMORY);
-
-  return FireAccessibleEvent(event);
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::WillDeleteText(nsIDOMCharacterData *aTextNode,
-                                                    PRInt32 aOffset, PRInt32 aLength)
-{
-  PRInt32 start;
-  PRUint32 length = aLength;
-  PRBool isInserted = PR_FALSE;
-
-  if (NS_FAILED(DOMPointToOffset(aTextNode, aOffset, &start)))
-    return NS_OK;
-
-  nsCOMPtr<nsIAccessibleTextChangeEvent> event =
-    new nsAccTextChangeEvent(this, start, length, isInserted);
-  NS_ENSURE_TRUE(event, NS_ERROR_OUT_OF_MEMORY);
-
-  return FireAccessibleEvent(event);
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::DidDeleteText(nsIDOMCharacterData *aTextNode, PRInt32 aOffset,
-                                                   PRInt32 aLength, nsresult aResult)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::WillDeleteSelection(nsISelection *aSelection)
-// <input> & <textarea> fires this event while deleting text
-// <editor> fires WillDeleteText/WillDeleteNode instead
-// XXX Deal with > 1 selections
-{
-  PRInt32 selectionStart, selectionEnd;
-  GetSelectionBounds(0, &selectionStart, &selectionEnd);
-
-  PRInt32 start = PR_MIN(selectionStart, selectionEnd);;
-  PRUint32 length = PR_ABS(selectionEnd - selectionStart);
-  PRBool isInserted = PR_FALSE;
-
-  nsCOMPtr<nsIAccessibleTextChangeEvent> event =
-    new nsAccTextChangeEvent(this, start, length, isInserted);
-  NS_ENSURE_TRUE(event, NS_ERROR_OUT_OF_MEMORY);
-
-  return FireAccessibleEvent(event);
-}
-
-NS_IMETHODIMP nsHyperTextAccessible::DidDeleteSelection(nsISelection *aSelection)
-{
-  return NS_OK;
-}
-
-/**
   * =================== Caret & Selection ======================
   */
 
 nsresult nsHyperTextAccessible::SetSelectionRange(PRInt32 aStartPos, PRInt32 aEndPos)
 {
   // Set the selection
   nsresult rv = SetSelectionBounds(0, aStartPos, aEndPos);
   NS_ENSURE_SUCCESS(rv, rv);
@@ -1395,17 +1253,17 @@ NS_IMETHODIMP nsHyperTextAccessible::Get
 
   nsCOMPtr<nsIDOMNode> caretNode;
   rv = domSel->GetFocusNode(getter_AddRefs(caretNode));
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRInt32 caretOffset;
   domSel->GetFocusOffset(&caretOffset);
 
-  return DOMPointToOffset(caretNode, caretOffset, aCaretOffset);
+  return DOMPointToHypertextOffset(caretNode, caretOffset, aCaretOffset);
 }
 
 nsresult nsHyperTextAccessible::GetSelections(nsISelectionController **aSelCon, nsISelection **aDomSel)
 {
   if (aSelCon) {
     *aSelCon = nsnull;
   }
   if (aDomSel) {
@@ -1488,29 +1346,29 @@ NS_IMETHODIMP nsHyperTextAccessible::Get
   nsCOMPtr<nsIDOMRange> range;
   rv = domSel->GetRangeAt(aSelectionNum, getter_AddRefs(range));
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIDOMNode> startNode;
   range->GetStartContainer(getter_AddRefs(startNode));
   PRInt32 startOffset;
   range->GetStartOffset(&startOffset);
-  rv = DOMPointToOffset(startNode, startOffset, aStartOffset);
+  rv = DOMPointToHypertextOffset(startNode, startOffset, aStartOffset);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIDOMNode> endNode;
   range->GetEndContainer(getter_AddRefs(endNode));
   PRInt32 endOffset;
   range->GetEndOffset(&endOffset);
   if (startNode == endNode && startOffset == endOffset) {
     // Shortcut for collapsed selection case (caret)
     *aEndOffset = *aStartOffset;
     return NS_OK;
   }
-  return DOMPointToOffset(endNode, endOffset, aEndOffset);
+  return DOMPointToHypertextOffset(endNode, endOffset, aEndOffset);
 }
 
 /*
  * Changes the start and end offset of the specified selection.
  */
 NS_IMETHODIMP nsHyperTextAccessible::SetSelectionBounds(PRInt32 aSelectionNum, PRInt32 aStartOffset, PRInt32 aEndOffset)
 {
   nsCOMPtr<nsISelection> domSel;
@@ -1601,8 +1459,44 @@ NS_IMETHODIMP nsHyperTextAccessible::Rem
   if (aSelectionNum < 0 || aSelectionNum >= rangeCount)
     return NS_ERROR_INVALID_ARG;
 
   nsCOMPtr<nsIDOMRange> range;
   domSel->GetRangeAt(aSelectionNum, getter_AddRefs(range));
   return domSel->RemoveRange(range);
 }
 
+nsresult nsHyperTextAccessible::ContentToRenderedOffset(nsIFrame *aFrame, PRInt32 aContentOffset,
+                                                        PRUint32 *aRenderedOffset)
+{
+  gfxSkipChars skipChars;
+  gfxSkipCharsIterator iter;
+  // Only get info up to original ofset, we know that will be larger than skipped offset
+  nsresult rv = aFrame->GetRenderedText(nsnull, &skipChars, &iter, 0, aContentOffset);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  PRUint32 ourRenderedStart = iter.GetSkippedOffset();
+  PRInt32 ourContentStart = iter.GetOriginalOffset();
+
+  *aRenderedOffset = iter.ConvertOriginalToSkipped(aContentOffset + ourContentStart) -
+                    ourRenderedStart;
+
+  return NS_OK;
+}
+
+nsresult nsHyperTextAccessible::RenderedToContentOffset(nsIFrame *aFrame, PRUint32 aRenderedOffset,
+                                                        PRInt32 *aContentOffset)
+{
+  gfxSkipChars skipChars;
+  gfxSkipCharsIterator iter;
+  // We only need info up to skipped offset -- that is what we're converting to original offset
+  nsresult rv = aFrame->GetRenderedText(nsnull, &skipChars, &iter, 0, aRenderedOffset);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  PRUint32 ourRenderedStart = iter.GetSkippedOffset();
+  PRInt32 ourContentStart = iter.GetOriginalOffset();
+
+  *aContentOffset = iter.ConvertSkippedToOriginal(aRenderedOffset + ourRenderedStart) - ourContentStart;
+
+  return NS_OK;
+}
+
+
--- a/accessible/src/html/nsHyperTextAccessible.h
+++ b/accessible/src/html/nsHyperTextAccessible.h
@@ -40,50 +40,84 @@
 #ifndef _nsHyperTextAccessible_H_
 #define _nsHyperTextAccessible_H_
 
 #include "nsAccessibleWrap.h"
 #include "nsIAccessibleText.h"
 #include "nsIAccessibleHyperText.h"
 #include "nsIAccessibleEditableText.h"
 #include "nsAccessibleEventData.h"
-#include "nsIEditActionListener.h"
 #include "nsIEditor.h"
 #include "nsFrameSelection.h"
 #include "nsISelectionController.h"
 
 enum EGetTextType { eGetBefore=-1, eGetAt=0, eGetAfter=1 };
 
 // This character marks where in the text returned via nsIAccessibleText(),
 // that embedded object characters exist
 const PRUnichar kEmbeddedObjectChar = 0xfffc;
 const PRUnichar kForcedNewLineChar = '\n';
 
+#define NS_HYPERTEXTACCESSIBLE_IMPL_CID                 \
+{  /* 245f3bc9-224f-4839-a92e-95239705f30b */           \
+  0x245f3bc9,                                           \
+  0x224f,                                               \
+  0x4839,                                               \
+  { 0xa9, 0x2e, 0x95, 0x23, 0x97, 0x05, 0xf3, 0x0b }    \
+}
+
+
 /**
   * Special Accessible that knows how contain both text and embedded objects
   */
 class nsHyperTextAccessible : public nsAccessibleWrap,
                               public nsIAccessibleText,
                               public nsIAccessibleHyperText,
-                              public nsIAccessibleEditableText,
-                              public nsIEditActionListener
+                              public nsIAccessibleEditableText
 {
 public:
   nsHyperTextAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell);
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_NSIACCESSIBLETEXT
   NS_DECL_NSIACCESSIBLEHYPERTEXT
   NS_DECL_NSIACCESSIBLEEDITABLETEXT
-  NS_DECL_NSIEDITACTIONLISTENER
+  NS_DECLARE_STATIC_IID_ACCESSOR(NS_HYPERTEXTACCESSIBLE_IMPL_CID)
 
   NS_IMETHOD GetRole(PRUint32 *aRole);
   NS_IMETHOD GetState(PRUint32 *aState, PRUint32 *aExtraState);
   virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
   void CacheChildren();
 
+  // Convert content offset to rendered text offset  
+  static nsresult ContentToRenderedOffset(nsIFrame *aFrame, PRInt32 aContentOffset,
+                                          PRUint32 *aRenderedOffset);
+  
+  // Convert rendered text offset to content offset
+  static nsresult RenderedToContentOffset(nsIFrame *aFrame, PRUint32 aRenderedOffset,
+                                          PRInt32 *aContentOffset);
+
+  /**
+    * Turn a DOM Node and offset into a character offset into this hypertext.
+    * Will look for closest match when the DOM node does not have an accessible
+    * object associated with it. Will return an offset for the end of
+    * the string if the node is not found.
+    *
+    * @param aNode - the node to look for
+    * @param aNodeOffset - the offset to look for
+    * @param aResultOffset - the character offset into the current
+    *                        nsHyperTextAccessible
+    * @param aFinalAccessible [optional] - returns the accessible child which
+    *                                      contained the offset, if it is within
+    *                                      the current nsHyperTextAccessible,
+    *                                      otherwise it is set to nsnull.
+    */
+  nsresult DOMPointToHypertextOffset(nsIDOMNode* aNode, PRInt32 aNodeOffset,
+                                     PRInt32 *aHypertextOffset,
+                                     nsIAccessible **aFinalAccessible = nsnull);
+
 protected:
   PRBool IsHyperText();
 
   /*
    * This does the work for nsIAccessibleText::GetText[At|Before|After]Offset
    * @param aType, eGetBefore, eGetAt, eGetAfter
    * @param aBoundaryType, char/word-start/word-end/line-start/line-end/paragraph/attribute
    * @param aOffset, offset into the hypertext to start from
@@ -107,44 +141,35 @@ protected:
     * @return, the resulting offset into this hypertext
     */
   PRInt32 GetRelativeOffset(nsIPresShell *aPresShell, nsIFrame *aFromFrame, PRInt32 aFromOffset,
                             nsSelectionAmount aAmount, nsDirection aDirection, PRBool aNeedsStart);
   /**
     * Given a start offset and end offset, get substring information. Different info is returned depending
     * on what optional paramters are provided.
     * @param aStartOffset, the start offset into the hyper text. This is also an out parameter used to return
-    *                      the offset into the start frame's text content (start frame is the @return)
-    * @param aEndOffset, the endoffset into the hyper text. This is also an out parameter used to return
-    *                    the offset into the end frame's text content
+    *                      the offset into the start frame's rendered text content (start frame is the @return)
+    * @param aEndHyperOffset, the endoffset into the hyper text. This is also an out parameter used to return
+    *                    the offset into the end frame's rendered text content
     * @param aText (optional), return the substring's text
     * @param aEndFrame (optional), return the end frame for this substring
     * @param aBoundsRect (optional), return the bounds rectangle for this substring
     * @return the start frame for this substring
     */
   nsIFrame* GetPosAndText(PRInt32& aStartOffset, PRInt32& aEndOffset, nsAString *aText = nsnull,
                           nsIFrame **aEndFrame = nsnull, nsIntRect *aBoundsRect = nsnull);
-  /**
-    * Turn a DOM Node and offset into a character offset into this hypertext. Will look for closest match
-    * when the DOM node does not have an accessible object associated with it.
-    * Will return an offset for the end of the string if the node is not found.
-    * @param aNode, the node to look for
-    * @param aNodeOffset, the offset to look for
-    * @param aResult, the character offset into the current nsHyperTextAccessible
-    * @param aFinalAccessible (optional), returns the accessible child which contained the offset,
-    *                                     if it is within the current nsHyperTextAccessible, otherwise
-    *                                     it is set to nsnull.
-    * @return failure/success code
-    */
-  nsresult DOMPointToOffset(nsIDOMNode* aNode, PRInt32 aNodeOffset, PRInt32 *aResultOffset,
-                            nsIAccessible **aFinalAccessible = nsnull);
-  nsIntRect GetBoundsForString(nsIFrame *aFrame, PRInt32 aStartOffset, PRInt32 aLength);
+
+  nsIntRect GetBoundsForString(nsIFrame *aFrame, PRInt32 aStartContentOffset, PRInt32 aEndContentOffset);
 
   // Editor helpers, subclasses of nsHyperTextAccessible may have editor
   virtual void SetEditor(nsIEditor *aEditor) { return; }
   virtual already_AddRefed<nsIEditor> GetEditor() { return nsnull; }
 
   // Selection helpers
   nsresult GetSelections(nsISelectionController **aSelCon, nsISelection **aDomSel);
   nsresult SetSelectionRange(PRInt32 aStartPos, PRInt32 aEndPos);
 };
 
+NS_DEFINE_STATIC_IID_ACCESSOR(nsHyperTextAccessible,
+                              NS_HYPERTEXTACCESSIBLE_IMPL_CID)
+
 #endif  // _nsHyperTextAccessible_H_
+
--- a/accessible/src/mac/nsAccessibleWrap.h
+++ b/accessible/src/mac/nsAccessibleWrap.h
@@ -76,23 +76,25 @@ class nsAccessibleWrap : public nsAccess
     
     virtual nsresult Shutdown ();
     virtual nsresult InvalidateChildren ();
 
     NS_IMETHOD FireAccessibleEvent(nsIAccessibleEvent *aEvent);
 
     // we'll flatten buttons and checkboxes. usually they have a text node
     // child, that is their title. Works in conjunction with IsPruned() below.
+    // XXX There is no IsPruned() method, so what does that comment mean?
     PRBool IsFlat() {
       PRUint32 role = Role(this);
       return (role == nsIAccessibleRole::ROLE_CHECKBUTTON ||
               role == nsIAccessibleRole::ROLE_PUSHBUTTON ||
               role == nsIAccessibleRole::ROLE_TOGGLE_BUTTON ||
               role == nsIAccessibleRole::ROLE_SPLITBUTTON ||
-              role == nsIAccessibleRole::ROLE_ENTRY);
+              role == nsIAccessibleRole::ROLE_ENTRY ||
+              role == nsIAccessibleRole::ROLE_IMAGE);
     }
     
     // ignored means that the accessible might still have children, but is not displayed
     // to the user. it also has no native accessible object represented for it.
     PRBool IsIgnored();
     
     PRInt32 GetUnignoredChildCount(PRBool aDeepCount);
     
--- a/accessible/src/mac/nsRoleMap.h
+++ b/accessible/src/mac/nsRoleMap.h
@@ -153,10 +153,11 @@ static const NSString* AXRoles [] = {
   NSAccessibilityUnknownRole,                   // ROLE_REDUNDANT_OBJECT
   NSAccessibilityGroupRole,                     // ROLE_FORM
   NSAccessibilityUnknownRole,                   // ROLE_IME
   NSAccessibilityUnknownRole,                   // ROLE_APP_ROOT. unused on OS X
   NSAccessibilityMenuItemRole,                  // ROLE_PARENT_MENUITEM
   NSAccessibilityGroupRole,                     // ROLE_CALENDAR
   NSAccessibilityMenuRole,                      // ROLE_COMBOBOX_LIST
   NSAccessibilityMenuItemRole,                  // ROLE_COMBOBOX_LISTITEM
+  NSAccessibilityImageRole,                     // ROLE_IMAGE_MAP
   @"ROLE_LAST_ENTRY"                            // ROLE_LAST_ENTRY. bogus role that will never be shown (just marks the end of this array)!
 };
--- a/accessible/src/msaa/nsAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsAccessibleWrap.cpp
@@ -429,23 +429,16 @@ STDMETHODIMP nsAccessibleWrap::get_accRo
   PRUint32 xpRole = 0, msaaRole = 0;
   if (NS_FAILED(xpAccessible->GetFinalRole(&xpRole)))
     return E_FAIL;
 
   msaaRole = gWindowsRoleMap[xpRole].msaaRole;
   NS_ASSERTION(gWindowsRoleMap[nsIAccessibleRole::ROLE_LAST_ENTRY].msaaRole == ROLE_WINDOWS_LAST_ENTRY,
                "MSAA role map skewed");
 
-  // Special case, not a great place for this, but it's better than adding extra role buttonmenu role to ARIA
-  // Other APIs do not have a special role for this.
-  // Really the HASPOPUP state should have been enough for MSAA, but this avoids asking vendors for a fix.
-  if (msaaRole == ROLE_SYSTEM_PUSHBUTTON && (State(xpAccessible) & nsIAccessibleStates::STATE_HASPOPUP)) {
-    msaaRole = ROLE_SYSTEM_BUTTONMENU;
-  }
-  
   // Special case, if there is a ROLE_ROW inside of a ROLE_TREE_TABLE, then call the MSAA role
   // a ROLE_OUTLINEITEM for consistency and compatibility.
   // We need this because ARIA has a role of "row" for both grid and treegrid
   if (xpRole == nsIAccessibleRole::ROLE_ROW) {
     nsCOMPtr<nsIAccessible> parent = GetParent();
     if (parent && Role(parent) == nsIAccessibleRole::ROLE_TREE_TABLE) {
       msaaRole = ROLE_SYSTEM_OUTLINEITEM;
     }
@@ -1404,17 +1397,17 @@ nsAccessibleWrap::get_attributes(BSTR *a
     }
 
     nsAutoString value;
     if (NS_FAILED(propElem->GetValue(value)))
       return E_FAIL;
 
     offset = 0;
     while ((offset = value.FindCharInSet(kCharsToEscape, offset)) != kNotFound) {
-      name.Insert('\\', offset);
+      value.Insert('\\', offset);
       offset += 2;
     }
 
     AppendUTF8toUTF16(name, strAttrs);
     strAttrs.Append(':');
     strAttrs.Append(value);
     strAttrs.Append(';');
   }
@@ -1714,8 +1707,18 @@ void nsAccessibleWrap::UpdateSystemCaret
     ::ShowCaret(caretWnd);
     RECT windowRect;
     ::GetWindowRect(caretWnd, &windowRect);
     ::SetCaretPos(caretRect.x - windowRect.left, caretRect.y - windowRect.top);
     ::DeleteObject(caretBitMap);
   }
 }
 
+PRBool nsAccessibleWrap::MustPrune(nsIAccessible *aAccessible)
+{ 
+  PRUint32 role = Role(aAccessible);
+  return role == nsIAccessibleRole::ROLE_MENUITEM || 
+         role == nsIAccessibleRole::ROLE_ENTRY ||
+         role == nsIAccessibleRole::ROLE_PASSWORD_TEXT ||
+         role == nsIAccessibleRole::ROLE_PUSHBUTTON ||
+         role == nsIAccessibleRole::ROLE_TOGGLE_BUTTON ||
+         role == nsIAccessibleRole::ROLE_GRAPHIC;
+}
--- a/accessible/src/msaa/nsAccessibleWrap.h
+++ b/accessible/src/msaa/nsAccessibleWrap.h
@@ -318,18 +318,17 @@ class nsAccessibleWrap : public nsAccess
 
 protected:
   // mEnumVARIANTPosition not the current accessible's position, but a "cursor" of 
   // where we are in the current list of children, with respect to
   // nsIEnumVariant::Reset(), Skip() and Next().
   PRUint16 mEnumVARIANTPosition;
 
   // Should this accessible be allowed to have any MSAA children
-  static PRBool MustPrune(nsIAccessible *accessible)
-    { PRUint32 role; return NS_SUCCEEDED(accessible->GetRole(&role)) && (role == nsIAccessibleRole::ROLE_ENTRY || role == nsIAccessibleRole::ROLE_PASSWORD_TEXT || role == nsIAccessibleRole::ROLE_PUSHBUTTON); }
+  static PRBool MustPrune(nsIAccessible *aAccessible);
 
   enum navRelations {
     NAVRELATION_CONTROLLED_BY = 0x1000,
     NAVRELATION_CONTROLLER_FOR = 0x1001,
     NAVRELATION_LABEL_FOR = 0x1002,
     NAVRELATION_LABELLED_BY = 0x1003,
     NAVRELATION_MEMBER_OF = 0x1004,
     NAVRELATION_NODE_CHILD_OF = 0x1005,
--- a/accessible/src/msaa/nsRoleMap.h
+++ b/accessible/src/msaa/nsRoleMap.h
@@ -417,12 +417,15 @@ static const WindowsRoleMapItem gWindows
   { ROLE_SYSTEM_CLIENT, ROLE_SYSTEM_CLIENT },
 
   // nsIAccessibleRole::ROLE_COMBOBOX_LIST
   { ROLE_SYSTEM_LIST, ROLE_SYSTEM_LIST },
 
   // nsIAccessibleRole::ROLE_COMBOBOX_LISTITEM
   { ROLE_SYSTEM_LISTITEM, ROLE_SYSTEM_LISTITEM },
 
+  // nsIAccessibleRole::ROLE_IMAGE_MAP
+  { ROLE_SYSTEM_GRAPHIC, ROLE_SYSTEM_GRAPHIC },
+
   // nsIAccessibleRole::ROLE_LAST_ENTRY
   { ROLE_WINDOWS_LAST_ENTRY, ROLE_WINDOWS_LAST_ENTRY }
 };
 
--- a/accessible/src/xforms/nsXFormsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsAccessible.cpp
@@ -359,22 +359,17 @@ nsXFormsEditableAccessible::GetEditor()
   nsIEditor *editor = mEditor;
   NS_IF_ADDREF(editor);
   return editor;
 }
 
 void
 nsXFormsEditableAccessible::SetEditor(nsIEditor *aEditor)
 {
-  if (mEditor)
-    mEditor->RemoveEditActionListener(this);
-
   mEditor = aEditor;
-  if (mEditor)
-    mEditor->AddEditActionListener(this);
 }
 
 // nsXFormsSelectableAccessible
 
 
 NS_IMPL_ISUPPORTS_INHERITED1(nsXFormsSelectableAccessible,
                              nsXFormsEditableAccessible,
                              nsIAccessibleSelectable)
--- a/accessible/src/xul/Makefile.in
+++ b/accessible/src/xul/Makefile.in
@@ -67,16 +67,17 @@ REQUIRES += editor
 endif
 
 CPPSRCS = \
   nsXULAlertAccessible.cpp \
   nsXULColorPickerAccessible.cpp \
   nsXULFormControlAccessible.cpp \
   nsXULMenuAccessible.cpp \
   nsXULSelectAccessible.cpp \
+  nsXULSliderAccessible.cpp \
   nsXULTabAccessible.cpp \
   nsXULTextAccessible.cpp \
   nsXULTreeAccessible.cpp \
   $(NULL)
 
 # we don't want the shared lib, but we want to force the creation of a static lib.
 FORCE_STATIC_LIB = 1
 
--- a/accessible/src/xul/nsXULAlertAccessible.cpp
+++ b/accessible/src/xul/nsXULAlertAccessible.cpp
@@ -59,51 +59,8 @@ nsXULAlertAccessible::GetState(PRUint32 
   nsresult rv = nsAccessible::GetState(aState, aExtraState);
   NS_ENSURE_SUCCESS(rv, rv);
 
   *aState &= ~nsIAccessibleStates::STATE_FOCUSABLE;
   *aState |= nsIAccessibleStates::STATE_ALERT_MEDIUM; // XUL has no markup for low, medium or high
   return NS_OK;
 }
 
-#if 0
-// We don't need this, but the AT will need to read all of the alert's children
-// when it receives EVENT_ALERT on a ROLE_ALERT
-NS_IMETHODIMP nsXULAlertAccessible::GetName(nsAString &aName)
-{
-  nsCOMPtr<nsIPresShell> presShell(do_QueryReferent(mWeakShell));
-  if (!presShell) {
-    return NS_ERROR_FAILURE; // Node already shut down
-  }
-  nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
-  NS_ASSERTION(content, "Should not be null if we still have a presShell");
-
-  nsCOMPtr<nsIDOMNodeList> siblingList;
-  // returns null if no anon nodes
-  presShell->GetDocument()->GetXBLChildNodesFor(content,
-                                                getter_AddRefs(siblingList));
-  if (siblingList) {
-    PRUint32 length, count;
-    siblingList->GetLength(&length);
-    for (count = 0; count < length; count ++) {
-      nsCOMPtr<nsIDOMNode> domNode;
-      siblingList->Item(count, getter_AddRefs(domNode));
-      nsCOMPtr<nsIDOMXULLabeledControlElement> labeledEl(do_QueryInterface(domNode));
-      if (labeledEl) {
-        nsAutoString label;
-        labeledEl->GetLabel(label);
-        aName += NS_LITERAL_STRING(" ") + label + NS_LITERAL_STRING(" ");
-      }
-      else {
-        nsCOMPtr<nsIContent> content(do_QueryInterface(domNode));
-        if (content) {
-          AppendFlatStringFromSubtree(content, &aName);
-        }
-      }
-    }
-  }
-  else {
-    AppendFlatStringFromSubtree(content, &aName);
-  }
-
-  return NS_OK;
-}
-#endif
--- a/accessible/src/xul/nsXULFormControlAccessible.cpp
+++ b/accessible/src/xul/nsXULFormControlAccessible.cpp
@@ -769,20 +769,17 @@ NS_IMPL_ISUPPORTS_INHERITED1(nsXULTextFi
 NS_IMETHODIMP nsXULTextFieldAccessible::Init()
 {
   CheckForEditor();
   return nsHyperTextAccessibleWrap::Init();
 }
 
 NS_IMETHODIMP nsXULTextFieldAccessible::Shutdown()
 {
-  if (mEditor) {
-    mEditor->RemoveEditActionListener(this);
-    mEditor = nsnull;
-  }
+  mEditor = nsnull;
   return nsHyperTextAccessibleWrap::Shutdown();
 }
 
 NS_IMETHODIMP nsXULTextFieldAccessible::GetValue(nsAString& aValue)
 {
   PRUint32 state;
   GetState(&state, nsnull);
   if (state & nsIAccessibleStates::STATE_PROTECTED)    // Don't return password text!
@@ -936,18 +933,16 @@ nsXULTextFieldAccessible::GetAllowsAnonC
 {
   *aAllowsAnonChildren = PR_FALSE;
   return NS_OK;
 }
 
 void nsXULTextFieldAccessible::SetEditor(nsIEditor* aEditor)
 {
   mEditor = aEditor;
-  if (mEditor)
-    mEditor->AddEditActionListener(this);
 }
 
 void nsXULTextFieldAccessible::CheckForEditor()
 {
   nsCOMPtr<nsIDOMNode> inputField = GetInputField();
   nsCOMPtr<nsIDOMNSEditableElement> editableElt(do_QueryInterface(inputField));
   if (!editableElt) {
     return;
new file mode 100644
--- /dev/null
+++ b/accessible/src/xul/nsXULSliderAccessible.cpp
@@ -0,0 +1,244 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2007
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Alexander Surkov <surkov.alexander@gmail.com> (original author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of the GNU General Public License Version 2 or later (the "GPL"),
+ * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "nsXULSliderAccessible.h"
+
+#include "nsIDOMDocument.h"
+#include "nsIDOMDocumentXBL.h"
+
+// nsXULSliderAccessible
+
+nsXULSliderAccessible::nsXULSliderAccessible(nsIDOMNode* aNode,
+                                             nsIWeakReference* aShell) :
+  nsAccessibleWrap(aNode, aShell)
+{
+}
+
+// nsIAccessible
+
+NS_IMETHODIMP
+nsXULSliderAccessible::GetRole(PRUint32 *aRole)
+{
+  NS_ENSURE_ARG_POINTER(aRole);
+
+  *aRole = nsIAccessibleRole::ROLE_SLIDER;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsXULSliderAccessible::GetValue(nsAString& aValue)
+{
+  return GetSliderAttr(nsAccessibilityAtoms::curpos, aValue);
+}
+
+// nsIAccessibleValue
+
+NS_IMETHODIMP
+nsXULSliderAccessible::GetMaximumValue(double *aValue)
+{
+  nsresult rv = nsAccessibleWrap::GetMaximumValue(aValue);
+
+  // ARIA redefined maximum value.
+  if (rv != NS_OK_NO_ARIA_VALUE)
+    return rv;
+
+  return GetSliderAttr(nsAccessibilityAtoms::maxpos, aValue);
+}
+
+NS_IMETHODIMP
+nsXULSliderAccessible::GetMinimumValue(double *aValue)
+{
+  nsresult rv = nsAccessibleWrap::GetMinimumValue(aValue);
+
+  // ARIA redefined minmum value.
+  if (rv != NS_OK_NO_ARIA_VALUE)
+    return rv;
+
+  return GetSliderAttr(nsAccessibilityAtoms::minpos, aValue);
+}
+
+NS_IMETHODIMP
+nsXULSliderAccessible::GetMinimumIncrement(double *aValue)
+{
+  nsresult rv = nsAccessibleWrap::GetMinimumIncrement(aValue);
+
+  // ARIA redefined minimum increment value.
+  if (rv != NS_OK_NO_ARIA_VALUE)
+    return rv;
+
+  return GetSliderAttr(nsAccessibilityAtoms::increment, aValue);
+}
+
+NS_IMETHODIMP
+nsXULSliderAccessible::GetCurrentValue(double *aValue)
+{
+  nsresult rv = nsAccessibleWrap::GetCurrentValue(aValue);
+
+  // ARIA redefined current value.
+  if (rv != NS_OK_NO_ARIA_VALUE)
+    return rv;
+
+  return GetSliderAttr(nsAccessibilityAtoms::curpos, aValue);
+}
+
+NS_IMETHODIMP
+nsXULSliderAccessible::SetCurrentValue(double aValue)
+{
+  nsresult rv = nsAccessibleWrap::SetCurrentValue(aValue);
+
+  // ARIA redefined current value.
+  if (rv != NS_OK_NO_ARIA_VALUE)
+    return rv;
+
+  return SetSliderAttr(nsAccessibilityAtoms::curpos, aValue);
+}
+
+// nsPIAccessible
+NS_IMETHODIMP
+nsXULSliderAccessible::GetAllowsAnonChildAccessibles(PRBool *aAllowsAnonChildren)
+{
+  NS_ENSURE_ARG_POINTER(aAllowsAnonChildren);
+
+  // Allow anonymous xul:thumb inside xul:slider.
+  *aAllowsAnonChildren = PR_TRUE;
+  return NS_OK;
+}
+
+// Utils
+
+already_AddRefed<nsIContent>
+nsXULSliderAccessible::GetSliderNode()
+{
+  if (!mDOMNode)
+    return nsnull;
+
+  if (!mSliderNode) {
+    nsCOMPtr<nsIDOMDocument> document;
+    mDOMNode->GetOwnerDocument(getter_AddRefs(document));
+    if (!document)
+      return nsnull;
+
+    nsCOMPtr<nsIDOMDocumentXBL> xblDoc(do_QueryInterface(document));
+    if (!xblDoc)
+      return nsnull;
+
+    // XXX: we depend on anonymous content.
+    nsCOMPtr<nsIDOMElement> domElm(do_QueryInterface(mDOMNode));
+    if (!domElm)
+      return nsnull;
+
+    xblDoc->GetAnonymousElementByAttribute(domElm, NS_LITERAL_STRING("anonid"),
+                                           NS_LITERAL_STRING("slider"),
+                                           getter_AddRefs(mSliderNode));
+  }
+
+  nsIContent *sliderNode = nsnull;
+  nsresult rv = CallQueryInterface(mSliderNode, &sliderNode);
+  return NS_FAILED(rv) ? nsnull : sliderNode;
+}
+
+nsresult
+nsXULSliderAccessible::GetSliderAttr(nsIAtom *aName, nsAString& aValue)
+{
+  aValue.Truncate();
+
+  if (!mDOMNode)
+    return NS_ERROR_FAILURE;
+
+  nsCOMPtr<nsIContent> sliderNode(GetSliderNode());
+  NS_ENSURE_STATE(sliderNode);
+
+  sliderNode->GetAttr(kNameSpaceID_None, aName, aValue);
+  return NS_OK;
+}
+
+nsresult
+nsXULSliderAccessible::SetSliderAttr(nsIAtom *aName, const nsAString& aValue)
+{
+  if (!mDOMNode)
+    return NS_ERROR_FAILURE;
+
+  nsCOMPtr<nsIContent> sliderNode(GetSliderNode());
+  NS_ENSURE_STATE(sliderNode);
+
+  sliderNode->SetAttr(kNameSpaceID_None, aName, aValue, PR_TRUE);
+  return NS_OK;
+}
+
+nsresult
+nsXULSliderAccessible::GetSliderAttr(nsIAtom *aName, double *aValue)
+{
+  NS_ENSURE_ARG_POINTER(aValue);
+  *aValue = 0;
+
+  nsAutoString value;
+  nsresult rv = GetSliderAttr(aName, value);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  PRInt32 error = NS_OK;
+  *aValue = value.ToFloat(&error);
+  return error;
+}
+
+nsresult
+nsXULSliderAccessible::SetSliderAttr(nsIAtom *aName, double aValue)
+{
+  nsAutoString value;
+  value.AppendFloat(aValue);
+
+  return SetSliderAttr(aName, value);
+}
+
+
+// nsXULThumbAccessible
+
+nsXULThumbAccessible::nsXULThumbAccessible(nsIDOMNode* aNode,
+                                           nsIWeakReference* aShell) :
+  nsAccessibleWrap(aNode, aShell) {}
+
+// nsIAccessible
+
+NS_IMETHODIMP
+nsXULThumbAccessible::GetRole(PRUint32 *aRole)
+{
+  NS_ENSURE_ARG_POINTER(aRole);
+
+  *aRole = nsIAccessibleRole::ROLE_INDICATOR;
+  return NS_OK;
+}
+
new file mode 100644
--- /dev/null
+++ b/accessible/src/xul/nsXULSliderAccessible.h
@@ -0,0 +1,89 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2007
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Alexander Surkov <surkov.alexander@gmail.com> (original author)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of the GNU General Public License Version 2 or later (the "GPL"),
+ * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef _nsXULSliderAccessible_H_
+#define _nsXULSliderAccessible_H_
+
+#include "nsAccessibleWrap.h"
+
+#include "nsIDOMElement.h"
+
+class nsXULSliderAccessible : public nsAccessibleWrap
+{
+public:
+  nsXULSliderAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell);
+
+  // nsIAccessible
+  NS_IMETHOD GetRole(PRUint32 *aRole);
+  NS_IMETHOD GetValue(nsAString& aValue);
+
+  // nsIAccessibleValue
+  NS_IMETHOD GetMaximumValue(double *aMaximumValue);
+  NS_IMETHOD GetMinimumValue(double *aMinimumValue);
+  NS_IMETHOD GetMinimumIncrement(double *aMinIncrement);
+  NS_IMETHOD GetCurrentValue(double *aValue);
+  NS_IMETHOD SetCurrentValue(double aValue);
+
+  // nsPIAccessible
+  NS_IMETHOD GetAllowsAnonChildAccessibles(PRBool *aAllowsAnonChildren);
+
+protected:
+  already_AddRefed<nsIContent> GetSliderNode();
+
+  nsresult GetSliderAttr(nsIAtom *aName, nsAString& aValue);
+  nsresult SetSliderAttr(nsIAtom *aName, const nsAString& aValue);
+
+  nsresult GetSliderAttr(nsIAtom *aName, double *aValue);
+  nsresult SetSliderAttr(nsIAtom *aName, double aValue);
+
+private:
+  nsCOMPtr<nsIDOMElement> mSliderNode;
+};
+
+
+class nsXULThumbAccessible : public nsAccessibleWrap
+{
+public:
+  nsXULThumbAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell);
+
+  // nsIAccessible
+  NS_IMETHOD GetRole(PRUint32 *aRole);
+};
+
+#endif
+
--- a/allmakefiles.sh
+++ b/allmakefiles.sh
@@ -171,16 +171,24 @@ gfx/cairo/libpixman/src/Makefile
 gfx/cairo/cairo/src/Makefile
 gfx/cairo/cairo/src/cairo-features.h
 gfx/cairo/glitz/src/Makefile
 gfx/cairo/glitz/src/glx/Makefile
 gfx/cairo/glitz/src/wgl/Makefile
 "
 fi
 
+if [ ! "$MOZ_NATIVE_LCMS" ] ; then
+MAKEFILES_gfx="$MAKEFILES_gfx
+modules/lcms/Makefile
+modules/lcms/include/Makefile
+modules/lcms/src/Makefile
+"
+fi
+
 MAKEFILES_htmlparser="
 parser/htmlparser/Makefile
 parser/htmlparser/robot/Makefile
 parser/htmlparser/robot/test/Makefile
 parser/htmlparser/public/Makefile
 parser/htmlparser/src/Makefile
 parser/htmlparser/tests/Makefile
 parser/htmlparser/tests/grabpage/Makefile
@@ -471,24 +479,17 @@ fi
 MAKEFILES_uriloader="
 uriloader/Makefile
 uriloader/base/Makefile
 uriloader/exthandler/Makefile
 "
 
 MAKEFILES_profile="
 profile/Makefile
-profile/src/Makefile
 profile/public/Makefile
-profile/resources/Makefile
-profile/pref-migrator/Makefile
-profile/pref-migrator/public/Makefile
-profile/pref-migrator/src/Makefile
-profile/pref-migrator/resources/Makefile
-profile/defaults/Makefile
 profile/dirserviceprovider/Makefile
 profile/dirserviceprovider/public/Makefile
 profile/dirserviceprovider/src/Makefile
 "
 
 MAKEFILES_rdf="
 rdf/Makefile
 rdf/base/Makefile
@@ -686,25 +687,23 @@ xpfe/components/sidebar/src/Makefile
 xpfe/components/startup/Makefile
 xpfe/components/startup/public/Makefile
 xpfe/components/startup/src/Makefile
 xpfe/components/autocomplete/Makefile
 xpfe/components/autocomplete/public/Makefile
 xpfe/components/autocomplete/src/Makefile
 xpfe/components/updates/Makefile
 xpfe/components/updates/src/Makefile
-xpfe/components/urlwidget/Makefile
 xpfe/components/winhooks/Makefile
 xpfe/components/windowds/Makefile
 xpfe/components/alerts/Makefile
 xpfe/components/alerts/public/Makefile
 xpfe/components/alerts/src/Makefile
 xpfe/components/console/Makefile
 xpfe/components/resetPref/Makefile
-xpfe/components/killAll/Makefile
 xpfe/components/build/Makefile
 xpfe/components/xremote/Makefile
 xpfe/components/xremote/public/Makefile
 xpfe/components/xremote/src/Makefile
 xpfe/appshell/Makefile
 xpfe/appshell/src/Makefile
 xpfe/appshell/public/Makefile
 xpfe/bootstrap/appleevents/Makefile
@@ -719,19 +718,19 @@ xpfe/global/resources/content/unix/Makef
 xpfe/global/resources/locale/Makefile
 xpfe/global/resources/locale/en-US/Makefile
 xpfe/global/resources/locale/en-US/mac/Makefile
 xpfe/global/resources/locale/en-US/os2/Makefile
 xpfe/global/resources/locale/en-US/unix/Makefile
 xpfe/global/resources/locale/en-US/win/Makefile
 xpfe/communicator/Makefile
 extensions/spellcheck/Makefile
+extensions/spellcheck/hunspell/Makefile
 extensions/spellcheck/idl/Makefile
 extensions/spellcheck/locales/Makefile
-extensions/spellcheck/myspell/Makefile
 extensions/spellcheck/src/Makefile
 "
 
 MAKEFILES_embedding="
 embedding/Makefile
 embedding/base/Makefile
 embedding/browser/Makefile
 embedding/browser/activex/src/Makefile
--- a/browser/app/Makefile.in
+++ b/browser/app/Makefile.in
@@ -269,31 +269,32 @@ ifdef BUILD_STATIC_LIBS
 
 LDFLAGS += -Zlinker /NOE
 endif
 endif
 
 ifneq (,$(filter-out OS2 WINNT,$(OS_ARCH)))
 
 $(MOZ_APP_NAME):: mozilla.in Makefile.in Makefile $(DEPTH)/config/autoconf.mk
-	cat $< | sed -e "s|%MOZAPPDIR%|$(mozappdir)|" \
-		-e "s|%MREDIR%|$(mredir)|" > $@
+	cat $< | sed -e "s|%MOZAPPDIR%|$(installdir)|" > $@
 	chmod +x $@
 
 libs:: $(MOZ_APP_NAME)
 	$(INSTALL) $< $(DIST)/bin
 
 install:: $(MOZ_APP_NAME)
 	$(SYSINSTALL) $< $(DESTDIR)$(bindir)
 
 GARBAGE += $(MOZ_APP_NAME)
 GARBAGE += $(addprefix $(DIST)/bin/defaults/pref/, firefox.js)
 
 endif
 
+endif # LIBXUL_SDK
+
 ifneq (,$(filter gtk2,$(MOZ_WIDGET_TOOLKIT)))
 
 ICON_FILES	= \
 		$(DIST)/branding/mozicon128.png \
 		$(DIST)/branding/mozicon50.xpm \
 		$(DIST)/branding/mozicon16.xpm \
 		$(DIST)/branding/document.png \
 		$(NULL)
@@ -358,40 +359,66 @@ endif
 
 AB_CD = $(MOZ_UI_LOCALE)
 
 AB := $(firstword $(subst -, ,$(AB_CD)))
 
 clean clobber repackage::
 	rm -rf $(DIST)/$(APP_NAME).app
 
-libs repackage:: $(PROGRAM)
+ifdef LIBXUL_SDK
+APPFILES = Resources
+else
+APPFILES = MacOS
+endif
+
+libs repackage:: $(PROGRAM) application.ini
 	mkdir -p $(DIST)/$(APP_NAME).app/Contents/MacOS
 	rsync -a --exclude CVS --exclude "*.in" $(srcdir)/macbuild/Contents $(DIST)/$(APP_NAME).app --exclude English.lproj
 	mkdir -p $(DIST)/$(APP_NAME).app/Contents/Resources/$(AB).lproj
 	rsync -a --exclude CVS --exclude "*.in" $(srcdir)/macbuild/Contents/Resources/English.lproj/ $(DIST)/$(APP_NAME).app/Contents/Resources/$(AB).lproj
 	sed -e "s/%APP_VERSION%/$(APP_VERSION)/" -e "s/%APP_NAME%/$(APP_NAME)/" $(srcdir)/macbuild/Contents/Info.plist.in > $(DIST)/$(APP_NAME).app/Contents/Info.plist
 	sed -e "s/%APP_VERSION%/$(APP_VERSION)/" -e "s/%APP_NAME%/$(APP_NAME)/" $(srcdir)/macbuild/Contents/Resources/English.lproj/InfoPlist.strings.in | iconv -f UTF-8 -t UTF-16 > $(DIST)/$(APP_NAME).app/Contents/Resources/$(AB).lproj/InfoPlist.strings
-	rsync -a $(DIST)/bin/ $(DIST)/$(APP_NAME).app/Contents/MacOS
-	rm -f $(DIST)/$(APP_NAME).app/Contents/MacOS/$(PROGRAM) $(DIST)/$(APP_NAME).app/Contents/MacOS/mangle $(DIST)/$(APP_NAME).app/Contents/MacOS/shlibsign
+	rsync -a $(DIST)/bin/ $(DIST)/$(APP_NAME).app/Contents/$(APPFILES)
+	$(RM) $(DIST)/$(APP_NAME).app/Contents/$(APPFILES)/mangle $(DIST)/$(APP_NAME).app/Contents/$(APPFILES)/shlibsign
+ifdef LIBXUL_SDK
+	cp $(LIBXUL_DIST)/bin/$(XR_STUB_NAME) $(DIST)/$(APP_NAME).app/Contents/MacOS/firefox-bin
+else
+	rm -f $(DIST)/$(APP_NAME).app/Contents/MacOS/$(PROGRAM)
 	rsync -aL $(PROGRAM) $(DIST)/$(APP_NAME).app/Contents/MacOS
+endif
 	mkdir -p $(DIST)/$(APP_NAME).app/Contents/Plug-Ins
-	rsync -a --copy-unsafe-links $(DIST)/package/PrintPDE.plugin $(DIST)/$(APP_NAME).app/Contents/Plug-Ins
-	-cp -L $(DIST)/bin/mangle $(DIST)/bin/shlibsign $(DIST)/$(APP_NAME).app/Contents/MacOS
+	rsync -a --copy-unsafe-links $(LIBXUL_DIST)/package/PrintPDE.plugin $(DIST)/$(APP_NAME).app/Contents/Plug-Ins
+	-cp -L $(DIST)/bin/mangle $(DIST)/bin/shlibsign $(DIST)/$(APP_NAME).app/Contents/$(APPFILES)
 	cp -RL $(DIST)/branding/firefox.icns $(DIST)/$(APP_NAME).app/Contents/Resources/firefox.icns
 	cp -RL $(DIST)/branding/document.icns $(DIST)/$(APP_NAME).app/Contents/Resources/document.icns
-	cp -RL $(DIST)/package/mozillaSuite.rsrc $(DIST)/$(APP_NAME).app/Contents/Resources/$(PROGRAM).rsrc
+	cp -RL $(LIBXUL_DIST)/package/mozillaSuite.rsrc $(DIST)/$(APP_NAME).app/Contents/Resources/firefox-bin.rsrc
 	echo -n APPLMOZB > $(DIST)/$(APP_NAME).app/Contents/PkgInfo
 #       remove CVS dirs from packaged app
 	find $(DIST)/$(APP_NAME).app -type d -name "CVS" -prune -exec rm -rf {} \;
 
+else
+ifdef LIBXUL_SDK
+libs::
+	cp $(LIBXUL_DIST)/bin/xulrunner-stub$(BIN_SUFFIX) $(DIST)/bin/firefox$(BIN_SUFFIX)
 endif
-
-endif # LIBXUL_SDK
+endif
 
 libs::
 	$(INSTALL) $(topsrcdir)/LICENSE	$(DIST)/bin
 
 libs:: $(srcdir)/profile/prefs.js
 	$(INSTALL) $^ $(DIST)/bin/defaults/profile
 
 install:: $(srcdir)/profile/prefs.js
 	$(SYSINSTALL) $(IFLAGS1) $^ $(DESTDIR)$(mozappdir)/defaults/profile
+
+ifdef LIBXUL_SDK
+ifndef SKIP_COPY_XULRUNNER
+libs::
+ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT))
+	rsync -a --copy-unsafe-links $(LIBXUL_DIST)/XUL.framework $(DIST)/$(APP_NAME).app/Contents/Frameworks
+else
+	$(NSINSTALL) -D $(DIST)/bin/xulrunner
+	(cd $(LIBXUL_SDK)/bin && tar $(TAR_CREATE_FLAGS) - .) | (cd $(DIST)/bin/xulrunner && tar -xf -)
+endif # cocoa
+endif # SKIP_COPY_XULRUNNER
+endif # LIBXUL_SDK
--- a/browser/app/module.ver
+++ b/browser/app/module.ver
@@ -1,8 +1,8 @@
 WIN32_MODULE_COMPANYNAME=Mozilla Corporation
 WIN32_MODULE_COPYRIGHT=©Firefox and Mozilla Developers, according to the MPL 1.1/GPL 2.0/LGPL 2.1 licenses, as applicable.
 WIN32_MODULE_PRODUCTVERSION=3,0,0,0
-WIN32_MODULE_PRODUCTVERSION_STRING=3.0a7pre
+WIN32_MODULE_PRODUCTVERSION_STRING=3.0a8pre
 WIN32_MODULE_TRADEMARKS=Firefox is a Trademark of The Mozilla Foundation.
 WIN32_MODULE_DESCRIPTION=Firefox
 WIN32_MODULE_PRODUCTNAME=Firefox
 WIN32_MODULE_NAME=Firefox
--- a/browser/app/mozilla.in
+++ b/browser/app/mozilla.in
@@ -31,34 +31,33 @@
 # 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 *****
 
-## $Id: mozilla.in,v 1.14 2007/06/23 05:30:29 ajschult%verizon.net Exp $
+## $Id: mozilla.in,v 1.15 2007/08/03 14:46:19 benjamin%smedbergs.us Exp $
 ## 
 ## Usage:
 ##
 ## $ mozilla [args]
 ##
 ## This script is meant to run the mozilla-bin binary from either 
 ## mozilla/xpfe/bootstrap or mozilla/dist/bin.
 ##
 ## The script will setup all the environment voodoo needed to make
 ## the mozilla-bin binary to work.
 ##
 
 #uncomment for debugging
 #set -x
 
 moz_libdir=%MOZAPPDIR%
-MRE_HOME=%MREDIR%
 
 # Use run-mozilla.sh in the current dir if it exists
 # If not, then start resolving symlinks until we find run-mozilla.sh
 found=0
 progname="$0"
 curdir=`dirname "$progname"`
 progbase=`basename "$progname"`
 run_moz="$curdir/run-mozilla.sh"
@@ -126,18 +125,16 @@ do
       arg="$1"
       shift
       set -- "$@" "$arg"
       pass_arg_count=`expr $pass_arg_count + 1`
       ;;
   esac
 done
 
-export MRE_HOME
-
 if [ $debugging = 1 ]
 then
   echo $dist_bin/run-mozilla.sh $script_args $dist_bin/$MOZILLA_BIN "$@"
 fi
 "$dist_bin/run-mozilla.sh" $script_args "$dist_bin/$MOZILLA_BIN" "$@"
 exitcode=$?
 
 exit $exitcode
--- a/browser/app/nsBrowserApp.cpp
+++ b/browser/app/nsBrowserApp.cpp
@@ -40,16 +40,20 @@
 #ifdef XP_WIN
 #include <windows.h>
 #include <stdlib.h>
 #endif
 
 #include <stdio.h>
 #include <stdarg.h>
 
+#include "plstr.h"
+#include "prprf.h"
+#include "prenv.h"
+
 #include "nsCOMPtr.h"
 #include "nsILocalFile.h"
 #include "nsStringGlue.h"
 
 static void Output(const char *fmt, ... )
 {
   va_list ap;
   va_start(ap, fmt);
@@ -62,35 +66,99 @@ static void Output(const char *fmt, ... 
   MessageBox(NULL, msg, "XULRunner", MB_OK | MB_ICONERROR);
 #else
   vfprintf(stderr, fmt, ap);
 #endif
 
   va_end(ap);
 }
 
+/**
+ * Return true if |arg| matches the given argument name.
+ */
+static PRBool IsArg(const char* arg, const char* s)
+{
+  if (*arg == '-')
+  {
+    if (*++arg == '-')
+      ++arg;
+    return !PL_strcasecmp(arg, s);
+  }
+
+#if defined(XP_WIN) || defined(XP_OS2)
+  if (*arg == '/')
+    return !PL_strcasecmp(++arg, s);
+#endif
+
+  return PR_FALSE;
+}
+
+/**
+ * A helper class which calls NS_LogInit/NS_LogTerm in its scope.
+ */
+class ScopedLogging
+{
+public:
+  ScopedLogging() { NS_LogInit(); }
+  ~ScopedLogging() { NS_LogTerm(); }
+};
+
 int main(int argc, char* argv[])
 {
+  ScopedLogging log;
+
   nsCOMPtr<nsILocalFile> appini;
   nsresult rv = XRE_GetBinaryPath(argv[0], getter_AddRefs(appini));
   if (NS_FAILED(rv)) {
     Output("Couldn't calculate the application directory.");
     return 255;
   }
   appini->SetNativeLeafName(NS_LITERAL_CSTRING("application.ini"));
 
+  // Allow firefox.exe to launch XULRunner apps via -app <application.ini>
+  // Note that -app must be the *first* argument.
+  char *appEnv = nsnull;
+  const char *appDataFile = PR_GetEnv("XUL_APP_FILE");
+  if (appDataFile && *appDataFile) {
+    rv = XRE_GetFileFromPath(appDataFile, getter_AddRefs(appini));
+    if (NS_FAILED(rv)) {
+      Output("Invalid path found: '%s'", appDataFile);
+      return 255;
+    }
+  }
+  else if (argc > 1 && IsArg(argv[1], "app")) {
+    if (argc == 2) {
+      Output("Incorrect number of arguments passed to -app");
+      return 255;
+    }
+
+    rv = XRE_GetFileFromPath(argv[2], getter_AddRefs(appini));
+    if (NS_FAILED(rv)) {
+      Output("application.ini path not recognized: '%s'", argv[2]);
+      return 255;
+    }
+
+    appEnv = PR_smprintf("XUL_APP_FILE=%s", argv[2]);
+    PR_SetEnv(appEnv);
+    argv[2] = argv[0];
+    argv += 2;
+    argc -= 2;
+  }
+
   nsXREAppData *appData;
   rv = XRE_CreateAppData(appini, &appData);
   if (NS_FAILED(rv)) {
     Output("Couldn't read application.ini");
     return 255;
   }
 
   int result = XRE_main(argc, argv, appData);
   XRE_FreeAppData(appData);
+  if (appEnv)
+    PR_smprintf_free(appEnv);
   return result;
 }
 
 #if defined( XP_WIN ) && defined( WIN32 ) && !defined(__GNUC__)
 // We need WinMain in order to not be a console app.  This function is
 // unused if we are a console application.
 int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR args, int )
 {
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -143,18 +143,18 @@ pref("app.update.incompatible.mode", 0);
 //  extensions.{GUID}.update.interval
 //  .. etc ..
 //
 pref("extensions.update.enabled", true);
 pref("extensions.update.url", "chrome://mozapps/locale/extensions/extensions.properties");
 pref("extensions.update.interval", 86400);  // Check for updates to Extensions and 
                                             // Themes every day
 // Non-symmetric (not shared by extensions) extension-specific [update] preferences
-pref("extensions.getMoreExtensionsURL", "http://%LOCALE%.add-ons.mozilla.com/%LOCALE%/%APP%/%VERSION%/extensions/");
-pref("extensions.getMoreThemesURL", "http://%LOCALE%.add-ons.mozilla.com/%LOCALE%/%APP%/%VERSION%/themes/");
+pref("extensions.getMoreExtensionsURL", "https://%LOCALE%.add-ons.mozilla.com/%LOCALE%/%APP%/%VERSION%/extensions/");
+pref("extensions.getMoreThemesURL", "https://%LOCALE%.add-ons.mozilla.com/%LOCALE%/%APP%/%VERSION%/themes/");
 pref("extensions.dss.enabled", false);          // Dynamic Skin Switching                                               
 pref("extensions.dss.switchPending", false);    // Non-dynamic switch pending after next
                                                 // restart.
 
 pref("xpinstall.whitelist.add", "update.mozilla.org");
 pref("xpinstall.whitelist.add.103", "addons.mozilla.org");
 
 pref("keyword.enabled", true);
@@ -177,24 +177,35 @@ pref("browser.shell.checkDefaultBrowser"
 
 // 0 = blank, 1 = home (browser.startup.homepage), 2 = last visited page, 3 = resume previous browser session
 // The behavior of option 3 is detailed at: http://wiki.mozilla.org/Session_Restore
 pref("browser.startup.page",                1);
 pref("browser.startup.homepage",            "resource:/browserconfig.properties");
 
 pref("browser.cache.disk.capacity",         50000);
 pref("browser.enable_automatic_image_resizing", true);
+pref("browser.chrome.site_icons", true);
+pref("browser.chrome.favicons", true);
+pref("browser.formfill.enable", true);
+pref("browser.warnOnQuit", true);
+
+#ifdef XP_UNIX
+pref("browser.urlbar.clickSelectsAll", false);
+#else
+pref("browser.urlbar.clickSelectsAll", true);
+#endif
+#ifdef UNIX_BUT_NOT_MAC
+pref("browser.urlbar.doubleClickSelectsAll", true);
+#else
+pref("browser.urlbar.doubleClickSelectsAll", false);
+#endif
 pref("browser.urlbar.autoFill", false);
 pref("browser.urlbar.matchOnlyTyped", false);
 pref("browser.urlbar.hideProtocols", "");
 pref("browser.urlbar.animateBlend", true);
-pref("browser.chrome.site_icons", true);
-pref("browser.chrome.favicons", true);
-pref("browser.formfill.enable", true);
-pref("browser.warnOnQuit", true);
 
 pref("browser.download.useDownloadDir", true);
 pref("browser.download.folderList", 0);
 pref("browser.download.manager.showAlertOnComplete", true);
 pref("browser.download.manager.showAlertInterval", 2000);
 pref("browser.download.manager.retention", 2);
 pref("browser.download.manager.showWhenStarting", true);
 pref("browser.download.manager.useWindow", true);
@@ -229,16 +240,17 @@ pref("browser.search.update.log", false)
 pref("browser.search.updateinterval", 6);
 
 // enable search suggestions by default
 pref("browser.search.suggest.enabled", true);
 
 pref("browser.history.grouping", "day");
 pref("browser.history.showSessions", false);
 pref("browser.sessionhistory.max_entries", 50);
+pref("browser.history_expire_days", 180);
 
 // handle external links
 // 0=default window, 1=current window/tab, 2=new window, 3=new tab in most recent window
 pref("browser.link.open_external", 3);
 
 // handle links targeting new windows
 pref("browser.link.open_newwindow", 3);
 
@@ -402,22 +414,16 @@ pref("network.protocol-handler.expose.nn
 
 // Default security warning dialogs to show once.
 pref("security.warn_entering_secure.show_once", true);
 pref("security.warn_entering_weak.show_once", true);
 pref("security.warn_leaving_secure.show_once", true);
 pref("security.warn_viewing_mixed.show_once", true);
 pref("security.warn_submit_insecure.show_once", true);
 
-#ifdef XP_UNIX
-pref("browser.urlbar.clickSelectsAll", false);
-#else
-pref("browser.urlbar.clickSelectsAll", true);
-#endif
-
 pref("accessibility.typeaheadfind", false);
 pref("accessibility.typeaheadfind.timeout", 5000);
 pref("accessibility.typeaheadfind.linksonly", false);
 pref("accessibility.typeaheadfind.flashBar", 1);
 
 // Disable the default plugin for firefox
 pref("plugin.default_plugin_disabled", true);
 
@@ -487,17 +493,17 @@ pref("browser.contentHandlers.types.5.ty
 pref("browser.feeds.handler", "ask");
 
 #ifdef MOZ_SAFE_BROWSING
 // Safe browsing does nothing unless both these prefs are set.
 pref("browser.safebrowsing.enabled", true);
 pref("browser.safebrowsing.remoteLookups", false);
 
 // Non-enhanced mode (local url lists) URL list to check for updates
-pref("browser.safebrowsing.provider.0.updateURL", "http://sb.google.com/safebrowsing/update?client={moz:client}&appver={moz:version}&");
+pref("browser.safebrowsing.provider.0.updateURL", "http://sb.google.com/safebrowsing/downloads?client={moz:client}&appver={moz:version}&pver=2.0");
 
 pref("browser.safebrowsing.dataProvider", 0);
 
 // Does the provider name need to be localizable?
 pref("browser.safebrowsing.provider.0.name", "Google");
 pref("browser.safebrowsing.provider.0.lookupURL", "http://sb.google.com/safebrowsing/lookup?sourceid=firefox-antiphish&features=TrustRank&client={moz:client}&appver={moz:version}&");
 pref("browser.safebrowsing.provider.0.keyURL", "https://sb-ssl.google.com/safebrowsing/getkey?client={moz:client}&");
 pref("browser.safebrowsing.provider.0.reportURL", "http://sb.google.com/safebrowsing/report?");
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -1092,27 +1092,31 @@ function delayedStartup()
   // Setup click-and-hold gestures access to the session history
   // menus if global click-and-hold isn't turned on
   if (!getBoolPref("ui.click_hold_context_menus", false))
     SetClickAndHoldHandlers();
 #endif
 
   // Initialize the microsummary service by retrieving it, prompting its factory
   // to create its singleton, whose constructor initializes the service.
-  Cc["@mozilla.org/microsummary/service;1"].getService(Ci.nsIMicrosummaryService);
+  try {
+    Cc["@mozilla.org/microsummary/service;1"].getService(Ci.nsIMicrosummaryService);
+  } catch (ex) {
+    Components.utils.reportError("Failed to init microsummary service:\n" + ex);
+  }
 
   // Initialize the content pref event sink and the text zoom setting.
   // We do this before the session restore service gets initialized so we can
   // apply text zoom settings to tabs restored by the session restore service.
   try {
     ContentPrefSink.init();
     TextZoom.init();
   }
   catch(ex) {
-    Components.utils.reportError(ex);
+    Components.utils.reportError("Failed to init content pref service:\n" + ex);
   }
 
   // initialize the session-restore service (in case it's not already running)
   if (document.documentElement.getAttribute("windowtype") == "navigator:browser") {
     try {
       var ss = Cc["@mozilla.org/browser/sessionstore;1"].
                getService(Ci.nsISessionStore);
       ss.init(window);
@@ -2167,17 +2171,17 @@ var urlbarObserver = {
     },
   onDrop: function (aEvent, aXferData, aDragSession)
     {
       var url = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType);
 
       // The URL bar automatically handles inputs with newline characters,
       // so we can get away with treating text/x-moz-url flavours as text/unicode.
       if (url) {
-        getBrowser().dragDropSecurityCheck(aEvent, aDragSession, url);
+        nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
 
         try {
           gURLBar.value = url;
           const nsIScriptSecMan = Components.interfaces.nsIScriptSecurityManager;
           urlSecurityCheck(gURLBar.value,
                            gBrowser.contentPrincipal,
                            nsIScriptSecMan.DISALLOW_INHERIT_PRINCIPAL);
           handleURLBarCommand();
@@ -2512,17 +2516,17 @@ var newTabButtonObserver = {
     },
   onDrop: function (aEvent, aXferData, aDragSession)
     {
       var xferData = aXferData.data.split("\n");
       var draggedText = xferData[0] || xferData[1];
       var postData = {};
       var url = getShortcutOrURI(draggedText, postData);
       if (url) {
-        getBrowser().dragDropSecurityCheck(aEvent, aDragSession, url);
+        nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
         // allow third-party services to fixup this URL
         openNewTabWith(url, null, postData.value, aEvent, true);
       }
     },
   getSupportedFlavours: function ()
     {
       var flavourSet = new FlavourSet();
       flavourSet.appendFlavour("text/unicode");
@@ -2548,17 +2552,17 @@ var newWindowButtonObserver = {
     },
   onDrop: function (aEvent, aXferData, aDragSession)
     {
       var xferData = aXferData.data.split("\n");
       var draggedText = xferData[0] || xferData[1];
       var postData = {};
       var url = getShortcutOrURI(draggedText, postData);
       if (url) {
-        getBrowser().dragDropSecurityCheck(aEvent, aDragSession, url);
+        nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
         // allow third-party services to fixup this URL
         openNewWindowWith(url, null, postData.value, true);
       }
     },
   getSupportedFlavours: function ()
     {
       var flavourSet = new FlavourSet();
       flavourSet.appendFlavour("text/unicode");
@@ -2584,17 +2588,17 @@ var goButtonObserver = {
     },
   onDrop: function (aEvent, aXferData, aDragSession)
     {
       var xferData = aXferData.data.split("\n");
       var draggedText = xferData[0] || xferData[1];
       var postData = {};
       var url = getShortcutOrURI(draggedText, postData);
       try {
-        getBrowser().dragDropSecurityCheck(aEvent, aDragSession, url);
+        nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
         urlSecurityCheck(url,
                          gBrowser.contentPrincipal,
                          Ci.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL);
         loadURI(url, null, postData.value, true);
       } catch (ex) {}
     },
   getSupportedFlavours: function ()
     {
@@ -2623,17 +2627,17 @@ var DownloadsButtonDNDObserver = {
     statusTextFld.label = "";
   },
 
   onDrop: function (aEvent, aXferData, aDragSession)
   {
     var split = aXferData.data.split("\n");
     var url = split[0];
     if (url != aXferData.data) {  //do nothing, not a valid URL
-      getBrowser().dragDropSecurityCheck(aEvent, aDragSession, url);
+      nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
 
       var name = split[1];
       saveURL(url, name, null, true, true);
     }
   },
   getSupportedFlavours: function ()
   {
     var flavourSet = new FlavourSet();
@@ -3420,17 +3424,17 @@ nsBrowserStatusHandler.prototype =
     if (document.tooltipNode) {
       // Optimise for the common case
       if (aWebProgress.DOMWindow == content) {
         document.getElementById("aHTMLTooltip").hidePopup();
         document.tooltipNode = null;
       }
       else {
         for (var tooltipWindow =
-               document.tooltipNode.target.ownerDocument.defaultView;
+               document.tooltipNode.ownerDocument.defaultView;
              tooltipWindow != tooltipWindow.parent;
              tooltipWindow = tooltipWindow.parent) {
           if (tooltipWindow == aWebProgress.DOMWindow) {
             document.getElementById("aHTMLTooltip").hidePopup();
             document.tooltipNode = null;
             break;
           }
         }
@@ -3614,26 +3618,37 @@ nsBrowserStatusHandler.prototype =
     return true;
   },
 
   onSecurityChange : function(aWebProgress, aRequest, aState)
   {
     const wpl = Components.interfaces.nsIWebProgressListener;
     this.securityButton.removeAttribute("label");
 
-    switch (aState) {
+    const wpl_security_bits = wpl.STATE_IS_SECURE |
+                              wpl.STATE_IS_BROKEN |
+                              wpl.STATE_IS_INSECURE |
+                              wpl.STATE_SECURE_HIGH |
+                              wpl.STATE_SECURE_MED |
+                              wpl.STATE_SECURE_LOW;
+
+    /* aState is defined as a bitmask that may be extended in the future.
+     * We filter out any unknown bits before testing for known values.
+     */
+    switch (aState & wpl_security_bits) {
       case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_HIGH:
         this.securityButton.setAttribute("level", "high");
         if (this.urlBar)
           this.urlBar.setAttribute("level", "high");
         try {
           this.securityButton.setAttribute("label",
             gBrowser.contentWindow.location.host);
         } catch(exception) {}
         break;
+      case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_MED:
       case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_LOW:
         this.securityButton.setAttribute("level", "low");
         if (this.urlBar)
           this.urlBar.setAttribute("level", "low");
         try {
           this.securityButton.setAttribute("label",
             gBrowser.contentWindow.location.host);
         } catch(exception) {}
@@ -4319,17 +4334,17 @@ var contentAreaDNDObserver = {
 
       // valid urls don't contain spaces ' '; if we have a space it
       // isn't a valid url, or if it's a javascript: or data: url,
       // bail out
       if (!url || !url.length || url.indexOf(" ", 0) != -1 ||
           /^\s*(javascript|data):/.test(url))
         return;
 
-      getBrowser().dragDropSecurityCheck(aEvent, aDragSession, url);
+      nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
 
       switch (document.documentElement.getAttribute('windowtype')) {
         case "navigator:browser":
           var postData = { };
           var uri = getShortcutOrURI(url, postData);
           loadURI(uri, null, postData.value, false);
           break;
         case "navigator:view-source":
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -196,32 +196,30 @@
 
       <toolbarbutton id="home-button" class="toolbarbutton-1 chromeclass-toolbar-additional"
                      label="&homeButton.label;"
                      ondragover="nsDragAndDrop.dragOver(event, homeButtonObserver);"
                      ondragdrop="nsDragAndDrop.drop(event, homeButtonObserver);"
                      ondragexit="nsDragAndDrop.dragExit(event, homeButtonObserver);"
                      onclick="BrowserHomeClick(event);"/>
 
-      <toolbaritem id="urlbar-container" align="center" flex="400"
+      <toolbaritem id="urlbar-container" align="center" flex="400" persist="width"
                    title="&locationItem.title;" class="chromeclass-location">
         <hbox id="urlbar-button-box" flex="1">
             <textbox id="urlbar" flex="1"
                      chromedir="&locale.dir;"
                      type="autocomplete"
                      autocompletesearch="history" 
                      autocompletepopup="PopupAutoComplete"
                      completeselectedindex="true"
                      tabscrolling="true"
                      showcommentcolumn="true"
                      enablehistory="true"
-#ifndef MOZILLA_1_8_BRANCH
-# bug 23485
+                     maxrows="10"
                      newlines="stripsurroundingwhitespace"
-#endif
                      oninput="gBrowser.userTypedValue = this.value"
                      ontextentered="return handleURLBarCommand(param);"
                      ontextreverted="return handleURLBarRevert();">
               <deck id="page-proxy-deck" onclick="PageProxyClickHandler(event);">
                 <image id="page-proxy-button"
                         ondraggesture="PageProxyDragGesture(event);"
                         tooltiptext="&proxyIcon.tooltip;"/>
                 <image id="page-proxy-favicon" validate="never"
@@ -283,17 +281,17 @@
                            ondragexit="nsDragAndDrop.dragExit(event, goButtonObserver);"
                            tooltiptext="&goEndCap.tooltip;"/>
           </stack>
         </hbox>
       </toolbaritem>
 
       <toolbaritem id="search-container" title="&searchItem.title;" 
                    align="center" class="chromeclass-toolbar-additional"
-                   flex="100">
+                   flex="100" persist="width">
         <searchbar id="searchbar" flex="1" chromedir="&locale.dir;"/>
       </toolbaritem>
 
       <toolbarbutton id="print-button" class="toolbarbutton-1 chromeclass-toolbar-additional"
                      label="&printButton.label;" command="cmd_print"
                      tooltiptext="&printButton.tooltip;"/>
 
       <toolbaritem id="throbber-box" title="&throbberItem.title;" align="center" pack="center">
@@ -363,19 +361,19 @@
 
     </toolbarpalette>
 
     <toolbar id="nav-bar" class="toolbar-primary chromeclass-toolbar"
              toolbarname="&navbarCmd.label;" accesskey="&navbarCmd.accesskey;"
              fullscreentoolbar="true" mode="icons" 
              customizable="true"
 #ifdef XP_MACOSX
-             defaultset="back-button,forward-button,reload-button,stop-button,home-button,urlbar-container,go-container,search-container,throbber-box"
+             defaultset="back-button,forward-button,reload-button,stop-button,home-button,urlbar-container,go-container,splitter,search-container,throbber-box"
 #else
-             defaultset="back-button,forward-button,reload-button,stop-button,home-button,urlbar-container,go-container,search-container,fullscreenflex,window-controls"
+             defaultset="back-button,forward-button,reload-button,stop-button,home-button,urlbar-container,go-container,splitter,search-container,fullscreenflex,window-controls"
 #endif
              context="toolbar-context-menu">
 #ifndef XP_MACOSX
       <hbox id="fullscreenflex" flex="1" hidden="true" fullscreencontrol="true"/>
       <hbox id="window-controls" hidden="true" fullscreencontrol="true">
         <toolbarbutton id="minimize-button" class="toolbarbutton-1"
                        tooltiptext="&fullScreenMinimize.tooltip;"
                        oncommand="window.minimize();"/>
--- a/browser/base/content/nsContextMenu.js
+++ b/browser/base/content/nsContextMenu.js
@@ -554,17 +554,20 @@ nsContextMenu.prototype = {
     var win = this.target.ownerDocument.defaultView;
     if (win) {
       var isEditable = false;
       try {
         var editingSession = win.QueryInterface(Ci.nsIInterfaceRequestor)
                                 .getInterface(Ci.nsIWebNavigation)
                                 .QueryInterface(Ci.nsIInterfaceRequestor)
                                 .getInterface(Ci.nsIEditingSession);
-        isEditable = editingSession.windowIsEditable(win);
+        if (editingSession.windowIsEditable(win) &&
+            this.getComputedStyle(this.target, "-moz-user-modify") == "read-write") {
+          isEditable = true;
+        }
       }
       catch(ex) {
         // If someone built with composer disabled, we can't get an editing session.
       }
 
       if (isEditable) {
         this.onTextInput       = true;
         this.onKeywordField    = false;
@@ -582,19 +585,19 @@ nsContextMenu.prototype = {
         this.showItem("spell-check-enabled", canSpell);
         this.showItem("spell-separator", canSpell);
       }
     }
   },
 
   // Returns the computed style attribute for the given element.
   getComputedStyle: function(aElem, aProp) {
-    return elem.ownerDocument
-               .defaultView
-               .getComputedStyle(aElem, "").getPropertyValue(prop);
+    return aElem.ownerDocument
+                .defaultView
+                .getComputedStyle(aElem, "").getPropertyValue(aProp);
   },
 
   // Returns a "url"-type computed style attribute value, with the url() stripped.
   getComputedURL: function(aElem, aProp) {
     var url = aElem.ownerDocument
                    .defaultView.getComputedStyle(aElem, "")
                    .getPropertyCSSValue(aProp);
     return url.primitiveType == CSSPrimitiveValue.CSS_URI ?
--- a/browser/base/content/pageinfo/feeds.js
+++ b/browser/base/content/pageinfo/feeds.js
@@ -57,18 +57,17 @@ function initFeedTab()
         type = feedTypes[type];
       else
         type = feedTypes["application/rss+xml"];
       addRow(feed.title, type, feed.href);
     }
   }
 
   var feedListbox = document.getElementById("feedListbox");
-  if (feedListbox.getRowCount() > 0)
-    document.getElementById("feedTab").hidden = false;
+  document.getElementById("feedTab").hidden = feedListbox.getRowCount() == 0;
 }
 
 function onSubscribeFeed()
 {
   var listbox = document.getElementById("feedListbox");
   openUILink(listbox.selectedItem.getAttribute("feedURL"),
              null, false, true, false, null);
 }
--- a/browser/base/content/pageinfo/pageInfo.js
+++ b/browser/base/content/pageinfo/pageInfo.js
@@ -238,19 +238,26 @@ const XHTMLre = RegExp(XHTMLNSre + "|" +
  * These arrays are used to hold callbacks that Page Info will call at
  * various stages. Use them by simply appending a function to them.
  * For example, add a function to onLoadRegistry by invoking
  *   "onLoadRegistry.push(XXXLoadFunc);"
  * The XXXLoadFunc should be unique to the overlay module, and will be
  * invoked as "XXXLoadFunc();"
  */
 
-// These functions are called once when the Page Info window is opened.
+// These functions are called to build the data displayed in the Page
+// Info window. The global variables gDocument and gWindow are set.
 var onLoadRegistry = [ ];
 
+// These functions are called to remove old data still displayed in
+// the window when the document whose information is displayed
+// changes. For example, at this time, the list of images of the Media
+// tab is cleared.
+var onResetRegistry = [ ];
+
 // These are called once for each subframe of the target document and
 // the target document itself. The frame is passed as an argument.
 var onProcessFrame = [ ];
 
 // These functions are called once for each element (in all subframes, if any)
 // in the target document. The element is passed as an argument.
 var onProcessElement = [ ];
 
@@ -289,50 +296,84 @@ function onLoadPageInfo()
   else {
     if ("gBrowser" in window.opener)
       gWindow = window.opener.gBrowser.contentWindow;
     else
       gWindow = window.opener.frames[0];
     gDocument = gWindow.document;
   }
 
-  var titleFormat = gWindow != gWindow.top ? "pageInfo.frame.title"
-                                           : "pageInfo.page.title";
-  document.title = gBundle.getFormattedString(titleFormat, [gDocument.location]);
-
-  document.getElementById("main-window").setAttribute("relatedUrl", gDocument.location);
-
-  // do the easy stuff first
-  makeGeneralTab();
-
   // init media view
   var imageTree = document.getElementById("imagetree");
   imageTree.view = gImageView;
 
-  // and then the hard stuff
-  makeTabs(gDocument, gWindow);
-
-  initFeedTab();
-  onLoadPermission();
-
-  /* Call registered overlay init functions */
-  onLoadRegistry.map(function(func) { func(); });
+  // build the content
+  loadPageInfo();
 
   /* Select the requested tab, if the name is specified */
   var initialTab = "general";
   if ("arguments" in window && window.arguments.length >= 1 &&
        window.arguments[0] && window.arguments[0].initialTab)
     initialTab = window.arguments[0].initialTab;
   var radioGroup = document.getElementById("viewGroup");
   initialTab = document.getElementById(initialTab + "Tab") || document.getElementById("generalTab");
   radioGroup.selectedItem = initialTab;
   radioGroup.selectedItem.doCommand();
   radioGroup.focus();
 }
 
+function loadPageInfo()
+{
+  var titleFormat = gWindow != gWindow.top ? "pageInfo.frame.title"
+                                           : "pageInfo.page.title";
+  document.title = gBundle.getFormattedString(titleFormat, [gDocument.location]);
+
+  document.getElementById("main-window").setAttribute("relatedUrl", gDocument.location);
+
+  // do the easy stuff first
+  makeGeneralTab();
+
+  // and then the hard stuff
+  makeTabs(gDocument, gWindow);
+
+  initFeedTab();
+  onLoadPermission();
+
+  /* Call registered overlay init functions */
+  onLoadRegistry.map(function(func) { func(); });
+}
+
+function resetPageInfo()
+{
+  /* Reset Meta tags part */
+  gMetaView.clear();
+
+  /* Reset Media tab */
+  var mediaTab = document.getElementById("mediaTab");
+  if (!mediaTab.hidden) {
+    var os = Components.classes["@mozilla.org/observer-service;1"]
+                       .getService(Components.interfaces.nsIObserverService);
+    os.removeObserver(imagePermissionObserver, "perm-changed");
+    mediaTab.hidden = true;
+  }
+  gImageView.clear();
+  gImageHash = {};
+
+  /* Reset Feeds Tab */
+  var feedListbox = document.getElementById("feedListbox");
+  while (feedListbox.firstChild)
+    feedListbox.removeChild(feedListbox.firstChild);
+
+  /* Call registered overlay reset functions */
+  onResetRegistry.map(function(func) { func(); });
+
+  /* And let's rebuild the data */
+  loadPageInfo();
+}
+
 function onUnloadPageInfo()
 {
   if (!document.getElementById("mediaTab").hidden) {
     var os = Components.classes["@mozilla.org/observer-service;1"]
                        .getService(Components.interfaces.nsIObserverService);
     os.removeObserver(imagePermissionObserver, "perm-changed");
   }
 
@@ -405,31 +446,32 @@ function makeGeneralTab()
   // get the document characterset
   var encoding = gDocument.characterSet;
   document.getElementById("encodingtext").value = encoding;
 
   // get the meta tags
   var metaNodes = gDocument.getElementsByTagName("meta");
   var length = metaNodes.length;
 
-  if (!length) {
-    var metaGroup = document.getElementById("metaTags");
+  var metaGroup = document.getElementById("metaTags");
+  if (!length)
     metaGroup.collapsed = true;
-  }
   else {
     var metaTagsCaption = document.getElementById("metaTagsCaption");
     if (length == 1)
       metaTagsCaption.label = gBundle.getString("generalMetaTag");
     else
       metaTagsCaption.label = gBundle.getFormattedString("generalMetaTags", [length]);
     var metaTree = document.getElementById("metatree");
     metaTree.treeBoxObject.view = gMetaView;
 
     for (var i = 0; i < length; i++)
       gMetaView.addRow([metaNodes[i].name || metaNodes[i].httpEquiv, metaNodes[i].content]);
+
+    metaGroup.collapsed = false;
   }
 
   // get the date of last modification
   var modifiedText = formatDate(gDocument.lastModified, gStrings.notSet);
   document.getElementById("modifiedtext").value = modifiedText;
 
   // get cache info
   var cacheKey = url.replace(/#.*$/, "");
--- a/browser/base/content/pageinfo/permissions.js
+++ b/browser/base/content/pageinfo/permissions.js
@@ -81,30 +81,32 @@ var permissionObserver = {
 };
 
 function onLoadPermission()
 {
   gPrefs = Components.classes[PREFERENCES_CONTRACTID]
                      .getService(Components.interfaces.nsIPrefBranch2);
 
   var uri = gDocument.documentURIObject;
+  var permTab = document.getElementById("permTab");
   if(/^https?/.test(uri.scheme)) {
     gPermURI = uri;
     var hostText = document.getElementById("hostText");
     hostText.value = gPermURI.host;
 
     for (var i in gPermObj)
       initRow(i);
     var os = Components.classes["@mozilla.org/observer-service;1"]
                        .getService(Components.interfaces.nsIObserverService);
     os.addObserver(permissionObserver, "perm-changed", false);
     onUnloadRegistry.push(onUnloadPermission);
+    permTab.hidden = false;
   }
   else
-    document.getElementById("permTab").hidden = true;
+    permTab.hidden = true;
 }
 
 function onUnloadPermission()
 {
   var os = Components.classes["@mozilla.org/observer-service;1"]
                      .getService(Components.interfaces.nsIObserverService);
   os.removeObserver(permissionObserver, "perm-changed");
 }
--- a/browser/base/content/pageinfo/security.js
+++ b/browser/base/content/pageinfo/security.js
@@ -157,20 +157,24 @@ var security = {
 };
 
 function securityOnLoad() {
   var bundle = srGetStrBundle("chrome://pippki/locale/pippki.properties");
   var pageInfoBundle = document.getElementById("pageinfobundle");
 
   var info = security._getSecurityInfo();
   if (!info) {
-    document.getElementById("securityTab").setAttribute("hidden", true);
+    document.getElementById("securityTab").hidden = true;
     document.getElementById("securityBox").collapsed = true;
     return;
   }
+  else {
+    document.getElementById("securityTab").hidden = false;
+    document.getElementById("securityBox").collapsed = false;
+  }
 
   /* Set Identity section text */
   setText("security-identity-domain-value", info.hostName);
   
   // FIXME - Should only be showing the next two if the cert is EV.  Waiting on
   // bug 374336
   var owner, verifier, generalPageIdentityString;
   if (info.cert && !info.isBroken) {
@@ -193,25 +197,25 @@ function securityOnLoad() {
     generalPageIdentityString = owner;
   }
 
   setText("security-identity-owner-value", owner);
   setText("security-identity-verifier-value", verifier);
   setText("general-security-identity", generalPageIdentityString);
 
   /* Manage the View Cert button*/
+  var viewCert = document.getElementById("security-view-cert");
   if (info.cert) {
     var viewText = pageInfoBundle.getString("securityCertText");
     setText("security-view-text", viewText);
     security._cert = info.cert;
+    viewCert.collapsed = false;
   }
-  else {
-    var viewCert = document.getElementById("security-view-cert");
+  else
     viewCert.collapsed = true;
-  }
 
   /* Set Privacy & History section text */
   var yesStr = pageInfoBundle.getString("yes");
   var noStr = pageInfoBundle.getString("no");
 
   setText("security-privacy-cookies-value",
           hostHasCookies(info.hostName) ? yesStr : noStr);
   setText("security-privacy-passwords-value",
--- a/browser/base/content/test/Makefile.in
+++ b/browser/base/content/test/Makefile.in
@@ -43,9 +43,9 @@ relativesrcdir  = browser/base/content/t
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES = 	test_feed_discovery.html \
 	   feed_discovery.html \
     $(NULL)
 
 libs:: $(_TEST_FILES)
-	$(INSTALL) $^ $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
+	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -81,53 +81,56 @@
 
       <xul:dropmarker anonid="historydropmarker" class="autocomplete-history-dropmarker"
                       allowevents="true"
                       xbl:inherits="open,enablehistory"/>
 
       <xul:popupset anonid="popupset" class="autocomplete-result-popupset"/>
     </content>
 
-    <implementation implements="nsIObserver">
+    <implementation implements="nsIObserver, nsIDOMEventListener">
       <constructor><![CDATA[
         this._ioService = Components.classes["@mozilla.org/network/io-service;1"]
                                     .getService(Components.interfaces.nsIIOService);
         this._prefs = Components.classes["@mozilla.org/preferences-service;1"]
                                 .getService(Components.interfaces.nsIPrefService)
                                 .getBranch("browser.urlbar.")
                                 .QueryInterface(Components.interfaces.nsIPrefBranch2);
 
         this._prefs.addObserver("", this, false);
         this._hideProtocols = this._prefs.getCharPref("hideProtocols").split(" ");
         this._animateBlend = this._prefs.getBoolPref("animateBlend");
         this.clickSelectsAll = this._prefs.getBoolPref("clickSelectsAll");
+        this.doubleClickSelectsAll = this._prefs.getBoolPref("doubleClickSelectsAll");
         this.completeDefaultIndex = this._prefs.getBoolPref("autoFill");
 
         this._inputBox = document.getAnonymousElementByAttribute(this, "anonid", "textbox-input-box");
         this._presentationBox = document.getAnonymousElementByAttribute(this, "anonid", "presentation-box");
         this._overflowEllipsis = document.getAnonymousElementByAttribute(this, "anonid", "overflow-ellipsis");
         this._prePath = document.getAnonymousElementByAttribute(this, "anonid", "prePath");
         this._protocol = document.getAnonymousElementByAttribute(this, "anonid", "protocol");
         this._subDomain = document.getAnonymousElementByAttribute(this, "anonid", "subdomain");
         this._domain = document.getAnonymousElementByAttribute(this, "anonid", "domain");
         this._port = document.getAnonymousElementByAttribute(this, "anonid", "port");
         this._path = document.getAnonymousElementByAttribute(this, "anonid", "path");
         this._urlTooltip = document.getElementById("urlTooltip");
 
         this.inputField.controllers.insertControllerAt(0, this._copyCutController);
+        this.inputField.addEventListener("mousedown", this, false);
 
         this._blendingTimers = [];
       ]]></constructor>
 
       <destructor><![CDATA[
         this._prefs.removeObserver("", this);
         this._prefs = null;
         this._ioService = null;
         this._tldService = null;
         this.inputField.controllers.removeController(this._copyCutController);
+        this.inputField.removeEventListener("mousedown", this, false);
       ]]></destructor>
 
       <!-- initially empty fields:
         <field name="_uri"/>
         <field name="_protocolHidden"/>
         <field name="_focused"/>
         <field name="_mouseover"/>
         <field name="_tooltipTimer"/>
@@ -260,21 +263,19 @@
       </method>
 
       <method name="_initPrettyView">
         <body><![CDATA[
           this._plain = false;
           this._protocol.hidden = false;
           this._presentationBox.hidden = false;
           this._prePath.width = "";
-          this.removeAttribute("protocolhidden");
           if (this._protocolHidden) {
             this._prePath.width = this._prePath.boxObject.width;
             this._protocol.hidden = true;
-            this.setAttribute("protocolhidden","true");
           }
         ]]></body>
       </method>
 
       <method name="_prettyView">
         <parameter name="aAnimateBlend"/>
         <body><![CDATA[
           if (!this._uri) {
@@ -403,28 +404,41 @@
             switch(aData) {
               case "hideProtocols":
                 this._hideProtocols = this._prefs.getCharPref(aData).split(" ");
                 this._syncValue();
                 if (!this.plain)
                   this._prettyView(false);
                 break;
               case "clickSelectsAll":
-                this.clickSelectsAll = this._prefs.getBoolPref(aData);
+              case "doubleClickSelectsAll":
+                this[aData] = this._prefs.getBoolPref(aData);
                 break;
               case "autoFill":
                 this.completeDefaultIndex = this._prefs.getBoolPref(aData);
                 break;
               case "animateBlend":
                 this._animateBlend = this._prefs.getBoolPref(aData);
                 break;
             }
           }
         ]]></body>
       </method>
+
+      <method name="handleEvent">
+        <parameter name="aEvent"/>
+        <body><![CDATA[
+          if (aEvent.type == "mousedown" &&
+              aEvent.button == 0 && aEvent.detail == 2 &&
+              this.doubleClickSelectsAll) {
+            this.inputField.select();
+            aEvent.preventDefault();
+          }
+        ]]></body>
+      </method>
     </implementation>
 
     <handlers>
       <handler event="input"
                action="this._syncValue();"/>
 
       <handler event="mousemove"><![CDATA[
         if (!this._focused && this._contentIsCropped)
--- a/browser/build.mk
+++ b/browser/build.mk
@@ -51,8 +51,11 @@ endif
 
 tier_app_dirs += browser
 
 installer:
 	@$(MAKE) -C browser/installer installer
 
 package:
 	@$(MAKE) -C browser/installer
+
+install::
+	@$(MAKE) -C browser/installer install
--- a/browser/components/build/Makefile.in
+++ b/browser/components/build/Makefile.in
@@ -73,17 +73,17 @@ endif
 ifdef MOZ_SAFE_BROWSING
 REQUIRES += safebrowsing
 LOCAL_INCLUDES += -I$(srcdir)/../safebrowsing/src
 SHARED_LIBRARY_LIBS += ../safebrowsing/src/$(LIB_PREFIX)safebrowsing_s.$(LIB_SUFFIX)
 endif
 
 EXTRA_DSO_LDOPTS += \
 	$(call EXPAND_LIBNAME_PATH,unicharutil_external_s,$(LIBXUL_DIST)/lib) \
-	$(LIBXUL_DIST)/../modules/libreg/src/$(LIB_PREFIX)mozreg_s.$(LIB_SUFFIX) \
+	$(LIBXUL_DIST)/lib/$(LIB_PREFIX)mozreg_s.$(LIB_SUFFIX) \
 	$(MOZ_JS_LIBS) \
 	$(LIBXUL_DIST)/lib/$(LIB_PREFIX)xpcomglue_s.$(LIB_SUFFIX) \
 	$(MOZ_COMPONENT_LIBS) \
 	$(NULL)
 
 # Mac: Need to link with CoreFoundation for Mac Migrators (PList reading code)
 # GTK2: Need to link with glib for GNOME shell service
 ifneq (,$(filter mac cocoa gtk2,$(MOZ_WIDGET_TOOLKIT)))
--- a/browser/components/microsummaries/src/nsMicrosummaryService.js
+++ b/browser/components/microsummaries/src/nsMicrosummaryService.js
@@ -53,17 +53,17 @@ const NS_ERROR_DOM_BAD_URI = NS_ERROR_MO
 // How often to check for microsummaries that need updating, in milliseconds.
 const CHECK_INTERVAL = 15 * 1000; // 15 seconds
 
 const MICSUM_NS = new Namespace("http://www.mozilla.org/microsummaries/0.1");
 const XSLT_NS = new Namespace("http://www.w3.org/1999/XSL/Transform");
 
 const FIELD_MICSUM_GEN_URI    = "microsummary/generatorURI";
 const FIELD_MICSUM_EXPIRATION = "microsummary/expiration";
-const FIELD_GENERATED_TITLE   = "bookmarks/generatedTitle";
+const FIELD_STATIC_TITLE      = "bookmarks/staticTitle";
 const FIELD_CONTENT_TYPE      = "bookmarks/contentType";
 
 const MAX_SUMMARY_LENGTH = 4096;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 
 function MicrosummaryService() { this._init() }
 
@@ -224,31 +224,33 @@ MicrosummaryService.prototype = {
       }
       catch(ex) {
         Cu.reportError(ex);
       }
     }
   },
   
   _updateMicrosummary: function MSS__updateMicrosummary(bookmarkID, microsummary) {
-    // Get the current live title to see if it's actually changed.
-    var oldValue = null;
-    if (this._hasField(bookmarkID, FIELD_GENERATED_TITLE))
-      oldValue = this._getField(bookmarkID, FIELD_GENERATED_TITLE);
+    var title = this._getTitle(bookmarkID);
+
+    // Ensure the user-given title is cached
+    if (!this._hasField(bookmarkID, FIELD_STATIC_TITLE))
+      this._setField(bookmarkID, FIELD_STATIC_TITLE, title);
 
     // A string identifying the bookmark to use when logging the update.
     var bookmarkIdentity = bookmarkID;
 
-    if (oldValue == null || oldValue != microsummary.content) {
-      this._setField(bookmarkID, FIELD_GENERATED_TITLE, microsummary.content);
+    // Update if the microsummary differs from the current title.
+    if (!title || title != microsummary.content) {
+      this._setTitle(bookmarkID, microsummary.content);
       var subject = new LiveTitleNotificationSubject(bookmarkID, microsummary);
       LOG("updated live title for " + bookmarkIdentity +
-          " from '" + (oldValue == null ? "<no live title>" : oldValue) +
+          " from '" + (title == null ? "<no live title>" : title) +
           "' to '" + microsummary.content + "'");
-      this._obs.notifyObservers(subject, "microsummary-livetitle-updated", oldValue);
+      this._obs.notifyObservers(subject, "microsummary-livetitle-updated", title);
     }
     else {
       LOG("didn't update live title for " + bookmarkIdentity + "; it hasn't changed");
     }
 
     // Whether or not the title itself has changed, we still save any changes
     // to the update interval, since the interval represents how long to wait
     // before checking again for updates, and that can vary across updates,
@@ -550,17 +552,17 @@ MicrosummaryService.prototype = {
       var generator = this._localGenerators[genURISpec];
 
       if (generator.appliesToURI(pageURI)) {
         var microsummary = new Microsummary(pageURI, generator);
 
         // If this is the current microsummary for this bookmark, load the content
         // from the datastore so it shows up immediately in microsummary picking UI.
         if (bookmarkID != -1 && this.isMicrosummary(bookmarkID, microsummary))
-          microsummary._content = this._getField(bookmarkID, FIELD_GENERATED_TITLE);
+          microsummary._content = this._getTitle(bookmarkID);
 
         microsummaries.AppendElement(microsummary);
       }
     }
 
     // If a bookmark identifier has been provided, list its microsummary
     // synchronously, if any.
     if (bookmarkID != -1 && this.hasMicrosummary(bookmarkID)) {
@@ -655,16 +657,24 @@ MicrosummaryService.prototype = {
   _setField: function MSS__setField(aBookmarkId, aFieldName, aFieldValue) {
     this._ans.setItemAnnotation(aBookmarkId,
                                 aFieldName,
                                 aFieldValue,
                                 0,
                                 this._ans.EXPIRE_NEVER);
   },
 
+  _getTitle: function MSS_getTitle(aBookmarkId) {
+    return this._bms.getItemTitle(aBookmarkId);
+  },
+
+  _setTitle: function MSS_setTitle(aBookmarkId, aValue) {
+    this._bms.setItemTitle(aBookmarkId, aValue);
+  },
+
   _clearField: function MSS__clearField(aBookmarkId, aFieldName) {
     this._ans.removeItemAnnotation(aBookmarkId, aFieldName);
   },
 
   _hasField: function MSS__hasField(aBookmarkId, fieldName) {
     return this._ans.itemHasAnnotation(aBookmarkId, fieldName);
   },
 
@@ -736,39 +746,39 @@ MicrosummaryService.prototype = {
    */
   setMicrosummary: function MSS_setMicrosummary(bookmarkID, microsummary) {
     this._setField(bookmarkID, FIELD_MICSUM_GEN_URI, microsummary.generator.uri.spec);
 
     if (microsummary.content) {
       this._updateMicrosummary(bookmarkID, microsummary);
     }
     else {
-      // Display a static title initially (unless there's already one set)
-      if (!this._hasField(bookmarkID, FIELD_GENERATED_TITLE))
-        this._setField(bookmarkID, FIELD_GENERATED_TITLE,
-                       microsummary.generator.name || microsummary.generator.uri.spec);
-
+      // Use the bookmark's title for now and attempt an update
       this.refreshMicrosummary(bookmarkID);
     }
   },
 
   /**
    * Remove the current microsummary for the given bookmark.
    *
    * @param   bookmarkID
    *          the bookmark for which to remove the current microsummary
    *
    */
   removeMicrosummary: function MSS_removeMicrosummary(bookmarkID) {
+    // Restore the user's title
+    if (this._hasField(bookmarkID, FIELD_STATIC_TITLE))
+      this._setTitle(bookmarkID, this._getField(bookmarkID, FIELD_STATIC_TITLE));
+
     var fields = [FIELD_MICSUM_GEN_URI,
                   FIELD_MICSUM_EXPIRATION,
-                  FIELD_GENERATED_TITLE,
+                  FIELD_STATIC_TITLE,
                   FIELD_CONTENT_TYPE];
 
-    for ( var i = 0; i < fields.length; i++ ) {
+    for (let i = 0; i < fields.length; i++) {
       var field = fields[i];
       if (this._hasField(bookmarkID, field))
         this._clearField(bookmarkID, field);
     }
   },
 
   /**
    * Whether or not the given bookmark has a current microsummary.
--- a/browser/components/nsBrowserGlue.js
+++ b/browser/components/nsBrowserGlue.js
@@ -74,17 +74,17 @@ BrowserGlue.prototype = {
       case "browser:purge-session-history":
         // reset the console service's error buffer
         const cs = Cc["@mozilla.org/consoleservice;1"].
                    getService(Ci.nsIConsoleService);
         cs.logStringMessage(null); // clear the console (in case it's open)
         cs.reset();
         break;
       case "quit-application-requested":
-        this._onQuitRequest(subject);
+        this._onQuitRequest(subject, data);
         break;
       case "quit-application-granted":
         if (this._saveSession) {
           var prefBranch = Cc["@mozilla.org/preferences-service;1"].
                            getService(Ci.nsIPrefBranch);
           prefBranch.setBoolPref("browser.sessionstore.resume_session_once", true);
         }
         break;
@@ -182,17 +182,17 @@ BrowserGlue.prototype = {
       this.Sanitizer.onShutdown();
 
     } catch(ex) {
     } finally {
       appStartup.exitLastWindowClosingSurvivalArea();
     }
   },
 
-  _onQuitRequest: function(aCancelQuit)
+  _onQuitRequest: function(aCancelQuit, aQuitType)
   {
     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
              getService(Ci.nsIWindowMediator);
     var windowcount = 0;
     var pagecount = 0;
     var browserEnum = wm.getEnumerator("navigator:browser");
     while (browserEnum.hasMoreElements()) {
       windowcount++;
@@ -202,16 +202,19 @@ BrowserGlue.prototype = {
       if (tabbrowser)
         pagecount += tabbrowser.browsers.length;
     }
 
     this._saveSession = false;
     if (pagecount < 2)
       return;
 
+    if (aQuitType != "restart")
+      aQuitType = "quit";
+
     var prefBranch = Cc["@mozilla.org/preferences-service;1"].
                      getService(Ci.nsIPrefBranch);
     var showPrompt = true;
     try {
       if (prefBranch.getIntPref("browser.startup.page") == 3 ||
           prefBranch.getBoolPref("browser.sessionstore.resume_session_once"))
         showPrompt = false;
       else
@@ -221,38 +224,43 @@ BrowserGlue.prototype = {
     var buttonChoice = 0;
     if (showPrompt) {
       var bundleService = Cc["@mozilla.org/intl/stringbundle;1"].
                           getService(Ci.nsIStringBundleService);
       var quitBundle = bundleService.createBundle("chrome://browser/locale/quitDialog.properties");
       var brandBundle = bundleService.createBundle("chrome://branding/locale/brand.properties");
 
       var appName = brandBundle.GetStringFromName("brandShortName");
-      var quitDialogTitle = quitBundle.formatStringFromName("quitDialogTitle",
-                                                            [appName], 1);
-      var quitTitle = quitBundle.GetStringFromName("quitTitle");
+      var quitDialogTitle = quitBundle.formatStringFromName(aQuitType + "DialogTitle",
+                                                              [appName], 1);
+      var quitTitle = quitBundle.GetStringFromName(aQuitType + "Title");
       var cancelTitle = quitBundle.GetStringFromName("cancelTitle");
       var saveTitle = quitBundle.GetStringFromName("saveTitle");
       var neverAskText = quitBundle.GetStringFromName("neverAsk");
 
-      if (windowcount == 1)
-        var message = quitBundle.formatStringFromName("messageNoWindows",
-                                                      [appName], 1);
+      var message;
+      if (aQuitType == "restart")
+        message = quitBundle.formatStringFromName("messageRestart",
+                                                  [appName], 1);
+      else if (windowcount == 1)
+        message = quitBundle.formatStringFromName("messageNoWindows",
+                                                  [appName], 1);
       else
-        var message = quitBundle.formatStringFromName("message",
-                                                      [appName], 1);
+        message = quitBundle.formatStringFromName("message",
+                                                  [appName], 1);
 
       var promptService = Cc["@mozilla.org/embedcomp/prompt-service;1"].
                           getService(Ci.nsIPromptService);
 
       var flags = promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
                   promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1 +
-                  promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_2 +
                   promptService.BUTTON_POS_0_DEFAULT;
       var neverAsk = {value:false};
+      if (aQuitType != "restart")
+        flags += promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_2;
       buttonChoice = promptService.confirmEx(null, quitDialogTitle, message,
                                    flags, quitTitle, cancelTitle, saveTitle,
                                    neverAskText, neverAsk);
 
       switch (buttonChoice) {
       case 0:
         if (neverAsk.value)
           prefBranch.setBoolPref("browser.warnOnQuit", false);
--- a/browser/components/places/content/bookmarkProperties.js
+++ b/browser/components/places/content/bookmarkProperties.js
@@ -85,16 +85,17 @@
  *     - "siteURI"
  *     - "folder picker" - hides both the tree and the menu.
  *
  * window.arguments[0].performed is set to true if any transaction has
  * been performed by the dialog.
  */
 
 const LAST_USED_ANNO = "bookmarkPropertiesDialog/lastUsed";
+const STATIC_TITLE_ANNO = "bookmarks/staticTitle";
 
 // This doesn't include "static" special folders (first two menu items)
 const MAX_FOLDER_ITEM_IN_MENU_LIST = 5;
 
 const BOOKMARK_ITEM = 0;
 const BOOKMARK_FOLDER = 1;
 const LIVEMARK_CONTAINER = 2;
 
@@ -547,17 +548,24 @@ var BookmarkPropertiesPanel = {
     }
 
     return menuItem;
   },
 
   _initNamePicker: function BPP_initNamePicker() {
     var userEnteredNameField = this._element("userEnteredName");
     var namePicker = this._element("namePicker");
-    userEnteredNameField.label = this._itemTitle;
+    const annos = PlacesUtils.annotations;
+
+    if (annos.itemHasAnnotation(this._bookmarkId, STATIC_TITLE_ANNO)) {
+      userEnteredNameField.label = annos.getItemAnnotation(this._bookmarkId,
+                                                           STATIC_TITLE_ANNO);
+    }
+    else
+      userEnteredNameField.label = this._itemTitle;
 
     // Non-bookmark items always use the item-title itself
     if (this._itemType != BOOKMARK_ITEM || !this._bookmarkURI) {
       namePicker.selectedItem = userEnteredNameField;
       return;
     }
 
     var itemToSelect = userEnteredNameField;
@@ -1017,17 +1025,17 @@ var BookmarkPropertiesPanel = {
       this._folderTree.setAttribute("height", this._folderTreeHeight);
       this._folderTree.collapsed = true;
       resizeTo(window.outerWidth, window.outerHeight - this._folderTreeHeight);
     }
     else {
       expander.className = "up";
       expander.setAttribute("tooltiptext",
                             expander.getAttribute("tooltiptextup"));
-      document.documentElement.buttons = "accept,cancel, extra2";
+      document.documentElement.buttons = "accept,cancel,extra2";
 
       if (!this._folderTree.treeBoxObject.view.isContainerOpen(0))
         this._folderTree.treeBoxObject.view.toggleOpenState(0);
       this._folderTree.selectFolders([this._getFolderIdFromMenuList()]);
       this._folderTree.focus();
 
       this._folderTree.collapsed = false;
       resizeTo(window.outerWidth, window.outerHeight + this._folderTreeHeight);
--- a/browser/components/places/content/controller.js
+++ b/browser/components/places/content/controller.js
@@ -35,17 +35,16 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 const NHRVO = Ci.nsINavHistoryResultViewObserver;
 
 // XXXmano: we should move most/all of these constants to PlacesUtils
-const ORGANIZER_ROOT_HISTORY_UNSORTED = "place:type=1";
 const ORGANIZER_ROOT_BOOKMARKS = "place:folder=2&group=3&excludeItems=1&queryType=1";
 const ORGANIZER_SUBSCRIPTIONS_QUERY = "place:annotation=livemark%2FfeedURI";
 
 // No change to the view, preserve current selection
 const RELOAD_ACTION_NOTHING = 0;
 // Inserting items new to the view, select the inserted rows
 const RELOAD_ACTION_INSERT = 1;
 // Removing items from the view, select the first item after the last selected
@@ -456,17 +455,17 @@ PlacesController.prototype = {
 
   /** 
    * Gathers information about the selected nodes according to the following
    * rules:
    *    "link"              node is a URI
    *    "bookmark"          node is a bookamrk
    *    "folder"            node is a folder
    *    "query"             node is a query
-   *    "remotecontainer"   node is a remote container
+   *    "dynamiccontainer"  node is a dynamic container
    *    "separator"         node is a separator line
    *    "host"              node is a host
    *    "mutable"           node can have items inserted or reordered
    *    "allLivemarks"      node is a query containing every livemark
    *    
    * @returns an array of objects corresponding the selected nodes. Each
    *          object has each of the properties above set if its corresponding
    *          node matches the rule. In addition, the annotations names for each 
@@ -492,26 +491,22 @@ PlacesController.prototype = {
       var uri = null;
 
       // We don't use the nodeIs* methods here to avoid going through the type
       // property way too often
       switch(nodeType) {
         case Ci.nsINavHistoryResultNode.RESULT_TYPE_QUERY:
           nodeData["query"] = true;
           break;
-        case Ci.nsINavHistoryResultNode.RESULT_TYPE_REMOTE_CONTAINER:
-          nodeData["remotecontainer"] = true;
+        case Ci.nsINavHistoryResultNode.RESULT_TYPE_DYNAMIC_CONTAINER:
+          nodeData["dynamiccontainer"] = true;
           break;
         case Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER:
           nodeData["folder"] = true;
           uri = PlacesUtils.bookmarks.getFolderURI(node.itemId);
-
-          // See nodeIsRemoteContainer
-          if (asContainer(node).remoteContainerType != "")
-            nodeData["remotecontainer"] = true;
           break;
         case Ci.nsINavHistoryResultNode.RESULT_TYPE_HOST:
           nodeData["host"] = true;
           break;
         case Ci.nsINavHistoryResultNode.RESULT_TYPE_SEPARATOR:
           nodeData["separator"] = true;
           break;
         case Ci.nsINavHistoryResultNode.RESULT_TYPE_URI:
@@ -1165,48 +1160,37 @@ PlacesController.prototype = {
     else
       nodes = this._view.getDragableSelection();
     var dataSet = new TransferDataSet();
     for (var i = 0; i < nodes.length; ++i) {
       var node = nodes[i];
 
       var data = new TransferData();
       function addData(type, overrideURI) {
-        data.addDataForFlavour(type, PlacesUtils._wrapString(PlacesUtils.wrapNode(node, type, overrideURI)));
+        data.addDataForFlavour(type, PlacesUtils._wrapString(
+                               PlacesUtils.wrapNode(node, type, overrideURI)));
       }
 
       function addURIData(overrideURI) {
         addData(PlacesUtils.TYPE_X_MOZ_URL, overrideURI);
         addData(PlacesUtils.TYPE_UNICODE, overrideURI);
         addData(PlacesUtils.TYPE_HTML, overrideURI);
       }
 
-      if (PlacesUtils.nodeIsFolder(node) || PlacesUtils.nodeIsQuery(node)) {
-        // Look up this node's place: URI in the annotation service to see if 
-        // it is a special, non-movable folder. 
-        // XXXben: TODO
-
-        addData(PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER);
-
-        // Allow dropping the feed uri of live-bookmark folders
-        if (PlacesUtils.nodeIsLivemarkContainer(node)) {
-          var uri = PlacesUtils.livemarks.getFeedURI(node.itemId);
-          addURIData(uri.spec);
-        }
-
-      }
-      else if (PlacesUtils.nodeIsSeparator(node)) {
-        addData(PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR);
-      }
-      else {
-        // This order is _important_! It controls how this and other 
-        // applications select data to be inserted based on type. 
-        addData(PlacesUtils.TYPE_X_MOZ_PLACE);
-        addURIData();
-      }
+      // This order is _important_! It controls how this and other 
+      // applications select data to be inserted based on type.
+      addData(PlacesUtils.TYPE_X_MOZ_PLACE);
+      
+      var uri;
+      
+      // Allow dropping the feed uri of live-bookmark folders
+      if (PlacesUtils.nodeIsLivemarkContainer(node))
+        uri = PlacesUtils.livemarks.getFeedURI(node.itemId).spec;
+      
+      addURIData(uri);
       dataSet.push(data);
     }
     return dataSet;
   },
 
   /**
    * Copy Bookmarks and Folders to the clipboard
    */
@@ -1470,29 +1454,43 @@ var PlacesControllerDragHelper = {
    */
   onDrop: function PCDH_onDrop(sourceView, targetView, insertionPoint) {
     var session = this.getSession();
     var copy = session.dragAction & Ci.nsIDragService.DRAGDROP_ACTION_COPY;
     var transactions = [];
     var xferable = this._initTransferable(session, targetView, 
                                           insertionPoint.orientation);
     var dropCount = session.numDropItems;
-    for (var i = dropCount - 1; i >= 0; --i) {
+    
+    var movedCount = 0;
+    
+    for (var i = 0; i < dropCount; ++i) {
       session.getData(xferable, i);
     
       var data = { }, flavor = { };
       xferable.getAnyTransferData(flavor, data, { });
       data.value.QueryInterface(Ci.nsISupportsString);
       
       // There's only ever one in the D&D case. 
       var unwrapped = PlacesUtils.unwrapNodes(data.value.data, 
                                               flavor.value)[0];
-      transactions.push(PlacesUtils.makeTransaction(unwrapped, 
-                        flavor.value, insertionPoint.itemId, 
-                        insertionPoint.index, copy));
+      var index = insertionPoint.index;
+      
+      // Adjust insertion index to prevent reversal of dragged items. When you
+      // drag multiple elts upward: need to increment index or each successive
+      // elt will be inserted at the same index, each above the previous.
+      if ((index != -1) && ((index < unwrapped.index) ||
+                           (unwrapped.folder && (index < unwrapped.folder.index)))) {
+        index = index + movedCount;
+        movedCount++;
+      }
+        
+      transactions.push(PlacesUtils.makeTransaction(unwrapped,
+                        flavor.value, insertionPoint.itemId,
+                        index, copy));
     }
 
     var txn = PlacesUtils.ptm.aggregateTransactions("DropItems", transactions);
     PlacesUtils.ptm.commitTransaction(txn);
   }
 };
 
 function goUpdatePlacesCommands() {
--- a/browser/components/places/content/history-panel.js
+++ b/browser/components/places/content/history-panel.js
@@ -59,17 +59,17 @@ function HistorySidebarInit()
     document.getElementById("bylastvisited").setAttribute("checked", "true");
   else if (gHistoryGrouping == "dayandsite")
     document.getElementById("bydayandsite").setAttribute("checked", "true");
   else
     document.getElementById("byday").setAttribute("checked", "true");
 
   initContextMenu();
   
-  initPlace();
+  searchHistory("");
 
   gSearchBox.focus();
 }
 
 function initContextMenu() {
   // Force-hide items in the context menu which never apply to this view
   var alwaysHideElements = ["placesContext_new:bookmark",
                             "placesContext_new:folder",
@@ -104,68 +104,60 @@ function historyAddBookmarks()
   // or if the selected item is not a URI node
   var node = gHistoryTree.selectedURINode;
   if (!node) 
     return;
 
   PlacesUtils.showMinimalAddBookmarkUI(PlacesUtils._uri(node.uri), node.title);
 }
 
-function SetSortingAndGrouping(aOptions) 
+function searchHistory(aInput)
 {
+  var query = PlacesUtils.history.getNewQuery();
+  var options = PlacesUtils.history.getNewQueryOptions();
+
   const NHQO = Ci.nsINavHistoryQueryOptions;
   var sortingMode;
-  var groups = [];
-  switch (gHistoryGrouping) {
-    case "site":
-      sortingMode = NHQO.SORT_BY_TITLE_ASCENDING;
-      break; 
-    case "visited":
-      sortingMode = NHQO.SORT_BY_VISITCOUNT_DESCENDING;
-      break; 
-    case "lastvisited":
-      sortingMode = NHQO.SORT_BY_DATE_DESCENDING;
-      break; 
-    case "dayandsite":
-      groups.push(NHQO.GROUP_BY_DAY);
-      groups.push(NHQO.GROUP_BY_HOST);
-      sortingMode = NHQO.SORT_BY_TITLE_ASCENDING;
-      break;
-    default:
-      groups.push(NHQO.GROUP_BY_DAY);
-      sortingMode = NHQO.SORT_BY_TITLE_ASCENDING;
-      break;
+  var groups = []; 
+  var resultType;
+
+  if (aInput) {
+    query.searchTerms = aInput;
+    sortingMode = NHQO.SORT_BY_TITLE_ASCENDING;
+    resultType = NHQO.RESULTS_AS_URI;
   }
-  aOptions.setGroupingMode(groups, groups.length);
-  aOptions.sortingMode = sortingMode;
-}
+  else {
+    switch (gHistoryGrouping) {
+      case "site":
+        resultType = NHQO.RESULTS_AS_URI;
+        sortingMode = NHQO.SORT_BY_TITLE_ASCENDING;
+        break; 
+      case "visited":
+        resultType = NHQO.RESULTS_AS_URI;
+        sortingMode = NHQO.SORT_BY_VISITCOUNT_DESCENDING;
+        break; 
+      case "lastvisited":
+        resultType = NHQO.RESULTS_AS_URI;
+        sortingMode = NHQO.SORT_BY_DATE_DESCENDING;
+        break; 
+      case "dayandsite":
+        resultType = NHQO.RESULTS_AS_VISIT;
+        groups.push(NHQO.GROUP_BY_DAY);
+        groups.push(NHQO.GROUP_BY_HOST);
+        sortingMode = NHQO.SORT_BY_TITLE_ASCENDING;
+        break;
+      default:
+        resultType = NHQO.RESULTS_AS_VISIT;
+        groups.push(NHQO.GROUP_BY_DAY);
+        sortingMode = NHQO.SORT_BY_TITLE_ASCENDING;
+        break;
+    }
+  }
 
-function initPlace()
-{
+  options.setGroupingMode(groups, groups.length);
+  options.sortingMode = sortingMode;
+  options.resultType = resultType;
+
   // call load() on the tree manually
   // instead of setting the place attribute in history-panel.xul
   // otherwise, we will end up calling load() twice
-  var optionsRef = {};
-  var queriesRef = {};
-  PlacesUtils.history.queryStringToQueries(ORGANIZER_ROOT_HISTORY_UNSORTED, queriesRef, {}, optionsRef);
-  SetSortingAndGrouping(optionsRef.value);
-  gHistoryTree.load(queriesRef.value, optionsRef.value);
+  gHistoryTree.load([query], options);
 }
-
-function searchHistory(aInput)
-{
-  if (aInput) {
-    if (!gSearching) {
-      // Unset grouping when searching; 
-      var options = gHistoryTree.getResult().root.queryOptions;
-      options.setGroupingMode([], 0);
-      gSearching = true;
-    }
-    
-    // applyFilter will update the view by calling load()
-    gHistoryTree.applyFilter(aInput, false /* onlyBookmarks */, 
-                             null /* folderRestrict */, null);
-  }
-  else {
-    initPlace();
-    gSearching = false;
-  }
-}
--- a/browser/components/places/content/menu.xml
+++ b/browser/components/places/content/menu.xml
@@ -235,32 +235,31 @@
             element.appendChild(popup);
 #ifndef XP_MACOSX
             // No context menus on menus on Mac
             // The context menu is set here instead of in the xbl constructor
             // because it doesn't get initialized properly if set in the constructor.
             popup.setAttribute("context", "placesContext");
 #endif
             popup._result = this._result;
-            popup._resultNode = child;
+            popup._resultNode = asContainer(child);
             element.className = "menu-iconic bookmark-item";
 #ifdef XP_MACOSX
             // If this is a child of the bookmarks menubar, we have to manually attach
             // its xbl binding, because it's not a dom node and the style rules don't
             // get applied correctly.
             if (this._needsBindingAttachment) {
               const MENU_URI = "chrome://browser/content/places/menu.xml#places-menupopup";
               document.addBinding(popup, MENU_URI);
             }
 #endif
             popup._containerNodesMap = this._containerNodesMap;
             this._containerNodesMap.push({ resultNode: child, domNode: popup });
           }
-          // else if (nodeIsQuery) ... add menu to build kids
-           
+
           if (element) {
             element.node = child;
             if (child.icon)
               element.setAttribute("image", child.icon.spec);
 
             if (before)
               this.insertBefore(element, before);
             else {
--- a/browser/components/places/content/moveBookmarks.js
+++ b/browser/components/places/content/moveBookmarks.js
@@ -68,17 +68,17 @@ var gMoveBookmarksDialog = {
 
     var transactions = [];
     for (var i=0; i < this._nodes.length; i++) {
       // Nothing to do if the node is already under the selected folder
       if (this._nodes[i].parent.itemId == selectedFolderID)
         continue;
 
       transactions.push(new
-        PlacesUtils.txn.moveItem(this._nodes[i].itemId, selectedFolderId, -1));
+        PlacesUtils.ptm.moveItem(this._nodes[i].itemId, selectedFolderID, -1));
     }
 
     if (transactions.length != 0) {
       var txn = PlacesUtils.ptm.aggregateTransactions("Move Items", transactions);
       this._tm.doTransaction(txn);
     }
   },
 
--- a/browser/components/places/content/places.js
+++ b/browser/components/places/content/places.js
@@ -356,17 +356,17 @@ var PlacesSearchBox = {
         (filterString == "" || this.searchFilter.hasAttribute("empty")))
       return;
 
     var content = PlacesOrganizer._content;
     var PO = PlacesOrganizer;
 
     switch (PlacesSearchBox.filterCollection) {
     case "collection":
-      var folderId = content.getResult().root.itemId;
+      var folderId = PlacesOrganizer._places.selectedNode.itemId;
       content.applyFilter(filterString, true, [folderId], OptionsFilter);
       PO.setHeaderText(PO.HEADER_TYPE_SEARCH, filterString);
       break;
     case "bookmarks":
       if (filterString != "")
         content.applyFilter(filterString, true);
       else
         PlacesOrganizer.onPlaceSelected();
--- a/browser/components/places/content/toolbar.xml
+++ b/browser/components/places/content/toolbar.xml
@@ -97,18 +97,16 @@
           //setTimeout(function() { self._init(); }, 0);
         }
         else
 #endif
           this._init();
       ]]></constructor>
       
       <destructor><![CDATA[ 
-        this.genericAnnoObserver.removeObserver("bookmarks/generatedTitle",
-                                                this._generatedTitleAnnoObserver);
         PlacesUtils.annotations.removeObserver(this.genericAnnoObserver);
         this._result.viewer = null;
         this._result = null;
       ]]></destructor>
 
       <property name="controller"
                 readonly="true"
                 onget="return this._controller;"/>
@@ -119,67 +117,32 @@
         this.controllers.appendController(this._controller);
 
         var t = this;
         window.addEventListener("resize",
                                 function f(e) { t.updateChevron(e); },
                                 false);
 
         PlacesUtils.annotations.addObserver(this.genericAnnoObserver);
-        this.genericAnnoObserver.addObserver("bookmarks/generatedTitle",
-                                             this._generatedTitleAnnoObserver);
 
         if (this.hasAttribute("place")) {
           // Do the initial build. 
           this.place = this.place;
         }
         ]]></body>
       </method>
 
       <field name="_dropIndicatorBar">document.getAnonymousElementByAttribute(this, "class", "toolbar-drop-indicator-bar")</field>
       <field name="_chevron">document.getAnonymousElementByAttribute(this, "class", "chevron")</field>
       
       <field name="_selection">null</field>
       
       <field name="_openedMenuButton">null</field>
       
       <field name="_result">null</field>
-
-      <!-- A cache of titles generated by the microsummary service/extensions.
-         - Generated titles override page/user-set titles as bookmark labels.
-         - The getter builds the cache the first time it's needed; afterwards,
-         - the _generatedTitleAnnoObserver maintains it by reflecting changes
-         - to "bookmarks/generatedTitle" annotations into it.
-         -->
-      <field name="__generatedTitles">null</field>
-      <property name="_generatedTitles">
-        <getter><![CDATA[
-          if (!this.__generatedTitles) {
-            this.__generatedTitles = {};
-
-            var annotations = PlacesUtils.annotations;
-            // This try/catch block is a temporary workaround for bug 336194.
-            var bookmarks = [];
-            try {
-              bookmarks = annotations.getItemsWithAnnotation("bookmarks/generatedTitle", {});
-            }
-            catch(e) { }
-
-            // XXX It'd be faster to grab the annotations in a single query
-            // instead of querying separately for each one, but the annotation
-            // service provides no mechanism for doing so.
-            for (var i = 0; i < bookmarks.length; i++) {
-              this.__generatedTitles[bookmarks[i]] =
-                annotations.getItemAnnotation(bookmarks[i], "bookmarks/generatedTitle");
-            }
-          }
-          
-          return this.__generatedTitles;
-        ]]></getter>
-      </property>
       
       <!-- nsIPlacesView -->
       <method name="getResult">
         <body><![CDATA[
           return this._result;
         ]]></body>
       </method>
 
@@ -226,22 +189,16 @@
         <parameter name="child"/>
         <parameter name="before"/>
         <body><![CDATA[
           const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
           var title = child.title;
           var button = null;
           if (PlacesUtils.nodeIsURI(child)) {
             button = document.createElementNS(XULNS, "toolbarbutton");
-
-            if (PlacesUtils.nodeIsBookmark(child)) {
-              // If the item has a generated title, use that instead.
-              if (this._generatedTitles[child.itemId])
-                title = this._generatedTitles[child.itemId];
-            }
           } else if (PlacesUtils.nodeIsSeparator(child)) {
             button = document.createElementNS(XULNS, "toolbarseparator");
           } else if (PlacesUtils.nodeIsContainer(child)) {
             button = document.createElementNS(XULNS, "toolbarbutton");
             button.setAttribute("type", "menu");
             button.setAttribute("container", "true");
             if (PlacesUtils.nodeIsLivemarkContainer(child)) {
               button.setAttribute("livemark", "true");
@@ -265,17 +222,17 @@
             // This is set here and not in the XBL constructor for the menu because
             // it doesn't get initialized properly in the constructor.
 #ifndef XP_MACOSX
             // No context menus on menuitems on Mac
             popup.setAttribute("context", "placesContext");
 #endif
             button.appendChild(popup);
             popup._result = this._result;
-            popup._resultNode = child;
+            popup._resultNode = asContainer(child);
             popup._containerNodesMap = this._containerNodesMap;
             this._containerNodesMap.push({ resultNode: child,
                                            domNode: popup });
           }
 
           button.setAttribute("label", title);
           if (child.icon)
             button.setAttribute("image", child.icon.spec);
@@ -548,24 +505,17 @@
               break;
             }
           }
 
           NS_ASSERT(button, "unable to find a toolbar element");
 
           var title = aNode.title;
 
-          if (PlacesUtils.nodeIsURI(aNode)) {
-            if (PlacesUtils.nodeIsBookmark(aNode)) {
-              // If the item has a generated title, use that instead.
-              if (this._self._generatedTitles[aNode.itemId])
-                title = this._self._generatedTitles[aNode.itemId];
-            }
-          } 
-          else if (PlacesUtils.nodeIsSeparator(aNode)) {
+          if (PlacesUtils.nodeIsSeparator(aNode)) {
             // nothing to do when a separator changes
             return;
           } 
           else if (PlacesUtils.nodeIsContainer(aNode)) {
             if (PlacesUtils.nodeIsLivemarkContainer(aNode)) {
               var folder = aNode.itemId;
               var siteURIString = PlacesUtils.livemarks.getSiteURI(folder).spec;
               if (siteURIString) {
@@ -888,58 +838,16 @@
           for (var i = 0; i < this._self.peerDropTypes.length; ++i)
             flavorSet.appendFlavour(this._self.peerDropTypes[i]);
           return flavorSet;
         }
         
       })]]></field>
 
       <!-- nsIAnnotationObserver -->
-      <field name="_generatedTitleAnnoObserver"><![CDATA[({
-        // Observes changes to "bookmarks/generatedTitle" annotations,
-        // which override page and user-set titles as bookmark labels.
-
-        // The microsummary service sets this annotation for summary bookmarks,
-        // and extensions might also set it.
-
-        // Inside this observer object's functions, "this" points to this
-        // observer object, while "_self" points to the toolbar XBL object.
-        _self: this,
-
-        onPageAnnotationSet: function() { },
-
-        onPageAnnotationRemoved: function() { },
-
-        onItemAnnotationSet:
-        function TBV_GTAO_onItemAnnotationSet(aItemId, aAnnoName) {
-          NS_ASSERT(aAnnoName == "bookmarks/generatedTitle",
-                    "annotation " + aAnnoName + ", is not 'bookmarks/generatedTitle'");
-          var newTitle =
-            PlacesUtils.annotations.getItemAnnotation(aItemId, aAnnoName);
-          this._self._generatedTitles[aItemId] = newTitle;
-          this._doRebuild();
-        },
-
-        onItemAnnotationRemoved:
-        function TBV_GTAO_onItemAnnotationRemoved(aItemId, aAnnoName) {
-          NS_ASSERT(aAnnoName == "bookmarks/generatedTitle",
-                    "annotation " + aAnnoName + ", is not 'bookmarks/generatedTitle'");
-          delete this._self._generatedTitles[aItemId];
-          this._doRebuild();
-        },
-
-        _doRebuild: function TBV_GTAO_doRebuild() {
-          function hitch(obj, meth) {
-            return function() { meth.apply(obj, arguments); }
-          }
-          setTimeout(hitch(this._self, this._self._rebuild), 1);
-        }
-      })]]></field>
-
-      <!-- nsIAnnotationObserver -->
       <field name="genericAnnoObserver"><![CDATA[({
         // A generic nsIAnnotationObserver that provides methods for registering
         // annotation-specific observers for this view.
 
         // Inside this observer object's functions, "this" points to this
         // observer object, while "_self" points to the toolbar XBL object.
         _self: this,
         
--- a/browser/components/places/content/tree.xml
+++ b/browser/components/places/content/tree.xml
@@ -104,17 +104,17 @@
 
       <method name="applyFilter">
         <parameter name="filterString"/>
         <parameter name="onlyBookmarks"/>
         <parameter name="folderRestrict"/>
         <parameter name="optionsFilter"/>
         <body><![CDATA[
           // preserve grouping
-          var queryNode = asQuery(this.getResult().root);
+          var queryNode = asQuery(this.getResultNode());
           var options = queryNode.queryOptions.clone();
           if (optionsFilter)
             options = optionsFilter.filter(queryNode.getQueries({}), options, 
                                            optionsFilter.historyHandler);
           
           var query = PlacesUtils.history.getNewQuery();
           query.searchTerms = filterString;
           query.onlyBookmarked = onlyBookmarks;
@@ -433,19 +433,22 @@
         ]]></getter>
       </property>
       
       <!-- nsIPlacesView -->
       <property name="insertionPoint">
         <getter><![CDATA[
           // there is no insertion point for history queries
           // so bail out now and save a lot of work when updating commands
-          var options = asQuery(this.getResult().root).queryOptions;
-          if (options.queryType == options.QUERY_TYPE_HISTORY)
-            return null;
+          var resultNode = this.getResultNode();
+          if (PlacesUtils.nodeIsQuery(resultNode)) {
+            var options = asQuery(resultNode).queryOptions;
+            if (options.queryType == options.QUERY_TYPE_HISTORY) 
+              return null;
+          }
 
           var orientation = NHRVO.DROP_AFTER;
           // If there is no selection, insert at the end of the container. 
           if (!this.hasSelection) {
             var index = this.view.rowCount - 1;
             return this._getInsertionPoint(index, orientation);
           }
 
@@ -786,17 +789,17 @@
                 if (foundNode)
                   break;
               }
             }
             aContainer.containerOpen = wasOpen;
             return foundNode;
           }
           var folder = null;
-          var root = asContainer(this.getResult().root);
+          var root = asContainer(this.getResultNode());
           if (PlacesUtils.nodeIsFolder(root) && 
               root.itemId == insertionPoint.itemId)
             folder = root;
           else
             folder = findFolder(insertionPoint.itemId, root);
           
           // Since we find the folder manually, using findFolder instead of 
           // PlacesUtils.getFolderContents, the folder is not opened for
--- a/browser/components/places/content/utils.js
+++ b/browser/components/places/content/utils.js
@@ -225,174 +225,164 @@ var PlacesUtils = {
 
   getString: function PU_getString(key) {
     return this._bundle.GetStringFromName(key);
   },
 
   /**
    * Determines whether or not a ResultNode is a Bookmark folder or not.
    * @param   aNode
-   *          A NavHistoryResultNode
+   *          A result node
    * @returns true if the node is a Bookmark folder, false otherwise
    */
   nodeIsFolder: function PU_nodeIsFolder(aNode) {
     NS_ASSERT(aNode, "null node");
     return (aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER);
   },
 
   /**
    * Determines whether or not a ResultNode represents a bookmarked URI.
    * @param   aNode
-   *          A NavHistoryResultNode
+   *          A result node
    * @returns true if the node represents a bookmarked URI, false otherwise
    */
   nodeIsBookmark: function PU_nodeIsBookmark(aNode) {
     NS_ASSERT(aNode, "null node");
     return aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_URI &&
            aNode.itemId != -1;
   },
 
   /**
    * Determines whether or not a ResultNode is a Bookmark separator.
    * @param   aNode
-   *          A NavHistoryResultNode
+   *          A result node
    * @returns true if the node is a Bookmark separator, false otherwise
    */
   nodeIsSeparator: function PU_nodeIsSeparator(aNode) {
     NS_ASSERT(aNode, "null node");
 
     return (aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_SEPARATOR);
   },
 
   /**
    * Determines whether or not a ResultNode is a visit item or not
    * @param   aNode
-   *          A NavHistoryResultNode
+   *          A result node
    * @returns true if the node is a visit item, false otherwise
    */
   nodeIsVisit: function PU_nodeIsVisit(aNode) {
     NS_ASSERT(aNode, "null node");
 
     const NHRN = Ci.nsINavHistoryResultNode;
     var type = aNode.type;
     return type == NHRN.RESULT_TYPE_VISIT ||
            type == NHRN.RESULT_TYPE_FULL_VISIT;
   },
 
   /**
    * Determines whether or not a ResultNode is a URL item or not
    * @param   aNode
-   *          A NavHistoryResultNode
+   *          A result node
    * @returns true if the node is a URL item, false otherwise
    */
   nodeIsURI: function PU_nodeIsURI(aNode) {
     NS_ASSERT(aNode, "null node");
 
     const NHRN = Ci.nsINavHistoryResultNode;
     var type = aNode.type;
     return type == NHRN.RESULT_TYPE_URI ||
            type == NHRN.RESULT_TYPE_VISIT ||
            type == NHRN.RESULT_TYPE_FULL_VISIT;
   },
 
   /**
    * Determines whether or not a ResultNode is a Query item or not
    * @param   aNode
-   *          A NavHistoryResultNode
+   *          A result node
    * @returns true if the node is a Query item, false otherwise
    */
   nodeIsQuery: function PU_nodeIsQuery(aNode) {
     NS_ASSERT(aNode, "null node");
 
     return aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_QUERY;
   },
 
   /**
    * Determines if a node is read only (children cannot be inserted, sometimes
    * they cannot be removed depending on the circumstance)
    * @param   aNode
-   *          A NavHistoryResultNode
+   *          A result node
    * @returns true if the node is readonly, false otherwise
    */
   nodeIsReadOnly: function PU_nodeIsReadOnly(aNode) {
     NS_ASSERT(aNode, "null node");
 
     if (this.nodeIsFolder(aNode))
       return this.bookmarks.getFolderReadonly(aNode.itemId);
     if (this.nodeIsQuery(aNode))
       return asQuery(aNode).childrenReadOnly;
     return false;
   },
 
   /**
    * Determines whether or not a ResultNode is a host folder or not
    * @param   aNode
-   *          A NavHistoryResultNode
+   *          A result node
    * @returns true if the node is a host item, false otherwise
    */
   nodeIsHost: function PU_nodeIsHost(aNode) {
     NS_ASSERT(aNode, "null node");
 
     return aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_HOST;
   },
 
   /**
    * Determines whether or not a ResultNode is a container item or not
    * @param   aNode
-   *          A NavHistoryResultNode
+   *          A result node
    * @returns true if the node is a container item, false otherwise
    */
   nodeIsContainer: function PU_nodeIsContainer(aNode) {
     NS_ASSERT(aNode, "null node");
 
     const NHRN = Ci.nsINavHistoryResultNode;
     var type = aNode.type;
     return type == NHRN.RESULT_TYPE_HOST ||
            type == NHRN.RESULT_TYPE_QUERY ||
            type == NHRN.RESULT_TYPE_FOLDER ||
            type == NHRN.RESULT_TYPE_DAY ||
-           type == NHRN.RESULT_TYPE_REMOTE_CONTAINER;
+           type == NHRN.RESULT_TYPE_DYNAMIC_CONTAINER;
   },
 
   /**
-   * Determines whether or not a ResultNode is a remotecontainer item.
-   * ResultNote may be either a remote container result type or a bookmark folder
-   * with a nonempty remoteContainerType.  The remote container result node
-   * type is for dynamically created remote containers (i.e., for the file
-   * browser service where you get your folders in bookmark menus).  Bookmark
-   * folders are marked as remote containers when some other component is
-   * registered as interested in them and providing some operations, in which
-   * case their remoteContainerType indicates which component is thus registered.
-   * For exmaple, the livemark service uses this mechanism.
+   * Determines whether or not a result-node is a dynamic-container item.
+   * The dynamic container result node type is for dynamically created
+   * containers (e.g. for the file browser service where you get your folders
+   * in bookmark menus).
    * @param   aNode
-   *          A NavHistoryResultNode
-   * @returns true if the node is a container item, false otherwise
+   *          A result node
+   * @returns true if the node is a dynamic container item, false otherwise
    */
-  nodeIsRemoteContainer: function PU_nodeIsRemoteContainer(aNode) {
+  nodeIsDynamicContainer: function PU_nodeIsDynamicContainer(aNode) {
     NS_ASSERT(aNode, "null node");
-
-    const NHRN = Ci.nsINavHistoryResultNode;
-    if (aNode.type == NHRN.RESULT_TYPE_REMOTE_CONTAINER)
+    if (aNode.type == NHRN.RESULT_TYPE_DYNAMIC_CONTAINER)
       return true;
-    if (this.nodeIsFolder(aNode))
-      return asContainer(aNode).remoteContainerType != "";
     return false;
   },
 
  /**
   * Determines whether a ResultNode is a remote container registered by the
   * livemark service.
   * @param aNode
   *        A NavHistory Result Node
   * @returns true if the node is a livemark container item
   */
   nodeIsLivemarkContainer: function PU_nodeIsLivemarkContainer(aNode) {
-    return (this.nodeIsRemoteContainer(aNode) &&
-            asContainer(aNode).remoteContainerType ==
-               "@mozilla.org/browser/livemark-service;2");
+    return this.nodeIsFolder(aNode) &&
+           this.annotations.itemHasAnnotation(aNode.itemId, "livemark/feedURI");
   },
 
  /**
   * Determines whether a ResultNode is a live-bookmark item
   * @param aNode
   *        A NavHistory Result Node
   * @returns true if the node is a livemark container item
   */
--- a/browser/components/places/public/nsIPlacesTransactionsService.idl
+++ b/browser/components/places/public/nsIPlacesTransactionsService.idl
@@ -36,29 +36,28 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsISupports.idl"
 
 interface nsIVariant;
 interface nsIURI;
-interface nsIInputStream;
 interface nsIMicrosummary;
 interface nsITransactionManager;
 interface nsITransaction;
 
 /**
  * nsIPlacesTransactionService is a service designed to handle
  * nsITransactions that correspond to changes in Places. It is here as a
  * service so that we can keep the transactions around without holding onto
  * the global scope of a js window.
  */
 
-[scriptable, uuid(224f6833-762b-43ba-8911-020b589b2da3)]
+[scriptable, uuid(2d176a73-a908-420b-8c5d-209a45997f45)]
 interface nsIPlacesTransactionsService : nsISupports
 {
   /**
    * Performs a transaction.
    *
    * @param aTransaction
    *        a transaction object for a transaction
    */
@@ -254,17 +253,17 @@ interface nsIPlacesTransactionsService :
    *
    * @param aURI
    *        uri to edit
    * @param aPostData
    *        post data
    * @returns nsITransaction object
    */
   nsITransaction editURIPostData(in nsIURI aURI,
-                                 in nsIInputStream aPostData);
+                                 in AString aPostData);
 
   /**
    * Transaction for editting a live bookmark's site URI.
    *
    * @param aFolderId
    *        id of the livemark
    * @param aURI
    *        new site uri
--- a/browser/components/places/src/nsPlacesImportExportService.cpp
+++ b/browser/components/places/src/nsPlacesImportExportService.cpp
@@ -114,24 +114,22 @@ static NS_DEFINE_CID(kParserCID, NS_PARS
 #define KEY_WEB_PANEL_LOWER "web_panel"
 #define KEY_LASTCHARSET_LOWER "last_charset"
 #define KEY_ICON_LOWER "icon"
 #define KEY_ICON_URI_LOWER "icon_uri"
 #define KEY_SHORTCUTURL_LOWER "shortcuturl"
 #define KEY_POST_DATA_LOWER "post_data"
 #define KEY_NAME_LOWER "name"
 #define KEY_MICSUM_GEN_URI_LOWER "micsum_gen_uri"
-#define KEY_GENERATED_TITLE_LOWER "generated_title"
 #define KEY_DATE_ADDED_LOWER "add_date"
 #define KEY_LAST_MODIFIED_LOWER "last_modified"
 
 #define LOAD_IN_SIDEBAR_ANNO NS_LITERAL_CSTRING("bookmarkProperties/loadInSidebar")
 #define DESCRIPTION_ANNO NS_LITERAL_CSTRING("bookmarkProperties/description")
 #define POST_DATA_ANNO NS_LITERAL_CSTRING("URIProperties/POSTData")
-#define GENERATED_TITLE_ANNO NS_LITERAL_CSTRING("bookmarks/generatedTitle")
 #define LAST_CHARSET_ANNO NS_LITERAL_CSTRING("URIProperties/characterSet")
 
 #define BOOKMARKS_MENU_ICON_URI "chrome://browser/skin/places/bookmarksMenu.png"
 
 // define to get debugging messages on console about import/export
 //#define DEBUG_IMPORT
 //#define DEBUG_EXPORT
 
@@ -800,17 +798,16 @@ BookmarkContentSink::HandleLinkBegin(con
   nsAutoString icon;
   nsAutoString iconUri;
   nsAutoString lastCharset;
   nsAutoString keyword;
   nsAutoString postData;
   nsAutoString webPanel;
   nsAutoString itemId;
   nsAutoString micsumGenURI;
-  nsAutoString generatedTitle;
   nsAutoString dateAdded;
   nsAutoString lastModified;
 
   PRInt32 attrCount = node.GetAttributeCount();
   for (PRInt32 i = 0; i < attrCount; i ++) {
     const nsAString& key = node.GetKeyAt(i);
     if (key.LowerCaseEqualsLiteral(KEY_HREF_LOWER)) {
       href = node.GetValueAt(i);
@@ -825,35 +822,32 @@ BookmarkContentSink::HandleLinkBegin(con
     } else if (key.LowerCaseEqualsLiteral(KEY_SHORTCUTURL_LOWER)) {
       keyword = node.GetValueAt(i);
     } else if (key.LowerCaseEqualsLiteral(KEY_POST_DATA_LOWER)) {
       postData = node.GetValueAt(i);
     } else if (key.LowerCaseEqualsLiteral(KEY_WEB_PANEL_LOWER)) {
       webPanel = node.GetValueAt(i);
     } else if (key.LowerCaseEqualsLiteral(KEY_MICSUM_GEN_URI_LOWER)) {
       micsumGenURI = node.GetValueAt(i);
-    } else if (key.LowerCaseEqualsLiteral(KEY_GENERATED_TITLE_LOWER)) {
-      generatedTitle = node.GetValueAt(i);
     } else if (key.LowerCaseEqualsLiteral(KEY_DATE_ADDED_LOWER)) {
       dateAdded = node.GetValueAt(i);
     } else if (key.LowerCaseEqualsLiteral(KEY_LAST_MODIFIED_LOWER)) {
       lastModified = node.GetValueAt(i);
     }
   }
   href.Trim(kWhitespace);
   feedUrl.Trim(kWhitespace);
   icon.Trim(kWhitespace);
   iconUri.Trim(kWhitespace);
   lastCharset.Trim(kWhitespace);
   keyword.Trim(kWhitespace);
   postData.Trim(kWhitespace);
   webPanel.Trim(kWhitespace);
   itemId.Trim(kWhitespace);
   micsumGenURI.Trim(kWhitespace);
-  generatedTitle.Trim(kWhitespace);
   dateAdded.Trim(kWhitespace);
   lastModified.Trim(kWhitespace);
 
   // For feeds, get the feed URL. If it is invalid, it will leave mPreviousFeed
   // NULL and we'll continue trying to create it as a normal bookmark.
   if (!feedUrl.IsEmpty()) {
     NS_NewURI(getter_AddRefs(frame.mPreviousFeed),
               NS_ConvertUTF16toUTF8(feedUrl), nsnull);
@@ -947,31 +941,25 @@ BookmarkContentSink::HandleLinkBegin(con
   if (webPanel.LowerCaseEqualsLiteral("true")) {
     // set load-in-sidebar annotation for the bookmark
     mAnnotationService->SetItemAnnotationInt32(frame.mPreviousId, LOAD_IN_SIDEBAR_ANNO,
                                                1, 0,
                                                nsIAnnotationService::EXPIRE_NEVER);
   }
 
   // import microsummary
-  // Note: expiration and generated title are ignored, and will be
-  // recalculated by the microsummary service
+  // Note: expiration and generated title are ignored, and will be recalculated
+  // by the microsummary service
   if (!micsumGenURI.IsEmpty()) {
     nsCOMPtr<nsIURI> micsumGenURIObject;
     if (NS_SUCCEEDED(NS_NewURI(getter_AddRefs(micsumGenURIObject), micsumGenURI))) {
       nsCOMPtr<nsIMicrosummary> microsummary;
       mMicrosummaryService->CreateMicrosummary(frame.mPreviousLink, micsumGenURIObject,
                                                getter_AddRefs(microsummary));
       mMicrosummaryService->SetMicrosummary(frame.mPreviousId, microsummary);
-
-      // create generated title anno
-      rv = mAnnotationService->SetItemAnnotationString(frame.mPreviousId, GENERATED_TITLE_ANNO,
-                                                       generatedTitle, 0,
-                                                       nsIAnnotationService::EXPIRE_NEVER);
-      NS_ASSERTION(NS_SUCCEEDED(rv), "Creating microsummary generated title failed");
     }
   }
 
   // import last charset
   if (!lastCharset.IsEmpty()) {
     PRBool hasCharset = PR_FALSE;
     mAnnotationService->PageHasAnnotation(frame.mPreviousLink,
                                           LAST_CHARSET_ANNO, &hasCharset);
@@ -2406,17 +2394,17 @@ nsPlacesImportExportService::ExportHTMLT
   NS_ENSURE_SUCCESS(rv, rv);
 
   // execute query
   nsCOMPtr<nsINavHistoryResult> result;
   rv = mHistoryService->ExecuteQuery(query, options, getter_AddRefs(result));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // get root (folder) node
-  nsCOMPtr<nsINavHistoryQueryResultNode> rootNode;
+  nsCOMPtr<nsINavHistoryContainerResultNode> rootNode;
   rv = result->GetRoot(getter_AddRefs(rootNode));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // '<H1'
   rv = strm->Write(kRootIntro, sizeof(kRootIntro)-1, &dummy); // <H1
   NS_ENSURE_SUCCESS(rv, rv);
 
   // bookmarks menu favicon
--- a/browser/components/places/src/nsPlacesTransactionsService.js
+++ b/browser/components/places/src/nsPlacesTransactionsService.js
@@ -251,17 +251,17 @@ placesCreateFolderTransactions.prototype
   // childItemsTransaction support
   get container() { return this._container; },
   set container(val) { return this._container = val; },
 
   doTransaction: function PCFT_doTransaction() {
     this._id = PlacesUtils.bookmarks.createFolder(this._container, 
                                                   this._name, this._index);
     if (this._annotations && this._annotations.length > 0)
-      PlacesUtils.setAnnotationsForItem(this.id, this._annotations);
+      PlacesUtils.setAnnotationsForItem(this._id, this._annotations);
 
     for (var i = 0; i < this._childItemsTransactions.length; ++i) {
       var txn = this._childItemsTransactions[i];
       txn.wrappedJSObject.container = this._id;
       txn.doTransaction();
     }
   },
 
--- a/browser/components/places/tests/unit/bookmarks.preplaces.html
+++ b/browser/components/places/tests/unit/bookmarks.preplaces.html
@@ -2,17 +2,17 @@
 <!-- This is an automatically generated file.
      It will be read and overwritten.
      DO NOT EDIT! -->
 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
 <TITLE>Bookmarks</TITLE>
 <H1 LAST_MODIFIED="1177541029">Bookmarks</H1>
 
 <DL><p>
-    <DT><A HREF="http://en-US.add-ons.mozilla.com/en-US/firefox/bookmarks/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAFo9M%2F3AAAABGdBTUEAANbY1E9YMgAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAPkSURBVHjaYmAAgrjyOnOGiKxqxT9%2F%2FvwHCCCGuNJKLpAo49KTL%2F5%2F%2F8PMABBADJFZFWwXnn%2F%2FDxJYeOLNf0aQ9AIg48%2Ff%2Fwwfvv1hAAggZpBAYlWdnrqJLcPVE4e%2Bsuy7%2FfH%2F%2B88%2FGdjY2Bj%2BcCqHMey6%2Ben%2F379%2F%2F%2F8B6unZ9ew%2Fy54jV249f6%2Bm9uXnX4Y9qyaoAAQAhAB7%2FwEAAAAAY3h%2BG1RdbeMMCgkB9%2Fr%2BAPL2%2FAC3vsyi5NG6YQFcbnwdZ3F44uru9gAAAQAAUjEVALPT7wDu9v4A5erz%2FgL19vr16PD6AAUHBgDu9PwA%2F%2F8AAO%2F2%2FgD0%2BP0A7e7x8QPYzsX38vj9g%2BPk6hkLFiAxy%2BP4AeHj5%2FXFtp9GonxaagII7AawXyprpf%2F%2FZ5L5%2Fe%2Fv9%2B%2Fff91ZN7nrG0icJSqrkknJxHm1h5Nl0J8%2F%2Fxg%2B%2FwDa%2Febzv39%2FWKQ2TG97ycIvq%2Bvn52oVxMHGxHDj8RcGQT4uEGZyCct98e3LL3YmJ2enNYxAi%2B48%2B8QQaizGIMLFBLaSlYWZgYWDWZaJhY2V%2BcvPfwz%2BeiIMf%2F%2F%2BY9CV4GAQ42Zh%2BPPvP8O%2Fv%2F%2BZmG7cff7u49c%2FDNtufGZgYmJiOHLvG8Pt1z8Yfv3%2Bz%2FDn19%2B3TCd2LNV7%2F%2FU3w7vPvxkWnHzDcOPFd4ZvQBPv3L79aM%2BS3nfMN88d%2BfyXkW0Lq6BiGAs7J8fHT9%2F%2FXTy%2BY82Lp0cdb5889hcgQJNU85JYFMXP%2B5aHqRmmZJ9kKMGAEBgtDCYYY6BFa%2BlrPc6yRf0LYYtZzG4YaNGibUNJVLuIcBNUTLMQM8ZoppdiaXnf9Xlf5z4ounDu4p57f%2Ff8Pt50SH9ZEfUuLehy93yMRBNroVAg6PV2yBbO9c94tK5v7suF3%2FlMs1o8oU27ltvIMic7fJv7uuqLJGa2UpPxlCILICBtGz1pYWooakeoDaTFgBtNWm04zl%2Fkbs53FnZ%2FZO%2BldGbFP5aaP50cj41pigi8XFjF2zp8ivpgsFMFHp0GgrQZL4DuYGCE6f3pzoBnUwRB8sYi4QGKHf7b5d8HiHWpMBsPvLKDeFiHmVEPBN0yMJyMIUhfb6gXbMkr4xtq1J6Z36eLpmiDH508LNShbDzB4kTIATguNsBqA1CHElJDhGdCGWsDkYY%2FTJh3lUelu384yTlzrtgDWVaggvG8qhDnYcEwwWi0wET%2FTNTh9Gh%2FvVn7v%2B2I%2BHlpWXS59ORgfOr7UGRkVNMUAWPtCMnHdbjjATFNKJeKpdLZYQY0crDzLUvfbHxdqfllj6a7p2VVjUqyGhYwPpZFqxYlf6hZ%2F7X3c736%2Fv4LV1blv94gEvsAAAAASUVORK5CYII%3D" ID="rdf:#$CnoJ1">Get Bookmark Add-ons</A>
+    <DT><A HREF="https://en-US.add-ons.mozilla.com/en-US/firefox/bookmarks/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAFo9M%2F3AAAABGdBTUEAANbY1E9YMgAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAPkSURBVHjaYmAAgrjyOnOGiKxqxT9%2F%2FvwHCCCGuNJKLpAo49KTL%2F5%2F%2F8PMABBADJFZFWwXnn%2F%2FDxJYeOLNf0aQ9AIg48%2Ff%2Fwwfvv1hAAggZpBAYlWdnrqJLcPVE4e%2Bsuy7%2FfH%2F%2B88%2FGdjY2Bj%2BcCqHMey6%2Ben%2F379%2F%2F%2F8B6unZ9ew%2Fy54jV249f6%2Bm9uXnX4Y9qyaoAAQAhAB7%2FwEAAAAAY3h%2BG1RdbeMMCgkB9%2Fr%2BAPL2%2FAC3vsyi5NG6YQFcbnwdZ3F44uru9gAAAQAAUjEVALPT7wDu9v4A5erz%2FgL19vr16PD6AAUHBgDu9PwA%2F%2F8AAO%2F2%2FgD0%2BP0A7e7x8QPYzsX38vj9g%2BPk6hkLFiAxy%2BP4AeHj5%2FXFtp9GonxaagII7AawXyprpf%2F%2FZ5L5%2Fe%2Fv9%2B%2Fff91ZN7nrG0icJSqrkknJxHm1h5Nl0J8%2F%2Fxg%2B%2FwDa%2Febzv39%2FWKQ2TG97ycIvq%2Bvn52oVxMHGxHDj8RcGQT4uEGZyCct98e3LL3YmJ2enNYxAi%2B48%2B8QQaizGIMLFBLaSlYWZgYWDWZaJhY2V%2BcvPfwz%2BeiIMf%2F%2F%2BY9CV4GAQ42Zh%2BPPvP8O%2Fv%2F%2BZmG7cff7u49c%2FDNtufGZgYmJiOHLvG8Pt1z8Yfv3%2Bz%2FDn19%2B3TCd2LNV7%2F%2FU3w7vPvxkWnHzDcOPFd4ZvQBPv3L79aM%2BS3nfMN88d%2BfyXkW0Lq6BiGAs7J8fHT9%2F%2FXTy%2BY82Lp0cdb5889hcgQJNU85JYFMXP%2B5aHqRmmZJ9kKMGAEBgtDCYYY6BFa%2BlrPc6yRf0LYYtZzG4YaNGibUNJVLuIcBNUTLMQM8ZoppdiaXnf9Xlf5z4ounDu4p57f%2Ff8Pt50SH9ZEfUuLehy93yMRBNroVAg6PV2yBbO9c94tK5v7suF3%2FlMs1o8oU27ltvIMic7fJv7uuqLJGa2UpPxlCILICBtGz1pYWooakeoDaTFgBtNWm04zl%2Fkbs53FnZ%2FZO%2BldGbFP5aaP50cj41pigi8XFjF2zp8ivpgsFMFHp0GgrQZL4DuYGCE6f3pzoBnUwRB8sYi4QGKHf7b5d8HiHWpMBsPvLKDeFiHmVEPBN0yMJyMIUhfb6gXbMkr4xtq1J6Z36eLpmiDH508LNShbDzB4kTIATguNsBqA1CHElJDhGdCGWsDkYY%2FTJh3lUelu384yTlzrtgDWVaggvG8qhDnYcEwwWi0wET%2FTNTh9Gh%2FvVn7v%2B2I%2BHlpWXS59ORgfOr7UGRkVNMUAWPtCMnHdbjjATFNKJeKpdLZYQY0crDzLUvfbHxdqfllj6a7p2VVjUqyGhYwPpZFqxYlf6hZ%2F7X3c736%2Fv4LV1blv94gEvsAAAAASUVORK5CYII%3D" ID="rdf:#$CnoJ1">Get Bookmark Add-ons</A>
     <HR>
     <DT><H3 LAST_MODIFIED="1177541040" PERSONAL_TOOLBAR_FOLDER="true" ID="rdf:#$FvPhC3">Bookmarks Toolbar Folder</H3>
 <DD>Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar
     <DL><p>
         <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/central/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$GvPhC3">Getting Started</A>
         <DT><A HREF="http://en-US.fxfeeds.mozilla.com/en-US/firefox/livebookmarks/" LAST_MODIFIED="1177541035" FEEDURL="http://en-US.fxfeeds.mozilla.com/en-US/firefox/headlines.xml" ID="rdf:#$HvPhC3">Latest Headlines</A>
 <DD>Livemark test comment
     </DL><p>
--- a/browser/components/places/tests/unit/test_placesTxn.js
+++ b/browser/components/places/tests/unit/test_placesTxn.js
@@ -104,33 +104,44 @@ var observer = {
     this._itemMovedNewIndex = newIndex;
   },
   QueryInterface: function(iid) {
     if (iid.equals(Ci.nsINavBookmarkObserver) ||
         iid.equals(Ci.nsISupports)) {
       return this;
     }
     throw Cr.NS_ERROR_NO_INTERFACE;
-  },
+  }
 };
 bmsvc.addObserver(observer, false);
 
 // get bookmarks root index
 var root = bmsvc.bookmarksRoot;
 
 // index at which items should begin
 var bmStartIndex = 1;
 
 // main
 function run_test() {
+  const DESCRIPTION_ANNO = "bookmarkProperties/description";
+  var testDescription = "this is my test description";
+  var annotationService = Cc["@mozilla.org/browser/annotation-service;1"].
+                          getService(Ci.nsIAnnotationService);
 
-  //Test creating a folder
-  var txn1 = ptSvc.createFolder("Testing folder", root, bmStartIndex);
+  //Test creating a folder with a description
+  var annos = [{ name: DESCRIPTION_ANNO,
+                 type: Ci.nsIAnnotationService.TYPE_STRING,
+                flags: 0,
+                value: testDescription,
+              expires: Ci.nsIAnnotationService.EXPIRE_NEVER }];
+  var txn1 = ptSvc.createFolder("Testing folder", root, bmStartIndex, annos);
   txn1.doTransaction();
   var folderId = bmsvc.getChildFolder(root, "Testing folder");
+  do_check_eq(testDescription, 
+              annotationService.getItemAnnotation(folderId, DESCRIPTION_ANNO));
   do_check_eq(observer._itemAddedIndex, bmStartIndex);
   do_check_eq(observer._itemAddedParent, root);
   do_check_eq(observer._itemAddedId, folderId);
   txn1.undoTransaction();
   do_check_eq(observer._itemRemovedId, folderId);
   do_check_eq(observer._itemRemovedFolder, root);
   do_check_eq(observer._itemRemovedIndex, bmStartIndex);
 
@@ -144,31 +155,32 @@ function run_test() {
   do_check_true(bmsvc.isBookmarked(uri("http://www.example.com")));
   txn2.undoTransaction();
   do_check_eq(observer._itemRemovedId, b);
   do_check_eq(observer._itemRemovedIndex, bmStartIndex);
 
   // Create to a folder
   var txn2a = ptSvc.createFolder("Folder", root, bmStartIndex);
   var fldrId = bmsvc.getChildFolder(root, "Folder");
-  var txn2b = ptSvc.createItem(uri("http://www.example.com"), fldrId, bmStartIndex, "Testing1b");
-  ptSvc.commitTransaction(txn2); 
-  var b2 = (bmsvc.getBookmarkIdsForURI(uri("http://www.example.com"), {}))[0];
+  var txn2b = ptSvc.createItem(uri("http://www.example2.com"), fldrId, bmStartIndex, "Testing1b");
+  ptSvc.commitTransaction(txn2b);
+  var b2 = (bmsvc.getBookmarkIdsForURI(uri("http://www.example2.com"), {}))[0];
   do_check_eq(observer._itemAddedId, b2);
   do_check_eq(observer._itemAddedIndex, bmStartIndex);
-  do_check_true(bmsvc.isBookmarked(uri("http://www.example.com")));
+  do_check_true(bmsvc.isBookmarked(uri("http://www.example2.com")));
   txn2.undoTransaction();
   do_check_eq(observer._itemRemovedId, b2);
   do_check_eq(observer._itemRemovedIndex, bmStartIndex);
 
   // Testing moving an item
-  ptSvc.commitTransaction(ptSvc.createItem(uri("http://www.example.com"), root, -1, "Testing2"));
-  ptSvc.commitTransaction(ptSvc.createItem(uri("http://www.example.com"), root, -1, "Testing3"));   
-  ptSvc.commitTransaction(ptSvc.createItem(uri("http://www.example.com"), fldrId, -1, "Testing4"));
-  var bkmkIds = bmsvc.getBookmarkIdsForURI(uri("http://www.example.com"), {});
+  ptSvc.commitTransaction(ptSvc.createItem(uri("http://www.example3.com"), root, -1, "Testing2"));
+  ptSvc.commitTransaction(ptSvc.createItem(uri("http://www.example3.com"), root, -1, "Testing3"));   
+  ptSvc.commitTransaction(ptSvc.createItem(uri("http://www.example3.com"), fldrId, -1, "Testing4"));
+  var bkmkIds = bmsvc.getBookmarkIdsForURI(uri("http://www.example3.com"), {});
+  bkmkIds.sort();
   var bkmk1Id = bkmkIds[0];
   var bkmk2Id = bkmkIds[1];
   var bkmk3Id = bkmkIds[2];
   var txn3 = ptSvc.moveItem(bkmk1Id, root, -1);
   txn3.doTransaction();
 
   // Moving items between the same folder
   do_check_eq(observer._itemMovedId, bkmk1Id);
@@ -261,17 +273,17 @@ function run_test() {
   var txn9 = ptSvc.editBookmarkURI(bkmk1Id, uri("http://newuri.com"));
   txn9.doTransaction();
   do_check_eq(observer._itemChangedId, bkmk1Id);
   do_check_eq(observer._itemChangedProperty, "uri");
   do_check_eq(observer._itemChangedValue, "http://newuri.com/");
   txn9.undoTransaction();
   do_check_eq(observer._itemChangedId, bkmk1Id);
   do_check_eq(observer._itemChangedProperty, "uri");
-  do_check_eq(observer._itemChangedValue, "http://www.example.com/");
+  do_check_eq(observer._itemChangedValue, "http://www.example3.com/");
   
   // Test edit item description
   var txn10 = ptSvc.editItemDescription(bkmk1Id, "Description1");
   txn10.doTransaction();
   do_check_eq(observer._itemChangedId, bkmk1Id);
   do_check_eq(observer._itemChangedProperty, "bookmarkProperties/description");
 
   // Testing edit keyword
@@ -340,16 +352,17 @@ function run_test() {
 
   // sortFolderByName
   ptSvc.commitTransaction(ptSvc.createFolder("Sorting folder", root, bmStartIndex, [], null));
   var srtFldId = bmsvc.getChildFolder(root, "Sorting folder");
   ptSvc.commitTransaction(ptSvc.createItem(uri("http://www.sortingtest.com"), srtFldId, -1, "c"));
   ptSvc.commitTransaction(ptSvc.createItem(uri("http://www.sortingtest.com"), srtFldId, -1, "b"));   
   ptSvc.commitTransaction(ptSvc.createItem(uri("http://www.sortingtest.com"), srtFldId, -1, "a"));
   var b = bmsvc.getBookmarkIdsForURI(uri("http://www.sortingtest.com"), {});
+  b.sort();
   var b1 = b[0];
   var b2 = b[1];
   var b3 = b[2];
   do_check_eq(0, bmsvc.getItemIndex(b1));
   do_check_eq(1, bmsvc.getItemIndex(b2));
   do_check_eq(2, bmsvc.getItemIndex(b3));
   var txn17 = ptSvc.sortFolderByName(srtFldId, 1);
   txn17.doTransaction();
@@ -367,18 +380,16 @@ function run_test() {
   ptSvc.commitTransaction(
   ptSvc.createItem(uri("http://dietrich.ganx4.com/mozilla/test-microsummary-content.php"),
                    root, -1, "micro test", null, null, null));
   var bId = (bmsvc.getBookmarkIdsForURI(uri("http://dietrich.ganx4.com/mozilla/test-microsummary-content.php"),{}))[0];
   do_check_true(!mss.hasMicrosummary(bId));
   var txn18 = ptSvc.editBookmarkMicrosummary(bId, tmpMs);
   txn18.doTransaction();
   do_check_eq(observer._itemChangedId, bId);
-  do_check_eq(observer._itemChangedProperty, "bookmarks/generatedTitle");
   do_check_true(mss.hasMicrosummary(bId));
   txn18.undoTransaction();
   do_check_eq(observer._itemChangedId, bId);
-  do_check_eq(observer._itemChangedProperty, "bookmarks/generatedTitle");
   do_check_true(!mss.hasMicrosummary(bId));
 
   // Testing edit Post Data...
   // mmm.. cant figure out a good way to test this.
 }
--- a/browser/components/preferences/privacy.xul
+++ b/browser/components/preferences/privacy.xul
@@ -97,25 +97,25 @@
     
     <script type="application/x-javascript" src="chrome://browser/content/preferences/privacy.js"/>
 
     <!-- History -->
     <groupbox id="historyGroup"
               xmlns:aaa="http://www.w3.org/2005/07/aaa">
       <caption label="&history.label;"/>
 
-      <hbox id="historyBox" align="center">
+      <hbox align="center">
         <checkbox id="rememberHistoryDays"
                   label="&rememberBefore.label;"
                   accesskey="&rememberBefore.accesskey;"
                   oncommand="gPrivacyPane.onchangeHistoryDaysCheck();"
-                  aaa:labelledby="historyBox"/>
+                  aaa:labelledby="rememberHistoryDays historyDays rememberAfter"/>
         <textbox id="historyDays" size="3"
-                 aaa:labelledby="historyBox"/>
-        <label>&rememberAfter.label;</label>
+                 aaa:labelledby="rememberHistoryDays historyDays rememberAfter"/>
+        <label id="rememberAfter"> &rememberAfter.label;</label>
       </hbox>
       <checkbox id="rememberForms"
                 label="&rememberForms.label;"
                 accesskey="&rememberForms.accesskey;"
                 preference="browser.formfill.enable"/>
       <checkbox id="rememberDownloads"
                 label="&rememberDownloads.label;"
                 accesskey="&rememberDownloads.accesskey;"
--- a/browser/components/preferences/security.js
+++ b/browser/components/preferences/security.js
@@ -356,18 +356,18 @@ var gSecurityPane = {
    * the master password button to show, and enables/disables it as necessary.
    * The master password is controlled by various bits of NSS functionality, so
    * the UI for it can't be controlled by the normal preference bindings.
    */
   _initMasterPasswordUI: function ()
   {
     var noMP = !this._masterPasswordSet();
 
-    var button = document.getElementById("changeMasterPassword");
-    button.disabled = noMP;
+    //var button = document.getElementById("changeMasterPassword");
+    //button.disabled = noMP;
 
     var checkbox = document.getElementById("useMasterPassword");
     checkbox.checked = !noMP;
   },
 
   /**
    * Returns true if the user has a master password set and false otherwise.
    */
--- a/browser/components/preferences/security.xul
+++ b/browser/components/preferences/security.xul
@@ -107,25 +107,25 @@
                 onsyncfrompreference="return gSecurityPane.readCheckPhish();"/>
       <radiogroup id="checkPhishChoice" class="indent"
                   preference="browser.safebrowsing.remoteLookups"
                   onsynctopreference="return gSecurityPane.writePhishChoice();">
         <radio id="cachedRadio"
                label="&useDownloadedList.label;"
                accesskey="&useDownloadedList.accesskey;"
                value="false"/>
-        <hbox id="onloadBox" align="center">
+        <hbox align="center">
           <radio id="onloadRadio"
                  label="&askThirdParty.label;"
                  accesskey="&askThirdParty.accesskey;"
-                 value="true" aaa:labelledby="onloadBox"/>
+                 value="true" aaa:labelledby="onloadRadio onloadProvider onloadAfter"/>
           <menulist id="onloadProvider"
                     preference="browser.safebrowsing.dataProvider"
                     onsyncfrompreference="return gSecurityPane.readOnloadPhishProvider();"
-                    aaa:labelledby="onloadBox"/>
+                    aaa:labelledby="onloadRadio onloadProvider onloadAfter"/>
           <label id="onloadAfter">&askThirdPartyAfter.label;</label>
         </hbox>
       </radiogroup>
 
     </groupbox>
 
     <!-- Passwords -->
     <groupbox id="passwordsGroup" orient="vertical">
@@ -138,21 +138,21 @@
                   onsyncfrompreference="return gSecurityPane.readSavePasswords();"/>
         <button id="passwordExceptions"
                 label="&passwordExceptions.label;"
                 accesskey="&passwordExceptions.accesskey;"
                 oncommand="gSecurityPane.showPasswordExceptions();"
                 preference="pref.privacy.disable_button.view_passwords_exceptions"/>
       </hbox>
       <hbox id="masterPasswordBox">
-        <checkbox id="useMasterPassword" flex="1"
+        <checkbox id="useMasterPassword" flex="1" disabled="true"
                   oncommand="gSecurityPane.updateMasterPasswordButton();"
                   label="&useMasterPassword.label;"
                   accesskey="&useMasterPassword.accesskey;"/>
-        <button id="changeMasterPassword"
+        <button id="changeMasterPassword" disabled="true"
                 label="&changeMasterPassword.label;"
                 accesskey="&changeMasterPassword.accesskey;"
                 oncommand="gSecurityPane.changeMasterPassword();"/>
       </hbox>
 
       <hbox id="showPasswordsBox">
         <spacer flex="1"/>
         <button id="showPasswords"
--- a/browser/components/safebrowsing/content/list-warden.js
+++ b/browser/components/safebrowsing/content/list-warden.js
@@ -183,87 +183,56 @@ PROT_ListWarden.prototype.isEvilURL = fu
  * @param callback Function to call with result 
  *       PROT_ListWarden.IN_BLACKLIST, PROT_ListWarden.IN_WHITELIST,
  *       or PROT_ListWarden.NOT_FOUND
  */
 function MultiTableQuerier(url, whiteTables, blackTables, callback) {
   this.debugZone = "multitablequerier";
   this.url_ = url;
 
-  this.whiteTables_ = whiteTables;
-  this.blackTables_ = blackTables;
-  this.whiteIdx_ = 0;
-  this.blackIdx_ = 0;
+  this.whiteTables_ = {};
+  for (var i = 0; i < whiteTables.length; i++) {
+    this.whiteTables_[whiteTables[i]] = true;
+  }
+
+  this.blackTables_ = {};
+  for (var i = 0; i < blackTables.length; i++) {
+    this.blackTables_[blackTables[i]] = true;
+  }
 
   this.callback_ = callback;
   this.listManager_ = Cc["@mozilla.org/url-classifier/listmanager;1"]
                       .getService(Ci.nsIUrlListManager);
 }
 
-/**
- * We first query the white tables in succession.  If any contain
- * the url, we stop.  If none contain the url, we query the black tables
- * in succession.  If any contain the url, we call callback and
- * stop.  If none of the black tables contain the url, then we just stop
- * (i.e., it's not black url).
- */
 MultiTableQuerier.prototype.run = function() {
-  var whiteTable = this.whiteTables_[this.whiteIdx_];
-  var blackTable = this.blackTables_[this.blackIdx_];
-  if (whiteTable) {
-    //G_Debug(this, "Looking in whitetable: " + whiteTable);
-    ++this.whiteIdx_;
-    this.listManager_.safeExists(whiteTable, this.url_,
-                                 BindToObject(this.whiteTableCallback_,
-                                              this));
-  } else if (blackTable) {
-    //G_Debug(this, "Looking in blacktable: " + blackTable);
-    ++this.blackIdx_;
-    this.listManager_.safeExists(blackTable, this.url_,
-                                 BindToObject(this.blackTableCallback_,
-                                              this));
-  } else {
-    // No tables left to check, so we quit.
-    G_Debug(this, "Not found in any tables: " + this.url_);
-    this.callback_(PROT_ListWarden.NOT_FOUND);
-
-    // Break circular ref to callback.
-    this.callback_ = null;
-    this.listManager_ = null;
-  }
+  /* ask the dbservice for all the tables to which this URL belongs */
+  this.listManager_.safeLookup(this.url_,
+                               BindToObject(this.lookupCallback_, this));
 }
 
-/**
- * After checking a white table, we return here.  If the url is found,
- * we can stop.  Otherwise, we call run again.
- */
-MultiTableQuerier.prototype.whiteTableCallback_ = function(isFound) {
-  //G_Debug(this, "whiteTableCallback_: " + isFound);
-  if (!isFound)
-    this.run();
-  else {
-    G_Debug(this, "Found in whitelist: " + this.url_)
-    this.callback_(PROT_ListWarden.IN_WHITELIST);
+MultiTableQuerier.prototype.lookupCallback_ = function(result) {
+  if (result == "") {
+    this.callback_(PROT_ListWarden.NOT_FOUND);
+    return;
+  }
 
-    // Break circular ref to callback.
-    this.callback_ = null;
-    this.listManager_ = null;
-  }
-}
+  var tableNames = result.split(",");
 
-/**
- * After checking a black table, we return here.  If the url is found,
- * we can call the callback and stop.  Otherwise, we call run again.
- */
-MultiTableQuerier.prototype.blackTableCallback_ = function(isFound) {
-  //G_Debug(this, "blackTableCallback_: " + isFound);
-  if (!isFound) {
-    this.run();
-  } else {
-    // In the blacklist, must be an evil url.
-    G_Debug(this, "Found in blacklist: " + this.url_)
-    this.callback_(PROT_ListWarden.IN_BLACKLIST);
+  /* Check the whitelists */
+  for (var i = 0; i < tableNames.length; i++) {
+    if (tableNames[i] && this.whiteTables_[tableNames[i]]) {
+      this.callback_(PROT_ListWarden.IN_WHITELIST);
+      return;
+    }
+  }
 
-    // Break circular ref to callback.
-    this.callback_ = null;
-    this.listManager_ = null;
+  /* Check the blacklists */
+  for (var i = 0; i < tableNames.length; i++) {
+    if (tableNames[i] && this.blackTables_[tableNames[i]]) {
+      this.callback_(PROT_ListWarden.IN_BLACKLIST);
+      return;
+    }
   }
+
+  /* Not in any lists we know about */
+  this.callback_(PROT_ListWarden.NOT_FOUND);
 }
--- a/browser/components/safebrowsing/content/sb-loader.js
+++ b/browser/components/safebrowsing/content/sb-loader.js
@@ -74,20 +74,18 @@ var safebrowsing = {
     safebrowsing.progressListener.QueryInterface(Ci.nsIWebProgressListener);
     var phishWarden = new appContext.PROT_PhishingWarden(
         safebrowsing.progressListener, getBrowser());
     safebrowsing.phishWarden = phishWarden;
 
     // Register tables
     // XXX: move table names to a pref that we originally will download
     // from the provider (need to workout protocol details)
-    phishWarden.registerWhiteTable("goog-white-domain");
-    phishWarden.registerWhiteTable("goog-white-url");
-    phishWarden.registerBlackTable("goog-black-url");
-    phishWarden.registerBlackTable("goog-black-enchash");
+    phishWarden.registerWhiteTable("goog-white-exp");
+    phishWarden.registerBlackTable("goog-phish-sha128");
 
     // Download/update lists if we're in non-enhanced mode
     phishWarden.maybeToggleUpdateChecking();
     safebrowsing.controller = new appContext.PROT_Controller(
         window, getBrowser(), phishWarden);
 
     // Remove the global progress listener.  The phishingWarden moves
     // the progress listener to the tabbrowser so we don't need it anymore.
--- a/browser/components/search/content/engineManager.js
+++ b/browser/components/search/content/engineManager.js
@@ -159,43 +159,46 @@ var gEngineManagerDialog = {
     var prompt = Cc["@mozilla.org/embedcomp/prompt-service;1"].
                  getService(Ci.nsIPromptService);
     var alias = { value: selectedEngine.alias };
     var strings = document.getElementById("engineManagerBundle");
     var title = strings.getString("editTitle");
     var msg = strings.getFormattedString("editMsg", [selectedEngine.name]);
 
     while (prompt.prompt(window, title, msg, alias, null, { })) {
-      var searchService = Cc["@mozilla.org/browser/search-service;1"].
-                          getService(Ci.nsIBrowserSearchService);
-      var engine = searchService.getEngineByAlias(alias.value);
       var bduplicate = false;
       var eduplicate = false;
 
-      if (engine) {
-        if (engine.name != selectedEngine.name)
-          eduplicate = true;
-      } else {
-        try {
-          var bmserv = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
-                       getService(Ci.nsINavBookmarksService);
-          if (bmserv.getURIForKeyword(alias.value))
-            bduplicate = true;
-        } catch(ex) {}
+      if (alias.value != "") {
+        var searchService = Cc["@mozilla.org/browser/search-service;1"].
+                            getService(Ci.nsIBrowserSearchService);
+        var engine = searchService.getEngineByAlias(alias.value);
 
-        // Check for duplicates in changes we haven't committed yet
-        var engines = gEngineView._engineStore.engines;
-        for each (var engine in engines) {
-          if (engine.alias == alias.value && 
-              engine.name != selectedEngine.name) {
+        if (engine) {
+          if (engine.name != selectedEngine.name)
             eduplicate = true;
-            break;
+        } else {
+          try {
+            var bmserv = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
+                         getService(Ci.nsINavBookmarksService);
+            if (bmserv.getURIForKeyword(alias.value))
+              bduplicate = true;
+          } catch(ex) {}
+
+          // Check for duplicates in changes we haven't committed yet
+          var engines = gEngineView._engineStore.engines;
+          for each (var engine in engines) {
+            if (engine.alias == alias.value && 
+                engine.name != selectedEngine.name) {
+              eduplicate = true;
+              break;
+            }
           }
         }
-      } 
+      }
 
       // Notify the user if they have chosen an existing engine/bookmark keyword
       if (eduplicate || bduplicate) {
         var dtitle = strings.getString("duplicateTitle");
         var bmsg = strings.getString("duplicateBookmarkMsg");
         var emsg = strings.getFormattedString("duplicateEngineMsg",
                                               [engine.name]);
 
--- a/browser/components/search/nsSearchSuggestions.js
+++ b/browser/components/search/nsSearchSuggestions.js
@@ -190,16 +190,25 @@ SuggestAutoCompleteResult.prototype = {
 
     if (index == 0)
       return "suggestfirst";  // category label on first line of results
 
     return "suggesthint";   // category label on any other line of results
   },
 
   /**
+   * Retrieves an image url.
+   * @param  index    the index of the image url requested
+   * @return          the image url at the specified index
+   */
+  getImageAt: function(index) {
+    return "";
+  },
+
+  /**
    * Removes a result from the resultset
    * @param  index    the index of the result to remove
    */
   removeValueAt: function(index, removeFromDatabase) {
     // Forward the removeValueAt call to the underlying result if we have one
     // Note: this assumes that the form history results were added to the top
     // of our arrays.
     if (removeFromDatabase && this._formHistoryResult &&
--- a/browser/components/sessionstore/src/nsSessionStore.js
+++ b/browser/components/sessionstore/src/nsSessionStore.js
@@ -475,16 +475,19 @@ SessionStoreService.prototype = {
       
       // clear this window from the list
       delete this._windows[aWindow.__SSi];
       
       // save the state without this window to disk
       this.saveStateDelayed();
     }
     
+    // cache the window state until the window is completely gone
+    aWindow.__SS_dyingCache = this._windows[aWindow.__SSi] || this._lastWindowClosed;
+    
     delete aWindow.__SSi;
   },
 
   /**
    * set up listeners for a new tab
    * @param aWindow
    *        Window reference
    * @param aPanel
@@ -636,34 +639,50 @@ SessionStoreService.prototype = {
       }
     });
 
     // restore to the given state
     this.restoreWindow(window, "(" + aState + ")", true);
   },
 
   getWindowState: function sss_getWindowState(aWindow) {
+    if (!aWindow.__SSi && aWindow.__SS_dyingCache)
+      return this._toJSONString({ windows: [aWindow.__SS_dyingCache] });
+    
     return this._toJSONString(this._getWindowState(aWindow));
   },
 
   setWindowState: function sss_setWindowState(aWindow, aState, aOverwrite) {
     this.restoreWindow(aWindow, "(" + aState + ")", aOverwrite);
   },
 
   getClosedTabCount: function sss_getClosedTabCount(aWindow) {
+    if (!aWindow.__SSi && aWindow.__SS_dyingCache)
+      return aWindow.__SS_dyingCache._closedTabs.length;
+    
     return this._windows[aWindow.__SSi]._closedTabs.length;
   },
 
   closedTabNameAt: function sss_closedTabNameAt(aWindow, aIx) {
-    var tabs = this._windows[aWindow.__SSi]._closedTabs;
+    var tabs;
     
-    return aIx in tabs ? tabs[aIx].title : null;
+    if (aWindow.__SSi && aWindow.__SSi in this._windows)
+      tabs = this._windows[aWindow.__SSi]._closedTabs;
+    else if (aWindow.__SS_dyingCache)
+      tabs = aWindow.__SS_dyingCache._closedTabs;
+    else
+      Components.returnCode = Cr.NS_ERROR_INVALID_ARG;
+    
+    return tabs && aIx in tabs ? tabs[aIx].title : null;
   },
 
   getClosedTabData: function sss_getClosedTabDataAt(aWindow) {
+    if (!aWindow.__SSi && aWindow.__SS_dyingCache)
+      return this._toJSONString(aWindow.__SS_dyingCache._closedTabs);
+    
     return this._toJSONString(this._windows[aWindow.__SSi]._closedTabs);
   },
 
   undoCloseTab: function sss_undoCloseTab(aWindow, aIndex) {
     var closedTabs = this._windows[aWindow.__SSi]._closedTabs;
 
     // default to the most-recently closed tab
     aIndex = aIndex || 0;
@@ -693,16 +712,20 @@ SessionStoreService.prototype = {
     }
   },
 
   getWindowValue: function sss_getWindowValue(aWindow, aKey) {
     if (aWindow.__SSi) {
       var data = this._windows[aWindow.__SSi].extData || {};
       return data[aKey] || "";
     }
+    else if (aWindow.__SS_dyingCache) {
+      data = aWindow.__SS_dyingCache.extData || {};
+      return data[aKey] || "";
+    }
     else {
       Components.returnCode = Cr.NS_ERROR_INVALID_ARG;
     }
   },
 
   setWindowValue: function sss_setWindowValue(aWindow, aKey, aStringValue) {
     if (aWindow.__SSi) {
       if (!this._windows[aWindow.__SSi].extData) {
--- a/browser/components/sessionstore/test/chrome/Makefile.in
+++ b/browser/components/sessionstore/test/chrome/Makefile.in
@@ -42,9 +42,9 @@ relativesrcdir  = browser/components/ses
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES =	test_bug350525.xul \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
-	$(INSTALL) $^ $(DEPTH)/_tests/testing/mochitest/chrome/$(relativesrcdir)
+	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/chrome/$(relativesrcdir)
--- a/browser/components/shell/src/Makefile.in
+++ b/browser/components/shell/src/Makefile.in
@@ -49,23 +49,24 @@ USE_STATIC_LIBS = 1
 
 REQUIRES	= \
 		  xpcom \
 		  string \
 		  uriloader \
 		  webbrowserpersist \
 		  dom \
 		  intl \
+		  unicharutil \
 		  necko \
 		  content \
 		  imglib2 \
 		  browsercomps \
 		  gfx \
 		  thebes \
-                  widget \
+		  widget \
 		  pref \
 		  layout \
 		  $(NULL)
 
 ifeq ($(OS_ARCH),WINNT)
 CPPSRCS = nsWindowsShellService.cpp
 else
 ifneq (,$(filter mac cocoa,$(MOZ_WIDGET_TOOLKIT)))
--- a/browser/components/shell/src/nsWindowsShellService.cpp
+++ b/browser/components/shell/src/nsWindowsShellService.cpp
@@ -16,20 +16,21 @@
  *
  * The Initial Developer of the Original Code is mozilla.org.
  * Portions created by the Initial Developer are Copyright (C) 2004
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
  *  Ben Goodger    <ben@mozilla.org>       (Clients, Mail, New Default Browser)
  *  Joe Hewitt     <hewitt@netscape.com>   (Set Background)
- *  Blake Ross     <blake@cs.stanford.edu  (Desktop Color, DDE support)
+ *  Blake Ross     <blake@cs.stanford.edu> (Desktop Color, DDE support)
  *  Jungshik Shin  <jshin@mailaps.org>     (I18N)
  *  Robert Strong  <robert.bugzilla@gmail.com>  (Long paths, DDE)
  *  Asaf Romano    <mano@mozilla.com>
+ *  Ryan Jones     <sciguyryan@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
@@ -54,81 +55,88 @@
 #include "nsNetUtil.h"
 #include "nsShellService.h"
 #include "nsWindowsShellService.h"
 #include "nsIProcess.h"
 #include "nsICategoryManager.h"
 #include "nsBrowserCompsCID.h"
 #include "nsDirectoryServiceUtils.h"
 #include "nsAppDirectoryServiceDefs.h"
-#include "shlobj.h"
 #include "nsIWindowsRegKey.h"
+#include "nsUnicharUtils.h"
 
 #include "windows.h"
 #include "shellapi.h"
+#include "shlobj.h"
 
 #include <mbstring.h>
 
 #ifndef MAX_BUF
 #define MAX_BUF 4096
 #endif
 
 #define REG_SUCCEEDED(val) \
   (val == ERROR_SUCCESS)
 
 #define REG_FAILED(val) \
   (val != ERROR_SUCCESS)
 
 NS_IMPL_ISUPPORTS2(nsWindowsShellService, nsIWindowsShellService, nsIShellService)
 
 static nsresult
-OpenUserKeyForReading(HKEY aStartKey, const char* aKeyName, HKEY* aKey)
+OpenUserKeyForReading(HKEY aStartKey, const nsAString& aKeyName, HKEY* aKey)
 {
-  DWORD result = ::RegOpenKeyEx(aStartKey, aKeyName, 0, KEY_READ, aKey);
+  const nsString &flatName = PromiseFlatString(aKeyName);
 
-  switch (result) {
+  DWORD res = ::RegOpenKeyExW(aStartKey, flatName.get(), 0, KEY_READ, aKey);
+  switch (res) {
   case ERROR_SUCCESS:
     break;
   case ERROR_ACCESS_DENIED:
     return NS_ERROR_FILE_ACCESS_DENIED;
   case ERROR_FILE_NOT_FOUND:
     if (aStartKey == HKEY_LOCAL_MACHINE) {
       // prevent infinite recursion on the second pass through here if 
       // ::RegOpenKeyEx fails in the all-users case. 
       return NS_ERROR_NOT_AVAILABLE;
     }
     return OpenUserKeyForReading(HKEY_LOCAL_MACHINE, aKeyName, aKey);
   }
+
   return NS_OK;
 }
 
 // Sets the default browser registry keys for Windows versions prior to Vista.
 // Try to open / create the key in HKLM and if that fails try to do the same
 // in HKCU. Though this is not strictly the behavior I would expect it is the
 // same behavior that IE has when setting the default browser previous to Vista.
 static nsresult
-OpenKeyForWriting(HKEY aStartKey, const char* aKeyName, HKEY* aKey,
+OpenKeyForWriting(HKEY aStartKey, const nsAString& aKeyName, HKEY* aKey,
                   PRBool aHKLMOnly)
 {
+  const nsString &flatName = PromiseFlatString(aKeyName);
+
   DWORD dwDisp = 0;
-  DWORD rv = ::RegCreateKeyEx(aStartKey, aKeyName, 0, NULL, 0,
-                              KEY_READ | KEY_WRITE, NULL, aKey, &dwDisp);
-
-  switch (rv) {
+  DWORD res = ::RegCreateKeyExW(aStartKey, flatName.get(), 0, NULL,
+                                0, KEY_READ | KEY_WRITE, NULL, aKey,
+                                &dwDisp);
+  switch (res) {
   case ERROR_SUCCESS:
     break;
   case ERROR_ACCESS_DENIED:
     if (aHKLMOnly || aStartKey == HKEY_CURRENT_USER)
       return NS_ERROR_FILE_ACCESS_DENIED;
     // fallback to HKCU immediately on access denied since we won't be able
     // to create the key.
     return OpenKeyForWriting(HKEY_CURRENT_USER, aKeyName, aKey, aHKLMOnly);
   case ERROR_FILE_NOT_FOUND:
-    rv = ::RegCreateKey(aStartKey, aKeyName, aKey);
-    if (rv != ERROR_SUCCESS) {
+    res = ::RegCreateKeyExW(aStartKey, flatName.get(), 0, NULL,
+                            0, KEY_READ | KEY_WRITE, NULL, aKey,
+                            NULL);
+    if (res != ERROR_SUCCESS) {
       if (aHKLMOnly || aStartKey == HKEY_CURRENT_USER) {
         // prevent infinite recursion on the second pass through here if 
         // ::RegCreateKey fails in the current user case.
         return NS_ERROR_FILE_ACCESS_DENIED;
       }
       return OpenKeyForWriting(HKEY_CURRENT_USER, aKeyName, aKey, aHKLMOnly);
     }
   }
@@ -197,22 +205,25 @@ OpenKeyForWriting(HKEY aStartKey, const 
 //     InstallInfo                      ShowIconsCommand  REG_SZ     <uninstpath> /ShowShortcuts
 //     shell\open\command               (default)         REG_SZ     <apppath>
 //     shell\properties                 (default)         REG_SZ     <appname> &Options
 //     shell\properties\command         (default)         REG_SZ     <apppath> -preferences
 //     shell\safemode                   (default)         REG_SZ     <appname> &Safe Mode
 //     shell\safemode\command           (default)         REG_SZ     <apppath> -safe-mode
 //
 
-typedef enum { NO_SUBSTITUTION           = 0x00,
-               APP_PATH_SUBSTITUTION     = 0x01,
-               EXE_NAME_SUBSTITUTION     = 0x02,
-               UNINST_PATH_SUBSTITUTION  = 0x04,
-               HKLM_ONLY                 = 0x08,
-               NON_ESSENTIAL             = 0x10 } SettingFlags;
+typedef enum {
+  NO_SUBSTITUTION           = 0x00,
+  APP_PATH_SUBSTITUTION     = 0x01,
+  EXE_NAME_SUBSTITUTION     = 0x02,
+  UNINST_PATH_SUBSTITUTION  = 0x04,
+  HKLM_ONLY                 = 0x08,
+  NON_ESSENTIAL             = 0x10
+} SettingFlags;
+
 typedef struct {
   char* keyName;
   char* valueName;
   char* valueData;
 
   PRInt32 flags;
 } SETTING;
 
@@ -325,25 +336,23 @@ static SETTING gSettings[] = {
   //     firefox.exe\shell\properties        (default)   REG_SZ  Firefox &Options
   //     firefox.exe\shell\safemode          (default)   REG_SZ  Firefox &Safe Mode
 };
 
 
 // Support for versions of shlobj.h that don't include the Vista API's
 #if !defined(IApplicationAssociationRegistration)
 
-typedef enum tagASSOCIATIONLEVEL
-{
+typedef enum tagASSOCIATIONLEVEL {
   AL_MACHINE,
   AL_EFFECTIVE,
   AL_USER
 } ASSOCIATIONLEVEL;
 
-typedef enum tagASSOCIATIONTYPE
-{
+typedef enum tagASSOCIATIONTYPE {
   AT_FILEEXTENSION,
   AT_URLPROTOCOL,
   AT_STARTMENUCLIENT,
   AT_MIMETYPE
 } ASSOCIATIONTYPE;
 
 MIDL_INTERFACE("4e530b0a-e611-4c77-a3ac-9031d022281b")
 IApplicationAssociationRegistration : public IUnknown
@@ -360,37 +369,36 @@ IApplicationAssociationRegistration : pu
                                                       BOOL *pfDefault) = 0;
   virtual HRESULT STDMETHODCALLTYPE QueryAppIsDefaultAll(ASSOCIATIONLEVEL alQueryLevel,
                                                          LPCWSTR pszAppRegistryName,
                                                          BOOL *pfDefault) = 0;
   virtual HRESULT STDMETHODCALLTYPE SetAppAsDefault(LPCWSTR pszAppRegistryName,
                                                     LPCWSTR pszSet,
                                                     ASSOCIATIONTYPE atSetType) = 0;
   virtual HRESULT STDMETHODCALLTYPE SetAppAsDefaultAll(LPCWSTR pszAppRegistryName) = 0;
-  virtual HRESULT STDMETHODCALLTYPE ClearUserAssociations( void) = 0;
+  virtual HRESULT STDMETHODCALLTYPE ClearUserAssociations(void) = 0;
 };
 #endif
 
 static const CLSID CLSID_ApplicationAssociationReg = {0x591209C7,0x767B,0x42B2,{0x9F,0xBA,0x44,0xEE,0x46,0x15,0xF2,0xC7}};
 static const IID   IID_IApplicationAssociationReg  = {0x4e530b0a,0xe611,0x4c77,{0xa3,0xac,0x90,0x31,0xd0,0x22,0x28,0x1b}};
 
 
 PRBool
 nsWindowsShellService::IsDefaultBrowserVista(PRBool aStartupCheck, PRBool* aIsDefaultBrowser)
 {
   IApplicationAssociationRegistration* pAAR;
   
-  HRESULT hr = CoCreateInstance (CLSID_ApplicationAssociationReg,
-                                 NULL,
-                                 CLSCTX_INPROC,
-                                 IID_IApplicationAssociationReg,
-                                 (void**)&pAAR);
+  HRESULT hr = CoCreateInstance(CLSID_ApplicationAssociationReg,
+                                NULL,
+                                CLSCTX_INPROC,
+                                IID_IApplicationAssociationReg,
+                                (void**)&pAAR);
   
-  if (SUCCEEDED(hr))
-  {
+  if (SUCCEEDED(hr)) {
     hr = pAAR->QueryAppIsDefaultAll(AL_EFFECTIVE,
                                     APP_REG_NAME,
                                     aIsDefaultBrowser);
     
     // If this is the first browser window, maintain internal state that we've
     // checked this session (so that subsequent window opens don't show the 
     // default browser dialog).
     if (aStartupCheck)
@@ -403,85 +411,85 @@ nsWindowsShellService::IsDefaultBrowserV
   return PR_FALSE;
 }
 
 PRBool
 nsWindowsShellService::SetDefaultBrowserVista()
 {
   IApplicationAssociationRegistration* pAAR;
   
-  HRESULT hr = CoCreateInstance (CLSID_ApplicationAssociationReg,
-                                 NULL,
-                                 CLSCTX_INPROC,
-                                 IID_IApplicationAssociationReg,
-                                 (void**)&pAAR);
+  HRESULT hr = CoCreateInstance(CLSID_ApplicationAssociationReg,
+                                NULL,
+                                CLSCTX_INPROC,
+                                IID_IApplicationAssociationReg,
+                                (void**)&pAAR);
   
-  if (SUCCEEDED(hr))
-  {
+  if (SUCCEEDED(hr)) {
     hr = pAAR->SetAppAsDefaultAll(APP_REG_NAME);
     
     pAAR->Release();
     return PR_TRUE;
   }
   
   return PR_FALSE;
 }
 
 NS_IMETHODIMP
-nsWindowsShellService::IsDefaultBrowser(PRBool aStartupCheck, PRBool* aIsDefaultBrowser)
+nsWindowsShellService::IsDefaultBrowser(PRBool aStartupCheck,
+                                        PRBool* aIsDefaultBrowser)
 {
   // To support side by side installs on Vista we also need to check if the
   // FirefoxHTML and FirefoxURL registry keys in HKLM / HKCU point to our
   // install location. If the HKLM keys point to this install location we have
   // to verify that the keys don't exist in HKCU and remove them if the app is
   // then set as default. If the HKLM keys don't point to this install location
   // then we have to add these keys in HKCU to over-ride the HKLM keys.
   if (IsDefaultBrowserVista(aStartupCheck, aIsDefaultBrowser))
     return NS_OK;
 
   SETTING* settings;
   SETTING* end = gSettings + sizeof(gSettings)/sizeof(SETTING);
 
   *aIsDefaultBrowser = PR_TRUE;
 
-  char exePath[MAX_BUF];
-  if (!::GetModuleFileName(0, exePath, MAX_BUF))
+  PRUnichar exePath[MAX_BUF];
+  if (!::GetModuleFileNameW(0, exePath, MAX_BUF))
     return NS_ERROR_FAILURE;
 
-  nsCAutoString appLongPath(exePath);
+  nsAutoString appLongPath(exePath);
 
   // Support short path to the exe so if it is already set the user is not
   // prompted to set the default browser again.
-  if (!::GetShortPathName(exePath, exePath, sizeof(exePath)))
+  if (!::GetShortPathNameW(exePath, exePath, sizeof(exePath)))
     return NS_ERROR_FAILURE;
 
-  nsCAutoString appShortPath;
-  ToUpperCase(appShortPath = exePath);
+  nsAutoString appShortPath(exePath);
+  ToUpperCase(appShortPath);
 
   nsCOMPtr<nsILocalFile> lf;
-  nsresult rv = NS_NewNativeLocalFile(nsDependentCString(exePath), PR_TRUE,
-                                      getter_AddRefs(lf));
+  nsresult rv = NS_NewLocalFile(appShortPath, PR_TRUE,
+                                getter_AddRefs(lf));
   if (NS_FAILED(rv))
     return rv;
 
-  nsCAutoString exeName;
-  rv = lf->GetNativeLeafName(exeName);
+  nsAutoString exeName;
+  rv = lf->GetLeafName(exeName);
   if (NS_FAILED(rv))
     return rv;
   ToUpperCase(exeName);
 
-  char currValue[MAX_BUF];
+  PRUnichar currValue[MAX_BUF];
   for (settings = gSettings; settings < end; ++settings) {
     if (settings->flags & NON_ESSENTIAL)
       continue; // This is not a registry key that determines whether
                 // or not we consider Firefox the "Default Browser."
-
-    nsCAutoString dataLongPath(settings->valueData);
-    nsCAutoString dataShortPath(settings->valueData);
-    nsCAutoString key(settings->keyName);
+    NS_ConvertUTF8toUTF16 dataLongPath(settings->valueData);
+    NS_ConvertUTF8toUTF16 dataShortPath(settings->valueData);
+    NS_ConvertUTF8toUTF16 key(settings->keyName);
+    NS_ConvertUTF8toUTF16 value(settings->valueName);
     if (settings->flags & APP_PATH_SUBSTITUTION) {
       PRInt32 offset = dataLongPath.Find("%APPPATH%");
       dataLongPath.Replace(offset, 9, appLongPath);
       // Remove the quotes around %APPPATH% in VAL_OPEN for short paths
       PRInt32 offsetQuoted = dataShortPath.Find("\"%APPPATH%\"");
       if (offsetQuoted != -1)
         dataShortPath.Replace(offsetQuoted, 11, appShortPath);
       else
@@ -489,23 +497,24 @@ nsWindowsShellService::IsDefaultBrowser(
     }
     if (settings->flags & EXE_NAME_SUBSTITUTION) {
       PRInt32 offset = key.Find("%APPEXE%");
       key.Replace(offset, 8, exeName);
     }
 
     ::ZeroMemory(currValue, sizeof(currValue));
     HKEY theKey;
-    nsresult rv = OpenUserKeyForReading(HKEY_CURRENT_USER, key.get(), &theKey);
+    rv = OpenUserKeyForReading(HKEY_CURRENT_USER, key, &theKey);
     if (NS_SUCCEEDED(rv)) {
       DWORD len = sizeof currValue;
-      DWORD result = ::RegQueryValueEx(theKey, settings->valueName, NULL, NULL, (LPBYTE)currValue, &len);
+      DWORD res = ::RegQueryValueExW(theKey, PromiseFlatString(value).get(),
+                                     NULL, NULL, (LPBYTE)currValue, &len);
       // Close the key we opened.
       ::RegCloseKey(theKey);
-      if (REG_FAILED(result) ||
+      if (REG_FAILED(res) ||
           !dataLongPath.Equals(currValue, CaseInsensitiveCompare) &&
           !dataShortPath.Equals(currValue, CaseInsensitiveCompare)) {
         // Key wasn't set, or was set to something else (something else became the default browser)
         *aIsDefaultBrowser = PR_FALSE;
         break;
       }
     }
   }
@@ -515,227 +524,243 @@ nsWindowsShellService::IsDefaultBrowser(
   // default browser dialog).
   if (aStartupCheck)
     mCheckedThisSession = PR_TRUE;
 
   return NS_OK;
 }
 
 DWORD
-nsWindowsShellService::DeleteRegKeyDefaultValue(HKEY baseKey, const char *keyName)
+nsWindowsShellService::DeleteRegKeyDefaultValue(HKEY baseKey,
+                                                const nsString& keyName)
 {
   HKEY key;
-  DWORD rc = ::RegOpenKeyEx(baseKey, keyName, 0, KEY_WRITE, &key);
-  if (rc == ERROR_SUCCESS) {
-    rc = ::RegDeleteValue(key, "");
+  DWORD res = ::RegOpenKeyExW(baseKey, keyName.get(),
+                              0, KEY_WRITE, &key);
+  if (res == ERROR_SUCCESS) {
+    res = ::RegDeleteValueW(key, EmptyString().get());
     ::RegCloseKey(key);
   }
-  return rc;
+
+  return res;
 }
 
 NS_IMETHODIMP
 nsWindowsShellService::SetDefaultBrowser(PRBool aClaimAllTypes, PRBool aForAllUsers)
 {
   // Delete the protocol and file handlers under HKCU if they exist. This way
   // the HKCU registry is cleaned up when HKLM is writeable or if it isn't
   // the values will then be added under HKCU.
-  (void)DeleteRegKey(HKEY_CURRENT_USER, "Software\\Classes\\http\\shell\\open");
-  (void)DeleteRegKey(HKEY_CURRENT_USER, "Software\\Classes\\http\\DefaultIcon");
-  (void)DeleteRegKey(HKEY_CURRENT_USER, "Software\\Classes\\https\\shell\\open");
-  (void)DeleteRegKey(HKEY_CURRENT_USER, "Software\\Classes\\https\\DefaultIcon");
-  (void)DeleteRegKey(HKEY_CURRENT_USER, "Software\\Classes\\ftp\\shell\\open");
-  (void)DeleteRegKey(HKEY_CURRENT_USER, "Software\\Classes\\ftp\\DefaultIcon");
-  (void)DeleteRegKey(HKEY_CURRENT_USER, "Software\\Classes\\FirefoxURL");
-  (void)DeleteRegKey(HKEY_CURRENT_USER, "Software\\Classes\\FirefoxHTML");
+  (void)DeleteRegKey(HKEY_CURRENT_USER,
+    NS_LITERAL_STRING("Software\\Classes\\http\\shell\\open"));
+  (void)DeleteRegKey(HKEY_CURRENT_USER,
+    NS_LITERAL_STRING("Software\\Classes\\http\\DefaultIcon"));
+  (void)DeleteRegKey(HKEY_CURRENT_USER,
+    NS_LITERAL_STRING("Software\\Classes\\https\\shell\\open"));
+  (void)DeleteRegKey(HKEY_CURRENT_USER,
+     NS_LITERAL_STRING("Software\\Classes\\https\\DefaultIcon"));
+  (void)DeleteRegKey(HKEY_CURRENT_USER,
+   NS_LITERAL_STRING("Software\\Classes\\ftp\\shell\\open"));
+  (void)DeleteRegKey(HKEY_CURRENT_USER,
+     NS_LITERAL_STRING("Software\\Classes\\ftp\\DefaultIcon"));
+  (void)DeleteRegKey(HKEY_CURRENT_USER,
+     NS_LITERAL_STRING("Software\\Classes\\FirefoxURL"));
+  (void)DeleteRegKey(HKEY_CURRENT_USER,
+     NS_LITERAL_STRING("Software\\Classes\\FirefoxHTML"));
 
-  (void)DeleteRegKeyDefaultValue(HKEY_CURRENT_USER, "Software\\Classes\\.htm");
-  (void)DeleteRegKeyDefaultValue(HKEY_CURRENT_USER, "Software\\Classes\\.html");
-  (void)DeleteRegKeyDefaultValue(HKEY_CURRENT_USER, "Software\\Classes\\.shtml");
-  (void)DeleteRegKeyDefaultValue(HKEY_CURRENT_USER, "Software\\Classes\\.xht");
-  (void)DeleteRegKeyDefaultValue(HKEY_CURRENT_USER, "Software\\Classes\\.xhtml");
+  (void)DeleteRegKeyDefaultValue(HKEY_CURRENT_USER,
+     NS_LITERAL_STRING("Software\\Classes\\.htm"));
+  (void)DeleteRegKeyDefaultValue(HKEY_CURRENT_USER,
+     NS_LITERAL_STRING("Software\\Classes\\.html"));
+  (void)DeleteRegKeyDefaultValue(HKEY_CURRENT_USER,
+     NS_LITERAL_STRING("Software\\Classes\\.shtml"));
+  (void)DeleteRegKeyDefaultValue(HKEY_CURRENT_USER,
+     NS_LITERAL_STRING("Software\\Classes\\.xht"));
+  (void)DeleteRegKeyDefaultValue(HKEY_CURRENT_USER,
+     NS_LITERAL_STRING("Software\\Classes\\.xhtml"));
 
   if (!aForAllUsers && SetDefaultBrowserVista())
     return NS_OK;
 
   SETTING* settings;
   SETTING* end = gSettings + sizeof(gSettings)/sizeof(SETTING);
 
-  char exePath[MAX_BUF];
-  if (!::GetModuleFileName(0, exePath, MAX_BUF))
+  PRUnichar exePath[MAX_BUF];
+  if (!::GetModuleFileNameW(0, exePath, MAX_BUF))
     return NS_ERROR_FAILURE;
 
-  nsCAutoString appLongPath(exePath);
+  nsAutoString appLongPath(exePath);
 
   nsCOMPtr<nsILocalFile> lf;
-  nsresult rv = NS_NewNativeLocalFile(nsDependentCString(exePath), PR_TRUE,
-                                      getter_AddRefs(lf));
+  nsresult rv = NS_NewLocalFile(nsDependentString(exePath), PR_TRUE,
+                                getter_AddRefs(lf));
   if (NS_FAILED(rv))
     return rv;
 
-  nsCAutoString exeName;
-  rv = lf->GetNativeLeafName(exeName);
+  nsAutoString exeName;
+  rv = lf->GetLeafName(exeName);
   if (NS_FAILED(rv))
     return rv;
   ToUpperCase(exeName);
 
   nsCOMPtr<nsIFile> appDir;
   rv = lf->GetParent(getter_AddRefs(appDir));
   if (NS_FAILED(rv))
     return rv;
 
-  nsCAutoString parentPath;
-  appDir->GetNativePath(parentPath);
-
-  nsCAutoString uninstLongPath(parentPath.get());
-  uninstLongPath.Append(UNINSTALL_EXE);
+  nsAutoString uninstLongPath;
+  appDir->GetPath(uninstLongPath);
+  uninstLongPath.AppendLiteral(UNINSTALL_EXE);
 
   for (settings = gSettings; settings < end; ++settings) {
-    nsCAutoString dataLongPath(settings->valueData);
-    nsCAutoString key(settings->keyName);
+    NS_ConvertUTF8toUTF16 dataLongPath(settings->valueData);
+    NS_ConvertUTF8toUTF16 key(settings->keyName);
+    NS_ConvertUTF8toUTF16 value(settings->valueName);
     if (settings->flags & APP_PATH_SUBSTITUTION) {
       PRInt32 offset = dataLongPath.Find("%APPPATH%");
       dataLongPath.Replace(offset, 9, appLongPath);
     }
     if (settings->flags & UNINST_PATH_SUBSTITUTION) {
       PRInt32 offset = dataLongPath.Find("%UNINSTPATH%");
       dataLongPath.Replace(offset, 12, uninstLongPath);
     }
     if (settings->flags & EXE_NAME_SUBSTITUTION) {
       PRInt32 offset = key.Find("%APPEXE%");
       key.Replace(offset, 8, exeName);
     }
 
-    SetRegKey(key.get(), settings->valueName, dataLongPath.get(),
+    SetRegKey(key, value, dataLongPath,
               (settings->flags & HKLM_ONLY));
   }
 
   // Select the Default Browser for the Windows XP Start Menu
-  SetRegKey(NS_LITERAL_CSTRING(SMI).get(), "", exeName.get(), PR_TRUE);
+  SetRegKey(NS_LITERAL_STRING(SMI), EmptyString(), exeName, PR_TRUE);
 
-  nsCOMPtr<nsIStringBundleService> bundleService(do_GetService("@mozilla.org/intl/stringbundle;1"));
+  nsCOMPtr<nsIStringBundleService>
+    bundleService(do_GetService("@mozilla.org/intl/stringbundle;1"));
   if (!bundleService)
     return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIStringBundle> bundle, brandBundle;
   rv = bundleService->CreateBundle(SHELLSERVICE_PROPERTIES, getter_AddRefs(bundle));
   NS_ENSURE_SUCCESS(rv, rv);
   rv = bundleService->CreateBundle(BRAND_PROPERTIES, getter_AddRefs(brandBundle));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Create the Start Menu item if it doesn't exist
   nsString brandFullName;
   brandBundle->GetStringFromName(NS_LITERAL_STRING("brandFullName").get(),
                                  getter_Copies(brandFullName));
-  nsCAutoString nativeFullName;
-  // For the now, we use 'A' APIs (see bug 240272, 239279)
-  NS_UTF16ToCString(brandFullName, NS_CSTRING_ENCODING_NATIVE_FILESYSTEM,
-                    nativeFullName);
 
-  nsCAutoString key1(NS_LITERAL_CSTRING(SMI));
+  nsAutoString key1(NS_LITERAL_STRING(SMI));
   key1.Append(exeName);
-  key1.Append("\\");
-  SetRegKey(key1.get(), "", nativeFullName.get(), PR_TRUE);
+  key1.AppendLiteral("\\");
+  SetRegKey(key1, EmptyString(), brandFullName, PR_TRUE);
 
   // Set the Options and Safe Mode start menu context menu item labels
-  nsCAutoString optionsKey(SMI);
+  nsAutoString optionsKey(NS_LITERAL_STRING(SMI));
   optionsKey.Append(exeName);
-  optionsKey.Append("\\shell\\properties");
+  optionsKey.AppendLiteral("\\shell\\properties");
 
-  nsCAutoString safeModeKey(SMI);
+  nsAutoString safeModeKey(NS_LITERAL_STRING(SMI));
   safeModeKey.Append(exeName);
-  safeModeKey.Append("\\shell\\safemode");
+  safeModeKey.AppendLiteral("\\shell\\safemode");
 
   nsString brandShortName;
   brandBundle->GetStringFromName(NS_LITERAL_STRING("brandShortName").get(),
                                  getter_Copies(brandShortName));
 
   const PRUnichar* brandNameStrings[] = { brandShortName.get() };
 
   // Set the Options menu item
   nsString optionsTitle;
   bundle->FormatStringFromName(NS_LITERAL_STRING("optionsLabel").get(),
-                               brandNameStrings, 1, getter_Copies(optionsTitle));
+                               brandNameStrings, 1,
+                               getter_Copies(optionsTitle));
   // Set the Safe Mode menu item
   nsString safeModeTitle;
   bundle->FormatStringFromName(NS_LITERAL_STRING("safeModeLabel").get(),
-                               brandNameStrings, 1, getter_Copies(safeModeTitle));
+                               brandNameStrings, 1,
+                               getter_Copies(safeModeTitle));
 
   // Set the registry keys
-  nsCAutoString nativeTitle;
-  // For the now, we use 'A' APIs (see bug 240272,  239279)
-  NS_UTF16ToCString(optionsTitle, NS_CSTRING_ENCODING_NATIVE_FILESYSTEM,
-                    nativeTitle);
-  SetRegKey(optionsKey.get(), "", nativeTitle.get(), PR_TRUE);
-  // For the now, we use 'A' APIs (see bug 240272,  239279)
-  NS_UTF16ToCString(safeModeTitle, NS_CSTRING_ENCODING_NATIVE_FILESYSTEM,
-                    nativeTitle);
-  SetRegKey(safeModeKey.get(), "", nativeTitle.get(), PR_TRUE);
+  SetRegKey(optionsKey, EmptyString(), optionsTitle, PR_TRUE);
+  SetRegKey(safeModeKey, EmptyString(), safeModeTitle, PR_TRUE);
 
   // Refresh the Shell
   SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);
   return NS_OK;
 }
 
 // Utility function to delete a registry subkey.
 DWORD
-nsWindowsShellService::DeleteRegKey(HKEY baseKey, const char *keyName)
+nsWindowsShellService::DeleteRegKey(HKEY baseKey, const nsString& keyName)
 {
- // Make sure input subkey isn't null. 
- if (!keyName || !::strlen(keyName))
-   return ERROR_BADKEY;
+  // Make sure input subkey isn't null.
+  if (keyName.IsEmpty())
+    return ERROR_BADKEY;
+
+  const nsString &flatName = PromiseFlatString(keyName);
 
- DWORD rc;
- // Open subkey.
- HKEY key;
- rc = ::RegOpenKeyEx(baseKey, keyName, 0, KEY_ENUMERATE_SUB_KEYS | DELETE, &key);
- 
- // Continue till we get an error or are done.
- while (rc == ERROR_SUCCESS) {
-   char subkeyName[_MAX_PATH];
-   DWORD len = sizeof subkeyName;
-   // Get first subkey name.  Note that we always get the
-   // first one, then delete it.  So we need to get
-   // the first one next time, also.
-   rc = ::RegEnumKeyEx(key, 0, subkeyName, &len, 0, 0, 0, 0);
-   if (rc == ERROR_NO_MORE_ITEMS) {
-     // No more subkeys.  Delete the main one.
-     rc = ::RegDeleteKey(baseKey, keyName);
-     break;
-   } 
-   if (rc == ERROR_SUCCESS) {
-     // Another subkey, delete it, recursively.
-     rc = DeleteRegKey(key, subkeyName);
-   }
- }
- 
- // Close the key we opened.
- ::RegCloseKey(key);
- return rc;
+  // Open subkey.
+  HKEY key;
+  DWORD res = ::RegOpenKeyExW(baseKey, flatName.get(), 0,
+                              KEY_ENUMERATE_SUB_KEYS | DELETE, &key);
+  // Continue till we get an error or are done.
+  while (res == ERROR_SUCCESS) {
+    PRUnichar subkeyName[MAX_PATH];
+    DWORD len = sizeof subkeyName;
+    // Get first subkey name.  Note that we always get the
+    // first one, then delete it.  So we need to get
+    // the first one next time, also.
+    res = ::RegEnumKeyExW(key, 0, subkeyName, &len, NULL, NULL,
+                          NULL, NULL);
+    if (res == ERROR_NO_MORE_ITEMS) {
+      // No more subkeys.  Delete the main one.
+      res = ::RegDeleteKeyW(baseKey, flatName.get());
+      break;
+    }
+    // If we find another subkey, delete it, recursively.
+    if (res == ERROR_SUCCESS)
+      res = DeleteRegKey(key, nsDependentString(subkeyName));
+  }
+  
+  // Close the key we opened.
+  ::RegCloseKey(key);
+  return res;
 }
 
 void
-nsWindowsShellService::SetRegKey(const char* aKeyName, const char* aValueName, 
-                                 const char* aValue, PRBool aHKLMOnly)
+nsWindowsShellService::SetRegKey(const nsString& aKeyName,
+                                 const nsString& aValueName,
+                                 const nsString& aValue, PRBool aHKLMOnly)
 {
-  char buf[MAX_BUF];
+  PRUnichar buf[MAX_BUF];
   DWORD len = sizeof buf;
 
   HKEY theKey;
-  nsresult rv = OpenKeyForWriting(HKEY_LOCAL_MACHINE, aKeyName, &theKey, aHKLMOnly);
+  nsresult rv = OpenKeyForWriting(HKEY_LOCAL_MACHINE, aKeyName, &theKey,
+                                  aHKLMOnly);
   if (NS_FAILED(rv))
     return;
 
   // Get the old value
-  DWORD result = ::RegQueryValueEx(theKey, aValueName, NULL, NULL, (LPBYTE)buf, &len);
+  DWORD res = ::RegQueryValueExW(theKey, PromiseFlatString(aValueName).get(),
+                                 NULL, NULL, (LPBYTE)buf, &len);
 
   // Set the new value
-  if (REG_FAILED(result) || strcmp(buf, aValue) != 0)
-    ::RegSetValueEx(theKey, aValueName, 0, REG_SZ, 
-                    (LPBYTE)aValue, nsDependentCString(aValue).Length());
-  
+  nsAutoString current(buf);
+  if (REG_FAILED(res) || !current.Equals(aValue)) {
+    const nsString &flatValue = PromiseFlatString(aValue);
+
+    ::RegSetValueExW(theKey, PromiseFlatString(aValueName).get(),
+                     0, REG_SZ, (const BYTE *)flatValue.get(),
+                     (flatValue.Length() + 1) * sizeof(PRUnichar));
+  }
+
   // Close the key we opened.
   ::RegCloseKey(theKey);
 }
 
 NS_IMETHODIMP
 nsWindowsShellService::GetShouldCheckDefaultBrowser(PRBool* aResult)
 {
   // If we've already checked, the browser has been started and this is a 
@@ -806,20 +831,18 @@ WriteBitmap(nsIFile* aFile, gfxIImageFra
   BITMAPFILEHEADER bf;
   bf.bfType = 0x4D42; // 'BM'
   bf.bfReserved1 = 0;
   bf.bfReserved2 = 0;
   bf.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
   bf.bfSize = bf.bfOffBits + bmi.biSizeImage;
 
   // get a file output stream
-  nsresult rv;
-
   nsCOMPtr<nsIOutputStream> stream;
-  rv = NS_NewLocalFileOutputStream(getter_AddRefs(stream), aFile);
+  nsresult rv = NS_NewLocalFileOutputStream(getter_AddRefs(stream), aFile);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // write the bitmap headers and rgb pixel data to the file
   rv = NS_ERROR_FAILURE;
   if (stream) {
     PRUint32 written;
     stream->Write((const char*)&bf, sizeof(BITMAPFILEHEADER), &written);
     if (written == sizeof(BITMAPFILEHEADER)) {
@@ -856,24 +879,27 @@ nsWindowsShellService::SetDesktopBackgro
 
   nsCOMPtr<gfxIImageFrame> gfxFrame;
 
   nsCOMPtr<nsIDOMHTMLImageElement> imgElement(do_QueryInterface(aElement));
   if (!imgElement) {
     // XXX write background loading stuff!
   } 
   else {
-    nsCOMPtr<nsIImageLoadingContent> imageContent = do_QueryInterface(aElement, &rv);
-    if (!imageContent) return rv;
+    nsCOMPtr<nsIImageLoadingContent> imageContent =
+      do_QueryInterface(aElement, &rv);
+    if (!imageContent)
+      return rv;
 
     // get the image container
     nsCOMPtr<imgIRequest> request;
     rv = imageContent->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
                                   getter_AddRefs(request));
-    if (!request) return rv;
+    if (!request)
+      return rv;
     nsCOMPtr<imgIContainer> container;
     rv = request->GetImage(getter_AddRefs(container));
     if (!container)
       return NS_ERROR_FAILURE;
 
     // get the current frame, which holds the image data
     container->GetCurrentFrame(getter_AddRefs(gfxFrame));
   }
@@ -903,162 +929,165 @@ nsWindowsShellService::SetDesktopBackgro
   rv = NS_GetSpecialDirectory(NS_APP_APPLICATION_REGISTRY_DIR,
                               getter_AddRefs(file));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // eventually, the path is "%APPDATA%\Mozilla\Firefox\Desktop Background.bmp"
   rv = file->Append(fileLeafName);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  nsCAutoString nativePath;
-  rv = file->GetNativePath(nativePath);
+  nsAutoString path;
+  rv = file->GetPath(path);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // write the bitmap to a file in the profile directory
   rv = WriteBitmap(file, gfxFrame);
 
   // if the file was written successfully, set it as the system wallpaper
   if (NS_SUCCEEDED(rv)) {
-     char   subKey[] = "Control Panel\\Desktop";
      PRBool result = PR_FALSE;
      DWORD  dwDisp = 0;
      HKEY   key;
      // Try to create/open a subkey under HKLM.
-     DWORD rc = ::RegCreateKeyEx( HKEY_CURRENT_USER,
-                                  subKey,
-                                  0,
-                                  NULL,
-                                  REG_OPTION_NON_VOLATILE,
-                                  KEY_WRITE,
-                                  NULL,
-                                  &key,
-                                  &dwDisp );
-    if (REG_SUCCEEDED(rc)) {
-      unsigned char tile[2];
-      unsigned char style[2];
-      if (aPosition == BACKGROUND_TILE) {
-        tile[0] = '1';
-        style[0] = '1';
-      }
-      else if (aPosition == BACKGROUND_CENTER) {
-        tile[0] = '0';
-        style[0] = '0';
-      }
-      else if (aPosition == BACKGROUND_STRETCH) {
-        tile[0] = '0';
-        style[0] = '2';
+     DWORD res = ::RegCreateKeyExW(HKEY_CURRENT_USER,
+                                   L"Control Panel\\Desktop",
+                                   0, NULL, REG_OPTION_NON_VOLATILE,
+                                   KEY_WRITE, NULL, &key, &dwDisp);
+    if (REG_SUCCEEDED(res)) {
+      PRUnichar tile[2], style[2];
+      switch (aPosition) {
+        case BACKGROUND_TILE:
+          tile[0] = '1';
+          style[0] = '1';
+          break;
+        case BACKGROUND_CENTER:
+          tile[0] = '0';
+          style[0] = '0';
+          break;
+        case BACKGROUND_STRETCH:
+          tile[0] = '0';
+          style[0] = '2';
+          break;
       }
       tile[1] = '\0';
       style[1] = '\0';
-      ::RegSetValueEx(key, "TileWallpaper", 0, REG_SZ, tile, sizeof(tile));
-      ::RegSetValueEx(key, "WallpaperStyle", 0, REG_SZ, style, sizeof(style));
-      ::SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (PVOID) nativePath.get(),
-                             SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
+
+      // The size is always 3 unicode characters.
+      PRInt32 size = 3 * sizeof(PRUnichar);
+      ::RegSetValueExW(key, L"TileWallpaper",
+                       0, REG_SZ, (const BYTE *)tile, size);
+      ::RegSetValueExW(key, L"WallpaperStyle",
+                       0, REG_SZ, (const BYTE *)style, size);
+      ::SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (PVOID)path.get(),
+                              SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
       // Close the key we opened.
       ::RegCloseKey(key);
     }
   }
   return rv;
 }
 
 NS_IMETHODIMP
 nsWindowsShellService::OpenApplication(PRInt32 aApplication)
 {
-  nsCAutoString application;
+  nsAutoString application;
   switch (aApplication) {
   case nsIShellService::APPLICATION_MAIL:
-    application = NS_LITERAL_CSTRING("Mail");
+    application.AssignLiteral("Mail");
     break;
   case nsIShellService::APPLICATION_NEWS:
-    application = NS_LITERAL_CSTRING("News");
+    application.AssignLiteral("News");
     break;
   }
 
   // The Default Client section of the Windows Registry looks like this:
   // 
   // Clients\aClient\
   //  e.g. aClient = "Mail"...
   //        \Mail\(default) = Client Subkey Name
   //             \Client Subkey Name
   //             \Client Subkey Name\shell\open\command\ 
   //             \Client Subkey Name\shell\open\command\(default) = path to exe
   //
-  nsCAutoString clientKey(NS_LITERAL_CSTRING("SOFTWARE\\Clients\\"));
-  clientKey += application;
+  nsAutoString clientKey;
+  clientKey.AssignLiteral("SOFTWARE\\Clients\\");
+  clientKey.Append(application);
 
   // Find the default application for this class.
   HKEY theKey;
-  nsresult rv = OpenUserKeyForReading(HKEY_CURRENT_USER, clientKey.get(), &theKey);
-  if (NS_FAILED(rv)) return rv;
+  nsresult rv = OpenUserKeyForReading(HKEY_CURRENT_USER, clientKey, &theKey);
+  if (NS_FAILED(rv))
+    return rv;
 
-  char buf[MAX_BUF];
+  PRUnichar buf[MAX_BUF];
   DWORD type, len = sizeof buf;
-  DWORD result = ::RegQueryValueEx(theKey, "", 0, &type, (LPBYTE)&buf, &len);
-  if (REG_FAILED(result) || nsDependentCString(buf).IsEmpty()) 
+  DWORD res = ::RegQueryValueExW(theKey, EmptyString().get(), 0,
+                                 &type, (LPBYTE)&buf, &len);
+
+  if (REG_FAILED(res) || !*buf)
     return NS_OK;
 
   // Close the key we opened.
   ::RegCloseKey(theKey);
 
   // Find the "open" command
-  clientKey.Append("\\");
+  clientKey.AppendLiteral("\\");
   clientKey.Append(buf);
-  clientKey.Append("\\shell\\open\\command");
+  clientKey.AppendLiteral("\\shell\\open\\command");
 
-  rv = OpenUserKeyForReading(HKEY_CURRENT_USER, clientKey.get(), &theKey);
-  if (NS_FAILED(rv)) return rv;
+  rv = OpenUserKeyForReading(HKEY_CURRENT_USER, clientKey, &theKey);
+  if (NS_FAILED(rv))
+    return rv;
 
   ::ZeroMemory(buf, sizeof(buf));
   len = sizeof buf;
-  result = ::RegQueryValueEx(theKey, "", 0, &type, (LPBYTE)&buf, &len);
-  if (REG_FAILED(result) || nsDependentCString(buf).IsEmpty()) 
+  res = ::RegQueryValueExW(theKey, EmptyString().get(), 0,
+                           &type, (LPBYTE)&buf, &len);
+  if (REG_FAILED(res) || !*buf)
     return NS_ERROR_FAILURE;
 
   // Close the key we opened.
   ::RegCloseKey(theKey);
 
-  nsCAutoString path(buf);
-
   // Look for any embedded environment variables and substitute their 
-  // values, as |::CreateProcess| is unable to do this. 
+  // values, as |::CreateProcessW| is unable to do this.
+  nsAutoString path(buf);
   PRInt32 end = path.Length();
   PRInt32 cursor = 0, temp = 0;
   ::ZeroMemory(buf, sizeof(buf));
   do {
-    // XXX : This would not work with multibyte strings. 
     cursor = path.FindChar('%', cursor);
     if (cursor < 0) 
       break;
 
     temp = path.FindChar('%', cursor + 1);
-
     ++cursor;
 
     ::ZeroMemory(&buf, sizeof(buf));
-    ::GetEnvironmentVariable(nsCAutoString(Substring(path, cursor, temp - cursor)).get(), 
-                             buf, sizeof(buf));
+
+    ::GetEnvironmentVariableW(nsAutoString(Substring(path, cursor, temp - cursor)).get(),
+                              buf, sizeof(buf));
     
     // "+ 2" is to subtract the extra characters used to delimit the environment
     // variable ('%').
-    path.Replace((cursor - 1), temp - cursor + 2, nsDependentCString(buf));
+    path.Replace((cursor - 1), temp - cursor + 2, nsDependentString(buf));
 
     ++cursor;
   }
   while (cursor < end);
 
-  STARTUPINFO si;
+  STARTUPINFOW si;
   PROCESS_INFORMATION pi;
 
-  ::ZeroMemory(&si, sizeof(STARTUPINFO));
+  ::ZeroMemory(&si, sizeof(STARTUPINFOW));
   ::ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
 
-  char *pathCStr = ToNewCString(path);
-  BOOL success = ::CreateProcess(NULL, pathCStr, NULL, NULL, FALSE, 0, NULL, 
-                                 NULL, &si, &pi);
-  nsMemory::Free(pathCStr);
+  BOOL success = ::CreateProcessW(NULL, (LPWSTR)path.get(), NULL,
+                                  NULL, FALSE, 0, NULL,  NULL,
+                                  &si, &pi);
   if (!success)
     return NS_ERROR_FAILURE;
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsWindowsShellService::GetDesktopBackgroundColor(PRUint32* aColor)
@@ -1074,74 +1103,82 @@ nsWindowsShellService::SetDesktopBackgro
   int aParameters[2] = { COLOR_BACKGROUND, COLOR_DESKTOP };
   BYTE r = (aColor >> 16);
   BYTE g = (aColor << 16) >> 24;
   BYTE b = (aColor << 24) >> 24;
   COLORREF colors[2] = { RGB(r,g,b), RGB(r,g,b) };
 
   ::SetSysColors(sizeof(aParameters) / sizeof(int), aParameters, colors);
 
-  char   subKey[] = "Control Panel\\Colors";
   PRBool result = PR_FALSE;
   DWORD  dwDisp = 0;
   HKEY   key;
   // Try to create/open a subkey under HKLM.
-  DWORD rc = ::RegCreateKeyEx(HKEY_CURRENT_USER, subKey, 0, NULL, 
-                              REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &key,
-                              &dwDisp);
-  if (REG_SUCCEEDED(rc)) {
-    unsigned char rgb[12];
+  DWORD rv = ::RegCreateKeyExW(HKEY_CURRENT_USER,
+                               L"Control Panel\\Colors", 0, NULL,
+                               REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL,
+                               &key, &dwDisp);
+
+  if (REG_SUCCEEDED(rv)) {
+    char rgb[12];
     sprintf((char*)rgb, "%u %u %u\0", r, g, b);
-    ::RegSetValueEx(key, "Background", 0, REG_SZ, (const unsigned char*)rgb, strlen((char*)rgb));
+    NS_ConvertUTF8toUTF16 backColor(rgb);
+
+    ::RegSetValueExW(key, L"Background",
+                     0, REG_SZ, (const BYTE *)backColor.get(),
+                     (backColor.Length() + 1) * sizeof(PRUnichar));
   }
   
   // Close the key we opened.
   ::RegCloseKey(key);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsWindowsShellService::GetUnreadMailCount(PRUint32* aCount)
 {
   *aCount = 0;
 
   HKEY accountKey;
   if (GetMailAccountKey(&accountKey)) {
     DWORD type, unreadCount;
     DWORD len = sizeof unreadCount;
-    DWORD result = ::RegQueryValueEx(accountKey, "MessageCount", 0, &type, 
-                                     (LPBYTE)&unreadCount, &len);
-    if (REG_SUCCEEDED(result)) {
+    DWORD res = ::RegQueryValueExW(accountKey, L"MessageCount", 0,
+                                   &type, (LPBYTE)&unreadCount, &len);
+    if (REG_SUCCEEDED(res))
       *aCount = unreadCount;
-    }
 
   // Close the key we opened.
   ::RegCloseKey(accountKey);
   }
 
   return NS_OK;
 }
 
 PRBool
 nsWindowsShellService::GetMailAccountKey(HKEY* aResult)
 {
+  NS_NAMED_LITERAL_STRING(unread,
+    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\UnreadMail\\");
+
   HKEY mailKey;
-  DWORD result = ::RegOpenKeyEx(HKEY_CURRENT_USER, 
-                                "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\UnreadMail\\",
-                                0, KEY_ENUMERATE_SUB_KEYS, &mailKey);
+  DWORD res = ::RegOpenKeyExW(HKEY_CURRENT_USER, unread.get(), 0,
+                              KEY_ENUMERATE_SUB_KEYS, &mailKey);
 
   PRInt32 i = 0;
   do {
-    char subkeyName[MAX_BUF];
+    PRUnichar subkeyName[MAX_BUF];
     DWORD len = sizeof subkeyName;
-    result = ::RegEnumKeyEx(mailKey, i++, subkeyName, &len, 0, 0, 0, 0);
-    if (REG_SUCCEEDED(result)) {
+    res = ::RegEnumKeyExW(mailKey, i++, subkeyName, &len, NULL, NULL,
+                          NULL, NULL);
+    if (REG_SUCCEEDED(res)) {
       HKEY accountKey;
-      result = ::RegOpenKeyEx(mailKey, subkeyName, 0, KEY_READ, &accountKey);
-      if (REG_SUCCEEDED(result)) {
+      res = ::RegOpenKeyExW(mailKey, PromiseFlatString(subkeyName).get(),
+                            0, KEY_READ, &accountKey);
+      if (REG_SUCCEEDED(res)) {
         *aResult = accountKey;
     
         // Close the key we opened.
         ::RegCloseKey(mailKey);
 	 
         return PR_TRUE;
       }
     }
@@ -1151,17 +1188,18 @@ nsWindowsShellService::GetMailAccountKey
   while (1);
 
   // Close the key we opened.
   ::RegCloseKey(mailKey);
   return PR_FALSE;
 }
 
 NS_IMETHODIMP
-nsWindowsShellService::OpenApplicationWithURI(nsILocalFile* aApplication, const nsACString& aURI)
+nsWindowsShellService::OpenApplicationWithURI(nsILocalFile* aApplication,
+                                              const nsACString& aURI)
 {
   nsresult rv;
   nsCOMPtr<nsIProcess> process = 
     do_CreateInstance("@mozilla.org/process/util;1", &rv);
   if (NS_FAILED(rv))
     return rv;
   
   rv = process->Init(aApplication);
--- a/browser/components/shell/src/nsWindowsShellService.h
+++ b/browser/components/shell/src/nsWindowsShellService.h
@@ -35,16 +35,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef nswindowsshellservice_h____
 #define nswindowsshellservice_h____
 
 #include "nscore.h"
+#include "nsStringAPI.h"
 #include "nsIWindowsShellService.h"
 
 #include <windows.h>
 #include <ole2.h>
 
 class nsWindowsShellService : public nsIWindowsShellService
 {
 public:
@@ -55,18 +56,21 @@ public:
   NS_DECL_NSISHELLSERVICE
   NS_DECL_NSIWINDOWSSHELLSERVICE
 
 protected:
   PRBool    IsDefaultBrowserVista(PRBool aStartupCheck, PRBool* aIsDefaultBrowser);
   PRBool    SetDefaultBrowserVista();
 
   PRBool    GetMailAccountKey(HKEY* aResult);
-  void      SetRegKey(const char* aKeyName, const char* aValueName, 
-                      const char* aValue, PRBool aHKLMOnly);
-  DWORD     DeleteRegKey(HKEY baseKey, const char *keyName);
-  DWORD     DeleteRegKeyDefaultValue(HKEY baseKey, const char *keyName);
+  void      SetRegKey(const nsString& aKeyName,
+                      const nsString& aValueName,
+                      const nsString& aValue, PRBool aHKLMOnly);
+
+  DWORD     DeleteRegKey(HKEY baseKey, const nsString& keyName);
+  DWORD     DeleteRegKeyDefaultValue(HKEY baseKey,
+                                     const nsString& keyName);
 
 private:
   PRBool    mCheckedThisSession;
 };
 
 #endif // nswindowsshellservice_h____
--- a/browser/config/version.txt
+++ b/browser/config/version.txt
@@ -1,1 +1,1 @@
-3.0a7pre
+3.0a8pre
--- a/browser/fuel/test/Makefile.in
+++ b/browser/fuel/test/Makefile.in
@@ -51,9 +51,9 @@ include $(topsrcdir)/config/rules.mk
 		browser_Bookmarks.js \
 		browser_Extensions.js \
 		ContentA.html \
 		ContentB.html \
 		ContentWithFrames.html \
 		$(NULL)
 
 libs::	$(_BROWSER_FILES)
-	$(INSTALL) $^ $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
+	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
--- a/browser/fuel/test/browser_ApplicationPrefs.js
+++ b/browser/fuel/test/browser_ApplicationPrefs.js
@@ -104,17 +104,17 @@ function test() {
   // test resetting an existing boolean property
   Application.prefs.get(testdata.boolean).reset();
   var val = Application.prefs.getValue(testdata.boolean, false);
   ok(val, "Reset existing string property for expected value");
   
   // test getting all preferences
   var allPrefs = Application.prefs.all;
   ok(allPrefs.length >= 800, "Check 'Application.prefs.all' for the right number of preferences");
-  is(allPrefs[0].name, "capability.policy.default.Window.parent.get", "Check 'Application.prefs.all' for the right starting preference");
+  ok(allPrefs[0].name.length > 0, "Check 'Application.prefs.all' for a valid name in the starting preference");
 
   // test the value of the preference root
   is(Application.prefs.root, "", "Check the Application preference root");
   
   // test for user changed preferences
   ok(Application.prefs.get("browser.shell.checkDefaultBrowser").modified, "A single preference is marked as modified.");
   ok(!Application.prefs.get(testdata.string).modified, "A single preference is marked as not modified.");
   
--- a/browser/installer/Makefile.in
+++ b/browser/installer/Makefile.in
@@ -62,44 +62,48 @@ ifneq (,$(BUILD_STATIC_LIBS)$(MOZ_ENABLE
 ifeq (WINNT,$(OS_ARCH))
 MOZ_PKG_MANIFEST_P = $(srcdir)/windows/packages-static
 else
 ifneq (,$(filter-out OS2 Darwin,$(OS_ARCH)))
 MOZ_PKG_MANIFEST_P = $(srcdir)/unix/packages-static
 endif
 endif
 else
-$(error you need a "--enable-static or --enable-libxul" build to create an installer)
+$(error you need a "--enable-static or --enable-libxul" build to package a build)
 endif
 
 MOZ_NONLOCALIZED_PKG_LIST = \
 	xpcom \
 	browser \
 	$(NULL)
 
 MOZ_LOCALIZED_PKG_LIST = $(AB_CD)
 
 MOZ_OPTIONAL_PKG_LIST = \
 	adt \
 	$(NULL)
 
-DEFINES += -DAB_CD=$(AB_CD) -DMOZ_APP_NAME=$(MOZ_APP_NAME)
+DEFINES += -DAB_CD=$(AB_CD) -DMOZ_APP_NAME=$(MOZ_APP_NAME) -DPREF_DIR=$(PREF_DIR)
 
 ifdef MOZ_PKG_MANIFEST_P
 MOZ_PKG_MANIFEST = packages-static
 
 $(MOZ_PKG_MANIFEST): $(MOZ_PKG_MANIFEST_P)
 	$(PERL) $(topsrcdir)/config/preprocessor.pl $(DEFINES) $(ACDEFINES) $< > $@
 endif
 
 ifneq (,$(filter mac cocoa,$(MOZ_WIDGET_TOOLKIT)))
 MOZ_PKG_MAC_DSSTORE=branding/dsstore
 MOZ_PKG_MAC_BACKGROUND=branding/background.png
 MOZ_PKG_MAC_ICON=branding/disk.icns
 MOZ_PKG_MAC_RSRC=branding/license.r
 endif
 
+ifndef LIBXUL_SDK
+INSTALL_SDK = 1
+endif
+
 include $(topsrcdir)/toolkit/mozapps/installer/packager.mk
 
 installer: removed-files
 ifdef INSTALLER_DIR
 	$(MAKE) -C $(INSTALLER_DIR)
 endif
--- a/browser/installer/unix/packages-static
+++ b/browser/installer/unix/packages-static
@@ -10,17 +10,17 @@
 
 #filter substitution
 
 bin/.autoreg
 
 [@AB_CD@]
 bin/chrome/@AB_CD@.jar
 bin/chrome/@AB_CD@.manifest
-bin/defaults/pref/firefox-l10n.js
+bin/@PREF_DIR@/firefox-l10n.js
 bin/defaults/existing-profile-defaults.js
 ; If you add a new directory you must explicitly call addDirectory in ab-CD.jst
 bin/browserconfig.properties
 bin/old-homepage-default.properties
 bin/searchplugins/*
 bin/defaults/profile/bookmarks.html
 bin/defaults/profile/localstore.rdf
 bin/defaults/profile/prefs.js
@@ -229,16 +229,18 @@ bin/components/nsURLFormatter.js
 bin/components/urlformatter.xpt
 bin/components/libbrowserdirprovider.so
 bin/components/libbrowsercomps.so
 bin/components/txEXSLTRegExFunctions.js
 bin/components/nsLivemarkService.js
 bin/components/nsTaggingService.js
 bin/components/nsDefaultCLH.js
 bin/components/nsContentPrefService.js
+bin/components/nsContentDispatchChooser.js
+bin/components/nsHandlerService.js
 
 ; Modules
 bin/modules/*
 
 ; Safe Browsing
 bin/components/nsSafebrowsingApplication.js
 bin/components/safebrowsing.xpt
 bin/components/nsUrlClassifierListManager.js
@@ -261,27 +263,27 @@ bin/chrome/classic.manifest
 bin/extensions/{972ce4c6-7e08-4474-a285-3208198ce6fd}/install.rdf
 bin/chrome/comm.jar
 bin/chrome/comm.manifest
 bin/chrome/toolkit.jar
 bin/chrome/toolkit.manifest
 bin/chrome/icons/default/default.xpm
 bin/chrome/reporter.manifest
 bin/chrome/reporter.jar
-bin/defaults/pref/reporter.js
+bin/@PREF_DIR@/reporter.js
 
 ; shell icons
 bin/icons/*.xpm
 bin/icons/*.png
 
 ; [Default Preferences]
 ; All the pref files must be part of base to prevent migration bugs
-bin/defaults/pref/firefox.js
-bin/defaults/pref/firefox-branding.js
-bin/defaults/pref/channel-prefs.js
+bin/@PREF_DIR@/firefox.js
+bin/@PREF_DIR@/firefox-branding.js
+bin/@PREF_DIR@/channel-prefs.js
 bin/greprefs/all.js
 bin/greprefs/security-prefs.js
 bin/greprefs/xpinstall.js
 bin/defaults/autoconfig/platform.js
 bin/defaults/autoconfig/prefcalls.js
 
 ; [Layout Engine Resources]
 ; Style Sheets, Graphics and other Resources used by the layout engine. 
@@ -341,16 +343,17 @@ bin/components/pipnss.xpt
 bin/components/pippki.xpt
 bin/libnss3.so
 bin/libsmime3.so
 bin/libsoftokn3.chk
 bin/libsoftokn3.so
 bin/libfreebl3.chk
 bin/libfreebl3.so
 bin/libssl3.so
+bin/libnssdbm3.so
 bin/chrome/pipnss.jar
 bin/chrome/pippki.jar
 bin/chrome/pippki.manifest
 
 ; [Updater]
 ;
 bin/updater
 
--- a/browser/installer/windows/nsis/installer.nsi
+++ b/browser/installer/windows/nsis/installer.nsi
@@ -815,29 +815,20 @@ Function preComponents
   ${Unless} ${FileExists} "$EXEDIR\optional\extensions\inspector@mozilla.org"
     Abort
   ${EndUnless}
   !insertmacro MUI_HEADER_TEXT "$(OPTIONAL_COMPONENTS_TITLE)" "$(OPTIONAL_COMPONENTS_SUBTITLE)"
   !insertmacro MUI_INSTALLOPTIONS_DISPLAY "components.ini"
 FunctionEnd
 
 Function leaveComponents
-  ; If DOMi exists then it will be Field 2.
-  StrCpy $R1 2
-  ${If} ${FileExists} "$EXEDIR\optional\extensions\inspector@mozilla.org"
-    ${MUI_INSTALLOPTIONS_READ} $R0 "components.ini" "Field $R1" "State"
-    ; State will be 1 for checked and 0 for unchecked so we can use that to set
-    ; the section flags for installation.
-    SectionSetFlags 1 $R0
-    IntOp $R1 $R1 + 1
-  ${Else}
-    SectionSetFlags 1 0 ; Disable install for DOMi
-  ${EndIf}
-
-  SectionSetFlags 2 0 ; Disable install of TalkBack
+  ${MUI_INSTALLOPTIONS_READ} $R0 "components.ini" "Field 2" "State"
+  ; State will be 1 for checked and 0 for unchecked so we can use that to set
+  ; the section flags for installation.
+  SectionSetFlags 1 $R0
 FunctionEnd
 
 Function preDirectory
   SetShellVarContext all  ; Set SHCTX to HKLM
   ${GetSingleInstallPath} "Software\Mozilla\${BrandFullNameInternal}" $R9
   ${If} $R9 == "false"
     SetShellVarContext current  ; Set SHCTX to HKCU
     ${GetSingleInstallPath} "Software\Mozilla\${BrandFullNameInternal}" $R9
@@ -1066,12 +1057,9 @@ Function .onInit
   ${If} ${FileExists} "$EXEDIR\optional\extensions\inspector@mozilla.org"
     ; Set the section size for DOMi.
     ${GetSize} "$EXEDIR\optional\extensions\inspector@mozilla.org" "/S=0K" $0 $8 $9
     SectionSetSize 1 $0
   ${Else}
     ; Hide DOMi in the components page if it isn't available.
     SectionSetText 1 ""
   ${EndIf}
-
-  ; Hide Talkback in the components page
-  SectionSetText 2 ""
 FunctionEnd
--- a/browser/installer/windows/nsis/shared.nsh
+++ b/browser/installer/windows/nsis/shared.nsh
@@ -53,16 +53,21 @@
 
   ${SetUninstallKeys}
 
   ${FixClassKeys}
 
   ; Remove files that may be left behind by the application in the
   ; VirtualStore directory.
   ${CleanVirtualStore}
+
+  ; Remove talkback if it is present (remove after bug 386760 is fixed)
+  ${If} ${FileExists} "$INSTDIR\extensions\talkback@mozilla.org\"
+    RmDir /r "$INSTDIR\extensions\talkback@mozilla.org\"
+  ${EndIf}
 !macroend
 !define PostUpdate "!insertmacro PostUpdate"
 
 !macro SetAsDefaultAppUser
   SetShellVarContext current
   ${SetHandlers}
 !macroend
 !define SetAsDefaultAppUser "!insertmacro SetAsDefaultAppUser"
@@ -421,10 +426,13 @@
 
   ; Remove the gopher key if the DefaultIcon is from firefox.exe.
   ReadRegStr $2 SHCTX "$0\gopher\DefaultIcon" ""
   ClearErrors
   ${WordFind} "$2" "${FileMainEXE}" "E+1{" $R1
   ${Unless} ${Errors}
     DeleteRegKey SHCTX "$0\gopher"
   ${EndUnless}
+
+  ; Remove protocol handler registry keys added by the MS shim
+  DeleteRegKey HKLM "Software\Classes\Firefox.URL"
 !macroend