Bug 733496 - Convert mail/components/addrbook/content to Services.jsm. r=mconley
authoraceman <acelists@atlas.sk>
Mon, 26 Mar 2012 20:38:08 -0400
changeset 9747 d3fb8aefb15c2dcf55414d6bf5bffe17573eb388
parent 9746 01a7a15d27bf5dbf8b5941d09c57cff83c9ce287
child 9748 888acdb0f4bff42bf2afbc03ab0e748d9df7c0dd
push id7443
push userryanvm@gmail.com
push dateTue, 27 Mar 2012 00:38:20 +0000
treeherdercomm-central@888acdb0f4bf [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmconley
bugs733496
Bug 733496 - Convert mail/components/addrbook/content to Services.jsm. r=mconley
mail/components/addrbook/content/abCardOverlay.js
mail/components/addrbook/content/abCardViewOverlay.js
mail/components/addrbook/content/abCommon.js
mail/components/addrbook/content/abContactsPanel.js
mail/components/addrbook/content/abTrees.js
mail/components/addrbook/content/addressbook.js
mailnews/addrbook/content/abDragDrop.js
--- a/mail/components/addrbook/content/abCardOverlay.js
+++ b/mail/components/addrbook/content/abCardOverlay.js
@@ -31,16 +31,19 @@
 # use your version of this file under the terms of the MPL, indicate your
 # decision by deleting the provisions above and replace them with the notice
 # and other provisions required by the GPL or the LGPL. If you do not delete
 # the provisions above, a recipient may use your version of this file under
 # the terms of any one of the MPL, the GPL or the LGPL.
 #
 # ***** END LICENSE BLOCK *****
 
+Components.utils.import("resource://gre/modules/Services.jsm");
+Components.utils.import("resource:///modules/mailServices.js");
+
 const kNonVcardFields =
         ["NickNameContainer", "SecondaryEmailContainer", "ScreenNameContainer",
          "customFields", "allowRemoteContent", "preferDisplayName"];
 
 const kPhoneticFields =
         ["PhoneticLastName", "PhoneticLabel1", "PhoneticSpacer1",
          "PhoneticFirstName", "PhoneticLabel2", "PhoneticSpacer2"];
 
@@ -148,19 +151,17 @@ function OnLoadNewCard()
 
     if ("okCallback" in window.arguments[0])
       gOkCallback = window.arguments[0].okCallback;
 
     if ("escapedVCardStr" in window.arguments[0]) {
       // hide non vcard values
       HideNonVcardFields();
       gEditCard.card =
-        Components.classes["@mozilla.org/abmanager;1"]
-                  .getService(Components.interfaces.nsIAbManager)
-                  .escapedVCardToAbCard(window.arguments[0].escapedVCardStr);
+        MailServices.ab.escapedVCardToAbCard(window.arguments[0].escapedVCardStr);
     }
 
     if ("titleProperty" in window.arguments[0])
       gEditCard.titleProperty = window.arguments[0].titleProperty;
 
     if ("hideABPicker" in window.arguments[0])
       gHideABPicker = window.arguments[0].hideABPicker;
   }
@@ -374,18 +375,18 @@ function NotifySaveListeners(directory)
   // the save listeners might have tweaked the card
   // in which case we need to commit it.
   directory.modifyCard(gEditCard.card);
 }
 
 function InitPhoneticFields()
 {
   var showPhoneticFields =
-        gPrefs.getComplexValue("mail.addr_book.show_phonetic_fields", 
-                               Components.interfaces.nsIPrefLocalizedString).data;
+    Services.prefs.getComplexValue("mail.addr_book.show_phonetic_fields",
+      Components.interfaces.nsIPrefLocalizedString).data;
 
   // hide phonetic fields if indicated by the pref
   if (showPhoneticFields == "true")
   {
     for (var i = kPhoneticFields.length; i-- > 0; )
       document.getElementById(kPhoneticFields[i]).hidden = false;
   }
 }
@@ -395,26 +396,24 @@ function InitEditCard()
   InitPhoneticFields();
 
   InitCommonJS();
 
   // Create gEditCard object that contains global variables for the current js
   //   file.
   gEditCard = new Object();
 
