Bug 666901 docshell should use mozilla::Preferences r=bz
authorMasayuki Nakano <masayuki@d-toybox.com>
Sat, 25 Jun 2011 10:55:46 +0900
changeset 72254 9c2e57bef5642561961e0c5e59419fca1ff9292f
parent 72253 f5e4c69084c84717915df0fc2469440b95043467
child 72255 12b5e82f6ffd64033518b62b81423e83a2b4192d
push idunknown
push userunknown
push dateunknown
reviewersbz
bugs666901
milestone7.0a1
Bug 666901 docshell should use mozilla::Preferences r=bz
docshell/base/nsDefaultURIFixup.cpp
docshell/base/nsDefaultURIFixup.h
docshell/base/nsDocShell.cpp
docshell/base/nsDocShell.h
docshell/build/nsDocShellModule.cpp
docshell/shistory/src/nsSHistory.cpp
docshell/shistory/src/nsSHistory.h
--- a/docshell/base/nsDefaultURIFixup.cpp
+++ b/docshell/base/nsDefaultURIFixup.cpp
@@ -39,37 +39,35 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsString.h"
 #include "nsReadableUtils.h"
 #include "nsNetUtil.h"
 #include "nsEscape.h"
 #include "nsCRT.h"
 
-#include "nsIPrefService.h"
-#include "nsIPrefLocalizedString.h"
 #include "nsIPlatformCharset.h"
 #include "nsILocalFile.h"
 
 #ifdef MOZ_TOOLKIT_SEARCH
 #include "nsIBrowserSearchService.h"
 #endif
 
 #include "nsIURIFixup.h"
 #include "nsDefaultURIFixup.h"
+#include "mozilla/Preferences.h"
+
+using namespace mozilla;
 
 /* Implementation file */
 NS_IMPL_ISUPPORTS1(nsDefaultURIFixup, nsIURIFixup)
 
 nsDefaultURIFixup::nsDefaultURIFixup()
 {
   /* member initializers and constructor code */
-
-  // Try and get the pref service
-  mPrefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID);
 }
 
 
 nsDefaultURIFixup::~nsDefaultURIFixup()
 {
   /* destructor code */
 }
 
@@ -129,23 +127,20 @@ nsDefaultURIFixup::CreateExposableURI(ns
     else
     {
         // clone the URI so zapping user:pass doesn't change the original
         nsresult rv = aURI->Clone(getter_AddRefs(uri));
         NS_ENSURE_SUCCESS(rv, rv);
     }
 
     // hide user:pass unless overridden by pref
-    PRBool hideUserPass = PR_TRUE;
-    if (mPrefBranch)
+    if (Preferences::GetBool("browser.fixup.hide_user_pass", PR_TRUE))
     {
-        mPrefBranch->GetBoolPref("browser.fixup.hide_user_pass", &hideUserPass);
+        uri->SetUserPass(EmptyCString());
     }
-    if (hideUserPass)
-        uri->SetUserPass(EmptyCString());
 
     // return the fixed-up URI
     *aReturn = uri;
     NS_ADDREF(*aReturn);
     return NS_OK;
 }
 
 /* nsIURI createFixupURI (in nsAUTF8String aURIText, in unsigned long aFixupFlags); */
@@ -269,20 +264,18 @@ nsDefaultURIFixup::CreateFixupURI(const 
             MakeAlternateURI(*aURI);
         return NS_OK;
     }
 
     // See if it is a keyword
     // Test whether keywords need to be fixed up
     PRBool fixupKeywords = PR_FALSE;
     if (aFixupFlags & FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP) {
-        if (mPrefBranch)
-        {
-            NS_ENSURE_SUCCESS(mPrefBranch->GetBoolPref("keyword.enabled", &fixupKeywords), NS_ERROR_FAILURE);
-        }
+        nsresult rv = Preferences::GetBool("keyword.enabled", &fixupKeywords);
+        NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
         if (fixupKeywords)
         {
             KeywordURIFixup(uriString, aURI);
             if(*aURI)
                 return NS_OK;
         }
     }
 
