Merge mozilla-central into build-system
authorGregory Szorc <gps@mozilla.com>
Tue, 29 Jan 2013 20:27:15 -0800
changeset 130144 677e87c11252bbb74d28060f7829db4373acc8a8
parent 130143 c638b856a1713a68310b851c43a01cc43e57d8e1 (current diff)
parent 130135 a31b07df79df0b56cd8cf8871a53dbf7592f3a3f (diff)
child 130216 5f9775715519260793af64eff6dfc56cbb356982
child 130342 887fe9aa34669850a4719c2614553f1de135e131
child 138152 020e863afa1dca8421076e9aa3f663da8f85e881
push id2323
push userbbajaj@mozilla.com
push dateMon, 01 Apr 2013 19:47:02 +0000
treeherdermozilla-beta@7712be144d91 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone21.0a1
first release with
nightly linux32
677e87c11252 / 21.0a1 / 20130130030907 / files
nightly linux64
677e87c11252 / 21.0a1 / 20130130030907 / files
nightly mac
677e87c11252 / 21.0a1 / 20130130030907 / files
nightly win32
677e87c11252 / 21.0a1 / 20130130030907 / files
nightly win64
677e87c11252 / 21.0a1 / 20130130030907 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge mozilla-central into build-system
browser/app/profile/extensions/testpilot@labs.mozilla.com/modules/setup.js.in
browser/app/profile/extensions/testpilot@labs.mozilla.com/modules/tasks.js.in
browser/base/content/test/browser_bug763468.js
browser/base/content/test/browser_bug767836.js
browser/base/content/test/browser_save_link.js
browser/base/content/test/browser_save_private_link.js
browser/base/content/test/browser_tabMatchesInAwesomebar.js
browser/base/content/test/newtab/browser_newtab_private_browsing.js
browser/base/content/test/social/browser_social_globalPB.js
browser/components/preferences/in-content/tests/browser_bug567487.js
browser/components/preferences/in-content/tests/browser_privacypane_2.js
browser/components/preferences/in-content/tests/browser_privacypane_6.js
browser/components/preferences/in-content/tests/browser_privacypane_7.js
browser/components/preferences/in-content/tests/privacypane_tests.js
browser/components/preferences/tests/browser_bug567487.js
browser/components/preferences/tests/browser_privacypane_2.js
browser/components/preferences/tests/browser_privacypane_6.js
browser/components/preferences/tests/browser_privacypane_7.js
browser/components/preferences/tests/privacypane_tests.js
browser/components/privatebrowsing/src/nsPrivateBrowsingService.js
browser/components/privatebrowsing/src/nsPrivateBrowsingService.manifest
browser/components/privatebrowsing/src/nsPrivateBrowsingServiceWrapper.cpp
browser/components/privatebrowsing/src/nsPrivateBrowsingServiceWrapper.h
browser/components/privatebrowsing/test/browser/global/Makefile.in
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_DownloadLastDirWithCPS.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_certexceptionsui.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_cookieacceptdialog.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_crh.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_downloadLastDir.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_downloadLastDir_c.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_downloadLastDir_toggle.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_geoprompt.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_geoprompt_page.html
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_localStorage.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_localStorage_before_after.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_localStorage_before_after_page.html
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_localStorage_before_after_page2.html
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_localStorage_page1.html
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_localStorage_page2.html
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_openLocationLastURL.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_opendir.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_openlocation.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_placestitle.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_popupblocker.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_protocolhandler.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_protocolhandler_page.html
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_theming.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_ui.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_urlbarfocus.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_windowtitle.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_windowtitle_page.html
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_zoom.js
browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_zoomrestore.js
browser/components/privatebrowsing/test/browser/global/ctxmenu-image.png
browser/components/privatebrowsing/test/browser/global/ctxmenu.html
browser/components/privatebrowsing/test/browser/global/head.js
browser/components/privatebrowsing/test/browser/global/popup.html
browser/components/privatebrowsing/test/browser/global/title.sjs
browser/components/privatebrowsing/test/browser/obsolete/Makefile.in
browser/components/privatebrowsing/test/browser/obsolete/browser_console_clear.js
browser/components/privatebrowsing/test/browser/obsolete/browser_privatebrowsing_beforeunload.js
browser/components/privatebrowsing/test/browser/obsolete/browser_privatebrowsing_commandline_toggle.js
browser/components/privatebrowsing/test/browser/obsolete/browser_privatebrowsing_fastswitch.js
browser/components/privatebrowsing/test/browser/obsolete/browser_privatebrowsing_findbar.js
browser/components/privatebrowsing/test/browser/obsolete/browser_privatebrowsing_forgetthissite.js
browser/components/privatebrowsing/test/browser/obsolete/browser_privatebrowsing_import.js
browser/components/privatebrowsing/test/browser/obsolete/browser_privatebrowsing_newwindow_stopcmd.js
browser/components/privatebrowsing/test/browser/obsolete/browser_privatebrowsing_pageinfo.js
browser/components/privatebrowsing/test/browser/obsolete/browser_privatebrowsing_popupmode.js
browser/components/privatebrowsing/test/browser/obsolete/browser_privatebrowsing_searchbar.js
browser/components/privatebrowsing/test/browser/obsolete/browser_privatebrowsing_sslsite_transition.js
browser/components/privatebrowsing/test/browser/obsolete/browser_privatebrowsing_transition.js
browser/components/privatebrowsing/test/browser/obsolete/browser_privatebrowsing_urlbarundo.js
browser/components/privatebrowsing/test/browser/obsolete/browser_privatebrowsing_viewsource.js
browser/components/privatebrowsing/test/browser/obsolete/head.js
browser/components/privatebrowsing/test/unit/do_test_0-privatebrowsing.js
browser/components/privatebrowsing/test/unit/do_test_placesTitleNoUpdate.js
browser/components/privatebrowsing/test/unit/do_test_privatebrowsing_autostart.js
browser/components/privatebrowsing/test/unit/do_test_privatebrowsing_commandline.js
browser/components/privatebrowsing/test/unit/do_test_privatebrowsing_exit.js
browser/components/privatebrowsing/test/unit/do_test_privatebrowsing_telemetry.js
browser/components/privatebrowsing/test/unit/head_privatebrowsing.js
browser/components/privatebrowsing/test/unit/tail_privatebrowsing.js
browser/components/privatebrowsing/test/unit/test_0-privatebrowsing.js
browser/components/privatebrowsing/test/unit/test_0-privatebrowsingwrapper.js
browser/components/privatebrowsing/test/unit/test_aboutprivatebrowsing.js
browser/components/privatebrowsing/test/unit/test_placesTitleNoUpdate.js
browser/components/privatebrowsing/test/unit/test_privatebrowsing_autostart.js
browser/components/privatebrowsing/test/unit/test_privatebrowsing_commandline.js
browser/components/privatebrowsing/test/unit/test_privatebrowsing_exit.js
browser/components/privatebrowsing/test/unit/test_privatebrowsing_telemetry.js
browser/components/privatebrowsing/test/unit/test_privatebrowsingwrapper_autostart.js
browser/components/privatebrowsing/test/unit/test_privatebrowsingwrapper_commandline.js
browser/components/privatebrowsing/test/unit/test_privatebrowsingwrapper_exit.js
browser/components/privatebrowsing/test/unit/test_privatebrowsingwrapper_placesTitleNoUpdate.js
browser/components/privatebrowsing/test/unit/test_privatebrowsingwrapper_telemetry.js
browser/components/privatebrowsing/test/unit/test_transition_nooffline.js
browser/components/privatebrowsing/test/unit/xpcshell.ini
browser/components/search/test/browser_private_search.js
browser/components/sessionstore/test/browser_248970_a.js
browser/components/sessionstore/test/browser_248970_b.js
browser/components/sessionstore/test/browser_354894.js
browser/components/sessionstore/test/browser_394759_privatebrowsing.js
browser/components/tabview/test/browser_tabview_bug624265.js
browser/components/tabview/test/browser_tabview_bug624727.js
browser/components/tabview/test/browser_tabview_bug650280.js
browser/components/tabview/test/browser_tabview_bug679853.js
browser/components/tabview/test/browser_tabview_privatebrowsing.js
browser/devtools/commandline/test/browser_cmd_screenshot.js
browser/devtools/styleeditor/test/browser_styleeditor_private.js
browser/devtools/webconsole/test/browser_webconsole_bug_618311_private_browsing.js
dom/bluetooth/BluetoothPropertyEvent.cpp
dom/bluetooth/BluetoothPropertyEvent.h
dom/bluetooth/linux/BluetoothDBusUtils.cpp
dom/bluetooth/nsIDOMBluetoothPropertyEvent.idl
dom/indexedDB/test/browser_privateBrowsing.js
dom/plugins/test/mochitest/test_privatemode.xul
dom/tests/browser/browser_ConsoleStoragePBTest.js
dom/tests/browser/browser_geolocation_privatebrowsing.js
dom/tests/mochitest/localstorage/pbSwitch.js
dom/tests/mochitest/localstorage/test_localStorageBasePrivateBrowsing.html
dom/tests/mochitest/localstorage/test_localStorageQuotaPrivateBrowsing.html
extensions/cookie/test/unit/test_bug468700.js
js/src/tests/js1_8_5/extensions/parseInt-octal.js
js/xpconnect/src/nsCSSPropertiesQS.h
layout/forms/test/test_bug536567.html
netwerk/base/public/nsIPrivateBrowsingService.idl
security/manager/ssl/tests/mochitest/stricttransportsecurity/test_sts_privatebrowsing.html
security/manager/ssl/tests/unit/test_bug627234.js
security/manager/ssl/tests/unit/test_sts_preloadlist.js
toolkit/components/downloads/test/unit/test_private_resume_global.js
toolkit/components/downloads/test/unit/test_privatebrowsing_cancel_global.js
toolkit/components/downloads/test/unit/test_privatebrowsing_global.js
toolkit/components/passwordmgr/test/test_privbrowsing.html
toolkit/components/places/tests/browser/browser_favicon_privatebrowsing.js
toolkit/components/places/tests/browser/browser_visituri_privatebrowsing.js
toolkit/components/places/tests/favicons/test_setAndFetchFaviconForPage.js
toolkit/components/places/tests/favicons/test_setAndFetchFaviconForPage_failures.js
toolkit/components/places/tests/mochitest/test_bug_461710.html
toolkit/components/places/tests/unit/test_248970.js
toolkit/components/satchel/test/test_privbrowsing.html
toolkit/mozapps/downloads/tests/chrome/test_privatebrowsing_title.xul
toolkit/mozapps/update/test/unit/test_bug497578.js
widget/tests/test_bug462106.xul
--- a/accessible/src/base/AccEvent.h
+++ b/accessible/src/base/AccEvent.h
@@ -118,17 +118,17 @@ public:
   NS_DECL_CYCLE_COLLECTION_NATIVE_CLASS(AccEvent)
 
 protected:
   bool mIsFromUserInput;
   uint32_t mEventType;
   EEventRule mEventRule;
   nsRefPtr<Accessible> mAccessible;
 
-  friend class NotificationController;
+  friend class EventQueue;
   friend class AccReorderEvent;
 };
 
 
 /**
  * Accessible state change event.
  */
 class AccStateChangeEvent: public AccEvent
@@ -158,17 +158,17 @@ public:
   // AccStateChangeEvent
   uint64_t GetState() const { return mState; }
   bool IsStateEnabled() const { return mIsEnabled; }
 
 private:
   uint64_t mState;
   bool mIsEnabled;
 
-  friend class NotificationController;
+  friend class EventQueue;
 };
 
 
 /**
  * Accessible text change event.
  */
 class AccTextChangeEvent: public AccEvent
 {
@@ -193,17 +193,17 @@ public:
   void GetModifiedText(nsAString& aModifiedText)
     { aModifiedText = mModifiedText; }
 
 private:
   int32_t mStart;
   bool mIsInserted;
   nsString mModifiedText;
 
-  friend class NotificationController;
+  friend class EventQueue;
   friend class AccReorderEvent;
 };
 
 
 /**
  * Base class for show and hide accessible events.
  */
 class AccMutationEvent: public AccEvent
@@ -230,17 +230,17 @@ public:
   bool IsShow() const { return mEventType == nsIAccessibleEvent::EVENT_SHOW; }
   bool IsHide() const { return mEventType == nsIAccessibleEvent::EVENT_HIDE; }
 
 protected:
   nsCOMPtr<nsINode> mNode;
   nsRefPtr<Accessible> mParent;
   nsRefPtr<AccTextChangeEvent> mTextChangeEvent;
 
-  friend class NotificationController;
+  friend class EventQueue;
 };
 
 
 /**
  * Accessible hide event.
  */
 class AccHideEvent: public AccMutationEvent
 {
@@ -260,17 +260,17 @@ public:
   Accessible* TargetParent() const { return mParent; }
   Accessible* TargetNextSibling() const { return mNextSibling; }
   Accessible* TargetPrevSibling() const { return mPrevSibling; }
 
 protected:
   nsRefPtr<Accessible> mNextSibling;
   nsRefPtr<Accessible> mPrevSibling;
 
-  friend class NotificationController;
+  friend class EventQueue;
 };
 
 
 /**
  * Accessible show event.
  */
 class AccShowEvent: public AccMutationEvent
 {
@@ -328,17 +328,17 @@ public:
   uint32_t IsShowHideEventTarget(const Accessible* aTarget) const;
 
 protected:
   /**
    * Show and hide events causing this reorder event.
    */
   nsTArray<AccMutationEvent*> mDependentEvents;
 
-  friend class NotificationController;
+  friend class EventQueue;
 };
 
 
 /**
  * Accessible caret move event.
  */
 class AccCaretMoveEvent: public AccEvent
 {
@@ -358,17 +358,17 @@ public:
   }
 
   // AccCaretMoveEvent
   int32_t GetCaretOffset() const { return mCaretOffset; }
 
 private:
   int32_t mCaretOffset;
 
-  friend class NotificationController;
+  friend class EventQueue;
 };
 
 
 /**
  * Accessible widget selection change event.
  */
 class AccSelChangeEvent : public AccEvent
 {
@@ -395,17 +395,17 @@ public:
 
 private:
   nsRefPtr<Accessible> mWidget;
   nsRefPtr<Accessible> mItem;
   SelChangeType mSelChangeType;
   uint32_t mPreceedingCount;
   AccSelChangeEvent* mPackedEvent;
 
-  friend class NotificationController;
+  friend class EventQueue;
 };
 
 
 /**
  * Accessible table change event.
  */
 class AccTableChangeEvent : public AccEvent
 {
copy from accessible/src/base/NotificationController.cpp
copy to accessible/src/base/EventQueue.cpp
--- a/accessible/src/base/NotificationController.cpp
+++ b/accessible/src/base/EventQueue.cpp
@@ -1,328 +1,57 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "NotificationController.h"
+#include "EventQueue.h"
 
 #include "Accessible-inl.h"
-#include "nsAccessibilityService.h"
-#include "nsAccUtils.h"
-#include "nsCoreUtils.h"
 #include "DocAccessible-inl.h"
 #include "nsEventShell.h"
-#include "FocusManager.h"
-#include "Role.h"
-#include "TextLeafAccessible.h"
-#include "TextUpdater.h"
-
-#ifdef A11Y_LOG
-#include "Logging.h"
-#endif
-
-#include "mozilla/dom/Element.h"
-#include "mozilla/Telemetry.h"
 
 using namespace mozilla;
 using namespace mozilla::a11y;
 
 // Defines the number of selection add/remove events in the queue when they
 // aren't packed into single selection within event.
 const unsigned int kSelChangeCountToPack = 5;
 
 ////////////////////////////////////////////////////////////////////////////////
-// NotificationCollector
+// EventQueue
 ////////////////////////////////////////////////////////////////////////////////
 
-NotificationController::NotificationController(DocAccessible* aDocument,
-                                               nsIPresShell* aPresShell) :
-  mObservingState(eNotObservingRefresh), mDocument(aDocument),
-  mPresShell(aPresShell)
-{
-  mTextHash.Init();
-
-  // Schedule initial accessible tree construction.
-  ScheduleProcessing();
-}
-
-NotificationController::~NotificationController()
-{
-  NS_ASSERTION(!mDocument, "Controller wasn't shutdown properly!");
-  if (mDocument)
-    Shutdown();
-}
-
-////////////////////////////////////////////////////////////////////////////////
-// NotificationCollector: AddRef/Release and cycle collection
-
-NS_IMPL_CYCLE_COLLECTING_NATIVE_ADDREF(NotificationController)
-NS_IMPL_CYCLE_COLLECTING_NATIVE_RELEASE(NotificationController)
-
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(NotificationController)
-  if (tmp->mDocument)
-    tmp->Shutdown();
-NS_IMPL_CYCLE_COLLECTION_UNLINK_END
-
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(NotificationController)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocument)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mHangingChildDocuments)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mContentInsertions)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEvents)
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
-
-NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(NotificationController, AddRef)
-NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(NotificationController, Release)
-
-////////////////////////////////////////////////////////////////////////////////
-// NotificationCollector: public
-
-void
-NotificationController::Shutdown()
-{
-  if (mObservingState != eNotObservingRefresh &&
-      mPresShell->RemoveRefreshObserver(this, Flush_Display)) {
-    mObservingState = eNotObservingRefresh;
-  }
-
-  // Shutdown handling child documents.
-  int32_t childDocCount = mHangingChildDocuments.Length();
-  for (int32_t idx = childDocCount - 1; idx >= 0; idx--) {
-    if (!mHangingChildDocuments[idx]->IsDefunct())
-      mHangingChildDocuments[idx]->Shutdown();
-  }
-
-  mHangingChildDocuments.Clear();
-
-  mDocument = nullptr;
-  mPresShell = nullptr;
-
-  mTextHash.Clear();
-  mContentInsertions.Clear();
-  mNotifications.Clear();
-  mEvents.Clear();
-}
-
-void
-NotificationController::QueueEvent(AccEvent* aEvent)
+bool
+EventQueue::PushEvent(AccEvent* aEvent)
 {
   NS_ASSERTION((aEvent->mAccessible && aEvent->mAccessible->IsApplication()) ||
                aEvent->GetDocAccessible() == mDocument,
                "Queued event belongs to another document!");
 
   if (!mEvents.AppendElement(aEvent))
-    return;
+    return false;
 
   // Filter events.
   CoalesceEvents();
 
   // Associate text change with hide event if it wasn't stolen from hiding
   // siblings during coalescence.
   AccMutationEvent* showOrHideEvent = downcast_accEvent(aEvent);
   if (showOrHideEvent && !showOrHideEvent->mTextChangeEvent)
     CreateTextChangeEventFor(showOrHideEvent);
 
-  ScheduleProcessing();
-}
-
-void
-NotificationController::ScheduleChildDocBinding(DocAccessible* aDocument)
-{
-  // Schedule child document binding to the tree.
-  mHangingChildDocuments.AppendElement(aDocument);
-  ScheduleProcessing();
-}
-
-void
-NotificationController::ScheduleContentInsertion(Accessible* aContainer,
-                                                 nsIContent* aStartChildNode,
-                                                 nsIContent* aEndChildNode)
-{
-  nsRefPtr<ContentInsertion> insertion = new ContentInsertion(mDocument,
-                                                              aContainer);
-  if (insertion && insertion->InitChildList(aStartChildNode, aEndChildNode) &&
-      mContentInsertions.AppendElement(insertion)) {
-    ScheduleProcessing();
-  }
-}
-
-////////////////////////////////////////////////////////////////////////////////
-// NotificationCollector: protected
-
-void
-NotificationController::ScheduleProcessing()
-{
-  // If notification flush isn't planed yet start notification flush
-  // asynchronously (after style and layout).
-  if (mObservingState == eNotObservingRefresh) {
-    if (mPresShell->AddRefreshObserver(this, Flush_Display))
-      mObservingState = eRefreshObserving;
-  }
-}
-
-bool
-NotificationController::IsUpdatePending()
-{
-  return mPresShell->IsLayoutFlushObserver() ||
-    mObservingState == eRefreshProcessingForUpdate ||
-    mContentInsertions.Length() != 0 || mNotifications.Length() != 0 ||
-    mTextHash.Count() != 0 ||
-    !mDocument->HasLoadState(DocAccessible::eTreeConstructed);
+  return true;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// NotificationCollector: private
+// EventQueue: private
 
 void
-NotificationController::WillRefresh(mozilla::TimeStamp aTime)
-{
-  Telemetry::AutoTimer<Telemetry::A11Y_UPDATE_TIME> updateTimer;
-
-  // If the document accessible that notification collector was created for is
-  // now shut down, don't process notifications anymore.
-  NS_ASSERTION(mDocument,
-               "The document was shut down while refresh observer is attached!");
-  if (!mDocument)
-    return;
-
-  // Any generic notifications should be queued if we're processing content
-  // insertions or generic notifications.
-  mObservingState = eRefreshProcessingForUpdate;
-
-  // Initial accessible tree construction.
-  if (!mDocument->HasLoadState(DocAccessible::eTreeConstructed)) {
-    // If document is not bound to parent at this point then the document is not
-    // ready yet (process notifications later).
-    if (!mDocument->IsBoundToParent()) {
-      mObservingState = eRefreshObserving;
-      return;
-    }
-
-#ifdef A11Y_LOG
-    if (logging::IsEnabled(logging::eTree)) {
-      logging::MsgBegin("TREE", "initial tree created");
-      logging::Address("document", mDocument);
-      logging::MsgEnd();
-    }
-#endif
-
-    mDocument->DoInitialUpdate();
-
-    NS_ASSERTION(mContentInsertions.Length() == 0,
-                 "Pending content insertions while initial accessible tree isn't created!");
-  }
-
-  // Initialize scroll support if needed.
-  if (!(mDocument->mDocFlags & DocAccessible::eScrollInitialized))
-    mDocument->AddScrollListener();
-
-  // Process content inserted notifications to update the tree. Process other
-  // notifications like DOM events and then flush event queue. If any new
-  // notifications are queued during this processing then they will be processed
-  // on next refresh. If notification processing queues up new events then they
-  // are processed in this refresh. If events processing queues up new events
-  // then new events are processed on next refresh.
-  // Note: notification processing or event handling may shut down the owning
-  // document accessible.
-
-  // Process only currently queued content inserted notifications.
-  nsTArray<nsRefPtr<ContentInsertion> > contentInsertions;
-  contentInsertions.SwapElements(mContentInsertions);
-
-  uint32_t insertionCount = contentInsertions.Length();
-  for (uint32_t idx = 0; idx < insertionCount; idx++) {
-    contentInsertions[idx]->Process();
-    if (!mDocument)
-      return;
-  }
-
-  // Process rendered text change notifications.
-  mTextHash.EnumerateEntries(TextEnumerator, mDocument);
-  mTextHash.Clear();
-
-  // Bind hanging child documents.
-  uint32_t hangingDocCnt = mHangingChildDocuments.Length();
-  for (uint32_t idx = 0; idx < hangingDocCnt; idx++) {
-    DocAccessible* childDoc = mHangingChildDocuments[idx];
-    if (childDoc->IsDefunct())
-      continue;
-
-    nsIContent* ownerContent = mDocument->DocumentNode()->
-      FindContentForSubDocument(childDoc->DocumentNode());
-    if (ownerContent) {
-      Accessible* outerDocAcc = mDocument->GetAccessible(ownerContent);
-      if (outerDocAcc && outerDocAcc->AppendChild(childDoc)) {
-        if (mDocument->AppendChildDocument(childDoc))
-          continue;
-
-        outerDocAcc->RemoveChild(childDoc);
-      }
-
-      // Failed to bind the child document, destroy it.
-      childDoc->Shutdown();
-    }
-  }
-  mHangingChildDocuments.Clear();
-
-  // If the document is ready and all its subdocuments are completely loaded
-  // then process the document load.
-  if (mDocument->HasLoadState(DocAccessible::eReady) &&
-      !mDocument->HasLoadState(DocAccessible::eCompletelyLoaded) &&
-      hangingDocCnt == 0) {
-    uint32_t childDocCnt = mDocument->ChildDocumentCount(), childDocIdx = 0;
-    for (; childDocIdx < childDocCnt; childDocIdx++) {
-      DocAccessible* childDoc = mDocument->GetChildDocumentAt(childDocIdx);
-      if (!childDoc->HasLoadState(DocAccessible::eCompletelyLoaded))
-        break;
-    }
-
-    if (childDocIdx == childDocCnt) {
-      mDocument->ProcessLoad();
-      if (!mDocument)
-        return;
-    }
-  }
-
-  // Process only currently queued generic notifications.
-  nsTArray < nsRefPtr<Notification> > notifications;
-  notifications.SwapElements(mNotifications);
-
-  uint32_t notificationCount = notifications.Length();
-  for (uint32_t idx = 0; idx < notificationCount; idx++) {
-    notifications[idx]->Process();
-    if (!mDocument)
-      return;
-  }
-
-  // Process invalidation list of the document after all accessible tree
-  // modification are done.
-  mDocument->ProcessInvalidationList();
-
-  // If a generic notification occurs after this point then we may be allowed to
-  // process it synchronously.
-  mObservingState = eRefreshObserving;
-
-  ProcessEventQueue();
-  if (!mDocument)
-    return;
-
-  // Stop further processing if there are no new notifications of any kind or
-  // events and document load is processed.
-  if (mContentInsertions.Length() == 0 && mNotifications.Length() == 0 &&
-      mEvents.Length() == 0 && mTextHash.Count() == 0 &&
-      mHangingChildDocuments.Length() == 0 &&
-      mDocument->HasLoadState(DocAccessible::eCompletelyLoaded) &&
-      mPresShell->RemoveRefreshObserver(this, Flush_Display)) {
-    mObservingState = eNotObservingRefresh;
-  }
-}
-
-void
-NotificationController::CoalesceEvents()
+EventQueue::CoalesceEvents()
 {
   NS_ASSERTION(mEvents.Length(), "There should be at least one pending event!");
   uint32_t tail = mEvents.Length() - 1;
   AccEvent* tailEvent = mEvents[tail];
 
   switch(tailEvent->mEventRule) {
     case AccEvent::eCoalesceReorder:
       CoalesceReorderEvents(tailEvent);
@@ -435,17 +164,17 @@ NotificationController::CoalesceEvents()
     } break; // case eRemoveDupes
 
     default:
       break; // case eAllowDupes, eDoNotEmit
   } // switch
 }
 
 void
-NotificationController::CoalesceReorderEvents(AccEvent* aTailEvent)
+EventQueue::CoalesceReorderEvents(AccEvent* aTailEvent)
 {
   uint32_t count = mEvents.Length();
   for (uint32_t index = count - 2; index < count; index--) {
     AccEvent* thisEvent = mEvents[index];
 
     // Skip events of different types and targeted to application accessible.
     if (thisEvent->mEventType != aTailEvent->mEventType ||
         thisEvent->mAccessible->IsApplication())
@@ -524,19 +253,19 @@ NotificationController::CoalesceReorderE
 
       tailParent = tailParent->Parent();
     }
 
   } // for (index)
 }
 
 void
-NotificationController::CoalesceSelChangeEvents(AccSelChangeEvent* aTailEvent,
-                                                AccSelChangeEvent* aThisEvent,
-                                                uint32_t aThisIndex)
+EventQueue::CoalesceSelChangeEvents(AccSelChangeEvent* aTailEvent,
+                                    AccSelChangeEvent* aThisEvent,
+                                    uint32_t aThisIndex)
 {
   aTailEvent->mPreceedingCount = aThisEvent->mPreceedingCount + 1;
 
   // Pack all preceding events into single selection within event
   // when we receive too much selection add/remove events.
   if (aTailEvent->mPreceedingCount >= kSelChangeCountToPack) {
     aTailEvent->mEventType = nsIAccessibleEvent::EVENT_SELECTION_WITHIN;
     aTailEvent->mAccessible = aTailEvent->mWidget;
@@ -604,18 +333,18 @@ NotificationController::CoalesceSelChang
 
   // Convert into selection add since control has single selection but other
   // selection events for this control are queued.
   if (aTailEvent->mEventType == nsIAccessibleEvent::EVENT_SELECTION)
     aTailEvent->mEventType = nsIAccessibleEvent::EVENT_SELECTION_ADD;
 }
 
 void
-NotificationController::CoalesceTextChangeEventsFor(AccHideEvent* aTailEvent,
-                                                    AccHideEvent* aThisEvent)
+EventQueue::CoalesceTextChangeEventsFor(AccHideEvent* aTailEvent,
+                                        AccHideEvent* aThisEvent)
 {
   // XXX: we need a way to ignore SplitNode and JoinNode() when they do not
   // affect the text within the hypertext.
 
   AccTextChangeEvent* textEvent = aThisEvent->mTextChangeEvent;
   if (!textEvent)
     return;
 
@@ -627,18 +356,18 @@ NotificationController::CoalesceTextChan
     aTailEvent->mAccessible->AppendTextTo(textEvent->mModifiedText);
     textEvent->mStart -= textEvent->GetLength() - oldLen;
   }
 
   aTailEvent->mTextChangeEvent.swap(aThisEvent->mTextChangeEvent);
 }
 
 void
-NotificationController::CoalesceTextChangeEventsFor(AccShowEvent* aTailEvent,
-                                                    AccShowEvent* aThisEvent)
+EventQueue::CoalesceTextChangeEventsFor(AccShowEvent* aTailEvent,
+                                        AccShowEvent* aThisEvent)
 {
   AccTextChangeEvent* textEvent = aThisEvent->mTextChangeEvent;
   if (!textEvent)
     return;
 
   if (aTailEvent->mAccessible->IndexInParent() ==
       aThisEvent->mAccessible->IndexInParent() + 1) {
     // If tail target was inserted after this target, i.e. tail target is next
@@ -654,17 +383,17 @@ NotificationController::CoalesceTextChan
     textEvent->mModifiedText = startText + textEvent->mModifiedText;
     textEvent->mStart -= startText.Length();
   }
 
   aTailEvent->mTextChangeEvent.swap(aThisEvent->mTextChangeEvent);
 }
 
 void
-NotificationController::CreateTextChangeEventFor(AccMutationEvent* aEvent)
+EventQueue::CreateTextChangeEventFor(AccMutationEvent* aEvent)
 {
   Accessible* container = aEvent->mAccessible->Parent();
   if (!container)
     return;
 
   HyperTextAccessible* textAccessible = container->AsHyperText();
   if (!textAccessible)
     return;
@@ -688,20 +417,20 @@ NotificationController::CreateTextChange
     return;
 
   aEvent->mTextChangeEvent =
     new AccTextChangeEvent(textAccessible, offset, text, aEvent->IsShow(),
                            aEvent->mIsFromUserInput ? eFromUserInput : eNoUserInput);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// NotificationController: event queue
+// EventQueue: event queue
 
 void
-NotificationController::ProcessEventQueue()
+EventQueue::ProcessEventQueue()
 {
   // Process only currently queued events.
   nsTArray<nsRefPtr<AccEvent> > events;
   events.SwapElements(mEvents);
 
   uint32_t eventCount = events.Length();
 #ifdef A11Y_LOG
   if (eventCount > 0 && logging::IsEnabled(logging::eEvents)) {
@@ -755,151 +484,8 @@ NotificationController::ProcessEventQueu
 
     if (event->mEventType == nsIAccessibleEvent::EVENT_HIDE)
       mDocument->ShutdownChildrenInSubtree(event->mAccessible);
 
     if (!mDocument)
       return;
   }
 }
-
-////////////////////////////////////////////////////////////////////////////////
-// Notification controller: text leaf accessible text update
-
-PLDHashOperator
-NotificationController::TextEnumerator(nsCOMPtrHashKey<nsIContent>* aEntry,
-                                       void* aUserArg)
-{
-  DocAccessible* document = static_cast<DocAccessible*>(aUserArg);
-  nsIContent* textNode = aEntry->GetKey();
-  Accessible* textAcc = document->GetAccessible(textNode);
-
-  // If the text node is not in tree or doesn't have frame then this case should
-  // have been handled already by content removal notifications.
-  nsINode* containerNode = textNode->GetParentNode();
-  if (!containerNode) {
-    NS_ASSERTION(!textAcc,
-                 "Text node was removed but accessible is kept alive!");
-    return PL_DHASH_NEXT;
-  }
-
-  nsIFrame* textFrame = textNode->GetPrimaryFrame();
-  if (!textFrame) {
-    NS_ASSERTION(!textAcc,
-                 "Text node isn't rendered but accessible is kept alive!");
-    return PL_DHASH_NEXT;
-  }
-
-  nsIContent* containerElm = containerNode->IsElement() ?
-    containerNode->AsElement() : nullptr;
-
-  nsAutoString text;
-  textFrame->GetRenderedText(&text);
-
-  // Remove text accessible if rendered text is empty.
-  if (textAcc) {
-    if (text.IsEmpty()) {
-#ifdef A11Y_LOG
-      if (logging::IsEnabled(logging::eTree | logging::eText)) {
-        logging::MsgBegin("TREE", "text node lost its content");
-        logging::Node("container", containerElm);
-        logging::Node("content", textNode);
-        logging::MsgEnd();
-      }
-#endif
-
-      document->ContentRemoved(containerElm, textNode);
-      return PL_DHASH_NEXT;
-    }
-
-    // Update text of the accessible and fire text change events.
-#ifdef A11Y_LOG
-    if (logging::IsEnabled(logging::eText)) {
-      logging::MsgBegin("TEXT", "text may be changed");
-      logging::Node("container", containerElm);
-      logging::Node("content", textNode);
-      logging::MsgEntry("old text '%s'",
-                        NS_ConvertUTF16toUTF8(textAcc->AsTextLeaf()->Text()).get());
-      logging::MsgEntry("new text: '%s'",
-                        NS_ConvertUTF16toUTF8(text).get());
-      logging::MsgEnd();
-    }
-#endif
-
-    TextUpdater::Run(document, textAcc->AsTextLeaf(), text);
-    return PL_DHASH_NEXT;
-  }
-
-  // Append an accessible if rendered text is not empty.
-  if (!text.IsEmpty()) {
-#ifdef A11Y_LOG
-    if (logging::IsEnabled(logging::eTree | logging::eText)) {
-      logging::MsgBegin("TREE", "text node gains new content");
-      logging::Node("container", containerElm);
-      logging::Node("content", textNode);
-      logging::MsgEnd();
-    }
-#endif
-
-    // Make sure the text node is in accessible document still.
-    Accessible* container = document->GetAccessibleOrContainer(containerNode);
-    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
-
-NotificationController::ContentInsertion::
-  ContentInsertion(DocAccessible* aDocument, Accessible* aContainer) :
-  mDocument(aDocument), mContainer(aContainer)
-{
-}
-
-bool
-NotificationController::ContentInsertion::
-  InitChildList(nsIContent* aStartChildNode, nsIContent* aEndChildNode)
-{
-  bool haveToUpdate = false;
-
-  nsIContent* node = aStartChildNode;
-  while (node != aEndChildNode) {
-    // Notification triggers for content insertion even if no content was
-    // actually inserted, check if the given content has a frame to discard
-    // this case early.
-    if (node->GetPrimaryFrame()) {
-      if (mInsertedContent.AppendElement(node))
-        haveToUpdate = true;
-    }
-
-    node = node->GetNextSibling();
-  }
-
-  return haveToUpdate;
-}
-
-NS_IMPL_CYCLE_COLLECTION_1(NotificationController::ContentInsertion,
-                           mContainer)
-
-NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(NotificationController::ContentInsertion,
-                                     AddRef)
-NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(NotificationController::ContentInsertion,
-                                       Release)
-
-void
-NotificationController::ContentInsertion::Process()
-{
-  mDocument->ProcessContentInserted(mContainer, &mInsertedContent);
-
-  mDocument = nullptr;
-  mContainer = nullptr;
-  mInsertedContent.Clear();
-}
-
copy from accessible/src/base/NotificationController.h
copy to accessible/src/base/EventQueue.h
--- a/accessible/src/base/NotificationController.h
+++ b/accessible/src/base/EventQueue.h
@@ -1,207 +1,46 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#ifndef NotificationController_h_
-#define NotificationController_h_
+#ifndef mozilla_a11y_EventQueue_h_
+#define mozilla_a11y_EventQueue_h_
 
 #include "AccEvent.h"
-#include "nsCycleCollectionParticipant.h"
-#include "nsRefreshDriver.h"
-
-#ifdef A11Y_LOG
-#include "Logging.h"
-#endif
 
 class nsIContent;
 
 namespace mozilla {
 namespace a11y {
 
-class Accessible;
 class DocAccessible;
 
 /**
- * Notification interface.
+ * Used to organize and coalesce pending events.
  */
-class Notification
-{
-public:
-  virtual ~Notification() { }
-
-  NS_INLINE_DECL_REFCOUNTING(Notification)
-
-  /**
-   * Process notification.
-   */
-  virtual void Process() = 0;
-
-protected:
-  Notification() { }
-
-private:
-  Notification(const Notification&);
-  Notification& operator = (const Notification&);
-};
-
-
-/**
- * Template class for generic notification.
- *
- * @note  Instance is kept as a weak ref, the caller must guarantee it exists
- *        longer than the document accessible owning the notification controller
- *        that this notification is processed by.
- */
-template<class Class, class Arg>
-class TNotification : public Notification
+class EventQueue
 {
-public:
-  typedef void (Class::*Callback)(Arg*);
-
-  TNotification(Class* aInstance, Callback aCallback, Arg* aArg) :
-    mInstance(aInstance), mCallback(aCallback), mArg(aArg) { }
-  virtual ~TNotification() { mInstance = nullptr; }
-
-  virtual void Process()
-  {
-    (mInstance->*mCallback)(mArg);
-
-    mInstance = nullptr;
-    mCallback = nullptr;
-    mArg = nullptr;
-  }
-
-private:
-  TNotification(const TNotification&);
-  TNotification& operator = (const TNotification&);
-
-  Class* mInstance;
-  Callback mCallback;
-  nsRefPtr<Arg> mArg;
-};
-
-/**
- * Used to process notifications from core for the document accessible.
- */
-class NotificationController : public nsARefreshObserver
-{
-public:
-  NotificationController(DocAccessible* aDocument, nsIPresShell* aPresShell);
-  virtual ~NotificationController();
-
-  NS_IMETHOD_(nsrefcnt) AddRef(void);
-  NS_IMETHOD_(nsrefcnt) Release(void);
-
-  NS_DECL_CYCLE_COLLECTION_NATIVE_CLASS(NotificationController)
-
-  /**
-   * Shutdown the notification controller.
-   */
-  void Shutdown();
+protected:
+  EventQueue(DocAccessible* aDocument) : mDocument(aDocument) { }
 
   /**
    * Put an accessible event into the queue to process it later.
    */
-  void QueueEvent(AccEvent* aEvent);
-
-  /**
-   * Schedule binding the child document to the tree of this document.
-   */
-  void ScheduleChildDocBinding(DocAccessible* aDocument);
-
-  /**
-   * Schedule the accessible tree update because of rendered text changes.
-   */
-  inline void ScheduleTextUpdate(nsIContent* aTextNode)
-  {
-    if (mTextHash.PutEntry(aTextNode))
-      ScheduleProcessing();
-  }
-
-  /**
-   * Pend accessible tree update for content insertion.
-   */
-  void ScheduleContentInsertion(Accessible* aContainer,
-                                nsIContent* aStartChildNode,
-                                nsIContent* aEndChildNode);
+  bool PushEvent(AccEvent* aEvent);
 
   /**
-   * Process the generic notification synchronously if there are no pending
-   * layout changes and no notifications are pending or being processed right
-   * now. Otherwise, queue it up to process asynchronously.
-   *
-   * @note  The caller must guarantee that the given instance still exists when
-   *        the notification is processed.
+   * Process events from the queue and fires events.
    */
-  template<class Class, class Arg>
-  inline void HandleNotification(Class* aInstance,
-                                 typename TNotification<Class, Arg>::Callback aMethod,
-                                 Arg* aArg)
-  {
-    if (!IsUpdatePending()) {
-#ifdef A11Y_LOG
-      if (mozilla::a11y::logging::IsEnabled(mozilla::a11y::logging::eNotifications))
-        mozilla::a11y::logging::Text("sync notification processing");
-#endif
-      (aInstance->*aMethod)(aArg);
-      return;
-    }
-
-    nsRefPtr<Notification> notification =
-      new TNotification<Class, Arg>(aInstance, aMethod, aArg);
-    if (notification && mNotifications.AppendElement(notification))
-      ScheduleProcessing();
-  }
-
-  /**
-   * Schedule the generic notification to process asynchronously.
-   *
-   * @note  The caller must guarantee that the given instance still exists when
-   *        the notification is processed.
-   */
-  template<class Class, class Arg>
-  inline void ScheduleNotification(Class* aInstance,
-                                   typename TNotification<Class, Arg>::Callback aMethod,
-                                   Arg* aArg)
-  {
-    nsRefPtr<Notification> notification =
-      new TNotification<Class, Arg>(aInstance, aMethod, aArg);
-    if (notification && mNotifications.AppendElement(notification))
-      ScheduleProcessing();
-  }
-
-#ifdef DEBUG
-  bool IsUpdating() const
-    { return mObservingState == eRefreshProcessingForUpdate; }
-#endif
-
-protected:
-  nsCycleCollectingAutoRefCnt mRefCnt;
-  NS_DECL_OWNINGTHREAD
-
-  /**
-   * Start to observe refresh to make notifications and events processing after
-   * layout.
-   */
-  void ScheduleProcessing();
-
-  /**
-   * Return true if the accessible tree state update is pending.
-   */
-  bool IsUpdatePending();
+  void ProcessEventQueue();
 
 private:
-  NotificationController(const NotificationController&);
-  NotificationController& operator = (const NotificationController&);
-
-  // nsARefreshObserver
-  virtual void WillRefresh(mozilla::TimeStamp aTime);
+  EventQueue(const EventQueue&) MOZ_DELETE;
+  EventQueue& operator = (const EventQueue&) MOZ_DELETE;
 
   // Event queue processing
   /**
    * Coalesce redundant events from the queue.
    */
   void CoalesceEvents();
 
   /**
@@ -226,132 +65,26 @@ private:
 
   /**
     * Create text change event caused by hide or show event. When a node is
     * hidden/removed or shown/appended, the text in an ancestor hyper text will
     * lose or get new characters.
     */
    void CreateTextChangeEventFor(AccMutationEvent* aEvent);
 
-  // Event queue processing
-
-  /**
-   * Process events from the queue and fires events.
-   */
-  void ProcessEventQueue();
-
-private:
-  /**
-   * Indicates whether we're waiting on an event queue processing from our
-   * notification controller to flush events.
-   */
-  enum eObservingState {
-    eNotObservingRefresh,
-    eRefreshObserving,
-    eRefreshProcessingForUpdate
-  };
-  eObservingState mObservingState;
+protected:
 
   /**
    * The document accessible reference owning this queue.
    */
   nsRefPtr<DocAccessible> mDocument;
 
   /**
-   * The presshell of the document accessible.
-   */
-  nsIPresShell* mPresShell;
-
-  /**
-   * Child documents that needs to be bound to the tree.
-   */
-  nsTArray<nsRefPtr<DocAccessible> > mHangingChildDocuments;
-
-  /**
-   * Storage for content inserted notification information.
-   */
-  class ContentInsertion
-  {
-  public:
-    ContentInsertion(DocAccessible* aDocument, Accessible* aContainer);
-    virtual ~ContentInsertion() { mDocument = nullptr; }
-
-    NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(ContentInsertion)
-    NS_DECL_CYCLE_COLLECTION_NATIVE_CLASS(ContentInsertion)
-
-    bool InitChildList(nsIContent* aStartChildNode, nsIContent* aEndChildNode);
-    void Process();
-
-  private:
-    ContentInsertion();
-    ContentInsertion(const ContentInsertion&);
-    ContentInsertion& operator = (const ContentInsertion&);
-
-    // The document used to process content insertion, matched to document of
-    // the notification controller that this notification belongs to, therefore
-    // it's ok to keep it as weak ref.
-    DocAccessible* mDocument;
-
-    // The container accessible that content insertion occurs within.
-    nsRefPtr<Accessible> mContainer;
-
-    // Array of inserted contents.
-    nsTArray<nsCOMPtr<nsIContent> > mInsertedContent;
-  };
-
-  /**
-   * A pending accessible tree update notifications for content insertions.
-   * Don't make this an nsAutoTArray; we use SwapElements() on it.
-   */
-  nsTArray<nsRefPtr<ContentInsertion> > mContentInsertions;
-
-  template<class T>
-  class nsCOMPtrHashKey : public PLDHashEntryHdr
-  {
-  public:
-    typedef T* KeyType;
-    typedef const T* KeyTypePointer;
-
-    nsCOMPtrHashKey(const T* aKey) : mKey(const_cast<T*>(aKey)) {}
-    nsCOMPtrHashKey(const nsPtrHashKey<T> &aToCopy) : mKey(aToCopy.mKey) {}
-    ~nsCOMPtrHashKey() { }
-
-    KeyType GetKey() const { return mKey; }
-    bool KeyEquals(KeyTypePointer aKey) const { return aKey == mKey; }
-
-    static KeyTypePointer KeyToPointer(KeyType aKey) { return aKey; }
-    static PLDHashNumber HashKey(KeyTypePointer aKey)
-      { return NS_PTR_TO_INT32(aKey) >> 2; }
-
-    enum { ALLOW_MEMMOVE = true };
-
-   protected:
-     nsCOMPtr<T> mKey;
-  };
-
-  /**
-   * A pending accessible tree update notifications for rendered text changes.
-   */
-  nsTHashtable<nsCOMPtrHashKey<nsIContent> > mTextHash;
-
-  /**
-   * Update the accessible tree for pending rendered text change notifications.
-   */
-  static PLDHashOperator TextEnumerator(nsCOMPtrHashKey<nsIContent>* aEntry,
-                                        void* aUserArg);
-
-  /**
-   * Other notifications like DOM events. Don't make this an nsAutoTArray; we
-   * use SwapElements() on it.
-   */
-  nsTArray<nsRefPtr<Notification> > mNotifications;
-
-  /**
    * Pending events array. Don't make this an nsAutoTArray; we use
    * SwapElements() on it.
    */
   nsTArray<nsRefPtr<AccEvent> > mEvents;
 };
 
 } // namespace a11y
 } // namespace mozilla
 
-#endif
+#endif // mozilla_a11y_EventQueue_h_
--- a/accessible/src/base/Makefile.in
+++ b/accessible/src/base/Makefile.in
@@ -17,16 +17,17 @@ LIBXUL_LIBRARY = 1
 CPPSRCS = \
   AccCollector.cpp \
   AccEvent.cpp \
   AccGroupInfo.cpp \
   AccIterator.cpp \
   Filters.cpp \
   ARIAStateMap.cpp \
   DocManager.cpp \
+  EventQueue.cpp \
   FocusManager.cpp \
   NotificationController.cpp \
   nsAccessNode.cpp \
   nsARIAMap.cpp \
   nsCoreUtils.cpp \
   nsAccUtils.cpp \
   nsAccessibilityService.cpp \
   nsAccessiblePivot.cpp \
--- a/accessible/src/base/NotificationController.cpp
+++ b/accessible/src/base/NotificationController.cpp
@@ -1,47 +1,37 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "NotificationController.h"
 
 #include "Accessible-inl.h"
-#include "nsAccessibilityService.h"
-#include "nsAccUtils.h"
-#include "nsCoreUtils.h"
 #include "DocAccessible-inl.h"
-#include "nsEventShell.h"
-#include "FocusManager.h"
-#include "Role.h"
 #include "TextLeafAccessible.h"
 #include "TextUpdater.h"
 
-#ifdef A11Y_LOG
-#include "Logging.h"
-#endif
-
 #include "mozilla/dom/Element.h"
 #include "mozilla/Telemetry.h"
 
 using namespace mozilla;
 using namespace mozilla::a11y;
 
 // Defines the number of selection add/remove events in the queue when they
 // aren't packed into single selection within event.
 const unsigned int kSelChangeCountToPack = 5;
 
 ////////////////////////////////////////////////////////////////////////////////
 // NotificationCollector
 ////////////////////////////////////////////////////////////////////////////////
 
 NotificationController::NotificationController(DocAccessible* aDocument,
                                                nsIPresShell* aPresShell) :
-  mObservingState(eNotObservingRefresh), mDocument(aDocument),
+  EventQueue(aDocument), mObservingState(eNotObservingRefresh),
   mPresShell(aPresShell)
 {
   mTextHash.Init();
 
   // Schedule initial accessible tree construction.
   ScheduleProcessing();
 }
 
@@ -98,38 +88,16 @@ NotificationController::Shutdown()
 
   mTextHash.Clear();
   mContentInsertions.Clear();
   mNotifications.Clear();
   mEvents.Clear();
 }
 
 void
-NotificationController::QueueEvent(AccEvent* aEvent)
-{
-  NS_ASSERTION((aEvent->mAccessible && aEvent->mAccessible->IsApplication()) ||
-               aEvent->GetDocAccessible() == mDocument,
-               "Queued event belongs to another document!");
-
-  if (!mEvents.AppendElement(aEvent))
-    return;
-
-  // Filter events.
-  CoalesceEvents();
-
-  // Associate text change with hide event if it wasn't stolen from hiding
-  // siblings during coalescence.
-  AccMutationEvent* showOrHideEvent = downcast_accEvent(aEvent);
-  if (showOrHideEvent && !showOrHideEvent->mTextChangeEvent)
-    CreateTextChangeEventFor(showOrHideEvent);
-
-  ScheduleProcessing();
-}
-
-void
 NotificationController::ScheduleChildDocBinding(DocAccessible* aDocument)
 {
   // Schedule child document binding to the tree.
   mHangingChildDocuments.AppendElement(aDocument);
   ScheduleProcessing();
 }
 
 void
@@ -311,461 +279,16 @@ NotificationController::WillRefresh(mozi
       mEvents.Length() == 0 && mTextHash.Count() == 0 &&
       mHangingChildDocuments.Length() == 0 &&
       mDocument->HasLoadState(DocAccessible::eCompletelyLoaded) &&
       mPresShell->RemoveRefreshObserver(this, Flush_Display)) {
     mObservingState = eNotObservingRefresh;
   }
 }
 
-void
-NotificationController::CoalesceEvents()
-{
-  NS_ASSERTION(mEvents.Length(), "There should be at least one pending event!");
-  uint32_t tail = mEvents.Length() - 1;
-  AccEvent* tailEvent = mEvents[tail];
-
-  switch(tailEvent->mEventRule) {
-    case AccEvent::eCoalesceReorder:
-      CoalesceReorderEvents(tailEvent);
-      break; // case eCoalesceReorder
-
-    case AccEvent::eCoalesceMutationTextChange:
-    {
-      for (uint32_t index = tail - 1; index < tail; index--) {
-        AccEvent* thisEvent = mEvents[index];
-        if (thisEvent->mEventRule != tailEvent->mEventRule)
-          continue;
-
-        // We don't currently coalesce text change events from show/hide events.
-        if (thisEvent->mEventType != tailEvent->mEventType)
-          continue;
-
-        // Show events may be duped because of reinsertion (removal is ignored
-        // because initial insertion is not processed). Ignore initial
-        // insertion.
-        if (thisEvent->mAccessible == tailEvent->mAccessible)
-          thisEvent->mEventRule = AccEvent::eDoNotEmit;
-
-        AccMutationEvent* tailMutationEvent = downcast_accEvent(tailEvent);
-        AccMutationEvent* thisMutationEvent = downcast_accEvent(thisEvent);
-        if (tailMutationEvent->mParent != thisMutationEvent->mParent)
-          continue;
-
-        // Coalesce text change events for hide and show events.
-        if (thisMutationEvent->IsHide()) {
-          AccHideEvent* tailHideEvent = downcast_accEvent(tailEvent);
-          AccHideEvent* thisHideEvent = downcast_accEvent(thisEvent);
-          CoalesceTextChangeEventsFor(tailHideEvent, thisHideEvent);
-          break;
-        }
-
-        AccShowEvent* tailShowEvent = downcast_accEvent(tailEvent);
-        AccShowEvent* thisShowEvent = downcast_accEvent(thisEvent);
-        CoalesceTextChangeEventsFor(tailShowEvent, thisShowEvent);
-        break;
-      }
-    } break; // case eCoalesceMutationTextChange
-
-    case AccEvent::eCoalesceOfSameType:
-    {
-      // Coalesce old events by newer event.
-      for (uint32_t index = tail - 1; index < tail; index--) {
-        AccEvent* accEvent = mEvents[index];
-        if (accEvent->mEventType == tailEvent->mEventType &&
-          accEvent->mEventRule == tailEvent->mEventRule) {
-          accEvent->mEventRule = AccEvent::eDoNotEmit;
-          return;
-        }
-      }
-    } break; // case eCoalesceOfSameType
-
-    case AccEvent::eCoalesceSelectionChange:
-    {
-      AccSelChangeEvent* tailSelChangeEvent = downcast_accEvent(tailEvent);
-      for (uint32_t index = tail - 1; index < tail; index--) {
-        AccEvent* thisEvent = mEvents[index];
-        if (thisEvent->mEventRule == tailEvent->mEventRule) {
-          AccSelChangeEvent* thisSelChangeEvent =
-            downcast_accEvent(thisEvent);
-
-          // Coalesce selection change events within same control.
-          if (tailSelChangeEvent->mWidget == thisSelChangeEvent->mWidget) {
-            CoalesceSelChangeEvents(tailSelChangeEvent, thisSelChangeEvent, index);
-            return;
-          }
-        }
-      }
-
-    } break; // eCoalesceSelectionChange
-
-    case AccEvent::eCoalesceStateChange:
-    {
-      // If state change event is duped then ignore previous event. If state
-      // change event is opposite to previous event then no event is emitted
-      // (accessible state wasn't changed).
-      for (uint32_t index = tail - 1; index < tail; index--) {
-        AccEvent* thisEvent = mEvents[index];
-        if (thisEvent->mEventRule != AccEvent::eDoNotEmit &&
-            thisEvent->mEventType == tailEvent->mEventType &&
-            thisEvent->mAccessible == tailEvent->mAccessible) {
-          AccStateChangeEvent* thisSCEvent = downcast_accEvent(thisEvent);
-          AccStateChangeEvent* tailSCEvent = downcast_accEvent(tailEvent);
-          if (thisSCEvent->mState == tailSCEvent->mState) {
-            thisEvent->mEventRule = AccEvent::eDoNotEmit;
-            if (thisSCEvent->mIsEnabled != tailSCEvent->mIsEnabled)
-              tailEvent->mEventRule = AccEvent::eDoNotEmit;
-          }
-        }
-      }
-      break; // eCoalesceStateChange
-    }
-
-    case AccEvent::eRemoveDupes:
-    {
-      // Check for repeat events, coalesce newly appended event by more older
-      // event.
-      for (uint32_t index = tail - 1; index < tail; index--) {
-        AccEvent* accEvent = mEvents[index];
-        if (accEvent->mEventType == tailEvent->mEventType &&
-          accEvent->mEventRule == tailEvent->mEventRule &&
-          accEvent->mAccessible == tailEvent->mAccessible) {
-          tailEvent->mEventRule = AccEvent::eDoNotEmit;
-          return;
-        }
-      }
-    } break; // case eRemoveDupes
-
-    default:
-      break; // case eAllowDupes, eDoNotEmit
-  } // switch
-}
-
-void
-NotificationController::CoalesceReorderEvents(AccEvent* aTailEvent)
-{
-  uint32_t count = mEvents.Length();
-  for (uint32_t index = count - 2; index < count; index--) {
-    AccEvent* thisEvent = mEvents[index];
-
-    // Skip events of different types and targeted to application accessible.
-    if (thisEvent->mEventType != aTailEvent->mEventType ||
-        thisEvent->mAccessible->IsApplication())
-      continue;
-
-    // If thisEvent target is not in document longer, i.e. if it was
-    // removed from the tree then do not emit the event.
-    if (!thisEvent->mAccessible->IsDoc() &&
-        !thisEvent->mAccessible->IsInDocument()) {
-      thisEvent->mEventRule = AccEvent::eDoNotEmit;
-      continue;
-    }
-
-    // Coalesce earlier event of the same target.
-    if (thisEvent->mAccessible == aTailEvent->mAccessible) {
-      if (thisEvent->mEventRule == AccEvent::eDoNotEmit) {
-        AccReorderEvent* tailReorder = downcast_accEvent(aTailEvent);
-        tailReorder->DoNotEmitAll();
-      } else {
-        thisEvent->mEventRule = AccEvent::eDoNotEmit;
-      }
-
-      return;
-    }
-
-    // If tailEvent contains thisEvent
-    // then
-    //   if show of tailEvent contains a grand parent of thisEvent
-    //   then assert
-    //   else if hide of tailEvent contains a grand parent of thisEvent
-    //   then ignore thisEvent and its show and hide events
-    //   otherwise ignore thisEvent but not its show and hide events
-    Accessible* thisParent = thisEvent->mAccessible;
-    while (thisParent && thisParent != mDocument) {
-      if (thisParent->Parent() == aTailEvent->mAccessible) {
-        AccReorderEvent* tailReorder = downcast_accEvent(aTailEvent);
-        uint32_t eventType = tailReorder->IsShowHideEventTarget(thisParent);
-
-        if (eventType == nsIAccessibleEvent::EVENT_SHOW) {
-           NS_ERROR("Accessible tree was created after it was modified! Huh?");
-        } else if (eventType == nsIAccessibleEvent::EVENT_HIDE) {
-          AccReorderEvent* thisReorder = downcast_accEvent(thisEvent);
-          thisReorder->DoNotEmitAll();
-        } else {
-          thisEvent->mEventRule = AccEvent::eDoNotEmit;
-        }
-
-        return;
-      }
-
-      thisParent = thisParent->Parent();
-    }
-
-    // If tailEvent is contained by thisEvent
-    // then
-    //   if show of thisEvent contains the tailEvent
-    //   then ignore tailEvent
-    //   if hide of thisEvent contains the tailEvent
-    //   then assert
-    //   otherwise ignore tailEvent but not its show and hide events
-    Accessible* tailParent = aTailEvent->mAccessible;
-    while (tailParent && tailParent != mDocument) {
-      if (tailParent->Parent() == thisEvent->mAccessible) {
-        AccReorderEvent* thisReorder = downcast_accEvent(thisEvent);
-        AccReorderEvent* tailReorder = downcast_accEvent(aTailEvent);
-        uint32_t eventType = thisReorder->IsShowHideEventTarget(tailParent);
-        if (eventType == nsIAccessibleEvent::EVENT_SHOW)
-          tailReorder->DoNotEmitAll();
-        else if (eventType == nsIAccessibleEvent::EVENT_HIDE)
-          NS_ERROR("Accessible tree was modified after it was removed! Huh?");
-        else
-          aTailEvent->mEventRule = AccEvent::eDoNotEmit;
-
-        return;
-      }
-
-      tailParent = tailParent->Parent();
-    }
-
-  } // for (index)
-}
-
-void
-NotificationController::CoalesceSelChangeEvents(AccSelChangeEvent* aTailEvent,
-                                                AccSelChangeEvent* aThisEvent,
-                                                uint32_t aThisIndex)
-{
-  aTailEvent->mPreceedingCount = aThisEvent->mPreceedingCount + 1;
-
-  // Pack all preceding events into single selection within event
-  // when we receive too much selection add/remove events.
-  if (aTailEvent->mPreceedingCount >= kSelChangeCountToPack) {
-    aTailEvent->mEventType = nsIAccessibleEvent::EVENT_SELECTION_WITHIN;
-    aTailEvent->mAccessible = aTailEvent->mWidget;
-    aThisEvent->mEventRule = AccEvent::eDoNotEmit;
-
-    // Do not emit any preceding selection events for same widget if they
-    // weren't coalesced yet.
-    if (aThisEvent->mEventType != nsIAccessibleEvent::EVENT_SELECTION_WITHIN) {
-      for (uint32_t jdx = aThisIndex - 1; jdx < aThisIndex; jdx--) {
-        AccEvent* prevEvent = mEvents[jdx];
-        if (prevEvent->mEventRule == aTailEvent->mEventRule) {
-          AccSelChangeEvent* prevSelChangeEvent =
-            downcast_accEvent(prevEvent);
-          if (prevSelChangeEvent->mWidget == aTailEvent->mWidget)
-            prevSelChangeEvent->mEventRule = AccEvent::eDoNotEmit;
-        }
-      }
-    }
-    return;
-  }
-
-  // Pack sequential selection remove and selection add events into
-  // single selection change event.
-  if (aTailEvent->mPreceedingCount == 1 &&
-      aTailEvent->mItem != aThisEvent->mItem) {
-    if (aTailEvent->mSelChangeType == AccSelChangeEvent::eSelectionAdd &&
-        aThisEvent->mSelChangeType == AccSelChangeEvent::eSelectionRemove) {
-      aThisEvent->mEventRule = AccEvent::eDoNotEmit;
-      aTailEvent->mEventType = nsIAccessibleEvent::EVENT_SELECTION;
-      aTailEvent->mPackedEvent = aThisEvent;
-      return;
-    }
-
-    if (aThisEvent->mSelChangeType == AccSelChangeEvent::eSelectionAdd &&
-        aTailEvent->mSelChangeType == AccSelChangeEvent::eSelectionRemove) {
-      aTailEvent->mEventRule = AccEvent::eDoNotEmit;
-      aThisEvent->mEventType = nsIAccessibleEvent::EVENT_SELECTION;
-      aThisEvent->mPackedEvent = aThisEvent;
-      return;
-    }
-  }
-
-  // Unpack the packed selection change event because we've got one
-  // more selection add/remove.
-  if (aThisEvent->mEventType == nsIAccessibleEvent::EVENT_SELECTION) {
-    if (aThisEvent->mPackedEvent) {
-      aThisEvent->mPackedEvent->mEventType =
-        aThisEvent->mPackedEvent->mSelChangeType == AccSelChangeEvent::eSelectionAdd ?
-          nsIAccessibleEvent::EVENT_SELECTION_ADD :
-          nsIAccessibleEvent::EVENT_SELECTION_REMOVE;
-
-      aThisEvent->mPackedEvent->mEventRule =
-        AccEvent::eCoalesceSelectionChange;
-
-      aThisEvent->mPackedEvent = nullptr;
-    }
-
-    aThisEvent->mEventType =
-      aThisEvent->mSelChangeType == AccSelChangeEvent::eSelectionAdd ?
-        nsIAccessibleEvent::EVENT_SELECTION_ADD :
-        nsIAccessibleEvent::EVENT_SELECTION_REMOVE;
-
-    return;
-  }
-
-  // Convert into selection add since control has single selection but other
-  // selection events for this control are queued.
-  if (aTailEvent->mEventType == nsIAccessibleEvent::EVENT_SELECTION)
-    aTailEvent->mEventType = nsIAccessibleEvent::EVENT_SELECTION_ADD;
-}
-
-void
-NotificationController::CoalesceTextChangeEventsFor(AccHideEvent* aTailEvent,
-                                                    AccHideEvent* aThisEvent)
-{
-  // XXX: we need a way to ignore SplitNode and JoinNode() when they do not
-  // affect the text within the hypertext.
-
-  AccTextChangeEvent* textEvent = aThisEvent->mTextChangeEvent;
-  if (!textEvent)
-    return;
-
-  if (aThisEvent->mNextSibling == aTailEvent->mAccessible) {
-    aTailEvent->mAccessible->AppendTextTo(textEvent->mModifiedText);
-
-  } else if (aThisEvent->mPrevSibling == aTailEvent->mAccessible) {
-    uint32_t oldLen = textEvent->GetLength();
-    aTailEvent->mAccessible->AppendTextTo(textEvent->mModifiedText);
-    textEvent->mStart -= textEvent->GetLength() - oldLen;
-  }
-
-  aTailEvent->mTextChangeEvent.swap(aThisEvent->mTextChangeEvent);
-}
-
-void
-NotificationController::CoalesceTextChangeEventsFor(AccShowEvent* aTailEvent,
-                                                    AccShowEvent* aThisEvent)
-{
-  AccTextChangeEvent* textEvent = aThisEvent->mTextChangeEvent;
-  if (!textEvent)
-    return;
-
-  if (aTailEvent->mAccessible->IndexInParent() ==
-      aThisEvent->mAccessible->IndexInParent() + 1) {
-    // If tail target was inserted after this target, i.e. tail target is next
-    // sibling of this target.
-    aTailEvent->mAccessible->AppendTextTo(textEvent->mModifiedText);
-
-  } else if (aTailEvent->mAccessible->IndexInParent() ==
-             aThisEvent->mAccessible->IndexInParent() -1) {
-    // If tail target was inserted before this target, i.e. tail target is
-    // previous sibling of this target.
-    nsAutoString startText;
-    aTailEvent->mAccessible->AppendTextTo(startText);
-    textEvent->mModifiedText = startText + textEvent->mModifiedText;
-    textEvent->mStart -= startText.Length();
-  }
-
-  aTailEvent->mTextChangeEvent.swap(aThisEvent->mTextChangeEvent);
-}
-
-void
-NotificationController::CreateTextChangeEventFor(AccMutationEvent* aEvent)
-{
-  Accessible* container = aEvent->mAccessible->Parent();
-  if (!container)
-    return;
-
-  HyperTextAccessible* textAccessible = container->AsHyperText();
-  if (!textAccessible)
-    return;
-
-  // Don't fire event for the first html:br in an editor.
-  if (aEvent->mAccessible->Role() == roles::WHITESPACE) {
-    nsCOMPtr<nsIEditor> editor = textAccessible->GetEditor();
-    if (editor) {
-      bool isEmpty = false;
-      editor->GetDocumentIsEmpty(&isEmpty);
-      if (isEmpty)
-        return;
-    }
-  }
-
-  int32_t offset = textAccessible->GetChildOffset(aEvent->mAccessible);
-
-  nsAutoString text;
-  aEvent->mAccessible->AppendTextTo(text);
-  if (text.IsEmpty())
-    return;
-
-  aEvent->mTextChangeEvent =
-    new AccTextChangeEvent(textAccessible, offset, text, aEvent->IsShow(),
-                           aEvent->mIsFromUserInput ? eFromUserInput : eNoUserInput);
-}
-
-////////////////////////////////////////////////////////////////////////////////
-// NotificationController: event queue
-
-void
-NotificationController::ProcessEventQueue()
-{
-  // Process only currently queued events.
-  nsTArray<nsRefPtr<AccEvent> > events;
-  events.SwapElements(mEvents);
-
-  uint32_t eventCount = events.Length();
-#ifdef A11Y_LOG
-  if (eventCount > 0 && logging::IsEnabled(logging::eEvents)) {
-    logging::MsgBegin("EVENTS", "events processing");
-    logging::Address("document", mDocument);
-    logging::MsgEnd();
-  }
-#endif
-
-  for (uint32_t idx = 0; idx < eventCount; idx++) {
-    AccEvent* event = events[idx];
-    if (event->mEventRule != AccEvent::eDoNotEmit) {
-      Accessible* target = event->GetAccessible();
-      if (!target || target->IsDefunct())
-        continue;
-
-      // Dispatch the focus event if target is still focused.
-      if (event->mEventType == nsIAccessibleEvent::EVENT_FOCUS) {
-        FocusMgr()->ProcessFocusEvent(event);
-        continue;
-      }
-
-      // Dispatch caret moved and text selection change events.
-      if (event->mEventType == nsIAccessibleEvent::EVENT_TEXT_CARET_MOVED) {
-        AccCaretMoveEvent* caretMoveEvent = downcast_accEvent(event);
-        HyperTextAccessible* hyperText = target->AsHyperText();
-        if (hyperText &&
-            NS_SUCCEEDED(hyperText->GetCaretOffset(&caretMoveEvent->mCaretOffset))) {
-
-          nsEventShell::FireEvent(caretMoveEvent);
-
-          // There's a selection so fire selection change as well.
-          int32_t selectionCount;
-          hyperText->GetSelectionCount(&selectionCount);
-          if (selectionCount)
-            nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_TEXT_SELECTION_CHANGED,
-                                    hyperText);
-        }
-        continue;
-      }
-
-      nsEventShell::FireEvent(event);
-
-      // Fire text change events.
-      AccMutationEvent* mutationEvent = downcast_accEvent(event);
-      if (mutationEvent) {
-        if (mutationEvent->mTextChangeEvent)
-          nsEventShell::FireEvent(mutationEvent->mTextChangeEvent);
-      }
-    }
-
-    if (event->mEventType == nsIAccessibleEvent::EVENT_HIDE)
-      mDocument->ShutdownChildrenInSubtree(event->mAccessible);
-
-    if (!mDocument)
-      return;
-  }
-}
-
 ////////////////////////////////////////////////////////////////////////////////
 // Notification controller: text leaf accessible text update
 
 PLDHashOperator
 NotificationController::TextEnumerator(nsCOMPtrHashKey<nsIContent>* aEntry,
                                        void* aUserArg)
 {
   DocAccessible* document = static_cast<DocAccessible*>(aUserArg);
--- a/accessible/src/base/NotificationController.h
+++ b/accessible/src/base/NotificationController.h
@@ -1,17 +1,18 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#ifndef NotificationController_h_
-#define NotificationController_h_
+#ifndef mozilla_a11y_NotificationController_h_
+#define mozilla_a11y_NotificationController_h_
 
-#include "AccEvent.h"
+#include "EventQueue.h"
+
 #include "nsCycleCollectionParticipant.h"
 #include "nsRefreshDriver.h"
 
 #ifdef A11Y_LOG
 #include "Logging.h"
 #endif
 
 class nsIContent;
@@ -79,17 +80,18 @@ private:
   Class* mInstance;
   Callback mCallback;
   nsRefPtr<Arg> mArg;
 };
 
 /**
  * Used to process notifications from core for the document accessible.
  */
-class NotificationController : public nsARefreshObserver
+class NotificationController : public EventQueue,
+                               public nsARefreshObserver
 {
 public:
   NotificationController(DocAccessible* aDocument, nsIPresShell* aPresShell);
   virtual ~NotificationController();
 
   NS_IMETHOD_(nsrefcnt) AddRef(void);
   NS_IMETHOD_(nsrefcnt) Release(void);
 
@@ -98,17 +100,21 @@ public:
   /**
    * Shutdown the notification controller.
    */
   void Shutdown();
 
   /**
    * Put an accessible event into the queue to process it later.
    */
-  void QueueEvent(AccEvent* aEvent);
+  void QueueEvent(AccEvent* aEvent)
+  {
+    if (PushEvent(aEvent))
+      ScheduleProcessing();
+  }
 
   /**
    * Schedule binding the child document to the tree of this document.
    */
   void ScheduleChildDocBinding(DocAccessible* aDocument);
 
   /**
    * Schedule the accessible tree update because of rendered text changes.
@@ -193,74 +199,29 @@ protected:
 
 private:
   NotificationController(const NotificationController&);
   NotificationController& operator = (const NotificationController&);
 
   // nsARefreshObserver
   virtual void WillRefresh(mozilla::TimeStamp aTime);
 
-  // Event queue processing
-  /**
-   * Coalesce redundant events from the queue.
-   */
-  void CoalesceEvents();
-
-  /**
-   * Coalesce events from the same subtree.
-   */
-  void CoalesceReorderEvents(AccEvent* aTailEvent);
-
-  /**
-   * Coalesce two selection change events within the same select control.
-   */
-  void CoalesceSelChangeEvents(AccSelChangeEvent* aTailEvent,
-                               AccSelChangeEvent* aThisEvent,
-                               uint32_t aThisIndex);
-
-  /**
-   * Coalesce text change events caused by sibling hide events.
-   */
-  void CoalesceTextChangeEventsFor(AccHideEvent* aTailEvent,
-                                   AccHideEvent* aThisEvent);
-  void CoalesceTextChangeEventsFor(AccShowEvent* aTailEvent,
-                                   AccShowEvent* aThisEvent);
-
-  /**
-    * Create text change event caused by hide or show event. When a node is
-    * hidden/removed or shown/appended, the text in an ancestor hyper text will
-    * lose or get new characters.
-    */
-   void CreateTextChangeEventFor(AccMutationEvent* aEvent);
-
-  // Event queue processing
-
-  /**
-   * Process events from the queue and fires events.
-   */
-  void ProcessEventQueue();
-
 private:
   /**
    * Indicates whether we're waiting on an event queue processing from our
    * notification controller to flush events.
    */
   enum eObservingState {
     eNotObservingRefresh,
     eRefreshObserving,
     eRefreshProcessingForUpdate
   };
   eObservingState mObservingState;
 
   /**
-   * The document accessible reference owning this queue.
-   */
-  nsRefPtr<DocAccessible> mDocument;
-
-  /**
    * The presshell of the document accessible.
    */
   nsIPresShell* mPresShell;
 
   /**
    * Child documents that needs to be bound to the tree.
    */
   nsTArray<nsRefPtr<DocAccessible> > mHangingChildDocuments;
@@ -338,20 +299,14 @@ private:
   static PLDHashOperator TextEnumerator(nsCOMPtrHashKey<nsIContent>* aEntry,
                                         void* aUserArg);
 
   /**
    * Other notifications like DOM events. Don't make this an nsAutoTArray; we
    * use SwapElements() on it.
    */
   nsTArray<nsRefPtr<Notification> > mNotifications;
-
-  /**
-   * Pending events array. Don't make this an nsAutoTArray; we use
-   * SwapElements() on it.
-   */
-  nsTArray<nsRefPtr<AccEvent> > mEvents;
 };
 
 } // namespace a11y
 } // namespace mozilla
 
-#endif
+#endif // mozilla_a11y_NotificationController_h_
--- a/accessible/src/generic/DocAccessible.h
+++ b/accessible/src/generic/DocAccessible.h
@@ -576,16 +576,17 @@ protected:
    * @see ProcessInvalidationList
    */
   nsTArray<nsIContent*> mInvalidationList;
 
   /**
    * Used to process notification from core and accessible events.
    */
   nsRefPtr<NotificationController> mNotificationController;
+  friend class EventQueue;
   friend class NotificationController;
 
 private:
 
   nsIPresShell* mPresShell;
 };
 
 inline DocAccessible*
--- a/accessible/src/generic/HyperTextAccessible.cpp
+++ b/accessible/src/generic/HyperTextAccessible.cpp
@@ -1179,16 +1179,19 @@ HyperTextAccessible::NativeAttributes()
     nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles,
                            NS_LITERAL_STRING("contentinfo"));
   else if (mContent->Tag() == nsGkAtoms::aside) 
     nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles,
                            NS_LITERAL_STRING("complementary"));
   else if (mContent->Tag() == nsGkAtoms::article)
     nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles,
                            NS_LITERAL_STRING("article"));
+  else if (mContent->Tag() == nsGkAtoms::main)
+    nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles,
+                           NS_LITERAL_STRING("main"));
 
   return attributes.forget();
 }
 
 /*
  * Given an offset, the x, y, width, and height values are filled appropriately.
  */
 NS_IMETHODIMP
--- a/accessible/tests/mochitest/attributes/test_xml-roles.html
+++ b/accessible/tests/mochitest/attributes/test_xml-roles.html
@@ -22,16 +22,17 @@
       // Some AT may look for this
       testAttrs("nav", {"xml-roles" : "navigation"}, true);
       testAttrs("footer", {"xml-roles" : "contentinfo"}, true);
       testAttrs("aside", {"xml-roles" : "complementary"}, true);
       testAttrs("section", {"xml-roles" : "region"}, true);
       testAttrs("main", {"xml-roles" : "main"}, true); // // ARIA override
       testAttrs("form", {"xml-roles" : "form"}, true);
       testAttrs("article", {"xml-roles" : "article"}, true);
+      testAttrs("main_element", {"xml-roles" : "main"}, true);
 
       SimpleTest.finish();
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   </script>
 </head>
@@ -74,11 +75,12 @@
 
   <nav id="nav">a nav</nav>
   <footer id="footer">a footer</footer>
   <aside id="aside">by the way I am an aside</aside>
   <section id="section">a section</section>
   <article id="main" role="main">a main area</article>
   <article id="form" role="form">a form area</article>
   <article id="article">article</article>
+  <main id="main_element">another main area</main>
 
 </body>
 </html>
--- a/accessible/tests/mochitest/events/test_scroll.xul
+++ b/accessible/tests/mochitest/events/test_scroll.xul
@@ -114,18 +114,22 @@
       gQueue.push(new loadTab(url));
       gQueue.push(new loadTabInBackground(url));
       gQueue.push(new switchToBackgroundTab());
       gQueue.onFinish = function() { closeBrowserWindow(); }
 
       gQueue.invoke(); // Will call SimpleTest.finish();
     }
 
-    SimpleTest.waitForExplicitFinish();
-    openBrowserWindow(doTest);
+    if (!MAC) {
+      SimpleTest.waitForExplicitFinish();
+      openBrowserWindow(doTest);
+    } else {
+      todo(false, "Re-enable on Mac after fixing bug 835338");
+    }
   ]]>
   </script>
 
   <vbox flex="1" style="overflow: auto;">
     <body xmlns="http://www.w3.org/1999/xhtml">
       <a target="_blank"
          href="https://bugzilla.mozilla.org/show_bug.cgi?id=691734"
          title="Make sure scrolling start event is fired when document receive focus">
--- a/b2g/app/b2g.js
+++ b/b2g/app/b2g.js
@@ -440,16 +440,20 @@ pref("full-screen-api.ignore-widgets", t
 #endif
 
 pref("media.volume.steps", 10);
 
 #ifdef ENABLE_MARIONETTE
 //Enable/disable marionette server, set listening port
 pref("marionette.defaultPrefs.enabled", true);
 pref("marionette.defaultPrefs.port", 2828);
+#ifndef MOZ_WIDGET_GONK
+// On desktop builds, we need to force the socket to listen on localhost only
+pref("marionette.force-local", true);
+#endif
 #endif
 
 #ifdef MOZ_UPDATER
 // When we're applying updates, we can't let anything hang us on
 // quit+restart.  The user has no recourse.
 pref("shutdown.watchdog.timeoutSecs", 5);
 // Timeout before the update prompt automatically installs the update
 pref("b2g.update.apply-prompt-timeout", 60000); // milliseconds
rename from browser/app/profile/extensions/testpilot@labs.mozilla.com/modules/setup.js.in
rename to browser/app/profile/extensions/testpilot@labs.mozilla.com/modules/setup.js
--- a/browser/app/profile/extensions/testpilot@labs.mozilla.com/modules/setup.js.in
+++ b/browser/app/profile/extensions/testpilot@labs.mozilla.com/modules/setup.js
@@ -167,20 +167,16 @@ let TestPilotSetup = {
 
     // Set up observation for task state changes
     var self = this;
     this._obs.add("testpilot:task:changed", this.onTaskStatusChanged, self);
     this._obs.add(
       "testpilot:task:dataAutoSubmitted", this._onTaskDataAutoSubmitted, self);
     // Set up observation for application shutdown.
     this._obs.add("quit-application", this.globalShutdown, self);
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-    // Set up observation for enter/exit private browsing:
-    this._obs.add("private-browsing", this.onPrivateBrowsingMode, self);
-#endif
 
     // Set up timers to remind user x minutes after startup
     // and once per day thereafter.  Use nsITimer so it doesn't belong to
     // any one window.
     logger.trace("Setting interval for showing reminders...");
 
     this._shortTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
     this._shortTimer.initWithCallback(
@@ -240,44 +236,29 @@ let TestPilotSetup = {
       self.taskList[i].onExperimentShutdown();
     }
     this.taskList = [];
     this._loader.unload();
     this._obs.remove("testpilot:task:changed", this.onTaskStatusChanged, self);
     this._obs.remove(
       "testpilot:task:dataAutoSubmitted", this._onTaskDataAutoSubmitted, self);
     this._obs.remove("quit-application", this.globalShutdown, self);
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-    this._obs.remove("private-browsing", this.onPrivateBrowsingMode, self);
-#endif
     this._loader.unload();
     this._shortTimer.cancel();
     this._longTimer.cancel();
     logger.trace("Done unregistering everything.");
   },
 
   _getFrontBrowserWindow: function TPS__getFrontWindow() {
     let wm = Cc["@mozilla.org/appshell/window-mediator;1"].
                getService(Ci.nsIWindowMediator);
     // TODO Is "most recent" the same as "front"?
     return wm.getMostRecentWindow("navigator:browser");
   },
 
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-  onPrivateBrowsingMode: function TPS_onPrivateBrowsingMode(topic, data) {
-    for (let i = 0; i < this.taskList.length; i++) {
-      if (data == "enter") {
-        this.taskList[i].onEnterPrivateBrowsing();
-      } else if (data == "exit") {
-        this.taskList[i].onExitPrivateBrowsing();
-      }
-    }
-  },
-#endif
-
   onWindowUnload: function TPS__onWindowRegistered(window) {
     this._logger.trace("Called TestPilotSetup.onWindow unload!");
     for (let i = 0; i < this.taskList.length; i++) {
       this.taskList[i].onWindowClosed(window);
     }
   },
 
   onWindowLoad: function TPS_onWindowLoad(window) {
rename from browser/app/profile/extensions/testpilot@labs.mozilla.com/modules/tasks.js.in
rename to browser/app/profile/extensions/testpilot@labs.mozilla.com/modules/tasks.js
--- a/browser/app/profile/extensions/testpilot@labs.mozilla.com/modules/tasks.js.in
+++ b/browser/app/profile/extensions/testpilot@labs.mozilla.com/modules/tasks.js
@@ -157,24 +157,16 @@ var TestPilotTask = {
   onAppStartup: function TestPilotTask_onAppStartup() {
     // Called by extension core when Firefox startup is complete.
   },
 
   onAppShutdown: function TestPilotTask_onAppShutdown() {
     // Called by extension core when Firefox is shutting down.
   },
 
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-  onEnterPrivateBrowsing: function TestPilotTask_onEnterPrivate() {
-  },
-
-  onExitPrivateBrowsing: function TestPilotTask_onExitPrivate() {
-  },
-#endif
-
   onNewWindow: function TestPilotTask_onNewWindow(window) {
   },
 
   onWindowClosed: function TestPilotTask_onWindowClosed(window) {
   },
 
   onUrlLoad: function TestPilotTask_onUrlLoad(url) {
   },
@@ -529,40 +521,16 @@ TestPilotExperiment.prototype = {
       try {
         this._handlers.doExperimentCleanup();
       } catch(e) {
         this._dataStore.logException("doExperimentCleanup: " + e);
       }
     }
   },
 
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-  onEnterPrivateBrowsing: function TestPilotExperiment_onEnterPrivate() {
-    this._logger.trace("Task is entering private browsing.");
-    if (this.experimentIsRunning()) {
-      try {
-        this._handlers.onEnterPrivateBrowsing();
-      } catch(e) {
-        this._dataStore.logException("onEnterPrivateBrowsing: " + e);
-      }
-    }
-  },
-
-  onExitPrivateBrowsing: function TestPilotExperiment_onExitPrivate() {
-    this._logger.trace("Task is exiting private browsing.");
-    if (this.experimentIsRunning()) {
-      try {
-        this._handlers.onExitPrivateBrowsing();
-      } catch(e) {
-        this._dataStore.logException("onExitPrivateBrowsing: " + e);
-      }
-    }
-  },
-#endif
-
   getStudyMetadata: function TestPilotExperiment_getStudyMetadata() {
     try {
       if (this._handlers.getStudyMetadata) {
         let metadata = this._handlers.getStudyMetadata();
         if (metadata.length) {
           // getStudyMetadata must return an array, otherwise it is invalid.
           return metadata;
         }
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -873,21 +873,16 @@ pref("toolkit.crashreporter.infoURL",
 pref("app.support.baseURL", "http://support.mozilla.org/1/firefox/%VERSION%/%OS%/%LOCALE%/");
 
 // Name of alternate about: page for certificate errors (when undefined, defaults to about:neterror)
 pref("security.alternate_certificate_error_page", "certerror");
 
 // Whether to start the private browsing mode at application startup
 pref("browser.privatebrowsing.autostart", false);
 
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-// Whether we should skip prompting before starting the private browsing mode
-pref("browser.privatebrowsing.dont_prompt_on_enter", false);
-#endif
-
 // Don't try to alter this pref, it'll be reset the next time you use the
 // bookmarking dialog
 pref("browser.bookmarks.editDialog.firstEditField", "namePicker");
 
 // Whether to use a panel that looks like an OS X sheet for customization
 #ifdef XP_MACOSX
 pref("toolbar.customization.usesheet", true);
 #else
--- a/browser/base/content/browser-appmenu.inc
+++ b/browser/base/content/browser-appmenu.inc
@@ -29,31 +29,21 @@
                       key="key_newNavigator"/>
             <menuseparator/>
             <menuitem id="appmenu_openFile"
                       label="&openFileCmd.label;"
                       command="Browser:OpenFile"
                       key="openFileKb"/>
           </menupopup>
       </splitmenu>
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
       <menuitem id="appmenu_newPrivateWindow"
                 class="menuitem-iconic menuitem-iconic-tooltip"
                 label="&newPrivateWindow.label;"
                 command="Tools:PrivateBrowsing"
                 key="key_privatebrowsing"/>
-#else
-      <menuitem id="appmenu_privateBrowsing"
-                class="menuitem-iconic menuitem-iconic-tooltip"
-                label="&privateBrowsingCmd.start.label;"
-                startlabel="&privateBrowsingCmd.start.label;"
-                stoplabel="&privateBrowsingCmd.stop.label;"
-                command="Tools:PrivateBrowsing"
-                key="key_privatebrowsing"/>
-#endif
       <menuitem label="&goOfflineCmd.label;"
                 id="appmenu_offlineModeRecovery"
                 type="checkbox"
                 observes="workOfflineMenuitemState"
                 oncommand="BrowserOffline.toggleOfflineStatus();"/>
       <menuseparator class="appmenu-menuseparator"/>
       <hbox>
         <menuitem id="appmenu-edit-label"
--- a/browser/base/content/browser-context.inc
+++ b/browser/base/content/browser-context.inc
@@ -23,22 +23,20 @@
       <menuitem id="context-openlinkintab"
                 label="&openLinkCmdInTab.label;"
                 accesskey="&openLinkCmdInTab.accesskey;"
                 oncommand="gContextMenu.openLinkInTab();"/>
       <menuitem id="context-openlink"
                 label="&openLinkCmd.label;"
                 accesskey="&openLinkCmd.accesskey;"
                 oncommand="gContextMenu.openLink();"/>
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
       <menuitem id="context-openlinkprivate"
                 label="&openLinkInPrivateWindowCmd.label;"
                 accesskey="&openLinkInPrivateWindowCmd.accesskey;"
                 oncommand="gContextMenu.openLinkInPrivateWindow();"/>
-#endif
       <menuseparator id="context-sep-open"/>
       <menuitem id="context-bookmarklink"
                 label="&bookmarkThisLinkCmd.label;"
                 accesskey="&bookmarkThisLinkCmd.accesskey;"
                 oncommand="gContextMenu.bookmarkLink();"/>
       <menuitem id="context-savelink"
                 label="&saveLinkCmd.label;"
                 accesskey="&saveLinkCmd.accesskey;"
--- a/browser/base/content/browser-menubar.inc
+++ b/browser/base/content/browser-menubar.inc
@@ -17,23 +17,21 @@
                           command="cmd_newNavigatorTab"
                           key="key_newNavigatorTab"
                           accesskey="&tabCmd.accesskey;"/>
                 <menuitem id="menu_newNavigator"
                           label="&newNavigatorCmd.label;"
                           accesskey="&newNavigatorCmd.accesskey;"
                           key="key_newNavigator"
                           command="cmd_newNavigator"/>
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
                 <menuitem id="menu_newPrivateWindow"
                           label="&newPrivateWindow.label;"
                           accesskey="&newPrivateWindow.accesskey;"
                           command="Tools:PrivateBrowsing"
                           key="key_privatebrowsing"/>
-#endif
                 <menuitem id="menu_openLocation"
                           class="show-only-for-keyboard"
                           label="&openLocationCmd.label;"
                           command="Browser:OpenLocation"
                           key="focusURLBar"
                           accesskey="&openLocationCmd.accesskey;"/>
                 <menuitem id="menu_openFile"
                           label="&openFileCmd.label;"
@@ -595,27 +593,16 @@
               <menuitem id="menu_pageInfo"
                         accesskey="&pageInfoCmd.accesskey;"
                         label="&pageInfoCmd.label;"
 #ifndef XP_WIN
                         key="key_viewInfo"
 #endif
                         command="View:PageInfo"/>
               <menuseparator id="sanitizeSeparator"/>
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-              <menuitem id="privateBrowsingItem"
-                        label="&privateBrowsingCmd.start.label;"
-                        accesskey="&privateBrowsingCmd.start.accesskey;"
-                        startlabel="&privateBrowsingCmd.start.label;"
-                        startaccesskey="&privateBrowsingCmd.start.accesskey;"
-                        stoplabel="&privateBrowsingCmd.stop.label;"
-                        stopaccesskey="&privateBrowsingCmd.stop.accesskey;"
-                        key="key_privatebrowsing"
-                        command="Tools:PrivateBrowsing"/>
-#endif
               <menuitem id="sanitizeItem"
                         accesskey="&clearRecentHistory.accesskey;"
                         label="&clearRecentHistory.label;"
                         key="key_sanitize"
                         command="Tools:Sanitize"/>
 #ifndef XP_UNIX
               <menuseparator id="prefSep"/>
               <menuitem id="menu_preferences"
--- a/browser/base/content/browser-sets.inc
+++ b/browser/base/content/browser-sets.inc
@@ -96,21 +96,17 @@
     <command id="Tools:Scratchpad" oncommand="Scratchpad.openScratchpad();" disabled="true" hidden="true"/>
     <command id="Tools:ResponsiveUI" oncommand="ResponsiveUI.toggle();" disabled="true" hidden="true"/>
     <command id="Tools:Addons" oncommand="BrowserOpenAddonsMgr();"/>
     <command id="Tools:ErrorConsole" oncommand="toJavaScriptConsole()" disabled="true" hidden="true"/>
     <command id="Tools:DevToolsConnect" oncommand="gDevToolsBrowser.openConnectScreen(gBrowser)" disabled="true" hidden="true"/>
     <command id="Tools:Sanitize"
      oncommand="Cc['@mozilla.org/browser/browserglue;1'].getService(Ci.nsIBrowserGlue).sanitize(window);"/>
     <command id="Tools:PrivateBrowsing"
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
       oncommand="OpenBrowserWindow({private: true});"/>
-#else
-      oncommand="gPrivateBrowsingUI.toggleMode();"/>
-#endif
     <command id="History:UndoCloseTab" oncommand="undoCloseTab();"/>
     <command id="History:UndoCloseWindow" oncommand="undoCloseWindow();"/>
     <command id="Browser:ToggleAddonBar" oncommand="toggleAddonBar();"/>
     <command id="Social:SharePage" oncommand="SocialShareButton.sharePage();" disabled="true"/>
     <command id="Social:UnsharePage" oncommand="SocialShareButton.unsharePage();"/>
     <command id="Social:ToggleSidebar" oncommand="Social.toggleSidebar();"/>
     <command id="Social:ToggleNotifications" oncommand="Social.toggleNotifications();"/>
     <command id="Social:FocusChat" oncommand="SocialChatBar.focus();" hidden="true" disabled="true"/>
--- a/browser/base/content/browser-social.js
+++ b/browser/base/content/browser-social.js
@@ -13,21 +13,16 @@ let SocialUI = {
   // Called on delayed startup to initialize the UI
   init: function SocialUI_init() {
     Services.obs.addObserver(this, "social:pref-changed", false);
     Services.obs.addObserver(this, "social:ambient-notification-changed", false);
     Services.obs.addObserver(this, "social:profile-changed", false);
     Services.obs.addObserver(this, "social:recommend-info-changed", false);
     Services.obs.addObserver(this, "social:frameworker-error", false);
     Services.obs.addObserver(this, "social:provider-set", false);
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-    // this observer is necessary so things are also correctly updated
-    // when per-window PB isn't active
-    Services.obs.addObserver(this, "private-browsing", false);
-#endif
 
     Services.prefs.addObserver("social.sidebar.open", this, false);
     Services.prefs.addObserver("social.toast-notifications.enabled", this, false);
 
     gBrowser.addEventListener("ActivateSocialFeature", this._activationEventHandler, true, true);
 
     // Called when we enter DOM full-screen mode.
     window.addEventListener("mozfullscreenchange", function () {
@@ -41,19 +36,16 @@ let SocialUI = {
   // Called on window unload
   uninit: function SocialUI_uninit() {
     Services.obs.removeObserver(this, "social:pref-changed");
     Services.obs.removeObserver(this, "social:ambient-notification-changed");
     Services.obs.removeObserver(this, "social:profile-changed");
     Services.obs.removeObserver(this, "social:recommend-info-changed");
     Services.obs.removeObserver(this, "social:frameworker-error");
     Services.obs.removeObserver(this, "social:provider-set");
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-    Services.obs.removeObserver(this, "private-browsing");
-#endif
 
     Services.prefs.removeObserver("social.sidebar.open", this);
     Services.prefs.removeObserver("social.toast-notifications.enabled", this);
   },
 
   // Called once, after window load, once Social.jsm's provider has been set.
   _providerReady: function SocialUI_providerReady() {
     this._updateActiveUI();
@@ -135,24 +127,16 @@ let SocialUI = {
 
         case "nsPref:changed":
           if (data == "social.sidebar.open") {
             SocialSidebar.update();
           } else if (data == "social.toast-notifications.enabled") {
             SocialToolbar.updateButton();
           }
           break;
-
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-        case "private-browsing":
-          this._updateEnabledState();
-          this._updateActiveUI();
-          SocialToolbar.init();
-          break;
-#endif
       }
     } catch (e) {
       Components.utils.reportError(e + "\n" + e.stack);
       throw e;
     }
   },
 
   nonBrowserWindowInit: function SocialUI_nonBrowserInit() {
@@ -168,21 +152,18 @@ let SocialUI = {
       // XXX Bug 789585 will implement an API for provider-specified login pages.
       openUILinkIn(Social.provider.origin, "tab");
     }
   },
 
   _updateActiveUI: function SocialUI_updateActiveUI() {
     // The "active" UI isn't dependent on there being a provider, just on
     // social being "active" (but also chromeless/PB)
-    let enabled = Social.active && !this._chromeless
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
-                  && !PrivateBrowsingUtils.isWindowPrivate(window)
-#endif
-        ;
+    let enabled = Social.active && !this._chromeless &&
+                  !PrivateBrowsingUtils.isWindowPrivate(window);
     let broadcaster = document.getElementById("socialActiveBroadcaster");
     broadcaster.hidden = !enabled;
 
     if (!Social.provider)
       return;
 
     let toggleCommand = document.getElementById("Social:Toggle");
     // We only need to update the command itself - all our menu items use it.
@@ -323,21 +304,17 @@ let SocialUI = {
     // multiple times...
     delete this._chromeless;
     this._chromeless = chromeless;
     return chromeless;
   },
 
   get enabled() {
     // Returns whether social is enabled *for this window*.
-    if (this._chromeless
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
-        || PrivateBrowsingUtils.isWindowPrivate(window)
-#endif
-       )
+    if (this._chromeless || PrivateBrowsingUtils.isWindowPrivate(window))
       return false;
     return !!(Social.active && Social.provider && Social.provider.enabled);
   },
 
 }
 
 let SocialChatBar = {
   get chatbar() {
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -1260,17 +1260,17 @@ var gBrowserInit = {
     IndexedDBPromptHelper.init();
     gFormSubmitObserver.init();
     SocialUI.init();
     AddonManager.addAddonListener(AddonsMgrListener);
     WebrtcIndicator.init();
 
     gBrowser.addEventListener("pageshow", function(event) {
       // Filter out events that are not about the document load we are interested in
-      if (event.target == content.document)
+      if (content && event.target == content.document)
         setTimeout(pageShowEventHandlers, 0, event);
     }, true);
 
     // Ensure login manager is up and running.
     Services.logins;
 
     if (mustLoadSidebar) {
       let sidebar = document.getElementById("sidebar");
@@ -1325,21 +1325,18 @@ var gBrowserInit = {
     NP.trackBrowserWindow(window);
 #endif
 
     // initialize the session-restore service (in case it's not already running)
     let ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
     ss.init(window);
 
     // Enable the Restore Last Session command if needed
-    if (ss.canRestoreLastSession
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
-        && !PrivateBrowsingUtils.isWindowPrivate(window)
-#endif
-        )
+    if (ss.canRestoreLastSession &&
+        !PrivateBrowsingUtils.isWindowPrivate(window))
       goSetCommandEnabled("Browser:RestoreLastSession", true);
 
     PlacesToolbarHelper.init();
 
     ctrlTab.readPref();
     gPrefService.addObserver(ctrlTab.prefName, ctrlTab, false);
     gPrefService.addObserver(allTabs.prefName, allTabs, false);
 
@@ -1546,20 +1543,16 @@ var gBrowserInit = {
     try {
       gBrowser.removeProgressListener(window.XULBrowserWindow);
       gBrowser.removeTabsProgressListener(window.TabsProgressListener);
     } catch (ex) {
     }
 
     PlacesStarButton.uninit();
 
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-    gPrivateBrowsingUI.uninit();
-#endif
-
     TabsOnTop.uninit();
 
     TabsInTitlebar.uninit();
 
     var enumerator = Services.wm.getEnumerator(null);
     enumerator.getNext();
     if (!enumerator.hasMoreElements()) {
       document.persist("sidebar-box", "sidebarcommand");
@@ -1695,20 +1688,16 @@ var gBrowserInit = {
     // If nonBrowserWindowDelayedStartup hasn't run yet, we have no work to do -
     // just cancel the pending timeout and return;
     if (this._delayedStartupTimeoutId) {
       clearTimeout(this._delayedStartupTimeoutId);
       return;
     }
 
     BrowserOffline.uninit();
-
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-    gPrivateBrowsingUI.uninit();
-#endif
   },
 #endif
 
   _initializeSanitizer: function() {
     const kDidSanitizeDomain = "privacy.sanitize.didShutdownSanitize";
     if (gPrefService.prefHasUserValue(kDidSanitizeDomain)) {
       gPrefService.clearUserPref(kDidSanitizeDomain);
       // We need to persist this preference change, since we want to
@@ -2505,21 +2494,18 @@ function BrowserOnAboutPageLoad(document
   if (document.documentURI.toLowerCase() == "about:home") {
     // XXX bug 738646 - when Marketplace is launched, remove this statement and
     // the hidden attribute set on the apps button in aboutHome.xhtml
     if (getBoolPref("browser.aboutHome.apps", false))
       document.getElementById("apps").removeAttribute("hidden");
 
     let ss = Components.classes["@mozilla.org/browser/sessionstore;1"].
              getService(Components.interfaces.nsISessionStore);
-    if (ss.canRestoreLastSession
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
-        && !PrivateBrowsingUtils.isWindowPrivate(window)
-#endif
-        )
+    if (ss.canRestoreLastSession &&
+        !PrivateBrowsingUtils.isWindowPrivate(window))
       document.getElementById("launcher").setAttribute("session", "true");
 
     // Inject search engine and snippets URL.
     let docElt = document.documentElement;
     docElt.setAttribute("snippetsURL", AboutHomeUtils.snippetsURL);
     docElt.setAttribute("searchEngineName",
                         AboutHomeUtils.defaultSearchEngine.name);
     docElt.setAttribute("searchEngineURL",
@@ -3530,21 +3516,17 @@ function OpenBrowserWindow(options)
 
   var charsetArg = new String();
   var handler = Components.classes["@mozilla.org/browser/clh;1"]
                           .getService(Components.interfaces.nsIBrowserHandler);
   var defaultArgs = handler.defaultArgs;
   var wintype = document.documentElement.getAttribute('windowtype');
 
   var extraFeatures = "";
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
   if (options && options.private) {
-#else
-  if (gPrivateBrowsingUI.privateBrowsingEnabled) {
-#endif
     extraFeatures = ",private";
     // Force the new window to load about:privatebrowsing instead of the default home page
     defaultArgs = "about:privatebrowsing";
   } else {
     extraFeatures = ",non-private";
   }
 
   // if and only if the current window is a browser window and it has a document with a character
@@ -6500,16 +6482,17 @@ function formatURL(aFormat, aIsPref) {
  * Utility object to handle manipulations of the identity indicators in the UI
  */
 var gIdentityHandler = {
   // Mode strings used to control CSS display
   IDENTITY_MODE_IDENTIFIED       : "verifiedIdentity", // High-quality identity information
   IDENTITY_MODE_DOMAIN_VERIFIED  : "verifiedDomain",   // Minimal SSL CA-signed domain verification
   IDENTITY_MODE_UNKNOWN          : "unknownIdentity",  // No trusted identity information
   IDENTITY_MODE_MIXED_CONTENT    : "unknownIdentity mixedContent",  // SSL with unauthenticated content
+  IDENTITY_MODE_MIXED_ACTIVE_CONTENT    : "unknownIdentity mixedContent mixedActiveContent",  // SSL with unauthenticated content
   IDENTITY_MODE_CHROMEUI         : "chromeUI",         // Part of the product's UI
 
   // Cache the most recent SSLStatus and Location seen in checkIdentity
   _lastStatus : null,
   _lastLocation : null,
   _mode : "unknownIdentity",
 
   // smart getters
@@ -6519,16 +6502,18 @@ var gIdentityHandler = {
     this._encryptionLabel[this.IDENTITY_MODE_DOMAIN_VERIFIED] =
       gNavigatorBundle.getString("identity.encrypted");
     this._encryptionLabel[this.IDENTITY_MODE_IDENTIFIED] =
       gNavigatorBundle.getString("identity.encrypted");
     this._encryptionLabel[this.IDENTITY_MODE_UNKNOWN] =
       gNavigatorBundle.getString("identity.unencrypted");
     this._encryptionLabel[this.IDENTITY_MODE_MIXED_CONTENT] =
       gNavigatorBundle.getString("identity.mixed_content");
+    this._encryptionLabel[this.IDENTITY_MODE_MIXED_ACTIVE_CONTENT] =
+      gNavigatorBundle.getString("identity.mixed_content");
     return this._encryptionLabel;
   },
   get _identityPopup () {
     delete this._identityPopup;
     return this._identityPopup = document.getElementById("identity-popup");
   },
   get _identityBox () {
     delete this._identityBox;
@@ -6651,26 +6636,31 @@ var gIdentityHandler = {
   checkIdentity : function(state, location) {
     var currentStatus = gBrowser.securityUI
                                 .QueryInterface(Components.interfaces.nsISSLStatusProvider)
                                 .SSLStatus;
     this._lastStatus = currentStatus;
     this._lastLocation = location;
 
     let nsIWebProgressListener = Ci.nsIWebProgressListener;
-    if (location.protocol == "chrome:" || location.protocol == "about:")
+    if (location.protocol == "chrome:" || location.protocol == "about:") {
       this.setMode(this.IDENTITY_MODE_CHROMEUI);
-    else if (state & nsIWebProgressListener.STATE_IDENTITY_EV_TOPLEVEL)
+    } else if (state & nsIWebProgressListener.STATE_IDENTITY_EV_TOPLEVEL) {
       this.setMode(this.IDENTITY_MODE_IDENTIFIED);
-    else if (state & nsIWebProgressListener.STATE_IS_SECURE)
+    } else if (state & nsIWebProgressListener.STATE_IS_SECURE) {
       this.setMode(this.IDENTITY_MODE_DOMAIN_VERIFIED);
-    else if (state & nsIWebProgressListener.STATE_IS_BROKEN)
-      this.setMode(this.IDENTITY_MODE_MIXED_CONTENT);
-    else
+    } else if (state & nsIWebProgressListener.STATE_IS_BROKEN) {
+      if (gBrowser.docShell.hasMixedActiveContentLoaded) {
+        this.setMode(this.IDENTITY_MODE_MIXED_ACTIVE_CONTENT);
+      } else {
+        this.setMode(this.IDENTITY_MODE_MIXED_CONTENT);
+      }
+    } else {
       this.setMode(this.IDENTITY_MODE_UNKNOWN);
+    }
   },
 
   /**
    * Return the eTLD+1 version of the current hostname
    */
   getEffectiveHost : function() {
     if (!this._IDNService)
       this._IDNService = Cc["@mozilla.org/network/idn-service;1"]
@@ -6915,25 +6905,16 @@ function getTabModalPromptBox(aWindow) {
     return gBrowser.getTabModalPromptBox(foundBrowser);
   return null;
 };
 
 /* DEPRECATED */
 function getBrowser() gBrowser;
 function getNavToolbox() gNavToolbox;
 
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
-
-# We define a new gPrivateBrowsingUI object, as the per-window PB implementation
-# is completely different to the global PB one.  Specifically, the per-window
-# PB implementation does not expose many APIs on the gPrivateBrowsingUI object,
-# and only uses it as a way to initialize and uninitialize private browsing
-# windows.  While we could use #ifdefs all around the global PB mode code to
-# make it work in both modes, the amount of duplicated code is small and the
-# code is much more readable this way.
 let gPrivateBrowsingUI = {
   init: function PBUI_init() {
     // Do nothing for normal windows
     if (!PrivateBrowsingUtils.isWindowPrivate(window)) {
       return;
     }
 
     // Disable the Clear Recent History... menu item when in PB mode
@@ -6960,277 +6941,38 @@ let gPrivateBrowsingUI = {
 
     if (gURLBar) {
       // Disable switch to tab autocompletion for private windows
       gURLBar.setAttribute("autocompletesearchparam", "");
     }
   }
 };
 
-#else
-
-let gPrivateBrowsingUI = {
-  _privateBrowsingService: null,
-  _searchBarValue: null,
-  _findBarValue: null,
-  _inited: false,
-
-  init: function PBUI_init() {
-    Services.obs.addObserver(this, "private-browsing", false);
-    Services.obs.addObserver(this, "private-browsing-transition-complete", false);
-
-    this._privateBrowsingService = Cc["@mozilla.org/privatebrowsing;1"].
-                                   getService(Ci.nsIPrivateBrowsingService);
-
-    if (this.privateBrowsingEnabled)
-      this.onEnterPrivateBrowsing(true);
-
-    this._inited = true;
-  },
-
-  uninit: function PBUI_unint() {
-    if (!this._inited)
-      return;
-
-    Services.obs.removeObserver(this, "private-browsing");
-    Services.obs.removeObserver(this, "private-browsing-transition-complete");
-  },
-
-  get _disableUIOnToggle() {
-    if (PrivateBrowsingUtils.permanentPrivateBrowsing)
-      return false;
-
-    try {
-      return !gPrefService.getBoolPref("browser.privatebrowsing.keep_current_session");
-    }
-    catch (e) {
-      return true;
-    }
-  },
-
-  observe: function PBUI_observe(aSubject, aTopic, aData) {
-    if (aTopic == "private-browsing") {
-      if (aData == "enter")
-        this.onEnterPrivateBrowsing();
-      else if (aData == "exit")
-        this.onExitPrivateBrowsing();
-    }
-    else if (aTopic == "private-browsing-transition-complete") {
-      if (this._disableUIOnToggle) {
-        document.getElementById("Tools:PrivateBrowsing")
-                .removeAttribute("disabled");
-      }
-    }
-  },
-
-  _shouldEnter: function PBUI__shouldEnter() {
-    try {
-      // Never prompt if the session is not going to be closed, or if user has
-      // already requested not to be prompted.
-      if (gPrefService.getBoolPref("browser.privatebrowsing.dont_prompt_on_enter") ||
-          gPrefService.getBoolPref("browser.privatebrowsing.keep_current_session"))
-        return true;
-    }
-    catch (ex) { }
-
-    var bundleService = Services.strings;
-    var pbBundle = bundleService.createBundle("chrome://browser/locale/browser.properties");
-    var brandBundle = bundleService.createBundle("chrome://branding/locale/brand.properties");
-
-    var appName = brandBundle.GetStringFromName("brandShortName");
-# On Mac, use the header as the title.
-#ifdef XP_MACOSX
-    var dialogTitle = pbBundle.GetStringFromName("privateBrowsingMessageHeader");
-    var header = "";
-#else
-    var dialogTitle = pbBundle.GetStringFromName("privateBrowsingDialogTitle");
-    var header = pbBundle.GetStringFromName("privateBrowsingMessageHeader") + "\n\n";
-#endif
-    var message = pbBundle.formatStringFromName("privateBrowsingMessage", [appName], 1);
-
-    var ps = Services.prompt;
-
-    var flags = ps.BUTTON_TITLE_IS_STRING * ps.BUTTON_POS_0 +
-                ps.BUTTON_TITLE_IS_STRING * ps.BUTTON_POS_1 +
-                ps.BUTTON_POS_0_DEFAULT;
-
-    var neverAsk = {value:false};
-    var button0Title = pbBundle.GetStringFromName("privateBrowsingYesTitle");
-    var button1Title = pbBundle.GetStringFromName("privateBrowsingNoTitle");
-    var neverAskText = pbBundle.GetStringFromName("privateBrowsingNeverAsk");
-
-    var result;
-    var choice = ps.confirmEx(null, dialogTitle, header + message,
-                              flags, button0Title, button1Title, null,
-                              neverAskText, neverAsk);
-
-    switch (choice) {
-    case 0: // Start Private Browsing
-      result = true;
-      if (neverAsk.value)
-        gPrefService.setBoolPref("browser.privatebrowsing.dont_prompt_on_enter", true);
-      break;
-    case 1: // Keep
-      result = false;
-      break;
-    }
-
-    return result;
-  },
-
-  onEnterPrivateBrowsing: function PBUI_onEnterPrivateBrowsing(aOnWindowOpen) {
-    if (BrowserSearch.searchBar)
-      this._searchBarValue = BrowserSearch.searchBar.textbox.value;
-
-    if (gFindBarInitialized)
-      this._findBarValue = gFindBar.getElement("findbar-textbox").value;
-
-    this._setPBMenuTitle("stop");
-
-    // Disable the Clear Recent History... menu item when in PB mode
-    // temporary fix until bug 463607 is fixed
-    document.getElementById("Tools:Sanitize").setAttribute("disabled", "true");
-
-    let docElement = document.documentElement;
-    if (PrivateBrowsingUtils.permanentPrivateBrowsing) {
-      // Disable the menu item in auto-start mode
-      document.getElementById("privateBrowsingItem")
-              .setAttribute("disabled", "true");
-#ifdef MENUBAR_CAN_AUTOHIDE
-      document.getElementById("appmenu_privateBrowsing")
-              .setAttribute("disabled", "true");
-#endif
-      document.getElementById("Tools:PrivateBrowsing")
-              .setAttribute("disabled", "true");
-      if (window.location.href == getBrowserURL())
-        docElement.setAttribute("privatebrowsingmode", "permanent");
-    }
-    else if (window.location.href == getBrowserURL()) {
-      // Adjust the window's title
-      docElement.setAttribute("title",
-        docElement.getAttribute("title_privatebrowsing"));
-      docElement.setAttribute("titlemodifier",
-        docElement.getAttribute("titlemodifier_privatebrowsing"));
-      docElement.setAttribute("privatebrowsingmode", "temporary");
-      gBrowser.updateTitlebar();
-    }
-
-    if (!aOnWindowOpen && this._disableUIOnToggle)
-      document.getElementById("Tools:PrivateBrowsing")
-              .setAttribute("disabled", "true");
-  },
-
-  onExitPrivateBrowsing: function PBUI_onExitPrivateBrowsing() {
-    if (BrowserSearch.searchBar) {
-      let searchBox = BrowserSearch.searchBar.textbox;
-      searchBox.reset();
-      if (this._searchBarValue) {
-        searchBox.value = this._searchBarValue;
-        this._searchBarValue = null;
-      }
-    }
-
-    if (gURLBar) {
-      gURLBar.editor.transactionManager.clear();
-    }
-
-    // Re-enable the Clear Recent History... menu item on exit of PB mode
-    // temporary fix until bug 463607 is fixed
-    document.getElementById("Tools:Sanitize").removeAttribute("disabled");
-
-    if (gFindBarInitialized) {
-      let findbox = gFindBar.getElement("findbar-textbox");
-      findbox.reset();
-      if (this._findBarValue) {
-        findbox.value = this._findBarValue;
-        this._findBarValue = null;
-      }
-    }
-
-    this._setPBMenuTitle("start");
-
-    if (window.location.href == getBrowserURL()) {
-      // Adjust the window's title
-      let docElement = document.documentElement;
-      docElement.setAttribute("title",
-        docElement.getAttribute("title_normal"));
-      docElement.setAttribute("titlemodifier",
-        docElement.getAttribute("titlemodifier_normal"));
-      docElement.removeAttribute("privatebrowsingmode");
-    }
-
-    // Enable the menu item in after exiting the auto-start mode
-    document.getElementById("privateBrowsingItem")
-            .removeAttribute("disabled");
-#ifdef MENUBAR_CAN_AUTOHIDE
-    document.getElementById("appmenu_privateBrowsing")
-            .removeAttribute("disabled");
-#endif
-    document.getElementById("Tools:PrivateBrowsing")
-            .removeAttribute("disabled");
-
-    gLastOpenDirectory.reset();
-
-    if (this._disableUIOnToggle)
-      document.getElementById("Tools:PrivateBrowsing")
-              .setAttribute("disabled", "true");
-  },
-
-  _setPBMenuTitle: function PBUI__setPBMenuTitle(aMode) {
-    let pbMenuItem = document.getElementById("privateBrowsingItem");
-    pbMenuItem.setAttribute("label", pbMenuItem.getAttribute(aMode + "label"));
-    pbMenuItem.setAttribute("accesskey", pbMenuItem.getAttribute(aMode + "accesskey"));
-#ifdef MENUBAR_CAN_AUTOHIDE
-    let appmenupbMenuItem = document.getElementById("appmenu_privateBrowsing");
-    appmenupbMenuItem.setAttribute("label", appmenupbMenuItem.getAttribute(aMode + "label"));
-    appmenupbMenuItem.setAttribute("accesskey", appmenupbMenuItem.getAttribute(aMode + "accesskey"));
-#endif
-  },
-
-  toggleMode: function PBUI_toggleMode() {
-    // prompt the users on entering the private mode, if needed
-    if (!this.privateBrowsingEnabled)
-      if (!this._shouldEnter())
-        return;
-
-    this._privateBrowsingService.privateBrowsingEnabled =
-      !this.privateBrowsingEnabled;
-  },
-
-  get privateBrowsingEnabled() {
-    return this._privateBrowsingService.privateBrowsingEnabled;
-  }
-};
-
-#endif
-
 
 /**
  * Switch to a tab that has a given URI, and focusses its browser window.
  * If a matching tab is in this window, it will be switched to. Otherwise, other
  * windows will be searched.
  *
  * @param aURI
  *        URI to search for
  * @param aOpenNew
  *        True to open a new tab and switch to it, if no existing tab is found.
  *        If no suitable window is found, a new one will be opened.
  * @return True if an existing tab was found, false otherwise
  */
 function switchToTabHavingURI(aURI, aOpenNew) {
   // This will switch to the tab in aWindow having aURI, if present.
   function switchIfURIInWindow(aWindow) {
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
     // Only switch to the tab if neither the source and desination window are
     // private.
     if (PrivateBrowsingUtils.isWindowPrivate(window) ||
         PrivateBrowsingUtils.isWindowPrivate(aWindow)) {
       return false;
     }
-#endif
 
     let browsers = aWindow.gBrowser.browsers;
     for (let i = 0; i < browsers.length; i++) {
       let browser = browsers[i];
       if (browser.currentURI.equals(aURI)) {
         // Focus the matching window & tab
         aWindow.focus();
         aWindow.gBrowser.tabContainer.selectedIndex = i;
--- a/browser/base/content/macBrowserOverlay.xul
+++ b/browser/base/content/macBrowserOverlay.xul
@@ -51,15 +51,13 @@
 #include browser-menubar.inc
 
 <!-- Dock menu -->
 <popupset>
   <menupopup id="menu_mac_dockmenu">
     <!-- The command cannot be cmd_newNavigator because we need to activate
          the application. -->
     <menuitem label="&newNavigatorCmd.label;" oncommand="OpenBrowserWindowFromDockMenu();" />
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
     <menuitem label="&newPrivateWindow.label;" oncommand="OpenBrowserWindowFromDockMenu({private: true});" />
-#endif
   </menupopup>
 </popupset>
 
 </overlay>
--- a/browser/base/content/nsContextMenu.js
+++ b/browser/base/content/nsContextMenu.js
@@ -132,23 +132,19 @@ nsContextMenu.prototype = {
       if (uri && uri.host) {
         this.linkURI = uri;
         this.linkURL = this.linkURI.spec;
         this.onPlainTextLink = true;
       }
     }
 
     var shouldShow = this.onSaveableLink || isMailtoInternal || this.onPlainTextLink;
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
     var isWindowPrivate = PrivateBrowsingUtils.isWindowPrivate(window);
     this.showItem("context-openlink", shouldShow && !isWindowPrivate);
     this.showItem("context-openlinkprivate", shouldShow);
-#else
-    this.showItem("context-openlink", shouldShow);
-#endif
     this.showItem("context-openlinkintab", shouldShow);
     this.showItem("context-openlinkincurrent", this.onPlainTextLink);
     this.showItem("context-sep-open", shouldShow);
   },
 
   initNavigationItems: function CM_initNavigationItems() {
     var shouldShow = !(this.isContentSelected || this.onLink || this.onImage ||
                        this.onCanvas || this.onVideo || this.onAudio ||
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -619,23 +619,20 @@
                     !(this.mBrowser.docShell.loadType & Ci.nsIDocShell.LOAD_CMD_PUSHSTATE))
                   this.mBrowser.mIconURL = null;
 
                 let autocomplete = this.mTabBrowser._placesAutocomplete;
                 if (this.mBrowser.registeredOpenURI) {
                   autocomplete.unregisterOpenPage(this.mBrowser.registeredOpenURI);
                   delete this.mBrowser.registeredOpenURI;
                 }
-                if (!isBlankPageURL(aLocation.spec)
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
-                    // Tabs in private windows aren't registered as "Open" so
-                    // that they don't appear as switch-to-tab candidates.
-                    && !PrivateBrowsingUtils.isWindowPrivate(window)
-#endif
-                    ) {
+                // Tabs in private windows aren't registered as "Open" so
+                // that they don't appear as switch-to-tab candidates.
+                if (!isBlankPageURL(aLocation.spec) &&
+                    !PrivateBrowsingUtils.isWindowPrivate(window)) {
                   autocomplete.registerOpenPage(aLocation);
                   this.mBrowser.registeredOpenURI = aLocation;
                 }
               }
 
               if (!this.mBlank) {
                 this._callProgressListeners("onLocationChange",
                                             [aWebProgress, aRequest, aLocation,
@@ -1900,23 +1897,21 @@
         </body>
       </method>
 
       <method name="swapBrowsersAndCloseOther">
         <parameter name="aOurTab"/>
         <parameter name="aOtherTab"/>
         <body>
           <![CDATA[
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
             // Do not allow transfering a private tab to a non-private window
             // and vice versa.
             if (PrivateBrowsingUtils.isWindowPrivate(window) !=
                 PrivateBrowsingUtils.isWindowPrivate(aOtherTab.ownerDocument.defaultView))
               return;
-#endif
 
             // That's gBrowser for the other window, not the tab's browser!
             var remoteBrowser = aOtherTab.ownerDocument.defaultView.gBrowser;
 
             // First, start teardown of the other browser.  Make sure to not
             // fire the beforeunload event in the process.  Close the other
             // window if this was its last tab.
             if (!remoteBrowser._beginRemoveTab(aOtherTab, true, true))
@@ -3458,23 +3453,21 @@
           // tabs are always added as the first type
           if (types[0] == TAB_DROP_TYPE) {
             var sourceNode = dt.mozGetDataAt(TAB_DROP_TYPE, 0);
             if (sourceNode instanceof XULElement &&
                 sourceNode.localName == "tab" &&
                 sourceNode.ownerDocument.defaultView instanceof ChromeWindow &&
                 sourceNode.ownerDocument.documentElement.getAttribute("windowtype") == "navigator:browser" &&
                 sourceNode.ownerDocument.defaultView.gBrowser.tabContainer == sourceNode.parentNode) {
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
               // Do not allow transfering a private tab to a non-private window
               // and vice versa.
               if (PrivateBrowsingUtils.isWindowPrivate(window) !=
                   PrivateBrowsingUtils.isWindowPrivate(sourceNode.ownerDocument.defaultView))
                 return dt.effectAllowed = "none";
-#endif
 
 #ifdef XP_MACOSX
               return dt.effectAllowed = event.altKey ? "copy" : "move";
 #else
               return dt.effectAllowed = event.ctrlKey ? "copy" : "move";
 #endif
             }
           }
--- a/browser/base/content/test/Makefile.in
+++ b/browser/base/content/test/Makefile.in
@@ -45,23 +45,19 @@ MOCHITEST_FILES = \
 		$(NULL)
 
 # test_contextmenu.html is disabled on Linux due to bug 513558
 ifneq (gtk2,$(MOZ_WIDGET_TOOLKIT))
 MOCHITEST_FILES += \
 		audio.ogg \
 		test_contextmenu.html \
 		subtst_contextmenu.html \
-		$(NULL)
-ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
-MOCHITEST_FILES += \
 		privateBrowsingMode.js \
 		$(NULL)
 endif
-endif
 
 # The following tests are disabled because they are unreliable:
 #   browser_bug423833.js is bug 428712
 #   browser_sanitize-download-history.js is bug 432425
 #
 # browser_sanitizeDialog_treeView.js is disabled until the tree view is added
 # back to the clear recent history dialog (sanitize.xul), if it ever is (bug
 # 480169)
@@ -158,18 +154,21 @@ endif
                  browser_bug655584.js \
                  browser_bug664672.js \
                  browser_bug710878.js \
                  browser_bug719271.js \
                  browser_bug724239.js \
                  browser_bug735471.js \
                  browser_bug743421.js \
                  browser_bug749738.js \
+                 browser_bug763468_perwindowpb.js \
+                 browser_bug767836_perwindowpb.js \
                  browser_bug783614.js \
                  browser_bug797677.js \
+                 browser_bug816527.js \
                  browser_bug832435.js \
                  browser_canonizeURL.js \
                  browser_customize.js \
                  browser_findbarClose.js \
                  browser_homeDrop.js \
                  browser_keywordBookmarklets.js \
                  browser_contextSearchTabPosition.js \
                  browser_ctrlTab.js \
@@ -185,26 +184,31 @@ endif
                  browser_locationBarExternalLoad.js \
                  browser_page_style_menu.js \
                  browser_pinnedTabs.js \
                  browser_plainTextLinks.js \
                  browser_pluginnotification.js \
                  browser_plugins_added_dynamically.js \
                  browser_CTPScriptPlugin.js \
                  browser_pluginplaypreview.js \
+                 browser_private_browsing_window.js \
                  browser_relatedTabs.js \
                  browser_sanitize-passwordDisabledHosts.js \
                  browser_sanitize-sitepermissions.js \
                  browser_sanitize-timespans.js \
                  browser_clearplugindata.js \
                  browser_clearplugindata.html \
                  browser_clearplugindata_noage.html \
                  browser_popupUI.js \
                  browser_sanitizeDialog.js \
+                 browser_save_link-perwindowpb.js \
+                 browser_save_private_link_perwindowpb.js \
                  browser_save_video.js \
+                 browser_tabMatchesInAwesomebar_perwindowpb.js \
+                 browser_tab_drag_drop_perwindow.js \
                  bug564387.html \
                  bug564387_video1.ogv \
                  bug564387_video1.ogv^headers^ \
                  bug792517.html \
                  bug792517-2.html \
                  bug792517.sjs \
                  browser_scope.js \
                  browser_selectTabAtIndex.js \
@@ -313,33 +317,12 @@ endif
 
 # bug 766546, disable browser_bug561636.js on Windows
 ifneq ($(OS_ARCH),WINNT)
 _BROWSER_FILES += \
                  browser_bug561636.js \
                  $(NULL)
 endif
 
-ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
-_BROWSER_FILES += \
-                browser_bug763468_perwindowpb.js \
-                browser_bug767836_perwindowpb.js \
-                browser_bug816527.js \
-                browser_private_browsing_window.js \
-                browser_save_link-perwindowpb.js \
-                browser_save_private_link_perwindowpb.js \
-                browser_tabMatchesInAwesomebar_perwindowpb.js \
-                browser_tab_drag_drop_perwindow.js \
-                $(NULL)
-else
-_BROWSER_FILES += \
-                browser_bug763468.js \
-                browser_bug767836.js \
-                browser_save_link.js \
-                browser_save_private_link.js \
-                browser_tabMatchesInAwesomebar.js \
-                $(NULL)
-endif
-
 include $(topsrcdir)/config/rules.mk
 
 libs::	$(_BROWSER_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
deleted file mode 100644
--- a/browser/base/content/test/browser_bug763468.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// This test makes sure that opening a new tab in private browsing mode opens about:privatebrowsing
-
-// initialization
-const pb = Cc["@mozilla.org/privatebrowsing;1"].
-           getService(Ci.nsIPrivateBrowsingService);
-
-const PREF = "browser.newtab.url";
-
-function test() {
-  let newTabUrl = Services.prefs.getCharPref(PREF) || "about:blank";
-
-  waitForExplicitFinish();
-  // check whether the mode that we start off with is normal or not
-  ok(!pb.privateBrowsingEnabled, "private browsing is disabled");
-
-  // Open a new tab page in normal mode
-  openNewTab(function () {
-    // Check the new tab opened while in normal mode
-    is(gBrowser.selectedBrowser.currentURI.spec, newTabUrl,
-       "URL of NewTab should be browser.newtab.url in Normal mode");
-
-    // enter private browsing mode
-    togglePrivateBrowsing(function () {
-      ok(pb.privateBrowsingEnabled, "private browsing is enabled");
-    
-      // Open a new tab page in private browsing mode
-      openNewTab(function () {
-        // Check the new tab opened while in private browsing mode
-        is(gBrowser.selectedBrowser.currentURI.spec, "about:privatebrowsing",
-           "URL of NewTab should be about:privatebrowsing in PB mode");
-
-        // exit private browsing mode
-        togglePrivateBrowsing(function () {
-          ok(!pb.privateBrowsingEnabled, "private browsing is disabled");
-          
-          // Open a new tab page in normal mode to check if
-          // returning from pb mode restores everything as it should
-          openNewTab(function () {
-            // Check the new tab opened while in normal mode
-            is(gBrowser.selectedBrowser.currentURI.spec, newTabUrl, 
-               "URL of NewTab should be browser.newtab.url in Normal mode");
-            gBrowser.removeTab(gBrowser.selectedTab);
-            gBrowser.removeTab(gBrowser.selectedTab);
-            finish();
-          });
-        });
-      });
-    });
-  });
-}
-
-function togglePrivateBrowsing(aCallback) {
-  let topic = "private-browsing-transition-complete";
-
-  Services.obs.addObserver(function observe() {
-    Services.obs.removeObserver(observe, topic);
-    executeSoon(aCallback);
-  }, topic, false);
-
-  pb.privateBrowsingEnabled = !pb.privateBrowsingEnabled;
-}
-
-function openNewTab(aCallback) {
-  // Open a new tab
-  BrowserOpenTab();
-
-  let browser = gBrowser.selectedBrowser;
-  if (browser.contentDocument.readyState == "complete") {
-    executeSoon(aCallback);
-    return;
-  }
-
-  browser.addEventListener("load", function onLoad() {
-    browser.removeEventListener("load", onLoad, true);
-    executeSoon(aCallback);
-  }, true);
-}
deleted file mode 100644
--- a/browser/base/content/test/browser_bug767836.js
+++ /dev/null
@@ -1,98 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// initialization
-const pb = Cc["@mozilla.org/privatebrowsing;1"].
-           getService(Ci.nsIPrivateBrowsingService);
-const PREF = "browser.newtab.url";
-const NEWTABURL = Services.prefs.getCharPref(PREF) || "about:blank";
-const TESTURL = "http://example.com/";
-  
-function test() {
-
-  waitForExplicitFinish();
-  // check whether the mode that we start off with is normal or not
-  ok(!pb.privateBrowsingEnabled, "private browsing is disabled");
-  // check whether any custom new tab url has been configured
-  ok(!Services.prefs.prefHasUserValue(PREF), "No custom newtab url is set");
-  
-  openNewTab(function () {
-    // Check the new tab opened while in normal mode
-    is(gBrowser.selectedBrowser.currentURI.spec, NEWTABURL,
-       "URL of NewTab should be browser.newtab.url in Normal mode");
-    // Set the custom newtab url
-    Services.prefs.setCharPref(PREF, TESTURL);
-    ok(Services.prefs.prefHasUserValue(PREF), "Custom newtab url is set");
-    
-    // Open a newtab after setting the custom newtab url
-    openNewTab(function () {
-      is(gBrowser.selectedBrowser.currentURI.spec, TESTURL,
-         "URL of NewTab should be the custom url");
-      
-      // clear the custom url preference
-      Services.prefs.clearUserPref(PREF);
-      ok(!Services.prefs.prefHasUserValue(PREF), "No custom newtab url is set");
-      
-      // enter private browsing mode
-      togglePrivateBrowsing(function () {
-        ok(pb.privateBrowsingEnabled, "private browsing is enabled");
-        
-        // Open a new tab page in private browsing mode
-        openNewTab(function () {
-          // Check the new tab opened while in private browsing mode
-          is(gBrowser.selectedBrowser.currentURI.spec, "about:privatebrowsing",
-             "URL of NewTab should be about:privatebrowsing in PB mode");
-          
-          Services.prefs.setCharPref(PREF, TESTURL);
-          ok(Services.prefs.prefHasUserValue(PREF), "Custom newtab url is set");
-          
-          // Open a newtab after setting the custom newtab url
-          openNewTab(function () {
-            is(gBrowser.selectedBrowser.currentURI.spec, TESTURL,
-               "URL of NewTab should be the custom url");
-
-            Services.prefs.clearUserPref(PREF);
-            ok(!Services.prefs.prefHasUserValue(PREF), "No custom newtab url is set");
-            
-            // exit private browsing mode
-            togglePrivateBrowsing(function () {
-              ok(!pb.privateBrowsingEnabled, "private browsing is disabled");
-              
-              gBrowser.removeTab(gBrowser.selectedTab);
-              gBrowser.removeTab(gBrowser.selectedTab);
-              finish();
-            });
-          });
-        });
-      });
-    });
-  });
-}
-
-function togglePrivateBrowsing(aCallback) {
-  let topic = "private-browsing-transition-complete";
-
-  Services.obs.addObserver(function observe() {
-    Services.obs.removeObserver(observe, topic);
-    executeSoon(aCallback);
-  }, topic, false);
-
-  pb.privateBrowsingEnabled = !pb.privateBrowsingEnabled;
-}
-
-function openNewTab(aCallback) {
-  // Open a new tab
-  BrowserOpenTab();
-
-  let browser = gBrowser.selectedBrowser;
-  if (browser.contentDocument.readyState == "complete") {
-    executeSoon(aCallback);
-    return;
-  }
-
-  browser.addEventListener("load", function onLoad() {
-    browser.removeEventListener("load", onLoad, true);
-    executeSoon(aCallback);
-  }, true);
-}
deleted file mode 100644
--- a/browser/base/content/test/browser_save_link.js
+++ /dev/null
@@ -1,128 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var MockFilePicker = SpecialPowers.MockFilePicker;
-MockFilePicker.init(window);
-
-let tempScope = {};
-Cu.import("resource://gre/modules/NetUtil.jsm", tempScope);
-let NetUtil = tempScope.NetUtil;
-
-// Trigger a save of a link in public mode, then trigger an identical save
-// in private mode and ensure that the second request is differentiated from
-// the first by checking the cookies that are sent.
-
-function triggerSave(aCallback) {
-  var fileName;
-  gBrowser.selectedTab = gBrowser.addTab();
-  let testBrowser = gBrowser.selectedBrowser;
-  testBrowser.loadURI("http://mochi.test:8888/browser/browser/base/content/test/bug792517-2.html");
-  testBrowser.addEventListener("pageshow", function pageShown(event) {
-    if (event.target.location == "about:blank")
-      return;
-    testBrowser.removeEventListener("pageshow", pageShown, false);
-
-    executeSoon(function () {
-      document.addEventListener("popupshown", contextMenuOpened, false);
-
-      var link = testBrowser.contentDocument.getElementById("fff");
-      EventUtils.synthesizeMouseAtCenter(link,
-                                         { type: "contextmenu", button: 2 },
-                                         testBrowser.contentWindow);
-    });
-  }, false);
-
-  function contextMenuOpened(event) {
-    event.currentTarget.removeEventListener("popupshown", contextMenuOpened, false);
-
-    // Create the folder the link will be saved into.
-    var destDir = createTemporarySaveDirectory();
-    var destFile = destDir.clone();
-
-    MockFilePicker.displayDirectory = destDir;
-    MockFilePicker.showCallback = function(fp) {
-      fileName = fp.defaultString;
-      destFile.append (fileName);
-      MockFilePicker.returnFiles = [destFile];
-      MockFilePicker.filterIndex = 1; // kSaveAsType_URL
-    };
-
-    mockTransferCallback = function(a) onTransferComplete(a, destFile, destDir);
-
-    // Select "Save Link As" option from context menu
-    var saveLinkCommand = document.getElementById("context-savelink");
-    saveLinkCommand.doCommand();
-
-    event.target.hidePopup();
-  }
-
-  function onTransferComplete(downloadSuccess, destFile, destDir) {
-    ok(downloadSuccess, "Link should have been downloaded successfully");
-    gBrowser.removeCurrentTab();
-
-    // Give the request a chance to finish
-    executeSoon(function() aCallback(destFile, destDir));
-  }
-}
-
-function readFile(file, callback) {
-  let channel = NetUtil.newChannel(file);
-  channel.contentType = "application/javascript";
-
-  NetUtil.asyncFetch(channel, function(inputStream, status) {
-    ok(Components.isSuccessCode(status),
-       "file was read successfully");
-
-    let content = NetUtil.readInputStreamToString(inputStream,
-                                                  inputStream.available());
-    executeSoon(function() callback(content));
-  });
-}
-
-function test() {
-  waitForExplicitFinish();
-
-  let pb = Cc["@mozilla.org/privatebrowsing;1"]
-             .getService(Ci.nsIPrivateBrowsingService);
-
-  mockTransferRegisterer.register();
-
-  registerCleanupFunction(function () {
-    mockTransferRegisterer.unregister();
-    MockFilePicker.cleanup();
-    pb.privateBrowsingEnabled = false;
-    Services.prefs.clearUserPref("browser.privatebrowsing.keep_current_session");
-  });
-
-  triggerSave(function(destFile, destDir) {
-    readFile(destFile, function(content) {
-      is(content, "cookie-not-present", "no cookie should be sent");
-      destDir.remove(true);
-
-      Services.prefs.setBoolPref("browser.privatebrowsing.keep_current_session", true);
-      pb.privateBrowsingEnabled = true;
-      triggerSave(function(destFile, destDir) {
-        readFile(destFile, function(content) {
-          is(content, "cookie-not-present", "no cookie should be sent");
-          destDir.remove(true);
-          finish();
-        });
-      });
-    });
-  });  
-}
-
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
-  .getService(Ci.mozIJSSubScriptLoader)
-  .loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
-                 this);
-
-function createTemporarySaveDirectory() {
-  var saveDir = Cc["@mozilla.org/file/directory_service;1"]
-                  .getService(Ci.nsIProperties)
-                  .get("TmpD", Ci.nsIFile);
-  saveDir.append("testsavedir");
-  if (!saveDir.exists())
-    saveDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0755);
-  return saveDir;
-}
deleted file mode 100644
--- a/browser/base/content/test/browser_save_private_link.js
+++ /dev/null
@@ -1,116 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var MockFilePicker = SpecialPowers.MockFilePicker;
-MockFilePicker.init(window);
-
-function checkDiskCacheFor(filename) {
-  let visitor = {
-    visitDevice: function(deviceID, deviceInfo) {
-      if (deviceID == "disk")
-        info(deviceID + " device contains " + deviceInfo.entryCount + " entries");
-      return deviceID == "disk";
-    },
-    
-    visitEntry: function(deviceID, entryInfo) {
-      info(entryInfo.key);
-      is(entryInfo.key.contains(filename), false, "web content present in disk cache");
-    }
-  };
-  cache.visitEntries(visitor);
-}
-
-var cache = Cc["@mozilla.org/network/cache-service;1"]
-              .getService(Ci.nsICacheService);
-
-function test() {
-  waitForExplicitFinish();
-  var fileName;
-
-  gPrefService.setBoolPref("browser.privatebrowsing.keep_current_session", true);
-  let pb = Cc["@mozilla.org/privatebrowsing;1"].
-           getService(Ci.nsIPrivateBrowsingService);
-  pb.privateBrowsingEnabled = true;
-
-  gBrowser.loadURI("http://mochi.test:8888/browser/browser/base/content/test/bug792517.html");
-
-  registerCleanupFunction(function () {
-    pb.privateBrowsingEnabled = false;
-    gPrefService.clearUserPref("browser.privatebrowsing.keep_current_session");
-    gBrowser.addTab();
-    gBrowser.removeCurrentTab();
-  });
-
-  gBrowser.addEventListener("pageshow", function pageShown(event) {
-    if (event.target.location == "about:blank")
-      return;
-    gBrowser.removeEventListener("pageshow", pageShown);
-
-    executeSoon(function () {
-      document.addEventListener("popupshown", contextMenuOpened);
-
-      var img = gBrowser.contentDocument.getElementById("img");
-      EventUtils.synthesizeMouseAtCenter(img,
-                                         { type: "contextmenu", button: 2 },
-                                         gBrowser.contentWindow);
-    });
-  });
-
-  function contextMenuOpened(event) {
-    cache.evictEntries(Ci.nsICache.STORE_ANYWHERE);
-
-    event.currentTarget.removeEventListener("popupshown", contextMenuOpened);
-
-    // Create the folder the image will be saved into.
-    var destDir = createTemporarySaveDirectory();
-    var destFile = destDir.clone();
-
-    MockFilePicker.displayDirectory = destDir;
-    MockFilePicker.showCallback = function(fp) {
-      fileName = fp.defaultString;
-      destFile.append (fileName);
-      MockFilePicker.returnFiles = [destFile];
-      MockFilePicker.filterIndex = 1; // kSaveAsType_URL
-    };
-
-    mockTransferCallback = onTransferComplete;
-    mockTransferRegisterer.register();
-
-    registerCleanupFunction(function () {
-      mockTransferRegisterer.unregister();
-      MockFilePicker.cleanup();
-      destDir.remove(true);
-    });
-
-    // Select "Save Image As" option from context menu
-    var saveVideoCommand = document.getElementById("context-saveimage");
-    saveVideoCommand.doCommand();
-
-    event.target.hidePopup();
-  }
-
-  function onTransferComplete(downloadSuccess) {
-    ok(downloadSuccess, "Image file should have been downloaded successfully");
-
-    // Give the request a chance to finish and create a cache entry
-    executeSoon(function() {
-      checkDiskCacheFor(fileName);
-      finish();
-    });
-  }
-}
-
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
-  .getService(Ci.mozIJSSubScriptLoader)
-  .loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
-                 this);
-
-function createTemporarySaveDirectory() {
-  var saveDir = Cc["@mozilla.org/file/directory_service;1"]
-                  .getService(Ci.nsIProperties)
-                  .get("TmpD", Ci.nsIFile);
-  saveDir.append("testsavedir");
-  if (!saveDir.exists())
-    saveDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0755);
-  return saveDir;
-}
deleted file mode 100644
--- a/browser/base/content/test/browser_tabMatchesInAwesomebar.js
+++ /dev/null
@@ -1,323 +0,0 @@
-/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- * vim:set ts=2 sw=2 sts=2 et:
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const TEST_URL_BASES = [
-  "http://example.org/browser/browser/base/content/test/dummy_page.html#tabmatch",
-  "http://example.org/browser/browser/base/content/test/moz.png#tabmatch"
-];
-
-var gPrivateBrowsing = Cc["@mozilla.org/privatebrowsing;1"].
-                         getService(Ci.nsIPrivateBrowsingService);
-var gController = Cc["@mozilla.org/autocomplete/controller;1"].
-                  getService(Ci.nsIAutoCompleteController);
-
-var gTabWaitCount = 0;
-var gTabCounter = 0;
-
-var gTestSteps = [
-  function() {
-    info("Running step 1");
-    for (let i = 0; i < 10; i++) {
-      let tab = gBrowser.addTab();
-      loadTab(tab, TEST_URL_BASES[0] + (++gTabCounter));
-    }
-  },
-  function() {
-    info("Running step 2");
-    gBrowser.selectTabAtIndex(1);
-    gBrowser.removeCurrentTab();
-    gBrowser.selectTabAtIndex(1);
-    gBrowser.removeCurrentTab();
-    for (let i = 1; i < gBrowser.tabs.length; i++)
-      loadTab(gBrowser.tabs[i], TEST_URL_BASES[1] + (++gTabCounter));
-  },
-  function() {
-    info("Running step 3");
-    for (let i = 1; i < gBrowser.tabs.length; i++)
-      loadTab(gBrowser.tabs[i], TEST_URL_BASES[0] + gTabCounter);
-  },
-  function() {
-    info("Running step 4");
-    let ps = Services.prefs;
-    ps.setBoolPref("browser.privatebrowsing.keep_current_session", true);
-    ps.setBoolPref("browser.tabs.warnOnClose", false);
-
-    // Make sure that all restored tabs are loaded without waiting for the user
-    // to bring them to the foreground. We ensure this by resetting the
-    // related preference (see the "firefox.js" defaults file for details).
-    ps.setBoolPref("browser.sessionstore.restore_on_demand", false);
-
-    gPrivateBrowsing.privateBrowsingEnabled = true;
-
-    executeSoon(function() {
-      ensure_opentabs_match_db(nextStep);
-    });
-  },
-  function() {
-    info("Running step 5");
-    gPrivateBrowsing.privateBrowsingEnabled = false;
-
-    executeSoon(function() {
-      let ps = Services.prefs;
-      ps.clearUserPref("browser.privatebrowsing.keep_current_session");
-      ps.clearUserPref("browser.tabs.warnOnClose");
-
-      ensure_opentabs_match_db(nextStep);
-    });
-  },
-  function() {
-    info("Running step 6 - ensure we don't register subframes as open pages");
-    let tab = gBrowser.addTab();
-    tab.linkedBrowser.addEventListener("load", function () {
-      tab.linkedBrowser.removeEventListener("load", arguments.callee, true);
-      // Start the sub-document load.
-      executeSoon(function () {
-        tab.linkedBrowser.addEventListener("load", function (e) {
-          tab.linkedBrowser.removeEventListener("load", arguments.callee, true);
-            ensure_opentabs_match_db(nextStep);
-        }, true);
-        tab.linkedBrowser.contentDocument.querySelector("iframe").src = "http://test2.example.org/";
-      });
-    }, true);
-    tab.linkedBrowser.loadURI('data:text/html,<body><iframe src=""></iframe></body>');
-  },
-  function() {
-    info("Running step 7 - remove tab immediately");
-    let tab = gBrowser.addTab("about:logo");
-    gBrowser.removeTab(tab);
-    ensure_opentabs_match_db(nextStep);
-  },
-  function() {
-    info("Running step 8 - check swapBrowsersAndCloseOther preserves registered switch-to-tab result");
-    let tabToKeep = gBrowser.addTab();
-    let tab = gBrowser.addTab();
-    tab.linkedBrowser.addEventListener("load", function () {
-      tab.linkedBrowser.removeEventListener("load", arguments.callee, true);
-      gBrowser.swapBrowsersAndCloseOther(tabToKeep, tab);
-      ensure_opentabs_match_db(function () {
-        gBrowser.removeTab(tabToKeep);
-        ensure_opentabs_match_db(nextStep);
-      });
-    }, true);
-    tab.linkedBrowser.loadURI("about:mozilla");
-  },
-  function() {
-    info("Running step 9 - enter private browsing mode, without keeping session");
-    let ps = Services.prefs;
-    ps.setBoolPref("browser.privatebrowsing.keep_current_session", false);
-    ps.setBoolPref("browser.tabs.warnOnClose", false);
-
-    Services.obs.addObserver(function(aSubject, aTopic, aData) {
-      Services.obs.removeObserver(arguments.callee, "private-browsing-transition-complete");
-
-      for (let i = 0; i < gBrowser.tabs.length; i++)
-        waitForRestoredTab(gBrowser.tabs[i]);
-    }, "private-browsing-transition-complete", false);
-
-    gPrivateBrowsing.privateBrowsingEnabled = true;
-  },
-  function() {
-    info("Running step 10 - open tabs in private browsing mode");
-    for (let i = 0; i < 3; i++) {
-      let tab = gBrowser.addTab();
-      loadTab(tab, TEST_URL_BASES[0] + (++gTabCounter));
-    }
-  },
-  function() {
-    info("Running step 11 - close tabs in private browsing mode");
-    gBrowser.removeCurrentTab();
-    ensure_opentabs_match_db(nextStep);
-  },
-  function() {
-    info("Running step 12 - leave private browsing mode");
-
-    Services.obs.addObserver(function(aSubject, aTopic, aData) {
-      Services.obs.removeObserver(arguments.callee, "private-browsing-transition-complete");
-
-      let ps = Services.prefs;
-      ps.clearUserPref("browser.privatebrowsing.keep_current_session");
-      ps.clearUserPref("browser.tabs.warnOnClose");
-
-      for (let i = 1; i < gBrowser.tabs.length; i++)
-        waitForRestoredTab(gBrowser.tabs[i]);
-
-    }, "private-browsing-transition-complete", false);
-
-    gPrivateBrowsing.privateBrowsingEnabled = false;
-  },
-  function() {
-    info("Running step 13 - close all tabs");
-
-    Services.prefs.clearUserPref("browser.sessionstore.restore_on_demand");
-
-    gBrowser.addTab("about:blank", {skipAnimation: true});
-    while (gBrowser.tabs.length > 1) {
-      info("Removing tab: " + gBrowser.tabs[0].linkedBrowser.currentURI.spec);
-      gBrowser.selectTabAtIndex(0);
-      gBrowser.removeCurrentTab();
-    }
-    ensure_opentabs_match_db(nextStep);
-  }
-];
-
-
-
-function test() {
-  waitForExplicitFinish();
-  nextStep();
-}
-
-function loadTab(tab, url) {
-  // Because adding visits is async, we will not be notified immediately.
-  let visited = gPrivateBrowsing.privateBrowsingEnabled;
-  let loaded = false;
-
-  function maybeCheckResults() {
-    if (visited && loaded && --gTabWaitCount == 0) {
-      ensure_opentabs_match_db(nextStep);
-    }
-  }
-
-  tab.linkedBrowser.addEventListener("load", function () {
-    tab.linkedBrowser.removeEventListener("load", arguments.callee, true);
-    loaded = true;
-    maybeCheckResults();
-  }, true);
-
-  if (!visited) {
-    Services.obs.addObserver(
-      function (aSubject, aTopic, aData) {
-        if (url != aSubject.QueryInterface(Ci.nsIURI).spec)
-          return;
-        Services.obs.removeObserver(arguments.callee, aTopic);
-        visited = true;
-        maybeCheckResults();
-      },
-      "uri-visit-saved",
-      false
-    );
-  }
-
-  gTabWaitCount++;
-  info("Loading page: " + url);
-  tab.linkedBrowser.loadURI(url);
-}
-
-function waitForRestoredTab(tab) {
-  gTabWaitCount++;
-
-  tab.linkedBrowser.addEventListener("load", function () {
-    tab.linkedBrowser.removeEventListener("load", arguments.callee, true);
-    if (--gTabWaitCount == 0) {
-      ensure_opentabs_match_db(nextStep);
-    }
-  }, true);
-}
-
-
-function nextStep() {
-  if (gTestSteps.length == 0) {
-    while (gBrowser.tabs.length > 1) {
-      gBrowser.selectTabAtIndex(1);
-      gBrowser.removeCurrentTab();
-    }
-
-    waitForClearHistory(finish);
-
-    return;
-  }
-
-  var stepFunc = gTestSteps.shift();
-  stepFunc();
-}
-
-function ensure_opentabs_match_db(aCallback) {
-  var tabs = {};
-
-  var winEnum = Services.wm.getEnumerator("navigator:browser");
-  while (winEnum.hasMoreElements()) {
-    let browserWin = winEnum.getNext();
-    // skip closed-but-not-destroyed windows
-    if (browserWin.closed)
-      continue;
-
-    for (let i = 0; i < browserWin.gBrowser.tabContainer.childElementCount; i++) {
-      let browser = browserWin.gBrowser.getBrowserAtIndex(i);
-      let url = browser.currentURI.spec;
-      if (browserWin.isBlankPageURL(url))
-        continue;
-      if (!(url in tabs))
-        tabs[url] = 1;
-      else
-        tabs[url]++;
-    }
-  }
-
-  checkAutocompleteResults(tabs, aCallback);
-}
-
-/**
- * Clears history invoking callback when done.
- */
-function waitForClearHistory(aCallback) {
-  const TOPIC_EXPIRATION_FINISHED = "places-expiration-finished";
-  let observer = {
-    observe: function(aSubject, aTopic, aData) {
-      Services.obs.removeObserver(this, TOPIC_EXPIRATION_FINISHED);
-      aCallback();
-    }
-  };
-  Services.obs.addObserver(observer, TOPIC_EXPIRATION_FINISHED, false);
-
-  PlacesUtils.bhistory.removeAllPages();
-}
-
-function checkAutocompleteResults(aExpected, aCallback)
-{
-  gController.input = {
-    timeout: 10,
-    textValue: "",
-    searches: ["history"],
-    searchParam: "enable-actions",
-    popupOpen: false,
-    minResultsForPopup: 0,
-    invalidate: function() {},
-    disableAutoComplete: false,
-    completeDefaultIndex: false,
-    get popup() { return this; },
-    onSearchBegin: function() {},
-    onSearchComplete:  function ()
-    {
-      info("Found " + gController.matchCount + " matches.");
-      // Check to see the expected uris and titles match up (in any order)
-      for (let i = 0; i < gController.matchCount; i++) {
-        let uri = gController.getValueAt(i).replace(/^moz-action:[^,]+,/i, "");
-
-        info("Search for '" + uri + "' in open tabs.");
-        ok(uri in aExpected, "Registered open page found in autocomplete.");
-        // Remove the found entry from expected results.
-        delete aExpected[uri];
-      }
-
-      // Make sure there is no reported open page that is not open.
-      for (let entry in aExpected) {
-        ok(false, "'" + entry + "' not found in autocomplete.");
-      }
-
-      executeSoon(aCallback);
-    },
-    setSelectedIndex: function() {},
-    get searchCount() { return this.searches.length; },
-    getSearchAt: function(aIndex) this.searches[aIndex],
-    QueryInterface: XPCOMUtils.generateQI([
-      Ci.nsIAutoCompleteInput,
-      Ci.nsIAutoCompletePopup,
-    ])
-  };
-
-  info("Searching open pages.");
-  gController.startSearch(Services.prefs.getCharPref("browser.urlbar.restrict.openpage"));
-}
--- a/browser/base/content/test/newtab/Makefile.in
+++ b/browser/base/content/test/newtab/Makefile.in
@@ -25,23 +25,14 @@ include $(topsrcdir)/config/rules.mk
 	browser_newtab_bug722273.js \
 	browser_newtab_bug723102.js \
 	browser_newtab_bug723121.js \
 	browser_newtab_bug725996.js \
 	browser_newtab_bug734043.js \
 	browser_newtab_bug735987.js \
 	browser_newtab_bug752841.js \
 	browser_newtab_bug765628.js \
+	browser_newtab_perwindow_private_browsing.js \
 	head.js \
 	$(NULL)
 
-ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
-_BROWSER_FILES += \
-        browser_newtab_perwindow_private_browsing.js \
-        $(NULL)
-else
-_BROWSER_FILES += \
-        browser_newtab_private_browsing.js \
-        $(NULL)
-endif
-
 libs::	$(_BROWSER_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
deleted file mode 100644
--- a/browser/base/content/test/newtab/browser_newtab_private_browsing.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * These tests ensure that all changes made to the new tab page in private
- * browsing mode are discarded after switching back to normal mode again.
- * The private browsing mode should start with the current grid shown in normal
- * mode.
- */
-let pb = Cc["@mozilla.org/privatebrowsing;1"]
-         .getService(Ci.nsIPrivateBrowsingService);
-
-function runTests() {
-  // prepare the grid
-  yield setLinks("0,1,2,3,4,5,6,7,8,9");
-  ok(!pb.privateBrowsingEnabled, "private browsing is disabled");
-
-  yield addNewTabPageTab();
-  pinCell(0);
-  checkGrid("0p,1,2,3,4,5,6,7,8");
-
-  // enter private browsing mode
-  yield togglePrivateBrowsing();
-  ok(pb.privateBrowsingEnabled, "private browsing is enabled");
-
-  yield addNewTabPageTab();
-  checkGrid("0p,1,2,3,4,5,6,7,8");
-
-  // modify the grid while we're in pb mode
-  yield blockCell(1);
-  checkGrid("0p,2,3,4,5,6,7,8");
-
-  yield unpinCell(0);
-  checkGrid("0,2,3,4,5,6,7,8");
-
-  // exit private browsing mode
-  yield togglePrivateBrowsing();
-  ok(!pb.privateBrowsingEnabled, "private browsing is disabled");
-
-  // check that the grid is the same as before entering pb mode
-  yield addNewTabPageTab();
-  checkGrid("0,2,3,4,5,6,7,8")
-}
-
-function togglePrivateBrowsing() {
-  let topic = "private-browsing-transition-complete";
-
-  Services.obs.addObserver(function observe() {
-    Services.obs.removeObserver(observe, topic);
-    executeSoon(TestRunner.next);
-  }, topic, false);
-
-  pb.privateBrowsingEnabled = !pb.privateBrowsingEnabled;
-}
--- a/browser/base/content/test/social/Makefile.in
+++ b/browser/base/content/test/social/Makefile.in
@@ -7,16 +7,17 @@ topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 relativesrcdir  = @relativesrcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 _BROWSER_FILES = \
                  head.js \
+                 browser_social_perwindowPB.js \
                  browser_social_toolbar.js \
                  browser_social_shareButton.js \
                  browser_social_sidebar.js \
                  browser_social_flyout.js \
                  browser_social_mozSocial_API.js \
                  browser_social_isVisible.js \
                  browser_social_chatwindow.js \
                  browser_social_multiprovider.js \
@@ -25,22 +26,12 @@ include $(DEPTH)/config/autoconf.mk
                  social_share_image.png \
                  social_sidebar.html \
                  social_chat.html \
                  social_flyout.html \
                  social_window.html \
                  social_worker.js \
                  $(NULL)
 
-ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
-_BROWSER_FILES += \
-                browser_social_perwindowPB.js \
-                $(NULL)
-else
-_BROWSER_FILES += \
-                browser_social_globalPB.js \
-                $(NULL)
-endif
-
 include $(topsrcdir)/config/rules.mk
 
 libs::	$(_BROWSER_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
deleted file mode 100644
--- a/browser/base/content/test/social/browser_social_globalPB.js
+++ /dev/null
@@ -1,147 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// a place for miscellaneous social tests
-
-
-const pb = Cc["@mozilla.org/privatebrowsing;1"].
-           getService(Ci.nsIPrivateBrowsingService);
-
-function waitForPortMessage(port, topic, callback) {
-  port.onmessage = function(evt) {
-    if (evt.data.topic == topic)
-      callback(evt.data);
-  }
-}
-
-function portClosed(port) {
-  try {
-    port.postMessage({topic: "ping"});
-    return false; // worked - port can't be closed!
-  } catch (ex) {
-    return true;
-  }
-}
-
-function test() {
-  waitForExplicitFinish();
-
-  let manifest = { // normal provider
-    name: "provider 1",
-    origin: "https://example.com",
-    sidebarURL: "https://example.com/browser/browser/base/content/test/social/social_sidebar.html",
-    workerURL: "https://example.com/browser/browser/base/content/test/social/social_worker.js",
-    iconURL: "https://example.com/browser/browser/base/content/test/moz.png"
-  };
-  runSocialTestWithProvider(manifest, function (finishcb) {
-    runSocialTests(tests, undefined, undefined, finishcb);
-  });
-}
-
-var tests = {
-  testPrivateBrowsing: function(next) {
-    let port = Social.provider.getWorkerPort();
-    ok(port, "provider has a port");
-    port.postMessage({topic: "test-init"});
-    port.onmessage = function (e) {
-      let topic = e.data.topic;
-      switch (topic) {
-        case "got-sidebar-message":
-          ok(true, "got sidebar message");
-          port.close();
-          togglePrivateBrowsing(function () {
-            ok(!Social.enabled, "Social shuts down during private browsing");
-            togglePrivateBrowsing(function () {
-              ok(Social.provider.getWorkerPort(), "port still obtainable after PB")
-              ok(Social.enabled, "Social enabled after private browsing");
-              next();
-            });
-          });
-          break;
-      }
-    };
-  },
-
-  testPrivateBrowsingSocialDisabled: function(next) {
-    // test PB from the perspective of entering PB without social enabled
-    // we expect social to be enabled at the start of the test, we need
-    // to disable it before testing PB transitions.
-    ok(Social.enabled, "social is still enabled");
-    let port = Social.provider.getWorkerPort();
-    ok(port, "provider has a port");
-    port.postMessage({topic: "test-init"});
-    port.onmessage = function (e) {
-      let topic = e.data.topic;
-      switch (topic) {
-        case "got-sidebar-message":
-          ok(true, "got sidebar message");
-          port.close();
-          Social.enabled = false;
-          break;
-      }
-    }
-
-    // wait for disable, then do some pb toggling. We expect social to remain
-    // disabled through these tests
-    Services.obs.addObserver(function observer(aSubject, aTopic) {
-      Services.obs.removeObserver(observer, aTopic);
-      ok(!Social.enabled, "Social is not enabled");
-      togglePrivateBrowsing(function () {
-        ok(!Social.enabled, "Social not available during private browsing");
-        togglePrivateBrowsing(function () {
-          ok(!Social.enabled, "Social is not enabled after private browsing");
-          // reenable social for next social test
-          Social.enabled = true;
-          next();
-        });
-      });
-    }, "social:pref-changed", false);
-  },
-
-  testPrivateBrowsingExitReloads: function(next) {
-    let port = Social.provider.getWorkerPort();
-    waitForPortMessage(port, "got-sidebar-message", function(data) {
-      ok(!portClosed(port), "port not closed before PB transition");
-      togglePrivateBrowsing(function () {
-        ok(!Social.enabled, "Social shuts down during private browsing");
-        // check the port we had before is dead.
-        ok(portClosed(port), "port closed after PB transition");
-        // enable it and stick a value in the window object.
-        Social.enabled = true;
-        port = Social.provider.getWorkerPort();
-        waitForPortMessage(port, "got-sidebar-message", function(data) {
-          // now just stuff a value in the sidebar - it should end
-          // up being removed when we leave PB mode via the sidebar
-          // being reloaded.
-          let sbw = document.getElementById("social-sidebar-browser").contentWindow;
-          sbw.wrappedJSObject.foo = "bar";
-          // Now toggle PB mode back to off.
-          togglePrivateBrowsing(function () {
-            ok(Social.enabled, "Social still enabled after leaving private browsing");
-            ok(portClosed(port), "port closed after PB transition");
-            port = Social.provider.getWorkerPort();
-            waitForPortMessage(port, "got-sidebar-message", function() {
-              sbw = document.getElementById("social-sidebar-browser").contentWindow;
-              is(sbw.wrappedJSObject.foo, undefined, "should have lost window variable when exiting")
-              next();
-            });
-            port.postMessage({topic: "test-init"});
-          });
-        });
-        port.postMessage({topic: "test-init"});
-      });
-    });
-    port.postMessage({topic: "test-init"});
-  },
-
-}
-
-function togglePrivateBrowsing(aCallback) {
-  Services.obs.addObserver(function observe(subject, topic, data) {
-    Services.obs.removeObserver(observe, topic);
-    executeSoon(aCallback);
-  }, "private-browsing-transition-complete", false);
-
-  pb.privateBrowsingEnabled = !pb.privateBrowsingEnabled;
-}
--- a/browser/base/content/utilityOverlay.js
+++ b/browser/base/content/utilityOverlay.js
@@ -5,44 +5,35 @@
 
 // Services = object with smart getters for common XPCOM services
 Components.utils.import("resource://gre/modules/Services.jsm");
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
 
 XPCOMUtils.defineLazyGetter(this, "BROWSER_NEW_TAB_URL", function () {
   const PREF = "browser.newtab.url";
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-  const TOPIC = "private-browsing-transition-complete";
-#endif
 
   function getNewTabPageURL() {
     if (!Services.prefs.prefHasUserValue(PREF)) {
       if (PrivateBrowsingUtils.isWindowPrivate(window) &&
           !PrivateBrowsingUtils.permanentPrivateBrowsing)
         return "about:privatebrowsing";
     }
     return Services.prefs.getCharPref(PREF) || "about:blank";
   }
 
   function update() {
     BROWSER_NEW_TAB_URL = getNewTabPageURL();
   }
 
   Services.prefs.addObserver(PREF, update, false);
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-  Services.obs.addObserver(update, TOPIC, false);
-#endif
 
   addEventListener("unload", function onUnload() {
     removeEventListener("unload", onUnload);
     Services.prefs.removeObserver(PREF, update);
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-    Services.obs.removeObserver(update, TOPIC);
-#endif
   });
 
   return getNewTabPageURL();
 });
 
 var TAB_DROP_TYPE = "application/x-moz-tabbrowser-tab";
 
 var gBidiUI = false;
@@ -270,21 +261,19 @@ function openLinkIn(url, where, params) 
 
     sa.AppendElement(wuri);
     sa.AppendElement(charset);
     sa.AppendElement(aReferrerURI);
     sa.AppendElement(aPostData);
     sa.AppendElement(allowThirdPartyFixupSupports);
 
     let features = "chrome,dialog=no,all";
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
     if (aIsPrivate) {
       features += ",private";
     }
-#endif
 
     Services.ww.openWindow(w || window, getBrowserURL(), null, features, sa);
     return;
   }
 
   let loadInBackground = where == "current" ? false : aInBackground;
   if (loadInBackground == null) {
     loadInBackground = aFromChrome ?
--- a/browser/components/build/Makefile.in
+++ b/browser/components/build/Makefile.in
@@ -39,21 +39,16 @@ OS_LIBS += $(call EXPAND_LIBNAME,version
 endif
 
 SHARED_LIBRARY_LIBS = \
 	../feeds/src/$(LIB_PREFIX)browser_feeds_s.$(LIB_SUFFIX) \
 	../about/$(LIB_PREFIX)browserabout_s.$(LIB_SUFFIX) \
 	../dirprovider/$(LIB_PREFIX)browserdir_s.$(LIB_SUFFIX) \
 	$(NULL)
 
-ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-LOCAL_INCLUDES += -I$(srcdir)/../privatebrowsing/src
-SHARED_LIBRARY_LIBS += ../privatebrowsing/src/$(LIB_PREFIX)privatebrowsing_s.$(LIB_SUFFIX)
-endif
-
 ifneq (,$(filter windows cocoa gtk2, $(MOZ_WIDGET_TOOLKIT)))
 SHARED_LIBRARY_LIBS += ../shell/src/$(LIB_PREFIX)shellservice_s.$(LIB_SUFFIX)
 endif
 
 EXTRA_DSO_LDOPTS += \
 	$(call EXPAND_LIBNAME_PATH,unicharutil_external_s,$(LIBXUL_DIST)/lib) \
 	$(XPCOM_STATICRUNTIME_GLUE_LDOPTS) \
 	$(MOZ_COMPONENT_LIBS) \
--- a/browser/components/build/nsModule.cpp
+++ b/browser/components/build/nsModule.cpp
@@ -20,19 +20,16 @@
 #include "nsIEHistoryEnumerator.h"
 #endif
 
 #include "rdf.h"
 #include "nsFeedSniffer.h"
 #include "AboutRedirector.h"
 #include "nsIAboutModule.h"
 
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-#include "nsPrivateBrowsingServiceWrapper.h"
-#endif
 #include "nsNetCID.h"
 
 using namespace mozilla::browser;
 
 /////////////////////////////////////////////////////////////////////////////
 
 NS_GENERIC_FACTORY_CONSTRUCTOR(DirectoryProvider)
 #if defined(XP_WIN)
@@ -44,54 +41,44 @@ NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsGN
 #endif
 
 #if defined(XP_WIN)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsIEHistoryEnumerator)
 #endif
 
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsFeedSniffer)
 
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsPrivateBrowsingServiceWrapper, Init)
-#endif
-
 NS_DEFINE_NAMED_CID(NS_BROWSERDIRECTORYPROVIDER_CID);
 #if defined(XP_WIN)
 NS_DEFINE_NAMED_CID(NS_SHELLSERVICE_CID);
 #elif defined(MOZ_WIDGET_GTK2)
 NS_DEFINE_NAMED_CID(NS_SHELLSERVICE_CID);
 #endif
 NS_DEFINE_NAMED_CID(NS_FEEDSNIFFER_CID);
 NS_DEFINE_NAMED_CID(NS_BROWSER_ABOUT_REDIRECTOR_CID);
 #if defined(XP_WIN)
 NS_DEFINE_NAMED_CID(NS_WINIEHISTORYENUMERATOR_CID);
 #elif defined(XP_MACOSX)
 NS_DEFINE_NAMED_CID(NS_SHELLSERVICE_CID);
 #endif
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-NS_DEFINE_NAMED_CID(NS_PRIVATE_BROWSING_SERVICE_WRAPPER_CID);
-#endif
 
 static const mozilla::Module::CIDEntry kBrowserCIDs[] = {
     { &kNS_BROWSERDIRECTORYPROVIDER_CID, false, NULL, DirectoryProviderConstructor },
 #if defined(XP_WIN)
     { &kNS_SHELLSERVICE_CID, false, NULL, nsWindowsShellServiceConstructor },
 #elif defined(MOZ_WIDGET_GTK2)
     { &kNS_SHELLSERVICE_CID, false, NULL, nsGNOMEShellServiceConstructor },
 #endif
     { &kNS_FEEDSNIFFER_CID, false, NULL, nsFeedSnifferConstructor },
     { &kNS_BROWSER_ABOUT_REDIRECTOR_CID, false, NULL, AboutRedirector::Create },
 #if defined(XP_WIN)
     { &kNS_WINIEHISTORYENUMERATOR_CID, false, NULL, nsIEHistoryEnumeratorConstructor },
 #elif defined(XP_MACOSX)
     { &kNS_SHELLSERVICE_CID, false, NULL, nsMacShellServiceConstructor },
 #endif
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-    { &kNS_PRIVATE_BROWSING_SERVICE_WRAPPER_CID, false, NULL, nsPrivateBrowsingServiceWrapperConstructor },
-#endif
     { NULL }
 };
 
 static const mozilla::Module::ContractIDEntry kBrowserContracts[] = {
     { NS_BROWSERDIRECTORYPROVIDER_CONTRACTID, &kNS_BROWSERDIRECTORYPROVIDER_CID },
 #if defined(XP_WIN)
     { NS_SHELLSERVICE_CONTRACTID, &kNS_SHELLSERVICE_CID },
 #elif defined(MOZ_WIDGET_GTK2)
@@ -120,19 +107,16 @@ static const mozilla::Module::ContractID
 #ifdef MOZ_SERVICES_HEALTHREPORT
     { NS_ABOUT_MODULE_CONTRACTID_PREFIX "healthreport", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
 #endif
 #if defined(XP_WIN)
     { NS_IEHISTORYENUMERATOR_CONTRACTID, &kNS_WINIEHISTORYENUMERATOR_CID },
 #elif defined(XP_MACOSX)
     { NS_SHELLSERVICE_CONTRACTID, &kNS_SHELLSERVICE_CID },
 #endif
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-    { NS_PRIVATE_BROWSING_SERVICE_CONTRACTID, &kNS_PRIVATE_BROWSING_SERVICE_WRAPPER_CID },
-#endif
     { NULL }
 };
 
 static const mozilla::Module::CategoryEntry kBrowserCategories[] = {
     { XPCOM_DIRECTORY_PROVIDER_CATEGORY, "browser-directory-provider", NS_BROWSERDIRECTORYPROVIDER_CONTRACTID },
     { NS_CONTENT_SNIFFER_CATEGORY, "Feed Sniffer", NS_FEEDSNIFFER_CONTRACTID },
     { NULL }
 };
--- a/browser/components/downloads/src/DownloadsCommon.jsm
+++ b/browser/components/downloads/src/DownloadsCommon.jsm
@@ -181,25 +181,21 @@ this.DownloadsCommon = {
   /**
    * Get access to one of the DownloadsData or PrivateDownloadsData objects,
    * depending on the privacy status of the window in question.
    *
    * @param aWindow
    *        The browser window which owns the download button.
    */
   getData: function DC_getData(aWindow) {
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
     if (PrivateBrowsingUtils.isWindowPrivate(aWindow)) {
       return PrivateDownloadsData;
     } else {
       return DownloadsData;
     }
-#else
-    return DownloadsData;
-#endif
   },
 
   /**
    * Initializes the data link for both the private and non-private downloads
    * data objects.
    *
    * @param aDownloadManagerService
    *        Reference to the service implementing nsIDownloadManager.  We need
@@ -234,57 +230,46 @@ this.DownloadsCommon = {
   },
 
   /**
    * Get access to one of the DownloadsIndicatorData or
    * PrivateDownloadsIndicatorData objects, depending on the privacy status of
    * the window in question.
    */
   getIndicatorData: function DC_getIndicatorData(aWindow) {
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
     if (PrivateBrowsingUtils.isWindowPrivate(aWindow)) {
       return PrivateDownloadsIndicatorData;
     } else {
       return DownloadsIndicatorData;
     }
-#else
-    return DownloadsIndicatorData;
-#endif
   },
 
   /**
    * Returns a reference to the DownloadsSummaryData singleton - creating one
    * in the process if one hasn't been instantiated yet.
    *
    * @param aWindow
    *        The browser window which owns the download button.
    * @param aNumToExclude
    *        The number of items on the top of the downloads list to exclude
    *        from the summary.
    */
   getSummary: function DC_getSummary(aWindow, aNumToExclude)
   {
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
     if (PrivateBrowsingUtils.isWindowPrivate(aWindow)) {
       if (this._privateSummary) {
         return this._privateSummary;
       }
       return this._privateSummary = new DownloadsSummaryData(true, aNumToExclude);
     } else {
       if (this._summary) {
         return this._summary;
       }
       return this._summary = new DownloadsSummaryData(false, aNumToExclude);
     }
-#else
-    if (this._summary) {
-      return this._summary;
-    }
-    return this._summary = new DownloadsSummaryData(false, aNumToExclude);
-#endif
   },
   _summary: null,
   _privateSummary: null,
 
   /**
    * Given an iterable collection of DownloadDataItems, generates and returns
    * statistics about that collection.
    *
@@ -554,22 +539,16 @@ function DownloadsDataCtor(aPrivate) {
 
   // This Object contains all the available DownloadsDataItem objects, indexed by
   // their globally unique identifier.  The identifiers of downloads that have
   // been removed from the Download Manager data are still present, however the
   // associated objects are replaced with the value "null".  This is required to
   // prevent race conditions when populating the list asynchronously.
   this.dataItems = {};
 
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-  // While operating in Private Browsing Mode, persistent data items are parked
-  // here until we return to the normal mode.
-  this._persistentDataItems = {};
-#endif
-
   // Array of view objects that should be notified when the available download
   // data changes.
   this._views = [];
 }
 
 DownloadsDataCtor.prototype = {
   /**
    * Starts receiving events for current downloads.
@@ -580,33 +559,26 @@ DownloadsDataCtor.prototype = {
    *        called, and we must ensure to register our listeners before the
    *        getService call for the Download Manager returns.
    */
   initializeDataLink: function DD_initializeDataLink(aDownloadManagerService)
   {
     // Start receiving real-time events.
     aDownloadManagerService.addPrivacyAwareListener(this);
     Services.obs.addObserver(this, "download-manager-remove-download-guid", false);
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-    Services.obs.addObserver(this, "download-manager-database-type-changed",
-                             false);
-#endif
   },
 
   /**
    * Stops receiving events for current downloads and cancels any pending read.
    */
   terminateDataLink: function DD_terminateDataLink()
   {
     this._terminateDataAccess();
 
     // Stop receiving real-time events.
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-    Services.obs.removeObserver(this, "download-manager-database-type-changed");
-#endif
     Services.obs.removeObserver(this, "download-manager-remove-download-guid");
     Services.downloads.removeListener(this);
   },
 
   //////////////////////////////////////////////////////////////////////////////
   //// Registration of views
 
   /**
@@ -912,51 +884,29 @@ DownloadsDataCtor.prototype = {
                                                  function(aStatus, aResult) {
               if (aStatus == Components.results.NS_ERROR_NOT_AVAILABLE) {
                 this._removeDataItem(dataItemBinding.downloadGuid);
               }
             }.bind(this));
           }
         }
         break;
-
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-      case "download-manager-database-type-changed":
-        let pbs = Cc["@mozilla.org/privatebrowsing;1"]
-                  .getService(Ci.nsIPrivateBrowsingService);
-        if (pbs.privateBrowsingEnabled) {
-          // Save a reference to the persistent store before terminating access.
-          this._persistentDataItems = this.dataItems;
-          this.clear();
-        } else {
-          // Terminate data access, then restore the persistent store.
-          this.clear();
-          this.dataItems = this._persistentDataItems;
-          this._persistentDataItems = null;
-        }
-        // Reinitialize the views with the current items.  View data has been
-        // already invalidated by the previous calls.
-        this._views.forEach(this._updateView, this);
-        break;
-#endif
     }
   },
 
   //////////////////////////////////////////////////////////////////////////////
   //// nsIDownloadProgressListener
 
   onDownloadStateChange: function DD_onDownloadStateChange(aOldState, aDownload)
   {
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
     if (aDownload.isPrivate != this._isPrivate) {
       // Ignore the downloads with a privacy status other than what we are
       // tracking.
       return;
     }
-#endif
 
     // When a new download is added, it may have the same identifier of a
     // download that we previously deleted during this session, and we also
     // want to provide a visible indication that the download started.
     let isNew = aOldState == nsIDM.DOWNLOAD_NOTSTARTED ||
                 aOldState == nsIDM.DOWNLOAD_QUEUED;
 
     let dataItem = this._getOrAddDataItem(aDownload, isNew);
@@ -1026,23 +976,21 @@ DownloadsDataCtor.prototype = {
   },
 
   onProgressChange: function DD_onProgressChange(aWebProgress, aRequest,
                                                   aCurSelfProgress,
                                                   aMaxSelfProgress,
                                                   aCurTotalProgress,
                                                   aMaxTotalProgress, aDownload)
   {
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
     if (aDownload.isPrivate != this._isPrivate) {
       // Ignore the downloads with a privacy status other than what we are
       // tracking.
       return;
     }
-#endif
 
     let dataItem = this._getOrAddDataItem(aDownload, false);
     if (!dataItem) {
       return;
     }
 
     dataItem.currBytes = aDownload.amountTransferred;
     dataItem.maxBytes = aDownload.size;
--- a/browser/components/downloads/src/DownloadsStartup.js
+++ b/browser/components/downloads/src/DownloadsStartup.js
@@ -26,32 +26,23 @@ const Cr = Components.results;
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "DownloadsCommon",
                                   "resource:///modules/DownloadsCommon.jsm");
 XPCOMUtils.defineLazyServiceGetter(this, "gSessionStartup",
                                    "@mozilla.org/browser/sessionstartup;1",
                                    "nsISessionStartup");
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-XPCOMUtils.defineLazyServiceGetter(this, "gPrivateBrowsingService",
-                                   "@mozilla.org/privatebrowsing;1",
-                                   "nsIPrivateBrowsingService");
-#endif
 
 const kObservedTopics = [
   "sessionstore-windows-restored",
   "sessionstore-browser-state-restored",
   "download-manager-initialized",
   "download-manager-change-retention",
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
   "last-pb-context-exited",
-#else
-  "private-browsing-transition-complete",
-#endif
   "browser-lastwindow-close-granted",
   "quit-application",
   "profile-change-teardown",
 ];
 
 /**
  * CID of our implementation of nsIDownloadManagerUI.
  */
@@ -140,46 +131,36 @@ DownloadsStartup.prototype = {
         if (!DownloadsCommon.useToolkitUI) {
           let removeFinishedDownloads = Services.prefs.getBoolPref(
                             "browser.download.panel.removeFinishedDownloads");
           aSubject.QueryInterface(Ci.nsISupportsPRInt32)
                   .data = removeFinishedDownloads ? 0 : 2;
         }
         break;
 
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-      case "private-browsing-transition-complete":
-        // Ensure that persistent data is reloaded only when the database
-        // connection is available again.
-        this._ensureDataLoaded();
-        break;
-#endif
-
       case "browser-lastwindow-close-granted":
         // When using the panel interface, downloads that are already completed
         // should be removed when the last full browser window is closed.  This
         // event is invoked only if the application is not shutting down yet.
         // If the Download Manager service is not initialized, we don't want to
         // initialize it just to clean up completed downloads, because they can
         // be present only in case there was a browser crash or restart.
         if (this._downloadsServiceInitialized &&
             !DownloadsCommon.useToolkitUI) {
           Services.downloads.cleanUp();
         }
         break;
 
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
       case "last-pb-context-exited":
         // Similar to the above notification, but for private downloads.
         if (this._downloadsServiceInitialized &&
             !DownloadsCommon.useToolkitUI) {
           Services.downloads.cleanUpPrivate();
         }
         break;
-#endif
 
       case "quit-application":
         // When the application is shutting down, we must free all resources in
         // addition to cleaning up completed downloads.  If the Download Manager
         // service is not initialized, we don't want to initialize it just to
         // clean up completed downloads, because they can be present only in
         // case there was a browser crash or restart.
         this._shuttingDown = true;
@@ -271,21 +252,17 @@ DownloadsStartup.prototype = {
     return aValue;
   },
 
   /**
    * Ensures that persistent download data is reloaded at the appropriate time.
    */
   _ensureDataLoaded: function DS_ensureDataLoaded()
   {
-    if (!this._downloadsServiceInitialized
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-        || gPrivateBrowsingService.privateBrowsingEnabled
-#endif
-       ) {
+    if (!this._downloadsServiceInitialized) {
       return;
     }
 
     // If the previous session has been already restored, then we ensure that
     // all the downloads are loaded.  Otherwise, we only ensure that the active
     // downloads from the previous session are loaded.
     DownloadsCommon.ensureAllPersistentDataLoaded(!this._recoverAllDownloads);
   }
--- a/browser/components/nsBrowserContentHandler.js
+++ b/browser/components/nsBrowserContentHandler.js
@@ -506,41 +506,32 @@ nsBrowserContentHandler.prototype = {
       }
     }
     if (cmdLine.handleFlag("preferences", false)) {
       openPreferences();
       cmdLine.preventDefault = true;
     }
     if (cmdLine.handleFlag("silent", false))
       cmdLine.preventDefault = true;
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
     if (cmdLine.handleFlag("private-window", false)) {
       openWindow(null, this.chromeURL, "_blank",
         "chrome,dialog=no,private,all" + this.getFeatures(cmdLine),
         "about:privatebrowsing");
       cmdLine.preventDefault = true;
     }
-#else
-    if (cmdLine.findFlag("private-toggle", false) >= 0)
-      cmdLine.preventDefault = true;
-#endif
 
     var searchParam = cmdLine.handleFlagWithParam("search", false);
     if (searchParam) {
       doSearch(searchParam, cmdLine);
       cmdLine.preventDefault = true;
     }
 
     // The global PB Service consumes this flag, so only eat it in per-window
     // PB builds.
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
     if (cmdLine.handleFlag("private", false)) {
-#else
-    if (cmdLine.findFlag("private", false) >= 0) {
-#endif
       PrivateBrowsingUtils.enterTemporaryAutoStartMode();
     }
 
     var fileParam = cmdLine.handleFlagWithParam("file", false);
     if (fileParam) {
       var file = cmdLine.resolveFile(fileParam);
       var ios = Components.classes["@mozilla.org/network/io-service;1"]
                           .getService(Components.interfaces.nsIIOService);
--- a/browser/components/nsBrowserGlue.js
+++ b/browser/components/nsBrowserGlue.js
@@ -152,19 +152,16 @@ BrowserGlue.prototype = {
     Cu.import("resource://services-sync/main.js");
     Weave.Service.scheduler.delayedAutoConnect(delay);
   },
 #endif
 
   // nsIObserver implementation 
   observe: function BG_observe(subject, topic, data) {
     switch (topic) {
-      case "xpcom-shutdown":
-        this._dispose();
-        break;
       case "prefservice:after-app-defaults":
         this._onAppDefaults();
         break;
       case "final-ui-startup":
         this._onProfileStartup();
         break;
       case "browser-delayed-startup-finished":
         this._onFirstWindowLoaded();
@@ -234,17 +231,17 @@ BrowserGlue.prototype = {
         this._isPlacesLockedObserver = false;
         break;
       case "places-shutdown":
         if (this._isPlacesShutdownObserver) {
           Services.obs.removeObserver(this, "places-shutdown");
           this._isPlacesShutdownObserver = false;
         }
         // places-shutdown is fired when the profile is about to disappear.
-        this._onProfileShutdown();
+        this._onPlacesShutdown();
         break;
       case "idle":
         if (this._idleService.idleTime > BOOKMARKS_BACKUP_IDLE_TIME * 1000)
           this._backupBookmarks();
         break;
       case "distribution-customization-complete":
         Services.obs.removeObserver(this, "distribution-customization-complete");
         // Customization has finished, we don't need the customizer anymore.
@@ -285,23 +282,25 @@ BrowserGlue.prototype = {
         if (!linkHandled.data) {
           let win = this.getMostRecentBrowserWindow();
           if (win) {
             win.openUILinkIn(data, "tab");
             linkHandled.data = true;
           }
         }
         break;
+      case "profile-before-change":
+        this._onProfileShutdown();
+        break;
     }
   }, 
 
   // initialization (called on application startup) 
   _init: function BG__init() {
     let os = Services.obs;
-    os.addObserver(this, "xpcom-shutdown", false);
     os.addObserver(this, "prefservice:after-app-defaults", false);
     os.addObserver(this, "final-ui-startup", false);
     os.addObserver(this, "browser-delayed-startup-finished", false);
     os.addObserver(this, "sessionstore-windows-restored", false);
     os.addObserver(this, "browser:purge-session-history", false);
     os.addObserver(this, "quit-application-requested", false);
     os.addObserver(this, "quit-application-granted", false);
 #ifdef OBSERVE_LASTWINDOW_CLOSE_TOPICS
@@ -317,22 +316,22 @@ BrowserGlue.prototype = {
     this._isPlacesInitObserver = true;
     os.addObserver(this, "places-database-locked", false);
     this._isPlacesLockedObserver = true;
     os.addObserver(this, "distribution-customization-complete", false);
     os.addObserver(this, "places-shutdown", false);
     this._isPlacesShutdownObserver = true;
     os.addObserver(this, "defaultURIFixup-using-keyword-pref", false);
     os.addObserver(this, "handle-xul-text-link", false);
+    os.addObserver(this, "profile-before-change", false);
   },
 
   // cleanup (called on application shutdown)
   _dispose: function BG__dispose() {
     let os = Services.obs;
-    os.removeObserver(this, "xpcom-shutdown");
     os.removeObserver(this, "prefservice:after-app-defaults");
     os.removeObserver(this, "final-ui-startup");
     os.removeObserver(this, "sessionstore-windows-restored");
     os.removeObserver(this, "browser:purge-session-history");
     os.removeObserver(this, "quit-application-requested");
     os.removeObserver(this, "quit-application-granted");
 #ifdef OBSERVE_LASTWINDOW_CLOSE_TOPICS
     os.removeObserver(this, "browser-lastwindow-close-requested");
@@ -348,20 +347,17 @@ BrowserGlue.prototype = {
     if (this._isPlacesInitObserver)
       os.removeObserver(this, "places-init-complete");
     if (this._isPlacesLockedObserver)
       os.removeObserver(this, "places-database-locked");
     if (this._isPlacesShutdownObserver)
       os.removeObserver(this, "places-shutdown");
     os.removeObserver(this, "defaultURIFixup-using-keyword-pref");
     os.removeObserver(this, "handle-xul-text-link");
-    UserAgentOverrides.uninit();
-    webappsUI.uninit();
-    SignInToWebsiteUX.uninit();
-    webrtcUI.uninit();
+    os.removeObserver(this, "profile-before-change");
   },
 
   _onAppDefaults: function BG__onAppDefaults() {
     // apply distribution customizations (prefs)
     // other customizations are applied in _onProfileStartup()
     this._distributionCustomizer.applyPrefDefaults();
   },
 
@@ -419,22 +415,28 @@ BrowserGlue.prototype = {
         Cc[WINTASKBAR_CONTRACTID].getService(Ci.nsIWinTaskbar).available) {
       let temp = {};
       Cu.import("resource://gre/modules/WindowsJumpLists.jsm", temp);
       temp.WinTaskbarJumpList.startup();
     }
 #endif
   },
 
-  // profile shutdown handler (contains profile cleanup routines)
+  /**
+   * Profile shutdown handler (contains profile cleanup routines).
+   * All components depending on Places should be shut down in
+   * _onPlacesShutdown() and not here.
+   */
   _onProfileShutdown: function BG__onProfileShutdown() {
-    this._shutdownPlaces();
-    this._sanitizer.onShutdown();
-    PageThumbs.uninit();
     BrowserNewTabPreloader.uninit();
+    UserAgentOverrides.uninit();
+    webappsUI.uninit();
+    SignInToWebsiteUX.uninit();
+    webrtcUI.uninit();
+    this._dispose();
   },
 
   // All initial windows have opened.
   _onWindowsRestored: function BG__onWindowsRestored() {
     // Show about:rights notification, if needed.
     if (this._shouldShowRights()) {
       this._showRightsNotification();
     }
@@ -1023,25 +1025,27 @@ BrowserGlue.prototype = {
       this._isIdleObserver = true;
     }
   },
 
   /**
    * Places shut-down tasks
    * - back up bookmarks if needed.
    * - export bookmarks as HTML, if so configured.
-   *
-   * Note: quit-application-granted notification is received twice
-   *       so replace this method with a no-op when first called.
+   * - finalize components depending on Places.
    */
-  _shutdownPlaces: function BG__shutdownPlaces() {
+  _onPlacesShutdown: function BG__onPlacesShutdown() {
+    this._sanitizer.onShutdown();
+    PageThumbs.uninit();
+
     if (this._isIdleObserver) {
       this._idleService.removeIdleObserver(this, BOOKMARKS_BACKUP_IDLE_TIME);
       this._isIdleObserver = false;
     }
+
     this._backupBookmarks();
 
     // Backup bookmarks to bookmarks.html to support apps that depend
     // on the legacy format.
     try {
       // If this fails to get the preference value, we don't export.
       if (Services.prefs.getBoolPref("browser.bookmarks.autoExportHTML")) {
         // Exceptionally, since this is a non-default setting and HTML format is
--- a/browser/components/places/content/controller.js
+++ b/browser/components/places/content/controller.js
@@ -134,23 +134,18 @@ PlacesController.prototype = {
       // If selection includes history nodes there's no reason to allow cut.
       for (var i = 0; i < nodes.length; i++) {
         if (nodes[i].itemId == -1)
           return false;
       }
       // Otherwise fallback to cmd_delete check.
     case "cmd_delete":
     case "placesCmd_delete":
+    case "placesCmd_deleteDataHost":
       return this._hasRemovableSelection(false);
-    case "placesCmd_deleteDataHost":
-      return this._hasRemovableSelection(false)
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-        && !PlacesUIUtils.privateBrowsing.privateBrowsingEnabled
-#endif
-        ;
     case "placesCmd_moveBookmarks":
       return this._hasRemovableSelection(true);
     case "cmd_copy":
     case "placesCmd_copy":
       return this._view.hasSelection;
     case "cmd_paste":
     case "placesCmd_paste":
       return this._canInsert(true) && this._isClipboardDataPasteable();
@@ -599,24 +594,17 @@ PlacesController.prototype = {
     var visibleItemsBeforeSep = false;
     var anyVisible = false;
     for (var i = 0; i < aPopup.childNodes.length; ++i) {
       var item = aPopup.childNodes[i];
       if (item.localName != "menuseparator") {
         // We allow pasting into tag containers, so special case that.
         var hideIfNoIP = item.getAttribute("hideifnoinsertionpoint") == "true" &&
                          noIp && !(ip && ip.isTag && item.id == "placesContext_paste");
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
-        var hideIfPB = false;
-#else
-        var hideIfPB = item.getAttribute("hideifprivatebrowsing") == "true" &&
-                       PlacesUIUtils.privateBrowsing.privateBrowsingEnabled;
-#endif
-        item.hidden = hideIfNoIP || hideIfPB ||
-                      !this._shouldShowMenuItem(item, metadata);
+        item.hidden = hideIfNoIP || !this._shouldShowMenuItem(item, metadata);
 
         if (!item.hidden) {
           visibleItemsBeforeSep = true;
           anyVisible = true;
 
           // Show the separator above the menu-item if any
           if (separator) {
             separator.hidden = false;
--- a/browser/components/places/content/places.js
+++ b/browser/components/places/content/places.js
@@ -70,20 +70,16 @@ var PlacesOrganizer = {
     var historyMenuForward = document.getElementById("historyMenuForward");
     historyMenuForward.removeAttribute("key");
 #endif
 
     // remove the "Properties" context-menu item, we've our own details pane
     document.getElementById("placesContext")
             .removeChild(document.getElementById("placesContext_show:info"));
 
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-    gPrivateBrowsingListener.init();
-#endif
-
     ContentArea.focus();
   },
 
   QueryInterface: function PO_QueryInterface(aIID) {
     if (aIID.equals(Components.interfaces.nsIDOMEventListener) ||
         aIID.equals(Components.interfaces.nsISupports))
       return this;
 
@@ -106,19 +102,16 @@ var PlacesOrganizer = {
         break;
       case "Search":
         PlacesSearchBox.findAll();
         break;
     }
   },
 
   destroy: function PO_destroy() {
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-    gPrivateBrowsingListener.uninit();
-#endif
   },
 
   _location: null,
   get location() {
     return this._location;
   },
 
   set location(aLocation) {
@@ -1193,55 +1186,16 @@ var ViewMenu = {
     aDirection = (aDirection || colLookupTable[columnId].dir).toUpperCase();
 
     var sortConst = "SORT_BY_" + colLookupTable[columnId].key + "_" + aDirection;
     result.sortingAnnotation = colLookupTable[columnId].anno || "";
     result.sortingMode = Ci.nsINavHistoryQueryOptions[sortConst];
   }
 }
 
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-/**
- * Disables the "Import and Backup->Import From Another Browser" menu item
- * in private browsing mode.
- */
-let gPrivateBrowsingListener = {
-  _cmd_import: null,
-
-  init: function PO_PB_init() {
-    this._cmd_import = document.getElementById("OrganizerCommand_browserImport");
-
-    let pbs = Cc["@mozilla.org/privatebrowsing;1"].
-              getService(Ci.nsIPrivateBrowsingService);
-    if (pbs.privateBrowsingEnabled)
-      this.updateUI(true);
-
-    Services.obs.addObserver(this, "private-browsing", false);
-  },
-
-  uninit: function PO_PB_uninit() {
-    Services.obs.removeObserver(this, "private-browsing");
-  },
-
-  observe: function PO_PB_observe(aSubject, aTopic, aData) {
-    if (aData == "enter")
-      this.updateUI(true);
-    else if (aData == "exit")
-      this.updateUI(false);
-  },
-
-  updateUI: function PO_PB_updateUI(PBmode) {
-    if (PBmode)
-      this._cmd_import.setAttribute("disabled", "true");
-    else
-      this._cmd_import.removeAttribute("disabled");
-  }
-};
-#endif
-
 let ContentArea = {
   _specialViews: new Map(),
 
   init: function CA_init() {
     this._deck = document.getElementById("placesViewsDeck");
     this._toolbar = document.getElementById("placesToolbar");
     ContentTree.init();
     this._setupView();
--- a/browser/components/places/src/PlacesUIUtils.jsm
+++ b/browser/components/places/src/PlacesUIUtils.jsm
@@ -1004,22 +1004,16 @@ XPCOMUtils.defineLazyGetter(PlacesUIUtil
   return PlacesUIUtils.RDF.GetDataSource("rdf:local-store");
 });
 
 XPCOMUtils.defineLazyGetter(PlacesUIUtils, "ellipsis", function() {
   return Services.prefs.getComplexValue("intl.ellipsis",
                                         Ci.nsIPrefLocalizedString).data;
 });
 
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-XPCOMUtils.defineLazyServiceGetter(PlacesUIUtils, "privateBrowsing",
-                                   "@mozilla.org/privatebrowsing;1",
-                                   "nsIPrivateBrowsingService");
-#endif
-
 XPCOMUtils.defineLazyServiceGetter(this, "URIFixup",
                                    "@mozilla.org/docshell/urifixup;1",
                                    "nsIURIFixup");
 
 XPCOMUtils.defineLazyGetter(this, "bundle", function() {
   const PLACES_STRING_BUNDLE_URI =
     "chrome://browser/locale/places/places.properties";
   return Cc["@mozilla.org/intl/stringbundle;1"].
--- a/browser/components/preferences/in-content/jar.mn
+++ b/browser/components/preferences/in-content/jar.mn
@@ -5,18 +5,18 @@
 browser.jar:
 *  content/browser/preferences/in-content/preferences.js
    content/browser/preferences/in-content/landing.xul
 *  content/browser/preferences/in-content/preferences.xul
 *  content/browser/preferences/in-content/main.xul
    content/browser/preferences/in-content/main.js
 *  content/browser/preferences/in-content/tabs.xul
 *  content/browser/preferences/in-content/tabs.js
-*  content/browser/preferences/in-content/privacy.xul
-*  content/browser/preferences/in-content/privacy.js
+   content/browser/preferences/in-content/privacy.xul
+   content/browser/preferences/in-content/privacy.js
 *  content/browser/preferences/in-content/advanced.xul
 *  content/browser/preferences/in-content/advanced.js
    content/browser/preferences/in-content/applications.xul
 *  content/browser/preferences/in-content/applications.js
    content/browser/preferences/in-content/content.xul
    content/browser/preferences/in-content/content.js
    content/browser/preferences/in-content/sync.xul
    content/browser/preferences/in-content/sync.js
--- a/browser/components/preferences/in-content/privacy.js
+++ b/browser/components/preferences/in-content/privacy.js
@@ -271,17 +271,16 @@ var gPrivacyPane = {
   },
 
   autoStartPrivateBrowsingObserver:
   {
     QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIObserver]),
 
     observe: function PPP_observe(aSubject, aTopic, aData)
     {
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
       if (!gPrivacyPane._shouldPromptForRestart) {
         // We're performing a revert. Just let it happen.
         gPrivacyPane._shouldPromptForRestart = true;
         return;
       }
 
       const Cc = Components.classes, Ci = Components.interfaces;
       let pref = document.getElementById("browser.privatebrowsing.autostart");
@@ -313,33 +312,16 @@ var gPrivacyPane = {
       let mode = document.getElementById("historyMode");
       if (mode.value != "custom") {
         mode.selectedIndex = pref.value ? 1 : 0;
         mode.doCommand();
       } else {
         let rememberHistoryCheckbox = document.getElementById("rememberHistory");
         rememberHistory.checked = pref.value;
       }
-#else
-      // Toggle the private browsing mode without switching the session
-      let prefValue = document.getElementById("browser.privatebrowsing.autostart").value;
-      let keepCurrentSession = document.getElementById("browser.privatebrowsing.keep_current_session");
-      keepCurrentSession.value = true;
-
-      let privateBrowsingService = Components.classes["@mozilla.org/privatebrowsing;1"].
-        getService(Components.interfaces.nsIPrivateBrowsingService);
-
-      // If activating from within the private browsing mode, reset the
-      // private session
-      if (prefValue && privateBrowsingService.privateBrowsingEnabled)
-        privateBrowsingService.privateBrowsingEnabled = false;
-      privateBrowsingService.privateBrowsingEnabled = prefValue;
-
-      keepCurrentSession.reset();
-#endif
     }
   },
 
   // HISTORY
 
   /**
    * Read the location bar enabled and suggestion prefs
    * @return Int value for suggestion menulist
--- a/browser/components/preferences/in-content/privacy.xul
+++ b/browser/components/preferences/in-content/privacy.xul
@@ -56,26 +56,18 @@
               type="bool"/>
   <preference id="privacy.sanitize.timeSpan"
               name="privacy.sanitize.timeSpan"
               type="int"/>
   <!-- Private Browsing -->
   <preference id="browser.privatebrowsing.autostart"
               name="browser.privatebrowsing.autostart"
               onchange="gPrivacyPane.updatePrivacyMicroControls();"
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
-              instantApply="true"
-#endif
-              type="bool"/>
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-  <preference id="browser.privatebrowsing.keep_current_session"
-              name="browser.privatebrowsing.keep_current_session"
               instantApply="true"
               type="bool"/>
-#endif
 
 </preferences>
 
 <hbox class="heading" data-category="panePrivacy" hidden="true">
   <image class="preference-icon" type="privacy"/>
   <html:h1>&panePrivacy.title;</html:h1>
 </hbox>
 
--- a/browser/components/preferences/in-content/tests/Makefile.in
+++ b/browser/components/preferences/in-content/tests/Makefile.in
@@ -12,40 +12,22 @@ include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _BROWSER_FILES = \
     head.js \
     browser_advanced_update.js \
     browser_bug410900.js \
     browser_bug731866.js \
     browser_connection.js \
-    $(NULL)
-
-ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-_BROWSER_FILES += \
-    privacypane_tests.js \
-    browser_bug567487.js \
-    browser_privacypane_1.js \
-    browser_privacypane_2.js \
-    browser_privacypane_3.js \
-    browser_privacypane_4.js \
-    browser_privacypane_5.js \
-    browser_privacypane_6.js \
-    browser_privacypane_7.js \
-    browser_privacypane_8.js \
-    $(NULL)
-else
-_BROWSER_FILES += \
-    privacypane_tests_perwindow.js \
     browser_privacypane_1.js \
     browser_privacypane_3.js \
     browser_privacypane_4.js \
     browser_privacypane_5.js \
     browser_privacypane_8.js \
+    privacypane_tests_perwindow.js \
     $(NULL)
-endif
 
 ifdef MOZ_SERVICES_HEALTHREPORT
 _BROWSER_FILES += browser_healthreport.js
 endif
 
 libs::	$(_BROWSER_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
deleted file mode 100644
--- a/browser/components/preferences/in-content/tests/browser_bug567487.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
-  waitForExplicitFinish();
-  resetPreferences();
-
-  function observer(win, topic, data) {
-    if (topic != "main-pane-loaded")
-      return;
-
-    Services.obs.removeObserver(observer, "main-pane-loaded");
-    runTest(win);
-  }
-  Services.obs.addObserver(observer, "main-pane-loaded", false);
-
-  gBrowser.selectedTab = gBrowser.addTab("about:preferences");
-}
-
-function runTest(win) {
-  win.gotoPref("general");
-  let doc = win.document;
-  let pbAutoStartPref = doc.getElementById("browser.privatebrowsing.autostart");
-  let startupPref = doc.getElementById("browser.startup.page");
-  let menu = doc.getElementById("browserStartupPage");
-  let option = doc.getElementById("browserStartupLastSession");
-  let defOption = doc.getElementById("browserStartupHomePage");
-  let otherOption = doc.getElementById("browserStartupBlank");
-
-  ok(!pbAutoStartPref.value, "Sanity check");
-  is(startupPref.value, startupPref.defaultValue, "Sanity check");
-
-  // First, check to make sure that setting pbAutoStartPref disables the menu item
-  pbAutoStartPref.value = true;
-  is(option.getAttribute("disabled"), "true", "Setting private browsing to autostart " +
-     "should disable the 'Show my tabs and windows from last time' option");
-  pbAutoStartPref.value = false;
-
-  // Now ensure the correct behavior when pbAutoStartPref is set with option enabled
-  startupPref.value = option.getAttribute("value");
-  is(menu.selectedItem, option, "Sanity check");
-  pbAutoStartPref.value = true;
-  is(option.getAttribute("disabled"), "true", "Setting private browsing to autostart " +
-     "should disable the 'Show my tabs and windows from last time' option");
-  is(menu.selectedItem, defOption, "The 'Show home page' option should be selected");
-  is(startupPref.value, option.getAttribute("value"), "But the value of the startup " +
-     "pref itself shouldn't change");
-  menu.selectedItem = otherOption;
-  menu.doCommand();
-  is(startupPref.value, otherOption.getAttribute("value"), "And we should be able to " +
-     "chnage it!");
-  pbAutoStartPref.value = false;
-
-  // Now, ensure that with 'Show my windows and tabs from last time' enabled, toggling
-  // pbAutoStartPref would restore that value in the menulist.
-  startupPref.value = option.getAttribute("value");
-  is(menu.selectedItem, option, "Sanity check");
-  pbAutoStartPref.value = true;
-  is(menu.selectedItem, defOption, "The 'Show home page' option should be selected");
-  pbAutoStartPref.value = false;
-  is(menu.selectedItem, option, "The correct value should be restored");
-
-  // cleanup
-  resetPreferences();
-  gBrowser.removeCurrentTab();
-  win.close();
-  finish();
-}
-
-function resetPreferences() {
-  Services.prefs.clearUserPref("browser.startup.page");
-  Services.prefs.clearUserPref("browser.privatebrowsing.autostart");
-}
--- a/browser/components/preferences/in-content/tests/browser_privacypane_1.js
+++ b/browser/components/preferences/in-content/tests/browser_privacypane_1.js
@@ -6,21 +6,17 @@ function test() {
                getService(Ci.mozIJSSubScriptLoader);
 
   let rootDir = getRootDirectory(gTestPath);
   let jar = getJar(rootDir);
   if (jar) {
     let tmpdir = extractJarToTmp(jar);
     rootDir = "file://" + tmpdir.path + '/';
   }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
+  loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
 
   run_test_subset([
     test_pane_visibility,
     test_dependent_elements,
     test_dependent_cookie_elements,
     test_dependent_clearonclose_elements,
     test_dependent_prefs,
 
deleted file mode 100644
--- a/browser/components/preferences/in-content/tests/browser_privacypane_2.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
-  let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
-               getService(Ci.mozIJSSubScriptLoader);
-
-  let rootDir = getRootDirectory(gTestPath);
-  let jar = getJar(rootDir);
-  if (jar) {
-    let tmpdir = extractJarToTmp(jar);
-    rootDir = "file://" + tmpdir.path + '/';
-  }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
-
-  run_test_subset([
-    test_historymode_retention("remember", undefined),
-    test_historymode_retention("dontremember", "remember"),
-    test_historymode_retention("custom", "dontremember"),
-    // custom without any micro-prefs changed won't retain
-    test_historymode_retention("remember", "dontremember"),
-    test_historymode_retention("custom", "remember"),
-    // custom without any micro-prefs changed won't retain
-    test_historymode_retention("remember", "remember"),
-
-    // reset all preferences to their default values once we're done
-    reset_preferences
-  ]);
-}
--- a/browser/components/preferences/in-content/tests/browser_privacypane_3.js
+++ b/browser/components/preferences/in-content/tests/browser_privacypane_3.js
@@ -5,21 +5,17 @@ function test() {
   let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
                getService(Ci.mozIJSSubScriptLoader);
   let rootDir = getRootDirectory(gTestPath);
   let jar = getJar(rootDir);
   if (jar) {
     let tmpdir = extractJarToTmp(jar);
     rootDir = "file://" + tmpdir.path + '/';
   }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
+  loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
 
   run_test_subset([
     test_custom_retention("rememberHistory", "remember"),
     test_custom_retention("rememberHistory", "custom"),
     test_custom_retention("rememberForms", "remember"),
     test_custom_retention("rememberForms", "custom"),
     test_historymode_retention("remember", "remember"),
 
--- a/browser/components/preferences/in-content/tests/browser_privacypane_4.js
+++ b/browser/components/preferences/in-content/tests/browser_privacypane_4.js
@@ -5,21 +5,17 @@ function test() {
   let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
                getService(Ci.mozIJSSubScriptLoader);
   let rootDir = getRootDirectory(gTestPath);
   let jar = getJar(rootDir);
   if (jar) {
     let tmpdir = extractJarToTmp(jar);
     rootDir = "file://" + tmpdir.path + '/';
   }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
+  loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
 
   run_test_subset([
     test_custom_retention("acceptCookies", "remember"),
     test_custom_retention("acceptCookies", "custom"),
     test_custom_retention("acceptThirdParty", "remember"),
     test_custom_retention("acceptThirdParty", "custom"),
     test_custom_retention("keepCookiesUntil", "remember", 1),
     test_custom_retention("keepCookiesUntil", "custom", 2),
--- a/browser/components/preferences/in-content/tests/browser_privacypane_5.js
+++ b/browser/components/preferences/in-content/tests/browser_privacypane_5.js
@@ -5,21 +5,17 @@ function test() {
   let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
                getService(Ci.mozIJSSubScriptLoader);
   let rootDir = getRootDirectory(gTestPath);
   let jar = getJar(rootDir);
   if (jar) {
     let tmpdir = extractJarToTmp(jar);
     rootDir = "file://" + tmpdir.path + '/';
   }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
+  loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
 
   run_test_subset([
     test_locbar_suggestion_retention(-1, undefined),
     test_locbar_suggestion_retention(1, -1),
     test_locbar_suggestion_retention(2, 1),
     test_locbar_suggestion_retention(0, 2),
     test_locbar_suggestion_retention(0, 0),
 
deleted file mode 100644
--- a/browser/components/preferences/in-content/tests/browser_privacypane_6.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
-  let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
-               getService(Ci.mozIJSSubScriptLoader);
-  let rootDir = getRootDirectory(gTestPath);
-  let jar = getJar(rootDir);
-  if (jar) {
-    let tmpdir = extractJarToTmp(jar);
-    rootDir = "file://" + tmpdir.path + '/';
-  }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
-
-  run_test_subset([
-    test_privatebrowsing_toggle,
-    enter_private_browsing, // once again, test with PB initially enabled
-    test_privatebrowsing_toggle,
-
-    // don't reset preferences, will pick up where we left off in browser_privacypane_7.js
-  ]);
-}
deleted file mode 100644
--- a/browser/components/preferences/in-content/tests/browser_privacypane_7.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
-  let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
-               getService(Ci.mozIJSSubScriptLoader);
-  let rootDir = getRootDirectory(gTestPath);
-  let jar = getJar(rootDir);
-  if (jar) {
-    let tmpdir = extractJarToTmp(jar);
-    rootDir = "file://" + tmpdir.path + '/';
-  }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
-
-  run_test_subset([
-    test_privatebrowsing_ui,
-    enter_private_browsing, // once again, test with PB initially enabled
-    test_privatebrowsing_ui,
-
-    // reset all preferences to their default values once we're done
-    reset_preferences
-  ]);
-}
--- a/browser/components/preferences/in-content/tests/browser_privacypane_8.js
+++ b/browser/components/preferences/in-content/tests/browser_privacypane_8.js
@@ -5,21 +5,17 @@ function test() {
   let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
                getService(Ci.mozIJSSubScriptLoader);
   let rootDir = getRootDirectory(gTestPath);
   let jar = getJar(rootDir);
   if (jar) {
     let tmpdir = extractJarToTmp(jar);
     rootDir = "file://" + tmpdir.path + '/';
   }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
+  loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
 
   run_test_subset([
     // history mode should be initialized to remember
     test_historymode_retention("remember", undefined),
 
     // history mode should remain remember; toggle acceptCookies checkbox
     test_custom_retention("acceptCookies", "remember"),
 
deleted file mode 100644
--- a/browser/components/preferences/in-content/tests/privacypane_tests.js
+++ /dev/null
@@ -1,491 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function runTestOnPrivacyPrefPane(testFunc) {
-  
-  gBrowser.tabContainer.addEventListener("TabOpen", function(aEvent) {
-    gBrowser.tabContainer.removeEventListener("TabOpen", arguments.callee, true);
-    let browser = aEvent.originalTarget.linkedBrowser;
-    browser.addEventListener("Initialized", function(aEvent) {
-      browser.removeEventListener("Initialized", arguments.callee, true);
-      is(browser.contentWindow.location.href, "about:preferences", "Checking if the preferences tab was opened");
-      testFunc(browser.contentWindow);
-      gBrowser.removeCurrentTab();
-      testRunner.runNext();
-    }, true);
-  }, true);
-  
-  gBrowser.selectedTab = gBrowser.addTab("about:preferences");
-}
-
-function controlChanged(element) {
-  element.doCommand();
-}
-
-function test_pane_visibility(win) {
-  let modes = {
-    "remember": "historyRememberPane",
-    "dontremember": "historyDontRememberPane",
-    "custom": "historyCustomPane"
-  };
-
-  let historymode = win.document.getElementById("historyMode");
-  ok(historymode, "history mode menulist should exist");
-  let historypane = win.document.getElementById("historyPane");
-  ok(historypane, "history mode pane should exist");
-
-  for (let mode in modes) {
-    historymode.value = mode;
-    controlChanged(historymode);
-    is(historypane.selectedPanel, win.document.getElementById(modes[mode]),
-      "The correct pane should be selected for the " + mode + " mode");
-  }
-}
-
-function test_dependent_elements(win) {
-  let historymode = win.document.getElementById("historyMode");
-  ok(historymode, "history mode menulist should exist");
-  let pbautostart = win.document.getElementById("privateBrowsingAutoStart");
-  ok(pbautostart, "the private browsing auto-start checkbox should exist");
-  let controls = [
-    win.document.getElementById("rememberHistory"),
-    win.document.getElementById("rememberForms"),
-    win.document.getElementById("keepUntil"),
-    win.document.getElementById("keepCookiesUntil"),
-    win.document.getElementById("alwaysClear"),
-  ];
-  controls.forEach(function(control) {
-    ok(control, "the dependent controls should exist");
-  });
-  let independents = [
-    win.document.getElementById("acceptCookies"),
-    win.document.getElementById("acceptThirdParty"),
-  ];
-  independents.forEach(function(control) {
-    ok(control, "the independent controls should exist");
-  });
-  let cookieexceptions = win.document.getElementById("cookieExceptions");
-  ok(cookieexceptions, "the cookie exceptions button should exist");
-  let keepuntil = win.document.getElementById("keepCookiesUntil");
-  ok(keepuntil, "the keep cookies until menulist should exist");
-  let alwaysclear = win.document.getElementById("alwaysClear");
-  ok(alwaysclear, "the clear data on close checkbox should exist");
-  let rememberhistory = win.document.getElementById("rememberHistory");
-  ok(rememberhistory, "the remember history checkbox should exist");
-  let rememberforms = win.document.getElementById("rememberForms");
-  ok(rememberforms, "the remember forms checkbox should exist");
-  let alwaysclearsettings = win.document.getElementById("clearDataSettings");
-  ok(alwaysclearsettings, "the clear data settings button should exist");
-
-  function expect_disabled(disabled) {
-    controls.forEach(function(control) {
-      is(control.disabled, disabled,
-        control.getAttribute("id") + " should " + (disabled ? "" : "not ") + "be disabled");
-    });
-    is(keepuntil.value, disabled ? 2 : 0,
-      "the keep cookies until menulist value should be as expected");
-    if (disabled) {
-     ok(!alwaysclear.checked,
-        "the clear data on close checkbox value should be as expected");
-     ok(!rememberhistory.checked,
-        "the remember history checkbox value should be as expected");
-     ok(!rememberforms.checked,
-        "the remember forms checkbox value should be as expected");
-    }
-  }
-  function check_independents(expected) {
-    independents.forEach(function(control) {
-      is(control.disabled, expected,
-        control.getAttribute("id") + " should " + (expected ? "" : "not ") + "be disabled");
-    });
-
-    ok(!cookieexceptions.disabled,
-      "the cookie exceptions button should never be disabled");
-    ok(alwaysclearsettings.disabled,
-      "the clear data settings button should always be disabled");
-  }
-
-  // controls should only change in custom mode
-  historymode.value = "remember";
-  controlChanged(historymode);
-  expect_disabled(false);
-  check_independents(false);
-
-  // setting the mode to custom shouldn't change anything
-  historymode.value = "custom";
-  controlChanged(historymode);
-  expect_disabled(false);
-  check_independents(false);
-
-  // controls should only change in custom mode
-  historymode.value = "dontremember";
-  controlChanged(historymode);
-  expect_disabled(false);
-  check_independents(false);
-
-  // controls should only change in custom mode
-  historymode.value = "custom";
-  controlChanged(historymode);
-  expect_disabled(true);
-  check_independents(false);
-
-  // dependent controls should follow pbautostart
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  expect_disabled(false);
-  check_independents(false);
-
-  // dependent controls should follow pbautostart
-  pbautostart.checked = true;
-  controlChanged(pbautostart);
-  expect_disabled(true);
-  check_independents(false);
-}
-
-function test_dependent_cookie_elements(win) {
-  let historymode = win.document.getElementById("historyMode");
-  ok(historymode, "history mode menulist should exist");
-  let pbautostart = win.document.getElementById("privateBrowsingAutoStart");
-  ok(pbautostart, "the private browsing auto-start checkbox should exist");
-  let controls = [
-    win.document.getElementById("acceptThirdParty"),
-    win.document.getElementById("keepUntil"),
-    win.document.getElementById("keepCookiesUntil"),
-  ];
-  controls.forEach(function(control) {
-    ok(control, "the dependent cookie controls should exist");
-  });
-  let acceptcookies = win.document.getElementById("acceptCookies");
-  ok(acceptcookies, "the accept cookies checkbox should exist");
-
-  function expect_disabled(disabled) {
-    controls.forEach(function(control) {
-      is(control.disabled, disabled,
-        control.getAttribute("id") + " should " + (disabled ? "" : "not ") + "be disabled");
-    });
-  }
-
-  historymode.value = "custom";
-  controlChanged(historymode);
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  expect_disabled(false);
-
-  acceptcookies.checked = false;
-  controlChanged(acceptcookies);
-  expect_disabled(true);
-
-  // pbautostart shouldn't change anything now
-  pbautostart.checked = true;
-  controlChanged(pbautostart);
-  expect_disabled(true);
-
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  expect_disabled(true);
-
-  acceptcookies.checked = true;
-  controlChanged(acceptcookies);
-  expect_disabled(false);
-
-  let accessthirdparty = controls.shift();
-  pbautostart.checked = true;
-  controlChanged(pbautostart);
-  expect_disabled(true);
-  ok(!accessthirdparty.disabled, "access third party button should be enabled");
-
-  acceptcookies.checked = false;
-  controlChanged(acceptcookies);
-  expect_disabled(true);
-  ok(accessthirdparty.disabled, "access third party button should be disabled");
-
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  expect_disabled(true);
-  ok(accessthirdparty.disabled, "access third party button should be disabled");
-
-  acceptcookies.checked = true;
-  controlChanged(acceptcookies);
-  expect_disabled(false);
-  ok(!accessthirdparty.disabled, "access third party button should be enabled");
-}
-
-function test_dependent_clearonclose_elements(win) {
-  let historymode = win.document.getElementById("historyMode");
-  ok(historymode, "history mode menulist should exist");
-  let pbautostart = win.document.getElementById("privateBrowsingAutoStart");
-  ok(pbautostart, "the private browsing auto-start checkbox should exist");
-  let alwaysclear = win.document.getElementById("alwaysClear");
-  ok(alwaysclear, "the clear data on close checkbox should exist");
-  let alwaysclearsettings = win.document.getElementById("clearDataSettings");
-  ok(alwaysclearsettings, "the clear data settings button should exist");
-
-  function expect_disabled(disabled) {
-    is(alwaysclearsettings.disabled, disabled,
-      "the clear data settings should " + (disabled ? "" : "not ") + "be disabled");
-  }
-
-  historymode.value = "custom";
-  controlChanged(historymode);
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  alwaysclear.checked = false;
-  controlChanged(alwaysclear);
-  expect_disabled(true);
-
-  alwaysclear.checked = true;
-  controlChanged(alwaysclear);
-  expect_disabled(false);
-
-  pbautostart.checked = true;
-  controlChanged(pbautostart);
-  expect_disabled(true);
-
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  expect_disabled(false);
-
-  alwaysclear.checked = false;
-  controlChanged(alwaysclear);
-  expect_disabled(true);
-}
-
-function test_dependent_prefs(win) {
-  let historymode = win.document.getElementById("historyMode");
-  ok(historymode, "history mode menulist should exist");
-  let controls = [
-    win.document.getElementById("rememberHistory"),
-    win.document.getElementById("rememberForms"),
-    win.document.getElementById("acceptCookies"),
-    win.document.getElementById("acceptThirdParty"),
-  ];
-  controls.forEach(function(control) {
-    ok(control, "the micro-management controls should exist");
-  });
-
-  function expect_checked(checked) {
-    controls.forEach(function(control) {
-      is(control.checked, checked,
-        control.getAttribute("id") + " should " + (checked ? "not " : "") + "be checked");
-    });
-  }
-
-  // controls should be checked in remember mode
-  historymode.value = "remember";
-  controlChanged(historymode);
-  expect_checked(true);
-
-  // even if they're unchecked in custom mode
-  historymode.value = "custom";
-  controlChanged(historymode);
-  controls.forEach(function(control) {
-    control.checked = false;
-    controlChanged(control);
-  });
-  expect_checked(false);
-  historymode.value = "remember";
-  controlChanged(historymode);
-  expect_checked(true);
-}
-
-function test_historymode_retention(mode, expect) {
-  return function(win) {
-    let historymode = win.document.getElementById("historyMode");
-    ok(historymode, "history mode menulist should exist");
-
-    if (expect !== undefined) {
-      is(historymode.value, expect,
-        "history mode is expected to remain " + expect);
-    }
-
-    historymode.value = mode;
-    controlChanged(historymode);
-  };
-}
-
-function test_custom_retention(controlToChange, expect, valueIncrement) {
-  return function(win) {
-    let historymode = win.document.getElementById("historyMode");
-    ok(historymode, "history mode menulist should exist");
-
-    if (expect !== undefined) {
-      is(historymode.value, expect,
-        "history mode is expected to remain " + expect);
-    }
-
-    historymode.value = "custom";
-    controlChanged(historymode);
-
-    controlToChange = win.document.getElementById(controlToChange);
-    ok(controlToChange, "the control to change should exist");
-    switch (controlToChange.localName) {
-    case "checkbox":
-      controlToChange.checked = !controlToChange.checked;
-      break;
-    case "textbox":
-      controlToChange.value = parseInt(controlToChange.value) + valueIncrement;
-      break;
-    case "menulist":
-      controlToChange.value = valueIncrement;
-      break;
-    }
-    controlChanged(controlToChange);
-  };
-}
-
-function test_locbar_suggestion_retention(mode, expect) {
-  return function(win) {
-    let locbarsuggest = win.document.getElementById("locationBarSuggestion");
-    ok(locbarsuggest, "location bar suggestion menulist should exist");
-
-    if (expect !== undefined) {
-      is(locbarsuggest.value, expect,
-        "location bar suggestion is expected to remain " + expect);
-    }
-
-    locbarsuggest.value = mode;
-    controlChanged(locbarsuggest);
-  };
-}
-
-function test_privatebrowsing_toggle(win) {
-  let historymode = win.document.getElementById("historyMode");
-  ok(historymode, "history mode menulist should exist");
-  let pbautostart = win.document.getElementById("privateBrowsingAutoStart");
-  ok(pbautostart, "the private browsing auto-start checkbox should exist");
-
-  let pbService = Cc["@mozilla.org/privatebrowsing;1"].
-                  getService(Ci.nsIPrivateBrowsingService);
-
-  // initial state
-  historymode.value = "remember";
-  controlChanged(historymode);
-
-  // switch to dontremember mode
-  historymode.value = "dontremember";
-  controlChanged(historymode);
-  ok(pbService.privateBrowsingEnabled, "private browsing should be activated");
-
-  // switch to remember mode
-  historymode.value = "remember";
-  controlChanged(historymode);
-  ok(!pbService.privateBrowsingEnabled, "private browsing should be deactivated");
-
-  // switch to custom mode
-  historymode.value = "custom";
-  controlChanged(historymode);
-  ok(!pbService.privateBrowsingEnabled, "private browsing should remain deactivated");
-
-  // check the autostart checkbox
-  pbautostart.checked = true;
-  controlChanged(pbautostart);
-  ok(pbService.privateBrowsingEnabled, "private browsing should be activated");
-
-  // uncheck the autostart checkbox
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  ok(!pbService.privateBrowsingEnabled, "private browsing should be deactivated");
-}
-
-function test_privatebrowsing_ui(win) {
-  let historymode = win.document.getElementById("historyMode");
-  ok(historymode, "history mode menulist should exist");
-  let pbautostart = win.document.getElementById("privateBrowsingAutoStart");
-  ok(pbautostart, "the private browsing auto-start checkbox should exist");
-
-  let pbmenuitem = document.getElementById("privateBrowsingItem");
-  ok(pbmenuitem, "the private browsing menu item should exist");
-  let pbcommand = document.getElementById("Tools:PrivateBrowsing");
-  ok(pbcommand, "the private browsing command should exist");
-
-  // initial state
-  historymode.value = "remember";
-  controlChanged(historymode);
-  ok(!pbmenuitem.hasAttribute("disabled"),
-    "private browsing menu item should not be initially disabled");
-  ok(!pbcommand.hasAttribute("disabled"),
-    "private browsing command should not be initially disabled");
-
-  // switch to dontremember mode
-  historymode.value = "dontremember";
-  controlChanged(historymode);
-  ok(pbmenuitem.hasAttribute("disabled"),
-    "private browsing menu item should be disabled");
-  ok(pbcommand.hasAttribute("disabled"),
-    "private browsing command should be disabled");
-
-  // switch to remember mode
-  historymode.value = "remember";
-  controlChanged(historymode);
-  ok(!pbmenuitem.hasAttribute("disabled"),
-    "private browsing menu item should be enabled");
-  ok(!pbcommand.hasAttribute("disabled"),
-    "private browsing command should be enabled");
-
-  // switch to custom mode
-  historymode.value = "custom";
-  controlChanged(historymode);
-  ok(!pbmenuitem.hasAttribute("disabled"),
-    "private browsing menu item should remain enabled");
-  ok(!pbcommand.hasAttribute("disabled"),
-    "private browsing command should remain enabled");
-
-  // check the autostart checkbox
-  pbautostart.checked = true;
-  controlChanged(pbautostart);
-  ok(pbmenuitem.hasAttribute("disabled"),
-    "private browsing menu item should be disabled");
-  ok(pbcommand.hasAttribute("disabled"),
-    "private browsing command should be disabled");
-
-  // uncheck the autostart checkbox
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  ok(!pbmenuitem.hasAttribute("disabled"),
-    "private browsing menu item should be enabled");
-  ok(!pbcommand.hasAttribute("disabled"),
-    "private browsing command should be enabled");
-}
-
-function enter_private_browsing(win) {
-  let pbService = Cc["@mozilla.org/privatebrowsing;1"].
-                  getService(Ci.nsIPrivateBrowsingService);
-  win.document.getElementById("browser.privatebrowsing.keep_current_session")
-              .value = true;
-  pbService.privateBrowsingEnabled = true;
-}
-
-function reset_preferences(win) {
-  let prefs = win.document.querySelectorAll("#privacyPreferences > preference");
-  for (let i = 0; i < prefs.length; ++i)
-    if (prefs[i].hasUserValue)
-      prefs[i].reset();
-}
-
-let testRunner;
-function run_test_subset(subset) {
-  Services.prefs.setBoolPref("browser.preferences.instantApply", true);
-
-  waitForExplicitFinish();
-  registerCleanupFunction(function() {
-    // Reset pref to its default
-    Services.prefs.clearUserPref("browser.preferences.instantApply");
-  });
-
-  testRunner = {
-    tests: subset,
-    counter: 0,
-    runNext: function() {
-      if (this.counter == this.tests.length) {
-        finish();
-      } else {
-        let self = this;
-        setTimeout(function() {
-          runTestOnPrivacyPrefPane(self.tests[self.counter++]);
-        }, 0);
-      }
-    }
-  };
-
-  testRunner.runNext();
-}
--- a/browser/components/preferences/jar.mn
+++ b/browser/components/preferences/jar.mn
@@ -27,18 +27,18 @@ browser.jar:
     content/browser/preferences/handlers.css
 *   content/browser/preferences/languages.xul
     content/browser/preferences/languages.js
 *   content/browser/preferences/main.xul
     content/browser/preferences/main.js
 *   content/browser/preferences/permissions.xul
     content/browser/preferences/permissions.js
 *   content/browser/preferences/preferences.xul
-*   content/browser/preferences/privacy.xul
-*   content/browser/preferences/privacy.js
+    content/browser/preferences/privacy.xul
+    content/browser/preferences/privacy.js
     content/browser/preferences/sanitize.xul
     content/browser/preferences/security.xul
     content/browser/preferences/security.js
     content/browser/preferences/selectBookmark.xul
     content/browser/preferences/selectBookmark.js
 #ifdef MOZ_SERVICES_SYNC
     content/browser/preferences/sync.xul
     content/browser/preferences/sync.js
--- a/browser/components/preferences/privacy.js
+++ b/browser/components/preferences/privacy.js
@@ -274,17 +274,16 @@ var gPrivacyPane = {
   },
 
   autoStartPrivateBrowsingObserver:
   {
     QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIObserver]),
 
     observe: function PPP_observe(aSubject, aTopic, aData)
     {
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
       if (!gPrivacyPane._shouldPromptForRestart) {
         // We're performing a revert. Just let it happen.
         gPrivacyPane._shouldPromptForRestart = true;
         return;
       }
 
       const Cc = Components.classes, Ci = Components.interfaces;
       let pref = document.getElementById("browser.privatebrowsing.autostart");
@@ -316,33 +315,16 @@ var gPrivacyPane = {
       let mode = document.getElementById("historyMode");
       if (mode.value != "custom") {
         mode.selectedIndex = pref.value ? 1 : 0;
         mode.doCommand();
       } else {
         let rememberHistoryCheckbox = document.getElementById("rememberHistory");
         rememberHistory.checked = pref.value;
       }
-#else
-      // Toggle the private browsing mode without switching the session
-      let prefValue = document.getElementById("browser.privatebrowsing.autostart").value;
-      let keepCurrentSession = document.getElementById("browser.privatebrowsing.keep_current_session");
-      keepCurrentSession.value = true;
-
-      let privateBrowsingService = Components.classes["@mozilla.org/privatebrowsing;1"].
-        getService(Components.interfaces.nsIPrivateBrowsingService);
-
-      // If activating from within the private browsing mode, reset the
-      // private session
-      if (prefValue && privateBrowsingService.privateBrowsingEnabled)
-        privateBrowsingService.privateBrowsingEnabled = false;
-      privateBrowsingService.privateBrowsingEnabled = prefValue;
-
-      keepCurrentSession.reset();
-#endif
     }
   },
 
   // HISTORY
 
   /**
    * Read the location bar enabled and suggestion prefs
    * @return Int value for suggestion menulist
--- a/browser/components/preferences/privacy.xul
+++ b/browser/components/preferences/privacy.xul
@@ -68,26 +68,18 @@
       <preference id="privacy.sanitize.timeSpan"
                   name="privacy.sanitize.timeSpan"
                   type="int"/>
 
       <!-- Private Browsing -->
       <preference id="browser.privatebrowsing.autostart"
                   name="browser.privatebrowsing.autostart"
                   onchange="gPrivacyPane.updatePrivacyMicroControls();"
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
-                  instantApply="true"
-#endif
-                  type="bool"/>
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-      <preference id="browser.privatebrowsing.keep_current_session"
-                  name="browser.privatebrowsing.keep_current_session"
                   instantApply="true"
                   type="bool"/>
-#endif
 
     </preferences>
     
     <stringbundle id="bundlePreferences" src="chrome://browser/locale/preferences/preferences.properties"/>
     
     <script type="application/javascript" src="chrome://browser/content/preferences/privacy.js"/>
 
     <!-- Tracking -->
--- a/browser/components/preferences/tests/Makefile.in
+++ b/browser/components/preferences/tests/Makefile.in
@@ -13,40 +13,22 @@ include $(topsrcdir)/config/rules.mk
 
 _BROWSER_FILES = \
     head.js \
     browser_advanced_update.js \
     browser_bug410900.js \
     browser_bug705422.js \
     browser_permissions.js \
     browser_chunk_permissions.js \
-    $(NULL)
-
-ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-_BROWSER_FILES += \
-    privacypane_tests.js \
-    browser_bug567487.js \
-    browser_privacypane_1.js \
-    browser_privacypane_2.js \
-    browser_privacypane_3.js \
-    browser_privacypane_4.js \
-    browser_privacypane_5.js \
-    browser_privacypane_6.js \
-    browser_privacypane_7.js \
-    browser_privacypane_8.js \
-    $(NULL)
-else
-_BROWSER_FILES += \
-    privacypane_tests_perwindow.js \
     browser_privacypane_1.js \
     browser_privacypane_3.js \
     browser_privacypane_4.js \
     browser_privacypane_5.js \
     browser_privacypane_8.js \
+    privacypane_tests_perwindow.js \
     $(NULL)
-endif
 
 ifdef MOZ_SERVICES_HEALTHREPORT
 _BROWSER_FILES += browser_healthreport.js
 endif
 
 libs::	$(_BROWSER_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
deleted file mode 100644
--- a/browser/components/preferences/tests/browser_bug567487.js
+++ /dev/null
@@ -1,70 +0,0 @@
-function test() {
-  waitForExplicitFinish();
-  resetPreferences();
-
-  function observer(win, topic, data) {
-    if (topic != "main-pane-loaded")
-      return;
-
-    Services.obs.removeObserver(observer, "main-pane-loaded");
-    runTest(win);
-  }
-  Services.obs.addObserver(observer, "main-pane-loaded", false);
-
-  openDialog("chrome://browser/content/preferences/preferences.xul", "Preferences",
-             "chrome,titlebar,toolbar,centerscreen,dialog=no", "paneMain");
-}
-
-function runTest(win) {
-  let doc = win.document;
-  let pbAutoStartPref = doc.getElementById("browser.privatebrowsing.autostart");
-  let startupPref = doc.getElementById("browser.startup.page");
-  let menu = doc.getElementById("browserStartupPage");
-  let option = doc.getElementById("browserStartupLastSession");
-  let defOption = doc.getElementById("browserStartupHomePage");
-  let otherOption = doc.getElementById("browserStartupBlank");
-
-  ok(!pbAutoStartPref.value, "Sanity check");
-  is(startupPref.value, startupPref.defaultValue, "Sanity check");
-
-  // First, check to make sure that setting pbAutoStartPref disables the menu item
-  pbAutoStartPref.value = true;
-  is(option.getAttribute("disabled"), "true", "Setting private browsing to autostart " +
-     "should disable the 'Show my tabs and windows from last time' option");
-  pbAutoStartPref.value = false;
-
-  // Now ensure the correct behavior when pbAutoStartPref is set with option enabled
-  startupPref.value = option.getAttribute("value");
-  is(menu.selectedItem, option, "Sanity check");
-  pbAutoStartPref.value = true;
-  is(option.getAttribute("disabled"), "true", "Setting private browsing to autostart " +
-     "should disable the 'Show my tabs and windows from last time' option");
-  is(menu.selectedItem, defOption, "The 'Show home page' option should be selected");
-  is(startupPref.value, option.getAttribute("value"), "But the value of the startup " +
-     "pref itself shouldn't change");
-  menu.selectedItem = otherOption;
-  menu.doCommand();
-  is(startupPref.value, otherOption.getAttribute("value"), "And we should be able to " +
-     "chnage it!");
-  pbAutoStartPref.value = false;
-
-  // Now, ensure that with 'Show my windows and tabs from last time' enabled, toggling
-  // pbAutoStartPref would restore that value in the menulist.
-  startupPref.value = option.getAttribute("value");
-  is(menu.selectedItem, option, "Sanity check");
-  pbAutoStartPref.value = true;
-  is(menu.selectedItem, defOption, "The 'Show home page' option should be selected");
-  pbAutoStartPref.value = false;
-  is(menu.selectedItem, option, "The correct value should be restored");
-
-  // cleanup
-  resetPreferences();
-
-  win.close();
-  finish();
-}
-
-function resetPreferences() {
-  Services.prefs.clearUserPref("browser.startup.page");
-  Services.prefs.clearUserPref("browser.privatebrowsing.autostart");
-}
--- a/browser/components/preferences/tests/browser_privacypane_1.js
+++ b/browser/components/preferences/tests/browser_privacypane_1.js
@@ -7,21 +7,17 @@ function test() {
                getService(Ci.mozIJSSubScriptLoader);
 
   let rootDir = getRootDirectory(gTestPath);
   let jar = getJar(rootDir);
   if (jar) {
     let tmpdir = extractJarToTmp(jar);
     rootDir = "file://" + tmpdir.path + '/';
   }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
+  loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
 
   run_test_subset([
     test_pane_visibility,
     test_dependent_elements,
     test_dependent_cookie_elements,
     test_dependent_clearonclose_elements,
     test_dependent_prefs,
 
deleted file mode 100644
--- a/browser/components/preferences/tests/browser_privacypane_2.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function test() {
-  let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
-               getService(Ci.mozIJSSubScriptLoader);
-
-  let rootDir = getRootDirectory(gTestPath);
-  let jar = getJar(rootDir);
-  if (jar) {
-    let tmpdir = extractJarToTmp(jar);
-    rootDir = "file://" + tmpdir.path + '/';
-  }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
-
-  run_test_subset([
-    test_historymode_retention("remember", undefined),
-    test_historymode_retention("dontremember", "remember"),
-    test_historymode_retention("custom", "dontremember"),
-    // custom without any micro-prefs changed won't retain
-    test_historymode_retention("remember", "dontremember"),
-    test_historymode_retention("custom", "remember"),
-    // custom without any micro-prefs changed won't retain
-    test_historymode_retention("remember", "remember"),
-
-    // reset all preferences to their default values once we're done
-    reset_preferences
-  ]);
-}
--- a/browser/components/preferences/tests/browser_privacypane_3.js
+++ b/browser/components/preferences/tests/browser_privacypane_3.js
@@ -6,21 +6,17 @@ function test() {
   let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
                getService(Ci.mozIJSSubScriptLoader);
   let rootDir = getRootDirectory(gTestPath);
   let jar = getJar(rootDir);
   if (jar) {
     let tmpdir = extractJarToTmp(jar);
     rootDir = "file://" + tmpdir.path + '/';
   }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
+  loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
 
   run_test_subset([
     test_custom_retention("rememberHistory", "remember"),
     test_custom_retention("rememberHistory", "custom"),
     test_custom_retention("rememberForms", "remember"),
     test_custom_retention("rememberForms", "custom"),
     test_historymode_retention("remember", "remember"),
 
--- a/browser/components/preferences/tests/browser_privacypane_4.js
+++ b/browser/components/preferences/tests/browser_privacypane_4.js
@@ -6,21 +6,17 @@ function test() {
   let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
                getService(Ci.mozIJSSubScriptLoader);
   let rootDir = getRootDirectory(gTestPath);
   let jar = getJar(rootDir);
   if (jar) {
     let tmpdir = extractJarToTmp(jar);
     rootDir = "file://" + tmpdir.path + '/';
   }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
+  loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
 
   run_test_subset([
     test_custom_retention("acceptCookies", "remember"),
     test_custom_retention("acceptCookies", "custom"),
     test_custom_retention("acceptThirdParty", "remember"),
     test_custom_retention("acceptThirdParty", "custom"),
     test_custom_retention("keepCookiesUntil", "remember", 1),
     test_custom_retention("keepCookiesUntil", "custom", 2),
--- a/browser/components/preferences/tests/browser_privacypane_5.js
+++ b/browser/components/preferences/tests/browser_privacypane_5.js
@@ -6,21 +6,17 @@ function test() {
   let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
                getService(Ci.mozIJSSubScriptLoader);
   let rootDir = getRootDirectory(gTestPath);
   let jar = getJar(rootDir);
   if (jar) {
     let tmpdir = extractJarToTmp(jar);
     rootDir = "file://" + tmpdir.path + '/';
   }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
+  loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
 
   run_test_subset([
     test_locbar_suggestion_retention(-1, undefined),
     test_locbar_suggestion_retention(1, -1),
     test_locbar_suggestion_retention(2, 1),
     test_locbar_suggestion_retention(0, 2),
     test_locbar_suggestion_retention(0, 0),
 
deleted file mode 100644
--- a/browser/components/preferences/tests/browser_privacypane_6.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function test() {
-  let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
-               getService(Ci.mozIJSSubScriptLoader);
-  let rootDir = getRootDirectory(gTestPath);
-  let jar = getJar(rootDir);
-  if (jar) {
-    let tmpdir = extractJarToTmp(jar);
-    rootDir = "file://" + tmpdir.path + '/';
-  }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
-
-  run_test_subset([
-    test_privatebrowsing_toggle,
-    enter_private_browsing, // once again, test with PB initially enabled
-    test_privatebrowsing_toggle,
-
-    // don't reset preferences, will pick up where we left off in browser_privacypane_7.js
-  ]);
-}
deleted file mode 100644
--- a/browser/components/preferences/tests/browser_privacypane_7.js
+++ /dev/null
@@ -1,28 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function test() {
-  let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
-               getService(Ci.mozIJSSubScriptLoader);
-  let rootDir = getRootDirectory(gTestPath);
-  let jar = getJar(rootDir);
-  if (jar) {
-    let tmpdir = extractJarToTmp(jar);
-    rootDir = "file://" + tmpdir.path + '/';
-  }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
-
-  run_test_subset([
-    test_privatebrowsing_ui,
-    enter_private_browsing, // once again, test with PB initially enabled
-    test_privatebrowsing_ui,
-
-    // reset all preferences to their default values once we're done
-    reset_preferences
-  ]);
-}
--- a/browser/components/preferences/tests/browser_privacypane_8.js
+++ b/browser/components/preferences/tests/browser_privacypane_8.js
@@ -6,21 +6,17 @@ function test() {
   let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
                getService(Ci.mozIJSSubScriptLoader);
   let rootDir = getRootDirectory(gTestPath);
   let jar = getJar(rootDir);
   if (jar) {
     let tmpdir = extractJarToTmp(jar);
     rootDir = "file://" + tmpdir.path + '/';
   }
-  try {
-    loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
-  } catch(x) {
-    loader.loadSubScript(rootDir + "privacypane_tests.js", this);
-  }
+  loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
 
   run_test_subset([
     // history mode should be initialized to remember
     test_historymode_retention("remember", undefined),
 
     // history mode should remain remember; toggle acceptCookies checkbox
     test_custom_retention("acceptCookies", "remember"),
 
deleted file mode 100644
--- a/browser/components/preferences/tests/privacypane_tests.js
+++ /dev/null
@@ -1,499 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function runTestOnPrivacyPrefPane(testFunc) {
-  let observer = {
-    observe: function(aSubject, aTopic, aData) {
-      if (aTopic == "domwindowopened") {
-        Services.ww.unregisterNotification(this);
-
-        let win = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
-        win.addEventListener("load", function() {
-          win.removeEventListener("load", arguments.callee, false);
-          testFunc(dialog.document.defaultView);
-
-          Services.ww.registerNotification(observer);
-          dialog.close();
-        }, false);
-      } else if (aTopic == "domwindowclosed") {
-        Services.ww.unregisterNotification(this);
-        testRunner.runNext();
-      }
-    }
-  };
-  Services.ww.registerNotification(observer);
-
-  let dialog = openDialog("chrome://browser/content/preferences/preferences.xul", "Preferences",
-                          "chrome,titlebar,toolbar,centerscreen,dialog=no", "panePrivacy");
-}
-
-function controlChanged(element) {
-  element.doCommand();
-}
-
-function test_pane_visibility(win) {
-  let modes = {
-    "remember": "historyRememberPane",
-    "dontremember": "historyDontRememberPane",
-    "custom": "historyCustomPane"
-  };
-
-  let historymode = win.document.getElementById("historyMode");
-  ok(historymode, "history mode menulist should exist");
-  let historypane = win.document.getElementById("historyPane");
-  ok(historypane, "history mode pane should exist");
-
-  for (let mode in modes) {
-    historymode.value = mode;
-    controlChanged(historymode);
-    is(historypane.selectedPanel, win.document.getElementById(modes[mode]),
-      "The correct pane should be selected for the " + mode + " mode");
-  }
-}
-
-function test_dependent_elements(win) {
-  let historymode = win.document.getElementById("historyMode");
-  ok(historymode, "history mode menulist should exist");
-  let pbautostart = win.document.getElementById("privateBrowsingAutoStart");
-  ok(pbautostart, "the private browsing auto-start checkbox should exist");
-  let controls = [
-    win.document.getElementById("rememberHistory"),
-    win.document.getElementById("rememberForms"),
-    win.document.getElementById("keepUntil"),
-    win.document.getElementById("keepCookiesUntil"),
-    win.document.getElementById("alwaysClear"),
-  ];
-  controls.forEach(function(control) {
-    ok(control, "the dependent controls should exist");
-  });
-  let independents = [
-    win.document.getElementById("acceptCookies"),
-    win.document.getElementById("acceptThirdParty"),
-  ];
-  independents.forEach(function(control) {
-    ok(control, "the independent controls should exist");
-  });
-  let cookieexceptions = win.document.getElementById("cookieExceptions");
-  ok(cookieexceptions, "the cookie exceptions button should exist");
-  let keepuntil = win.document.getElementById("keepCookiesUntil");
-  ok(keepuntil, "the keep cookies until menulist should exist");
-  let alwaysclear = win.document.getElementById("alwaysClear");
-  ok(alwaysclear, "the clear data on close checkbox should exist");
-  let rememberhistory = win.document.getElementById("rememberHistory");
-  ok(rememberhistory, "the remember history checkbox should exist");
-  let rememberforms = win.document.getElementById("rememberForms");
-  ok(rememberforms, "the remember forms checkbox should exist");
-  let alwaysclearsettings = win.document.getElementById("clearDataSettings");
-  ok(alwaysclearsettings, "the clear data settings button should exist");
-
-  function expect_disabled(disabled) {
-    controls.forEach(function(control) {
-      is(control.disabled, disabled,
-        control.getAttribute("id") + " should " + (disabled ? "" : "not ") + "be disabled");
-    });
-    is(keepuntil.value, disabled ? 2 : 0,
-      "the keep cookies until menulist value should be as expected");
-    if (disabled) {
-     ok(!alwaysclear.checked,
-        "the clear data on close checkbox value should be as expected");
-     ok(!rememberhistory.checked,
-        "the remember history checkbox value should be as expected");
-     ok(!rememberforms.checked,
-        "the remember forms checkbox value should be as expected");
-    }
-  }
-  function check_independents(expected) {
-    independents.forEach(function(control) {
-      is(control.disabled, expected,
-        control.getAttribute("id") + " should " + (expected ? "" : "not ") + "be disabled");
-    });
-    ok(!cookieexceptions.disabled,
-      "the cookie exceptions button should never be disabled");
-    ok(alwaysclearsettings.disabled,
-      "the clear data settings button should always be disabled");
-  }
-
-  // controls should only change in custom mode
-  historymode.value = "remember";
-  controlChanged(historymode);
-  expect_disabled(false);
-  check_independents(false);
-
-  // setting the mode to custom shouldn't change anything
-  historymode.value = "custom";
-  controlChanged(historymode);
-  expect_disabled(false);
-  check_independents(false);
-
-  // controls should only change in custom mode
-  historymode.value = "dontremember";
-  controlChanged(historymode);
-  expect_disabled(false);
-  check_independents(false);
-
-  // controls should only change in custom mode
-  historymode.value = "custom";
-  controlChanged(historymode);
-  expect_disabled(true);
-  check_independents(false);
-
-  // dependent controls should follow pbautostart
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  expect_disabled(false);
-  check_independents(false);
-
-  // dependent controls should follow pbautostart
-  pbautostart.checked = true;
-  controlChanged(pbautostart);
-  expect_disabled(true);
-  check_independents(false);
-}
-
-function test_dependent_cookie_elements(win) {
-  let historymode = win.document.getElementById("historyMode");
-  ok(historymode, "history mode menulist should exist");
-  let pbautostart = win.document.getElementById("privateBrowsingAutoStart");
-  ok(pbautostart, "the private browsing auto-start checkbox should exist");
-  let controls = [
-    win.document.getElementById("acceptThirdParty"),
-    win.document.getElementById("keepUntil"),
-    win.document.getElementById("keepCookiesUntil"),
-  ];
-  controls.forEach(function(control) {
-    ok(control, "the dependent cookie controls should exist");
-  });
-  let acceptcookies = win.document.getElementById("acceptCookies");
-  ok(acceptcookies, "the accept cookies checkbox should exist");
-
-  function expect_disabled(disabled) {
-    controls.forEach(function(control) {
-      is(control.disabled, disabled,
-        control.getAttribute("id") + " should " + (disabled ? "" : "not ") + "be disabled");
-    });
-  }
-
-  historymode.value = "custom";
-  controlChanged(historymode);
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  expect_disabled(false);
-
-  acceptcookies.checked = false;
-  controlChanged(acceptcookies);
-  expect_disabled(true);
-
-  // pbautostart shouldn't change anything now
-  pbautostart.checked = true;
-  controlChanged(pbautostart);
-  expect_disabled(true);
-
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  expect_disabled(true);
-
-  acceptcookies.checked = true;
-  controlChanged(acceptcookies);
-  expect_disabled(false);
-
-  let accessthirdparty = controls.shift();
-  pbautostart.checked = true;
-  controlChanged(pbautostart);
-  expect_disabled(true);
-  ok(!accessthirdparty.disabled, "access third party button should be enabled");
-
-  acceptcookies.checked = false;
-  controlChanged(acceptcookies);
-  expect_disabled(true);
-  ok(accessthirdparty.disabled, "access third party button should be disabled");
-
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  expect_disabled(true);
-  ok(accessthirdparty.disabled, "access third party button should be disabled");
-
-  acceptcookies.checked = true;
-  controlChanged(acceptcookies);
-  expect_disabled(false);
-  ok(!accessthirdparty.disabled, "access third party button should be enabled");
-}
-
-function test_dependent_clearonclose_elements(win) {
-  let historymode = win.document.getElementById("historyMode");
-  ok(historymode, "history mode menulist should exist");
-  let pbautostart = win.document.getElementById("privateBrowsingAutoStart");
-  ok(pbautostart, "the private browsing auto-start checkbox should exist");
-  let alwaysclear = win.document.getElementById("alwaysClear");
-  ok(alwaysclear, "the clear data on close checkbox should exist");
-  let alwaysclearsettings = win.document.getElementById("clearDataSettings");
-  ok(alwaysclearsettings, "the clear data settings button should exist");
-
-  function expect_disabled(disabled) {
-    is(alwaysclearsettings.disabled, disabled,
-      "the clear data settings should " + (disabled ? "" : "not ") + "be disabled");
-  }
-
-  historymode.value = "custom";
-  controlChanged(historymode);
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  alwaysclear.checked = false;
-  controlChanged(alwaysclear);
-  expect_disabled(true);
-
-  alwaysclear.checked = true;
-  controlChanged(alwaysclear);
-  expect_disabled(false);
-
-  pbautostart.checked = true;
-  controlChanged(pbautostart);
-  expect_disabled(true);
-
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  expect_disabled(false);
-
-  alwaysclear.checked = false;
-  controlChanged(alwaysclear);
-  expect_disabled(true);
-}
-
-function test_dependent_prefs(win) {
-  let historymode = win.document.getElementById("historyMode");
-  ok(historymode, "history mode menulist should exist");
-  let controls = [
-    win.document.getElementById("rememberHistory"),
-    win.document.getElementById("rememberForms"),
-    win.document.getElementById("acceptCookies"),
-    win.document.getElementById("acceptThirdParty"),
-  ];
-  controls.forEach(function(control) {
-    ok(control, "the micro-management controls should exist");
-  });
-
-  function expect_checked(checked) {
-    controls.forEach(function(control) {
-      is(control.checked, checked,
-        control.getAttribute("id") + " should " + (checked ? "not " : "") + "be checked");
-    });
-  }
-
-  // controls should be checked in remember mode
-  historymode.value = "remember";
-  controlChanged(historymode);
-  expect_checked(true);
-
-  // even if they're unchecked in custom mode
-  historymode.value = "custom";
-  controlChanged(historymode);
-  controls.forEach(function(control) {
-    control.checked = false;
-    controlChanged(control);
-  });
-  expect_checked(false);
-  historymode.value = "remember";
-  controlChanged(historymode);
-  expect_checked(true);
-}
-
-function test_historymode_retention(mode, expect) {
-  return function(win) {
-    let historymode = win.document.getElementById("historyMode");
-    ok(historymode, "history mode menulist should exist");
-
-    if (expect !== undefined) {
-      is(historymode.value, expect,
-        "history mode is expected to remain " + expect);
-    }
-
-    historymode.value = mode;
-    controlChanged(historymode);
-  };
-}
-
-function test_custom_retention(controlToChange, expect, valueIncrement) {
-  return function(win) {
-    let historymode = win.document.getElementById("historyMode");
-    ok(historymode, "history mode menulist should exist");
-
-    if (expect !== undefined) {
-      is(historymode.value, expect,
-        "history mode is expected to remain " + expect);
-    }
-
-    historymode.value = "custom";
-    controlChanged(historymode);
-
-    controlToChange = win.document.getElementById(controlToChange);
-    ok(controlToChange, "the control to change should exist");
-    switch (controlToChange.localName) {
-    case "checkbox":
-      controlToChange.checked = !controlToChange.checked;
-      break;
-    case "textbox":
-      controlToChange.value = parseInt(controlToChange.value) + valueIncrement;
-      break;
-    case "menulist":
-      controlToChange.value = valueIncrement;
-      break;
-    }
-    controlChanged(controlToChange);
-  };
-}
-
-function test_locbar_suggestion_retention(mode, expect) {
-  return function(win) {
-    let locbarsuggest = win.document.getElementById("locationBarSuggestion");
-    ok(locbarsuggest, "location bar suggestion menulist should exist");
-
-    if (expect !== undefined) {
-      is(locbarsuggest.value, expect,
-        "location bar suggestion is expected to remain " + expect);
-    }
-
-    locbarsuggest.value = mode;
-    controlChanged(locbarsuggest);
-  };
-}
-
-function test_privatebrowsing_toggle(win) {
-  let historymode = win.document.getElementById("historyMode");
-  ok(historymode, "history mode menulist should exist");
-  let pbautostart = win.document.getElementById("privateBrowsingAutoStart");
-  ok(pbautostart, "the private browsing auto-start checkbox should exist");
-
-  let pbService = Cc["@mozilla.org/privatebrowsing;1"].
-                  getService(Ci.nsIPrivateBrowsingService);
-
-  // initial state
-  historymode.value = "remember";
-  controlChanged(historymode);
-
-  // switch to dontremember mode
-  historymode.value = "dontremember";
-  controlChanged(historymode);
-  ok(pbService.privateBrowsingEnabled, "private browsing should be activated");
-
-  // switch to remember mode
-  historymode.value = "remember";
-  controlChanged(historymode);
-  ok(!pbService.privateBrowsingEnabled, "private browsing should be deactivated");
-
-  // switch to custom mode
-  historymode.value = "custom";
-  controlChanged(historymode);
-  ok(!pbService.privateBrowsingEnabled, "private browsing should remain deactivated");
-
-  // check the autostart checkbox
-  pbautostart.checked = true;
-  controlChanged(pbautostart);
-  ok(pbService.privateBrowsingEnabled, "private browsing should be activated");
-
-  // uncheck the autostart checkbox
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  ok(!pbService.privateBrowsingEnabled, "private browsing should be deactivated");
-}
-
-function test_privatebrowsing_ui(win) {
-  let historymode = win.document.getElementById("historyMode");
-  ok(historymode, "history mode menulist should exist");
-  let pbautostart = win.document.getElementById("privateBrowsingAutoStart");
-  ok(pbautostart, "the private browsing auto-start checkbox should exist");
-
-  let pbmenuitem = document.getElementById("privateBrowsingItem");
-  ok(pbmenuitem, "the private browsing menu item should exist");
-  let pbcommand = document.getElementById("Tools:PrivateBrowsing");
-  ok(pbcommand, "the private browsing command should exist");
-
-  // initial state
-  historymode.value = "remember";
-  controlChanged(historymode);
-  ok(!pbmenuitem.hasAttribute("disabled"),
-    "private browsing menu item should not be initially disabled");
-  ok(!pbcommand.hasAttribute("disabled"),
-    "private browsing command should not be initially disabled");
-
-  // switch to dontremember mode
-  historymode.value = "dontremember";
-  controlChanged(historymode);
-  ok(pbmenuitem.hasAttribute("disabled"),
-    "private browsing menu item should be disabled");
-  ok(pbcommand.hasAttribute("disabled"),
-    "private browsing command should be disabled");
-
-  // switch to remember mode
-  historymode.value = "remember";
-  controlChanged(historymode);
-  ok(!pbmenuitem.hasAttribute("disabled"),
-    "private browsing menu item should be enabled");
-  ok(!pbcommand.hasAttribute("disabled"),
-    "private browsing command should be enabled");
-
-  // switch to custom mode
-  historymode.value = "custom";
-  controlChanged(historymode);
-  ok(!pbmenuitem.hasAttribute("disabled"),
-    "private browsing menu item should remain enabled");
-  ok(!pbcommand.hasAttribute("disabled"),
-    "private browsing command should remain enabled");
-
-  // check the autostart checkbox
-  pbautostart.checked = true;
-  controlChanged(pbautostart);
-  ok(pbmenuitem.hasAttribute("disabled"),
-    "private browsing menu item should be disabled");
-  ok(pbcommand.hasAttribute("disabled"),
-    "private browsing command should be disabled");
-
-  // uncheck the autostart checkbox
-  pbautostart.checked = false;
-  controlChanged(pbautostart);
-  ok(!pbmenuitem.hasAttribute("disabled"),
-    "private browsing menu item should be enabled");
-  ok(!pbcommand.hasAttribute("disabled"),
-    "private browsing command should be enabled");
-}
-
-function enter_private_browsing(win) {
-  let pbService = Cc["@mozilla.org/privatebrowsing;1"].
-                  getService(Ci.nsIPrivateBrowsingService);
-  win.document.getElementById("browser.privatebrowsing.keep_current_session")
-              .value = true;
-  pbService.privateBrowsingEnabled = true;
-}
-
-function reset_preferences(win) {
-  let prefs = win.document.getElementsByTagName("preference");
-  for (let i = 0; i < prefs.length; ++i)
-    if (prefs[i].hasUserValue)
-      prefs[i].reset();
-}
-
-let testRunner;
-function run_test_subset(subset) {
-  let instantApplyOrig = Services.prefs.getBoolPref("browser.preferences.instantApply");
-  Services.prefs.setBoolPref("browser.preferences.instantApply", true);
-
-  waitForExplicitFinish();
-
-  testRunner = {
-    tests: subset,
-    counter: 0,
-    runNext: function() {
-      if (this.counter == this.tests.length) {
-        // cleanup
-        Services.prefs.setBoolPref("browser.preferences.instantApply", instantApplyOrig);
-        finish();
-      } else {
-        let self = this;
-        setTimeout(function() {
-          runTestOnPrivacyPrefPane(self.tests[self.counter++]);
-        }, 0);
-      }
-    }
-  };
-
-  testRunner.runNext();
-}
--- a/browser/components/privatebrowsing/content/aboutPrivateBrowsing.xhtml
+++ b/browser/components/privatebrowsing/content/aboutPrivateBrowsing.xhtml
@@ -8,51 +8,37 @@
   <!ENTITY % htmlDTD PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
   %htmlDTD;
   <!ENTITY % netErrorDTD SYSTEM "chrome://global/locale/netError.dtd">
   %netErrorDTD;
   <!ENTITY % globalDTD SYSTEM "chrome://global/locale/global.dtd">
   %globalDTD;
   <!ENTITY % browserDTD SYSTEM "chrome://browser/locale/browser.dtd">
   %browserDTD;
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
 #ifdef XP_MACOSX
   <!ENTITY basePBMenu.label   "&fileMenu.label;">
 #else
   <!ENTITY basePBMenu.label   "<span class='appMenuButton'>&brandShortName;</span><span class='fileMenu'>&fileMenu.label;</span>">
 #endif
-#else
-#ifdef XP_MACOSX
-  <!ENTITY basePBMenu.label   "&toolsMenu.label;">
-#else
-  <!ENTITY basePBMenu.label   "<span class='appMenuButton'>&brandShortName;</span><span class='toolsMenu'>&toolsMenu.label;</span>">
-#endif
-#endif
   <!ENTITY % privatebrowsingpageDTD SYSTEM "chrome://browser/locale/aboutPrivateBrowsing.dtd">
   %privatebrowsingpageDTD;
 ]>
 
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <link rel="stylesheet" href="chrome://global/skin/netError.css" type="text/css" media="all"/>
     <link rel="stylesheet" href="chrome://browser/skin/aboutPrivateBrowsing.css" type="text/css" media="all"/>
     <style type="text/css"><![CDATA[
       body.normal .showPrivate,
       body.private .showNormal {
         display: none;
       }
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
       body.appMenuButtonVisible .fileMenu {
         display: none;
       }
-#else
-      body.appMenuButtonVisible .toolsMenu {
-        display: none;
-      }
-#endif
       body.appMenuButtonInvisible .appMenuButton {
         display: none;
       }
     ]]></style>
     <script type="application/javascript;version=1.7"><![CDATA[
       const Cc = Components.classes;
       const Ci = Components.interfaces;
 
@@ -103,25 +89,19 @@
         // Show the correct menu structure based on whether the App Menu button is
         // shown or not.
         var menuBar = mainWindow.document.getElementById("toolbar-menubar");
         var appMenuButtonIsVisible = menuBar.getAttribute("autohide") == "true";
         document.body.classList.add(appMenuButtonIsVisible ? "appMenuButtonVisible" :
                                                              "appMenuButtonInvisible");
       }, false);
 
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
       function openPrivateWindow() {
         mainWindow.OpenBrowserWindow({private: true});
       }
-#else
-      function togglePrivateBrowsing() {
-        mainWindow.gPrivateBrowsingUI.toggleMode();
-      }
-#endif
     ]]></script>
   </head>
 
   <body dir="&locale.dir;"
         class="private">
 
     <!-- PAGE CONTAINER (for styling purposes only) -->
     <div id="errorPageContainer">
@@ -132,58 +112,37 @@
         <h1 id="errorTitleTextNormal" class="showNormal">&privatebrowsingpage.title.normal;</h1>
       </div>
 
       <!-- LONG CONTENT (the section most likely to require scrolling) -->
       <div id="errorLongContent">
 
         <!-- Short Description -->
         <div id="errorShortDesc">
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
           <p id="errorShortDescText" class="showPrivate">&privatebrowsingpage.perwindow.issueDesc;</p>
           <p id="errorShortDescTextNormal" class="showNormal">&privatebrowsingpage.perwindow.issueDesc.normal;</p>
-#else
-          <p id="errorShortDescText" class="showPrivate">&privatebrowsingpage.issueDesc;</p>
-          <p id="errorShortDescTextNormal" class="showNormal">&privatebrowsingpage.issueDesc.normal;</p>
-#endif
         </div>
 
         <!-- Long Description -->
         <div id="errorLongDesc">
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
           <p id="errorLongDescText">&privatebrowsingpage.perwindow.description;</p>
-#else
-          <p id="errorLongDescText">&privatebrowsingpage.description;</p>
-#endif
         </div>
 
         <!-- Start Private Browsing -->
         <div id="startPrivateBrowsingDesc" class="showNormal">
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
           <button xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
                   id="startPrivateBrowsing" label="&privatebrowsingpage.openPrivateWindow.label;"
                   accesskey="&privatebrowsingpage.openPrivateWindow.accesskey;"
                   oncommand="openPrivateWindow();"/>
-#else
-          <button xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
-                  id="startPrivateBrowsing" label="&privatebrowsingpage.startPrivateBrowsing.label;"
-                  accesskey="&privatebrowsingpage.startPrivateBrowsing.accesskey;"
-                  oncommand="togglePrivateBrowsing();"/>
-#endif
         </div>
 
         <!-- Footer -->
         <div id="footerDesc">
-#ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
           <p id="footerText" class="showPrivate">&privatebrowsingpage.howToStop3;</p>
           <p id="footerTextNormal" class="showNormal">&privatebrowsingpage.howToStart3;</p>
-#else
-          <p id="footerText" class="showPrivate">&privatebrowsingpage.howToStop2;</p>
-          <p id="footerTextNormal" class="showNormal">&privatebrowsingpage.howToStart2;</p>
-#endif
         </div>
 
         <!-- More Info -->
         <div id="moreInfo" class="showPrivate">
           <p id="moreInfoText">
             &privatebrowsingpage.moreInfo;
           </p>
           <p id="moreInfoLinkContainer">
--- a/browser/components/privatebrowsing/src/Makefile.in
+++ b/browser/components/privatebrowsing/src/Makefile.in
@@ -10,34 +10,14 @@ VPATH   = @srcdir@
 include $(DEPTH)/config/autoconf.mk
 
 MODULE = privatebrowsing
 LIBRARY_NAME = privatebrowsing_s
 
 FORCE_STATIC_LIB = 1
 USE_STATIC_LIBS = 1
 
-ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
-
 EXTRA_COMPONENTS = \
   nsPrivateBrowsingServiceObsolete.manifest \
   nsPrivateBrowsingServiceObsolete.js \
   $(NULL)
 
-else
-
-CPPSRCS = \
-	nsPrivateBrowsingServiceWrapper.cpp \
-	$(NULL)
-
-LOCAL_INCLUDES = -I$(srcdir)/../../build
-
-EXTRA_COMPONENTS = \
-  nsPrivateBrowsingService.manifest \
-  $(NULL)
-
-EXTRA_PP_COMPONENTS = \
-	nsPrivateBrowsingService.js \
-	$(NULL)
-
-endif
-
 include $(topsrcdir)/config/rules.mk
deleted file mode 100644
--- a/browser/components/privatebrowsing/src/nsPrivateBrowsingService.js
+++ /dev/null
@@ -1,593 +0,0 @@
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-#ifndef XP_WIN
-#define BROKEN_WM_Z_ORDER
-#endif
-
-////////////////////////////////////////////////////////////////////////////////
-//// Constants
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
-const Cr = Components.results;
-
-const STATE_IDLE = 0;
-const STATE_TRANSITION_STARTED = 1;
-const STATE_WAITING_FOR_RESTORE = 2;
-const STATE_RESTORE_FINISHED = 3;
-
-////////////////////////////////////////////////////////////////////////////////
-//// PrivateBrowsingService
-
-function PrivateBrowsingService() {
-  this._obs = Cc["@mozilla.org/observer-service;1"].
-              getService(Ci.nsIObserverService);
-  this._obs.addObserver(this, "profile-after-change", true);
-  this._obs.addObserver(this, "quit-application-granted", true);
-  this._obs.addObserver(this, "private-browsing", true);
-  this._obs.addObserver(this, "command-line-startup", true);
-  this._obs.addObserver(this, "sessionstore-browser-state-restored", true);
-
-  // List of nsIXULWindows we are going to be closing during the transition
-  this._windowsToClose = [];
-}
-
-PrivateBrowsingService.prototype = {
-  // Preferences Service
-  get _prefs() {
-    let prefs = Cc["@mozilla.org/preferences-service;1"].
-                getService(Ci.nsIPrefBranch);
-    this.__defineGetter__("_prefs", function() prefs);
-    return this._prefs;
-  },
-
-  // Whether the private browsing mode is currently active or not.
-  _inPrivateBrowsing: false,
-
-  // Saved browser state before entering the private mode.
-  _savedBrowserState: null,
-
-  // Whether we're in the process of shutting down
-  _quitting: false,
-
-  // How to treat the non-private session
-  _saveSession: true,
-
-  // The current status of the private browsing service
-  _currentStatus: STATE_IDLE,
-
-  // Whether the private browsing mode has been started automatically (ie. always-on)
-  _autoStarted: false,
-
-  // List of view source window URIs for restoring later
-  _viewSrcURLs: [],
-
-  // Whether private browsing has been turned on from the command line
-  _lastChangedByCommandLine: false,
-
-  // Telemetry measurements
-  _enterTimestamps: {},
-  _exitTimestamps: {},
-
-  // XPCOM registration
-  classID: Components.ID("{c31f4883-839b-45f6-82ad-a6a9bc5ad599}"),
-
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIPrivateBrowsingService,
-                                         Ci.nsIObserver,
-                                         Ci.nsISupportsWeakReference,
-                                         Ci.nsICommandLineHandler]),
-
-  _unload: function PBS__destroy() {
-    // Force an exit from the private browsing mode on shutdown
-    this._quitting = true;
-    if (this._inPrivateBrowsing)
-      this.privateBrowsingEnabled = false;
-  },
-
-  _setPerWindowPBFlag: function PBS__setPerWindowPBFlag(aWindow, aFlag) {
-    aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
-           .getInterface(Ci.nsIWebNavigation)
-           .QueryInterface(Ci.nsIDocShellTreeItem)
-           .treeOwner
-           .QueryInterface(Ci.nsIInterfaceRequestor)
-           .getInterface(Ci.nsIXULWindow)
-           .docShell.QueryInterface(Ci.nsILoadContext)
-           .usePrivateBrowsing = aFlag;
-  },
-
-  _adjustPBFlagOnExistingWindows: function PBS__adjustPBFlagOnExistingWindows() {
-    var windowsEnum = Services.wm.getEnumerator(null);
-    while (windowsEnum.hasMoreElements()) {
-      var window = windowsEnum.getNext();
-      this._setPerWindowPBFlag(window, this._inPrivateBrowsing);
-    }
-  },
-
-  _onBeforePrivateBrowsingModeChange: function PBS__onBeforePrivateBrowsingModeChange() {
-    // If we're about to enter PB mode, adjust the flags now
-    if (this._inPrivateBrowsing) {
-      this._adjustPBFlagOnExistingWindows();
-    }
-
-    // nothing needs to be done here if we're enabling at startup
-    if (!this._autoStarted) {
-      let ss = Cc["@mozilla.org/browser/sessionstore;1"].
-               getService(Ci.nsISessionStore);
-      let blankState = JSON.stringify({
-        "windows": [{
-          "tabs": [{
-            "entries": [{
-              "url": "about:blank"
-            }]
-          }],
-          "_closedTabs": []
-        }]
-      });
-
-      if (this._inPrivateBrowsing) {
-        // save the whole browser state in order to restore all windows/tabs later
-        if (this._saveSession && !this._savedBrowserState) {
-          if (this._getBrowserWindow())
-            this._savedBrowserState = ss.getBrowserState();
-          else // no open browser windows, just restore a blank state on exit
-            this._savedBrowserState = blankState;
-        }
-      }
-
-      this._closePageInfoWindows();
-
-      // save view-source windows URIs and close them
-      let viewSrcWindowsEnum = Services.wm.getEnumerator("navigator:view-source");
-      while (viewSrcWindowsEnum.hasMoreElements()) {
-        let win = viewSrcWindowsEnum.getNext();
-        if (this._inPrivateBrowsing) {
-          let plainURL = win.gBrowser.currentURI.spec;
-          if (plainURL.indexOf("view-source:") == 0) {
-            plainURL = plainURL.substr(12);
-            this._viewSrcURLs.push(plainURL);
-          }
-        }
-        win.close();
-      }
-
-      if (!this._quitting && this._saveSession) {
-        let browserWindow = this._getBrowserWindow();
-
-        // if there are open browser windows, load a dummy session to get a distinct 
-        // separation between private and non-private sessions
-        if (browserWindow) {
-          // set an empty session to transition from/to pb mode, see bug 476463
-          ss.setBrowserState(blankState);
-
-          // just in case the only remaining window after setBrowserState is different.
-          // it probably shouldn't be with the current sessionstore impl, but we shouldn't
-          // rely on behaviour the API doesn't guarantee
-          browserWindow = this._getBrowserWindow();
-          let browser = browserWindow.gBrowser;
-
-          // this ensures a clean slate from which to transition into or out of
-          // private browsing
-          browser.addTab();
-          browser.getBrowserForTab(browser.tabContainer.firstChild).stop();
-          browser.removeTab(browser.tabContainer.firstChild);
-          browserWindow.getInterface(Ci.nsIWebNavigation)
-                       .QueryInterface(Ci.nsIDocShellTreeItem)
-                       .treeOwner
-                       .QueryInterface(Ci.nsIInterfaceRequestor)
-                       .getInterface(Ci.nsIXULWindow)
-                       .docShell.contentViewer.resetCloseWindow();
-        }
-      }
-    }
-    else
-      this._saveSession = false;
-
-    // If we're about to leave PB mode, adjust the flags now
-    if (!this._inPrivateBrowsing) {
-      this._adjustPBFlagOnExistingWindows();
-    }
-  },
-
-  _onAfterPrivateBrowsingModeChange: function PBS__onAfterPrivateBrowsingModeChange() {
-    // nothing to do here if we're enabling at startup or the current session is being
-    // used
-    if (!this._autoStarted && this._saveSession) {
-      let ss = Cc["@mozilla.org/browser/sessionstore;1"].
-               getService(Ci.nsISessionStore);
-      // if we have transitioned out of private browsing mode and the session is
-      // to be restored, do it now
-      if (!this._inPrivateBrowsing) {
-        this._currentStatus = STATE_WAITING_FOR_RESTORE;
-        if (!this._getBrowserWindow()) {
-          ss.init(null);
-        }
-        ss.setBrowserState(this._savedBrowserState);
-        this._savedBrowserState = null;
-
-        this._closePageInfoWindows();
-
-        // re-open all view-source windows
-        let windowWatcher = Cc["@mozilla.org/embedcomp/window-watcher;1"].
-                            getService(Ci.nsIWindowWatcher);
-        this._viewSrcURLs.forEach(function(uri) {
-          let args = Cc["@mozilla.org/supports-array;1"].
-                     createInstance(Ci.nsISupportsArray);
-          let str = Cc["@mozilla.org/supports-string;1"].
-                    createInstance(Ci.nsISupportsString);
-          str.data = uri;
-          args.AppendElement(str);
-          args.AppendElement(null); // charset
-          args.AppendElement(null); // page descriptor
-          args.AppendElement(null); // line number
-          let forcedCharset = Cc["@mozilla.org/supports-PRBool;1"].
-                              createInstance(Ci.nsISupportsPRBool);
-          forcedCharset.data = false;
-          args.AppendElement(forcedCharset);
-          windowWatcher.openWindow(null, "chrome://global/content/viewSource.xul",
-            "_blank", "all,dialog=no", args);
-        });
-        this._viewSrcURLs = [];
-      }
-      else {
-        // otherwise, if we have transitioned into private browsing mode, load
-        // about:privatebrowsing
-        let privateBrowsingState = {
-          "windows": [{
-            "tabs": [{
-              "entries": [{
-                "url": "about:privatebrowsing"
-              }]
-            }],
-            "_closedTabs": []
-          }]
-        };
-        // Transition into private browsing mode
-        this._currentStatus = STATE_WAITING_FOR_RESTORE;
-        if (!this._getBrowserWindow()) {
-          ss.init(null);
-        }
-        ss.setBrowserState(JSON.stringify(privateBrowsingState));
-      }
-    }
-  },
-
-  _notifyIfTransitionComplete: function PBS__notifyIfTransitionComplete() {
-    switch (this._currentStatus) {
-      case STATE_TRANSITION_STARTED:
-        // no session store operation was needed, so just notify of transition completion
-      case STATE_RESTORE_FINISHED:
-        // restore has been completed
-        this._currentStatus = STATE_IDLE;
-        this._obs.notifyObservers(null, "private-browsing-transition-complete", "");
-        this._recordTransitionTime("completed");
-        break;
-      case STATE_WAITING_FOR_RESTORE:
-        // too soon to notify...
-        break;
-      case STATE_IDLE:
-        // no need to notify
-        break;
-      default:
-        // unexpected state observed
-        Cu.reportError("Unexpected private browsing status reached: " +
-                       this._currentStatus);
-        break;
-    }
-  },
-
-  _recordTransitionTime: function PBS__recordTransitionTime(aPhase) {
-    // To record the time spent in private browsing transitions, note that we
-    // cannot use the TelemetryStopwatch module, because it reports its results
-    // immediately when the timer is stopped.  In this case, we need to delay
-    // the actual histogram update after we are out of private browsing mode.
-    if (this._inPrivateBrowsing) {
-      this._enterTimestamps[aPhase] = Date.now();
-    } else {
-      if (this._quitting) {
-        // If we are quitting the browser, we don't care collecting the data,
-        // because we wouldn't be able to record it with telemetry.
-        return;
-      }
-      this._exitTimestamps[aPhase] = Date.now();
-      if (aPhase == "completed") {
-        // After we finished exiting the private browsing mode, we can finally
-        // record the telemetry data, for the enter and the exit processes.
-        this._reportTelemetry();
-      }
-    }
-  },
-
-  _reportTelemetry: function PBS__reportTelemetry() {
-    function reportTelemetryEntry(aHistogramId, aValue) {
-      try {
-        Services.telemetry.getHistogramById(aHistogramId).add(aValue);
-      } catch (ex) {
-        Cu.reportError(ex);
-      }
-    }
-
-    reportTelemetryEntry(
-          "PRIVATE_BROWSING_TRANSITION_ENTER_PREPARATION_MS",
-          this._enterTimestamps.prepared - this._enterTimestamps.started);
-    reportTelemetryEntry(
-          "PRIVATE_BROWSING_TRANSITION_ENTER_TOTAL_MS",
-          this._enterTimestamps.completed - this._enterTimestamps.started);
-    reportTelemetryEntry(
-          "PRIVATE_BROWSING_TRANSITION_EXIT_PREPARATION_MS",
-          this._exitTimestamps.prepared - this._exitTimestamps.started);
-    reportTelemetryEntry(
-          "PRIVATE_BROWSING_TRANSITION_EXIT_TOTAL_MS",
-          this._exitTimestamps.completed - this._exitTimestamps.started);
-  },
-
-  _canEnterPrivateBrowsingMode: function PBS__canEnterPrivateBrowsingMode() {
-    let cancelEnter = Cc["@mozilla.org/supports-PRBool;1"].
-                      createInstance(Ci.nsISupportsPRBool);
-    cancelEnter.data = false;
-    this._obs.notifyObservers(cancelEnter, "private-browsing-cancel-vote", "enter");
-    return !cancelEnter.data;
-  },
-
-  _canLeavePrivateBrowsingMode: function PBS__canLeavePrivateBrowsingMode() {
-    let cancelLeave = Cc["@mozilla.org/supports-PRBool;1"].
-                      createInstance(Ci.nsISupportsPRBool);
-    cancelLeave.data = false;
-    this._obs.notifyObservers(cancelLeave, "private-browsing-cancel-vote", "exit");
-    if (!cancelLeave.data) {
-      this._obs.notifyObservers(cancelLeave, "last-pb-context-exiting", null);
-    }
-    return !cancelLeave.data;
-  },
-
-  _getBrowserWindow: function PBS__getBrowserWindow() {
-    var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
-             getService(Ci.nsIWindowMediator);
-
-    var win = wm.getMostRecentWindow("navigator:browser");
-
-    // We don't just return |win| now because of bug 528706.
-
-    if (!win)
-      return null;
-    if (!win.closed)
-      return win;
-
-#ifdef BROKEN_WM_Z_ORDER
-    win = null;
-    var windowsEnum = wm.getEnumerator("navigator:browser");
-    // this is oldest to newest, so this gets a bit ugly
-    while (windowsEnum.hasMoreElements()) {
-      let nextWin = windowsEnum.getNext();
-      if (!nextWin.closed)
-        win = nextWin;
-    }
-    return win;
-#else
-    var windowsEnum = wm.getZOrderDOMWindowEnumerator("navigator:browser", true);
-    while (windowsEnum.hasMoreElements()) {
-      win = windowsEnum.getNext();
-      if (!win.closed)
-        return win;
-    }
-    return null;
-#endif
-  },
-
-  _ensureCanCloseWindows: function PBS__ensureCanCloseWindows() {
-    // whether we should save and close the current session
-    this._saveSession = true;
-    try {
-      if (this._prefs.getBoolPref("browser.privatebrowsing.keep_current_session")) {
-        this._saveSession = false;
-        return;
-      }
-    } catch (ex) {}
-
-    let windowMediator = Cc["@mozilla.org/appshell/window-mediator;1"].
-                         getService(Ci.nsIWindowMediator);
-    let windowsEnum = windowMediator.getEnumerator("navigator:browser");
-
-    while (windowsEnum.hasMoreElements()) {
-      let win = windowsEnum.getNext();
-      if (win.closed)
-        continue;
-      let xulWin = win.QueryInterface(Ci.nsIInterfaceRequestor).
-                   getInterface(Ci.nsIWebNavigation).
-                   QueryInterface(Ci.nsIDocShellTreeItem).
-                   treeOwner.QueryInterface(Ci.nsIInterfaceRequestor).
-                   getInterface(Ci.nsIXULWindow);
-      if (xulWin.docShell.contentViewer.permitUnload(true))
-        this._windowsToClose.push(xulWin);
-      else
-        throw Cr.NS_ERROR_ABORT;
-    }
-  },
-
-  _closePageInfoWindows: function PBS__closePageInfoWindows() {
-    let pageInfoEnum = Cc["@mozilla.org/appshell/window-mediator;1"].
-                       getService(Ci.nsIWindowMediator).
-                       getEnumerator("Browser:page-info");
-    while (pageInfoEnum.hasMoreElements()) {
-      let win = pageInfoEnum.getNext();
-      win.close();
-    }
-  },
-
-  // nsIObserver
-
-  observe: function PBS_observe(aSubject, aTopic, aData) {
-    switch (aTopic) {
-      case "profile-after-change":
-        // If the autostart prefs has been set, simulate entering the
-        // private browsing mode upon startup.
-        // This won't interfere with the session store component, because
-        // that component will be initialized on final-ui-startup.
-        if (!this._autoStarted) {
-          this._autoStarted = this._prefs.getBoolPref("browser.privatebrowsing.autostart");
-          if (this._autoStarted)
-            this.privateBrowsingEnabled = true;
-        }
-        this._obs.removeObserver(this, "profile-after-change");
-        break;
-      case "quit-application-granted":
-        this._unload();
-        break;
-      case "private-browsing":
-        if (!this._inPrivateBrowsing) {
-          // Clear the error console
-          let consoleService = Cc["@mozilla.org/consoleservice;1"].
-                               getService(Ci.nsIConsoleService);
-          consoleService.logStringMessage(null); // trigger the listeners
-          consoleService.reset();
-        }
-        break;
-      case "command-line-startup":
-        this._obs.removeObserver(this, "command-line-startup");
-        aSubject.QueryInterface(Ci.nsICommandLine);
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-        if (aSubject.findFlag("private", false) >= 0) {
-          // Don't need to go into PB mode if it's already set to autostart
-          if (this._autoStarted)
-            aSubject.handleFlag("private", false);
-
-          this.privateBrowsingEnabled = true;
-          this._autoStarted = true;
-          this._lastChangedByCommandLine = true;
-        }
-        else
-#endif
-        if (aSubject.findFlag("private-toggle", false) >= 0) {
-          this._lastChangedByCommandLine = true;
-        }
-        break;
-      case "sessionstore-browser-state-restored":
-        if (this._currentStatus == STATE_WAITING_FOR_RESTORE) {
-          this._currentStatus = STATE_RESTORE_FINISHED;
-          this._notifyIfTransitionComplete();
-        }
-        break;
-    }
-  },
-
-  // nsICommandLineHandler
-
-  handle: function PBS_handle(aCmdLine) {
-#ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-    if (aCmdLine.handleFlag("private", false))
-      aCmdLine.preventDefault = true; // It has already been handled
-    else
-#endif
-    if (aCmdLine.handleFlag("private-toggle", false)) {
-      if (this._autoStarted) {
-        throw Cr.NS_ERROR_ABORT;
-      }
-      this.privateBrowsingEnabled = !this.privateBrowsingEnabled;
-      this._lastChangedByCommandLine = true;
-    }
-  },
-
-  get helpInfo() {
-    return "  -private           Enable private browsing mode.\n" +
-           "  -private-toggle    Toggle private browsing mode.\n";
-  },
-
-  // nsIPrivateBrowsingService
-
-  /**
-   * Return the current status of private browsing.
-   */
-  get privateBrowsingEnabled() {
-    return this._inPrivateBrowsing;
-  },
-
-  /**
-   * Enter or leave private browsing mode.
-   */
-  set privateBrowsingEnabled(val) {
-    // Allowing observers to set the private browsing status from their
-    // notification handlers is not desired, because it will change the
-    // status of the service while it's in the process of another transition.
-    // So, we detect a reentrant call here and throw an error.
-    // This is documented in nsIPrivateBrowsingService.idl.
-    if (this._currentStatus != STATE_IDLE)
-      throw Cr.NS_ERROR_FAILURE;
-
-    if (val == this._inPrivateBrowsing)
-      return;
-
-    try {
-      if (val) {
-        if (!this._canEnterPrivateBrowsingMode())
-          return;
-      }
-      else {
-        if (!this._canLeavePrivateBrowsingMode())
-          return;
-      }
-
-      this._ensureCanCloseWindows();
-
-      // start the transition now that we know that we can
-      this._currentStatus = STATE_TRANSITION_STARTED;
-
-      this._autoStarted = this._prefs.getBoolPref("browser.privatebrowsing.autostart");
-      this._inPrivateBrowsing = val != false;
-
-      this._recordTransitionTime("started");
-
-      let data = val ? "enter" : "exit";
-
-      let quitting = Cc["@mozilla.org/supports-PRBool;1"].
-                     createInstance(Ci.nsISupportsPRBool);
-      quitting.data = this._quitting;
-
-      // notify observers of the pending private browsing mode change
-      this._obs.notifyObservers(quitting, "private-browsing-change-granted", data);
-
-      // destroy the current session and start initial cleanup
-      this._onBeforePrivateBrowsingModeChange();
-
-      this._obs.notifyObservers(quitting, "private-browsing", data);
-
-      this._recordTransitionTime("prepared");
-
-      // load the appropriate session
-      this._onAfterPrivateBrowsingModeChange();
-    } catch (ex) {
-      // We aborted the transition to/from private browsing, we must restore the
-      // beforeunload handling on all the windows for which we switched it off.
-      for (let i = 0; i < this._windowsToClose.length; i++)
-        this._windowsToClose[i].docShell.contentViewer.resetCloseWindow();
-      // We don't log an error when the transition is canceled from beforeunload
-      if (ex != Cr.NS_ERROR_ABORT)
-        Cu.reportError("Exception thrown while processing the " +
-          "private browsing mode change request: " + ex.toString());
-    } finally {
-      this._windowsToClose = [];
-      this._notifyIfTransitionComplete();
-      this._lastChangedByCommandLine = false;
-    }
-  },
-
-  /**
-   * Whether private browsing has been started automatically.
-   */
-  get autoStarted() {
-    return this._inPrivateBrowsing && this._autoStarted;
-  },
-
-  /**
-   * Whether the latest transition was initiated from the command line.
-   */
-  get lastChangedByCommandLine() {
-    return this._lastChangedByCommandLine;
-  }
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([PrivateBrowsingService]);
deleted file mode 100644
--- a/browser/components/privatebrowsing/src/nsPrivateBrowsingService.manifest
+++ /dev/null
@@ -1,17 +0,0 @@
-# WebappRT doesn't need these instructions, and they don't necessarily work
-# with it, but it does use a GRE directory that the GRE shares with Firefox,
-# so in order to prevent the instructions from being processed for WebappRT,
-# we need to restrict them to the applications that depend on them, i.e.:
-#
-#   b2g:            {3c2e2abc-06d4-11e1-ac3b-374f68613e61}
-#   browser:        {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
-#   mobile/android: {aa3c5121-dab2-40e2-81ca-7ea25febc110}
-#   mobile/xul:     {a23983c0-fd0e-11dc-95ff-0800200c9a66}
-#
-# In theory we should do this for all these instructions, but in practice it is
-# sufficient to do it for the app-startup one, and the file is simpler that way.
-
-component {c31f4883-839b-45f6-82ad-a6a9bc5ad599} nsPrivateBrowsingService.js
-contract @mozilla.org/privatebrowsing;1 {c31f4883-839b-45f6-82ad-a6a9bc5ad599}
-category command-line-handler m-privatebrowsing @mozilla.org/privatebrowsing;1
-category app-startup nsPrivateBrowsingService service,@mozilla.org/privatebrowsing;1 application={3c2e2abc-06d4-11e1-ac3b-374f68613e61} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110} application={a23983c0-fd0e-11dc-95ff-0800200c9a66}
deleted file mode 100644
--- a/browser/components/privatebrowsing/src/nsPrivateBrowsingServiceWrapper.cpp
+++ /dev/null
@@ -1,93 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsPrivateBrowsingServiceWrapper.h"
-#include "nsServiceManagerUtils.h"
-#include "jsapi.h"
-#include "nsIJSContextStack.h"
-
-class JSStackGuard
-{
-public:
-  JSStackGuard();
-  ~JSStackGuard();
-
-private:
-  nsCOMPtr<nsIJSContextStack> mJSStack;
-};
-
-NS_IMPL_ISUPPORTS2(nsPrivateBrowsingServiceWrapper, nsIPrivateBrowsingService, nsIObserver)
-
-nsresult
-nsPrivateBrowsingServiceWrapper::Init()
-{
-  nsresult rv;
-  mPBService = do_GetService("@mozilla.org/privatebrowsing;1", &rv);
-  return rv;
-}
-
-JSStackGuard::JSStackGuard()
-  : mJSStack(nullptr)
-{
-  nsresult rv;
-  mJSStack = do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv);
-
-  if (NS_SUCCEEDED(rv) && mJSStack) {
-    rv = mJSStack->Push(nullptr);
-    if (NS_FAILED(rv))
-      mJSStack = nullptr;
-  }
-}
-
-JSStackGuard::~JSStackGuard()
-{
-  if (mJSStack) {
-    JSContext *cx;
-    mJSStack->Pop(&cx);
-    NS_ASSERTION(cx == nullptr, "JSContextStack mismatch");
-  }
-}
-
-NS_IMETHODIMP
-nsPrivateBrowsingServiceWrapper::GetPrivateBrowsingEnabled(bool *aPrivateBrowsingEnabled)
-{
-  if (!aPrivateBrowsingEnabled)
-    return NS_ERROR_NULL_POINTER;
-  JSStackGuard guard;
-  return mPBService->GetPrivateBrowsingEnabled(aPrivateBrowsingEnabled);
-}
-
-NS_IMETHODIMP
-nsPrivateBrowsingServiceWrapper::SetPrivateBrowsingEnabled(bool aPrivateBrowsingEnabled)
-{
-  JSStackGuard guard;
-  return mPBService->SetPrivateBrowsingEnabled(aPrivateBrowsingEnabled);
-}
-
-NS_IMETHODIMP
-nsPrivateBrowsingServiceWrapper::GetAutoStarted(bool *aAutoStarted)
-{
-  if (!aAutoStarted)
-    return NS_ERROR_NULL_POINTER;
-  JSStackGuard guard;
-  return mPBService->GetAutoStarted(aAutoStarted);
-}
-
-NS_IMETHODIMP
-nsPrivateBrowsingServiceWrapper::GetLastChangedByCommandLine(bool *aReason)
-{
-  if (!aReason)
-    return NS_ERROR_NULL_POINTER;
-  JSStackGuard guard;
-  return mPBService->GetLastChangedByCommandLine(aReason);
-}
-
-NS_IMETHODIMP
-nsPrivateBrowsingServiceWrapper::Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData)
-{
-  JSStackGuard guard;
-  nsCOMPtr<nsIObserver> observer(do_QueryInterface(mPBService));
-  NS_ENSURE_TRUE(observer, NS_ERROR_FAILURE);
-  return observer->Observe(aSubject, aTopic, aData);
-}
deleted file mode 100644
--- a/browser/components/privatebrowsing/src/nsPrivateBrowsingServiceWrapper.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsCOMPtr.h"
-#include "nsIPrivateBrowsingService.h"
-#include "nsIObserver.h"
-#include "mozilla/Attributes.h"
-
-class nsIJSContextStack;
-
-class nsPrivateBrowsingServiceWrapper MOZ_FINAL : public nsIPrivateBrowsingService,
-                                                  public nsIObserver
-{
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIPRIVATEBROWSINGSERVICE
-  NS_DECL_NSIOBSERVER
-
-  nsresult Init();
-
-private:
-  nsCOMPtr<nsIPrivateBrowsingService> mPBService;
-};
--- a/browser/components/privatebrowsing/test/Makefile.in
+++ b/browser/components/privatebrowsing/test/Makefile.in
@@ -7,21 +7,12 @@ topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 relativesrcdir  = @relativesrcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE		= test_privatebrowsing
 
-# Most xpcshell PB tests use the global PB service, which means that we should
-# not attempt to run them in regular builds.  We should look at the list and
-# decide which ones of them should be ported to the browser/perwindow suite
-# in the future.
-
-ifndef MOZ_PER_WINDOW_PRIVATE_BROWSING
-XPCSHELL_TESTS	= unit
-endif
-
 DIRS +=	browser \
 		$(NULL)
 
 include $(topsrcdir)/config/rules.mk
--- a/browser/components/privatebrowsing/test/browser/Makefile.in
+++ b/browser/components/privatebrowsing/test/browser/Makefile.in
@@ -7,26 +7,11 @@ topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 relativesrcdir  = @relativesrcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE		= test_privatebrowsing
 
-# We have three category of browser-chrome tests:
-#  global: these tests focus on the global PB service implementation.
-#  perwindow: these tests focus on the per-window PB implementation.
-#  obsolete: these tests focus on the global mode, but the functionality
-#            that they are testing is specific to the global mode, and
-#            will never have a per-window counterpart.
-#
-# As a transition plan, we have divided the existing tests into the
-# global and obsolete categories, and we'll then focus on rewriting the
-# global tests to test the per-window mode.
-
-ifdef MOZ_PER_WINDOW_PRIVATE_BROWSING
 DIRS += perwindow
-else
-DIRS += global obsolete
-endif
 
 include $(topsrcdir)/config/rules.mk
deleted file mode 100644
--- a/browser/components/privatebrowsing/test/browser/global/Makefile.in
+++ /dev/null
@@ -1,56 +0,0 @@
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-DEPTH		= @DEPTH@
-topsrcdir	= @top_srcdir@
-srcdir		= @srcdir@
-VPATH		= @srcdir@
-relativesrcdir  = @relativesrcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-MOCHITEST_BROWSER_FILES =  \
-		head.js \
-		browser_privatebrowsing_certexceptionsui.js \
-		browser_privatebrowsing_crh.js \
-		browser_privatebrowsing_downloadLastDir.js \
-		browser_privatebrowsing_downloadLastDir_c.js \
-		browser_privatebrowsing_downloadLastDir_toggle.js \
-		browser_privatebrowsing_DownloadLastDirWithCPS.js \
-		browser_privatebrowsing_geoprompt.js \
-		browser_privatebrowsing_geoprompt_page.html \
-		browser_privatebrowsing_localStorage.js \
-		browser_privatebrowsing_localStorage_before_after.js \
-		browser_privatebrowsing_localStorage_before_after_page.html \
-		browser_privatebrowsing_localStorage_before_after_page2.html \
-		browser_privatebrowsing_localStorage_page1.html \
-		browser_privatebrowsing_localStorage_page2.html \
-		browser_privatebrowsing_opendir.js \
-		browser_privatebrowsing_openlocation.js \
-		browser_privatebrowsing_openLocationLastURL.js \
-		browser_privatebrowsing_placestitle.js \
-		browser_privatebrowsing_popupblocker.js \
-		browser_privatebrowsing_protocolhandler.js \
-		browser_privatebrowsing_protocolhandler_page.html \
-		browser_privatebrowsing_theming.js \
-		browser_privatebrowsing_ui.js \
-		browser_privatebrowsing_urlbarfocus.js \
-		browser_privatebrowsing_windowtitle.js \
-		browser_privatebrowsing_windowtitle_page.html \
-		browser_privatebrowsing_zoom.js \
-		browser_privatebrowsing_zoomrestore.js \
-		ctxmenu.html \
-		ctxmenu-image.png \
-		popup.html \
-		title.sjs \
-		$(NULL)
-
-# Turn off private browsing tests that perma-timeout on Linux.
-ifneq (Linux,$(OS_ARCH))
-MOCHITEST_BROWSER_FILES += \
-		browser_privatebrowsing_cookieacceptdialog.js \
-		$(NULL)
-endif
-
-include $(topsrcdir)/config/rules.mk
deleted file mode 100644
--- a/browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_DownloadLastDirWithCPS.js
+++ /dev/null
@@ -1,259 +0,0 @@
-/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-let gTests;
-function test() {
-  waitForExplicitFinish();
-  gTests = runTest();
-  moveAlong();
-}
-
-function moveAlong() {
-  try {
-    gTests.next();
-  } catch (x if x instanceof StopIteration) {
-    finish();
-  }
-}
-
-function waitForPB() {
-  function observer(aSubject, aTopic, aData) {
-    Services.obs.removeObserver(observer, "last-pb-context-exited", false);
-    executeSoon(moveAlong);
-  }
-  Services.obs.addObserver(observer, "last-pb-context-exited", false);
-}
-
-function runTest() {
-  let tmpScope = {};
-  Cu.import("resource://gre/modules/DownloadLastDir.jsm", tmpScope);
-  let gDownloadLastDir = new tmpScope.DownloadLastDir(window);
-  Cu.import("resource://gre/modules/Services.jsm");
-  Cu.import("resource://gre/modules/FileUtils.jsm", tmpScope);
-  let FileUtils = tmpScope.FileUtils;
-
-  let pb = Cc["@mozilla.org/privatebrowsing;1"].
-           getService(Ci.nsIPrivateBrowsingService);
-
-  function clearHistory() {
-    // simulate clearing the private data
-    Services.obs.notifyObservers(null, "browser:purge-session-history", "");
-  }
-
-  is(typeof gDownloadLastDir, "object", "gDownloadLastDir should be a valid object");
-  is(gDownloadLastDir.file, null, "LastDir pref should be null to start with");
-
-  let tmpDir = FileUtils.getDir("TmpD", [], true);
-
-  let uri1 = Services.io.newURI("http://test1.com/", null, null);
-  let uri2 = Services.io.newURI("http://test2.com/", null, null);
-  let uri3 = Services.io.newURI("http://test3.com/", null, null);
-  let uri4 = Services.io.newURI("http://test4.com/", null, null);
-
-  function newDir() {
-    let dir = tmpDir.clone();
-    dir.append("testdir");
-    dir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0700);
-    return dir;
-  }
-
-  let dir1 = newDir();
-  let dir2 = newDir();
-  let dir3 = newDir();
-  try {
-    { // set up last dir
-      gDownloadLastDir.setFile(null, tmpDir);
-      is(gDownloadLastDir.file.path, tmpDir.path, "LastDir should point to the tmpDir");
-      isnot(gDownloadLastDir.file, tmpDir, "gDownloadLastDir.file should not be pointing to tmpDir");
-    }
-
-    { // set uri1 to dir1, all should now return dir1
-      // also check that a new object is returned
-      gDownloadLastDir.setFile(uri1, dir1);
-      is(gDownloadLastDir.file.path, dir1.path, "gDownloadLastDir should return dir1");
-      isnot(gDownloadLastDir.file, dir1, "gDownloadLastDir.file should not return dir1");
-      is(gDownloadLastDir.getFile(uri1).path, dir1.path, "uri1 should return dir1"); // set in CPS
-      isnot(gDownloadLastDir.getFile(uri1), dir1, "getFile on uri1 should not return dir1");
-      is(gDownloadLastDir.getFile(uri2).path, dir1.path, "uri2 should return dir1"); // fallback
-      isnot(gDownloadLastDir.getFile(uri2), dir1, "getFile on uri2 should not return dir1");
-      is(gDownloadLastDir.getFile(uri3).path, dir1.path, "uri3 should return dir1"); // fallback
-      isnot(gDownloadLastDir.getFile(uri3), dir1, "getFile on uri3 should not return dir1");
-      is(gDownloadLastDir.getFile(uri4).path, dir1.path, "uri4 should return dir1"); // fallback
-      isnot(gDownloadLastDir.getFile(uri4), dir1, "getFile on uri4 should not return dir1");
-    }
-
-    { // set uri2 to dir2, all except uri1 should now return dir2
-      gDownloadLastDir.setFile(uri2, dir2);
-      is(gDownloadLastDir.file.path, dir2.path, "gDownloadLastDir should point to dir2");
-      is(gDownloadLastDir.getFile(uri1).path, dir1.path, "uri1 should return dir1"); // set in CPS
-      is(gDownloadLastDir.getFile(uri2).path, dir2.path, "uri2 should return dir2"); // set in CPS
-      is(gDownloadLastDir.getFile(uri3).path, dir2.path, "uri3 should return dir2"); // fallback
-      is(gDownloadLastDir.getFile(uri4).path, dir2.path, "uri4 should return dir2"); // fallback
-    }
-
-    { // set uri3 to dir3, all except uri1 and uri2 should now return dir3
-      gDownloadLastDir.setFile(uri3, dir3);
-      is(gDownloadLastDir.file.path, dir3.path, "gDownloadLastDir should point to dir3");
-      is(gDownloadLastDir.getFile(uri1).path, dir1.path, "uri1 should return dir1"); // set in CPS
-      is(gDownloadLastDir.getFile(uri2).path, dir2.path, "uri2 should return dir2"); // set in CPS
-      is(gDownloadLastDir.getFile(uri3).path, dir3.path, "uri3 should return dir3"); // set in CPS
-      is(gDownloadLastDir.getFile(uri4).path, dir3.path, "uri4 should return dir4"); // fallback
-    }
-
-    { // set uri1 to dir2, all except uri3 should now return dir2
-      gDownloadLastDir.setFile(uri1, dir2);
-      is(gDownloadLastDir.file.path, dir2.path, "gDownloadLastDir should point to dir2");
-      is(gDownloadLastDir.getFile(uri1).path, dir2.path, "uri1 should return dir2"); // set in CPS
-      is(gDownloadLastDir.getFile(uri2).path, dir2.path, "uri2 should return dir2"); // set in CPS
-      is(gDownloadLastDir.getFile(uri3).path, dir3.path, "uri3 should return dir3"); // set in CPS
-      is(gDownloadLastDir.getFile(uri4).path, dir2.path, "uri4 should return dir2"); // fallback
-    }
-
-    { // check clearHistory removes all data
-      clearHistory();
-      is(gDownloadLastDir.file, null, "clearHistory removes all data");
-      is(Services.contentPrefs.hasPref(uri1, "browser.download.lastDir", null), false, "LastDir preference should be absent");
-      is(gDownloadLastDir.getFile(uri1), null, "uri1 should point to null");
-      is(gDownloadLastDir.getFile(uri2), null, "uri2 should point to null");
-      is(gDownloadLastDir.getFile(uri3), null, "uri3 should point to null");
-      is(gDownloadLastDir.getFile(uri4), null, "uri4 should point to null");
-    }
-
-    Services.prefs.setBoolPref("browser.privatebrowsing.keep_current_session", true);
-
-    { // check data set outside PB mode is remembered
-      gDownloadLastDir.setFile(null, tmpDir);
-      pb.privateBrowsingEnabled = true;
-      is(gDownloadLastDir.file.path, tmpDir.path, "LastDir should point to tmpDir inside PB mode");
-      is(gDownloadLastDir.getFile(uri1).path, tmpDir.path, "uri1 should return tmpDir inside PB mode");
-
-      waitForPB();
-      pb.privateBrowsingEnabled = false;
-      yield;
-      is(gDownloadLastDir.file.path, tmpDir.path, "LastDir should point to tmpDir outside PB mode");
-      is(gDownloadLastDir.getFile(uri1).path, tmpDir.path, "uri1 should return tmpDir outside PB mode");
-
-      clearHistory();
-    }
-
-    { // check data set using CPS outside PB mode is remembered
-      gDownloadLastDir.setFile(uri1, dir1);
-      pb.privateBrowsingEnabled = true;
-      is(gDownloadLastDir.file.path, dir1.path, "LastDir should point to dir1 inside PB mode");
-      is(gDownloadLastDir.getFile(uri1).path, dir1.path, "uri1 should return dir1 inside PB mode");
-
-      waitForPB();
-      pb.privateBrowsingEnabled = false;
-      yield;
-      is(gDownloadLastDir.file.path, dir1.path, "LastDir should point to dir1 outside PB mode");
-      is(gDownloadLastDir.getFile(uri1).path, dir1.path, "uri1 should return dir1 outside PB mode");
-
-      clearHistory();
-    }
-
-    { // check data set inside PB mode is forgotten
-      pb.privateBrowsingEnabled = true;
-      gDownloadLastDir.setFile(null, tmpDir);
-      is(gDownloadLastDir.file.path, tmpDir.path, "LastDir should return tmpDir inside PB mode");
-      is(gDownloadLastDir.getFile(uri1).path, tmpDir.path, "uri1 should return tmpDir inside PB mode");
-
-      waitForPB();
-      pb.privateBrowsingEnabled = false;
-      yield;
-      is(gDownloadLastDir.file, null, "LastDir should be null outside PB mode");
-      is(gDownloadLastDir.getFile(uri1), null, "uri1 should return null outside PB mode");
-
-      clearHistory();
-    }
-
-    { // check data set using CPS inside PB mode is forgotten
-      pb.privateBrowsingEnabled = true;
-      gDownloadLastDir.setFile(uri1, dir1);
-      is(gDownloadLastDir.file.path, dir1.path, "LastDir should point to dir1 inside PB mode");
-      is(gDownloadLastDir.getFile(uri1).path, dir1.path, "uri1 should return dir1 inside PB mode");
-
-      waitForPB();
-      pb.privateBrowsingEnabled = false;
-      yield;
-      is(gDownloadLastDir.file, null, "LastDir should point to null outside PB mode");
-      is(gDownloadLastDir.getFile(uri1), null, "uri1 should return null outside PB mode");
-
-      clearHistory();
-    }
-
-    { // check data set outside PB mode but changed inside is remembered correctly
-      gDownloadLastDir.setFile(uri1, dir1);
-      pb.privateBrowsingEnabled = true;
-      gDownloadLastDir.setFile(uri1, dir2);
-      is(gDownloadLastDir.file.path, dir2.path, "LastDir should point to dir2 inside PB mode");
-      is(gDownloadLastDir.getFile(uri1).path, dir2.path, "uri1 should return dir2 inside PB mode");
-
-      waitForPB();
-      pb.privateBrowsingEnabled = false;
-      yield;
-      is(gDownloadLastDir.file.path, dir1.path, "LastDir should point to dir1 outside PB mode");
-      is(gDownloadLastDir.getFile(uri1).path, dir1.path, "uri1 should return dir1 outside PB mode");
-
-      // check that the last dir store got cleared
-      pb.privateBrowsingEnabled = true;
-      is(gDownloadLastDir.file.path, dir1.path, "LastDir should be cleared");
-      is(gDownloadLastDir.getFile(uri1).path, dir1.path, "uri1 should return dir1");
-
-      waitForPB();
-      pb.privateBrowsingEnabled = false;
-      yield;
-      clearHistory();
-    }
-
-    { // check clearHistory inside PB mode clears data outside PB mode
-      pb.privateBrowsingEnabled = true;
-      gDownloadLastDir.setFile(uri1, dir2);
-
-      clearHistory();
-      is(gDownloadLastDir.file, null, "LastDir should be null afer clearing history");
-      is(gDownloadLastDir.getFile(uri1), null, "uri1 should return null");
-
-      waitForPB();
-      pb.privateBrowsingEnabled = false;
-      yield;
-      is(gDownloadLastDir.file, null, "LastDir should be null");
-      is(gDownloadLastDir.getFile(uri1), null, "uri1 should return null");
-    }
-
-    { // check that disabling CPS works
-      Services.prefs.setBoolPref("browser.download.lastDir.savePerSite", false);
-
-      gDownloadLastDir.setFile(uri1, dir1);
-      is(gDownloadLastDir.file.path, dir1.path, "LastDir should be set to dir1");
-      is(gDownloadLastDir.getFile(uri1).path, dir1.path, "uri1 should return dir1");
-      is(gDownloadLastDir.getFile(uri2).path, dir1.path, "uri2 should return dir1");
-      is(gDownloadLastDir.getFile(uri3).path, dir1.path, "uri3 should return dir1");
-      is(gDownloadLastDir.getFile(uri4).path, dir1.path, "uri4 should return dir1");
-
-      gDownloadLastDir.setFile(uri2, dir2);
-      is(gDownloadLastDir.file.path, dir2.path, "LastDir should be set to dir2");
-      is(gDownloadLastDir.getFile(uri1).path, dir2.path, "uri1 should return dir2");
-      is(gDownloadLastDir.getFile(uri2).path, dir2.path, "uri2 should return dir2");
-      is(gDownloadLastDir.getFile(uri3).path, dir2.path, "uri3 should return dir2");
-      is(gDownloadLastDir.getFile(uri4).path, dir2.path, "uri4 should return dir2");
-
-      Services.prefs.clearUserPref("browser.download.lastDir.savePerSite");
-    }
-
-    { // check that passing null to setFile clears the stored value
-      gDownloadLastDir.setFile(uri3, dir3);
-      is(gDownloadLastDir.getFile(uri3).path, dir3.path, "LastDir should be set to dir3");
-      gDownloadLastDir.setFile(uri3, null);
-      is(gDownloadLastDir.getFile(uri3), null, "uri3 should return null");
-    }
-  } finally {
-      dir1.remove(true);
-      dir2.remove(true);
-      dir3.remove(true);
-      Services.prefs.clearUserPref("browser.download.lastDir.savePerSite");
-      Services.prefs.clearUserPref("browser.download.lastDir");
-      gDownloadLastDir.cleanupPrivateFile();
-  }
-}
deleted file mode 100644
--- a/browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_certexceptionsui.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// This test makes sure that certificate exceptions UI behaves correctly
-// inside the private browsing mode, based on whether it's opened from the prefs
-// window or from the SSL error page (see bug 461627).
-
-function test() {
-  // initialization
-  let pb = Cc["@mozilla.org/privatebrowsing;1"].
-           getService(Ci.nsIPrivateBrowsingService);
-
-  const EXCEPTIONS_DLG_URL = 'chrome://pippki/content/exceptionDialog.xul';
-  const EXCEPTIONS_DLG_FEATURES = 'chrome,centerscreen';
-  const INVALID_CERT_LOCATION = 'https://nocert.example.com/';
-  waitForExplicitFinish();
-
-  // enter private browsing mode
-  pb.privateBrowsingEnabled = true;
-
-  doTest();
-
-  // Test the certificate exceptions dialog
-  function doTest() {
-    let params = {
-      exceptionAdded : false,
-      location: INVALID_CERT_LOCATION,
-      prefetchCert: true,
-    };
-    function testCheckbox() {
-      win.removeEventListener("load", testCheckbox, false);
-      Services.obs.addObserver(function (aSubject, aTopic, aData) {
-        Services.obs.removeObserver(arguments.callee, "cert-exception-ui-ready", false);
-        ok(win.gCert, "The certificate information should be available now");
-
-        let checkbox = win.document.getElementById("permanent");
-        ok(checkbox.hasAttribute("disabled"),
-          "the permanent checkbox should be disabled when handling the private browsing mode");
-        ok(!checkbox.hasAttribute("checked"),
-          "the permanent checkbox should not be checked when handling the private browsing mode");
-        win.close();
-        cleanup();
-      }, "cert-exception-ui-ready", false);
-    }
-    var win = openDialog(EXCEPTIONS_DLG_URL, "", EXCEPTIONS_DLG_FEATURES, params);
-    win.addEventListener("load", testCheckbox, false);
-  }
-
-  function cleanup() {
-    // leave the private browsing mode
-    pb.privateBrowsingEnabled = false;
-    finish();
-  }
-}
deleted file mode 100644
--- a/browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_cookieacceptdialog.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// This test makes sure that private browsing mode disables the "remember"
-// option in the cookie accept dialog.
-
-function test() {
-  // initialization
-  let pb = Cc["@mozilla.org/privatebrowsing;1"].
-           getService(Ci.nsIPrivateBrowsingService);
-  let cp = Cc["@mozilla.org/embedcomp/cookieprompt-service;1"].
-           getService(Ci.nsICookiePromptService);
-
-  waitForExplicitFinish();
-
-  function checkRememberOption(expectedDisabled, callback) {
-    function observer(aSubject, aTopic, aData) {
-      if (aTopic != "domwindowopened")
-        return;
-
-      Services.ww.unregisterNotification(observer);
-      let win = aSubject.QueryInterface(Ci.nsIDOMWindow);
-      win.addEventListener("load", function onLoad(event) {
-        win.removeEventListener("load", onLoad, false);
-
-        executeSoon(function () {
-          let doc = win.document;
-          let remember = doc.getElementById("persistDomainAcceptance");
-          ok(remember, "The remember checkbox should exist");
-
-          if (expectedDisabled)
-            is(remember.getAttribute("disabled"), "true",
-               "The checkbox should be disabled");
-          else
-            ok(!remember.hasAttribute("disabled"),
-               "The checkbox should not be disabled");
-
-          win.close();
-          callback();
-        });
-      }, false);
-    }
-    Services.ww.registerNotification(observer);
-
-    let remember = {};
-    const time = (new Date("Jan 1, 2030")).getTime() / 1000;
-    let cookie = {
-      name: "foo",
-      value: "bar",
-      isDomain: true,
-      host: "mozilla.org",
-      path: "/baz",
-      isSecure: false,
-      expires: time,
-      status: 0,
-      policy: 0,
-      isSession: false,
-      expiry: time,
-      isHttpOnly: true,
-      QueryInterface: function(iid) {
-        const validIIDs = [Ci.nsISupports,
-                           Ci.nsICookie,
-                           Ci.nsICookie2];
-        for (var i = 0; i < validIIDs.length; ++i)
-          if (iid == validIIDs[i])
-            return this;
-        throw Cr.NS_ERROR_NO_INTERFACE;
-      }
-    };
-    cp.cookieDialog(window, cookie, "mozilla.org", 10, false, remember);
-  }
-
-  checkRememberOption(false, function() {
-    pb.privateBrowsingEnabled = true;
-    checkRememberOption(true, function() {
-      pb.privateBrowsingEnabled = false;
-      checkRememberOption(false, finish);
-    });
-  });
-}
deleted file mode 100644
--- a/browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_crh.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// This test makes sure that the Clear Recent History menu item and command 
-// is disabled inside the private browsing mode.
-
-function test() {
-  // initialization
-  let pb = Cc["@mozilla.org/privatebrowsing;1"].
-           getService(Ci.nsIPrivateBrowsingService);
-
-  let crhCommand = document.getElementById("Tools:Sanitize");
-
-  // make sure the command is not disabled to begin with
-  ok(!crhCommand.hasAttribute("disabled"),
-    "Clear Recent History command should not be disabled outside of the private browsing mode");
-
-  // enter private browsing mode
-  pb.privateBrowsingEnabled = true;
-
-  ok(crhCommand.hasAttribute("disabled"),
-    "Clear Recent History command should be disabled inside of the private browsing mode");
-
-  // leave private browsing mode
-  pb.privateBrowsingEnabled = false;
-
-  ok(!crhCommand.hasAttribute("disabled"),
-    "Clear Recent History command should not be disabled after leaving the private browsing mode");
-}
deleted file mode 100644
--- a/browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_downloadLastDir.js
+++ /dev/null
@@ -1,99 +0,0 @@
-/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function test() {
-  let tempScope = {};
-  let downloadModule = {};
-  Cu.import("resource://gre/modules/Services.jsm");
-  Cu.import("resource://gre/modules/DownloadLastDir.jsm", downloadModule);
-  Cu.import("resource://gre/modules/FileUtils.jsm", tempScope);
-  let FileUtils = tempScope.FileUtils;
-  let MockFilePicker = SpecialPowers.MockFilePicker;
-  let gDownloadLastDir = new downloadModule.DownloadLastDir(window);
-
-  let launcher = {
-    source: Services.io.newURI("http://test1.com/file", null, null)
-  };
-  let pb = Cc["@mozilla.org/privatebrowsing;1"].
-           getService(Ci.nsIPrivateBrowsingService);
-
-  MockFilePicker.init(window);
-   MockFilePicker.returnValue = Ci.nsIFilePicker.returnOK;
-
-  Services.prefs.setBoolPref("browser.privatebrowsing.keep_current_session", true);
-  let prefs = Services.prefs.getBranch("browser.download.");
-  let launcherDialog = Cc["@mozilla.org/helperapplauncherdialog;1"].
-                       getService(Ci.nsIHelperAppLauncherDialog);
-  let tmpDir = FileUtils.getDir("TmpD", [], true);
-  function newDirectory() {
-    let dir = tmpDir.clone();
-    dir.append("testdir");
-    dir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0700);
-    return dir;
-  }
-  function newFileInDirectory(dir) {
-    let file = dir.clone();
-    file.append("testfile");
-    file.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0600);
-    return file;
-  }
-
-  let dir1 = newDirectory();
-  let dir2 = newDirectory();
-  let dir3 = newDirectory();
-  let file1 = newFileInDirectory(dir1);
-  let file2 = newFileInDirectory(dir2);
-  let file3 = newFileInDirectory(dir3);
-
-  // cleanup functions registration
-  registerCleanupFunction(function () {
-    Services.prefs.clearUserPref("browser.privatebrowsing.keep_current_session");
-    Services.prefs.clearUserPref("browser.download.lastDir");
-    [dir1, dir2, dir3].forEach(function(dir) dir.remove(true));
-    MockFilePicker.cleanup();
-    gDownloadLastDir.cleanupPrivateFile();
-    delete FileUtils;
-  });
-
-  let context = gBrowser.selectedBrowser.contentWindow;
-
-  prefs.setComplexValue("lastDir", Ci.nsIFile, tmpDir);
-  MockFilePicker.returnFiles = [file1];
-  let file = launcherDialog.promptForSaveToFile(launcher, context, null, null, null);
-  ok(!!file, "promptForSaveToFile correctly returned a file");
-  // file picker should start with browser.download.lastDir
-  is(MockFilePicker.displayDirectory.path, tmpDir.path, "File picker should start with browser.download.lastDir");
-  // browser.download.lastDir should be modified before entering the private browsing mode
-  is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, dir1.path, "LastDir should be modified before entering the PB mode");
-  // gDownloadLastDir should be usable outside of the private browsing mode
-  is(gDownloadLastDir.file.path, dir1.path, "gDownloadLastDir should be usable outside of the PB mode");
-
-  pb.privateBrowsingEnabled = true;
-  is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, dir1.path, "LastDir should be that set before entering PB mode");
-  MockFilePicker.returnFiles = [file2];
-  MockFilePicker.displayDirectory = null;
-  file = launcherDialog.promptForSaveToFile(launcher, context, null, null, null);
-  ok(!!file, "promptForSaveToFile correctly returned a file");
-  // file picker should start with browser.download.lastDir as set before entering the private browsing mode
-  is(MockFilePicker.displayDirectory.path, dir1.path, "Start with LastDir as set before entering the PB mode");
-  // browser.download.lastDir should not be modified inside the private browsing mode
-  is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, dir1.path, "LastDir should not be modified inside the PB mode");
-  // but gDownloadLastDir should be modified
-  is(gDownloadLastDir.file.path, dir2.path, "gDownloadLastDir should be modified inside PB mode");
-
-  pb.privateBrowsingEnabled = false;
-  // gDownloadLastDir should be cleared after leaving the private browsing mode
-  is(gDownloadLastDir.file.path, dir1.path, "gDownloadLastDir should be cleared after leaving the PB mode");
-  MockFilePicker.returnFiles = [file3];
-  MockFilePicker.displayDirectory = null;
-  file = launcherDialog.promptForSaveToFile(launcher, context, null, null, null);
-  ok(!!file, "promptForSaveToFile correctly returned a file");
-  // file picker should start with browser.download.lastDir as set before entering the private browsing mode
-  is(MockFilePicker.displayDirectory.path, dir1.path, "Start with LastDir as set before entering the PB mode");
-  // browser.download.lastDir should be modified after leaving the private browsing mode
-  is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, dir3.path, "LastDir should be modified after leaving the PB mode");
-  // gDownloadLastDir should be usable after leaving the private browsing mode
-  is(gDownloadLastDir.file.path, dir3.path, "gDownloadLastDir should be usable after leaving the PB mode");
-}
deleted file mode 100644
--- a/browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_downloadLastDir_c.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function test() {
-  let tmpScope = {};
-  let downloadModule = {};
-  Cu.import("resource://gre/modules/DownloadLastDir.jsm", downloadModule);
-  Cu.import("resource://gre/modules/FileUtils.jsm", tmpScope);
-  let FileUtils = tmpScope.FileUtils;
-  Cu.import("resource://gre/modules/Services.jsm");
-  let MockFilePicker = SpecialPowers.MockFilePicker;
-  let gDownloadLastDir = new downloadModule.DownloadLastDir(window);
-
-  let pb = Cc["@mozilla.org/privatebrowsing;1"].
-           getService(Ci.nsIPrivateBrowsingService);
-
-  MockFilePicker.init(window);
-  MockFilePicker.returnValue = Ci.nsIFilePicker.returnOK;
-
-  //let stringBundleToRestore = ContentAreaUtils.stringBundle;
-  let validateFileNameToRestore = validateFileName;
-
-  Services.prefs.setBoolPref("browser.privatebrowsing.keep_current_session", true);
-  let prefs = Services.prefs.getBranch("browser.download.");
-  let tmpDir = FileUtils.getDir("TmpD", [], true);
-  function newDirectory() {
-    let dir = tmpDir.clone();
-    dir.append("testdir");
-    dir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0700);
-    return dir;
-  }
-
-  function newFileInDirectory(dir) {
-    let file = dir.clone();
-    file.append("testfile");
-    file.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0600);
-    return file;
-  }
-
-  let dir1 = newDirectory();
-  let dir2 = newDirectory();
-  let dir3 = newDirectory();
-  let file1 = newFileInDirectory(dir1);
-  let file2 = newFileInDirectory(dir2);
-  let file3 = newFileInDirectory(dir3);
-
-  // cleanup function registration
-  registerCleanupFunction(function () {
-    Services.prefs.clearUserPref("browser.privatebrowsing.keep_current_session");
-    Services.prefs.clearUserPref("browser.download.lastDir");
-    [dir1, dir2, dir3].forEach(function(dir) dir.remove(true));
-    MockFilePicker.cleanup();
-    //ContentAreaUtils.stringBundle = stringBundleToRestore;
-    validateFileName = validateFileNameToRestore;
-    gDownloadLastDir.cleanupPrivateFile();
-    delete FileUtils;
-  });
-
-  // Overwrite stringBundle to return an object masquerading as a string bundle
-  /*delete ContentAreaUtils.stringBundle;
-  ContentAreaUtils.stringBundle = {
-    GetStringFromName: function() ""
-  };*/
-
-  // Overwrite validateFileName to validate everything
-  validateFileName = function(foo) foo;
-
-  let params = {
-    //fpTitleKey: "test",
-    fileInfo: new FileInfo("test.txt", "test.txt", "test", "txt", "http://mozilla.org/test.txt"),
-    contentType: "text/plain",
-    saveMode: SAVEMODE_FILEONLY,
-    saveAsType: kSaveAsType_Complete,
-    file: null
-  };
-
-  prefs.setComplexValue("lastDir", Ci.nsIFile, tmpDir);
-  MockFilePicker.returnFiles = [file1];
-  MockFilePicker.displayDirectory = null;
-  ok(getTargetFile(params), "Show the file picker dialog with given params");
-  // file picker should start with browser.download.lastDir
-  is(MockFilePicker.displayDirectory.path, tmpDir.path, "file picker should start with browser.download.lastDir");
-  // browser.download.lastDir should be modified before entering the private browsing mode
-  is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, dir1.path, "LastDir should be modified before entering PB mode");
-  // gDownloadLastDir should be usable outside of the private browsing mode
-  is(gDownloadLastDir.file.path, dir1.path, "gDownloadLastDir should be usable outside of the PB mode");
-
-  pb.privateBrowsingEnabled = true;
-  is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, dir1.path, "LastDir should be that set before PB mode");
-  MockFilePicker.returnFiles = [file2];
-  MockFilePicker.displayDirectory = null;
-  ok(getTargetFile(params), "Show the file picker dialog with the given params");
-  // file picker should start with browser.download.lastDir as set before entering the private browsing mode
-  is(MockFilePicker.displayDirectory.path, dir1.path, "File picker should start with LastDir set before entering PB mode");
-  // browser.download.lastDir should not be modified inside the private browsing mode
-  is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, dir1.path, "LastDir should not be modified inside PB mode");
-  // but gDownloadLastDir should be modified
-  is(gDownloadLastDir.file.path, dir2.path, "gDownloadLastDir should be modified");
-
-  pb.privateBrowsingEnabled = false;
-  // gDownloadLastDir should be cleared after leaving the private browsing mode
-  is(gDownloadLastDir.file.path, dir1.path, "gDownloadLastDir should be cleared after leaving PB mode");
-  MockFilePicker.returnFiles = [file3];
-  MockFilePicker.displayDirectory = null;
-  ok(getTargetFile(params), "Show the file picker dialog with the given params");
-  // file picker should start with browser.download.lastDir as set before entering the private browsing mode
-  is(MockFilePicker.displayDirectory.path, dir1.path, "File picker should start with LastDir set before PB mode");
-  // browser.download.lastDir should be modified after leaving the private browsing mode
-  is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, dir3.path, "LastDir should be modified after leaving PB mode");
-  // gDownloadLastDir should be usable after leaving the private browsing mode
-  is(gDownloadLastDir.file.path, dir3.path, "gDownloadLastDir should be usable after leaving PB mode");
-}
deleted file mode 100644
--- a/browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_downloadLastDir_toggle.js
+++ /dev/null
@@ -1,76 +0,0 @@
-/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function test() {
-  var tmpScope = {};
-  let downloadModule = {};
-  Cu.import("resource://gre/modules/DownloadLastDir.jsm", downloadModule);
-  Cu.import("resource://gre/modules/FileUtils.jsm", tmpScope);
-  Cu.import("resource://gre/modules/Services.jsm");
-  let FileUtils = tmpScope.FileUtils;
-  let gDownloadLastDir = new downloadModule.DownloadLastDir(window);
-
-  let pb = Cc["@mozilla.org/privatebrowsing;1"].
-           getService(Ci.nsIPrivateBrowsingService);
-
-  function clearHistory() {
-    // simulate clearing the private data
-    Services.obs.notifyObservers(null, "browser:purge-session-history", "");
-  }
-
-  is(typeof gDownloadLastDir, "object", "gDownloadLastDir should be a valid object");
-  is(gDownloadLastDir.file, null, "gDownloadLastDir.file should be null to start with");
-  let tmpDir = FileUtils.getDir("TmpD", [], true);
-  let newDir = tmpDir.clone();
-
-  registerCleanupFunction(function () {
-    Services.prefs.clearUserPref("browser.privatebrowsing.keep_current_session");
-    Services.prefs.clearUserPref("browser.download.lastDir");
-    newDir.remove(true);
-    gDownloadLastDir.cleanupPrivateFile();
-    delete FileUtils;
-  });
-
-  newDir.append("testdir");
-  newDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0700);
-
-  gDownloadLastDir.file = tmpDir;
-  is(gDownloadLastDir.file.path, tmpDir.path, "LastDir should point to the temporary directory");
-  isnot(gDownloadLastDir.file, tmpDir, "gDownloadLastDir.file should not be pointing to the tmpDir");
-
-  gDownloadLastDir.file = 1; // not an nsIFile
-  is(gDownloadLastDir.file, null, "gDownloadLastDir.file should be null");
-  gDownloadLastDir.file = tmpDir;
-
-  clearHistory();
-  is(gDownloadLastDir.file, null, "gDownloadLastDir.file should be null");
-  gDownloadLastDir.file = tmpDir;
-
-  Services.prefs.setBoolPref("browser.privatebrowsing.keep_current_session", true);
-
-  pb.privateBrowsingEnabled = true;
-  is(gDownloadLastDir.file.path, tmpDir.path, "LastDir should point to the temporary directory");
-  isnot(gDownloadLastDir.file, tmpDir, "gDownloadLastDir.file should not be pointing to the tmpDir");
-
-  pb.privateBrowsingEnabled = false;
-  is(gDownloadLastDir.file.path, tmpDir.path, "LastDir should point to the tmpDir");
-  pb.privateBrowsingEnabled = true;
-
-  gDownloadLastDir.file = newDir;
-  is(gDownloadLastDir.file.path, newDir.path, "gDownloadLastDir should be modified in PB mode");
-  isnot(gDownloadLastDir.file, newDir, "gDownloadLastDir should not point to the newDir");
-
-  pb.privateBrowsingEnabled = false;
-  is(gDownloadLastDir.file.path, tmpDir.path, "gDownloadLastDir should point to the earlier directory outside PB mode");
-  isnot(gDownloadLastDir.file, tmpDir, "gDownloadLastDir should not be modifief outside PB mode");
-
-  pb.privateBrowsingEnabled = true;
-  isnot(gDownloadLastDir.file, null, "gDownloadLastDir should not be null inside PB mode");
-  clearHistory();
-  is(gDownloadLastDir.file, null, "gDownloadLastDir should be null after clearing history");
-
-  pb.privateBrowsingEnabled = false;
-  is(gDownloadLastDir.file, null, "gDownloadLastDir should be null outside PB mode");
-}
deleted file mode 100644
--- a/browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_geoprompt.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// This test makes sure that the geolocation prompt does not show a remember
-// control inside the private browsing mode.
-
-function test() {
-  // initialization
-  let pb = Cc["@mozilla.org/privatebrowsing;1"].
-           getService(Ci.nsIPrivateBrowsingService);
-
-  const testPageURL = "http://mochi.test:8888/browser/" +
-    "browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_geoprompt_page.html";
-  waitForExplicitFinish();
-
-  gBrowser.selectedTab = gBrowser.addTab();
-  gBrowser.selectedBrowser.addEventListener("load", function () {
-    gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
-
-    let notification = PopupNotifications.getNotification("geolocation");
-    ok(notification, "Notification should exist");
-    ok(notification.secondaryActions.length > 1, "Secondary actions should exist (always/never remember)");
-    notification.remove();
-
-    gBrowser.removeCurrentTab();
-
-    // enter the private browsing mode
-    pb.privateBrowsingEnabled = true;
-
-    gBrowser.selectedTab = gBrowser.addTab();
-    gBrowser.selectedBrowser.addEventListener("load", function () {
-      gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
-
-      // Make sure the notification is correctly displayed without a remember control
-      let notification = PopupNotifications.getNotification("geolocation");
-      ok(notification, "Notification should exist");
-      is(notification.secondaryActions.length, 0, "Secondary actions shouldn't exist (always/never remember)");
-      notification.remove();
-
-      gBrowser.removeCurrentTab();
-
-      // cleanup
-      pb.privateBrowsingEnabled = false;
-      finish();
-    }, true);
-    content.location = testPageURL;
-  }, true);
-  content.location = testPageURL;
-}
deleted file mode 100644
--- a/browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_geoprompt_page.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<html>
-  <head>
-    <title>Geolocation invoker</title>
-  </head>
-  <body>
-    <script type="text/javascript">
-      navigator.geolocation.getCurrentPosition(function (pos) {
-        // ignore
-      });
-    </script>
-  </body>
-</html>
deleted file mode 100644
--- a/browser/components/privatebrowsing/test/browser/global/browser_privatebrowsing_localStorage.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function test() {
-  let pb = Cc["@mozilla.org/privatebrowsing;1"].
-           getService(Ci.nsIPrivateBrowsingService);
-  waitForExplicitFinish();
-  pb.privateBrowsingEnabled = true;
-  let tab = gBrowser.selectedTab = gBrowser.addTab();
-  let browser = gBrowser.selectedBrowser;
-  browser.addEventListener('load', function() {
-    browser.removeEventListener('load', arguments.callee, true);
-    let tab2 = gBrowser.selectedTab = gBrowser.addTab();
-    browser.contentWindow.location = 'http://mochi.test:8888/browser/browser/components/privatebrowsing/test/browser/global/' +
-                     'browser_privatebrowsing_localStorage_page2.html';
-    browser.addEventListener('load', function() {
-      browser.removeEventListener('load', arguments.callee, true);
-      is(browser.contentWindow.document.title, '2', "localStorage should contain 2 items");
-      pb.privateBrowsingEnabled = false;
-      finish();
-    }, true);
-  }, true);
-  browser.loadURI('http://mochi.test:8888/browser/browser/components/priv