-  gEditCard.prefs = gPrefs;
-
   // get specific prefs that gEditCard will need
   try {
     var displayLastNameFirst =
-        gPrefs.getComplexValue("mail.addr_book.displayName.lastnamefirst", 
-                               Components.interfaces.nsIPrefLocalizedString).data;
+      Services.prefs.getComplexValue("mail.addr_book.displayName.lastnamefirst",
+        Components.interfaces.nsIPrefLocalizedString).data;
     gEditCard.displayLastNameFirst = (displayLastNameFirst == "true");
     gEditCard.generateDisplayName =
-      gPrefs.getBoolPref("mail.addr_book.displayName.autoGeneration");
+      Services.prefs.getBoolPref("mail.addr_book.displayName.autoGeneration");
   }
   catch (ex) {
     dump("ex: failed to get pref" + ex + "\n");
   }
 }
 
 function NewCardOKButton()
 {
@@ -625,44 +624,38 @@ function CleanUpWebPage(webPage)
 //          true - All required data are present.
 function CheckCardRequiredDataPresence(doc)
 {
   // Bug 314995 We require at least one of the following fields to be
   // filled in: email address, first name, last name, display name,
   //            organization (company name).
   var primaryEmail = doc.getElementById("PrimaryEmail");
   if (primaryEmail.textLength == 0 &&
-      doc.getElementById("FirstName").textLength == 0 &&
-      doc.getElementById("LastName").textLength == 0 &&
-      doc.getElementById("DisplayName").textLength == 0 &&
-      doc.getElementById("Company").textLength == 0)
+    doc.getElementById("FirstName").textLength == 0 &&
+    doc.getElementById("LastName").textLength == 0 &&
+    doc.getElementById("DisplayName").textLength == 0 &&
+    doc.getElementById("Company").textLength == 0)
   {
-    Components
-      .classes["@mozilla.org/embedcomp/prompt-service;1"]
-      .getService(Components.interfaces.nsIPromptService)
-      .alert(
-        window,
-        gAddressBookBundle.getString("cardRequiredDataMissingTitle"),
-        gAddressBookBundle.getString("cardRequiredDataMissingMessage"));
+    Services.prompt.alert(
+      window,
+      gAddressBookBundle.getString("cardRequiredDataMissingTitle"),
+      gAddressBookBundle.getString("cardRequiredDataMissingMessage"));
 
     return false;
   }
 
   // Simple checks that the primary email should be of the form |user@host|.
   // Note: if the length of the primary email is 0 then we skip the check
   // as some other field must have something as per the check above.
   if (primaryEmail.textLength != 0 && !/.@./.test(primaryEmail.value))
   {
-    Components
-      .classes["@mozilla.org/embedcomp/prompt-service;1"]
-      .getService(Components.interfaces.nsIPromptService)
-      .alert(
-        window,
-        gAddressBookBundle.getString("incorrectEmailAddressFormatTitle"),
-        gAddressBookBundle.getString("incorrectEmailAddressFormatMessage"));
+    Services.prompt.alert(
+      window,
+      gAddressBookBundle.getString("incorrectEmailAddressFormatTitle"),
+      gAddressBookBundle.getString("incorrectEmailAddressFormatMessage"));
 
     // Focus the dialog field, to help the user.
     document.getElementById("abTabs").selectedIndex = 0;
     primaryEmail.focus();
 
     return false;
   }
 
@@ -1070,55 +1063,47 @@ var genericPhotoHandler = {
   }
 }
 
 var filePhotoHandler = {
 
   onLoad: function(aCard, aDocument) {
     var photoURI = aCard.getProperty("PhotoURI", "");
     try {
-      var file = Components.classes["@mozilla.org/network/io-service;1"]
-                           .getService(Components.interfaces.nsIIOService)
-                           .newURI(photoURI, null, null)
-                           .QueryInterface(Components.interfaces.nsIFileURL)
-                           .file;
+      var file = Services.io.newURI(photoURI, null, null)
+                            .QueryInterface(Components.interfaces.nsIFileURL)
+                            .file;
     } catch (e) {}
 
     if (!file)
       return false;
 
     aDocument.getElementById("PhotoFile").file = file;
     return true;
   },
 
   onShow: function(aCard, aDocument, aTargetID) {
     var file = aDocument.getElementById("PhotoFile").file;
     try {
-      var value = Components.classes["@mozilla.org/network/io-service;1"]
-                            .getService(Components.interfaces.nsIIOService)
-                            .newFileURI(file)
-                            .spec;
+      var value = Services.io.newFileURI(file).spec;
     } catch (e) {}
 
     if (!value)
       return false;
 
     aDocument.getElementById(aTargetID).setAttribute("src", value);
     return true;
   },
 
   onSave: function(aCard, aDocument) {
     var file = aDocument.getElementById("PhotoFile").file;
     if (!file)
       return false;
 
-    var photoURI = Components.classes["@mozilla.org/network/io-service;1"]
-                             .getService(Components.interfaces.nsIIOService)
-                             .newFileURI(file)
-                             .spec;
+    var photoURI = Services.io.newFileURI(file).spec;
 
     var file = storePhoto(photoURI);
 
     if (!file)
       return false;
 
     // Remove the original, if any
     removePhoto(aCard.getProperty("PhotoName", null));
--- a/mail/components/addrbook/content/abCardViewOverlay.js
+++ b/mail/components/addrbook/content/abCardViewOverlay.js
@@ -36,27 +36,25 @@
 # and other provisions required by the GPL or the LGPL. If you do not delete
 # the provisions above, a recipient may use your version of this file under
 # the terms of any one of the MPL, the GPL or the LGPL.
 #
 # ***** END LICENSE BLOCK *****
 
 //NOTE: gAddressBookBundle must be defined and set or this Overlay won't work
 
-var gPrefs = Components.classes["@mozilla.org/preferences-service;1"];
-gPrefs = gPrefs.getService();
-gPrefs = gPrefs.QueryInterface(Components.interfaces.nsIPrefBranch);
+Components.utils.import("resource://gre/modules/Services.jsm");
 
 var gProfileDirURL;
 
-var gMapItURLFormat = gPrefs.getComplexValue("mail.addr_book.mapit_url.format",
-                                              Components.interfaces.nsIPrefLocalizedString).data;
+var gMapItURLFormat = Services.prefs.getComplexValue("mail.addr_book.mapit_url.format",
+  Components.interfaces.nsIPrefLocalizedString).data;
 
-var gIOService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
-var gFileHandler = gIOService.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler);
+var gFileHandler = Services.io.getProtocolHandler("file")
+  .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
 var gPhotoDisplayHandlers = {};
 
 var zListName;
 var zPrimaryEmail;
 var zSecondaryEmail;
 var zScreenName;
 var zNickname;
 var zDisplayName;
@@ -188,17 +186,18 @@ function GetAddressesFromURI(uri)
       addresses += ", " + addressList.queryElementAt(i, Components.interfaces.nsIAbCard).primaryEmail;
     }
   }
   return addresses;
 }
 
 function DisplayCardViewPane(realCard)
 {
-  var generatedName = realCard.generateName(gPrefs.getIntPref("mail.addr_book.lastnamefirst"));
+  let generatedName = realCard.generateName(
+    Services.prefs.getIntPref("mail.addr_book.lastnamefirst"));
 
   // This will become neater when bug 312116 is fixed...
   // (card.property instead of card.getProperty("Property"))
   var card = { getProperty : function (prop) {
                  return realCard.getProperty(prop, "");
                },
                primaryEmail : realCard.primaryEmail,
                displayName : realCard.displayName,
@@ -405,24 +404,22 @@ function DisplayCardViewPane(realCard)
 
   // make the card view box visible
   cvSetVisible(top.cvData.CardViewBox, true);
 }
 
 function setBuddyIcon(card, buddyIcon)
 {
   try {
-    var myScreenName = gPrefs.getCharPref("aim.session.screenname");
+    let myScreenName = Services.prefs.getCharPref("aim.session.screenname");
     if (myScreenName && card.primaryEmail) {
       if (!gProfileDirURL) {
         // lazily create these file urls, and keep them around
-        var dirService = Components.classes["@mozilla.org/file/directory_service;1"]
-            .getService(Components.interfaces.nsIProperties);
-        var profileDir = dirService.get("ProfD", Components.interfaces.nsIFile);
-        gProfileDirURL = gIOService.newFileURI(profileDir);
+        let profileDir = Services.dirsvc.get("ProfD", Components.interfaces.nsIFile);
+        gProfileDirURL = Services.io.newFileURI(profileDir);
       }
 
       // if we did have a buddy icon on disk for this screenname, this would be the file url spec for it
       var iconURLStr = gProfileDirURL.spec + "/NIM/" + myScreenName + "/picture/" + card.getProperty("_AimScreenName") + ".gif";
 
       // check if the file exists
       var file = gFileHandler.getFileFromURLSpec(iconURLStr);
 
--- a/mail/components/addrbook/content/abCommon.js
+++ b/mail/components/addrbook/content/abCommon.js
@@ -36,27 +36,25 @@
 # use your version of this file under the terms of the MPL, indicate your
 # decision by deleting the provisions above and replace them with the notice
 # and other provisions required by the GPL or the LGPL. If you do not delete
 # the provisions above, a recipient may use your version of this file under
 # the terms of any one of the MPL, the GPL or the LGPL.
 #
 # ***** END LICENSE BLOCK *****
 
+Components.utils.import("resource://gre/modules/Services.jsm");
 Components.utils.import("resource:///modules/mailServices.js");
 
 var gDirTree;
 var abList = 0;
 var gAbResultsTree = null;
 var gAbView = null;
 var gAddressBookBundle;
 
-var gPrefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
-var gHeaderParser = Components.classes["@mozilla.org/messenger/headerparser;1"].getService(Components.interfaces.nsIMsgHeaderParser);
-
 const kDefaultSortColumn = "GeneratedName";
 const kDefaultAscending = "ascending";
 const kDefaultDescending = "descending";
 const kLdapUrlPrefix = "moz-abldapdirectory://";
 const kPersonalAddressbookURI = "moz-abmdbdirectory://abook.mab";
 const kCollectedAddressbookURI = "moz-abmdbdirectory://history.mab";
 // The default image for contacts
 var defaultPhotoURI = "chrome://messenger/skin/addressbook/icons/contact-generic.png";
@@ -111,17 +109,17 @@ var DirPaneController =
           // If the selected directory is an ldap directory
           // and if the prefs for this directory are locked
           // disable the delete button.
           if (selectedDir.lastIndexOf(kLdapUrlPrefix, 0) == 0)
           {
             var disable = false;
             try {
               var prefName = selectedDir.substr(kLdapUrlPrefix.length);
-              disable = gPrefs.getBoolPref(prefName + ".disable_delete");
+              disable = Services.prefs.getBoolPref(prefName + ".disable_delete");
             }
             catch(ex) {
               // if this preference is not set its ok.
             }
             if (disable)
               return false;
           }
           return true;
@@ -226,53 +224,51 @@ function AbDeleteSelectedDirectory()
   if (!selectedABURI)
     return;
 
   AbDeleteDirectory(selectedABURI);
 }
 
 function AbDeleteDirectory(aURI)
 {
-  var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
-
   var directory = GetDirectoryFromURI(aURI);
   var confirmDeleteMessage;
   var clearPrefsRequired = false;
 
   if (directory.isMailList)
     confirmDeleteMessage = gAddressBookBundle.getString("confirmDeleteMailingList");
   else {
     // Check if this address book is being used for collection
-    if (gPrefs.getCharPref("mail.collect_addressbook") == aURI &&
-        gPrefs.getBoolPref("mail.collect_email_address_outgoing")) {
+    if (Services.prefs.getCharPref("mail.collect_addressbook") == aURI &&
+        Services.prefs.getBoolPref("mail.collect_email_address_outgoing")) {
       var brandShortName = document.getElementById("bundle_brand").getString("brandShortName");
 
       confirmDeleteMessage = gAddressBookBundle.getFormattedString("confirmDeleteCollectionAddressbook", [brandShortName]);
       clearPrefsRequired = true;
     }
     else {
       confirmDeleteMessage = gAddressBookBundle.getString("confirmDeleteAddressbook");
     }
   }
 
-  if (!promptService.confirm(window,
-                             gAddressBookBundle.getString(
-                                                directory.isMailList ?
-                                                "confirmDeleteMailingListTitle" :
-                                                "confirmDeleteAddressbookTitle"),
-                             confirmDeleteMessage))
+  if (!Services.prompt.confirm(window,
+                               gAddressBookBundle.getString(
+                                                  directory.isMailList ?
+                                                  "confirmDeleteMailingListTitle" :
+                                                  "confirmDeleteAddressbookTitle"),
+                               confirmDeleteMessage))
     return;
 
   // First clear/reset the prefs if required
   if (clearPrefsRequired) {
-    gPrefs.setBoolPref("mail.collect_email_address_outgoing", false);
+    Services.prefs.setBoolPref("mail.collect_email_address_outgoing", false);
 
     // Also reset the displayed value so that we don't get a blank item in the
     // prefs dialog if it gets enabled.
-    gPrefs.setCharPref("mail.collect_addressbook", kPersonalAddressbookURI);
+    Services.prefs.setCharPref("mail.collect_addressbook", kPersonalAddressbookURI);
   }
 
   MailServices.ab.deleteAddressBook(aURI);
 }
 
 function GetParentRow(aTree, aRow)
 {
   var row = aRow;
@@ -295,34 +291,33 @@ function InitCommonJS()
 }
 
 function AbDelete()
 {
   var types = GetSelectedCardTypes();
   if (types == kNothingSelected)
     return;
 
-  var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
   // If at least one mailing list is selected then prompt users for deletion.
 
   var confirmDeleteMessage;
   if (types == kListsAndCards)
     confirmDeleteMessage = gAddressBookBundle.getString("confirmDeleteListsAndContacts");
   else if (types == kMultipleListsOnly)
     confirmDeleteMessage = gAddressBookBundle.getString("confirmDeleteMailingLists");
   else if (types == kSingleListOnly)
     confirmDeleteMessage = gAddressBookBundle.getString("confirmDeleteMailingList");
   else if (types == kCardsOnly && gAbView && gAbView.selection) {
     if (gAbView.selection.count < 2)
       confirmDeleteMessage = gAddressBookBundle.getString("confirmDeleteContact");
     else
       confirmDeleteMessage = gAddressBookBundle.getString("confirmDeleteContacts");
   }
 
-  if (confirmDeleteMessage && promptService.confirm(window, null, confirmDeleteMessage))
+  if (confirmDeleteMessage && Services.prompt.confirm(window, null, confirmDeleteMessage))
     gAbView.deleteSelectedCards();
 }
 
 function AbNewCard()
 {
   goNewCardDialog(GetSelectedDirectory());
 }
 
@@ -340,18 +335,16 @@ function AbEditCard(card)
     goEditCardDialog(GetSelectedDirectory(), card);
   }
 }
 
 function AbNewMessage()
 {
   var msgComposeType = Components.interfaces.nsIMsgCompType;
   var msgComposFormat = Components.interfaces.nsIMsgCompFormat;
-  var msgComposeService = Components.classes["@mozilla.org/messengercompose;1"].getService();
-  msgComposeService = msgComposeService.QueryInterface(Components.interfaces.nsIMsgComposeService);
 
   var params = Components.classes["@mozilla.org/messengercompose/composeparams;1"].createInstance(Components.interfaces.nsIMsgComposeParams);
   if (params)
   {
     params.type = msgComposeType.New;
     params.format = msgComposFormat.Default;
     var composeFields = Components.classes["@mozilla.org/messengercompose/composefields;1"].createInstance(Components.interfaces.nsIMsgCompFields);
     if (composeFields)
@@ -378,17 +371,17 @@ function AbNewMessage()
           composeFields.bcc = GetSelectedAddressesFromDirTree();
         else
           composeFields.to = GetSelectedAddressesFromDirTree();
       }
       else
         composeFields.to = GetSelectedAddresses();
 
       params.composeFields = composeFields;
-      msgComposeService.OpenComposeWindowWithParams(null, params);
+      MailServices.compose.OpenComposeWindowWithParams(null, params);
     }
   }
 }
 
 /**
  * Set up items in the View > Layout menupopup.  This function is responsible
  * for updating the menu items' state to reflect reality.
  *
@@ -589,17 +582,17 @@ function GenerateAddressFromCard(card)
   if (card.isMailList)
   {
     var directory = GetDirectoryFromURI(card.mailListURI);
     email = directory.description || card.displayName;
   }
   else
     email = card.primaryEmail;
 
-  return gHeaderParser.makeFullAddress(card.displayName, email);
+  return MailServices.headerParser.makeFullAddress(card.displayName, email);
 }
 
 function GetDirectoryFromURI(uri)
 {
   return MailServices.ab.getDirectory(uri);
 }
 
 // returns null if abURI is not a mailing list URI
@@ -664,19 +657,19 @@ var gLDAPSession;
 
 function setupLdapAutocompleteSession()
 {
     var autocompleteLdap = false;
     var autocompleteDirectory = null;
     var prevAutocompleteDirectory = gCurrentAutocompleteDirectory;
     var i;
 
-    autocompleteLdap = gPrefs.getBoolPref("ldap_2.autoComplete.useDirectory");
+    autocompleteLdap = Services.prefs.getBoolPref("ldap_2.autoComplete.useDirectory");
     if (autocompleteLdap)
-        autocompleteDirectory = gPrefs.getCharPref(
+        autocompleteDirectory = Services.prefs.getCharPref(
             "ldap_2.autoComplete.directoryServer");
 
 
     // use a temporary to do the setup so that we don't overwrite the
     // global, then have some problem and throw an exception, and leave the
     // global with a partially setup session.  we'll assign the temp
     // into the global after we're done setting up the session
     //
@@ -693,57 +686,54 @@ function setupLdapAutocompleteSession()
         // the compose window code adds an observer on the directory server
         // prefs, but I don't think we need this here.
         gCurrentAutocompleteDirectory = autocompleteDirectory;
 
         // fill in the session params if there is a session
         //
         if (LDAPSession) {
             let url =
-              gPrefs.getComplexValue(autocompleteDirectory +".uri",
-				     Components.interfaces.nsISupportsString).data;
+              Services.prefs.getComplexValue(autocompleteDirectory + ".uri",
+                Components.interfaces.nsISupportsString).data;
 
-            LDAPSession.serverURL =
-              Components.classes["@mozilla.org/network/io-service;1"]
-                        .getService(Components.interfaces.nsIIOService)
-                        .newURI(url, null, null)
-                        .QueryInterface(Components.interfaces.nsILDAPURL);
+            LDAPSession.serverURL = Services.io.newURI(url, null, null)
+              .QueryInterface(Components.interfaces.nsILDAPURL);
 
             // get the login to authenticate as, if there is one
             //
             try {
-		LDAPSession.login =gPrefs.getComplexValue(
+                LDAPSession.login = Services.prefs.getComplexValue(
                     autocompleteDirectory + ".auth.dn",
                     Components.interfaces.nsISupportsString).data;
             } catch (ex) {
                 // if we don't have this pref, no big deal
             }
-            
+
             try {
-                LDAPSession.saslMechanism = gPrefs.getComplexValue(
+                LDAPSession.saslMechanism = Services.prefs.getComplexValue(
                     autocompleteDirectory + ".auth.saslmech",
                     Components.interfaces.nsISupportsString).data;
             } catch (ex) {
                 // if we don't have a mechanism, we'll just use simple binds
             }
 
             // don't search on non-CJK strings shorter than this
             //
             try {
-                LDAPSession.minStringLength = gPrefs.getIntPref(
+                LDAPSession.minStringLength = Services.prefs.getIntPref(
                     autocompleteDirectory + ".autoComplete.minStringLength");
             } catch (ex) {
                 // if this pref isn't there, no big deal.  just let
                 // nsLDAPAutoCompleteSession use its default.
             }
 
             // don't search on CJK strings shorter than this
             //
             try {
-                LDAPSession.cjkMinStringLength = gPrefs.getIntPref(
+                LDAPSession.cjkMinStringLength = Services.prefs.getIntPref(
                   autocompleteDirectory + ".autoComplete.cjkMinStringLength");
             } catch (ex) {
                 // if this pref isn't there, no big deal.  just let
                 // nsLDAPAutoCompleteSession use its default.
             }
 
             // we don't try/catch here, because if this fails, we're outta luck
             //
@@ -751,65 +741,65 @@ function setupLdapAutocompleteSession()
                 "@mozilla.org/ldap-autocomplete-formatter;1?type=addrbook"]
                 .createInstance().QueryInterface(
                     Components.interfaces.nsIAbLDAPAutoCompFormatter);
 
             // override autocomplete name format?
             //
             try {
                 ldapFormatter.nameFormat =
-                    gPrefs.getComplexValue(autocompleteDirectory +
-                                      ".autoComplete.nameFormat",
-                                      Components.interfaces.nsISupportsString).data;
+                    Services.prefs.getComplexValue(autocompleteDirectory +
+                        ".autoComplete.nameFormat",
+                        Components.interfaces.nsISupportsString).data;
             } catch (ex) {
                 // if this pref isn't there, no big deal.  just let
                 // nsAbLDAPAutoCompFormatter use its default.
             }
 
             // override autocomplete mail address format?
             //
             try {
                 ldapFormatter.addressFormat =
-                    gPrefs.getComplexValue(autocompleteDirectory +
-                                      ".autoComplete.addressFormat",
-                                      Components.interfaces.nsISupportsString).data;
+                    Services.prefs.getComplexValue(autocompleteDirectory +
+                        ".autoComplete.addressFormat",
+                        Components.interfaces.nsISupportsString).data;
             } catch (ex) {
                 // if this pref isn't there, no big deal.  just let
                 // nsAbLDAPAutoCompFormatter use its default.
             }
 
             try {
                 // figure out what goes in the comment column, if anything
                 //
                 // 0 = none
                 // 1 = name of addressbook this card came from
                 // 2 = other per-addressbook format
                 //
                 var showComments = 0;
-                showComments = gPrefs.getIntPref(
+                showComments = Services.prefs.getIntPref(
                     "mail.autoComplete.commentColumn");
 
                 switch (showComments) {
 
                 case 1:
                     // use the name of this directory
                     //
-                    ldapFormatter.commentFormat = gPrefs.getComplexValue(
-                                autocompleteDirectory + ".description",
-                                Components.interfaces.nsISupportsString).data;
+                    ldapFormatter.commentFormat = Services.prefs.getComplexValue(
+                        autocompleteDirectory + ".description",
+                        Components.interfaces.nsISupportsString).data;
                     break;
 
                 case 2:
                     // override ldap-specific autocomplete entry?
                     //
                     try {
                         ldapFormatter.commentFormat =
-                            gPrefs.getComplexValue(autocompleteDirectory +
-                                        ".autoComplete.commentFormat",
-                                        Components.interfaces.nsISupportsString).data;
+                            Services.prefs.getComplexValue(autocompleteDirectory +
+                                ".autoComplete.commentFormat",
+                                Components.interfaces.nsISupportsString).data;
                     } catch (innerException) {
                         // if nothing has been specified, use the ldap
                         // organization field
                         ldapFormatter.commentFormat = "[o]";
                     }
                     break;
 
                 case 0:
@@ -827,45 +817,45 @@ function setupLdapAutocompleteSession()
             // various formats
             //
             LDAPSession.formatter = ldapFormatter;
 
             // override autocomplete entry formatting?
             //
             try {
                 LDAPSession.outputFormat =
-                    gPrefs.getComplexValue(autocompleteDirectory +
-                                      ".autoComplete.outputFormat",
-                                      Components.interfaces.nsISupportsString).data;
+                    Services.prefs.getComplexValue(autocompleteDirectory +
+                        ".autoComplete.outputFormat",
+                        Components.interfaces.nsISupportsString).data;
 
             } catch (ex) {
                 // if this pref isn't there, no big deal.  just let
                 // nsLDAPAutoCompleteSession use its default.
             }
 
             // override default search filter template?
             //
             try {
-                LDAPSession.filterTemplate = gPrefs.getComplexValue(
+                LDAPSession.filterTemplate = Services.prefs.getComplexValue(
                     autocompleteDirectory + ".autoComplete.filterTemplate",
                     Components.interfaces.nsISupportsString).data;
 
             } catch (ex) {
                 // if this pref isn't there, no big deal.  just let
                 // nsLDAPAutoCompleteSession use its default
             }
 
             // override default maxHits (currently 100)
             //
             try {
                 // XXXdmose should really use .autocomplete.maxHits,
                 // but there's no UI for that yet
                 //
                 LDAPSession.maxHits =
-                    gPrefs.getIntPref(autocompleteDirectory + ".maxHits");
+                    Services.prefs.getIntPref(autocompleteDirectory + ".maxHits");
             } catch (ex) {
                 // if this pref isn't there, or is out of range, no big deal.
                 // just let nsLDAPAutoCompleteSession use its default.
             }
 
             if (!gSessionAdded) {
                 // if we make it here, we know that session initialization has
                 // succeeded; add the session for all recipients, and
@@ -902,19 +892,17 @@ function setupLdapAutocompleteSession()
     gSetupLdapAutocomplete = true;
 }
 
 /**
  * Returns an nsIFile of the directory in which contact photos are stored.
  * This will create the directory if it does not yet exist.
  */
 function getPhotosDir() {
-  var file = Components.classes["@mozilla.org/file/directory_service;1"]
-                       .getService(Components.interfaces.nsIProperties)
-                       .get("ProfD", Components.interfaces.nsIFile);
+  let file = Services.dirsvc.get("ProfD", Components.interfaces.nsIFile);
   // Get the Photos directory
   file.append("Photos");
   if (!file.exists() || !file.isDirectory())
     file.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);
   return file;
 }
 
 /**
@@ -933,19 +921,17 @@ function getPhotoURI(aPhotoName) {
   try {
     file.append(aPhotoName);
   }
   catch (e) {
     return defaultPhotoURI;
   }
   if (!file.exists())
     return defaultPhotoURI;
-  return Components.classes["@mozilla.org/network/io-service;1"]
-                   .getService(Components.interfaces.nsIIOService)
-                   .newFileURI(file).spec;
+  return Services.io.newFileURI(file).spec;
 }
 
 /**
  * Saves the given input stream to a file.
  *
  * @param aIStream The input stream to save.
  * @param aFile    The file to which the stream is saved.
  */
