Merge m-c to s-c
authorPhilipp von Weitershausen <philipp@weitershausen.de>
Tue, 06 Sep 2011 09:07:39 -0700
changeset 76743 f9a690b1bd21b496784e70b39bdb6b6a36e7dc37
parent 76742 ac2f7fe1b6bf301958501e2359248bd106d26bf0 (current diff)
parent 76569 1f5cd567c93a7ef6db27aa0539bdc2a4099935d0 (diff)
child 76744 6c980882ea3a4874af5def8e1bb4a7573bc4523f
push id3
push userfelipc@gmail.com
push dateFri, 30 Sep 2011 20:09:13 +0000
milestone9.0a1
Merge m-c to s-c
browser/base/content/test/tabview/browser_tabview_bug604699.js
browser/base/content/test/tabview/browser_tabview_bug627239.js
content/canvas/src/WebGLValidateStrings.h
content/xslt/build.mk
content/xslt/confvars.sh
content/xslt/src/base/txSimpleErrorObserver.cpp
content/xslt/src/base/txStringUtils.cpp
content/xslt/src/main/Makefile.in
content/xslt/src/main/testXalan.cpp
content/xslt/src/main/transformiix.cpp
content/xslt/src/main/txTestExpr.cpp
content/xslt/src/main/txXSLTMarkDriver.cpp
content/xslt/src/xml/txAttr.cpp
content/xslt/src/xml/txDocument.cpp
content/xslt/src/xml/txElement.cpp
content/xslt/src/xml/txNodeDefinition.cpp
content/xslt/src/xml/txProcessingInstruction.cpp
content/xslt/src/xpath/txStandaloneXPathTreeWalker.cpp
content/xslt/src/xslt/txHTMLOutput.cpp
content/xslt/src/xslt/txHTMLOutput.h
content/xslt/src/xslt/txStandaloneStylesheetCompiler.cpp
content/xslt/src/xslt/txStandaloneStylesheetCompiler.h
content/xslt/src/xslt/txStandaloneXSLTProcessor.cpp
content/xslt/src/xslt/txStandaloneXSLTProcessor.h
content/xslt/src/xslt/txTextOutput.cpp
content/xslt/src/xslt/txTextOutput.h
content/xslt/src/xslt/txXMLOutput.cpp
content/xslt/src/xslt/txXMLOutput.h
js/src/jsinvoke.cpp
netwerk/build.mk
netwerk/confvars.sh
xpcom/reflect/xptcall/src/md/unix/xptcinvoke_asm_irix.s
xpcom/reflect/xptcall/src/md/unix/xptcinvoke_irix.cpp
xpcom/reflect/xptcall/src/md/unix/xptcstubs_asm_irix.s
xpcom/reflect/xptcall/src/md/unix/xptcstubs_irix.cpp
--- a/accessible/public/nsIAccessible.idl
+++ b/accessible/public/nsIAccessible.idl
@@ -51,17 +51,17 @@ interface nsIAccessibleRelation;
  * accessibility APIs like MSAA and ATK. Contains the sum of what's needed
  * to support IAccessible as well as ATK's generic accessibility objects.
  * Can also be used by in-process accessibility clients to get information
  * about objects in the accessible tree. The accessible tree is a subset of 
  * nodes in the DOM tree -- such as documents, focusable elements and text.
  * Mozilla creates the implementations of nsIAccessible on demand.
  * See http://www.mozilla.org/projects/ui/accessibility for more information.
  */
-[scriptable, uuid(c7ac764a-b4c5-4479-9fb7-06e3c9f3db34)]
+[scriptable, uuid(3126544c-826c-4694-a2ed-67bfe56a1f37)]
 interface nsIAccessible : nsISupports
 {
   /**
    * Parent node in accessible tree.
    */
   readonly attribute nsIAccessible parent;
 
   /**
@@ -217,36 +217,16 @@ interface nsIAccessible : nsISupports
   nsIAccessible getDeepestChildAtPoint(in long x, in long y);
 
   /**
    * Nth accessible child using zero-based index or last child if index less than zero
    */
   nsIAccessible getChildAt(in long aChildIndex);
 
   /**
-   * Accessible node geometrically to the right of this one
-   */
-  nsIAccessible getAccessibleToRight();
-
-  /**
-   * Accessible node geometrically to the left of this one
-   */
-  nsIAccessible getAccessibleToLeft();
-
-  /**
-   * Accessible node geometrically above this one
-   */
-  nsIAccessible getAccessibleAbove();
-
-  /**
-   * Accessible node geometrically below this one
-   */
-  nsIAccessible getAccessibleBelow();
-
-  /**
    * Return accessible relation by the given relation type (see.
    * constants defined in nsIAccessibleRelation).
    */
   nsIAccessibleRelation getRelationByType(in unsigned long aRelationType);
 
   /**
    * Returns multiple accessible relations for this object.
    */
--- a/accessible/src/base/NotificationController.cpp
+++ b/accessible/src/base/NotificationController.cpp
@@ -676,20 +676,25 @@ NotificationController::TextEnumerator(n
         if (atomid)
           atomid->ToUTF8String(id);
       }
 
       printf("\npending text node insertion: container: %s@id='%s', index in container: %d\n\n",
              tag.get(), id.get(), index);
 #endif
 
+    // Make sure the text node is in accessible document still.
     nsAccessible* container = document->GetAccessibleOrContainer(containerNode);
-    nsTArray<nsCOMPtr<nsIContent> > insertedContents;
-    insertedContents.AppendElement(textNode);
-    document->ProcessContentInserted(container, &insertedContents);
+    NS_ASSERTION(container,
+                 "Text node having rendered text hasn't accessible document!");
+    if (container) {
+      nsTArray<nsCOMPtr<nsIContent> > insertedContents;
+      insertedContents.AppendElement(textNode);
+      document->ProcessContentInserted(container, &insertedContents);
+    }
   }
 
   return PL_DHASH_NEXT;
 }
 
 
 ////////////////////////////////////////////////////////////////////////////////
 // NotificationController: content inserted notification
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -638,16 +638,19 @@ nsAccessibilityService::GetAccessibleFor
                                          nsIAccessible **aAccessible)
 {
   NS_ENSURE_ARG_POINTER(aAccessible);
   *aAccessible = nsnull;
   if (!aNode)
     return NS_OK;
 
   nsCOMPtr<nsINode> node(do_QueryInterface(aNode));
+  if (!node)
+    return NS_ERROR_INVALID_ARG;
+
   NS_IF_ADDREF(*aAccessible = GetAccessible(node));
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsAccessibilityService::GetStringRole(PRUint32 aRole, nsAString& aString)
 {
   if ( aRole >= NS_ARRAY_LENGTH(kRoleNames)) {
@@ -807,24 +810,30 @@ nsAccessibilityService::GetStringRelatio
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsAccessibilityService::GetAccessibleFromCache(nsIDOMNode* aNode,
                                                nsIAccessible** aAccessible)
 {
   NS_ENSURE_ARG_POINTER(aAccessible);
+  *aAccessible = nsnull;
+  if (!aNode)
+    return NS_OK;
+
+  nsCOMPtr<nsINode> node(do_QueryInterface(aNode));
+  if (!node)
+    return NS_ERROR_INVALID_ARG;
 
   // Search for an accessible in each of our per document accessible object
   // caches. If we don't find it, and the given node is itself a document, check
   // our cache of document accessibles (document cache). Note usually shutdown
   // document accessibles are not stored in the document cache, however an
   // "unofficially" shutdown document (i.e. not from nsAccDocManager) can still
   // exist in the document cache.
-  nsCOMPtr<nsINode> node(do_QueryInterface(aNode));
   nsAccessible* accessible = FindAccessibleInCache(node);
   if (!accessible) {
     nsCOMPtr<nsIDocument> document(do_QueryInterface(node));
     if (document)
       accessible = GetDocAccessibleFromCache(document);
   }
 
   NS_IF_ADDREF(*aAccessible = accessible);
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -1969,40 +1969,16 @@ nsAccessible::DoAction(PRUint8 aIndex)
 }
 
 /* DOMString getHelp (); */
 NS_IMETHODIMP nsAccessible::GetHelp(nsAString& _retval)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
-/* nsIAccessible getAccessibleToRight(); */
-NS_IMETHODIMP nsAccessible::GetAccessibleToRight(nsIAccessible **_retval)
-{
-  return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-/* nsIAccessible getAccessibleToLeft(); */
-NS_IMETHODIMP nsAccessible::GetAccessibleToLeft(nsIAccessible **_retval)
-{
-  return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-/* nsIAccessible getAccessibleAbove(); */
-NS_IMETHODIMP nsAccessible::GetAccessibleAbove(nsIAccessible **_retval)
-{
-  return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-/* nsIAccessible getAccessibleBelow(); */
-NS_IMETHODIMP nsAccessible::GetAccessibleBelow(nsIAccessible **_retval)
-{
-  return NS_ERROR_NOT_IMPLEMENTED;
-}
-
 nsIContent*
 nsAccessible::GetAtomicRegion() const
 {
   nsIContent *loopContent = mContent;
   nsAutoString atomic;
   while (loopContent && !loopContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::aria_atomic, atomic))
     loopContent = loopContent->GetParent();
 
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -1412,21 +1412,19 @@ nsDocAccessible::ContentRemoved(nsIConte
 void
 nsDocAccessible::RecreateAccessible(nsIContent* aContent)
 {
   // XXX: we shouldn't recreate whole accessible subtree, instead we should
   // subclass hide and show events to handle them separately and implement their
   // coalescence with normal hide and show events. Note, in this case they
   // should be coalesced with normal show/hide events.
 
-  // Check if the node is in DOM still.
-  nsIContent* parentContent = aContent->GetParent();
-  if (parentContent && parentContent->IsInDoc()) {
-    nsAccessible* container = GetAccessibleOrContainer(parentContent);
-
+  // Check if the node is in accessible document.
+  nsAccessible* container = GetContainerAccessible(aContent);
+  if (container) {
     // Remove and reinsert.
     UpdateTree(container, aContent, false);
     container->UpdateChildren();
     UpdateTree(container, aContent, true);
   }
 }
 
 void
@@ -1435,18 +1433,16 @@ nsDocAccessible::ProcessInvalidationList
   // Invalidate children of container accessible for each element in
   // invalidation list. Allow invalidation list insertions while container
   // children are recached.
   for (PRUint32 idx = 0; idx < mInvalidationList.Length(); idx++) {
     nsIContent* content = mInvalidationList[idx];
     nsAccessible* accessible = GetAccessible(content);
     if (!accessible) {
       nsAccessible* container = GetContainerAccessible(content);
-      NS_ASSERTION(container,
-                   "Got a referenced element that is not in document!");
       if (container) {
         container->UpdateChildren();
         accessible = GetAccessible(content);
       }
     }
 
     // Make sure the subtree is created.
     if (accessible)
--- a/accessible/src/html/nsHTMLFormControlAccessible.cpp
+++ b/accessible/src/html/nsHTMLFormControlAccessible.cpp
@@ -441,16 +441,25 @@ NS_IMETHODIMP nsHTMLTextFieldAccessible:
   nsCOMPtr<nsIDOMHTMLInputElement> inputElement(do_QueryInterface(mContent));
   if (inputElement) {
     return inputElement->GetValue(_retval);
   }
 
   return NS_ERROR_FAILURE;
 }
 
+void
+nsHTMLTextFieldAccessible::ApplyARIAState(PRUint64* aState)
+{
+  nsHyperTextAccessibleWrap::ApplyARIAState(aState);
+
+  nsStateMapEntry::MapToStates(mContent, aState, eARIAAutoComplete);
+
+}
+
 PRUint64
 nsHTMLTextFieldAccessible::NativeState()
 {
   PRUint64 state = nsHyperTextAccessibleWrap::NativeState();
 
   // can be focusable, focused, protected. readonly, unavailable, selected
   if (mContent->AttrValueIs(kNameSpaceID_None, nsAccessibilityAtoms::type,
                             nsAccessibilityAtoms::password, eIgnoreCase)) {
--- a/accessible/src/html/nsHTMLFormControlAccessible.h
+++ b/accessible/src/html/nsHTMLFormControlAccessible.h
@@ -154,16 +154,17 @@ public:
   NS_IMETHOD GetValue(nsAString& _retval); 
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
   NS_IMETHOD DoAction(PRUint8 index);
 
   // nsIAccessibleEditableText
   NS_IMETHOD GetAssociatedEditor(nsIEditor **aEditor);
 
   // nsAccessible
+  virtual void ApplyARIAState(PRUint64* aState);
   virtual nsresult GetNameInternal(nsAString& aName);
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
 
   // ActionAccessible
   virtual PRUint8 ActionCount();
 };
 
--- a/accessible/src/msaa/nsAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsAccessibleWrap.cpp
@@ -805,52 +805,45 @@ STDMETHODIMP nsAccessibleWrap::accNaviga
       /* [in] */ long navDir,
       /* [optional][in] */ VARIANT varStart,
       /* [retval][out] */ VARIANT __RPC_FAR *pvarEndUpAt)
 {
 __try {
   if (!pvarEndUpAt)
     return E_INVALIDARG;
 
-  nsAccessible *xpAccessibleStart = GetXPAccessibleFor(varStart);
-  if (!xpAccessibleStart || IsDefunct())
+  nsAccessible* accessible = GetXPAccessibleFor(varStart);
+  if (!accessible || accessible->IsDefunct())
     return E_FAIL;
 
   VariantInit(pvarEndUpAt);
 
-  nsCOMPtr<nsIAccessible> xpAccessibleResult;
+  nsAccessible* navAccessible = nsnull;
   PRUint32 xpRelation = 0;
 
   switch(navDir) {
-    case NAVDIR_DOWN:
-      xpAccessibleStart->GetAccessibleBelow(getter_AddRefs(xpAccessibleResult));
-      break;
     case NAVDIR_FIRSTCHILD:
-      if (!nsAccUtils::MustPrune(xpAccessibleStart))
-        xpAccessibleStart->GetFirstChild(getter_AddRefs(xpAccessibleResult));
+      if (!nsAccUtils::MustPrune(accessible))
+        navAccessible = accessible->FirstChild();
       break;
     case NAVDIR_LASTCHILD:
-      if (!nsAccUtils::MustPrune(xpAccessibleStart))
-        xpAccessibleStart->GetLastChild(getter_AddRefs(xpAccessibleResult));
-      break;
-    case NAVDIR_LEFT:
-      xpAccessibleStart->GetAccessibleToLeft(getter_AddRefs(xpAccessibleResult));
+      if (!nsAccUtils::MustPrune(accessible))
+        navAccessible = accessible->LastChild();
       break;
     case NAVDIR_NEXT:
-      xpAccessibleStart->GetNextSibling(getter_AddRefs(xpAccessibleResult));
+      navAccessible = accessible->NextSibling();
       break;
     case NAVDIR_PREVIOUS:
-      xpAccessibleStart->GetPreviousSibling(getter_AddRefs(xpAccessibleResult));
+      navAccessible = accessible->PrevSibling();
       break;
+    case NAVDIR_DOWN:
+    case NAVDIR_LEFT:
     case NAVDIR_RIGHT:
-      xpAccessibleStart->GetAccessibleToRight(getter_AddRefs(xpAccessibleResult));
-      break;
     case NAVDIR_UP:
-      xpAccessibleStart->GetAccessibleAbove(getter_AddRefs(xpAccessibleResult));
-      break;
+      return E_NOTIMPL;
 
     // MSAA relationship extensions to accNavigate
     case NAVRELATION_CONTROLLED_BY:
       xpRelation = nsIAccessibleRelation::RELATION_CONTROLLED_BY;
       break;
     case NAVRELATION_CONTROLLER_FOR:
       xpRelation = nsIAccessibleRelation::RELATION_CONTROLLER_FOR;
       break;
@@ -891,27 +884,30 @@ STDMETHODIMP nsAccessibleWrap::accNaviga
       xpRelation = nsIAccessibleRelation::RELATION_DEFAULT_BUTTON;
       break;
     case NAVRELATION_DESCRIBED_BY:
       xpRelation = nsIAccessibleRelation::RELATION_DESCRIBED_BY;
       break;
     case NAVRELATION_DESCRIPTION_FOR:
       xpRelation = nsIAccessibleRelation::RELATION_DESCRIPTION_FOR;
       break;
+
+    default:
+      return E_INVALIDARG;
   }
 
   pvarEndUpAt->vt = VT_EMPTY;
 
   if (xpRelation) {
     Relation rel = RelationByType(xpRelation);
-    xpAccessibleResult = rel.Next();
+    navAccessible = rel.Next();
   }
 
-  if (xpAccessibleResult) {
-    pvarEndUpAt->pdispVal = NativeAccessible(xpAccessibleResult);
+  if (navAccessible) {
+    pvarEndUpAt->pdispVal = NativeAccessible(navAccessible);
     pvarEndUpAt->vt = VT_DISPATCH;
     return S_OK;
   }
 } __except(nsAccessNodeWrap::FilterA11yExceptions(::GetExceptionCode(), GetExceptionInformation())) { }
   return E_FAIL;
 }
 
 STDMETHODIMP nsAccessibleWrap::accHitTest(
--- a/accessible/tests/mochitest/states/test_aria.html
+++ b/accessible/tests/mochitest/states/test_aria.html
@@ -62,16 +62,19 @@
       // aria_autocomplete
       testStates("textbox_autocomplete_inline", 0, EXT_STATE_SUPPORTS_AUTOCOMPLETION);
       testStates("textbox_autocomplete_list", STATE_HASPOPUP, EXT_STATE_SUPPORTS_AUTOCOMPLETION);
       testStates("textbox_autocomplete_both", STATE_HASPOPUP, EXT_STATE_SUPPORTS_AUTOCOMPLETION);
       testStates("combobox_autocomplete_inline", STATE_HASPOPUP, EXT_STATE_SUPPORTS_AUTOCOMPLETION);
       testStates("combobox_autocomplete_list", STATE_HASPOPUP, EXT_STATE_SUPPORTS_AUTOCOMPLETION);
       testStates("combobox_autocomplete_both", STATE_HASPOPUP, EXT_STATE_SUPPORTS_AUTOCOMPLETION);
 
+      testStates("htmltext_autocomplete_list", STATE_HASPOPUP, EXT_STATE_SUPPORTS_AUTOCOMPLETION);
+      testStates("htmltextarea_autocomplete_list", STATE_HASPOPUP, EXT_STATE_SUPPORTS_AUTOCOMPLETION);
+
       // aria-busy
       testStates("textbox_busy_false", 0, 0, STATE_BUSY);
       testStates("textbox_busy_true", STATE_BUSY);
       testStates("textbox_busy_error", STATE_INVALID);
 
       // aria-expanded
       testStates("combobox", STATE_COLLAPSED);
       testStates("combobox_expanded", STATE_EXPANDED);
@@ -147,28 +150,36 @@
      title="Propagate aria-disabled to descendants">
     Mozilla Bug 429285
   </a>
   <a target="_blank"
      href="https://bugzilla.mozilla.org/show_bug.cgi?id=499653"
      title="Unify ARIA state attributes mapping rules">
     Mozilla Bug 499653
   </a>
+  <a target="_blank"
+     href="https://bugzilla.mozilla.org/show_bug.cgi?id=681674"
+     title="aria-autocomplete not supported on standard form text input controls">
+    Mozilla Bug 681674
+  </a>
   <p id="display"></p>
   <div id="content" style="display: none"></div>
   <pre id="test">
   </pre>
 
   <div id="textbox_autocomplete_inline" role="textbox" aria-autocomplete="inline"></div>
   <div id="textbox_autocomplete_list" role="textbox" aria-autocomplete="list"></div>
   <div id="textbox_autocomplete_both" role="textbox" aria-autocomplete="both"></div>
   <div id="combobox_autocomplete_inline" role="combobox" aria-autocomplete="inline"></div>
   <div id="combobox_autocomplete_list" role="combobox" aria-autocomplete="list"></div>
   <div id="combobox_autocomplete_both" role="combobox" aria-autocomplete="both"></div>
 
+  <input id="htmltext_autocomplete_list" type="text" aria-autocomplete="list" />
+  <textarea id="htmltextarea_autocomplete_list" aria-autocomplete="list"></textarea>
+
   <div id="textbox_busy_false" role="textbox" aria-busy="false"></div>
   <div id="textbox_busy_true" role="textbox" aria-busy="true"></div>
   <div id="textbox_busy_error" role="textbox" aria-busy="error"></div>
 
   <div id="combobox" role="combobox">combobox</div>
   <div id="combobox_expanded" role="combobox"
        aria-expanded="true">combobox</div>
 
--- a/aclocal.m4
+++ b/aclocal.m4
@@ -11,16 +11,17 @@ builtin(include, build/autoconf/pkg.m4)d
 builtin(include, build/autoconf/freetype2.m4)dnl
 builtin(include, build/autoconf/codeset.m4)dnl
 builtin(include, build/autoconf/altoptions.m4)dnl
 builtin(include, build/autoconf/mozprog.m4)dnl
 builtin(include, build/autoconf/mozheader.m4)dnl
 builtin(include, build/autoconf/acwinpaths.m4)dnl
 builtin(include, build/autoconf/lto.m4)dnl
 builtin(include, build/autoconf/gcc-pr49911.m4)dnl
+builtin(include, build/autoconf/frameptr.m4)dnl
 
 MOZ_PROG_CHECKMSYS()
 
 # Read the user's .mozconfig script.  We can't do this in
 # configure.in: autoconf puts the argument parsing code above anything
 # expanded from configure.in, and we need to get the configure options
 # from .mozconfig in place before that argument parsing code.
 MOZ_READ_MOZCONFIG(.)
--- a/browser/base/content/browser-fullZoom.js
+++ b/browser/base/content/browser-fullZoom.js
@@ -63,21 +63,18 @@ var FullZoom = {
   },
 
   // browser.zoom.siteSpecific preference cache
   _siteSpecificPref: undefined,
 
   // browser.zoom.updateBackgroundTabs preference cache
   updateBackgroundTabs: undefined,
 
-  // whether we are in private browsing mode
-  _inPrivateBrowsing: false,
-
   get siteSpecific() {
-    return !this._inPrivateBrowsing && this._siteSpecificPref;
+    return this._siteSpecificPref;
   },
 
   //**************************************************************************//
   // nsISupports
 
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIDOMEventListener,
                                          Ci.nsIObserver,
                                          Ci.nsIContentPrefObserver,
@@ -89,36 +86,26 @@ var FullZoom = {
 
   init: function FullZoom_init() {
     // Listen for scrollwheel events so we can save scrollwheel-based changes.
     window.addEventListener("DOMMouseScroll", this, false);
 
     // Register ourselves with the service so we know when our pref changes.
     Services.contentPrefs.addObserver(this.name, this);
 
-    // We disable site-specific preferences in Private Browsing mode, because the
-    // content preferences module is disabled
-    Services.obs.addObserver(this, "private-browsing", true);
-
-    // Retrieve the initial status of the Private Browsing mode.
-    this._inPrivateBrowsing = Cc["@mozilla.org/privatebrowsing;1"].
-                              getService(Ci.nsIPrivateBrowsingService).
-                              privateBrowsingEnabled;
-
     this._siteSpecificPref =
       gPrefService.getBoolPref("browser.zoom.siteSpecific");
     this.updateBackgroundTabs =
       gPrefService.getBoolPref("browser.zoom.updateBackgroundTabs");
     // Listen for changes to the browser.zoom branch so we can enable/disable
     // updating background tabs and per-site saving and restoring of zoom levels.
     gPrefService.addObserver("browser.zoom.", this, true);
   },
 
   destroy: function FullZoom_destroy() {
-    Services.obs.removeObserver(this, "private-browsing");
     gPrefService.removeObserver("browser.zoom.", this);
     Services.contentPrefs.removeObserver(this.name, this);
     window.removeEventListener("DOMMouseScroll", this, false);
   },
 
 
   //**************************************************************************//
   // Event Handlers
@@ -182,26 +169,16 @@ var FullZoom = {
               gPrefService.getBoolPref("browser.zoom.siteSpecific");
             break;
           case "browser.zoom.updateBackgroundTabs":
             this.updateBackgroundTabs =
               gPrefService.getBoolPref("browser.zoom.updateBackgroundTabs");
             break;
         }
         break;
-      case "private-browsing":
-        switch (aData) {
-          case "enter":
-            this._inPrivateBrowsing = true;
-            break;
-          case "exit":
-            this._inPrivateBrowsing = false;
-            break;
-        }
-        break;
     }
   },
 
   // nsIContentPrefObserver
 
   onContentPrefSet: function FullZoom_onContentPrefSet(aGroup, aName, aValue) {
     if (aGroup == Services.contentPrefs.grouper.group(gBrowser.currentURI))
       this._applyPrefToSetting(aValue);
@@ -316,24 +293,22 @@ var FullZoom = {
    * and perhaps the same is true for full zoom
    * (although DocumentViewerImpl::SetFullZoom doesn't mention it).
    *
    * So when we apply new zoom values to the browser, we simply set the zoom.
    * We don't check first to see if the new value is the same as the current
    * one.
    **/
   _applyPrefToSetting: function FullZoom__applyPrefToSetting(aValue, aBrowser) {
-    if ((!this.siteSpecific && !this._inPrivateBrowsing) ||
-        gInPrintPreviewMode)
+    if ((!this.siteSpecific) || gInPrintPreviewMode)
       return;
 
     var browser = aBrowser || (gBrowser && gBrowser.selectedBrowser);
     try {
-      if (browser.contentDocument instanceof Ci.nsIImageDocument ||
-          this._inPrivateBrowsing)
+      if (browser.contentDocument instanceof Ci.nsIImageDocument)
         ZoomManager.setZoomForBrowser(browser, 1);
       else if (typeof aValue != "undefined")
         ZoomManager.setZoomForBrowser(browser, this._ensureValid(aValue));
       else if (typeof this.globalValue != "undefined")
         ZoomManager.setZoomForBrowser(browser, this.globalValue);
       else
         ZoomManager.setZoomForBrowser(browser, 1);
     }
--- a/browser/base/content/nsContextMenu.js
+++ b/browser/base/content/nsContextMenu.js
@@ -316,20 +316,18 @@ nsContextMenu.prototype = {
                   !this.onTextInput && top.gBidiUI);
   },
 
   initSpellingItems: function() {
     var canSpell = InlineSpellCheckerUI.canSpellCheck;
     var onMisspelling = InlineSpellCheckerUI.overMisspelling;
     this.showItem("spell-check-enabled", canSpell);
     this.showItem("spell-separator", canSpell || this.onEditableArea);
-    if (canSpell) {
-      document.getElementById("spell-check-enabled")
-              .setAttribute("checked", InlineSpellCheckerUI.enabled);
-    }
+    document.getElementById("spell-check-enabled")
+            .setAttribute("checked", canSpell && InlineSpellCheckerUI.enabled);
 
     this.showItem("spell-add-to-dictionary", onMisspelling);
 
     // suggestion list
     this.showItem("spell-suggestions-separator", onMisspelling);
     if (onMisspelling) {
       var suggestionsSeparator =
         document.getElementById("spell-add-to-dictionary");
--- a/browser/base/content/tabview/content.js
+++ b/browser/base/content/tabview/content.js
@@ -29,18 +29,161 @@
  * 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 ***** */
 
-addEventListener("DOMWillOpenModalDialog", function (event) {
-  // (event.isTrusted == true) when the event is generated by a user action
-  // and does not originate from a script.
-  if (event.isTrusted) {
+"use strict";
+
+const Cu = Components.utils;
+
+Cu.import("resource:///modules/tabview/utils.jsm");
+
+// Bug 671101 - directly using webProgress in this context
+// causes docShells to leak
+__defineGetter__("webProgress", function () {
+  let ifaceReq = docShell.QueryInterface(Ci.nsIInterfaceRequestor);
+  return ifaceReq.getInterface(Ci.nsIWebProgress);
+});
+
+// ----------
+// WindowEventHandler
+//
+// Handles events dispatched by the content window.
+let WindowEventHandler = {
+  // ----------
+  // Function: onDOMContentLoaded
+  // Sends an asynchronous message when the "onDOMContentLoaded" event for the
+  // current page is fired.
+  onDOMContentLoaded: function WEH_onDOMContentLoaded(event) {
+    sendAsyncMessage("Panorama:DOMContentLoaded");
+  },
+
+  // ----------
+  // Function: onDOMWillOpenModalDialog
+  // Sends a synchronous message when the "onDOMWillOpenModalDialog" event
+  // is fired right before a modal dialog will be opened by the current page.
+  onDOMWillOpenModalDialog: function WEH_onDOMWillOpenModalDialog(event) {
+    // (event.isTrusted == true) when the event is generated by a user action
+    // and does not originate from a script.
+    if (!event.isTrusted)
+      return;
+
     // we're intentionally sending a synchronous message to handle this event
     // as quick as possible, switch the selected tab and hide the tabview
     // before the modal dialog is shown
     sendSyncMessage("Panorama:DOMWillOpenModalDialog");
   }
-}, true);
+};
+
+// add event listeners
+addEventListener("DOMContentLoaded", WindowEventHandler.onDOMContentLoaded, false);
+addEventListener("DOMWillOpenModalDialog", WindowEventHandler.onDOMWillOpenModalDialog, false);
+
+// ----------
+// WindowMessageHandler
+//
+// Handles messages sent by the chrome process.
+let WindowMessageHandler = {
+  // ----------
+  // Function: isDocumentLoaded
+  // Checks if the currently active document is loaded.
+  isDocumentLoaded: function WMH_isDocumentLoaded(cx) {
+    let isLoaded = (content.document.readyState == "complete" &&
+                    !webProgress.isLoadingDocument);
+
+    sendAsyncMessage(cx.name, {isLoaded: isLoaded});
+  }
+};
+
+// add message listeners
+addMessageListener("Panorama:isDocumentLoaded", WindowMessageHandler.isDocumentLoaded);
+
+// ----------
+// WebProgressListener
+//
+// Observe the web progress of content pages loaded into this browser. When the
+// state of a page changes we check if we're still allowed to store page
+// information permanently.
+let WebProgressListener = {
+  // ----------
+  // Function: onStateChange
+  // Called by the webProgress when its state changes.
+  onStateChange: function WPL_onStateChange(webProgress, request, flag, status) {
+    // The browser just started loading (again). Explicitly grant storage
+    // because the browser might have been blocked before (e.g. when navigating
+    // from a https-page to a http-page).
+    if (flag & Ci.nsIWebProgressListener.STATE_START) {
+      // ensure the dom window is the top one
+      if (this._isTopWindow(webProgress))
+        sendAsyncMessage("Panorama:StoragePolicy:granted");
+    }
+
+    // The browser finished loading - check the cache control headers. Send
+    // a message if we're not allowed to store information about this page.
+    if (flag & Ci.nsIWebProgressListener.STATE_STOP) {
+      // ensure the dom window is the top one
+      if (this._isTopWindow(webProgress) &&
+          request && request instanceof Ci.nsIHttpChannel) {
+        request.QueryInterface(Ci.nsIHttpChannel);
+
+        let exclude = false;
+        let reason = "";
+
+        // Check if the "Cache-Control" header is "no-store". In this case we're
+        // not allowed to store information about the current page.
+        if (this._isNoStoreResponse(request)) {
+          exclude = true;
+          reason = "no-store";
+        }
+        // Otherwise we'll deny storage if we're currently viewing a https
+        // page without a "Cache-Control: public" header.
+        else if (request.URI.schemeIs("https")) {
+          let cacheControlHeader = this._getCacheControlHeader(request);
+          if (cacheControlHeader && !(/public/i).test(cacheControlHeader)) {
+            exclude = true;
+            reason = "https";
+          }
+        }
+
+        if (exclude)
+          sendAsyncMessage("Panorama:StoragePolicy:denied", {reason: reason});
+      }
+    }
+  },
+
+  // ----------
+  // Function: _isTopWindow
+  // Returns whether the DOMWindow associated with the webProgress is the
+  // top content window (and not an iframe or similar).
+  _isTopWindow: function WPL__isTopWindow(webProgress) {
+    // can throw if there's no associated DOMWindow
+    return !!Utils.attempt(function () webProgress.DOMWindow == content);
+  },
+
+  // ----------
+  // Function: _isNoStoreResponse
+  // Checks if the "Cache-Control" header is "no-store".
+  _isNoStoreResponse: function WPL__isNoStoreResponse(req) {
+    // can throw if called before the response has been received
+    return !!Utils.attempt(function () req.isNoStoreResponse());
+  },
+
+  // ----------
+  // Function: _getCacheControlHeader
+  // Returns the value of the "Cache-Control" header.
+  _getCacheControlHeader: function WPL__getCacheControlHeader(req) {
+    // can throw when the "Cache-Control" header doesn't exist
+    return Utils.attempt(function () req.getResponseHeader("Cache-Control"));
+  },
+
+  // ----------
+  // Implements progress listener interface.
+  QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
+                                         Ci.nsISupportsWeakReference,
+                                         Ci.nsISupports])
+};
+
+// add web progress listener
+webProgress.addProgressListener(WebProgressListener, Ci.nsIWebProgress.NOTIFY_STATE_WINDOW);
--- a/browser/base/content/tabview/modules/utils.jsm
+++ b/browser/base/content/tabview/modules/utils.jsm
@@ -771,10 +771,27 @@ let Utils = {
           if (copy !== undefined)
             target[name] = copy;
         }
       }
     }
 
     // Return the modified object
     return target;
+  },
+
+  // ----------
+  // Function: attempt
+  // Tries to execute a number of functions. Returns immediately the return
+  // value of the first non-failed function without executing successive
+  // functions, or null.
+  attempt: function () {
+    let args = arguments;
+
+    for (let i = 0; i < args.length; i++) {
+      try {
+        return args[i]();
+      } catch (e) {}
+    }
+
+    return null;
   }
 };
--- a/browser/base/content/tabview/storage.js
+++ b/browser/base/content/tabview/storage.js
@@ -94,57 +94,37 @@ let Storage = {
   },
 
   // ----------
   // Function: saveTab
   // Saves the data for a single tab.
   saveTab: function Storage_saveTab(tab, data) {
     Utils.assert(tab, "tab");
 
-    if (data != null) {
-      let imageData = data.imageData;
-      // Remove imageData from payload
-      delete data.imageData;
-
-      if (imageData != null)
-        ThumbnailStorage.saveThumbnail(tab, imageData);
-    }
-
     this._sessionStore.setTabValue(tab, this.TAB_DATA_IDENTIFIER,
       JSON.stringify(data));
   },
 
   // ----------
   // Function: getTabData
-  // Load tab data from session store and return it. Asynchrously loads the tab's
-  // thumbnail from the cache and calls <callback>(imageData) when done.
-  getTabData: function Storage_getTabData(tab, callback) {
+  // Load tab data from session store and return it.
+  getTabData: function Storage_getTabData(tab) {
     Utils.assert(tab, "tab");
-    Utils.assert(typeof callback == "function", "callback arg must be a function");
 
     let existingData = null;
 
     try {
       let tabData = this._sessionStore.getTabValue(tab, this.TAB_DATA_IDENTIFIER);
-      if (tabData != "") {
+      if (tabData != "")
         existingData = JSON.parse(tabData);
-      }
     } catch (e) {
       // getTabValue will fail if the property doesn't exist.
       Utils.log(e);
     }
 
-    if (existingData) {
-      ThumbnailStorage.loadThumbnail(
-        tab, existingData.url,
-        function(status, imageData) { 
-          callback(imageData);
-        }
-      );
-    }
     return existingData;
   },
 
   // ----------
   // Function: saveGroupItem
   // Saves the data for a single groupItem, associated with a specific window.
   saveGroupItem: function Storage_saveGroupItem(win, data) {
     var id = data.id;
new file mode 100644
--- /dev/null
+++ b/browser/base/content/tabview/storagePolicy.js
@@ -0,0 +1,208 @@
+/* ***** 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 storagePolicy.js.
+ *
+ * The Initial Developer of the Original Code is
+ * the Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ * Tim Taubert <ttaubert@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
+ * 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 ***** */
+
+// **********
+// Title: storagePolicy.js
+
+// ##########
+// Class: StoragePolicy
+// Singleton for implementing a storage policy for sensitive data.
+let StoragePolicy = {
+  // Pref that controls whether we can store SSL content on disk
+  PREF_DISK_CACHE_SSL: "browser.cache.disk_cache_ssl",
+
+  // Used to keep track of disk_cache_ssl preference
+  _enablePersistentHttpsCaching: null,
+
+  // Used to keep track of browsers whose data we shouldn't store permanently
+  _deniedBrowsers: [],
+
+  // ----------
+  // Function: toString
+  // Prints [StoragePolicy] for debug use.
+  toString: function StoragePolicy_toString() {
+    return "[StoragePolicy]";
+  },
+
+  // ----------
+  // Function: init
+  // Initializes the StoragePolicy object.
+  init: function StoragePolicy_init() {
+    // store the preference value
+    this._enablePersistentHttpsCaching =
+      Services.prefs.getBoolPref(this.PREF_DISK_CACHE_SSL);
+
+    Services.prefs.addObserver(this.PREF_DISK_CACHE_SSL, this, false);
+
+    // tabs are already loaded before UI is initialized so cache-control
+    // values are unknown. We add browsers with https to the list for now.
+    if (!this._enablePersistentHttpsCaching)
+      Array.forEach(gBrowser.browsers, this._initializeBrowser.bind(this));
+
+    // make sure to remove tab browsers when tabs get closed
+    this._onTabClose = this._onTabClose.bind(this);
+    gBrowser.tabContainer.addEventListener("TabClose", this._onTabClose, false);
+
+    let mm = gWindow.messageManager;
+
+    // add message listeners for storage granted
+    this._onGranted = this._onGranted.bind(this);
+    mm.addMessageListener("Panorama:StoragePolicy:granted", this._onGranted);
+
+    // add message listeners for storage denied
+    this._onDenied = this._onDenied.bind(this);
+    mm.addMessageListener("Panorama:StoragePolicy:denied", this._onDenied);
+  },
+
+  // ----------
+  // Function: _initializeBrowser
+  // Initializes the given browser and checks if we need to add it to our
+  // internal exclusion list.
+  _initializeBrowser: function StoragePolicy__initializeBrowser(browser) {
+    let self = this;
+
+    function checkExclusion() {
+      if (browser.currentURI.schemeIs("https"))
+        self._deniedBrowsers.push(browser);
+    }
+
+    function waitForDocumentLoad() {
+      let mm = browser.messageManager;
+
+      mm.addMessageListener("Panorama:DOMContentLoaded", function onLoad(cx) {
+        mm.removeMessageListener(cx.name, onLoad);
+        checkExclusion(browser);
+      });
+    }
+
+    this._isDocumentLoaded(browser, function (isLoaded) {
+      if (isLoaded)
+        checkExclusion();
+      else
+        waitForDocumentLoad();
+    });
+  },
+
+  // ----------
+  // Function: _isDocumentLoaded
+  // Check if the given browser's document is loaded.
+  _isDocumentLoaded: function StoragePolicy__isDocumentLoaded(browser, callback) {
+    let mm = browser.messageManager;
+    let message = "Panorama:isDocumentLoaded";
+
+    mm.addMessageListener(message, function onMessage(cx) {
+      mm.removeMessageListener(cx.name, onMessage);
+      callback(cx.json.isLoaded);
+    });
+
+    mm.sendAsyncMessage(message);
+  },
+
+  // ----------
+  // Function: uninit
+  // Is called by UI.init() when the browser windows is closed.
+  uninit: function StoragePolicy_uninit() {
+    Services.prefs.removeObserver(this.PREF_DISK_CACHE_SSL, this);
+    gBrowser.removeTabsProgressListener(this);
+    gBrowser.tabContainer.removeEventListener("TabClose", this._onTabClose, false);
+
+    let mm = gWindow.messageManager;
+
+    // remove message listeners
+    mm.removeMessageListener("Panorama:StoragePolicy:granted", this._onGranted);
+    mm.removeMessageListener("Panorama:StoragePolicy:denied", this._onDenied);
+  },
+
+  // ----------
+  // Function: _onGranted
+  // Handle the 'granted' message and remove the given browser from the list
+  // of denied browsers.
+  _onGranted: function StoragePolicy__onGranted(cx) {
+    let index = this._deniedBrowsers.indexOf(cx.target);
+
+    if (index > -1)
+      this._deniedBrowsers.splice(index, 1);
+  },
+
+  // ----------
+  // Function: _onDenied
+  // Handle the 'denied' message and add the given browser to the list of denied
+  // browsers.
+  _onDenied: function StoragePolicy__onDenied(cx) {
+    // exclusion is optional because cache-control is not no-store or public and
+    // the protocol is https. don't exclude when persistent https caching is
+    // enabled.
+    if ("https" == cx.json.reason && this._enablePersistentHttpsCaching)
+      return;
+
+    let browser = cx.target;
+
+    if (this._deniedBrowsers.indexOf(browser) == -1)
+      this._deniedBrowsers.push(browser);
+  },
+
+  // ----------
+  // Function: _onTabClose
+  // Remove the browser from our internal exclusion list when a tab gets closed.
+  _onTabClose: function StoragePolicy__onTabClose(event) {
+    let browser = event.target.linkedBrowser;
+    let index = this._deniedBrowsers.indexOf(browser);
+
+    if (index > -1)
+      this._deniedBrowsers.splice(index, 1);
+  },
+
+  // ----------
+  // Function: canStoreThumbnailForTab
+  // Returns whether we're allowed to store the thumbnail of the given tab.
+  canStoreThumbnailForTab: function StoragePolicy_canStoreThumbnailForTab(tab) {
+    // deny saving thumbnails in private browsing mode
+    if (gPrivateBrowsing.privateBrowsingEnabled &&
+        UI._privateBrowsing.transitionMode != "enter")
+      return false;
+
+    return (this._deniedBrowsers.indexOf(tab.linkedBrowser) == -1);
+  },
+
+  // ----------
+  // Function: observe
+  // Observe pref changes.
+  observe: function StoragePolicy_observe(subject, topic, data) {
+    this._enablePersistentHttpsCaching =
+      Services.prefs.getBoolPref(this.PREF_DISK_CACHE_SSL);
+  }
+};
--- a/browser/base/content/tabview/tabitems.js
+++ b/browser/base/content/tabview/tabitems.js
@@ -64,40 +64,45 @@ function TabItem(tab, options) {
   document.body.appendChild(TabItems.fragment().cloneNode(true));
   
   // The document fragment contains just one Node
   // As per DOM3 appendChild: it will then be the last child
   let div = document.body.lastChild;
   let $div = iQ(div);
 
   this._cachedImageData = null;
+  this._thumbnailNeedsSaving = false;
   this.canvasSizeForced = false;
   this.$thumb = iQ('.thumb', $div);
   this.$fav   = iQ('.favicon', $div);
   this.$tabTitle = iQ('.tab-title', $div);
   this.$canvas = iQ('.thumb canvas', $div);
   this.$cachedThumb = iQ('img.cached-thumb', $div);
   this.$favImage = iQ('.favicon>img', $div);
   this.$close = iQ('.close', $div);
 
   this.tabCanvas = new TabCanvas(this.tab, this.$canvas[0]);
 
+  let self = this;
+
+  // when we paint onto the canvas make sure our thumbnail gets saved
+  this.tabCanvas.addSubscriber("painted", function () {
+    self._thumbnailNeedsSaving = true;
+  });
+
   this.defaultSize = new Point(TabItems.tabWidth, TabItems.tabHeight);
   this._hidden = false;
   this.isATabItem = true;
   this.keepProportional = true;
   this._hasBeenDrawn = false;
   this._reconnected = false;
+  this.isDragging = false;
   this.isStacked = false;
   this.url = "";
 
-  var self = this;
-
-  this.isDragging = false;
-
   // Read off the total vertical and horizontal padding on the tab container
   // and cache this value, as it must be the same for every TabItem.
   if (Utils.isEmptyObject(TabItems.tabItemPadding)) {
     TabItems.tabItemPadding.x = parseInt($div.css('padding-left'))
         + parseInt($div.css('padding-right'));
   
     TabItems.tabItemPadding.y = parseInt($div.css('padding-top'))
         + parseInt($div.css('padding-bottom'));
@@ -189,107 +194,162 @@ TabItem.prototype = Utils.extend(new Ite
 
   // ----------
   // Function: showCachedData
   // Shows the cached data i.e. image and title.  Note: this method should only
   // be called at browser startup with the cached data avaliable.
   //
   // Parameters:
   //   tabData - the tab data
-  showCachedData: function TabItem_showCachedData(tabData) {
-    this._cachedImageData = tabData.imageData;
+  //   imageData - the image data
+  showCachedData: function TabItem_showCachedData(tabData, imageData) {
+    this._cachedImageData = imageData;
     this.$cachedThumb.attr("src", this._cachedImageData).show();
-    this.$canvas.css({opacity: 0.0});
+    this.$canvas.css({opacity: 0});
     this.$tabTitle.text(tabData.title ? tabData.title : "");
+
+    this._sendToSubscribers("showingCachedData");
   },
 
   // ----------
   // Function: hideCachedData
   // Hides the cached data i.e. image and title and show the canvas.
   hideCachedData: function TabItem_hideCachedData() {
     this.$cachedThumb.hide();
     this.$canvas.css({opacity: 1.0});
     if (this._cachedImageData)
       this._cachedImageData = null;
   },
 
   // ----------
   // Function: getStorageData
   // Get data to be used for persistent storage of this object.
-  //
-  // Parameters:
-  //   getImageData - true to include thumbnail pixels (and page title as well); default false
-  getStorageData: function TabItem_getStorageData(getImageData) {
-    let imageData = null;
-
-    if (getImageData) { 
-      if (this._cachedImageData)
-        imageData = this._cachedImageData;
-      else if (this.tabCanvas)
-        imageData = this.tabCanvas.toImageData();
-    }
-
+  getStorageData: function TabItem_getStorageData() {
     return {
       url: this.tab.linkedBrowser.currentURI.spec,
       groupID: (this.parent ? this.parent.id : 0),
-      imageData: imageData,
-      title: getImageData && this.tab.label || null
+      title: this.tab.label
     };
   },
 
   // ----------
   // Function: save
   // Store persistent for this object.
-  //
-  // Parameters:
-  //   saveImageData - true to include thumbnail pixels (and page title as well); default false
-  save: function TabItem_save(saveImageData) {
-    try{
+  save: function TabItem_save() {
+    try {
       if (!this.tab || this.tab.parentNode == null || !this._reconnected) // too soon/late to save
         return;
 
-      var data = this.getStorageData(saveImageData);
+      let data = this.getStorageData();
       if (TabItems.storageSanity(data))
         Storage.saveTab(this.tab, data);
     } catch(e) {
       Utils.log("Error in saving tab value: "+e);
     }
   },
 
   // ----------
+  // Function: loadThumbnail
+  // Loads the tabItems thumbnail.
+  loadThumbnail: function TabItem_loadThumbnail(tabData) {
+    Utils.assert(tabData, "invalid or missing argument <tabData>");
+
+    let self = this;
+
+    function TabItem_loadThumbnail_callback(error, imageData) {
+      // we could have been unlinked while waiting for the thumbnail to load
+      if (error || !imageData || !self.tab)
+        return;
+
+      self._sendToSubscribers("loadedCachedImageData");
+
+      // If we have a cached image, then show it if the loaded URL matches
+      // what the cache is from, OR the loaded URL is blank, which means
+      // that the page hasn't loaded yet.
+      let currentUrl = self.tab.linkedBrowser.currentURI.spec;
+      if (tabData.url == currentUrl || currentUrl == "about:blank")
+        self.showCachedData(tabData, imageData);
+    }
+
+    ThumbnailStorage.loadThumbnail(tabData.url, TabItem_loadThumbnail_callback);
+  },
+
+  // ----------
+  // Function: saveThumbnail
+  // Saves the tabItems thumbnail.
+  saveThumbnail: function TabItem_saveThumbnail(options) {
+    if (!this.tabCanvas)
+      return;
+
+    // nothing to do if the thumbnail hasn't changed
+    if (!this._thumbnailNeedsSaving)
+      return;
+
+    // check the storage policy to see if we're allowed to store the thumbnail
+    if (!StoragePolicy.canStoreThumbnailForTab(this.tab)) {
+      this._sendToSubscribers("deniedToSaveImageData");
+      return;
+    }
+
+    let url = this.tab.linkedBrowser.currentURI.spec;
+    let delayed = this._saveThumbnailDelayed;
+    let synchronously = (options && options.synchronously);
+
+    // is there a delayed save waiting?
+    if (delayed) {
+      // check if url has changed since last call to saveThumbnail
+      if (!synchronously && url == delayed.url)
+        return;
+
+      // url has changed in the meantime, clear the timeout
+      clearTimeout(delayed.timeout);
+    }
+
+    let self = this;
+
+    function callback(error) {
+      if (!error) {
+        self._thumbnailNeedsSaving = false;
+        self._sendToSubscribers("savedCachedImageData");
+      }
+    }
+
+    function doSaveThumbnail() {
+      self._saveThumbnailDelayed = null;
+
+      // we could have been unlinked in the meantime
+      if (!self.tabCanvas)
+        return;
+
+      let imageData = self.tabCanvas.toImageData();
+      ThumbnailStorage.saveThumbnail(url, imageData, callback, options);
+    }
+
+    if (synchronously) {
+      doSaveThumbnail();
+    } else {
+      let timeout = setTimeout(doSaveThumbnail, 2000);
+      this._saveThumbnailDelayed = {url: url, timeout: timeout};
+    }
+  },
+
+  // ----------
   // Function: _reconnect
   // Load the reciever's persistent data from storage. If there is none, 
   // treats it as a new tab. 
   _reconnect: function TabItem__reconnect() {
     Utils.assertThrow(!this._reconnected, "shouldn't already be reconnected");
     Utils.assertThrow(this.tab, "should have a xul:tab");
 
-    let tabData = null;
     let self = this;
-    let imageDataCb = function(imageData) {
-      // we could have been unlinked while waiting for the thumbnail to load
-      if (!self.tab)
-        return;
-
-      Utils.assertThrow(tabData, "tabData");
-      tabData.imageData = imageData;
+    let tabData = Storage.getTabData(this.tab);
 
-      let currentUrl = self.tab.linkedBrowser.currentURI.spec;
-      // If we have a cached image, then show it if the loaded URL matches
-      // what the cache is from, OR the loaded URL is blank, which means
-      // that the page hasn't loaded yet.
-      if (tabData.imageData &&
-          (tabData.url == currentUrl || currentUrl == 'about:blank')) {
-        self.showCachedData(tabData);
-      }
-    };
-    // getTabData returns the sessionstore contents, but passes
-    // a callback to run when the thumbnail is finally loaded.
-    tabData = Storage.getTabData(this.tab, imageDataCb);
     if (tabData && TabItems.storageSanity(tabData)) {
+      this.loadThumbnail(tabData);
+
       if (self.parent)
         self.parent.remove(self, {immediately: true});
 
       let groupItem;
 
       if (tabData.groupID) {
         groupItem = GroupItems.groupItem(tabData.groupID);
       } else {
@@ -931,16 +991,17 @@ let TabItems = {
           tabItem.$canvas[0].height = h;
         }
       }
 
       this._lastUpdateTime = Date.now();
       tabItem._lastTabUpdateTime = this._lastUpdateTime;
 
       tabItem.tabCanvas.paint();
+      tabItem.saveThumbnail();
 
       // ___ cache
       if (tabItem.isShowingCachedData())
         tabItem.hideCachedData();
 
       // ___ notify subscribers that a full update has completed.
       tabItem._sendToSubscribers("updated");
     } catch(e) {
@@ -1141,23 +1202,32 @@ let TabItems = {
   // Returns a copy of the master array of <TabItem>s.
   getItems: function TabItems_getItems() {
     return Utils.copy(this.items);
   },
 
   // ----------
   // Function: saveAll
   // Saves all open <TabItem>s.
-  //
-  // Parameters:
-  //   saveImageData - true to include thumbnail pixels (and page title as well); default false
-  saveAll: function TabItems_saveAll(saveImageData) {
-    var items = this.getItems();
-    items.forEach(function(item) {
-      item.save(saveImageData);
+  saveAll: function TabItems_saveAll() {
+    let tabItems = this.getItems();
+
+    tabItems.forEach(function TabItems_saveAll_forEach(tabItem) {
+      tabItem.save();
+    });
+  },
+
+  // ----------
+  // Function: saveAllThumbnails
+  // Saves thumbnails of all open <TabItem>s.
+  saveAllThumbnails: function TabItems_saveAllThumbnails(options) {
+    let tabItems = this.getItems();
+
+    tabItems.forEach(function TabItems_saveAllThumbnails_forEach(tabItem) {
+      tabItem.saveThumbnail(options);
     });
   },
 
   // ----------
   // Function: storageSanity
   // Checks the specified data (as returned by TabItem.getStorageData or loaded from storage)
   // and returns true if it looks valid.
   // TODO: this is a stub, please implement
@@ -1337,17 +1407,17 @@ TabPriorityQueue.prototype = {
 // Class: TabCanvas
 // Takes care of the actual canvas for the tab thumbnail
 // Does not need to be accessed from outside of tabitems.js
 function TabCanvas(tab, canvas) {
   this.tab = tab;
   this.canvas = canvas;
 };
 
-TabCanvas.prototype = {
+TabCanvas.prototype = Utils.extend(new Subscribable(), {
   // ----------
   // Function: toString
   // Prints [TabCanvas (tab)] for debug use
   toString: function TabCanvas_toString() {
     return "[TabCanvas (" + this.tab + ")]";
   },
 
   // ----------
@@ -1381,16 +1451,18 @@ TabCanvas.prototype = {
       } catch (e) {
         Utils.error('paint', e);
       }
     } else {
       // General case where nearest neighbor algorithm looks good
       // Draw directly to the destination canvas
       this._drawWindow(ctx, w, h, bgColor);
     }
+
+    this._sendToSubscribers("painted");
   },
 
   // ----------
   // Function: _fillCanvasBackground
   // Draws a rectangle of <width>x<height> with color <bgColor> to the given
   // canvas context.
   _fillCanvasBackground: function TabCanvas__fillCanvasBackground(ctx, width, height, bgColor) {
     ctx.fillStyle = bgColor;
@@ -1449,9 +1521,9 @@ TabCanvas.prototype = {
     return new Rect(left, top, width, height);
   },
 
   // ----------
   // Function: toImageData
   toImageData: function TabCanvas_toImageData() {
     return this.canvas.toDataURL("image/png");
   }
-};
+});
--- a/browser/base/content/tabview/tabview.js
+++ b/browser/base/content/tabview/tabview.js
@@ -66,16 +66,17 @@ let AllTabs = {
     gBrowser.tabContainer.removeEventListener(this._events[eventName], callback, false);
   }
 };
 
 # NB: Certain files need to evaluate before others
 
 #include iq.js
 #include storage.js
+#include storagePolicy.js
 #include items.js
 #include groupitems.js
 #include tabitems.js
 #include drag.js
 #include trench.js
 #include thumbnailStorage.js
 #include ui.js
 #include search.js
--- a/browser/base/content/tabview/thumbnailStorage.js
+++ b/browser/base/content/tabview/thumbnailStorage.js
@@ -39,36 +39,26 @@
 // Title: thumbnailStorage.js
 
 // ##########
 // Class: ThumbnailStorage
 // Singleton for persistent storage of thumbnail data.
 let ThumbnailStorage = {
   CACHE_CLIENT_IDENTIFIER: "tabview-cache",
   CACHE_PREFIX: "moz-panorama:",
-  PREF_DISK_CACHE_SSL: "browser.cache.disk_cache_ssl",
 
   // Holds the cache session reference
   _cacheSession: null,
 
   // Holds the string input stream reference
   _stringInputStream: null,
 
   // Holds the storage stream reference
   _storageStream: null,
 
-  // Holds the progress listener reference
-  _progressListener: null,
-
-  // Used to keep track of disk_cache_ssl preference
-  enablePersistentHttpsCaching: null,
-
-  // Used to keep track of browsers whose thumbs we shouldn't save
-  excludedBrowsers: [],
-
   // ----------
   // Function: toString
   // Prints [ThumbnailStorage] for debug use.
   toString: function ThumbnailStorage_toString() {
     return "[ThumbnailStorage]";
   },
 
   // ----------
@@ -82,174 +72,132 @@ let ThumbnailStorage = {
     this._cacheSession = cacheService.createSession(
       this.CACHE_CLIENT_IDENTIFIER, Ci.nsICache.STORE_ON_DISK, true);
     this._stringInputStream = Components.Constructor(
       "@mozilla.org/io/string-input-stream;1", "nsIStringInputStream",
       "setData");
     this._storageStream = Components.Constructor(
       "@mozilla.org/storagestream;1", "nsIStorageStream", 
       "init");
-
-    // store the preference value
-    this.enablePersistentHttpsCaching =
-      Services.prefs.getBoolPref(this.PREF_DISK_CACHE_SSL);
-
-    Services.prefs.addObserver(this.PREF_DISK_CACHE_SSL, this, false);
-
-    let self = this;
-    // tabs are already loaded before UI is initialized so cache-control
-    // values are unknown.  We add browsers with https to the list for now.
-    gBrowser.browsers.forEach(function(browser) {
-      let checkAndAddToList = function(browserObj) {
-        if (!self.enablePersistentHttpsCaching &&
-            browserObj.currentURI.schemeIs("https"))
-          self.excludedBrowsers.push(browserObj);
-      };
-      if (browser.contentDocument.readyState != "complete" ||
-          browser.webProgress.isLoadingDocument) {
-        browser.addEventListener("load", function onLoad() {
-          browser.removeEventListener("load", onLoad, true);
-          checkAndAddToList(browser);
-        }, true);
-      } else {
-        checkAndAddToList(browser);
-      }
-    });
-    gBrowser.addTabsProgressListener(this);
-  },
-
-  // Function: uninit
-  // Should be called when window is unloaded.
-  uninit: function ThumbnailStorage_uninit() {
-    gBrowser.removeTabsProgressListener(this);
-    Services.prefs.removeObserver(this.PREF_DISK_CACHE_SSL, this);
   },
 
   // ----------
   // Function: _openCacheEntry
   // Opens a cache entry for the given <url> and requests access <access>.
   // Calls <successCallback>(entry) when the entry was successfully opened with
   // requested access rights. Otherwise calls <errorCallback>().
-  _openCacheEntry: function ThumbnailStorage__openCacheEntry(url, access, successCallback, errorCallback) {
-    let onCacheEntryAvailable = function(entry, accessGranted, status) {
+  //
+  // Parameters:
+  //   url - the url to use as the storage key
+  //   access - access flags, see Ci.nsICache.ACCESS_*
+  //   successCallback - the callback to be called on success
+  //   errorCallback - the callback to be called when an error occured
+  //   options - an object with additional parameters, see below
+  //
+  // Possible options:
+  //   synchronously - set to true to force sync mode
+  _openCacheEntry:
+    function ThumbnailStorage__openCacheEntry(url, access, successCallback,
+                                              errorCallback, options) {
+    Utils.assert(url, "invalid or missing argument <url>");
+    Utils.assert(access, "invalid or missing argument <access>");
+    Utils.assert(successCallback, "invalid or missing argument <successCallback>");
+    Utils.assert(errorCallback, "invalid or missing argument <errorCallback>");
+
+    function onCacheEntryAvailable(entry, accessGranted, status) {
       if (entry && access == accessGranted && Components.isSuccessCode(status)) {
         successCallback(entry);
       } else {
-        entry && entry.close();
+        if (entry)
+          entry.close();
+
         errorCallback();
       }
     }
 
     let key = this.CACHE_PREFIX + url;
 
-    // switch to synchronous mode if parent window is about to close
-    if (UI.isDOMWindowClosing) {
+    if (options && options.synchronously) {
       let entry = this._cacheSession.openCacheEntry(key, access, true);
       let status = Cr.NS_OK;
       onCacheEntryAvailable(entry, entry.accessGranted, status);
     } else {
       let listener = new CacheListener(onCacheEntryAvailable);
       this._cacheSession.asyncOpenCacheEntry(key, access, listener);
     }
   },
 
-  // Function: _shouldSaveThumbnail
-  // Checks whether to save tab's thumbnail or not.
-  _shouldSaveThumbnail : function ThumbnailStorage__shouldSaveThumbnail(tab) {
-    return (this.excludedBrowsers.indexOf(tab.linkedBrowser) == -1);
-  },
-
   // ----------
   // Function: saveThumbnail
-  // Saves the <imageData> to the cache using the given <url> as key.
-  // Calls <callback>(status, data) when finished, passing true or false
-  // (indicating whether the operation succeeded).
-  saveThumbnail: function ThumbnailStorage_saveThumbnail(tab, imageData, callback) {
-    Utils.assert(tab, "tab");
-    Utils.assert(imageData, "imageData");
-    
-    if (!this._shouldSaveThumbnail(tab)) {
-      tab._tabViewTabItem._sendToSubscribers("deniedToCacheImageData");
-      if (callback)
-        callback(false);
-      return;
-    }
+  // Saves the given thumbnail in the cache.
+  //
+  // Parameters:
+  //   url - the url to use as the storage key
+  //   imageData - the image data to save for the given key
+  //   callback - the callback that is called when the operation is finished
+  //   options - an object with additional parameters, see below
+  //
+  // Possible options:
+  //   synchronously - set to true to force sync mode
+  saveThumbnail:
+    function ThumbnailStorage_saveThumbnail(url, imageData, callback, options) {
+    Utils.assert(url, "invalid or missing argument <url>");
+    Utils.assert(imageData, "invalid or missing argument <imageData>");
+    Utils.assert(callback, "invalid or missing argument <callback>");
 
+    let synchronously = (options && options.synchronously);
     let self = this;
 
-    let completed = function(status) {
-      if (callback)
-        callback(status);
-
-      if (status) {
-        // Notify subscribers
-        tab._tabViewTabItem._sendToSubscribers("savedCachedImageData");
-      } else {
-        Utils.log("Error while saving thumbnail: " + e);
-      }
-    };
-
-    let onCacheEntryAvailable = function(entry) {
+    function onCacheEntryAvailable(entry) {
       let outputStream = entry.openOutputStream(0);
 
-      let cleanup = function() {
+      function cleanup() {
         outputStream.close();
         entry.close();
       }
 
-      // switch to synchronous mode if parent window is about to close
-      if (UI.isDOMWindowClosing) {
+      // synchronous mode
+      if (synchronously) {
         outputStream.write(imageData, imageData.length);
         cleanup();
-        completed(true);
+        callback();
         return;
       }
 
       // asynchronous mode
       let inputStream = new self._stringInputStream(imageData, imageData.length);
       gNetUtil.asyncCopy(inputStream, outputStream, function (result) {
         cleanup();
         inputStream.close();
-        completed(Components.isSuccessCode(result));
+        callback(Components.isSuccessCode(result) ? "" : "failure");
       });
     }
 
-    let onCacheEntryUnavailable = function() {
-      completed(false);
+    function onCacheEntryUnavailable() {
+      callback("unavailable");
     }
 
-    this._openCacheEntry(tab.linkedBrowser.currentURI.spec, 
-        Ci.nsICache.ACCESS_WRITE, onCacheEntryAvailable, 
-        onCacheEntryUnavailable);
+    this._openCacheEntry(url, Ci.nsICache.ACCESS_WRITE, onCacheEntryAvailable,
+                         onCacheEntryUnavailable, options);
   },
 
   // ----------
   // Function: loadThumbnail
-  // Asynchrously loads image data from the cache using the given <url> as key.
-  // Calls <callback>(status, data) when finished, passing true or false
-  // (indicating whether the operation succeeded) and the retrieved image data.
-  loadThumbnail: function ThumbnailStorage_loadThumbnail(tab, url, callback) {
-    Utils.assert(tab, "tab");
-    Utils.assert(url, "url");
-    Utils.assert(typeof callback == "function", "callback arg must be a function");
+  // Loads a thumbnail from the cache.
+  //
+  // Parameters:
+  //   url - the url to use as the storage key
+  //   callback - the callback that is called when the operation is finished
+  loadThumbnail: function ThumbnailStorage_loadThumbnail(url, callback) {
+    Utils.assert(url, "invalid or missing argument <url>");
+    Utils.assert(callback, "invalid or missing argument <callback>");
 
     let self = this;
 
-    let completed = function(status, imageData) {
-      callback(status, imageData);
-
-      if (status) {
-        // Notify subscribers
-        tab._tabViewTabItem._sendToSubscribers("loadedCachedImageData");
-      } else {
-        Utils.log("Error while loading thumbnail");
-      }
-    }
-
-    let onCacheEntryAvailable = function(entry) {
+    function onCacheEntryAvailable(entry) {
       let imageChunks = [];
       let nativeInputStream = entry.openInputStream(0);
 
       const CHUNK_SIZE = 0x10000; // 65k
       const PR_UINT32_MAX = 0xFFFFFFFF;
       let storageStream = new self._storageStream(CHUNK_SIZE, PR_UINT32_MAX, null);
       let storageOutStream = storageStream.getOutputStream(0);
 
@@ -273,81 +221,26 @@ let ThumbnailStorage = {
         if (isSuccess) {
           let storageInStream = storageStream.newInputStream(0);
           imageData = gNetUtil.readInputStreamToString(storageInStream,
             storageInStream.available());
           storageInStream.close();
         }
 
         cleanup();
-        completed(isSuccess, imageData);
+        callback(isSuccess ? "" : "failure", imageData);
       });
     }
 
-    let onCacheEntryUnavailable = function() {
-      completed(false);
+    function onCacheEntryUnavailable() {
+      callback("unavailable");
     }
 
-    this._openCacheEntry(url, Ci.nsICache.ACCESS_READ,
-        onCacheEntryAvailable, onCacheEntryUnavailable);
-  },
-
-  // ----------
-  // Function: observe
-  // Implements the observer interface.
-  observe: function ThumbnailStorage_observe(subject, topic, data) {
-    this.enablePersistentHttpsCaching =
-      Services.prefs.getBoolPref(this.PREF_DISK_CACHE_SSL);
-  },
-
-  // ----------
-  // Implements progress listener interface.
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
-                                         Ci.nsISupportsWeakReference,
-                                         Ci.nsISupports]),
-
-  onStateChange: function ThumbnailStorage_onStateChange(
-    browser, webProgress, request, flag, status) {
-    if (flag & Ci.nsIWebProgressListener.STATE_START &&
-        flag & Ci.nsIWebProgressListener.STATE_IS_WINDOW) {
-      // ensure the dom window is the top one
-      if (webProgress.DOMWindow.parent == webProgress.DOMWindow) {
-        let index = this.excludedBrowsers.indexOf(browser);
-        if (index != -1)
-          this.excludedBrowsers.splice(index, 1);
-      }
-    }
-    if (flag & Ci.nsIWebProgressListener.STATE_STOP &&
-        flag & Ci.nsIWebProgressListener.STATE_IS_WINDOW) {
-      // ensure the dom window is the top one
-      if (webProgress.DOMWindow.parent == webProgress.DOMWindow &&
-          request && request instanceof Ci.nsIHttpChannel) {
-        request.QueryInterface(Ci.nsIHttpChannel);
-
-        let inhibitPersistentThumb = false;
-        if (request.isNoStoreResponse()) {
-           inhibitPersistentThumb = true;
-        } else if (!this.enablePersistentHttpsCaching &&
-                   request.URI.schemeIs("https")) {
-          let cacheControlHeader;
-          try {
-            cacheControlHeader = request.getResponseHeader("Cache-Control");
-          } catch(e) {
-            // this error would occur when "Cache-Control" doesn't exist in
-            // the eaders
-          }
-          if (cacheControlHeader && !(/public/i).test(cacheControlHeader))
-            inhibitPersistentThumb = true;
-        }
-
-        if (inhibitPersistentThumb &&
-            this.excludedBrowsers.indexOf(browser) == -1)
-          this.excludedBrowsers.push(browser);
-      }
-    }
+    this._openCacheEntry(url, Ci.nsICache.ACCESS_READ, onCacheEntryAvailable,
+                         onCacheEntryUnavailable);
   }
 }
 
 // ##########
 // Class: CacheListener
 // Generic CacheListener for feeding to asynchronous cache calls.
 // Calls <callback>(entry, access, status) when the requested cache entry
 // is available.
--- a/browser/base/content/tabview/ui.js
+++ b/browser/base/content/tabview/ui.js
@@ -170,16 +170,19 @@ let UI = {
       this._initPageDirection();
 
       // ___ thumbnail storage
       ThumbnailStorage.init();
 
       // ___ storage
       Storage.init();
 
+      // ___ storage policy
+      StoragePolicy.init();
+
       if (Storage.readWindowBusyState(gWindow))
         this.storageBusy();
 
       let data = Storage.readUIData(gWindow);
       this._storageSanity(data);
       this._pageBounds = data.pageBounds;
 
       // ___ currentTab
@@ -275,23 +278,26 @@ let UI = {
       iQ(window).resize(function() {
         self._resize();
       });
 
       // ___ setup event listener to save canvas images
       gWindow.addEventListener("SSWindowClosing", function onWindowClosing() {
         gWindow.removeEventListener("SSWindowClosing", onWindowClosing, false);
 
+        // XXX bug #635975 - don't unlink the tab if the dom window is closing.
         self.isDOMWindowClosing = true;
 
         if (self.isTabViewVisible())
           GroupItems.removeHiddenGroups();
 
+        TabItems.saveAll();
+        TabItems.saveAllThumbnails({synchronously: true});
+
         Storage.saveActiveGroupName(gWindow);
-        TabItems.saveAll(true);
         self._save();
       }, false);
 
       // ___ load frame script
       let frameScript = "chrome://browser/content/tabview-content.js";
       gWindow.messageManager.loadFrameScript(frameScript, true);
 
       // ___ Done
@@ -318,17 +324,17 @@ let UI = {
       func();
     });
     this._cleanupFunctions = [];
 
     // additional clean up
     TabItems.uninit();
     GroupItems.uninit();
     Storage.uninit();
-    ThumbnailStorage.uninit();
+    StoragePolicy.uninit();
 
     this._removeTabActionHandlers();
     this._currentTab = null;
     this._pageBounds = null;
     this._reorderTabItemsOnShow = null;
     this._reorderTabsOnHide = null;
     this._frameInitialized = false;
   },
@@ -708,16 +714,21 @@ let UI = {
           self._privateBrowsing.wasInTabView = self.isTabViewVisible();
           if (self.isTabViewVisible())
             self.goToTab(gBrowser.selectedTab);
         }
       } else if (topic == "private-browsing-change-granted") {
         if (data == "enter" || data == "exit") {
           hideSearch();
           self._privateBrowsing.transitionMode = data;
+
+          // make sure to save all thumbnails that haven't been saved yet
+          // before we enter the private browsing mode
+          if (data == "enter")
+            TabItems.saveAllThumbnails({synchronously: true});
         }
       } else if (topic == "private-browsing-transition-complete") {
         // We use .transitionMode here, as aData is empty.
         if (self._privateBrowsing.transitionMode == "exit" &&
             self._privateBrowsing.wasInTabView)
           self.showTabView(false);
 
         self._privateBrowsing.transitionMode = "";
--- a/browser/base/content/test/tabview/Makefile.in
+++ b/browser/base/content/test/tabview/Makefile.in
@@ -77,17 +77,16 @@ include $(topsrcdir)/config/rules.mk
                  browser_tabview_bug597980.js \
                  browser_tabview_bug598375.js \
                  browser_tabview_bug598600.js \
                  browser_tabview_bug599626.js \
                  browser_tabview_bug600645.js \
                  browser_tabview_bug600812.js \
                  browser_tabview_bug602432.js \
                  browser_tabview_bug604098.js \
-                 browser_tabview_bug604699.js \
                  browser_tabview_bug606657.js \
                  browser_tabview_bug606905.js \
                  browser_tabview_bug607108.js \
                  browser_tabview_bug608037.js \
                  browser_tabview_bug608184.js \
                  browser_tabview_bug608158.js \
                  browser_tabview_bug608405.js \
                  browser_tabview_bug610208.js \
@@ -109,17 +108,16 @@ include $(topsrcdir)/config/rules.mk
                  browser_tabview_bug624953.js \
                  browser_tabview_bug625195.js \
                  browser_tabview_bug625269.js \
                  browser_tabview_bug625424.js \
                  browser_tabview_bug626368.js \
                  browser_tabview_bug626455.js \
                  browser_tabview_bug626525.js \
                  browser_tabview_bug626791.js \
-                 browser_tabview_bug627239.js \
                  browser_tabview_bug627288.js \
                  browser_tabview_bug627736.js \
                  browser_tabview_bug628061.js \
                  browser_tabview_bug628165.js \
                  browser_tabview_bug628270.js \
                  browser_tabview_bug628887.js \
                  browser_tabview_bug629189.js \
                  browser_tabview_bug629195.js \
@@ -150,31 +148,34 @@ include $(topsrcdir)/config/rules.mk
                  browser_tabview_bug656778.js \
                  browser_tabview_bug656913.js \
                  browser_tabview_bug662266.js \
                  browser_tabview_bug663421.js \
                  browser_tabview_bug665502.js \
                  browser_tabview_bug669694.js \
                  browser_tabview_bug673196.js \
                  browser_tabview_bug673729.js \
+                 browser_tabview_bug677310.js \
                  browser_tabview_bug679853.js \
                  browser_tabview_bug681599.js \
                  browser_tabview_click_group.js \
                  browser_tabview_dragdrop.js \
                  browser_tabview_exit_button.js \
                  browser_tabview_expander.js \
                  browser_tabview_firstrun_pref.js \
                  browser_tabview_group.js \
                  browser_tabview_launch.js \
                  browser_tabview_multiwindow_search.js \
                  browser_tabview_privatebrowsing.js \
                  browser_tabview_rtl.js \
                  browser_tabview_search.js \
                  browser_tabview_snapping.js \
                  browser_tabview_startup_transitions.js \
+                 browser_tabview_storage_policy.js \
+                 browser_tabview_thumbnail_storage.js \
                  browser_tabview_undo_group.js \
                  dummy_page.html \
                  head.js \
                  search1.html \
                  search2.html \
                  test_bug600645.html \
                  test_bug644097.html \
                  $(NULL)
--- a/browser/base/content/test/tabview/browser_tabview_bug597248.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug597248.js
@@ -29,17 +29,19 @@ function setupTwo(win) {
 
   let tabItems = contentWindow.TabItems.getItems();
   is(tabItems.length, 3, "There should be 3 tab items before closing");
 
   let numTabsToSave = tabItems.length;
 
   // force all canvases to update, and hook in imageData save detection
   tabItems.forEach(function(tabItem) {
-    contentWindow.TabItems.update(tabItem.tab);
+    // mark thumbnail as dirty
+    tabItem.tabCanvas.paint();
+
     tabItem.addSubscriber("savedCachedImageData", function onSaved(item) {
       item.removeSubscriber("savedCachedImageData", onSaved);
 
       if (!--numTabsToSave)
         restoreWindow();
     });
   });
 
@@ -76,18 +78,18 @@ function setupTwo(win) {
             else
               frameInitialized = true;
           }
 
           let tabItems = restoredContentWindow.TabItems.getItems();
           let count = tabItems.length;
 
           tabItems.forEach(function(tabItem) {
-            tabItem.addSubscriber("loadedCachedImageData", function onLoaded() {
-              tabItem.removeSubscriber("loadedCachedImageData", onLoaded);
+            tabItem.addSubscriber("showingCachedData", function onLoaded() {
+              tabItem.removeSubscriber("showingCachedData", onLoaded);
               ok(tabItem.isShowingCachedData(),
                 "Tab item is showing cached data and is just connected. " +
                 tabItem.tab.linkedBrowser.currentURI.spec);
               if (--count == 0)
                 nextStep();
             });
           });
         }
deleted file mode 100644
--- a/browser/base/content/test/tabview/browser_tabview_bug604699.js
+++ /dev/null
@@ -1,85 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
-  let url = "http://www.example.com/";
-  let cw;
-  let tab = gBrowser.tabs[0];
-
-  let finishTest = function () {
-    is(1, gBrowser.tabs.length, "there is one tab, only");
-    ok(!TabView.isVisible(), "tabview is not visible");
-    finish();
-  }
-
-  waitForExplicitFinish();
-
-  let testErroneousLoading = function () {
-    cw.ThumbnailStorage.loadThumbnail(tab, url, function (status, data) {
-      ok(!status, "thumbnail entry failed to load");
-      is(null, data, "no thumbnail data received");
-      next();
-    });
-  }
-
-  let testAsynchronousSaving = function () {
-    let saved = false;
-    let data = "thumbnail-data-asynchronous";
-
-    cw.ThumbnailStorage.saveThumbnail(tab, data, function (status) {
-      ok(status, "thumbnail entry was saved");
-      ok(saved, "thumbnail was saved asynchronously");
-
-      cw.ThumbnailStorage.loadThumbnail(tab, url, function (status, imageData) {
-        ok(status, "thumbnail entry was loaded");
-        is(imageData, data, "valid thumbnail data received");
-        next();
-      });
-    });
-
-    saved = true;
-  }
-
-  let testSynchronousSaving = function () {
-    let saved = false;
-    let data = "thumbnail-data-synchronous";
-
-    cw.UI.isDOMWindowClosing = true;
-    registerCleanupFunction(function () cw.UI.isDOMWindowClosing = false);
-
-    cw.ThumbnailStorage.saveThumbnail(tab, data, function (status) {
-      ok(status, "thumbnail entry was saved");
-      ok(!saved, "thumbnail was saved synchronously");
-
-      cw.ThumbnailStorage.loadThumbnail(tab, url, function (status, imageData) {
-        ok(status, "thumbnail entry was loaded");
-        is(imageData, data, "valid thumbnail data received");
-
-        cw.UI.isDOMWindowClosing = false;
-        next();
-      });
-    });
-
-    saved = true;
-  }
-
-  let tests = [testErroneousLoading, testAsynchronousSaving, testSynchronousSaving];
-
-  let next = function () {
-    let test = tests.shift();
-    if (test)
-      test();
-    else
-      hideTabView(finishTest);
-  }
-
-  tab.linkedBrowser.loadURI(url);
-  afterAllTabsLoaded(function() {
-    showTabView(function () {
-      registerCleanupFunction(function () TabView.hide());
-      cw = TabView.getContentWindow();
-
-      next();
-    });
-  });
-}
--- a/browser/base/content/test/tabview/browser_tabview_bug627288.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug627288.js
@@ -17,27 +17,28 @@ function test() {
       tab = gBrowser.loadOneTab('http://mochi.test:8888/', {inBackground: true});
 
       afterAllTabsLoaded(function () {
         tabItem = tab._tabViewTabItem;
 
         tabItem.addSubscriber("savedCachedImageData", function onSaved() {
           tabItem.removeSubscriber("savedCachedImageData", onSaved);
 
-          tabItem.addSubscriber("loadedCachedImageData", function onLoaded() {
-            tabItem.removeSubscriber("loadedCachedImageData", onLoaded);
+          tabItem.addSubscriber("showingCachedData", function onLoaded() {
+            tabItem.removeSubscriber("showingCachedData", onLoaded);
 
             ok(tabItem.isShowingCachedData(), 'tabItem shows cached data');
             testChangeUrlAfterReconnect();
           });
 
           cw.TabItems.resumeReconnecting();
         });
 
         cw.Storage.saveTab(tab, data);
+        tabItem.saveThumbnail();
       });
     });
   }
 
   let testChangeUrlAfterReconnect = function () {
     tab.linkedBrowser.loadURI('http://mochi.test:8888/browser/');
 
     whenTabAttrModified(tab, function () {
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/tabview/browser_tabview_bug677310.js
@@ -0,0 +1,48 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+let pb = Cc["@mozilla.org/privatebrowsing;1"].
+         getService(Ci.nsIPrivateBrowsingService);
+
+function test() {
+  let thumbnailsSaved = false;
+
+  waitForExplicitFinish();
+
+  registerCleanupFunction(function () {
+    ok(thumbnailsSaved, "thumbs have been saved before entering pb mode");
+    pb.privateBrowsingEnabled = false;
+  });
+
+  afterAllTabsLoaded(function () {
+    showTabView(function () {
+      hideTabView(function () {
+        let numConditions = 2;
+
+        function check() {
+          if (--numConditions)
+            return;
+
+          togglePrivateBrowsing(finish);
+        }
+
+        let tabItem = gBrowser.tabs[0]._tabViewTabItem;
+
+        // save all thumbnails synchronously to cancel all delayed thumbnail
+        // saves that might be active
+        tabItem.saveThumbnail({synchronously: true});
+
+        // force a tabCanvas paint to flag the thumbnail as dirty
+        tabItem.tabCanvas.paint();
+
+        tabItem.addSubscriber("savedCachedImageData", function onSaved() {
+          tabItem.removeSubscriber("savedCachedImageData", onSaved);
+          thumbnailsSaved = true;
+          check();
+        });
+
+        togglePrivateBrowsing(check);
+      });
+    });
+  });
+}
rename from browser/base/content/test/tabview/browser_tabview_bug627239.js
rename to browser/base/content/test/tabview/browser_tabview_storage_policy.js
--- a/browser/base/content/test/tabview/browser_tabview_bug627239.js
+++ b/browser/base/content/test/tabview/browser_tabview_storage_policy.js
@@ -1,127 +1,145 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const PREF_DISK_CACHE_SSL = "browser.cache.disk_cache_ssl";
+
+let pb = Cc["@mozilla.org/privatebrowsing;1"].
+         getService(Ci.nsIPrivateBrowsingService);
+
 let contentWindow;
-let enablePersistentHttpsCaching;
 let newTab;
 
 function test() {
   waitForExplicitFinish();
 
   newTab = gBrowser.addTab();
 
   HttpRequestObserver.register();
 
   registerCleanupFunction(function () {
     HttpRequestObserver.unregister();
     if (gBrowser.tabs[1])
       gBrowser.removeTab(gBrowser.tabs[1]);
     hideTabView();
 
-    contentWindow.ThumbnailStorage.enablePersistentHttpsCaching =
-        enablePersistentHttpsCaching;
+    Services.prefs.clearUserPref(PREF_DISK_CACHE_SSL);
+    pb.privateBrowsingEnabled = false;
   });
 
   showTabView(function() {
     contentWindow = TabView.getContentWindow();
     test1();
   });
 }
 
 
 function test1() {
   // page with cache-control: no-store, should not save thumbnail
   HttpRequestObserver.cacheControlValue = "no-store";
-  newTab.linkedBrowser.loadURI("http://www.example.com/browser/browser/base/content/test/tabview/dummy_page.html");
 
-  afterAllTabsLoaded(function() {
+  whenStorageDenied(newTab, function () {
     let tabItem = newTab._tabViewTabItem;
 
-    ok(!contentWindow.ThumbnailStorage._shouldSaveThumbnail(newTab), 
+    ok(!contentWindow.StoragePolicy.canStoreThumbnailForTab(newTab), 
        "Should not save the thumbnail for tab");
 
-    whenDeniedToCacheImageData(tabItem, test2);
-    tabItem.save(true);
+    whenDeniedToSaveImageData(tabItem, test2);
+    tabItem.saveThumbnail({synchronously: true});
     HttpRequestObserver.cacheControlValue = null;
   });
+
+  newTab.linkedBrowser.loadURI("http://www.example.com/browser/browser/base/content/test/tabview/dummy_page.html");
 }
 
 function test2() {
   // page with cache-control: private, should save thumbnail
   HttpRequestObserver.cacheControlValue = "private";
 
   newTab.linkedBrowser.loadURI("http://www.example.com/");
   afterAllTabsLoaded(function() {
     let tabItem = newTab._tabViewTabItem;
 
-    ok(contentWindow.ThumbnailStorage._shouldSaveThumbnail(newTab), 
+    ok(contentWindow.StoragePolicy.canStoreThumbnailForTab(newTab), 
        "Should save the thumbnail for tab");
 
     whenSavedCachedImageData(tabItem, test3);
-    tabItem.save(true);
+    tabItem.saveThumbnail({synchronously: true});
   });
 }
 
 function test3() {
   // page with cache-control: private with https caching enabled, should save thumbnail
   HttpRequestObserver.cacheControlValue = "private";
 
-  enablePersistentHttpsCaching =
-    contentWindow.ThumbnailStorage.enablePersistentHttpsCaching;
-  contentWindow.ThumbnailStorage.enablePersistentHttpsCaching = true;
+  Services.prefs.setBoolPref(PREF_DISK_CACHE_SSL, true);
 
   newTab.linkedBrowser.loadURI("https://example.com/browser/browser/base/content/test/tabview/dummy_page.html");
   afterAllTabsLoaded(function() {
     let tabItem = newTab._tabViewTabItem;
 
-    ok(contentWindow.ThumbnailStorage._shouldSaveThumbnail(newTab),
+    ok(contentWindow.StoragePolicy.canStoreThumbnailForTab(newTab),
        "Should save the thumbnail for tab");
 
     whenSavedCachedImageData(tabItem, test4);
-    tabItem.save(true);
+    tabItem.saveThumbnail({synchronously: true});
   });
 }
 
 function test4() {
   // page with cache-control: public with https caching disabled, should save thumbnail
   HttpRequestObserver.cacheControlValue = "public";
 
-  contentWindow.ThumbnailStorage.enablePersistentHttpsCaching = false;
+  Services.prefs.setBoolPref(PREF_DISK_CACHE_SSL, false);
 
   newTab.linkedBrowser.loadURI("https://example.com/browser/browser/base/content/test/tabview/");
   afterAllTabsLoaded(function() {
     let tabItem = newTab._tabViewTabItem;
 
-    ok(contentWindow.ThumbnailStorage._shouldSaveThumbnail(newTab),
+    ok(contentWindow.StoragePolicy.canStoreThumbnailForTab(newTab),
        "Should save the thumbnail for tab");
 
     whenSavedCachedImageData(tabItem, test5);
-    tabItem.save(true);
+    tabItem.saveThumbnail({synchronously: true});
   });
 }
 
 function test5() {
   // page with cache-control: private with https caching disabled, should not save thumbnail
   HttpRequestObserver.cacheControlValue = "private";
- 
-  newTab.linkedBrowser.loadURI("https://example.com/");
-  afterAllTabsLoaded(function() {
+
+  whenStorageDenied(newTab, function () {
     let tabItem = newTab._tabViewTabItem;
 
-    ok(!contentWindow.ThumbnailStorage._shouldSaveThumbnail(newTab),
-       "Should not the thumbnail for tab");
+    ok(!contentWindow.StoragePolicy.canStoreThumbnailForTab(newTab),
+       "Should not save the thumbnail for tab");
+
+    whenDeniedToSaveImageData(tabItem, function () {
+      gBrowser.removeTab(newTab);
+      test6();
+    });
+
+    tabItem.saveThumbnail({synchronously: true});
+  });
 
-    whenDeniedToCacheImageData(tabItem, function () {
-      hideTabView(function () {
-        gBrowser.removeTab(gBrowser.tabs[1]);
-        finish();
-      });
-    });
-    tabItem.save(true);
+  newTab.linkedBrowser.loadURI("https://example.com/");
+}
+
+// ensure that no thumbnails are saved while in private browsing mode
+function test6() {
+  HttpRequestObserver.cacheControlValue = "public";
+
+  togglePrivateBrowsing(function () {
+    let tab = gBrowser.tabs[0];
+
+    ok(!contentWindow.StoragePolicy.canStoreThumbnailForTab(tab),
+       "Should not save the thumbnail for tab");
+
+    togglePrivateBrowsing(finish);
   });
 }
 
 let HttpRequestObserver = {
   cacheControlValue: null,
 
   observe: function(subject, topic, data) {
     if (topic == "http-on-examine-response" && this.cacheControlValue) {
@@ -141,14 +159,23 @@ let HttpRequestObserver = {
 
 function whenSavedCachedImageData(tabItem, callback) {
   tabItem.addSubscriber("savedCachedImageData", function onSaved() {
     tabItem.removeSubscriber("savedCachedImageData", onSaved);
     callback();
   });
 }
 
-function whenDeniedToCacheImageData(tabItem, callback) {
-  tabItem.addSubscriber("deniedToCacheImageData", function onDenied() {
-    tabItem.removeSubscriber("deniedToCacheImageData", onDenied);
+function whenDeniedToSaveImageData(tabItem, callback) {
+  tabItem.addSubscriber("deniedToSaveImageData", function onDenied() {
+    tabItem.removeSubscriber("deniedToSaveImageData", onDenied);
     callback();
   });
 }
+
+function whenStorageDenied(tab, callback) {
+  let mm = tab.linkedBrowser.messageManager;
+
+  mm.addMessageListener("Panorama:StoragePolicy:denied", function onDenied() {
+    mm.removeMessageListener("Panorama:StoragePolicy:denied", onDenied);
+    executeSoon(callback);
+  });
+}
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/tabview/browser_tabview_thumbnail_storage.js
@@ -0,0 +1,161 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+let tests = [testRawSyncSave, testRawAsyncSave, testRawLoadError,
+             testAsyncSave, testSyncSave, testOverrideAsyncSave,
+             testSaveCleanThumbnail];
+
+function test() {
+  waitForExplicitFinish();
+  loadTabView(next);
+}
+
+function testRawSyncSave() {
+  let cw = TabView.getContentWindow();
+  let url = "http://example.com/sync-url";
+  let data = "thumbnail-data-sync";
+  let saved = false;
+
+  cw.ThumbnailStorage.saveThumbnail(url, data, function (error) {
+    ok(!error, "thumbnail entry was saved");
+    ok(!saved, "thumbnail was saved synchronously");
+
+    cw.ThumbnailStorage.loadThumbnail(url, function (error, imageData) {
+      ok(!error, "thumbnail entry was loaded");
+      is(imageData, data, "valid thumbnail data received");
+      next();
+    });
+  }, {synchronously: true});
+
+  saved = true;
+}
+
+function testRawAsyncSave() {
+  let cw = TabView.getContentWindow();
+  let url = "http://example.com/async-url";
+  let data = "thumbnail-data-async";
+  let saved = false;
+
+  cw.ThumbnailStorage.saveThumbnail(url, data, function (error) {
+    ok(!error, "thumbnail entry was saved");
+    ok(saved, "thumbnail was saved asynchronously");
+
+    cw.ThumbnailStorage.loadThumbnail(url, function (error, imageData) {
+      ok(!error, "thumbnail entry was loaded");
+      is(imageData, data, "valid thumbnail data received");
+      next();
+    });
+  });
+
+  saved = true;
+}
+
+function testRawLoadError() {
+  let cw = TabView.getContentWindow();
+
+  cw.ThumbnailStorage.loadThumbnail("non-existant-url", function (error, data) {
+    ok(error, "thumbnail entry failed to load");
+    is(null, data, "no thumbnail data received");
+    next();
+  });
+}
+
+function testSyncSave() {
+  let tabItem = gBrowser.tabs[0]._tabViewTabItem;
+
+  // set the thumbnail to dirty
+  tabItem.tabCanvas.paint();
+
+  let saved = false;
+
+  whenThumbnailSaved(tabItem, function () {
+    ok(!saved, "thumbnail was saved synchronously");
+    next();
+  });
+
+  tabItem.saveThumbnail({synchronously: true});
+  saved = true;
+}
+
+function testAsyncSave() {
+  let tabItem = gBrowser.tabs[0]._tabViewTabItem;
+
+  // set the thumbnail to dirty
+  tabItem.tabCanvas.paint();
+
+  let saved = false;
+
+  whenThumbnailSaved(tabItem, function () {
+    ok(saved, "thumbnail was saved asynchronously");
+    next();
+  });
+
+  tabItem.saveThumbnail();
+  saved = true;
+}
+
+function testOverrideAsyncSave() {
+  let tabItem = gBrowser.tabs[0]._tabViewTabItem;
+
+  // set the thumbnail to dirty
+  tabItem.tabCanvas.paint();
+
+  // initiate async save
+  tabItem.saveThumbnail();
+
+  let saveCount = 0;
+
+  whenThumbnailSaved(tabItem, function () {
+    saveCount = 1;
+  });
+
+  tabItem.saveThumbnail({synchronously: true});
+
+  is(saveCount, 1, "thumbnail got saved once");
+  next();
+}
+
+function testSaveCleanThumbnail() {
+  let tabItem = gBrowser.tabs[0]._tabViewTabItem;
+
+  // set the thumbnail to dirty
+  tabItem.tabCanvas.paint();
+
+  let saveCount = 0;
+
+  whenThumbnailSaved(tabItem, function () saveCount++);
+  tabItem.saveThumbnail({synchronously: true});
+  tabItem.saveThumbnail({synchronously: true});
+
+  is(saveCount, 1, "thumbnail got saved once, only");
+  next();
+}
+
+// ----------
+function whenThumbnailSaved(tabItem, callback) {
+  tabItem.addSubscriber("savedCachedImageData", function onSaved() {
+    tabItem.removeSubscriber("savedCachedImageData", onSaved);
+    callback();
+  });
+}
+
+// ----------
+function loadTabView(callback) {
+  afterAllTabsLoaded(function () {
+    showTabView(function () {
+      hideTabView(callback);
+    });
+  });
+}
+
+// ----------
+function next() {
+  let test = tests.shift();
+
+  if (test) {
+    info("* running " + test.name + "...");
+    test();
+  } else {
+    finish();
+  }
+}
--- a/browser/branding/nightly/pref/firefox-branding.js
+++ b/browser/branding/nightly/pref/firefox-branding.js
@@ -1,13 +1,12 @@
 pref("startup.homepage_override_url","http://www.mozilla.org/projects/%APP%/%VERSION%/whatsnew/");
 pref("startup.homepage_welcome_url","http://www.mozilla.org/projects/%APP%/%VERSION%/firstrun/");
 // The time interval between checks for a new version (in seconds)
-// nightly=8 hours, official=24 hours
-pref("app.update.interval", 28800);
+pref("app.update.interval", 7200); // 2 hours
 // The time interval between the downloading of mar file chunks in the
 // background (in seconds)
 pref("app.update.download.backgroundInterval", 60);
 // URL user can browse to manually if for some reason all update installation
 // attempts fail.
 pref("app.update.url.manual", "http://nightly.mozilla.org/");
 // A default value for the "More information about this update" link
 // supplied in the "An update is available" page of the update wizard. 
--- a/browser/branding/unofficial/pref/firefox-branding.js
+++ b/browser/branding/unofficial/pref/firefox-branding.js
@@ -1,13 +1,12 @@
 pref("startup.homepage_override_url","http://www.mozilla.org/projects/%APP%/%VERSION%/whatsnew/");
 pref("startup.homepage_welcome_url","http://www.mozilla.org/projects/%APP%/%VERSION%/firstrun/");
 // The time interval between checks for a new version (in seconds)
-// nightly=8 hours, official=24 hours
-pref("app.update.interval", 28800);
+pref("app.update.interval", 86400); // 24 hours
 // The time interval between the downloading of mar file chunks in the
 // background (in seconds)
 pref("app.update.download.backgroundInterval", 60);
 // URL user can browse to manually if for some reason all update installation
 // attempts fail.
 pref("app.update.url.manual", "http://www.mozilla.org/products/%APP%/");
 // A default value for the "More information about this update" link
 // supplied in the "An update is available" page of the update wizard. 
--- a/browser/components/sessionstore/src/nsSessionStore.js
+++ b/browser/components/sessionstore/src/nsSessionStore.js
@@ -481,16 +481,21 @@ SessionStoreService.prototype = {
     case "domwindowclosed": // catch closed windows
       this.onClose(aSubject);
       break;
     case "quit-application-requested":
       // get a current snapshot of all windows
       this._forEachBrowserWindow(function(aWindow) {
         this._collectWindowData(aWindow);
       });
+      // we must cache this because _getMostRecentBrowserWindow will always
+      // return null by the time quit-application occurs
+      var activeWindow = this._getMostRecentBrowserWindow();
+      if (activeWindow)
+        this.activeWindowSSiCache = activeWindow.__SSi || "";
       this._dirtyWindows = [];
       break;
     case "quit-application-granted":
       // freeze the data at what we've got (ignoring closing windows)
       this._loadState = STATE_QUITTING;
       break;
     case "browser-lastwindow-close-granted":
       // last browser window is quitting.
@@ -1507,16 +1512,23 @@ SessionStoreService.prototype = {
 
     // We want to re-use the last opened window instead of opening a new one in
     // the case where it's "empty" and not associated with a window in the session.
     // We will do more processing via _prepWindowToRestoreInto if we need to use
     // the lastWindow.
     let lastWindow = this._getMostRecentBrowserWindow();
     let canUseLastWindow = lastWindow &&
                            !lastWindow.__SS_lastSessionWindowID;
+    let lastSessionFocusedWindow = null;
+    this.windowToFocus = lastWindow;
+
+    // move the last focused window to the start of the array so that we
+    // minimize window movement (see bug 669272)
+    lastSessionState.windows.unshift(
+      lastSessionState.windows.splice(lastSessionState.selectedWindow - 1, 1)[0]);
 
     // Restore into windows or open new ones as needed.
     for (let i = 0; i < lastSessionState.windows.length; i++) {
       let winState = lastSessionState.windows[i];
       let lastSessionWindowID = winState.__lastSessionWindowID;
       // delete lastSessionWindowID so we don't add that to the window again
       delete winState.__lastSessionWindowID;
 
@@ -1544,19 +1556,28 @@ SessionStoreService.prototype = {
         // Restore into that window - pretend it's a followup since we'll already
         // have a focused window.
         //XXXzpao This is going to merge extData together (taking what was in
         //        winState over what is in the window already. The hack we have
         //        in _preWindowToRestoreInto will prevent most (all?) Panorama
         //        weirdness but we will still merge other extData.
         //        Bug 588217 should make this go away by merging the group data.
         this.restoreWindow(windowToUse, { windows: [winState] }, canOverwriteTabs, true);
+        if (i == 0)
+          lastSessionFocusedWindow = windowToUse;
+
+        // if we overwrote the tabs for our last focused window, we should
+        // give focus to the window that had it in the previous session
+        if (canOverwriteTabs && windowToUse == lastWindow)
+          this.windowToFocus = lastSessionFocusedWindow;
       }
       else {
-        this._openWindowWithState({ windows: [winState] });
+        let win = this._openWindowWithState({ windows: [winState] });
+        if (i == 0)
+          lastSessionFocusedWindow = win;
       }
     }
 
     // Merge closed windows from this session with ones from last session
     if (lastSessionState._closedWindows) {
       this._closedWindows = this._closedWindows.concat(lastSessionState._closedWindows);
       this._capClosedWindows();
     }
@@ -2539,28 +2560,29 @@ SessionStoreService.prototype = {
     // We're not returning from this before we end up calling restoreHistoryPrecursor
     // for this window, so make sure we send the SSWindowStateBusy event.
     this._setWindowStateBusy(aWindow);
 
     if (root._closedWindows)
       this._closedWindows = root._closedWindows;
 
     var winData;
-    if (!aState.selectedWindow) {
-      aState.selectedWindow = 0;
+    if (!root.selectedWindow) {
+      root.selectedWindow = 0;
+    } else {
+      // put the selected window at the beginning of the array to ensure that
+      // it gets restored first
+      root.windows.unshift(root.windows.splice(root.selectedWindow - 1, 1)[0]);
     }
     // open new windows for all further window entries of a multi-window session
     // (unless they don't contain any tab data)
     for (var w = 1; w < root.windows.length; w++) {
       winData = root.windows[w];
       if (winData && winData.tabs && winData.tabs[0]) {
         var window = this._openWindowWithState({ windows: [winData] });
-        if (w == aState.selectedWindow - 1) {
-          this.windowToFocus = window;
-        }
       }
     }
     winData = root.windows[0];
     if (!winData.tabs) {
       winData.tabs = [];
     }
     // don't restore a single blank tab when we've had an external
     // URL passed in for loading at startup (cf. bug 357419)
--- a/browser/devtools/styleinspector/StyleInspector.jsm
+++ b/browser/devtools/styleinspector/StyleInspector.jsm
@@ -50,17 +50,23 @@ var StyleInspector = {
    * Is the Style Inspector enabled?
    * @returns {Boolean} true or false
    */
   get isEnabled()
   {
     return Services.prefs.getBoolPref("devtools.styleinspector.enabled");
   },
 
-  createPanel: function SI_createPanel()
+  /**
+   * Factory method to create the actual style panel
+   * @param {Boolean} aPreserveOnHide Prevents destroy from being called
+   * onpopuphide. USE WITH CAUTION: When this value is set to true then you are
+   * responsible to manually call destroy from outside the style inspector.
+   */
+  createPanel: function SI_createPanel(aPreserveOnHide)
   {
     let win = Services.wm.getMostRecentWindow("navigator:browser");
     let popupSet = win.document.getElementById("mainPopupSet");
     let ns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
     let panel = win.document.createElementNS(ns, "panel");
 
     panel.setAttribute("orient", "vertical");
     panel.setAttribute("ignorekeys", "true");
@@ -93,31 +99,45 @@ var StyleInspector = {
     spacer.setAttribute("flex", "1");
     hbox.appendChild(spacer);
 
     let resizer = win.document.createElement("resizer");
     resizer.setAttribute("dir", "bottomend");
     hbox.appendChild(resizer);
     popupSet.appendChild(panel);
 
-    panel.addEventListener("popupshown", function SI_popup_shown() {
+    /**
+     * Initialize the popup when it is first shown
+     */
+    function SI_popupShown() {
       if (!this.cssHtmlTree) {
         this.cssLogic = new CssLogic();
         this.cssHtmlTree = new CssHtmlTree(iframe, this.cssLogic, this);
       }
 
       this.cssLogic.highlight(this.selectedNode);
       this.cssHtmlTree.highlight(this.selectedNode);
       Services.obs.notifyObservers(null, "StyleInspector-opened", null);
-    }, false);
+    }
 
-    panel.addEventListener("popuphidden", function SI_popup_hidden() {
-      Services.obs.notifyObservers(null, "StyleInspector-closed", null);
-    }, false);
-    
+    /**
+     * Hide the popup and conditionally destroy it
+     */
+    function SI_popupHidden() {
+      if (panel.preserveOnHide) {
+        Services.obs.notifyObservers(null, "StyleInspector-closed", null);
+      } else {
+        panel.destroy();
+      }
+    }
+
+    panel.addEventListener("popupshown", SI_popupShown);
+    panel.addEventListener("popuphidden", SI_popupHidden);
+    panel.preserveOnHide = !!aPreserveOnHide;
+
     /**
      * Check if the style inspector is open
      */
     panel.isOpen = function SI_isOpen()
     {
       return this.state && this.state == "open";
     };
 
@@ -134,16 +154,29 @@ var StyleInspector = {
         this.cssHtmlTree.highlight(aNode);
       } else {
         let win = Services.wm.getMostRecentWindow("navigator:browser");
         this.openPopup(win.gBrowser.selectedBrowser, "end_before", 0, 0, false, false);
       }
     };
 
     /**
+     * Destroy the style panel, remove listeners etc.
+     */
+    panel.destroy = function SI_destroy()
+    {
+      this.cssLogic = null;
+      this.cssHtmlTree = null;
+      this.removeEventListener("popupshown", SI_popupShown);
+      this.removeEventListener("popuphidden", SI_popupHidden);
+      this.parentNode.removeChild(this);
+      Services.obs.notifyObservers(null, "StyleInspector-closed", null);
+    };
+
+    /**
      * Is the Style Inspector initialized?
      * @returns {Boolean} true or false
      */
     function isInitialized()
     {
       return panel.cssLogic && panel.cssHtmlTree;
     }
 
--- a/browser/devtools/webconsole/HUDService.jsm
+++ b/browser/devtools/webconsole/HUDService.jsm
@@ -1781,17 +1781,16 @@ HUD_SERVICE.prototype =
     let popupset = hud.chromeDocument.getElementById("mainPopupSet");
     let panels = popupset.querySelectorAll("panel[hudId=" + aHUDId + "]");
     for (let i = 0; i < panels.length; i++) {
       panels[i].hidePopup();
     }
     panels = popupset.querySelectorAll("panel[hudToolId=" + aHUDId + "]");
     for (let i = 0; i < panels.length; i++) {
       panels[i].hidePopup();
-      popupset.removeChild(panels[i]);
     }
 
     let id = ConsoleUtils.supString(aHUDId);
     Services.obs.notifyObservers(id, "web-console-destroyed", null);
 
     if (Object.keys(this.hudReferences).length == 0) {
       let autocompletePopup = hud.chromeDocument.
                               getElementById("webConsole_autocompletePopup");
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -174,16 +174,17 @@
 @BINPATH@/components/htmlparser.xpt
 @BINPATH@/components/imglib2.xpt
 @BINPATH@/components/imgicon.xpt
 @BINPATH@/components/inspector.xpt
 @BINPATH@/components/intl.xpt
 @BINPATH@/components/jar.xpt
 @BINPATH@/components/jetpack.xpt
 @BINPATH@/components/jsdservice.xpt
+@BINPATH@/components/jsdebugger.xpt
 @BINPATH@/components/layout_base.xpt
 @BINPATH@/components/layout_forms.xpt
 #ifdef NS_PRINTING
 @BINPATH@/components/layout_printing.xpt
 #endif
 @BINPATH@/components/layout_xul_tree.xpt
 @BINPATH@/components/layout_xul.xpt
 @BINPATH@/components/locale.xpt
--- a/browser/themes/pinstripe/browser/browser.css
+++ b/browser/themes/pinstripe/browser/browser.css
@@ -806,19 +806,32 @@ toolbar[mode="icons"] #zoom-in-button {
   box-shadow: 0 1px rgba(255, 255, 255, 0.2), inset 0 1px hsla(0,0%,0%,.05);
   margin: 0 4px;
   padding: 0;
   border: 1px solid;
   border-color: #626262 #787878 #8c8c8c;
   background-clip: padding-box;
 }
 
-#urlbar:-moz-window-inactive,
-.searchbar-textbox:-moz-window-inactive {
-  border-color: @toolbarbuttonInactiveBorderColor@;
+@media (-moz-mac-lion-theme) {
+  #urlbar,
+  .searchbar-textbox {
+    background-image: -moz-linear-gradient(hsl(0,0%,97%), hsl(0,0%,100%));
+    border-color: hsla(0,0%,0%,.35) hsla(0,0%,0%,.25) hsla(0,0%,0%,.15);
+    box-shadow: 0 1px 0 hsla(0,0%,100%,.2),
+                inset 0 0 1px hsla(0,0%,0%,.05),
+                inset 0 1px 2px hsla(0,0%,0%,.1);
+  }
+}
+
+@media not all and (-moz-mac-lion-theme) {
+  #urlbar:-moz-window-inactive,
+  .searchbar-textbox:-moz-window-inactive {
+    border-color: @toolbarbuttonInactiveBorderColor@;
+  }
 }
 
 #urlbar[focused="true"],
 .searchbar-textbox[focused="true"] {
   border-color: -moz-mac-focusring;
   box-shadow: @focusRingShadow@;
 }
 
@@ -2561,8 +2574,53 @@ panel[dimmed="true"] {
   outline: 1px dashed rgba(255,255,255,0.5);
   outline-offset: -1px;
 }
 
 #highlighter-veil-transparentbox[locked] {
   box-shadow: 0 0 0 1px black;
   outline-color: white;
 }
+
+/* Highlighter toolbar */
+
+#inspector-toolbar {
+  -moz-appearance: none;
+  height: 32px;
+  padding: 0 3px;
+  border-top: 1px solid hsla(210, 8%, 5%, .65);
+  box-shadow: 0 1px 0 0 hsla(210, 16%, 76%, .2) inset;
+  background-image: -moz-linear-gradient(top, hsl(210,11%,36%), hsl(210,11%,18%));
+}
+
+#inspector-inspect-toolbutton,
+#inspector-tools > toolbarbutton {
+  -moz-appearance: none;
+  width: 78px;
+  margin: 3px 5px;
+  color: hsl(210,30%,85%);
+  text-shadow: 0 -1px 0 hsla(210,8%,5%,.45);
+  border: 1px solid hsla(210,8%,5%,.45);
+  border-radius: @toolbarbuttonCornerRadius@;
+  background: -moz-linear-gradient(hsla(212,7%,57%,.35), hsla(212,7%,57%,.1));
+  background-clip: padding-box;
+  box-shadow: 0 1px 0 hsla(210,16%,76%,.15) inset, 0 0 0 1px hsla(210,16%,76%,.15) inset, 0 1px 0 hsla(210,16%,76%,.15);
+}
+
+#inspector-inspect-toolbutton:not([checked]):hover:active,
+#inspector-tools > toolbarbutton:not([checked]):hover:active {
+  border-color: hsla(210,8%,5%,.6);
+  background: -moz-linear-gradient(hsla(220,6%,10%,.3), hsla(212,7%,57%,.15) 65%, hsla(212,7%,57%,.3));
+  box-shadow: 0 0 3px hsla(210,8%,5%,.25) inset, 0 1px 3px hsla(210,8%,5%,.25) inset, 0 1px 0 hsla(210,16%,76%,.15);
+}
+
+#inspector-inspect-toolbutton[checked],
+#inspector-tools > toolbarbutton[checked] {
+  color: hsl(208,100%,60%) !important;
+  border-color: hsla(210,8%,5%,.6);
+  background: -moz-linear-gradient(hsla(220,6%,10%,.6), hsla(210,11%,18%,.45) 75%, hsla(210,11%,30%,.4));
+  box-shadow: 0 1px 3px hsla(210,8%,5%,.25) inset, 0 1px 3px hsla(210,8%,5%,.25) inset, 0 1px 0 hsla(210,16%,76%,.15);
+}
+
+#inspector-inspect-toolbutton[checked]:hover:active,
+#inspector-tools > toolbarbutton[checked]:hover:active {
+  background-color: hsla(210,8%,5%,.2);
+}
new file mode 100644
--- /dev/null
+++ b/build/autoconf/frameptr.m4
@@ -0,0 +1,25 @@
+dnl Set MOZ_FRAMEPTR_FLAGS to the flags that should be used for enabling or
+dnl disabling frame pointers in this architecture based on the configure
+dnl options
+
+AC_DEFUN([MOZ_SET_FRAMEPTR_FLAGS], [
+  if test "$GNU_CC"; then
+    MOZ_ENABLE_FRAME_PTR="-fno-omit-frame-pointer"
+    MOZ_DISABLE_FRAME_PTR="-fomit-frame-pointer"
+  else
+    case "$target" in
+    *-mingw*)
+      MOZ_ENABLE_FRAME_PTR="-Oy-"
+      MOZ_DISABLE_FRAME_PTR="-Oy"
+    ;;
+    esac
+  fi
+
+  # if we are debugging or profiling, we want a frame pointer.
+  if test -z "$MOZ_OPTIMIZE" -o \
+          -n "$MOZ_PROFILING" -o -n "$MOZ_DEBUG"; then
+    MOZ_FRAMEPTR_FLAGS="$MOZ_ENABLE_FRAME_PTR"
+  else
+    MOZ_FRAMEPTR_FLAGS="$MOZ_DISABLE_FRAME_PTR"
+  fi
+])
--- a/caps/src/nsScriptSecurityManager.cpp
+++ b/caps/src/nsScriptSecurityManager.cpp
@@ -2418,25 +2418,25 @@ nsScriptSecurityManager::doGetObjectPrin
 
     // A common case seen in this code is that we enter this function
     // with aObj being a Function object, whose parent is a Call
     // object. Neither of those have object principals, so we can skip
     // those objects here before we enter the below loop. That way we
     // avoid wasting time checking properties of their classes etc in
     // the loop.
 
-    if (jsClass == &js_FunctionClass) {
+    if (jsClass == &js::FunctionClass) {
         aObj = aObj->getParent();
 
         if (!aObj)
             return nsnull;
 
         jsClass = aObj->getClass();
 
-        if (jsClass == &js_CallClass) {
+        if (jsClass == &js::CallClass) {
             aObj = aObj->getParent();
 
             if (!aObj)
                 return nsnull;
 
             jsClass = aObj->getClass();
         }
     }
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -246,17 +246,16 @@ MOZ_TREE_CAIRO = @MOZ_TREE_CAIRO@
 MOZ_TREE_PIXMAN = @MOZ_TREE_PIXMAN@
 
 MOZ_UPDATE_XTERM = @MOZ_UPDATE_XTERM@
 MOZ_PERMISSIONS = @MOZ_PERMISSIONS@
 MOZ_XTF = @MOZ_XTF@
 MOZ_SVG_DLISTS = @MOZ_SVG_DLISTS@
 MOZ_CAIRO_CFLAGS = @MOZ_CAIRO_CFLAGS@
 MOZ_SMIL = @MOZ_SMIL@
-MOZ_XSLT_STANDALONE = @MOZ_XSLT_STANDALONE@
 
 MOZ_PREF_EXTENSIONS = @MOZ_PREF_EXTENSIONS@
 
 MOZ_CAIRO_LIBS = @MOZ_CAIRO_LIBS@
 
 MOZ_ENABLE_GNOMEUI = @MOZ_ENABLE_GNOMEUI@
 MOZ_GNOMEUI_CFLAGS = @MOZ_GNOMEUI_CFLAGS@
 MOZ_GNOMEUI_LIBS = @MOZ_GNOMEUI_LIBS@
@@ -299,16 +298,17 @@ OS_COMPILE_CXXFLAGS = $(OS_CPPFLAGS) @CO
 
 OS_INCLUDES	= $(NSPR_CFLAGS) $(NSS_CFLAGS) $(JPEG_CFLAGS) $(PNG_CFLAGS) $(ZLIB_CFLAGS)
 OS_LIBS		= @LIBS@
 ACDEFINES	= @MOZ_DEFINES@
 
 WARNINGS_AS_ERRORS = @WARNINGS_AS_ERRORS@
 
 MOZ_OPTIMIZE	= @MOZ_OPTIMIZE@
+MOZ_FRAMEPTR_FLAGS = @MOZ_FRAMEPTR_FLAGS@
 MOZ_OPTIMIZE_FLAGS = @MOZ_OPTIMIZE_FLAGS@
 MOZ_PGO_OPTIMIZE_FLAGS = @MOZ_PGO_OPTIMIZE_FLAGS@
 MOZ_OPTIMIZE_LDFLAGS = @MOZ_OPTIMIZE_LDFLAGS@
 MOZ_OPTIMIZE_SIZE_TWEAK = @MOZ_OPTIMIZE_SIZE_TWEAK@
 
 MOZ_RTTI_FLAGS_ON = @_MOZ_RTTI_FLAGS_ON@
 MOZ_EXCEPTIONS_FLAGS_ON = @_MOZ_EXCEPTIONS_FLAGS_ON@
 
--- a/config/config.mk
+++ b/config/config.mk
@@ -458,16 +458,19 @@ else
 HOST_CFLAGS	+= $(MOZ_OPTIMIZE_FLAGS)
 endif # MODULE_OPTIMIZE_FLAGS
 else
 HOST_CFLAGS	+= $(MOZ_OPTIMIZE_FLAGS)
 endif # MOZ_OPTIMIZE == 1
 endif # MOZ_OPTIMIZE
 endif # CROSS_COMPILE
 
+CFLAGS += $(MOZ_FRAMEPTR_FLAGS)
+CXXFLAGS += $(MOZ_FRAMEPTR_FLAGS)
+
 # Check for FAIL_ON_WARNINGS & FAIL_ON_WARNINGS_DEBUG (Shorthand for Makefiles
 # to request that we use the 'warnings as errors' compile flags)
 
 # NOTE: First, we clear FAIL_ON_WARNINGS[_DEBUG] if we're doing a Windows PGO
 # build, since WARNINGS_AS_ERRORS has been suspected of causing isuses in that
 # situation. (See bug 437002.)
 ifeq (WINNT_1,$(OS_ARCH)_$(MOZ_PROFILE_GENERATE)$(MOZ_PROFILE_USE))
 FAIL_ON_WARNINGS_DEBUG=
--- a/configure.in
+++ b/configure.in
@@ -2066,22 +2066,17 @@ case "$target" in
 	    MKSHLIB_UNFORCE_ALL=''
 	;;
     esac
     ;;
 
 *-darwin*)
     MKSHLIB='$(CXX) $(CXXFLAGS) $(DSO_PIC_CFLAGS) $(DSO_LDOPTS) -o $@'
     MKCSHLIB='$(CC) $(CFLAGS) $(DSO_PIC_CFLAGS) $(DSO_LDOPTS) -o $@'
-    # If we're building with --enable-profiling, we need a frame pointer.
-    if test -z "$MOZ_PROFILING"; then
-        MOZ_OPTIMIZE_FLAGS="-O3 -fomit-frame-pointer"
-    else
-        MOZ_OPTIMIZE_FLAGS="-O3 -fno-omit-frame-pointer"
-    fi
+    MOZ_OPTIMIZE_FLAGS="-O3"
     _PEDANTIC=
     CFLAGS="$CFLAGS -fno-common"
     CXXFLAGS="$CXXFLAGS -fno-common"
     DLL_SUFFIX=".dylib"
     DSO_LDOPTS=''
     STRIP="$STRIP -x -S"
     # Check whether we're targeting OS X or iOS
     AC_CACHE_CHECK(for iOS target,
@@ -2183,22 +2178,17 @@ ia64*-hpux*)
 
 *-android*|*-linuxandroid*)
     AC_DEFINE(NO_PW_GECOS)
     no_x=yes
     _PLATFORM_DEFAULT_TOOLKIT=cairo-android
     TARGET_NSPR_MDCPUCFG='\"md/_linux.cfg\"'
 
     MOZ_GFX_OPTIMIZE_MOBILE=1
-    # If we're building with --enable-profiling, we need a frame pointer.
-    if test -z "$MOZ_PROFILING"; then
-        MOZ_OPTIMIZE_FLAGS="-Os -freorder-blocks -fno-reorder-functions -fomit-frame-pointer"
-    else
-        MOZ_OPTIMIZE_FLAGS="-Os -freorder-blocks -fno-reorder-functions -fno-omit-frame-pointer"
-    fi
+    MOZ_OPTIMIZE_FLAGS="-Os -freorder-blocks -fno-reorder-functions"
     ;;
 
 *-*linux*)
     # Note: both GNU_CC and INTEL_CC are set when using Intel's C compiler.
     # Similarly for GNU_CXX and INTEL_CXX.
     if test "$INTEL_CC" -o "$INTEL_CXX"; then
         # -Os has been broken on Intel's C/C++ compilers for quite a
         # while; Intel recommends against using it.
@@ -2206,24 +2196,18 @@ ia64*-hpux*)
         MOZ_DEBUG_FLAGS="-g"
     elif test "$GNU_CC" -o "$GNU_CXX"; then
         GCC_VERSION=`$CC -v 2>&1 | awk '/^gcc version/ { print $3 }'`
         case $GCC_VERSION in
         4.1.*|4.2.*|4.5.*)
             # -Os is broken on gcc 4.1.x 4.2.x, 4.5.x we need to tweak it to get good results.
             MOZ_OPTIMIZE_SIZE_TWEAK="-finline-limit=50"
         esac
-        # If we're building with --enable-profiling, we need a frame pointer.
-        if test -z "$MOZ_PROFILING"; then
-            MOZ_FRAMEPTR_FLAGS="-fomit-frame-pointer"
-        else
-            MOZ_FRAMEPTR_FLAGS="-fno-omit-frame-pointer"
-        fi
-        MOZ_PGO_OPTIMIZE_FLAGS="-O3 $MOZ_FRAMEPTR_FLAGS"
-        MOZ_OPTIMIZE_FLAGS="-Os -freorder-blocks $MOZ_OPTIMIZE_SIZE_TWEAK $MOZ_FRAMEPTR_FLAGS"
+        MOZ_PGO_OPTIMIZE_FLAGS="-O3"
+        MOZ_OPTIMIZE_FLAGS="-Os -freorder-blocks $MOZ_OPTIMIZE_SIZE_TWEAK"
         MOZ_DEBUG_FLAGS="-g"
     fi
 
     TARGET_NSPR_MDCPUCFG='\"md/_linux.cfg\"'
 
     MOZ_MEMORY=1
 
     case "${target_cpu}" in
@@ -2310,22 +2294,17 @@ ia64*-hpux*)
         CXXFLAGS="$CXXFLAGS -wd4800" # disable warning "forcing value to bool"
         # make 'foo == bar;' error out
         CFLAGS="$CFLAGS -we4553"
         CXXFLAGS="$CXXFLAGS -we4553"
         LIBS="$LIBS kernel32.lib user32.lib gdi32.lib winmm.lib wsock32.lib advapi32.lib"
         MOZ_DEBUG_FLAGS='-Zi'
         MOZ_DEBUG_LDFLAGS='-DEBUG -DEBUGTYPE:CV'
         WARNINGS_AS_ERRORS='-WX'
-        # If we're building with --enable-profiling, we need -Oy-, which forces a frame pointer.
-        if test -z "$MOZ_PROFILING"; then
-            MOZ_OPTIMIZE_FLAGS='-O1'
-        else
-            MOZ_OPTIMIZE_FLAGS='-O1 -Oy-'
-        fi
+        MOZ_OPTIMIZE_FLAGS='-O1'
         MOZ_FIX_LINK_PATHS=
         DYNAMIC_XPCOM_LIBS='$(LIBXUL_DIST)/lib/xpcom.lib $(LIBXUL_DIST)/lib/xpcom_core.lib $(LIBXUL_DIST)/lib/mozalloc.lib'
         XPCOM_FROZEN_LDOPTS='$(LIBXUL_DIST)/lib/xpcom.lib $(LIBXUL_DIST)/lib/mozalloc.lib'
         LIBXUL_LIBS='$(LIBXUL_DIST)/lib/xpcom.lib $(LIBXUL_DIST)/lib/xul.lib $(LIBXUL_DIST)/lib/mozalloc.lib'
         MOZ_COMPONENT_NSPR_LIBS='$(NSPR_LIBS)'
         if test $_MSC_VER -ge 1400; then
             LDFLAGS="$LDFLAGS -LARGEADDRESSAWARE -NXCOMPAT"
             dnl For profile-guided optimization
@@ -4480,17 +4459,16 @@ MOZ_REFLOW_PERF=
 MOZ_SAFE_BROWSING=
 MOZ_HELP_VIEWER=
 MOZ_SPELLCHECK=1
 MOZ_SVG_DLISTS=
 MOZ_TOOLKIT_SEARCH=1
 MOZ_UI_LOCALE=en-US
 MOZ_UNIVERSALCHARDET=1
 MOZ_URL_CLASSIFIER=
-MOZ_XSLT_STANDALONE=
 MOZ_XTF=1
 MOZ_XUL=1
 MOZ_ZIPWRITER=1
 NS_PRINTING=1
 MOZ_PDF_PRINTING=
 MOZ_DISABLE_DOMCRYPTO=
 NSS_DISABLE_DBM=
 NECKO_WIFI=1
@@ -4536,18 +4514,16 @@ case "${target}" in
         ;;
 esac
 
 MOZ_ARG_ENABLE_STRING(application,
 [  --enable-application=APP
                           Options include:
                             browser (Firefox)
                             xulrunner
-                            content/xslt (Standalone Transformiix XSLT)
-                            netwerk (Standalone Necko)
                             tools/update-packaging (AUS-related packaging tools)],
 [ MOZ_BUILD_APP=$enableval ] )
 
 MOZ_ARG_WITH_STRING(xulrunner-stub-name,
 [  --with-xulrunner-stub-name=appname   Create the xulrunner stub with the given name],
   XULRUNNER_STUB_NAME=$withval)
 
 if test -z "$XULRUNNER_STUB_NAME"; then
@@ -4611,21 +4587,16 @@ esac
 case "$MOZ_BUILD_APP" in
 browser)
   AC_DEFINE(MOZ_PHOENIX)
   ;;
 
 xulrunner)
   AC_DEFINE(MOZ_XULRUNNER)
   ;;
-
-content/xslt)
-  AC_DEFINE(TX_EXE)
-  ;;
-
 esac
 
 AC_SUBST(MOZ_BUILD_APP)
 AC_SUBST(MOZ_PHOENIX)
 AC_SUBST(MOZ_XULRUNNER)
 
 AC_DEFINE_UNQUOTED(MOZ_BUILD_APP,$MOZ_BUILD_APP)
 
@@ -6900,16 +6871,18 @@ MOZ_ARG_ENABLE_STRING(optimize,
     if test -n "$enableval" -a "$enableval" != "yes"; then
         MOZ_OPTIMIZE_FLAGS=`echo "$enableval" | sed -e 's|\\\ | |g'`
         MOZ_OPTIMIZE=2
     fi
 else
     MOZ_OPTIMIZE=
 fi ], MOZ_OPTIMIZE=1)
 
+MOZ_SET_FRAMEPTR_FLAGS
+
 if test "$COMPILE_ENVIRONMENT"; then
 if test -n "$MOZ_OPTIMIZE"; then
     AC_MSG_CHECKING([for valid optimization flags])
     _SAVE_CFLAGS=$CFLAGS
     CFLAGS="$CFLAGS $MOZ_OPTIMIZE_FLAGS"
     AC_TRY_COMPILE([#include <stdio.h>],
         [printf("Hello World\n");],
         _results=yes,
@@ -6918,16 +6891,17 @@ if test -n "$MOZ_OPTIMIZE"; then
     if test "$_results" = "no"; then
         AC_MSG_ERROR([These compiler flags are invalid: $MOZ_OPTIMIZE_FLAGS])
     fi
     CFLAGS=$_SAVE_CFLAGS
 fi
 fi # COMPILE_ENVIRONMENT
 
 AC_SUBST(MOZ_OPTIMIZE)
+AC_SUBST(MOZ_FRAMEPTR_FLAGS)
 AC_SUBST(MOZ_OPTIMIZE_FLAGS)
 AC_SUBST(MOZ_OPTIMIZE_LDFLAGS)
 AC_SUBST(MOZ_OPTIMIZE_SIZE_TWEAK)
 AC_SUBST(MOZ_PGO_OPTIMIZE_FLAGS)
 
 dnl ========================================================
 dnl = Enable generation of debug symbols
 dnl ========================================================
@@ -8538,17 +8512,16 @@ AC_SUBST(NS_USE_NATIVE)
 AC_SUBST(MOZ_WIDGET_TOOLKIT)
 AC_SUBST(MOZ_UPDATE_XTERM)
 AC_SUBST(MOZ_PLATFORM_MAEMO)
 AC_SUBST(MOZ_AUTH_EXTENSION)
 AC_SUBST(MOZ_PERMISSIONS)
 AC_SUBST(MOZ_XTF)
 AC_SUBST(MOZ_PREF_EXTENSIONS)
 AC_SUBST(MOZ_SMIL)
-AC_SUBST(MOZ_XSLT_STANDALONE)
 AC_SUBST(MOZ_JS_LIBS)
 AC_SUBST(MOZ_PSM)
 AC_SUBST(MOZ_DEBUG)
 AC_SUBST(MOZ_DEBUG_SYMBOLS)
 AC_SUBST(MOZ_DEBUG_ENABLE_DEFS)
 AC_SUBST(MOZ_DEBUG_DISABLE_DEFS)
 AC_SUBST(MOZ_DEBUG_FLAGS)
 AC_SUBST(MOZ_DEBUG_LDFLAGS)
new file mode 100644
--- /dev/null
+++ b/content/base/crashtests/679689-1.html
@@ -0,0 +1,2 @@
+<!DOCTYPE html>
+<img crossorigin>
--- a/content/base/crashtests/crashtests.list
+++ b/content/base/crashtests/crashtests.list
@@ -88,8 +88,9 @@ load 610571-1.html
 load 604262-1.html
 load 628599-1.html
 load 637214-1.svg
 load 637214-2.svg
 load 642022-1.html
 load 646184.html
 load 658845-1.svg
 load 667336-1.html
+load 679689-1.html
--- a/content/base/public/nsContentUtils.h
+++ b/content/base/public/nsContentUtils.h
@@ -1695,16 +1695,36 @@ public:
   /**
    * Determine whether a content node is focused or not,
    *
    * @param aContent the content node to check
    * @return true if the content node is focused, false otherwise.
    */
   static PRBool IsFocusedContent(const nsIContent *aContent);
 
+  /**
+   * Returns PR_TRUE if the DOM full-screen API is enabled.
+   */
+  static PRBool IsFullScreenApiEnabled();
+
+  /**
+   * Returns PR_TRUE if requests for full-screen are allowed in the current
+   * context. Requests are only allowed if the user initiated them (like with
+   * a mouse-click or key press), unless this check has been disabled by
+   * setting the pref "full-screen-api.allow-trusted-requests-only" to false.
+   */
+  static PRBool IsRequestFullScreenAllowed();
+
+  /**
+   * Returns PR_TRUE if key input is restricted in DOM full-screen mode
+   * to non-alpha-numeric key codes only. This mirrors the
+   * "full-screen-api.key-input-restricted" pref.
+   */
+  static PRBool IsFullScreenKeyInputRestricted();
+
   static void GetShiftText(nsAString& text);
   static void GetControlText(nsAString& text);
   static void GetMetaText(nsAString& text);
   static void GetAltText(nsAString& text);
   static void GetModifierSeparatorText(nsAString& text);
 
   /**
    * Returns if aContent has a tabbable subdocument.
@@ -1859,16 +1879,19 @@ private:
   static nsTArray< nsCOMPtr<nsIRunnable> >* sBlockedScriptRunners;
   static PRUint32 sRunnersCountAtFirstBlocker;
   static PRUint32 sScriptBlockerCountWhereRunnersPrevented;
 
   static nsIInterfaceRequestor* sSameOriginChecker;
 
   static PRBool sIsHandlingKeyBoardEvent;
   static PRBool sAllowXULXBL_for_file;
+  static PRBool sIsFullScreenApiEnabled;
+  static PRBool sTrustedFullScreenOnly;
+  static PRBool sFullScreenKeyInputRestricted;
 
   static nsHtml5Parser* sHTMLFragmentParser;
   static nsIParser* sXMLFragmentParser;
   static nsIFragmentContentSink* sXMLFragmentSink;
 
   static nsString* sShiftText;
   static nsString* sControlText;
   static nsString* sMetaText;
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -120,20 +120,19 @@ class Loader;
 } // namespace css
 
 namespace dom {
 class Link;
 class Element;
 } // namespace dom
 } // namespace mozilla
 
-
 #define NS_IDOCUMENT_IID      \
-{ 0x455e4d79, 0x756b, 0x4f73,  \
- { 0x95, 0xea, 0x3f, 0xf6, 0x0c, 0x6a, 0x8c, 0xa6 } }
+{ 0x170d5a75, 0xff0b, 0x4599,  \
+ { 0x9b, 0x68, 0x18, 0xb7, 0x42, 0xe0, 0xf9, 0xf7 } }
 
 // Flag for AddStyleSheet().
 #define NS_STYLESHEET_FROM_CATALOG                (1 << 0)
 
 // Document states
 
 // RTL locale: specific to the XUL localedir attribute
 #define NS_DOCUMENT_STATE_RTL_LOCALE              NS_DEFINE_EVENT_STATE_MACRO(0)
@@ -737,16 +736,53 @@ public:
   /**
    * Add/Remove an element to the document's id and name hashes
    */
   virtual void AddToIdTable(Element* aElement, nsIAtom* aId) = 0;
   virtual void RemoveFromIdTable(Element* aElement, nsIAtom* aId) = 0;
   virtual void AddToNameTable(Element* aElement, nsIAtom* aName) = 0;
   virtual void RemoveFromNameTable(Element* aElement, nsIAtom* aName) = 0;
 
+  /**
+   * Resets the current full-screen element to nsnull.
+   */
+  virtual void ResetFullScreenElement() = 0;
+
+  /**
+   * Returns the element which either is the full-screen element, or
+   * contains the full-screen element if a child of this document contains
+   * the fullscreen element.
+   */
+  virtual Element* GetFullScreenElement() = 0;
+
+  /**
+   * Requests that the document make aElement the full-screen element,
+   * and move into full-screen mode.
+   */
+  virtual void RequestFullScreen(Element* aElement) = 0;
+
+  /**
+   * Requests that the document, and all documents in its hierarchy exit
+   * from DOM full-screen mode.
+   */
+  virtual void CancelFullScreen() = 0;
+
+  /**
+   * Updates the full-screen status on this document, setting the full-screen
+   * mode to aIsFullScreen. This doesn't affect the window's full-screen mode,
+   * this updates the document's internal state which determines whether the
+   * document reports as being in full-screen mode.
+   */
+  virtual void UpdateFullScreenStatus(PRBool aIsFullScreen) = 0;
+
+  /**
+   * Returns PR_TRUE if this document is in full-screen mode.
+   */
+  virtual PRBool IsFullScreenDoc() = 0;
+
   //----------------------------------------------------------------------
 
   // Document notification API's
 
   /**
    * Add a new observer of document change notifications. Whenever
    * content is changed, appended, inserted or removed the observers are
    * informed.  An observer that is already observing the document must
--- a/content/base/public/nsINode.h
+++ b/content/base/public/nsINode.h
@@ -277,18 +277,18 @@ private:
 #define DOM_USER_DATA         1
 #define DOM_USER_DATA_HANDLER 2
 #ifdef MOZ_SMIL
 #define SMIL_MAPPED_ATTR_ANIMVAL 3
 #endif // MOZ_SMIL
 
 // IID for the nsINode interface
 #define NS_INODE_IID \
-{ 0x5572c8a9, 0xbda9, 0x4b78, \
-  { 0xb4, 0x1a, 0xdb, 0x1a, 0x83, 0xef, 0x53, 0x7e } }
+{ 0xb59269fe, 0x7f60, 0x4672, \
+  { 0x8e, 0x56, 0x01, 0x84, 0xb2, 0x58, 0x14, 0xb0 } }
 
 /**
  * An internal interface that abstracts some DOMNode-related parts that both
  * nsIContent and nsIDocument share.  An instance of this interface has a list
  * of nsIContent children and provides access to them.
  */
 class nsINode : public nsIDOMEventTarget,
                 public nsWrapperCache
@@ -1080,16 +1080,24 @@ public:
    * descendants of aRoot, not including aRoot itself, will be returned.
    * Returns null if there are no more nodes to traverse.
    */
   nsIContent* GetNextNonChildNode(const nsINode* aRoot = nsnull) const
   {
     return GetNextNodeImpl(aRoot, PR_TRUE);
   }
 
+  /**
+   * Returns true if 'this' is either document or element or
+   * document fragment and aOther is a descendant in the same
+   * anonymous tree.
+   */
+  PRBool Contains(const nsINode* aOther) const;
+  nsresult Contains(nsIDOMNode* aOther, PRBool* aReturn);
+
 private:
 
   nsIContent* GetNextNodeImpl(const nsINode* aRoot,
                               const PRBool aSkipChildren) const
   {
     // Can't use nsContentUtils::ContentIsDescendantOf here, since we
     // can't include it here.
 #ifdef DEBUG
--- a/content/base/src/nsAttrValue.cpp
+++ b/content/base/src/nsAttrValue.cpp
@@ -1107,34 +1107,34 @@ nsAttrValue::ParseNonNegativeIntValue(co
 
   PRInt32 ec;
   PRBool strict;
   PRInt32 originalVal = StringToInteger(aString, &strict, &ec);
   if (NS_FAILED(ec) || originalVal < 0) {
     return PR_FALSE;
   }
 
-  SetIntValueAndType(originalVal, eInteger, nsnull);
+  SetIntValueAndType(originalVal, eInteger, strict ? nsnull : &aString);
 
   return PR_TRUE;
 }
 
 PRBool
 nsAttrValue::ParsePositiveIntValue(const nsAString& aString)
 {
   ResetIfSet();
 
   PRInt32 ec;
   PRBool strict;
   PRInt32 originalVal = StringToInteger(aString, &strict, &ec);
   if (NS_FAILED(ec) || originalVal <= 0) {
     return PR_FALSE;
   }
 
-  SetIntValueAndType(originalVal, eInteger, nsnull);
+  SetIntValueAndType(originalVal, eInteger, strict ? nsnull : &aString);
 
   return PR_TRUE;
 }
 
 void
 nsAttrValue::SetColorValue(nscolor aColor, const nsAString& aString)
 {
   nsStringBuffer* buf = GetStringBuffer(aString);
@@ -1245,20 +1245,24 @@ nsAttrValue::ParseIntMarginValue(const n
 void
 nsAttrValue::SetMiscAtomOrString(const nsAString* aValue)
 {
   NS_ASSERTION(GetMiscContainer(), "Must have MiscContainer!");
   NS_ASSERTION(!GetMiscContainer()->mStringBits,
                "Trying to re-set atom or string!");
   if (aValue) {
     PRUint32 len = aValue->Length();
-    // We're allowing eCSSStyleRule attributes to store empty strings as it
-    // can be beneficial to store an empty style attribute as a parsed rule.
+    // * We're allowing eCSSStyleRule attributes to store empty strings as it
+    //   can be beneficial to store an empty style attribute as a parsed rule.
+    // * We're allowing enumerated values because sometimes the empty
+    //   string corresponds to a particular enumerated value, especially
+    //   for enumerated values that are not limited enumerated.
     // Add other types as needed.
-    NS_ASSERTION(len || Type() == eCSSStyleRule, "Empty string?");
+    NS_ASSERTION(len || Type() == eCSSStyleRule || Type() == eEnum,
+                 "Empty string?");
     MiscContainer* cont = GetMiscContainer();
     if (len <= NS_ATTRVALUE_MAX_STRINGLENGTH_ATOM) {
       nsIAtom* atom = NS_NewAtom(*aValue);
       if (atom) {
         cont->mStringBits = reinterpret_cast<PtrBits>(atom) | eAtomBase;
       }
     } else {
       nsStringBuffer* buf = GetStringBuffer(*aValue);
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -171,16 +171,17 @@ static NS_DEFINE_CID(kXTFServiceCID, NS_
 #include "nsLayoutUtils.h"
 #include "nsFrameManager.h"
 #include "BasicLayers.h"
 #include "nsFocusManager.h"
 #include "nsTextEditorState.h"
 #include "nsIPluginHost.h"
 #include "nsICategoryManager.h"
 #include "nsIViewManager.h"
+#include "nsEventStateManager.h"
 
 #ifdef IBMBIDI
 #include "nsIBidiKeyboard.h"
 #endif
 #include "nsCycleCollectionParticipant.h"
 
 // for ReportToConsole
 #include "nsIStringBundle.h"
@@ -256,16 +257,19 @@ PRBool nsContentUtils::sAllowXULXBL_for_
 
 nsString* nsContentUtils::sShiftText = nsnull;
 nsString* nsContentUtils::sControlText = nsnull;
 nsString* nsContentUtils::sMetaText = nsnull;
 nsString* nsContentUtils::sAltText = nsnull;
 nsString* nsContentUtils::sModifierSeparator = nsnull;
 
 PRBool nsContentUtils::sInitialized = PR_FALSE;
+PRBool nsContentUtils::sIsFullScreenApiEnabled = PR_FALSE;
+PRBool nsContentUtils::sTrustedFullScreenOnly = PR_TRUE;
+PRBool nsContentUtils::sFullScreenKeyInputRestricted = PR_TRUE;
 
 nsHtml5Parser* nsContentUtils::sHTMLFragmentParser = nsnull;
 nsIParser* nsContentUtils::sXMLFragmentParser = nsnull;
 nsIFragmentContentSink* nsContentUtils::sXMLFragmentSink = nsnull;
 
 static PLDHashTable sEventListenerManagersHash;
 
 class EventListenerManagerMapEntry : public PLDHashEntryHdr
@@ -379,16 +383,25 @@ nsContentUtils::Init()
     }
   }
 
   sBlockedScriptRunners = new nsTArray< nsCOMPtr<nsIRunnable> >;
 
   Preferences::AddBoolVarCache(&sAllowXULXBL_for_file,
                                "dom.allow_XUL_XBL_for_file");
 
+  Preferences::AddBoolVarCache(&sIsFullScreenApiEnabled,
+                               "full-screen-api.enabled");
+
+  Preferences::AddBoolVarCache(&sTrustedFullScreenOnly,
+                               "full-screen-api.allow-trusted-requests-only");
+
+  Preferences::AddBoolVarCache(&sFullScreenKeyInputRestricted,
+                               "full-screen-api.key-input-restricted");
+
   sInitialized = PR_TRUE;
 
   return NS_OK;
 }
 
 void
 nsContentUtils::GetShiftText(nsAString& text)
 {
@@ -5691,8 +5704,25 @@ nsContentUtils::IsPatternMatching(nsAStr
   JSBool res;
 
   res = JS_ExecuteRegExpNoStatics(ctx, re, reinterpret_cast<jschar*>
                                     (aValue.BeginWriting()),
                                   aValue.Length(), &idx, JS_TRUE, &rval);
 
   return res == JS_FALSE || rval != JSVAL_NULL;
 }
+
+PRBool
+nsContentUtils::IsFullScreenApiEnabled()
+{
+  return sIsFullScreenApiEnabled;
+}
+
+PRBool nsContentUtils::IsRequestFullScreenAllowed()
+{
+  return !sTrustedFullScreenOnly || nsEventStateManager::IsHandlingUserInput();
+}
+
+PRBool
+nsContentUtils::IsFullScreenKeyInputRestricted()
+{
+  return sFullScreenKeyInputRestricted;
+}
--- a/content/base/src/nsDOMAttribute.cpp
+++ b/content/base/src/nsDOMAttribute.cpp
@@ -653,16 +653,22 @@ nsDOMAttribute::SetTextContent(const nsA
 NS_IMETHODIMP
 nsDOMAttribute::IsSameNode(nsIDOMNode *other, PRBool *aResult)
 {
   *aResult = other == this;
   return NS_OK;
 }
 
 NS_IMETHODIMP
+nsDOMAttribute::Contains(nsIDOMNode* aOther, PRBool* aReturn)
+{
+  return nsINode::Contains(aOther, aReturn);
+}
+
+NS_IMETHODIMP
 nsDOMAttribute::LookupPrefix(const nsAString & namespaceURI,
                              nsAString & aResult)
 {
   SetDOMStringToNull(aResult);
   return NS_OK;
 }
 
 NS_IMETHODIMP
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -176,16 +176,17 @@
 #ifdef MOZ_MEDIA
 #include "nsHTMLMediaElement.h"
 #endif // MOZ_MEDIA
 
 #include "mozAutoDocUpdate.h"
 #include "nsGlobalWindow.h"
 #include "mozilla/dom/indexedDB/IndexedDatabaseManager.h"
 #include "nsDOMNavigationTiming.h"
+#include "nsEventStateManager.h"
 
 #ifdef MOZ_SMIL
 #include "nsSMILAnimationController.h"
 #include "imgIContainer.h"
 #include "nsSVGUtils.h"
 #endif // MOZ_SMIL
 
 #include "nsRefreshDriver.h"
@@ -1539,16 +1540,17 @@ nsDOMImplementation::CreateHTMLDocument(
 // ==================================================================
 
   // NOTE! nsDocument::operator new() zeroes out all members, so don't
   // bother initializing members to 0.
 
 nsDocument::nsDocument(const char* aContentType)
   : nsIDocument()
   , mAnimatingImages(PR_TRUE)
+  , mIsFullScreen(PR_FALSE)
 {
   SetContentTypeInternal(nsDependentCString(aContentType));
   
 #ifdef PR_LOGGING
   if (!gDocumentLeakPRLog)
     gDocumentLeakPRLog = PR_NewLogModule("DocumentLeak");
 
   if (gDocumentLeakPRLog)
@@ -1866,16 +1868,17 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mLayoutHistoryState)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOnloadBlocker)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mFirstBaseNodeWithHref)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mDOMImplementation)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mImageMaps,
                                                        nsIDOMNodeList)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOriginalDocument)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mCachedEncoder)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mFullScreenElement)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mStateObjectCached)
 
   // Traverse all our nsCOMArrays.
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mStyleSheets)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mCatalogSheets)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mPreloadingImages)
 
   for (PRUint32 i = 0; i < tmp->mAnimationFrameListeners.Length(); ++i) {
@@ -1922,16 +1925,17 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(ns
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mXPathEvaluatorTearoff)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCachedRootElement)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDisplayDocument)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mFirstBaseNodeWithHref)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDOMImplementation)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mImageMaps)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOriginalDocument)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCachedEncoder)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mFullScreenElement)
 
   tmp->mParentDocument = nsnull;
 
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMARRAY(mPreloadingImages)
 
   
   if (tmp->mBoxObjectTable) {
    tmp->mBoxObjectTable->EnumerateRead(ClearAllBoxObjects, nsnull);
@@ -5870,16 +5874,22 @@ nsDocument::SetUserData(const nsAString 
 NS_IMETHODIMP
 nsDocument::GetUserData(const nsAString & key,
                         nsIVariant **aResult)
 {
   return nsINode::GetUserData(key, aResult);
 }
 
 NS_IMETHODIMP
+nsDocument::Contains(nsIDOMNode* aOther, PRBool* aReturn)
+{
+  return nsINode::Contains(aOther, aReturn);
+}
+
+NS_IMETHODIMP
 nsDocument::GetInputEncoding(nsAString& aInputEncoding)
 {
   if (mHaveInputEncoding) {
     return GetCharacterSet(aInputEncoding);
   }
 
   SetDOMStringToNull(aInputEncoding);
   return NS_OK;
@@ -8454,16 +8464,231 @@ nsIDocument::SizeOf() const
   for (nsIContent* node = GetFirstChild(); node;
        node = node->GetNextNode(this)) {
     size += node->SizeOf();
   }
 
   return size;
 }
 
+// Returns the root document in a document hierarchy.
+static nsIDocument*
+GetRootDocument(nsIDocument* aDoc)
+{
+  if (!aDoc) {
+    return nsnull;
+  }
+  nsCOMPtr<nsIPresShell> shell = aDoc->GetShell();
+  if (!shell) {
+    return nsnull;
+  }
+  nsPresContext* ctx = shell->GetPresContext();
+  if (!ctx) {
+    return nsnull;
+  }
+  nsRootPresContext* rpc = ctx->GetRootPresContext();
+  if (!rpc) {
+    return nsnull;
+  }
+  return rpc->Document();
+}
+
+class nsDispatchFullScreenChange : public nsRunnable
+{
+public:
+  nsDispatchFullScreenChange(nsIDocument *aDoc)
+    : mDoc(aDoc)
+  {
+    mTarget = aDoc->GetFullScreenElement();
+    if (!mTarget) {
+      mTarget = aDoc;
+    }
+  }
+
+  NS_IMETHOD Run()
+  {
+    nsContentUtils::DispatchTrustedEvent(mDoc,
+                                         mTarget,
+                                         NS_LITERAL_STRING("mozfullscreenchange"),
+                                         PR_TRUE,
+                                         PR_FALSE);
+    return NS_OK;
+  }
+
+  nsCOMPtr<nsIDocument> mDoc;
+  nsCOMPtr<nsISupports> mTarget;
+};
+
+void
+nsDocument::UpdateFullScreenStatus(PRBool aIsFullScreen)
+{
+  if (mIsFullScreen != aIsFullScreen) {
+    nsCOMPtr<nsIRunnable> event(new nsDispatchFullScreenChange(this));
+    NS_DispatchToCurrentThread(event);
+  }
+  mIsFullScreen = aIsFullScreen;
+  if (!mIsFullScreen) {
+    // Full-screen is being turned off. Reset the full-screen element, to
+    // save us from having to traverse the document hierarchy again in
+    // MozCancelFullScreen().
+    ResetFullScreenElement();
+  }
+}
+
+static PRBool
+UpdateFullScreenStatus(nsIDocument* aDocument, void* aData)
+{
+  aDocument->UpdateFullScreenStatus(*static_cast<PRBool*>(aData));
+  aDocument->EnumerateSubDocuments(UpdateFullScreenStatus, aData);
+  return PR_TRUE;
+}
+
+static void
+UpdateFullScreenStatusInDocTree(nsIDocument* aDoc, PRBool aIsFullScreen)
+{
+  nsIDocument* root = GetRootDocument(aDoc);
+  if (root) {
+    UpdateFullScreenStatus(root, static_cast<void*>(&aIsFullScreen));
+  }
+}
+
+void
+nsDocument::ResetFullScreenElement()
+{
+  if (mFullScreenElement) {
+    nsEventStateManager::SetFullScreenState(mFullScreenElement, PR_FALSE);
+  }
+  mFullScreenElement = nsnull;
+}
+
+static PRBool
+ResetFullScreenElement(nsIDocument* aDocument, void* aData)
+{
+  aDocument->ResetFullScreenElement();
+  aDocument->EnumerateSubDocuments(ResetFullScreenElement, aData);
+  return PR_TRUE;
+}
+
+static void
+ResetFullScreenElementInDocTree(nsIDocument* aDoc)
+{
+  nsIDocument* root = GetRootDocument(aDoc);
+  if (root) {
+    ResetFullScreenElement(root, nsnull);
+  }
+}
+
+NS_IMETHODIMP
+nsDocument::MozCancelFullScreen()
+{
+  if (!nsContentUtils::IsRequestFullScreenAllowed()) {
+    return NS_OK;
+  }
+  CancelFullScreen();
+  return NS_OK;
+}
+
+void
+nsDocument::CancelFullScreen()
+{
+  if (!nsContentUtils::IsFullScreenApiEnabled() ||
+      !IsFullScreenDoc() ||
+      !GetWindow()) {
+    return;
+  }
+
+  // Disable full-screen mode in all documents in this hierarchy.
+  UpdateFullScreenStatusInDocTree(this, PR_FALSE);
+
+  // Move the window out of full-screen mode.
+  GetWindow()->SetFullScreen(PR_FALSE);
+
+  return;
+}
+
+PRBool
+nsDocument::IsFullScreenDoc()
+{
+  return nsContentUtils::IsFullScreenApiEnabled() && mIsFullScreen;
+}
+
+void
+nsDocument::RequestFullScreen(Element* aElement)
+{
+  if (!aElement || !nsContentUtils::IsFullScreenApiEnabled() || !GetWindow()) {
+    return;
+  }
+
+  // Reset the full-screen elements of every document in this document
+  // hierarchy.
+  ResetFullScreenElementInDocTree(this);
+  
+  if (aElement->IsInDoc()) {
+    // Propagate up the document hierarchy, setting the full-screen element as
+    // the element's container in ancestor documents. Note we don't propagate
+    // down the document hierarchy, the full-screen element (or its container)
+    // is not visible there.
+    mFullScreenElement = aElement;
+    // Set the full-screen state on the element, so the css-pseudo class
+    // applies to the element.
+    nsEventStateManager::SetFullScreenState(mFullScreenElement, PR_TRUE);
+    nsIDocument* child = this;
+    nsIDocument* parent;
+    while (parent = child->GetParentDocument()) {
+      nsIContent* content = parent->FindContentForSubDocument(child);
+      nsCOMPtr<Element> element(do_QueryInterface(content));
+      // Containing frames also need the css-pseudo class applied.
+      nsEventStateManager::SetFullScreenState(element, PR_TRUE);
+      static_cast<nsDocument*>(parent)->mFullScreenElement = element;
+      child = parent;
+    }
+  }
+
+  // Set all documents in hierarchy to full-screen mode.
+  UpdateFullScreenStatusInDocTree(this, PR_TRUE);
+
+  // Make the window full-screen. Note we must make the state changes above
+  // before making the window full-screen, as then the document reports as
+  // being in full-screen mode when the Chrome "fullscreen" event fires,
+  // enabling browser.js to distinguish between browser and dom full-screen
+  // modes.
+  GetWindow()->SetFullScreen(PR_TRUE);
+}
+
+NS_IMETHODIMP
+nsDocument::GetMozFullScreenElement(nsIDOMHTMLElement **aFullScreenElement)
+{
+  NS_ENSURE_ARG_POINTER(aFullScreenElement);
+  if (!nsContentUtils::IsFullScreenApiEnabled() || !IsFullScreenDoc()) {
+    *aFullScreenElement = nsnull;
+    return NS_OK;
+  }
+  nsCOMPtr<nsIDOMHTMLElement> e(do_QueryInterface(GetFullScreenElement()));
+  NS_IF_ADDREF(*aFullScreenElement = e);
+  return NS_OK;
+}
+
+Element*
+nsDocument::GetFullScreenElement()
+{
+  if (!nsContentUtils::IsFullScreenApiEnabled() ||
+      (mFullScreenElement && !mFullScreenElement->IsInDoc())) {
+    return nsnull;
+  }
+  return mFullScreenElement;
+}
+
+NS_IMETHODIMP
+nsDocument::GetMozFullScreen(PRBool *aFullScreen)
+{
+  NS_ENSURE_ARG_POINTER(aFullScreen);
+  *aFullScreen = nsContentUtils::IsFullScreenApiEnabled() && IsFullScreenDoc();
+  return NS_OK;
+}
+
 PRInt64
 nsDocument::SizeOf() const
 {
   PRInt64 size = MemoryReporter::GetBasicSize<nsDocument, nsIDocument>(this);
   size += mAttrStyleSheet ? mAttrStyleSheet->DOMSizeOf() : 0;
   return size;
 }
 
--- a/content/base/src/nsDocument.h
+++ b/content/base/src/nsDocument.h
@@ -936,16 +936,23 @@ public:
 
   virtual nsresult GetStateObject(nsIVariant** aResult);
 
   virtual nsDOMNavigationTiming* GetNavigationTiming() const;
   virtual nsresult SetNavigationTiming(nsDOMNavigationTiming* aTiming);
 
   virtual Element* FindImageMap(const nsAString& aNormalizedMapName);
 
+  virtual void ResetFullScreenElement();
+  virtual Element* GetFullScreenElement();
+  virtual void RequestFullScreen(Element* aElement);
+  virtual void CancelFullScreen();
+  virtual void UpdateFullScreenStatus(PRBool aIsFullScreen);
+  virtual PRBool IsFullScreenDoc();
+
 protected:
   friend class nsNodeUtils;
 
   /**
    * Check that aId is not empty and log a message to the console
    * service if it is.
    * @returns PR_TRUE if aId looks correct, PR_FALSE otherwise.
    */
@@ -1073,16 +1080,19 @@ protected:
    */
   nsTHashtable<nsIdentifierMapEntry> mIdentifierMap;
 
   nsClassHashtable<nsStringHashKey, nsRadioGroupStruct> mRadioGroups;
 
   // Recorded time of change to 'loading' state.
   mozilla::TimeStamp mLoadingTimeStamp;
 
+  // The current full-screen element of this document.
+  nsCOMPtr<Element> mFullScreenElement;
+
   // True if the document has been detached from its content viewer.
   PRPackedBool mIsGoingAway:1;
   // True if the document is being destroyed.
   PRPackedBool mInDestructor:1;
 
   // True if this document has ever had an HTML or SVG <title> element
   // bound to it
   PRPackedBool mMayHaveTitleElement:1;
@@ -1105,16 +1115,19 @@ protected:
   PRPackedBool mLoadedAsInteractiveData:1;
 
   // Whether we're currently holding a lock on all of our images.
   PRPackedBool mLockingImages:1;
 
   // Whether we currently require our images to animate
   PRPackedBool mAnimatingImages:1;
 
+  // Whether we are currently in full-screen mode, as per the DOM API.
+  PRPackedBool mIsFullScreen:1;
+
   PRUint8 mXMLDeclarationBits;
 
   PRUint8 mDefaultElementType;
 
   nsInterfaceHashtable<nsVoidPtrHashKey, nsPIBoxObject> *mBoxObjectTable;
 
   // The channel that got passed to StartDocumentLoad(), if any
   nsCOMPtr<nsIChannel> mChannel;
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -5525,8 +5525,49 @@ nsGenericElement::SizeOf() const
       return NS_OK;                                                          \
     }                                                                        \
     return elm->SetJSEventListenerToJsval(nsGkAtoms::on##name_, cx, obj, v); \
 }
 #define TOUCH_EVENT EVENT
 #include "nsEventNameList.h"
 #undef TOUCH_EVENT
 #undef EVENT
+
+PRBool
+nsINode::Contains(const nsINode* aOther) const
+{
+  if (!aOther ||
+      aOther == this ||
+      GetOwnerDoc() != aOther->GetOwnerDoc() ||
+      IsInDoc() != aOther->IsInDoc() ||
+      !(aOther->IsElement() ||
+        aOther->IsNodeOfType(nsINode::eCONTENT)) ||
+      !GetFirstChild()) {
+    return PR_FALSE;
+  }
+
+  const nsIContent* other = static_cast<const nsIContent*>(aOther);
+  if (this == GetOwnerDoc()) {
+    // document.contains(aOther) returns true if aOther is in the document,
+    // but is not in any anonymous subtree.
+    // IsInDoc() check is done already before this.
+    return !other->IsInAnonymousSubtree();
+  }
+
+  if (!IsElement() && !IsNodeOfType(nsINode::eDOCUMENT_FRAGMENT)) {
+    return PR_FALSE;
+  }
+
+  const nsIContent* thisContent = static_cast<const nsIContent*>(this);
+  if (thisContent->GetBindingParent() != other->GetBindingParent()) {
+    return PR_FALSE;
+  }
+
+  return nsContentUtils::ContentIsDescendantOf(other, this);
+}
+
+nsresult
+nsINode::Contains(nsIDOMNode* aOther, PRBool* aReturn)
+{
+  nsCOMPtr<nsINode> node = do_QueryInterface(aOther);
+  *aReturn = Contains(node);
+  return NS_OK;
+}
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -58,16 +58,17 @@
 #endif 
 
 //---------------------------------------------------------------------------
 // Generic atoms
 //---------------------------------------------------------------------------
 
 GK_ATOM(_empty, "")
 GK_ATOM(moz, "_moz")
+GK_ATOM(mozallowfullscreen, "mozallowfullscreen")
 GK_ATOM(moztype, "_moz-type")
 GK_ATOM(mozdirty, "_moz_dirty")
 GK_ATOM(mozdonotsend, "moz-do-not-send")
 GK_ATOM(mozeditorbogusnode, "_moz_editor_bogus_node")
 GK_ATOM(mozgeneratedcontentbefore, "_moz_generated_content_before")
 GK_ATOM(mozgeneratedcontentafter, "_moz_generated_content_after")
 GK_ATOM(mozgeneratedcontentimage, "_moz_generated_content_image")
 GK_ATOM(_moz_original_size, "_moz_original_size")
@@ -578,16 +579,17 @@ GK_ATOM(mode, "mode")
 GK_ATOM(modifiers, "modifiers")
 GK_ATOM(monochrome, "monochrome")
 GK_ATOM(mousedown, "mousedown")
 GK_ATOM(mousemove, "mousemove")
 GK_ATOM(mouseout, "mouseout")
 GK_ATOM(mouseover, "mouseover")
 GK_ATOM(mousethrough, "mousethrough")
 GK_ATOM(mouseup, "mouseup")
+GK_ATOM(mozfullscreenchange, "mozfullscreenchange")
 GK_ATOM(moz_opaque, "moz-opaque")
 GK_ATOM(moz_action_hint, "mozactionhint")
 GK_ATOM(x_moz_errormessage, "x-moz-errormessage")
 GK_ATOM(msthemecompatible, "msthemecompatible")
 GK_ATOM(multicol, "multicol")
 GK_ATOM(multiple, "multiple")
 GK_ATOM(name, "name")
 GK_ATOM(_namespace, "namespace")
@@ -690,16 +692,17 @@ GK_ATOM(onmessage, "onmessage")
 GK_ATOM(onmousedown, "onmousedown")
 GK_ATOM(onmousemove, "onmousemove")
 GK_ATOM(onmouseout, "onmouseout")
 GK_ATOM(onmouseover, "onmouseover")
 GK_ATOM(onMozMouseHittest, "onMozMouseHittest")
 GK_ATOM(onmouseup, "onmouseup")
 GK_ATOM(onMozAfterPaint, "onMozAfterPaint")
 GK_ATOM(onMozBeforePaint, "onMozBeforePaint")
+GK_ATOM(onmozfullscreenchange, "onmozfullscreenchange")
 GK_ATOM(onMozMousePixelScroll, "onMozMousePixelScroll")
 GK_ATOM(onMozScrolledAreaChanged, "onMozScrolledAreaChanged")
 GK_ATOM(ononline, "ononline")
 GK_ATOM(onoffline, "onoffline")
 GK_ATOM(onopen, "onopen")
 GK_ATOM(onoverflow, "onoverflow")
 GK_ATOM(onoverflowchanged, "onoverflowchanged")
 GK_ATOM(onpagehide, "onpagehide")
--- a/content/base/test/chrome/Makefile.in
+++ b/content/base/test/chrome/Makefile.in
@@ -64,15 +64,16 @@ include $(topsrcdir)/config/rules.mk
     file_bug616841.xul \
     test_bug635835.xul \
     test_fileconstructor.xul \
     fileconstructor_file.png \
     test_bug339494.xul \
     test_bug357450.xul \
     test_bug571390.xul \
     test_bug574596.html \
+    test_bug683852.xul \
     $(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
 
 libs:: $(_CHROME_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/chrome/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/content/base/test/chrome/test_bug683852.xul
@@ -0,0 +1,67 @@
+<?xml version="1.0"?>
+<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
+<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=683852
+-->
+<window title="Mozilla Bug 683852"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
+  <button value="testbutton" id="testbutton"/>
+  <!-- test results are displayed in the html:body -->
+  <body xmlns="http://www.w3.org/1999/xhtml">
+  <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=683852"
+     target="_blank" id="link">Mozilla Bug 683852</a>
+  </body>
+
+  <!-- test code goes here -->
+  <script type="application/javascript">
+  <![CDATA[
+  /** Test for Bug 683852 **/
+  SimpleTest.waitForExplicitFinish();
+
+  function startTest() {
+    is(document.contains(document), false, "Document should not contain itself!");
+
+    var tb = document.getElementById("testbutton");
+    is(document.contains(tb), true, "Document should contain element in it!");
+    var anon = document.getAnonymousElementByAttribute(tb, "anonid", "button-box");
+    is(document.contains(anon), false, "Document should not contain anonymous element in it!");
+    is(tb.contains(anon), false, "Element should not contain anonymous element in it!");
+    is(document.documentElement.contains(tb), true, "Element should contain element in it!");
+    is(document.contains(document.createElement("foo")), false, "Document shouldn't contain element which is't in the document");
+    is(document.contains(document.createTextNode("foo")), false, "Document shouldn't contain text node which is't in the document");
+
+    var link = document.getElementById("link");
+    is(document.contains(link.firstChild), true,
+       "Document should contain a text node in it.");
+    is(link.contains(link.firstChild), true,
+       "Element should contain a text node in it.");
+    is(link.firstChild.contains(link), false, "text node shouldn't contain its parent.");
+
+    is(document.contains(null), false, "Document shouldn't contain null.");
+
+    var pi = document.createProcessingInstruction("adf", "asd");
+    is(pi.contains(document), false, "Processing instruction shouldn't contain document");
+    document.documentElement.appendChild(pi);
+    document.contains(pi, true, "Document should contain processing instruction");
+
+    var df = document.createRange().createContextualFragment("<div>foo</div>");
+    is(df.contains(df.firstChild), true, "Document fragment should contain its child");
+    is(df.contains(df.firstChild.firstChild), true,
+       "Document fragment should contain its descendant");
+    is(df.contains(df), false, "Document fragment shouldn't contain itself.");
+
+    var d = document.implementation.createHTMLDocument("");
+    is(document.contains(d), false,
+       "Document shouldn't contain another document.");
+    is(document.contains(d.createElement("div")), false,
+       "Document shouldn't contain an element from another document.");
+
+    SimpleTest.finish();
+  }
+
+  addLoadEvent(startTest);
+  ]]>
+  </script>
+</window>
--- a/content/base/test/test_bug482935.html
+++ b/content/base/test/test_bug482935.html
@@ -33,61 +33,16 @@ function testCancelInPhase4() {
           // This request was cancelled, so the responseText should be empty string
           is(xhr.responseText, "", "Expected empty response to cancelled request");
 
           // Second request - should be found in cache
           var xhr2 = new XMLHttpRequest();
 
           xhr2.addEventListener("load", function() {
             is(xhr2.responseText, "0", "Received fresh value for second request");
-            testCancelBeforePhase4();
-          }, false);
-
-          xhr2.open("GET", url);
-          xhr2.setRequestHeader("X-Request", "1", false);
-
-          try { xhr2.send(); }
-          catch(e) {
-            is(xhr2.status, "200", "Exception!");
-          }
-        }, 0);
-      }, false);
-
-      xhr.abort();
-    }
-  }, false);
-
-  xhr.open("GET", url, true);
-  xhr.setRequestHeader("X-Request", "0", false);
-  try { xhr.send(); }
-  catch(e) {
-    is("Nothing", "Exception", "Boom: " + e);
-  }
-}
-
-// Tests that response is NOT cached if the request is cancelled
-// before it has reached state 4
-function testCancelBeforePhase4() {
-
-  clearCache();
-
-  // First request - should be loaded from server
-  var xhr = new XMLHttpRequest();
-  xhr.addEventListener("readystatechange", function(e) {
-    if (xhr.readyState == 3) {
-      xhr.addEventListener("abort", function() {
-        setTimeout(function() {
-          // This request was cancelled, so the responseText should be empty string
-          is(xhr.responseText, "", "Expected empty response to cancelled request");
-
-          // Second request - should be found in cache
-          var xhr2 = new XMLHttpRequest();
-
-          xhr2.addEventListener("load", function() {
-            is(xhr2.responseText, "1", "Received cached value for second request");
             SimpleTest.finish();
           }, false);
 
           xhr2.open("GET", url);
           xhr2.setRequestHeader("X-Request", "1", false);
 
           try { xhr2.send(); }
           catch(e) {
--- a/content/canvas/src/WebGLContext.cpp
+++ b/content/canvas/src/WebGLContext.cpp
@@ -1202,16 +1202,32 @@ DOMCI_DATA(WebGLExtension, WebGLExtensio
 
 NS_INTERFACE_MAP_BEGIN(WebGLExtension)
   NS_INTERFACE_MAP_ENTRY(WebGLExtension)
   NS_INTERFACE_MAP_ENTRY(nsIWebGLExtension)
   NS_INTERFACE_MAP_ENTRY(nsISupports)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(WebGLExtension)
 NS_INTERFACE_MAP_END
 
+/* readonly attribute WebGLsizei drawingBufferWidth; */
+NS_IMETHODIMP
+WebGLContext::GetDrawingBufferWidth(WebGLsizei *aWidth)
+{
+    *aWidth = mWidth;
+    return NS_OK;
+}
+
+/* readonly attribute WebGLsizei drawingBufferHeight; */
+NS_IMETHODIMP
+WebGLContext::GetDrawingBufferHeight(WebGLsizei *aHeight)
+{
+    *aHeight = mHeight;
+    return NS_OK;
+}
+
 /* [noscript] attribute WebGLint location; */
 NS_IMETHODIMP
 WebGLUniformLocation::GetLocation(WebGLint *aLocation)
 {
     return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 NS_IMETHODIMP
--- a/content/canvas/src/WebGLContext.h
+++ b/content/canvas/src/WebGLContext.h
@@ -423,16 +423,26 @@ protected:
     void BindFakeBlackTextures();
     void UnbindFakeBlackTextures();
 
     int WhatDoesVertexAttrib0Need();
     void DoFakeVertexAttrib0(WebGLuint vertexCount);
     void UndoFakeVertexAttrib0();
     void InvalidateFakeVertexAttrib0();
 
+    static CheckedUint32 GetImageSize(WebGLsizei height, 
+                                      WebGLsizei width, 
+                                      PRUint32 pixelSize,
+                                      PRUint32 alignment);
+
+    // Returns x rounded to the next highest multiple of y.
+    static CheckedUint32 RoundedToNextMultipleOf(CheckedUint32 x, CheckedUint32 y) {
+        return ((x + y - 1) / y) * y;
+    }
+
     nsCOMPtr<nsIDOMHTMLCanvasElement> mCanvasElement;
     nsHTMLCanvasElement *HTMLCanvasElement() {
         return static_cast<nsHTMLCanvasElement*>(mCanvasElement.get());
     }
 
     nsRefPtr<gl::GLContext> gl;
 
     PRInt32 mWidth, mHeight;
@@ -487,19 +497,17 @@ protected:
     PRBool ValidateFaceEnum(WebGLenum face, const char *info);
     PRBool ValidateBufferUsageEnum(WebGLenum target, const char *info);
     PRBool ValidateTexFormatAndType(WebGLenum format, WebGLenum type, int jsArrayType,
                                       PRUint32 *texelSize, const char *info);
     PRBool ValidateDrawModeEnum(WebGLenum mode, const char *info);
     PRBool ValidateAttribIndex(WebGLuint index, const char *info);
     PRBool ValidateStencilParamsForDrawCall();
     
-    bool ValidateGLSLVariableName(const nsAString& name, const char *info);
-    bool ValidateGLSLCharacter(PRUnichar c);
-    bool ValidateGLSLString(const nsAString& string, const char *info);
+    bool  ValidateGLSLIdentifier(const nsAString& name, const char *info);
 
     static PRUint32 GetTexelSize(WebGLenum format, WebGLenum type);
 
     void Invalidate();
     void DestroyResourcesAndContext();
 
     void MakeContextCurrent() { gl->MakeCurrent(); }
 
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -57,17 +57,16 @@
 #include "jstypedarray.h"
 
 #if defined(USE_ANGLE)
 // shader translator
 #include "angle/ShaderLang.h"
 #endif
 
 #include "WebGLTexelConversions.h"
-#include "WebGLValidateStrings.h"
 
 using namespace mozilla;
 
 static PRBool BaseTypeAndSizeFromUniformType(WebGLenum uType, WebGLenum *baseType, WebGLint *unitSize);
 static WebGLenum InternalFormatForFormatAndType(WebGLenum format, WebGLenum type, bool isGLES2);
 
 /* Helper macros for when we're just wrapping a gl method, so that
  * we can avoid having to type this 500 times.  Note that these MUST
@@ -178,36 +177,41 @@ WebGLContext::AttachShader(nsIWebGLProgr
 
 NS_IMETHODIMP
 WebGLContext::BindAttribLocation(nsIWebGLProgram *pobj, WebGLuint location, const nsAString& name)
 {
     WebGLuint progname;
     if (!GetGLName<WebGLProgram>("bindAttribLocation: program", pobj, &progname))
         return NS_OK;
 
-    if (!ValidateGLSLVariableName(name, "bindAttribLocation"))
-        return NS_OK;
+    if (name.IsEmpty())
+        return ErrorInvalidValue("BindAttribLocation: name can't be null or empty");
 
     if (!ValidateAttribIndex(location, "bindAttribLocation"))
         return NS_OK;
 
     MakeContextCurrent();
 
     gl->fBindAttribLocation(progname, location, NS_LossyConvertUTF16toASCII(name).get());
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::BindBuffer(WebGLenum target, nsIWebGLBuffer *bobj)
 {
     WebGLuint bufname;
     WebGLBuffer* buf;
-    PRBool isNull;
-    if (!GetConcreteObjectAndGLName("bindBuffer", bobj, &buf, &bufname, &isNull))
+    PRBool isNull; // allow null objects
+    PRBool isDeleted; // allow deleted objects
+    if (!GetConcreteObjectAndGLName("bindBuffer", bobj, &buf, &bufname, &isNull, &isDeleted))
+        return NS_OK;
+
+    // silently ignore a deleted buffer
+    if (isDeleted)
         return NS_OK;
 
     if (target != LOCAL_GL_ARRAY_BUFFER &&
         target != LOCAL_GL_ELEMENT_ARRAY_BUFFER)
     {
         return ErrorInvalidEnumInfo("bindBuffer: target", target);
     }
 
@@ -232,23 +236,28 @@ WebGLContext::BindBuffer(WebGLenum targe
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::BindFramebuffer(WebGLenum target, nsIWebGLFramebuffer *fbobj)
 {
     WebGLuint framebuffername;
-    PRBool isNull;
+    PRBool isNull; // allow null objects
+    PRBool isDeleted; // allow deleted objects
     WebGLFramebuffer *wfb;
 
     if (target != LOCAL_GL_FRAMEBUFFER)
         return ErrorInvalidEnum("BindFramebuffer: target must be GL_FRAMEBUFFER");
 
-    if (!GetConcreteObjectAndGLName("bindFramebuffer", fbobj, &wfb, &framebuffername, &isNull))
+    if (!GetConcreteObjectAndGLName("bindFramebuffer", fbobj, &wfb, &framebuffername, &isNull, &isDeleted))
+        return NS_OK;
+
+    // silently ignore a deleted frame buffer
+    if (isDeleted)
         return NS_OK;
 
     MakeContextCurrent();
 
     if (isNull) {
         gl->fBindFramebuffer(target, gl->GetOffscreenFBO());
     } else {
         gl->fBindFramebuffer(target, framebuffername);
@@ -259,23 +268,28 @@ WebGLContext::BindFramebuffer(WebGLenum 
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::BindRenderbuffer(WebGLenum target, nsIWebGLRenderbuffer *rbobj)
 {
     WebGLuint renderbuffername;
-    PRBool isNull;
+    PRBool isNull; // allow null objects
+    PRBool isDeleted; // allow deleted objects
     WebGLRenderbuffer *wrb;
 
     if (target != LOCAL_GL_RENDERBUFFER)
         return ErrorInvalidEnumInfo("bindRenderbuffer: target", target);
 
-    if (!GetConcreteObjectAndGLName("bindRenderBuffer", rbobj, &wrb, &renderbuffername, &isNull))
+    if (!GetConcreteObjectAndGLName("bindRenderBuffer", rbobj, &wrb, &renderbuffername, &isNull, &isDeleted))
+        return NS_OK;
+
+    // silently ignore a deleted buffer
+    if (isDeleted)
         return NS_OK;
 
     if (!isNull)
         wrb->SetHasEverBeenBound(PR_TRUE);
 
     MakeContextCurrent();
 
     gl->fBindRenderbuffer(target, renderbuffername);
@@ -285,18 +299,23 @@ WebGLContext::BindRenderbuffer(WebGLenum
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::BindTexture(WebGLenum target, nsIWebGLTexture *tobj)
 {
     WebGLuint texturename;
     WebGLTexture *tex;
-    PRBool isNull; // allow null object
-    if (!GetConcreteObjectAndGLName("bindTexture", tobj, &tex, &texturename, &isNull))
+    PRBool isNull; // allow null objects
+    PRBool isDeleted; // allow deleted objects
+    if (!GetConcreteObjectAndGLName("bindTexture", tobj, &tex, &texturename, &isNull, &isDeleted))
+        return NS_OK;
+
+    // silently ignore a deleted texture
+    if (isDeleted)
         return NS_OK;
 
     if (target == LOCAL_GL_TEXTURE_2D) {
         mBound2DTextures[mActiveTexture] = tex;
     } else if (target == LOCAL_GL_TEXTURE_CUBE_MAP) {
         mBoundCubeMapTextures[mActiveTexture] = tex;
     } else {
         return ErrorInvalidEnumInfo("bindTexture: target", target);
@@ -741,26 +760,18 @@ WebGLContext::CopyTexSubImage2D_base(Web
         /*** first, we initialize the texture as black ***/
 
         // first, compute the size of the buffer we should allocate to initialize the texture as black
 
         PRUint32 texelSize = 0;
         if (!ValidateTexFormatAndType(internalformat, LOCAL_GL_UNSIGNED_BYTE, -1, &texelSize, info))
             return NS_OK;
 
-        CheckedUint32 checked_plainRowSize = CheckedUint32(width) * texelSize;
-
-        PRUint32 unpackAlignment = mPixelStoreUnpackAlignment;
-
-        // alignedRowSize = row size rounded up to next multiple of packAlignment
-        CheckedUint32 checked_alignedRowSize
-            = ((checked_plainRowSize + unpackAlignment-1) / unpackAlignment) * unpackAlignment;
-
-        CheckedUint32 checked_neededByteLength
-            = (height-1) * checked_alignedRowSize + checked_plainRowSize;
+        CheckedUint32 checked_neededByteLength = 
+            GetImageSize(height, width, texelSize, mPixelStoreUnpackAlignment);
 
         if (!checked_neededByteLength.valid())
             return ErrorInvalidOperation("%s: integer overflow computing the needed buffer size", info);
 
         PRUint32 bytesNeeded = checked_neededByteLength.value();
 
         // now that the size is known, create the buffer
 
@@ -1058,16 +1069,19 @@ WebGLContext::DeleteFramebuffer(nsIWebGL
         return NS_OK;
 
     MakeContextCurrent();
 
     gl->fDeleteFramebuffers(1, &fbufname);
     fbuf->Delete();
     mMapFramebuffers.Remove(fbufname);
 
+    if (mBoundFramebuffer && mBoundFramebuffer->GLName() == fbufname)
+        mBoundFramebuffer = NULL;
+
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::DeleteRenderbuffer(nsIWebGLRenderbuffer *rbobj)
 {
     WebGLuint rbufname;
     WebGLRenderbuffer *rbuf;
@@ -1088,20 +1102,22 @@ WebGLContext::DeleteRenderbuffer(nsIWebG
             must be taken when deleting a renderbuffer object if the image of the renderbuffer
             is attached to a framebuffer object. In this case, if the deleted renderbuffer object is
             attached to the currently bound framebuffer object, it is 
             automatically detached.  However, attachments to any other framebuffer objects are the
             responsibility of the application.
     */
 
     gl->fDeleteRenderbuffers(1, &rbufname);
-
     rbuf->Delete();
     mMapRenderbuffers.Remove(rbufname);
 
+    if (mBoundRenderbuffer && mBoundRenderbuffer->GLName() == rbufname)
+        mBoundRenderbuffer = NULL;
+
     return NS_OK;
 }
 
 NS_IMETHODIMP
 WebGLContext::DeleteTexture(nsIWebGLTexture *tobj)
 {
     WebGLuint texname;
     WebGLTexture *tex;
@@ -1835,17 +1851,17 @@ WebGLContext::GetAttribLocation(nsIWebGL
                                 PRInt32 *retval)
 {
     *retval = 0;
 
     WebGLuint progname;
     if (!GetGLName<WebGLProgram>("getAttribLocation: program", pobj, &progname))
         return NS_OK;
 
-    if (!ValidateGLSLVariableName(name, "getAttribLocation"))
+    if (!ValidateGLSLIdentifier(name, "getAttribLocation"))
         return NS_OK; 
 
     MakeContextCurrent();
     *retval = gl->fGetAttribLocation(progname, NS_LossyConvertUTF16toASCII(name).get());
     return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -2192,20 +2208,16 @@ WebGLContext::GetFramebufferAttachmentPa
                 return ErrorInvalidEnumInfo("GetFramebufferAttachmentParameter: pname", pname);
         }
     } else {
         switch (pname) {
             case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
                 wrval->SetAsInt32(LOCAL_GL_NONE);
                 break;
 
-            case LOCAL_GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:
-                wrval->SetAsEmpty();
-                break;
-
             default:
                 return ErrorInvalidEnumInfo("GetFramebufferAttachmentParameter: pname", pname);
         }
     }
 
     *retval = wrval.forget().get();
 
     return NS_OK;
@@ -2335,24 +2347,18 @@ WebGLContext::GetProgramParameter(nsIWeb
         }
             break;
         case LOCAL_GL_DELETE_STATUS:
         case LOCAL_GL_LINK_STATUS:
         case LOCAL_GL_VALIDATE_STATUS:
         {
             GLint i = 0;
 #ifdef XP_MACOSX
-            if (pname == LOCAL_GL_VALIDATE_STATUS &&
-                gl->Vendor() == gl::GLContext::VendorNVIDIA)
-            {
-                // See comment in ValidateProgram below.
-                i = 1;
-            } else {
-                gl->fGetProgramiv(progname, pname, &i);
-            }
+            // See comment in ValidateProgram below.
+            i = 1;
 #else
             gl->fGetProgramiv(progname, pname, &i);
 #endif
             wrval->SetAsBool(PRBool(i));
         }
             break;
 
         default:
@@ -2660,17 +2666,17 @@ WebGLContext::GetUniformLocation(nsIWebG
 {
     *retval = nsnull;
 
     WebGLuint progname;
     WebGLProgram *prog;
     if (!GetConcreteObjectAndGLName("getUniformLocation: program", pobj, &prog, &progname))
         return NS_OK;
 
-    if (!ValidateGLSLVariableName(name, "getUniformLocation"))
+    if (!ValidateGLSLIdentifier(name, "getUniformLocation"))
         return NS_OK; 
 
     MakeContextCurrent();
 
     GLint intlocation = gl->fGetUniformLocation(progname, NS_LossyConvertUTF16toASCII(name).get());
 
     nsRefPtr<nsIWebGLUniformLocation> loc = prog->GetUniformLocationObject(intlocation);
     *retval = loc.forget().get();
@@ -2995,26 +3001,23 @@ WebGLContext::ReadPixels_base(WebGLint x
 
     if (badFormat && badType)
         return ErrorInvalidOperation("readPixels: bad format and type");
     if (badFormat)
         return ErrorInvalidEnumInfo("readPixels: format", format);
     if (badType)
         return ErrorInvalidEnumInfo("ReadPixels: type", type);
 
+    CheckedUint32 checked_neededByteLength =
+        GetImageSize(height, width, size, mPixelStorePackAlignment);
+
     CheckedUint32 checked_plainRowSize = CheckedUint32(width) * size;
 
-    PRUint32 packAlignment = mPixelStorePackAlignment;
-
-    // alignedRowSize = row size rounded up to next multiple of packAlignment
-    CheckedUint32 checked_alignedRowSize
-        = ((checked_plainRowSize + packAlignment-1) / packAlignment) * packAlignment;
-
-    CheckedUint32 checked_neededByteLength
-        = (height-1) * checked_alignedRowSize + checked_plainRowSize;
+    CheckedUint32 checked_alignedRowSize = 
+        RoundedToNextMultipleOf(checked_plainRowSize, mPixelStorePackAlignment);
 
     if (!checked_neededByteLength.valid())
         return ErrorInvalidOperation("ReadPixels: integer overflow computing the needed buffer size");
 
     if (checked_neededByteLength.value() > byteLength)
         return ErrorInvalidOperation("ReadPixels: buffer too small");
 
     MakeContextCurrent();
@@ -3065,18 +3068,19 @@ WebGLContext::ReadPixels_base(WebGLint x
             subrect_width > width || subrect_height > height)
             return ErrorInvalidOperation("ReadPixels: integer overflow computing clipped rect size");
 
         // now we know that subrect_width is in the [0..width] interval, and same for heights.
 
         // now, same computation as above to find the size of the intermediate buffer to allocate for the subrect
         // no need to check again for integer overflow here, since we already know the sizes aren't greater than before
         PRUint32 subrect_plainRowSize = subrect_width * size;
-        PRUint32 subrect_alignedRowSize = (subrect_plainRowSize + packAlignment-1) &
-            ~PRUint32(packAlignment-1);
+	// There are checks above to ensure that this doesn't overflow.
+        PRUint32 subrect_alignedRowSize = 
+            RoundedToNextMultipleOf(subrect_plainRowSize, mPixelStorePackAlignment).value();
         PRUint32 subrect_byteLength = (subrect_height-1)*subrect_alignedRowSize + subrect_plainRowSize;
 
         // create subrect buffer, call glReadPixels, copy pixels into destination buffer, delete subrect buffer
         GLubyte *subrect_data = new GLubyte[subrect_byteLength];
         gl->fReadPixels(subrect_x, subrect_y, subrect_width, subrect_height, format, type, subrect_data);
 
         // notice that this for loop terminates because we already checked that subrect_height is at most height
         for (GLint y_inside_subrect = 0; y_inside_subrect < subrect_height; ++y_inside_subrect) {
@@ -4128,20 +4132,17 @@ WebGLContext::GetShaderSource(nsIWebGLSh
 
 NS_IMETHODIMP
 WebGLContext::ShaderSource(nsIWebGLShader *sobj, const nsAString& source)
 {
     WebGLShader *shader;
     WebGLuint shadername;
     if (!GetConcreteObjectAndGLName("shaderSource: shader", sobj, &shader, &shadername))
         return NS_OK;
-
-    if (!ValidateGLSLString(source, "shaderSource"))
-        return NS_OK;
-
+    
     const nsPromiseFlatString& flatSource = PromiseFlatString(source);
 
     if (!NS_IsAscii(flatSource.get()))
         return ErrorInvalidValue("shaderSource: non-ascii characters found in source");
 
     const nsCString& sourceCString = NS_LossyConvertUTF16toASCII(flatSource);
     
     const PRUint32 maxSourceLength = (PRUint32(1)<<18) - 1;
@@ -4285,17 +4286,17 @@ WebGLContext::TexImage2D_base(WebGLenum 
         case LOCAL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
             if (width != height)
                 return ErrorInvalidValue("texImage2D: with cube map targets, width and height must be equal");
             break;
         default:
             return ErrorInvalidEnumInfo("texImage2D: target", target);
     }
 
-    switch (internalformat) {
+    switch (format) {
         case LOCAL_GL_RGB:
         case LOCAL_GL_RGBA:
         case LOCAL_GL_ALPHA:
         case LOCAL_GL_LUMINANCE:
         case LOCAL_GL_LUMINANCE_ALPHA:
             break;
         default:
             return ErrorInvalidEnumInfo("texImage2D: internal format", internalformat);
@@ -4326,26 +4327,23 @@ WebGLContext::TexImage2D_base(WebGLenum 
 
     if (border != 0)
         return ErrorInvalidValue("TexImage2D: border must be 0");
 
     PRUint32 texelSize = 0;
     if (!ValidateTexFormatAndType(format, type, jsArrayType, &texelSize, "texImage2D"))
         return NS_OK;
 
+    CheckedUint32 checked_neededByteLength = 
+        GetImageSize(height, width, texelSize, mPixelStoreUnpackAlignment); 
+
     CheckedUint32 checked_plainRowSize = CheckedUint32(width) * texelSize;
 
-    PRUint32 unpackAlignment = mPixelStoreUnpackAlignment;
-
-    // alignedRowSize = row size rounded up to next multiple of packAlignment
-    CheckedUint32 checked_alignedRowSize
-        = ((checked_plainRowSize + unpackAlignment-1) / unpackAlignment) * unpackAlignment;
-
-    CheckedUint32 checked_neededByteLength
-        = (height-1) * checked_alignedRowSize + checked_plainRowSize;
+    CheckedUint32 checked_alignedRowSize =
+        RoundedToNextMultipleOf(checked_plainRowSize.value(), mPixelStoreUnpackAlignment);
 
     if (!checked_neededByteLength.valid())
         return ErrorInvalidOperation("texImage2D: integer overflow computing the needed buffer size");
 
     PRUint32 bytesNeeded = checked_neededByteLength.value();
 
     if (byteLength && byteLength < bytesNeeded)
         return ErrorInvalidOperation("TexImage2D: not enough data for operation (need %d, have %d)",
@@ -4526,26 +4524,23 @@ WebGLContext::TexSubImage2D_base(WebGLen
 
     PRUint32 texelSize = 0;
     if (!ValidateTexFormatAndType(format, type, jsArrayType, &texelSize, "texSubImage2D"))
         return NS_OK;
 
     if (width == 0 || height == 0)
         return NS_OK; // ES 2.0 says it has no effect, we better return right now
 
+    CheckedUint32 checked_neededByteLength = 
+        GetImageSize(height, width, texelSize, mPixelStoreUnpackAlignment);
+
     CheckedUint32 checked_plainRowSize = CheckedUint32(width) * texelSize;
 
-    PRUint32 unpackAlignment = mPixelStoreUnpackAlignment;
-
-    // alignedRowSize = row size rounded up to next multiple of packAlignment
-    CheckedUint32 checked_alignedRowSize
-        = ((checked_plainRowSize + unpackAlignment-1) / unpackAlignment) * unpackAlignment;
-
-    CheckedUint32 checked_neededByteLength
-        = (height-1) * checked_alignedRowSize + checked_plainRowSize;
+    CheckedUint32 checked_alignedRowSize = 
+        RoundedToNextMultipleOf(checked_plainRowSize.value(), mPixelStoreUnpackAlignment);
 
     if (!checked_neededByteLength.valid())
         return ErrorInvalidOperation("texSubImage2D: integer overflow computing the needed buffer size");
 
     PRUint32 bytesNeeded = checked_neededByteLength.value();
  
     if (byteLength < bytesNeeded)
         return ErrorInvalidOperation("texSubImage2D: not enough data for operation (need %d, have %d)", bytesNeeded, byteLength);
@@ -4566,17 +4561,18 @@ WebGLContext::TexSubImage2D_base(WebGLen
 
     MakeContextCurrent();
 
     int dstFormat = GetWebGLTexelFormat(format, type);
     int actualSrcFormat = srcFormat == WebGLTexelFormat::Auto ? dstFormat : srcFormat;
     size_t srcStride = srcStrideOrZero ? srcStrideOrZero : checked_alignedRowSize.value();
 
     size_t dstPlainRowSize = texelSize * width;
-    size_t dstStride = ((dstPlainRowSize + unpackAlignment-1) / unpackAlignment) * unpackAlignment;
+    // There are checks above to ensure that this won't overflow.
+    size_t dstStride = RoundedToNextMultipleOf(dstPlainRowSize, mPixelStoreUnpackAlignment).value();
 
     if (actualSrcFormat == dstFormat &&
         srcPremultiplied == mPixelStorePremultiplyAlpha &&
         srcStride == dstStride &&
         !mPixelStoreFlipY)
     {
         // no conversion, no flipping, so we avoid copying anything and just pass the source pointer
         gl->fTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
--- a/content/canvas/src/WebGLContextUtils.cpp
+++ b/content/canvas/src/WebGLContextUtils.cpp
@@ -112,16 +112,34 @@ WebGLContext::LogMessageIfVerbose(const 
         LogMessage(fmt, ap);
     else if (firstTime)
         LogMessage("There are WebGL warnings or messages in this page, but they are hidden. To see them, "
                    "go to about:config, set the webgl.verbose preference, and reload this page.");
 
     firstTime = PR_FALSE;
 }
 
+CheckedUint32
+WebGLContext::GetImageSize(WebGLsizei height, 
+                           WebGLsizei width, 
+                           PRUint32 pixelSize,
+                           PRUint32 packOrUnpackAlignment)
+{
+    CheckedUint32 checked_plainRowSize = CheckedUint32(width) * pixelSize;
+
+    // alignedRowSize = row size rounded up to next multiple of packAlignment
+    CheckedUint32 checked_alignedRowSize = RoundedToNextMultipleOf(checked_plainRowSize, packOrUnpackAlignment);
+
+    // if height is 0, we don't need any memory to store this; without this check, we'll get an overflow
+    CheckedUint32 checked_neededByteLength
+        = height <= 0 ? 0 : (height-1) * checked_alignedRowSize + checked_plainRowSize;
+
+    return checked_neededByteLength;
+}
+
 nsresult
 WebGLContext::SynthesizeGLError(WebGLenum err)
 {
     // If there is already a pending error, don't overwrite it;
     // but if there isn't, then we need to check for a gl error
     // that may have occurred before this one and use that code
     // instead.
     
--- a/content/canvas/src/WebGLContextValidate.cpp
+++ b/content/canvas/src/WebGLContextValidate.cpp
@@ -323,41 +323,24 @@ PRBool WebGLContext::ValidateDrawModeEnu
         case LOCAL_GL_LINES:
             return PR_TRUE;
         default:
             ErrorInvalidEnumInfo(info, mode);
             return PR_FALSE;
     }
 }
 
-bool WebGLContext::ValidateGLSLVariableName(const nsAString& name, const char *info)
+bool WebGLContext::ValidateGLSLIdentifier(const nsAString& name, const char *info)
 {
-    const PRUint32 maxSize = 255;
+    const PRUint32 maxSize = 4095;
     if (name.Length() > maxSize) {
         ErrorInvalidValue("%s: identifier is %d characters long, exceeds the maximum allowed length of %d characters",
                           info, name.Length(), maxSize);
         return false;
     }
-
-    if (!ValidateGLSLString(name, info)) {
-        return false;
-    }
-
-    return true;
-}
-
-bool WebGLContext::ValidateGLSLString(const nsAString& string, const char *info)
-{
-    for (PRUint32 i = 0; i < string.Length(); ++i) {
-        if (!ValidateGLSLCharacter(string.CharAt(i))) {
-             ErrorInvalidValue("%s: string contains the illegal character '%d'", info, string.CharAt(i));
-             return false;
-        }
-    }
-
     return true;
 }
 
 PRUint32 WebGLContext::GetTexelSize(WebGLenum format, WebGLenum type)
 {
     if (type == LOCAL_GL_UNSIGNED_BYTE || type == LOCAL_GL_FLOAT) {
         int multiplier = type == LOCAL_GL_FLOAT ? 4 : 1;
         switch (format) {
deleted file mode 100644
--- a/content/canvas/src/WebGLValidateStrings.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2011 Mozilla Corporation. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WEBGLVALIDATESTRINGS_H_
-#define WEBGLVALIDATESTRINGS_H_
-
-#include "WebGLContext.h"
-
-namespace mozilla {
-
-// The following function was taken from the WebKit WebGL implementation,
-// which can be found here:
-// http://trac.webkit.org/browser/trunk/Source/WebCore/html/canvas/WebGLRenderingContext.cpp#L123
-/****** BEGIN CODE TAKEN FROM WEBKIT ******/
-bool WebGLContext::ValidateGLSLCharacter(PRUnichar c)
-{
-    // Printing characters are valid except " $ ` @ \ ' DEL.
-    if (c >= 32 && c <= 126 &&
-        c != '"' && c != '$' && c != '`' && c != '@' && c != '\\' && c != '\'')
-    {
-        return true;
-    }
-
-    // Horizontal tab, line feed, vertical tab, form feed, carriage return are also valid.
-    if (c >= 9 && c <= 13) {
-        return true;
-    }
-
-    return false;
-}
-/****** END CODE TAKEN FROM WEBKIT ******/
-
-} // end namespace mozilla
-
-#endif // WEBGLVALIDATESTRINGS_H_
--- a/content/canvas/test/webgl/failing_tests_linux.txt
+++ b/content/canvas/test/webgl/failing_tests_linux.txt
@@ -1,26 +1,23 @@
-conformance/buffer-offscreen-test.html
 conformance/drawingbuffer-static-canvas-test.html
 conformance/drawingbuffer-test.html
 conformance/framebuffer-object-attachment.html
 conformance/shaders/glsl-features/../../glsl-features.html?feature=abs-frag&reffs=shaders/glsl-features/abs-ref.frag&testfs=shaders/glsl-features/abs.frag
 conformance/shaders/glsl-features/../../glsl-features.html?feature=abs-vert-vec2&refvs=shaders/glsl-features/abs-vec2-ref.vert&testvs=shaders/glsl-features/abs-vec2.vert
 conformance/shaders/glsl-features/../../glsl-features.html?feature=abs-vert-vec3&refvs=shaders/glsl-features/abs-vec3-ref.vert&testvs=shaders/glsl-features/abs-vec3.vert
 conformance/shaders/glsl-features/../../glsl-features.html?feature=abs-vert-vec4&refvs=shaders/glsl-features/abs-vec4-ref.vert&testvs=shaders/glsl-features/abs-vec4.vert
 conformance/shaders/glsl-features/../../glsl-features.html?feature=sign-frag-vec4&reffs=shaders/glsl-features/sign-vec4-ref.frag&testfs=shaders/glsl-features/sign-vec4.frag
 conformance/shaders/glsl-features/../../glsl-features.html?feature=sign-vert-vec4&refvs=shaders/glsl-features/sign-vec4-ref.vert&testvs=shaders/glsl-features/sign-vec4.vert
 conformance/gl-get-active-attribute.html
 conformance/gl-getshadersource.html
 conformance/gl-uniform-bool.html
 conformance/glsl-conformance.html
 conformance/glsl-long-variable-names.html
-conformance/object-deletion-behaviour.html
+conformance/invalid-passed-params.html
 conformance/premultiplyalpha-test.html
 conformance/read-pixels-test.html
 conformance/uninitialized-test.html
-conformance/webgl-specific.html
 conformance/more/conformance/quickCheckAPI.html
 conformance/more/functions/copyTexImage2D.html
 conformance/more/functions/copyTexSubImage2D.html
 conformance/more/functions/deleteBufferBadArgs.html
-conformance/more/functions/texImage2DBadArgs.html
 conformance/more/functions/uniformfArrayLen1.html
--- a/content/canvas/test/webgl/failing_tests_mac.txt
+++ b/content/canvas/test/webgl/failing_tests_mac.txt
@@ -1,23 +1,20 @@
-conformance/buffer-offscreen-test.html
 conformance/context-attributes-alpha-depth-stencil-antialias.html
 conformance/drawingbuffer-static-canvas-test.html
 conformance/drawingbuffer-test.html
 conformance/framebuffer-object-attachment.html
 conformance/gl-getshadersource.html
 conformance/gl-object-get-calls.html
 conformance/glsl-conformance.html
 conformance/glsl-long-variable-names.html
-conformance/object-deletion-behaviour.html
+conformance/invalid-passed-params.html
 conformance/premultiplyalpha-test.html
 conformance/program-test.html
 conformance/read-pixels-test.html
 conformance/tex-input-validation.html
 conformance/texture-npot.html
-conformance/webgl-specific.html
 conformance/more/conformance/quickCheckAPI.html
 conformance/more/functions/copyTexImage2D.html
 conformance/more/functions/copyTexSubImage2D.html
 conformance/more/functions/deleteBufferBadArgs.html
-conformance/more/functions/texImage2DBadArgs.html
 conformance/more/functions/uniformfBadArgs.html
 conformance/more/functions/uniformiBadArgs.html
--- a/content/canvas/test/webgl/failing_tests_windows.txt
+++ b/content/canvas/test/webgl/failing_tests_windows.txt
@@ -1,17 +1,14 @@
-conformance/buffer-offscreen-test.html
 conformance/drawingbuffer-static-canvas-test.html
 conformance/drawingbuffer-test.html
 conformance/framebuffer-object-attachment.html
 conformance/gl-getshadersource.html
 conformance/glsl-conformance.html
 conformance/glsl-long-variable-names.html
-conformance/object-deletion-behaviour.html
+conformance/invalid-passed-params.html
 conformance/premultiplyalpha-test.html
 conformance/read-pixels-test.html
-conformance/webgl-specific.html
 conformance/more/conformance/quickCheckAPI.html
 conformance/more/functions/copyTexImage2D.html
 conformance/more/functions/copyTexSubImage2D.html
 conformance/more/functions/deleteBufferBadArgs.html
-conformance/more/functions/texImage2DBadArgs.html
 conformance/more/functions/uniformfArrayLen1.html
--- a/content/canvas/test/webgl/test_webgl_conformance_test_suite.html
+++ b/content/canvas/test/webgl/test_webgl_conformance_test_suite.html
@@ -387,41 +387,45 @@ function start() {
 
 </script>
 </head>
 <body onload="start()">
 <p id="display"></p>
 <div id="content" style="display: none">
 
 </div>
-<table border="2">
-<tr style="height: 300px;">
-<td>
-<table>
-<tr><td><h4>WebGL Conformance Test Runner</h4>
-<tr><td>
-  <div style="border: 1px">
-    <b>Status:</b> <div><span id="status"></span></div><br />
-    <b>Results:</b>
-    <div><span id="results-default"></span></div>
-    <br />
-    <div><span id="expectedtofail"></span></div>
-    <br />
-    <div><span id="ignoredtests"></span></div>
-  </div>
-</td></tr>
-</table>
-</td>
-<td>
-<iframe id="testframe" scrolling="yes" width="100%" height="100%"></iframe>
-</td>
-</tr>
-<tr>
-<td colspan="2">
-<div style="text-align: left; width: 100%; height: 100%; overflow: auto;">
-<div><ul id="results"></ul></div>
-</div>
-</td>
-</tr>
+<table border="2px">
+  <tr style="height: 500px;">
+    <td style="width: 500px;">
+      <iframe id="testframe" scrolling="no" width="500px" height="500px"></iframe>
+    </td>
+    <td>
+      <table>
+        <tr>
+          <td><h4>WebGL Conformance Test Runner</h4></td>
+        </tr>
+        <tr>
+          <td>
+            <div style="border: 1px">
+              <b>Status:</b> <div><span id="status"></span></div><br />
+              <b>Results:</b>
+              <div><span id="results-default"></span></div>
+              <br />
+              <div><span id="expectedtofail"></span></div>
+              <br />
+              <div><span id="ignoredtests"></span></div>
+            </div>
+          </td>
+        </tr>
+      </table>
+    </td>
+  </tr>
+  <tr>
+    <td colspan="2">
+      <div style="text-align: left; width: 100%; height: 100%; overflow: auto;">
+        <div><ul id="results"></ul></div>
+      </div>
+    </td>
+  </tr>
 </table>
 <canvas id="webglcheck-default" style="display: none;"></canvas>
 </body>
 </html>
--- a/content/events/public/nsEventNameList.h
+++ b/content/events/public/nsEventNameList.h
@@ -238,16 +238,20 @@ EVENT(mouseout,
 EVENT(mouseover,
       NS_MOUSE_ENTER_SYNTH,
       EventNameType_All,
       NS_MOUSE_EVENT)
 EVENT(mouseup,
       NS_MOUSE_BUTTON_UP,
       EventNameType_All,
       NS_MOUSE_EVENT)
+EVENT(mozfullscreenchange,
+      NS_FULLSCREENCHANGE,
+      EventNameType_HTML,
+      NS_EVENT_NULL)
 // Not supported yet; probably never because "wheel" is a better idea.
 // EVENT(mousewheel)
 EVENT(pause,
       NS_PAUSE,
       EventNameType_HTML,
       NS_EVENT_NULL)
 EVENT(play,
       NS_PLAY,
--- a/content/events/public/nsEventStates.h
+++ b/content/events/public/nsEventStates.h
@@ -256,21 +256,25 @@ private:
 // Content shows its placeholder
 #define NS_EVENT_STATE_MOZ_PLACEHOLDER NS_DEFINE_EVENT_STATE_MACRO(30)
 // Content is a submit control and the form isn't valid.
 #define NS_EVENT_STATE_MOZ_SUBMITINVALID NS_DEFINE_EVENT_STATE_MACRO(31)
 // UI friendly version of :invalid pseudo-class.
 #define NS_EVENT_STATE_MOZ_UI_INVALID NS_DEFINE_EVENT_STATE_MACRO(32)
 // UI friendly version of :valid pseudo-class.
 #define NS_EVENT_STATE_MOZ_UI_VALID NS_DEFINE_EVENT_STATE_MACRO(33)
+// Content is the full screen element, or a frame containing the
+// current full-screen element.
+#define NS_EVENT_STATE_FULL_SCREEN   NS_DEFINE_EVENT_STATE_MACRO(34)
 
 /**
  * NOTE: do not go over 63 without updating nsEventStates::InternalType!
  */
 
 #define ESM_MANAGED_STATES (NS_EVENT_STATE_ACTIVE | NS_EVENT_STATE_FOCUS |     \
                             NS_EVENT_STATE_HOVER | NS_EVENT_STATE_DRAGOVER |   \
-                            NS_EVENT_STATE_URLTARGET | NS_EVENT_STATE_FOCUSRING)
+                            NS_EVENT_STATE_URLTARGET | NS_EVENT_STATE_FOCUSRING | \
+                            NS_EVENT_STATE_FULL_SCREEN)
 
 #define INTRINSIC_STATES (~ESM_MANAGED_STATES)
 
 #endif // nsEventStates_h__
 
--- a/content/events/src/nsDOMEvent.cpp
+++ b/content/events/src/nsDOMEvent.cpp
@@ -87,16 +87,17 @@ static const char* const sEventNames[] =
   "loadstart", "progress", "suspend", "emptied", "stalled", "play", "pause",
   "loadedmetadata", "loadeddata", "waiting", "playing", "canplay",
   "canplaythrough", "seeking", "seeked", "timeupdate", "ended", "ratechange",
   "durationchange", "volumechange", "MozAudioAvailable",
 #endif // MOZ_MEDIA
   "MozAfterPaint",
   "MozBeforePaint",
   "MozBeforeResize",
+  "mozfullscreenchange",
   "MozSwipeGesture",
   "MozMagnifyGestureStart",
   "MozMagnifyGestureUpdate",
   "MozMagnifyGesture",
   "MozRotateGestureStart",
   "MozRotateGestureUpdate",
   "MozRotateGesture",
   "MozTapGesture",
@@ -1361,16 +1362,18 @@ const char* nsDOMEvent::GetEventName(PRU
   case NS_ANIMATION_END:
     return sEventNames[eDOMEvents_animationend];
   case NS_ANIMATION_ITERATION:
     return sEventNames[eDOMEvents_animationiteration];
   case NS_DEVICE_MOTION:
     return sEventNames[eDOMEvents_devicemotion];
   case NS_DEVICE_ORIENTATION:
     return sEventNames[eDOMEvents_deviceorientation];
+  case NS_FULLSCREENCHANGE:
+    return sEventNames[eDOMEvents_mozfullscreenchange];
   default:
     break;
   }
   // XXXldb We can hit this case for nsEvent objects that we didn't
   // create and that are not user defined events since this function and
   // SetEventType are incomplete.  (But fixing that requires fixing the
   // arrays in nsEventListenerManager too, since the events for which
   // this is a problem generally *are* created by nsDOMEvent.)
--- a/content/events/src/nsDOMEvent.h
+++ b/content/events/src/nsDOMEvent.h
@@ -172,16 +172,17 @@ public:
     eDOMEvents_ratechange,
     eDOMEvents_durationchange,
     eDOMEvents_volumechange,
     eDOMEvents_mozaudioavailable,
 #endif
     eDOMEvents_afterpaint,
     eDOMEvents_beforepaint,
     eDOMEvents_beforeresize,
+    eDOMEvents_mozfullscreenchange,
     eDOMEvents_MozSwipeGesture,
     eDOMEvents_MozMagnifyGestureStart,
     eDOMEvents_MozMagnifyGestureUpdate,
     eDOMEvents_MozMagnifyGesture,
     eDOMEvents_MozRotateGestureStart,
     eDOMEvents_MozRotateGestureUpdate,
     eDOMEvents_MozRotateGesture,
     eDOMEvents_MozTapGesture,
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -4380,16 +4380,24 @@ static nsIContent* FindCommonAncestor(ns
       }
       return anc1;
     }
   }
   return nsnull;
 }
 
 /* static */
+void
+nsEventStateManager::SetFullScreenState(Element* aElement,
+                                        PRBool aIsFullScreen)
+{
+  DoStateChange(aElement, NS_EVENT_STATE_FULL_SCREEN, aIsFullScreen);
+}
+
+/* static */
 inline void
 nsEventStateManager::DoStateChange(Element* aElement, nsEventStates aState,
                                    PRBool aAddState)
 {
   if (aAddState) {
     aElement->AddStates(aState);
   } else {
     aElement->RemoveStates(aState);
--- a/content/events/src/nsEventStateManager.h
+++ b/content/events/src/nsEventStateManager.h
@@ -198,16 +198,20 @@ public:
   static nsIDocument* sMouseOverDocument;
 
   static nsEventStateManager* GetActiveEventStateManager() { return sActiveESM; }
 
   // Sets aNewESM to be the active event state manager, and
   // if aContent is non-null, marks the object as active.
   static void SetActiveManager(nsEventStateManager* aNewESM,
                                nsIContent* aContent);
+
+  // Sets the full-screen event state on aElement to aIsFullScreen.
+  static void SetFullScreenState(mozilla::dom::Element* aElement, PRBool aIsFullScreen);
+
 protected:
   void UpdateCursor(nsPresContext* aPresContext, nsEvent* aEvent, nsIFrame* aTargetFrame, nsEventStatus* aStatus);
   /**
    * Turn a GUI mouse event into a mouse event targeted at the specified
    * content.  This returns the primary frame for the content (or null
    * if it goes away during the event).
    */
   nsIFrame* DispatchMouseEvent(nsGUIEvent* aEvent, PRUint32 aMessage,
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -3374,16 +3374,60 @@ nsGenericHTMLElement::Blur()
 nsresult
 nsGenericHTMLElement::Focus()
 {
   nsIFocusManager* fm = nsFocusManager::GetFocusManager();
   nsCOMPtr<nsIDOMElement> elem = do_QueryInterface(this);
   return fm ? fm->SetFocus(elem, 0) : NS_OK;
 }
 
+nsresult nsGenericHTMLElement::MozRequestFullScreen()
+{
+  // Only grant full-screen requests if this is called from inside a trusted
+  // event handler (i.e. inside an event handler for a user initiated event).
+  // This stops the full-screen from being abused similar to the popups of old,
+  // and it also makes it harder for bad guys' script to go full-screen and
+  // spoof the browser chrome/window and phish logins etc.
+  if (!nsContentUtils::IsFullScreenApiEnabled() ||
+      !nsContentUtils::IsRequestFullScreenAllowed()) {
+    return NS_OK;
+  }
+
+  // Ensure that all ancestor <iframe> elements have the mozallowfullscreen
+  // boolean attribute set.
+  nsINode* node = static_cast<nsINode*>(this);
+  do {
+    nsIContent* content = static_cast<nsIContent*>(node);
+    if (content->IsHTML(nsGkAtoms::iframe) &&
+        !content->HasAttr(kNameSpaceID_None, nsGkAtoms::mozallowfullscreen)) {
+      // The node requesting fullscreen, or one of its crossdoc ancestors,
+      // is an iframe which doesn't have the "mozalllowfullscreen" attribute.
+      // This request is not authorized by the parent document.
+      return NS_OK;
+    }
+    node = nsContentUtils::GetCrossDocParentNode(node);
+  } while (node);
+
+  nsIDocument* doc = GetOwnerDoc();
+  NS_ENSURE_STATE(doc);
+  doc->RequestFullScreen(this);
+#ifdef DEBUG
+  nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(doc->GetWindow());
+  NS_ENSURE_STATE(window);
+  PRBool fullscreen;
+  window->GetFullScreen(&fullscreen);
+  NS_ASSERTION(fullscreen, "Windows should report fullscreen");
+  nsCOMPtr<nsIDOMDocument> domDocument(do_QueryInterface(doc));
+  domDocument->GetMozFullScreen(&fullscreen);
+  NS_ASSERTION(fullscreen, "Document should report fullscreen");
+  NS_ASSERTION(doc->IsFullScreenDoc(), "Should be in full screen state!");
+#endif
+  return NS_OK;
+}
+
 nsresult nsGenericHTMLElement::Click()
 {
   if (HasFlag(NODE_HANDLING_CLICK))
     return NS_OK;
 
   // Strong in case the event kills it
   nsCOMPtr<nsIDocument> doc = GetCurrentDoc();
 
--- a/content/html/content/src/nsGenericHTMLElement.h
+++ b/content/html/content/src/nsGenericHTMLElement.h
@@ -134,16 +134,17 @@ public:
   nsresult GetOffsetWidth(PRInt32* aOffsetWidth);
   nsresult GetOffsetHeight(PRInt32* aOffsetHeight);
   nsresult GetOffsetParent(nsIDOMElement** aOffsetParent);
   virtual nsresult GetInnerHTML(nsAString& aInnerHTML);
   virtual nsresult SetInnerHTML(const nsAString& aInnerHTML);
   virtual nsresult InsertAdjacentHTML(const nsAString& aPosition,
                                       const nsAString& aText);
   nsresult ScrollIntoView(PRBool aTop, PRUint8 optional_argc);
+  nsresult MozRequestFullScreen();
   // Declare Focus(), Blur(), GetTabIndex(), SetTabIndex(), GetHidden(),
   // SetHidden(), GetSpellcheck(), SetSpellcheck(), and GetDraggable() such that
   // classes that inherit interfaces with those methods properly override them.
   NS_IMETHOD Focus();
   NS_IMETHOD Blur();
   NS_IMETHOD Click();
   NS_IMETHOD GetTabIndex(PRInt32 *aTabIndex);
   NS_IMETHOD SetTabIndex(PRInt32 aTabIndex);
--- a/content/html/content/src/nsHTMLIFrameElement.cpp
+++ b/content/html/content/src/nsHTMLIFrameElement.cpp
@@ -126,16 +126,17 @@ NS_IMPL_STRING_ATTR(nsHTMLIFrameElement,
 NS_IMPL_STRING_ATTR(nsHTMLIFrameElement, Height, height)
 NS_IMPL_URI_ATTR(nsHTMLIFrameElement, LongDesc, longdesc)
 NS_IMPL_STRING_ATTR(nsHTMLIFrameElement, MarginHeight, marginheight)
 NS_IMPL_STRING_ATTR(nsHTMLIFrameElement, MarginWidth, marginwidth)
 NS_IMPL_STRING_ATTR(nsHTMLIFrameElement, Name, name)
 NS_IMPL_STRING_ATTR(nsHTMLIFrameElement, Scrolling, scrolling)
 NS_IMPL_URI_ATTR(nsHTMLIFrameElement, Src, src)
 NS_IMPL_STRING_ATTR(nsHTMLIFrameElement, Width, width)
+NS_IMPL_BOOL_ATTR(nsHTMLIFrameElement, MozAllowFullScreen, mozallowfullscreen)
 
 NS_IMETHODIMP
 nsHTMLIFrameElement::GetContentDocument(nsIDOMDocument** aContentDocument)
 {
   return nsGenericHTMLFrameElement::GetContentDocument(aContentDocument);
 }
 
 NS_IMETHODIMP
--- a/content/html/content/src/nsHTMLInputElement.cpp
+++ b/content/html/content/src/nsHTMLInputElement.cpp
@@ -99,18 +99,16 @@
 #include "nsIRadioGroupContainer.h"
 
 // input type=file
 #include "nsILocalFile.h"
 #include "nsNetUtil.h"
 #include "nsDOMFile.h"
 #include "nsIFilePicker.h"
 #include "nsDirectoryServiceDefs.h"
-#include "nsIPrivateBrowsingService.h"
-#include "nsIContentURIGrouper.h"
 #include "nsIContentPrefService.h"
 #include "nsIObserverService.h"
 #include "nsIPopupWindowManager.h"
 #include "nsGlobalWindow.h"
 
 // input type=image
 #include "nsImageLoadingContent.h"
 
@@ -448,58 +446,30 @@ NS_IMPL_ISUPPORTS2(UploadLastDir, nsIObs
 void
 nsHTMLInputElement::InitUploadLastDir() {
   gUploadLastDir = new UploadLastDir();
   NS_ADDREF(gUploadLastDir);
 
   nsCOMPtr<nsIObserverService> observerService =
     mozilla::services::GetObserverService();
   if (observerService && gUploadLastDir) {
-    observerService->AddObserver(gUploadLastDir, NS_PRIVATE_BROWSING_SWITCH_TOPIC, PR_TRUE);
     observerService->AddObserver(gUploadLastDir, "browser:purge-session-history", PR_TRUE);
   }
 }
 
 void 
 nsHTMLInputElement::DestroyUploadLastDir() {
   NS_IF_RELEASE(gUploadLastDir);
 }
 
-UploadLastDir::UploadLastDir():
-  mInPrivateBrowsing(PR_FALSE)
-{
-  nsCOMPtr<nsIPrivateBrowsingService> pbService =
-    do_GetService(NS_PRIVATE_BROWSING_SERVICE_CONTRACTID);
-  if (pbService) {
-    pbService->GetPrivateBrowsingEnabled(&mInPrivateBrowsing);
-  }
-
-  mUploadLastDirStore.Init();
-}
-
 nsresult
 UploadLastDir::FetchLastUsedDirectory(nsIURI* aURI, nsILocalFile** aFile)
 {
   NS_PRECONDITION(aURI, "aURI is null");
   NS_PRECONDITION(aFile, "aFile is null");
-  // Retrieve the data from memory if it's present during private browsing mode,
-  // otherwise fall through to check the CPS
-  if (mInPrivateBrowsing) {
-    nsCOMPtr<nsIContentURIGrouper> hostnameGrouperService =
-      do_GetService(NS_HOSTNAME_GROUPER_SERVICE_CONTRACTID);
-    if (!hostnameGrouperService)
-      return NS_ERROR_NOT_AVAILABLE;
-    nsString group;
-    hostnameGrouperService->Group(aURI, group);
-
-    if (mUploadLastDirStore.Get(group, aFile)) {
-      return NS_OK;
-    }
-  }
-
   // Attempt to get the CPS, if it's not present we'll just return
   nsCOMPtr<nsIContentPrefService> contentPrefService =
     do_GetService(NS_CONTENT_PREF_SERVICE_CONTRACTID);
   if (!contentPrefService)
     return NS_ERROR_NOT_AVAILABLE;
   nsCOMPtr<nsIWritableVariant> uri = do_CreateInstance(NS_VARIANT_CONTRACTID);
   if (!uri)
     return NS_ERROR_OUT_OF_MEMORY;
@@ -531,28 +501,16 @@ UploadLastDir::StoreLastUsedDirectory(ns
   NS_PRECONDITION(aFile, "aFile is null");
   nsCOMPtr<nsIFile> parentFile;
   aFile->GetParent(getter_AddRefs(parentFile));
   if (!parentFile) {
     return NS_OK;
   }
   nsCOMPtr<nsILocalFile> localFile = do_QueryInterface(parentFile);
 
-  // Store the data in memory instead of the CPS during private browsing mode
-  if (mInPrivateBrowsing) {
-    nsCOMPtr<nsIContentURIGrouper> hostnameGrouperService =
-      do_GetService(NS_HOSTNAME_GROUPER_SERVICE_CONTRACTID);
-    if (!hostnameGrouperService)
-      return NS_ERROR_NOT_AVAILABLE;
-    nsString group;
-    hostnameGrouperService->Group(aURI, group);
-
-    return mUploadLastDirStore.Put(group, localFile);
-  }
-
   // Attempt to get the CPS, if it's not present we'll just return
   nsCOMPtr<nsIContentPrefService> contentPrefService =
     do_GetService(NS_CONTENT_PREF_SERVICE_CONTRACTID);
   if (!contentPrefService)
     return NS_ERROR_NOT_AVAILABLE;
   nsCOMPtr<nsIWritableVariant> uri = do_CreateInstance(NS_VARIANT_CONTRACTID);
   if (!uri)
     return NS_ERROR_OUT_OF_MEMORY;
@@ -568,29 +526,17 @@ UploadLastDir::StoreLastUsedDirectory(ns
     return NS_ERROR_OUT_OF_MEMORY;
   prefValue->SetAsAString(unicodePath);
   return contentPrefService->SetPref(uri, CPS_PREF_NAME, prefValue);
 }
 
 NS_IMETHODIMP
 UploadLastDir::Observe(nsISupports *aSubject, char const *aTopic, PRUnichar const *aData)
 {
-  if (strcmp(aTopic, NS_PRIVATE_BROWSING_SWITCH_TOPIC) == 0) {
-    if (NS_LITERAL_STRING(NS_PRIVATE_BROWSING_ENTER).Equals(aData)) {
-      mInPrivateBrowsing = PR_TRUE;
-    } else if (NS_LITERAL_STRING(NS_PRIVATE_BROWSING_LEAVE).Equals(aData)) {
-      mInPrivateBrowsing = PR_FALSE;
-      if (mUploadLastDirStore.IsInitialized()) {
-        mUploadLastDirStore.Clear();
-      }
-    }
-  } else if (strcmp(aTopic, "browser:purge-session-history") == 0) {
-    if (mUploadLastDirStore.IsInitialized()) {
-      mUploadLastDirStore.Clear();
-    }
+  if (strcmp(aTopic, "browser:purge-session-history") == 0) {
     nsCOMPtr<nsIContentPrefService> contentPrefService =
       do_GetService(NS_CONTENT_PREF_SERVICE_CONTRACTID);
     if (contentPrefService)
       contentPrefService->RemovePrefsByName(CPS_PREF_NAME);
   }
   return NS_OK;
 }
 
--- a/content/html/content/src/nsHTMLInputElement.h
+++ b/content/html/content/src/nsHTMLInputElement.h
@@ -80,18 +80,16 @@ class nsIRadioGroupContainer;
 class nsIRadioGroupVisitor;
 class nsIRadioVisitor;
 
 class UploadLastDir : public nsIObserver, public nsSupportsWeakReference {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIOBSERVER
 
-  UploadLastDir();
-
   /**
    * Fetch the last used directory for this location from the content
    * pref service, if it is available.
    *
    * @param aURI URI of the current page
    * @param aFile path to the last used directory
    */
   nsresult FetchLastUsedDirectory(nsIURI* aURI, nsILocalFile** aFile);
@@ -99,20 +97,16 @@ public:
   /**
    * Store the last used directory for this location using the
    * content pref service, if it is available
    * @param aURI URI of the current page
    * @param aFile file chosen by the user - the path to the parent of this
    *        file will be stored
    */
   nsresult StoreLastUsedDirectory(nsIURI* aURI, nsILocalFile* aFile);
-private:
-  // Directories are stored here during private browsing mode
-  nsInterfaceHashtable<nsStringHashKey, nsILocalFile> mUploadLastDirStore;
-  PRBool mInPrivateBrowsing;
 };
 
 class nsHTMLInputElement : public nsGenericHTMLFormElement,
                            public nsImageLoadingContent,
                            public nsIDOMHTMLInputElement,
                            public nsITextControlElement,
                            public nsIPhonetic,
                            public nsIDOMNSEditableElement,
--- a/content/html/content/test/Makefile.in
+++ b/content/html/content/test/Makefile.in
@@ -272,12 +272,15 @@ include $(topsrcdir)/config/rules.mk
 		test_bug666666.html \
 		test_bug674558.html \
 		test_bug583533.html \
 		test_restore_from_parser_fragment.html \
 		test_bug617528.html \
 		test_checked.html \
 		test_bug677658.html \
 		test_bug677463.html \
+		file_fullscreen-api.html \
+		file_fullscreen-api-keys.html \
+		test_fullscreen-api.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/file_fullscreen-api-keys.html
@@ -0,0 +1,250 @@
+ <!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=545812
+
+Test that restricted key pressed drop documents out of DOM full-screen mode.
+
+-->
+<head>
+  <title>Test for Bug 545812</title>
+  <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
+</head>
+<body onload="document.body.mozRequestFullScreen();">
+
+<script type="application/javascript">
+
+/** Test for Bug 545812 **/
+
+// List of key codes, and whether they're restricted in full-screen mode.
+var keyList = [
+  // Allowed: DOM_VK_CANCEL to DOM_VK_CAPS_LOCK, inclusive
+  { code: "VK_CANCEL",        allowed: true},
+  { code: "VK_HELP",          allowed: true},
+  { code: "VK_BACK_SPACE",    allowed: true},
+  { code: "VK_TAB",           allowed: true},
+  { code: "VK_CLEAR",         allowed: true},
+  { code: "VK_RETURN",        allowed: true},
+  { code: "VK_ENTER",         allowed: true},
+  { code: "VK_SHIFT",         allowed: true},
+  { code: "VK_CONTROL",       allowed: true},
+  { code: "VK_ALT",           allowed: true},
+  { code: "VK_PAUSE",         allowed: true},
+  { code: "VK_CAPS_LOCK",     allowed: true},
+
+  { code: "VK_KANA",          allowed: false},
+  { code: "VK_HANGUL",        allowed: false},
+  { code: "VK_JUNJA",         allowed: false},
+  { code: "VK_FINAL",         allowed: false},
+  { code: "VK_HANJA",         allowed: false},
+  { code: "VK_KANJI",         allowed: false},
+  { code: "VK_ESCAPE",        allowed: false},
+  { code: "VK_CONVERT",       allowed: false},
+  { code: "VK_NONCONVERT",    allowed: false},
+  { code: "VK_ACCEPT",        allowed: false},
+  { code: "VK_MODECHANGE",    allowed: false},
+
+  // Allowed: DOM_VK_SPACE to DOM_VK_DELETE, inclusive
+  { code: "VK_SPACE",         allowed: true},
+  { code: "VK_PAGE_UP",       allowed: true},
+  { code: "VK_PAGE_DOWN",     allowed: true},
+  { code: "VK_END",           allowed: true},
+  { code: "VK_HOME",          allowed: true},
+  { code: "VK_LEFT",          allowed: true},
+  { code: "VK_UP",            allowed: true},
+  { code: "VK_RIGHT",         allowed: true},
+  { code: "VK_DOWN",          allowed: true},
+  { code: "VK_SELECT",        allowed: true},
+  { code: "VK_PRINT",         allowed: true},
+  { code: "VK_EXECUTE",       allowed: true},
+  { code: "VK_PRINTSCREEN",   allowed: true},
+  { code: "VK_INSERT",        allowed: true},
+  { code: "VK_DELETE",        allowed: true},
+
+  { code: "VK_0",             allowed: false},
+  { code: "VK_1",             allowed: false},
+  { code: "VK_2",             allowed: false},
+  { code: "VK_3",             allowed: false},
+  { code: "VK_4",             allowed: false},
+  { code: "VK_5",             allowed: false},
+  { code: "VK_6",             allowed: false},
+  { code: "VK_7",             allowed: false},
+  { code: "VK_8",             allowed: false},
+  { code: "VK_9",             allowed: false},
+
+  // Allowed: DOM_VK_SPACE to DOM_VK_DELETE, inclusive
+  { code: "VK_SEMICOLON",     allowed: true},
+  { code: "VK_EQUALS",        allowed: true},
+
+  { code: "VK_A",             allowed: false},
+  { code: "VK_B",             allowed: false},
+  { code: "VK_C",             allowed: false},
+  { code: "VK_D",             allowed: false},
+  { code: "VK_E",             allowed: false},
+  { code: "VK_F",             allowed: false},
+  { code: "VK_G",             allowed: false},
+  { code: "VK_H",             allowed: false},
+  { code: "VK_I",             allowed: false},
+  { code: "VK_J",             allowed: false},
+  { code: "VK_K",             allowed: false},
+  { code: "VK_L",             allowed: false},
+  { code: "VK_M",             allowed: false},
+  { code: "VK_N",             allowed: false},
+  { code: "VK_O",             allowed: false},
+  { code: "VK_P",             allowed: false},
+  { code: "VK_Q",             allowed: false},
+  { code: "VK_R",             allowed: false},
+  { code: "VK_S",             allowed: false},
+  { code: "VK_T",             allowed: false},
+  { code: "VK_U",             allowed: false},
+  { code: "VK_V",             allowed: false},
+  { code: "VK_W",             allowed: false},
+  { code: "VK_X",             allowed: false},
+  { code: "VK_Y",             allowed: false},
+  { code: "VK_Z",             allowed: false},
+  { code: "VK_CONTEXT_MENU",  allowed: false},
+  { code: "VK_SLEEP",         allowed: false},
+  { code: "VK_NUMPAD0",       allowed: false},
+  { code: "VK_NUMPAD1",       allowed: false},
+  { code: "VK_NUMPAD2",       allowed: false},
+  { code: "VK_NUMPAD3",       allowed: false},
+  { code: "VK_NUMPAD4",       allowed: false},
+  { code: "VK_NUMPAD5",       allowed: false},
+  { code: "VK_NUMPAD6",       allowed: false},
+  { code: "VK_NUMPAD7",       allowed: false},
+  { code: "VK_NUMPAD8",       allowed: false},
+  { code: "VK_NUMPAD9",       allowed: false},
+
+  // Allowed: DOM_VK_MULTIPLY to DOM_VK_META, inclusive
+  { code: "VK_MULTIPLY",      allowed: true},
+  { code: "VK_ADD",           allowed: true},
+  { code: "VK_SEPARATOR",     allowed: true},
+  { code: "VK_SUBTRACT",      allowed: true},
+  { code: "VK_DECIMAL",       allowed: true},
+  { code: "VK_DIVIDE",        allowed: true},
+  { code: "VK_F1",            allowed: true},
+  { code: "VK_F2",            allowed: true},
+  { code: "VK_F3",            allowed: true},
+  { code: "VK_F4",            allowed: true},
+  { code: "VK_F5",            allowed: true},
+  { code: "VK_F6",            allowed: true},
+  { code: "VK_F7",            allowed: true},
+  { code: "VK_F8",            allowed: true},
+  { code: "VK_F9",            allowed: true},
+  { code: "VK_F10",           allowed: true},
+  { code: "VK_F11",           allowed: true},
+  { code: "VK_F12",           allowed: true},
+  { code: "VK_F13",           allowed: true},
+  { code: "VK_F14",           allowed: true},
+  { code: "VK_F15",           allowed: true},
+  { code: "VK_F16",           allowed: true},
+  { code: "VK_F17",           allowed: true},
+  { code: "VK_F18",           allowed: true},
+  { code: "VK_F19",           allowed: true},
+  { code: "VK_F20",           allowed: true},
+  { code: "VK_F21",           allowed: true},
+  { code: "VK_F22",           allowed: true},
+  { code: "VK_F23",           allowed: true},
+  { code: "VK_F24",           allowed: true},
+  { code: "VK_NUM_LOCK",      allowed: true},
+  { code: "VK_SCROLL_LOCK",   allowed: true},
+  { code: "VK_COMMA",         allowed: true},
+  { code: "VK_PERIOD",        allowed: true},
+  { code: "VK_SLASH",         allowed: true},
+  { code: "VK_BACK_QUOTE",    allowed: true},
+  { code: "VK_OPEN_BRACKET",  allowed: true},
+  { code: "VK_BACK_SLASH",    allowed: true},
+  { code: "VK_CLOSE_BRACKET", allowed: true},
+  { code: "VK_QUOTE",         allowed: true},
+  { code: "VK_META",          allowed: true},
+];
+
+function ok(condition, msg) {
+  opener.ok(condition, msg);
+}
+
+function is(a, b, msg) {
+  opener.is(a, b, msg);
+}
+
+var gKeyTestIndex = 0;
+var gKeyName;
+var gKeyCode;
+var gKeyAllowed;
+var gKeyReceived = false;
+
+function keyHandler(event) {
+  event.preventDefault()
+  gKeyReceived = true;
+}
+
+function checkKeyEffect() {
+  is(document.mozFullScreen, gKeyAllowed,
+     (gKeyAllowed ? ("Should remain in full-screen mode for allowed key press " + gKeyName)
+                  : ("Should drop out of full-screen mode for restricted key press " + gKeyName)));
+
+  if (gKeyTestIndex < keyList.length) {
+    setTimeout(testNextKey, 0);
+  } else {
+    opener.keysTestFinished();
+  }
+}
+
+function testTrustedKeyEvents() {
+  document.body.focus();
+  gKeyReceived = false;
+  synthesizeKey(gKeyName, {});
+  setTimeout(checkKeyEffect, 0);
+}
+
+function testScriptInitiatedKeyEvents() {
+  // Script initiated untrusted key events should not be blocked.
+  document.body.focus();
+  gKeyReceived = false;
+  var evt = document.createEvent("KeyEvents");
+  evt.initKeyEvent("keydown", true, true, window,
+                   false, false, false, false,
+                   gKeyCode, 0);
+  document.body.dispatchEvent(evt);
+
+  evt = document.createEvent("KeyEvents");
+  evt.initKeyEvent("keypress", true, true, window,
+                   false, false, false, false,
+                   gKeyCode, 0);
+  document.body.dispatchEvent(evt);
+
+  evt = document.createEvent("KeyEvents");
+  evt.initKeyEvent("keyup", true, true, window,
+                   false, false, false, false,
+                   gKeyCode, 0);
+  document.body.dispatchEvent(evt);
+  
+  ok(gKeyReceived, "dispatchEvent should dispatch events synchronously");
+  ok(document.mozFullScreen,
+     "Should remain in full-screen mode for script initiated key events for " + gKeyName);
+}
+
+function testNextKey() {
+  if (!document.mozFullScreen) {
+    document.body.mozRequestFullScreen();
+  }
+  ok(document.mozFullScreen, "Must be in full-screen mode");
+
+  gKeyName = keyList[gKeyTestIndex].code;
+  gKeyCode = KeyEvent["DOM_" + gKeyName];
+  gKeyAllowed = keyList[gKeyTestIndex].allowed;
+  gKeyTestIndex++;
+
+  testScriptInitiatedKeyEvents();
+  testTrustedKeyEvents();
+}
+
+window.addEventListener("keydown", keyHandler, true);
+window.addEventListener("keyup", keyHandler, true);
+window.addEventListener("keypress", keyHandler, true);
+setTimeout(testNextKey, 0);
+
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/file_fullscreen-api.html
@@ -0,0 +1,161 @@
+ <!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=545812
+
+Test DOM full-screen API.
+
+-->
+<head>
+  <title>Test for Bug 545812</title>
+  <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
+  <style>
+  body:-moz-full-screen, div:-moz-full-screen {
+    background-color: red;
+  }
+  </style>
+</head>
+<body onload="document.body.mozRequestFullScreen();">
+
+<script type="application/javascript">
+
+/** Test for Bug 545812 **/
+
+function ok(condition, msg) {
+  opener.ok(condition, msg);
+}
+
+function is(a, b, msg) {
+  opener.is(a, b, msg);
+}
+
+/*
+<html>
+  <body onload='document.body.mozRequestFullScreen();'>
+  </body>
+</html>
+*/
+var iframeContents = "data:text/html;charset=utf-8,<html>%0D%0A  <body onload%3D'document.body.mozRequestFullScreen()%3B'>%0D%0A  <%2Fbody>%0D%0A<%2Fhtml>";
+
+var iframe = null;
+var outOfDocElement = null;
+var inDocElement = null;
+var button = null;
+
+var fullScreenChangeCount = 0;
+
+function sendMouseClick(element) {
+  synthesizeMouseAtCenter(element, {});
+}
+
+function setRequireTrustedContext(value) {
+  opener.SpecialPowers.setBoolPref("full-screen-api.allow-trusted-requests-only", value);
+}
+
+function fullScreenChange(event) {
+  switch (fullScreenChangeCount) {
+    case 0: {
+      ok(document.mozFullScreen, "Should be in full-screen mode (first time)");
+      is(event.target, document.body, "Event target should be full-screen element");
+      is(document.mozFullScreenElement, document.body,
+         "Full-screen element should be body element.");
+      document.mozCancelFullScreen();
+      break;
+    }
+    case 1: {
+      ok(!document.mozFullScreen, "Should have left full-screen mode (first time)");
+      is(event.target, document.body, "Event target should be full-screen element");
+      is(document.mozFullScreenElement, null, "Full-screen element should be null.");
+      iframe = document.createElement("iframe");
+      iframe.mozAllowFullScreen = true;
+      document.body.appendChild(iframe);
+      iframe.src = iframeContents;
+      break;
+    }
+    case 2: {
+      ok(document.mozFullScreen, "Should be back in full-screen mode (second time)");
+      is(event.target, iframe,
+         "Event target should be full-screen element container");
+      is(document.mozFullScreenElement, iframe,
+        "Full-screen element should be iframe element.");
+      document.mozCancelFullScreen();
+      break;
+    }
+    case 3: {
+      ok(!document.mozFullScreen, "Should be back in non-full-screen mode (second time)");
+      is(event.target, iframe,
+         "Event target should be full-screen element container");
+      is(document.mozFullScreenElement, null, "Full-screen element should be null.");
+      document.body.removeChild(iframe);
+      iframe = null;
+      outOfDocElement = document.createElement("div");
+      outOfDocElement.mozRequestFullScreen();
+      break;
+    }
+    case 4: {
+      ok(document.mozFullScreen, "Should be back in full-screen mode (third time)");
+      is(event.target, document, "Event target should be document");
+      is(document.mozFullScreenElement, null,
+        "Should not have a full-screen element when element not in document requests full-screen.");
+       
+      // Set another element to be the full-screen element. It should immediately
+      // become the current full-screen element.
+      inDocElement = document.createElement("div");
+      document.body.appendChild(inDocElement);
+      inDocElement.mozRequestFullScreen();
+       
+      ok(document.mozFullScreen, "Should remain in full-screen mode (third and a half time)");
+      is(document.mozFullScreenElement, inDocElement,
+        "Full-screen element should be in doc again.");
+
+      // Remove full-screen element from document before exiting full screen.
+      document.body.removeChild(inDocElement);
+      ok(document.mozFullScreen,
+         "Should remain in full-screen mode after removing full-screen element from document");
+      is(document.mozFullScreenElement, null,
+        "Should not have a full-screen element again.");
+
+      document.mozCancelFullScreen();
+      break;
+    }
+    case 5: {
+      ok(!document.mozFullScreen, "Should be back in non-full-screen mode (third time)");
+      setRequireTrustedContext(true);
+      document.body.mozRequestFullScreen();
+      ok(!document.mozFullScreen, "Should still be in normal mode, because calling context isn't trusted.");
+
+      button = document.createElement("button");
+      button.onclick = function(){document.body.mozRequestFullScreen();}
+      document.body.appendChild(button);
+      sendMouseClick(button);
+      break;
+    }
+    case 6: {
+      ok(document.mozFullScreen, "Moved to full-screen after mouse click");
+      document.mozCancelFullScreen();
+      ok(document.mozFullScreen, "Should still be in full-screen mode, because calling context isn't trusted.");
+      setRequireTrustedContext(false);
+      document.mozCancelFullScreen();
+      ok(!document.mozFullScreen, "Should have left full-screen mode.");
+      break;
+    }
+    case 7: {
+      ok(!document.mozFullScreen, "Should have left full-screen mode (last time).");      
+      // Set timeout for calling finish(), so that any pending "mozfullscreenchange" events
+      // would have a chance to fire.
+      setTimeout(function(){opener.apiTestFinished();}, 0);
+      break;
+    }
+    default: {
+      ok(false, "Should not receive any more fullscreenchange events!");
+    }
+  }
+  fullScreenChangeCount++;
+}
+
+document.addEventListener("mozfullscreenchange", fullScreenChange, false);
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/html/content/test/test_bug430392.html
+++ b/content/html/content/test/test_bug430392.html
@@ -35,14 +35,13 @@ function test() {
   is(edit.innerHTML, html,
      "adding and then deleting returns should not change text");
 
   SimpleTest.finish();
 }
 
 SimpleTest.waitForExplicitFinish();
 addLoadEvent(test);
-addLoadEvent(SimpleTest.finish);
 
 </script>
 </pre>
 </body>
 </html>
--- a/content/html/content/test/test_bug618948.html
+++ b/content/html/content/test/test_bug618948.html
@@ -69,17 +69,17 @@ i.oninput = function(event) {
 i.onchange = function(event) {
   eventHandler(event);
   i.onchange = null;
   synthesizeMouseAtCenter(b, {});
 };
 
 i.oninvalid = function(event) {
   eventHandler(event);
-  i.oninvad = null;
+  i.oninvalid = null;
   endTest();
 };
 
 SimpleTest.waitForExplicitFinish();
 
 SimpleTest.waitForFocus(beginTest);
 
 </script>
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_fullscreen-api.html
@@ -0,0 +1,83 @@
+ <!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for Bug 545812</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/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=545812">Mozilla Bug 545812</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 545812 **/
+var testWindow = null;
+
+/*
+<html>
+  <body onload='document.body.mozRequestFullScreen();'>
+  </body>
+</html>
+*/
+var requestFullScreenContents = "data:text/html;charset=utf-8,<html>%0D%0A  <body onload%3D'document.body.mozRequestFullScreen()%3B'>%0D%0A  <%2Fbody>%0D%0A<%2Fhtml>";
+
+var prevTrusted = false;
+var prevEnabled = false;
+
+function run() {
+  document.addEventListener("mozfullscreenchange",
+    function(){ok(false, "Should never receive a mozfullscreenchange event in the main window.");},
+    false);
+
+  // Ensure the full-screen api is enabled, and will be disabled on test exit.
+  prevEnabled = SpecialPowers.getBoolPref("full-screen-api.enabled");
+  SpecialPowers.setBoolPref("full-screen-api.enabled", true);
+
+  prevTrusted = SpecialPowers.getBoolPref("full-screen-api.allow-trusted-requests-only");
+
+  // Request full-screen from a non trusted context (this script isn't a user
+  // generated event!). We should not receive a "mozfullscreenchange" event.
+  SpecialPowers.setBoolPref("full-screen-api.allow-trusted-requests-only", true);
+  document.body.mozRequestFullScreen();
+
+  // Disable the requirement for trusted contexts only, so the tests are easier
+  // to write.
+  SpecialPowers.setBoolPref("full-screen-api.allow-trusted-requests-only", false);
+
+  // Load an iframe whose contents requests full-screen. This request should
+  // fail, and we should never receive a "mozfullscreenchange" event, because the
+  // iframe doesn't have a mozallowfullscreen attribute.
+  var iframe = document.createElement("iframe");
+  iframe.src = requestFullScreenContents;
+  document.body.appendChild(iframe);
+ 
+  // Run the tests which go full-screen in a new window, as mochitests normally
+  // run in an iframe, which by default will not have the mozallowfullscreen
+  // attribute set, so full-screen won't work.
+  testWindow = window.open("file_fullscreen-api.html", "", "width=500,height=500");
+}
+
+function apiTestFinished() {
+  testWindow.close();
+  testWindow = window.open("file_fullscreen-api-keys.html", "", "width=500,height=500");
+}
+
+function keysTestFinished() {
+  testWindow.close();
+  SpecialPowers.setBoolPref("full-screen-api.enabled", prevEnabled);
+  SpecialPowers.setBoolPref("full-screen-api.allow-trusted-requests-only", prevTrusted);	
+  SimpleTest.finish();
+}
+
+addLoadEvent(run);
+SimpleTest.waitForExplicitFinish();
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/html/document/src/MediaDocument.cpp
+++ b/content/html/document/src/MediaDocument.cpp
@@ -257,16 +257,35 @@ MediaDocument::CreateSyntheticDocument()
   NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
 
   // Create a <head> so our title has somewhere to live
   nsRefPtr<nsGenericHTMLElement> head = NS_NewHTMLHeadElement(nodeInfo.forget());
   if (!head) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
+  nsCOMPtr<nsINodeInfo> nodeInfoMeta;
+  nodeInfoMeta = mNodeInfoManager->GetNodeInfo(nsGkAtoms::meta, nsnull,
+                                               kNameSpaceID_XHTML,
+                                               nsIDOMNode::ELEMENT_NODE);
+  NS_ENSURE_TRUE(nodeInfoMeta, NS_ERROR_OUT_OF_MEMORY);
+
+  nsRefPtr<nsGenericHTMLElement> metaContent = NS_NewHTMLMetaElement(nodeInfoMeta.forget());
+  if (!metaContent) {
+    return NS_ERROR_OUT_OF_MEMORY;
+  }
+  metaContent->SetAttr(kNameSpaceID_None, nsGkAtoms::name,
+                       NS_LITERAL_STRING("viewport"),
+                       PR_TRUE);
+
+  metaContent->SetAttr(kNameSpaceID_None, nsGkAtoms::content,
+                       NS_LITERAL_STRING("width=device-width; height=device-height;"),
+                       PR_TRUE);
+  head->AppendChildTo(metaContent, PR_FALSE);
+
   root->AppendChildTo(head, PR_FALSE);
 
   nodeInfo = mNodeInfoManager->GetNodeInfo(nsGkAtoms::body, nsnull,
                                            kNameSpaceID_XHTML,
                                            nsIDOMNode::ELEMENT_NODE);
   NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
 
   nsRefPtr<nsGenericHTMLElement> body = NS_NewHTMLBodyElement(nodeInfo.forget());
new file mode 100644
--- /dev/null
+++ b/content/smil/crashtests/678847-1.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg">
+<animate id="a" end="a.end+6s" />
+</svg>
new file mode 100644
--- /dev/null
+++ b/content/smil/crashtests/678938-1.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" class="reftest-wait">
+<script>
+  window.addEventListener("load", function() {
+    setTimeout(function() {
+      document.documentElement.setCurrentTime(0);
+      document.documentElement.removeAttribute("class");
+    }, 0);
+  }, false);
+</script>
+<set id="c"/><set id="b" begin="c.begin; b.begin"/>
+</svg>
--- a/content/smil/crashtests/crashtests.list
+++ b/content/smil/crashtests/crashtests.list
@@ -32,11 +32,13 @@ load 606101-1.svg
 load 608549-1.svg
 load 608295-1.html
 load 611927-1.svg
 load 615002-1.svg
 load 615872-1.svg
 load 650732-1.svg
 load 665334-1.svg
 load 669225-1.svg
+load 669225-2.svg
 load 670313-1.svg
-load 669225-2.svg
 load 678822-1.svg
+load 678847-1.svg
+load 678938-1.svg
--- a/content/smil/nsSMILAnimationFunction.cpp
+++ b/content/smil/nsSMILAnimationFunction.cpp
@@ -473,16 +473,31 @@ nsSMILAnimationFunction::InterpolateResu
   }
 
   // Discrete-CalcMode case
   // Note: If interpolation failed (isn't supported for this type), the SVG
   // spec says to force discrete mode.
   if (calcMode == CALC_DISCRETE || NS_FAILED(rv)) {
     double scaledSimpleProgress =
       ScaleSimpleProgress(simpleProgress, CALC_DISCRETE);
+
+    // Floating-point errors can mean that, for example, a sample time of 29s in
+    // a 100s duration animation gives us a simple progress of 0.28999999999
+    // instead of the 0.29 we'd expect. Normally this isn't a noticeable
+    // problem, but when we have sudden jumps in animation values (such as is
+    // the case here with discrete animation) we can get unexpected results.
+    //
+    // To counteract this, before we perform a floor() on the animation
+    // progress, we add a tiny fudge factor to push us into the correct interval
+    // in cases where floating-point errors might cause us to fall short.
+    static const double kFloatingPointFudgeFactor = 1.0e-16;
+    if (scaledSimpleProgress + kFloatingPointFudgeFactor <= 1.0) {
+      scaledSimpleProgress += kFloatingPointFudgeFactor;
+    }
+
     if (IsToAnimation()) {
       // We don't follow SMIL 3, 12.6.4, where discrete to animations
       // are the same as <set> animations.  Instead, we treat it as a
       // discrete animation with two values (the underlying value and
       // the to="" value), and honor keyTimes="" as well.
       PRUint32 index = (PRUint32)floor(scaledSimpleProgress * 2);
       aResult = index == 0 ? aBaseValue : aValues[0];
     } else {
--- a/content/smil/nsSMILTimedElement.cpp
+++ b/content/smil/nsSMILTimedElement.cpp
@@ -753,20 +753,20 @@ nsSMILTimedElement::Rewind()
     mSeekState = mElementState == STATE_ACTIVE ?
                  SEEK_BACKWARD_FROM_ACTIVE :
                  SEEK_BACKWARD_FROM_INACTIVE;
   }
   NS_ABORT_IF_FALSE(mSeekState == SEEK_BACKWARD_FROM_INACTIVE ||
                     mSeekState == SEEK_BACKWARD_FROM_ACTIVE,
                     "Rewind in the middle of a forwards seek?");
 
+  // Putting us in the startup state will ensure we skip doing any interval
+  // updates
+  mElementState = STATE_STARTUP;
   ClearIntervals();
-  // ClearIntervals puts us in to the POSTACTIVE state but we're doing a full
-  // rewind so go back to the startup state
-  mElementState = STATE_STARTUP;
 
   UnsetBeginSpec(RemoveNonDynamic);
   UnsetEndSpec(RemoveNonDynamic);
 
   if (mClient) {
     mClient->Inactivate(PR_FALSE);
   }
 
@@ -779,16 +779,18 @@ nsSMILTimedElement::Rewind()
   if (mAnimationElement->HasAnimAttr(nsGkAtoms::end)) {
     nsAutoString attValue;
     mAnimationElement->GetAnimAttr(nsGkAtoms::end, attValue);
     SetEndSpec(attValue, &mAnimationElement->AsElement(), RemoveNonDynamic);
   }
 
   mPrevRegisteredMilestone = sMaxMilestone;
   RegisterMilestone();
+  NS_ABORT_IF_FALSE(!mCurrentInterval,
+                    "Current interval is set at end of rewind");
 }
 
 namespace
 {
   PRBool
   RemoveNonDOM(nsSMILInstanceTime* aInstanceTime)
   {
     return !aInstanceTime->FromDOM() && !aInstanceTime->ShouldPreserve();
@@ -1327,17 +1329,19 @@ nsSMILTimedElement::ClearSpecs(TimeValue
   aSpecs.Clear();
   RemoveByFunction removeByFunction(aRemove);
   RemoveInstanceTimes(aInstances, removeByFunction);
 }
 
 void
 nsSMILTimedElement::ClearIntervals()
 {
-  mElementState = STATE_POSTACTIVE;
+  if (mElementState != STATE_STARTUP) {
+    mElementState = STATE_POSTACTIVE;
+  }
   mCurrentRepeatIteration = 0;
   ResetCurrentInterval();
 
   // Remove old intervals
   for (PRInt32 i = mOldIntervals.Length() - 1; i >= 0; --i) {
     mOldIntervals[i]->Unlink();
   }
   mOldIntervals.Clear();
@@ -1679,24 +1683,25 @@ nsSMILTimedElement::GetNextInterval(cons
           prevIntervalWasZeroDur) {
         tempEnd = GetNextGreater(mEndInstances, tempBegin->Time(), endPos);
       }
 
       // If all the ends are before the beginning we have a bad interval UNLESS:
       // a) We never had any end attribute to begin with (and hence we should
       //    just use the active duration after allowing for the possibility of
       //    an end instance provided by a DOM call), OR
-      // b) We have an end attribute but no end instances--this is a special
-      //    case that is needed for syncbase timing so that animations of the
-      //    following sort: <animate id="a" end="a.begin+1s" ... /> can be
-      //    resolved (see SVGT 1.2 Test Suite animate-elem-221-t.svg) by first
-      //    establishing an interval of unresolved duration, OR
+      // b) We have no resolved (not incl. indefinite) end instances
+      //    (SMIL only says "if the instance list is empty"--but if we have
+      //    indefinite/unresolved instance times then there must be a good
+      //    reason we haven't used them (since they'll be >= tempBegin) such as
+      //    avoiding creating a self-referential loop. In any case, the interval
+      //    should be allowed to be open.), OR
       // c) We have end events which leave the interval open-ended.
       PRBool openEndedIntervalOk = mEndSpecs.IsEmpty() ||
-                                   mEndInstances.IsEmpty() ||
+                                   !HaveResolvedEndTimes() ||
                                    EndHasEventConditions();
       if (!tempEnd && !openEndedIntervalOk)
         return PR_FALSE; // Bad interval
 
       nsSMILTimeValue intervalEnd = tempEnd
                                   ? tempEnd->Time() : nsSMILTimeValue();
       nsSMILTimeValue activeEnd = CalcActiveEnd(tempBegin->Time(), intervalEnd);
 
@@ -2244,16 +2249,27 @@ const nsSMILInterval*
 nsSMILTimedElement::GetPreviousInterval() const
 {
   return mOldIntervals.IsEmpty()
     ? nsnull
     : mOldIntervals[mOldIntervals.Length()-1].get();
 }
 
 PRBool
+nsSMILTimedElement::HaveResolvedEndTimes() const
+{
+  if (mEndInstances.IsEmpty())
+    return PR_FALSE;
+
+  // mEndInstances is sorted so if the first time is not resolved then none of
+  // them are
+  return mEndInstances[0]->Time().IsResolved();
+}
+
+PRBool
 nsSMILTimedElement::EndHasEventConditions() const
 {
   for (PRUint32 i = 0; i < mEndSpecs.Length(); ++i) {
     if (mEndSpecs[i]->IsEventBased())
       return PR_TRUE;
   }
   return PR_FALSE;
 }
--- a/content/smil/nsSMILTimedElement.h
+++ b/content/smil/nsSMILTimedElement.h
@@ -520,16 +520,17 @@ protected:
   void              NotifyChangedInterval(nsSMILInterval* aInterval,
                                           PRBool aBeginObjectChanged,
                                           PRBool aEndObjectChanged);
 
   void              FireTimeEventAsync(PRUint32 aMsg, PRInt32 aDetail);
   const nsSMILInstanceTime* GetEffectiveBeginInstance() const;
   const nsSMILInterval* GetPreviousInterval() const;
   PRBool            HasPlayed() const { return !mOldIntervals.IsEmpty(); }
+  PRBool            HaveResolvedEndTimes() const;
   PRBool            EndHasEventConditions() const;
 
   // Reset the current interval by first passing ownership to a temporary
   // variable so that if Unlink() results in us receiving a callback,
   // mCurrentInterval will be nsnull and we will be in a consistent state.
   void ResetCurrentInterval()
   {
     if (mCurrentInterval) {
--- a/content/svg/content/test/Makefile.in
+++ b/content/svg/content/test/Makefile.in
@@ -55,16 +55,17 @@ include $(topsrcdir)/config/rules.mk
 		a_href_helper_01.svg \
 		a_href_helper_02_03.svg \
 		a_href_helper_04.svg \
 		test_animLengthObjectIdentity.xhtml \
 		test_animLengthReadonly.xhtml \
 		test_animLengthUnits.xhtml \
 		test_bbox.xhtml \
 		test_bbox-with-invalid-viewBox.xhtml \
+		test_bounds.html \
 		bbox-helper.svg \
 		bounds-helper.svg \
 		test_dataTypes.html \
 		dataTypes-helper.svg \
 		getCTM-helper.svg \
 		test_getCTM.html \
 		test_getSubStringLength.xhtml \
 		getSubStringLength-helper.svg \
--- a/content/svg/content/test/bounds-helper.svg
+++ b/content/svg/content/test/bounds-helper.svg
@@ -2,29 +2,28 @@
 <svg xmlns="http://www.w3.org/2000/svg" width="750"
      xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
   <style type="text/css">
 text { font: 20px monospace; }
   </style>
 
 <g id="g">
   <text id="text1" x="25" y="25">abc</text>
+  <text id="text1a" x="85" y="25" stroke="black" stroke-width="4">abc</text>
   <rect id="rect1" x="50" y="50" width="50" height="50" fill="green"/>
-  <rect id="rect1a" x="50" y="50" width="50" height="50" fill="none" stroke-width="2" stroke="yellow"/>
+  <rect id="rect1a" x="50" y="50" width="50" height="50" fill="none" stroke-width="4" stroke="yellow"/>
   <text id="text2" x="125" y="25">abc</text>
+  <text id="text2a" x="185" y="25" stroke="black" stroke-width="10">abc</text>
   <g transform="rotate(45 175 75)">
     <rect id="rect2" x="150" y="50" width="50" height="50" fill="yellow"/>
-    <rect id="rect2a" x="150" y="50" width="50" height="50" fill="none" stroke-width="2" stroke="blue"/>
+    <rect id="rect2a" x="150" y="50" width="50" height="50" fill="none" stroke-width="4" stroke="blue"/>
     <text id="text3" x="150" y="50" text-anchor="middle">abc</text>
   </g>
   <g transform="scale(2)">
     <rect id="rect3" x="25" y="80" width="50" height="50" fill="green"/>
-    <rect id="rect3a" x="25" y="80" width="50" height="50" fill="none" stroke-width="2" stroke="blue"/>
+    <rect id="rect3a" x="25" y="80" width="50" height="50" fill="none" stroke-width="4" stroke="blue"/>
   </g>
   <g transform="scale(2) rotate(45 175 75)">
     <rect id="rect4" x="150" y="50" width="50" height="50" fill="yellow"/>
-    <rect id="rect4a" x="150" y="50" width="50" height="50" fill="none" stroke-width="2" stroke="blue"/>
-    <text id="text4" x="125" y="125">abc</text>
+    <rect id="rect4a" x="150" y="50" width="50" height="50" fill="none" stroke-width="4" stroke="blue"/>
   </g>
-  <text id="text1a" x="85" y="25" stroke="black" stroke-width="1">M</text>
-  <text id="text2a" x="185" y="25" stroke="black" stroke-width="10">M</text>
 </g>
 </svg>
--- a/content/svg/content/test/test_bounds.html
+++ b/content/svg/content/test/test_bounds.html
@@ -14,111 +14,130 @@ https://bugzilla.mozilla.org/show_bug.cg
 <div id="content" style="display: none"></div>
 
 <iframe id="svg" src="bounds-helper.svg"></iframe>
 
 <pre id="test">
 <script class="testbody" type="application/javascript">
 SimpleTest.waitForExplicitFinish();
 
+function Rect(left, top, width, height)
+{
+  this.left = left;
+  this.top = top;
+  this.width = width;
+  this.height = height;
+}
+
+Rect.prototype.roundOut = function()
+{
+  this.width = Math.ceil(this.left + this.width) - Math.floor(this.left);
+  this.height = Math.ceil(this.top + this.height) - Math.floor(this.top);
+  this.left = Math.floor(this.left);
+  this.top = Math.floor(this.top);
+}
+
+var delta = 1;
+
+function isApproximately(a, b, message)
+{
+  ok(delta >= Math.abs(a - b), message + " - got " + a + ", expected " + b + " ± " + delta);
+}
+
 function runTest()
 {
-  function isRounded(a, b, message) {
-    is (Math.round(a), Math.round(b), message);
-  }
+  var doc = $("svg").contentWindow.document;
 
-  var doc = $("svg").contentWindow.document;
-  
   var text1 = doc.getElementById("text1");
-  
-  var len = text1.getComputedTextLength();
-  
+
   var text1Bounds = text1.getBoundingClientRect();
   var text2Bounds = doc.getElementById("text2").getBoundingClientRect();
   var text3Bounds = doc.getElementById("text3").getBoundingClientRect();
-  var text4Bounds = doc.getElementById("text4").getBoundingClientRect();
 
   var sin45 = Math.sin(Math.PI / 4);
 
-  isRounded(text1Bounds.left, 25, "text1.getBoundingClientRect().left");
-  isRounded(text1Bounds.width, len, "text1.getBoundingClientRect().width");
+  isApproximately(text1Bounds.left, 24, "text1.getBoundingClientRect().left");
 
-  isRounded(text2Bounds.left, text1Bounds.left + 100, "text2.getBoundingClientRect().left");
-  isRounded(text2Bounds.top, text1Bounds.top, "text2.getBoundingClientRect().top");
-  isRounded(text2Bounds.width, text1Bounds.width, "text2.getBoundingClientRect().width");
-  isRounded(text2Bounds.height, text1Bounds.height, "text2.getBoundingClientRect().height");
+  is(text2Bounds.left, text1Bounds.left + 100, "text2.getBoundingClientRect().left");
+  is(text2Bounds.top, text1Bounds.top, "text2.getBoundingClientRect().top");
+  is(text2Bounds.width, text1Bounds.width, "text2.getBoundingClientRect().width");
+  is(text2Bounds.height, text1Bounds.height, "text2.getBoundingClientRect().height");
 
-  isRounded(text3Bounds.width, (text1Bounds.width + text1Bounds.height) * sin45 + .5, "text3.getBoundingClientRect().width");
-  isRounded(text3Bounds.height, (text1Bounds.height  + text1Bounds.width) * sin45 + .5, "text3.getBoundingClientRect().height");
-
-  isRounded(text4Bounds.width, 2 * (text1Bounds.width + text1Bounds.height) * sin45, "text4.getBoundingClientRect().width");
-  isRounded(text4Bounds.height, 2 * ((text1Bounds.height  + text1Bounds.width) * sin45 - .5), "text4.getBoundingClientRect().height");
+  var r = (text1Bounds.width + text1Bounds.height) * sin45;
+  isApproximately(text3Bounds.width, Math.ceil(r), "text3.getBoundingClientRect().width");
+  isApproximately(text3Bounds.height, Math.ceil(r), "text3.getBoundingClientRect().height");
 
   var rect1Bounds = doc.getElementById("rect1").getBoundingClientRect();
   var rect2Bounds = doc.getElementById("rect2").getBoundingClientRect();
   var rect3Bounds = doc.getElementById("rect3").getBoundingClientRect();
   var rect4Bounds = doc.getElementById("rect4").getBoundingClientRect();
-  
-  isRounded(rect1Bounds.left, 50, "rect1.getBoundingClientRect().left");
-  isRounded(rect1Bounds.top, 50, "rect1.getBoundingClientRect().top");
-  isRounded(rect1Bounds.width, 50, "rect1.getBoundingClientRect().width");
-  isRounded(rect1Bounds.height, 50, "rect1.getBoundingClientRect().height");
+
+  is(rect1Bounds.left, 50, "rect1.getBoundingClientRect().left");
+  is(rect1Bounds.top, 50, "rect1.getBoundingClientRect().top");
+  is(rect1Bounds.width, 50, "rect1.getBoundingClientRect().width");
+  is(rect1Bounds.height, 50, "rect1.getBoundingClientRect().height");
 
-  isRounded(rect2Bounds.left, 175 - 50 * sin45 - .5, "rect2.getBoundingClientRect().left");
-  isRounded(rect2Bounds.top, 75 - 50 * sin45 - .5, "rect2.getBoundingClientRect().top");
-  isRounded(rect2Bounds.width, (50 * sin45 + .5) * 2, "rect2.getBoundingClientRect().width");
-  isRounded(rect2Bounds.height, (50 * sin45 + .5) * 2, "rect2.getBoundingClientRect().height");
+  rect = new Rect(175 - 50 * sin45, 75 - 50 * sin45, 50 * sin45 * 2, 50 * sin45 * 2);
+  rect.roundOut();
+  is(rect2Bounds.left, rect.left, "rect2.getBoundingClientRect().left");
+  is(rect2Bounds.top, rect.top, "rect2.getBoundingClientRect().top");
+  is(rect2Bounds.width, rect.width, "rect2.getBoundingClientRect().width");
+  is(rect2Bounds.height, rect.height, "rect2.getBoundingClientRect().height");
 
-  isRounded(rect3Bounds.left, 50, "rect3.getBoundingClientRect().left");
-  isRounded(rect3Bounds.top, 160, "rect3.getBoundingClientRect().top");
-  isRounded(rect3Bounds.width, 100, "rect3.getBoundingClientRect().width");
-  isRounded(rect3Bounds.height, 100, "rect3.getBoundingClientRect().height");
+  is(rect3Bounds.left, 50, "rect3.getBoundingClientRect().left");
+  is(rect3Bounds.top, 160, "rect3.getBoundingClientRect().top");
+  is(rect3Bounds.width, 100, "rect3.getBoundingClientRect().width");
+  is(rect3Bounds.height, 100, "rect3.getBoundingClientRect().height");
 
-  isRounded(rect4Bounds.left, 350 - 100 * sin45 - .5, "rect4.getBoundingClientRect().left");
-  isRounded(rect4Bounds.top, 150 - 100 * sin45 - .5, "rect4.getBoundingClientRect().top");
-  isRounded(rect4Bounds.width, (100 * sin45 + .5) * 2, "rect4.getBoundingClientRect().width");
-  isRounded(rect4Bounds.height, (100 * sin45 + .5) * 2, "rect4.getBoundingClientRect().height");
+  rect = new Rect(350 - 100 * sin45, 150 - 100 * sin45, 100 * sin45 * 2, 100 * sin45 * 2);
+  rect.roundOut();
+  is(rect4Bounds.left, rect.left, "rect4.getBoundingClientRect().left");
+  is(rect4Bounds.top, rect.top, "rect4.getBoundingClientRect().top");
+  is(rect4Bounds.width, rect.width, "rect4.getBoundingClientRect().width");
+  is(rect4Bounds.height, rect.height, "rect4.getBoundingClientRect().height");
 
   var rect1aBounds = doc.getElementById("rect1a").getBoundingClientRect();
   var rect2aBounds = doc.getElementById("rect2a").getBoundingClientRect();
   var rect3aBounds = doc.getElementById("rect3a").getBoundingClientRect();
   var rect4aBounds = doc.getElementById("rect4a").getBoundingClientRect();
-  
-  isRounded(rect1aBounds.left, 49, "rect1a.getBoundingClientRect().left");
-  isRounded(rect1aBounds.top, 49, "rect1a.getBoundingClientRect().top");
-  isRounded(rect1aBounds.width, 52, "rect1a.getBoundingClientRect().width");
-  isRounded(rect1aBounds.height, 52, "rect1a.getBoundingClientRect().height");
+
+  is(rect1aBounds.left, 48, "rect1a.getBoundingClientRect().left");
+  is(rect1aBounds.top, 48, "rect1a.getBoundingClientRect().top");
+  is(rect1aBounds.width, 54, "rect1a.getBoundingClientRect().width");
+  is(rect1aBounds.height, 54, "rect1a.getBoundingClientRect().height");
 
-  isRounded(rect2aBounds.left, 175 - 52 * sin45 - .5, "rect2a.getBoundingClientRect().left");
-  isRounded(rect2aBounds.top, 75 - 52 * sin45 - .5, "rect2a.getBoundingClientRect().top");
-  isRounded(rect2aBounds.width, 52 * sin45 * 2, "rect2a.getBoundingClientRect().width");
-  isRounded(rect2aBounds.height, 52 * sin45 * 2, "rect2a.getBoundingClientRect().height");
+  rect = new Rect(175 - 54 * sin45, 75 - 54 * sin45, 54 * sin45 * 2, 54 * sin45 * 2);
+  rect.roundOut();
+  is(rect2aBounds.left, rect.left, "rect2a.getBoundingClientRect().left");
+  is(rect2aBounds.top, rect.top, "rect2a.getBoundingClientRect().top");
+  is(rect2aBounds.width, rect.width, "rect2a.getBoundingClientRect().width");
+  is(rect2aBounds.height, rect.height, "rect2a.getBoundingClientRect().height");
 
-  isRounded(rect3aBounds.left, 48, "rect3a.getBoundingClientRect().left");
-  isRounded(rect3aBounds.top, 158, "rect3a.getBoundingClientRect().top");
-  isRounded(rect3aBounds.width, 104, "rect3a.getBoundingClientRect().width");
-  isRounded(rect3aBounds.height, 104, "rect3a.getBoundingClientRect().height");
+  is(rect3aBounds.left, 46, "rect3a.getBoundingClientRect().left");
+  is(rect3aBounds.top, 156, "rect3a.getBoundingClientRect().top");
+  is(rect3aBounds.width, 108, "rect3a.getBoundingClientRect().width");
+  is(rect3aBounds.height, 108, "rect3a.getBoundingClientRect().height");
 
-  isRounded(rect4aBounds.left, 350 - 104 * sin45 - .5, "rect4a.getBoundingClientRect().left");
-  isRounded(rect4aBounds.top, 150 - 104 * sin45 - .5, "rect4a.getBoundingClientRect().top");
-  isRounded(rect4aBounds.width, (104 * sin45 + .5) * 2, "rect4a.getBoundingClientRect().width");
-  isRounded(rect4aBounds.height, (104 * sin45 + .5) * 2, "rect4a.getBoundingClientRect().height");
+  rect = new Rect(350 - 108 * sin45, 150 - 108 * sin45, 108 * sin45 * 2, 108 * sin45 * 2);
+  rect.roundOut();
+  is(rect4aBounds.left, rect.left, "rect4a.getBoundingClientRect().left");
+  is(rect4aBounds.top, rect.top, "rect4a.getBoundingClientRect().top");
+  is(rect4aBounds.width, rect.width, "rect4a.getBoundingClientRect().width");
+  is(rect4aBounds.height, rect.height, "rect4a.getBoundingClientRect().height");
 
   var text1a = doc.getElementById("text1a");
-  
+
   var text1aBounds = text1a.getBoundingClientRect();
   var text2aBounds = doc.getElementById("text2a").getBoundingClientRect();
 
-  var len = text1a.getComputedTextLength();
+  isApproximately(text1aBounds.left, 82, "text1a.getBoundingClientRect().left");
+  is(text1aBounds.width, text1Bounds.width + 4, "text1a.getBoundingClientRect().width");
 
-  isRounded(text1aBounds.left, 85 - 1, "text1a.getBoundingClientRect().left");
-  isRounded(text1aBounds.width, len + 1, "text1a.getBoundingClientRect().width");
-  
-  isRounded(text2aBounds.left, text1aBounds.left + 100 - 4, "text2a.getBoundingClientRect().left");
-  isRounded(text2aBounds.width, text1aBounds.width + 9, "text2a.getBoundingClientRect().width");
+  is(text2aBounds.left, text1aBounds.left + 100 - 3, "text2a.getBoundingClientRect().left");
+  is(text2aBounds.width, text1aBounds.width + 6, "text2a.getBoundingClientRect().width");
 
   SimpleTest.finish();
 }
 
 window.addEventListener("load", runTest, false);
 </script>
 </pre>
 </body>
deleted file mode 100644
--- a/content/xslt/build.mk
+++ /dev/null
@@ -1,46 +0,0 @@
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is the Mozilla build system.
-#
-# The Initial Developer of the Original Code is
-# the Mozilla Foundation <http://www.mozilla.org/>.
-# Portions created by the Initial Developer are Copyright (C) 2006
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Benjamin Smedberg <benjamin@smedbergs.us> (Initial Code)
-#
-# 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 $(topsrcdir)/config/nspr/build.mk
-include $(topsrcdir)/xpcom/build.mk
-
-TIERS += app
-
-tier_app_dirs += \
-	parser/expat \
-	content/xslt/src \
-	$(NULL)
deleted file mode 100755
--- a/content/xslt/confvars.sh
+++ /dev/null
@@ -1,42 +0,0 @@
-#! /bin/sh
-# ***** 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 Build System
-#
-# The Initial Developer of the Original Code is
-# Ben Turner <mozilla@songbirdnest.com>
-#
-# 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 *****
-
-MOZ_APP_NAME=mozilla
-MOZ_EXTENSIONS_DEFAULT=""
-MOZ_XSLT_STANDALONE=1
-MOZ_APP_VERSION=$MOZILLA_VERSION
--- a/content/xslt/src/Makefile.in
+++ b/content/xslt/src/Makefile.in
@@ -39,13 +39,9 @@ DEPTH           = ../../..
 topsrcdir       = @top_srcdir@
 srcdir          = @srcdir@
 VPATH           = @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 PARALLEL_DIRS   = base xml xpath xslt 
 
-ifdef MOZ_XSLT_STANDALONE
-PARALLEL_DIRS += main
-endif
-
 include $(topsrcdir)/config/rules.mk
--- a/content/xslt/src/base/Makefile.in
+++ b/content/xslt/src/base/Makefile.in
@@ -41,30 +41,22 @@ srcdir          = @srcdir@
 VPATH           = @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE = transformiix
 LIBRARY_NAME = txbase_s
 LIBXUL_LIBRARY = 1
 
-
-
 CPPSRCS	= txDouble.cpp \
 	txList.cpp \
 	txExpandedNameMap.cpp \
 	txNamespaceMap.cpp \
 	txURIUtils.cpp
 
-ifdef MOZ_XSLT_STANDALONE
-CPPSRCS += txSimpleErrorObserver.cpp \
-	txStringUtils.cpp \
-	txAtoms.cpp
-endif
-
 # we don't want the shared lib, but we want to force the creation of a
 # static lib.
 FORCE_STATIC_LIB = 1
 
 include $(topsrcdir)/config/rules.mk
 
 INCLUDES += \
 	-I$(srcdir)/../../public \
--- a/content/xslt/src/base/txAtoms.h
+++ b/content/xslt/src/base/txAtoms.h
@@ -34,80 +34,15 @@
  * 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 TRANSFRMX_ATOMS_H
 #define TRANSFRMX_ATOMS_H
 
-#ifndef TX_EXE
-
 #include "nsGkAtoms.h"
 typedef class nsGkAtoms txXPathAtoms;
 typedef class nsGkAtoms txXMLAtoms;
 typedef class nsGkAtoms txXSLTAtoms;
 typedef class nsGkAtoms txHTMLAtoms;
 
-#else
-
-class nsIAtom;
-
-/*
- * Declare all atoms
- *
- * The atom names and values are stored in tx*AtomList.h and
- * are brought to you by the magic of C preprocessing.
- * Add new atoms to tx*AtomList.h and all support logic will
- * be auto-generated.
- */
-
-#define DOM_ATOMS                               \
-TX_ATOM(comment, "#comment")                    \
-TX_ATOM(document, "#document")                  \
-TX_ATOM(text, "#text")
-
-#define XML_ATOMS             \
-TX_ATOM(_empty, "")           \
-TX_ATOM(base, "base")         \
-TX_ATOM(_default, "default")  \
-TX_ATOM(lang, "lang")         \
-TX_ATOM(preserve, "preserve") \
-TX_ATOM(space, "space")       \
-TX_ATOM(xml, "xml")           \
-TX_ATOM(xmlns, "xmlns")       \
-DOM_ATOMS
-
-#define TX_ATOM(_name, _value) static nsIAtom* _name;
-
-class txXMLAtoms
-{
-public:
-    static void init();
-XML_ATOMS
-};
-
-class txXPathAtoms
-{
-public:
-    static void init();
-#include "txXPathAtomList.h"
-};
-
-class txXSLTAtoms
-{
-public:
-    static void init();
-#include "txXSLTAtomList.h"
-};
-
-class txHTMLAtoms
-{
-public:
-    static void init();
-#include "txHTMLAtomList.h"
-};
-
-#undef TX_ATOM
-
 #endif
-
-#endif
--- a/content/xslt/src/base/txErrorObserver.h
+++ b/content/xslt/src/base/txErrorObserver.h
@@ -35,19 +35,16 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef MITRE_ERROROBSERVER_H
 #define MITRE_ERROROBSERVER_H
 
 #include "txCore.h"
-#ifdef TX_EXE
-#include <iostream.h>
-#endif
 
 /**
  * A simple interface for observing errors
 **/
 class ErrorObserver {
 
 public:
 
@@ -69,44 +66,9 @@ public:
     {
         receiveError(errorMessage, NS_ERROR_FAILURE);
     }
 
         
 
 }; //-- ErrorObserver
 
-#ifdef TX_EXE
-/**
- * A simple ErrorObserver which allows printing error messages to a stream
-**/
-class SimpleErrorObserver : public ErrorObserver {
-
-public:
-
-    /**
-     * Creates a new SimpleErrorObserver.
-     * All errors will be printed to the console (cout).
-    **/
-    SimpleErrorObserver();
-
-    /**
-     * Creates a new SimpleErrorObserver.
-     * All errors will be printed to the given ostream.
-    **/
-    SimpleErrorObserver(ostream& errStream);
-
-    /**
-     *  Notifies this Error observer of a new error aRes
-    **/
-    void receiveError(const nsAString& errorMessage, nsresult aRes);
-
-    virtual void suppressWarnings(MBool suppress);
-
-private:
-
-    ostream* errStream;
-    MBool hideWarnings;
-}; //-- SimpleErrorObserver
 #endif
-
-#endif
-
deleted file mode 100644
--- a/content/xslt/src/base/txSimpleErrorObserver.cpp
+++ /dev/null
@@ -1,80 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* ***** 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 TransforMiiX XSLT processor code.
- *
- * The Initial Developer of the Original Code is
- * The MITRE Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1999
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Keith Visco <kvisco@ziplink.net> (Original Author)
- *
- * 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 "txErrorObserver.h"
-#include "nsString.h"
-
-/**
- * Creates a new SimpleErrorObserver.
- * All errors will be printed to the console (cout).
-**/
-SimpleErrorObserver::SimpleErrorObserver() {
-#ifdef TX_EXE
-    errStream = &cout;
-#endif
-    hideWarnings = MB_FALSE;
-} //-- SimpleErrorObserver
-
-/**
- * Creates a new SimpleErrorObserver.
- * All errors will be printed to the given ostream.
-**/
-SimpleErrorObserver::SimpleErrorObserver(ostream& errStream) {
-    this->errStream = &errStream;
-    hideWarnings = MB_FALSE;
-} //-- SimpleErrorObserver
-
-/**
- *  Notifies this Error observer of a new error using the given error level
-**/
-void SimpleErrorObserver::receiveError(const nsAString& errorMessage,
-                                       nsresult aRes)
-{
-#ifdef TX_EXE
-    if (NS_FAILED(aRes)) {
-        *errStream << "error: ";
-    }
-
-    *errStream << NS_LossyConvertUTF16toASCII(errorMessage).get() << endl;
-    errStream->flush();
-#endif
-}
-
-void SimpleErrorObserver::suppressWarnings(MBool suppress) {
-    this->hideWarnings = suppress;
-} //-- suppressWarnings
deleted file mode 100644
--- a/content/xslt/src/base/txStringUtils.cpp
+++ /dev/null
@@ -1,152 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* ***** 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 TransforMiiX XSLT processor code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 2002
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Axel Hecht <axel@pike.org>
- *   Peter Van der Beken <peterv@propagandism.org>
- *
- * 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 "txStringUtils.h"
-#include "nsDependentString.h"
-
-int
-txCaseInsensitiveStringComparator::operator()(const char_type* lhs,
-                                              const char_type* rhs,
-                                              PRUint32 aLength ) const
-{
-  PRUnichar thisChar, otherChar;
-  PRUint32 compLoop = 0;
-  while (compLoop < aLength) {
-    thisChar = lhs[compLoop];
-    if ((thisChar >= 'A') && (thisChar <= 'Z')) {
-      thisChar += 32;
-    }
-    otherChar = rhs[compLoop];
-    if ((otherChar >= 'A') && (otherChar <= 'Z')) {
-      otherChar += 32;
-    }
-    if (thisChar != otherChar) {
-      return thisChar - otherChar;
-    }
-    ++compLoop;
-  }
-  return 0;
-
-}
-
-int
-txCaseInsensitiveStringComparator::operator()(char_type lhs,
-                                              char_type rhs) const
-{
-  if (lhs >= 'A' && lhs <= 'Z') {
-    lhs += 32;
-  }
-  if (rhs >= 'A' && rhs <= 'Z') {
-    rhs += 32;
-  }
-  return lhs - rhs;
-} 
-
-/**
- * A character sink for case conversion.
- */
-class ConvertToLowerCase
-{
-public:
-  typedef PRUnichar value_type;
-
-  void write( const PRUnichar* aSource, PRUint32 aSourceLength)
-  {
-    PRUnichar* cp = const_cast<PRUnichar*>(aSource);
-    const PRUnichar* end = aSource + aSourceLength;
-    while (cp != end) {
-      PRUnichar ch = *cp;
-      if ((ch >= 'A') && (ch <= 'Z'))
-        *cp = ch + ('a' - 'A');
-      ++cp;
-    }
-  }
-};
-
-void TX_ToLowerCase(nsAString& aString)
-{
-  nsAString::iterator fromBegin, fromEnd;
-  ConvertToLowerCase converter;
-  copy_string(aString.BeginWriting(fromBegin), aString.EndWriting(fromEnd),
-              converter);
-}
-
-/**
- * A character sink for copying with case conversion.
- */
-class CopyToLowerCase
-{
-public:
-  typedef PRUnichar value_type;
-
-  CopyToLowerCase(nsAString::iterator& aDestIter) : mIter(aDestIter)
-  {
-  }
-
-  void write(const PRUnichar* aSource, PRUint32 aSourceLength)
-  {
-    PRUint32 len = NS_MIN(PRUint32(mIter.size_forward()), aSourceLength);
-    PRUnichar* cp = mIter.get();
-    const PRUnichar* end = aSource + len;
-    while (aSource != end) {
-      PRUnichar ch = *aSource;
-      if ((ch >= 'A') && (ch <= 'Z'))
-        *cp = ch + ('a' - 'A');
-      else
-        *cp = ch;
-      ++aSource;
-      ++cp;
-    }
-    mIter.advance(len);
-  }
-
-protected:
-  nsAString::iterator& mIter;
-};
-
-void TX_ToLowerCase(const nsAString& aSource, nsAString& aDest)
-{
-  nsAString::const_iterator fromBegin, fromEnd;
-  nsAString::iterator toBegin;
-  if (!EnsureStringLength(aDest, aSource.Length()))
-    return; // XXX no way to signal out-of-memory
-  CopyToLowerCase converter(aDest.BeginWriting(toBegin));
-  copy_string(aSource.BeginReading(fromBegin), aSource.EndReading(fromEnd),
-              converter);
-}
--- a/content/xslt/src/base/txStringUtils.h
+++ b/content/xslt/src/base/txStringUtils.h
@@ -37,50 +37,31 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef txStringUtils_h__
 #define txStringUtils_h__
 
 #include "nsAString.h"
 #include "nsIAtom.h"
+#include "nsUnicharUtils.h"
+
+#define TX_ToLowerCase ToLowerCase
+
+typedef nsCaseInsensitiveStringComparator txCaseInsensitiveStringComparator;
 
 /**
  * Check equality between a string and an atom containing ASCII.
  */
 inline PRBool
 TX_StringEqualsAtom(const nsASingleFragmentString& aString, nsIAtom* aAtom)
 {
   return aAtom->Equals(aString);
 }
 
-#ifndef TX_EXE
-
-#include "nsUnicharUtils.h"
-typedef nsCaseInsensitiveStringComparator txCaseInsensitiveStringComparator;
-
-#define TX_ToLowerCase ToLowerCase
-
-#else
-
-// These only work for ASCII ranges!
-
-class txCaseInsensitiveStringComparator
-: public nsStringComparator
-{
-public:
-  virtual int operator()(const char_type*, const char_type*, PRUint32 aLength) const;
-  virtual int operator()(char_type, char_type) const;
-};
-
-void TX_ToLowerCase(nsAString& aString);
-void TX_ToLowerCase(const nsAString& aSource, nsAString& aDest);
-
-#endif
-
 inline already_AddRefed<nsIAtom>
 TX_ToLowerCaseAtom(nsIAtom* aAtom)
 {
   nsAutoString str;
   aAtom->ToString(str);
   TX_ToLowerCase(str);
   return do_GetAtom(str);
 }
--- a/content/xslt/src/base/txURIUtils.cpp
+++ b/content/xslt/src/base/txURIUtils.cpp
@@ -33,180 +33,54 @@
  * 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 "txURIUtils.h"
-
-#ifndef TX_EXE
 #include "nsNetUtil.h"
 #include "nsIAttribute.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsIContent.h"
 #include "nsIPrincipal.h"
 #include "nsINodeInfo.h"
-#endif
 
 /**
  * URIUtils
  * A set of utilities for handling URIs
 **/
 
-#ifdef TX_EXE
-//- Constants -/
-
-const char   URIUtils::HREF_PATH_SEP  = '/';
-
-/**
- * Implementation of utility functions for parsing URLs.
- * Just file paths for now.
- */
-void
-txParsedURL::init(const nsAFlatString& aSpec)
-{
-    mPath.Truncate();
-    mName.Truncate();
-    mRef.Truncate();
-    PRUint32 specLength = aSpec.Length();
-    if (!specLength) {
-        return;
-    }
-    const PRUnichar* start = aSpec.get();
-    const PRUnichar* end = start + specLength;
-    const PRUnichar* c = end - 1;
-
-    // check for #ref
-    for (; c >= start; --c) {
-        if (*c == '#') {
-            // we could eventually unescape this, too.
-            mRef = Substring(c + 1, end);
-            end = c;
-            --c;
-            if (c == start) {
-                // we're done,
-                return;
-            }
-            break;
-        }
-    }
-    for (c = end - 1; c >= start; --c) {
-        if (*c == '/') {
-            mName = Substring(c + 1, end);
-            mPath = Substring(start, c + 1);
-            return;
-        }
-    }
-    mName = Substring(start, end);
-}
-
-void
-txParsedURL::resolve(const txParsedURL& aRef, txParsedURL& aDest)
-{
-    /*
-     * No handling of absolute URLs now.
-     * These aren't really URLs yet, anyway, but paths with refs
-     */
-    aDest.mPath = mPath + aRef.mPath;
-
-    if (aRef.mName.IsEmpty() && aRef.mPath.IsEmpty()) {
-        // the relative URL is just a fragment identifier
-        aDest.mName = mName;
-        if (aRef.mRef.IsEmpty()) {
-            // and not even that, keep the base ref
-            aDest.mRef = mRef;
-            return;
-        }
-        aDest.mRef = aRef.mRef;
-        return;
-    }
-    aDest.mName = aRef.mName;
-    aDest.mRef = aRef.mRef;
-}
-
-/**
- * Returns an InputStream for the file represented by the href
- * argument
- * @param href the href of the file to get the input stream for.
- * @return an InputStream to the desired resource
- * @exception java.io.FileNotFoundException when the file could not be
- * found
-**/
-istream* URIUtils::getInputStream(const nsAString& href, nsAString& errMsg)
-{
-    return new ifstream(NS_LossyConvertUTF16toASCII(href).get(), ios::in);
-} //-- getInputStream
-
-/**
-    * Returns the document base of the href argument
-    * @return the document base of the given href
-**/
-void URIUtils::getDocumentBase(const nsAFlatString& href, nsAString& dest)
-{
-    if (href.IsEmpty()) {
-        return;
-    }
-
-    nsAFlatString::const_char_iterator temp;
-    href.BeginReading(temp);
-    PRUint32 iter = href.Length();
-    while (iter > 0) {
-        if (temp[--iter] == HREF_PATH_SEP) {
-            dest.Append(StringHead(href, iter));
-            break;
-        }
-    }
-}
-#endif
-
 /**
  * Resolves the given href argument, using the given documentBase
  * if necessary.
  * The new resolved href will be appended to the given dest String
 **/
 void URIUtils::resolveHref(const nsAString& href, const nsAString& base,
                            nsAString& dest) {
     if (base.IsEmpty()) {
         dest.Append(href);
         return;
     }
     if (href.IsEmpty()) {
         dest.Append(base);
         return;
     }
-
-#ifndef TX_EXE
     nsCOMPtr<nsIURI> pURL;
     nsAutoString resultHref;
     nsresult result = NS_NewURI(getter_AddRefs(pURL), base);
     if (NS_SUCCEEDED(result)) {
         NS_MakeAbsoluteURI(resultHref, href, pURL);
         dest.Append(resultHref);
     }
-#else
-    nsAutoString documentBase;
-    getDocumentBase(PromiseFlatString(base), documentBase);
-
-    //-- join document base + href
-    if (!documentBase.IsEmpty()) {
-        dest.Append(documentBase);
-        if (documentBase.CharAt(documentBase.Length()-1) != HREF_PATH_SEP)
-            dest.Append(PRUnichar(HREF_PATH_SEP));
-    }
-    dest.Append(href);
-
-#endif
 } //-- resolveHref
 
-#ifndef TX_EXE
-
 // static
 void
 URIUtils::ResetWithSource(nsIDocument *aNewDoc, nsIDOMNode *aSourceNode)
 {
     nsCOMPtr<nsINode> node = do_QueryInterface(aSourceNode);
     if (!node) {
         // XXXbz passing nsnull as the first arg to Reset is illegal
         aNewDoc->Reset(nsnull, nsnull);
@@ -240,10 +114,8 @@ URIUtils::ResetWithSource(nsIDocument *a
     aNewDoc->SetPrincipal(sourcePrincipal);
     aNewDoc->SetBaseURI(sourceDoc->GetDocBaseURI());
 
     // Copy charset
     aNewDoc->SetDocumentCharacterSetSource(
           sourceDoc->GetDocumentCharacterSetSource());
     aNewDoc->SetDocumentCharacterSet(sourceDoc->GetDocumentCharacterSet());
 }
-
-#endif /* TX_EXE */
--- a/content/xslt/src/base/txURIUtils.h
+++ b/content/xslt/src/base/txURIUtils.h
@@ -34,72 +34,33 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef TRANSFRMX_URIUTILS_H
 #define TRANSFRMX_URIUTILS_H
 
 #include "txCore.h"
-#ifdef TX_EXE
-#include <fstream.h>
-#include <iostream.h>
-#include "nsString.h"
-#else
+
 class nsIDocument;
 class nsIDOMNode;
 
-#endif
-
 /**
  * A utility class for URI handling
  * Not yet finished, only handles file URI at this point
 **/
 
-#ifdef TX_EXE
-class txParsedURL
-{
-public:
-    void init(const nsAFlatString& aSpec);
-    void resolve(const txParsedURL& aRef, txParsedURL& aDest);
-    void getFile(nsString& aResult) const
-    {
-        aResult = mPath + mName;
-    }
-    nsString mPath, mName, mRef;
-};
-#endif
-
 class URIUtils {
 public:
 
-#ifdef TX_EXE
-    /**
-     * the path separator for an URI
-    **/
-    static const char HREF_PATH_SEP;
-
-    static istream* getInputStream
-        (const nsAString& href, nsAString& errMsg);
-
-    /**
-     * Returns the document base of the href argument
-     * The document base will be appended to the given dest String
-    **/
-    static void getDocumentBase(const nsAFlatString& href, nsAString& dest);
-
-#else /* TX_EXE */
-
     /**
      * Reset the given document with the document of the source node
      */
     static void ResetWithSource(nsIDocument *aNewDoc, nsIDOMNode *aSourceNode);
 
-#endif /* TX_EXE */
-
     /**
      * Resolves the given href argument, using the given documentBase
      * if necessary.
      * The new resolved href will be appended to the given dest String
     **/
     static void resolveHref(const nsAString& href, const nsAString& base,
                             nsAString& dest);
 }; //-- URIUtils
deleted file mode 100644
--- a/content/xslt/src/main/Makefile.in
+++ /dev/null
@@ -1,80 +0,0 @@
-# ***** 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 TransforMiiX XSLT processor code.
-#
-# The Initial Developer of the Original Code is
-# Axel Hecht.
-# Portions created by the Initial Developer are Copyright (C) 2001
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Axel Hecht <axel@pike.org>
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either the GNU General Public License Version 2 or later (the "GPL"), or
-# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-DEPTH           = ../../../..
-topsrcdir       = @top_srcdir@
-srcdir          = @srcdir@
-VPATH           = @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-MOZILLA_INTERNAL_API = 1
-SIMPLE_PROGRAMS = transformiix$(BIN_SUFFIX) testXalan$(BIN_SUFFIX) \
-                  txTestExpr$(BIN_SUFFIX)
-ifdef MARK_INC
-SIMPLE_PROGRAMS += txXSLTMarkDriver$(BIN_SUFFIX)
-endif
-
-
-CPP_PROG_LINK          = 1
-
-TX_LIBS = \
-	txxslt_s \
-	txxpath_s \
-	txxml_s \
-	txbase_s \
-	mozexpat_s \
-	$(NULL)
-
-LIBS = \
-	$(addprefix $(DIST)/lib/$(LIB_PREFIX),$(addsuffix .$(LIB_SUFFIX),$(TX_LIBS))) \
-	$(MOZ_COMPONENT_LIBS) \
-	$(NULL)
-
-ifdef MOZ_JPROF
-LIBS         += -ljprof
-endif
-
-include $(topsrcdir)/config/rules.mk
-
-INCLUDES += \
-	-I$(srcdir)/../base \
-	-I$(srcdir)/../xml \
-  -I$(srcdir)/../xpath \
-	-I$(srcdir)/../xslt \
-	$(MARK_INC) \
-	$(NULL)
deleted file mode 100644
--- a/content/xslt/src/main/testXalan.cpp
+++ /dev/null
@@ -1,423 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* ***** 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 TransforMiiX XSLT processor code.
- *
- * The Initial Developer of the Original Code is
- * Axel Hecht.
- * Portions created by the Initial Developer are Copyright (C) 2003
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Axel Hecht <axel@pike.org>
- *
- * 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 "txStandaloneXSLTProcessor.h"
-#include "nsXPCOM.h"
-#include <fstream.h>
-#include "nsDoubleHashtable.h"
-#include "nsIComponentManager.h"
-#include "nsILocalFile.h"
-#include "nsISimpleEnumerator.h"
-#include "nsString.h"
-#include "prenv.h"
-#include "prsystem.h"
-#include "nsDirectoryServiceUtils.h"
-#include "nsDirectoryServiceDefs.h"
-
-#ifdef NS_TRACE_MALLOC
-#include "nsTraceMalloc.h"
-#endif
-#ifdef MOZ_JPROF
-#include "jprof.h"
-#endif
-
-/**
- * Prints the command line help screen to the console
- */
-void printHelp()
-{
-  cerr << "testXalan [-o output-file] [category]*" << endl << endl;
-  cerr << "Options:";
-  cerr << endl << endl;
-  cerr << "\t-o  specify output file (default: write to stdout)";
-  cerr << endl << endl;
-  cerr << "\t Specify XALAN_DIR in your environement." << endl;
-  cerr << endl;
-}
-
-/**
- * Helper class to report success and failure to RDF
- */
-class txRDFOut
-{
-public:
-    explicit txRDFOut(ostream* aOut)
-        : mOut(aOut), mSuccess(0), mFail(0), mParent(nsnull)
-    {
-    }
-    explicit txRDFOut(const nsACString& aName, txRDFOut* aParent)
-        : mName(aName), mOut(aParent->mOut), mSuccess(0), mFail(0),
-          mParent(aParent)
-    {
-    }
-    ~txRDFOut()
-    {
-        *mOut << "  <RDF:Description about=\"urn:x-buster:conf" <<
-            mName.get() <<
-            "\">\n" <<
-            "    <NC:orig_succCount NC:parseType=\"Integer\">" <<
-            mSuccess <<
-            "</NC:orig_succCount>\n" <<
-            "    <NC:orig_failCount NC:parseType=\"Integer\">" <<
-            mFail <<
-            "</NC:orig_failCount>\n" <<
-            "  </RDF:Description>" << endl;
-    }
-
-    void feed(const nsACString& aTest, PRBool aSuccess)
-    {
-        *mOut << "  <RDF:Description about=\"urn:x-buster:" <<
-            PromiseFlatCString(aTest).get() <<
-            "\"\n                   NC:orig_succ=\"";
-        if (aSuccess) {
-            *mOut << "yes";
-            succeeded();
-        }
-        else {
-            *mOut << "no";
-            failed();
-        }
-        *mOut << "\" />\n";
-    }
-
-    void succeeded()
-    {
-        if (mParent)
-            mParent->succeeded();
-        ++mSuccess;
-    }
-    void failed()
-    {
-        if (mParent)
-            mParent->failed();
-        ++mFail;
-    }
-private:
-    nsCAutoString mName;
-    ostream* mOut;
-    PRUint32 mSuccess, mFail;
-    txRDFOut* mParent;
-};
-
-static void
-readToString(istream& aIstream, nsACString& aString)
-{
-    static char buffer[1024];
-    int read = 0;
-    do {
-        aIstream.read(buffer, 1024);
-        read = aIstream.gcount();
-        aString.Append(Substring(buffer, buffer + read));
-    } while (!aIstream.eof());
-}
-
-/**
- * Get the XALAN_DIR environment variable and return a nsIFile for
- * the conf and the conf-gold subdirectory. Create a TEMP file, too.
- * Return an error if either does not exist.
- */
-static nsresult
-setupXalan(const char* aPath, nsIFile** aConf, nsIFile** aConfGold,
-           nsIFile** aTemp)
-{
-    nsresult rv;
-    nsCOMPtr<nsILocalFile> conf(do_CreateInstance(NS_LOCAL_FILE_CONTRACTID,
-                                                  &rv));
-    NS_ENSURE_SUCCESS(rv, rv);
-    nsCOMPtr <nsIFile> tmpFile;
-    rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(tmpFile));
-    NS_ENSURE_SUCCESS(rv, rv);
-    tmpFile->Append(NS_LITERAL_STRING("xalan.out"));
-    rv = tmpFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0600);
-    rv = conf->InitWithNativePath(nsDependentCString(aPath));
-    NS_ENSURE_SUCCESS(rv, rv);
-    nsCOMPtr<nsIFile> gold;
-    rv = conf->Clone(getter_AddRefs(gold));
-    NS_ENSURE_SUCCESS(rv, rv);
-    rv = conf->Append(NS_LITERAL_STRING("conf"));
-    NS_ENSURE_SUCCESS(rv, rv);
-    PRBool isDir;
-    rv = conf->IsDirectory(&isDir);
-    if (NS_FAILED(rv) || !isDir) {
-        return NS_ERROR_FILE_NOT_DIRECTORY;
-    }
-    rv = gold->Append(NS_LITERAL_STRING("conf-gold"));
-    NS_ENSURE_SUCCESS(rv, rv);
-    rv = gold->IsDirectory(&isDir);
-    if (NS_FAILED(rv) || !isDir || !conf || !gold) {
-        return NS_ERROR_FILE_NOT_DIRECTORY;
-    }
-    // got conf and conf-gold subdirectories
-    *aConf = conf;
-    NS_ADDREF(*aConf);
-    *aConfGold = gold;
-    NS_ADDREF(*aConfGold);
-    *aTemp = tmpFile;
-    NS_ADDREF(*aTemp);
-    return NS_OK;
-}
-
-/**
- * Run a category of Xalan tests
- */
-void runCategory(nsIFile* aConfCat, nsIFile* aGoldCat, nsIFile* aRefTmp,
-                 txRDFOut* aOut)
-{
-    nsresult rv;
-    //clone the nsIFiles, so that we can return easily
-    nsCOMPtr<nsIFile> conf, gold;
-    aConfCat->Clone(getter_AddRefs(conf));
-    aGoldCat->Clone(getter_AddRefs(gold));
-    nsCAutoString catName, refTmp;
-    conf->GetNativeLeafName(catName);
-    aRefTmp->GetNativePath(refTmp);
-    txRDFOut results(catName, aOut);
-    nsCOMPtr<nsISimpleEnumerator> tests;
-    rv = conf->GetDirectoryEntries(getter_AddRefs(tests));
-    if (NS_FAILED(rv))
-        return;
-    PRBool hasMore, isFile;
-    nsCAutoString leaf;
-    NS_NAMED_LITERAL_CSTRING(xsl, ".xsl");
-    while (NS_SUCCEEDED(tests->HasMoreElements(&hasMore)) && hasMore) {
-        nsCOMPtr<nsILocalFile> test;
-        tests->GetNext(getter_AddRefs(test));
-        test->GetNativeLeafName(leaf);
-        if (xsl.Equals(Substring(leaf, leaf.Length()-4, 4))) {
-            // we have a stylesheet, let's look for source and reference
-            nsAFlatCString::char_iterator start, ext;
-            leaf.BeginWriting(start);
-            leaf.EndWriting(ext);
-            ext -= 2;
-            // overwrite extension with .xml
-            *ext = 'm'; // this one was easy
-            nsCOMPtr<nsIFile> source;
-            conf->Clone(getter_AddRefs(source));
-            rv = source->AppendNative(leaf);
-            if (NS_SUCCEEDED(rv) && NS_SUCCEEDED(source->IsFile(&isFile)) &&
-                isFile) {
-                nsCOMPtr<nsIFile> reference;
-                gold->Clone(getter_AddRefs(reference));
-                // overwrite extension with .out
-                --ext;
-                nsCharTraits<char>::copy(ext, "out", 3);
-                rv = reference->AppendNative(leaf);
-                if (NS_SUCCEEDED(rv) &&
-                    NS_SUCCEEDED(reference->IsFile(&isFile)) &&
-                    isFile) {
-                    nsCAutoString src, style, refPath;
-                    test->GetNativePath(style);
-                    source->GetNativePath(src);
-                    reference->GetNativePath(refPath);
-                    if (PR_GetDirectorySeparator() =='\\') {
-                        src.ReplaceChar('\\','/');
-                        style.ReplaceChar('\\','/');
-                        refPath.ReplaceChar('\\','/');
-                    }
-                    SimpleErrorObserver obs;
-                    txStandaloneXSLTProcessor proc;
-                    fstream result(refTmp.get(),
-                                   ios::in | ios::out | ios::trunc);
-                    rv = proc.transform(src, style, result, obs);
-                    PRBool success = PR_FALSE;
-                    if (NS_SUCCEEDED(rv)) {
-                        result.flush();
-                        PRInt64 resultSize, refSize;
-                        aRefTmp->GetFileSize(&resultSize);
-                        reference->GetFileSize(&refSize);
-                        result.seekg(0);
-                        int toread = (int)resultSize;
-                        nsCString resContent, refContent;
-                        resContent.SetCapacity(toread);
-                        readToString(result, resContent);
-                        result.close();
-                        ifstream refStream(refPath.get());
-                        toread = (int)refSize;
-                        refContent.SetCapacity(toread);
-                        readToString(refStream, refContent);
-                        refStream.close();
-                        success = resContent.Equals(refContent);
-                    }
-                    ext--;
-                    results.feed(Substring(start, ext), success);
-                }
-            }
-        }
-    }
-}
-/**
- * The Xalan testcases app
- */
-int main(int argc, char** argv)
-{
-#ifdef NS_TRACE_MALLOC
-    NS_TraceMallocStartupArgs(argc, argv);
-#endif
-#ifdef MOZ_JPROF
-    setupProfilingStuff();
-#endif
-    char* xalan = PR_GetEnv("XALAN_DIR");
-    if (!xalan) {
-        printHelp();
-        return 1;
-    }
-    nsresult rv;
-    rv = NS_InitXPCOM2(nsnull, nsnull, nsnull);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    nsCOMPtr<nsIFile> conf, gold, resFile;
-    rv = setupXalan(xalan, getter_AddRefs(conf), getter_AddRefs(gold),
-                    getter_AddRefs(resFile));
-    if (NS_FAILED(rv)) {
-        NS_ShutdownXPCOM(nsnull);
-        printHelp();
-        return -1;
-    }
-
-    //-- handle output stream
-    ostream* resultOutput = &cout;
-    ofstream resultFileStream;
-
-    int argn = 1;
-    // skip -- gnu style options
-    while (argn < argc) {
-        nsDependentCString opt(argv[argn]);
-        if (!Substring(opt, 0, 2).EqualsLiteral("--")) {
-            break;
-        }
-        ++argn;
-    }
-    if (argn < argc) {
-        nsDependentCString opt(argv[argn]);
-        if (Substring(opt, 0, 2).EqualsLiteral("-o")) {
-            if (opt.Length() > 2) {
-                const nsAFlatCString& fname = 
-                    PromiseFlatCString(Substring(opt, 2, opt.Length()-2));
-                resultFileStream.open(fname.get(), ios::out);
-            }
-            else {
-                ++argn;
-                if (argn < argc) {
-                    resultFileStream.open(argv[argn], ios::out);
-                }
-            }
-            if (!resultFileStream) {
-                cerr << "error opening output file" << endl;
-                PRBool exists;
-                if (NS_SUCCEEDED(resFile->Exists(&exists)) && exists)
-                    resFile->Remove(PR_FALSE);
-                NS_ShutdownXPCOM(nsnull);
-                return -1;
-            }
-            ++argn;
-            resultOutput = &resultFileStream;
-        }
-    }
-
-    if (!txXSLTProcessor::init()) {
-        PRBool exists;
-        if (NS_SUCCEEDED(resFile->Exists(&exists)) && exists)
-            resFile->Remove(PR_FALSE);
-        NS_ShutdownXPCOM(nsnull);
-        return 1;
-    }
-
-    *resultOutput << "<?xml version=\"1.0\"?>\n" << 
-        "<RDF:RDF xmlns:NC=\"http://home.netscape.com/NC-rdf#\"\n" <<
-        "         xmlns:RDF=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">" << endl;
-
-    txRDFOut* rdfOut = new txRDFOut(resultOutput);
-    nsCOMPtr<nsIFile> tempFile;
-    if (argn < argc) {
-        // categories are specified
-        while (argn < argc) {
-            nsDependentCString cat(argv[argn++]);
-            rv = conf->AppendNative(cat);
-            if (NS_SUCCEEDED(rv)) {
-                rv = gold->AppendNative(cat);
-                if (NS_SUCCEEDED(rv)) {
-                    runCategory(conf, gold, resFile, rdfOut);
-                    rv = gold->GetParent(getter_AddRefs(tempFile));
-                    NS_ASSERTION(NS_SUCCEEDED(rv), "can't go back?");
-                    gold = tempFile;
-                }
-                rv = conf->GetParent(getter_AddRefs(tempFile));
-                NS_ASSERTION(NS_SUCCEEDED(rv), "can't go back?");
-                conf = tempFile;
-            }
-        }
-    }
-    else {
-        // no category specified, do everything
-        nsCOMPtr<nsISimpleEnumerator> cats;
-        rv = conf->GetDirectoryEntries(getter_AddRefs(cats));
-        PRBool hasMore, isDir;
-        nsCAutoString leaf;
-        while (NS_SUCCEEDED(cats->HasMoreElements(&hasMore)) && hasMore) {
-            nsCOMPtr<nsILocalFile> cat;
-            cats->GetNext(getter_AddRefs(cat));
-            rv = cat->IsDirectory(&isDir);
-            if (NS_SUCCEEDED(rv) && isDir) {
-                rv = cat->GetNativeLeafName(leaf);
-                if (NS_SUCCEEDED(rv) && 
-                    !leaf.EqualsLiteral("CVS")) {
-                    rv = gold->AppendNative(leaf);
-                    if (NS_SUCCEEDED(rv)) {
-                        runCategory(cat, gold, resFile, rdfOut);
-                        rv = gold->GetParent(getter_AddRefs(tempFile));
-                        gold = tempFile;
-                    }
-                }
-            }
-        }
-    }
-    delete rdfOut;
-    rdfOut = nsnull;
-    *resultOutput << "</RDF:RDF>" << endl;
-    PRBool exists;
-    if (NS_SUCCEEDED(resFile->Exists(&exists)) && exists)
-        resFile->Remove(PR_FALSE);
-    resultFileStream.close();
-    txXSLTProcessor::shutdown();
-    rv = NS_ShutdownXPCOM(nsnull);
-#ifdef NS_TRACE_MALLOC
-    NS_TraceMallocShutdown();
-#endif
-    NS_ENSURE_SUCCESS(rv, rv);
-    return 0;
-}
deleted file mode 100644
--- a/content/xslt/src/main/transformiix.cpp
+++ /dev/null
@@ -1,206 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* ***** 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 TransforMiiX XSLT processor code.
- *
- * The Initial Developer of the Original Code is
- * The MITRE Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1999
- * 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 "txStandaloneXSLTProcessor.h"
-#include "nsXPCOM.h"
-#include <fstream.h>
-#include "nsDoubleHashtable.h"
-#include "nsTArray.h"
-#ifdef MOZ_JPROF
-#include "jprof.h"
-#endif
-
-/**
- * Prints the command line help screen to the console
- */
-void printHelp()
-{
-  cerr << "transfrmx [-h] [-i xml-file] [-s xslt-file] [-o output-file]" << endl << endl;
-  cerr << "Options:";
-  cerr << endl << endl;
-  cerr << "\t-i  specify XML file to process" << endl;
-  cerr << "\t-s  specify XSLT file to use for processing (default: use stylesheet" << endl
-       << "\t\tspecified in XML file)" << endl;
-  cerr << "\t-o  specify output file (default: write to stdout)" << endl;
-  cerr << "\t-h  this help screen" << endl;
-  cerr << endl;
-  cerr << "You may use '-' in place of the output-file to explicitly specify" << endl;
-  cerr << "standard output." << endl;
-  cerr << endl;
-}
-
-/**
- * Prints the command line usage information to the console
- */
-void printUsage()
-{
-  cerr << "transfrmx [-h] [-i xml-file] [-s xslt-file] [-o output-file]" << endl << endl;
-  cerr << "For more infomation use the -h flag" << endl;
-}
-
-class txOptionEntry : public PLDHashCStringEntry
-{
-public:
-    txOptionEntry(const void* aKey) : PLDHashCStringEntry(aKey)
-    {
-    }
-    nsTArray<nsCString> mValues;
-};
-
-DECL_DHASH_WRAPPER(txOptions, txOptionEntry, nsACString&)
-DHASH_WRAPPER(txOptions, txOptionEntry, nsACString&)
-
-/**
- * Parses the command line
- */
-void parseCommandLine(int argc, char** argv, txOptions& aOptions)
-{
-    nsCAutoString flag;
-
-    for (int i = 1; i < argc; ++i) {
-        nsDependentCString arg(argv[i]);
-        if (*argv[i] == '-' && arg.Length() > 1) {
-            // clean up previous flag
-            if (!flag.IsEmpty()) {
-                aOptions.AddEntry(flag);
-                flag.Truncate();
-            }
-
-            // get next flag
-            flag = Substring(arg, 1, arg.Length() - 1);
-        }
-        else {
-            txOptionEntry* option = aOptions.AddEntry(flag);
-            if (option) {
-                option->mValues.AppendElement(nsCString(arg));
-            }
-            flag.Truncate();
-        }
-    }
-
-    if (!flag.IsEmpty()) {
-        aOptions.AddEntry(flag);
-    }
-}
-
-/**
- * The TransforMiiX command line interface
- */
-int main(int argc, char** argv)
-{
-    using namespace std;
-    nsresult rv;
-#ifdef MOZ_JPROF
-    setupProfilingStuff();
-#endif
-    rv = NS_InitXPCOM2(nsnull, nsnull, nsnull);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    if (!txXSLTProcessor::init())
-        return 1;
-
-    txOptions options;
-    if (NS_FAILED(options.Init(4))) {
-        return 1;
-    }
-    parseCommandLine(argc, argv, options);
-
-    if (!options.GetEntry(NS_LITERAL_CSTRING("q"))) {
-        NS_NAMED_LITERAL_CSTRING(copyright, "(C) 1999 The MITRE Corporation, Keith Visco, and contributors");
-        cerr << "TransforMiiX ";
-        cerr << MOZILLA_VERSION << endl;
-        cerr << copyright.get() << endl;
-        //-- print banner line
-        PRUint32 fillSize = copyright.Length() + 1;
-        PRUint32 counter;
-        for (counter = 0; counter < fillSize; ++counter)
-            cerr << '-';
-        cerr << endl << endl;
-    }
-
-    if (options.GetEntry(NS_LITERAL_CSTRING("h"))) {
-        printHelp();
-        return 0;
-    }
-
-    //-- handle output stream
-    ostream* resultOutput = &cout;
-    ofstream resultFileStream;
-
-    txOptionEntry* option = options.GetEntry(NS_LITERAL_CSTRING("o"));
-    if (option &&
-        option->mValues.Length() > 0 &&
-        !option->mValues[0].EqualsLiteral("-")) {
-        resultFileStream.open(option->mValues[0].get(), ios::out);
-        if (!resultFileStream) {
-            cerr << "error opening output file: ";
-            cerr << option->mValues[0].get() << endl;
-            return -1;
-        }
-        resultOutput = &resultFileStream;
-    }
-
-    option = options.GetEntry(NS_LITERAL_CSTRING("i"));
-    if (!option || option->mValues.Length() == 0) {
-        cerr << "you must specify at least a source XML path" << endl;
-        printUsage();
-        return -1;
-    }
-
-    SimpleErrorObserver obs;
-    txStandaloneXSLTProcessor proc;
-
-    txOptionEntry* styleOption = options.GetEntry(NS_LITERAL_CSTRING("s"));
-    if (!styleOption || styleOption->mValues.Length() == 0) {
-        rv = proc.transform(option->mValues[0], *resultOutput, obs);
-    }
-    else {
-        // XXX TODO: Handle multiple stylesheets
-        rv = proc.transform(option->mValues[0], styleOption->mValues[0],
-                            *resultOutput, obs);
-    }
-
-    if (NS_FAILED(rv)) {
-        cerr << "transformation failed with " << hex << rv << endl;
-    }
-
-    resultFileStream.close();
-    txXSLTProcessor::shutdown();
-    rv = NS_ShutdownXPCOM(nsnull);
-    NS_ENSURE_SUCCESS(rv, rv);
-    return 0;
-}
deleted file mode 100644
--- a/content/xslt/src/main/txTestExpr.cpp
+++ /dev/null
@@ -1,146 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* ***** 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 TransforMiiX XSLT processor code.
- *
- * The Initial Developer of the Original Code is
- * Axel Hecht.
- * Portions created by the Initial Developer are Copyright (C) 2003
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Axel Hecht <axel@pike.org>
- *
- * 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 "nsXPCOM.h"
-#include "txStandaloneXSLTProcessor.h"
-#include "nsString.h"
-#include "nsTArray.h"
-#include "txExprParser.h"
-#include "txIXPathContext.h"
-
-/**
- * A ExprParser test exe
- */
-
-static const char* kTokens[] = {"(", "concat", "(", "foo", ",", "'", "bar",
-                                "'",")", "//", ".", "[", "preceding-sibling",
-                                "::", "bar", "]", "/", "*", "[", "23", "]",
-                                "|", "node", "(", ")", ")", "<", "3"};
-static const PRUint8 kCount = sizeof(kTokens)/sizeof(char*);
-
-class ParseContextImpl : public txIParseContext
-{
-public:
-    nsresult
-    resolveNamespacePrefix(nsIAtom* aPrefix, PRInt32& aID)
-    {
-        return NS_ERROR_FAILURE;
-    }
-    nsresult
-    resolveFunctionCall(nsIAtom* aName, PRInt32 aID, FunctionCall** aFunction)
-    {
-        return NS_ERROR_XPATH_UNKNOWN_FUNCTION;
-    }
-    PRBool
-    caseInsensitiveNameTests()
-    {
-        return PR_FALSE;
-    }
-    void
-    SetErrorOffset(PRUint32 aOffset)
-    {
-        mOff = aOffset;
-    }
-    PRUint32 mOff;
-};
-
-static void doTest(const nsASingleFragmentString& aExpr)
-{
-    ParseContextImpl ct;
-    nsAutoPtr<Expr> expression;
-    cout << NS_LossyConvertUTF16toASCII(aExpr).get() << endl;
-    ct.mOff = 0;
-    nsresult rv = txExprParser::createExpr(aExpr, &ct,
-                                           getter_Transfers(expression));
-
-    cout << "createExpr returned " << ios::hex << rv  << ios::dec;
-    cout << " at " << ct.mOff << endl;
-    if (NS_FAILED(rv)) {
-        NS_LossyConvertUTF16toASCII cstring(aExpr);
-        cout << NS_LossyConvertUTF16toASCII(StringHead(aExpr, ct.mOff)).get();
-        cout << " ^ ";
-        cout << NS_LossyConvertUTF16toASCII(StringTail(aExpr, aExpr.Length()-ct.mOff)).get();
-        cout << endl << endl;
-    }
-#ifdef TX_TO_STRING
-    else {
-        nsAutoString expr;
-        expression->toString(expr);
-        cout << "parsed expression: ";
-        cout << NS_LossyConvertUTF16toASCII(expr).get() << endl << endl;
-    }
-#endif
-}
-
-int main(int argc, char** argv)
-{
-    using namespace std;
-    nsresult rv = NS_InitXPCOM2(nsnull, nsnull, nsnull);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    if (!txXSLTProcessor::init())
-        return 1;
-
-    nsAutoString exprOrig, expr;
-    nsTArray<nsString> exprHead, exprTail;
-    PRUint8 i, dropStart, dropEnd;
-    exprHead.AppendElement(NS_ConvertASCIItoUTF16(kTokens[0]));
-    exprTail.AppendiElement(NS_ConvertASCIItoUTF16(kTokens[kCount - 1]));
-    for (i = 2; i < kCount; ++i) {
-        exprHead.AppendElement(exprHead[i - 2] +
-                              NS_ConvertASCIItoUTF16(kTokens[i - 1]));
-        exprTail.AppendElement(NS_ConvertASCIItoUTF16(kTokens[kCount - i]) +
-                              exprTail[i - 2]);
-    }
-    exprOrig = NS_ConvertASCIItoUTF16(kTokens[0]) + exprTail[kCount - 2];
-    cout << NS_LossyConvertUTF16toASCII(exprOrig).get() << endl << endl;
-    for (dropStart = 0; dropStart < kCount - 2; ++dropStart) {
-        doTest(exprTail[kCount - 2 - dropStart]);
-        for (dropEnd = kCount - 3 - dropStart; dropEnd > 0; --dropEnd) {
-            expr = exprHead[dropStart] + exprTail[dropEnd];
-            doTest(expr);
-        }
-        doTest(exprHead[dropStart]);
-    }
-    doTest(exprHead[kCount - 2]);
-
-    txXSLTProcessor::shutdown();
-    rv = NS_ShutdownXPCOM(nsnull);
-    NS_ENSURE_SUCCESS(rv, rv);
-    return 0;
-}
deleted file mode 100644
--- a/content/xslt/src/main/txXSLTMarkDriver.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* ***** 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 TransforMiiX XSLT processor code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 2002
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Axel Hecht <axel@pike.org> (Original Author)
- *
- * 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 ***** */
-
-/**
- * Driver for running XSLTMark on standalone
- *
- * See http://www.datapower.com/XSLTMark/
- */
-
-#include "txStandaloneStylesheetCompiler.h"
-#include "txStandaloneXSLTProcessor.h"
-#include "nsXPCOM.h"
-#include "xmExternalDriver.hpp"
-#ifdef MOZ_JPROF
-#include "jprof.h"
-#endif
-
-class txDriverProcessor : public txStandaloneXSLTProcessor,
-                          public xmExternalDriver
-{
-public:
-    txDriverProcessor() : mXML(0), mOut(0)
-    {
-    }
-
-    int loadStylesheet (char * filename)
-    {
-        txParsedURL url;
-        url.init(NS_ConvertASCIItoUTF16(filename));
-        nsresult rv =
-            TX_CompileStylesheetPath(url, getter_AddRefs(mStylesheet));
-        return NS_SUCCEEDED(rv) ? 0 : 1;
-    }
-    int setInputDocument (char * filename)
-    {
-        delete mXML;
-        mXML = parsePath(nsDependentCString(filename), mObserver);
-        return mXML ? 0 : 1;
-    }
-    int openOutput (char * outputFilename)
-    {
-        mOut = new ofstream(outputFilename);
-        return mXML ? 0 : 1;
-    }
-    int runTransform ()
-    {
-        if (!mXML || !mStylesheet || !mOut)
-            return 1;
-        nsresult rv = transform(*mXML, mStylesheet, *mOut, mObserver);
-        return NS_FAILED(rv);
-    }
-    int closeOutput ()
-    {
-        if (mOut)
-            mOut->close();
-        delete mOut;
-        mOut = 0;
-        return 0;
-    }
-    int terminate()
-    {
-        delete mXML;
-        mXML = 0;
-        if (mOut && mOut->is_open())
-            mOut->close();
-        delete mOut;
-        mOut = 0;
-        mStylesheet = 0;
-        return 0;
-    }
-    ~txDriverProcessor()
-    {
-        delete mXML;
-        delete mOut;
-    }
-private:
-    txXPathNode *mXML;
-    nsRefPtr<txStylesheet> mStylesheet;
-    SimpleErrorObserver mObserver;
-    ofstream* mOut;
-};
-
-int main (int argc, char ** argv)
-{
-    txDriverProcessor driver;
-#ifdef MOZ_JPROF
-    setupProfilingStuff();
-#endif
-    NS_InitXPCOM2(nsnull, nsnull, nsnull);
-    if (!txDriverProcessor::init())
-        return 1;
-    driver.main (argc, argv);
-    txDriverProcessor::shutdown();
-    NS_ShutdownXPCOM(nsnull);
-    return 0;
-}
--- a/content/xslt/src/xml/Makefile.in
+++ b/content/xslt/src/xml/Makefile.in
@@ -41,33 +41,21 @@ srcdir          = @srcdir@
 VPATH           = @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE = transformiix
 LIBRARY_NAME = txxml_s
 LIBXUL_LIBRARY = 1
 
-
-
 CPPSRCS	= \
 	txXMLUtils.cpp \
 	txXMLParser.cpp \
 	$(NULL)
 
-ifdef MOZ_XSLT_STANDALONE
-CPPSRCS += \
-	txAttr.cpp \
-	txDocument.cpp \
-	txElement.cpp \
-	txNodeDefinition.cpp \
-	txProcessingInstruction.cpp \
-	$(NULL)
-endif
-
 # we don't want the shared lib, but we want to force the creation of a
 # static lib.
 FORCE_STATIC_LIB = 1
 
 include $(topsrcdir)/config/rules.mk
 
 INCLUDES += \
 	-I$(srcdir)/../base \
deleted file mode 100644
--- a/content/xslt/src/xml/txAttr.cpp
+++ /dev/null
@@ -1,113 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is TransforMiiX XSLT processor code.
- *
- * The Initial Developer of the Original Code is
- * The MITRE Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1999
- * 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 ***** */
-
-// Tom Kneeland (3/29/99)
-//
-//  Implementation of the Document Object Model Level 1 Core
-//    Implementation of the Attr class
-//
-
-#include "txDOM.h"
-#include "txAtoms.h"
-#include "txXMLUtils.h"
-
-Attr::Attr(nsIAtom *aPrefix, nsIAtom *aLocalName, PRInt32 aNamespaceID,
-           Element *aOwnerElement, const nsAString &aValue) :
-    NodeDefinition(Node::ATTRIBUTE_NODE, aLocalName, aValue,
-                   aOwnerElement->getOwnerDocument()),
-    mPrefix(aPrefix),
-    mNamespaceID(aNamespaceID),
-    mOwnerElement(aOwnerElement)
-{
-}
-
-//
-//Not implemented anymore, return null as an error.
-//
-Node* Attr::appendChild(Node* newChild)
-{
-  NS_ERROR("not implemented");
-  return nsnull;
-}
-
-nsresult
-Attr::getNodeName(nsAString& aName) const
-{
-  if (mPrefix) {
-    mPrefix->ToString(aName);
-    aName.Append(PRUnichar(':'));
-  }
-  else {
-    aName.Truncate();
-  }
-
-  const char* ASCIIAtom;
-  mLocalName->GetUTF8String(&ASCIIAtom);
-  AppendUTF8toUTF16(ASCIIAtom, aName);
-
-  return NS_OK;
-}
-
-//
-//Return the attributes local (unprefixed) name atom.
-//
-MBool Attr::getLocalName(nsIAtom** aLocalName)
-{
-  if (!aLocalName)
-    return MB_FALSE;
-  *aLocalName = mLocalName;
-  NS_ADDREF(*aLocalName);
-  return MB_TRUE;
-}
-
-//
-//Return the namespace the attribute belongs to. If the attribute doesn't
-//have a prefix it doesn't belong to any namespace per the namespace spec,
-//and is handled in the constructor.
-//
-PRInt32 Attr::getNamespaceID()
-{
-  return mNamespaceID;
-}
-
-//
-//Return the attributes owning element
-//
-Node* Attr::getXPathParent()
-{
-  return mOwnerElement;
-}
deleted file mode 100644
--- a/content/xslt/src/xml/txDocument.cpp
+++ /dev/null
@@ -1,177 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is TransforMiiX XSLT processor code.
- *
- * The Initial Developer of the Original Code is
- * The MITRE Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1999
- * 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 ***** */
-
-// Tom Kneeland (3/29/99)
-//
-//  Implementation of the Document Object Model Level 1 Core
-//    Implementation of the Document class
-//
-// Modification History:
-// Who  When        What
-// TK   03/29/99    Created
-// LF   08/06/1999  Removed Default argument initializer from
-//                  Document() constructor
-// LF   08/06/1999  fixed typo: defalut to default
-//
-
-#include "txDOM.h"
-#include "txAtoms.h"
-
-//
-//Construct a Document.  Currently no parameters are required, but the the
-//node constructor is called to identify the node type.
-//
-Document::Document() :
-  NodeDefinition(Node::DOCUMENT_NODE, txXMLAtoms::document, EmptyString(),
-                 nsnull),
-  documentElement(nsnull)
-{
-  mIDMap.Init(0);
-}
-
-//
-//Return the one and only element for this document
-//
-Element* Document::getDocumentElement()
-{
-  return documentElement;
-}
-
-Element*
-Document::createElementNS(nsIAtom *aPrefix, nsIAtom *aLocalName,
-                          PRInt32 aNamespaceID)
-{
-  return new Element(aPrefix, aLocalName, aNamespaceID, this);
-}
-
-//
-//Construct a text node with the given data
-//
-Node* Document::createTextNode(const nsAString& theData)
-{
-  return new NodeDefinition(Node::TEXT_NODE, txXMLAtoms::text, theData, this);
-}
-
-//
-//Construct a comment node with the given data
-//
-Node* Document::createComment(const nsAString& theData)
-{
-  return new NodeDefinition(Node::COMMENT_NODE, txXMLAtoms::comment, theData,
-                            this);
-}
-
-//
-//Construct a ProcessingInstruction node with the given targe and data.
-//
-ProcessingInstruction*
-  Document::createProcessingInstruction(nsIAtom *aTarget,
-                                        const nsAString& data)
-{
-  return new ProcessingInstruction(aTarget, data, this);
-}
-
-//
-//Return an Element by ID, introduced by DOM2
-//
-DHASH_WRAPPER(txIDMap, txIDEntry, nsAString&)
-
-Element* Document::getElementById(const nsAString& aID)
-{
-  txIDEntry* entry = mIDMap.GetEntry(aID);
-  if (entry)
-    return entry->mElement;
-  return nsnull;
-}
-
-/**
- * private setter for element ID
- */
-PRBool
-Document::setElementID(const nsAString& aID, Element* aElement)
-{
-  txIDEntry* id = mIDMap.AddEntry(aID);
-  // make sure IDs are unique
-  if (id->mElement) {
-    return PR_FALSE;
-  }
-  id->mElement = aElement;
-  id->mElement->setIDValue(aID);
-  return PR_TRUE;
-}
-
-Node* Document::appendChild(Node* newChild)
-{
-  unsigned short nodeType = newChild->getNodeType();
-
-  // Convert to a NodeDefinition Pointer
-  NodeDefinition* pNewChild = (NodeDefinition*)newChild;
-
-  if (pNewChild->parentNode == this)
-    {
-      pNewChild = implRemoveChild(pNewChild);
-      if (nodeType == Node::ELEMENT_NODE)
-        documentElement = nsnull;
-    }
-
-  switch (nodeType)
-    {
-      case Node::PROCESSING_INSTRUCTION_NODE :
-      case Node::COMMENT_NODE :
-      case Node::DOCUMENT_TYPE_NODE :
-        return implAppendChild(pNewChild);
-
-      case Node::ELEMENT_NODE :
-        if (!documentElement)
-          {
-            Node* returnVal = implAppendChild(pNewChild);
-            documentElement = (Element*)pNewChild;
-            return returnVal;
-          }
-
-      default:
-        break;
-    }
-
-  return nsnull;
-}
-
-nsresult Document::getBaseURI(nsAString& aURI)
-{
-  aURI = documentBaseURI;
-  return NS_OK;
-}
deleted file mode 100644
--- a/content/xslt/src/xml/txElement.cpp
+++ /dev/null
@@ -1,200 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is TransforMiiX XSLT processor code.
- *
- * The Initial Developer of the Original Code is
- * The MITRE Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1999
- * 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 ***** */
-
-// Tom Kneeland (3/29/99)
-//
-//  Implementation of the Document Object Model Level 1 Core
-//    Implementation of the Element class
-//
-
-#include "txDOM.h"
-#include "txAtoms.h"
-#include "txXMLUtils.h"
-
-Element::Element(nsIAtom *aPrefix, nsIAtom *aLocalName, PRInt32 aNamespaceID,
-                 Document* aOwner) :
-  NodeDefinition(Node::ELEMENT_NODE, aLocalName, EmptyString(), aOwner),
-  mPrefix(aPrefix),
-  mNamespaceID(aNamespaceID)
-{
-}
-
-Node* Element::appendChild(Node* newChild)
-{
-  switch (newChild->getNodeType())
-    {
-      case Node::ELEMENT_NODE :
-      case Node::TEXT_NODE :
-      case Node::COMMENT_NODE :
-      case Node::PROCESSING_INSTRUCTION_NODE :
-        {
-          // Remove the "newChild" if it is already a child of this node
-          NodeDefinition* pNewChild = (NodeDefinition*)newChild;
-          if (pNewChild->getParentNode() == this)
-            pNewChild = implRemoveChild(pNewChild);
-
-          return implAppendChild(pNewChild);
-        }
-
-      default:
-        break;
-    }
-
-  return nsnull;
-}
-
-nsresult
-Element::getNodeName(nsAString& aName) const
-{
-  if (mPrefix) {
-    mPrefix->ToString(aName);
-    aName.Append(PRUnichar(':'));
-  }
-  else {
-    aName.Truncate();
-  }
-
-  const char* ASCIIAtom;
-  mLocalName->GetUTF8String(&ASCIIAtom);
-  AppendUTF8toUTF16(ASCIIAtom, aName);
-
-  return NS_OK;
-}
-
-//
-//Return the elements local (unprefixed) name.
-//
-MBool Element::getLocalName(nsIAtom** aLocalName)
-{
-  if (!aLocalName)
-    return MB_FALSE;
-  *aLocalName = mLocalName;
-  NS_ADDREF(*aLocalName);
-  return MB_TRUE;
-}
-
-//
-//Return the namespace the elements belongs to.
-//
-PRInt32 Element::getNamespaceID()
-{
-  return mNamespaceID;
-}
-
-nsresult
-Element::appendAttributeNS(nsIAtom *aPrefix, nsIAtom *aLocalName,
-                           PRInt32 aNamespaceID, const nsAString& aValue)
-{
-  nsAutoPtr<Attr> newAttribute;
-  newAttribute = new Attr(aPrefix, aLocalName, aNamespaceID, this, aValue);
-  if (!newAttribute) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
-  if (mFirstAttribute) {
-    Attr *lastAttribute = mFirstAttribute;
-    while (lastAttribute->mNextAttribute) {
-      lastAttribute = lastAttribute->mNextAttribute;
-    }
-    lastAttribute->mNextAttribute = newAttribute;
-  }
-  else {
-    mFirstAttribute = newAttribute;
-  }
-
-  return NS_OK;
-}
-
-//
-// Return true if the attribute specified by localname and nsID
-// exists, and sets aValue to the value of the attribute.
-// Return false, if the attribute does not exist.
-//
-MBool Element::getAttr(nsIAtom* aLocalName, PRInt32 aNSID,
-                       nsAString& aValue)
-{
-  aValue.Truncate();
-  Attr *attribute = mFirstAttribute;
-  while (attribute) {
-    if (attribute->equals(aLocalName, aNSID)) {
-      attribute->getNodeValue(aValue);
-
-      return PR_TRUE;
-    }
-
-    attribute = attribute->mNextAttribute;
-  }
-
-  return PR_FALSE;
-}
-
-//
-// Return true if the attribute specified by localname and nsID
-// exists. Return false otherwise.
-//
-MBool Element::hasAttr(nsIAtom* aLocalName, PRInt32 aNSID)
-{
-  Attr *attribute = mFirstAttribute;
-  while (attribute) {
-    if (attribute->equals(aLocalName, aNSID)) {
-      return PR_TRUE;
-    }
-
-    attribute = attribute->mNextAttribute;
-  }
-
-  return PR_FALSE;
-}
-
-/**
- * ID accessors. Getter used for id() patterns, private setter for parser
- */
-PRBool
-Element::getIDValue(nsAString& aValue)
-{
-  if (mIDValue.IsEmpty()) {
-    return PR_FALSE;
-  }
-  aValue = mIDValue;
-  return PR_TRUE;
-}
-
-void
-Element::setIDValue(const nsAString& aValue)
-{
-  mIDValue = aValue;
-}
deleted file mode 100644
--- a/content/xslt/src/xml/txNodeDefinition.cpp
+++ /dev/null
@@ -1,378 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is TransforMiiX XSLT processor code.
- *
- * The Initial Developer of the Original Code is
- * The MITRE Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1999
- * 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 ***** */
-
-// Tom Kneeland (3/29/99)
-//
-//  Implementation of the Document Object Model Level 1 Core
-//    Implementation of the NodeDefinition Class
-//
-// Modification History:
-// Who  When      What
-// TK   03/29/99  Created
-//
-
-#include "txDOM.h"
-#include "nsTArray.h"
-#include "txURIUtils.h"
-#include "txAtoms.h"
-#include <string.h>
-
-NodeDefinition::NodeDefinition(NodeType type, nsIAtom *aLocalName,
-                               const nsAString& value, Document* owner) :
-    mLocalName(aLocalName),
-    nodeValue(value),
-    nodeType(type),
-    parentNode(nsnull),
-    previousSibling(nsnull),
-    nextSibling(nsnull),
-    ownerDocument(owner),
-    length(0),
-    firstChild(nsnull),
-    lastChild(nsnull),
-    mOrderInfo(nsnull)
-{
-}
-
-//
-// This node is being destroyed, so loop through and destroy all the children.
-//
-NodeDefinition::~NodeDefinition()
-{
-  NodeDefinition* pCurrent = firstChild;
-  NodeDefinition* pDestroyer;
-
-  while (pCurrent)
-    {
-      pDestroyer = pCurrent;
-      pCurrent = pCurrent->nextSibling;
-      delete pDestroyer;
-    }
-
-  delete mOrderInfo;
-}
-
-nsresult NodeDefinition::getNodeName(nsAString& aName) const
-{
-  mLocalName->ToString(aName);
-  return NS_OK;
-}
-
-nsresult NodeDefinition::getNodeValue(nsAString& aValue)
-{
-  aValue = nodeValue;
-  return NS_OK;
-}
-
-unsigned short NodeDefinition::getNodeType() const
-{
-  return nodeType;
-}
-
-Node* NodeDefinition::getParentNode() const
-{
-  return parentNode;
-}
-
-Node* NodeDefinition::getFirstChild() const
-{
-  return firstChild;
-}
-
-Node* NodeDefinition::getLastChild() const
-{
-  return lastChild;
-}
-
-Node* NodeDefinition::getPreviousSibling() const
-{
-  return previousSibling;
-}
-
-Node* NodeDefinition::getNextSibling() const
-{
-  return nextSibling;
-}
-
-Document* NodeDefinition::getOwnerDocument() const
-{
-  return ownerDocument;
-}
-
-Node* NodeDefinition::appendChild(Node* newChild)
-{
-  return nsnull;
-}
-
-NodeDefinition* NodeDefinition::implAppendChild(NodeDefinition* newChild)
-{
-  // The new child should not be a child of any other node
-  if (!newChild->previousSibling && !newChild->nextSibling &&
-      !newChild->parentNode)
-    {
-      newChild->previousSibling = lastChild;
-
-      if (lastChild)
-        lastChild->nextSibling = newChild;
-
-      lastChild = newChild;
-
-      newChild->parentNode = this;
-
-      if (!newChild->previousSibling)
-        firstChild = newChild;
-
-      ++length;
-
-      return newChild;
-    }
-
-  return nsnull;
-}
-
-NodeDefinition* NodeDefinition::implRemoveChild(NodeDefinition* oldChild)
-{
-  if (oldChild != firstChild)
-    oldChild->previousSibling->nextSibling = oldChild->nextSibling;
-  else
-    firstChild = oldChild->nextSibling;
-
-  if (oldChild != lastChild)
-    oldChild->nextSibling->previousSibling = oldChild->previousSibling;
-  else
-    lastChild = oldChild->previousSibling;
-
-  oldChild->nextSibling = nsnull;
-  oldChild->previousSibling = nsnull;
-  oldChild->parentNode = nsnull;
-
-  --length;
-
-  return oldChild;
-}
-
-MBool NodeDefinition::hasChildNodes() const
-{
-  if (firstChild)
-    return MB_TRUE;
-  else
-    return MB_FALSE;
-}
-
-MBool NodeDefinition::getLocalName(nsIAtom** aLocalName)
-{
-  if (!aLocalName)
-    return MB_FALSE;
-  *aLocalName = 0;
-  return MB_TRUE;
-}
-
-nsresult NodeDefinition::getNamespaceURI(nsAString& aNSURI)
-{
-  return txStandaloneNamespaceManager::getNamespaceURI(getNamespaceID(),
-                                                       aNSURI);
-}
-
-PRInt32 NodeDefinition::getNamespaceID()
-{
-  return kNameSpaceID_None;
-}
-
-Node* NodeDefinition::getXPathParent()
-{
-  return parentNode;
-}
-
-//
-// Returns the base URI of the node. Acccounts for xml:base
-// attributes.
-//
-// @return base URI for the node
-//
-nsresult NodeDefinition::getBaseURI(nsAString& aURI)
-{
-  Node* node = this;
-  nsTArray<nsString> baseUrls;
-  nsAutoString url;
-
-  while (node) {
-    switch (node->getNodeType()) {
-      case Node::ELEMENT_NODE :
-        if (((Element*)node)->getAttr(txXMLAtoms::base, kNameSpaceID_XML,
-                                      url))
-          baseUrls.AppendElement(url);
-        break;
-
-      case Node::DOCUMENT_NODE :
-        node->getBaseURI(url);
-        baseUrls.AppendElement(url);
-        break;
-    
-      default:
-        break;
-    }
-    node = node->getXPathParent();
-  }
-
-  PRUint32 count = baseUrls.Length();
-  if (count) {
-    aURI = baseUrls[--count];
-
-    while (count > 0) {
-      nsAutoString dest;
-      URIUtils::resolveHref(baseUrls[--count], aURI, dest);
-      aURI = dest;
-    }
-  }
-  
-  return NS_OK;
-} // getBaseURI
-
-/*
- * Compares document position of this node relative to another node
- */
-PRInt32 NodeDefinition::compareDocumentPosition(Node* aOther)
-{
-  OrderInfo* myOrder = getOrderInfo();
-  OrderInfo* otherOrder = ((NodeDefinition*)aOther)->getOrderInfo();
-  if (!myOrder || !otherOrder)
-      return -1;
-
-  if (myOrder->mRoot == otherOrder->mRoot) {
-    int c = 0;
-    while (c < myOrder->mSize && c < otherOrder->mSize) {
-      if (myOrder->mOrder[c] < otherOrder->mOrder[c])
-        return -1;
-      if (myOrder->mOrder[c] > otherOrder->mOrder[c])
-        return 1;
-      ++c;
-    }
-    if (c < myOrder->mSize)
-      return 1;
-    if (c < otherOrder->mSize)
-      return -1;
-    return 0;
-  }
-
-  if (myOrder->mRoot < otherOrder->mRoot)
-    return -1;
-
-  return 1;
-}
-
-/*
- * Get order information for node
- */
-NodeDefinition::OrderInfo* NodeDefinition::getOrderInfo()
-{
-  if (mOrderInfo)
-    return mOrderInfo;
-
-  mOrderInfo = new OrderInfo;
-  if (!mOrderInfo)
-    return 0;
-
-  Node* parent = getXPathParent();
-  if (!parent) {
-    mOrderInfo->mOrder = 0;
-    mOrderInfo->mSize = 0;
-    mOrderInfo->mRoot = this;
-    return mOrderInfo;
-  }
-
-  OrderInfo* parentOrder = ((NodeDefinition*)parent)->getOrderInfo();
-  mOrderInfo->mSize = parentOrder->mSize + 1;
-  mOrderInfo->mRoot = parentOrder->mRoot;
-  mOrderInfo->mOrder = new PRUint32[mOrderInfo->mSize];
-  if (!mOrderInfo->mOrder) {
-    delete mOrderInfo;
-    mOrderInfo = 0;
-    return 0;
-  }
-  memcpy(mOrderInfo->mOrder,
-         parentOrder->mOrder,
-         parentOrder->mSize * sizeof(PRUint32*));
-
-  // Get childnumber of this node
-  int lastElem = parentOrder->mSize;
-  switch (getNodeType()) {
-    case Node::ATTRIBUTE_NODE:
-    {
-      NS_ASSERTION(parent->getNodeType() == Node::ELEMENT_NODE,
-                   "parent to attribute is not an element");
-
-      Element* elem = (Element*)parent;
-      Attr *attribute = elem->getFirstAttribute();
-      PRUint32 i = 0;
-      while (attribute) {
-        if (attribute == this) {
-          mOrderInfo->mOrder[lastElem] = i + kTxAttrIndexOffset;
-          return mOrderInfo;
-        }
-        attribute = attribute->getNextAttribute();
-        ++i;
-      }
-      break;
-    }
-    // XXX Namespace: need to take care of namespace nodes here
-    default:
-    {
-      PRUint32 i = 0;
-      Node * child = parent->getFirstChild();
-      while (child) {
-        if (child == this) {
-          mOrderInfo->mOrder[lastElem] = i + kTxChildIndexOffset;
-          return mOrderInfo;
-        }
-        ++i;
-        child = child->getNextSibling();
-      }
-      break;
-    }
-  }
-
-  NS_ERROR("unable to get childnumber");
-  mOrderInfo->mOrder[lastElem] = 0;
-  return mOrderInfo;
-}
-
-/*
- * OrderInfo destructor
- */
-NodeDefinition::OrderInfo::~OrderInfo()
-{
-    delete [] mOrder;
-}
deleted file mode 100644
--- a/content/xslt/src/xml/txProcessingInstruction.cpp
+++ /dev/null
@@ -1,73 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is TransforMiiX XSLT processor code.
- *
- * The Initial Developer of the Original Code is
- * The MITRE Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1999
- * 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 ***** */
-
-// Tom Kneeland (3/29/99)
-//
-//  Implementation of the Document Object Model Level 1 Core
-//    Implementation of the ProcessingInstruction class
-//
-// Modification History:
-// Who  When      What
-// TK   03/29/99  Created
-//
-
-#include "txDOM.h"
-#include "nsIAtom.h"
-
-//
-//Construct a text object with the specified document owner and data
-//
-ProcessingInstruction::ProcessingInstruction(nsIAtom *theTarget,
-                                             const nsAString& theData,
-                                             Document* owner) :
-  NodeDefinition(Node::PROCESSING_INSTRUCTION_NODE, theTarget, theData, owner)
-{
-}
-
-//
-//ProcessingInstruction nodes can not have any children, so just return null
-//from all child manipulation functions.
-//
-
-MBool ProcessingInstruction::getLocalName(nsIAtom** aLocalName)
-{
-  if (!aLocalName)
-    return MB_FALSE;
-  *aLocalName = mLocalName;
-  NS_ADDREF(*aLocalName);
-  return MB_TRUE;
-}
--- a/content/xslt/src/xml/txXMLParser.cpp
+++ b/content/xslt/src/xml/txXMLParser.cpp
@@ -35,68 +35,28 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "txXMLParser.h"
 #include "txURIUtils.h"
 #include "txXPathTreeWalker.h"
 
-#ifndef TX_EXE
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsSyncLoadService.h"
 #include "nsNetUtil.h"
 #include "nsIPrincipal.h"
-#else
-#include "expat_config.h"
-#include "expat.h"
-#include "txXMLUtils.h"
-#endif
-
-#ifdef TX_EXE
-/**
- *  Implementation of an In-Memory DOM based XML parser.  The actual XML
- *  parsing is provided by EXPAT.
- */
-class txXMLParser
-{
-  public:
-    nsresult parse(istream& aInputStream, const nsAString& aUri,
-                   txXPathNode** aResultDoc);
-    const nsAString& getErrorString();
-
-    /**
-     * Expat handlers
-     */
-    int StartElement(const XML_Char *aName, const XML_Char **aAtts);
-    int EndElement(const XML_Char* aName);
-    void CharacterData(const XML_Char* aChars, int aLength);
-    void Comment(const XML_Char* aChars);
-    int ProcessingInstruction(const XML_Char *aTarget, const XML_Char *aData);
-    int ExternalEntityRef(const XML_Char *aContext, const XML_Char *aBase,
-                          const XML_Char *aSystemId,
-                          const XML_Char *aPublicId);
-
-  protected:
-    void createErrorString();
-    nsString  mErrorString;
-    Document* mDocument;
-    Node*  mCurrentNode;
-    XML_Parser mExpatParser;
-};
-#endif
 
 nsresult
 txParseDocumentFromURI(const nsAString& aHref, const txXPathNode& aLoader,
                        nsAString& aErrMsg, txXPathNode** aResult)
 {
     NS_ENSURE_ARG_POINTER(aResult);
     *aResult = nsnull;
-#ifndef TX_EXE
     nsCOMPtr<nsIURI> documentURI;
     nsresult rv = NS_NewURI(getter_AddRefs(documentURI), aHref);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsIDocument* loaderDocument = txXPathNativeNode::getDocument(aLoader);
 
     nsCOMPtr<nsILoadGroup> loadGroup = loaderDocument->GetDocumentLoadGroup();
 
@@ -118,316 +78,9 @@ txParseDocumentFromURI(const nsAString& 
 
     *aResult = txXPathNativeNode::createXPathNode(theDocument);
     if (!*aResult) {
         NS_RELEASE(theDocument);
         return NS_ERROR_FAILURE;
     }
 
     return NS_OK;
-#else
-    istream* xslInput = URIUtils::getInputStream(aHref, aErrMsg);
-    if (!xslInput) {
-        return NS_ERROR_FAILURE;
-    }
-    return txParseFromStream(*xslInput, aHref, aErrMsg, aResult);
-#endif
 }
-
-#ifdef TX_EXE
-nsresult
-txParseFromStream(istream& aInputStream, const nsAString& aUri,
-                  nsAString& aErrorString, txXPathNode** aResult)
-{
-    NS_ENSURE_ARG_POINTER(aResult);
-    txXMLParser parser;
-    nsresult rv = parser.parse(aInputStream, aUri, aResult);
-    aErrorString = parser.getErrorString();
-    return rv;
-}
-
-/**
- * expat C stub handlers
- */
-
-// shortcut macro for redirection into txXMLParser method calls
-#define TX_XMLPARSER(_userData) static_cast<txXMLParser*>(_userData)
-#define TX_ENSURE_DATA(_userData)                       \
-  PR_BEGIN_MACRO                                        \
-    if (!aUserData) {                                   \
-        NS_WARNING("no userData in comment handler");   \
-        return;                                         \
-    }                                                   \
-  PR_END_MACRO
-
-static void
-startElement(void *aUserData, const XML_Char *aName, const XML_Char **aAtts)
-{
-    TX_ENSURE_DATA(aUserData);
-    TX_XMLPARSER(aUserData)->StartElement(aName, aAtts);
-}
-
-static void
-endElement(void *aUserData, const XML_Char* aName)
-{
-    TX_ENSURE_DATA(aUserData);
-    TX_XMLPARSER(aUserData)->EndElement(aName);
-}
-
-static void
-charData(void* aUserData, const XML_Char* aChars, int aLength)
-{
-    TX_ENSURE_DATA(aUserData);
-    TX_XMLPARSER(aUserData)->CharacterData(aChars, aLength);
-}
-
-static void
-commentHandler(void* aUserData, const XML_Char* aChars)
-{
-    TX_ENSURE_DATA(aUserData);
-    TX_XMLPARSER(aUserData)->Comment(aChars);
-}
-
-static void
-piHandler(void *aUserData, const XML_Char *aTarget, const XML_Char *aData)
-{
-    TX_ENSURE_DATA(aUserData);
-    TX_XMLPARSER(aUserData)->ProcessingInstruction(aTarget, aData);
-}
-
-static int
-externalEntityRefHandler(XML_Parser aParser,
-                         const XML_Char *aContext,
-                         const XML_Char *aBase,
-                         const XML_Char *aSystemId,
-                         const XML_Char *aPublicId)
-{
-    // aParser is aUserData is the txXMLParser,
-    // we set that in txXMLParser::parse
-    NS_ENSURE_TRUE(aParser, XML_ERROR_NONE);
-    return ((txXMLParser*)aParser)->ExternalEntityRef(aContext, aBase,
-                                                      aSystemId, aPublicId);
-}
-
-
-/**
- *  Parses the given input stream and returns a DOM Document.
- *  A NULL pointer will be returned if errors occurred
- */
-nsresult
-txXMLParser::parse(istream& aInputStream, const nsAString& aUri,
-                   txXPathNode** aResultDoc)
-{
-    mErrorString.Truncate();
-    *aResultDoc = nsnull;
-    if (!aInputStream) {
-        mErrorString.AppendLiteral("unable to parse xml: invalid or unopen stream encountered.");
-        return NS_ERROR_FAILURE;
-    }
-
-    static const XML_Memory_Handling_Suite memsuite = {
-        (void *(*)(size_t))PR_Malloc,
-        (void *(*)(void *, size_t))PR_Realloc,
-        PR_Free
-    };
-    static const PRUnichar expatSeparator = kExpatSeparatorChar;
-    mExpatParser = XML_ParserCreate_MM(nsnull, &memsuite, &expatSeparator);
-    if (!mExpatParser) {
-        return NS_ERROR_OUT_OF_MEMORY;
-    }
-    mDocument = new Document();
-    if (!mDocument) {
-        XML_ParserFree(mExpatParser);
-        return NS_ERROR_OUT_OF_MEMORY;
-    }
-    mDocument->documentBaseURI = aUri;
-    mCurrentNode = mDocument;
-
-    XML_SetReturnNSTriplet(mExpatParser, XML_TRUE);
-    XML_SetUserData(mExpatParser, this);
-    XML_SetElementHandler(mExpatParser, startElement, endElement);
-    XML_SetCharacterDataHandler(mExpatParser, charData);
-    XML_SetProcessingInstructionHandler(mExpatParser, piHandler);
-    XML_SetCommentHandler(mExpatParser, commentHandler);
-#ifdef XML_DTD
-    XML_SetParamEntityParsing(mExpatParser, XML_PARAM_ENTITY_PARSING_ALWAYS);
-#endif
-    XML_SetExternalEntityRefHandler(mExpatParser, externalEntityRefHandler);
-    XML_SetExternalEntityRefHandlerArg(mExpatParser, this);
-    XML_SetBase(mExpatParser,
-                (const XML_Char*)(PromiseFlatString(aUri).get()));
-
-    const int bufferSize = 1024;
-    char buf[bufferSize];
-    PRBool done;
-    do {
-        aInputStream.read(buf, bufferSize);
-        done = aInputStream.eof();
-
-        if (!XML_Parse(mExpatParser, buf, aInputStream.gcount(), done)) {
-            createErrorString();
-            done = MB_TRUE;
-            delete mDocument;
-            mDocument = nsnull;
-        }
-    } while (!done);
-    aInputStream.clear();
-
-    // clean up
-    XML_ParserFree(mExpatParser);
-    // ownership to the caller
-    *aResultDoc = txXPathNativeNode::createXPathNode(mDocument);
-    mDocument = nsnull;
-    return *aResultDoc ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
-}
-
-const nsAString&
-txXMLParser::getErrorString()
-{
-    return mErrorString;
-}
-
-
-int
-txXMLParser::StartElement(const XML_Char *aName, const XML_Char **aAtts)
-{
-    nsCOMPtr<nsIAtom> prefix, localName;
-    PRInt32 nsID;
-    XMLUtils::splitExpatName(aName, getter_AddRefs(prefix),
-                             getter_AddRefs(localName), &nsID);
-    Element* newElement = mDocument->createElementNS(prefix, localName, nsID);
-    if (!newElement) {
-        return XML_ERROR_NO_MEMORY;
-    }
-
-    const XML_Char** theAtts = aAtts;
-    while (*theAtts) {
-        XMLUtils::splitExpatName(*theAtts++, getter_AddRefs(prefix),
-                                 getter_AddRefs(localName), &nsID);
-        nsDependentString attValue(*theAtts++);
-        nsresult rv = newElement->appendAttributeNS(prefix, localName, nsID,
-                                                    attValue);
-        if (NS_FAILED(rv)) {
-            return XML_ERROR_NO_MEMORY;
-        }
-    }
-
-    int idx;
-    if ((idx = XML_GetIdAttributeIndex(mExpatParser)) > -1) {
-        nsDependentString idName((const PRUnichar*)*(aAtts + idx));
-        nsDependentString idValue((const PRUnichar*)*(aAtts + idx + 1));
-        // make sure IDs are unique
-        if (!idValue.IsEmpty()) {
-            mDocument->setElementID(idValue, newElement);
-        }
-    }
-    mCurrentNode->appendChild(newElement);
-    mCurrentNode = newElement;
-
-    return XML_ERROR_NONE;
-}
-
-int
-txXMLParser::EndElement(const XML_Char* aName)
-{
-    if (mCurrentNode->getParentNode()) {
-        mCurrentNode = mCurrentNode->getParentNode();
-    }
-    return XML_ERROR_NONE;
-}
-
-void
-txXMLParser::CharacterData(const XML_Char* aChars, int aLength)
-{
-    Node* prevSib = mCurrentNode->getLastChild();
-    const PRUnichar* pChars = static_cast<const PRUnichar*>(aChars);
-    if (prevSib && prevSib->getNodeType() == Node::TEXT_NODE) {
-        static_cast<NodeDefinition*>(prevSib)->appendData(pChars, aLength);
-    }
-    else {
-        // aChars is not null-terminated so we use Substring here.
-        Node* node = mDocument->createTextNode(Substring(pChars,
-                                                         pChars + aLength));
-        mCurrentNode->appendChild(node);
-    }
-}
-
-void
-txXMLParser::Comment(const XML_Char* aChars)
-{
-    Node* node = mDocument->createComment(
-        nsDependentString(static_cast<const PRUnichar*>(aChars)));
-    mCurrentNode->appendChild(node);
-}
-
-int
-txXMLParser::ProcessingInstruction(const XML_Char *aTarget,
-                                   const XML_Char *aData)
-{
-    nsCOMPtr<nsIAtom> target = do_GetAtom(aTarget);
-    nsDependentString data((const PRUnichar*)aData);
-    Node* node = mDocument->createProcessingInstruction(target, data);
-    mCurrentNode->appendChild(node);
-
-    return XML_ERROR_NONE;
-}
-
-int
-txXMLParser::ExternalEntityRef(const XML_Char *aContext,
-                               const XML_Char *aBase,
-                               const XML_Char *aSystemId,
-                               const XML_Char *aPublicId)
-{
-    if (aPublicId) {
-        // not supported, this is "http://some.site.net/foo.dtd" stuff
-        return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
-    }
-    nsAutoString absUrl;
-    URIUtils::resolveHref(nsDependentString((PRUnichar*)aSystemId),
-                          nsDependentString((PRUnichar*)aBase), absUrl);
-    istream* extInput = URIUtils::getInputStream(absUrl, mErrorString);
-    if (!extInput) {
-        return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
-    }
-    XML_Parser parent = mExpatParser;
-    mExpatParser = 
-        XML_ExternalEntityParserCreate(mExpatParser, aContext, nsnull);
-    if (!mExpatParser) {
-        mExpatParser = parent;
-        delete extInput;
-        return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
-    }
-    XML_SetBase(mExpatParser, absUrl.get());
-
-    const int bufSize = 1024;
-    char buffer[bufSize];
-    int result;
-    PRBool done;
-    do {
-        extInput->read(buffer, bufSize);
-        done = extInput->eof();
-        if (!(result =
-              XML_Parse(mExpatParser, buffer,  extInput->gcount(), done))) {
-            createErrorString();
-            mErrorString.Append(PRUnichar('\n'));
-            done = MB_TRUE;
-        }
-    } while (!done);
-
-    delete extInput;
-    XML_ParserFree(mExpatParser);
-
-    mExpatParser = parent;
-
-    return result;
-}
-
-void
-txXMLParser::createErrorString()
-{
-    XML_Error errCode = XML_GetErrorCode(mExpatParser);
-    mErrorString.AppendWithConversion(XML_ErrorString(errCode));
-    mErrorString.AppendLiteral(" at line ");
-    mErrorString.AppendInt(XML_GetCurrentLineNumber(mExpatParser));
-    mErrorString.AppendLiteral(" in ");
-    mErrorString.Append((const PRUnichar*)XML_GetBase(mExpatParser));
-}
-#endif
--- a/content/xslt/src/xml/txXMLParser.h
+++ b/content/xslt/src/xml/txXMLParser.h
@@ -36,36 +36,24 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef MITRE_XMLPARSER_H
 #define MITRE_XMLPARSER_H
 
 #include "txCore.h"
 
-#ifdef TX_EXE
-#include <iostream.h>
-#endif
-
 class txXPathNode;
 
 /**
  * API to load XML files into DOM datastructures.
  * Parsing is either done by expat, or by expat via the syncloaderservice
  */
 
 /**
  * Parse a document from the aHref location, with referrer URI on behalf
  * of the document aLoader.
  */
 extern "C" nsresult
 txParseDocumentFromURI(const nsAString& aHref, const txXPathNode& aLoader,
                        nsAString& aErrMsg, txXPathNode** aResult);
 
-#ifdef TX_EXE
-/**
- * Parse a document from the given stream
- */
-extern "C" nsresult
-txParseFromStream(istream& aInputStream, const nsAString& aUri,
-                  nsAString& aErrorString, txXPathNode** aResult);
 #endif
-#endif
--- a/content/xslt/src/xml/txXMLUtils.h
+++ b/content/xslt/src/xml/txXMLUtils.h
@@ -43,21 +43,18 @@
 #ifndef MITRE_XMLUTILS_H
 #define MITRE_XMLUTILS_H
 
 #include "txCore.h"
 #include "nsCOMPtr.h"
 #include "nsDependentSubstring.h"
 #include "nsIAtom.h"
 #include "txXPathNode.h"
-
-#ifndef TX_EXE
 #include "nsIParserService.h"
 #include "nsContentUtils.h"
-#endif
 
 #define kExpatSeparatorChar 0xFFFF
 
 class nsIAtom;
 class txNamespaceMap;
 
 class txExpandedName {
 public:
@@ -109,23 +106,16 @@ public:
         return ((mLocalName != rhs.mLocalName) ||
                 (mNamespaceID != rhs.mNamespaceID));
     }
 
     PRInt32 mNamespaceID;
     nsCOMPtr<nsIAtom> mLocalName;
 };
 
-#ifdef TX_EXE
-extern "C" int MOZ_XMLCheckQName(const char* ptr, const char* end,
-                                 int ns_aware, const char** colon);
-extern "C" int MOZ_XMLIsLetter(const char* ptr);
-extern "C" int MOZ_XMLIsNCNameChar(const char* ptr);
-#endif
-
 class XMLUtils {
 
 public:
     static nsresult splitExpatName(const PRUnichar *aExpatName,
                                    nsIAtom **aPrefix, nsIAtom **aLocalName,
                                    PRInt32* aNameSpaceID);
     static nsresult splitQName(const nsAString& aName, nsIAtom** aPrefix,
                                nsIAtom** aLocalName);
@@ -152,58 +142,36 @@ public:
     static void normalizePIValue(nsAString& attValue);
 
     /**
      * Returns true if the given string is a valid XML QName
      */
     static PRBool isValidQName(const nsAFlatString& aQName,
                                const PRUnichar** aColon)
     {
-#ifdef TX_EXE
-        const PRUnichar* end;
-        aQName.EndReading(end);
-
-        const char *colonPtr;
-        int result = MOZ_XMLCheckQName(reinterpret_cast<const char*>
-                                                       (aQName.get()),
-                                       reinterpret_cast<const char*>
-                                                       (end),
-                                       PR_TRUE, &colonPtr);
-        *aColon = reinterpret_cast<const PRUnichar*>(colonPtr);
-        return result == 0;
-#else
         nsIParserService* ps = nsContentUtils::GetParserService();
         return ps && NS_SUCCEEDED(ps->CheckQName(aQName, PR_TRUE, aColon));
-#endif
     }
 
     /**
      * Returns true if the given character represents an Alpha letter
      */
     static PRBool isLetter(PRUnichar aChar)
     {
-#ifdef TX_EXE
-        return MOZ_XMLIsLetter(reinterpret_cast<const char*>(&aChar));
-#else
         nsIParserService* ps = nsContentUtils::GetParserService();
         return ps && ps->IsXMLLetter(aChar);
-#endif
     }
 
     /**
      * Returns true if the given character is an allowable NCName character
      */
     static PRBool isNCNameChar(PRUnichar aChar)
     {
-#ifdef TX_EXE
-        return MOZ_XMLIsNCNameChar(reinterpret_cast<const char*>(&aChar));
-#else
         nsIParserService* ps = nsContentUtils::GetParserService();
         return ps && ps->IsXMLNCNameChar(aChar);
-#endif
     }
 
     /*
      * Walks up the document tree and returns true if the closest xml:space
      * attribute is "preserve"
      */
     static MBool getXMLSpacePreserve(const txXPathNode& aNode);
 };
--- a/content/xslt/src/xpath/Makefile.in
+++ b/content/xslt/src/xpath/Makefile.in
@@ -41,18 +41,16 @@ srcdir          = @srcdir@
 VPATH           = @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE = transformiix
 LIBRARY_NAME = txxpath_s
 LIBXUL_LIBRARY = 1
 
-
-
 CPPSRCS = \
         txBooleanExpr.cpp \
         txBooleanResult.cpp \
         txCoreFunctionCall.cpp \
         txExpr.cpp \
         txExprLexer.cpp \
         txExprParser.cpp \
         txFilterExpr.cpp \
@@ -74,28 +72,24 @@ CPPSRCS = \
         txNodeTypeTest.cpp \
         txForwardContext.cpp \
         txNodeSetContext.cpp \
         txResultRecycler.cpp \
         txUnionExpr.cpp \
         txUnionNodeTest.cpp \
         txUnaryExpr.cpp \
         txVariableRefExpr.cpp \
-        txXPathOptimizer.cpp
-ifndef MOZ_XSLT_STANDALONE
-CPPSRCS += nsXPathEvaluator.cpp \
-           nsXPathExpression.cpp \
-           nsXPathNSResolver.cpp \
-           nsXPathResult.cpp \
-           txMozillaXPathTreeWalker.cpp \
-           txNodeSetAdaptor.cpp \
-           txXPCOMExtensionFunction.cpp
-else
-CPPSRCS += txStandaloneXPathTreeWalker.cpp
-endif
+        txXPathOptimizer.cpp \
+        nsXPathEvaluator.cpp \
+        nsXPathExpression.cpp \
+        nsXPathNSResolver.cpp \
+        nsXPathResult.cpp \
+        txMozillaXPathTreeWalker.cpp \
+        txNodeSetAdaptor.cpp \
+        txXPCOMExtensionFunction.cpp
 
 # we don't want the shared lib, but we want to force the creation of a
 # static lib.
 FORCE_STATIC_LIB = 1
 
 include $(topsrcdir)/config/rules.mk
 
 INCLUDES += \
--- a/content/xslt/src/xpath/txNameTest.cpp
+++ b/content/xslt/src/xpath/txNameTest.cpp
@@ -68,20 +68,18 @@ PRBool txNameTest::matches(const txXPath
     }
 
     // Totally wild?
     if (mLocalName == txXPathAtoms::_asterix && !mPrefix)
         return MB_TRUE;
 
     // Compare namespaces
     if (mNamespace != txXPathNodeUtils::getNamespaceID(aNode) 
-#ifndef TX_EXE
         && !(mNamespace == kNameSpaceID_None &&
              txXPathNodeUtils::isHTMLElementInHTMLDocument(aNode))
-#endif
        )
         return MB_FALSE;
 
     // Name wild?
     if (mLocalName == txXPathAtoms::_asterix)
         return MB_TRUE;
 
     // Compare local-names
deleted file mode 100644
--- a/content/xslt/src/xpath/txStandaloneXPathTreeWalker.cpp
+++ /dev/null
@@ -1,446 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* ***** 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 TransforMiiX XSLT processor code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 2003
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Peter Van der Beken <peterv@propagandism.org>
- *   Axel Hecht <axel@pike.org>
- *
- * 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