Dev : Using preferences: Difference between revisions

From MozillaZine Knowledge Base
Jump to navigationJump to search
No edit summary
Line 212: Line 212:
...
...
var QuickMenuMC_pref = Components.classes["@mozilla.org/preferences-service;1"]
var QuickMenuMC_pref = Components.classes["@mozilla.org/preferences-service;1"]
                                    .getService(Components.interfaces.nsIPrefBranch);
                              .getService(Components.interfaces.nsIPrefBranch);
...
...
if(QuickMenuMC_pref.prefHasUserValue("QuickMenuMC.FolderLabel")){
if(QuickMenuMC_pref.prefHasUserValue("QuickMenuMC.FolderLabel")){

Revision as of 16:57, 8 December 2005

This page is part of the extension development documentation project.

Ask your questions in MozillaZine Forums. Also try browsing example code.

Note: development documentation is in process of being moved to Mozilla Development Center (MDC).

This article is about using Mozilla Preferences system. Information here applies to the Mozilla Suite, Firefox, Thunderbird and possibly other Mozilla-based applications. Intended audience is Mozilla extension developers who wish to learn details about using preferences in Mozilla.

If you haven't yet, read other documents about Mozilla preferences on XUL Planet and on mozilla.org (links below in Resources section).

Note: This article doesn't cover all available methods for manipulating preferences yet, please refer to XulPlanet XPCOM reference pages listed in Resources section for the complete list of methods. The interfaces dealing with preferences are fairly well documented, so using the methods not documented here should be easy.

XPCOM interfaces for preferences system

Mozilla exposes its preferences system through a few XPCOM interfaces. Look in the Resources section below for the link to list of preferences-related interfaces.

Three most used interfaces are nsIPrefService, nsIPrefBranch and nsIPrefBranchInternal. First two are frozen and will not change, last one is “internal”, but is very useful because it allows you to set up prefs observers — see below for an example.

It's worth noting that there also is an nsIPref interface. Despite it being used in some places, it is deprecated and should not be used.

Preferences service is instantiated exactly as any other service. (See Creating XPCOM Components document at XUL Planet for details.) To get an nsIPrefBranch, either QI the pref service (that will give you the root branch) or call nsIPrefService.getBranch() to get a sub-branch.

Here are two examples:

// Get the root branch
var prefs = Components.classes["@mozilla.org/preferences-service;1"].
                    getService(Components.interfaces.nsIPrefBranch);
// Get the "extensions.myext." branch
var prefs = Components.classes["@mozilla.org/preferences-service;1"].
                    getService(Components.interfaces.nsIPrefService);
prefs = prefs.getBranch("extensions.myext.");

Simple types

There are three types of preferences: string, integer and boolean. Each entry in preferences database (prefs.js) has one of those types. There are six methods of nsIPrefBranch that read and write them: getBoolPref, setBoolPref, getCharPref, setCharPref, getIntPref and setIntPref. Using them is as easy as:

// prefs is an nsIPrefBranch.
// Look in the above section for examples of getting one.
var value = prefs.getBoolPref("accessibility.typeaheadfind"); // get a pref
prefs.setBoolPref("accessibility.typeaheadfind", !value); // set a pref

Complex types

As noted in previous section, each entry in prefs database (prefs.js) must have a string, an integer or a boolean value. However, there is a concept of complex types, which makes it easier for developers to save and load nsILocalFile and nsISupportsString objects in preferences (as strings — note that from the preferences system's POV, complex values have a nsIPrefBranch.PREF_STRING type.)

There are two nsIPrefBranch methods implementing the concept — setComplexValue and getComplexValue. You can look up their implementation in nsPrefBranch.cpp. Here is the IDL definition:

void getComplexValue(in string aPrefName, in nsIIDRef aType, 
		[iid_is(aType), retval] out nsQIResult aValue);

void setComplexValue(in string aPrefName, in nsIIDRef aType, in nsISupports aValue);

As you can see, both of them take aType parameter. It can have the following values (to be precise, you should pass Components.interfaces.nsIWhatever instead of just nsIWhatever, which is undefined):

  • nsISupportsString — used to handle unicode strings in preferences. Use this when the preference value may contain non-ASCII characters (for example, user's name).
  • nsIPrefLocalizedString — almost same as nsISupportsString, but it is handled differently in getComplexValue when there's no user value for given preference, see below for details.
  • nsILocalFile and nsIRelativeFilePref — store paths in preferences. nsILocalFile is used to store absolute paths, while nsIRelativeFilePref is used to store paths relative to one of “special” directories, like the profile folder.

nsISupportsString

As noted above, this is used to handle unicode strings in preferences. Example:

// prefs is an nsIPrefBranch

// Example 1: getting unicode value
var value = prefs.getComplexValue("preference.with.non.ascii.value",
      Components.interfaces.nsISupportsString).data;

// Example 2: setting unicode value
var str = Components.classes["@mozilla.org/supports-string;1"]
      .createInstance(Components.interfaces.nsISupportsString);
str.data = "some non-ascii text";
prefs.setComplexValue("preference.with.non.ascii.value", 
      Components.interfaces.nsISupportsString, str);

nsIPrefLocalizedString

Another complex type supported by Mozilla is nsIPrefLocalizedString. It is similar to nsISupportsString, the only difference is that when there is no user value, getComplexValue gets the default value from a locale file (thus making the default value localizable).

It's easier to explain this on example. Let's say you want to make the default value for extensions.myext.welcomemessage preference localizable. You should do the following:

  1. Add this line to some .properties file (for all of your locales), say to chrome://myext/locale/defaults.properties:
    extensions.myext.welcomemessage=Localized default value
  2. Add the default value for extensions.myext.welcomemessage, pointing to that properties file, by adding the following line to your file with default preferences (see below).
    pref("extensions.myext.welcomemessage", "chrome://myext/locale/defaults.properties");
  3. Read the preference with getComplexValue, passing nsIPrefLocalizedString as aType:
    var prefs = Components.classes["@mozilla.org/preferences-service;1"].
          getService(Components.interfaces.nsIPrefService);
    var branch = prefs.getBranch("extensions.myext.");
    var value = branch.getComplexValue("welcomemessage",
          Components.interfaces.nsIPrefLocalizedString).data;
    

The code in step 3 will read the default value from chrome://myext/locale/defaults.properties when no user value is set, and will behave exactly the same as if nsISupportsString was passed as aType otherwise.

nsILocalFile and nsIRelativeFilePref

Please see the File IO article for details on nsILocalFile and nsIRelativeFilePref.

Default preferences

Each preference may have up to two values — current and default. That means there are two “pref trees” — current and default, — and each of them may or may not have a value for preference in question.

You can see the list of preferences in about:config (where available). Preferences that have user value are bold, those that don't have a user value are printed in normal font.

You can get both trees using nsIPrefService.getBranch() and nsIPrefService.getDefaultBranch() functions. See below for details.

What effect do default preferences have on various get methods

When one of get methods of nsIPrefBranch (assuming it's a branch of the tree with current values) is called, it does the following:

  1. Checks whether the “current” tree has a value for the pref and whether the pref is locked.
  2. If there's a value of correct type (f.e. getBoolValue expects a value of type nsIPrefBranch.PREF_BOOL), and the preference is not locked, the method returns that value.
  3. If there's a value of incorrect type and the pref is not locked, an exception is thrown (NS_ERROR_UNEXPECTED)
  4. If the preference is locked or if there is no value for that preference in “current” tree, the get method checks the default tree.
  5. If there's a value of expected type in the “default” tree, it is returned (with the only exception, getComplexValue with aType parameter = nsIPrefLocalizedString, described above)
  6. Otherwise an exception is thrown (NS_ERROR_UNEXPECTED).

If the branch is from the “default” tree, the get method doesn't check the tree with current values at all.

(This is not exactly how it's coded in libpref, but it's equivalent)

Where are the default values read from

  • All Mozilla-based applications read (application directory)/defaults/pref/*.js .
  • In addition to that, recent versions of Toolkit applications (Firefox 1.0, Thunderbird 1.0 and the like; not Mozilla Suite) read extension defaults—usually (profile folder)/extensions/(ID)/defaults/preferences/

These files use simple JS-like syntax. To add a default value for a preference, you should add a line like this to your default preferences file:

pref("extensions.infolister.hide_menu_item", false);

How to install extension's defaults files

For Mozilla, copy them to (appdir)/defaults/pref in your install script.

For Firefox/Thunderbird, just put them in myext.xpi/defaults/preferences/. They will be copied and registered with the prefs system automatically.

More about preferences "branches"

Preferences names consist of a few strings separated with dots, and related prefs usually share the same prefix. For example, most accessibility preferences in Mozilla start with "accessibility."

This means that all existing preferences can be imagined as if they were in a tree, like this:

+
|
+-- accessibility
|         |
|         +-- typeaheadfind
|         |         |
|         |         +-- autostart (accessibility.typeaheadfind.autostart)
|         |         |
|         |         +-- enablesound (accessibility.typeaheadfind.enablesound)
|         |
|         +-- usebrailledisplay (accessibility.usebrailledisplay)
|
+-- extensions
          |
          +-- lastAppVersion (extensions.lastAppVersion)

This is the metaphor behind nsIPrefBranch. However, you should be aware of the fact that Mozilla preferences system doesn't treat dots in a special way. For example this code will also read the value of accessibility.typeaheadfind.enablesound preference:

var prefs = Components.classes["@mozilla.org/preferences-service;1"].
                    getService(Components.interfaces.nsIPrefService);
var branch = prefs.getBranch("acce");
var enablesound = branch.getBoolPref("ssibility.typeaheadfind.enablesound");

This is the reason why you should usually pass strings ending with a dot to getBranch(), like prefs.getBranch("accessibility.").

Another caveat you should be aware of is that nsIPrefBranch.getChildList("") returns an array of preferences names that start with that branch's root, for example

var branch = prefs.getBranch("accessibility.");
var children = branch.getChildList("", {});

will return these items (for the example tree above): "typeaheadfind.autostart", "typeaheadfind.enablesound", "usebrailledisplay", -- not just direct children ("typeaheadfind" and "usebrailledisplay"), as you might have expected.

Using preferences observers

You can use nsIPrefBranchInternal interface to “listen” to changes to preferences in a certain branch.

Note: During Gecko 1.8 development, nsIPrefBranchInternal was renamed to nsIPrefBranch2 [1] and was frozen. nsIPrefBranchInternal name is still supported in Gecko 1.8, so this is what you should use in extensions that need to be compatible with Gecko 1.7 and Gecko 1.8 (Firefox 1.0/1.1). For newer extensions use nsIPrefBranch2.

Here's an example (note, this code hasn't actually been tested, so it may contain typos and other errors):

var myPrefObserver =
{
  register: function()
  {
    var prefService = Components.classes["@mozilla.org/preferences-service;1"]
                                .getService(Components.interfaces.nsIPrefService);
    this._branch = prefService.getBranch("extensions.myextension.");
    this._branch.QueryInterface(Components.interfaces.nsIPrefBranchInternal);
    this._branch.addObserver("", this, false);
  },

  unregister: function()
  {
    if(!this._branch) return;
    this._branch.removeObserver("", this);
  },

  observe: function(aSubject, aTopic, aData)
  {
    if(aTopic != "nsPref:changed") return;
    // aSubject is the nsIPrefBranch we're observing
    // aData is the name of the pref that's been changed (relative to aSubject)
    switch (aData) {
      case "pref1":
        // extensions.myextension.pref1 was changed
        break;
      case "pref2":
        // extensions.myextension.pref2 was changed
        break;
    }
  }
}
myPrefListener.register();

Using prefHasUserValue

prefHasUserValue(preference) checks whether the preference has been changes from the default value to another one (by an user or an extension), if so it will return true, else false. in addition prefHasUserValue can be also used to check whether a preference exists. if calling a preference e.g. by getCharPref which was not defined previously the system will throw an exception (which of course can be handled by try...catch (which is not a nice solution to check whether a preference exists)). Using prefHasUserValue will return false if the preference was not defined before. This can be used for example to initialize an extension (see code snippet below).

...
var QuickMenuMC_pref = Components.classes["@mozilla.org/preferences-service;1"]
                               .getService(Components.interfaces.nsIPrefBranch);
...
if(QuickMenuMC_pref.prefHasUserValue("QuickMenuMC.FolderLabel")){
...
}

Using preferences in extensions

If you're writing your extension for one of Toolkit applications (Firefox, Thunderbird, Nvu), it's recommended to provide default values for your extension's preferences (see above for information on how to do it). It has the following benefits:

  • You don't have to duplicate default values in various parts of your code.
  • The code reading preferences is simplified, you don't need to worry about get* methods throw an exception, because under normal circumstances they won't do it.

JavaScript wrappers for preferences system

There are a few JavaScript wrappers to make your life easier: see this, this, and the nsPreferences wrapper included with Firefox and Thunderbird (chrome://global/content/nsUserSettings.js).

Resources