@@ -991,23 +977,21 @@ function saveStreamToFile(aIStream, aFil
  * @return An nsIFile representation of the photo.
  */
 function storePhoto(aUri)
 {
   if (!aUri)
     return false;
 
   // Get the photos directory and check that it exists
-  var file = getPhotosDir();
+  let file = getPhotosDir();
 
   // Create a channel from the URI and open it as an input stream
-  var ios = Components.classes["@mozilla.org/network/io-service;1"]
-                      .getService(Components.interfaces.nsIIOService);
-  var channel = ios.newChannelFromURI(ios.newURI(aUri, null, null));
-  var istream = channel.open();
+  let channel = Services.io.newChannelFromURI(Services.io.newURI(aUri, null, null));
+  let istream = channel.open();
 
   // Get the photo file
   file = makePhotoFile(file, findPhotoExt(channel));
 
   return saveStreamToFile(istream, file);
 }
 
 /**
@@ -1048,10 +1032,8 @@ function makePhotoFile(aDir, aExtension)
   // Find a random filename for the photo that doesn't exist yet
   do {
     filename = new String(Math.random()).replace("0.", "") + "." + aExtension;
     newFile = aDir.clone();
     newFile.append(filename);
   } while (newFile.exists());
   return newFile;
 }
-
-
--- a/mail/components/addrbook/content/abContactsPanel.js
+++ b/mail/components/addrbook/content/abContactsPanel.js
@@ -158,20 +158,20 @@ function AbResultsPaneDoubleClick(card)
 
 function UpdateCardView() 
 {
   // do nothing for ab panel
 }
 
 function onEnterInSearchBar()
 {
-  if (!gQueryURIFormat) 
-    gQueryURIFormat = gPrefs.getComplexValue("mail.addr_book.quicksearchquery.format", 
-                                              Components.interfaces.nsIPrefLocalizedString).data;
- 
+  if (!gQueryURIFormat)
+    gQueryURIFormat = Services.prefs.getComplexValue("mail.addr_book.quicksearchquery.format",
+      Components.interfaces.nsIPrefLocalizedString).data;
+
   var searchURI = GetSelectedDirectory();
   var searchInput = document.getElementById("peopleSearchInput");
 
   if (searchInput.value != "")
     searchURI += gQueryURIFormat.replace(/@V/g, encodeURIComponent(searchInput.value));
 
   SetAbView(searchURI);
 }
--- a/mail/components/addrbook/content/abTrees.js
+++ b/mail/components/addrbook/content/abTrees.js
@@ -34,16 +34,17 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 /**
  * This file contains our implementation for various addressbook trees.  It
  * depends on jsTreeView.js being loaded before this script is loaded.
  */
 
+Components.utils.import("resource://gre/modules/Services.jsm");
 Components.utils.import("resource:///modules/mailServices.js");
 
 /**
  * Each abDirTreeItem corresponds to one row in the tree view.
  */
 function abDirTreeItem(aDirectory) {
   this._directory = aDirectory;
 }
@@ -110,18 +111,17 @@ directoryTreeView.prototype = {
   __proto__: new PROTO_TREE_VIEW(),
 
   init: function dtv_init(aTree, aJSONFile) {
     const Cc = Components.classes;
     const Ci = Components.interfaces;
 
     if (aJSONFile) {
       // Parse our persistent-open-state json file
-      let file = Cc["@mozilla.org/file/directory_service;1"]
-                    .getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
+      let file = Services.dirsvc.get("ProfD", Ci.nsIFile);
       file.append(aJSONFile);
 
       if (file.exists()) {
         let data = "";
         let fstream = Cc["@mozilla.org/network/file-input-stream;1"]
                          .createInstance(Ci.nsIFileInputStream);
         let sstream = Cc["@mozilla.org/scriptableinputstream;1"]
                          .createInstance(Ci.nsIScriptableInputStream);
@@ -144,18 +144,17 @@ directoryTreeView.prototype = {
   shutdown: function dtv_shutdown(aJSONFile) {
     const Cc = Components.classes;
     const Ci = Components.interfaces;
 
     // Write out the persistOpenMap to our JSON file
     if (aJSONFile) {
       // Write out our json file...
       let data = JSON.stringify(this._persistOpenMap);
-      let file = Cc["@mozilla.org/file/directory_service;1"]
-                 .getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
+      let file = Services.dirsvc.get("ProfD", Ci.nsIFile);
       file.append(aJSONFile);
       let foStream = Cc["@mozilla.org/network/safe-file-output-stream;1"]
                     .createInstance(Ci.nsIFileOutputStream);
 
       foStream.init(file, 0x02 | 0x08 | 0x20, 0666, 0);
       foStream.write(data, data.length);
       foStream.QueryInterface(Ci.nsISafeOutputStream).finish();
       foStream.close();
--- a/mail/components/addrbook/content/addressbook.js
+++ b/mail/components/addrbook/content/addressbook.js
@@ -36,25 +36,25 @@
 # use your version of this file under the terms of the MPL, indicate your
 # decision by deleting the provisions above and replace them with the notice
 # and other provisions required by the GPL or the LGPL. If you do not delete
 # the provisions above, a recipient may use your version of this file under
 # the terms of any one of the MPL, the GPL or the LGPL.
 #
 # ***** END LICENSE BLOCK *****
 
+Components.utils.import("resource://gre/modules/Services.jsm");
 // Ensure the activity modules are loaded for this window.
 Components.utils.import("resource:///modules/activity/activityModules.js");
 Components.utils.import("resource:///modules/mailServices.js");
 
 const nsIAbListener = Components.interfaces.nsIAbListener;
 const kPrefMailAddrBookLastNameFirst = "mail.addr_book.lastnamefirst";
 const kPersistCollapseMapStorage = "directoryTree.json";
 
-var cvPrefs = 0;
 var gSearchTimer = null;
 var gStatusText = null;
 var gQueryURIFormat = null;
 var gCardViewBox;
 var gCardViewBoxEmail1;
 var gPreviousDirTreeIndex = -1;
 
 var msgWindow = Components.classes["@mozilla.org/messenger/msgwindow;1"]
@@ -128,19 +128,17 @@ function OnUnloadAddressBook()
 {
   MailServices.ab.removeAddressBookListener(gAddressBookAbListener);
   MailServices.ab.removeAddressBookListener(gDirectoryTreeView);
 
   // Shutdown the tree view - this will also save the open/collapsed
   // state of the tree view to a JSON file.
   gDirectoryTreeView.shutdown(kPersistCollapseMapStorage);
 
-  Components.classes["@mozilla.org/messenger/services/session;1"]
-            .getService(Components.interfaces.nsIMsgMailSession)
-            .RemoveMsgWindow(msgWindow);
+  MailServices.mailSession.RemoveMsgWindow(msgWindow);
 
   CloseAbView();
 }
 
 var gAddressBookAbViewListener = {
   onSelectionChanged: function() {
     ResultsPaneSelectionChanged();
   },
@@ -192,17 +190,17 @@ function delayedOnLoadAddressBook()
 
   // Initialize the Address Book tree view
   gDirectoryTreeView.init(gDirTree,
                           kPersistCollapseMapStorage);
 
   SelectFirstAddressBook();
 
   // if the pref is locked disable the menuitem New->LDAP directory
-  if (gPrefs.prefIsLocked("ldap_2.disable_button_add"))
+  if (Services.prefs.prefIsLocked("ldap_2.disable_button_add"))
     document.getElementById("addLDAP").setAttribute("disabled", "true");
 
   // Add a listener, so we can switch directories if the current directory is
   // deleted. This listener cares when a directory (= address book), or a
   // directory item is/are removed. In the case of directory items, we are
   // only really interested in mailing list changes and not cards but we have
   // to have both.
   MailServices.ab.addAddressBookListener(gAddressBookAbListener,
@@ -221,54 +219,46 @@ function delayedOnLoadAddressBook()
   toolbox.toolbarset = toolbarset;
 
   // Ensure we don't load xul error pages into the main window
   window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
         .getInterface(Components.interfaces.nsIWebNavigation)
         .QueryInterface(Components.interfaces.nsIDocShell)
         .useErrorPages = false;
 
-  Components.classes["@mozilla.org/messenger/services/session;1"]
-            .getService(Components.interfaces.nsIMsgMailSession)
-            .AddMsgWindow(msgWindow);
+  MailServices.mailSession.AddMsgWindow(msgWindow);
 }
 
 
 function GetCurrentPrefs()
 {
-  // prefs
-  if ( cvPrefs == 0 )
-    cvPrefs = new Object;
-
-  cvPrefs.prefs = gPrefs;
-
   // check "Show Name As" menu item based on pref
   var menuitemID;
-  switch (gPrefs.getIntPref(kPrefMailAddrBookLastNameFirst))
+  switch (Services.prefs.getIntPref(kPrefMailAddrBookLastNameFirst))
   {
     case kFirstNameFirst:
       menuitemID = 'firstLastCmd';
       break;
     case kLastNameFirst:
       menuitemID = 'lastFirstCmd';
       break;
     case kDisplayName:
     default:
       menuitemID = 'displayNameCmd';
       break;
   }
 
   var menuitem = top.document.getElementById(menuitemID);
-  if ( menuitem )
+  if (menuitem)
     menuitem.setAttribute('checked', 'true');
 
   // initialize phonetic
   var showPhoneticFields =
-        gPrefs.getComplexValue("mail.addr_book.show_phonetic_fields",
-                               Components.interfaces.nsIPrefLocalizedString).data;
+    Services.prefs.getComplexValue("mail.addr_book.show_phonetic_fields",
+      Components.interfaces.nsIPrefLocalizedString).data;
   // show phonetic fields if indicated by the pref
   if (showPhoneticFields == "true")
     document.getElementById("cmd_SortBy_PhoneticName")
             .setAttribute("hidden", "false");
 
 }
 
 
@@ -284,17 +274,17 @@ function SetNameColumn(cmd)
     case 'lastFirstCmd':
       prefValue = kLastNameFirst;
       break;
     case 'displayNameCmd':
       prefValue = kDisplayName;
       break;
   }
 
-  cvPrefs.prefs.setIntPref(kPrefMailAddrBookLastNameFirst, prefValue);
+  Services.prefs.setIntPref(kPrefMailAddrBookLastNameFirst, prefValue);
 }
 
 function onOSXFileMenuInit()
 {
   document.getElementById('menu_osxAddressBook')
           .setAttribute("checked", AbOSXAddressBookExists());
 }
 
@@ -423,43 +413,39 @@ function AbPrintAddressBook()
 function AbPrintPreviewAddressBook()
 {
   AbPrintAddressBookInternal(true, Components.interfaces.nsIMsgPrintEngine.MNAB_PRINTPREVIEW_ADDRBOOK);
 }
 
 function AbExport()
 {
   try {
-    var selectedABURI = GetSelectedDirectory();
+    let selectedABURI = GetSelectedDirectory();
     if (!selectedABURI) return;
 
-    var directory = GetDirectoryFromURI(selectedABURI);
+    let directory = GetDirectoryFromURI(selectedABURI);
     MailServices.ab.exportAddressBook(window, directory);
   }
   catch (ex) {
-    var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
+    let message;
+    switch (ex.result) {
+      case Components.results.NS_ERROR_FILE_ACCESS_DENIED:
+        message = gAddressBookBundle.getString("failedToExportMessageFileAccessDenied");
+        break;
+      case Components.results.NS_ERROR_FILE_NO_DEVICE_SPACE:
+        message = gAddressBookBundle.getString("failedToExportMessageNoDeviceSpace");
+        break;
+      default:
+        message = ex.message;
+        break;
+    }
 
-    if (promptService) {
-      var message;
-      switch (ex.result) {
-        case Components.results.NS_ERROR_FILE_ACCESS_DENIED:
-          message = gAddressBookBundle.getString("failedToExportMessageFileAccessDenied");
-          break;
-        case Components.results.NS_ERROR_FILE_NO_DEVICE_SPACE:
-          message = gAddressBookBundle.getString("failedToExportMessageNoDeviceSpace");
-          break;
-        default:
-          message = ex.message;
-          break;
-      }
-
-      promptService.alert(window,
-        gAddressBookBundle.getString("failedToExportTitle"),
-        message);
-    }
+    Services.prompt.alert(window,
+      gAddressBookBundle.getString("failedToExportTitle"),
+      message);
   }
 }
 
 function SetStatusText(total)
 {
   if (!gStatusText)
     gStatusText = document.getElementById('statusText');
 
@@ -499,34 +485,33 @@ function AbResultsPaneDoubleClick(card)
   AbEditCard(card);
 }
 
 function onAdvancedAbSearch()
 {
   var selectedABURI = GetSelectedDirectory();
   if (!selectedABURI) return;
 
-  var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].
-                                 getService(Components.interfaces.nsIWindowMediator);
-  var existingSearchWindow = windowManager.getMostRecentWindow("mailnews:absearch");
+  let existingSearchWindow = Services.wm.getMostRecentWindow("mailnews:absearch");
   if (existingSearchWindow)
     existingSearchWindow.focus();
   else
     window.openDialog("chrome://messenger/content/ABSearchDialog.xul", "",
                       "chrome,resizable,status,centerscreen,dialog=no",
                       {directory: selectedABURI});
 }
 
 function onEnterInSearchBar()
 {
   ClearCardViewPane();
 
   if (!gQueryURIFormat)
-    gQueryURIFormat = gPrefs.getComplexValue("mail.addr_book.quicksearchquery.format",
-                                              Components.interfaces.nsIPrefLocalizedString).data;
+    gQueryURIFormat = Services.prefs
+      .getComplexValue("mail.addr_book.quicksearchquery.format",
+                       Components.interfaces.nsIPrefLocalizedString).data;
 
   var searchURI = GetSelectedDirectory();
   if (!searchURI) return;
 
   /*
    XXX todo, handle the case where the LDAP url
    already has a query, like
    moz-abldapdirectory://nsdirectory.netscape.com:389/ou=People,dc=netscape,dc=com?(or(Department,=,Applications))
@@ -708,32 +693,29 @@ function getMailToolbox()
   return document.getElementById("ab-toolbox");
 }
 
 const kOSXDirectoryURI = "moz-abosxdirectory:///";
 const kOSXPrefBase = "ldap_2.servers.osx";
 
 function AbOSXAddressBookExists()
 {
-  var prefSvc = Components.classes["@mozilla.org/preferences-service;1"]
-                          .getService(Components.interfaces.nsIPrefBranch);
-
   // I hate doing it this way - until we redo how we manage address books
   // I can't think of a better way though.
 
   // See if the pref exists, if so, then we need to delete the address book
   var uriPresent = false;
   var position = 1;
   try {
-    uriPresent = prefSvc.getCharPref(kOSXPrefBase + ".uri") == kOSXDirectoryURI;
+    uriPresent = Services.prefs.getCharPref(kOSXPrefBase + ".uri") == kOSXDirectoryURI;
   }
   catch (e) { }
 
   try {
-    position = prefSvc.getIntPref(kOSXPrefBase + ".position");
+    position = Services.prefs.getIntPref(kOSXPrefBase + ".position");
   }
   catch (e) { }
 
   // Address book exists if the uri is correct and the position is not zero.
   return uriPresent && position != 0;
 }
 
 function AbShowHideOSXAddressBook()
--- a/mailnews/addrbook/content/abDragDrop.js
+++ b/mailnews/addrbook/content/abDragDrop.js
@@ -85,17 +85,17 @@ var abResultsPaneObserver = {
   getSupportedFlavours: function ()
     {
       return null;
     }
 };
 
 
 var dragService = Components.classes["@mozilla.org/widget/dragservice;1"]
-                            .getService().QueryInterface(Components.interfaces.nsIDragService);
+                            .getService(Components.interfaces.nsIDragService);
 
 var abDirTreeObserver = {
   /**
    * canDrop - determine if the tree will accept the dropping of a item
    * onto it.
    *
    * Note 1: We don't allow duplicate mailing list names, therefore copy
    * is not allowed for mailing lists.