@@ -353,38 +346,29 @@ nsDefaultURIFixup::CreateFixupURI(const 
 
     return rv;
 }
 
 NS_IMETHODIMP nsDefaultURIFixup::KeywordToURI(const nsACString& aKeyword,
                                               nsIURI **aURI)
 {
     *aURI = nsnull;
-    NS_ENSURE_STATE(mPrefBranch);
+    NS_ENSURE_STATE(Preferences::GetRootBranch());
 
     // Strip leading "?" and leading/trailing spaces from aKeyword
     nsCAutoString keyword(aKeyword);
     if (StringBeginsWith(keyword, NS_LITERAL_CSTRING("?"))) {
         keyword.Cut(0, 1);
     }
     keyword.Trim(" ");
 
-    nsXPIDLCString url;
-    nsCOMPtr<nsIPrefLocalizedString> keywordURL;
-    mPrefBranch->GetComplexValue("keyword.URL", 
-                                 NS_GET_IID(nsIPrefLocalizedString),
-                                 getter_AddRefs(keywordURL));
-
-    if (keywordURL) {
-        nsXPIDLString wurl;
-        keywordURL->GetData(getter_Copies(wurl));
-        CopyUTF16toUTF8(wurl, url);
-    } else {
+    nsAdoptingCString url = Preferences::GetLocalizedCString("keyword.URL");
+    if (!url) {
         // Fall back to a non-localized pref, for backwards compat
-        mPrefBranch->GetCharPref("keyword.URL", getter_Copies(url));
+        url = Preferences::GetCString("keyword.URL");
     }
 
     // If the pref is set and non-empty, use it.
     if (!url.IsEmpty()) {
         // Escape keyword, then prepend URL
         nsCAutoString spec;
         if (!NS_Escape(keyword, spec, url_XPAlphas)) {
             return NS_ERROR_OUT_OF_MEMORY;
@@ -436,23 +420,21 @@ NS_IMETHODIMP nsDefaultURIFixup::Keyword
 #endif
 
     // out of options
     return NS_ERROR_NOT_AVAILABLE;
 }
 
 PRBool nsDefaultURIFixup::MakeAlternateURI(nsIURI *aURI)
 {
-    if (!mPrefBranch)
+    if (!Preferences::GetRootBranch())
     {
         return PR_FALSE;
     }
-    PRBool makeAlternate = PR_TRUE;
-    mPrefBranch->GetBoolPref("browser.fixup.alternate.enabled", &makeAlternate);
-    if (!makeAlternate)
+    if (!Preferences::GetBool("browser.fixup.alternate.enabled", PR_TRUE))
     {
         return PR_FALSE;
     }
 
     // Code only works for http. Not for any other protocol including https!
     PRBool isHttp = PR_FALSE;
     aURI->SchemeIs("http", &isHttp);
     if (!isHttp) {
@@ -484,27 +466,27 @@ PRBool nsDefaultURIFixup::MakeAlternateU
 
 
     nsresult rv;
 
     // Get the prefix and suffix to stick onto the new hostname. By default these
     // are www. & .com but they could be any other value, e.g. www. & .org
 
     nsCAutoString prefix("www.");
-    nsXPIDLCString prefPrefix;
-    rv = mPrefBranch->GetCharPref("browser.fixup.alternate.prefix", getter_Copies(prefPrefix));
-    if (NS_SUCCEEDED(rv))
+    nsAdoptingCString prefPrefix =
+        Preferences::GetCString("browser.fixup.alternate.prefix");
+    if (prefPrefix)
     {
         prefix.Assign(prefPrefix);
     }
 
     nsCAutoString suffix(".com");
-    nsXPIDLCString prefSuffix;
-    rv = mPrefBranch->GetCharPref("browser.fixup.alternate.suffix", getter_Copies(prefSuffix));
-    if (NS_SUCCEEDED(rv))
+    nsAdoptingCString prefSuffix =
+        Preferences::GetCString("browser.fixup.alternate.suffix");
+    if (prefSuffix)
     {
         suffix.Assign(prefSuffix);
     }
     
     if (numDots == 0)
     {
         newHost.Assign(prefix);
         newHost.Append(oldHost);
--- a/docshell/base/nsDefaultURIFixup.h
+++ b/docshell/base/nsDefaultURIFixup.h
@@ -35,17 +35,16 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef NSDEFAULTURIFIXUP_H
 #define NSDEFAULTURIFIXUP_H
 
-#include "nsIPrefBranch.h"
 #include "nsIURIFixup.h"
 
 #include "nsCOMPtr.h"
 
 #include "nsCDefaultURIFixup.h"
 
 /* Header file */
 class nsDefaultURIFixup : public nsIURIFixup
@@ -66,13 +65,12 @@ private:
     nsresult KeywordURIFixup(const nsACString &aStringURI, nsIURI** aURI);
     PRBool PossiblyByteExpandedFileName(const nsAString& aIn);
     PRBool PossiblyHostPortUrl(const nsACString& aUrl);
     PRBool MakeAlternateURI(nsIURI *aURI);
     PRBool IsLikelyFTP(const nsCString& aHostSpec);
     const char * GetFileSystemCharset();
     const char * GetCharsetForUrlBar();
 
-    nsCOMPtr<nsIPrefBranch> mPrefBranch;
     nsCString mFsCharset;
 };
 
 #endif
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -90,32 +90,30 @@
 #include "nsIScriptObjectPrincipal.h"
 #include "nsDocumentCharsetInfoCID.h"
 #include "nsIScrollableFrame.h"
 #include "nsContentPolicyUtils.h" // NS_CheckContentLoadPolicy(...)
 #include "nsICategoryManager.h"
 #include "nsXPCOMCID.h"
 #include "nsISeekableStream.h"
 #include "nsAutoPtr.h"
-#include "nsIPrefService.h"
-#include "nsIPrefBranch.h"
-#include "nsIPrefBranch2.h"
 #include "nsIWritablePropertyBag2.h"
 #include "nsIAppShell.h"
 #include "nsWidgetsCID.h"
 #include "nsDOMJSUtils.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIView.h"
 #include "nsIViewManager.h"
 #include "nsIScriptChannel.h"
 #include "nsIOfflineCacheUpdate.h"
 #include "nsCPrefetchService.h"
 #include "nsJSON.h"
 #include "IHistory.h"
 #include "mozilla/Services.h"
+#include "mozilla/Preferences.h"
 
 // we want to explore making the document own the load group
 // so we can associate the document URI with the load group.
 // until this point, we have an evil hack:
 #include "nsIHttpChannelInternal.h"  
 
 
 // Local Includes
@@ -302,31 +300,24 @@ FavorPerformanceHint(PRBool perfOverStar
 //   a ping via FTP.
 //
 // @returns
 //   PR_TRUE if pings are enabled and PR_FALSE otherwise.
 //
 static PRBool
 PingsEnabled(PRInt32 *maxPerLink, PRBool *requireSameHost)
 {
-  PRBool allow = PR_FALSE;
+  PRBool allow = Preferences::GetBool(PREF_PINGS_ENABLED, PR_FALSE);
 
   *maxPerLink = 1;
   *requireSameHost = PR_TRUE;
 
-  nsCOMPtr<nsIPrefBranch> prefs =
-      do_GetService(NS_PREFSERVICE_CONTRACTID);
-  if (prefs) {
-    PRBool val;
-    if (NS_SUCCEEDED(prefs->GetBoolPref(PREF_PINGS_ENABLED, &val)))
-      allow = val;
-    if (allow) {
-      prefs->GetIntPref(PREF_PINGS_MAX_PER_LINK, maxPerLink);
-      prefs->GetBoolPref(PREF_PINGS_REQUIRE_SAME_HOST, requireSameHost);
-    }
+  if (allow) {
+    Preferences::GetInt(PREF_PINGS_MAX_PER_LINK, maxPerLink);
+    Preferences::GetBool(PREF_PINGS_REQUIRE_SAME_HOST, requireSameHost);
   }
 
   return allow;
 }
 
 static PRBool
 CheckPingURI(nsIURI* uri, nsIContent* content)
 {
@@ -734,16 +725,17 @@ nsDocShell::nsDocShell():
     mBusyFlags(BUSY_FLAGS_NONE),
     mAppType(nsIDocShell::APP_TYPE_UNKNOWN),
     mMarginWidth(-1),
     mMarginHeight(-1),
     mItemType(typeContent),
     mPreviousTransIndex(-1),
     mLoadType(0),
     mLoadedTransIndex(-1),
+    mCreated(PR_FALSE),
     mAllowSubframes(PR_TRUE),
     mAllowPlugins(PR_TRUE),
     mAllowJavascript(PR_TRUE),
     mAllowMetaRedirects(PR_TRUE),
     mAllowImages(PR_TRUE),
     mAllowDNSPrefetch(PR_TRUE),
     mCreatingDocument(PR_FALSE),
     mUseErrorPages(PR_FALSE),
@@ -1595,19 +1587,17 @@ nsDocShell::FirePageHideNotification(PRB
 
 nsresult
 nsDocShell::MaybeInitTiming()
 {
     if (mTiming) {
         return NS_OK;
     }
 
-    PRBool enabled;
-    nsresult rv = mPrefs->GetBoolPref("dom.enable_performance", &enabled);
-    if (NS_SUCCEEDED(rv) && enabled) {
+    if (Preferences::GetBool("dom.enable_performance", PR_FALSE)) {
         mTiming = new nsDOMNavigationTiming();
         mTiming->NotifyNavigationStart();
     }
     return NS_OK;
 }
 
 
 //
@@ -2196,21 +2186,18 @@ nsDocShell::GetUseErrorPages(PRBool *aUs
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDocShell::SetUseErrorPages(PRBool aUseErrorPages)
 {
     // If mUseErrorPages is set explicitly, stop observing the pref.
     if (mObserveErrorPages) {
-        nsCOMPtr<nsIPrefBranch2> prefs(do_QueryInterface(mPrefs));
-        if (prefs) {
-            prefs->RemoveObserver("browser.xul.error_pages.enabled", this);
-            mObserveErrorPages = PR_FALSE;
-        }
+        Preferences::RemoveObserver(this, "browser.xul.error_pages.enabled");
+        mObserveErrorPages = PR_FALSE;
     }
     mUseErrorPages = aUseErrorPages;
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDocShell::GetPreviousTransIndex(PRInt32 *aPreviousTransIndex)
 {
@@ -3914,44 +3901,41 @@ nsDocShell::DisplayLoadError(nsresult aE
 
                 PRBool isStsHost = PR_FALSE;
                 rv = stss->IsStsURI(aURI, &isStsHost);
                 NS_ENSURE_SUCCESS(rv, rv);
 
                 if (isStsHost)
                   cssClass.AssignLiteral("badStsCert");
 
-                PRBool expert = PR_FALSE;
-                mPrefs->GetBoolPref("browser.xul.error_pages.expert_bad_cert",
-                                    &expert);
-                if (expert) {
+                if (Preferences::GetBool(
+                        "browser.xul.error_pages.expert_bad_cert", PR_FALSE)) {
                     cssClass.AssignLiteral("expertBadCert");
                 }
 
                 // See if an alternate cert error page is registered
-                nsXPIDLCString alternateErrorPage;
-                mPrefs->GetCharPref("security.alternate_certificate_error_page",
-                                    getter_Copies(alternateErrorPage));
+                nsAdoptingCString alternateErrorPage =
+                    Preferences::GetCString(
+                        "security.alternate_certificate_error_page");
                 if (alternateErrorPage)
                     errorPage.Assign(alternateErrorPage);
             } else {
                 error.AssignLiteral("nssFailure2");
             }
         }
     } else if (NS_ERROR_PHISHING_URI == aError || NS_ERROR_MALWARE_URI == aError) {
         nsCAutoString host;
         aURI->GetHost(host);
         CopyUTF8toUTF16(host, formatStrs[0]);
         formatStrCount = 1;
 
         // Malware and phishing detectors may want to use an alternate error
         // page, but if the pref's not set, we'll fall back on the standard page
-        nsXPIDLCString alternateErrorPage;
-        mPrefs->GetCharPref("urlclassifier.alternate_error_page",
-                            getter_Copies(alternateErrorPage));
+        nsAdoptingCString alternateErrorPage =
+            Preferences::GetCString("urlclassifier.alternate_error_page");
         if (alternateErrorPage)
             errorPage.Assign(alternateErrorPage);
 
         if (NS_ERROR_PHISHING_URI == aError)
             error.AssignLiteral("phishingBlocked");
         else
             error.AssignLiteral("malwareBlocked");
         cssClass.AssignLiteral("blacklist");
@@ -4487,52 +4471,42 @@ nsDocShell::InitWindow(nativeWindow pare
     SetPositionAndSize(x, y, cx, cy, PR_FALSE);
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDocShell::Create()
 {
-    if (mPrefs) {
+    if (mCreated) {
         // We've already been created
         return NS_OK;
     }
 
     NS_ASSERTION(mItemType == typeContent || mItemType == typeChrome,
                  "Unexpected item type in docshell");
 
-    nsresult rv = NS_ERROR_FAILURE;
-    mPrefs = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    PRBool tmpbool;
-
-    rv = mPrefs->GetBoolPref("browser.frames.enabled", &tmpbool);
-    if (NS_SUCCEEDED(rv))
-        mAllowSubframes = tmpbool;
+    NS_ENSURE_TRUE(Preferences::GetRootBranch(), NS_ERROR_FAILURE);
+    mCreated = PR_TRUE;
+
+    mAllowSubframes =
+        Preferences::GetBool("browser.frames.enabled", mAllowSubframes);
 
     if (gValidateOrigin == (PRBool)0xffffffff) {
         // Check pref to see if we should prevent frameset spoofing
-        rv = mPrefs->GetBoolPref("browser.frame.validate_origin", &tmpbool);
-        if (NS_SUCCEEDED(rv)) {
-            gValidateOrigin = tmpbool;
-        } else {
-            gValidateOrigin = PR_TRUE;
-        }
+        gValidateOrigin =
+            Preferences::GetBool("browser.frame.validate_origin", PR_TRUE);
     }
 
     // Should we use XUL error pages instead of alerts if possible?
-    rv = mPrefs->GetBoolPref("browser.xul.error_pages.enabled", &tmpbool);
-    if (NS_SUCCEEDED(rv))
-        mUseErrorPages = tmpbool;
-
-    nsCOMPtr<nsIPrefBranch2> prefs(do_QueryInterface(mPrefs, &rv));
-    if (NS_SUCCEEDED(rv) && mObserveErrorPages) {
-        prefs->AddObserver("browser.xul.error_pages.enabled", this, PR_FALSE);
+    mUseErrorPages =
+        Preferences::GetBool("browser.xul.error_pages.enabled", mUseErrorPages);
+
+    if (mObserveErrorPages) {
+        Preferences::AddStrongObserver(this, "browser.xul.error_pages.enabled");
     }
 
     nsCOMPtr<nsIObserverService> serv = do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
     if (serv) {
         const char* msg = mItemType == typeContent ?
             NS_WEBNAVIGATION_CREATE : NS_CHROME_WEBNAVIGATION_CREATE;
         serv->NotifyObservers(GetAsSupports(this), msg, nsnull);
     }
@@ -4555,21 +4529,18 @@ nsDocShell::Destroy()
             serv->NotifyObservers(GetAsSupports(this), msg, nsnull);
         }
     }
     
     mIsBeingDestroyed = PR_TRUE;
 
     // Remove our pref observers
     if (mObserveErrorPages) {
-        nsCOMPtr<nsIPrefBranch2> prefs(do_QueryInterface(mPrefs));
-        if (prefs) {
-            prefs->RemoveObserver("browser.xul.error_pages.enabled", this);
-            mObserveErrorPages = PR_FALSE;
-        }
+        Preferences::RemoveObserver(this, "browser.xul.error_pages.enabled");
+        mObserveErrorPages = PR_FALSE;
     }
 
     // Make sure to blow away our mLoadingURI just in case.  No loads
     // from inside this pagehide.
     mLoadingURI = nsnull;
 
     // Fire unload event before we blow anything away.
     (void) FirePageHideNotification(PR_TRUE);
@@ -5966,19 +5937,17 @@ nsDocShell::OnStateChange(nsIWebProgress
             }
         
         }
         // Page has begun to load
         mBusyFlags = BUSY_FLAGS_BUSY | BUSY_FLAGS_BEFORE_PAGE_LOAD;
 
         if ((aStateFlags & STATE_RESTORING) == 0) {
             // Show the progress cursor if the pref is set
-            PRBool tmpBool = PR_FALSE;
-            if (NS_SUCCEEDED(mPrefs->GetBoolPref("ui.use_activity_cursor", &tmpBool))
-                && tmpBool) {
+            if (Preferences::GetBool("ui.use_activity_cursor", PR_FALSE)) {
                 nsCOMPtr<nsIWidget> mainWidget;
                 GetMainWidget(getter_AddRefs(mainWidget));
                 if (mainWidget) {
                     mainWidget->SetCursor(eCursor_spinning);
                 }
             }
         }
     }
@@ -5986,19 +5955,17 @@ nsDocShell::OnStateChange(nsIWebProgress
         // Page is loading
         mBusyFlags = BUSY_FLAGS_BUSY | BUSY_FLAGS_PAGE_LOADING;
     }
     else if ((aStateFlags & STATE_STOP) && (aStateFlags & STATE_IS_NETWORK)) {
         // Page has finished loading
         mBusyFlags = BUSY_FLAGS_NONE;
 
         // Hide the progress cursor if the pref is set
-        PRBool tmpBool = PR_FALSE;
-        if (NS_SUCCEEDED(mPrefs->GetBoolPref("ui.use_activity_cursor", &tmpBool))
-            && tmpBool) {
+        if (Preferences::GetBool("ui.use_activity_cursor", PR_FALSE)) {
             nsCOMPtr<nsIWidget> mainWidget;
             GetMainWidget(getter_AddRefs(mainWidget));
             if (mainWidget) {
                 mainWidget->SetCursor(eCursor_standard);
             }
         }
     }
     if ((~aStateFlags & (STATE_IS_DOCUMENT | STATE_STOP)) == 0) {
@@ -6235,22 +6202,18 @@ nsDocShell::EndPageLoad(nsIWebProgress *
 
             nsCAutoString oldSpec;
             url->GetSpec(oldSpec);
       
             //
             // First try keyword fixup
             //
             if (aStatus == NS_ERROR_UNKNOWN_HOST && mAllowKeywordFixup) {
-                PRBool keywordsEnabled = PR_FALSE;
-
-                if (mPrefs &&
-                    NS_FAILED(mPrefs->GetBoolPref("keyword.enabled",
-                                                  &keywordsEnabled)))
-                    keywordsEnabled = PR_FALSE;
+                PRBool keywordsEnabled =
+                    Preferences::GetBool("keyword.enabled", PR_FALSE);
 
                 nsCAutoString host;
                 url->GetHost(host);
 
                 nsCAutoString scheme;
                 url->GetScheme(scheme);
 
                 PRInt32 dotLoc = host.FindChar('.');
@@ -6695,19 +6658,19 @@ nsDocShell::CanSavePresentation(PRUint32
 
     // Avoid doing the work of saving the presentation state in the case where
     // the content viewer cache is disabled.
     if (nsSHistory::GetMaxTotalViewers() == 0)
         return PR_FALSE;
 
     // Don't cache the content viewer if we're in a subframe and the subframe
     // pref is disabled.
-    PRBool cacheFrames = PR_FALSE;
-    mPrefs->GetBoolPref("browser.sessionhistory.cache_subframes",
-                        &cacheFrames);
+    PRBool cacheFrames =
+        Preferences::GetBool("browser.sessionhistory.cache_subframes",
+                             PR_FALSE);
     if (!cacheFrames) {
         nsCOMPtr<nsIDocShellTreeItem> root;
         GetSameTypeParent(getter_AddRefs(root));
         if (root && root != this) {
             return PR_FALSE;  // this is a subframe load
         }
     }
 
@@ -9207,32 +9170,26 @@ nsresult nsDocShell::DoChannelLoad(nsICh
     case LOAD_RELOAD_BYPASS_PROXY:
     case LOAD_RELOAD_BYPASS_PROXY_AND_CACHE:
         loadFlags |= nsIRequest::LOAD_BYPASS_CACHE;
         break;
 
     case LOAD_NORMAL:
     case LOAD_LINK:
         // Set cache checking flags
-        PRInt32 prefSetting;
-        if (NS_SUCCEEDED
-            (mPrefs->
-             GetIntPref("browser.cache.check_doc_frequency",
-                        &prefSetting))) {
-            switch (prefSetting) {
-            case 0:
-                loadFlags |= nsIRequest::VALIDATE_ONCE_PER_SESSION;
-                break;
-            case 1:
-                loadFlags |= nsIRequest::VALIDATE_ALWAYS;
-                break;
-            case 2:
-                loadFlags |= nsIRequest::VALIDATE_NEVER;
-                break;
-            }
+        switch (Preferences::GetInt("browser.cache.check_doc_frequency", -1)) {
+        case 0:
+            loadFlags |= nsIRequest::VALIDATE_ONCE_PER_SESSION;
+            break;
+        case 1:
+            loadFlags |= nsIRequest::VALIDATE_ALWAYS;
+            break;
+        case 2:
+            loadFlags |= nsIRequest::VALIDATE_NEVER;
+            break;
         }
         break;
     }
 
     if (!aBypassClassifier) {
         loadFlags |= nsIChannel::LOAD_CLASSIFY_URI;
     }
 
@@ -9695,21 +9652,18 @@ nsDocShell::AddState(nsIVariant *aData, 
 
         PRBool principalsEqual = PR_FALSE;
         origPrincipal->Equals(newPrincipal, &principalsEqual);
         NS_ENSURE_TRUE(principalsEqual, NS_ERROR_DOM_SECURITY_ERR);
     }
 
     // Check that the state object isn't too long.
     // Default max length: 640k bytes.
-    PRInt32 maxStateObjSize = 0xA0000;
-    if (mPrefs) {
-        mPrefs->GetIntPref("browser.history.maxStateObjectSize",
-                           &maxStateObjSize);
-    }
+    PRInt32 maxStateObjSize =
+        Preferences::GetInt("browser.history.maxStateObjectSize", 0xA0000);
     if (maxStateObjSize < 0) {
         maxStateObjSize = 0;
     }
 
     PRUint64 scSize;
     rv = scContainer->GetSerializedNBytes(&scSize);
     NS_ENSURE_SUCCESS(rv, rv);
 
@@ -11201,21 +11155,18 @@ nsDocShell::Observe(nsISupports *aSubjec
                     const PRUnichar *aData)
 {
     nsresult rv = NS_OK;
     if (mObserveErrorPages &&
         !nsCRT::strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID) &&
         !nsCRT::strcmp(aData,
           NS_LITERAL_STRING("browser.xul.error_pages.enabled").get())) {
 
-        nsCOMPtr<nsIPrefBranch> prefs(do_QueryInterface(aSubject, &rv));
-        NS_ENSURE_SUCCESS(rv, rv);
-
         PRBool tmpbool;
-        rv = prefs->GetBoolPref("browser.xul.error_pages.enabled", &tmpbool);
+        rv = Preferences::GetBool("browser.xul.error_pages.enabled", &tmpbool);
         if (NS_SUCCEEDED(rv))
             mUseErrorPages = tmpbool;
 
     } else {
         rv = NS_ERROR_UNEXPECTED;
     }
     return rv;
 }
--- a/docshell/base/nsDocShell.h
+++ b/docshell/base/nsDocShell.h
@@ -39,17 +39,16 @@
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef nsDocShell_h__
 #define nsDocShell_h__
 
 #include "nsIDOMNode.h"
 #include "nsIDOMNodeList.h"
 #include "nsIContentViewer.h"
-#include "nsIPrefBranch.h"
 #include "nsInterfaceHashtable.h"
 #include "nsIScriptContext.h"
 #include "nsITimer.h"
 
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocShellTreeNode.h"
 #include "nsIBaseWindow.h"
@@ -713,17 +712,16 @@ protected:
     nsIntPoint                 mDefaultScrollbarPref; // persistent across doc loads
 
     nsCOMPtr<nsISupportsArray> mRefreshURIList;
     nsCOMPtr<nsISupportsArray> mSavedRefreshURIList;
     nsRefPtr<nsDSURIContentListener> mContentListener;
     nsCOMPtr<nsIContentViewer> mContentViewer;
     nsCOMPtr<nsIDocumentCharsetInfo> mDocumentCharsetInfo;
     nsCOMPtr<nsIWidget>        mParentWidget;
-    nsCOMPtr<nsIPrefBranch>    mPrefs;
 
     // mCurrentURI should be marked immutable on set if possible.
     nsCOMPtr<nsIURI>           mCurrentURI;
     nsCOMPtr<nsIURI>           mReferrerURI;
     nsCOMPtr<nsIScriptGlobalObject> mScriptGlobal;
     nsCOMPtr<nsISHistory>      mSessionHistory;
     nsCOMPtr<nsIGlobalHistory2> mGlobalHistory;
     nsCOMPtr<nsIWebBrowserFind> mFind;
@@ -786,16 +784,17 @@ protected:
     // Create() is called, the type is not expected to change.
     PRInt32                    mItemType;
 
     // Index into the SHTransaction list, indicating the previous and current
     // transaction at the time that this DocShell begins to load
     PRInt32                    mPreviousTransIndex;
     PRInt32                    mLoadedTransIndex;
 
+    PRPackedBool               mCreated;
     PRPackedBool               mAllowSubframes;
     PRPackedBool               mAllowPlugins;
     PRPackedBool               mAllowJavascript;
     PRPackedBool               mAllowMetaRedirects;
     PRPackedBool               mAllowImages;
     PRPackedBool               mAllowDNSPrefetch;
     PRPackedBool               mCreatingDocument; // (should be) debugging only
     PRPackedBool               mUseErrorPages;
--- a/docshell/build/nsDocShellModule.cpp
+++ b/docshell/build/nsDocShellModule.cpp
@@ -89,16 +89,17 @@ Initialize()
 
   rv = nsSHEntry::Startup();
   return rv;
 }
 
 static void
 Shutdown()
 {
+  nsSHistory::Shutdown();
   nsSHEntry::Shutdown();
   gInitialized = PR_FALSE;
 }
 
 // docshell
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsDocShell, Init)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsDefaultURIFixup)
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsWebNavigationInfo, Init)
--- a/docshell/shistory/src/nsSHistory.cpp
+++ b/docshell/shistory/src/nsSHistory.cpp
@@ -38,45 +38,54 @@
  * ***** END LICENSE BLOCK ***** */
 
 // Local Includes 
 #include "nsSHistory.h"
 
 // Helper Classes
 #include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
+#include "mozilla/Preferences.h"
 
 // Interfaces Needed
 #include "nsILayoutHistoryState.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellLoadInfo.h"
 #include "nsISHContainer.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocShellTreeNode.h"
 #include "nsIDocShellLoadInfo.h"
 #include "nsIServiceManager.h"
-#include "nsIPrefService.h"
 #include "nsIURI.h"
 #include "nsIContentViewer.h"
 #include "nsICacheService.h"
 #include "nsIObserverService.h"
 #include "prclist.h"
 #include "mozilla/Services.h"
 #include "nsTArray.h"
 #include "nsCOMArray.h"
 #include "nsDocShell.h"
 
 // For calculating max history entries and max cachable contentviewers
 #include "nspr.h"
 #include <math.h>  // for log()
 
+using namespace mozilla;
+
 #define PREF_SHISTORY_SIZE "browser.sessionhistory.max_entries"
 #define PREF_SHISTORY_MAX_TOTAL_VIEWERS "browser.sessionhistory.max_total_viewers"
 #define PREF_SHISTORY_OPTIMIZE_EVICTION "browser.sessionhistory.optimize_eviction"
 
+static const char* kObservedPrefs[] = {
+  PREF_SHISTORY_SIZE,
+  PREF_SHISTORY_MAX_TOTAL_VIEWERS,
+  PREF_SHISTORY_OPTIMIZE_EVICTION,
+  nsnull
+};
+
 static PRInt32  gHistoryMaxSize = 50;
 // Max viewers allowed per SHistory objects
 static const PRInt32  gHistoryMaxViewers = 3;
 // List of all SHistory objects, used for content viewer cache eviction
 static PRCList gSHistoryList;
 // Max viewers allowed total, across all SHistory objects - negative default
 // means we will calculate how many viewers to cache based on total memory
 PRInt32 nsSHistory::sHistoryMaxTotalViewers = -1;
@@ -110,28 +119,27 @@ public:
   NS_DECL_NSIOBSERVER
 
   nsSHistoryObserver() {}
 
 protected:
   ~nsSHistoryObserver() {}
 };
 
+static nsSHistoryObserver* gObserver = nsnull;
+
 NS_IMPL_ISUPPORTS1(nsSHistoryObserver, nsIObserver)
 
 NS_IMETHODIMP
 nsSHistoryObserver::Observe(nsISupports *aSubject, const char *aTopic,
                             const PRUnichar *aData)
 {
   if (!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
-    nsCOMPtr<nsIPrefBranch> prefs = do_QueryInterface(aSubject);
-    if (prefs) {
-      nsSHistory::UpdatePrefs(prefs);
-      nsSHistory::EvictGlobalContentViewer();
-    }
+    nsSHistory::UpdatePrefs();
+    nsSHistory::EvictGlobalContentViewer();
   } else if (!strcmp(aTopic, NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID) ||
              !strcmp(aTopic, "memory-pressure")) {
     nsSHistory::EvictAllContentViewersGlobally();
   }
 
   return NS_OK;
 }
 
@@ -222,88 +230,84 @@ nsSHistory::CalcMaxTotalViewers()
   if (viewers > 8) {
     viewers = 8;
   }
   return viewers;
 }
 
 // static
 void
-nsSHistory::UpdatePrefs(nsIPrefBranch *aPrefBranch)
+nsSHistory::UpdatePrefs()
 {
-  aPrefBranch->GetIntPref(PREF_SHISTORY_SIZE, &gHistoryMaxSize);
-  aPrefBranch->GetIntPref(PREF_SHISTORY_MAX_TOTAL_VIEWERS,
-                          &sHistoryMaxTotalViewers);
-  aPrefBranch->GetBoolPref(PREF_SHISTORY_OPTIMIZE_EVICTION,
-                          &gOptimizeEviction);
+  Preferences::GetInt(PREF_SHISTORY_SIZE, &gHistoryMaxSize);
+  Preferences::GetInt(PREF_SHISTORY_MAX_TOTAL_VIEWERS,
+                      &sHistoryMaxTotalViewers);
+  Preferences::GetBool(PREF_SHISTORY_OPTIMIZE_EVICTION, &gOptimizeEviction);
   // If the pref is negative, that means we calculate how many viewers
   // we think we should cache, based on total memory
   if (sHistoryMaxTotalViewers < 0) {
     sHistoryMaxTotalViewers = CalcMaxTotalViewers();
   }
 }
 
 // static
 nsresult
 nsSHistory::Startup()
 {
-  nsCOMPtr<nsIPrefService> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
-  if (prefs) {
-    nsCOMPtr<nsIPrefBranch> sesHBranch;
-    prefs->GetBranch(nsnull, getter_AddRefs(sesHBranch));
-    if (sesHBranch) {
-      UpdatePrefs(sesHBranch);
-    }
-
-    // The goal of this is to unbreak users who have inadvertently set their
-    // session history size to less than the default value.
-    PRInt32  defaultHistoryMaxSize = 50;
-    nsCOMPtr<nsIPrefBranch> defaultBranch;
-    prefs->GetDefaultBranch(nsnull, getter_AddRefs(defaultBranch));
-    if (defaultBranch) {
-      defaultBranch->GetIntPref(PREF_SHISTORY_SIZE, &defaultHistoryMaxSize);
-    }
+  UpdatePrefs();
 
-    if (gHistoryMaxSize < defaultHistoryMaxSize) {
-      gHistoryMaxSize = defaultHistoryMaxSize;
-    }
-    
-    // Allow the user to override the max total number of cached viewers,
-    // but keep the per SHistory cached viewer limit constant
-    nsCOMPtr<nsIPrefBranch2> branch = do_QueryInterface(sesHBranch);
-    if (branch) {
-      nsSHistoryObserver* obs = new nsSHistoryObserver();
-      if (!obs) {
-        return NS_ERROR_OUT_OF_MEMORY;
-      }
-      branch->AddObserver(PREF_SHISTORY_SIZE, obs, PR_FALSE);
-      branch->AddObserver(PREF_SHISTORY_MAX_TOTAL_VIEWERS,
-                          obs, PR_FALSE);
-      branch->AddObserver(PREF_SHISTORY_OPTIMIZE_EVICTION,
-                          obs, PR_FALSE);
+  // The goal of this is to unbreak users who have inadvertently set their
+  // session history size to less than the default value.
+  PRInt32 defaultHistoryMaxSize =
+    Preferences::GetDefaultInt(PREF_SHISTORY_SIZE, 50);
+  if (gHistoryMaxSize < defaultHistoryMaxSize) {
+    gHistoryMaxSize = defaultHistoryMaxSize;
+  }
+  
+  // Allow the user to override the max total number of cached viewers,
+  // but keep the per SHistory cached viewer limit constant
+  if (!gObserver) {
+    gObserver = new nsSHistoryObserver();
+    NS_ADDREF(gObserver);
+    Preferences::AddStrongObservers(gObserver, kObservedPrefs);
 
-      nsCOMPtr<nsIObserverService> obsSvc =
-        mozilla::services::GetObserverService();
-      if (obsSvc) {
-        // Observe empty-cache notifications so tahat clearing the disk/memory
-        // cache will also evict all content viewers.
-        obsSvc->AddObserver(obs,
-                            NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID, PR_FALSE);
+    nsCOMPtr<nsIObserverService> obsSvc =
+      mozilla::services::GetObserverService();
+    if (obsSvc) {
+      // Observe empty-cache notifications so tahat clearing the disk/memory
+      // cache will also evict all content viewers.
+      obsSvc->AddObserver(gObserver,
+                          NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID, PR_FALSE);
 
-        // Same for memory-pressure notifications
-        obsSvc->AddObserver(obs, "memory-pressure", PR_FALSE);
-      }
+      // Same for memory-pressure notifications
+      obsSvc->AddObserver(gObserver, "memory-pressure", PR_FALSE);
     }
   }
 
   // Initialize the global list of all SHistory objects
   PR_INIT_CLIST(&gSHistoryList);
   return NS_OK;
 }
 
+// static
+void
+nsSHistory::Shutdown()
+{
+  if (gObserver) {
+    Preferences::RemoveObservers(gObserver, kObservedPrefs);
+    nsCOMPtr<nsIObserverService> obsSvc =
+      mozilla::services::GetObserverService();
+    if (obsSvc) {
+      obsSvc->RemoveObserver(gObserver, NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID);
+      obsSvc->RemoveObserver(gObserver, "memory-pressure");
+    }
+    NS_RELEASE(gObserver);
+  }
+}
+
 /* Add an entry to the History list at mIndex and 
  * increment the index to point to the new entry
  */
 NS_IMETHODIMP
 nsSHistory::AddEntry(nsISHEntry * aSHEntry, PRBool aPersist)
 {
   NS_ENSURE_ARG(aSHEntry);
 
--- a/docshell/shistory/src/nsSHistory.h
+++ b/docshell/shistory/src/nsSHistory.h
@@ -48,17 +48,16 @@
 #include "nsISHistoryInternal.h"
 #include "nsISHTransaction.h"
 #include "nsIWebNavigation.h"
 #include "nsIWeakReference.h"
 #include "nsISimpleEnumerator.h"
 #include "nsISHistoryListener.h"
 #include "nsIHistoryEntry.h"
 #include "nsIObserver.h"
-#include "nsIPrefBranch2.h"
 
 // Needed to maintain global list of all SHistory objects
 #include "prclist.h"
 
 class nsIDocShell;
 class nsSHEnumerator;
 class nsSHistoryObserver;
 class nsSHistory: public PRCList,
@@ -71,17 +70,18 @@ public:
 
   NS_DECL_ISUPPORTS
   NS_DECL_NSISHISTORY
   NS_DECL_NSISHISTORYINTERNAL
   NS_DECL_NSIWEBNAVIGATION
 
   // One time initialization method called upon docshell module construction
   static nsresult Startup();
-  static void UpdatePrefs(nsIPrefBranch *aPrefBranch);
+  static void Shutdown();
+  static void UpdatePrefs();
 
   // Max number of total cached content viewers.  If the pref
   // browser.sessionhistory.max_total_viewers is negative, then
   // this value is calculated based on the total amount of memory.
   // Otherwise, it comes straight from the pref.
   static PRUint32 GetMaxTotalViewers() { return sHistoryMaxTotalViewers; }
 
 protected: