Bug 1508415 - Convert some remaining cases where MailServices.jsm and Services.jsm can be used in Thunderbird JS files. r=mkmelin
authoraceman <acelists@atlas.sk>
Sat, 01 Dec 2018 06:05:00 +0100
changeset 33854 76501a6119d4b01fc313c94b0e5185afa6bb782e
parent 33853 654b68255a76f5204502f8ad10a2b9febad5a860
child 33855 f51f341a4d9cb315ba830d242e246442458bfb1c
push id388
push userclokep@gmail.com
push dateMon, 28 Jan 2019 20:54:56 +0000
reviewersmkmelin
bugs1508415
Bug 1508415 - Convert some remaining cases where MailServices.jsm and Services.jsm can be used in Thunderbird JS files. r=mkmelin
mail/base/content/nsDragAndDrop.js
mail/base/test/unit/test_windows_font_migration.js
mail/components/preferences/applications.js
mail/test/mozmill/cloudfile/test-cloudfile-add-account-dialog.js
mail/test/mozmill/shared-modules/test-cloudfile-helpers.js
mail/test/mozmill/shared-modules/test-content-tab-helpers.js
mailnews/base/prefs/content/AccountManager.js
mailnews/base/prefs/content/AccountWizard.js
mailnews/base/prefs/content/am-server.js
mailnews/base/prefs/content/aw-accounttype.js
mailnews/base/prefs/content/converterDialog.js
mailnews/base/src/msgOAuth2Module.js
mailnews/base/test/unit/test_nsIMsgFolderListenerLocal.js
mailnews/db/gloda/content/glodacomplete.xml
mailnews/extensions/bayesian-spam-filter/test/unit/test_msgCorpus.js
mailnews/imap/test/unit/test_nsIMsgFolderListenerIMAP.js
mailnews/import/test/unit/test_becky_addressbook.js
mailnews/local/test/unit/test_fileName.js
mailnews/mime/src/jsmime.jsm
mailnews/mime/test/unit/test_structured_headers.js
mailnews/news/test/unit/test_getNewsMessage.js
mailnews/news/test/unit/test_uriParser.js
mailnews/test/resources/msgFolderListenerSetup.js
--- a/mail/base/content/nsDragAndDrop.js
+++ b/mail/base/content/nsDragAndDrop.js
@@ -17,16 +17,18 @@ ChromeUtils.defineModuleGetter(this, "Se
 
 /**
  *  nsTransferable - a wrapper for nsITransferable that simplifies
  *                   javascript clipboard and drag&drop. for use in
  *                   these situations you should use the nsClipboard
  *                   and nsDragAndDrop wrappers for more convenience
  **/
 
+ChromeUtils.import("resource://gre/modules/Services.jsm");
+
 var nsTransferable = {
   /**
    * nsITransferable set (TransferData aTransferData) ;
    *
    * Creates a transferable with data for a list of supported types ("flavours")
    *
    * @param TransferData aTransferData
    *        a javascript object in the format described above
@@ -524,32 +526,30 @@ var nsDragAndDrop = {
       uri = Services.io.newURI(aDraggedText);
     } catch (e) {
     }
 
     if (!uri)
       return;
 
     // aDraggedText is a URI, do the security check.
-    const nsIScriptSecurityManager = Ci.nsIScriptSecurityManager;
-    var secMan = Cc["@mozilla.org/scriptsecuritymanager;1"]
-                   .getService(nsIScriptSecurityManager);
+    var secMan = Services.scriptSecurityManager;
 
     if (!aDragSession)
       aDragSession = this.mDragService.getCurrentSession();
 
     var sourceDoc = aDragSession.sourceDocument;
     // Use "file:///" as the default sourceURI so that drops of file:// URIs
     // are always allowed.
     var principal = sourceDoc ? sourceDoc.nodePrincipal
                               : secMan.createCodebasePrincipal(Services.io.newURI("file:///"), {});
 
     try {
       secMan.checkLoadURIStrWithPrincipal(principal, aDraggedText,
-                                          nsIScriptSecurityManager.STANDARD);
+                                          Ci.nsIScriptSecurityManager.STANDARD);
     } catch (e) {
       // Stop event propagation right here.
       aEvent.stopPropagation();
 
       throw "Drop of " + aDraggedText + " denied.";
     }
   },
 };
--- a/mail/base/test/unit/test_windows_font_migration.js
+++ b/mail/base/test/unit/test_windows_font_migration.js
@@ -109,19 +109,18 @@ var gCTVerifier = makeVerifier({
 var kWindowsVersions = {
   // Windows XP
   "xp": [5.1, gNonCTVerifier],
   // Windows Vista
   "vista": [6.0, gCTVerifier],
 };
 
 function set_windows_version(aVersion) {
-  let sysInfo = Cc["@mozilla.org/system-info;1"]
-                  .getService(Ci.nsIWritablePropertyBag2);
-  sysInfo.setPropertyAsDouble("version", aVersion);
+  Services.sysinfo.QueryInterface(Ci.nsIWritablePropertyBag2)
+          .setPropertyAsDouble("version", aVersion);
 }
 
 /**
  * Encodings to worry about while clearing prefs.
  */
 var kEncodingsToClear = ["x-unicode", "x-western", "x-cyrillic", "el"];
 
 /**
--- a/mail/components/preferences/applications.js
+++ b/mail/components/preferences/applications.js
@@ -19,17 +19,16 @@ var gNodeToObjectMap = new WeakMap();
 
 // CloudFile account tools used by gCloudFileTab.
 ChromeUtils.import("resource:///modules/cloudFileAccounts.js");
 ChromeUtils.import("resource://gre/modules/Services.jsm");
 ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 ChromeUtils.import("resource://gre/modules/AppConstants.jsm");
 
 XPCOMUtils.defineLazyServiceGetters(this, {
-  gCategoryManager: ["@mozilla.org/categorymanager;1", "nsICategoryManager"],
   gHandlerService: ["@mozilla.org/uriloader/handler-service;1", "nsIHandlerService"],
   gMIMEService: ["@mozilla.org/mime;1", "nsIMIMEService"],
 });
 
 // ---------
 // Utilities
 
 function getDisplayNameForFile(aFile) {
--- a/mail/test/mozmill/cloudfile/test-cloudfile-add-account-dialog.js
+++ b/mail/test/mozmill/cloudfile/test-cloudfile-add-account-dialog.js
@@ -23,43 +23,40 @@ ChromeUtils.import('resource:///modules/
 ChromeUtils.import('resource:///modules/iteratorUtils.jsm');
 
 var kCategory = 'cloud-files';
 var kDialogId = 'addCloudFileAccount';
 var kRootURL = collector.addHttpResource('../cloudfile/html', '');
 var kSettingsWithForm = kRootURL + 'settings-with-form.xhtml';
 
 var gOldProviders = {};
-XPCOMUtils.defineLazyServiceGetter(this, 'gCategoryMan',
-                                   '@mozilla.org/categorymanager;1',
-                                   'nsICategoryManager');
 
 function setupModule(module) {
   for (let lib of MODULE_REQUIRES) {
     collector.getModule(lib).installInto(module);
   }
 
   // Save the old providers...
-  for (let entry of fixIterator(gCategoryMan.enumerateCategory(kCategory),
+  for (let entry of fixIterator(Services.catMan.enumerateCategory(kCategory),
                                 Ci.nsISupportsCString)) {
-    let value = gCategoryMan.getCategoryEntry(kCategory, entry.data);
+    let value = Services.catMan.getCategoryEntry(kCategory, entry.data);
     gOldProviders[entry] = value;
   }
 
   // Clear out the old entries
-  gCategoryMan.deleteCategory(kCategory);
+  Services.catMan.deleteCategory(kCategory);
 }
 
 function teardownModule(module) {
   // Clear out any leftover entries.
-  gCategoryMan.deleteCategory(kCategory);
+  Services.catMan.deleteCategory(kCategory);
 
   // Put the old entries back
   for (let [key, value] of Object.entries(gOldProviders))
-    gCategoryMan.addCategoryEntry(kCategory, key, value, false, true);
+    Services.catMan.addCategoryEntry(kCategory, key, value, false, true);
 }
 
 /**
  * Helper function that ensures that we know the number of registered
  * Filelink service providers.
  *
  * @param aNum the number of expected registered Filelink service providers.
  */
--- a/mail/test/mozmill/shared-modules/test-cloudfile-helpers.js
+++ b/mail/test/mozmill/shared-modules/test-cloudfile-helpers.js
@@ -161,40 +161,35 @@ var gMockCloudfileManager = {
 
     let component = new moh.MockObjectRegisterer(
       mockContractID,
       mockCID,
       MockCloudfileProviderGenerator(aID, aOverrides));
 
     this._mock_map[aID] = component;
 
-    gCategoryManager.addCategoryEntry("cloud-files", mockID,
-                                      mockContractID, false, true);
+    Services.catMan.addCategoryEntry("cloud-files", mockID,
+                                     mockContractID, false, true);
     this._mock_map[aID].register();
   },
 
   unregister: function MCM_unregister(aID) {
     if (!aID)
       aID = "default";
 
     if (!(aID in this._mock_map))
       throw Error("No registered mock cloudfile provider with id = " +
                   aID);
 
-    gCategoryManager.deleteCategoryEntry("cloud-files", aID, false);
+    Services.catMan.deleteCategoryEntry("cloud-files", aID, false);
     this._mock_map[aID].unregister();
     delete this._mock_map[aID];
   },
 
   _generateCID: function MCM__generateCID() {
     let uuid = this._uuidService.generateUUID().toString();
     return uuid.replace('{', '').replace('}', '');
   },
 }
 
 XPCOMUtils.defineLazyServiceGetter(gMockCloudfileManager, "_uuidService",
                                    "@mozilla.org/uuid-generator;1",
                                    "nsIUUIDGenerator");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gCategoryManager",
-                                   "@mozilla.org/categorymanager;1",
-                                   "nsICategoryManager");
-
--- a/mail/test/mozmill/shared-modules/test-content-tab-helpers.js
+++ b/mail/test/mozmill/shared-modules/test-content-tab-helpers.js
@@ -464,24 +464,22 @@ function plugins_run_in_separate_process
   else {
     supportsOOPP = Services.prefs.getBoolPref("dom.ipc.plugins.enabled");
   }
 
   return supportsOOPP;
 }
 
 function updateBlocklist(aController, aCallback) {
-  let blocklistNotifier = Cc["@mozilla.org/extensions/blocklist;1"]
-                            .getService(Ci.nsITimerCallback);
   let observer = function() {
     Services.obs.removeObserver(observer, "blocklist-updated");
     aController.window.setTimeout(aCallback, 0);
   };
   Services.obs.addObserver(observer, "blocklist-updated");
-  blocklistNotifier.notify(null);
+  Services.blocklist.QueryInterface(Ci.nsITimerCallback).notify(null);
 }
 
 function setAndUpdateBlocklist(aController, aURL, aCallback) {
   if (!_originalBlocklistURL) {
     _originalBlocklistURL = Services.prefs.getCharPref("extensions.blocklist.url");
   }
   Services.prefs.setCharPref("extensions.blocklist.url", aURL);
   updateBlocklist(aController, aCallback);
--- a/mailnews/base/prefs/content/AccountManager.js
+++ b/mailnews/base/prefs/content/AccountManager.js
@@ -1562,25 +1562,23 @@ var gAccountTree = {
         // Check offline/diskspace support level.
         let diskspace = server.supportsDiskSpace;
         if (server.offlineSupportLevel >= 10 && diskspace)
           panelsToKeep.push(panels[2]);
         else if (diskspace)
           panelsToKeep.push(panels[3]);
 
         // extensions
-        let catMan = Cc["@mozilla.org/categorymanager;1"]
-                       .getService(Ci.nsICategoryManager);
         const CATEGORY = "mailnews-accountmanager-extensions";
-        let catEnum = catMan.enumerateCategory(CATEGORY);
+        let catEnum = Services.catMan.enumerateCategory(CATEGORY);
         while (catEnum.hasMoreElements()) {
           let entryName = null;
           try {
             entryName = catEnum.getNext().QueryInterface(Ci.nsISupportsCString).data;
-            let svc = Cc[catMan.getCategoryEntry(CATEGORY, entryName)]
+            let svc = Cc[Services.catMan.getCategoryEntry(CATEGORY, entryName)]
                         .getService(Ci.nsIMsgAccountManagerExtension);
             if (svc.showPanel(server)) {
               let bundleName = "chrome://" + svc.chromePackageName +
                                "/locale/am-" + svc.name + ".properties";
               let bundle = Services.strings.createBundle(bundleName);
               let title = bundle.GetStringFromName("prefPanel-" + svc.name);
               panelsToKeep.push({string: title, src: "am-" + svc.name + ".xul"});
             }
--- a/mailnews/base/prefs/content/AccountWizard.js
+++ b/mailnews/base/prefs/content/AccountWizard.js
@@ -36,16 +36,17 @@ var okCallback = null;
    accounttype -> identity -> server -> login -> accname -> done
                              \-> newsserver ----/
 
    where the accounttype determines which path to take
    (server vs. newsserver)
 */
 
 ChromeUtils.import("resource:///modules/MailServices.jsm");
+ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 var contentWindow;
 
 var gPageData;
 
 var nsIMsgIdentity = Ci.nsIMsgIdentity;
 var nsIMsgIncomingServer = Ci.nsIMsgIncomingServer;
 var gPrefsBundle, gMessengerBundle;
--- a/mailnews/base/prefs/content/am-server.js
+++ b/mailnews/base/prefs/content/am-server.js
@@ -428,20 +428,18 @@ function folderPickerChange(aEvent)
   var folder = aEvent.target._folder;
   // Since we need to deal with localised folder names, we simply use
   // the path of the URI like we do in nsImapIncomingServer::DiscoveryDone().
   // Note that the path is returned with a leading slash which we need to remove.
   var folderPath = Services.io.newURI(folder.URI).pathQueryRef.substring(1);
   // We need to convert that from MUTF-7 to Unicode.
   var manager = Cc['@mozilla.org/charset-converter-manager;1']
                   .getService(Ci.nsICharsetConverterManager);
-  var util = Cc["@mozilla.org/network/util;1"]
-               .getService(Ci.nsINetUtil);
   var trashUnicode = manager.mutf7ToUnicode(
-    util.unescapeString(folderPath, Ci.nsINetUtil.ESCAPE_URL_PATH));
+    Services.netUtils.unescapeString(folderPath, Ci.nsINetUtil.ESCAPE_URL_PATH));
 
   // Set the value to be persisted.
   document.getElementById("imap.trashFolderName")
           .setAttribute("value", trashUnicode);
 
   // Update the widget to show/do correct things even for subfolders.
   var trashFolderPicker = document.getElementById("msgTrashFolderPicker");
   trashFolderPicker.menupopup.selectFolder(folder);
--- a/mailnews/base/prefs/content/aw-accounttype.js
+++ b/mailnews/base/prefs/content/aw-accounttype.js
@@ -71,18 +71,17 @@ function setupWizardPanels() {
             showServerDetailsOnWizardSummary: true,
             incomingServer: {},
           });
           wizardPanels = ["identitypage", "outgoingpage", "accnamepage"];
           setPageData(pageData, "server", "servertype", "movemail");
           setPageData(pageData, "server", "hostname", "localhost");
           setPageData(pageData, "server", "port", "");
         } else if (pages == "rss") {
-          let accountName = Cc["@mozilla.org/intl/stringbundle;1"]
-                              .getService(Ci.nsIStringBundleService)
+          let accountName = Services.strings
                               .createBundle("chrome://messenger-newsblog/locale/newsblog.properties")
                               .GetStringFromName("feeds-accountname");
           SetCurrentAccountData({
             wizardAccountName: accountName,
             wizardAutoGenerateUniqueHostname: true,
             wizardHideIncoming: true,
             showServerDetailsOnWizardSummary: false,
             incomingServer: {
--- a/mailnews/base/prefs/content/converterDialog.js
+++ b/mailnews/base/prefs/content/converterDialog.js
@@ -33,22 +33,20 @@ var gDeferredAccounts = [];
 var gOriginalOffline;
 /**
  * Place account name in migration dialog modal.
  * @param {nsIMsgIncomingServer} aServer - account server.
  */
 function placeAccountName(aServer) {
   gOriginalOffline = Services.io.offline;
 
-  let bundle = Cc["@mozilla.org/intl/stringbundle;1"]
-    .getService(Ci.nsIStringBundleService)
+  let bundle = Services.strings
     .createBundle("chrome://messenger/locale/converterDialog.properties");
 
-  let brandShortName = Cc["@mozilla.org/intl/stringbundle;1"]
-    .getService(Ci.nsIStringBundleService)
+  let brandShortName = Services.strings
     .createBundle("chrome://branding/locale/brand.properties")
     .GetStringFromName("brandShortName");
 
   // 'deferredToRootFolder' holds path of rootMsgFolder of account to which
   // other accounts have been deferred.
   let deferredToRootFolder = aServer.rootMsgFolder.filePath.path;
   // String to hold names of deferred accounts separated by commas.
   let deferredAccountsString = "";
@@ -163,18 +161,17 @@ function placeAccountName(aServer) {
  * Start the conversion process.
  * @param {String} aSelectedStoreType - mailstore type selected by user.
  * @param {Object} aResponse - response from the migration dialog modal.
  */
 function startContinue(aSelectedStoreType, aResponse) {
   gResponse = aResponse;
   gFolder = gServer.rootFolder.filePath;
 
-  let bundle = Cc["@mozilla.org/intl/stringbundle;1"]
-    .getService(Ci.nsIStringBundleService)
+  let bundle = Services.strings
     .createBundle("chrome://messenger/locale/converterDialog.properties");
 
   document.getElementById("progress").addEventListener("progress", function(e) {
    document.getElementById("progress").value = e.detail;
    document.getElementById("progressPrcnt").innerHTML =
      bundle.formatStringFromName("converterDialog.percentDone", [e.detail], 1);
   });
 
--- a/mailnews/base/src/msgOAuth2Module.js
+++ b/mailnews/base/src/msgOAuth2Module.js
@@ -87,53 +87,48 @@ OAuth2Module.prototype = {
       get: () => this.refreshToken,
       set: (token) => this.refreshToken = token
     });
 
     return true;
   },
 
   get refreshToken() {
-    let loginMgr = Cc["@mozilla.org/login-manager;1"]
-                     .getService(Ci.nsILoginManager);
-    let logins = loginMgr.findLogins({}, this._loginUrl, null, this._scope);
+    let logins = Services.logins.findLogins({}, this._loginUrl, null, this._scope);
     for (let login of logins) {
       if (login.username == this._username)
         return login.password;
     }
     return '';
   },
   set refreshToken(token) {
-    let loginMgr = Cc["@mozilla.org/login-manager;1"]
-                     .getService(Ci.nsILoginManager);
-
     // Check if we already have a login with this username, and modify the
     // password on that, if we do.
-    let logins = loginMgr.findLogins({}, this._loginUrl, null, this._scope);
+    let logins = Services.logins.findLogins({}, this._loginUrl, null, this._scope);
     for (let login of logins) {
       if (login.username == this._username) {
         if (token) {
           let propBag = Cc["@mozilla.org/hash-property-bag;1"].
                         createInstance(Ci.nsIWritablePropertyBag);
           propBag.setProperty("password", token);
-          loginMgr.modifyLogin(login, propBag);
+          Services.logins.modifyLogin(login, propBag);
         }
         else
-          loginMgr.removeLogin(login);
+          Services.logins.removeLogin(login);
         return token;
       }
     }
 
     // Unless the token is null, we need to create and fill in a new login
     if (token) {
       let login = Cc["@mozilla.org/login-manager/loginInfo;1"]
                     .createInstance(Ci.nsILoginInfo);
       login.init(this._loginUrl, null, this._scope, this._username, token,
         '', '');
-      loginMgr.addLogin(login);
+      Services.logins.addLogin(login);
     }
     return token;
   },
 
   connect(aWithUI, aListener) {
     let oauth = this._oauth;
     let promptlistener = {
       onPromptStartAsync: function(callback) {
--- a/mailnews/base/test/unit/test_nsIMsgFolderListenerLocal.js
+++ b/mailnews/base/test/unit/test_nsIMsgFolderListenerLocal.js
@@ -26,17 +26,17 @@ var gMsgFile1, gMsgFile2, gMsgFile3;
 var gRootFolder;
 var gLocalFolder2;
 var gLocalFolder3;
 var gLocalTrashFolder;
 
 // storeIn takes a string containing the variable to store the new folder in
 function addFolder(parent, folderName, storeIn)
 {
-  gExpectedEvents = [[gMFNService.folderAdded, parent, folderName, storeIn]];
+  gExpectedEvents = [[MailServices.mfn.folderAdded, parent, folderName, storeIn]];
   // We won't receive a copy listener notification for this
   gCurrStatus |= kStatus.onStopCopyDone;
   parent.createSubfolder(folderName, null);
   gCurrStatus |= kStatus.functionCallDone;
   if (gCurrStatus == kStatus.everythingDone)
     resetStatusAndProceed();
 }
 
@@ -44,47 +44,47 @@ function addFolder(parent, folderName, s
  * This will introduce a new message to the system which will generate an added
  * notification and subsequently a classification notification.  For the
  * classification because no messages have yet been marked as junk and there
  * are no traits configured, aJunkProcessed and aTraitProcessed will be false.
  */
 function copyFileMessage(file, destFolder, isDraftOrTemplate)
 {
   copyListener.mFolderStoredIn = destFolder;
-  gExpectedEvents = [[gMFNService.msgAdded, gHdrsReceived],
-                     [gMFNService.msgsClassified, gHdrsReceived, false, false]];
+  gExpectedEvents = [[MailServices.mfn.msgAdded, gHdrsReceived],
+                     [MailServices.mfn.msgsClassified, gHdrsReceived, false, false]];
   gCopyService.CopyFileMessage(file, destFolder, null, isDraftOrTemplate, 0, "",
                                copyListener, null);
   gCurrStatus |= kStatus.functionCallDone;
   if (gCurrStatus == kStatus.everythingDone)
     resetStatusAndProceed();
 }
 
 function copyMessages(items, isMove, srcFolder, destFolder)
 {
   var array = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
   items.forEach(function (item) {
     array.appendElement(item);
   });
   gExpectedEvents = [
-    [gMFNService.msgsMoveCopyCompleted, isMove, items, destFolder, true]];
+    [MailServices.mfn.msgsMoveCopyCompleted, isMove, items, destFolder, true]];
   gCopyService.CopyMessages(srcFolder, array, destFolder, isMove, copyListener,
                             null, true);
   gCurrStatus |= kStatus.functionCallDone;
   if (gCurrStatus == kStatus.everythingDone)
     resetStatusAndProceed();
 }
 
 function copyFolders(items, isMove, destFolder)
 {
   var array = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
   items.forEach(function (item) {
     array.appendElement(item);
   });
-  gExpectedEvents = [[gMFNService.folderMoveCopyCompleted, isMove, items, destFolder]];
+  gExpectedEvents = [[MailServices.mfn.folderMoveCopyCompleted, isMove, items, destFolder]];
   gCopyService.CopyFolders(array, destFolder, isMove, copyListener, null);
   gCurrStatus |= kStatus.functionCallDone;
   if (gCurrStatus == kStatus.everythingDone)
     resetStatusAndProceed();
 }
 
 function deleteMessages(srcFolder, items, deleteStorage, isMove)
 {
@@ -94,32 +94,32 @@ function deleteMessages(srcFolder, items
   });
   // We should only get the delete notification only if we are not moving, and are deleting from
   // the storage/trash. We should get only the move/copy notification if we aren't.
   var isTrashFolder = srcFolder.getFlag(Ci.nsMsgFolderFlags.Trash);
   if (!isMove && (deleteStorage || isTrashFolder))
   {
     // We won't be getting any OnStopCopy notification in this case
     gCurrStatus = kStatus.onStopCopyDone;
-    gExpectedEvents = [[gMFNService.msgsDeleted, items]];
+    gExpectedEvents = [[MailServices.mfn.msgsDeleted, items]];
   }
   else
     // We have to be getting a move notification, even if isMove is false
-    gExpectedEvents = [[gMFNService.msgsMoveCopyCompleted, true, items,
+    gExpectedEvents = [[MailServices.mfn.msgsMoveCopyCompleted, true, items,
                         gLocalTrashFolder, true]];
 
   srcFolder.deleteMessages(array, null, deleteStorage, isMove, copyListener, true);
   gCurrStatus |= kStatus.functionCallDone;
   if (gCurrStatus == kStatus.everythingDone)
     resetStatusAndProceed();
 }
 
 function renameFolder(folder, newName)
 {
-  gExpectedEvents = [[gMFNService.folderRenamed, [folder], newName]];
+  gExpectedEvents = [[MailServices.mfn.folderRenamed, [folder], newName]];
   gCurrStatus = kStatus.onStopCopyDone;
   folder.rename(newName, null);
   gCurrStatus |= kStatus.functionCallDone;
   if (gCurrStatus == kStatus.everythingDone)
     resetStatusAndProceed();
 }
 
 function deleteFolder(folder, child)
@@ -130,32 +130,34 @@ function deleteFolder(folder, child)
   // We won't be getting any OnStopCopy notification at all
   // XXX delete to trash should get one, but we'll need to pass the listener
   // somehow to deleteSubFolders
   gCurrStatus = kStatus.onStopCopyDone;
   // If ancestor is trash, expect a folderDeleted, otherwise expect
   // a folderMoveCopyCompleted.
   if (gLocalTrashFolder.isAncestorOf(folder))
     if (child)
-      gExpectedEvents = [[gMFNService.folderDeleted, [child]], [gMFNService.folderDeleted, [folder]]];
+      gExpectedEvents = [[MailServices.mfn.folderDeleted, [child]],
+                         [MailServices.mfn.folderDeleted, [folder]]];
     else
-      gExpectedEvents = [[gMFNService.folderDeleted, [folder]]];
+      gExpectedEvents = [[MailServices.mfn.folderDeleted, [folder]]];
   else
-    gExpectedEvents = [[gMFNService.folderMoveCopyCompleted, true, [folder], gLocalTrashFolder]];
+    gExpectedEvents = [[MailServices.mfn.folderMoveCopyCompleted, true,
+                        [folder], gLocalTrashFolder]];
 
   folder.parent.deleteSubFolders(array, null);
   gCurrStatus |= kStatus.functionCallDone;
   if (gCurrStatus == kStatus.everythingDone)
     resetStatusAndProceed();
 }
 
 function compactFolder(folder)
 {
-  gExpectedEvents = [[gMFNService.itemEvent, folder, "FolderCompactStart"],
-                     [gMFNService.itemEvent, folder, "FolderCompactFinish"]];
+  gExpectedEvents = [[MailServices.mfn.itemEvent, folder, "FolderCompactStart"],
+                     [MailServices.mfn.itemEvent, folder, "FolderCompactFinish"]];
   // We won't receive a copy listener notification for this
   gCurrStatus |= kStatus.onStopCopyDone;
   folder.compact(null, null);
   gCurrStatus |= kStatus.functionCallDone;
   if (gCurrStatus == kStatus.everythingDone)
     resetStatusAndProceed();
 }
 
@@ -302,17 +304,17 @@ var gTestArray =
 ];
   // Folder structure should just be
   // Inbox
   // Trash
 
 function run_test()
 {
   // Add a listener.
-  gMFNService.addListener(gMFListener, allTestedEvents);
+  MailServices.mfn.addListener(gMFListener, allTestedEvents);
 
   localAccountUtils.loadLocalMailAccount();
 
   // Load up some messages so that we can copy them in later.
   gMsgFile1 = do_get_file("../../../data/bugmail10");
   gMsgFile2 = do_get_file("../../../data/bugmail11");
   gMsgFile3 = do_get_file("../../../data/draft1");
 
@@ -341,12 +343,12 @@ function doTest(test)
       );
     dump("=== Test: " + testFn.name + "\n");
     testFn();
   }
   else
   {
     gHdrsReceived = null;
     gMsgHdrs = null;
-    gMFNService.removeListener(gMFListener);
+    MailServices.mfn.removeListener(gMFListener);
     do_test_finished(); // for the one in run_test()
   }
 }
--- a/mailnews/db/gloda/content/glodacomplete.xml
+++ b/mailnews/db/gloda/content/glodacomplete.xml
@@ -7,16 +7,22 @@
 <bindings id="autocompleteBindings"
           xmlns="http://www.mozilla.org/xbl"
           xmlns:html="http://www.w3.org/1999/xhtml"
           xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
           xmlns:xbl="http://www.mozilla.org/xbl">
 
   <binding id="glodacomplete-rich-result-popup" extends="chrome://global/content/bindings/autocomplete.xml#autocomplete-rich-result-popup">
     <implementation implements="nsIAutoCompletePopup">
+      <constructor>
+        <![CDATA[
+          ChromeUtils.import("resource://gre/modules/Services.jsm");
+          ]]>
+      </constructor>
+
       <method name="_appendCurrentResult">
         <body>
           <![CDATA[
           var controller = this.mInput.controller;
 
           // Process maxRows per chunk to improve performance and user experience
           for (let i = 0; i < this.maxRows; i++) {
             if (this._currentIndex >= this.matchCount)
@@ -24,19 +30,18 @@
 
             var existingItemsCount = this.richlistbox.childNodes.length;
             var item;
 
             // trim the leading/trailing whitespace
             var trimmedSearchString = controller.searchString.trim();
 
             // Unescape the URI spec for showing as an entry in the popup
-            let url = Cc["@mozilla.org/intl/texttosuburi;1"]
-                        .getService(Ci.nsITextToSubURI)
-                        .unEscapeURIForUI("UTF-8", controller.getValueAt(this._currentIndex));
+            let url = Services.textToSubURI
+                              .unEscapeURIForUI("UTF-8", controller.getValueAt(this._currentIndex));
 
             // Unlike our superclass, we create nodes every time because we have
             //  heterogeneous results and we cannot rely on the XBL bindings to
             //  to change fast enough.
             item = document.createElementNS("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", "richlistitem");
 
             let glodaCompleter = Cc["@mozilla.org/autocomplete/search;1?name=gloda"]
                                    .getService(Ci.nsIAutoCompleteSearch)
--- a/mailnews/extensions/bayesian-spam-filter/test/unit/test_msgCorpus.js
+++ b/mailnews/extensions/bayesian-spam-filter/test/unit/test_msgCorpus.js
@@ -1,17 +1,17 @@
 /* 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/. */
 
 // Tests corpus management functions using nsIMsgCorpus
 
-var msgCorpus =
-  Cc["@mozilla.org/messenger/filter-plugin;1?name=bayesianfilter"]
-    .getService(Ci.nsIMsgCorpus);
+ChromeUtils.import("resource:///modules/MailServices.jsm");
+
+var msgCorpus = MailServices.junk.QueryInterface(Ci.nsIMsgCorpus);
 
 // tokens found in the test corpus file. trait 1001 was trained with
 // 2 messages, and trait 1003 with 1.
 
 var tokenData = [
 // [traitid, count, token]
   [1001, 0, "iDoNotExist"],
   [1001, 1, "linecount"],
--- a/mailnews/imap/test/unit/test_nsIMsgFolderListenerIMAP.js
+++ b/mailnews/imap/test/unit/test_nsIMsgFolderListenerIMAP.js
@@ -36,17 +36,17 @@ var gMsgId3 = "4849BF7B.2030800@example.
 var gMsgId4 = "bugmail7.m47LtAEf007542@mrapp51.mozilla.org";
 var gMsgId5 = "bugmail6.m47LtAEf007542@mrapp51.mozilla.org";
 var gMsgWindow = Cc["@mozilla.org/messenger/msgwindow;1"]
                   .createInstance(Ci.nsIMsgWindow);
 
 
 function addFolder(parent, folderName, storeIn)
 {
-  gExpectedEvents = [[gMFNService.folderAdded, parent, folderName, storeIn]];
+  gExpectedEvents = [[MailServices.mfn.folderAdded, parent, folderName, storeIn]];
   // No copy listener notification for this
   gCurrStatus |= kStatus.onStopCopyDone;
   parent.createSubfolder(folderName, null);
   gCurrStatus |= kStatus.functionCallDone;
   gServer.performTest("LIST");
   if (gCurrStatus == kStatus.everythingDone)
     resetStatusAndProceed();
 }
@@ -61,18 +61,18 @@ function copyFileMessage(file, messageId
   // the copy listener, without which it will *not* send the notification.
 
   // ...but wait, nsImapProtocol.cpp requires SEARCH afterwards to retrieve the
   // message header, and fakeserver doesn't implement it yet. So get it to fail
   // earlier by *not* sending the message id.
   // copyListener.mMessageId = messageId;
 
   // Instead store the message id in gExpectedEvents, so we can match that up
-  gExpectedEvents = [[gMFNService.msgAdded, {expectedMessageId: messageId}],
-                     [gMFNService.msgsClassified, [messageId], false, false]];
+  gExpectedEvents = [[MailServices.mfn.msgAdded, {expectedMessageId: messageId}],
+                     [MailServices.mfn.msgsClassified, [messageId], false, false]];
   destFolder.updateFolder(null);
   gCopyService.CopyFileMessage(file, destFolder, null, true, 0, "", copyListener, null);
   gCurrStatus |= kStatus.functionCallDone;
   gServer.performTest("APPEND");
   // Allow some time for the append operation to complete, so update folder
   // every second
   gFolderBeingUpdated = destFolder;
   doUpdateFolder(gTest);
@@ -98,19 +98,19 @@ function addMessagesToServer(messages, m
 {
   // For every message we have, we need to convert it to a file:/// URI
   messages.forEach(function (message)
   {
     let URI = Services.io.newFileURI(message.file).QueryInterface(Ci.nsIFileURL);
     // Create the imapMessage and store it on the mailbox.
     mailbox.addMessage(new imapMessage(URI.spec, mailbox.uidnext++, []));
     // We can't get the headers again, so just pass on the message id
-    gExpectedEvents.push([gMFNService.msgAdded, {expectedMessageId: message.messageId}]);
+    gExpectedEvents.push([MailServices.mfn.msgAdded, {expectedMessageId: message.messageId}]);
   });
-  gExpectedEvents.push([gMFNService.msgsClassified,
+  gExpectedEvents.push([MailServices.mfn.msgsClassified,
                         messages.map(hdr => hdr.messageId),
                         false, false]);
 
   // No copy listener notification for this
   gCurrStatus |= kStatus.functionCallDone | kStatus.onStopCopyDone;
 
   gFolderBeingUpdated = localFolder;
   doUpdateFolder(gTest);
@@ -118,29 +118,29 @@ function addMessagesToServer(messages, m
 
 function copyMessages(messages, isMove, srcFolder, destFolder)
 {
   let array = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
   messages.forEach(function (message)
   {
     array.appendElement(message);
   });
-  gExpectedEvents = [[gMFNService.msgsMoveCopyCompleted, isMove, messages, destFolder, true]];
+  gExpectedEvents = [[MailServices.mfn.msgsMoveCopyCompleted, isMove, messages, destFolder, true]];
   // We'll also get the msgAdded events when we go and update the destination
   // folder
   messages.forEach(function (message)
   {
     // We can't use the headers directly, because the notifications we'll
     // receive are for message headers in the destination folder
-    gExpectedEvents.push([gMFNService.msgKeyChanged,
+    gExpectedEvents.push([MailServices.mfn.msgKeyChanged,
                           {expectedMessageId: message.messageId}]);
-    gExpectedEvents.push([gMFNService.msgAdded,
+    gExpectedEvents.push([MailServices.mfn.msgAdded,
                           {expectedMessageId: message.messageId}]);
   });
-  gExpectedEvents.push([gMFNService.msgsClassified,
+  gExpectedEvents.push([MailServices.mfn.msgsClassified,
                         messages.map(hdr => hdr.messageId),
                         false, false]);
   gCopyService.CopyMessages(srcFolder, array, destFolder, isMove, copyListener, gMsgWindow, true);
   gCurrStatus |= kStatus.functionCallDone;
 
   gServer.performTest("COPY");
 
   gFolderBeingUpdated = destFolder;
@@ -187,17 +187,17 @@ var gTestArray =
 ];
 
 function run_test()
 {
   // This is before any of the actual tests, so...
   gTest = 0;
 
   // Add a listener.
-  gMFNService.addListener(gMFListener, allTestedEvents);
+  MailServices.mfn.addListener(gMFListener, allTestedEvents);
   gIMAPDaemon = new imapDaemon();
   gServer = makeServer(gIMAPDaemon, "");
 
   gIMAPIncomingServer = createLocalIMAPServer(gServer.port);
 
   // Also make sure a local folders server is created, as that's what is used
   // for sent items
   localAccountUtils.loadLocalMailAccount();
@@ -227,17 +227,17 @@ function run_test()
   Services.prefs.setBoolPref("mail.server.server1.download_on_biff", false);
 
   // Get the server list...
   gIMAPIncomingServer.performExpand(null);
 
   // We get these notifications on initial discovery
   gRootFolder = gIMAPIncomingServer.rootFolder;
   gIMAPInbox = gRootFolder.getChildNamed("Inbox");
-  gExpectedEvents = [[gMFNService.folderAdded, gRootFolder, "Trash",
+  gExpectedEvents = [[MailServices.mfn.folderAdded, gRootFolder, "Trash",
                      "gIMAPTrashFolder"]];
   gCurrStatus |= kStatus.onStopCopyDone | kStatus.functionCallDone;
 
   gServer.performTest("SUBSCRIBE");
 
   // "Master" do_test_pending(), paired with a do_test_finished() at the end of
   // all the operations.
   do_test_pending();
@@ -256,17 +256,17 @@ function doTest(test)
           do_throw("Notifications not received in 10000 ms for operation " + testFn.name +
             ", current status is " + gCurrStatus);
         }
       );
     testFn();
   }
   else
   {
-    gMFNService.removeListener(gMFListener);
+    MailServices.mfn.removeListener(gMFListener);
     // Cleanup, null out everything, close all cached connections and stop the
     // server
     gRootFolder = null;
     gIMAPInbox.msgDatabase = null;
     gIMAPInbox = null;
     gIMAPFolder2 = null;
     gIMAPFolder3 = null;
     gIMAPTrashFolder = null;
--- a/mailnews/import/test/unit/test_becky_addressbook.js
+++ b/mailnews/import/test/unit/test_becky_addressbook.js
@@ -1,13 +1,15 @@
+ChromeUtils.import("resource:///modules/MailServices.jsm");
+
 function run_test()
 {
   // Due to the import code using nsIAbManager off the main thread, we need
   // to ensure that it is initialized before we start the main test.
-  let abMgr = Cc["@mozilla.org/abmanager;1"].getService(Ci.nsIAbManager);
+  let abMgr = MailServices.ab;
 
   let file = do_get_file("resources/becky/addressbooks");
   let helper = new AbImportHelper(file, "Becky!", "addressbooks",
                                   "becky_addressbook");
   let vcfSupportedAttributes =
     ["FirstName", "LastName", "DisplayName", "NickName", "PrimaryEmail",
      "SecondEmail", "WorkPhone", "HomePhone", "FaxNumber", "PagerNumber",
      "CellularNumber", "HomeAddress", "HomeAddress2", "HomeCity", "HomeState",
--- a/mailnews/local/test/unit/test_fileName.js
+++ b/mailnews/local/test/unit/test_fileName.js
@@ -3,17 +3,17 @@
  * Test handling of special chars in folder names
  */
 
 ChromeUtils.import("resource:///modules/MailServices.jsm");
 ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 function run_test() {
   let testFolderName = "";
-  let OSname = Cc["@mozilla.org/system-info;1"].getService(Ci.nsIPropertyBag2).getProperty("name");
+  let OSname = Services.sysinfo.getProperty("name");
   if (OSname == "Windows_NT") {
     // On Windows test file with ' ' in the name.
     testFolderName = "bugmail 1";
   } else if (OSname == "Linux") {
     // On Linux test file with '`' in the name.
     testFolderName = "bugmail`1";
   } else if (OSname == "Darwin") {
     // On Mac test file with ':' in the name (generated from Mozilla 1.8 branch).
--- a/mailnews/mime/src/jsmime.jsm
+++ b/mailnews/mime/src/jsmime.jsm
@@ -58,24 +58,21 @@ function MimeTextDecoder(charset, option
 
 
 // The following code loads custom MIME encoders.
 var CATEGORY_NAME = "custom-mime-encoder";
 Services.obs.addObserver(function (subject, topic, data) {
   subject = subject.QueryInterface(Ci.nsISupportsCString)
                    .data;
   if (data == CATEGORY_NAME) {
-    let url = catman.getCategoryEntry(CATEGORY_NAME, subject);
+    let url = Services.catMan.getCategoryEntry(CATEGORY_NAME, subject);
     Services.scriptloader.loadSubScript(url, {}, "UTF-8");
   }
 }, "xpcom-category-entry-added");
 
-var catman = Cc["@mozilla.org/categorymanager;1"]
-               .getService(Ci.nsICategoryManager);
-
-var entries = catman.enumerateCategory(CATEGORY_NAME);
+var entries = Services.catMan.enumerateCategory(CATEGORY_NAME);
 while (entries.hasMoreElements()) {
   let string = entries.getNext()
                       .QueryInterface(Ci.nsISupportsCString)
                       .data;
-  let url = catman.getCategoryEntry(CATEGORY_NAME, string);
+  let url = Services.catMan.getCategoryEntry(CATEGORY_NAME, string);
   Services.scriptloader.loadSubScript(url, {}, "UTF-8");
 }
--- a/mailnews/mime/test/unit/test_structured_headers.js
+++ b/mailnews/mime/test/unit/test_structured_headers.js
@@ -51,19 +51,18 @@ add_task(async function check_custom_hea
     function observer(subject, topic, data) {
       Assert.equal(topic, "xpcom-category-entry-added");
       Assert.equal(data, "custom-mime-encoder");
       resolve();
       Services.obs.removeObserver(observer, "xpcom-category-entry-added");
     }
     Services.obs.addObserver(observer, "xpcom-category-entry-added");
   });
-  Cc["@mozilla.org/categorymanager;1"]
-    .getService(Ci.nsICategoryManager)
-    .addCategoryEntry("custom-mime-encoder", "X-Unusual", url, false, true);
+  Services.catMan
+          .addCategoryEntry("custom-mime-encoder", "X-Unusual", url, false, true);
   // The category manager doesn't fire until a later timestep.
   await promise;
   let headers = new StructuredHeaders();
   headers.setRawHeader("X-Unusual", "10", null);
   Assert.equal(headers.getHeader("X-Unusual"), 16);
   headers.setHeader("X-Unusual", 32);
   Assert.equal(headers.getRawHeader("X-Unusual"), "20");
 });
--- a/mailnews/news/test/unit/test_getNewsMessage.js
+++ b/mailnews/news/test/unit/test_getNewsMessage.js
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /*
  * Tests:
  * - getNewMessages for a newsgroup folder (single message).
  * - DisplayMessage for a newsgroup message
  *   - Downloading a single message and checking content in stream is correct.
  */
 
+ChromeUtils.import("resource:///modules/MailServices.jsm");
 ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 
 // The basic daemon to use for testing nntpd.js implementations
 var daemon = setupNNTPDaemon();
 
 var server;
 var localserver;
 
@@ -77,18 +78,17 @@ function run_test() {
     Assert.ok(folder.hasNewMessages);
 
     server.resetTest();
 
     var message = folder.firstNewMessage;
 
     var messageUri = folder.getUriForMsg(message);
 
-    var nntpService = Cc["@mozilla.org/messenger/nntpservice;1"]
-      .getService(Ci.nsIMsgMessageService);
+    var nntpService = MailServices.nntp.QueryInterface(Ci.nsIMsgMessageService);
 
     do_test_pending();
 
     nntpService.DisplayMessage(messageUri, streamListener, null, null, null, {});
   } catch (e) {
     server.stop();
     do_throw(e);
   }
--- a/mailnews/news/test/unit/test_uriParser.js
+++ b/mailnews/news/test/unit/test_uriParser.js
@@ -1,11 +1,12 @@
 // Tests nsINntpUrl parsing.
 
 ChromeUtils.import("resource://gre/modules/Services.jsm");
+ChromeUtils.import("resource:///modules/MailServices.jsm");
 
 var localserver;
 var tests = [
   // news://host/-based URIs
   { uri: "news://localhost/?newgroups",
     get server() { return localserver; },
     folder: null,
     newsAction: Ci.nsINntpUrl.ActionListNewGroups
@@ -136,18 +137,17 @@ var invalid_uris = [
   "nntp://localhost/a.group/hello",
   "nntp://localhost/a.group/0",
   "nntp:a.group"
 ];
 
 function run_test() {
   // We're not running the server, just setting it up
   localserver = setupLocalServer(119);
-  let nntpService = Cc["@mozilla.org/messenger/nntpservice;1"]
-                      .getService(Ci.nsIProtocolHandler);
+  let nntpService = MailServices.nntp.QueryInterface(Ci.nsIProtocolHandler);
   for (let test of tests) {
     dump("Checking URL " + test.uri + "\n");
     let url = nntpService.newURI(test.uri);
     url.QueryInterface(Ci.nsIMsgMailNewsUrl);
     url.QueryInterface(Ci.nsINntpUrl);
     for (let prop in test) {
       if (prop == "uri")
         continue;
--- a/mailnews/test/resources/msgFolderListenerSetup.js
+++ b/mailnews/test/resources/msgFolderListenerSetup.js
@@ -1,28 +1,21 @@
 ChromeUtils.import("resource:///modules/MailServices.jsm");
 
-var nsIMsgDBHdr = Ci.nsIMsgDBHdr;
-var nsIArray = Ci.nsIArray;
-var nsIMsgFolder = Ci.nsIMsgFolder;
-
-var gMFNService = Cc["@mozilla.org/messenger/msgnotificationservice;1"]
-                      .getService(Ci.nsIMsgFolderNotificationService);
-
 var allTestedEvents =
-  gMFNService.msgAdded |
-  gMFNService.msgsClassified |
-  gMFNService.msgsDeleted |
-  gMFNService.msgsMoveCopyCompleted |
-  gMFNService.msgKeyChanged |
-  gMFNService.folderAdded |
-  gMFNService.folderDeleted |
-  gMFNService.folderMoveCopyCompleted |
-  gMFNService.folderRenamed |
-  gMFNService.itemEvent;
+  MailServices.mfn.msgAdded |
+  MailServices.mfn.msgsClassified |
+  MailServices.mfn.msgsDeleted |
+  MailServices.mfn.msgsMoveCopyCompleted |
+  MailServices.mfn.msgKeyChanged |
+  MailServices.mfn.folderAdded |
+  MailServices.mfn.folderDeleted |
+  MailServices.mfn.folderMoveCopyCompleted |
+  MailServices.mfn.folderRenamed |
+  MailServices.mfn.itemEvent;
 
 var gCopyService = MailServices.copy;
 
 // Current test being executed
 var gTest = 1;
 
 // Which events are expected
 var gExpectedEvents;
@@ -43,135 +36,135 @@ var gHdrsReceived = new Array();
 
 var gMsgHdrs = new Array();
 
 // Our listener, which captures events and verifies them as they are received.
 var gMFListener =
 {
   msgAdded: function(aMsg)
   {
-    verify([gMFNService.msgAdded, aMsg]);
+    verify([MailServices.mfn.msgAdded, aMsg]);
     // We might not actually have a header in gHdrsReceived in the IMAP case,
     // so use the aMsg we got instead
     gMsgHdrs.push({hdr: aMsg, ID: aMsg.messageId});
     if (gExpectedEvents.length == 0)
     {
       gCurrStatus |= kStatus.notificationsDone;
       if (gCurrStatus == kStatus.everythingDone)
         resetStatusAndProceed();
     }
-    else if (gExpectedEvents[0][0] == gMFNService.msgsClassified)
+    else if (gExpectedEvents[0][0] == MailServices.mfn.msgsClassified)
     {
       // XXX this is a hack to deal with limitations of the classification logic
       //  and the new list.  We want to issue a call to clear the list once all
       //  the messages have been added, which would be when the next expected
       //  event is msgsClassified.  (The limitation is that if we don't do this,
       //  we can end up getting told about this message again later.)
       aMsg.folder.clearNewMessages();
     }
   },
 
   msgsClassified: function(aMsgs, aJunkProcessed, aTraitProcessed)
   {
     dump("classified id: " + aMsgs.queryElementAt(0, Ci.nsIMsgDBHdr).messageId + "\n");
-    verify([gMFNService.msgsClassified, aMsgs, aJunkProcessed,
+    verify([MailServices.mfn.msgsClassified, aMsgs, aJunkProcessed,
               aTraitProcessed]);
     if (gExpectedEvents.length == 0)
     {
       gCurrStatus |= kStatus.notificationsDone;
       if (gCurrStatus == kStatus.everythingDone)
         resetStatusAndProceed();
     }
   },
 
   msgsDeleted: function(aMsgs)
   {
-    verify([gMFNService.msgsDeleted, aMsgs]);
+    verify([MailServices.mfn.msgsDeleted, aMsgs]);
     if (gExpectedEvents.length == 0)
     {
       gCurrStatus |= kStatus.notificationsDone;
       if (gCurrStatus == kStatus.everythingDone)
         resetStatusAndProceed();
     }
   },
 
   msgsMoveCopyCompleted: function(aMove, aSrcMsgs, aDestFolder, aDestMsgs)
   {
-    verify([gMFNService.msgsMoveCopyCompleted, aMove, aSrcMsgs, aDestFolder,
+    verify([MailServices.mfn.msgsMoveCopyCompleted, aMove, aSrcMsgs, aDestFolder,
             aDestMsgs]);
     if (gExpectedEvents.length == 0)
     {
       gCurrStatus |= kStatus.notificationsDone;
       if (gCurrStatus == kStatus.everythingDone)
         resetStatusAndProceed();
     }
   },
 
   msgKeyChanged: function(aOldKey, aNewMsgHdr)
   {
-    verify([gMFNService.msgKeyChanged, aOldKey, aNewMsgHdr]);
+    verify([MailServices.mfn.msgKeyChanged, aOldKey, aNewMsgHdr]);
     if (gExpectedEvents.length == 0)
     {
       gCurrStatus |= kStatus.notificationsDone;
       if (gCurrStatus == kStatus.everythingDone)
         resetStatusAndProceed();
     }
   },
 
   folderAdded: function(aFolder)
   {
-    verify([gMFNService.folderAdded, aFolder]);
+    verify([MailServices.mfn.folderAdded, aFolder]);
     if (gExpectedEvents.length == 0)
     {
       gCurrStatus |= kStatus.notificationsDone;
       if (gCurrStatus == kStatus.everythingDone)
         resetStatusAndProceed();
     }
   },
 
   folderDeleted: function(aFolder)
   {
-    verify([gMFNService.folderDeleted, aFolder]);
+    verify([MailServices.mfn.folderDeleted, aFolder]);
     if (gExpectedEvents.length == 0)
     {
       gCurrStatus |= kStatus.notificationsDone;
       if (gCurrStatus == kStatus.everythingDone)
         resetStatusAndProceed();
     }
   },
 
   folderMoveCopyCompleted: function(aMove, aSrcFolder, aDestFolder)
   {
-    verify([gMFNService.folderMoveCopyCompleted, aMove, aSrcFolder, aDestFolder]);
+    verify([MailServices.mfn.folderMoveCopyCompleted, aMove, aSrcFolder, aDestFolder]);
     if (gExpectedEvents.length == 0)
     {
       gCurrStatus |= kStatus.notificationsDone;
       if (gCurrStatus == kStatus.everythingDone)
         resetStatusAndProceed();
     }
   },
 
   folderRenamed: function(aOrigFolder, aNewFolder)
   {
-    verify([gMFNService.folderRenamed, aOrigFolder, aNewFolder]);
+    verify([MailServices.mfn.folderRenamed, aOrigFolder, aNewFolder]);
     if (gExpectedEvents.length == 0)
     {
       gCurrStatus |= kStatus.notificationsDone;
       if (gCurrStatus == kStatus.everythingDone)
         resetStatusAndProceed();
     }
   },
 
   itemEvent: function(aFolder, aEvent, aBetterBeNull, aBetterBeEmpty)
   {
     // we currently require the third argument to be null, and the fourth to be
     // empty...
     Assert.equal(aBetterBeNull, null);
     Assert.equal(aBetterBeEmpty, "");
-    verify([gMFNService.itemEvent, aFolder, aEvent]);
+    verify([MailServices.mfn.itemEvent, aFolder, aEvent]);
     if (gExpectedEvents.length == 0)
     {
       gCurrStatus |= kStatus.notificationsDone;
       if (gCurrStatus == kStatus.everythingDone)
         resetStatusAndProceed();
     }
   }
 };
@@ -211,44 +204,44 @@ function resetStatusAndProceed()
   // to return
   do_timeout(0, function(){doTest(++gTest);});
 }
 
 // Checks whether the array returned from a function has exactly these elements.
 function hasExactlyElements(array, elements)
 {
   // If an nsIArray (it could also be a single header or a folder)
-  if (elements instanceof nsIArray)
+  if (elements instanceof Ci.nsIArray)
   {
     var count = elements.length;
 
     // Check: array sizes should be equal.
     Assert.equal(count, array.length);
 
     for (var i = 0; i < count; i++)
     {
       // Check: query element, must be a header or folder and present in the array
       var currElement;
       try {
-        currElement = elements.queryElementAt(i, nsIMsgDBHdr);
+        currElement = elements.queryElementAt(i, Ci.nsIMsgDBHdr);
       }
       catch (e) {}
       if (!currElement)
       {
         try {
-          currElement = elements.queryElementAt(i, nsIMsgFolder);
+          currElement = elements.queryElementAt(i, Ci.nsIMsgFolder);
         }
         catch (e) {}
       }
       Assert.notEqual(currElement, undefined);
       Assert.notEqual(mailTestUtils.non_strict_index_of(array, currElement), -1);
     }
   }
   // If a single header or a folder
-  else if (elements instanceof nsIMsgDBHdr || elements instanceof nsIMsgFolder)
+  else if (elements instanceof Ci.nsIMsgDBHdr || elements instanceof Ci.nsIMsgFolder)
   {
     // Check: there should be only one element in the array.
     Assert.equal(array.length, 1);
 
     // Check: the element should be present
     Assert.notEqual(mailTestUtils.non_strict_index_of(array, elements), -1);
   }
   // This shouldn't happen
@@ -266,104 +259,104 @@ function verify(event)
   // Check: events match.
   var eventType = expected[0];
   Assert.equal(event[0], eventType);
 
   dump("..... Verifying event type " + eventType + "\n");
 
   switch (eventType)
   {
-  case gMFNService.msgAdded:
+  case MailServices.mfn.msgAdded:
     // So for IMAP right now, we aren't able to get the actual nsIMsgDBHdr.
     // Instead, we'll match up message ids as a (poor?) substitute.
     if (expected[1].expectedMessageId)
     {
       Assert.equal(event[1].messageId, expected[1].expectedMessageId);
       break;
     }
     // If we do have a header, fall through to the case below
-  case gMFNService.msgsDeleted:
-  case gMFNService.folderDeleted:
+  case MailServices.mfn.msgsDeleted:
+  case MailServices.mfn.folderDeleted:
     // Check: headers match/folder matches.
     hasExactlyElements(expected[1], event[1]);
     break;
-  case gMFNService.msgsClassified:
+  case MailServices.mfn.msgsClassified:
     // In the IMAP case expected[1] is a list of mesage-id strings whereas in
     // the local case (where we are copying from files), we actually have
     // the headers.
     if (typeof(expected[1][0]) == "string") { // IMAP; message id strings
       // The IMAP case has additional complexity in that the 'new message'
       // list is not tailored to our needs and so may over-report about
       // new messagse.  So to deal with this we make sure the msgsClassified
       // event is telling us about at least the N expected events and that
       // the last N of these events match
       if (event[1].length < expected[1].length)
         do_throw("Not enough reported classified messages.");
       let ignoreCount = event[1].length - expected[1].length;
       for (let i = 0; i < expected[1].length; i++) {
         let eventHeader = event[1].queryElementAt(i + ignoreCount,
-                                                  nsIMsgDBHdr);
+                                                  Ci.nsIMsgDBHdr);
         Assert.equal(expected[1][i], eventHeader.messageId);
       }
     }
     else { // actual headers
       hasExactlyElements(expected[1], event[1]);
     }
     // aJunkProcessed: was the message processed for junk?
     Assert.equal(expected[2], event[2]);
     // aTraitProcessed: was the message processed for traits?
     Assert.equal(expected[3], event[3]);
     break;
-  case gMFNService.msgKeyChanged:
+  case MailServices.mfn.msgKeyChanged:
     Assert.equal(expected[1].messageId, event[2].expectedMessageId);
     break;
-  case gMFNService.msgsMoveCopyCompleted:
-  case gMFNService.folderMoveCopyCompleted:
+  case MailServices.mfn.msgsMoveCopyCompleted:
+  case MailServices.mfn.folderMoveCopyCompleted:
     // Check: Move or copy as expected.
     Assert.equal(expected[1], event[1]);
 
     // Check: headers match/folder matches.
     hasExactlyElements(expected[2], event[2]);
 
     // Check: destination folder matches.
     Assert.equal(expected[3], event[3]);
 
-    if (eventType == gMFNService.folderMoveCopyCompleted)
+    if (eventType == MailServices.mfn.folderMoveCopyCompleted)
       break;
 
     // Check: destination headers.  We expect these for local and imap folders,
     //  but we will not have heard about the headers ahead of time,
     //  so the best we can do is make sure they match up.  To this end,
     //  we check that the message-id header values match up.
     for (let iMsg = 0; iMsg < event[2].length; iMsg++)
     {
-      let srcHdr = event[2].queryElementAt(iMsg, nsIMsgDBHdr);
-      let destHdr = event[4].queryElementAt(iMsg, nsIMsgDBHdr);
+      let srcHdr = event[2].queryElementAt(iMsg, Ci.nsIMsgDBHdr);
+      let destHdr = event[4].queryElementAt(iMsg, Ci.nsIMsgDBHdr);
       Assert.equal(srcHdr.messageId, destHdr.messageId);
     }
     break;
-  case gMFNService.folderAdded:
+  case MailServices.mfn.folderAdded:
     // Check: parent folder matches
     Assert.equal(event[1].parent, expected[1]);
 
     // Check: folder name matches
     Assert.equal(event[1].prettyName, expected[2]);
     Assert.equal(event[1].name, expected[2]);
 
     // Not a check, but if we have to store this folder somewhere, do it
     if (expected[3])
       eval(expected[3] + "= event[1]");
     break;
-  case gMFNService.folderRenamed:
+  case MailServices.mfn.folderRenamed:
     // Check: source folder matches
     hasExactlyElements(expected[1], event[1]);
 
     // Check: destination folder name matches
     Assert.equal(expected[2], event[2].prettyName);
     break;
-  case gMFNService.itemEvent:
+  case MailServices.mfn.itemEvent:
     // the event string should match
     Assert.equal(expected[2], event[2]);
     // and so should the folder we are talking about
     Assert.equal(expected[1], event[1]);
     break;
   }
 }