Merge from cvs-trunk-mirror to mozilla-central
authorbenjamin@smedbergs.us
Thu, 17 Jan 2008 16:40:00 -0500
changeset 10368 f12729556fbb
parent 9995 27d22dda60ff (current diff)
parent 10367 8662aaa3c1a0 (diff)
child 10836 d403bde8a07c
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.9b3pre
Merge from cvs-trunk-mirror to mozilla-central
client.mk
client.py
config/autoconf.mk.in
config/rules.mk
configure.in
db/sqlite3/src/sqlite3file.h
dom/src/offline/nsDOMOfflineLoadStatusList.h
dom/tests/mochitest/ajax/offline/test_isLocallyAvailable.html
dom/tests/mochitest/ajax/offline/test_offlineResources.html
dom/tests/mochitest/ajax/offline/test_pendingOfflineLoads.html
embedding/browser/gtk/src/gtkmozembedmarshal.c
embedding/browser/gtk/src/gtkmozembedmarshal.h
js/src/Makefile.in
js/src/Makefile.ref
js/src/js.cpp
js/src/jsapi.cpp
js/src/jsarena.cpp
js/src/jsdbgapi.cpp
js/src/jsemit.cpp
js/src/jsgc.cpp
js/src/jshash.cpp
js/src/jsinterp.cpp
js/src/jslock.cpp
js/src/jsnum.cpp
js/src/jsobj.cpp
js/src/jsparse.cpp
js/src/jsregexp.cpp
js/src/jsscan.cpp
js/src/jsscope.cpp
js/src/jsscript.cpp
js/src/jsstr.cpp
js/src/jsutil.cpp
js/src/jsxml.cpp
storage/src/mozStorageAsyncIO.cpp
toolkit/content/widgets/nativescrollbar.xml
widget/public/nsIMenuRollup.idl
xpcom/ds/nsValueArray.cpp
xpcom/ds/nsValueArray.h
xpfe/global/resources/content/bindings/nativescrollbar.xml
--- a/accessible/src/base/nsBaseWidgetAccessible.cpp
+++ b/accessible/src/base/nsBaseWidgetAccessible.cpp
@@ -138,31 +138,16 @@ nsLinkableAccessible::GetState(PRUint32 
       nsLinkState linkState;
       link->GetLinkState(linkState);
       if (linkState == eLinkState_Visited) {
         *aState |= nsIAccessibleStates::STATE_TRAVERSED;
       }
     }
   }
 
-  // XXX What if we're in a contenteditable container?
-  //     We may need to go up the parent chain unless a better API is found
-  nsCOMPtr<nsIAccessible> docAccessible =
-    do_QueryInterface(nsCOMPtr<nsIAccessibleDocument>(GetDocAccessible()));
-  if (docAccessible) {
-    PRUint32 docState = 0, docExtraState = 0;
-    rv = docAccessible->GetFinalState(&docState, &docExtraState);
-    if (NS_SUCCEEDED(rv) &&
-        (docExtraState & nsIAccessibleStates::EXT_STATE_EDITABLE)) {
-      // Links not focusable in editor
-      *aState &= ~(nsIAccessibleStates::STATE_FOCUSED |
-                   nsIAccessibleStates::STATE_FOCUSABLE);
-    }
-  }
-
   return NS_OK;
 }
 
 NS_IMETHODIMP nsLinkableAccessible::GetValue(nsAString& _retval)
 {
   if (mIsLink) {
     nsCOMPtr<nsIDOMNode> linkNode(do_QueryInterface(mActionContent));
     nsCOMPtr<nsIPresShell> presShell(do_QueryReferent(mWeakShell));
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -1501,17 +1501,18 @@ NS_IMETHODIMP nsDocAccessible::FlushPend
     nsCOMPtr<nsIAccessible> accessible;
     accessibleEvent->GetAccessible(getter_AddRefs(accessible));
 
     PRUint32 eventType;
     accessibleEvent->GetEventType(&eventType);
     if (eventType == nsIAccessibleEvent::EVENT_DOM_CREATE || 
         eventType == nsIAccessibleEvent::EVENT_ASYNCH_SHOW) {
       nsCOMPtr<nsIAccessible> containerAccessible;
-      if (accessible) {
+      if (accessible && eventType == nsIAccessibleEvent::EVENT_ASYNCH_SHOW) {
+        // For asynch show, delayed invalidatation of parent's children
         accessible->GetParent(getter_AddRefs(containerAccessible));
         nsCOMPtr<nsPIAccessible> privateContainerAccessible =
           do_QueryInterface(containerAccessible);
         if (privateContainerAccessible)
           privateContainerAccessible->InvalidateChildren();
       }
 
       // Also fire text changes if the node being created could affect the text in an nsIAccessibleText parent.
@@ -1848,16 +1849,25 @@ NS_IMETHODIMP nsDocAccessible::Invalidat
   // We need to get an accessible for the mutation event's container node
   // If there is no accessible for that node, we need to keep moving up the parent
   // chain so there is some accessible.
   // We will use this accessible to fire the accessible mutation event.
   // We're guaranteed success, because we will eventually end up at the doc accessible,
   // and there is always one of those.
 
   if (aChild && !isHiding) {
+    if (!isAsynch) {
+      // DOM already updated with new objects -- invalidate parent's children now
+      // For asynch we must wait until layout updates before we invalidate the children
+      nsCOMPtr<nsPIAccessible> privateContainerAccessible =
+        do_QueryInterface(containerAccessible);
+      if (privateContainerAccessible) {
+        privateContainerAccessible->InvalidateChildren();
+      }
+    }
     // Fire EVENT_SHOW, EVENT_MENUPOPUP_START for newly visible content.
     // Fire after a short timer, because we want to make sure the view has been
     // updated to make this accessible content visible. If we don't wait,
     // the assistive technology may receive the event and then retrieve
     // nsIAccessibleStates::STATE_INVISIBLE for the event's accessible object.
     PRUint32 additionEvent = isAsynch ? nsIAccessibleEvent::EVENT_ASYNCH_SHOW :
                                         nsIAccessibleEvent::EVENT_DOM_CREATE;
     FireDelayedToolkitEvent(additionEvent, childNode, nsnull,
--- a/accessible/src/xul/nsXULMenuAccessible.cpp
+++ b/accessible/src/xul/nsXULMenuAccessible.cpp
@@ -46,18 +46,22 @@
 #include "nsIDOMKeyEvent.h"
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
 #include "nsIServiceManager.h"
 #include "nsIPresShell.h"
 #include "nsIContent.h"
 #include "nsGUIEvent.h"
 #include "nsXULFormControlAccessible.h"
+#include "nsILookAndFeel.h"
+#include "nsWidgetsCID.h"
 
 
+static NS_DEFINE_CID(kLookAndFeelCID, NS_LOOKANDFEEL_CID);
+
 /** ------------------------------------------------------ */
 /**  Impl. of nsXULSelectableAccessible                    */
 /** ------------------------------------------------------ */
 
 // Helper methos
 nsXULSelectableAccessible::nsXULSelectableAccessible(nsIDOMNode* aDOMNode,
                                                      nsIWeakReference* aShell):
 nsAccessibleWrap(aDOMNode, aShell)
@@ -317,38 +321,34 @@ nsXULMenuitemAccessible::GetState(PRUint
     nsAutoString checkValue;
     element->GetAttribute(NS_LITERAL_STRING("checked"), checkValue);
     if (checkValue.EqualsLiteral("true")) {
       *aState |= nsIAccessibleStates::STATE_CHECKED;
     }
   }
 
   // Combo box listitem
-  if (Role(this) == nsIAccessibleRole::ROLE_COMBOBOX_OPTION) {
+  PRBool isComboboxOption =
+    (Role(this) == nsIAccessibleRole::ROLE_COMBOBOX_OPTION);
+  if (isComboboxOption) {
     // Is selected?
     PRBool isSelected = PR_FALSE;
     nsCOMPtr<nsIDOMXULSelectControlItemElement>
       item(do_QueryInterface(mDOMNode));
     NS_ENSURE_TRUE(item, NS_ERROR_FAILURE);
     item->GetSelected(&isSelected);
 
     // Is collapsed?
     PRBool isCollapsed = PR_FALSE;
     nsCOMPtr<nsIAccessible> parentAccessible(GetParent());
     if (parentAccessible &&
         State(parentAccessible) & nsIAccessibleStates::STATE_INVISIBLE) {
       isCollapsed = PR_TRUE;
     }
     
-    // Is disabled?
-    if (0 == (*aState & nsIAccessibleStates::STATE_UNAVAILABLE)) {
-      *aState |= (nsIAccessibleStates::STATE_FOCUSABLE |
-                  nsIAccessibleStates::STATE_SELECTABLE);
-    }
-
     if (isSelected) {
       *aState |= nsIAccessibleStates::STATE_SELECTED;
       
       // Selected and collapsed?
       if (isCollapsed) {
         // Set selected option offscreen/invisible according to combobox state
         nsCOMPtr<nsIAccessible> grandParentAcc;
         parentAccessible->GetParent(getter_AddRefs(grandParentAcc));
@@ -364,16 +364,33 @@ nsXULMenuitemAccessible::GetState(PRUint
         if (aExtraState) {
           *aExtraState |=
             grandParentExtState & nsIAccessibleStates::EXT_STATE_OPAQUE;
         }
       } // isCollapsed
     } // isSelected
   } // ROLE_COMBOBOX_OPTION
 
+  // Set focusable and selectable for items that are available
+  // and whose metric setting does allow disabled items to be focused.
+  if (*aState & nsIAccessibleStates::STATE_UNAVAILABLE) {
+    // Honour the LookAndFeel metric.
+    nsCOMPtr<nsILookAndFeel> lookNFeel(do_GetService(kLookAndFeelCID));
+    PRInt32 skipDisabledMenuItems = 0;
+    lookNFeel->GetMetric(nsILookAndFeel::eMetric_SkipNavigatingDisabledMenuItem,
+                         skipDisabledMenuItems);
+    // We don't want the focusable and selectable states for combobox items,
+    // so exclude them here as well.
+    if (skipDisabledMenuItems || isComboboxOption) {
+      return NS_OK;
+    }
+  }
+  *aState|= (nsIAccessibleStates::STATE_FOCUSABLE |
+             nsIAccessibleStates::STATE_SELECTABLE);
+
   return NS_OK;
 }
 
 NS_IMETHODIMP nsXULMenuitemAccessible::GetName(nsAString& _retval)
 {
   nsCOMPtr<nsIDOMElement> element(do_QueryInterface(mDOMNode));
   if (!element) {
     return NS_ERROR_FAILURE;
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -107,26 +107,25 @@ pref("app.update.url", "https://aus2.moz
 // app.update.url.details is in branding section
 
 // User-settable override to app.update.url for testing purposes.
 //pref("app.update.url.override", "");
 
 // Interval: Time between checks for a new version (in seconds)
 //           default=1 day
 pref("app.update.interval", 86400);
-// Interval: Time before prompting the user to download a new version that 
-//           is available (in seconds) default=1 day
-pref("app.update.nagTimer.download", 86400);
-// Interval: Time before prompting the user to restart to install the latest
-//           download (in seconds) default=30 minutes
-pref("app.update.nagTimer.restart", 1800);
+// Interval: Time before prompting the user again to restart to install the
+//           latest download (in seconds) default=1 day
+pref("app.update.nagTimer.restart", 86400);
 // Interval: When all registered timers should be checked (in milliseconds)
 //           default=10 minutes
 pref("app.update.timer", 600000);
-// Show the Update Checking UI when the user was idle for x seconds
+// Give the user x seconds to react before showing the big UI. default=12 hrs
+pref("app.update.promptWaitTime", 43200);
+// Show the Update Checking/Ready UI when the user was idle for x seconds
 pref("app.update.idletime", 60);
 
 // Whether or not we show a dialog box informing the user that the update was
 // successfully applied. This is off in Firefox by default since we show a 
 // upgrade start page instead! Other apps may wish to show this UI, and supply
 // a whatsNewURL field in their brand.properties that contains a link to a page
 // which tells users what's new in this new update.
 pref("app.update.showInstalledUI", false);
@@ -530,17 +529,17 @@ pref("gecko.handlerService.schemes.webca
 // Safe browsing does nothing unless both these prefs are set.
 pref("browser.safebrowsing.enabled", true);
 pref("browser.safebrowsing.remoteLookups", false);
 
 // Prevent loading of pages identified as malware
 pref("browser.safebrowsing.malware.enabled", true);
 
 // Non-enhanced mode (local url lists) URL list to check for updates
-pref("browser.safebrowsing.provider.0.updateURL", "http://sb.google.com/safebrowsing/downloads?client={moz:client}&appver={moz:version}&pver=2.0");
+pref("browser.safebrowsing.provider.0.updateURL", "http://sb.google.com/safebrowsing/downloads?client={moz:client}&appver={moz:version}&pver=2.1");
 
 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?");
@@ -578,16 +577,18 @@ pref("browser.sessionstore.interval", 10
 // maximum amount of POSTDATA to be saved in bytes per history entry (-1 = all of it)
 // (NB: POSTDATA will be saved either entirely or not at all)
 pref("browser.sessionstore.postdata", 0);
 // on which sites to save text data, POSTDATA and cookies
 // 0 = everywhere, 1 = unencrypted sites, 2 = nowhere
 pref("browser.sessionstore.privacy_level", 1);
 // how many tabs can be reopened (per window)
 pref("browser.sessionstore.max_tabs_undo", 10);
+// maximum number of pages of back-history per tab to save
+pref("browser.sessionstore.max_tab_back_history", 10);
 
 // allow META refresh by default
 pref("accessibility.blockautorefresh", false);
 
 // import bookmarks.html into Places bookmarks
 pref("browser.places.importBookmarksHTML", true);
 
 // if false, will add the "Smart Bookmarks" folder to the personal toolbar
--- a/browser/base/content/aboutDialog.js
+++ b/browser/base/content/aboutDialog.js
@@ -44,17 +44,18 @@ function init(aEvent)
 
   var prefs = Components.classes["@mozilla.org/preferences-service;1"]
                         .getService(Components.interfaces.nsIPrefBranch);
 
   try {
     var distroId = prefs.getCharPref("distribution.id");
     if (distroId) {
       var distroVersion = prefs.getCharPref("distribution.version");
-      var distroAbout = prefs.getComplexValue("distribution.about", Ci.nsISupportsString);
+      var distroAbout = prefs.getComplexValue("distribution.about",
+        Component.interfaces.nsISupportsString);
   
       var distroField = document.getElementById("distribution");
       distroField.value = distroAbout;
       distroField.style.display = "block";
     
       var distroIdField = document.getElementById("distributionId");
       distroIdField.value = distroId + " - " + distroVersion;
       distroIdField.style.display = "block";
--- a/browser/base/content/baseMenuOverlay.xul
+++ b/browser/base/content/baseMenuOverlay.xul
@@ -107,43 +107,40 @@
         <menuitem id="aboutName"
                   accesskey="&aboutCmd.accesskey;"
                   label="&aboutCmd.label;"
                   oncommand="openAboutDialog();"/>
       </menupopup>
     </menu>
 
     <keyset id="baseMenuKeyset">
-        <key id="key_openHelp"
-            oncommand="openHelp('firefox-help', 'chrome://browser/locale/help/help.rdf');"
-# VK_HELP doesn't work on other platforms yet
 #ifdef XP_MACOSX
-            keycode="&openHelpMac.commandkey;"/>
-<!-- On mac, we support both the help key and Cmd+?
-     ...Map Cmd+Shift+/, show Cmd+
+<!-- On mac, we map Cmd+Shift+/, but show Cmd+?
      (that's for en-US, it might be different for other keyboard layouts) -->
         <key id="key_openHelpMac"
              oncommand="openHelp('firefox-help', 'chrome://browser/locale/help/help.rdf');"
-             key="&openHelpMac2.commandkey;"
-             modifiers="&openHelpMac2.modifiers;"/>
+             key="&openHelpMac.commandkey;"
+             modifiers="&openHelpMac.modifiers;"/>
         <key id="key_openHelpMacFrontend"
-             key="&openHelpMac2.frontendCommandkey;"
-             modifiers="&openHelpMac2.frontendModifiers;"/>
+             key="&openHelpMac.frontendCommandkey;"
+             modifiers="&openHelpMac.frontendModifiers;"/>
 <!-- These are used to build the Application menu under Cocoa widgets -->
         <key id="key_preferencesCmdMac"
              key="&preferencesCmdMac.commandkey;"
              modifiers="&preferencesCmdMac.modifiers;"/>
         <key id="key_hideThisAppCmdMac"
              key="&hideThisAppCmdMac.commandkey;"
              modifiers="&hideThisAppCmdMac.modifiers;"/>
         <key id="key_hideOtherAppsCmdMac"
              key="&hideOtherAppsCmdMac.commandkey;"
              modifiers="&hideOtherAppsCmdMac.modifiers;"/>
 #else
-             keycode="&openHelp.commandkey;"/>
+        <key id="key_openHelp"
+            oncommand="openHelp('firefox-help', 'chrome://browser/locale/help/help.rdf');"
+            keycode="&openHelp.commandkey;"/>
 #endif
     </keyset>
 
     <stringbundleset id="stringbundleset">
         <stringbundle id="bundle_browser" src="chrome://browser/locale/browser.properties"/>
         <stringbundle id="bundle_browser_region" src="chrome://browser-region/locale/region.properties"/>
     </stringbundleset>
 </overlay>
--- a/browser/base/content/browser-menubar.inc
+++ b/browser/base/content/browser-menubar.inc
@@ -351,26 +351,29 @@
 #endif
                           chromedir="&locale.dir;"
                           oncommand="BrowserForward(event, true)"
                           onclick="checkForMiddleClick(this, event);">
                   <observes element="Browser:Forward" attribute="disabled" />
                 </menuitem>
 
                 <menuitem label="&historyHomeCmd.label;"
-                          command="Browser:Home"
+                          oncommand="BrowserGoHome(event);"
+                          onclick="checkForMiddleClick(this, event);"
                           key="goHome"/>
+                <menuitem label="&showAllHistoryCmd.label;"
+#ifndef XP_MACOSX
+                          key="showAllHistoryKb"
+#endif
+                          command="Browser:ShowAllHistory"/>
                 <menuseparator id="startHistorySeparator" builder="start"/>
                 <menuseparator id="endHistorySeparator" builder="end"/>
                 <menu id="historyUndoMenu" label="&historyUndoMenu.label;" disabled="true">
                   <menupopup id="historyUndoPopup" onpopupshowing="HistoryMenu.populateUndoSubmenu();"/>
                 </menu>
-                <menuseparator id="endUndoSeparator"/>
-                <menuitem label="&showAllHistoryCmd.label;"
-                          command="Browser:ShowAllHistory"/>
               </menupopup>
             </menu>
 
   <menu id="bookmarksMenu" 
         label="&bookmarksMenu.label;" accesskey="&bookmarksMenu.accesskey;"
         ondragenter="PlacesMenuDNDController.onBookmarksMenuDragEnter(event);"
         ondragdrop="nsDragAndDrop.drop(event, BookmarksMenuDropHandler);"
         ondragover="nsDragAndDrop.dragOver(event, BookmarksMenuDropHandler);"
@@ -378,17 +381,17 @@
     <menupopup id="bookmarksMenuPopup"
                type="places" asyncinit="true"
                place="place:folder=2&amp;expandQueries=1"
                context="placesContext"
                openInTabs="children"
                oncommand="BookmarksEventHandler.onCommand(event);"
                onclick="BookmarksEventHandler.onClick(event);"
                onpopupshowing="BookmarksEventHandler.onPopupShowing(event);">
-      <menuitem label="&addCurPageAsCmd.label;" 
+      <menuitem label="&bookmarkThisPageCmd.label;" 
                 command="Browser:AddBookmarkAs" key="addBookmarkAsKb"/>
       <menuitem id="subscribeToPageMenuitem"
                 label="&subscribeToPageMenuitem.label;"
                 oncommand="return FeedHandler.subscribeToFeed(null, event);"
                 onclick="checkForMiddleClick(this, event);"
                 disabled="true"/>
       <menu id="subscribeToPageMenupopup"
             label="&subscribeToPageMenupopup.label;"
--- a/browser/base/content/browser-places.js
+++ b/browser/base/content/browser-places.js
@@ -592,21 +592,19 @@ var BookmarksMenuDropHandler = {
    *          A drop event
    * @param   data
    *          Data that was dropped
    * @param   session
    *          The active DragSession
    */
   onDrop: function BMDH_onDrop(event, data, session) {
     var view = document.getElementById("bookmarksMenuPopup");
-
-    // The insertion point for a menupopup view should be -1 during a drag
-    // & drop operation.
-    NS_ASSERT(view.insertionPoint.index == -1, "Insertion point for an menupopup view during a drag must be -1!");
-    PlacesControllerDragHelper.onDrop(null, view, view.insertionPoint, 1);
+    // Put the item at the end of bookmark menu
+    var ip = new InsertionPoint(PlacesUtils.bookmarksMenuFolderId, -1);
+    PlacesControllerDragHelper.onDrop(null, view, ip);
     view._rebuild();
   }
 };
 
 /**
  * Handles special drag and drop functionality for menus on the Bookmarks 
  * Toolbar and Bookmarks Menu.
  */
--- a/browser/base/content/browser-sets.inc
+++ b/browser/base/content/browser-sets.inc
@@ -239,35 +239,36 @@
 #endif
 #ifdef XP_UNIX
     <key id="goBackKb2" key="&goBackCmd.commandKey;" command="Browser:Back" modifiers="accel"/>
     <key id="goForwardKb2" key="&goForwardCmd.commandKey;" command="Browser:Forward" modifiers="accel"/>
 #endif
     <key id="goHome" keycode="VK_HOME" command="Browser:Home" modifiers="alt"/>
     <key keycode="VK_F5" command="Browser:Reload"/>
 #ifndef XP_MACOSX
+    <key id="showAllHistoryKb" key="&showAllHistoryCmd.commandkey;" command="Browser:ShowAllHistory" modifiers="accel,shift"/>
     <key keycode="VK_F5" command="Browser:ReloadSkipCache" modifiers="accel"/>
     <key id="key_fullScreen" keycode="VK_F11" command="View:FullScreen"/>
 #endif
     <key key="&reloadCmd.commandkey;" command="Browser:Reload" modifiers="accel" id="key_reload"/>
     <key key="&reloadCmd.commandkey;" command="Browser:ReloadSkipCache" modifiers="accel,shift"/>
     <key id="key_viewSource" key="&pageSourceCmd.commandkey;" command="View:PageSource" modifiers="accel"/>
 #ifndef XP_WIN
     <key id="key_viewInfo"   key="&pageInfoCmd.commandkey;"   command="View:PageInfo"   modifiers="accel"/>
 #endif
     <key id="key_find" key="&findOnCmd.commandkey;" command="cmd_find" modifiers="accel"/>
     <key id="key_findAgain" key="&findAgainCmd.commandkey;" command="cmd_findAgain" modifiers="accel"/>
     <key id="key_findPrevious" key="&findAgainCmd.commandkey;" command="cmd_findPrevious" modifiers="accel,shift"/>
     <key keycode="&findAgainCmd.commandkey2;" command="cmd_findAgain"/>
     <key keycode="&findAgainCmd.commandkey2;"  command="cmd_findPrevious" modifiers="shift"/>
 
-    <key id="addBookmarkAsKb" key="&addCurPageAsCmd.commandkey;" command="Browser:AddBookmarkAs" modifiers="accel"/>
+    <key id="addBookmarkAsKb" key="&bookmarkThisPageCmd.commandkey;" command="Browser:AddBookmarkAs" modifiers="accel"/>
 # Accel+Shift+A-F are reserved on GTK2
 #ifndef MOZ_WIDGET_GTK2
-    <key id="bookmarkAllTabsKb" key="&addCurPageAsCmd.commandkey;" command="Browser:BookmarkAllTabs" modifiers="accel,shift"/>
+    <key id="bookmarkAllTabsKb" key="&bookmarkThisPageCmd.commandkey;" command="Browser:BookmarkAllTabs" modifiers="accel,shift"/>
     <key id="manBookmarkKb" key="&bookmarksSidebarCmd.commandkey;" command="Browser:ShowAllBookmarks" modifiers="accel,shift"/>
 #endif
     <key id="viewBookmarksSidebarKb" key="&bookmarksSidebarCmd.commandkey;" command="viewBookmarksSidebar" modifiers="accel"/>
 #ifdef XP_WIN
 # Cmd+I is conventially mapped to Info on MacOS X, thus it should not be 
 # overridden for other purposes there. 
     <key id="viewBookmarksSidebarWinKb" key="&bookmarksSidebarWinCmd.commandkey;" command="viewBookmarksSidebar" modifiers="accel"/>
 #endif
--- a/browser/base/content/browser.css
+++ b/browser/base/content/browser.css
@@ -1,30 +1,33 @@
 searchbar {
   -moz-binding: url("chrome://browser/content/search/search.xml#searchbar");
 }
 
+tabbrowser {
+  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser");
+}
+
+toolbar[printpreview="true"] {
+  -moz-binding: url("chrome://global/content/printPreviewBindings.xml#printpreviewtoolbar");
+}
+
 /* ::::: location bar ::::: */
 #urlbar {
   -moz-binding: url(chrome://browser/content/urlbarBindings.xml#urlbar);
 }
 
 #PopupAutoComplete {
   -moz-binding: url("chrome://browser/content/urlbarBindings.xml#browser-autocomplete-result-popup");
 }
 
 #PopupAutoCompleteRichResult {
   -moz-binding: url("chrome://browser/content/urlbarBindings.xml#urlbar-rich-result-popup");
 }
 
-/* ::::: print preview toolbar ::::: */
-toolbar[printpreview="true"] {
-  -moz-binding: url("chrome://global/content/printPreviewBindings.xml#printpreviewtoolbar");
-}
-
 menuitem.spell-suggestion {
   font-weight: bold;
 }
 
 #sidebar-box toolbarbutton.tabs-closebutton {
   -moz-user-focus: normal;
 }
 
@@ -32,53 +35,23 @@ menuitem.spell-suggestion {
   display: none;
 }
 
 /* apply Fitts' law to the notification bar's close button */
 window[sizemode="maximized"] #content .notification-inner {
   border-right: 0px !important;
 }
 
-tabbrowser {
-  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser");
-}
-
-.tabbrowser-tabs {
-  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-tabs");
-}
-
-%ifdef XP_MACOSX
-.tabbrowser-arrowscrollbox {
-  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-arrowscrollbox");
-}
-%endif
-
-.tabs-alltabs-popup {
-  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-alltabs-popup");
-}
-
-.tabbrowser-tab {
-  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-tab");
-}
-
-.tabbrowser-tab > .tab-close-button,
-.tabbrowser-tabs .tabs-closebutton {
-  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-close-tab-button");
-}
-
-.tab-close-button {
+/* Hide extension toolbars that neglected to set the proper class */
+window[chromehidden~="location"][chromehidden~="toolbar"] toolbar:not(.chromeclass-menubar),
+window[chromehidden~="toolbar"] toolbar:not(.toolbar-primary):not(.chromeclass-menubar) {
   display: none;
 }
 
-.tabbrowser-tabs:not([closebuttons="noclose"]):not([closebuttons="closeatend"]) > .tabbrowser-tab[selected="true"] > .tab-close-button {
-  display: -moz-box;
+#navigator-toolbox ,
+#status-bar ,
+#mainPopupSet {
+  min-width: 1px;
 }
 
-.tabbrowser-tabs[closebuttons="alltabs"] > .tabbrowser-tab > .tab-close-button {
-  display: -moz-box;
+#FindToolbar {
+  overflow-x: hidden;
 }
-
-/* Hide extension toolbars that neglected to set the proper class */
-window[chromehidden~="location"][chromehidden~="toolbar"] toolbar:not(.chromeclass-menubar),
-window[chromehidden~="toolbar"] toolbar:not(.toolbar-primary):not(.chromeclass-menubar)
-{
-  display: none;
-}
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -37,16 +37,17 @@
 #   Tom Germeau <tom.germeau@epigoon.com>
 #   Jesse Ruderman <jruderman@gmail.com>
 #   Joe Hughes <joe@retrovirus.com>
 #   Pamela Greene <pamg.bugs@gmail.com>
 #   Michael Ventnor <m.ventnor@gmail.com>
 #   Simon Bünzli <zeniko@gmail.com>
 #   Johnathan Nightingale <johnath@mozilla.com>
 #   Ehsan Akhgari <ehsan.akhgari@gmail.com>
+#   Dão Gottwald <dao@mozilla.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
@@ -1318,17 +1319,17 @@ function gotoHistoryIndex(aEvent)
     return false;
 
   var where = whereToOpenLink(aEvent);
 
   if (where == "current") {
     // Normal click.  Go there in the current tab and update session history.
 
     try {
-      getWebNavigation().gotoIndex(index);
+      getBrowser().gotoIndex(index);
     }
     catch(ex) {
       return false;
     }
     return true;
   }
   else {
     // Modified click.  Go there in a new tab/window.
@@ -1343,17 +1344,17 @@ function gotoHistoryIndex(aEvent)
 }
 
 function BrowserForward(aEvent, aIgnoreAlt)
 {
   var where = whereToOpenLink(aEvent, false, aIgnoreAlt);
 
   if (where == "current") {
     try {
-      getWebNavigation().goForward();
+      getBrowser().goForward();
     }
     catch(ex) {
     }
   }
   else {
     var sessionHistory = getWebNavigation().sessionHistory;
     var currentIndex = sessionHistory.index;
     var entry = sessionHistory.getEntryAtIndex(currentIndex + 1, false);
@@ -1363,17 +1364,17 @@ function BrowserForward(aEvent, aIgnoreA
 }
 
 function BrowserBack(aEvent, aIgnoreAlt)
 {
   var where = whereToOpenLink(aEvent, false, aIgnoreAlt);
 
   if (where == "current") {
     try {
-      getWebNavigation().goBack();
+      getBrowser().goBack();
     }
     catch(ex) {
     }
   }
   else {
     var sessionHistory = getWebNavigation().sessionHistory;
     var currentIndex = sessionHistory.index;
     var entry = sessionHistory.getEntryAtIndex(currentIndex - 1, false);
@@ -1440,19 +1441,20 @@ function BrowserReloadSkipCache()
 }
 
 function BrowserHome()
 {
   var homePage = gHomeButton.getHomePage();
   loadOneOrMoreURIs(homePage);
 }
 
-function BrowserHomeClick(aEvent)
+function BrowserGoHome(aEvent)
 {
-  if (aEvent.button == 2) // right-click: do nothing
+  if (aEvent && "button" in aEvent &&
+      aEvent.button == 2) // right-click: do nothing
     return;
 
   var homePage = gHomeButton.getHomePage();
   var where = whereToOpenLink(aEvent);
   var urls;
 
   // openUILinkIn in utilityOverlay.js doesn't handle loading multiple pages
   switch (where) {
@@ -1605,17 +1607,17 @@ function loadURI(uri, referrer, postData
 {
   try {
     if (postData === undefined)
       postData = null;
     var flags = nsIWebNavigation.LOAD_FLAGS_NONE;
     if (allowThirdPartyFixup) {
       flags = nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP;
     }
-    getWebNavigation().loadURI(uri, flags, referrer, postData, null);
+    getBrowser().loadURIWithFlags(uri, flags, referrer, null, postData);
   } catch (e) {
   }
 }
 
 function BrowserLoadURL(aTriggeringEvent, aPostData) {
   var url = gURLBar.value;
 
   if (aTriggeringEvent instanceof MouseEvent) {
@@ -1871,39 +1873,71 @@ function checkForDirectoryListing()
 {
   if ( "HTTPIndex" in content &&
        content.HTTPIndex instanceof Components.interfaces.nsIHTTPIndex ) {
     content.wrappedJSObject.defaultCharacterset =
       getMarkupDocumentViewer().defaultCharacterSet;
   }
 }
 
+function URLBarSetURI(aURI) {
+  var value = getBrowser().userTypedValue;
+  var state = "invalid";
+
+  if (!value) {
+    if (aURI) {
+      // If the url has "wyciwyg://" as the protocol, strip it off.
+      // Nobody wants to see it on the urlbar for dynamically generated
+      // pages.
+      if (!gURIFixup)
+        gURIFixup = Cc["@mozilla.org/docshell/urifixup;1"]
+                      .getService(Ci.nsIURIFixup);
+      try {
+        aURI = gURIFixup.createExposableURI(aURI);
+      } catch (ex) {}
+    } else {
+      aURI = getWebNavigation().currentURI;
+    }
+
+    value = aURI.spec;
+    if (value == "about:blank") {
+      // Replace "about:blank" with an empty string
+      // only if there's no opener (bug 370555).
+      if (!content.opener)
+        value = "";
+    } else {
+      // try to decode as UTF-8
+      try {
+        value = decodeURI(value).replace(/%/g, "%25");
+      } catch(e) {}
+
+      state = "valid";
+    }
+  }
+
+  gURLBar.value = value;
+  SetPageProxyState(state);
+}
+
 // If "ESC" is pressed in the url bar, we replace the urlbar's value with the url of the page
-// and highlight it, unless it is about:blank, where we reset it to "".
-function handleURLBarRevert()
-{
-  var url = getWebNavigation().currentURI.spec;
+// and highlight it, unless it is empty.
+function handleURLBarRevert() {
   var throbberElement = document.getElementById("navigator-throbber");
-
   var isScrolling = gURLBar.popupOpen;
 
+  gBrowser.userTypedValue = null;
+
   // don't revert to last valid url unless page is NOT loading
   // and user is NOT key-scrolling through autocomplete list
   if ((!throbberElement || !throbberElement.hasAttribute("busy")) && !isScrolling) {
-    if (url != "about:blank" || content.opener) {
-      gURLBar.value = url;
+    URLBarSetURI();
+    if (gURLBar.value)
       gURLBar.select();
-      SetPageProxyState("valid");
-    } else { //if about:blank, urlbar becomes ""
-      gURLBar.value = "";
-    }
   }
 
-  gBrowser.userTypedValue = null;
-
   // tell widget to revert to last typed text only if the user
   // was scrolling when they hit escape
   return !isScrolling;
 }
 
 function handleURLBarCommand(aTriggeringEvent) {
   if (!gURLBar.value)
     return;
@@ -2010,17 +2044,17 @@ function UpdateUrlbarSearchSplitterState
   }
 
   if (ibefore) {
     if (!splitter) {
       splitter = document.createElement("splitter");
       splitter.id = "urlbar-search-splitter";
       splitter.setAttribute("resizebefore", "flex");
       splitter.setAttribute("resizeafter", "flex");
-      splitter.className = "toolbar-splitter chromeclass-toolbar-additional";
+      splitter.className = "chromeclass-toolbar-additional";
     }
     urlbar.parentNode.insertBefore(splitter, ibefore);
   } else if (splitter)
     splitter.parentNode.removeChild(splitter);
 }
 
 function UpdatePageProxyState()
 {
@@ -3027,20 +3061,18 @@ function BrowserToolboxCustomizeDone(aTo
     gHomeButton.updateTooltip();
     gIdentityHandler._cacheElements();
     window.XULBrowserWindow.init();
   }
 
   UpdateUrlbarSearchSplitterState();
 
   // Update the urlbar
-  var url = getWebNavigation().currentURI.spec;
   if (gURLBar) {
-    gURLBar.value = url == "about:blank" ? "" : url;
-    SetPageProxyState("valid");
+    URLBarSetURI();
     XULBrowserWindow.asyncUpdateUI();
     PlacesStarButton.updateState();
   }
 
   // Re-enable parts of the UI we disabled during the dialog
   var menubar = document.getElementById("main-menubar");
   for (var i = 0; i < menubar.childNodes.length; ++i)
     menubar.childNodes[i].setAttribute("disabled", false);
@@ -3460,59 +3492,30 @@ nsBrowserStatusHandler.prototype =
     // searched
     // Update urlbar only if a new page was loaded on the primary content area
     // Do not update urlbar if there was a subframe navigation
 
     var browser = getBrowser().selectedBrowser;
     if (aWebProgress.DOMWindow == content) {
 
       if ((location == "about:blank" && !content.opener) ||
-           location == "") {                        //second condition is for new tabs, otherwise
-        location = "";                              //reload function is enabled until tab is refreshed
+           location == "") {  // Second condition is for new tabs, otherwise
+                              // reload function is enabled until tab is refreshed.
         this.reloadCommand.setAttribute("disabled", "true");
         this.reloadSkipCacheCommand.setAttribute("disabled", "true");
       } else {
         this.reloadCommand.removeAttribute("disabled");
         this.reloadSkipCacheCommand.removeAttribute("disabled");
       }
 
-      // The document loaded correctly, clear the value if we should
-      if (browser.userTypedClear > 0 && aRequest)
-        browser.userTypedValue = null;
-
       if (!gBrowser.mTabbedMode && aWebProgress.isLoadingDocument)
         gBrowser.setIcon(gBrowser.mCurrentTab, null);
 
-      //XXXBlake don't we have to reinit this.urlBar, etc.
-      //         when the toolbar changes?
       if (gURLBar) {
-        var userTypedValue = browser.userTypedValue;
-        if (!userTypedValue) {
-          // If the url has "wyciwyg://" as the protocol, strip it off.
-          // Nobody wants to see it on the urlbar for dynamically generated
-          // pages.
-          if (!gURIFixup)
-            gURIFixup = Components.classes["@mozilla.org/docshell/urifixup;1"]
-                                  .getService(Components.interfaces.nsIURIFixup);
-          if (location && gURIFixup) {
-            try {
-              location = gURIFixup.createExposableURI(aLocationURI).spec;
-            } catch (ex) {}
-          }
-
-          gURLBar.value = location;
-          SetPageProxyState("valid");
-
-          // Setting the urlBar value in some cases causes userTypedValue to
-          // become set because of oninput, so reset it to its old value.
-          browser.userTypedValue = userTypedValue;
-        } else {
-          gURLBar.value = userTypedValue;
-          SetPageProxyState("invalid");
-        }
+        URLBarSetURI(aLocationURI);
 
         // Update starring UI
         PlacesStarButton.updateState();
       }
     }
     UpdateBackForwardCommands(gBrowser.webNavigation);
 
     if (gFindBar.findMode != gFindBar.FIND_NORMAL) {
@@ -3713,23 +3716,16 @@ nsBrowserStatusHandler.prototype =
     if (loadingDone)
       return;
     this.onStatusChange(gBrowser.webProgress, null, 0, aMessage);
     this.onProgressChange(gBrowser.webProgress, 0, 0, aTotalProgress, 1);
   },
 
   startDocumentLoad : function(aRequest)
   {
-    // It's okay to clear what the user typed when we start
-    // loading a document. If the user types, this counter gets
-    // set to zero, if the document load ends without an
-    // onLocationChange, this counter gets decremented
-    // (so we keep it while switching tabs after failed loads)
-    getBrowser().userTypedClear++;
-
     // clear out feed data
     gBrowser.mCurrentBrowser.feeds = null;
 
     // clear out search-engine data
     gBrowser.mCurrentBrowser.engines = null;    
 
     const nsIChannel = Components.interfaces.nsIChannel;
     var urlStr = aRequest.QueryInterface(nsIChannel).URI.spec;
@@ -3738,21 +3734,16 @@ nsBrowserStatusHandler.prototype =
     try {
       observerService.notifyObservers(content, "StartDocumentLoad", urlStr);
     } catch (e) {
     }
   },
 
   endDocumentLoad : function(aRequest, aStatus)
   {
-    // The document is done loading, we no longer want the
-    // value cleared.
-    if (getBrowser().userTypedClear > 0)
-      getBrowser().userTypedClear--;
-
     const nsIChannel = Components.interfaces.nsIChannel;
     var urlStr = aRequest.QueryInterface(nsIChannel).originalURI.spec;
 
     var observerService = Components.classes["@mozilla.org/observer-service;1"]
                                     .getService(Components.interfaces.nsIObserverService);
 
     var notification = Components.isSuccessCode(aStatus) ? "EndDocumentLoad" : "FailDocumentLoad";
     try {
@@ -3807,21 +3798,26 @@ nsBrowserAccess.prototype =
     switch(aWhere) {
       case Ci.nsIBrowserDOMWindow.OPEN_NEWWINDOW :
         // FIXME: Bug 408379. So how come this doesn't send the
         // referrer like the other loads do?
         var url = aURI ? aURI.spec : "about:blank";
         newWindow = openDialog(getBrowserURL(), "_blank", "all,dialog=no", url);
         break;
       case Ci.nsIBrowserDOMWindow.OPEN_NEWTAB :
+        var win = this._getMostRecentBrowserWindow();
+        if (!win) {
+          // we couldn't find a suitable window, a new one needs to be opened.
+          return null;
+        }
         var loadInBackground = gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground");
-        var newTab = gBrowser.loadOneTab("about:blank", null, null, null, loadInBackground, false);
-        newWindow = gBrowser.getBrowserForTab(newTab).docShell
-                            .QueryInterface(Ci.nsIInterfaceRequestor)
-                            .getInterface(Ci.nsIDOMWindow);
+        var newTab = win.gBrowser.loadOneTab("about:blank", null, null, null, loadInBackground, false);
+        newWindow = win.gBrowser.getBrowserForTab(newTab).docShell
+                                .QueryInterface(Ci.nsIInterfaceRequestor)
+                                .getInterface(Ci.nsIDOMWindow);
         try {
           if (aURI) {
             if (aOpener) {
               location = aOpener.location;
               referrer =
                       Components.classes["@mozilla.org/network/io-service;1"]
                                 .getService(Components.interfaces.nsIIOService)
                                 .newURI(location, null, null);
@@ -3850,28 +3846,77 @@ nsBrowserAccess.prototype =
                        .getInterface(nsIWebNavigation)
                        .loadURI(aURI.spec, loadflags, referrer, null, null);
             }
           } else {
             newWindow = gBrowser.selectedBrowser.docShell
                                 .QueryInterface(Ci.nsIInterfaceRequestor)
                                 .getInterface(Ci.nsIDOMWindow);
             if (aURI) {
-              getWebNavigation().loadURI(aURI.spec, loadflags, null, 
-                                         null, null);
+              gBrowser.loadURIWithFlags(aURI.spec, loadflags, null, 
+                                        null, null);
             }
           }
           if(!gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground"))
             content.focus();
         } catch(e) {
         }
     }
     return newWindow;
   },
 
+#ifdef XP_UNIX
+#ifndef XP_MACOSX
+#define BROKEN_WM_Z_ORDER
+#endif
+#endif
+#ifdef XP_OS2
+#define BROKEN_WM_Z_ORDER
+#endif
+
+  // this returns the most recent non-popup browser window
+  _getMostRecentBrowserWindow : function ()
+  {
+    if (!window.document.documentElement.getAttribute("chromehidden"))
+      return window;
+ 
+    var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
+                       .getService(Components.interfaces.nsIWindowMediator);
+ 
+#ifdef BROKEN_WM_Z_ORDER
+    var win = wm.getMostRecentWindow("navigator:browser", true);
+ 
+    // if we're lucky, this isn't a popup, and we can just return this
+    if (win && win.document.documentElement.getAttribute("chromehidden")) {
+      win = null;
+      var windowList = wm.getEnumerator("navigator:browser", true);
+      // this is oldest to newest, so this gets a bit ugly
+      while (windowList.hasMoreElements()) {
+        var nextWin = windowList.getNext();
+        if (!nextWin.document.documentElement.getAttribute("chromehidden"))
+          win = nextWin;
+      }
+    }
+#else
+    var windowList = wm.getZOrderDOMWindowEnumerator("navigator:browser", true);
+    if (!windowList.hasMoreElements())
+      return null;
+ 
+    var win = windowList.getNext();
+    while (win.document.documentElement.getAttribute("chromehidden")) {
+      if (!windowList.hasMoreElements()) 
+        return null;
+ 
+      win = windowList.getNext();
+    }
+#endif
+
+    return win;
+  },
+
   isTabContentWindow : function(aWindow)
   {
     var browsers = gBrowser.browsers;
     for (var ctr = 0; ctr < browsers.length; ctr++)
       if (browsers.item(ctr).contentWindow == aWindow)
         return true;
     return false;
   }
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -242,17 +242,17 @@
                      command="Browser:Stop"
                      tooltiptext="&stopButton.tooltip;"/>
 
       <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);"/>
+                     onclick="BrowserGoHome(event);"/>
 
       <toolbaritem id="urlbar-container" align="center" flex="400" persist="width"
                    title="&locationItem.title;" class="chromeclass-location">
         <textbox id="urlbar" flex="1"
                  chromedir="&locale.dir;"
                  type="autocomplete"
                  autocompletesearch="history"
                  autocompletepopup="PopupAutoCompleteRichResult"
--- a/browser/base/content/pageinfo/security.js
+++ b/browser/base/content/pageinfo/security.js
@@ -133,20 +133,26 @@ var security = {
    */
   viewCookies : function()
   {
     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                        .getService(Components.interfaces.nsIWindowMediator);
     var win = wm.getMostRecentWindow("Browser:Cookies");
     var eTLDService = Components.classes["@mozilla.org/network/effective-tld-service;1"].
                       getService(Components.interfaces.nsIEffectiveTLDService);
-    var eTLD = "";
 
-    if (this._getSecurityInfo().hostName)
-      eTLD = eTLDService.getBaseDomainFromHost(this._getSecurityInfo().hostName);
+    var eTLD;
+    var uri = gDocument.documentURIObject;
+    try {
+      eTLD = eTLDService.getBaseDomain(uri);
+    }
+    catch (e) {
+      // getBaseDomain will fail if the host is an IP address or is empty
+      eTLD = uri.asciiHost;
+    }
 
     if (win) {
       win.gCookiesWindow.setFilter(eTLD);
       win.focus();
     }
     else
       window.openDialog("chrome://browser/content/preferences/cookies.xul",
                         "Browser:Cookies", "", {filterString : eTLD});
@@ -228,20 +234,21 @@ function securityOnLoad() {
   }
   else
     viewCert.collapsed = true;
 
   /* Set Privacy & History section text */
   var yesStr = pageInfoBundle.getString("yes");
   var noStr = pageInfoBundle.getString("no");
 
+  var uri = gDocument.documentURIObject;
   setText("security-privacy-cookies-value",
-          hostHasCookies(info.hostName) ? yesStr : noStr);
+          hostHasCookies(uri) ? yesStr : noStr);
   setText("security-privacy-passwords-value",
-          realmHasPasswords(info.fullLocation) ? yesStr : noStr);
+          realmHasPasswords(uri) ? yesStr : noStr);
   
   var visitCount = previousVisitCount(info.hostName);
   if(visitCount > 1) {
     setText("security-privacy-history-value",
             pageInfoBundle.getFormattedString("securityNVisits", [visitCount.toLocaleString()]));
   }
   else if (visitCount == 1) {
     setText("security-privacy-history-value",
@@ -308,40 +315,33 @@ function viewCertHelper(parent, cert)
   if (!cert)
     return;
 
   var cd = Components.classes[CERTIFICATEDIALOGS_CONTRACTID].getService(nsICertificateDialogs);
   cd.viewCert(parent, cert);
 }
 
 /**
- * Return true iff we have cookies for hostName
+ * Return true iff we have cookies for uri
  */
-function hostHasCookies(hostName) {
-  if (!hostName)
-    return false;
-  
+function hostHasCookies(uri) {
   var cookieManager = Components.classes["@mozilla.org/cookiemanager;1"]
                                 .getService(Components.interfaces.nsICookieManager2);
 
-  return cookieManager.countCookiesFromHost(hostName) > 0;
+  return cookieManager.countCookiesFromHost(uri.asciiHost) > 0;
 }
 
 /**
- * Return true iff realm (proto://host:port) (extracted from location) has
+ * Return true iff realm (proto://host:port) (extracted from uri) has
  * saved passwords
  */
-function realmHasPasswords(location) {
-  if (!location) 
-    return false;
-  
-  var realm = makeURI(location).prePath;
+function realmHasPasswords(uri) {
   var passwordManager = Components.classes["@mozilla.org/login-manager;1"]
                                   .getService(Components.interfaces.nsILoginManager);
-  return passwordManager.countLogins(realm, "", "");
+  return passwordManager.countLogins(uri.prePath, "", "") > 0;
 }
 
 /**
  * Return the number of previous visits recorded for host before today.
  *
  * @param host - the domain name to look for in history
  */
 function previousVisitCount(host, endTimeReference) {
new file mode 100644
--- /dev/null
+++ b/browser/base/content/tabbrowser.css
@@ -0,0 +1,33 @@
+.tabbrowser-tabs {
+  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-tabs");
+}
+
+.tabbrowser-tab {
+  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-tab");
+}
+
+%ifdef XP_MACOSX
+.tabbrowser-arrowscrollbox {
+  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-arrowscrollbox");
+}
+%endif
+
+.tabs-alltabs-popup {
+  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-alltabs-popup");
+}
+
+.tab-close-button, .tabs-closebutton {
+  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-close-tab-button");
+}
+
+.tab-close-button {
+  display: none;
+}
+
+.tabbrowser-tabs:not([closebuttons="noclose"]):not([closebuttons="closeatend"]) > .tabbrowser-tab[selected="true"] > .tab-close-button {
+  display: -moz-box;
+}
+
+.tabbrowser-tabs[closebuttons="alltabs"] > .tabbrowser-tab > .tab-close-button {
+  display: -moz-box;
+}
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -54,17 +54,17 @@
 
 <bindings id="tabBrowserBindings"
           xmlns="http://www.mozilla.org/xbl"
           xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
           xmlns:xbl="http://www.mozilla.org/xbl">
 
   <binding id="tabbrowser">
     <resources>
-      <stylesheet src="chrome://browser/skin/browser.css"/>
+      <stylesheet src="chrome://browser/content/tabbrowser.css"/>
     </resources>
 
     <content>
       <xul:stringbundle anonid="tbstringbundle" src="chrome://browser/locale/tabbrowser.properties"/>
       <xul:tabbox anonid="tabbox" flex="1" eventnode="document" xbl:inherits="handleCtrlPageUpDown"
                   onselect="if (!('updateCurrentBrowser' in this.parentNode) || event.target.localName != 'tabpanels') return; this.parentNode.updateCurrentBrowser();">
         <xul:hbox class="tab-drop-indicator-bar" collapsed="true" chromedir="&locale.dir;">
           <xul:hbox class="tab-drop-indicator" mousethrough="always"/>
@@ -339,34 +339,39 @@
 
               if (aStateFlags & nsIWebProgressListener.STATE_START &&
                   aStateFlags & nsIWebProgressListener.STATE_IS_NETWORK) {
                 // It's okay to clear what the user typed when we start
                 // loading a document. If the user types, this counter gets
                 // set to zero, if the document load ends without an
                 // onLocationChange, this counter gets decremented
                 // (so we keep it while switching tabs after failed loads)
+                // We need to add 2 because loadURIWithFlags may have
+                // cancelled a pending load which would have cleared
+                // its anchor scroll detection temporary increment.
                 if (aWebProgress.DOMWindow == this.mBrowser.contentWindow)
-                  this.mBrowser.userTypedClear++;
+                  this.mBrowser.userTypedClear += 2;
 
                 if (!this.mBlank) {
                   this.mTab.setAttribute("busy", "true");
                   this.mTabBrowser.updateIcon(this.mTab);
                   this.mTabBrowser.setTabTitleLoading(this.mTab);
 
                   if (this.mTabBrowser.mCurrentTab == this.mTab)
                     this.mTabBrowser.mIsBusy = true;
                 }
               }
               else if (aStateFlags & nsIWebProgressListener.STATE_STOP &&
                        aStateFlags & nsIWebProgressListener.STATE_IS_NETWORK) {
                 if (aWebProgress.DOMWindow == this.mBrowser.contentWindow) {
                   // The document is done loading, we no longer want the
                   // value cleared.
-                  if (this.mBrowser.userTypedClear > 0)
+                  if (this.mBrowser.userTypedClear > 1)
+                    this.mBrowser.userTypedClear -= 2;
+                  else if (this.mBrowser.userTypedClear > 0)
                     this.mBrowser.userTypedClear--;
 
                   if (!this.mBrowser.mIconURL)
                     this.mTabBrowser.useDefaultIcon(this.mTab);
                 }
 
                 if (this.mBlank)
                   this.mBlank = false;
@@ -406,17 +411,17 @@
               }
               this.mStateFlags = aStateFlags;
               this.mStatus = aStatus;
             },
 
             onLocationChange : function(aWebProgress, aRequest, aLocation)
             {
               // The document loaded correctly, clear the value if we should
-              if (this.mBrowser.userTypedClear > 0 && aRequest)
+              if (this.mBrowser.userTypedClear > 0)
                 this.mBrowser.userTypedValue = null;
 
               if (aWebProgress.DOMWindow == this.mBrowser.contentWindow &&
                   aWebProgress.isLoadingDocument)
                 this.mTabBrowser.setIcon(this.mTab, null);
 
               // changing location, clear out the missing plugins list
               this.mBrowser.missingPlugins = null;
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -38,18 +38,16 @@
 #
 # ***** END LICENSE BLOCK *****
 
 <bindings id="urlbarBindings" xmlns="http://www.mozilla.org/xbl">
 
   <binding id="urlbar" extends="chrome://global/content/bindings/autocomplete.xml#autocomplete">
     <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.clickSelectsAll = this._prefs.getBoolPref("clickSelectsAll");
         this.doubleClickSelectsAll = this._prefs.getBoolPref("doubleClickSelectsAll");
@@ -61,51 +59,22 @@
         this.inputField.addEventListener("mousedown", this, false);
         this.inputField.addEventListener("mousemove", this, false);
         this.inputField.addEventListener("mouseout", this, false);
       ]]></constructor>
 
       <destructor><![CDATA[
         this._prefs.removeObserver("", this);
         this._prefs = null;
-        this._ioService = null;
         this.inputField.controllers.removeController(this._copyCutController);
         this.inputField.removeEventListener("mousedown", this, false);
         this.inputField.removeEventListener("mousemove", this, false);
         this.inputField.removeEventListener("mouseout", this, false);
       ]]></destructor>
 
-      <property name="value"
-                onget="return this.inputField.value;">
-        <setter><![CDATA[
-          this.mIgnoreInput = true;
-
-          if (val != "") {
-            var uri;
-            try {
-              uri = this._ioService.newURI(val, null, null);
-            } catch(e) {}
-            if (uri) {
-              val = uri.spec;
-              try {
-                // try to decode as UTF-8
-                val = decodeURI(val);
-              } catch(e) {}
-            }
-          }
-          this.inputField.value = val;
-
-          this.mIgnoreInput = false;
-          var event = document.createEvent("Events");
-          event.initEvent("ValueChange", true, true);
-          this.inputField.dispatchEvent(event);
-          return val;
-        ]]></setter>
-      </property>
-
       <method name="_initURLTooltip">
         <body><![CDATA[
           if (this.focused || this.value == "")
             return;
           if (this._tooltipTimer)
             clearTimeout(this._tooltipTimer);
           this._tooltipTimer = setTimeout(function (self) {
             self._tooltipTimer = 0;
@@ -182,31 +151,33 @@
             var start = urlbar.selectionStart;
             var end = urlbar.selectionEnd;
             if (start == end)
               return;
             var val;
             if (start == 0 && end == urlbar.textLength) {
               // if the entire value is selected and it's a valid URI, encode it
               val = urlbar.value;
+              var ioService = Cc["@mozilla.org/network/io-service;1"]
+                                .getService(Ci.nsIIOService);
               try {
-                val = urlbar._ioService.newURI(val, null, null).spec;
+                val = ioService.newURI(val, null, null).spec;
               } catch(e) {}
               if (aCommand == "cmd_cut")
                 urlbar.value = "";
             } else {
               val = urlbar.value.substring(start, end);
               if (aCommand == "cmd_cut") {
                 urlbar.value = urlbar.value.substring(0, start) + urlbar.value.substring(end);
                 urlbar.selectionStart = urlbar.selectionEnd = start;
               }
             }
-            Components.classes["@mozilla.org/widget/clipboardhelper;1"]
-                      .getService(Components.interfaces.nsIClipboardHelper)
-                      .copyString(val);
+            Cc["@mozilla.org/widget/clipboardhelper;1"]
+              .getService(Ci.nsIClipboardHelper)
+              .copyString(val);
           },
           supportsCommand: function(aCommand) {
             switch (aCommand) {
               case "cmd_copy":
               case "cmd_cut":
                 return true;
             }
             return false;
--- a/browser/base/content/utilityOverlay.js
+++ b/browser/base/content/utilityOverlay.js
@@ -417,17 +417,17 @@ function checkForUpdates()
   var prompter = 
       Components.classes["@mozilla.org/updates/update-prompt;1"].
       createInstance(Components.interfaces.nsIUpdatePrompt);
 
   // If there's an update ready to be applied, show the "Update Downloaded"
   // UI instead and let the user know they have to restart the browser for
   // the changes to be applied. 
   if (um.activeUpdate && um.activeUpdate.state == "pending")
-    prompter.showUpdateDownloaded(um.activeUpdate, false);
+    prompter.showUpdateDownloaded(um.activeUpdate);
   else
     prompter.checkForUpdates();
 }
 
 function buildHelpMenu()
 {
   // Enable/disable the "Report Web Forgery" menu item.  safebrowsing object
   // may not exist in OSX
--- a/browser/base/jar.mn
+++ b/browser/base/jar.mn
@@ -32,18 +32,19 @@ browser.jar:
 *       content/browser/openLocation.js               (content/openLocation.js)
 *       content/browser/openLocation.xul              (content/openLocation.xul)
 *       content/browser/pageReport.js                 (content/pageReport.js)
 *       content/browser/pageReport.xul                (content/pageReport.xul)
 *       content/browser/pageReportFirstTime.xul       (content/pageReportFirstTime.xul)
 *       content/browser/safeMode.js                   (content/safeMode.js)
 *       content/browser/safeMode.xul                  (content/safeMode.xul)
 *       content/browser/sanitize.js                   (content/sanitize.js)
+*       content/browser/sanitize.xul                  (content/sanitize.xul)
+*       content/browser/tabbrowser.css                (content/tabbrowser.css)
 *       content/browser/tabbrowser.xml                (content/tabbrowser.xml)
-*       content/browser/sanitize.xul                  (content/sanitize.xul)
 *       content/browser/urlbarBindings.xml            (content/urlbarBindings.xml)
 *       content/browser/utilityOverlay.js             (content/utilityOverlay.js)
 *       content/browser/web-panels.js                 (content/web-panels.js)
 *       content/browser/web-panels.xul                (content/web-panels.xul)
 *       content/browser/baseMenuOverlay.xul           (content/baseMenuOverlay.xul)
 *       content/browser/nsContextMenu.js              (content/nsContextMenu.js)
 # XXX: We should exclude this one as well (bug 71895)
 *       content/browser/hiddenWindow.xul              (content/hiddenWindow.xul)
--- a/browser/components/feeds/public/nsIFeedResultService.idl
+++ b/browser/components/feeds/public/nsIFeedResultService.idl
@@ -37,17 +37,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsISupports.idl"
 interface nsIURI;
 interface nsIRequest;
 interface nsIFeedResult;
 
 /**
- * nsIFeedResultService provides a globally-accessible object for retreiving
+ * nsIFeedResultService provides a globally-accessible object for retrieving
  * the results of feed processing.
  */
 [scriptable, uuid(f3262589-48b2-4019-9947-90e5269bbfb9)]
 interface nsIFeedResultService : nsISupports
 {
   /**
    * When set to true, forces the preview page to be displayed, regardless
    * of the user's preferences.
--- a/browser/components/microsummaries/src/nsMicrosummaryService.js
+++ b/browser/components/microsummaries/src/nsMicrosummaryService.js
@@ -1762,16 +1762,18 @@ MicrosummaryResource.prototype = {
   set lastMod(aMod) { this._lastMod = aMod },
 
   // Implement notification callback interfaces so we can suppress UI
   // and abort loads for bad SSL certs and HTTP authorization requests.
   
   // Interfaces this component implements.
   interfaces: [Ci.nsIAuthPromptProvider,
                Ci.nsIAuthPrompt,
+               Ci.nsIBadCertListener2,
+               Ci.nsISSLErrorListener,
                Ci.nsIPrompt,
                Ci.nsIProgressEventSink,
                Ci.nsIInterfaceRequestor,
                Ci.nsISupports],
 
   // nsISupports
 
   QueryInterface: function MSR_QueryInterface(iid) {
@@ -1792,16 +1794,29 @@ MicrosummaryResource.prototype = {
   },
 
   // nsIInterfaceRequestor
   
   getInterface: function MSR_getInterface(iid) {
     return this.QueryInterface(iid);
   },
 
+  // nsIBadCertListener2
+  // Suppress any certificate errors
+  notifyCertProblem: function MSR_certProblem(socketInfo, status, targetSite) {
+    return true;
+  },
+
+  // nsISSLErrorListener
+  // Suppress any ssl errors
+  notifySSLError: function MSR_SSLError(socketInfo, error, targetSite) {
+    return true;
+  },
+
+  
   // Suppress UI and abort loads for files secured by authentication.
 
   // Auth requests appear to succeed when we cancel them (since the server
   // redirects us to a "you're not authorized" page), so we have to set a flag
   // to let the load handler know to treat the load as a failure.
   get _authFailed()         { return this.__authFailed; },
   set _authFailed(newValue) { return this.__authFailed = newValue },
 
--- a/browser/components/migration/src/nsBrowserProfileMigratorUtils.cpp
+++ b/browser/components/migration/src/nsBrowserProfileMigratorUtils.cpp
@@ -261,17 +261,18 @@ ImportBookmarksHTML(nsIFile* aBookmarksF
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Create an imported bookmarks folder under the bookmarks menu.
   PRInt64 root;
   rv = bms->GetBookmarksMenuFolder(&root);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRInt64 folder;
-  rv = bms->CreateFolder(root, importedBookmarksTitle, -1, &folder);
+  rv = bms->CreateFolder(root, NS_ConvertUTF16toUTF8(importedBookmarksTitle),
+                         -1, &folder);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Import the bookmarks into the folder.
   return importer->ImportHTMLFromFileToFolder(localFile, folder, PR_FALSE);
 }
 
 nsresult
 InitializeBookmarks(nsIFile* aTargetProfile)
--- a/browser/components/migration/src/nsIEProfileMigrator.cpp
+++ b/browser/components/migration/src/nsIEProfileMigrator.cpp
@@ -1275,17 +1275,18 @@ nsIEProfileMigrator::CopyFavorites(PRBoo
     bundle->GetStringFromName(NS_LITERAL_STRING("sourceNameIE").get(), 
                               getter_Copies(sourceNameIE));
 
     const PRUnichar* sourceNameStrings[] = { sourceNameIE.get() };
     nsString importedIEFavsTitle;
     bundle->FormatStringFromName(NS_LITERAL_STRING("importedBookmarksFolder").get(),
                                  sourceNameStrings, 1, getter_Copies(importedIEFavsTitle));
 
-    bms->CreateFolder(root, importedIEFavsTitle, -1, &folder);
+    bms->CreateFolder(root, NS_ConvertUTF16toUTF8(importedIEFavsTitle), -1,
+                      &folder);
   }
   else {
     // Initialize the default bookmarks
     nsCOMPtr<nsIFile> profile;
     GetProfilePath(nsnull, profile);
     rv = InitializeBookmarks(profile);
     NS_ENSURE_SUCCESS(rv, rv);
 
@@ -1366,17 +1367,18 @@ nsIEProfileMigrator::CopySmartKeywords(P
         nsString sourceNameIE;
         bundle->GetStringFromName(NS_LITERAL_STRING("sourceNameIE").get(), 
                                   getter_Copies(sourceNameIE));
 
         const PRUnichar* sourceNameStrings[] = { sourceNameIE.get() };
         nsString importedIESearchUrlsTitle;
         bundle->FormatStringFromName(NS_LITERAL_STRING("importedSearchURLsFolder").get(),
                                     sourceNameStrings, 1, getter_Copies(importedIESearchUrlsTitle));
-        bms->CreateFolder(aParentFolder, importedIESearchUrlsTitle, -1, &keywordsFolder);
+        bms->CreateFolder(aParentFolder, NS_ConvertUTF16toUTF8(importedIESearchUrlsTitle),
+                          -1, &keywordsFolder);
       }
 
       nsCOMPtr<nsIWindowsRegKey> childKey; 
       if (NS_SUCCEEDED(regKey->OpenChild(keyName,
                        nsIWindowsRegKey::ACCESS_READ,
                        getter_AddRefs(childKey)))) {
         nsAutoString url; 
         if (NS_SUCCEEDED(childKey->ReadStringValue(EmptyString(), url))) {
@@ -1384,17 +1386,18 @@ nsIEProfileMigrator::CopySmartKeywords(P
           if (NS_FAILED(NS_NewURI(getter_AddRefs(uri), url))) {
             NS_WARNING("Invalid url while importing smart keywords of MS IE");
             ++offset;
             childKey->Close();
             continue;
           }
           PRInt64 id;
           bms->InsertBookmark(keywordsFolder, uri,
-                              nsINavBookmarksService::DEFAULT_INDEX, keyName,
+                              nsINavBookmarksService::DEFAULT_INDEX,
+                              NS_ConvertUTF16toUTF8(keyName),
                               &id);
         }
         childKey->Close();
       }
 
       ++offset;
     }
   }
@@ -1496,28 +1499,28 @@ nsIEProfileMigrator::ParseFavoritesFolde
         bookmarkName.SetLength(lnkExtStart);
 
       nsCOMPtr<nsIURI> bookmarkURI;
       rv = NS_NewFileURI(getter_AddRefs(bookmarkURI), localFile);
       NS_ENSURE_SUCCESS(rv, rv);
       PRInt64 id;
       rv = aBookmarksService->InsertBookmark(aParentFolder, bookmarkURI,
                                              nsINavBookmarksService::DEFAULT_INDEX,
-                                             bookmarkName, &id);
+                                             NS_ConvertUTF16toUTF8(bookmarkName), &id);
       NS_ENSURE_SUCCESS(rv, rv);
       if (NS_FAILED(rv)) continue;
     }
     else if (isDir) {
       PRInt64 folder;
       if (bookmarkName.Equals(aPersonalToolbarFolderName)) {
         aBookmarksService->GetToolbarFolder(&folder);
       }
       else {
         rv = aBookmarksService->CreateFolder(aParentFolder,
-                                             bookmarkName,
+                                             NS_ConvertUTF16toUTF8(bookmarkName),
                                              nsINavBookmarksService::DEFAULT_INDEX,
                                              &folder);
         if (NS_FAILED(rv)) continue;
       }
 
       rv = ParseFavoritesFolder(currFile, folder, aBookmarksService, aPersonalToolbarFolderName, PR_FALSE);
       if (NS_FAILED(rv)) continue;
     }
@@ -1539,17 +1542,17 @@ nsIEProfileMigrator::ParseFavoritesFolde
       ResolveShortcut(path, getter_Copies(resolvedURL));
 
       nsCOMPtr<nsIURI> resolvedURI;
       rv = NS_NewURI(getter_AddRefs(resolvedURI), resolvedURL);
       NS_ENSURE_SUCCESS(rv, rv);
       PRInt64 id;
       rv = aBookmarksService->InsertBookmark(aParentFolder, resolvedURI,
                                              nsINavBookmarksService::DEFAULT_INDEX,
-                                             name, &id);
+                                             NS_ConvertUTF16toUTF8(name), &id);
       if (NS_FAILED(rv)) continue;
     }
   }
   while (1);
 
   return rv;
 }
 
--- a/browser/components/migration/src/nsOperaProfileMigrator.cpp
+++ b/browser/components/migration/src/nsOperaProfileMigrator.cpp
@@ -1070,17 +1070,17 @@ nsOperaProfileMigrator::CopyBookmarks(PR
                               getter_Copies(sourceNameOpera));
 
     const PRUnichar* sourceNameStrings[] = { sourceNameOpera.get() };
     nsString importedOperaHotlistTitle;
     bundle->FormatStringFromName(NS_LITERAL_STRING("importedBookmarksFolder").get(),
                                  sourceNameStrings, 1, 
                                  getter_Copies(importedOperaHotlistTitle));
 
-    bms->CreateFolder(parentFolder, importedOperaHotlistTitle,
+    bms->CreateFolder(parentFolder, NS_ConvertUTF16toUTF8(importedOperaHotlistTitle),
                       nsINavBookmarksService::DEFAULT_INDEX, &parentFolder);
   }
   else {
     nsCOMPtr<nsIFile> profile;
     GetProfilePath(nsnull, profile);
     rv = InitializeBookmarks(profile);
     NS_ENSURE_SUCCESS(rv, rv);
   }
@@ -1135,17 +1135,17 @@ nsOperaProfileMigrator::CopySmartKeyword
 
   const PRUnichar* sourceNameStrings[] = { sourceNameOpera.get() };
   nsString importedSearchUrlsTitle;
   aBundle->FormatStringFromName(NS_LITERAL_STRING("importedSearchURLsFolder").get(),
                                 sourceNameStrings, 1, 
                                 getter_Copies(importedSearchUrlsTitle));
 
   PRInt64 keywordsFolder;
-  rv = aBMS->CreateFolder(aParentFolder, importedSearchUrlsTitle,
+  rv = aBMS->CreateFolder(aParentFolder, NS_ConvertUTF16toUTF8(importedSearchUrlsTitle),
                           nsINavBookmarksService::DEFAULT_INDEX, &keywordsFolder);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRInt32 sectionIndex = 1;
   nsCAutoString name, url, keyword;
   do {
     nsCAutoString section("Search Engine ");
     section.AppendInt(sectionIndex++);
@@ -1165,32 +1165,31 @@ nsOperaProfileMigrator::CopySmartKeyword
     PRInt32 post;
     rv = GetInteger(parser, section.get(), "Is post", &post);
     if (NS_SUCCEEDED(rv) && post)
       continue;
 
     if (url.IsEmpty() || keyword.IsEmpty() || name.IsEmpty())
       continue;
 
-    NS_ConvertUTF8toUTF16 nameStr(name);
-    PRUint32 length = nameStr.Length();
+    PRUint32 length = name.Length();
     PRInt32 index = 0; 
     do {
-      index = nameStr.FindChar('&', index);
+      index = name.FindChar('&', index);
       if (index >= length - 2)
         break;
 
       // Assume "&&" is an escaped ampersand in the search query title. 
-      if (nameStr.CharAt(index + 1) == '&') {
-        nameStr.Cut(index, 1);
+      if (name.CharAt(index + 1) == '&') {
+        name.Cut(index, 1);
         index += 2;
         continue;
       }
 
-      nameStr.Cut(index, 1);
+      name.Cut(index, 1);
     }
     while (index < length);
 
     nsCOMPtr<nsIURI> uri;
     NS_NewURI(getter_AddRefs(uri), url.get());
     if (!uri)
       return NS_ERROR_OUT_OF_MEMORY;
 
@@ -1201,17 +1200,17 @@ nsOperaProfileMigrator::CopySmartKeyword
     const PRUnichar* descStrings[] = { NS_ConvertUTF8toUTF16(keyword).get(), host.get() };
     nsString keywordDesc;
     aBundle->FormatStringFromName(NS_LITERAL_STRING("importedSearchUrlDesc").get(),
                                   descStrings, 2, getter_Copies(keywordDesc));
 
     PRInt64 newId;
     rv = aBMS->InsertBookmark(keywordsFolder, uri,
                               nsINavBookmarksService::DEFAULT_INDEX,
-                              nameStr, &newId);
+                              name, &newId);
     NS_ENSURE_SUCCESS(rv, rv);
     // TODO -- set bookmark keyword to keyword and description to keywordDesc.
   }
   while (1);
   
   return rv;
 }
 #endif
@@ -1272,18 +1271,18 @@ nsOperaProfileMigrator::ParseBookmarksFo
                                              PRInt64 aParent,
                                              PRInt64 aToolbar,
                                              nsINavBookmarksService* aBMS)
 {
   nsresult rv;
   PRBool moreData = PR_FALSE;
   nsAutoString buffer;
   EntryType entryType = EntryType_BOOKMARK;
-  nsAutoString name, keyword, description;
-  nsCAutoString url;
+  nsAutoString keyword, description;
+  nsCAutoString url, name;
   PRBool onToolbar = PR_FALSE;
   do {
     nsCAutoString cBuffer;
     rv = aStream->ReadLine(cBuffer, &moreData);
     if (NS_FAILED(rv)) return rv;
     
     CopyUTF8toUTF16(cBuffer, buffer);
     nsString data;
@@ -1297,17 +1296,17 @@ nsOperaProfileMigrator::ParseBookmarksFo
       break;
     case LineType_SEPARATOR:
       // If we're here, we need to break out of the loop for the current folder, 
       // essentially terminating this instance of ParseBookmarksFolder and return
       // to the calling function, which is either ParseBookmarksFolder for a parent
       // folder, or CopyBookmarks (which means we're done parsing all bookmarks).
       goto done;
     case LineType_NAME:
-      name = data;
+      name.Assign(NS_ConvertUTF16toUTF8(data));
       break;
     case LineType_URL:
       url.Assign(NS_ConvertUTF16toUTF8(data));
       break;
     case LineType_KEYWORD:
       keyword = data;
       break;
     case LineType_DESCRIPTION:
--- a/browser/components/migration/src/nsSafariProfileMigrator.cpp
+++ b/browser/components/migration/src/nsSafariProfileMigrator.cpp
@@ -921,18 +921,18 @@ nsSafariProfileMigrator::CopyBookmarks(P
                               getter_Copies(sourceNameSafari));
 
     const PRUnichar* sourceNameStrings[] = { sourceNameSafari.get() };
     nsString importedSafariBookmarksTitle;
     bundle->FormatStringFromName(NS_LITERAL_STRING("importedBookmarksFolder").get(),
                                  sourceNameStrings, 1,
                                  getter_Copies(importedSafariBookmarksTitle));
 
-    bms->CreateFolder(root, importedSafariBookmarksTitle, nsINavBookmarksService::DEFAULT_INDEX,
-                      &folder);
+    bms->CreateFolder(root, NS_ConvertUTF16toUTF8(importedSafariBookmarksTitle),
+                      nsINavBookmarksService::DEFAULT_INDEX, &folder);
   }
   else {
     nsCOMPtr<nsIFile> profile;
     GetProfilePath(nsnull, profile);
     rv = InitializeBookmarks(profile);
     NS_ENSURE_SUCCESS(rv, rv);
     // In replace mode we are merging at the top level.
     folder = root;
@@ -1001,18 +1001,18 @@ nsSafariProfileMigrator::ParseBookmarksF
       continue;
 
     if (!type.EqualsLiteral("WebBookmarkTypeList") &&
         !type.EqualsLiteral("WebBookmarkTypeLeaf"))
       continue;
 
     if (::CFDictionaryContainsKey(entry, CFSTR("Children")) &&
         type.EqualsLiteral("WebBookmarkTypeList")) {
-      nsAutoString title;
-      if (!GetDictionaryStringValue(entry, CFSTR("Title"), title))
+      nsCAutoString title;
+      if (!GetDictionaryCStringValue(entry, CFSTR("Title"), title, kCFStringEncodingUTF8))
         continue;
 
       CFArrayRef children = (CFArrayRef)::CFDictionaryGetValue(entry,
                                                                CFSTR("Children"));
 
       // Look for the BookmarksBar Bookmarks and add them into the appropriate
       // Personal Toolbar Root
       if (title.EqualsLiteral("BookmarksBar") && aIsAtRootLevel) {
@@ -1043,19 +1043,19 @@ nsSafariProfileMigrator::ParseBookmarksF
                                    aBookmarksService,
                                    PR_FALSE);
       }
     }
     else if (type.EqualsLiteral("WebBookmarkTypeLeaf")) {
       // Encountered a Bookmark, so add it to the current folder...
       CFDictionaryRef URIDictionary = (CFDictionaryRef)
                       ::CFDictionaryGetValue(entry, CFSTR("URIDictionary"));
-      nsAutoString title, url;
-      if (GetDictionaryStringValue(URIDictionary, CFSTR("title"), title) &&
-          GetDictionaryStringValue(entry, CFSTR("URLString"), url)) {
+      nsCAutoString title, url;
+      if (GetDictionaryCStringValue(URIDictionary, CFSTR("title"), title, kCFStringEncodingUTF8) &&
+          GetDictionaryCStringValue(entry, CFSTR("URLString"), url, kCFStringEncodingUTF8)) {
         nsCOMPtr<nsIURI> uri;
         PRInt64 id;
         rv |= NS_NewURI(getter_AddRefs(uri), url);
         rv |= aBookmarksService->InsertBookmark(aParentFolder, uri,
                                                 nsINavBookmarksService::DEFAULT_INDEX,
                                                 title, &id);
       }
     }
--- a/browser/components/places/content/controller.js
+++ b/browser/components/places/content/controller.js
@@ -933,35 +933,32 @@ PlacesController.prototype = {
   /**
    * Removes the selection
    * @param   aTxnName
    *          A name for the transaction if this is being performed
    *          as part of another operation.
    */
   remove: function PC_remove(aTxnName) {
     NS_ASSERT(aTxnName !== undefined, "Must supply Transaction Name");
-    this._view.saveSelection(this._view.SAVE_SELECTION_REMOVE);
 
     var root = this._view.getResult().root;
 
     if (PlacesUtils.nodeIsFolder(root)) 
       this._removeRowsFromBookmarks(aTxnName);
     else if (PlacesUtils.nodeIsQuery(root)) {
       var queryType = asQuery(root).queryOptions.queryType;
       if (queryType == Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS)
         this._removeRowsFromBookmarks(aTxnName);
       else if (queryType == Ci.nsINavHistoryQueryOptions.QUERY_TYPE_HISTORY)
         this._removeRowsFromHistory();
       else
         NS_ASSERT(false, "implement support for QUERY_TYPE_UNIFIED");
     }
     else
       NS_ASSERT(false, "unexpected root");
-      
-    this._view.restoreSelection();
   },
 
   /**
    * Get a TransferDataSet containing the content of the selection that can be
    * dropped elsewhere. 
    * @param   dragAction
    *          The action to happen when dragging, i.e. copy
    * @returns A TransferDataSet object that can be dragged and dropped 
--- a/browser/components/places/content/editBookmarkOverlay.js
+++ b/browser/components/places/content/editBookmarkOverlay.js
@@ -343,16 +343,17 @@ var gEditItemOverlay = {
         // Show the drop marker if there are microsummaries
         droppable = true;
         while (enumerator.hasMoreElements()) {
           var microsummary = enumerator.getNext()
                                        .QueryInterface(Ci.nsIMicrosummary);
           var menuItem = this._createMicrosummaryMenuItem(microsummary);
           if (PlacesUtils.microsummaries
                          .isMicrosummary(this._itemId, microsummary))
+            itemToSelect = menuItem;
 
           menupopup.appendChild(menuItem);
         }
       }
 
       this._microsummaries.addObserver(this);
     }
 
--- a/browser/components/places/content/editBookmarkOverlay.xul
+++ b/browser/components/places/content/editBookmarkOverlay.xul
@@ -55,16 +55,17 @@
     <grid id="editBookmarkPanelGrid" flex="1">
       <columns>
         <column/>
         <column flex="1"/>
       </columns>
       <rows>
         <row align="center" id="editBMPanel_nameRow">
           <label value="&editBookmarkOverlay.name.label;"
+                 accesskey="&editBookmarkOverlay.name.accesskey;"
                  control="editBMPanel_namePicker"
                  observes="paneElementsBroadcaster"/>
           <menulist id="editBMPanel_namePicker"
                     flex="1"
                     editable="true"
                     droppable="false"
                     oninput="gEditItemOverlay.onNamePickerInput();"
                     onblur="gEditItemOverlay.onNamePickerChange();"
@@ -77,34 +78,37 @@
                 <label value="&editBookmarkOverlay.liveTitlesSeparator.label;"/>
               </menuitem>
             </menupopup>
           </menulist>
         </row>
 
         <row align="center" id="editBMPanel_locationRow">
           <label value="&editBookmarkOverlay.location.label;"
+                 accesskey="&editBookmarkOverlay.location.accesskey;"
                  control="editBMPanel_locationField"
                  observes="paneElementsBroadcaster"/>
           <textbox id="editBMPanel_locationField"
                    onblur="gEditItemOverlay.onLocationFieldBlur();"
                    observes="paneElementsBroadcaster"/>
         </row>
 
         <row align="center" id="editBMPanel_feedLocationRow">
           <label value="&editBookmarkOverlay.feedLocation.label;"
+                 accesskey="&editBookmarkOverlay.feedLocation.accesskey;"
                  control="editBMPanel_feedLocationField"
                  observes="paneElementsBroadcaster"/>
           <textbox id="editBMPanel_feedLocationField"
                    onblur="gEditItemOverlay.onFeedLocationFieldBlur();"
                    observes="paneElementsBroadcaster"/>
         </row>
 
         <row align="center" id="editBMPanel_siteLocationRow">
           <label value="&editBookmarkOverlay.siteLocation.label;"
+                 accesskey="&editBookmarkOverlay.siteLocation.accesskey;"
                  control="editBMPanel_siteLocationField"
                  observes="paneElementsBroadcaster"/>
           <textbox id="editBMPanel_siteLocationField"
                    onblur="gEditItemOverlay.onSiteLocationFieldBlur();"
                    observes="paneElementsBroadcaster"/>
         </row>
 
         <row align="center" id="editBMPanel_folderRow">
@@ -146,16 +150,17 @@
           <treecols>
             <treecol anonid="title" flex="1" primary="true" hideheader="true"/>
           </treecols>
           <treechildren flex="1"/>
         </tree>
 
         <row align="center" id="editBMPanel_tagsRow">
           <label value="&editBookmarkOverlay.tags.label;"
+                 accesskey="&editBookmarkOverlay.tags.accesskey;"
                  control="editBMPanel_tagsField"
                  observes="paneElementsBroadcaster"/>
           <textbox id="editBMPanel_tagsField"
                    onblur="gEditItemOverlay.onTagsFieldBlur();"
                    observes="paneElementsBroadcaster"/>
           <button id="editBMPanel_tagsSelectorExpander"
                   class="expander-down"
                   tooltiptext="&editBookmarkOverlay.tagsExpanderDown.tooltip;"
@@ -166,32 +171,35 @@
         </row>
 
         <listbox id="editBMPanel_tagsSelector"
                  height="150" collapsed="true"
                  observes="paneElementsBroadcaster"/>
 
         <row id="editBMPanel_keywordRow">
           <label value="&editBookmarkOverlay.keyword.label;"
+                 accesskey="&editBookmarkOverlay.keyword.accesskey;"
                  control="editBMPanel_keywordField"
                  observes="paneElementsBroadcaster"/>
           <textbox id="editBMPanel_keywordField"
                    onblur="gEditItemOverlay.onKeywordFieldBlur();"
                    observes="paneElementsBroadcaster"/>
         </row>
 
         <row id="editBMPanel_descriptionRow">
           <label value="&editBookmarkOverlay.description.label;"
+                 accesskey="&editBookmarkOverlay.description.accesskey;"
                  control="editBMPanel_descriptionField"
                  observes="paneElementsBroadcaster"/>
           <textbox id="editBMPanel_descriptionField"
                    multiline="true"
                    onblur="gEditItemOverlay.onDescriptionFieldBlur();"
                    observes="paneElementsBroadcaster"/>
         </row>
         <checkbox id="editBMPanel_loadInSidebarCheckbox"
                   label="&editBookmarkOverlay.loadInSidebar.label;"
+                  accesskey="&editBookmarkOverlay.loadInSidebar.accesskey;"
                   oncommand="gEditItemOverlay.onLoadInSidebarCheckboxCommand();"
                   observes="paneElementsBroadcaster"/>
       </rows>
     </grid>
   </vbox>
 </overlay>
--- a/browser/components/places/content/menu.xml
+++ b/browser/components/places/content/menu.xml
@@ -287,17 +287,17 @@
             }
           }
         },
 
         itemMoved:
         function PMV_itemMoved(aItem, aOldParent, aOldIndex, aNewParent,
                                aNewIndex) {
           // This cannot actually happen yet (see IDL)
-          if (aNewParent != aOldParent);
+          if (aNewParent != aOldParent)
             return;
 
           var popup = this._getPopupForContainer(aNewParent);
           var index = popup._startMarker + 1 + aNewIndex;
           var children = popup.childNodes;
           for (var i = 0; i < children.length; i++) {
             var menuItem = children[i];
             if (menuItem.node == aItem) {
--- a/browser/components/places/content/places.js
+++ b/browser/components/places/content/places.js
@@ -609,20 +609,22 @@ var PlacesOrganizer = {
   },
 
   toggleAdditionalInfoFields: function PO_toggleAdditionalInfoFields() {
     var infoScrollbox = document.getElementById("infoScrollbox");
     var scrollboxExpander = document.getElementById("infoScrollboxExpander");
     if (infoScrollbox.getAttribute("minimal") == "true") {
       infoScrollbox.removeAttribute("minimal");
       scrollboxExpander.label = scrollboxExpander.getAttribute("lesslabel");
+      scrollboxExpander.accessKey = scrollboxExpander.getAttribute("lessaccesskey");
     }
     else {
       infoScrollbox.setAttribute("minimal", "true");
       scrollboxExpander.label = scrollboxExpander.getAttribute("morelabel");
+      scrollboxExpander.accessKey = scrollboxExpander.getAttribute("moreaccesskey");
     }
   },
 
   /**
    * Save the current search (or advanced query) to the bookmarks root.
    */
   saveSearch: function PO_saveSearch() {
     // Get the place: uri for the query.
--- a/browser/components/places/content/places.xul
+++ b/browser/components/places/content/places.xul
@@ -447,18 +447,21 @@
                   </description>
                   <spacer flex="3"/>
                 </vbox>
                 <scrollbox id="infoScrollbox" minimal="true" orient="vertical" flex="1" style='overflow: auto;'>
                   <vbox id="editBookmarkPanelContent"/>
                   <hbox>
                     <button type="image" id="infoScrollboxExpander"
                             lesslabel="&detailsPane.less.label;"
+                            lessaccesskey="&detailsPane.less.accesskey;"
                             morelabel="&detailsPane.more.label;"
+                            moreaccesskey="&detailsPane.more.accesskey;"
                             label="&detailsPane.more.label;"
+                            accesskey="&detailsPane.more.accesskey;"
                             oncommand="PlacesOrganizer.toggleAdditionalInfoFields();"
                             observes="paneElementsBroadcaster"/>
                     <spacer flex="1"/>
                   </hbox>
                 </scrollbox>
               </deck>
             </hbox>
           </vbox>
--- a/browser/components/places/content/toolbar.xml
+++ b/browser/components/places/content/toolbar.xml
@@ -495,17 +495,17 @@
             }
           }
         },
 
         itemMoved:
         function TV_V_itemMoved(aItem, aOldParent, aOldIndex, aNewParent,
                                 aNewIndex) {
           // This cannot actually happen yet (see IDL)
-          if (aNewParent != aOldParent);
+          if (aNewParent != aOldParent)
             return;
 
           if (aNewParent == this._self.getResultNode()) {
             var children = this._self.childNodes;
             for (var i = 0; i < children.length; i++) {
               var button = children[i];
               if (button.node == aItem) {
                 this._self.removeChild(button);
--- a/browser/components/places/content/tree.xml
+++ b/browser/components/places/content/tree.xml
@@ -431,17 +431,17 @@
         <getter><![CDATA[
           var view = this.view;
           var selection = view.selection;
           var rc = selection.getRangeCount();
           if (rc != 1) 
             return null;
           var min = { }, max = { };
           selection.getRangeAt(0, min, max);
-          
+
           return this.getResultView().nodeForTreeIndex(min.value);
         ]]></getter>
       </property>
       
       <!-- nsIPlacesView -->
       <property name="selectedURINode">
         <getter><![CDATA[
           var view = this.view;
@@ -824,37 +824,24 @@
         onPerformAction: function VO_onPerformAction(action) { },
         onPerformActionOnRow: function VO_onPerformActionOnRow(action, row) { },
         onPerformActionOnCell: function VO_onPerformActionOnCell(action, row, column) { }
       })]]></field>
       
       <field name="_nextSelection">[]</field>
       <field name="SAVE_SELECTION_RELOAD">0</field>
       <field name="SAVE_SELECTION_INSERT">1</field>
-      <field name="SAVE_SELECTION_REMOVE">2</field>
       <method name="saveSelection">
         <parameter name="mode"/>
         <body><![CDATA[ 
           // mode can be one of any of the SAVE_SELECTION field values, 
           // specifying how selection is to be saved.
           var s = this.view.selection;
           var rc = s.getRangeCount();
           switch (mode) {
-          case this.SAVE_SELECTION_REMOVE:
-            var min = { }, max = { };
-            s.getRangeAt(rc - 1, min, max);
-            var rowCount = this.view.rowCount;
-            var index = -1;
-            if (max.value == (rowCount - 1) || 
-                this.view.getLevel(max.value + 1) != this.view.getLevel(max.value))
-              index = max.value - s.count;
-            else
-              index = max.value - s.count + 1;
-            this._nextSelection = [{ min: index, max: index }];
-            break;
           case this.SAVE_SELECTION_INSERT:
             var min = { }, max = { };
             s.getRangeAt(rc - 1, min, max);
             this._nextSelection = [{ min: max.value, max: max.value }];
             break;
           case this.SAVE_SELECTION_RELOAD:
             this._nextSelection = [];
             for (var i = 0; i < rc; ++i) {
--- a/browser/components/places/content/treeView.js
+++ b/browser/components/places/content/treeView.js
@@ -301,28 +301,29 @@ PlacesTreeView.prototype = {
     // We don't replace the container item itself so we decrease the
     // replaceCount by 1. We don't do so though if there is no visible item
     // for the container. This happens when aContainer is the root node and
     // showRoot is not set.
     if (aContainer.viewIndex != -1)
       replaceCount-=1;
 
     // Persist selection state
-    var nodesToSelect = [];
+    var previouslySelectedNodes = [];
     var selection = this.selection;
     var rc = selection.getRangeCount();
     for (var rangeIndex = 0; rangeIndex < rc; rangeIndex++) {
       var min = { }, max = { };
       selection.getRangeAt(rangeIndex, min, max);
       var lastIndex = Math.min(max.value, startReplacement + replaceCount -1);
       if (min.value < startReplacement || min.value > lastIndex)
         continue;
 
       for (var nodeIndex = min.value; nodeIndex <= lastIndex; nodeIndex++)
-        nodesToSelect.push(this._visibleElements[nodeIndex]);
+        previouslySelectedNodes.push({ node: this._visibleElements[nodeIndex],
+                                       oldIndex: nodeIndex });
     }
 
     // Mark the removes as invisible
     for (var i = 0; i < replaceCount; i++)
       this._visibleElements[startReplacement + i].viewIndex = -1;
 
     // Building the new list will set the new elements' visible indices.
     var newElements = [];
@@ -340,17 +341,17 @@ PlacesTreeView.prototype = {
     if (replaceCount != newElements.length) {
       for (i = startReplacement + newElements.length;
            i < this._visibleElements.length; i ++) {
         this._visibleElements[i].viewIndex = i;
       }
     }
 
     // now update the number of elements
-    if (nodesToSelect.length > 0)
+    if (previouslySelectedNodes.length > 0)
       selection.selectEventsSuppressed = true;
 
     this._tree.beginUpdateBatch();
     if (replaceCount)
       this._tree.rowCountChanged(startReplacement, -replaceCount);
     if (newElements.length)
       this._tree.rowCountChanged(startReplacement, newElements.length);
 
@@ -368,43 +369,53 @@ PlacesTreeView.prototype = {
       // and didn't find a match, so we can open our item
       if (!parent)
         item.containerOpen = !item.containerOpen;
     }
 
     this._tree.endUpdateBatch();
 
     // restore selection
-    if (nodesToSelect.length > 0) {
-      for each (var node in nodesToSelect) {
-        var index = node.viewIndex;
+    if (previouslySelectedNodes.length > 0) {
+      for each (var nodeInfo in previouslySelectedNodes) {
+        var index = nodeInfo.node.viewIndex;
 
         // if the same node was used (happens on sorting-changes),
         // just use viewIndex
         if (index == -1) { // otherwise, try to find an equal node
-          var itemId = node.itemId;
+          var itemId = nodeInfo.node.itemId;
           if (itemId != 1) { // bookmark-nodes in queries case
             for (i=0; i < newElements.length && index == -1; i++) {
               if (newElements[i].itemId == itemId)
                 index = newElements[i].viewIndex;
             }
           }
           else { // history nodes
-            var uri = node.uri;
+            var uri = nodeInfo.node.uri;
             if (uri) {
               for (i=0; i < newElements.length && index == -1; i++) {
                 if (newElements[i].uri == uri)
                   index = newElements[i].viewIndex;
               }
             }
           }
         }
         if (index != -1)
           selection.rangedSelect(index, index, true);
       }
+
+      // if only one node was previously selected and there's no selection now,
+      // select the node at its old-viewIndex, if any
+      if (previouslySelectedNodes.length == 1 &&
+          selection.getRangeCount() == 0 &&
+          this._visibleElements.length > previouslySelectedNodes[0].oldIndex) {
+        selection.rangedSelect(previouslySelectedNodes[0].oldIndex,
+                               previouslySelectedNodes[0].oldIndex, true);
+      }
+
       selection.selectEventsSuppressed = false;
     }
   },
 
   /**
    * This returns true if the two results can be collapsed as duplicates.
    * aShowThisOne will be either 0 or 1, indicating which of the
    * duplicates should be shown.
@@ -662,16 +673,27 @@ PlacesTreeView.prototype = {
     NS_ASSERT(this._result, "Got a notification but have no result!");
     if (!this._tree)
       return; // nothing to do
 
     var oldViewIndex = aItem.viewIndex;
     if (oldViewIndex < 0)
       return; // item was already invisible, nothing to do
 
+    // if the item was exclusively selected, the node next to it will be
+    // selected
+    var selectNext = false;
+    var selection = this.selection;
+    if (selection.getRangeCount() == 1) {
+      var min = { }, max = { };
+      selection.getRangeAt(0, min, max);
+      if (min.value == max.value)
+        selectNext = true;
+    }
+
     // this may have been a container, in which case it has a lot of rows
     var count = this._countVisibleRowsForItem(aItem);
 
     // We really want tail recursion here, since we sometimes do another
     // remove after this when duplicates are being collapsed. This loop
     // emulates that.
     while (true) {
       NS_ASSERT(oldViewIndex <= this._visibleElements.length,
@@ -705,16 +727,20 @@ PlacesTreeView.prototype = {
         }
       }
       break; // normal path: just remove once
     }
 
     // redraw parent because twisty may have changed
     if (!aParent.hasChildren)
       this.itemChanged(aParent);
+
+    // restore selection
+    if (selectNext && this._visibleElements.length > oldViewIndex)
+      selection.rangedSelect(oldViewIndex, oldViewIndex, true);
   },
 
   /**
    * Be careful, aOldIndex and aNewIndex specify the index in the
    * corresponding parent nodes, not the visible indexes.
    */
   itemMoved:
   function PTV_itemMoved(aItem, aOldParent, aOldIndex, aNewParent, aNewIndex) {
--- a/browser/components/places/content/utils.js
+++ b/browser/components/places/content/utils.js
@@ -1599,35 +1599,45 @@ var PlacesUtils = {
       let contents = this.getFolderContents(aNode.itemId, false, false).root;
       for (let i = 0; i < contents.childCount; ++i) {
         let child = contents.getChild(i);
         if (this.nodeIsURI(child))
           urls.push({uri: child.uri, isBookmark: this.nodeIsBookmark(child)});
       }
     }
     else {
-      let result, oldViewer;
+      let result, oldViewer, wasOpen;
       try {
         let wasOpen = aNode.containerOpen;
+        result = aNode.parentResult;
+        oldViewer = result.viewer;
         if (!wasOpen) {
-          result = aNode.parentResult;
-          oldViewer = result.viewer;
           result.viewer = null;
           aNode.containerOpen = true;
         }
         for (let i = 0; i < aNode.childCount; ++i) {
+          // Include visible url nodes only
           let child = aNode.getChild(i);
-          if (this.nodeIsURI(child))
-            urls.push({uri: child.uri, isBookmark: this.nodeIsBookmark(child)});
+          if (this.nodeIsURI(child)) {
+            // If the node contents is visible, add the uri only if its node is
+            // visible. Otherwise follow viewer's collapseDuplicates property,
+            // default to true
+            if ((wasOpen && oldViewer && child.viewIndex != -1) ||
+                (oldViewer && !oldViewer.collapseDuplicates) ||
+                urls.indexOf(child.uri) == -1) {
+              urls.push({ uri: child.uri,
+                          isBookmark: this.nodeIsBookmark(child) });
+            }
+          }
         }
         if (!wasOpen)
           aNode.containerOpen = false;
       }
       finally {
-        if (oldViewer)
+        if (!wasOpen)
           result.viewer = oldViewer;
       }
     }
 
     return urls;
   },
 
   /**
--- a/browser/components/places/src/nsPlacesImportExportService.cpp
+++ b/browser/components/places/src/nsPlacesImportExportService.cpp
@@ -913,17 +913,17 @@ BookmarkContentSink::HandleLinkBegin(con
   }
 
   // if no previous id (or a legacy id), create a new bookmark
   if (frame.mPreviousId == 0) {
     // create the bookmark
     rv = mBookmarksService->InsertBookmark(frame.mContainerID,
                                            frame.mPreviousLink,
                                            mBookmarksService->DEFAULT_INDEX,
-                                           EmptyString(),
+                                           EmptyCString(),
                                            &frame.mPreviousId);
     NS_ASSERTION(NS_SUCCEEDED(rv), "InsertBookmark failed");
 
     // set the date added value, if we have it
     // important:  this has to happen after InsertBookmark
     // so that we set the imported value
     if (!dateAdded.IsEmpty()) {
       PRTime convertedDateAdded = ConvertImportedDateToInternalDate(NS_ConvertUTF16toUTF8(dateAdded));
@@ -1021,17 +1021,17 @@ BookmarkContentSink::HandleLinkEnd()
         PrintNesting();
         printf("Updating livemark '%s' %lld\n",
                NS_ConvertUTF16toUTF8(frame.mPreviousText).get(), frame.mPreviousId);
 #endif
         rv = mLivemarkService->SetSiteURI(frame.mPreviousId, frame.mPreviousLink);
         NS_ASSERTION(NS_SUCCEEDED(rv), "SetSiteURI failed!");
         rv = mLivemarkService->SetFeedURI(frame.mPreviousId, frame.mPreviousFeed);
         NS_ASSERTION(NS_SUCCEEDED(rv), "SetFeedURI failed!");
-        rv = mBookmarksService->SetItemTitle(frame.mPreviousId, frame.mPreviousText);
+        rv = mBookmarksService->SetItemTitle(frame.mPreviousId, NS_ConvertUTF16toUTF8(frame.mPreviousText));
         NS_ASSERTION(NS_SUCCEEDED(rv), "SetItemTitle failed!");
       }
     }
 
     if (!isLivemark) {
       if (mIsImportDefaults) {
         rv = mLivemarkService->CreateLivemarkFolderOnly(mBookmarksService,
                                                    frame.mContainerID,
@@ -1064,21 +1064,21 @@ BookmarkContentSink::HandleLinkEnd()
            NS_ConvertUTF16toUTF8(frame.mPreviousText).get(), frame.mPreviousId);
 #endif
     if (frame.mPreviousMicrosummary) {
       rv = mAnnotationService->SetItemAnnotationString(frame.mPreviousId, STATIC_TITLE_ANNO,
                                                        frame.mPreviousText, 0,
                                                        nsIAnnotationService::EXPIRE_NEVER);
       NS_ASSERTION(NS_SUCCEEDED(rv), "Could not store user's bookmark title!");
 
-      mBookmarksService->SetItemTitle(frame.mPreviousId, frame.mPreviousMicrosummaryText);
+      mBookmarksService->SetItemTitle(frame.mPreviousId, NS_ConvertUTF16toUTF8(frame.mPreviousMicrosummaryText));
       mMicrosummaryService->SetMicrosummary(frame.mPreviousId, frame.mPreviousMicrosummary);
     }
     else
-      mBookmarksService->SetItemTitle(frame.mPreviousId, frame.mPreviousText);
+      mBookmarksService->SetItemTitle(frame.mPreviousId, NS_ConvertUTF16toUTF8(frame.mPreviousText));
   }
 
   // Set last-modified-date for bookmarks and livemarks here so that the
   // imported date overrides the date from the call to that sets the description
   // that we made above.
   if (frame.mPreviousId > 0 && frame.mPreviousLastModifiedDate > 0) {
     rv = mBookmarksService->SetItemLastModified(frame.mPreviousId, frame.mPreviousLastModifiedDate);
     NS_ASSERTION(NS_SUCCEEDED(rv), "SetItemLastModified failed");
@@ -1114,17 +1114,17 @@ BookmarkContentSink::HandleSeparator(con
   for (PRInt32 i = 0; i < attrCount; i ++) {
     const nsAString& key = aNode.GetKeyAt(i);
     if (key.LowerCaseEqualsLiteral(KEY_NAME_LOWER))
       name = aNode.GetValueAt(i);
   }
   name.Trim(kWhitespace);
 
   if (!name.IsEmpty())
-    mBookmarksService->SetItemTitle(frame.mPreviousId, name);
+    mBookmarksService->SetItemTitle(frame.mPreviousId, NS_ConvertUTF16toUTF8(name));
 
   // Note: we do not need to import ADD_DATE or LAST_MODIFIED for separators
   // because pre-Places bookmarks does not support them.
   // and we can't write them out because attributes other than NAME
   // will make Firefox 2.x crash/hang - see bug #381129
 }
 
 
@@ -1145,17 +1145,17 @@ BookmarkContentSink::NewFrame()
   frame.ConsumeHeading(&containerName, &containerType);
 
   PRBool updateFolder = PR_FALSE;
   
   switch (containerType) {
     case BookmarkImportFrame::Container_Normal:
       // append a new folder
       rv = mBookmarksService->CreateFolder(CurFrame().mContainerID,
-                                           containerName,
+                                           NS_ConvertUTF16toUTF8(containerName),
                                            mBookmarksService->DEFAULT_INDEX, 
                                            &ourID);
       NS_ENSURE_SUCCESS(rv, rv);
       break;
     case BookmarkImportFrame::Container_Places:
       // places root, never reparent here, when we're building the initial
       // hierarchy, it will only be defined at the top level
       rv = mBookmarksService->GetPlacesRoot(&ourID);
@@ -1197,17 +1197,17 @@ BookmarkContentSink::NewFrame()
 #ifdef DEBUG_IMPORT
   PrintNesting();
   printf("Folder %lld \'%s\'", ourID, NS_ConvertUTF16toUTF8(containerName).get());
 #endif
 
   if (updateFolder) {
     // move the menu folder to the current position
     mBookmarksService->MoveItem(ourID, CurFrame().mContainerID, -1);
-    mBookmarksService->SetItemTitle(ourID, containerName);
+    mBookmarksService->SetItemTitle(ourID, NS_ConvertUTF16toUTF8(containerName));
 #ifdef DEBUG_IMPORT
     printf(" [reparenting]");
 #endif
   }
 
 #ifdef DEBUG_IMPORT
   printf("\n");
 #endif
@@ -2060,23 +2060,23 @@ nsPlacesImportExportService::WriteSepara
   // XXX: separator result nodes don't support the title getter yet
   PRInt64 itemId;
   rv = aItem->GetItemId(&itemId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Note: we can't write the separator ID or anything else other than NAME
   // because it makes Firefox 2.x crash/hang - see bug #381129
 
-  nsAutoString title;
+  nsCAutoString title;
   rv = mBookmarksService->GetItemTitle(itemId, title);
   if (NS_SUCCEEDED(rv) && !title.IsEmpty()) {
     rv = aOutput->Write(kNameAttribute, strlen(kNameAttribute), &dummy);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    char* escapedTitle = nsEscapeHTML(NS_ConvertUTF16toUTF8(title).get());
+    char* escapedTitle = nsEscapeHTML(title.get());
     if (escapedTitle) {
       PRUint32 dummy;
       rv = aOutput->Write(escapedTitle, strlen(escapedTitle), &dummy);
       nsMemory::Free(escapedTitle);
       NS_ENSURE_SUCCESS(rv, rv);
       rv = aOutput->Write(kQuoteStr, sizeof(kQuoteStr)-1, &dummy);
       NS_ENSURE_SUCCESS(rv, rv);
     }
--- a/browser/components/places/src/nsPlacesTransactionsService.js
+++ b/browser/components/places/src/nsPlacesTransactionsService.js
@@ -801,17 +801,23 @@ placesSortFolderByNameTransactions.proto
 
     var contents = PlacesUtils.getFolderContents(this._folderId, false, false).root;
     var count = contents.childCount;
 
     // sort between separators
     var newOrder = []; 
     var preSep = []; // temporary array for sorting each group of items
     var sortingMethod =
-      function (a, b) { return a.title.localeCompare(b.title); };
+      function (a, b) {
+        if (PlacesUtils.nodeIsContainer(a) && !PlacesUtils.nodeIsContainer(b))
+          return -1;
+        if (!PlacesUtils.nodeIsContainer(a) && PlacesUtils.nodeIsContainer(b))
+          return 1;
+        return a.title.localeCompare(b.title);
+      };
 
     for (var i = 0; i < count; ++i) {
       var item = contents.getChild(i);
       this._oldOrder[item.itemId] = i;
       if (PlacesUtils.nodeIsSeparator(item)) {
         if (preSep.length > 0) {
           preSep.sort(sortingMethod);
           newOrder = newOrder.concat(preSep);
--- a/browser/components/preferences/Makefile.in
+++ b/browser/components/preferences/Makefile.in
@@ -38,16 +38,20 @@
 
 DEPTH		= ../../..
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
+ifdef MOZ_MOCHITEST
+DIRS += tests
+endif
+
 include $(topsrcdir)/config/rules.mk
 
 DEFINES += \
 	-DMOZ_APP_NAME=$(MOZ_APP_NAME) \
 	-DMOZ_APP_DISPLAYNAME=$(MOZ_APP_DISPLAYNAME) \
 	$(NULL)
 
 ifneq (,$(filter windows gtk2 mac cocoa, $(MOZ_WIDGET_TOOLKIT)))
--- a/browser/components/preferences/applications.js
+++ b/browser/components/preferences/applications.js
@@ -1243,61 +1243,67 @@ var gApplicationsPane = {
       askMenuItem.setAttribute("alwaysAsk", "true");
       let label;
       if (handlerInfo.type == TYPE_MAYBE_FEED)
         label = this._prefsBundle.getFormattedString("previewInApp",
                                                      [this._brandShortName]);
       else
         label = this._prefsBundle.getString("alwaysAsk");
       askMenuItem.setAttribute("label", label);
+      askMenuItem.setAttribute("tooltiptext", label);
       askMenuItem.setAttribute("image", ICON_URL_ASK);
       menuPopup.appendChild(askMenuItem);
     }
 
     // If this is the feed type, add a Live Bookmarks item.
     if (handlerInfo.type == TYPE_MAYBE_FEED) {
       var internalMenuItem = document.createElementNS(kXULNS, "menuitem");
       internalMenuItem.setAttribute("action", Ci.nsIHandlerInfo.handleInternally);
       let label = this._prefsBundle.getFormattedString("liveBookmarksInApp",
                                                        [this._brandShortName]);
       internalMenuItem.setAttribute("label", label);
+      internalMenuItem.setAttribute("tooltiptext", label);
       internalMenuItem.setAttribute("image", ICON_URL_LIVEMARK);
       menuPopup.appendChild(internalMenuItem);
 
       // Add a separator to distinguish these items from the helper app items
       // that follow them.
       let menuItem = document.createElementNS(kXULNS, "menuseparator");
       menuPopup.appendChild(menuItem);
     }
 
     // Create a menu item for the OS default application, if any.
     if (handlerInfo.hasDefaultHandler) {
       var defaultMenuItem = document.createElementNS(kXULNS, "menuitem");
       defaultMenuItem.setAttribute("action", Ci.nsIHandlerInfo.useSystemDefault);
       defaultMenuItem.setAttribute("label", handlerInfo.defaultDescription);
+      defaultMenuItem.setAttribute("tooltiptext", handlerInfo.defaultDescription);
       defaultMenuItem.setAttribute("image", this._getIconURLForSystemDefault(handlerInfo));
 
       menuPopup.appendChild(defaultMenuItem);
     }
 
     // Create menu items for possible handlers.
     let preferredApp = handlerInfo.preferredApplicationHandler;
     let possibleApps = handlerInfo.possibleApplicationHandlers.enumerate();
     var possibleAppMenuItems = [];
     while (possibleApps.hasMoreElements()) {
       let possibleApp = possibleApps.getNext();
       if (!this.isValidHandlerApp(possibleApp))
         continue;
 
       let menuItem = document.createElementNS(kXULNS, "menuitem");
       menuItem.setAttribute("action", Ci.nsIHandlerInfo.useHelperApp);
+      let label;
       if (possibleApp instanceof Ci.nsILocalHandlerApp)
-        menuItem.setAttribute("label", getDisplayNameForFile(possibleApp.executable));
+        label = getDisplayNameForFile(possibleApp.executable);
       else
-        menuItem.setAttribute("label", possibleApp.name);
+        label = possibleApp.name;
+      menuItem.setAttribute("label", label);
+      menuItem.setAttribute("tooltiptext", label);
       menuItem.setAttribute("image", this._getIconURLForHandlerApp(possibleApp));
 
       // Attach the handler app object to the menu item so we can use it
       // to make changes to the datastore when the user selects the item.
       menuItem.handlerApp = possibleApp;
 
       menuPopup.appendChild(menuItem);
       possibleAppMenuItems.push(menuItem);
@@ -1306,37 +1312,49 @@ var gApplicationsPane = {
     // Create a menu item for the plugin.
     if (handlerInfo.plugin) {
       var pluginMenuItem = document.createElementNS(kXULNS, "menuitem");
       pluginMenuItem.setAttribute("action", kActionUsePlugin);
       let label = this._prefsBundle.getFormattedString("pluginName",
                                                        [handlerInfo.plugin.name,
                                                         this._brandShortName]);
       pluginMenuItem.setAttribute("label", label);
+      pluginMenuItem.setAttribute("tooltiptext", label);
       pluginMenuItem.setAttribute("image", ICON_URL_PLUGIN);
       menuPopup.appendChild(pluginMenuItem);
     }
 
     // Create a menu item for selecting a local application.
+#ifdef XP_WIN
+    // On Windows, selecting an application to open another application
+    // would be meaningless so we special case executables.
+    var executableType = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService)
+                                                  .getTypeFromExtension("exe");
+    if (handlerInfo.type != executableType)
+#endif
     {
       let menuItem = document.createElementNS(kXULNS, "menuitem");
       menuItem.setAttribute("oncommand", "gApplicationsPane.chooseApp(event)");
-      menuItem.setAttribute("label", this._prefsBundle.getString("chooseApp"));
+      let label = this._prefsBundle.getString("chooseApp");
+      menuItem.setAttribute("label", label);
+      menuItem.setAttribute("tooltiptext", label);
       menuPopup.appendChild(menuItem);
     }
 
     // Create a menu item for saving to disk.
     // Note: this option isn't available to protocol types, since we don't know
     // what it means to save a URL having a certain scheme to disk, nor is it
     // available to feeds, since the feed code doesn't implement the capability.
     if ((handlerInfo.wrappedHandlerInfo instanceof Ci.nsIMIMEInfo) &&
         handlerInfo.type != TYPE_MAYBE_FEED) {
       var saveMenuItem = document.createElementNS(kXULNS, "menuitem");
       saveMenuItem.setAttribute("action", Ci.nsIHandlerInfo.saveToDisk);
-      saveMenuItem.setAttribute("label", this._prefsBundle.getString("saveFile"));
+      let label = this._prefsBundle.getString("saveFile");
+      saveMenuItem.setAttribute("label", label);
+      saveMenuItem.setAttribute("tooltiptext", label);
       saveMenuItem.setAttribute("image", ICON_URL_SAVE);
       menuPopup.appendChild(saveMenuItem);
     }
 
     // Select the item corresponding to the preferred action.  If the always
     // ask flag is set, it overrides the preferred action.  Otherwise we pick
     // the item identified by the preferred action (when the preferred action
     // is to use a helper app, we have to pick the specific helper app item).
--- a/browser/components/preferences/handlers.xml
+++ b/browser/components/preferences/handlers.xml
@@ -56,39 +56,40 @@
         </getter>
       </property>
     </implementation>
   </binding>
 
   <binding id="handler" extends="chrome://browser/content/preferences/handlers.xml#handler-base">
     <content>
       <xul:hbox flex="1" equalsize="always">
-        <xul:hbox flex="1" align="center">
+        <xul:hbox flex="1" align="center" xbl:inherits="tooltiptext=typeDescription">
           <xul:image src="moz-icon://goat?size=16" class="typeIcon"
                      xbl:inherits="src=typeIcon" height="16" width="16"/>
           <xul:label flex="1" crop="end" xbl:inherits="value=typeDescription"/>
         </xul:hbox>
-        <xul:hbox flex="1" align="center">
+        <xul:hbox flex="1" align="center" xbl:inherits="tooltiptext=actionDescription">
           <xul:image xbl:inherits="src=actionIcon" height="16" width="16" class="actionIcon"/>
           <xul:label flex="1" crop="end" xbl:inherits="value=actionDescription"/>
         </xul:hbox>
       </xul:hbox>
     </content>
   </binding>
 
   <binding id="handler-selected" extends="chrome://browser/content/preferences/handlers.xml#handler-base">
     <content>
       <xul:hbox flex="1" equalsize="always">
-        <xul:hbox flex="1" align="center">
+        <xul:hbox flex="1" align="center" xbl:inherits="tooltiptext=typeDescription">
           <xul:image src="moz-icon://goat?size=16" class="typeIcon"
                      xbl:inherits="src=typeIcon" height="16" width="16"/>
           <xul:label flex="1" crop="end" xbl:inherits="value=typeDescription"/>
         </xul:hbox>
         <xul:hbox flex="1">
           <xul:menulist class="actionsMenu" flex="1" crop="end" selectedIndex="1"
+                        xbl:inherits="tooltiptext=actionDescription"
                         oncommand="gApplicationsPane.onSelectAction(event.originalTarget)">
             <xul:menupopup/>
           </xul:menulist>
         </xul:hbox>
       </xul:hbox>
     </content>
 
     <implementation>
--- a/browser/components/preferences/privacy.xul
+++ b/browser/components/preferences/privacy.xul
@@ -178,17 +178,17 @@
                 accesskey="&clearDataSettings.accesskey;"
                 oncommand="gPrivacyPane.showClearPrivateDataSettings();"/>
       </hbox>
       <hbox id="askClearBox">
         <checkbox id="askBeforeClear" flex="1"
                   preference="privacy.sanitize.promptOnSanitize"
                   label="&askBeforeClear.label;"
                   accesskey="&askBeforeClear.accesskey;"/>
-        <button id="clearDataNow"
+        <button id="clearDataNow" icon="clear"
                 label1="&clearDataNow.label;"
                 label2="&clearDataNow.label2;"
                 accesskey="&clearDataNow.accesskey;"
                 oncommand="gPrivacyPane.clearPrivateDataNow();"/>
       </hbox>
     </groupbox>
 
   </prefpane>
new file mode 100644
--- /dev/null
+++ b/browser/components/preferences/tests/Makefile.in
@@ -0,0 +1,50 @@
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is mozilla.org code.
+#
+# The Initial Developer of the Original Code is Mozilla Foundation.
+# Portions created by the Initial Developer are Copyright (C) 2007
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#   Ryan Flint <rflint@dslr.net> (Original Author)
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either of the GNU General Public License Version 2 or later (the "GPL"),
+# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+DEPTH		= ../../../..
+topsrcdir	= @top_srcdir@
+srcdir		= @srcdir@
+VPATH		= @srcdir@
+relativesrcdir  = browser/components/preferences/tests
+
+include $(DEPTH)/config/autoconf.mk
+include $(topsrcdir)/config/rules.mk
+
+_BROWSER_FILES = browser_bug410900.js \
+    $(NULL)
+
+libs::	$(_BROWSER_FILES)
+	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/browser/components/preferences/tests/browser_bug410900.js
@@ -0,0 +1,43 @@
+function test() {
+  waitForExplicitFinish();
+
+  // setup a phony hander to ensure the app pane will be populated.
+  var handler = Cc["@mozilla.org/uriloader/web-handler-app;1"].
+                createInstance(Ci.nsIWebHandlerApp);
+  handler.name = "App pane alive test";
+  handler.uriTemplate = "http://test.mozilla.org/%s";
+
+  var extps = Cc["@mozilla.org/uriloader/external-protocol-service;1"].
+              getService(Ci.nsIExternalProtocolService);
+  var info = extps.getProtocolHandlerInfo("apppanetest");
+  info.possibleApplicationHandlers.appendElement(handler, false);
+
+  var hserv = Cc["@mozilla.org/uriloader/handler-service;1"].
+              getService(Ci.nsIHandlerService);
+  hserv.store(info);
+
+  openDialog("chrome://browser/content/preferences/preferences.xul", "Preferences",
+             "chrome,titlebar,toolbar,centerscreen,dialog=no", "paneApplications");
+  setTimeout(runTest, 1000);
+}
+
+function runTest() {
+  var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
+           getService(Ci.nsIWindowMediator);
+  var win = wm.getMostRecentWindow("Browser:Preferences");
+  ok(win, "Pref window opened");
+
+  if (win) {
+    var sel = win.document.documentElement.getAttribute("lastSelected");
+    ok(sel == "paneApplications", "Specified pane was opened");
+
+    var rbox = win.document.getElementById("handlersView");
+    ok(rbox, "handlersView is present");
+
+    var items = rbox && rbox.getElementsByTagName("richlistitem");
+    ok(items && items.length > 0, "App handler list populated");
+
+    win.close();
+  }
+  finish();
+}
--- a/browser/components/safebrowsing/content/malware-warden.js
+++ b/browser/components/safebrowsing/content/malware-warden.js
@@ -70,18 +70,36 @@ function PROT_MalwareWarden() {
     "n:1000\ni:test-phish-simple\nad:1\n" +
     "a:1:" + testData.length + "\n" +
     testData +
     "\n";
 
   var dbService_ = Cc["@mozilla.org/url-classifier/dbservice;1"]
                    .getService(Ci.nsIUrlClassifierDBService);
 
-  dbService_.update(testUpdate);
-  dbService_.finish(function(result) {}, function(error) {});
+  var listener = {
+    QueryInterface: function(iid)
+    {
+      if (iid.equals(Ci.nsISupports) ||
+          iid.equals(Ci.nsIUrlClassifierUpdateObserver))
+        return this;
+      throw Cr.NS_ERROR_NO_INTERFACE;
+    },
+
+    updateUrlRequested: function(url) { },
+    streamCompleted: function() { },
+    updateError: function(errorCode) { },
+    updateSuccess: function(requestedTimeout) { }
+  };
+
+  dbService_.beginUpdate(listener);
+  dbService_.beginStream();
+  dbService_.updateStream(testUpdate);
+  dbService_.finishStream();
+  dbService_.finishUpdate();
 
   G_Debug(this, "malwareWarden initialized");
 }
 
 PROT_MalwareWarden.inherits(PROT_ListWarden);
 
 /**
  * Cleanup on shutdown.
--- a/browser/components/search/nsSearchService.js
+++ b/browser/components/search/nsSearchService.js
@@ -288,16 +288,18 @@ loadListener.prototype = {
   _stream: null,
 
   QueryInterface: function SRCH_loadQI(aIID) {
     if (aIID.equals(Ci.nsISupports)           ||
         aIID.equals(Ci.nsIRequestObserver)    ||
         aIID.equals(Ci.nsIStreamListener)     ||
         aIID.equals(Ci.nsIChannelEventSink)   ||
         aIID.equals(Ci.nsIInterfaceRequestor) ||
+        aIID.equals(Ci.nsIBadCertListener2)   ||
+        aIID.equals(Ci.nsISSLErrorListener)   ||
         // See FIXME comment below
         aIID.equals(Ci.nsIHttpEventSink)      ||
         aIID.equals(Ci.nsIProgressEventSink)  ||
         false)
       return this;
 
     throw Cr.NS_ERROR_NO_INTERFACE;
   },
@@ -343,16 +345,26 @@ loadListener.prototype = {
     this._channel = aNewChannel;
   },
 
   // nsIInterfaceRequestor
   getInterface: function SRCH_load_GI(aIID) {
     return this.QueryInterface(aIID);
   },
 
+  // nsIBadCertListener2
+  notifyCertProblem: function SRCH_certProblem(socketInfo, status, targetSite) {
+    return true;
+  },
+
+  // nsISSLErrorListener
+  notifySSLError: function SRCH_SSLError(socketInfo, error, targetSite) {
+    return true;
+  },
+
   // FIXME: bug 253127
   // nsIHttpEventSink
   onRedirect: function (aChannel, aNewChannel) {},
   // nsIProgressEventSink
   onProgress: function (aRequest, aContext, aProgress, aProgressMax) {},
   onStatus: function (aRequest, aContext, aStatus, aStatusArg) {}
 }
 
--- a/browser/components/search/nsSearchSuggestions.js
+++ b/browser/components/search/nsSearchSuggestions.js
@@ -642,16 +642,17 @@ SuggestAutoComplete.prototype = {
     // Actually do the search
     this._request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
                     createInstance(Ci.nsIXMLHttpRequest);
     var submission = engine.getSubmission(searchString,
                                           SEARCH_RESPONSE_SUGGESTION_JSON);
     this._suggestURI = submission.uri;
     var method = (submission.postData ? "POST" : "GET");
     this._request.open(method, this._suggestURI.spec, true);
+    this._request.channel.notificationCallbacks = new SearchSuggestLoadListener();
 
     var self = this;
     function onReadyStateChange() {
       self.onReadyStateChange();
     }
     this._request.onreadystatechange = onReadyStateChange;
     this._request.send(submission.postData);
 
@@ -706,16 +707,40 @@ SuggestAutoComplete.prototype = {
     os.removeObserver(this, XPCOM_SHUTDOWN_TOPIC);
   },
 
   // nsISupports
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteSearch,
                                          Ci.nsIAutoCompleteObserver])
 };
 
+function SearchSuggestLoadListener() {
+}
+SearchSuggestLoadListener.prototype = {
+  // nsIBadCertListener2
+  notifyCertProblem: function SSLL_certProblem(socketInfo, status, targetSite) {
+    return true;
+  },
+
+  // nsISSLErrorListener
+  notifySSLError: function SSLL_SSLError(socketInfo, error, targetSite) {
+    return true;
+  },
+
+  // nsIInterfaceRequestor
+  getInterface: function SSLL_getInterface(iid) {
+    return this.QueryInterface(iid);
+  },
+
+  // nsISupports
+  QueryInterface: XPCOMUtils.generateQI([Ci.nsIBadCertListener2,
+                                         Ci.nsISSLErrorListener,
+                                         Ci.nsIInterfaceRequestor])
+};
+
 /**
  * SearchSuggestAutoComplete is a service implementation that handles suggest
  * results specific to web searches.
  * @constructor
  */
 function SearchSuggestAutoComplete() {
   // This calls _init() in the parent class (SuggestAutoComplete) via the
   // prototype, below.
--- a/browser/components/sessionstore/src/nsSessionStore.js
+++ b/browser/components/sessionstore/src/nsSessionStore.js
@@ -14,17 +14,17 @@
  * The Original Code is the nsSessionStore component.
  *
  * The Initial Developer of the Original Code is
  * Simon Bünzli <zeniko@gmail.com>
  * Portions created by the Initial Developer are Copyright (C) 2006
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
- *   Dietrich Ayala <autonome@gmail.com>
+ *   Dietrich Ayala <dietrich@mozilla.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
@@ -52,24 +52,27 @@
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 const Cr = Components.results;
 const Cu = Components.utils;
 
 const STATE_STOPPED = 0;
 const STATE_RUNNING = 1;
 const STATE_QUITTING = -1;
+const STATE_DISABLED = -2;
 
 const STATE_STOPPED_STR = "stopped";
 const STATE_RUNNING_STR = "running";
 
 const PRIVACY_NONE = 0;
 const PRIVACY_ENCRYPTED = 1;
 const PRIVACY_FULL = 2;
 
+const NOTIFY_WINDOWS_RESTORED = "sessionstore-windows-restored";
+
 // global notifications observed
 const OBSERVING = [
   "domwindowopened", "domwindowclosed",
   "quit-application-requested", "quit-application-granted",
   "quit-application", "browser:purge-session-history"
 ];
 
 /*
@@ -127,16 +130,19 @@ SessionStoreService.prototype = {
   _loadState: STATE_STOPPED,
 
   // minimal interval between two save operations (in milliseconds)
   _interval: 10000,
 
   // when crash recovery is disabled, session data is not written to disk
   _resume_from_crash: true,
 
+  // During the initial restore tracks the number of windows yet to be restored
+  _restoreCount: 0,
+
   // time in milliseconds (Date.now()) when the session was last written to file
   _lastSaveTime: 0, 
 
   // states for all currently opened windows
   _windows: {},
 
   // in case the last closed window ain't a navigator:browser one
   _lastWindowClosed: null,
@@ -148,35 +154,43 @@ SessionStoreService.prototype = {
   _dirty: false,
 
 /* ........ Global Event Handlers .............. */
 
   /**
    * Initialize the component
    */
   init: function sss_init(aWindow) {
+    if (this._loadState == STATE_DISABLED)
+      return;
+
     if (!aWindow || this._loadState == STATE_RUNNING) {
       // make sure that all browser windows which try to initialize
       // SessionStore are really tracked by it
       if (aWindow && (!aWindow.__SSi || !this._windows[aWindow.__SSi]))
         this.onLoad(aWindow);
       return;
     }
 
     this._prefBranch = Cc["@mozilla.org/preferences-service;1"].
                        getService(Ci.nsIPrefService).getBranch("browser.");
     this._prefBranch.QueryInterface(Ci.nsIPrefBranch2);
 
-    // if the service is disabled, do not init 
-    if (!this._prefBranch.getBoolPref("sessionstore.enabled"))
-      return;
-
     var observerService = Cc["@mozilla.org/observer-service;1"].
                           getService(Ci.nsIObserverService);
 
+    // if the service is disabled, do not init 
+    if (!this._prefBranch.getBoolPref("sessionstore.enabled")) {
+      // Notify observers that the sessionstore has done everything it is going to.
+      observerService.notifyObservers(null, NOTIFY_WINDOWS_RESTORED, "");
+      // Mark as disabled so we don't even try to initialise again.
+      this._loadState = STATE_DISABLED;
+      return;
+    }
+
     OBSERVING.forEach(function(aTopic) {
       observerService.addObserver(this, aTopic, true);
     }, this);
     
     // get interval from prefs - used often, so caching/observing instead of fetching on-demand
     this._interval = this._prefBranch.getIntPref("sessionstore.interval");
     this._prefBranch.addObserver("sessionstore.interval", this, true);
     
@@ -415,19 +429,26 @@ SessionStoreService.prototype = {
       // don't save during the first ten seconds
       // (until most of the pages have been restored)
       this.saveStateDelayed(aWindow, 10000);
 
       // restore a crashed session resp. resume the last session if requested
       if (this._initialState) {
         // make sure that the restored tabs are first in the window
         this._initialState._firstTabs = true;
+        this._restoreCount = this._initialState.windows ? this._initialState.windows.length : 0;
         this.restoreWindow(aWindow, this._initialState, this._isCmdLineEmpty(aWindow));
         delete this._initialState;
       }
+      else {
+        // Nothing to restore, notify observers things are complete.
+        var observerService = Cc["@mozilla.org/observer-service;1"].
+                              getService(Ci.nsIObserverService);
+        observerService.notifyObservers(null, NOTIFY_WINDOWS_RESTORED, "");
+      }
     }
     
     var tabbrowser = aWindow.getBrowser();
     var tabpanels = tabbrowser.mPanelContainer;
     
     // add tab change listeners to all already existing tabs
     for (var i = 0; i < tabpanels.childNodes.length; i++) {
       this.onTabAdd(aWindow, tabpanels.childNodes[i], true);
@@ -823,20 +844,25 @@ SessionStoreService.prototype = {
     catch (ex) { } // this could happen if we catch a tab during (de)initialization
     
     if (history && browser.parentNode.__SS_data &&
         browser.parentNode.__SS_data.entries[history.index]) {
       tabData = browser.parentNode.__SS_data;
       tabData.index = history.index + 1;
     }
     else if (history && history.count > 0) {
-      for (var j = 0; j < history.count; j++)
+      // Cap the number of back history entries saved. (-1 = no cap)
+      var cap = this._prefBranch.getIntPref("sessionstore.max_tab_back_history");
+
+      var startIndex = -1 < cap && cap < history.index ? history.index - cap : 0;
+      for (var j = startIndex; j < history.count; j++)
         tabData.entries.push(this._serializeHistoryEntry(history.getEntryAtIndex(j, false)));
-      tabData.index = history.index + 1;
-      
+
+      tabData.index = history.index - startIndex + 1;
+
       browser.parentNode.__SS_data = tabData;
     }
     else {
       tabData.entries[0] = { url: browser.currentURI.spec };
       tabData.index = 1;
     }
     
     tabData.zoom = browser.markupDocumentViewer.textZoom;
@@ -1286,16 +1312,26 @@ SessionStoreService.prototype = {
    * @param aState
    *        JS object or its eval'able source
    * @param aOverwriteTabs
    *        bool overwrite existing tabs w/ new ones
    * @param aFollowUp
    *        bool this isn't the restoration of the first window
    */
   restoreWindow: function sss_restoreWindow(aWindow, aState, aOverwriteTabs, aFollowUp) {
+    if (this._restoreCount) {
+      this._restoreCount--;
+      if (this._restoreCount == 0) {
+        // This was the last window restored at startup, notify observers.
+        var observerService = Cc["@mozilla.org/observer-service;1"].
+                              getService(Ci.nsIObserverService);
+        observerService.notifyObservers(null, NOTIFY_WINDOWS_RESTORED, "");
+      }
+    }
+
     if (!aFollowUp) {
       this.windowToFocus = aWindow;
     }
     // initialize window if necessary
     if (aWindow && (!aWindow.__SSi || !this._windows[aWindow.__SSi]))
       this.onLoad(aWindow);
 
     try {
--- a/browser/installer/unix/packages-static
+++ b/browser/installer/unix/packages-static
@@ -86,16 +86,17 @@ bin/components/docshell.xpt
 bin/components/dom.xpt
 bin/components/dom_base.xpt
 bin/components/dom_canvas.xpt
 bin/components/dom_core.xpt
 bin/components/dom_css.xpt
 bin/components/dom_events.xpt
 bin/components/dom_html.xpt
 bin/components/dom_offline.xpt
+bin/components/dom_json.xpt
 bin/components/dom_range.xpt
 bin/components/dom_sidebar.xpt
 bin/components/dom_storage.xpt
 bin/components/dom_stylesheets.xpt
 bin/components/dom_traversal.xpt
 bin/components/dom_views.xpt
 bin/components/dom_xbl.xpt
 bin/components/dom_xpath.xpt
@@ -236,16 +237,17 @@ 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
 bin/components/nsScriptableIO.js
 bin/components/nsWebHandlerApp.js
+bin/components/libdbusservice.so
 
 ; Modules
 bin/modules/*
 
 ; Safe Browsing
 bin/components/nsSafebrowsingApplication.js
 bin/components/safebrowsing.xpt
 bin/components/nsUrlClassifierListManager.js
--- a/browser/installer/windows/packages-static
+++ b/browser/installer/windows/packages-static
@@ -94,16 +94,17 @@ bin\components\docshell_base.xpt
 bin\components\dom.xpt
 bin\components\dom_base.xpt
 bin\components\dom_canvas.xpt
 bin\components\dom_core.xpt
 bin\components\dom_css.xpt
 bin\components\dom_events.xpt
 bin\components\dom_html.xpt
 bin\components\dom_offline.xpt
+bin\components\dom_json.xpt
 bin\components\dom_range.xpt
 bin\components\dom_sidebar.xpt
 bin\components\dom_storage.xpt
 bin\components\dom_stylesheets.xpt
 bin\components\dom_traversal.xpt
 bin\components\dom_views.xpt
 bin\components\dom_xbl.xpt
 bin\components\dom_xpath.xpt
--- a/browser/locales/en-US/chrome/browser/baseMenuOverlay.dtd
+++ b/browser/locales/en-US/chrome/browser/baseMenuOverlay.dtd
@@ -13,24 +13,23 @@
 <!ENTITY aboutCmd.label           "About &brandFullName;">
 <!ENTITY aboutCmd.accesskey       "A">
 <!ENTITY helpContents.label       "Help Contents">
 <!ENTITY helpContents.accesskey   "H">
 <!ENTITY helpContentsMac.label    "&brandShortName; Help">
 <!ENTITY helpForIEUsers.label     "For Internet Explorer Users">
 <!ENTITY helpForIEUsers.accesskey "I">
 <!ENTITY openHelp.commandkey      "VK_F1">
-<!ENTITY openHelpMac.commandkey   "VK_HELP">
-<!-- LOCALIZATION NOTE openHelpMac2.commandkey and openHelpMac2.modifiers
+<!-- LOCALIZATION NOTE openHelpMac.commandkey and openHelpMac.modifiers
                        are all the necessary keys to hit OS X's open-help 
                        keyboard (visible) shortcut (that's Cmd+? for most locales) -->
-<!ENTITY openHelpMac2.commandkey           "/">
-<!ENTITY openHelpMac2.modifiers            "accel,shift">
-<!ENTITY openHelpMac2.frontendCommandkey   "?">
-<!ENTITY openHelpMac2.frontendModifiers    "accel">
+<!ENTITY openHelpMac.commandkey           "/">
+<!ENTITY openHelpMac.modifiers            "accel,shift">
+<!ENTITY openHelpMac.frontendCommandkey   "?">
+<!ENTITY openHelpMac.frontendModifiers    "accel">
 
 <!ENTITY helpReleaseNotes.label         "Release Notes">
 <!ENTITY helpReleaseNotes.accesskey     "N">
 <!ENTITY updateCmd.label                "Check for Updates…">
 <!ENTITY updateCmd.accesskey            "o">
 
 <!ENTITY preferencesCmdMac.label        "Preferences…">
 <!ENTITY preferencesCmdMac.commandkey   ",">
--- a/browser/locales/en-US/chrome/browser/browser.dtd
+++ b/browser/locales/en-US/chrome/browser/browser.dtd
@@ -50,18 +50,18 @@
 <!ENTITY fullScreenRestore.tooltip "Restore">
 <!ENTITY fullScreenClose.tooltip "Close">
 
 <!ENTITY closeWindow.label "Close Window">
 <!ENTITY closeWindow.accesskey "d">
 
 <!ENTITY bookmarksMenu.label "Bookmarks">
 <!ENTITY bookmarksMenu.accesskey "B">
-<!ENTITY addCurPageAsCmd.label "Bookmark This Page…">
-<!ENTITY addCurPageAsCmd.commandkey "d">
+<!ENTITY bookmarkThisPageCmd.label "Bookmark This Page">
+<!ENTITY bookmarkThisPageCmd.commandkey "d">
 <!ENTITY subscribeToPageMenupopup.label "Subscribe to This Page">
 <!ENTITY subscribeToPageMenuitem.label "Subscribe to This Page…">
 <!ENTITY addCurPagesCmd.label "Bookmark All Tabs…">
 <!ENTITY showAllBookmarksCmd.label "Show All Bookmarks…">
 <!ENTITY bookmarkAllCmd.label "Bookmark All Tabs…">
 
 <!ENTITY backCmd.label                "Back">
 <!ENTITY backCmd.accesskey            "B">
@@ -168,16 +168,17 @@
 <!ENTITY viewCustomizeToolbar.accesskey     "C">
 
 <!ENTITY historyMenu.label "History">
 <!ENTITY historyMenu.accesskey "s">
 <!ENTITY historyUndoMenu.label "Recently Closed Tabs">
 
 <!ENTITY historyHomeCmd.label "Home">
 <!ENTITY showAllHistoryCmd.label "Show All History…">
+<!ENTITY showAllHistoryCmd.commandkey "H">
 
 <!ENTITY openCmd.commandkey           "l">
 <!ENTITY urlbar.accesskey             "d">
 
 <!-- 
   Comment duplicated from browser-sets.inc:
 
   Search Command Key Logic works like this:
--- a/browser/locales/en-US/chrome/browser/places/editBookmarkOverlay.dtd
+++ b/browser/locales/en-US/chrome/browser/places/editBookmarkOverlay.dtd
@@ -1,13 +1,21 @@
 <!ENTITY editBookmarkOverlay.name.label                      "Name:">
+<!ENTITY editBookmarkOverlay.name.accesskey                  "N">
 <!ENTITY editBookmarkOverlay.location.label                  "Location:">
+<!ENTITY editBookmarkOverlay.location.accesskey              "L">
 <!ENTITY editBookmarkOverlay.feedLocation.label              "Feed Location:">
+<!ENTITY editBookmarkOverlay.feedLocation.accesskey          "F">
 <!ENTITY editBookmarkOverlay.siteLocation.label              "Site Location:">
+<!ENTITY editBookmarkOverlay.siteLocation.accesskey          "S">
 <!ENTITY editBookmarkOverlay.liveTitlesSeparator.label       "Live Titles">
 <!ENTITY editBookmarkOverlay.folder.label                    "Folder:">
 <!ENTITY editBookmarkOverlay.foldersExpanderDown.tooltip     "Show all the bookmarks folders">
 <!ENTITY editBookmarkOverlay.expanderUp.tooltip              "Hide">
 <!ENTITY editBookmarkOverlay.tags.label                      "Tags:">
+<!ENTITY editBookmarkOverlay.tags.accesskey                  "T">
 <!ENTITY editBookmarkOverlay.description.label               "Description:">
+<!ENTITY editBookmarkOverlay.description.accesskey           "D">
 <!ENTITY editBookmarkOverlay.keyword.label                   "Keyword:">
+<!ENTITY editBookmarkOverlay.keyword.accesskey               "K">
 <!ENTITY editBookmarkOverlay.tagsExpanderDown.tooltip        "Show all tags">
 <!ENTITY editBookmarkOverlay.loadInSidebar.label             "Load this bookmark in the sidebar">
+<!ENTITY editBookmarkOverlay.loadInSidebar.accesskey         "h">
--- a/browser/locales/en-US/chrome/browser/places/places.dtd
+++ b/browser/locales/en-US/chrome/browser/places/places.dtd
@@ -199,11 +199,13 @@
 <!ENTITY backCmd.accesskey   "B">
 <!ENTITY backButton.tooltip  "Go back">
 
 <!ENTITY forwardCmd.label       "Forward">
 <!ENTITY forwardCmd.accesskey   "F">
 <!ENTITY forwardButton.tooltip  "Go forward">
 
 <!ENTITY detailsPane.more.label "More">
+<!ENTITY detailsPane.more.accesskey "e">
 <!ENTITY detailsPane.less.label "Less">
+<!ENTITY detailsPane.less.accesskey "e">
 <!ENTITY detailsPane.noPreviewAvailable.label "Preview">
 <!ENTITY detailsPane.selectAnItemText.description "Select an item to view and edit its properties">
--- a/browser/locales/en-US/chrome/help/firebird-toc.rdf
+++ b/browser/locales/en-US/chrome/help/firebird-toc.rdf
@@ -352,17 +352,17 @@
         <rdf:li> <rdf:Description ID="menu-go-history" nc:name="Show in Sidebar" nc:link="menu_reference.xhtml#go_history"/> </rdf:li>
       </rdf:Seq>
     </nc:subheadings>
   </rdf:Description>
 
   <rdf:Description about="#menu-bookmarks">
     <nc:subheadings>
       <rdf:Seq>
-        <rdf:li> <rdf:Description ID="menu-bookmarks-add-to-bookmarks" nc:name="Bookmark This Page…" nc:link="menu_reference.xhtml#add_to_bookmarks"/> </rdf:li>
+        <rdf:li> <rdf:Description ID="menu-bookmarks-add-to-bookmarks" nc:name="Bookmark This Page" nc:link="menu_reference.xhtml#add_to_bookmarks"/> </rdf:li>
         <rdf:li> <rdf:Description ID="menu-bookmarks-subscribe" nc:name="Subscribe to This Page…" nc:link="menu_reference.xhtml#subscribe"/> </rdf:li>
         <rdf:li> <rdf:Description ID="menu-bookmarks-bookmark-all-tabs" nc:name="Bookmark All Tabs…" nc:link="menu_reference.xhtml#bookmark_all_tabs"/> </rdf:li>
         <rdf:li> <rdf:Description ID="menu-bookmarks-organize-bookmarks" nc:name="Organize Bookmarks…" nc:link="menu_reference.xhtml#organize_bookmarks"/> </rdf:li>
       </rdf:Seq>
     </nc:subheadings>
   </rdf:Description>
 
   <rdf:Description about="#menu-tools">
--- a/browser/locales/en-US/chrome/help/menu_reference.xhtml
+++ b/browser/locales/en-US/chrome/help/menu_reference.xhtml
@@ -295,17 +295,17 @@ Contributors:
   <p>Displays the History Sidebar, which keeps track of the sites you have
     visited. To change how many days a site should be remembered, select
     &pref.menuPath; and select the <em>Privacy</em> panel.</p>
 
 <h2 id="bookmarks">Bookmarks</h2>
 
   <p>This menu contains all your stored bookmarks.</p>
 
-  <h3 id="add_to_bookmarks">Bookmark This Page…</h3>
+  <h3 id="add_to_bookmarks">Bookmark This Page</h3>
   <p>Adds the current page to your bookmarks. A dialog will be displayed,
     allowing you to choose a title for the bookmark and specify where you
     want it to be stored.</p>
 
   <h3 id="subscribe">Subscribe to This Page…</h3>
   <p>Shows a preview of the <a href="glossary.xhtml#feed">feed</a> offered by
     the current site. From the preview page, you can subscribe to the feed using
     a <a href="glossary.xhtml#live_bookmark">Live Bookmark</a>, a feed reader
--- a/browser/locales/en-US/chrome/overrides/appstrings.properties
+++ b/browser/locales/en-US/chrome/overrides/appstrings.properties
@@ -47,17 +47,17 @@ confirmRepostPrompt=To display this page
 resendButton.label=Resend
 unknownSocketType=Firefox doesn't know how to communicate with the server.
 netReset=The connection to the server was reset while the page was loading.
 netOffline=Firefox is currently in offline mode and can't browse the Web.
 isprinting=The document cannot change while Printing or in Print Preview.
 deniedPortAccess=This address uses a network port which is normally used for purposes other than Web browsing. Firefox has canceled the request for your protection.
 proxyResolveFailure=Firefox is configured to use a proxy server that can't be found.
 proxyConnectFailure=Firefox is configured to use a proxy server that is refusing connections.
-contentEncodingError=The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression. Please contact the website owners to inform them of this problem.
+contentEncodingError=The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression.
 unsafeContentType=The page you are trying to view cannot be shown because it is contained in a file type that may not be safe to open. Please contact the website owners to inform them of this problem.
 externalProtocolTitle=External Protocol Request
 externalProtocolPrompt=An external application must be launched to handle %1$S: links.\n\n\nRequested link:\n\n%2$S\n\nApplication: %3$S\n\n\nIf you were not expecting this request it may be an attempt to exploit a weakness in that other program. Cancel this request unless you are sure it is not malicious.\n
 #LOCALIZATION NOTE (externalProtocolUnknown): The following string is shown if the application name can't be determined
 externalProtocolUnknown=<Unknown>
 externalProtocolChkMsg=Remember my choice for all links of this type.
 externalProtocolLaunchBtn=Launch application
 malwareBlocked=The site at %S has been reported as an attack site and has been blocked based on your security preferences.
--- a/browser/locales/jar.mn
+++ b/browser/locales/jar.mn
@@ -80,17 +80,20 @@
     locale/browser/help/using_firebird.xhtml          (%chrome/help/using_firebird.xhtml)
     locale/browser/help/customization.xhtml           (%chrome/help/customization.xhtml)
     locale/browser/help/firefox_welcome.xhtml         (%chrome/help/firefox_welcome.xhtml)
     locale/browser/help/download_manager.xhtml        (%chrome/help/download_manager.xhtml)
     locale/browser/help/platformStrings.dtd           (%chrome/help/platformStrings.dtd)
     locale/browser/help/tabbed_browsing.xhtml         (%chrome/help/tabbed_browsing.xhtml)
     locale/browser/help/glossary.xhtml                (%chrome/help/glossary.xhtml)
 # the following files are browser-specific overrides
-*   locale/@AB_CD@/global/netError.dtd                (%chrome/overrides/netError.dtd)
-*   locale/@AB_CD@/global/appstrings.properties       (%chrome/overrides/appstrings.properties)
-*   locale/@AB_CD@/mozapps/downloads/settingsChange.dtd  (%chrome/overrides/settingsChange.dtd)
+*   locale/browser/netError.dtd                (%chrome/overrides/netError.dtd)
+*   locale/browser/appstrings.properties       (%chrome/overrides/appstrings.properties)
+*   locale/browser/downloads/settingsChange.dtd  (%chrome/overrides/settingsChange.dtd)
+% override chrome://global/locale/netErrorApp.dtd chrome://browser/locale/netError.dtd
+% override chrome://global/locale/appstrings.properties chrome://browser/locale/appstrings.properties
+% override chrome://mozapps/locale/downloads/settingsChange.dtd chrome://browser/locale/downloads/settingsChange.dtd
 #ifdef MOZ_USE_GENERIC_BRANDING
 % locale branding @AB_CD@ %locale/branding/
     locale/branding/brand.dtd         (%chrome/branding/brand.dtd)
     locale/branding/brand.properties  (%chrome/branding/brand.properties)
 #endif
 #includesubst @LOCALE_SRCDIR@/extra-jar.mn
--- a/browser/themes/gnomestripe/browser/browser.css
+++ b/browser/themes/gnomestripe/browser/browser.css
@@ -109,16 +109,25 @@ toolbarbutton.bookmark-item[open="true"]
 .bookmark-item > .toolbarbutton-text {
   display: -moz-box !important;
 }
 
 .bookmark-item > .toolbarbutton-menu-dropmarker {
   display: none;
 }
 
+/* Hide icons for the container ("folder") items and use a dropmarker instead */
+.bookmark-item[container] > .toolbarbutton-menu-dropmarker {
+  display: -moz-box !important;
+}
+
+.bookmark-item[container] > .toolbarbutton-icon {
+  display: none !important;
+}
+
 .bookmarks-toolbar-customize {
   display: none;
   max-width: 15em !important;
 }
 
 toolbarpaletteitem[place="toolbar"] .bookmarks-toolbar-customize {
   display: -moz-box;
 }
@@ -763,16 +772,31 @@ toolbar[iconsize="small"] #paste-button[
   -moz-padding-end: 2px;
 }
 
 #urlbar[pageproxystate="invalid"] > #urlbar-icons > :not(#go-button) ,
 #urlbar[pageproxystate="valid"] > #urlbar-icons > #go-button {
   visibility: collapse;
 }
 
+#urlbar-search-splitter {
+  -moz-appearance: none;
+  width: 8px;
+  -moz-margin-start: -4px;
+}
+
+/*XXX The first two selectors are there because adjacent selectors aren't
+      working reliably (bug 229915). */
+#search-container + #urlbar-container > #urlbar ,
+#urlbar-container + #search-container > #searchbar > .searchbar-textbox ,
+#urlbar-search-splitter + #urlbar-container > #urlbar ,
+#urlbar-search-splitter + #search-container > #searchbar > .searchbar-textbox {
+  -moz-margin-start: 0;
+}
+
 #wrapper-urlbar-container #urlbar {
   -moz-user-input: disabled;
   cursor: -moz-grab;
 }
 
 #wrapper-urlbar-container #urlbar > .autocomplete-history-dropmarker {
   display: none;
 }
--- a/browser/themes/gnomestripe/browser/places/editBookmarkOverlay.css
+++ b/browser/themes/gnomestripe/browser/places/editBookmarkOverlay.css
@@ -90,17 +90,17 @@
   -moz-border-top-colors: ThreeDShadow ThreeDDarkShadow;
   -moz-border-right-colors: ThreeDHighlight ThreeDLightShadow;
   -moz-border-bottom-colors: ThreeDHighlight ThreeDLightShadow;
   -moz-border-left-colors: ThreeDShadow ThreeDDarkShadow;
   background-color: -moz-Field;
   color: -moz-FieldText;
 }
 
-#editBMPanel_namePicker[droppable="false"] > .menulist-dropmarker {
+#editBMPanel_namePicker[droppable="false"] > .menulist-editable-box {
   /* Normal editable menulists set this to "menulist-textfield". */
   -moz-appearance: none;
   padding: 2px 2px 3px 4px;
 }
 
 
 /* Hide the drop marker and the popup. */
 #editBMPanel_namePicker[droppable="false"] > .menulist-dropmarker,
--- a/browser/themes/gnomestripe/browser/preferences/applications.css
+++ b/browser/themes/gnomestripe/browser/preferences/applications.css
@@ -59,18 +59,20 @@ richlistitem label {
 }
 
 richlistitem {
   min-height: 25px;
 }
 
 .actionsMenu .menulist-icon {
   -moz-margin-end: 1px;
+  height: 16px;
+  width: 16px;
 }
 
 .actionsMenu > menupopup > menuitem > .menu-iconic-left {
   -moz-padding-start: 0;
-  -moz-padding-end: 4px;
+  -moz-padding-end: 4px !important;
 }
 
 .actionsMenu > menupopup > menuitem {
   -moz-padding-start: 3px;
 }
--- a/browser/themes/pinstripe/browser/browser.css
+++ b/browser/themes/pinstripe/browser/browser.css
@@ -859,16 +859,31 @@ toolbar[iconsize="small"] #paste-button:
 #urlbar[level="high"][pageproxystate="valid"] > .autocomplete-history-dropmarker,
 #urlbar[level="low"][pageproxystate="valid"] > .autocomplete-history-dropmarker
  {
   margin: -2px;
   padding: 2px 6px;
   background: url("chrome://browser/skin/Secure-background.gif") #FFFED8 repeat-x;
 }
 
+#urlbar-search-splitter {
+  min-width: 8px;
+  -moz-margin-start: -4px;
+  background: transparent;
+}
+
+/*XXX The first two selectors are there because adjacent selectors aren't
+      working reliably (bug 229915). */
+#search-container + #urlbar-container > #urlbar ,
+#urlbar-container + #search-container > #searchbar > .searchbar-textbox ,
+#urlbar-search-splitter + #urlbar-container > #urlbar ,
+#urlbar-search-splitter + #search-container > #searchbar > .searchbar-textbox {
+  -moz-margin-start: 0;
+}
+
 #wrapper-urlbar-container #urlbar {
   -moz-user-input: disabled;
   cursor: -moz-grab;
 }
 
 #wrapper-urlbar-container #urlbar > .autocomplete-history-dropmarker {
   display: none;
 }
--- a/browser/themes/winstripe/browser/browser.css
+++ b/browser/themes/winstripe/browser/browser.css
@@ -849,16 +849,32 @@ toolbar[iconsize="small"] #paste-button:
   -moz-padding-end: 2px;
 }
 
 #urlbar[pageproxystate="invalid"] > #urlbar-icons > :not(#go-button) ,
 #urlbar[pageproxystate="valid"] > #urlbar-icons > #go-button {
   visibility: collapse;
 }
 
+#urlbar-search-splitter {
+  min-width: 8px;
+  -moz-margin-start: -4px;
+  border: none;
+  background: transparent;
+}
+
+/*XXX The first two selectors are there because adjacent selectors aren't
+      working reliably (bug 229915). */
+#search-container + #urlbar-container > #urlbar ,
+#urlbar-container + #search-container > #searchbar > .searchbar-textbox ,
+#urlbar-search-splitter + #urlbar-container > #urlbar ,
+#urlbar-search-splitter + #search-container > #searchbar > .searchbar-textbox {
+  -moz-margin-start: 0;
+}
+
 #wrapper-urlbar-container #urlbar {
   -moz-user-input: disabled;
   cursor: -moz-grab;
 }
 
 #wrapper-urlbar-container #urlbar > .autocomplete-history-dropmarker {
   display: none;
 }
@@ -1092,49 +1108,46 @@ toolbar[mode="text"] #navigator-throbber
 
 .tabs-container:not([overflow="true"]) {
   -moz-padding-start: 3px;
 }
 
 /* Tabs */
 .tabbrowser-tab {
   -moz-appearance: none;
-  height: 22px;
   background: url("chrome://browser/skin/tabbrowser/tab-bkgnd.png") repeat-x;
   margin: 3px 0px 4px;
-  padding: 0px 0px 1px;
+  padding: 0px 1px 1px 0px;
   border: 2px solid;
+  border-right-width: 1px;
   border-bottom: none;
   -moz-border-radius-topleft: 2px;
   -moz-border-radius-topright: 2px;
-  -moz-border-top-colors: #b5b3a8 #e8e6dc;
-  -moz-border-right-colors: #c1bfb3 #e8e6dc;
-  -moz-border-left-colors: #c1bfb3 #e8e6dc;
+  -moz-border-top-colors: ThreeDShadow rgba(255,255,255,.3);
+  -moz-border-right-colors: rgba(0,0,0,.1);
+  -moz-border-left-colors: ThreeDShadow rgba(255,255,255,.3);
 }
 
 .tabbrowser-tab:hover,
 .tabbrowser-tab[selected="true"] {
-  border: 1px solid;
-  border-bottom: none;
+  border-width: 1px;
   -moz-border-radius-topleft: 4px;
   -moz-border-radius-topright: 4px;
-  -moz-border-top-colors: #9a9890;
-  -moz-border-right-colors: #aaa89f;
-  -moz-border-left-colors: #aaa89f;
+  -moz-border-top-colors: ThreeDShadow;
+  -moz-border-right-colors: ThreeDShadow;
+  -moz-border-left-colors: ThreeDShadow;
 }
 
 .tabbrowser-tab:not([selected="true"]):hover {
-  height: 23px;
   margin: 2px 0px 4px;
   padding: 2px 1px 1px;
   background: url("chrome://browser/skin/tabbrowser/tab-active-bkgnd.png") repeat-x;
 }
 
 .tabbrowser-tab[selected="true"] {
-  height: 24px;
   margin: 2px 0px 3px;
   padding: 1px;
   background: -moz-dialog url("chrome://browser/skin/tabbrowser/tab-active-bkgnd.png") repeat-x;
   font-weight: bold;
 }
 
 .tabbrowser-tab[busy] > .tab-icon-image {
   list-style-image: url("chrome://global/skin/throbber/Throbber-small.gif") !important;
@@ -1220,214 +1233,121 @@ tabpanels {
      it's getting closed */
   -moz-user-focus: normal;
 }
 
 .tab-close-button:focus {
   outline: none !important;
 }
 
-/* Tab scrollbox arrow buttons */
+/* Tab scrollbox arrow and all-tabs buttons */
 .tabbrowser-arrowscrollbox > .scrollbutton-up,
-.tabbrowser-arrowscrollbox > .scrollbutton-down {
+.tabbrowser-arrowscrollbox > .scrollbutton-down,
+.tabs-alltabs-button {
   -moz-appearance: none;
   width: 18px;
   margin: 3px 0px 4px;
   padding: 0px;
   border: 2px solid;
+  border-right-width: 1px;
   border-bottom: none;
-  -moz-border-top-colors: #b5b3a8 #e8e6dc;
-  -moz-border-right-colors: #c1bfb3 #e8e6dc;
-  -moz-border-left-colors: #c1bfb3 #e8e6dc;
+  -moz-border-top-colors: ThreeDShadow rgba(255,255,255,.3);
+  -moz-border-right-colors: ThreeDShadow;
+  -moz-border-left-colors: ThreeDShadow rgba(255,255,255,.3);
   background: url("chrome://browser/skin/tabbrowser/tab-bkgnd.png");
   background-repeat: repeat-x;
+  -moz-image-region: rect(0, 11px, 14px, 0);
+}
+
+.tabbrowser-arrowscrollbox > .scrollbutton-up:not([disabled="true"]):hover,
+.tabbrowser-arrowscrollbox > .scrollbutton-down:not([disabled="true"]):hover,
+.tabs-alltabs-button:hover {
+  border-top-width: 1px;
+  padding-top: 1px;
+  -moz-border-top-colors: ThreeDShadow;
+  -moz-border-right-colors: ThreeDShadow;
+  -moz-border-left-colors: ThreeDShadow transparent;
+  background: url("chrome://browser/skin/tabbrowser/tab-active-bkgnd.png");
+  background-repeat: repeat-x;
 }
 
 .tabbrowser-arrowscrollbox > .scrollbutton-up:not([disabled="true"]):hover,
 .tabbrowser-arrowscrollbox > .scrollbutton-down:not([disabled="true"]):hover {
-  border: 1px solid;
-  border-bottom: none;
-  -moz-border-top-colors: #9a9890;
-  -moz-border-right-colors: #aaa89f;
-  -moz-border-left-colors: #aaa89f;
-  background: url("chrome://browser/skin/tabbrowser/tab-active-bkgnd.png");
-  background-repeat: repeat-x;
+  -moz-image-region: rect(0, 22px, 14px, 11px);
+}
+
+.tabbrowser-arrowscrollbox > .scrollbutton-up[disabled="true"],
+.tabbrowser-arrowscrollbox > .scrollbutton-down[disabled="true"] {
+  opacity: .4;
+}
+
+.tabbrowser-arrowscrollbox > .scrollbutton-up:not([disabled="true"]):hover:active,
+.tabbrowser-arrowscrollbox > .scrollbutton-down:not([disabled="true"]):hover:active {
+  -moz-image-region: rect(0, 44px, 14px, 33px);
 }
 
 .tabbrowser-arrowscrollbox > .scrollbutton-up {
-  border-left: none;
+  border-left-style: none;
   list-style-image: url("chrome://browser/skin/tabbrowser/tab-arrow-start.png");
-  -moz-image-region: rect(0, 11px, 14px, 0);
   -moz-border-radius-topright: 2px;
 }
 
 .tabbrowser-arrowscrollbox > .scrollbutton-up[chromedir="rtl"] {
-  border-left: 2px solid;
-  border-right: none;
-  list-style-image: url("chrome://browser/skin/tabbrowser/tab-arrow-end.png");
+  border-left-style: solid;
+  border-right-style: none;
   -moz-border-radius-topleft: 2px;
   -moz-border-radius-topright: 0px;
-}
-
-.tabbrowser-arrowscrollbox > .scrollbutton-up[disabled="true"] {
-  -moz-border-radius-topright: 4px;
-  -moz-image-region: rect(0, 33px, 14px, 22px);
-}
-
-.tabbrowser-arrowscrollbox > .scrollbutton-up[chromedir="rtl"][disabled="true"] {
-  -moz-border-radius-topright: 0px;
-  -moz-border-radius-topleft: 4px;
-}
-
-.tabbrowser-arrowscrollbox > .scrollbutton-up:not([disabled="true"]):hover {
-  -moz-border-radius-topright: 4px;
-  -moz-border-radius-topleft: 0px;
-  border-left: none;
-  -moz-image-region: rect(0, 22px, 14px, 11px);
-}
-
-.tabbrowser-arrowscrollbox > .scrollbutton-up[chromedir="rtl"]:not([disabled="true"]):hover {
-  -moz-border-radius-topright: 0px;
-  -moz-border-radius-topleft: 4px;
-  border-left: 1px solid;
-  border-right: none;
-}
-
-.tabbrowser-arrowscrollbox > .scrollbutton-up:not([disabled="true"]):hover:active {
-  -moz-image-region: rect(0, 44px, 14px, 33px);
+  list-style-image: url("chrome://browser/skin/tabbrowser/tab-arrow-end.png");
 }
 
 .tabbrowser-arrowscrollbox > .scrollbutton-up > .toolbarbutton-icon {    
   margin: 6px 0px 0px 0px;
-}                                                                            
+}
+
+.tabbrowser-arrowscrollbox > .scrollbutton-down,
+.tabs-alltabs-button {
+  border-right-style: none;
+  -moz-border-radius-topleft: 2px;
+}
 
 .tabbrowser-arrowscrollbox > .scrollbutton-down {
-  border-right: none;
-  -moz-border-radius-topleft: 2px;
-  -moz-border-radius-topright: 0px;
   list-style-image: url("chrome://browser/skin/tabbrowser/tab-arrow-end.png");
-  -moz-image-region: rect(0, 11px, 14px, 0);
+}
+
+.tabbrowser-arrowscrollbox > .scrollbutton-down[chromedir="rtl"],
+.tabs-container > stack[chromedir="rtl"] > .tabs-alltabs-button {
+  border-left-style: none;
+  border-right-style: solid;
+  -moz-border-radius-topleft: 0px;
+  -moz-border-radius-topright: 2px;
 }
 
 .tabbrowser-arrowscrollbox > .scrollbutton-down[chromedir="rtl"] {
-  border-left: none;
-  border-right: 2px solid;
-  -moz-border-radius-topleft: 0px;
-  -moz-border-radius-topright: 2px;
   list-style-image: url("chrome://browser/skin/tabbrowser/tab-arrow-start.png");
 }
 
-.tabbrowser-arrowscrollbox > .scrollbutton-down[disabled="true"] {
-  -moz-border-radius-topleft: 4px;
-  -moz-border-radius-topright: 0px;
-  -moz-image-region: rect(0, 33px, 14px, 22px);
-}
-
-.tabbrowser-arrowscrollbox > .scrollbutton-down[chromedir="rtl"][disabled="true"] {
-  -moz-border-radius-topleft: 0px;
-  -moz-border-radius-topright: 4px;
-}
-
-.tabbrowser-arrowscrollbox > .scrollbutton-down:not([disabled="true"]):hover {
-  -moz-padding-start: 1px;
-  -moz-border-radius-topleft: 4px;
-  -moz-border-radius-topright: 0px;
-  border-right: none;
-  -moz-image-region: rect(0, 22px, 14px, 11px);
-}
-
-.tabbrowser-arrowscrollbox > .scrollbutton-down[chromedir="rtl"]:not([disabled="true"]):hover {
-  border-left: none;
-  border-right: 1px solid;
-  -moz-border-radius-topleft: 0px;
-  -moz-border-radius-topright: 4px;
-}
-
-.tabbrowser-arrowscrollbox > .scrollbutton-down:not([disabled="true"]):hover:active {
-  -moz-image-region: rect(0, 44px, 14px, 33px);
-}
-
 .tabbrowser-arrowscrollbox > .scrollbutton-down > .toolbarbutton-icon {
   margin-top: 6px;
-}
-
-/* All tabs button */
-.tabs-alltabs-box {
-  margin-top: 2px;
-  margin-bottom: 4px;
-  width: 18px !important;
-  height: 23px !important;
-  background-image: url("chrome://browser/skin/tabbrowser/tab-arrow-end-bkgnd-enabled.png");
-  background-repeat: no-repeat;
-  -moz-border-radius-topleft: 4px;
-}
-
-stack[chromedir="rtl"] > hbox > .tabs-alltabs-box {
-  background-image: url("chrome://browser/skin/tabbrowser/tab-arrow-start-bkgnd-enabled.png");
-  -moz-border-radius-topleft: 0px;
-  -moz-border-radius-topright: 4px;
+  -moz-margin-end: 2px;
 }
 
-.tabbrowser-tabs[overflow="true"] .tabs-alltabs-box {
-  background-image: url("chrome://browser/skin/tabbrowser/alltabs-box-overflow-end-bkgnd.png");
-  -moz-border-radius-topleft: 0px;
-  -moz-border-radius-topright: 0px;
-}
-
-.tabbrowser-tabs[overflow="true"] stack[chromedir="rtl"] > hbox > .tabs-alltabs-box {
-  background-image: url("chrome://browser/skin/tabbrowser/alltabs-box-overflow-start-bkgnd.png");
-}
-
-.tabs-alltabs-button {
-  -moz-appearance: none !important;
-  border: 0px !important;
-  margin-top: 2px;
-  margin-bottom: 4px;
-  width: 18px !important;
-  height: 23px !important;
-  border: 0px !important;
-  -moz-padding-start: 4px !important;
-  -moz-padding-end: 4px !important;
-  padding: 0px;
-}
-
-.tabs-alltabs-button > .toolbarbutton-text {
+.tabs-alltabs-button > .toolbarbutton-text,
+.tabs-alltabs-button > .toolbarbutton-icon {
   display: none;
 }
 
-.tabs-alltabs-button > .toolbarbutton-icon {
-  -moz-margin-end: 2px;
-}
-
 .tabs-alltabs-button > .toolbarbutton-menu-dropmarker {
-  margin-top: 3px !important;
-}
-
-.tabs-alltabs-button:hover {
-  background-image: url("chrome://browser/skin/tabbrowser/tab-arrow-end-bkgnd-hover.png");
-  background-repeat: no-repeat;
-}
-
-stack[chromedir="rtl"] > hbox > .tabs-alltabs-button:hover {
-  background-image: url("chrome://browser/skin/tabbrowser/tab-arrow-start-bkgnd-hover.png");
-}
-
-.tabbrowser-tabs[overflow="true"] .tabs-alltabs-button:hover {
-  background-image: url("chrome://browser/skin/tabbrowser/alltabs-box-overflow-end-bkgnd-hover.png");
-}
-
-.tabbrowser-tabs[overflow="true"] stack[chromedir="rtl"] > hbox > .tabs-alltabs-button:hover {
-  background-image: url("chrome://browser/skin/tabbrowser/alltabs-box-overflow-start-bkgnd-hover.png");
+  margin-top: 3px;
+  margin-bottom: 1px;
 }
 
 .tabs-alltabs-box-animate {
   margin-top: 2px;
   margin-bottom: 4px;
   width: 18px !important;
-  height: 23px !important;
   background-image: url("chrome://browser/skin/tabbrowser/alltabs-box-overflow-end-bkgnd-animate.png");
   background-repeat: no-repeat;
   opacity: 0.0;
 }
 
 stack[chromedir="rtl"] > hbox > .tabs-alltabs-box-animate {
   background-image: url("chrome://browser/skin/tabbrowser/alltabs-box-overflow-start-bkgnd-animate.png");
 }
@@ -1473,21 +1393,24 @@ stack[chromedir="rtl"] > hbox > .tabs-al
 
 .tabs-container > .tabs-closebutton {
   margin: 3px 0px 3px;
   padding: 4px 2px 2px;
   background: -moz-dialog url("chrome://browser/skin/tabbrowser/tab-active-bkgnd.png");
   background-repeat: repeat-x;
   border-left: 1px solid threedshadow;
   border-top: 1px solid threedshadow;
+  -moz-border-radius-topleft: 2px;
 }
 
 .tabs-container > .tabs-closebutton[chromedir="rtl"] {
   border-left: none;
   border-right: 1px solid threedshadow;
+  -moz-border-radius-topleft: 0px;
+  -moz-border-radius-topright: 2px;
 }
 
 #sidebar-box .tabs-closebutton {
   margin-bottom: 0px !important;
   padding: 0px 2px 0px 2px !important;
 }
 
 toolbarbutton.chevron {
--- a/browser/themes/winstripe/browser/jar.mn
+++ b/browser/themes/winstripe/browser/jar.mn
@@ -54,22 +54,18 @@ classic.jar:
         skin/classic/browser/safebrowsing/warning16x16.png            (safebrowsing/warning16x16.png)
         skin/classic/browser/safebrowsing/warning24x24.png            (safebrowsing/warning24x24.png)
 #endif
         skin/classic/browser/preferences/application.png        (preferences/application.png)
         skin/classic/browser/preferences/Options.png            (preferences/Options.png)
         skin/classic/browser/preferences/plugin.png             (preferences/plugin.png)
         skin/classic/browser/preferences/preferences.css        (preferences/preferences.css)
         skin/classic/browser/preferences/applications.css       (preferences/applications.css)
-        skin/classic/browser/tabbrowser/alltabs-box-overflow-end-bkgnd.png           (tabbrowser/alltabs-box-overflow-end-bkgnd.png)
         skin/classic/browser/tabbrowser/alltabs-box-overflow-end-bkgnd-animate.png   (tabbrowser/alltabs-box-overflow-end-bkgnd-animate.png)
-        skin/classic/browser/tabbrowser/alltabs-box-overflow-end-bkgnd-hover.png     (tabbrowser/alltabs-box-overflow-end-bkgnd-hover.png)
-        skin/classic/browser/tabbrowser/alltabs-box-overflow-start-bkgnd.png         (tabbrowser/alltabs-box-overflow-start-bkgnd.png)
-        skin/classic/browser/tabbrowser/alltabs-box-overflow-start-bkgnd-animate.png (tabbrowser/alltabs-box-overflow-start-bkgnd-animate.png)        
-        skin/classic/browser/tabbrowser/alltabs-box-overflow-start-bkgnd-hover.png   (tabbrowser/alltabs-box-overflow-start-bkgnd-hover.png)
+        skin/classic/browser/tabbrowser/alltabs-box-overflow-start-bkgnd-animate.png (tabbrowser/alltabs-box-overflow-start-bkgnd-animate.png)
         skin/classic/browser/tabbrowser/tab-arrow-end.png                  (tabbrowser/tab-arrow-end.png)
         skin/classic/browser/tabbrowser/tab-arrow-start.png                (tabbrowser/tab-arrow-start.png)
         skin/classic/browser/tabbrowser/tabbrowser-tabs-bkgnd.png          (tabbrowser/tabbrowser-tabs-bkgnd.png)
         skin/classic/browser/tabbrowser/tabDragIndicator.png               (tabbrowser/tabDragIndicator.png)
         skin/classic/browser/tabbrowser/tab-bkgnd.png                      (tabbrowser/tab-bkgnd.png)
         skin/classic/browser/tabbrowser/tab-active-bkgnd.png               (tabbrowser/tab-active-bkgnd.png)
         skin/classic/browser/tabbrowser/tabstrip-bottom.png                (tabbrowser/tabstrip-bottom.png)
         icon.png
--- a/browser/themes/winstripe/browser/places/editBookmarkOverlay.css
+++ b/browser/themes/winstripe/browser/places/editBookmarkOverlay.css
@@ -90,17 +90,17 @@
   -moz-border-top-colors: ThreeDShadow ThreeDDarkShadow;
   -moz-border-right-colors: ThreeDHighlight ThreeDLightShadow;
   -moz-border-bottom-colors: ThreeDHighlight ThreeDLightShadow;
   -moz-border-left-colors: ThreeDShadow ThreeDDarkShadow;
   background-color: -moz-Field;
   color: -moz-FieldText;
 }
 
-#editBMPanel_namePicker[droppable="false"] > .menulist-dropmarker {
+#editBMPanel_namePicker[droppable="false"] > .menulist-editable-box {
   /* Normal editable menulists set this to "menulist-textfield". */
   -moz-appearance: none;
   padding: 2px 2px 3px 4px;
 }
 
 
 /* Hide the drop marker and the popup. */
 
index 3db331b6cf7678dcdf0723a10a5e5fb2dc713397..56dbb5a3ac384d3b8cb630397a288355f5e9993f
GIT binary patch
literal 456
zc$@*q0XP1MP)<h;3K|Lk000e1NJLTq000sI002t}1^@s6eNWeD00007bV*G`2iO4y
z0X7dZ)1+Mh000SaNLh0L03N{r03N{s!)a7g00004XF*Lt006O%3;baP00043Nkl<Z
zc-rliO-=(b425kcT!al*;sWI+921Ex%kD;0Oz>ZlS;k?BBeiKq%Gc-j>=fT_w`cHm
z90%;KDsS(vFCYB@5$%Hz5$<1~V4we>s8j-EA?MlP=VVm^L)q7<mH1R^4H|!GXb@2-
z6(R&cT8qHY4hk3%{BZyzzm6tDcl5GQX#tN4nLnsuHC1Oqn!%PqrI;de1^SxGLZykZ
z+CIbV$qj+DoMOimylu7|a&Jcb7;8=j74Aqjy!vQd6ALw@#?EJoomFKp6)uD7Q`OXD
zSn*O8Mf*rbLll*YqZ$F1cxmKjyG7VxL9@xDpYgld1i{X(btvdp$7qLjLF^IVL29;{
zV*Nuq*9gFzF<E1P=e`8OKBVrpmPE6}We_*g<r<l3g;RSxzDH7X=G>zQsC%R%GGd20
ybBk;5Pb@(RN>G9ll%ND9C_xEIP=XTl|3JUQUmtIB_vxho0000<MNUMnLSTYhX1SFB
--- a/build/Makefile.in
+++ b/build/Makefile.in
@@ -51,17 +51,19 @@ DIRS		= unix
 endif
 
 ifeq (WINNT,$(OS_ARCH))
 DIRS = win32
 endif
 
 include $(topsrcdir)/config/rules.mk
 
+ifdef ENABLE_TESTS
 # Install bloaturls.txt file for tinderbox bloat test.
 libs:: bloaturls.txt
 	$(INSTALL) $< $(DIST)/bin
 
 # Install bloatcycle.html into dist/bin/res, for auto-cycling
 # of bloaturls.txt.  This is for browsers that can't do -f
 # autocycling of URLs.
 libs:: bloatcycle.html
 	$(INSTALL) $< $(DIST)/bin/res
+endif
--- a/caps/include/nsScriptSecurityManager.h
+++ b/caps/include/nsScriptSecurityManager.h
@@ -421,17 +421,17 @@ private:
     doGetSubjectPrincipal(nsresult* rv);
     
     static nsresult 
     ReportError(JSContext* cx, const nsAString& messageTag,
                 nsIURI* aSource, nsIURI* aTarget);
 
     nsresult
     CheckPropertyAccessImpl(PRUint32 aAction,
-                            nsIXPCNativeCallContext* aCallContext,
+                            nsAXPCNativeCallContext* aCallContext,
                             JSContext* cx, JSObject* aJSObject,
                             nsISupports* aObj, nsIURI* aTargetURI,
                             nsIClassInfo* aClassInfo,
                             const char* aClassName, jsval aProperty,
                             void** aCachedClassPolicy);
 
     nsresult
     CheckSameOriginPrincipalInternal(nsIPrincipal* aSubject,
--- a/caps/src/nsNullPrincipal.cpp
+++ b/caps/src/nsNullPrincipal.cpp
@@ -41,17 +41,16 @@
  * anything other than itself and chrome; null principals are not
  * same-origin with anything but themselves.
  */
 
 #include "nsNullPrincipal.h"
 #include "nsMemory.h"
 #include "nsIUUIDGenerator.h"
 #include "nsID.h"
-#include "prmem.h" // For PF_Free, 'cause nsID::ToString sucks like that
 #include "nsNetUtil.h"
 #include "nsIClassInfoImpl.h"
 #include "nsNetCID.h"
 
 static NS_DEFINE_CID(kSimpleURICID, NS_SIMPLEURI_CID);
 
 NS_IMPL_QUERY_INTERFACE2_CI(nsNullPrincipal,
                             nsIPrincipal,
@@ -100,31 +99,29 @@ nsNullPrincipal::Init()
   nsCOMPtr<nsIUUIDGenerator> uuidgen =
     do_GetService("@mozilla.org/uuid-generator;1", &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsID id;
   rv = uuidgen->GenerateUUIDInPlace(&id);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  char* chars = id.ToString();
-  NS_ENSURE_TRUE(chars, NS_ERROR_OUT_OF_MEMORY);
+  char chars[NSID_LENGTH];
+  id.ToProvidedString(chars);
 
-  PRUint32 suffixLen = strlen(chars);
+  PRUint32 suffixLen = NSID_LENGTH - 1;
   PRUint32 prefixLen = NS_ARRAY_LENGTH(NS_NULLPRINCIPAL_PREFIX) - 1;
 
   // Use an nsCString so we only do the allocation once here and then share
   // with nsJSPrincipals
   nsCString str;
   str.SetCapacity(prefixLen + suffixLen);
 
   str.Append(NS_NULLPRINCIPAL_PREFIX);
   str.Append(chars);
-
-  PR_Free(chars);
   
   if (str.Length() != prefixLen + suffixLen) {
     NS_WARNING("Out of memory allocating null-principal URI");
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   // Use CID so we're sure we get the impl we want.  Note that creating the URI
   // directly is ok because we have our own private URI scheme.  In effect,
--- a/caps/src/nsScriptSecurityManager.cpp
+++ b/caps/src/nsScriptSecurityManager.cpp
@@ -721,17 +721,17 @@ nsScriptSecurityManager::CheckSameOrigin
     return CheckSameOriginPrincipalInternal(aSourcePrincipal,
                                             aTargetPrincipal,
                                             PR_FALSE);
 }
 
 
 nsresult
 nsScriptSecurityManager::CheckPropertyAccessImpl(PRUint32 aAction,
-                                                 nsIXPCNativeCallContext* aCallContext,
+                                                 nsAXPCNativeCallContext* aCallContext,
                                                  JSContext* cx, JSObject* aJSObject,
                                                  nsISupports* aObj, nsIURI* aTargetURI,
                                                  nsIClassInfo* aClassInfo,
                                                  const char* aClassName, jsval aProperty,
                                                  void** aCachedClassPolicy)
 {
     nsresult rv;
     nsIPrincipal* subjectPrincipal = GetSubjectPrincipal(cx, &rv);
@@ -790,28 +790,31 @@ nsScriptSecurityManager::CheckPropertyAc
             rv = NS_OK;
             break;
 
         case SCRIPT_SECURITY_SAME_ORIGIN_ACCESS:
             {
 #ifdef DEBUG_CAPS_CheckPropertyAccessImpl
                 printf("sameOrigin ");
 #endif
-                nsCOMPtr<nsIPrincipal> objectPrincipal;
+                nsCOMPtr<nsIPrincipal> principalHolder;
+                nsIPrincipal *objectPrincipal;
                 if(aJSObject)
                 {
                     objectPrincipal = doGetObjectPrincipal(cx, aJSObject);
                     if (!objectPrincipal)
                         rv = NS_ERROR_DOM_SECURITY_ERR;
                 }
                 else if(aTargetURI)
                 {
                     if (NS_FAILED(GetCodebasePrincipal(
-                          aTargetURI, getter_AddRefs(objectPrincipal))))
+                          aTargetURI, getter_AddRefs(principalHolder))))
                         return NS_ERROR_FAILURE;
+
+                    objectPrincipal = principalHolder;
                 }
                 else
                 {
                     NS_ERROR("CheckPropertyAccessImpl called without a target object or URL");
                     return NS_ERROR_FAILURE;
                 }
                 if(NS_SUCCEEDED(rv))
                     rv = CheckSameOriginDOMProp(subjectPrincipal, objectPrincipal,
@@ -837,17 +840,17 @@ nsScriptSecurityManager::CheckPropertyAc
             rv = NS_ERROR_DOM_SECURITY_ERR;
         else
             rv = NS_OK;
     }
 
     if (NS_SUCCEEDED(rv) && classInfoData.IsContentNode())
     {
         // No access to anonymous content from the web!  (bug 164086)
-        nsCOMPtr<nsIContent> content(do_QueryInterface(aObj));
+        nsIContent *content = static_cast<nsIContent*>(aObj);
         NS_ASSERTION(content, "classinfo had CONTENT_NODE set but node did not"
                               "implement nsIContent!  Fasten your seat belt.");
         if (content->IsNativeAnonymous()) {
             rv = NS_ERROR_DOM_SECURITY_ERR;
         }
     }
 
     if (NS_SUCCEEDED(rv))
@@ -934,18 +937,18 @@ nsScriptSecurityManager::CheckPropertyAc
                                                         NS_ARRAY_LENGTH(formatStrings),
                                                         getter_Copies(errorMsg));
         NS_ENSURE_SUCCESS(rv2, rv2);
 
         SetPendingException(cx, errorMsg.get());
 
         if (sXPConnect)
         {
-            nsCOMPtr<nsIXPCNativeCallContext> xpcCallContext;
-            sXPConnect->GetCurrentNativeCallContext(getter_AddRefs(xpcCallContext));
+            nsAXPCNativeCallContext *xpcCallContext = nsnull;
+            sXPConnect->GetCurrentNativeCallContext(&xpcCallContext);
             if (xpcCallContext)
                 xpcCallContext->SetExceptionWasThrown(PR_TRUE);
         }
     }
 
     return rv;
 }
 
@@ -1540,18 +1543,18 @@ nsScriptSecurityManager::ReportError(JSC
     // Otherwise, print the error message directly to the JS console
     // and to standard output
     if (cx)
     {
         SetPendingException(cx, message.get());
         // Tell XPConnect that an exception was thrown, if appropriate
         if (sXPConnect)
         {
-            nsCOMPtr<nsIXPCNativeCallContext> xpcCallContext;
-            sXPConnect->GetCurrentNativeCallContext(getter_AddRefs(xpcCallContext));
+            nsAXPCNativeCallContext* xpcCallContext = nsnull;
+            sXPConnect->GetCurrentNativeCallContext(&xpcCallContext);
              if (xpcCallContext)
                 xpcCallContext->SetExceptionWasThrown(PR_TRUE);
         }
     }
     else // Print directly to the console
     {
         nsCOMPtr<nsIConsoleService> console(
             do_GetService("@mozilla.org/consoleservice;1"));
@@ -3067,18 +3070,18 @@ nsScriptSecurityManager::CanCreateInstan
     {
         rv = CheckComponentPermissions(cx, aCID);
     }
     if (NS_FAILED(rv))
 #endif
     {
         //-- Access denied, report an error
         nsCAutoString errorMsg("Permission denied to create instance of class. CID=");
-        nsXPIDLCString cidStr;
-        cidStr += aCID.ToString();
+        char cidStr[NSID_LENGTH];
+        aCID.ToProvidedString(cidStr);
         errorMsg.Append(cidStr);
         SetPendingException(cx, errorMsg.get());
 
 #ifdef DEBUG_CAPS_CanCreateInstance
         printf("DENIED\n");
     }
     else
     {
@@ -3098,18 +3101,18 @@ nsScriptSecurityManager::CanGetService(J
     nsCRT::free(cidStr);
 #endif
 
     nsresult rv = CheckXPCPermissions(nsnull, nsnull);
     if (NS_FAILED(rv))
     {
         //-- Access denied, report an error
         nsCAutoString errorMsg("Permission denied to get service. CID=");
-        nsXPIDLCString cidStr;
-        cidStr += aCID.ToString();
+        char cidStr[NSID_LENGTH];
+        aCID.ToProvidedString(cidStr);
         errorMsg.Append(cidStr);
         SetPendingException(cx, errorMsg.get());
 
 #ifdef DEBUG_CAPS_CanGetService
         printf("DENIED\n");
     }
     else
     {
@@ -3118,17 +3121,17 @@ nsScriptSecurityManager::CanGetService(J
     }
 
     return rv;
 }
 
 
 NS_IMETHODIMP
 nsScriptSecurityManager::CanAccess(PRUint32 aAction,
-                                   nsIXPCNativeCallContext* aCallContext,
+                                   nsAXPCNativeCallContext* aCallContext,
                                    JSContext* cx,
                                    JSObject* aJSObject,
                                    nsISupports* aObj,
                                    nsIClassInfo* aClassInfo,
                                    jsval aPropertyName,
                                    void** aPolicy)
 {
     return CheckPropertyAccessImpl(aAction, aCallContext, cx,
--- a/client.py
+++ b/client.py
@@ -1,11 +1,11 @@
 #!/usr/bin/python
 
-NSPR_CO_TAG = 'NSPR_HEAD_20071218'
+NSPR_CO_TAG = 'NSPR_HEAD_20080113'
 NSS_CO_TAG  = 'NSS_3_12_ALPHA_2B'
 
 NSPR_DIRS = ('nsprpub',)
 NSS_DIRS  = ('dbm',
              'security/nss',
              'security/coreconf',
              'security/dbm')
 
--- a/config/Makefile.in
+++ b/config/Makefile.in
@@ -100,16 +100,25 @@ HEADERS = \
 export:: $(TARGETS) $(HEADERS)
 	$(INSTALL) $(IFLAGS1) $(HEADERS) $(DIST)/include
 	-rm -f $(FINAL_LINK_COMPS) $(FINAL_LINK_LIBS) $(FINAL_LINK_COMP_NAMES)
 	-rm -f $(DIST)/bin/chrome/chromelist.txt
 ifdef HOST_PROGRAM
 	$(INSTALL) $(HOST_PROGRAM) $(DIST)/bin
 endif
 
+# Generate a new buildid every time we "export" in config... that's only
+# supposed to be once per-build!
+export::
+ifdef MOZ_BUILD_DATE
+	printf "%s" $(MOZ_BUILD_DATE) > buildid
+else
+	$(PYTHON) $(topsrcdir)/toolkit/xre/make-platformini.py --print-buildid > buildid
+endif
+
 ifdef WRAP_SYSTEM_INCLUDES
 export::
 	if test ! -d system_wrappers; then mkdir system_wrappers; fi
 	$(PERL) $(topsrcdir)/config/preprocessor.pl $(DEFINES) $(ACDEFINES) \
 		-DBUILD_STATIC_LIBS=$(BUILD_STATIC_LIBS) \
 		-DMOZ_TREE_CAIRO=$(MOZ_TREE_CAIRO) \
 		-DMOZ_ENABLE_LIBXUL=$(MOZ_ENABLE_LIBXUL) \
 		-DMOZ_NATIVE_ZLIB=$(MOZ_NATIVE_ZLIB) \
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -96,16 +96,17 @@ MOZ_DEBUG_LDFLAGS=@MOZ_DEBUG_LDFLAGS@
 MOZ_DBGRINFO_MODULES	= @MOZ_DBGRINFO_MODULES@
 MOZ_EXTENSIONS  = @MOZ_EXTENSIONS@
 MOZ_IMG_DECODERS= @MOZ_IMG_DECODERS@
 MOZ_IMG_ENCODERS= @MOZ_IMG_ENCODERS@
 MOZ_JSDEBUGGER  = @MOZ_JSDEBUGGER@
 MOZ_PERF_METRICS = @MOZ_PERF_METRICS@
 MOZ_LEAKY	= @MOZ_LEAKY@
 MOZ_JPROF       = @MOZ_JPROF@
+MOZ_SHARK       = @MOZ_SHARK@
 MOZ_XPCTOOLS    = @MOZ_XPCTOOLS@
 ENABLE_EAZEL_PROFILER=@ENABLE_EAZEL_PROFILER@
 EAZEL_PROFILER_CFLAGS=@EAZEL_PROFILER_CFLAGS@
 EAZEL_PROFILER_LIBS=@EAZEL_PROFILER_LIBS@
 GC_LEAK_DETECTOR = @GC_LEAK_DETECTOR@
 NS_TRACE_MALLOC = @NS_TRACE_MALLOC@
 USE_ELF_DYNSTR_GC = @USE_ELF_DYNSTR_GC@
 USE_PREBINDING = @USE_PREBINDING@
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -1082,16 +1082,29 @@ ifdef IS_COMPONENT
 	  cp $(VMS_SYMVEC_FILE_COMP) $(VMS_SYMVEC_FILE); \
 	fi
 endif
 endif
 ifdef NO_LD_ARCHIVE_FLAGS
 ifdef SHARED_LIBRARY_LIBS
 	@rm -f $(SUB_SHLOBJS)
 	@for lib in $(SHARED_LIBRARY_LIBS); do $(AR_EXTRACT) $${lib}; $(CLEANUP2); done
+ifeq ($(OS_ARCH),Darwin)
+	@echo Making symlinks to the original object files in the archive libraries $(SHARED_LIBRARY_LIBS)
+	@for lib in $(SHARED_LIBRARY_LIBS); do \
+		libdir=`echo $$lib|sed -e 's,/[^/]*\.a,,'`; \
+		ofiles=`$(AR_LIST) $${lib}`; \
+		for ofile in $$ofiles; do \
+			if [ -f $$libdir/$$ofile ]; then \
+				rm -f $$ofile; \
+				ln -s $$libdir/$$ofile $$ofile; \
+			fi; \
+		done; \
+	done
+endif
 endif # SHARED_LIBRARY_LIBS
 endif # NO_LD_ARCHIVE_FLAGS
 ifdef DTRACE_LIB_DEPENDENT
 	@rm -f $(PROBE_LOBJS)
 	@for lib in $(MOZILLA_PROBE_LIBS); do $(AR_EXTRACT) $${lib}; $(CLEANUP2); done
 ifndef XP_MACOSX
 	dtrace -G -C -32 -s $(MOZILLA_DTRACE_SRC) -o  $(DTRACE_PROBE_OBJ) $(PROBE_LOBJS)
 endif
@@ -1117,27 +1130,16 @@ ifdef EMBED_MANIFEST_AT
 	@if test -f $@.manifest; then \
 		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;$(EMBED_MANIFEST_AT); \
 		rm -f $@.manifest; \
 	fi
 endif   # EMBED_MANIFEST_AT
 endif	# MSVC with manifest tool
 endif	# WINNT && !GCC
 ifeq ($(OS_ARCH),Darwin)
-	@for lib in $(SHARED_LIBRARY_LIBS); do \
-		libdir=`echo $$lib|sed -e 's,/[^/]*\.a,,'`; \
-		ofiles=`$(AR_LIST) $${lib}`; \
-		for ofile in $$ofiles; do \
-			if [ -f $$libdir/$$ofile ]; then \
-				rm -f $$ofile; \
-				ln -s $$libdir/$$ofile $$ofile; \
-			fi; \
-		done; \
-	done
-	@touch $(SHARED_LIBRARY)
 else # non-Darwin
 	@rm -f $(SUB_SHLOBJS)
 endif # Darwin
 	@rm -f foodummyfilefoo $(DELETE_AFTER_LINK)
 else # os2 vacpp
 	$(MKSHLIB) -O:$@ -DLL -INC:_dllentry $(LDFLAGS) $(OBJS) $(LOBJS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE)
 endif # !os2 vacpp
 	chmod +x $@
--- a/config/system-headers
+++ b/config/system-headers
@@ -613,17 +613,16 @@ shlobj.h
 sigcontext.h
 signal.h
 SimpleGameSound.h
 SIOUX.h
 size_t.h
 someincludefile.h
 Sound.h
 sqlite3.h
-sqlite3file.h
 ssdef.h
 sslerr.h
 ssl.h
 sslproto.h
 sstream
 stack
 StandardFile.h
 starlet.h
--- a/config/version.mk
+++ b/config/version.mk
@@ -31,18 +31,16 @@
 # the provisions above, a recipient may use your version of this file under
 # the terms of any one of the MPL, the GPL or the LGPL.
 #
 # ***** END LICENSE BLOCK *****
 
 ifndef INCLUDED_VERSION_MK
 INCLUDED_VERSION_MK=1
 
-
-
 # Windows gmake build:
 # Build default .rc file if $(RESFILE) isn't defined.
 # TODO:
 # PBI      : Private build info.  Not used currently.
 #            Guessing the best way would be to set an env var.
 # BINARY   : Binary name.  Not used currently.
 ifeq ($(MOZ_WIDGET_TOOLKIT),windows)
 ifndef RESFILE
@@ -73,23 +71,15 @@ ifdef RCINCLUDE
 _RC_STRING += -RCINCLUDE $(srcdir)/$(RCINCLUDE)
 endif
 
 GARBAGE += $(RESFILE) $(RCFILE)
 
 #dummy target so $(RCFILE) doesn't become the default =P
 all::
 
-$(RCFILE): $(RCINCLUDE)
+$(RCFILE): $(RCINCLUDE) $(topsrcdir)/config/version_win.pl
 	$(PERL) $(topsrcdir)/config/version_win.pl $(_RC_STRING)
 
 endif  # RESFILE
 endif  # Windows
 
-
-ifdef VERSION_TMPL
-GARBAGE += $(VERSION_TMPL)
-
-export::
-	$(PERL) $(topsrcdir)/config/milestone.pl --topsrcdir $(topsrcdir) --objdir . --srcdir $(srcdir) --template $(VERSION_TMPL)
 endif
-
-endif
--- a/config/version_win.pl
+++ b/config/version_win.pl
@@ -38,24 +38,37 @@
 #use diagnostics;
 require strict;
 my $dir = $0;
 $dir =~ s/[^\/]*$//;
 push(@INC, "$dir");
 require "Moz/Milestone.pm";
 use Getopt::Long;
 use Getopt::Std;
+use POSIX;
+
+# Calculate the number of days since Jan. 1, 2000 from a buildid string
+sub daysFromBuildID
+{
+    my ($buildid,) = @_;
+
+    my ($y, $m, $d, $h) = ($buildid =~ /^(\d{4})(\d{2})(\d{2})(\d{2})$/);
+    $d || die("Unrecognized buildid string.");
+
+    my $secondstodays = 60 * 60 * 24;
+    return (POSIX::mktime(00, 00, 00, $d, $m, $y - 1900) -
+            POSIX::mktime(00, 00, 00, 01, 01, 100)) / $secondstodays;
+}
 
 #Creates version resource file
 
 #Paramaters are passed on the command line:
 
-#Example: -PBI=blah -DEBUG=1
+#Example: -MODNAME nsToolkitCompsModule -DEBUG=1
 
-# PBI - your private build information (if not a milestone or nightly)
 # DEBUG - Mozilla's global debug variable - tells if its debug version
 # OFFICIAL - tells Mozilla is building a milestone or nightly
 # MSTONE - tells which milestone is being built;
 # OBJDIR - Holds the object directory;
 # MODNAME - tells what the name of the module is like nsBMPModule
 # DEPTH - Holds the path to the root obj dir
 # TOPSRCDIR - Holds the path to the root mozilla dir
 # SRCDIR - Holds module.ver and source
@@ -85,64 +98,61 @@ sub getNextEntry
 				$value =~ s/^\s*(.*?)\s*$/$1/;
 				return ($entry,$value);
 			}
 		}
 	}
 	return undef;
 }
 
-my ($quiet,$privateinfo,$objdir,$debug,$official,$milestone,$module,$binary,$depth,$rcinclude,$bits,$srcdir);
+my ($quiet,$objdir,$debug,$official,$milestone,$buildid,$module,$binary,$depth,$rcinclude,$bits,$srcdir,$fileversion,$productversion);
 
 GetOptions( "QUIET" => \$quiet,
-		"PBI=s" => \$privateinfo,
 		"DEBUG=s" => \$debug,
 		"OFFICIAL=s" => \$official,
 		"MSTONE=s" => \$milestone,
 		"MODNAME=s" => \$module,
 		"BINARY=s" => \$binary,
 		"DISPNAME=s" => \$displayname,
 		"SRCDIR=s" => \$srcdir,
 		"TOPSRCDIR=s" => \$topsrcdir,
 		"DEPTH=s" => \$depth,
 		"RCINCLUDE=s" => \$rcinclude,
 		"OBJDIR=s" => \$objdir,
 		"BITS=s" => \$bits);
-if (!defined($privateinfo)) {$privateinfo="";}
 if (!defined($debug)) {$debug="";}
 if (!defined($official)) {$official="";}
 if (!defined($milestone)) {$milestone="";}
 if (!defined($module)) {$module="";}
 if (!defined($binary)) {$binary="";}
 if (!defined($displayname)) {$displayname="Mozilla";}
 if (!defined($depth)) {$depth=".";}
 if (!defined($rcinclude)) {$rcinclude="";}
 if (!defined($objdir)) {$objdir=".";}
 if (!defined($srcdir)) {$srcdir=".";}
 if (!defined($topsrcdir)) {$topsrcdir=".";}
 if (!defined($bits)) {$bits="";}
 my $mfversion = "Personal";
 my $mpversion = "Personal";
-my $fileflags = "VS_FF_PRIVATEBUILD";
+my @fileflags = ("0");
 my $comment="";
 my $description="";
 if (!defined($module))
 {
 	$module = $binary;
 	($module) = split(/\./,$module);
 }
 
-my $productversion = "0,0,0,0";
-my $fileversion = $productversion;
 my $fileos = "VOS__WINDOWS32";
 if ($bits eq "16") { $fileos="VOS__WINDOWS16"; }
 
 my $bufferstr="    ";
 
 my $MILESTONE_FILE = "$topsrcdir/config/milestone.txt";
+my $BUILDID_FILE = "$depth/config/buildid";
 
 #Read module.ver file
 #Version file overrides for WIN32:
 #WIN32_MODULE_COMMENT
 #WIN32_MODULE_DESCRIPTION
 #WIN32_MODULE_FILEVERSION
 #WIN32_MODULE_COMPANYNAME
 #WIN32_MODULE_FILEVERSION_STRING
@@ -196,73 +206,70 @@ else
 #Get rid of trailing and leading whitespace
 $debug =~ s/^\s*(.*)\s*$/$1/;
 $comment =~ s/^\s*(.*)\s*$/$1/;
 $official =~ s/^\s*(.*)\s*$/$1/;
 $milestone =~ s/^\s*(.*)\s*$/$1/;
 $description =~ s/^\s*(.*)\s*$/$1/;
 $module =~ s/^\s*(.*)\s*$/$1/;
 $depth =~ s/^\s*(.*)\s*$/$1/;
-$privateinfo =~ s/^\s*(.*)\s*$/$1/;
 $binary =~ s/^\s*(.*)\s*$/$1/;
 $displayname =~ s/^\s*(.*)\s*$/$1/;
 
+open(BUILDID, "<", $BUILDID_FILE) || die("Couldn't open buildid file: $BUILDID_FILE");
+$buildid = <BUILDID>;
+$buildid =~ s/\s*$//;
+close BUILDID;
+
+my $daycount = daysFromBuildID($buildid);
+
+if ($milestone eq "") {
+    $milestone = Moz::Milestone::getOfficialMilestone($MILESTONE_FILE);
+}
+
+$mfversion = $mpversion = $milestone;
+
 if ($debug eq "1")
 {
-	$fileflags .= " | VS_FF_DEBUG";
+	push @fileflags, "VS_FF_DEBUG";
 	$mpversion .= " Debug";
 	$mfversion .= " Debug";
 }
 
-if ($official eq "1") {
-	#its an official build
-	$privateinfo = "";
-	$fileflags = "VS_FF_PRERELEASE";
-	if ($debug eq "1") {
-		$fileflags = "VS_FF_PRERELEASE | VS_FF_DEBUG";
-	}
+if ($official ne "1") {
+    push @fileflags, "VS_FF_PRIVATEBUILD";
+}
+
+if ($milestone =~ /[a-z]/) {
+    push @fileflags, "VS_FF_PRERELEASE";
+}
 
-        # Try to grab milestone.
-        # I'd love to put this in the makefiles rather than here,
-        # since I could run it once per build rather than once per
-        # dll/program, but I can't seem to get backticks working
-        # properly in the makefiles =P
-        if ($milestone eq "") {
-            $milestone = Moz::Milestone::getOfficialMilestone($MILESTONE_FILE);
-        }
-
-	if ($milestone ne "" && $milestone !~ /\+$/) {
-		#its a milestone build
-
-		$mpversion = $milestone;
-
-		$fileflags = "0";
-	      
-		my @mstone = split(/\./,$milestone);
-		$mstone[1] =~s/\D*$//g;
-		$productversion="$mstone[0],$mstone[1],0,0";
-
-	}
-
-	$mfversion = $mpversion = "$milestone";
+my @mstone = split(/\./,$milestone);
+$mstone[1] =~s/\D.*$//;
+if (!$mstone[2]) {
+    $mstone[2] = "0";
 }
+else {
+    $mstone[2] =~s/\D.*$//;
+}
+$fileversion = $productversion="$mstone[0],$mstone[1],$mstone[2],$daycount";
 
 my $copyright = "License: MPL 1.1/GPL 2.0/LGPL 2.1";
 my $company = "Mozilla Foundation";
 my $trademarks = "Mozilla";
 my $productname = $displayname;
 
 
 if (defined($override_comment)){$override_comment =~ s/\@MOZ_APP_DISPLAYNAME\@/$displayname/g; $comment=$override_comment;}
 if (defined($override_description)){$override_description =~ s/\@MOZ_APP_DISPLAYNAME\@/$displayname/g; $description=$override_description;}
 if (defined($override_fileversion)){$fileversion=$override_fileversion;}
 if (defined($override_mfversion)){$mfversion=$override_mfversion;}
 if (defined($override_company)){$company=$override_company;}
 if (defined($override_module)){$override_module =~ s/\@MOZ_APP_DISPLAYNAME\@/$displayname/g; $module=$override_module;}
-if (defined($override_copyright)){$override_copyright =~ s/\@MOZ_APP_DISPLAYNAME\@/$displayname/g; $copyright=$override_company;}
+if (defined($override_copyright)){$override_copyright =~ s/\@MOZ_APP_DISPLAYNAME\@/$displayname/g; $copyright=$override_copyright;}
 if (defined($override_trademarks)){$override_trademarks =~ s/\@MOZ_APP_DISPLAYNAME\@/$displayname/g; $trademarks=$override_trademarks;}
 if (defined($override_filename)){$binary=$override_filename;}
 if (defined($override_productname)){$override_productname =~ s/\@MOZ_APP_DISPLAYNAME\@/$displayname/g; $productname=$override_productname;}
 if (defined($override_productversion)){$productversion=$override_productversion;}
 if (defined($override_mpversion)){$mpversion=$override_mpversion;}
 
 
 #Override section
@@ -365,25 +372,28 @@ if (open(RCINCLUDE, "<$rcinclude"))
 #					print RCFILE "$nocomment\n";	
 #				}
 #			}
 #		}
 #	}
 	
 }
 
+my $fileflags = join(' | ', @fileflags);
+
 print RCFILE qq{
 
 
 /////////////////////////////////////////////////////////////////////////////
 //
 // Version
 //
 
 1 VERSIONINFO
+ FILEVERSION    $fileversion
  PRODUCTVERSION $productversion
  FILEFLAGSMASK 0x3fL
  FILEFLAGS $fileflags
  FILEOS $fileos
  FILETYPE VFT_DLL
  FILESUBTYPE 0x0L
 BEGIN
     BLOCK "StringFileInfo"
@@ -394,24 +404,18 @@ BEGIN
             VALUE "LegalCopyright", "$copyright"
             VALUE "CompanyName", "$company"
             VALUE "FileDescription", "$description"
             VALUE "FileVersion", "$mfversion"
             VALUE "ProductVersion", "$mpversion"
             VALUE "InternalName", "$module"
             VALUE "LegalTrademarks", "$trademarks"
             VALUE "OriginalFilename", "$binary"
-};
-if ($official ne "1") {
-print RCFILE qq{
-            VALUE "PrivateBuild", "$privateinfo"
-};
-}
-print RCFILE qq{
             VALUE "ProductName", "$productname"
+            VALUE "BuildID", "$buildid"
         END
     END
     BLOCK "VarFileInfo"
     BEGIN
         VALUE "Translation", 0x0, 1200
     END
 END
 
--- a/configure.in
+++ b/configure.in
@@ -1251,17 +1251,21 @@ if test "$GNU_CC"; then
     # Turn on GNU specific features
     # -Wall - turn on all warnings
     # -pedantic - make compiler warn about non-ANSI stuff, and
     #             be a little bit stricter
     # Warnings slamm took out for now (these were giving more noise than help):
     # -Wbad-function-cast - warns when casting a function to a new return type
     # -Wconversion - complained when char's or short's were used a function args
     # -Wshadow - removed because it generates more noise than help --pete
-    _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wall -W -Wno-unused -Wpointer-arith -Wcast-align"
+    _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wall -W -Wno-unused -Wpointer-arith"
+    if test "$CPU_ARCH" != "ia64"; then
+        # only use -Wcast-align for non-ia64, it's noisy on that platform
+        _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wcast-align"
+    fi
 
     dnl Turn pedantic on but disable the warnings for long long
     _PEDANTIC=1
     _IGNORE_LONG_LONG_WARNINGS=1
 
     _DEFINES_CFLAGS='-include $(DEPTH)/mozilla-config.h -DMOZILLA_CLIENT'
     _USE_CPP_INCLUDE_FLAG=1
 else
@@ -1276,17 +1280,21 @@ else
 
     DSO_CFLAGS=''
     DSO_PIC_CFLAGS='-KPIC'
     _DEFINES_CFLAGS='$(ACDEFINES) -D_MOZILLA_CONFIG_H_ -DMOZILLA_CLIENT'
 fi
 
 if test "$GNU_CXX"; then
     # Turn on GNU specific features
-    _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wall -Wconversion -Wpointer-arith -Wcast-align -Woverloaded-virtual -Wsynth -Wno-ctor-dtor-privacy -Wno-non-virtual-dtor"
+    _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wall -Wconversion -Wpointer-arith -Woverloaded-virtual -Wsynth -Wno-ctor-dtor-privacy -Wno-non-virtual-dtor"
+    if test "$CPU_ARCH" != "ia64"; then
+        # only use -Wcast-align for non-ia64, it's noisy on that platform
+        _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wcast-align"
+    fi
 
     _DEFINES_CXXFLAGS='-DMOZILLA_CLIENT -include $(DEPTH)/mozilla-config.h'
     _USE_CPP_INCLUDE_FLAG=1
 else
     _DEFINES_CXXFLAGS='-DMOZILLA_CLIENT -D_MOZILLA_CONFIG_H_ $(ACDEFINES)'
 fi
 
 dnl gcc can come with its own linker so it is better to use the pass-thru calls
@@ -6090,16 +6098,26 @@ dnl ====================================
 MOZ_ARG_ENABLE_BOOL(jprof,
 [  --enable-jprof          Enable jprof profiling tool (needs mozilla/tools/jprof)],
     MOZ_JPROF=1,
     MOZ_JPROF= )
 if test -n "$MOZ_JPROF"; then
     AC_DEFINE(MOZ_JPROF)
 fi
 
+dnl ========================================================
+dnl shark
+dnl ========================================================
+MOZ_ARG_ENABLE_BOOL(shark,
+[  --enable-shark          Enable shark remote profiling (needs CHUD framework)],
+    MOZ_SHARK=1,
+    MOZ_SHARK= )
+if test -n "$MOZ_SHARK"; then
+    AC_DEFINE(MOZ_SHARK)
+fi
 
 dnl ========================================================
 dnl = Enable stripping of libs & executables
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(strip,
 [  --enable-strip          Enable stripping of libs & executables ],
     ENABLE_STRIP=1,
     ENABLE_STRIP= )
@@ -7418,16 +7436,17 @@ AC_SUBST(MOZ_PLUGINS)
 AC_SUBST(ENABLE_EAZEL_PROFILER)
 AC_SUBST(EAZEL_PROFILER_CFLAGS)
 AC_SUBST(EAZEL_PROFILER_LIBS)
 AC_SUBST(MOZ_PERF_METRICS)
 AC_SUBST(GC_LEAK_DETECTOR)
 AC_SUBST(MOZ_LOG_REFCNT)
 AC_SUBST(MOZ_LEAKY)
 AC_SUBST(MOZ_JPROF)
+AC_SUBST(MOZ_SHARK)
 AC_SUBST(MOZ_XPCTOOLS)
 AC_SUBST(MOZ_JSLOADER)
 AC_SUBST(MOZ_USE_NATIVE_UCONV)
 AC_SUBST(MOZ_INSURE)
 AC_SUBST(MOZ_INSURE_DIRS)
 AC_SUBST(MOZ_INSURE_EXCLUDE_DIRS)
 AC_SUBST(MOZ_QUANTIFY)
 AC_SUBST(MOZ_INSURIFYING)
--- a/content/Makefile.in
+++ b/content/Makefile.in
@@ -48,16 +48,20 @@ DIRS		= base canvas html xml xul xbl xsl
 ifdef MOZ_SVG
 DIRS		+= svg
 endif
 
 ifdef MOZ_XTF
 DIRS            += xtf
 endif
 
+ifdef MOZ_MATHML
+DIRS            += mathml
+endif
+
 DIRS           += events
 
 ifdef ENABLE_TESTS
 TOOL_DIRS += test
 endif
 
 include $(topsrcdir)/config/rules.mk
 
--- a/content/base/public/nsContentUtils.h
+++ b/content/base/public/nsContentUtils.h
@@ -1147,16 +1147,31 @@ public:
    * nsNativeKeyEvent. It's also used in DOMEventToNativeKeyEvent.
    * See bug 406407 for details.
    */
   static nsEvent* GetNativeEvent(nsIDOMEvent* aDOMEvent);
   static PRBool DOMEventToNativeKeyEvent(nsIDOMEvent* aDOMEvent,
                                          nsNativeKeyEvent* aNativeEvent,
                                          PRBool aGetCharCode);
 
+  /**
+   * Get the application manifest URI for this context.  The manifest URI
+   * is specified in the manifest= attribute of the root element of the
+   * toplevel window.
+   *
+   * @param aWindow The context to check.
+   * @param aURI The manifest URI.
+   */
+  static void GetOfflineAppManifest(nsIDOMWindow *aWindow, nsIURI **aURI);
+
+  /**
+   * Check whether an application should be allowed to use offline APIs.
+   */
+  static PRBool OfflineAppAllowed(nsIURI *aURI);
+
 private:
 
   static PRBool InitializeEventTable();
 
   static nsresult doReparentContentWrapper(nsIContent *aChild,
                                            JSContext *cx,
                                            JSObject *aOldGlobal,
                                            JSObject *aNewGlobal,
@@ -1218,17 +1233,16 @@ private:
 
 #ifdef IBMBIDI
   static nsIBidiKeyboard* sBidiKeyboard;
 #endif
 
   static PRBool sInitialized;
 };
 
-
 #define NS_HOLD_JS_OBJECTS(obj, clazz)                                         \
   nsContentUtils::HoldJSObjects(NS_CYCLE_COLLECTION_UPCAST(obj, clazz),        \
                                 &NS_CYCLE_COLLECTION_NAME(clazz))
 
 #define NS_DROP_JS_OBJECTS(obj, clazz)                                         \
   nsContentUtils::DropJSObjects(NS_CYCLE_COLLECTION_UPCAST(obj, clazz))
 
 
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -270,17 +270,17 @@ public:
   /**
    * Return the language of this document.
    */
   void GetContentLanguage(nsAString& aContentLanguage) const
   {
     CopyASCIItoUTF16(mContentLanguage, aContentLanguage);
   }
 
-  // The state BidiEnabled should persist across multiple views
+  // The states BidiEnabled and MathMLEnabled should persist across multiple views
   // (screen, print) of the same document.
 
   /**
    * Check if the document contains bidi data.
    * If so, we have to apply the Unicode Bidi Algorithm.
    */
   PRBool GetBidiEnabled() const
   {
@@ -292,16 +292,29 @@ public:
    * Currently, we cannot disable bidi, because once bidi is enabled,
    * it affects a frame model irreversibly, and plays even though
    * the document no longer contains bidi data.
    */
   void SetBidiEnabled(PRBool aBidiEnabled)
   {
     mBidiEnabled = aBidiEnabled;
   }
+  
+  /**
+   * Check if the document contains (or has contained) any MathML elements.
+   */
+  PRBool GetMathMLEnabled() const
+  {
+    return mMathMLEnabled;
+  }
+  
+  void SetMathMLEnabled()
+  {
+    mMathMLEnabled = PR_TRUE;
+  }
 
   /**
    * Ask this document whether it's the initial document in its window.
    */
   PRBool IsInitialDocument() const
   {
     return mIsInitialDocumentInWindow;
   }
@@ -960,16 +973,18 @@ protected:
   // Table of element properties for this document.
   nsPropertyTable mPropertyTable;
 
   // Compatibility mode
   nsCompatibility mCompatMode;
 
   // True if BIDI is enabled.
   PRPackedBool mBidiEnabled;
+  // True if a MathML element has ever been owned by this document.
+  PRPackedBool mMathMLEnabled;
 
   // True if this document is the initial document for a window.  This should
   // basically be true only for documents that exist in newly-opened windows or
   // documents created to satisfy a GetDocument() on a window when there's no
   // document in it.
   PRPackedBool mIsInitialDocumentInWindow;
 
   PRPackedBool mShellsAreHidden;
--- a/content/base/public/nsINode.h
+++ b/content/base/public/nsINode.h
@@ -175,17 +175,19 @@ public:
     /** XUL elements */
     eXUL                 = 1 << 9,
     /** svg elements */
     eSVG                 = 1 << 10,
     /** document fragments */
     eDOCUMENT_FRAGMENT   = 1 << 11,
     /** data nodes (comments, PIs, text). Nodes of this type always
      returns a non-null value for nsIContent::GetText() */
-    eDATA_NODE           = 1 << 12
+    eDATA_NODE           = 1 << 12,
+    /** nsMathMLElement */
+    eMATHML              = 1 << 13
   };
 
   /**
    * API for doing a quick check if a content is of a given
    * type, such as HTML, XUL, Text, ...  Use this when you can instead of
    * checking the tag.
    *
    * @param aFlags what types you want to test for (see above)
--- a/content/base/src/Makefile.in
+++ b/content/base/src/Makefile.in
@@ -131,16 +131,17 @@ CPPSRCS		= \
 		nsGenericDOMDataNode.cpp \
 		nsGenericDOMNodeList.cpp \
 		nsGenericElement.cpp \
 		nsGkAtoms.cpp \
 		nsHTMLContentSerializer.cpp \
 		nsImageLoadingContent.cpp \
 		nsLineBreaker.cpp \
 		nsLoadListenerProxy.cpp \
+		nsMappedAttributeElement.cpp \
 		nsMappedAttributes.cpp \
 		nsNameSpaceManager.cpp \
 		nsNoDataProtocolContentPolicy.cpp \
 		nsNodeInfo.cpp \
 		nsNodeInfoManager.cpp \
 		nsNodeUtils.cpp \
 		nsObjectLoadingContent.cpp \
 		nsParserUtils.cpp \
--- a/content/base/src/nsAttrAndChildArray.cpp
+++ b/content/base/src/nsAttrAndChildArray.cpp
@@ -37,17 +37,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Storage of the children and attributes of a DOM node; storage for
  * the two is unified to minimize footprint.
  */
 
 #include "nsAttrAndChildArray.h"
-#include "nsGenericHTMLElement.h"
+#include "nsMappedAttributeElement.h"
 #include "prmem.h"
 #include "prbit.h"
 #include "nsString.h"
 #include "nsHTMLStyleSheet.h"
 #include "nsRuleWalker.h"
 #include "nsMappedAttributes.h"
 #include "nsUnicharUtils.h"
 #include "nsAutoPtr.h"
@@ -556,17 +556,17 @@ nsAttrAndChildArray::IndexOfAttr(nsIAtom
   }
 
   return -1;
 }
 
 nsresult
 nsAttrAndChildArray::SetAndTakeMappedAttr(nsIAtom* aLocalName,
                                           nsAttrValue& aValue,
-                                          nsGenericHTMLElement* aContent,
+                                          nsMappedAttributeElement* aContent,
                                           nsHTMLStyleSheet* aSheet)
 {
   nsRefPtr<nsMappedAttributes> mapped;
   nsresult rv = GetModifiableMapped(aContent, aSheet, PR_TRUE,
                                     getter_AddRefs(mapped));
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = mapped->SetAndTakeAttr(aLocalName, aValue);
@@ -646,17 +646,17 @@ nsAttrAndChildArray::NonMappedAttrCount(
 
 PRUint32
 nsAttrAndChildArray::MappedAttrCount() const
 {
   return mImpl && mImpl->mMappedAttrs ? (PRUint32)mImpl->mMappedAttrs->Count() : 0;
 }
 
 nsresult
-nsAttrAndChildArray::GetModifiableMapped(nsGenericHTMLElement* aContent,
+nsAttrAndChildArray::GetModifiableMapped(nsMappedAttributeElement* aContent,
                                          nsHTMLStyleSheet* aSheet,
                                          PRBool aWillAddAttr,
                                          nsMappedAttributes** aModifiable)
 {
   *aModifiable = nsnull;
 
   if (mImpl && mImpl->mMappedAttrs) {
     *aModifiable = mImpl->mMappedAttrs->Clone(aWillAddAttr);
--- a/content/base/src/nsAttrAndChildArray.h
+++ b/content/base/src/nsAttrAndChildArray.h
@@ -48,17 +48,17 @@
 #include "nsAttrName.h"
 #include "nsAttrValue.h"
 
 class nsINode;
 class nsIContent;
 class nsMappedAttributes;
 class nsHTMLStyleSheet;
 class nsRuleWalker;
-class nsGenericHTMLElement;
+class nsMappedAttributeElement;
 
 #define ATTRCHILD_ARRAY_GROWSIZE 8
 #define ATTRCHILD_ARRAY_LINEAR_THRESHOLD 32
 
 #define ATTRCHILD_ARRAY_ATTR_SLOTS_BITS 10
 
 #define ATTRCHILD_ARRAY_MAX_ATTR_COUNT \
     ((1 << ATTRCHILD_ARRAY_ATTR_SLOTS_BITS) - 1)
@@ -115,31 +115,31 @@ public:
   // Returns attribute name at given position or null if aPos is out-of-bounds
   const nsAttrName* GetSafeAttrNameAt(PRUint32 aPos) const;
 
   // aName is UTF-8 encoded
   const nsAttrName* GetExistingAttrNameFromQName(const nsACString& aName) const;
   PRInt32 IndexOfAttr(nsIAtom* aLocalName, PRInt32 aNamespaceID = kNameSpaceID_None) const;
 
   nsresult SetAndTakeMappedAttr(nsIAtom* aLocalName, nsAttrValue& aValue,
-                                nsGenericHTMLElement* aContent,
+                                nsMappedAttributeElement* aContent,
                                 nsHTMLStyleSheet* aSheet);
   nsresult SetMappedAttrStyleSheet(nsHTMLStyleSheet* aSheet);
   void WalkMappedAttributeStyleRules(nsRuleWalker* aRuleWalker);
 
 private:
   nsAttrAndChildArray(const nsAttrAndChildArray& aOther); // Not to be implemented
   nsAttrAndChildArray& operator=(const nsAttrAndChildArray& aOther); // Not to be implemented
 
   void Clear();
 
   PRUint32 NonMappedAttrCount() const;
   PRUint32 MappedAttrCount() const;
 
-  nsresult GetModifiableMapped(nsGenericHTMLElement* aContent,
+  nsresult GetModifiableMapped(nsMappedAttributeElement* aContent,
                                nsHTMLStyleSheet* aSheet,
                                PRBool aWillAddAttr,
                                nsMappedAttributes** aModifiable);
   nsresult MakeMappedUnique(nsMappedAttributes* aAttributes);
 
   PRUint32 AttrSlotsSize() const
   {
     return AttrSlotCount() * ATTRSIZE;
--- a/content/base/src/nsContentSink.cpp
+++ b/content/base/src/nsContentSink.cpp
@@ -65,20 +65,18 @@
 #include "nsIViewManager.h"
 #include "nsIContentViewer.h"
 #include "nsIAtom.h"
 #include "nsGkAtoms.h"
 #include "nsIDOMWindowInternal.h"
 #include "nsIPrincipal.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsNetCID.h"
-#include "nsICache.h"
-#include "nsICacheService.h"
-#include "nsICacheSession.h"
 #include "nsIOfflineCacheUpdate.h"
+#include "nsIScriptSecurityManager.h"
 #include "nsIDOMLoadStatus.h"
 #include "nsICookieService.h"
 #include "nsIPrompt.h"
 #include "nsServiceManagerUtils.h"
 #include "nsContentUtils.h"
 #include "nsParserUtils.h"
 #include "nsCRT.h"
 #include "nsEscape.h"
@@ -89,16 +87,17 @@
 #include "nsIAppShell.h"
 #include "nsWidgetsCID.h"
 #include "nsIDOMNSDocument.h"
 #include "nsIRequest.h"
 #include "nsNodeUtils.h"
 #include "nsIDOMNode.h"
 #include "nsThreadUtils.h"
 #include "nsPresShellIterator.h"
+#include "nsPIDOMWindow.h"
 
 PRLogModuleInfo* gContentSinkLogModuleInfo;
 
 class nsScriptLoaderObserverProxy : public nsIScriptLoaderObserver
 {
 public:
   nsScriptLoaderObserverProxy(nsIScriptLoaderObserver* aInner)
     : mInner(do_GetWeakReference(aInner))
@@ -679,21 +678,16 @@ nsContentSink::ProcessLink(nsIContent* a
   nsStyleLinkElement::ParseLinkTypes(aRel, linkTypes);
 
   PRBool hasPrefetch = (linkTypes.IndexOf(NS_LITERAL_STRING("prefetch")) != -1);
   // prefetch href if relation is "next" or "prefetch"
   if (hasPrefetch || linkTypes.IndexOf(NS_LITERAL_STRING("next")) != -1) {
     PrefetchHref(aHref, aElement, hasPrefetch);
   }
 
-  // fetch href into the offline cache if relation is "offline-resource"
-  if (linkTypes.IndexOf(NS_LITERAL_STRING("offline-resource")) != -1) {
-    AddOfflineResource(aHref, aElement);
-  }
-
   // is it a stylesheet link?
   if (linkTypes.IndexOf(NS_LITERAL_STRING("stylesheet")) == -1) {
     return NS_OK;
   }
 
   PRBool isAlternate = linkTypes.IndexOf(NS_LITERAL_STRING("alternate")) != -1;
   return ProcessStyleLink(aElement, aHref, isAlternate, aTitle, aType,
                           aMedia);
@@ -815,74 +809,72 @@ nsContentSink::PrefetchHref(const nsAStr
               mDocumentBaseURI);
     if (uri) {
       nsCOMPtr<nsIDOMNode> domNode = do_QueryInterface(aSource);
       prefetchService->PrefetchURI(uri, mDocumentURI, domNode, aExplicit);
     }
   }
 }
 
-nsresult
-nsContentSink::AddOfflineResource(const nsAString &aHref, nsIContent *aSource)
+void
+nsContentSink::ProcessOfflineManifest(nsIContent *aElement)
 {
-  PRBool match;
-  nsresult rv;
+  // Check for a manifest= attribute.
+  nsAutoString manifestSpec;
+  aElement->GetAttr(kNameSpaceID_None, nsGkAtoms::manifest, manifestSpec);
 
-  nsCOMPtr<nsIURI> innerURI = NS_GetInnermostURI(mDocumentURI);
-  if (!innerURI)
-    return NS_ERROR_FAILURE;
-
-  if (!mHaveOfflineResources) {
-    mHaveOfflineResources = PR_TRUE;
-
-    // only let http and https urls add offline resources
-    nsresult rv = innerURI->SchemeIs("http", &match);
-    NS_ENSURE_SUCCESS(rv, rv);
+  if (manifestSpec.IsEmpty() ||
+      manifestSpec.FindChar('#') != kNotFound) {
+    return;
+  }
 
-    if (!match) {
-      rv = innerURI->SchemeIs("https", &match);
-      NS_ENSURE_SUCCESS(rv, rv);
-      if (!match)
-        return NS_OK;
-    }
-
-    // create updater
-    mOfflineCacheUpdate =
-      do_CreateInstance(NS_OFFLINECACHEUPDATE_CONTRACTID, &rv);
-    NS_ENSURE_SUCCESS(rv, rv);
+  // We only care about manifests in toplevel windows.
+  nsCOMPtr<nsPIDOMWindow> pwindow =
+    do_QueryInterface(mDocument->GetScriptGlobalObject());
+  if (!pwindow) {
+    return;
+  }
 
-    nsCAutoString ownerDomain;
-    rv = innerURI->GetHostPort(ownerDomain);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    nsCAutoString ownerSpec;
-    rv = mDocumentURI->GetSpec(ownerSpec);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    rv = mOfflineCacheUpdate->Init(PR_FALSE, ownerDomain,
-                                   ownerSpec, mDocumentURI);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    // Kick off this update when the document is done loading
-    nsCOMPtr<nsIDOMDocument> doc = do_QueryInterface(mDocument);
-    mOfflineCacheUpdate->ScheduleOnDocumentStop(doc);
+  nsCOMPtr<nsIDOMWindow> window =
+    do_QueryInterface(pwindow->GetOuterWindow());
+  if (!window) {
+    return;
   }
 
-  if (!mOfflineCacheUpdate) return NS_OK;
+  nsCOMPtr<nsIDOMWindow> parent;
+  window->GetParent(getter_AddRefs(parent));
+  if (parent.get() != window.get()) {
+    return;
+  }
+
+  // Only update if the document has permission to use offline APIs.
+  if (!nsContentUtils::OfflineAppAllowed(mDocumentURI)) {
+    return;
+  }
 
-  const nsACString &charset = mDocument->GetDocumentCharacterSet();
-  nsCOMPtr<nsIURI> uri;
-  rv = NS_NewURI(getter_AddRefs(uri), aHref,
-                 charset.IsEmpty() ? nsnull : PromiseFlatCString(charset).get(),
-                 mDocumentBaseURI);
-  NS_ENSURE_SUCCESS(rv, rv);
+  nsCOMPtr<nsIURI> manifestURI;
+  nsContentUtils::NewURIWithDocumentCharset(getter_AddRefs(manifestURI),
+                                            manifestSpec, mDocument,
+                                            mDocumentURI);
+  if (!manifestURI) {
+    return;
+  }
 
-  nsCOMPtr<nsIDOMNode> domNode = do_QueryInterface(aSource);
+  // Documents must list a manifest from the same origin
+  nsresult rv = nsContentUtils::GetSecurityManager()->
+                   CheckSameOriginURI(manifestURI, mDocumentURI, PR_TRUE);
+  if (NS_FAILED(rv)) {
+    return;
+  }
 
-  return mOfflineCacheUpdate->AddURI(uri, domNode);
+  // Start the update
+  nsCOMPtr<nsIDOMDocument> domdoc = do_QueryInterface(mDocument);
+  nsCOMPtr<nsIOfflineCacheUpdateService> updateService =
+    do_GetService(NS_OFFLINECACHEUPDATESERVICE_CONTRACTID);
+  updateService->ScheduleOnDocumentStop(manifestURI, mDocumentURI, domdoc);
 }
 
 void
 nsContentSink::ScrollToRef()
 {
   if (mRef.IsEmpty()) {
     return;
   }
--- a/content/base/src/nsContentSink.h
+++ b/content/base/src/nsContentSink.h
@@ -70,17 +70,16 @@ class nsIDocShell;
 class nsICSSLoader;
 class nsIParser;
 class nsIAtom;
 class nsIChannel;
 class nsIContent;
 class nsIViewManager;
 class nsNodeInfoManager;
 class nsScriptLoader;
-class nsIOfflineCacheUpdate;
 
 #ifdef NS_DEBUG
 
 extern PRLogModuleInfo* gContentSinkLogModuleInfo;
 
 #define SINK_TRACE_CALLS              0x1
 #define SINK_TRACE_REFLOW             0x2
 #define SINK_ALWAYS_REFLOW            0x4
@@ -164,17 +163,17 @@ protected:
                                     const nsSubstring& aHref,
                                     PRBool aAlternate,
                                     const nsSubstring& aTitle,
                                     const nsSubstring& aType,
                                     const nsSubstring& aMedia);
 
   void PrefetchHref(const nsAString &aHref, nsIContent *aSource,
                     PRBool aExplicit);
-  nsresult AddOfflineResource(const nsAString &aHref, nsIContent *aSource);
+  void ProcessOfflineManifest(nsIContent *aElement);
 
   void ScrollToRef();
   nsresult RefreshIfEnabled(nsIViewManager* vm);
 
   // Start layout.  If aIgnorePendingSheets is true, this will happen even if
   // we still have stylesheet loads pending.  Otherwise, we'll wait until the
   // stylesheets are all done loading.
   void StartLayout(PRBool aIgnorePendingSheets);
@@ -255,33 +254,28 @@ protected:
   // frequency parser interrupt mode without falling through to the
   // logic which decides whether to switch to the high frequency
   // parser interrupt mode.
   PRUint8 mDeflectedCount;
 
   // Do we notify based on time?
   PRPackedBool mNotifyOnTimer;
 
-  // For saving <link rel="offline-resource"> links
-  nsCOMPtr<nsIOfflineCacheUpdate> mOfflineCacheUpdate;
-
   // Have we already called BeginUpdate for this set of content changes?
   PRUint8 mBeganUpdate : 1;
   PRUint8 mLayoutStarted : 1;
   PRUint8 mScrolledToRefAlready : 1;
   PRUint8 mCanInterruptParser : 1;
   PRUint8 mDynamicLowerValue : 1;
   PRUint8 mParsing : 1;
   PRUint8 mDroppedTimer : 1;
   PRUint8 mInTitle : 1;
   PRUint8 mChangeScrollPosWhenScrollingToRef : 1;
   // If true, we deferred starting layout until sheets load
   PRUint8 mDeferredLayoutStart : 1;
-  // true if an <link rel="offline-resource"> nodes have been encountered.
-  PRUint8 mHaveOfflineResources : 1;
   // If true, we deferred notifications until sheets load
   PRUint8 mDeferredFlushTags : 1;
   
   // -- Can interrupt parsing members --
   PRUint32 mDelayTimerStart;
 
   // Interrupt parsing during token procesing after # of microseconds
   PRInt32 mMaxTokenProcessingTime;
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -140,16 +140,17 @@ static NS_DEFINE_CID(kXTFServiceCID, NS_
 #include "nsContentErrors.h"
 #include "nsUnicharUtilCIID.h"
 #include "nsICaseConversion.h"
 #include "nsCompressedCharMap.h"
 #include "nsINativeKeyBindings.h"
 #include "nsIDOMNSUIEvent.h"
 #include "nsIDOMNSEvent.h"
 #include "nsIPrivateDOMEvent.h"
+#include "nsIPermissionManager.h"
 
 #ifdef IBMBIDI
 #include "nsIBidiKeyboard.h"
 #endif
 #include "nsCycleCollectionParticipant.h"
 
 // for ReportToConsole
 #include "nsIStringBundle.h"
@@ -670,16 +671,92 @@ DEFINE_CCMAP(gPuncCharsCCMap, const);
 
 // static
 PRBool
 nsContentUtils::IsPunctuationMark(PRUnichar aChar)
 {
   return CCMAP_HAS_CHAR(gPuncCharsCCMap, aChar);
 }
 
+/* static */
+void
+nsContentUtils::GetOfflineAppManifest(nsIDOMWindow *aWindow, nsIURI **aURI)
+{
+  nsCOMPtr<nsIDOMWindow> top;
+  aWindow->GetTop(getter_AddRefs(top));
+  if (!top) {
+    return;
+  }
+
+  nsCOMPtr<nsIDOMDocument> topDOMDocument;
+  top->GetDocument(getter_AddRefs(topDOMDocument));
+  nsCOMPtr<nsIDocument> topDoc = do_QueryInterface(topDOMDocument);
+  if (!topDoc) {
+    return;
+  }
+
+  nsCOMPtr<nsIContent> docElement = topDoc->GetRootContent();
+  if (!docElement) {
+    return;
+  }
+
+  nsAutoString manifestSpec;
+  docElement->GetAttr(kNameSpaceID_None, nsGkAtoms::manifest, manifestSpec);
+
+  // Manifest URIs can't have fragment identifiers.
+  if (manifestSpec.IsEmpty() ||
+      manifestSpec.FindChar('#') != kNotFound) {
+    return;
+  }
+
+  nsContentUtils::NewURIWithDocumentCharset(aURI, manifestSpec,
+                                            topDoc, topDoc->GetBaseURI());
+}
+
+/* static */
+PRBool
+nsContentUtils::OfflineAppAllowed(nsIURI *aURI)
+{
+  nsCOMPtr<nsIURI> innerURI = NS_GetInnermostURI(aURI);
+  if (!innerURI)
+    return PR_FALSE;
+
+  // only http and https applications can use offline APIs.
+  PRBool match;
+  nsresult rv = innerURI->SchemeIs("http", &match);
+  NS_ENSURE_SUCCESS(rv, PR_FALSE);
+
+  if (!match) {
+    rv = innerURI->SchemeIs("https", &match);
+    NS_ENSURE_SUCCESS(rv, PR_FALSE);
+    if (!match) {
+      return PR_FALSE;
+    }
+  }
+
+  nsCOMPtr<nsIPermissionManager> permissionManager =
+    do_GetService(NS_PERMISSIONMANAGER_CONTRACTID);
+  if (!permissionManager) {
+    return PR_FALSE;
+  }
+
+  PRUint32 perm;
+  permissionManager->TestExactPermission(innerURI, "offline-app", &perm);
+
+  if (perm == nsIPermissionManager::UNKNOWN_ACTION) {
+    return GetBoolPref("offline-apps.allow_by_default");
+  }
+
+  if (perm == nsIPermissionManager::DENY_ACTION) {
+    return PR_FALSE;
+  }
+
+  return PR_TRUE;
+}
+
 // static
 void
 nsContentUtils::Shutdown()
 {
   sInitialized = PR_FALSE;
 
   NS_HTMLParanoidFragmentSinkShutdown();
   NS_XHTMLParanoidFragmentSinkShutdown();
@@ -2664,18 +2741,18 @@ nsContentUtils::IsChromeDoc(nsIDocument 
 
 void
 nsContentUtils::NotifyXPCIfExceptionPending(JSContext* aCx)
 {
   if (!::JS_IsExceptionPending(aCx)) {
     return;
   }
 
-  nsCOMPtr<nsIXPCNativeCallContext> nccx;
-  XPConnect()->GetCurrentNativeCallContext(getter_AddRefs(nccx));
+  nsAXPCNativeCallContext *nccx = nsnull;
+  XPConnect()->GetCurrentNativeCallContext(&nccx);
   if (nccx) {
     // Check to make sure that the JSContext that nccx will mess with is the
     // same as the JSContext we've set an exception on.  If they're not the
     // same, don't mess with nccx.
     JSContext* cx;
     nccx->GetJSContext(&cx);
     if (cx == aCx) {
       nccx->SetExceptionWasThrown(PR_TRUE);
--- a/content/base/src/nsDOMParser.cpp
+++ b/content/base/src/nsDOMParser.cpp
@@ -485,20 +485,20 @@ nsDOMParser::Initialize(nsISupports* aOw
   return Init(prin, documentURI, baseURI, scriptglobal);
 }
 
 NS_IMETHODIMP
 nsDOMParser::Init()
 {
   AttemptedInitMarker marker(&mAttemptedInit);
 
-  nsCOMPtr<nsIXPCNativeCallContext> ncc;
+  nsAXPCNativeCallContext *ncc = nsnull;
 
   nsresult rv = nsContentUtils::XPConnect()->
-    GetCurrentNativeCallContext(getter_AddRefs(ncc));
+    GetCurrentNativeCallContext(&ncc);
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(ncc, NS_ERROR_UNEXPECTED);
 
   JSContext *cx = nsnull;
   rv = ncc->GetJSContext(&cx);
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(cx, NS_ERROR_UNEXPECTED);
 
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -714,26 +714,26 @@ nsNSElementTearoff::GetElementsByClassNa
                                            nsIDOMNodeList** aReturn)
 {
   return nsDocument::GetElementsByClassNameHelper(mContent, aClasses, aReturn);
 }
 
 static nsPoint
 GetOffsetFromInitialContainingBlock(nsIFrame* aFrame)
 {
-  nsIFrame* rootFrame = aFrame->PresContext()->FrameManager()->GetRootFrame();
-  nsPoint pt(0,0);
-  for (nsIFrame* p = aFrame; p != rootFrame; p = p->GetParent()) {
-    // coordinates of elements inside a foreignobject are relative to the top-left
-    // of the nearest foreignobject
-    if (p->IsFrameOfType(nsIFrame::eSVGForeignObject) && p != aFrame)
-      return pt;
-    pt += p->GetPosition();
-  }
-  return pt;
+  nsIFrame* refFrame = aFrame->GetParent();
+  if (!refFrame)
+    return nsPoint(0, 0);
+
+  // get the nearest enclosing SVG foreign object frame or the root frame
+  while (refFrame->GetParent() &&
+         !refFrame->IsFrameOfType(nsIFrame::eSVGForeignObject))
+    refFrame = refFrame->GetParent();
+
+  return aFrame->GetOffsetTo(refFrame);
 }
 
 static double
 RoundFloat(double aValue)
 {
   return floor(aValue + 0.5);
 }
 
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -471,16 +471,17 @@ GK_ATOM(listrows, "listrows")
 GK_ATOM(load, "load")
 GK_ATOM(localName, "local-name")
 GK_ATOM(longdesc, "longdesc")
 GK_ATOM(lowerFirst, "lower-first")
 GK_ATOM(lowest, "lowest")
 GK_ATOM(lowsrc, "lowsrc")
 GK_ATOM(ltr, "ltr")
 GK_ATOM(map, "map")
+GK_ATOM(manifest, "manifest")
 GK_ATOM(marginheight, "marginheight")
 GK_ATOM(marginwidth, "marginwidth")
 GK_ATOM(marquee, "marquee")
 GK_ATOM(match, "match")
 GK_ATOM(max, "max")
 GK_ATOM(maxheight, "maxheight")
 GK_ATOM(maxlength, "maxlength")
 GK_ATOM(maxpos, "maxpos")
new file mode 100644
--- /dev/null
+++ b/content/base/src/nsMappedAttributeElement.cpp
@@ -0,0 +1,98 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim:set tw=80 expandtab softtabstop=2 ts=2 sw=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 Communicator client code.
+ *
+ * The Initial Developer of the Original Code is
+ * Netscape Communications Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 1998
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Mats Palmgren <mats.palmgren@bredband.net>
+ *   Daniel Kraft <d@domob.eu>
+ *
+ * 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 "nsMappedAttributeElement.h"
+#include "nsIDocument.h"
+
+nsresult
+nsMappedAttributeElement::BindToTree(nsIDocument* aDocument, nsIContent* aParent,
+                                     nsIContent* aBindingParent,
+                                     PRBool aCompileEventHandlers)
+{
+  nsresult rv = nsMappedAttributeElementBase::BindToTree(aDocument, aParent,
+                                                         aBindingParent,
+                                                         aCompileEventHandlers);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  if (aDocument) {
+    // If we're in a document now, let our mapped attrs know what their new
+    // sheet is.
+    nsHTMLStyleSheet* sheet = aDocument->GetAttributeStyleSheet();
+    if (sheet) {
+      mAttrsAndChildren.SetMappedAttrStyleSheet(sheet);
+    }
+  }
+
+  return rv;
+}
+
+nsresult
+nsMappedAttributeElement::WalkContentStyleRules(nsRuleWalker* aRuleWalker)
+{
+  mAttrsAndChildren.WalkMappedAttributeStyleRules(aRuleWalker);
+  return NS_OK;
+}
+
+PRBool
+nsMappedAttributeElement::SetMappedAttribute(nsIDocument* aDocument,
+                                             nsIAtom* aName,
+                                             nsAttrValue& aValue,
+                                             nsresult* aRetval)
+{
+  NS_PRECONDITION(aDocument == GetCurrentDoc(), "Unexpected document");
+  nsHTMLStyleSheet* sheet = aDocument ?
+    aDocument->GetAttributeStyleSheet() : nsnull;
+
+  *aRetval = mAttrsAndChildren.SetAndTakeMappedAttr(aName, aValue,
+                                                    this, sheet);
+  return PR_TRUE;
+}
+
+nsMapRuleToAttributesFunc
+nsMappedAttributeElement::GetAttributeMappingFunction() const
+{
+  return &MapNoAttributesInto;
+}
+
+void
+nsMappedAttributeElement::MapNoAttributesInto(const nsMappedAttributes* aAttributes,
+                                              nsRuleData* aData)
+{
+}
new file mode 100644
--- /dev/null
+++ b/content/base/src/nsMappedAttributeElement.h
@@ -0,0 +1,84 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim:set tw=80 expandtab softtabstop=2 ts=2 sw=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 Communicator client code.
+ *
+ * The Initial Developer of the Original Code is
+ * Netscape Communications Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 1998
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Daniel Kraft <d@domob.eu>
+ *
+ * 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 ***** */
+
+/**
+ * nsMappedAttributeElement is the base for elements supporting style mapped
+ * attributes via nsMappedAttributes (HTML and MathML).
+ */
+
+#ifndef NS_MAPPEDATTRIBUTEELEMENT_H_
+#define NS_MAPPEDATTRIBUTEELEMENT_H_
+
+#include "nsStyledElement.h"
+
+class nsMappedAttributes;
+struct nsRuleData;
+
+typedef void (*nsMapRuleToAttributesFunc)(const nsMappedAttributes* aAttributes, 
+                                          nsRuleData* aData);
+
+typedef nsStyledElement nsMappedAttributeElementBase;
+
+class nsMappedAttributeElement : public nsMappedAttributeElementBase
+{
+
+protected:
+
+  nsMappedAttributeElement(nsINodeInfo *aNodeInfo)
+    : nsMappedAttributeElementBase(aNodeInfo)
+  {}
+
+public:
+  virtual nsresult BindToTree(nsIDocument* aDocument, nsIContent* aParent,
+                              nsIContent* aBindingParent,
+                              PRBool aCompileEventHandlers);
+
+  virtual nsMapRuleToAttributesFunc GetAttributeMappingFunction() const;
+
+  static void MapNoAttributesInto(const nsMappedAttributes* aAttributes, 
+                                  nsRuleData* aRuleData);
+
+  NS_IMETHOD WalkContentStyleRules(nsRuleWalker* aRuleWalker);
+  virtual PRBool SetMappedAttribute(nsIDocument* aDocument,
+                                    nsIAtom* aName,
+                                    nsAttrValue& aValue,
+                                    nsresult* aRetval);
+};
+
+#endif // NS_MAPPEDATTRIBUTEELEMENT_H_
--- a/content/base/src/nsMappedAttributes.h
+++ b/content/base/src/nsMappedAttributes.h
@@ -40,17 +40,17 @@
  * A unique per-element set of attributes that is used as an
  * nsIStyleRule; used to implement presentational attributes.
  */
 
 #ifndef nsMappedAttributes_h___
 #define nsMappedAttributes_h___
 
 #include "nsAttrAndChildArray.h"
-#include "nsGenericHTMLElement.h"
+#include "nsMappedAttributeElement.h"
 #include "nsIStyleRule.h"
 
 class nsIAtom;
 class nsHTMLStyleSheet;
 class nsRuleWalker;
 
 class nsMappedAttributes : public nsIStyleRule
 {
--- a/content/base/src/nsScriptLoader.cpp
+++ b/content/base/src/nsScriptLoader.cpp
@@ -623,19 +623,19 @@ nsScriptLoader::EvaluateScript(nsScriptL
     cx = (JSContext *)context->GetNativeContext();
     ::JS_BeginRequest(cx);
     ::JS_ReportPendingException(cx);
   }
 
   context->SetProcessingScriptTag(oldProcessingScriptTag);
 
   if (stid == nsIProgrammingLanguage::JAVASCRIPT) {
-    nsCOMPtr<nsIXPCNativeCallContext> ncc;
+    nsAXPCNativeCallContext *ncc = nsnull;
     nsContentUtils::XPConnect()->
-      GetCurrentNativeCallContext(getter_AddRefs(ncc));
+      GetCurrentNativeCallContext(&ncc);
 
     if (ncc) {
       NS_ASSERTION(!::JS_IsExceptionPending(cx),
                    "JS_ReportPendingException wasn't called");
       ncc->SetExceptionWasThrown(PR_FALSE);
     }
     ::JS_EndRequest(cx);
   }
--- a/content/base/src/nsXMLHttpRequest.cpp
+++ b/content/base/src/nsXMLHttpRequest.cpp
@@ -1368,20 +1368,20 @@ nsXMLHttpRequest::OpenRequest(const nsAC
 /* void open (in AUTF8String method, in AUTF8String url); */
 NS_IMETHODIMP
 nsXMLHttpRequest::Open(const nsACString& method, const nsACString& url)
 {
   nsresult rv = NS_OK;
   PRBool async = PR_TRUE;
   nsAutoString user, password;
 
-  nsCOMPtr<nsIXPCNativeCallContext> cc;
+  nsAXPCNativeCallContext *cc = nsnull;
   nsIXPConnect *xpc = nsContentUtils::XPConnect();
   if (xpc) {
-    rv = xpc->GetCurrentNativeCallContext(getter_AddRefs(cc));
+    rv = xpc->GetCurrentNativeCallContext(&cc);
   }
 
   if (NS_SUCCEEDED(rv) && cc) {
     PRUint32 argc;
     rv = cc->GetArgc(&argc);
     if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
 
     jsval* argv;
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -51,16 +51,17 @@ include $(topsrcdir)/config/rules.mk
 		file_bug218236_multipart.txt^headers^ \
 		test_bug218277.html \
 		test_bug238409.html \
 		test_bug276037-1.html \
 		test_bug276037-2.xhtml \
 		test_bug308484.html \
 		test_bug311681.xml \
 		test_bug322317.html \
+		test_bug330925.xhtml \
 		test_bug337631.html \
 		test_bug338541.xhtml \
 		test_bug338679.html \
 		test_bug339494.html \
 		test_bug339494.xhtml \
 		test_bug339494.xul \
 		test_bug343596.html \
 		test_bug352728.html \
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_bug330925.xhtml
@@ -0,0 +1,74 @@
+<html xmlns="http://www.w3.org/1999/xhtml">
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=330925
+-->
+<head>
+  <title>Test for Bug 330925</title>
+  <script type="text/javascript" src="/MochiKit/packed.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+
+<style type="text/css">
+#t {
+-moz-binding: url(#randomxbl);
+}
+</style>
+
+<bindings xmlns="http://www.mozilla.org/xbl">
+<binding id="randomxbl" inheritstyle="false">
+<content>
+xbl textnode1
+<div>
+xbl textnode2
+<children xmlns="http://www.mozilla.org/xbl"/>
+</div>
+</content>
+</binding>
+</bindings>
+
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=330925">Mozilla Bug 330925</a>
+
+<p id="display">
+<div id="t" />
+</p>
+
+<pre id="test">
+<script class="testbody" type="text/javascript">
+<![CDATA[
+
+/** Test for Bug 330925 **/
+
+// We have to wait until onload because XBL doesn't bind immediately.
+SimpleTest.waitForExplicitFinish();
+addLoadEvent(init);
+
+function init()
+{
+  var t = document.getElementById("t");
+
+  is(document.getBindingParent(document.getAnonymousNodes(t)[0]), 
+     t,
+     "Wrong binding parent for anonymous node");
+     
+  is(document.getBindingParent(document.getAnonymousNodes(t)[1].childNodes[0]), 
+     t,
+     "Wrong binding parent for child of anonymous node");
+     
+  is(document.getBindingParent(t), 
+     null,
+     "Non-anonymous node should not have a binding parent");
+     
+  is(document.getBindingParent(document.documentElement), 
+     null,
+     "Document element should not have a binding parent");
+     
+  SimpleTest.finish();
+}
+
+]]>
+</script>
+</pre>
+</body>
+</html>
--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
@@ -1848,19 +1848,19 @@ nsCanvasRenderingContext2D::IsPointInPat
 // drawImage(in HTMLImageElement image, in float sx, in float sy, in float sw, in float sh, in float dx, in float dy, in float dw, in float dh);
 //   -- render the region defined by (sx,sy,sw,wh) in image-local space into the region (dx,dy,dw,dh) on the canvas
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2D::DrawImage()
 {
     nsresult rv;
 
-    nsCOMPtr<nsIXPCNativeCallContext> ncc;
+    nsAXPCNativeCallContext *ncc = nsnull;
     rv = nsContentUtils::XPConnect()->
-        GetCurrentNativeCallContext(getter_AddRefs(ncc));
+        GetCurrentNativeCallContext(&ncc);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!ncc)
         return NS_ERROR_FAILURE;
 
     JSContext *ctx = nsnull;
 
     rv = ncc->GetJSContext(&ctx);
@@ -2374,19 +2374,19 @@ NS_IMETHODIMP
 nsCanvasRenderingContext2D::GetImageData()
 {
     if (mCanvasElement->IsWriteOnly() && !nsContentUtils::IsCallerTrustedForRead()) {
       // not permitted to use DrawWindow
       // XXX ERRMSG we need to report an error to developers here! (bug 329026)
       return NS_ERROR_DOM_SECURITY_ERR;
     }
 
-    nsCOMPtr<nsIXPCNativeCallContext> ncc;
+    nsAXPCNativeCallContext *ncc = nsnull;
     nsresult rv = nsContentUtils::XPConnect()->
-        GetCurrentNativeCallContext(getter_AddRefs(ncc));
+        GetCurrentNativeCallContext(&ncc);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!ncc)
         return NS_ERROR_FAILURE;
 
     JSContext *ctx = nsnull;
 
     rv = ncc->GetJSContext(&ctx);
@@ -2499,19 +2499,19 @@ nsCanvasRenderingContext2D::GetImageData
 }
 
 // void putImageData (in ImageData d, in float x, in float y);
 NS_IMETHODIMP
 nsCanvasRenderingContext2D::PutImageData()
 {
     nsresult rv;
 
-    nsCOMPtr<nsIXPCNativeCallContext> ncc;
+    nsAXPCNativeCallContext *ncc = nsnull;
     rv = nsContentUtils::XPConnect()->
-        GetCurrentNativeCallContext(getter_AddRefs(ncc));
+        GetCurrentNativeCallContext(&ncc);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!ncc)
         return NS_ERROR_FAILURE;
 
     JSContext *ctx = nsnull;
 
     rv = ncc->GetJSContext(&ctx);
--- a/content/events/public/nsIEventStateManager.h
+++ b/content/events/public/nsIEventStateManager.h
@@ -210,10 +210,13 @@ NS_DEFINE_STATIC_IID_ACCESSOR(nsIEventSt
 // Content suppressed by the user (ad blocking, etc)
 #define NS_EVENT_STATE_SUPPRESSED    0x00100000
 // Content is still loading such that there is nothing to show the
 // user (eg an image which hasn't started coming in yet)
 #define NS_EVENT_STATE_LOADING       0x00200000
 // Content is of a type that gecko can't handle
 #define NS_EVENT_STATE_TYPE_UNSUPPORTED \
                                      0x00400000
+#ifdef MOZ_MATHML
+#define NS_EVENT_STATE_INCREMENT_SCRIPT_LEVEL 0x00800000
+#endif
 
 #endif // nsIEventStateManager_h__
--- a/content/html/content/src/nsFormSubmission.cpp
+++ b/content/html/content/src/nsFormSubmission.cpp
@@ -1046,17 +1046,16 @@ nsFSTextPlain::GetEncodedSubmission(nsIU
     nsCOMPtr<nsIMIMEInputStream> mimeStream
         = do_CreateInstance("@mozilla.org/network/mime-input-stream;1", &rv);
     NS_ENSURE_SUCCESS(rv, rv);
 
     mimeStream->AddHeader("Content-Type", "text/plain");
     mimeStream->SetAddContentLength(PR_TRUE);
     mimeStream->SetData(bodyStream);
     CallQueryInterface(mimeStream, aPostDataStream);
-    NS_ADDREF(*aPostDataStream);
   }
 
   return rv;
 }
 
 
 //
 // CLASS nsFormSubmission
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -1141,23 +1141,16 @@ nsGenericHTMLElement::BindToTree(nsIDocu
 
   if (aDocument) {
     if (HasFlag(NODE_IS_EDITABLE) && GetContentEditableValue() == eTrue) {
       nsCOMPtr<nsIHTMLDocument> htmlDocument = do_QueryInterface(aDocument);
       if (htmlDocument) {
         htmlDocument->ChangeContentEditableCount(this, +1);
       }
     }
-
-    // If we're in a document now, let our mapped attrs know what their new
-    // sheet is.
-    nsHTMLStyleSheet* sheet = aDocument->GetAttributeStyleSheet();
-    if (sheet) {
-      mAttrsAndChildren.SetMappedAttrStyleSheet(sheet);
-    }
   }
 
   return rv;
 }
 
 void
 nsGenericHTMLElement::UnbindFromTree(PRBool aDeep, PRBool aNullParent)
 {
@@ -1430,23 +1423,16 @@ nsGenericHTMLElement::UnsetAttr(PRInt32 
       }
     }
   }
 
   return nsGenericHTMLElementBase::UnsetAttr(aNameSpaceID, aAttribute,
                                              aNotify);
 }
 
-nsresult
-nsGenericHTMLElement::WalkContentStyleRules(nsRuleWalker* aRuleWalker)
-{
-  mAttrsAndChildren.WalkMappedAttributeStyleRules(aRuleWalker);
-  return NS_OK;
-}
-
 already_AddRefed<nsIURI>
 nsGenericHTMLElement::GetBaseURI() const
 {
   nsIDocument* doc = GetOwnerDoc();
 
   void* prop;
   if (HasFlag(NODE_HAS_PROPERTIES) && (prop = GetProperty(nsGkAtoms::htmlBaseHref))) {
     nsIURI* uri = static_cast<nsIURI*>(prop);
@@ -1535,32 +1521,16 @@ nsGenericHTMLElement::IsAttributeMapped(
 {
   static const MappedAttributeEntry* const map[] = {
     sCommonAttributeMap
   };
   
   return FindAttributeDependence(aAttribute, map, NS_ARRAY_LENGTH(map));
 }
 
-PRBool
-nsGenericHTMLElement::SetMappedAttribute(nsIDocument* aDocument,
-                                         nsIAtom* aName,
-                                         nsAttrValue& aValue,
-                                         nsresult* aRetval)
-{
-  NS_PRECONDITION(aDocument == GetCurrentDoc(), "Unexpected document");
-  nsHTMLStyleSheet* sheet = aDocument ?
-    aDocument->GetAttributeStyleSheet() : nsnull;
-  
-  *aRetval = mAttrsAndChildren.SetAndTakeMappedAttr(aName, aValue,
-                                                    this, sheet);
-  return PR_TRUE;
-}
-
-
 nsMapRuleToAttributesFunc
 nsGenericHTMLElement::GetAttributeMappingFunction() const
 {
   return &MapCommonAttributesInto;
 }
 
 // static
 nsIFormControlFrame*
--- a/content/html/content/src/nsGenericHTMLElement.h
+++ b/content/html/content/src/nsGenericHTMLElement.h
@@ -33,48 +33,43 @@
  * 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 nsGenericHTMLElement_h___
 #define nsGenericHTMLElement_h___
 
-#include "nsStyledElement.h"
+#include "nsMappedAttributeElement.h"
 #include "nsIDOMHTMLElement.h"
 #include "nsINameSpaceManager.h"  // for kNameSpaceID_None
 #include "nsIFormControl.h"
 #include "nsIDOMNSHTMLFrameElement.h"
 #include "nsFrameLoader.h"
 #include "nsGkAtoms.h"
 
 class nsIDOMAttr;
 class nsIDOMEventListener;
 class nsIDOMNodeList;
 class nsIFrame;
-class nsMappedAttributes;
 class nsIStyleRule;
 class nsChildContentList;
 class nsDOMCSSDeclaration;
 class nsIDOMCSSStyleDeclaration;
 class nsIURI;
 class nsIFormControlFrame;
 class nsIForm;
 class nsPresState;
 class nsIScrollableView;
 class nsILayoutHistoryState;
 class nsIEditor;
 struct nsRect;
 struct nsSize;
-struct nsRuleData;
 
-typedef void (*nsMapRuleToAttributesFunc)(const nsMappedAttributes* aAttributes, 
-                                          nsRuleData* aData);
-
-typedef nsStyledElement nsGenericHTMLElementBase;
+typedef nsMappedAttributeElement nsGenericHTMLElementBase;
 
 /**
  * A common superclass for HTML elements
  */
 class nsGenericHTMLElement : public nsGenericHTMLElementBase
 {
 public:
   nsGenericHTMLElement(nsINodeInfo *aNodeInfo)
@@ -234,33 +229,28 @@ public:
   // Callers must hold a reference to nsHTMLUtils's global reference count.
   nsresult GetHrefURIForAnchors(nsIURI** aURI) const;
 
   // HTML element methods
   const nsAttrValue* GetParsedAttr(nsIAtom* aAttr) const
   {
     return mAttrsAndChildren.GetAttr(aAttr);
   }
-  virtual nsMapRuleToAttributesFunc GetAttributeMappingFunction() const;
 
   virtual void UpdateEditableState();
 
-  NS_IMETHOD WalkContentStyleRules(nsRuleWalker* aRuleWalker);
   already_AddRefed<nsIURI> GetBaseURI() const;
 
   virtual PRBool ParseAttribute(PRInt32 aNamespaceID,
                                 nsIAtom* aAttribute,
                                 const nsAString& aValue,
                                 nsAttrValue& aResult);
 
   NS_IMETHOD_(PRBool) IsAttributeMapped(const nsIAtom* aAttribute) const;
-  virtual PRBool SetMappedAttribute(nsIDocument* aDocument,
-                                    nsIAtom* aName,
-                                    nsAttrValue& aValue,
-                                    nsresult* aRetval);
+  virtual nsMapRuleToAttributesFunc GetAttributeMappingFunction() const;
 
   /**
    * Get the base target for any links within this piece
    * of content. Generally, this is the document's base target,
    * but certain content carries a local base for backward
    * compatibility.
    *
    * @param aBaseTarget the base target [OUT]
--- a/content/html/content/src/nsHTMLCanvasElement.cpp
+++ b/content/html/content/src/nsHTMLCanvasElement.cpp
@@ -282,19 +282,19 @@ nsHTMLCanvasElement::ParseAttribute(PRIn
 
 // nsHTMLCanvasElement::toDataURL
 
 NS_IMETHODIMP
 nsHTMLCanvasElement::ToDataURL(nsAString& aDataURL)
 {
   nsresult rv;
 
-  nsCOMPtr<nsIXPCNativeCallContext> ncc;
+  nsAXPCNativeCallContext *ncc = nsnull;
   rv = nsContentUtils::XPConnect()->
-    GetCurrentNativeCallContext(getter_AddRefs(ncc));
+    GetCurrentNativeCallContext(&ncc);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!ncc)
     return NS_ERROR_FAILURE;
 
   JSContext *ctx = nsnull;
 
   rv = ncc->GetJSContext(&ctx);
--- a/content/html/content/test/Makefile.in
+++ b/content/html/content/test/Makefile.in
@@ -68,44 +68,46 @@ include $(topsrcdir)/config/rules.mk
 		bug277724_iframe2.xhtml \
 		test_bug277724.html \
 		bug277890_iframe.html \
 		bug277890_load.html \
 		test_bug277890.html \
 		test_bug300691-1.html \
 		test_bug300691-2.html \
 		test_bug300691-3.xhtml \
-		bug340800_iframe.txt \
-		test_bug340800.html \
 		test_bug330705-1.html \
+		test_bug332246.html \
 		test_bug332893-1.html \
 		test_bug332893-2.html \
 		test_bug332893-3.html \
 		test_bug332893-4.html \
-		test_bug388558.html \
 		test_bug332893-5.html \
 		test_bug332893-6.html \
+		bug340800_iframe.txt \
+		test_bug340800.html \
 		test_bug353415-1.html \
 		test_bug353415-2.html \
 		test_bug371375.html \
 		test_bug373589.html \
 		bug372098-link-target.html \
 		test_bug372098.html \
 		test_bug375003-1.html \
 		test_bug375003-2.html \
 		test_bug384419.html \
 		test_bug386496.html \
 		test_bug386728.html \
 		test_bug386996.html \
+		test_bug388558.html \
 		test_bug388746.html \
 		test_bug389797.html \
 		test_bug390975.html \
 		test_bug391994.html \
 		test_bug392567.html \
 		bug392567.jar       \
 		bug392567.jar^headers^ \
 		test_bug394700.html \
 		test_bug395107.html \
 		test_bug401160.xhtml \
+		test_bug408231.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
--- a/content/html/content/test/test_bug332246.html
+++ b/content/html/content/test/test_bug332246.html
@@ -36,18 +36,25 @@ https://bugzilla.mozilla.org/show_bug.cg
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 332246 **/
 
 var a1 = document.getElementById('a1');
 var a2 = document.getElementById('a2');
 a2.scrollIntoView(true);
-  todo(a1.scrollTop == 100, "Wrong scrollTop value!"); //bug 401904
+//bug 401904 for windows, bug 411297 for the Mac
+if (navigator.platform == "Win32" || navigator.platform.indexOf("Mac") == 0)
+  todo(a1.scrollTop == 100, "Wrong scrollTop value!");
+else
+  ok(a1.scrollTop == 100, "Wrong scrollTop value!");
 a2.scrollIntoView(false);
+if (navigator.platform.indexOf("Mac") == 0) //Mac bug 411297 again
+  todo((a1.scrollHeight - a1.offsetHeight - a1.scrollTop) == 100, "Wrong (scrollHeight - offsetHeight - scrollTop) value!");
+else
   ok((a1.scrollHeight - a1.offsetHeight - a1.scrollTop) == 100, "Wrong (scrollHeight - offsetHeight - scrollTop) value!");
 
 var b1 = document.getElementById('b1');
 var b2 = document.getElementById('b2');
 b2.scrollIntoView(true);
   ok(b1.scrollTop == 100, "Wrong scrollTop value!");
 b2.scrollIntoView(false);
   ok((b1.scrollHeight - b1.offsetHeight - b1.scrollTop) == 100, "Wrong (scrollHeight - offsetHeight - scrollTop) value!");
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug408231.html
@@ -0,0 +1,199 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=408231
+-->
+<head>
+  <title>Test for Bug 408231</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=408231">Mozilla Bug 408231</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+
+/** Test for Bug 408231 **/
+
+    var commandEnabledResults = [
+      ["contentReadOnly", "true"],
+      ["copy", "false"],
+      ["createlink", "true"],
+      ["cut", "false"],
+      ["decreasefontsize", "true"],
+      ["delete", "false"],
+      ["fontname", "true"],
+      ["fontsize", "true"],
+      ["formatblock", "true"],
+      ["heading", "true"],
+      ["hilitecolor", "true"],
+      ["increasefontsize", "true"],
+      ["indent", "true"],
+      ["inserthorizontalrule", "true"],
+      ["inserthtml", "true"],
+      ["insertimage", "true"],
+      ["insertorderedlist", "true"],
+      ["insertunorderedlist", "true"],
+      ["insertparagraph", "true"],
+      ["italic", "true"],
+      ["justifycenter", "true"],
+      ["justifyfull", "true"],
+      ["justifyleft", "true"],
+      ["justifyright", "true"],
+      ["outdent", "false"],
+      //["paste", "true"],
+      ["redo", "false"],
+      ["removeformat", "true"],
+      ["selectall", "true"],
+      ["strikethrough", "true"],
+      ["styleWithCSS", "true"],
+      ["subscript", "true"],
+      ["superscript", "true"],
+      ["underline", "true"],
+      ["undo", "false"],
+      ["unlink", "true"],
+      ["not-a-command", "exception"]
+    ];
+    
+    var commandStateResults = [
+      ["contentReadOnly", "exception"],
+      ["copy", "exception"],
+      ["createlink", "exception"],
+      ["cut", "exception"],
+      ["decreasefontsize", "exception"],
+      ["delete", "exception"],
+      ["fontname", "exception"],
+      ["fontsize", "exception"],
+      ["formatblock", "exception"],
+      ["heading", "exception"],
+      ["hilitecolor", "exception"],
+      ["increasefontsize", "exception"],
+      ["indent", "exception"],
+      ["inserthorizontalrule", "exception"],
+      ["inserthtml", "exception"],
+      ["insertimage", "exception"],
+      ["insertorderedlist", "false"],
+      ["insertunorderedlist", "false"],
+      ["insertparagraph", "exception"],
+      ["italic", "false"],
+      ["justifycenter", "false"],
+      ["justifyfull", "false"],
+      ["justifyleft", "true"],
+      ["justifyright", "false"],
+      ["outdent", "exception"],
+      //["paste", "exception"],
+      ["redo", "exception"],
+      ["removeformat", "exception"],
+      ["selectall", "exception"],
+      ["strikethrough", "false"],
+      ["styleWithCSS", "exception"],
+      ["subscript", "false"],
+      ["superscript", "false"],
+      ["underline", "false"],
+      ["undo", "exception"],
+      ["unlink", "false"],
+      ["not-a-command", "exception"]
+    ];
+    
+    var commandValueResults = [
+      ["contentReadOnly", "exception"],
+      ["copy", ""],
+      ["createlink", ""],
+      ["cut", ""],
+      ["decreasefontsize", ""],
+      ["delete", ""],
+      ["fontname", ""],
+      ["fontsize", ""],
+      ["formatblock", ""],
+      ["heading", ""],
+      ["hilitecolor", "transparent"],
+      ["increasefontsize", ""],
+      ["indent", ""],
+      ["inserthorizontalrule", ""],
+      ["inserthtml", ""],
+      ["insertimage", ""],
+      ["insertorderedlist", ""],
+      ["insertunorderedlist", ""],
+      ["insertparagraph", ""],
+      ["italic", ""],
+      ["justifycenter", "left"],
+      ["justifyfull", "left"],
+      ["justifyleft", "left"],
+      ["justifyright", "left"],
+      ["outdent", ""],
+      //["paste", ""],
+      ["redo", ""],
+      ["removeformat", ""],
+      ["selectall", ""],
+      ["strikethrough", ""],
+      ["styleWithCSS", "exception"],
+      ["subscript", ""],
+      ["superscript", ""],
+      ["underline", ""],
+      ["undo", ""],
+      ["unlink", ""],
+      ["not-a-command", "exception"],
+    ];
+    
+  
+    function callQueryCommandEnabled(cmdName) {
+      var result;
+      try {
+        result = '' + document.queryCommandEnabled( cmdName );
+      } catch( error ) {
+        result = 'exception';
+      }
+      return result;
+    }
+    
+    function callQueryCommandState(cmdName) {
+      var result;
+      try {
+        result = '' + document.queryCommandState( cmdName );
+      } catch( error ) {
+        result = 'exception';
+      }
+      return result;
+    }
+
+    function callQueryCommandValue(cmdName) {
+      var result;
+      try {
+        result = '' + document.queryCommandValue( cmdName );
+      } catch( error ) {
+        result = 'exception';
+      }
+      return result;    
+    }
+
+    function testQueryCommand(expectedResults, fun, funName) {
+      for (i=0; i<expectedResults.length; i++) {
+        var commandName = expectedResults[i][0];
+        var expectedResult = expectedResults[i][1];
+        var result = fun(commandName);
+        ok(result == expectedResult, funName + '('+commandName+') result=' +result+ ' expected=' + expectedResult);
+      }
+    }
+
+    function runTests() {
+      document.designMode='on';
+      testQueryCommand(commandEnabledResults, callQueryCommandEnabled, "queryCommandEnabled");
+      testQueryCommand(commandStateResults, callQueryCommandState, "queryCommandState");
+      testQueryCommand(commandValueResults, callQueryCommandValue, "queryCommandValue");
+      document.designMode='off';
+      SimpleTest.finish();
+    }
+    
+    window.onload = runTests;
+    SimpleTest.waitForExplicitFinish();
+
+</script>
+</pre>
+</body>
+</html>
+
new file mode 100644
--- /dev/null
+++ b/content/html/document/crashtests/407053.html
@@ -0,0 +1,6 @@
+<!DOCTYPE html>
+<html>
+<body onload="document.execCommand('copy', false, '');">
+<div contenteditable="true"></div>
+</body>
+</html>
--- a/content/html/document/crashtests/crashtests.list
+++ b/content/html/document/crashtests/crashtests.list
@@ -1,1 +1,2 @@
 load 388183-1.html
+load 407053.html
--- a/content/html/document/src/nsHTMLContentSink.cpp
+++ b/content/html/document/src/nsHTMLContentSink.cpp
@@ -2341,16 +2341,17 @@ HTMLContentSink::OpenContainer(const nsI
     case eHTMLTag_html:
       if (mRoot) {
         // If we've already hit this code once, need to check for
         // already-present attributes on the root.
         AddAttributes(aNode, mRoot, PR_TRUE, mNotifiedRootInsertion);
         if (!mNotifiedRootInsertion) {
           NotifyRootInsertion();
         }
+        ProcessOfflineManifest(mRoot);
       }
       break;
     case eHTMLTag_form:
       rv = OpenForm(aNode);
       break;
     default:
       rv = mCurrentContext->OpenContainer(aNode);
       break;
@@ -2987,23 +2988,16 @@ HTMLContentSink::ProcessLINKTag(const ns
         PRBool hasPrefetch = (linkTypes.IndexOf(NS_LITERAL_STRING("prefetch")) != -1);
         if (hasPrefetch || linkTypes.IndexOf(NS_LITERAL_STRING("next")) != -1) {
           nsAutoString hrefVal;
           element->GetAttr(kNameSpaceID_None, nsGkAtoms::href, hrefVal);
           if (!hrefVal.IsEmpty()) {
             PrefetchHref(hrefVal, element, hasPrefetch);
           }
         }
-        if (linkTypes.IndexOf(NS_LITERAL_STRING("offline-resource")) != -1) {
-          nsAutoString hrefVal;
-          element->GetAttr(kNameSpaceID_None, nsGkAtoms::href, hrefVal);
-          if (!hrefVal.IsEmpty()) {
-            AddOfflineResource(hrefVal, element);
-          }
-        }
       }
     }
   }
 
   return result;
 }
 
 #ifdef DEBUG
--- a/content/html/document/src/nsHTMLDocument.cpp
+++ b/content/html/document/src/nsHTMLDocument.cpp
@@ -166,16 +166,31 @@ const PRInt32 kBackward = 1;
 // Returns the name atom of aContent, if the content is a named item
 // and has a name atom.
 static nsIAtom* IsNamedItem(nsIContent* aContent);
 
 static NS_DEFINE_CID(kCParserCID, NS_PARSER_CID);
 
 PRUint32       nsHTMLDocument::gWyciwygSessionCnt = 0;
 
+// this function will return false if the command is not recognized
+// inCommandID will be converted as necessary for internal operations
+// inParam will be converted as necessary for internal operations
+// outParam will be Empty if no parameter is needed or if returning a boolean
+// outIsBoolean will determine whether to send param as a boolean or string
+// outBooleanParam will not be set unless outIsBoolean
+static PRBool ConvertToMidasInternalCommand(const nsAString & inCommandID,
+                                            const nsAString & inParam,
+                                            nsACString& outCommandID,
+                                            nsACString& outParam,
+                                            PRBool& isBoolean,
+                                            PRBool& boolValue);
+
+static PRBool ConvertToMidasInternalCommand(const nsAString & inCommandID,
+                                            nsACString& outCommandID);
 static int PR_CALLBACK
 MyPrefChangedCallback(const char*aPrefName, void* instance_data)
 {
   const nsAdoptingString& detector_name =
     nsContentUtils::GetLocalizedStringPref("intl.charset.detector");
 
   if (detector_name.Length() > 0) {
     PL_strncpy(g_detector_contractid, NS_CHARSET_DETECTOR_CONTRACTID_BASE,
@@ -2465,20 +2480,20 @@ NS_IMETHODIMP
 nsHTMLDocument::Writeln(const nsAString& aText)
 {
   return WriteCommon(aText, PR_TRUE);
 }
 
 nsresult
 nsHTMLDocument::ScriptWriteCommon(PRBool aNewlineTerminate)
 {
-  nsCOMPtr<nsIXPCNativeCallContext> ncc;
+  nsAXPCNativeCallContext *ncc = nsnull;
 
   nsresult rv = nsContentUtils::XPConnect()->
-    GetCurrentNativeCallContext(getter_AddRefs(ncc));
+    GetCurrentNativeCallContext(&ncc);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (ncc) {
     // We're called from JS, concatenate the extra arguments into
     // string_buffer
     PRUint32 i, argc;
 
     ncc->GetArgc(&argc);
@@ -4209,30 +4224,24 @@ static const char* const gBlocks[] = {
   "H3",
   "H4",
   "H5",
   "H6",
   "P",
   "PRE"
 };
 
-
-// this function will return false if the command is not recognized
-// inCommandID will be converted as necessary for internal operations
-// inParam will be converted as necessary for internal operations
-// outParam will be Empty if no parameter is needed or if returning a boolean
-// outIsBoolean will determine whether to send param as a boolean or string
-// outBooleanParam will not be set unless outIsBoolean
-PRBool
-nsHTMLDocument::ConvertToMidasInternalCommand(const nsAString & inCommandID,
-                                              const nsAString & inParam,
-                                              nsACString& outCommandID,
-                                              nsACString& outParam,
-                                              PRBool& outIsBoolean,
-                                              PRBool& outBooleanValue)
+static PRBool
+ConvertToMidasInternalCommandInner(const nsAString & inCommandID,
+                                   const nsAString & inParam,
+                                   nsACString& outCommandID,
+                                   nsACString& outParam,
+                                   PRBool& outIsBoolean,
+                                   PRBool& outBooleanValue,
+                                   PRBool aIgnoreParams)
 {
   NS_ConvertUTF16toUTF8 convertedCommandID(inCommandID);
 
   // Hack to support old boolean commands that were backwards (see bug 301490).
   PRBool invertBool = PR_FALSE;
   if (convertedCommandID.LowerCaseEqualsLiteral("usecss")) {
     convertedCommandID.Assign("styleWithCSS");
     invertBool = PR_TRUE;
@@ -4254,71 +4263,98 @@ nsHTMLDocument::ConvertToMidasInternalCo
 
   if (found) {
     // set outCommandID (what we use internally)
     outCommandID.Assign(gMidasCommandTable[i].internalCommandString);
 
     // set outParam & outIsBoolean based on flags from the table
     outIsBoolean = gMidasCommandTable[i].convertToBoolean;
 
-    if (gMidasCommandTable[i].useNewParam) {
-      outParam.Assign(gMidasCommandTable[i].internalParamString);
-    }
-    else {
-      // handle checking of param passed in
-      if (outIsBoolean) {
-        // if this is a boolean value and it's not explicitly false
-        // (e.g. no value) we default to "true". For old backwards commands
-        // we invert the check (see bug 301490).
-        if (invertBool) {
-          outBooleanValue = inParam.LowerCaseEqualsLiteral("false");
-        }
-        else {
-          outBooleanValue = !inParam.LowerCaseEqualsLiteral("false");
-        }
-        outParam.Truncate();
+    if (!aIgnoreParams) {
+      if (gMidasCommandTable[i].useNewParam) {
+        outParam.Assign(gMidasCommandTable[i].internalParamString);
       }
       else {
-        // check to see if we need to convert the parameter
-        if (outCommandID.EqualsLiteral("cmd_paragraphState")) {
-          const PRUnichar *start = inParam.BeginReading();
-          const PRUnichar *end = inParam.EndReading();
-          if (start != end && *start == '<' && *(end - 1) == '>') {
-            ++start;
-            --end;
+        // handle checking of param passed in
+        if (outIsBoolean) {
+          // if this is a boolean value and it's not explicitly false
+          // (e.g. no value) we default to "true". For old backwards commands
+          // we invert the check (see bug 301490).
+          if (invertBool) {
+            outBooleanValue = inParam.LowerCaseEqualsLiteral("false");
           }
-
-          NS_ConvertUTF16toUTF8 convertedParam(Substring(start, end));
-          PRUint32 j;
-          for (j = 0; j < NS_ARRAY_LENGTH(gBlocks); ++j) {
-            if (convertedParam.Equals(gBlocks[j],
-                                      nsCaseInsensitiveCStringComparator())) {
-              outParam.Assign(gBlocks[j]);
-              break;
-            }
+          else {
+            outBooleanValue = !inParam.LowerCaseEqualsLiteral("false");
           }
-
-          return j != NS_ARRAY_LENGTH(gBlocks);
+          outParam.Truncate();
         }
         else {
-          CopyUTF16toUTF8(inParam, outParam);
+          // check to see if we need to convert the parameter
+          if (outCommandID.EqualsLiteral("cmd_paragraphState")) {
+            const PRUnichar *start = inParam.BeginReading();
+            const PRUnichar *end = inParam.EndReading();
+            if (start != end && *start == '<' && *(end - 1) == '>') {
+              ++start;
+              --end;
+            }
+
+            NS_ConvertUTF16toUTF8 convertedParam(Substring(start, end));
+            PRUint32 j;
+            for (j = 0; j < NS_ARRAY_LENGTH(gBlocks); ++j) {
+              if (convertedParam.Equals(gBlocks[j],
+                                        nsCaseInsensitiveCStringComparator())) {
+                outParam.Assign(gBlocks[j]);
+                break;
+              }
+            }
+
+            return j != NS_ARRAY_LENGTH(gBlocks);
+          }
+          else {
+            CopyUTF16toUTF8(inParam, outParam);
+          }
         }
       }
     }
   } // end else for useNewParam (do convert existing param)
   else {
     // reset results if the command is not found in our table
     outCommandID.SetLength(0);
     outParam.SetLength(0);
     outIsBoolean = PR_FALSE;
   }
 
   return found;
 }
 
+static PRBool
+ConvertToMidasInternalCommand(const nsAString & inCommandID,
+                              const nsAString & inParam,
+                              nsACString& outCommandID,
+                              nsACString& outParam,
+                              PRBool& outIsBoolean,
+                              PRBool& outBooleanValue)
+{
+  return ConvertToMidasInternalCommandInner(inCommandID, inParam, outCommandID,
+                                            outParam, outIsBoolean,
+                                            outBooleanValue, PR_FALSE);
+}
+
+static PRBool
+ConvertToMidasInternalCommand(const nsAString & inCommandID,
+                              nsACString& outCommandID)
+{
+  nsCAutoString dummyCString;
+  nsAutoString dummyString;
+  PRBool dummyBool;
+  return ConvertToMidasInternalCommandInner(inCommandID, dummyString,
+                                            outCommandID, dummyCString,
+                                            dummyBool, dummyBool, PR_TRUE);
+}
+
 jsval
 nsHTMLDocument::sCutCopyInternal_id = JSVAL_VOID;
 jsval
 nsHTMLDocument::sPasteInternal_id = JSVAL_VOID;
 
 /* Helper function to check security of clipboard commands. If aPaste is */
 /* true, we check paste, else we check cutcopy */
 nsresult
@@ -4327,16 +4363,21 @@ nsHTMLDocument::DoClipboardSecurityCheck
   nsresult rv = NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIJSContextStack> stack =
     do_GetService("@mozilla.org/js/xpc/ContextStack;1");
 
   if (stack) {
     JSContext *cx = nsnull;
     stack->Peek(&cx);
+    if (!cx) {
+      return NS_OK;
+    }
+
+    JSAutoRequest ar(cx);
 
     NS_NAMED_LITERAL_CSTRING(classNameStr, "Clipboard");
 
     nsIScriptSecurityManager *secMan = nsContentUtils::GetSecurityManager();
 
     if (aPaste) {
       if (nsHTMLDocument::sPasteInternal_id == JSVAL_VOID) {
         nsHTMLDocument::sPasteInternal_id =
@@ -4474,19 +4515,17 @@ nsHTMLDocument::QueryCommandEnabled(cons
   if (!cmdMgr)
     return NS_ERROR_FAILURE;
 
   nsIDOMWindow *window = GetWindow();
   if (!window)
     return NS_ERROR_FAILURE;
 
   nsCAutoString cmdToDispatch, paramStr;
-  PRBool isBool, boolVal;
-  if (!ConvertToMidasInternalCommand(commandID, commandID,
-                                     cmdToDispatch, paramStr, isBool, boolVal))
+  if (!ConvertToMidasInternalCommand(commandID, cmdToDispatch))
     return NS_ERROR_NOT_IMPLEMENTED;
 
   return cmdMgr->IsCommandEnabled(cmdToDispatch.get(), window, _retval);
 }
 
 /* boolean queryCommandIndeterm (in DOMString commandID); */
 NS_IMETHODIMP
 nsHTMLDocument::QueryCommandIndeterm(const nsAString & commandID,
@@ -4637,19 +4676,17 @@ nsHTMLDocument::QueryCommandValue(const 
   if (!cmdMgr)
     return NS_ERROR_FAILURE;
 
   nsIDOMWindow *window = GetWindow();
   if (!window)
     return NS_ERROR_FAILURE;
 
   nsCAutoString cmdToDispatch, paramStr;
-  PRBool isBool, boolVal;
-  if (!ConvertToMidasInternalCommand(commandID, commandID,
-                                     cmdToDispatch, paramStr, isBool, boolVal))
+  if (!ConvertToMidasInternalCommand(commandID, cmdToDispatch))
     return NS_ERROR_NOT_IMPLEMENTED;
 
   // create params
   nsresult rv;
   nsCOMPtr<nsICommandParams> cmdParams = do_CreateInstance(
                                            NS_COMMAND_PARAMS_CONTRACTID, &rv);
   if (!cmdParams)
     return NS_ERROR_OUT_OF_MEMORY;
--- a/content/html/document/src/nsHTMLDocument.h
+++ b/content/html/document/src/nsHTMLDocument.h
@@ -357,22 +357,17 @@ protected:
    *    ones if IdTableIsLive() is true.
    */
   PLDHashTable mIdAndNameHashTable;
 
   nsCOMPtr<nsIWyciwygChannel> mWyciwygChannel;
 
   /* Midas implementation */
   nsresult   GetMidasCommandManager(nsICommandManager** aCommandManager);
-  PRBool     ConvertToMidasInternalCommand(const nsAString & inCommandID,
-                                           const nsAString & inParam,
-                                           nsACString& outCommandID,
-                                           nsACString& outParam,
-                                           PRBool& isBoolean,
-                                           PRBool& boolValue);
+
   nsCOMPtr<nsICommandManager> mMidasCommandManager;
 
   nsresult TurnEditingOff();
   nsresult EditingStateChanged();
 
   PRUint32 mContentEditableCount;
   EditingState mEditingState;
 
--- a/content/html/document/src/nsImageDocument.cpp
+++ b/content/html/document/src/nsImageDocument.cpp
@@ -603,17 +603,17 @@ nsImageDocument::CreateSyntheticDocument
 
   return NS_OK;
 }
 
 nsresult
 nsImageDocument::CheckOverflowing(PRBool changeState)
 {
   /* Create a scope so that the style context gets destroyed before we might
-   * call ClearStyleDataAndReflow.  Also, holding onto pointers to the
+   * call RebuildStyleData.  Also, holding onto pointers to the
    * presentatation through style resolution is potentially dangerous.
    */
   {
     nsIPresShell *shell = GetPrimaryShell();
     if (!shell) {
       return NS_OK;
     }
 
new file mode 100644
--- /dev/null
+++ b/content/mathml/Makefile.in
@@ -0,0 +1,47 @@
+#
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is mozilla.org code.
+#
+# The Initial Developer of the Original Code is
+# Netscape Communications Corporation.
+# Portions created by the Initial Developer are Copyright (C) 1998
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either of the GNU General Public License Version 2 or later (the "GPL"),
+# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+DEPTH		= ../..
+topsrcdir	= @top_srcdir@
+srcdir		= @srcdir@
+VPATH		= @srcdir@
+
+include $(DEPTH)/config/autoconf.mk
+
+DIRS		= content
+
+include $(topsrcdir)/config/rules.mk
new file mode 100644
--- /dev/null
+++ b/content/mathml/content/Makefile.in
@@ -0,0 +1,48 @@
+#
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is mozilla.org code.
+#
+# The Initial Developer of the Original Code is
+# Netscape Communications Corporation.
+# Portions created by the Initial Developer are Copyright (C) 1998
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either of the GNU General Public License Version 2 or later (the "GPL"),
+# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+DEPTH		= ../../..
+topsrcdir	= @top_srcdir@
+srcdir		= @srcdir@
+VPATH		= @srcdir@
+
+include $(DEPTH)/config/autoconf.mk
+
+DIRS		= src
+
+include $(topsrcdir)/config/rules.mk
+
new file mode 100644
--- /dev/null
+++ b/content/mathml/content/src/Makefile.in
@@ -0,0 +1,87 @@
+#
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is Mozilla MathML DOM code.
+#
+# The Initial Developer of the Original Code is
+# mozilla.org.
+# Portions created by the Initial Developer are Copyright (C) 2007
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#   Vlad Sukhoy <vladimir.sukhoy@gmail.com> (original developer)
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either of the GNU General Public License Version 2 or later (the "GPL"),
+# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+DEPTH		= ../../../..
+topsrcdir	= @top_srcdir@
+srcdir		= @srcdir@
+VPATH		= @srcdir@
+
+include $(DEPTH)/config/autoconf.mk
+
+MODULE		= content
+LIBRARY_NAME	= gkcontentmathml_s
+LIBXUL_LIBRARY	= 1
+REQUIRES	= xpcom       \
+		  string      \
+		  layout      \
+		  content     \
+		  widget      \
+		  gfx         \
+		  dom         \
+		  js          \
+		  locale      \
+		  pref        \
+		  webshell    \
+		  unicharutil \
+		  docshell    \
+		  thebes      \
+		  $(NULL)
+
+CPPSRCS		= \
+		nsMathMLElement.cpp               \
+		nsMathMLElementFactory.cpp        \
+		$(NULL)
+
+include $(topsrcdir)/config/config.mk
+
+# we don't want the shared lib, but we want to force the creation of a static 
+# lib.
+FORCE_STATIC_LIB = 1
+
+EXPORTS = \
+	$(NULL)
+
+
+include $(topsrcdir)/config/rules.mk
+
+INCLUDES += 	\
+		-I$(srcdir)/../../../shared/public \
+		-I$(srcdir)/../../../base/src \
+		$(NULL)
+
+DEFINES += -D_IMPL_NS_LAYOUT
new file mode 100644
--- /dev/null
+++ b/content/mathml/content/src/nsMathMLElement.cpp
@@ -0,0 +1,457 @@
+/* -*- 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 MathML DOM code.
+ *
+ * The Initial Developer of the Original Code is
+ * mozilla.org.
+ * Portions created by the Initial Developer are Copyright (C) 2007
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *    Vlad Sukhoy <vladimir.sukhoy@gmail.com> (original developer)
+ *    Daniel Kraft <d@domob.eu> (nsMathMLElement patch, attachment 262925)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "nsMathMLElement.h"
+#include "nsDOMClassInfoID.h" // for eDOMClassInfo_MathElement_id.
+#include "nsGkAtoms.h"
+#include "nsCRT.h"
+#include "nsRuleData.h"
+#include "nsCSSValue.h"
+#include "nsMappedAttributes.h"
+#include "nsStyleConsts.h"
+#include "nsIDocument.h"
+#include "nsIEventStateManager.h"
+#include "nsPresShellIterator.h"
+#include "nsIPresShell.h"
+#include "nsPresContext.h"
+#include "nsDOMClassInfoID.h"
+
+//----------------------------------------------------------------------
+// nsISupports methods:
+
+NS_IMETHODIMP 
+nsMathMLElement::QueryInterface(REFNSIID aIID, void** aInstancePtr)
+{
+  NS_PRECONDITION(aInstancePtr, "null out param");
+
+  nsresult rv = nsMathMLElementBase::QueryInterface(aIID, aInstancePtr);
+
+  if (NS_SUCCEEDED(rv))
+    return rv;
+
+  nsISupports *inst = nsnull;
+
+  if (aIID.Equals(NS_GET_IID(nsIDOMNode))) {
+    inst = static_cast<nsIDOMNode *>(this);
+  } else if (aIID.Equals(NS_GET_IID(nsIDOMElement))) {
+    inst = static_cast<nsIDOMElement *>(this);
+  } else if (aIID.Equals(NS_GET_IID(nsIClassInfo))) {
+    inst = NS_GetDOMClassInfoInstance(eDOMClassInfo_Element_id);
+    NS_ENSURE_TRUE(inst, NS_ERROR_OUT_OF_MEMORY);
+  } else {
+    return PostQueryInterface(aIID, aInstancePtr);
+  }
+
+  NS_ADDREF(inst);
+
+  *aInstancePtr = inst;
+
+  return NS_OK;
+}
+
+NS_IMPL_ADDREF_INHERITED(nsMathMLElement, nsMathMLElementBase)
+NS_IMPL_RELEASE_INHERITED(nsMathMLElement, nsMathMLElementBase)
+
+nsresult
+nsMathMLElement::BindToTree(nsIDocument* aDocument, nsIContent* aParent,
+                            nsIContent* aBindingParent,
+                            PRBool aCompileEventHandlers)
+{
+  static const char kMathMLStyleSheetURI[] = "resource://gre/res/mathml.css";
+
+  nsresult rv = nsMathMLElementBase::BindToTree(aDocument, aParent,
+                                                aBindingParent,
+                                                aCompileEventHandlers);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  if (aDocument && !aDocument->GetMathMLEnabled()) {
+    // Enable MathML and setup the style sheet during binding, not element
+    // construction, because we could move a MathML element from the document
+    // that created it to another document.
+    aDocument->SetMathMLEnabled();
+    aDocument->EnsureCatalogStyleSheet(kMathMLStyleSheetURI);
+
+    // Rebuild style data for all the presshells, because style system
+    // optimizations may have taken place assuming MathML was disabled.
+    // (See nsRuleNode::CheckSpecifiedProperties.)
+    // nsPresShellIterator skips hidden presshells, but that's OK because
+    // if we're changing the document for one of those presshells the whole
+    // presshell will be torn down.
+    nsPresShellIterator iter(aDocument);
+    nsCOMPtr<nsIPresShell> shell;
+    while ((shell = iter.GetNextShell()) != nsnull) {
+      shell->GetPresContext()->PostRebuildAllStyleDataEvent();
+    }
+  }
+
+  return rv;
+}
+
+PRBool
+nsMathMLElement::ParseAttribute(PRInt32 aNamespaceID,
+                                nsIAtom* aAttribute,
+                                const nsAString& aValue,
+                                nsAttrValue& aResult)
+{
+  if (aNamespaceID == kNameSpaceID_None) {
+    if (aAttribute == nsGkAtoms::color ||
+        aAttribute == nsGkAtoms::mathcolor_ ||
+        aAttribute == nsGkAtoms::background ||
+        aAttribute == nsGkAtoms::mathbackground_) {
+      return aResult.ParseColor(aValue, GetOwnerDoc());
+    }
+  }
+
+  return nsMathMLElementBase::ParseAttribute(aNamespaceID, aAttribute,
+                                             aValue, aResult);
+}
+
+static nsGenericElement::MappedAttributeEntry sTokenStyles[] = {
+  { &nsGkAtoms::mathsize_ },
+  { &nsGkAtoms::fontsize_ },
+  { &nsGkAtoms::mathcolor_ },
+  { &nsGkAtoms::color },
+  { &nsGkAtoms::mathbackground_ },
+  { &nsGkAtoms::fontfamily_ },
+  { nsnull }
+};
+
+static nsGenericElement::MappedAttributeEntry sEnvironmentStyles[] = {
+  { &nsGkAtoms::scriptlevel_ },
+  { &nsGkAtoms::scriptminsize_ },
+  { &nsGkAtoms::scriptsizemultiplier_ },
+  { &nsGkAtoms::background },
+  { nsnull }
+};
+
+PRBool
+nsMathMLElement::IsAttributeMapped(const nsIAtom* aAttribute) const
+{
+  static const MappedAttributeEntry* const tokenMap[] = {
+    sTokenStyles
+  };
+  static const MappedAttributeEntry* const mstyleMap[] = {
+    sTokenStyles,
+    sEnvironmentStyles
+  };
+  
+  // We don't support mglyph (yet).
+  nsIAtom* tag = Tag();
+  if (tag == nsGkAtoms::ms_ || tag == nsGkAtoms::mi_ ||
+      tag == nsGkAtoms::mn_ || tag == nsGkAtoms::mo_ ||
+      tag == nsGkAtoms::mtext_)
+    return FindAttributeDependence(aAttribute, tokenMap,
+                                   NS_ARRAY_LENGTH(tokenMap));
+  if (tag == nsGkAtoms::mstyle_)
+    return FindAttributeDependence(aAttribute, mstyleMap,
+                                   NS_ARRAY_LENGTH(mstyleMap));
+  return PR_FALSE;
+}
+
+nsMapRuleToAttributesFunc
+nsMathMLElement::GetAttributeMappingFunction() const
+{
+  // It doesn't really matter what our tag is here, because only attributes
+  // that satisfy IsAttributeMapped will be stored in the mapped attributes
+  // list and available to the mapping function
+  return &MapMathMLAttributesInto;
+}
+
+// ================
+// Utilities for parsing and retrieving numeric values
+
+/*
+The REC says:
+  An explicit plus sign ('+') is not allowed as part of a numeric value
+  except when it is specifically listed in the syntax (as a quoted '+'
+  or "+"),
+
+  Units allowed
+  ID  Description
+  em  ems (font-relative unit traditionally used for horizontal lengths)
+  ex  exs (font-relative unit traditionally used for vertical lengths)
+  px  pixels, or pixel size of a "typical computer display"
+  in  inches (1 inch = 2.54 centimeters)
+  cm  centimeters
+  mm  millimeters
+  pt  points (1 point = 1/72 inch)
+  pc  picas (1 pica = 12 points)
+  %   percentage of default value
+
+Implementation here:
+  The numeric value is valid only if it is of the form [-] nnn.nnn
+  [h/v-unit]
+*/
+
+/* static */ PRBool
+nsMathMLElement::ParseNumericValue(const nsString& aString,
+                                   nsCSSValue&     aCSSValue,
+                                   PRBool          aRequireLengthUnit)
+{
+  nsAutoString str(aString);
+  str.CompressWhitespace(); // aString is const in this code...
+
+  PRInt32 stringLength = str.Length();
+  if (!stringLength)
+    return PR_FALSE;
+
+  nsAutoString number, unit;
+
+  // see if the negative sign is there
+  PRInt32 i = 0;
+  PRUnichar c = str[0];
+  if (c == '-') {
+    number.Append(c);
+    i++;
+
+    // skip any space after the negative sign
+    if (i < stringLength && nsCRT::IsAsciiSpace(str[i]))
+      i++;
+  }
+
+  // Gather up characters that make up the number
+  PRBool gotDot = PR_FALSE;
+  for ( ; i < stringLength; i++) {
+    c = str[i];
+    if (gotDot && c == '.')
+      return PR_FALSE;  // two dots encountered
+    else if (c == '.')
+      gotDot = PR_TRUE;
+    else if (!nsCRT::IsAsciiDigit(c)) {
+      str.Right(unit, stringLength - i);
+      // some authors leave blanks before the unit, but that shouldn't
+      // be allowed, so don't CompressWhitespace on 'unit'.
+      break;
+    }
+    number.Append(c);
+  }
+
+  // Convert number to floating point
+  PRInt32 errorCode;
+  float floatValue = number.ToFloat(&errorCode);
+  if (NS_FAILED(errorCode))
+    return PR_FALSE;
+
+  nsCSSUnit cssUnit;
+  if (unit.IsEmpty()) {
+    if (aRequireLengthUnit) {
+      // We are supposed to have a length unit, but there isn't one.
+      // If the value is 0 we can just call it "pixels" otherwise
+      // this is illegal.
+      if (floatValue != 0.0)
+        return PR_FALSE;
+      cssUnit = eCSSUnit_Pixel;
+    } else {
+      // no explicit unit, this is a number that will act as a multiplier
+      cssUnit = eCSSUnit_Number;
+    }
+  }
+  else if (unit.EqualsLiteral("%")) {
+    aCSSValue.SetPercentValue(floatValue / 100.0f);
+    return PR_TRUE;
+  }
+  else if (unit.EqualsLiteral("em")) cssUnit = eCSSUnit_EM;
+  else if (unit.EqualsLiteral("ex")) cssUnit = eCSSUnit_XHeight;
+  else if (unit.EqualsLiteral("px")) cssUnit = eCSSUnit_Pixel;
+  else if (unit.EqualsLiteral("in")) cssUnit = eCSSUnit_Inch;
+  else if (unit.EqualsLiteral("cm")) cssUnit = eCSSUnit_Centimeter;
+  else if (unit.EqualsLiteral("mm")) cssUnit = eCSSUnit_Millimeter;
+  else if (unit.EqualsLiteral("pt")) cssUnit = eCSSUnit_Point;
+  else if (unit.EqualsLiteral("pc")) cssUnit = eCSSUnit_Pica;
+  else // unexpected unit
+    return PR_FALSE;
+
+  aCSSValue.SetFloatValue(floatValue, cssUnit);
+  return PR_TRUE;
+}
+
+void
+nsMathMLElement::MapMathMLAttributesInto(const nsMappedAttributes* aAttributes,
+                                         nsRuleData* aData)
+{
+  if (aData->mSIDs & NS_STYLE_INHERIT_BIT(Font)) {
+    const nsAttrValue* value =
+      aAttributes->GetAttr(nsGkAtoms::scriptsizemultiplier_);
+    if (value && value->Type() == nsAttrValue::eString &&
+        aData->mFontData->mScriptSizeMultiplier.GetUnit() == eCSSUnit_Null) {
+      nsAutoString str(value->GetStringValue());
+      str.CompressWhitespace();
+      // MathML numbers can't have leading '+'
+      if (str.Length() > 0 && str.CharAt(0) != '+') {
+        PRInt32 errorCode;
+        float floatValue = str.ToFloat(&errorCode);
+        // Negative scriptsizemultipliers are not parsed
+        if (NS_SUCCEEDED(errorCode) && floatValue >= 0.0f) {
+          aData->mFontData->mScriptSizeMultiplier.
+            SetFloatValue(floatValue, eCSSUnit_Number);
+        }
+      }
+    }
+
+    value = aAttributes->GetAttr(nsGkAtoms::scriptminsize_);
+    if (value && value->Type() == nsAttrValue::eString &&
+        aData->mFontData->mScriptMinSize.GetUnit() == eCSSUnit_Null) {
+      ParseNumericValue(value->GetStringValue(),
+                        aData->mFontData->mScriptMinSize, PR_TRUE);
+    }
+
+    value = aAttributes->GetAttr(nsGkAtoms::scriptlevel_);
+    if (value && value->Type() == nsAttrValue::eString &&
+        aData->mFontData->mScriptLevel.GetUnit() == eCSSUnit_Null) {
+      nsAutoString str(value->GetStringValue());
+      str.CompressWhitespace();
+      if (str.Length() > 0) {
+        PRInt32 errorCode;
+        PRInt32 intValue = str.ToInteger(&errorCode);
+        if (NS_SUCCEEDED(errorCode)) {
+          // This is kind of cheesy ... if the scriptlevel has a sign,
+          // then it's a relative value and we store the nsCSSValue as an
+          // Integer to indicate that. Otherwise we store it as a Number
+          // to indicate that the scriptlevel is absolute.
+          PRUnichar ch = str.CharAt(0);
+          if (ch == '+' || ch == '-') {
+            aData->mFontData->mScriptLevel.SetIntValue(intValue, eCSSUnit_Integer);
+          } else {
+            aData->mFontData->mScriptLevel.SetFloatValue(intValue, eCSSUnit_Number);
+          }
+        }
+      }
+    }
+
+    PRBool parseSizeKeywords = PR_TRUE;
+    value = aAttributes->GetAttr(nsGkAtoms::mathsize_);
+    if (!value) {
+      parseSizeKeywords = PR_FALSE;
+      value = aAttributes->GetAttr(nsGkAtoms::fontsize_);
+    }
+    if (value && value->Type() == nsAttrValue::eString &&
+        aData->mFontData->mSize.GetUnit() == eCSSUnit_Null) {
+      nsAutoString str(value->GetStringValue());
+      if (!ParseNumericValue(str, aData->mFontData->mSize, PR_TRUE) &&
+          parseSizeKeywords) {
+        static const char sizes[3][7] = { "small", "normal", "big" };
+        static const PRInt32 values[NS_ARRAY_LENGTH(sizes)] = {
+          NS_STYLE_FONT_SIZE_SMALL, NS_STYLE_FONT_SIZE_MEDIUM,
+          NS_STYLE_FONT_SIZE_LARGE
+        };
+        str.CompressWhitespace();
+        for (PRInt32 i = 0; i < NS_ARRAY_LENGTH(sizes); ++i) {
+          if (str.EqualsASCII(sizes[i])) {
+            aData->mFontData->mSize.SetIntValue(values[i], eCSSUnit_Enumerated);
+            break;
+          }
+        }
+      }
+    }
+
+    value = aAttributes->GetAttr(nsGkAtoms::fontfamily_);
+    if (value && value->Type() == nsAttrValue::eString &&
+        aData->mFontData->mFamily.GetUnit() == eCSSUnit_Null) {
+      aData->mFontData->mFamily.SetStringValue(value->GetStringValue(),
+                                               eCSSUnit_String);
+      aData->mFontData->mFamilyFromHTML = PR_FALSE;
+    }
+  }
+
+  if (aData->mSIDs & NS_STYLE_INHERIT_BIT(Background)) {
+    const nsAttrValue* value =
+      aAttributes->GetAttr(nsGkAtoms::mathbackground_);
+    if (!value) {
+      value = aAttributes->GetAttr(nsGkAtoms::background);
+    }
+    if (value && aData->mColorData->mBackColor.GetUnit() == eCSSUnit_Null) {
+      nscolor color;
+      if (value->GetColorValue(color)) {
+        aData->mColorData->mBackColor.SetColorValue(color);
+      } else {
+        nsAutoString str(value->GetStringValue());
+        str.CompressWhitespace();
+        if (str.EqualsLiteral("transparent")) {
+          aData->mColorData->mBackColor.SetColorValue(NS_RGBA(0,0,0,0));
+        }
+      }
+    }
+  }
+
+  if (aData->mSIDs & NS_STYLE_INHERIT_BIT(Color)) {
+    const nsAttrValue* value = aAttributes->GetAttr(nsGkAtoms::mathcolor_);
+    if (!value) {
+      value = aAttributes->GetAttr(nsGkAtoms::color);
+    }
+    nscolor color;
+    if (value && value->GetColorValue(color) &&
+        aData->mColorData->mColor.GetUnit() == eCSSUnit_Null) {
+      aData->mColorData->mColor.SetColorValue(color);
+    }
+  }
+}
+
+NS_IMPL_ELEMENT_CLONE(nsMathMLElement)
+
+PRInt32
+nsMathMLElement::IntrinsicState() const
+{
+  return nsMathMLElementBase::IntrinsicState() |
+    (mIncrementScriptLevel ? NS_EVENT_STATE_INCREMENT_SCRIPT_LEVEL : 0);
+}
+
+PRBool
+nsMathMLElement::IsNodeOfType(PRUint32 aFlags) const
+{
+  return !(aFlags & ~(eCONTENT | eELEMENT | eMATHML));
+}
+
+void
+nsMathMLElement::SetIncrementScriptLevel(PRBool aIncrementScriptLevel,
+                                         PRBool aNotify)
+{
+  if (aIncrementScriptLevel == mIncrementScriptLevel)
+    return;
+  mIncrementScriptLevel = aIncrementScriptLevel;
+
+  NS_ASSERTION(aNotify, "We always notify!");
+
+  nsIDocument* doc = GetCurrentDoc();
+  if (!doc)
+    return;
+
+  mozAutoDocUpdate upd(doc, UPDATE_CONTENT_STATE, PR_TRUE);
+  doc->ContentStatesChanged(this, nsnull,
+                            NS_EVENT_STATE_INCREMENT_SCRIPT_LEVEL);
+}
new file mode 100644
--- /dev/null
+++ b/content/mathml/content/src/nsMathMLElement.h
@@ -0,0 +1,103 @@
+/* -*- 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 MathML DOM code.
+ *
+ * The Initial Developer of the Original Code is
+ * mozilla.org.
+ * Portions created by the Initial Developer are Copyright (C) 2007
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *    Vlad Sukhoy <vladimir.sukhoy@gmail.com> (original developer)
+ *    Daniel Kraft <d@domob.eu> (nsMathMLElement patch, attachment 262925) 
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef nsMathMLElement_h
+#define nsMathMLElement_h
+
+#include "nsMappedAttributeElement.h"
+#include "nsIDOMElement.h"
+
+class nsCSSValue;
+
+typedef nsMappedAttributeElement nsMathMLElementBase;
+
+/*
+ * The base class for MathML elements.
+ */
+class nsMathMLElement : public nsMathMLElementBase
+                      , public nsIDOMElement
+{
+public:
+  nsMathMLElement(nsINodeInfo* aNodeInfo)
+    : nsMathMLElementBase(aNodeInfo), mIncrementScriptLevel(PR_FALSE)
+  {}
+
+  // Implementation of nsISupports is inherited from nsMathMLElementBase
+  NS_DECL_ISUPPORTS_INHERITED
+
+  // Forward implementations of parent interfaces of nsMathMLElement to 
+  // our base class
+  NS_FORWARD_NSIDOMNODE(nsMathMLElementBase::)
+  NS_FORWARD_NSIDOMELEMENT(nsMathMLElementBase::)
+
+  nsresult BindToTree(nsIDocument* aDocument, nsIContent* aParent,
+                      nsIContent* aBindingParent,
+                      PRBool aCompileEventHandlers);
+
+  virtual PRBool ParseAttribute(PRInt32 aNamespaceID,
+                                nsIAtom* aAttribute,
+                                const nsAString& aValue,
+                                nsAttrValue& aResult);
+
+  NS_IMETHOD_(PRBool) IsAttributeMapped(const nsIAtom* aAttribute) const;
+  virtual nsMapRuleToAttributesFunc GetAttributeMappingFunction() const;
+
+  static PRBool ParseNumericValue(const nsString& aString,
+                                  nsCSSValue&     aCSSValue,
+                                  PRBool          aRequireLengthUnit);
+
+  static void MapMathMLAttributesInto(const nsMappedAttributes* aAttributes, 
+                                      nsRuleData* aRuleData);
+  
+  nsresult Clone(nsINodeInfo*, nsINode**) const;
+  virtual PRInt32 IntrinsicState() const;
+  virtual PRBool IsNodeOfType(PRUint32 aFlags) const;
+
+  // Set during reflow as necessary. Does a style change notification,
+  // aNotify must be true.
+  void SetIncrementScriptLevel(PRBool aIncrementScriptLevel, PRBool aNotify);
+  PRBool GetIncrementScriptLevel() const {
+    return mIncrementScriptLevel;
+  }
+
+private:
+  PRPackedBool mIncrementScriptLevel;
+};
+
+#endif // nsMathMLElement_h
new file mode 100644
--- /dev/null
+++ b/content/mathml/content/src/nsMathMLElementFactory.cpp
@@ -0,0 +1,55 @@
+/* -*- 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 MathML DOM code.
+ *
+ * The Initial Developer of the Original Code is
+ * mozilla.org.
+ * Portions created by the Initial Developer are Copyright (C) 2007
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *    Vlad Sukhoy <vladimir.sukhoy@gmail.com> (original developer)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "nsContentCreatorFunctions.h"
+#include "nsGkAtoms.h"
+#include "nsIDocument.h"
+#include "nsMathMLElement.h"
+
+// MathML Element Factory (declared in nsContentCreatorFunctions.h)
+nsresult
+NS_NewMathMLElement(nsIContent** aResult, nsINodeInfo* aNodeInfo)
+{
+  aNodeInfo->SetIDAttributeAtom(nsGkAtoms::id);
+
+  nsMathMLElement* it = new (aNodeInfo) nsMathMLElement(aNodeInfo);
+  NS_ENSURE_TRUE(it, NS_ERROR_OUT_OF_MEMORY);
+
+  NS_ADDREF(*aResult = it);
+  return NS_OK;
+}
new file mode 100644
--- /dev/null
+++ b/content/svg/content/src/crashtests/410659-1.svg
@@ -0,0 +1,19 @@
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+
+  <filter id="filter1">
+    <feImage x="0"
+             y="0"
+             width="5%"
+             height="20%"
+             result="raster1"
+             xlink:href="../../../../../testing/crashtest/images/tree.gif" />
+
+  </filter>
+
+  <rect x="0"
+        y="0"
+        width="100%"
+        height="100%"
+        filter="url(#filter1)" />
+
+</svg>
new file mode 100644
--- /dev/null
+++ b/content/svg/content/src/crashtests/410659-2.svg
@@ -0,0 +1,19 @@
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+
+  <filter id="filter1">
+    <feImage x="0"
+             y="0"
+             width="5%"
+             height="20%"
+             result="raster1" />
+
+
+  </filter>
+
+  <rect x="0"
+        y="0"
+        width="100%"
+        height="100%"
+        filter="url(#filter1)" />
+
+</svg>
new file mode 100644
--- /dev/null
+++ b/content/svg/content/src/crashtests/410659-3.svg
@@ -0,0 +1,19 @@
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+
+  <filter id="filter1">
+    <feImage x="0"
+             y="0"
+             width="5%"
+             height="20%"
+             result="raster1" 
+             xlink:href="../../../../../testing/crashtest/images/tree.gif" />
+    <feTile />
+  </filter>
+
+  <rect x="0"
+        y="0"
+        width="100%"
+        height="100%"
+        filter="url(#filter1)" />
+
+</svg>
--- a/content/svg/content/src/crashtests/crashtests.list
+++ b/content/svg/content/src/crashtests/crashtests.list
@@ -20,8 +20,11 @@ load 388712-1.svg
 load 397017-1.html
 load 397551-1.svg
 load 398926-both-different.svg
 load 398926-both-same.svg
 load 398926-fill.svg
 load 398926-stroke.svg
 load 405639-1.svg
 load 406361-1.html
+load 410659-1.svg
+load 410659-2.svg
+load 410659-3.svg
--- a/content/svg/content/src/nsSVGElement.cpp
+++ b/content/svg/content/src/nsSVGElement.cpp
@@ -733,20 +733,25 @@ nsSVGElement::GetOwnerSVGElement(nsIDOMS
   }
 
   if (!parent) {
     // if we didn't find an anonymous parent, use the explicit one,
     // whether it's null or not...
     parent = GetParent();
   }
 
-  while (parent) {    
-    nsCOMPtr<nsIDOMSVGSVGElement> SVGSVGElement = do_QueryInterface(parent);
-    if (SVGSVGElement) {
-      *aOwnerSVGElement = SVGSVGElement;
+  while (parent && parent->GetNameSpaceID() == kNameSpaceID_SVG) {
+    nsIAtom* tag = parent->Tag();
+    if (tag == nsGkAtoms::foreignObject) {
+      // SVG in a foreignObject must have its own <svg> (nsSVGOuterSVGFrame).
+      // Leave *aOwnerSVGElement nulled out, but don't throw.
+      return NS_OK;
+    }
+    if (tag == nsGkAtoms::svg) {
+      *aOwnerSVGElement = static_cast<nsSVGSVGElement*>(parent);
       NS_ADDREF(*aOwnerSVGElement);
       return NS_OK;
     }
     nsIContent* next = nsnull;
 
     if (bindingManager) {
       next = bindingManager->GetInsertionParent(parent);
     }
@@ -756,18 +761,19 @@ nsSVGElement::GetOwnerSVGElement(nsIDOMS
     }
     
     parent = next;
   }
 
   // we don't have a parent SVG element...
 
   // are _we_ the outermost SVG element? If yes, return nsnull, but don't fail
-  nsCOMPtr<nsIDOMSVGSVGElement> SVGSVGElement = do_QueryInterface((nsIDOMSVGElement*)this);
-  if (SVGSVGElement) return NS_OK;
+  if (Tag() == nsGkAtoms::svg) {
+    return NS_OK;
+  }
   
   // no owner found and we aren't the outermost SVG element either.
   // this situation can e.g. occur during content tree teardown. 
   return NS_ERROR_FAILURE;
 }
 
 /* readonly attribute nsIDOMSVGElement viewportElement; */
 NS_IMETHODIMP
--- a/content/svg/content/src/nsSVGEnum.h
+++ b/content/svg/content/src/nsSVGEnum.h
@@ -45,18 +45,16 @@ typedef PRUint8 nsSVGEnumValue;
 
 struct nsSVGEnumMapping {
   nsIAtom **mKey;
   nsSVGEnumValue mVal;
 };
 
 class nsSVGEnum
 {
-friend class nsSVGMarkerElement;
-
 public:
   void Init(PRUint8 aAttrEnum, PRUint16 aValue) {
     mAnimVal = mBaseVal = PRUint8(aValue);
     mAttrEnum = aAttrEnum;
   }
 
   nsresult SetBaseValueString(const nsAString& aValue,
                               nsSVGElement *aSVGElement,
@@ -78,20 +76,16 @@ public:
 
 private:
   nsSVGEnumValue mAnimVal;
   nsSVGEnumValue mBaseVal;
   PRUint8 mAttrEnum; // element specified tracking for attribute
 
   nsSVGEnumMapping *GetMapping(nsSVGElement *aSVGElement);
 
-  nsresult SetBaseValue(PRUint16 aValue)
-  { mAnimVal = mBaseVal = PRUint8(aValue);
-    return NS_OK; }
-
   struct DOMAnimatedEnum : public nsIDOMSVGAnimatedEnumeration
   {
     NS_DECL_ISUPPORTS
 
     DOMAnimatedEnum(nsSVGEnum* aVal, nsSVGElement *aSVGElement)
       : mVal(aVal), mSVGElement(aSVGElement) {}
 
     nsSVGEnum *mVal; // kept alive because it belongs to content
@@ -101,9 +95,9 @@ private:
       { *aResult = mVal->GetBaseValue(); return NS_OK; }
     NS_IMETHOD SetBaseVal(PRUint16 aValue)
       { return mVal->SetBaseValue(aValue, mSVGElement, PR_TRUE); }
     NS_IMETHOD GetAnimVal(PRUint16* aResult)
       { *aResult = mVal->GetAnimValue(); return NS_OK; }
   };
 };
 
-#endif //__NS_SVGENUM2_H__
+#endif //__NS_SVGENUM_H__
--- a/content/svg/content/src/nsSVGFilters.cpp
+++ b/content/svg/content/src/nsSVGFilters.cpp
@@ -59,26 +59,26 @@
 #include "nsIDocument.h"
 #include "nsIFrame.h"
 #include "gfxContext.h"
 #include "nsSVGLengthList.h"
 #include "nsIDOMSVGURIReference.h"
 #include "nsImageLoadingContent.h"
 #include "imgIContainer.h"
 #include "gfxIImageFrame.h"
-#if defined(XP_WIN) && !defined(NOUSER)
-// Prevent Windows redefining LoadImage
-#define NOUSER
-#endif
 #include "nsThebesImage.h"
 #include "nsSVGAnimatedPreserveAspectRatio.h"
 #include "nsSVGPreserveAspectRatio.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsSVGMatrix.h"
 #include "nsSVGFilterElement.h"
+#if defined(XP_WIN)
+// Prevent Windows redefining LoadImage
+#undef LoadImage
+#endif
 
 //--------------------Filter Resource-----------------------
 /**
   * nsSVGFilterResource provides functionality for managing images used by
   * filters.  PLEASE NOTE that nsSVGFilterResource should ONLY be used on the
   * stack because it has nsAutoString member.  Also note that ReleaseTarget,
   * and thus the destructor, depends on AcquireSourceImage having been called
   * one or more times before it is executed.
--- a/content/svg/content/src/nsSVGGraphicElement.cpp
+++ b/content/svg/content/src/nsSVGGraphicElement.cpp
@@ -70,25 +70,23 @@ nsSVGGraphicElement::nsSVGGraphicElement
 }
 
 //----------------------------------------------------------------------
 // nsIDOMSVGLocatable methods
 
 /* readonly attribute nsIDOMSVGElement nearestViewportElement; */
 NS_IMETHODIMP nsSVGGraphicElement::GetNearestViewportElement(nsIDOMSVGElement * *aNearestViewportElement)
 {
-  NS_NOTYETIMPLEMENTED("nsSVGGraphicElement::GetNearestViewportElement");
-  return NS_ERROR_NOT_IMPLEMENTED;
+  return nsSVGUtils::GetNearestViewportElement(this, aNearestViewportElement);
 }
 
 /* readonly attribute nsIDOMSVGElement farthestViewportElement; */
 NS_IMETHODIMP nsSVGGraphicElement::GetFarthestViewportElement(nsIDOMSVGElement * *aFarthestViewportElement)
 {
-  NS_NOTYETIMPLEMENTED("nsSVGGraphicElement::GetFarthestViewportElement");
-  return NS_ERROR_NOT_IMPLEMENTED;
+  return nsSVGUtils::GetFarthestViewportElement(this, aFarthestViewportElement);
 }
 
 /* nsIDOMSVGRect getBBox (); */
 NS_IMETHODIMP nsSVGGraphicElement::GetBBox(nsIDOMSVGRect **_retval)
 {
   *_retval = nsnull;
 
   nsIFrame* frame = GetPrimaryFrame(Flush_Layout);
--- a/content/svg/content/src/nsSVGMarkerElement.cpp
+++ b/content/svg/content/src/nsSVGMarkerElement.cpp
@@ -73,47 +73,80 @@ nsSVGElement::AngleInfo nsSVGMarkerEleme
   { &nsGkAtoms::orient, 0, nsIDOMSVGAngle::SVG_ANGLETYPE_UNSPECIFIED }
 };
 
 NS_IMPL_NS_NEW_SVG_ELEMENT(Marker)
 
 //----------------------------------------------------------------------
 // nsISupports methods
 
+NS_IMPL_ADDREF(nsSVGOrientType::DOMAnimatedEnum)
+NS_IMPL_RELEASE(nsSVGOrientType::DOMAnimatedEnum)
+
+NS_INTERFACE_MAP_BEGIN(nsSVGOrientType::DOMAnimatedEnum)
+  NS_INTERFACE_MAP_ENTRY(nsIDOMSVGAnimatedEnumeration)
+  NS_INTERFACE_MAP_ENTRY(nsISupports)
+  NS_INTERFACE_MAP_ENTRY_CONTENT_CLASSINFO(SVGAnimatedEnumeration)
+NS_INTERFACE_MAP_END
+
 NS_IMPL_ADDREF_INHERITED(nsSVGMarkerElement,nsSVGMarkerElementBase)
 NS_IMPL_RELEASE_INHERITED(nsSVGMarkerElement,nsSVGMarkerElementBase)
 
 NS_INTERFACE_MAP_BEGIN(nsSVGMarkerElement)
   NS_INTERFACE_MAP_ENTRY(nsIDOMNode)
   NS_INTERFACE_MAP_ENTRY(nsIDOMElement)
   NS_INTERFACE_MAP_ENTRY(nsIDOMSVGElement)
   NS_INTERFACE_MAP_ENTRY(nsIDOMSVGFitToViewBox)
   NS_INTERFACE_MAP_ENTRY(nsIDOMSVGMarkerElement)
   NS_INTERFACE_MAP_ENTRY_CONTENT_CLASSINFO(SVGMarkerElement)
 NS_INTERFACE_MAP_END_INHERITING(nsSVGMarkerElementBase)
 
 //----------------------------------------------------------------------
 // Implementation
 
+nsresult
+nsSVGOrientType::SetBaseValue(PRUint16 aValue,
+                              nsSVGElement *aSVGElement)
+{
+  if (aValue == nsIDOMSVGMarkerElement::SVG_MARKER_ORIENT_AUTO ||
+      aValue == nsIDOMSVGMarkerElement::SVG_MARKER_ORIENT_ANGLE) {
+    SetBaseValue(aValue);
+    aSVGElement->SetAttr(
+      kNameSpaceID_None, nsGkAtoms::orient, nsnull,
+      (aValue ==nsIDOMSVGMarkerElement::SVG_MARKER_ORIENT_AUTO ?
+        NS_LITERAL_STRING("auto") : NS_LITERAL_STRING("0")),
+      PR_TRUE);
+    return NS_OK;
+  }
+  return NS_ERROR_FAILURE;
+}
+
+nsresult
+nsSVGOrientType::ToDOMAnimatedEnum(nsIDOMSVGAnimatedEnumeration **aResult,
+                                   nsSVGElement *aSVGElement)
+{
+  *aResult = new DOMAnimatedEnum(this, aSVGElement);
+  if (!*aResult)
+    return NS_ERROR_OUT_OF_MEMORY;
+
+  NS_ADDREF(*aResult);
+  return NS_OK;
+}
+
 nsSVGMarkerElement::nsSVGMarkerElement(nsINodeInfo *aNodeInfo)
   : nsSVGMarkerElementBase(aNodeInfo), mCoordCtx(nsnull)
 {
 }
 
 nsresult
 nsSVGMarkerElement::Init()
 {
   nsresult rv = nsSVGMarkerElementBase::Init();
   NS_ENSURE_SUCCESS(rv,rv);
 
-  // derived (non-attrib) DOM properties
-
-  // DOM property: orientType
-  mOrientType.Init(ORIENTTYPE, SVG_MARKER_ORIENT_ANGLE);
-
   // Create mapped properties:
 
   // DOM property: viewBox
   {
     nsCOMPtr<nsIDOMSVGRect> viewbox;
     rv = NS_NewSVGRect(getter_AddRefs(viewbox));
     NS_ENSURE_SUCCESS(rv,rv);
     rv = NS_NewSVGAnimatedRect(getter_AddRefs(mViewBox), viewbox);
--- a/content/svg/content/src/nsSVGMarkerElement.h
+++ b/content/svg/content/src/nsSVGMarkerElement.h
@@ -39,16 +39,61 @@
 
 #include "nsSVGGraphicElement.h"
 #include "nsIDOMSVGMarkerElement.h"
 #include "nsIDOMSVGFitToViewBox.h"
 #include "nsSVGLength2.h"
 #include "nsSVGEnum.h"
 #include "nsSVGAngle.h"
 
+class nsSVGOrientType
+{
+public:
+  nsSVGOrientType()
+   : mAnimVal(nsIDOMSVGMarkerElement::SVG_MARKER_ORIENT_ANGLE),
+     mBaseVal(nsIDOMSVGMarkerElement::SVG_MARKER_ORIENT_ANGLE) {}
+
+  nsresult SetBaseValue(PRUint16 aValue,
+                        nsSVGElement *aSVGElement);
+
+  void SetBaseValue(PRUint16 aValue)
+    { mAnimVal = mBaseVal = PRUint8(aValue); }
+
+  PRUint16 GetBaseValue() const
+    { return mBaseVal; }
+  PRUint16 GetAnimValue() const
+    { return mAnimVal; }
+
+  nsresult ToDOMAnimatedEnum(nsIDOMSVGAnimatedEnumeration **aResult,
+                             nsSVGElement* aSVGElement);
+
+private:
+  nsSVGEnumValue mAnimVal;
+  nsSVGEnumValue mBaseVal;
+
+  struct DOMAnimatedEnum : public nsIDOMSVGAnimatedEnumeration
+  {
+    NS_DECL_ISUPPORTS
+
+    DOMAnimatedEnum(nsSVGOrientType* aVal,
+                    nsSVGElement *aSVGElement)
+      : mVal(aVal), mSVGElement(aSVGElement) {}
+
+    nsSVGOrientType *mVal; // kept alive because it belongs to content
+    nsRefPtr<nsSVGElement> mSVGElement;
+
+    NS_IMETHOD GetBaseVal(PRUint16* aResult)
+      { *aResult = mVal->GetBaseValue(); return NS_OK; }
+    NS_IMETHOD SetBaseVal(PRUint16 aValue)
+      { return mVal->SetBaseValue(aValue, mSVGElement); }
+    NS_IMETHOD GetAnimVal(PRUint16* aResult)
+      { *aResult = mVal->GetAnimValue(); return NS_OK; }
+  };
+};
+
 typedef nsSVGGraphicElement nsSVGMarkerElementBase;
 
 class nsSVGMarkerElement : public nsSVGMarkerElementBase,
                            public nsIDOMSVGMarkerElement,
                            public nsIDOMSVGFitToViewBox
 {
   friend class nsSVGMarkerFrame;
 
@@ -104,27 +149,27 @@ protected:
   virtual LengthAttributesInfo GetLengthInfo();
   virtual AngleAttributesInfo GetAngleInfo();
   virtual EnumAttributesInfo GetEnumInfo();
 
   enum { REFX, REFY, MARKERWIDTH, MARKERHEIGHT };
   nsSVGLength2 mLengthAttributes[4];
   static LengthInfo sLengthInfo[4];
 
-  enum { MARKERUNITS, ORIENTTYPE = 0xFF };
+  enum { MARKERUNITS };
   nsSVGEnum mEnumAttributes[1];
   static nsSVGEnumMapping sUnitsMap[];
   static EnumInfo sEnumInfo[1];
 
   enum { ORIENT };
   nsSVGAngle mAngleAttributes[1];
   static AngleInfo sAngleInfo[1];
 
   // derived properties (from 'orient') handled separately
-  nsSVGEnum                              mOrientType;
+  nsSVGOrientType                        mOrientType;
 
   nsSVGSVGElement                       *mCoordCtx;
   nsCOMPtr<nsIDOMSVGAnimatedRect>        mViewBox;
   nsCOMPtr<nsIDOMSVGAnimatedPreserveAspectRatio> mPreserveAspectRatio;
   nsCOMPtr<nsIDOMSVGMatrix>         mViewBoxToViewportTransform;
 };
 
 #endif
--- a/content/svg/content/src/nsSVGPathElement.cpp
+++ b/content/svg/content/src/nsSVGPathElement.cpp
@@ -530,21 +530,21 @@ nsSVGPathElement::GetMarkPoints(nsTArray
   float cx = 0.0f; // current point
   float cy = 0.0f;
 
   float cx1 = 0.0f; // last controlpoint (for s,S,t,T)
   float cy1 = 0.0f;
 
   PRUint16 lastSegmentType = nsIDOMSVGPathSeg::PATHSEG_UNKNOWN;
 
-  float px, py;    // subpath initial point
-  float pathAngle;
-  PRUint32 pathIndex;
+  float px = 0, py = 0;    // subpath initial point
+  float pathAngle = 0;
+  PRUint32 pathIndex = 0;
 
-  float prevAngle = 0, startAngle, endAngle;
+  float prevAngle = 0, startAngle = 0, endAngle = 0;
 
   PRBool newSegment = PR_FALSE;
 
   PRUint32 i;
   for (i = 0; i < count; ++i) {
     nsCOMPtr<nsIDOMSVGPathSeg> segment;
     mSegments->GetItem(i, getter_AddRefs(segment));
 
--- a/content/svg/content/src/nsSVGSVGElement.cpp
+++ b/content/svg/content/src/nsSVGSVGElement.cpp
@@ -651,52 +651,50 @@ nsSVGSVGElement::GetPreserveAspectRatio(
 
 //----------------------------------------------------------------------
 // nsIDOMSVGLocatable methods
 
 /* readonly attribute nsIDOMSVGElement nearestViewportElement; */
 NS_IMETHODIMP
 nsSVGSVGElement::GetNearestViewportElement(nsIDOMSVGElement * *aNearestViewportElement)
 {
-  NS_NOTYETIMPLEMENTED("nsSVGSVGElement::GetNearestViewportElement");
-  return NS_ERROR_NOT_IMPLEMENTED;
+  return nsSVGUtils::GetNearestViewportElement(this, aNearestViewportElement);
 }
 
 /* readonly attribute nsIDOMSVGElement farthestViewportElement; */
 NS_IMETHODIMP
 nsSVGSVGElement::GetFarthestViewportElement(nsIDOMSVGElement * *aFarthestViewportElement)
 {
-  NS_NOTYETIMPLEMENTED("nsSVGSVGElement::GetFarthestViewportElement");
-  return NS_ERROR_NOT_IMPLEMENTED;
+  return nsSVGUtils::GetFarthestViewportElement(this, aFarthestViewportElement);
 }
 
 /* nsIDOMSVGRect getBBox (); */
 NS_IMETHODIMP
 nsSVGSVGElement::GetBBox(nsIDOMSVGRect **_retval)
 {
   *_retval = nsnull;
 
   nsIFrame* frame = GetPrimaryFrame(Flush_Layout);
 
-  if (frame) {
-    nsISVGChildFrame* svgframe;
-    CallQueryInterface(frame, &svgframe);
-    if (svgframe) {
-      svgframe->SetMatrixPropagation(PR_FALSE);
-      svgframe->NotifyCanvasTMChanged(PR_TRUE);
-      nsresult rv = svgframe->GetBBox(_retval);
-      svgframe->SetMatrixPropagation(PR_TRUE);
-      svgframe->NotifyCanvasTMChanged(PR_TRUE);
-      return rv;
-    } else {
-      // XXX: outer svg
-      return NS_ERROR_NOT_IMPLEMENTED;
-    }
+  if (!frame || (frame->GetStateBits() & NS_STATE_SVG_NONDISPLAY_CHILD))
+    return NS_ERROR_FAILURE;
+
+  nsISVGChildFrame* svgframe;
+  CallQueryInterface(frame, &svgframe);
+  if (svgframe) {
+    svgframe->SetMatrixPropagation(PR_FALSE);
+    svgframe->NotifyCanvasTMChanged(PR_TRUE);
+    nsresult rv = svgframe->GetBBox(_retval);
+    svgframe->SetMatrixPropagation(PR_TRUE);
+    svgframe->NotifyCanvasTMChanged(PR_TRUE);
+    return rv;
+  } else {
+    // XXX: outer svg
+    return NS_ERROR_NOT_IMPLEMENTED;
   }
-  return NS_ERROR_FAILURE;
 }
 
 /* nsIDOMSVGMatrix getCTM (); */
 NS_IMETHODIMP
 nsSVGSVGElement::GetCTM(nsIDOMSVGMatrix **_retval)
 {
   nsresult rv;
   *_retval = nsnull;
--- a/content/xbl/src/nsXBLPrototypeBinding.cpp
+++ b/content/xbl/src/nsXBLPrototypeBinding.cpp
@@ -1344,51 +1344,44 @@ nsXBLPrototypeBinding::ConstructInterfac
     char* token = nsCRT::strtok( str, ", ", &newStr );
     while( token != NULL ) {
       // get the InterfaceInfo for the name
       nsCOMPtr<nsIInterfaceInfo> iinfo;
       infoManager->GetInfoForName(token, getter_AddRefs(iinfo));
 
       if (iinfo) {
         // obtain an IID.
-        nsIID* iid = nsnull;
-        iinfo->GetInterfaceIID(&iid);
+        const nsIID* iid = nsnull;
+        iinfo->GetIIDShared(&iid);
 
         if (iid) {
           // We found a valid iid.  Add it to our table.
           nsIIDKey key(*iid);
           mInterfaceTable->Put(&key, mBinding);
 
           // this block adds the parent interfaces of each interface
           // defined in the xbl definition (implements="nsI...")
           nsCOMPtr<nsIInterfaceInfo> parentInfo;
           // if it has a parent, add it to the table
           while (NS_SUCCEEDED(iinfo->GetParent(getter_AddRefs(parentInfo))) && parentInfo) {
-            // free the nsMemory::Clone()ed iid
-            nsMemory::Free(iid);
-
             // get the iid
-            parentInfo->GetInterfaceIID(&iid);
+            parentInfo->GetIIDShared(&iid);
 
             // don't add nsISupports to the table
             if (!iid || iid->Equals(NS_GET_IID(nsISupports)))
               break;
 
             // add the iid to the table
             nsIIDKey parentKey(*iid);
             mInterfaceTable->Put(&parentKey, mBinding);
 
             // look for the next parent
             iinfo = parentInfo;
           }
         }
-
-        // free the nsMemory::Clone()ed iid
-        if (iid)
-          nsMemory::Free(iid);
       }
 
       token = nsCRT::strtok( newStr, ", ", &newStr );
     }
   }
 
   return NS_OK;
 }
--- a/content/xml/document/src/nsXMLContentSink.cpp
+++ b/content/xml/document/src/nsXMLContentSink.cpp
@@ -904,38 +904,16 @@ nsXMLContentSink::MaybeStartLayout(PRBoo
   // XXXbz if aIgnorePendingSheets is true, what should we do when
   // mXSLTProcessor or CanStillPrettyPrint()?
   if (mLayoutStarted || mXSLTProcessor || CanStillPrettyPrint()) {
     return;
   }
   StartLayout(aIgnorePendingSheets);
 }
 
-#ifdef MOZ_MATHML
-////////////////////////////////////////////////////////////////////////
-// MathML Element Factory - temporary location for bug 132844
-// Will be factored out post 1.0
-
-nsresult
-NS_NewMathMLElement(nsIContent** aResult, nsINodeInfo* aNodeInfo)
-{
-  static const char kMathMLStyleSheetURI[] = "resource://gre/res/mathml.css";
-
-  aNodeInfo->SetIDAttributeAtom(nsGkAtoms::id);
-  
-  // this bit of code is to load mathml.css on demand
-  nsIDocument *doc = aNodeInfo->GetDocument();
-  if (doc)
-    doc->EnsureCatalogStyleSheet(kMathMLStyleSheetURI);
-
-  return NS_NewXMLElement(aResult, aNodeInfo);
-}
-#endif // MOZ_MATHML
-
-
 ////////////////////////////////////////////////////////////////////////
 
 PRBool
 nsXMLContentSink::SetDocElement(PRInt32 aNameSpaceID,
                                 nsIAtom* aTagName,
                                 nsIContent *aContent)
 {
   if (mDocElement)
--- a/content/xslt/public/txDouble.h
+++ b/content/xslt/public/txDouble.h
@@ -39,65 +39,67 @@
 
 #ifndef __txdouble_h__
 #define __txdouble_h__
 
 //A trick to handle IEEE floating point exceptions on FreeBSD - E.D.
 #ifdef __FreeBSD__
 #include <ieeefp.h>
 #ifdef __alpha__
-fp_except_t allmask = FP_X_INV|FP_X_OFL|FP_X_UFL|FP_X_DZ|FP_X_IMP;
+static fp_except_t allmask = FP_X_INV|FP_X_OFL|FP_X_UFL|FP_X_DZ|FP_X_IMP;
 #else
-fp_except_t allmask = FP_X_INV|FP_X_OFL|FP_X_UFL|FP_X_DZ|FP_X_IMP|FP_X_DNML;
+static fp_except_t allmask = FP_X_INV|FP_X_OFL|FP_X_UFL|FP_X_DZ|FP_X_IMP|FP_X_DNML;
 #endif
-fp_except_t oldmask = fpsetmask(~allmask);
+static fp_except_t oldmask = fpsetmask(~allmask);
 #endif
 
 /**
  * Macros to workaround math-bugs bugs in various platforms
  */
 
 /**
  * Stefan Hanske <sh990154@mail.uni-greifswald.de> reports:
  *  ARM is a little endian architecture but 64 bit double words are stored
  * differently: the 32 bit words are in little endian byte order, the two words
  * are stored in big endian`s way.
  */
 
 #if defined(__arm) || defined(__arm32__) || defined(__arm26__) || defined(__arm__)
-#define CPU_IS_ARM
+#if !defined(__VFP_FP__)
+#define FPU_IS_ARM_FPA
+#endif
 #endif
 
 #if (__GNUC__ == 2 && __GNUC_MINOR__ > 95) || __GNUC__ > 2
 /**
  * This version of the macros is safe for the alias optimizations
  * that gcc does, but uses gcc-specific extensions.
  */
 
 typedef union txdpun {
     PRFloat64 d;
     struct {
-#if defined(IS_LITTLE_ENDIAN) && !defined(CPU_IS_ARM)
+#if defined(IS_LITTLE_ENDIAN) && !defined(FPU_IS_ARM_FPA)
         PRUint32 lo, hi;
 #else
         PRUint32 hi, lo;
 #endif
     } s;
 } txdpun;
 
 #define TX_DOUBLE_HI32(x) (__extension__ ({ txdpun u; u.d = (x); u.s.hi; }))
 #define TX_DOUBLE_LO32(x) (__extension__ ({ txdpun u; u.d = (x); u.s.lo; }))
 
 #else // __GNUC__
 
 /* We don't know of any non-gcc compilers that perform alias optimization,
  * so this code should work.
  */
 
-#if defined(IS_LITTLE_ENDIAN) && !defined(CPU_IS_ARM)
+#if defined(IS_LITTLE_ENDIAN) && !defined(FPU_IS_ARM_FPA)
 #define TX_DOUBLE_HI32(x)        (((PRUint32 *)&(x))[1])
 #define TX_DOUBLE_LO32(x)        (((PRUint32 *)&(x))[0])
 #else
 #define TX_DOUBLE_HI32(x)        (((PRUint32 *)&(x))[0])
 #define TX_DOUBLE_LO32(x)        (((PRUint32 *)&(x))[1])
 #endif
 
 #endif // __GNUC__
--- a/content/xslt/src/xslt/txMozillaXSLTProcessor.cpp
+++ b/content/xslt/src/xslt/txMozillaXSLTProcessor.cpp
@@ -1445,18 +1445,18 @@ txVariable::Convert(nsIVariant *aValue, 
             // Convert random JS Objects to a string.
             nsCOMPtr<nsIXPConnectJSObjectHolder> holder =
                 do_QueryInterface(supports);
             if (holder) {
                 nsCOMPtr<nsIXPConnect> xpc =
                     do_GetService(nsIXPConnect::GetCID(), &rv);
                 NS_ENSURE_SUCCESS(rv, rv);
                 
-                nsCOMPtr<nsIXPCNativeCallContext> cc;
-                rv = xpc->GetCurrentNativeCallContext(getter_AddRefs(cc));
+                nsAXPCNativeCallContext *cc = nsnull;
+                rv = xpc->GetCurrentNativeCallContext(&cc);
                 NS_ENSURE_SUCCESS(rv, rv);
 
                 JSContext* cx;
                 rv = cc->GetJSContext(&cx);
                 NS_ENSURE_SUCCESS(rv, rv);
 
                 JSObject *jsobj;
                 rv = holder->GetJSObject(&jsobj);
--- a/db/sqlite3/README.MOZILLA
+++ b/db/sqlite3/README.MOZILLA
@@ -1,23 +1,15 @@
-This is sqlite 3.4.1
+This is sqlite 3.5.4
 
-This version has some security stuff dealing with the upper
-bounds of data types.  See the change log for more details:
-http://www.sqlite.org/changes.html#version_3_4_1
 
--- Shawn Wilsher <me@shawnwilsher.com> 08/2007
+-- Shawn Wilsher <me@shawnwilsher.com> 01/2008
 
 See http://www.sqlite.org/ for more info.
 
 We have a mozilla-specific Makefile.in in src/ (normally no
 Makefile.in there) that we use to build.
 
 To move to a new version:
 
 Simply copy the sqlite3.h and sqlite3.c files from the amalgamation of sqlite.
 
-Then you need to update sqlite3file.h, which pulls out random bits of the
-internal files that we need to export. If any of these internal structures
-change, they need to be changed in sqlite3file.h as well.  This may involve
-downloading the whole source (not the amalgamation) to check.
-
--- Shawn Wilsher <me@shawnwilsher.com> 06/2007
+-- Shawn Wilsher <me@shawnwilsher.com> 01/2008
--- a/db/sqlite3/src/Makefile.in
+++ b/db/sqlite3/src/Makefile.in
@@ -17,16 +17,17 @@
 # The Initial Developer of the Original Code is
 #   sqlite3
 # Portions created by the Initial Developer are Copyright (C) 2004
 # the Initial Developer. All Rights Reserved.
 #
 # Contributor(s):
 #   Vladimir Vukicevic <vladimir.vukicevic@oracle.com>
 #   Shawn Wilsher <me@shawnwilsher.com>
+#   Ryan VanderMeulen <ryanvm@gmail.com>
 #
 # Alternatively, the contents of this file may be used under the terms of
 # either of the GNU General Public License Version 2 or later (the "GPL"),
 # or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 # in which case the provisions of the GPL or the LGPL are applicable instead
 # of those above. If you wish to allow use of your version of this file only
 # under the terms of either the GPL or the LGPL, and not to allow others to
 # use your version of this file under the terms of the MPL, indicate your
@@ -43,45 +44,54 @@ srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE           = sqlite3
 LIBRARY_NAME     = sqlite3
 FORCE_SHARED_LIB = 1
 VISIBILITY_FLAGS =
-LIB_IS_C_ONLY = 1
+LIB_IS_C_ONLY    = 1
 
 ifeq (,$(filter-out WINNT WINCE,$(OS_ARCH)))
 ifndef GNU_CC
 DEFFILE = $(win_srcdir)/sqlite.def
+RCFILE  = sqlite.rc
+RESFILE = sqlite.res
+
+GARBAGE += sqlite-version.h
+
+sqlite-version.h: sqlite-version.py sqlite3.h
+	$(PYTHON) $^ > $@
+export:: sqlite-version.h
 endif
 endif
 
 ifdef GNU_CC
 MODULE_OPTIMIZE_FLAGS = -O2
 else
 ifeq ($(OS_ARCH),SunOS)
 MODULE_OPTIMIZE_FLAGS = -xO5
 endif
 ifeq ($(OS_ARCH),WINNT)
 MODULE_OPTIMIZE_FLAGS = -O2
 endif
 endif
 
-EXPORTS = sqlite3.h sqlite3file.h
+EXPORTS = \
+  sqlite3.h \
+  $(NULL)
 
 CSRCS = \
 	sqlite3.c \
 	$(NULL)
 
-# REDEF_IO allows us to override IO functions, which is used in the AsyncIO
 # -DSQLITE_SECURE_DELETE=1 will cause SQLITE to 0-fill delete data so we
 # don't have to vacuum to make sure the data is not visible in the file.
-DEFINES = -DSQLITE_ENABLE_REDEF_IO -DSQLITE_SECURE_DELETE=1 -DTHREADSAFE=1
+DEFINES = -DSQLITE_SECURE_DELETE=1 -DTHREADSAFE=1
 
 ifeq ($(OS_ARCH),OS2)
 ifdef MOZ_OS2_HIGH_MEMORY
 DEFINES += -DOS2_HIGH_MEMORY
 endif
 endif
 
 include $(topsrcdir)/config/rules.mk
new file mode 100644
--- /dev/null
+++ b/db/sqlite3/src/sqlite-version.py
@@ -0,0 +1,57 @@
+# ***** 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 Python script to generate SQLite major, minor,
+# patch, and subpatch numbers from original version string.
+#
+# The Initial Developer of the Original Code is Ryan VanderMeulen.
+# Portions created by the Initial Developer are Copyright (C) 2008
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either the GNU General Public License Version 2 or later (the "GPL"), or
+# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+import sys
+import re
+
+# Define RegEx for finding and breaking apart SQLITE_VERSION string
+versionString = "^#define SQLITE_VERSION\D*(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?\D*"
+
+#Use command line argument pointing to sqlite3.h to open the file and use
+#the RegEx to search for the line #define SQLITE_VERSION. When the RegEx
+#matches and the line is found, print the version strings to the console
+#with #definey goodness.
+for line in open(sys.argv[1]):
+    result = re.search(versionString, line)
+    if result is not None:    #If RegEx matches, print version numbers and stop
+        splitVersion = list(result.groups())
+        if splitVersion[3] is None:       #Make 4th list element 0 if undefined
+            splitVersion[3:] = ['0']
+        print "#define SQLITE_VERSION_MAJOR " + splitVersion[0]
+        print "#define SQLITE_VERSION_MINOR " + splitVersion[1]
+        print "#define SQLITE_VERSION_PATCH " + splitVersion[2]
+        print "#define SQLITE_VERSION_SUBPATCH " + splitVersion[3]
+        break
--- a/db/sqlite3/src/sqlite.def
+++ b/db/sqlite3/src/sqlite.def
@@ -87,40 +87,53 @@ EXPORTS
         sqlite3_enable_load_extension
         sqlite3_enable_shared_cache
         sqlite3_errcode
         sqlite3_errmsg
         sqlite3_errmsg16
         sqlite3_exec
         sqlite3_expired
         sqlite3_extended_result_codes
+        sqlite3_file_control
         sqlite3_finalize
         sqlite3_free
         sqlite3_free_table
         sqlite3_get_autocommit
         sqlite3_get_auxdata
         sqlite3_get_table
         sqlite3_global_recover
         sqlite3_interrupt
         sqlite3_last_insert_rowid
         sqlite3_libversion
         sqlite3_libversion_number
         sqlite3_load_extension
         sqlite3_malloc
+        sqlite3_memory_alarm
+        sqlite3_memory_highwater
+        sqlite3_memory_used
+        sqlite3_mutex_alloc
+        sqlite3_mutex_enter
+        sqlite3_mutex_free
+        sqlite3_mutex_held
+        sqlite3_mutex_leave
+        sqlite3_mutex_notheld
+        sqlite3_mutex_try
         sqlite3_mprintf
         sqlite3_open
+        sqlite3_open_v2
         sqlite3_open16
         sqlite3_overload_function
         sqlite3_prepare
         sqlite3_prepare16
         sqlite3_prepare16_v2
         sqlite3_prepare_v2
         sqlite3_profile
         sqlite3_progress_handler
         sqlite3_realloc
+        sqlite3_release_memory
         sqlite3_reset
         sqlite3_reset_auto_extension
         sqlite3_result_blob
         sqlite3_result_double
         sqlite3_result_error
         sqlite3_result_error16
         sqlite3_result_int
         sqlite3_result_int64
@@ -150,10 +163,12 @@ EXPORTS
         sqlite3_value_int64
         sqlite3_value_numeric_type
         sqlite3_value_text
         sqlite3_value_text16
         sqlite3_value_text16be
         sqlite3_value_text16le
         sqlite3_value_type
         sqlite3_version
+        sqlite3_vfs_find
+        sqlite3_vfs_unregister
+        sqlite3_vfs_register
         sqlite3_vmprintf
-        sqlite3Os DATA               ;needed by mozStorage
new file mode 100644
--- /dev/null
+++ b/db/sqlite3/src/sqlite.rc
@@ -0,0 +1,76 @@
+/* ***** 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 resource file for sqlite.
+ *
+ * The Initial Developer of the Original Code is Ryan VanderMeulen.
+ * Portions created by the Initial Developer are Copyright (C) 2007
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "sqlite3.h"
+#include "sqlite-version.h"
+#include <winver.h>
+
+#define SQLITE_COMPANY_NAME "sqlite.org"
+#define SQLITE_INTERNAL_NAME "sqlite3"
+#define SQLITE_FILEDESCRIPTION "SQLite Database Library"
+
+#define MY_FILEOS VOS_NT_WINDOWS32
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Version-information resource
+//
+
+VS_VERSION_INFO VERSIONINFO
+
+ FILEVERSION SQLITE_VERSION_MAJOR,SQLITE_VERSION_MINOR,SQLITE_VERSION_PATCH,SQLITE_VERSION_SUBPATCH
+ PRODUCTVERSION SQLITE_VERSION_MAJOR,SQLITE_VERSION_MINOR,SQLITE_VERSION_PATCH,SQLITE_VERSION_SUBPATCH
+ FILEOS MY_FILEOS
+ FILETYPE VFT_DLL
+
+BEGIN
+    BLOCK "StringFileInfo"
+    BEGIN
+        BLOCK "040904B0" // Lang=US English, CharSet=Unicode
+        BEGIN
+            VALUE "CompanyName", SQLITE_COMPANY_NAME "\0"
+            VALUE "FileDescription", SQLITE_FILEDESCRIPTION "\0"
+            VALUE "FileVersion", SQLITE_VERSION "\0"
+            VALUE "InternalName", SQLITE_INTERNAL_NAME "\0"
+            VALUE "OriginalFilename", SQLITE_INTERNAL_NAME ".dll\0"
+            VALUE "ProductName", SQLITE_FILEDESCRIPTION "\0"
+            VALUE "ProductVersion", SQLITE_VERSION "\0"
+        END
+    END
+    BLOCK "VarFileInfo"
+    BEGIN
+        VALUE "Translation", 0x409, 1200
+    END
+END
--- a/db/sqlite3/src/sqlite3.c
+++ b/db/sqlite3/src/sqlite3.c
@@ -1,2825 +1,115 @@
 /******************************************************************************
 ** This file is an amalgamation of many separate C source files from SQLite
-** version 3.4.1.  By combining all the individual C code files into this 
+** version 3.5.4.  By combining all the individual C code files into this 
 ** single large file, the entire code can be compiled as a one translation
 ** unit.  This allows many compilers to do optimizations that would not be
 ** possible if the files were compiled separately.  Performance improvements
 ** of 5% are more are commonly seen when SQLite is compiled as a single
 ** translation unit.
 **
 ** This file is all you need to compile SQLite.  To use SQLite in other
 ** programs, you need this file and the "sqlite3.h" header file that defines
 ** the programming interface to the SQLite library.  (If you do not have 
 ** the "sqlite3.h" header file at hand, you will find a copy in the first
-** 2702 lines past this header comment.)  Additional code files may be
+** 3840 lines past this header comment.)  Additional code files may be
 ** needed if you want a wrapper to interface SQLite with your choice of
 ** programming language.  The code for the "sqlite3" command-line shell
 ** is also in a separate file.  This file contains only code for the core
 ** SQLite library.
 **
-** This amalgamation was generated on 2007-07-20 11:05:39 UTC.
+** This amalgamation was generated on 2007-12-14 17:40:56 UTC.
 */
 #define SQLITE_AMALGAMATION 1
 #ifndef SQLITE_PRIVATE
 # define SQLITE_PRIVATE static
 #endif
 #ifndef SQLITE_API
 # define SQLITE_API
 #endif
-/************** Begin file sqlite3.h *****************************************/
-/*
-** 2001 September 15
-**
-** The author disclaims copyright to this source code.  In place of
-** a legal notice, here is a blessing:
-**
-**    May you do good and not evil.
-**    May you find forgiveness for yourself and forgive others.
-**    May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This header file defines the interface that the SQLite library
-** presents to client programs.  If a C-function, structure, datatype,
-** or constant definition does not appear in this file, then it is
-** not a published API of SQLite, is subject to change without
-** notice, and should not be referenced by programs that use SQLite.
-**
-** Some of the definitions that are in this file are marked as
-** "experimental".  Experimental interfaces are normally new
-** features recently added to SQLite.  We do not anticipate changes 
-** to experimental interfaces but reserve to make minor changes if
-** experience from use "in the wild" suggest such changes are prudent.
-**
-** The official C-language API documentation for SQLite is derived
-** from comments in this file.  This file is the authoritative source
-** on how SQLite interfaces are suppose to operate.
-**
-** The name of this file under configuration management is "sqlite.h.in".
-** The makefile makes some minor changes to this file (such as inserting
-** the version number) and changes its name to "sqlite3.h" as
-** part of the build process.
-**
-** @(#) $Id: sqlite3.c,v 1.8 2007/09/14 21:07:51 dmose%mozilla.org Exp $
-*/
-#ifndef _SQLITE3_H_
-#define _SQLITE3_H_
-#include <stdarg.h>     /* Needed for the definition of va_list */
-
-/*
-** Make sure we can call this stuff from C++.
-*/
-#if 0
-extern "C" {
-#endif
-
-/*
-** Make sure these symbols where not defined by some previous header
-** file.
-*/
-#ifdef SQLITE_VERSION
-# undef SQLITE_VERSION
-#endif
-#ifdef SQLITE_VERSION_NUMBER
-# undef SQLITE_VERSION_NUMBER
-#endif
-
-/*
-** CAPI3REF: Compile-Time Library Version Numbers
-**
-** The version of the SQLite library is contained in the sqlite3.h
-** header file in a #define named SQLITE_VERSION.  The SQLITE_VERSION
-** macro resolves to a string constant.
-**
-** The format of the version string is "X.Y.Z", where
-** X is the major version number, Y is the minor version number and Z
-** is the release number.  The X.Y.Z might be followed by "alpha" or "beta".
-** For example "3.1.1beta".
-**
-** The X value is always 3 in SQLite.  The X value only changes when
-** backwards compatibility is broken and we intend to never break
-** backwards compatibility.  The Y value only changes when
-** there are major feature enhancements that are forwards compatible
-** but not backwards compatible.  The Z value is incremented with
-** each release but resets back to 0 when Y is incremented.
-**
-** The SQLITE_VERSION_NUMBER is an integer with the value 
-** (X*1000000 + Y*1000 + Z). For example, for version "3.1.1beta", 
-** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using 
-** version 3.1.1 or greater at compile time, programs may use the test 
-** (SQLITE_VERSION_NUMBER>=3001001).
-**
-** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
-*/
-#define SQLITE_VERSION         "3.4.1"
-#define SQLITE_VERSION_NUMBER 3004001
-
-/*
-** CAPI3REF: Run-Time Library Version Numbers
-**
-** These routines return values equivalent to the header constants
-** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER].  The values returned
-** by this routines should only be different from the header values
-** if you compile your program using an sqlite3.h header from a
-** different version of SQLite that the version of the library you
-** link against.
-**
-** The sqlite3_version[] string constant contains the text of the
-** [SQLITE_VERSION] string.  The sqlite3_libversion() function returns
-** a poiner to the sqlite3_version[] string constant.  The function
-** is provided for DLL users who can only access functions and not
-** constants within the DLL.
-*/
-extern const char sqlite3_version[];
-SQLITE_API const char *sqlite3_libversion(void);
-int sqlite3_libversion_number(void);
-
-/*
-** CAPI3REF: Database Connection Handle
-**
-** Each open SQLite database is represented by pointer to an instance of the
-** opaque structure named "sqlite3".  It is useful to think of an sqlite3
-** pointer as an object.  The [sqlite3_open] interface is its constructor
-** and [sqlite3_close] is its destructor.  There are many other interfaces
-** (such as [sqlite3_prepare_v2], [sqlite3_create_function], and
-** [sqlite3_busy_timeout] to name but three) that are methods on this
-** object.
-*/
-typedef struct sqlite3 sqlite3;
-
-
-/*
-** CAPI3REF: 64-Bit Integer Types
-**
-** Some compilers do not support the "long long" datatype.  So we have
-** to do compiler-specific typedefs for 64-bit signed and unsigned integers.
-**
-** Many SQLite interface functions require a 64-bit integer arguments.
-** Those interfaces are declared using this typedef.
-*/
-#ifdef SQLITE_INT64_TYPE
-  typedef SQLITE_INT64_TYPE sqlite_int64;
-  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
-#elif defined(_MSC_VER) || defined(__BORLANDC__)
-  typedef __int64 sqlite_int64;
-  typedef unsigned __int64 sqlite_uint64;
-#else
-  typedef long long int sqlite_int64;
-  typedef unsigned long long int sqlite_uint64;
-#endif
-
-/*
-** If compiling for a processor that lacks floating point support,
-** substitute integer for floating-point
-*/
-#ifdef SQLITE_OMIT_FLOATING_POINT
-# define double sqlite_int64
-#endif
-
-/*
-** CAPI3REF: Closing A Database Connection
-**
-** Call this function with a pointer to a structure that was previously
-** returned from [sqlite3_open()] and the corresponding database will by
-** closed.
-**
-** All SQL statements prepared using [sqlite3_prepare_v2()] or
-** [sqlite3_prepare16_v2()] must be destroyed using [sqlite3_finalize()]
-** before this routine is called. Otherwise, SQLITE_BUSY is returned and the
-** database connection remains open.
-*/
-SQLITE_API int sqlite3_close(sqlite3 *);
-
-/*
-** The type for a callback function.
-** This is legacy and deprecated.  It is included for historical
-** compatibility and is not documented.
-*/
-typedef int (*sqlite3_callback)(void*,int,char**, char**);
-
-/*
-** CAPI3REF: One-Step Query Execution Interface
-**
-** This interface is used to do a one-time evaluatation of zero
-** or more SQL statements.  UTF-8 text of the SQL statements to
-** be evaluted is passed in as the second parameter.  The statements
-** are prepared one by one using [sqlite3_prepare()], evaluated
-** using [sqlite3_step()], then destroyed using [sqlite3_finalize()].
-**
-** If one or more of the SQL statements are queries, then
-** the callback function specified by the 3rd parameter is
-** invoked once for each row of the query result.  This callback
-** should normally return 0.  If the callback returns a non-zero
-** value then the query is aborted, all subsequent SQL statements
-** are skipped and the sqlite3_exec() function returns the SQLITE_ABORT.
-**
-** The 4th parameter to this interface is an arbitrary pointer that is
-** passed through to the callback function as its first parameter.
-**
-** The 2nd parameter to the callback function is the number of
-** columns in the query result.  The 3rd parameter to the callback
-** is an array of strings holding the values for each column
-** as extracted using [sqlite3_column_text()].
-** The 4th parameter to the callback is an array of strings
-** obtained using [sqlite3_column_name()] and holding
-** the names of each column.
-**
-** The callback function may be NULL, even for queries.  A NULL
-** callback is not an error.  It just means that no callback
-** will be invoked.
-**
-** If an error occurs while parsing or evaluating the SQL (but
-** not while executing the callback) then an appropriate error
-** message is written into memory obtained from [sqlite3_malloc()] and
-** *errmsg is made to point to that message.  The calling function
-** is responsible for freeing the memory that holds the error
-** message.   Use [sqlite3_free()] for this.  If errmsg==NULL,
-** then no error message is ever written.
-**
-** The return value is is SQLITE_OK if there are no errors and
-** some other [SQLITE_OK | return code] if there is an error.  
-** The particular return value depends on the type of error. 
-**
-*/
-SQLITE_API int sqlite3_exec(
-  sqlite3*,                                  /* An open database */
-  const char *sql,                           /* SQL to be evaluted */
-  int (*callback)(void*,int,char**,char**),  /* Callback function */
-  void *,                                    /* 1st argument to callback */
-  char **errmsg                              /* Error msg written here */
-);
-
-/*
-** CAPI3REF: Result Codes
-** KEYWORDS: SQLITE_OK
-**
-** Many SQLite functions return an integer result code from the set shown
-** above in order to indicates success or failure.
-**
-** The result codes above are the only ones returned by SQLite in its
-** default configuration.  However, the [sqlite3_extended_result_codes()]
-** API can be used to set a database connectoin to return more detailed
-** result codes.
-**
-** See also: [SQLITE_IOERR_READ | extended result codes]
-**
-*/
-#define SQLITE_OK           0   /* Successful result */
-/* beginning-of-error-codes */
-#define SQLITE_ERROR        1   /* SQL error or missing database */
-#define SQLITE_INTERNAL     2   /* NOT USED. Internal logic error in SQLite */
-#define SQLITE_PERM         3   /* Access permission denied */
-#define SQLITE_ABORT        4   /* Callback routine requested an abort */
-#define SQLITE_BUSY         5   /* The database file is locked */
-#define SQLITE_LOCKED       6   /* A table in the database is locked */
-#define SQLITE_NOMEM        7   /* A malloc() failed */
-#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
-#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
-#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
-#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
-#define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
-#define SQLITE_FULL        13   /* Insertion failed because database is full */
-#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
-#define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
-#define SQLITE_EMPTY       16   /* Database is empty */
-#define SQLITE_SCHEMA      17   /* The database schema changed */
-#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
-#define SQLITE_CONSTRAINT  19   /* Abort due to contraint violation */
-#define SQLITE_MISMATCH    20   /* Data type mismatch */
-#define SQLITE_MISUSE      21   /* Library used incorrectly */
-#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
-#define SQLITE_AUTH        23   /* Authorization denied */
-#define SQLITE_FORMAT      24   /* Auxiliary database format error */
-#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
-#define SQLITE_NOTADB      26   /* File opened that is not a database file */
-#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
-#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
-/* end-of-error-codes */
-
-/*
-** CAPI3REF: Extended Result Codes
-**
-** In its default configuration, SQLite API routines return one of 26 integer
-** result codes described at result-codes.  However, experience has shown that
-** many of these result codes are too course-grained.  They do not provide as
-** much information about problems as users might like.  In an effort to
-** address this, newer versions of SQLite (version 3.3.8 and later) include
-** support for additional result codes that provide more detailed information
-** about errors.  The extended result codes are enabled (or disabled) for 
-** each database
-** connection using the [sqlite3_extended_result_codes()] API.
-** 
-** Some of the available extended result codes are listed above.
-** We expect the number of extended result codes will be expand
-** over time.  Software that uses extended result codes should expect
-** to see new result codes in future releases of SQLite.
-** 
-** The symbolic name for an extended result code always contains a related
-** primary result code as a prefix.  Primary result codes contain a single
-** "_" character.  Extended result codes contain two or more "_" characters.
-** The numeric value of an extended result code can be converted to its
-** corresponding primary result code by masking off the lower 8 bytes.
-**
-** The SQLITE_OK result code will never be extended.  It will always
-** be exactly zero.
-*/
-#define SQLITE_IOERR_READ          (SQLITE_IOERR | (1<<8))
-#define SQLITE_IOERR_SHORT_READ    (SQLITE_IOERR | (2<<8))
-#define SQLITE_IOERR_WRITE         (SQLITE_IOERR | (3<<8))
-#define SQLITE_IOERR_FSYNC         (SQLITE_IOERR | (4<<8))
-#define SQLITE_IOERR_DIR_FSYNC     (SQLITE_IOERR | (5<<8))
-#define SQLITE_IOERR_TRUNCATE      (SQLITE_IOERR | (6<<8))
-#define SQLITE_IOERR_FSTAT         (SQLITE_IOERR | (7<<8))
-#define SQLITE_IOERR_UNLOCK        (SQLITE_IOERR | (8<<8))
-#define SQLITE_IOERR_RDLOCK        (SQLITE_IOERR | (9<<8))
-#define SQLITE_IOERR_DELETE        (SQLITE_IOERR | (10<<8))
-#define SQLITE_IOERR_BLOCKED       (SQLITE_IOERR | (11<<8))
-
-/*
-** CAPI3REF: Enable Or Disable Extended Result Codes
-**
-** This routine enables or disables the
-** [SQLITE_IOERR_READ | extended result codes] feature.
-** By default, SQLite API routines return one of only 26 integer
-** [SQLITE_OK | result codes].  When extended result codes
-** are enabled by this routine, the repetoire of result codes can be
-** much larger and can (hopefully) provide more detailed information
-** about the cause of an error.
-**
-** The second argument is a boolean value that turns extended result
-** codes on and off.  Extended result codes are off by default for
-** backwards compatibility with older versions of SQLite.
-*/
-int sqlite3_extended_result_codes(sqlite3*, int onoff);
-
-/*
-** CAPI3REF: Last Insert Rowid
-**
-** Each entry in an SQLite table has a unique 64-bit signed integer key
-** called the "rowid". The rowid is always available as an undeclared
-** column named ROWID, OID, or _ROWID_.  If the table has a column of
-** type INTEGER PRIMARY KEY then that column is another an alias for the
-** rowid.
-**
-** This routine returns the rowid of the most recent INSERT into
-** the database from the database connection given in the first 
-** argument.  If no inserts have ever occurred on this database
-** connection, zero is returned.
-**
-** If an INSERT occurs within a trigger, then the rowid of the
-** inserted row is returned by this routine as long as the trigger
-** is running.  But once the trigger terminates, the value returned
-** by this routine reverts to the last value inserted before the
-** trigger fired.
-*/
-sqlite_int64 sqlite3_last_insert_rowid(sqlite3*);
-
-/*
-** CAPI3REF: Count The Number Of Rows Modified
-**
-** This function returns the number of database rows that were changed
-** (or inserted or deleted) by the most recent SQL statement.  Only
-** changes that are directly specified by the INSERT, UPDATE, or
-** DELETE statement are counted.  Auxiliary changes caused by
-** triggers are not counted.  Use the [sqlite3_total_changes()] function
-** to find the total number of changes including changes caused by triggers.
-**
-** Within the body of a trigger, the sqlite3_changes() interface can be
-** called to find the number of
-** changes in the most recently completed INSERT, UPDATE, or DELETE
-** statement within the body of the trigger.
-**
-** All changes are counted, even if they were later undone by a
-** ROLLBACK or ABORT.  Except, changes associated with creating and
-** dropping tables are not counted.
-**
-** If a callback invokes [sqlite3_exec()] or [sqlite3_step()] recursively,
-** then the changes in the inner, recursive call are counted together
-** with the changes in the outer call.
-**
-** SQLite implements the command "DELETE FROM table" without a WHERE clause
-** by dropping and recreating the table.  (This is much faster than going
-** through and deleting individual elements from the table.)  Because of
-** this optimization, the change count for "DELETE FROM table" will be
-** zero regardless of the number of elements that were originally in the
-** table. To get an accurate count of the number of rows deleted, use
-** "DELETE FROM table WHERE 1" instead.
-*/
-SQLITE_API int sqlite3_changes(sqlite3*);
-
-/*
-** CAPI3REF: Total Number Of Rows Modified
-***
-** This function returns the number of database rows that have been
-** modified by INSERT, UPDATE or DELETE statements since the database handle
-** was opened. This includes UPDATE, INSERT and DELETE statements executed
-** as part of trigger programs. All changes are counted as soon as the
-** statement that makes them is completed (when the statement handle is
-** passed to [sqlite3_reset()] or [sqlite_finalise()]).
-**
-** See also the [sqlite3_change()] interface.
-**
-** SQLite implements the command "DELETE FROM table" without a WHERE clause
-** by dropping and recreating the table.  (This is much faster than going
-** through and deleting individual elements form the table.)  Because of
-** this optimization, the change count for "DELETE FROM table" will be
-** zero regardless of the number of elements that were originally in the
-** table. To get an accurate count of the number of rows deleted, use
-** "DELETE FROM table WHERE 1" instead.
-*/
-int sqlite3_total_changes(sqlite3*);
-
-/*
-** CAPI3REF: Interrupt A Long-Running Query
-**
-** This function causes any pending database operation to abort and
-** return at its earliest opportunity.  This routine is typically
-** called in response to a user action such as pressing "Cancel"
-** or Ctrl-C where the user wants a long query operation to halt
-** immediately.
-**
-** It is safe to call this routine from a thread different from the
-** thread that is currently running the database operation.
-**
-** The SQL operation that is interrupted will return [SQLITE_INTERRUPT].
-** If an interrupted operation was an update that is inside an
-** explicit transaction, then the entire transaction will be rolled
-** back automatically.
-*/
-SQLITE_API void sqlite3_interrupt(sqlite3*);
-
-/*
-** CAPI3REF: Determine If An SQL Statement Is Complete
-**
-** These functions return true if the given input string comprises
-** one or more complete SQL statements. For the sqlite3_complete() call,
-** the parameter must be a nul-terminated UTF-8 string. For
-** sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string
-** is required.
-**
-** These routines are useful for command-line input to determine if the
-** currently entered text forms one or more complete SQL statements or
-** if additional input is needed before sending the statements into
-** SQLite for parsing. The algorithm is simple.  If the 
-** last token other than spaces and comments is a semicolon, then return 
-** true.  Actually, the algorithm is a little more complicated than that
-** in order to deal with triggers, but the basic idea is the same:  the
-** statement is not complete unless it ends in a semicolon.
-*/
-SQLITE_API int sqlite3_complete(const char *sql);
-SQLITE_API int sqlite3_complete16(const void *sql);
-
-/*
-** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
-**
-** This routine identifies a callback function that might be invoked
-** whenever an attempt is made to open a database table 
-** that another thread or process has locked.
-** If the busy callback is NULL, then [SQLITE_BUSY]
-** (or sometimes [SQLITE_IOERR_BLOCKED])
-** is returned immediately upon encountering the lock.
-** If the busy callback is not NULL, then the
-** callback will be invoked with two arguments.  The
-** first argument to the handler is a copy of the void* pointer which
-** is the third argument to this routine.  The second argument to
-** the handler is the number of times that the busy handler has
-** been invoked for this locking event. If the
-** busy callback returns 0, then no additional attempts are made to
-** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
-** If the callback returns non-zero, then another attempt is made to open the
-** database for reading and the cycle repeats.
-**
-** The presence of a busy handler does not guarantee that
-** it will be invoked when there is lock contention.
-** If SQLite determines that invoking the busy handler could result in
-** a deadlock, it will return [SQLITE_BUSY] instead.
-** Consider a scenario where one process is holding a read lock that
-** it is trying to promote to a reserved lock and
-** a second process is holding a reserved lock that it is trying
-** to promote to an exclusive lock.  The first process cannot proceed
-** because it is blocked by the second and the second process cannot
-** proceed because it is blocked by the first.  If both processes
-** invoke the busy handlers, neither will make any progress.  Therefore,
-** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
-** will induce the first process to release its read lock and allow
-** the second process to proceed.
-**
-** The default busy callback is NULL.
-**
-** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] when
-** SQLite is in the middle of a large transaction where all the
-** changes will not fit into the in-memory cache.  SQLite will
-** already hold a RESERVED lock on the database file, but it needs
-** to promote this lock to EXCLUSIVE so that it can spill cache
-** pages into the database file without harm to concurrent
-** readers.  If it is unable to promote the lock, then the in-memory
-** cache will be left in an inconsistent state and so the error
-** code is promoted from the relatively benign [SQLITE_BUSY] to
-** the more severe [SQLITE_IOERR_BLOCKED].  This error code promotion
-** forces an automatic rollback of the changes. See the
-** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
-** CorruptionFollowingBusyError</a> wiki page for a discussion of why
-** this is important.
-**	
-** Sqlite is re-entrant, so the busy handler may start a new query. 
-** (It is not clear why anyone would every want to do this, but it
-** is allowed, in theory.)  But the busy handler may not close the
-** database.  Closing the database from a busy handler will delete 
-** data structures out from under the executing query and will 
-** probably result in a segmentation fault or other runtime error.
-**
-** There can only be a single busy handler defined for each database
-** connection.  Setting a new busy handler clears any previous one.
-** Note that calling [sqlite3_busy_timeout()] will also set or clear
-** the busy handler.
-*/
-int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
-
-/*
-** CAPI3REF: Set A Busy Timeout
-**
-** This routine sets a busy handler that sleeps for a while when a
-** table is locked.  The handler will sleep multiple times until 
-** at least "ms" milliseconds of sleeping have been done.  After
-** "ms" milliseconds of sleeping, the handler returns 0 which
-** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
-**
-** Calling this routine with an argument less than or equal to zero
-** turns off all busy handlers.
-**
-** There can only be a single busy handler for a particular database
-** connection.  If another busy handler was defined  
-** (using [sqlite3_busy_handler()]) prior to calling
-** this routine, that other busy handler is cleared.
-*/
-int sqlite3_busy_timeout(sqlite3*, int ms);
-
-/*
-** CAPI3REF: Convenience Routines For Running Queries
-**
-** This next routine is a convenience wrapper around [sqlite3_exec()].
-** Instead of invoking a user-supplied callback for each row of the
-** result, this routine remembers each row of the result in memory
-** obtained from [sqlite3_malloc()], then returns all of the result after the
-** query has finished. 
-**
-** As an example, suppose the query result where this table:
-**
-** <pre>
-**        Name        | Age
-**        -----------------------
-**        Alice       | 43
-**        Bob         | 28
-**        Cindy       | 21
-** </pre>
-**
-** If the 3rd argument were &azResult then after the function returns
-** azResult will contain the following data:
-**
-** <pre>
-**        azResult[0] = "Name";
-**        azResult[1] = "Age";
-**        azResult[2] = "Alice";
-**        azResult[3] = "43";
-**        azResult[4] = "Bob";
-**        azResult[5] = "28";
-**        azResult[6] = "Cindy";
-**        azResult[7] = "21";
-** </pre>
-**
-** Notice that there is an extra row of data containing the column
-** headers.  But the *nrow return value is still 3.  *ncolumn is
-** set to 2.  In general, the number of values inserted into azResult
-** will be ((*nrow) + 1)*(*ncolumn).
-**
-** After the calling function has finished using the result, it should 
-** pass the result data pointer to sqlite3_free_table() in order to 
-** release the memory that was malloc-ed.  Because of the way the 
-** [sqlite3_malloc()] happens, the calling function must not try to call 
-** [sqlite3_free()] directly.  Only [sqlite3_free_table()] is able to release 
-** the memory properly and safely.
-**
-** The return value of this routine is the same as from [sqlite3_exec()].
-*/
-int sqlite3_get_table(
-  sqlite3*,              /* An open database */
-  const char *sql,       /* SQL to be executed */
-  char ***resultp,       /* Result written to a char *[]  that this points to */
-  int *nrow,             /* Number of result rows written here */
-  int *ncolumn,          /* Number of result columns written here */
-  char **errmsg          /* Error msg written here */
-);
-void sqlite3_free_table(char **result);
-
-/*
-** CAPI3REF: Formatted String Printing Functions
-**
-** These routines are workalikes of the "printf()" family of functions
-** from the standard C library.
-**
-** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
-** results into memory obtained from [sqlite_malloc()].
-** The strings returned by these two routines should be
-** released by [sqlite3_free()].  Both routines return a
-** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
-** memory to hold the resulting string.
-**
-** In sqlite3_snprintf() routine is similar to "snprintf()" from
-** the standard C library.  The result is written into the
-** buffer supplied as the second parameter whose size is given by
-** the first parameter.  Note that the order of the
-** first two parameters is reversed from snprintf().  This is an
-** historical accident that cannot be fixed without breaking
-** backwards compatibility.  Note also that sqlite3_snprintf()
-** returns a pointer to its buffer instead of the number of
-** characters actually written into the buffer.  We admit that
-** the number of characters written would be a more useful return
-** value but we cannot change the implementation of sqlite3_snprintf()
-** now without breaking compatibility.
-**
-** As long as the buffer size is greater than zero, sqlite3_snprintf()
-** guarantees that the buffer is always zero-terminated.  The first
-** parameter "n" is the total size of the buffer, including space for
-** the zero terminator.  So the longest string that can be completely
-** written will be n-1 characters.
-**
-** These routines all implement some additional formatting
-** options that are useful for constructing SQL statements.
-** All of the usual printf formatting options apply.  In addition, there
-** is are "%q" and "%Q" options.
-**
-** The %q option works like %s in that it substitutes a null-terminated
-** string from the argument list.  But %q also doubles every '\'' character.
-** %q is designed for use inside a string literal.  By doubling each '\''
-** character it escapes that character and allows it to be inserted into
-** the string.
-**
-** For example, so some string variable contains text as follows:
-**
-** <blockquote><pre>
-**  char *zText = "It's a happy day!";
-** </pre></blockquote>
-**
-** One can use this text in an SQL statement as follows:
-**
-** <blockquote><pre>
-**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
-**  sqlite3_exec(db, zSQL, 0, 0, 0);
-**  sqlite3_free(zSQL);
-** </pre></blockquote>
-**
-** Because the %q format string is used, the '\'' character in zText
-** is escaped and the SQL generated is as follows:
-**
-** <blockquote><pre>
-**  INSERT INTO table1 VALUES('It''s a happy day!')
-** </pre></blockquote>
-**
-** This is correct.  Had we used %s instead of %q, the generated SQL
-** would have looked like this:
-**
-** <blockquote><pre>
-**  INSERT INTO table1 VALUES('It's a happy day!');
-** </pre></blockquote>
-**
-** This second example is an SQL syntax error.  As a general rule you
-** should always use %q instead of %s when inserting text into a string 
-** literal.
-**
-** The %Q option works like %q except it also adds single quotes around
-** the outside of the total string.  Or if the parameter in the argument
-** list is a NULL pointer, %Q substitutes the text "NULL" (without single
-** quotes) in place of the %Q option.  So, for example, one could say:
-**
-** <blockquote><pre>
-**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
-**  sqlite3_exec(db, zSQL, 0, 0, 0);
-**  sqlite3_free(zSQL);
-** </pre></blockquote>
-**
-** The code above will render a correct SQL statement in the zSQL
-** variable even if the zText variable is a NULL pointer.
-*/
-SQLITE_API char *sqlite3_mprintf(const char*,...);
-SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
-SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
-
-/*
-** CAPI3REF: Memory Allocation Functions
-**
-** SQLite uses its own memory allocator.  On some installations, this
-** memory allocator is identical to the standard malloc()/realloc()/free()
-** and can be used interchangable.  On others, the implementations are
-** different.  For maximum portability, it is best not to mix calls
-** to the standard malloc/realloc/free with the sqlite versions.
-*/
-SQLITE_API void *sqlite3_malloc(int);
-SQLITE_API void *sqlite3_realloc(void*, int);
-SQLITE_API void sqlite3_free(void*);
-
-/*
-** CAPI3REF: Compile-Time Authorization Callbacks
-***
-** This routine registers a authorizer callback with the SQLite library.  
-** The authorizer callback is invoked as SQL statements are being compiled
-** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
-** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  At various
-** points during the compilation process, as logic is being created
-** to perform various actions, the authorizer callback is invoked to
-** see if those actions are allowed.  The authorizer callback should
-** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the
-** specific action but allow the SQL statement to continue to be
-** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
-** rejected with an error.  
-**
-** Depending on the action, the [SQLITE_IGNORE] and [SQLITE_DENY] return
-** codes might mean something different or they might mean the same
-** thing.  If the action is, for example, to perform a delete opertion,
-** then [SQLITE_IGNORE] and [SQLITE_DENY] both cause the statement compilation
-** to fail with an error.  But if the action is to read a specific column
-** from a specific table, then [SQLITE_DENY] will cause the entire
-** statement to fail but [SQLITE_IGNORE] will cause a NULL value to be
-** read instead of the actual column value.
-**
-** The first parameter to the authorizer callback is a copy of
-** the third parameter to the sqlite3_set_authorizer() interface.
-** The second parameter to the callback is an integer 
-** [SQLITE_COPY | action code] that specifies the particular action
-** to be authorized.  The available action codes are
-** [SQLITE_COPY | documented separately].  The third through sixth
-** parameters to the callback are strings that contain additional
-** details about the action to be authorized.
-**
-** An authorizer is used when preparing SQL statements from an untrusted
-** source, to ensure that the SQL statements do not try to access data
-** that they are not allowed to see, or that they do not try to
-** execute malicious statements that damage the database.  For
-** example, an application may allow a user to enter arbitrary
-** SQL queries for evaluation by a database.  But the application does
-** not want the user to be able to make arbitrary changes to the
-** database.  An authorizer could then be put in place while the
-** user-entered SQL is being prepared that disallows everything
-** except SELECT statements.  
-**
-** Only a single authorizer can be in place on a database connection
-** at a time.  Each call to sqlite3_set_authorizer overrides the
-** previous call.  A NULL authorizer means that no authorization
-** callback is invoked.  The default authorizer is NULL.
-**
-** Note that the authorizer callback is invoked only during 
-** [sqlite3_prepare()] or its variants.  Authorization is not
-** performed during statement evaluation in [sqlite3_step()].
-*/
-int sqlite3_set_authorizer(
-  sqlite3*,
-  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
-  void *pUserData
-);
-
-/*
-** CAPI3REF: Authorizer Return Codes
-**
-** The [sqlite3_set_authorizer | authorizer callback function] must
-** return either [SQLITE_OK] or one of these two constants in order
-** to signal SQLite whether or not the action is permitted.  See the
-** [sqlite3_set_authorizer | authorizer documentation] for additional
-** information.
-*/
-#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
-#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
-
-/*
-** CAPI3REF: Authorizer Action Codes
-**
-** The [sqlite3_set_authorizer()] interface registers a callback function
-** that is invoked to authorizer certain SQL statement actions.  The
-** second parameter to the callback is an integer code that specifies
-** what action is being authorized.  These are the integer action codes that
-** the authorizer callback may be passed.
-**
-** These action code values signify what kind of operation is to be 
-** authorized.  The 3rd and 4th parameters to the authorization callback
-** function will be parameters or NULL depending on which of these
-** codes is used as the second parameter.  The 5th parameter to the
-** authorizer callback is the name of the database ("main", "temp", 
-** etc.) if applicable.  The 6th parameter to the authorizer callback
-** is the name of the inner-most trigger or view that is responsible for
-** the access attempt or NULL if this access attempt is directly from 
-** top-level SQL code.
-*/
-/******************************************* 3rd ************ 4th ***********/
-#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
-#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
-#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
-#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
-#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
-#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
-#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
-#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
-#define SQLITE_DELETE                9   /* Table Name      NULL            */
-#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
-#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
-#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
-#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
-#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
-#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
-#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
-#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
-#define SQLITE_INSERT               18   /* Table Name      NULL            */
-#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
-#define SQLITE_READ                 20   /* Table Name      Column Name     */
-#define SQLITE_SELECT               21   /* NULL            NULL            */
-#define SQLITE_TRANSACTION          22   /* NULL            NULL            */
-#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
-#define SQLITE_ATTACH               24   /* Filename        NULL            */
-#define SQLITE_DETACH               25   /* Database Name   NULL            */
-#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
-#define SQLITE_REINDEX              27   /* Index Name      NULL            */
-#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
-#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
-#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
-#define SQLITE_FUNCTION             31   /* Function Name   NULL            */
-#define SQLITE_COPY                  0   /* No longer used */
-
-/*
-** CAPI3REF: Tracing And Profiling Functions
-**
-** These routines register callback functions that can be used for
-** tracing and profiling the execution of SQL statements.
-** The callback function registered by sqlite3_trace() is invoked
-** at the first [sqlite3_step()] for the evaluation of an SQL statement.
-** The callback function registered by sqlite3_profile() is invoked
-** as each SQL statement finishes and includes
-** information on how long that statement ran.
-**
-** The sqlite3_profile() API is currently considered experimental and
-** is subject to change.
-*/
-SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
-SQLITE_API void *sqlite3_profile(sqlite3*,
-   void(*xProfile)(void*,const char*,sqlite_uint64), void*);
-
-/*
-** CAPI3REF: Query Progress Callbacks
-**
-** This routine configures a callback function - the progress callback - that
-** is invoked periodically during long running calls to [sqlite3_exec()],
-** [sqlite3_step()] and [sqlite3_get_table()].  An example use for this 
-** interface is to keep a GUI updated during a large query.
-**
-** The progress callback is invoked once for every N virtual machine opcodes,
-** where N is the second argument to this function. The progress callback
-** itself is identified by the third argument to this function. The fourth
-** argument to this function is a void pointer passed to the progress callback
-** function each time it is invoked.
-**
-** If a call to [sqlite3_exec()], [sqlite3_step()], or [sqlite3_get_table()]
-** results in fewer than N opcodes being executed, then the progress 
-** callback is never invoked.
-** 
-** Only a single progress callback function may be registered for each
-** open database connection.  Every call to sqlite3_progress_handler()
-** overwrites the results of the previous call.
-** To remove the progress callback altogether, pass NULL as the third
-** argument to this function.
-**
-** If the progress callback returns a result other than 0, then the current 
-** query is immediately terminated and any database changes rolled back.
-** The containing [sqlite3_exec()], [sqlite3_step()], or
-** [sqlite3_get_table()] call returns SQLITE_INTERRUPT.   This feature
-** can be used, for example, to implement the "Cancel" button on a
-** progress dialog box in a GUI.
-*/
-void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
-
-/*
-** CAPI3REF: Opening A New Database Connection
-**
-** Open the sqlite database file "filename".  The "filename" is UTF-8
-** encoded for sqlite3_open() and UTF-16 encoded in the native byte order
-** for sqlite3_open16().  An [sqlite3*] handle is returned in *ppDb, even
-** if an error occurs. If the database is opened (or created) successfully,
-** then SQLITE_OK is returned. Otherwise an error code is returned. The
-** sqlite3_errmsg() or sqlite3_errmsg16()  routines can be used to obtain
-** an English language description of the error.
-**
-** If the database file does not exist, then a new database will be created
-** as needed.  The default encoding for the database will be UTF-8 if
-** sqlite3_open() is called and UTF-16 if sqlite3_open16 is used.
-**
-** Whether or not an error occurs when it is opened, resources associated
-** with the [sqlite3*] handle should be released by passing it to
-** sqlite3_close() when it is no longer required.
-**
-** Note to windows users:  The encoding used for the filename argument
-** of sqlite3_open() must be UTF-8, not whatever codepage is currently
-** defined.  Filenames containing international characters must be converted
-** to UTF-8 prior to passing them into sqlite3_open().
-*/
-SQLITE_API int sqlite3_open(
-  const char *filename,   /* Database filename (UTF-8) */
-  sqlite3 **ppDb          /* OUT: SQLite db handle */
-);
-SQLITE_API int sqlite3_open16(
-  const void *filename,   /* Database filename (UTF-16) */
-  sqlite3 **ppDb          /* OUT: SQLite db handle */
-);
-
-/*
-** CAPI3REF: Error Codes And Messages
-**
-** The sqlite3_errcode() interface returns the numeric
-** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code]
-** for the most recent failed sqlite3_* API call associated
-** with [sqlite3] handle 'db'.  If a prior API call failed but the
-** most recent API call succeeded, the return value from sqlite3_errcode()
-** is undefined. 
-**
-** The sqlite3_errmsg() and sqlite3_errmsg16() return English-langauge
-** text that describes the error, as either UTF8 or UTF16 respectively.
-** Memory to hold the error message string is managed internally.  The 
-** string may be overwritten or deallocated by subsequent calls to SQLite
-** interface functions.
-**
-** Calls to many sqlite3_* functions set the error code and string returned
-** by [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()]
-** (overwriting the previous values). Note that calls to [sqlite3_errcode()],
-** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the
-** results of future invocations.  Calls to API routines that do not return
-** an error code (examples: [sqlite3_data_count()] or [sqlite3_mprintf()]) do
-** not change the error code returned by this routine.
-**
-** Assuming no other intervening sqlite3_* API calls are made, the error
-** code returned by this function is associated with the same error as
-** the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()].
-*/
-SQLITE_API int sqlite3_errcode(sqlite3 *db);
-SQLITE_API const char *sqlite3_errmsg(sqlite3*);
-SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
-
-/*
-** CAPI3REF: SQL Statement Object
-**
-** Instance of this object represent single SQL statements.  This
-** is variously known as a "prepared statement" or a 
-** "compiled SQL statement" or simply as a "statement".
-** 
-** The life of a statement object goes something like this:
-**
-** <ol>
-** <li> Create the object using [sqlite3_prepare_v2()] or a related
-**      function.
-** <li> Bind values to host parameters using
-**      [sqlite3_bind_blob | sqlite3_bind_* interfaces].
-** <li> Run the SQL by calling [sqlite3_step()] one or more times.
-** <li> Reset the statement using [sqlite3_reset()] then go back
-**      to step 2.  Do this zero or more times.
-** <li> Destroy the object using [sqlite3_finalize()].
-** </ol>
-**
-** Refer to documentation on individual methods above for additional
-** information.
-*/
-typedef struct sqlite3_stmt sqlite3_stmt;
-
-/*
-** CAPI3REF: Compiling An SQL Statement
-**
-** To execute an SQL query, it must first be compiled into a byte-code
-** program using one of these routines. 
-**
-** The first argument "db" is an [sqlite3 | SQLite database handle] 
-** obtained from a prior call to [sqlite3_open()] or [sqlite3_open16()].
-** The second argument "zSql" is the statement to be compiled, encoded
-** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
-** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
-** use UTF-16.
-**
-** If the nByte argument is less
-** than zero, then zSql is read up to the first zero terminator.  If
-** nByte is non-negative, then it is the maximum number of 
-** bytes read from zSql.  When nByte is non-negative, the
-** zSql string ends at either the first '\000' character or 
-** until the nByte-th byte, whichever comes first.
-**
-** *pzTail is made to point to the first byte past the end of the first
-** SQL statement in zSql.  This routine only compiles the first statement
-** in zSql, so *pzTail is left pointing to what remains uncompiled.
-**
-** *ppStmt is left pointing to a compiled 
-** [sqlite3_stmt | SQL statement structure] that can be
-** executed using [sqlite3_step()].  Or if there is an error, *ppStmt may be
-** set to NULL.  If the input text contained no SQL (if the input is and
-** empty string or a comment) then *ppStmt is set to NULL.  The calling
-** procedure is responsible for deleting the compiled SQL statement
-** using [sqlite3_finalize()] after it has finished with it.
-**
-** On success, [SQLITE_OK] is returned.  Otherwise an 
-** [SQLITE_ERROR | error code] is returned.
-**
-** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
-** recommended for all new programs. The two older interfaces are retained
-** for backwards compatibility, but their use is discouraged.
-** In the "v2" interfaces, the prepared statement
-** that is returned (the [sqlite3_stmt] object) contains a copy of the 
-** original SQL text. This causes the [sqlite3_step()] interface to
-** behave a differently in two ways:
-**
-** <ol>
-** <li>
-** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
-** always used to do, [sqlite3_step()] will automatically recompile the SQL
-** statement and try to run it again.  If the schema has changed in a way
-** that makes the statement no longer valid, [sqlite3_step()] will still
-** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
-** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
-** error go away.  Note: use [sqlite3_errmsg()] to find the text of the parsing
-** error that results in an [SQLITE_SCHEMA] return.
-** </li>
-**
-** <li>
-** When an error occurs, 
-** [sqlite3_step()] will return one of the detailed 
-** [SQLITE_ERROR | result codes] or
-** [SQLITE_IOERR_READ | extended result codes] such as directly.
-** The legacy behavior was that [sqlite3_step()] would only return a generic
-** [SQLITE_ERROR] result code and you would have to make a second call to
-** [sqlite3_reset()] in order to find the underlying cause of the problem.
-** With the "v2" prepare interfaces, the underlying reason for the error is
-** returned immediately.
-** </li>
-** </ol>
-*/
-SQLITE_API int sqlite3_prepare(
-  sqlite3 *db,            /* Database handle */
-  const char *zSql,       /* SQL statement, UTF-8 encoded */
-  int nByte,              /* Maximum length of zSql in bytes. */
-  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
-  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
-);
-int sqlite3_prepare_v2(
-  sqlite3 *db,            /* Database handle */
-  const char *zSql,       /* SQL statement, UTF-8 encoded */
-  int nByte,              /* Maximum length of zSql in bytes. */
-  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
-  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
-);
-SQLITE_API int sqlite3_prepare16(
-  sqlite3 *db,            /* Database handle */
-  const void *zSql,       /* SQL statement, UTF-16 encoded */
-  int nByte,              /* Maximum length of zSql in bytes. */
-  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
-  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
-);
-int sqlite3_prepare16_v2(
-  sqlite3 *db,            /* Database handle */
-  const void *zSql,       /* SQL statement, UTF-16 encoded */
-  int nByte,              /* Maximum length of zSql in bytes. */
-  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
-  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
-);
-
-/*
-** CAPI3REF:  Dynamically Typed Value Object
-**
-** SQLite uses dynamic typing for the values it stores.  Values can 
-** be integers, floating point values, strings, BLOBs, or NULL.  When
-** passing around values internally, each value is represented as
-** an instance of the sqlite3_value object.
-*/
-typedef struct Mem sqlite3_value;
-
-/*
-** CAPI3REF:  SQL Function Context Object
-**
-** The context in which an SQL function executes is stored in an
-** sqlite3_context object.  A pointer to such an object is the
-** first parameter to user-defined SQL functions.
-*/
-typedef struct sqlite3_context sqlite3_context;
-
-/*
-** CAPI3REF:  Binding Values To Prepared Statements
-**
-** In the SQL strings input to [sqlite3_prepare_v2()] and its variants,
-** one or more literals can be replace by a parameter in one of these
-** forms:
-**
-** <ul>
-** <li>  ?
-** <li>  ?NNN
-** <li>  :AAA
-** <li>  @AAA
-** <li>  $VVV
-** </ul>
-**
-** In the parameter forms shown above NNN is an integer literal,
-** AAA is an alphanumeric identifier and VVV is a variable name according
-** to the syntax rules of the TCL programming language.
-** The values of these parameters (also called "host parameter names")
-** can be set using the sqlite3_bind_*() routines defined here.
-**
-** The first argument to the sqlite3_bind_*() routines always is a pointer
-** to the [sqlite3_stmt] object returned from [sqlite3_prepare_v2()] or
-** its variants.  The second
-** argument is the index of the parameter to be set.  The first parameter has
-** an index of 1. When the same named parameter is used more than once, second
-** and subsequent
-** occurrences have the same index as the first occurrence.  The index for
-** named parameters can be looked up using the
-** [sqlite3_bind_parameter_name()] API if desired.  The index for "?NNN"
-** parametes is the value of NNN.
-** The NNN value must be between 1 and the compile-time
-** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999).
-** See <a href="limits.html">limits.html</a> for additional information.
-**
-** The third argument is the value to bind to the parameter.
-**
-** In those
-** routines that have a fourth argument, its value is the number of bytes
-** in the parameter.  To be clear: the value is the number of bytes in the
-** string, not the number of characters.  The number
-** of bytes does not include the zero-terminator at the end of strings.
-** If the fourth parameter is negative, the length of the string is
-** number of bytes up to the first zero terminator.
-**
-** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
-** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
-** text after SQLite has finished with it.  If the fifth argument is the
-** special value [SQLITE_STATIC], then the library assumes that the information
-** is in static, unmanaged space and does not need to be freed.  If the
-** fifth argument has the value [SQLITE_TRANSIENT], then SQLite makes its
-** own private copy of the data immediately, before the sqlite3_bind_*()
-** routine returns.
-**
-** The sqlite3_bind_zeroblob() routine binds a BLOB of length n that
-** is filled with zeros.  A zeroblob uses a fixed amount of memory
-** (just an integer to hold it size) while it is being processed.
-** Zeroblobs are intended to serve as place-holders for BLOBs whose
-** content is later written using 
-** [sqlite3_blob_open | increment BLOB I/O] routines.
-**
-** The sqlite3_bind_*() routines must be called after
-** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
-** before [sqlite3_step()].
-** Bindings are not cleared by the [sqlite3_reset()] routine.
-** Unbound parameters are interpreted as NULL.
-**
-** These routines return [SQLITE_OK] on success or an error code if
-** anything goes wrong.  [SQLITE_RANGE] is returned if the parameter
-** index is out of range.  [SQLITE_NOMEM] is returned if malloc fails.
-** [SQLITE_MISUSE] is returned if these routines are called on a virtual
-** machine that is the wrong state or which has already been finalized.
-*/
-int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
-int sqlite3_bind_double(sqlite3_stmt*, int, double);
-int sqlite3_bind_int(sqlite3_stmt*, int, int);
-int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite_int64);
-int sqlite3_bind_null(sqlite3_stmt*, int);
-int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
-int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
-int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
-int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
-
-/*
-** CAPI3REF: Number Of Host Parameters
-**
-** Return the largest host parameter index in the precompiled statement given
-** as the argument.  When the host parameters are of the forms like ":AAA"
-** or "?", then they are assigned sequential increasing numbers beginning
-** with one, so the value returned is the number of parameters.  However
-** if the same host parameter name is used multiple times, each occurrance
-** is given the same number, so the value returned in that case is the number
-** of unique host parameter names.  If host parameters of the form "?NNN"
-** are used (where NNN is an integer) then there might be gaps in the
-** numbering and the value returned by this interface is the index of the
-** host parameter with the largest index value.
-*/
-int sqlite3_bind_parameter_count(sqlite3_stmt*);
-
-/*
-** CAPI3REF: Name Of A Host Parameter
-**
-** This routine returns a pointer to the name of the n-th parameter in a 
-** [sqlite3_stmt | prepared statement].
-** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name
-** which is the string ":AAA" or "@AAA" or "$VVV".  
-** In other words, the initial ":" or "$" or "@"
-** is included as part of the name.
-** Parameters of the form "?" or "?NNN" have no name.
-**
-** The first bound parameter has an index of 1, not 0.
-**
-** If the value n is out of range or if the n-th parameter is nameless,
-** then NULL is returned.  The returned string is always in the
-** UTF-8 encoding even if the named parameter was originally specified
-** as UTF-16 in [sqlite3_prepare16()] or [sqlite3_prepare16_v2()].
-*/
-const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
-
-/*
-** CAPI3REF: Index Of A Parameter With A Given Name
-**
-** This routine returns the index of a host parameter with the given name.
-** The name must match exactly.  If no parameter with the given name is 
-** found, return 0.  Parameter names must be UTF8.
-*/
-int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
-
-/*
-** CAPI3REF: Reset All Bindings On A Prepared Statement
-**