MozillaZine

JavaScript Preferences Class

From MozillaZine Knowledge Base

Revision as of 19:05, 9 March 2005; view current revision
←Older revision | Newer revision→

Javascript Preferences Class

This class encapsulates many of the commonly used features of Mozilla's preferences-related interfaces into a single class. Sample usage is shown in the leading comments.

/**************************************************************************
 * preferences.js - a javascript class which provides a safe wrapper      *
 *                  around nsIPrefService.                                *
 *                                                                        *
 *                  It keeps code clean by centralizing the use of        *
 *                  nsIPrefService, translating exceptions into null or   *
 *                  false return values (as appropriate), typechecking    *
 *                  all values, and other good things.                    *
 *                                                                        *
 * author:  eric h. jung (grimholtz@yahoo.com)                            *
 * version: 0.1                                                           *
 * date: 07 March 2005                                                    *
 *                                                                        *
 * Usage: Include this file in your code then --                          *
 *                                                                        *
 *   var prefs = new PrefsWrapper("extensions.myextension.");             *
 *   prefs.setXXX("foo.bar", fooBarPref);                                 *
 *   // Note you can optionally provide a default value for all           *
 *   // getters. If the pref doesn't exist in either the current or       *
 *   // default preference tree, the default value will be                *
 *   // returned.                                                         *
 *   var fooBarPref = prefs.getXXX("foo.bar");                            *
 *   var fooBarBarPref = prefs.getXXX("foo.bar.bar", "my default");       *
 *                                                                        *
 * Read the comments of each function to see what it returns and when.    *
 * For details about Mozilla preferences, see                             *
 * http://kb.mozillazine.org/Dev_:_Using_preferences                      *
 *                                                                        *
 **************************************************************************/


/**
 * Constructor
 */
function PrefsWrapper(branch) {
  this._prefsService = this._prefsService.getBranch(branch);
}

/**
 * Retrieves the state of an individual boolean preference.
 * Returns true/false if the preference exists in either the current or 
 * default preference tree. Returns the default argument
 * if the preference does not exist in either of those trees, or is not of boolean type.
 * If no default argument is specified, null is returned in its place.
 */
function getBool(prefName, defawlt) {
  try {
    return this._prefsService.getPrefType(prefName) == this._prefsService.PREF_BOOL ?
      this._prefsService.getBoolPref(prefName) : defawlt;
	}
	catch (e) {
	  return defawlt;
	}
}

/**
 * Retrieves the state of an individual string preference.
 * Returns the value of the preference if it exists in either the current or
 * default preference tree. Returns the default argument
 * if the preference does not exist in either of those trees, or is not of string type.
 * If no default argument is specified, null is returned in its place.
 */
function getChar(prefName, defawlt) {
  try {
	  return this._prefsService.getPrefType(prefName) == this._prefsService.PREF_STRING ?
      this._prefsService.getCharPref(prefName) : defawlt;
	}
	catch (e) {
	  return defawlt;
	}
}

/**
 * Retrieves the state of an individual integer preference.
 * Returns the value of the preferenceif it exists in either the current or
 * default preference tree. Returns the default argument
 * if the preference does not exist in either of those trees, or is not of integer type.
 * If no default argument is specified, null is returned in its place.
 */
function getInt(prefName, defawlt) {
  try {
	  return this._prefsService.getPrefType(prefName) == this._prefsService.PREF_INT ?
      this._prefsService.getIntPref(prefName) : defawlt;
	}
	catch (e) {
	  return defawlt;
	}
}

/**
 * Retrieves the state of an individual Unicode string preference.
 * Returns the value of the preference if it exists in either the current or
 * default preference tree. Returns the default argument
 * if the preference does not exist in either of those trees, or is not of string type.
 * If no default argument is specified, null is returned in its place.
 */
function getUnicodeChar(prefName, defawlt) {
  try {
	  return this._prefsService.getPrefType(prefName) == this._prefsService.PREF_STRING ?
      this._prefsService.getComplexValue(Components.interfaces.nsISupportsString).data : defawlt;
	}
	catch (e) {
	  return defawlt;
	}
}

/**
 * Retrieves the state of an individual localized string preference.
 * Returns the value of the preference if it exists in either the current or
 * default preference tree. Returns the default argument
 * if the preference does not exist in either of those trees, or is not of string type.
 * If no default argument is specified, null is returned in its place.
 */
function getLocalizedChar(prefName, defawlt) {
  try {
	  return this._prefsService.getPrefType(prefName) == this._prefsService.PREF_STRING ?
      this._prefsService.getComplexValue(Components.interfaces.nsIPrefLocalizedString).data : defawlt;
	}
	catch (e) {
	  return defawlt;
	}
}

/**
 * Set the state of an individual boolean preference.
 * Returns true if the value was successfully set; false if it wasn't set.
 * _b_ can be a boolean, or case-insensensitive versions of
 * "yes", "no", "true", or "false".
 */
function setBool(prefName, b) {
  if (typeof(b) == "boolean") {
	  this._prefsService.setBoolPref(prefName, b);
    return true;
  }
  else {
    try {
      b = b.toLowerCase();
   	  this._prefsService.setBoolPref(prefName, ("true" == b || "yes" == b));
      return true;
    }
    catch (e) {
      // toLowerCase() doesn't work and
      // b isn't type boolean
      return false;
    }
  }
}

/**
 * Set the state of an individual string preference.
 * Returns true if the value was successfully set; false if it wasn't set.
 */
function setChar(prefName, str) {
  if (typeof(str) == "string") {
    this._prefsService.setCharPref(prefName, str);
    return true;
  }
  return false;
}

/**
 * Set the state of an individual integer preference.
 * Returns true if the value was successfully set; false if it wasn't set.
 */
function setInt(prefName, i) {
  if (!isNaN(i) && String(i).indexOf(".") == -1) {
	  this._prefsService.setIntPref(prefName, i);
    return true;
  }
  return false;
}

/**
 * Set the state of an individual Unicode string preference.
 * Returns true if the value was successfully set; false if it wasn't set.
 * The second argument, value, is a string which can contain non-ascii characters.
 */
function setUnicodeChar(prefName, value) {
  try {
    var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
    str.data = value;
    this._prefsService.setComplexValue(prefName, Components.interfaces.nsISupportsString, str);
    return true;
  }
  catch (e) {
    return false;
  }
}

PrefsWrapper.prototype._prefsService =
  Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
PrefsWrapper.prototype.setInt = setInt;
PrefsWrapper.prototype.setChar = setChar;
PrefsWrapper.prototype.setBool = setBool;
PrefsWrapper.prototype.setUnicodeChar = setUnicodeChar;
PrefsWrapper.prototype.getInt = getInt;
PrefsWrapper.prototype.getChar = getChar;
PrefsWrapper.prototype.getBool = getBool;
PrefsWrapper.prototype.getUnicodeChar = getUnicodeChar;
PrefsWrapper.prototype.getLocalizedChar = getLocalizedChar;