browser/components/preferences/in-content/applications.js

Wed, 31 Dec 2014 13:27:57 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 13:27:57 +0100
branch
TOR_BUG_3246
changeset 6
8bccb770b82d
permissions
-rw-r--r--

Ignore runtime configuration files generated during quality assurance.

     1 /* This Source Code Form is subject to the terms of the Mozilla Public
     2  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
     3  * You can obtain one at http://mozilla.org/MPL/2.0/. */
     5 //****************************************************************************//
     6 // Constants & Enumeration Values
     8 Components.utils.import('resource://gre/modules/Services.jsm');
     9 const TYPE_MAYBE_FEED = "application/vnd.mozilla.maybe.feed";
    10 const TYPE_MAYBE_VIDEO_FEED = "application/vnd.mozilla.maybe.video.feed";
    11 const TYPE_MAYBE_AUDIO_FEED = "application/vnd.mozilla.maybe.audio.feed";
    12 const TYPE_PDF = "application/pdf";
    14 const PREF_PDFJS_DISABLED = "pdfjs.disabled";
    15 const TOPIC_PDFJS_HANDLER_CHANGED = "pdfjs:handlerChanged";
    17 const PREF_DISABLED_PLUGIN_TYPES = "plugin.disable_full_page_plugin_for_types";
    19 // Preferences that affect which entries to show in the list.
    20 const PREF_SHOW_PLUGINS_IN_LIST = "browser.download.show_plugins_in_list";
    21 const PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS =
    22   "browser.download.hide_plugins_without_extensions";
    24 /*
    25  * Preferences where we store handling information about the feed type.
    26  *
    27  * browser.feeds.handler
    28  * - "bookmarks", "reader" (clarified further using the .default preference),
    29  *   or "ask" -- indicates the default handler being used to process feeds;
    30  *   "bookmarks" is obsolete; to specify that the handler is bookmarks,
    31  *   set browser.feeds.handler.default to "bookmarks";
    32  *
    33  * browser.feeds.handler.default
    34  * - "bookmarks", "client" or "web" -- indicates the chosen feed reader used
    35  *   to display feeds, either transiently (i.e., when the "use as default"
    36  *   checkbox is unchecked, corresponds to when browser.feeds.handler=="ask")
    37  *   or more permanently (i.e., the item displayed in the dropdown in Feeds
    38  *   preferences)
    39  *
    40  * browser.feeds.handler.webservice
    41  * - the URL of the currently selected web service used to read feeds
    42  *
    43  * browser.feeds.handlers.application
    44  * - nsILocalFile, stores the current client-side feed reading app if one has
    45  *   been chosen
    46  */
    47 const PREF_FEED_SELECTED_APP    = "browser.feeds.handlers.application";
    48 const PREF_FEED_SELECTED_WEB    = "browser.feeds.handlers.webservice";
    49 const PREF_FEED_SELECTED_ACTION = "browser.feeds.handler";
    50 const PREF_FEED_SELECTED_READER = "browser.feeds.handler.default";
    52 const PREF_VIDEO_FEED_SELECTED_APP    = "browser.videoFeeds.handlers.application";
    53 const PREF_VIDEO_FEED_SELECTED_WEB    = "browser.videoFeeds.handlers.webservice";
    54 const PREF_VIDEO_FEED_SELECTED_ACTION = "browser.videoFeeds.handler";
    55 const PREF_VIDEO_FEED_SELECTED_READER = "browser.videoFeeds.handler.default";
    57 const PREF_AUDIO_FEED_SELECTED_APP    = "browser.audioFeeds.handlers.application";
    58 const PREF_AUDIO_FEED_SELECTED_WEB    = "browser.audioFeeds.handlers.webservice";
    59 const PREF_AUDIO_FEED_SELECTED_ACTION = "browser.audioFeeds.handler";
    60 const PREF_AUDIO_FEED_SELECTED_READER = "browser.audioFeeds.handler.default";
    62 // The nsHandlerInfoAction enumeration values in nsIHandlerInfo identify
    63 // the actions the application can take with content of various types.
    64 // But since nsIHandlerInfo doesn't support plugins, there's no value
    65 // identifying the "use plugin" action, so we use this constant instead.
    66 const kActionUsePlugin = 5;
    68 /*
    69 #if MOZ_WIDGET_GTK == 2
    70 */
    71 const ICON_URL_APP      = "moz-icon://dummy.exe?size=16";
    72 /*
    73 #else
    74 */
    75 const ICON_URL_APP      = "chrome://browser/skin/preferences/application.png";
    76 /*
    77 #endif
    78 */
    80 // For CSS. Can be one of "ask", "save", "plugin" or "feed". If absent, the icon URL
    81 // was set by us to a custom handler icon and CSS should not try to override it.
    82 const APP_ICON_ATTR_NAME = "appHandlerIcon";
    84 //****************************************************************************//
    85 // Utilities
    87 function getFileDisplayName(file) {
    88 #ifdef XP_WIN
    89   if (file instanceof Ci.nsILocalFileWin) {
    90     try {
    91       return file.getVersionInfoField("FileDescription");
    92     } catch (e) {}
    93   }
    94 #endif
    95 #ifdef XP_MACOSX
    96   if (file instanceof Ci.nsILocalFileMac) {
    97     try {
    98       return file.bundleDisplayName;
    99     } catch (e) {}
   100   }
   101 #endif
   102   return file.leafName;
   103 }
   105 function getLocalHandlerApp(aFile) {
   106   var localHandlerApp = Cc["@mozilla.org/uriloader/local-handler-app;1"].
   107                         createInstance(Ci.nsILocalHandlerApp);
   108   localHandlerApp.name = getFileDisplayName(aFile);
   109   localHandlerApp.executable = aFile;
   111   return localHandlerApp;
   112 }
   114 /**
   115  * An enumeration of items in a JS array.
   116  *
   117  * FIXME: use ArrayConverter once it lands (bug 380839).
   118  * 
   119  * @constructor
   120  */
   121 function ArrayEnumerator(aItems) {
   122   this._index = 0;
   123   this._contents = aItems;
   124 }
   126 ArrayEnumerator.prototype = {
   127   _index: 0,
   129   hasMoreElements: function() {
   130     return this._index < this._contents.length;
   131   },
   133   getNext: function() {
   134     return this._contents[this._index++];
   135   }
   136 };
   138 function isFeedType(t) {
   139   return t == TYPE_MAYBE_FEED || t == TYPE_MAYBE_VIDEO_FEED || t == TYPE_MAYBE_AUDIO_FEED;
   140 }
   142 //****************************************************************************//
   143 // HandlerInfoWrapper
   145 /**
   146  * This object wraps nsIHandlerInfo with some additional functionality
   147  * the Applications prefpane needs to display and allow modification of
   148  * the list of handled types.
   149  *
   150  * We create an instance of this wrapper for each entry we might display
   151  * in the prefpane, and we compose the instances from various sources,
   152  * including plugins and the handler service.
   153  *
   154  * We don't implement all the original nsIHandlerInfo functionality,
   155  * just the stuff that the prefpane needs.
   156  *
   157  * In theory, all of the custom functionality in this wrapper should get
   158  * pushed down into nsIHandlerInfo eventually.
   159  */
   160 function HandlerInfoWrapper(aType, aHandlerInfo) {
   161   this._type = aType;
   162   this.wrappedHandlerInfo = aHandlerInfo;
   163 }
   165 HandlerInfoWrapper.prototype = {
   166   // The wrapped nsIHandlerInfo object.  In general, this object is private,
   167   // but there are a couple cases where callers access it directly for things
   168   // we haven't (yet?) implemented, so we make it a public property.
   169   wrappedHandlerInfo: null,
   172   //**************************************************************************//
   173   // Convenience Utils
   175   _handlerSvc: Cc["@mozilla.org/uriloader/handler-service;1"].
   176                getService(Ci.nsIHandlerService),
   178   _prefSvc: Cc["@mozilla.org/preferences-service;1"].
   179             getService(Ci.nsIPrefBranch),
   181   _categoryMgr: Cc["@mozilla.org/categorymanager;1"].
   182                 getService(Ci.nsICategoryManager),
   184   element: function(aID) {
   185     return document.getElementById(aID);
   186   },
   189   //**************************************************************************//
   190   // nsIHandlerInfo
   192   // The MIME type or protocol scheme.
   193   _type: null,
   194   get type() {
   195     return this._type;
   196   },
   198   get description() {
   199     if (this.wrappedHandlerInfo.description)
   200       return this.wrappedHandlerInfo.description;
   202     if (this.primaryExtension) {
   203       var extension = this.primaryExtension.toUpperCase();
   204       return this.element("bundlePreferences").getFormattedString("fileEnding",
   205                                                                   [extension]);
   206     }
   208     return this.type;
   209   },
   211   get preferredApplicationHandler() {
   212     return this.wrappedHandlerInfo.preferredApplicationHandler;
   213   },
   215   set preferredApplicationHandler(aNewValue) {
   216     this.wrappedHandlerInfo.preferredApplicationHandler = aNewValue;
   218     // Make sure the preferred handler is in the set of possible handlers.
   219     if (aNewValue)
   220       this.addPossibleApplicationHandler(aNewValue)
   221   },
   223   get possibleApplicationHandlers() {
   224     return this.wrappedHandlerInfo.possibleApplicationHandlers;
   225   },
   227   addPossibleApplicationHandler: function(aNewHandler) {
   228     var possibleApps = this.possibleApplicationHandlers.enumerate();
   229     while (possibleApps.hasMoreElements()) {
   230       if (possibleApps.getNext().equals(aNewHandler))
   231         return;
   232     }
   233     this.possibleApplicationHandlers.appendElement(aNewHandler, false);
   234   },
   236   removePossibleApplicationHandler: function(aHandler) {
   237     var defaultApp = this.preferredApplicationHandler;
   238     if (defaultApp && aHandler.equals(defaultApp)) {
   239       // If the app we remove was the default app, we must make sure
   240       // it won't be used anymore
   241       this.alwaysAskBeforeHandling = true;
   242       this.preferredApplicationHandler = null;
   243     }
   245     var handlers = this.possibleApplicationHandlers;
   246     for (var i = 0; i < handlers.length; ++i) {
   247       var handler = handlers.queryElementAt(i, Ci.nsIHandlerApp);
   248       if (handler.equals(aHandler)) {
   249         handlers.removeElementAt(i);
   250         break;
   251       }
   252     }
   253   },
   255   get hasDefaultHandler() {
   256     return this.wrappedHandlerInfo.hasDefaultHandler;
   257   },
   259   get defaultDescription() {
   260     return this.wrappedHandlerInfo.defaultDescription;
   261   },
   263   // What to do with content of this type.
   264   get preferredAction() {
   265     // If we have an enabled plugin, then the action is to use that plugin.
   266     if (this.pluginName && !this.isDisabledPluginType)
   267       return kActionUsePlugin;
   269     // If the action is to use a helper app, but we don't have a preferred
   270     // handler app, then switch to using the system default, if any; otherwise
   271     // fall back to saving to disk, which is the default action in nsMIMEInfo.
   272     // Note: "save to disk" is an invalid value for protocol info objects,
   273     // but the alwaysAskBeforeHandling getter will detect that situation
   274     // and always return true in that case to override this invalid value.
   275     if (this.wrappedHandlerInfo.preferredAction == Ci.nsIHandlerInfo.useHelperApp &&
   276         !gApplicationsPane.isValidHandlerApp(this.preferredApplicationHandler)) {
   277       if (this.wrappedHandlerInfo.hasDefaultHandler)
   278         return Ci.nsIHandlerInfo.useSystemDefault;
   279       else
   280         return Ci.nsIHandlerInfo.saveToDisk;
   281     }
   283     return this.wrappedHandlerInfo.preferredAction;
   284   },
   286   set preferredAction(aNewValue) {
   287     // We don't modify the preferred action if the new action is to use a plugin
   288     // because handler info objects don't understand our custom "use plugin"
   289     // value.  Also, leaving it untouched means that we can automatically revert
   290     // to the old setting if the user ever removes the plugin.
   292     if (aNewValue != kActionUsePlugin)
   293       this.wrappedHandlerInfo.preferredAction = aNewValue;
   294   },
   296   get alwaysAskBeforeHandling() {
   297     // If this type is handled only by a plugin, we can't trust the value
   298     // in the handler info object, since it'll be a default based on the absence
   299     // of any user configuration, and the default in that case is to always ask,
   300     // even though we never ask for content handled by a plugin, so special case
   301     // plugin-handled types by returning false here.
   302     if (this.pluginName && this.handledOnlyByPlugin)
   303       return false;
   305     // If this is a protocol type and the preferred action is "save to disk",
   306     // which is invalid for such types, then return true here to override that
   307     // action.  This could happen when the preferred action is to use a helper
   308     // app, but the preferredApplicationHandler is invalid, and there isn't
   309     // a default handler, so the preferredAction getter returns save to disk
   310     // instead.
   311     if (!(this.wrappedHandlerInfo instanceof Ci.nsIMIMEInfo) &&
   312         this.preferredAction == Ci.nsIHandlerInfo.saveToDisk)
   313       return true;
   315     return this.wrappedHandlerInfo.alwaysAskBeforeHandling;
   316   },
   318   set alwaysAskBeforeHandling(aNewValue) {
   319     this.wrappedHandlerInfo.alwaysAskBeforeHandling = aNewValue;
   320   },
   323   //**************************************************************************//
   324   // nsIMIMEInfo
   326   // The primary file extension associated with this type, if any.
   327   //
   328   // XXX Plugin objects contain an array of MimeType objects with "suffixes"
   329   // properties; if this object has an associated plugin, shouldn't we check
   330   // those properties for an extension?
   331   get primaryExtension() {
   332     try {
   333       if (this.wrappedHandlerInfo instanceof Ci.nsIMIMEInfo &&
   334           this.wrappedHandlerInfo.primaryExtension)
   335         return this.wrappedHandlerInfo.primaryExtension
   336     } catch(ex) {}
   338     return null;
   339   },
   342   //**************************************************************************//
   343   // Plugin Handling
   345   // A plugin that can handle this type, if any.
   346   //
   347   // Note: just because we have one doesn't mean it *will* handle the type.
   348   // That depends on whether or not the type is in the list of types for which
   349   // plugin handling is disabled.
   350   plugin: null,
   352   // Whether or not this type is only handled by a plugin or is also handled
   353   // by some user-configured action as specified in the handler info object.
   354   //
   355   // Note: we can't just check if there's a handler info object for this type,
   356   // because OS and user configuration is mixed up in the handler info object,
   357   // so we always need to retrieve it for the OS info and can't tell whether
   358   // it represents only OS-default information or user-configured information.
   359   //
   360   // FIXME: once handler info records are broken up into OS-provided records
   361   // and user-configured records, stop using this boolean flag and simply
   362   // check for the presence of a user-configured record to determine whether
   363   // or not this type is only handled by a plugin.  Filed as bug 395142.
   364   handledOnlyByPlugin: undefined,
   366   get isDisabledPluginType() {
   367     return this._getDisabledPluginTypes().indexOf(this.type) != -1;
   368   },
   370   _getDisabledPluginTypes: function() {
   371     var types = "";
   373     if (this._prefSvc.prefHasUserValue(PREF_DISABLED_PLUGIN_TYPES))
   374       types = this._prefSvc.getCharPref(PREF_DISABLED_PLUGIN_TYPES);
   376     // Only split if the string isn't empty so we don't end up with an array
   377     // containing a single empty string.
   378     if (types != "")
   379       return types.split(",");
   381     return [];
   382   },
   384   disablePluginType: function() {
   385     var disabledPluginTypes = this._getDisabledPluginTypes();
   387     if (disabledPluginTypes.indexOf(this.type) == -1)
   388       disabledPluginTypes.push(this.type);
   390     this._prefSvc.setCharPref(PREF_DISABLED_PLUGIN_TYPES,
   391                               disabledPluginTypes.join(","));
   393     // Update the category manager so existing browser windows update.
   394     this._categoryMgr.deleteCategoryEntry("Gecko-Content-Viewers",
   395                                           this.type,
   396                                           false);
   397   },
   399   enablePluginType: function() {
   400     var disabledPluginTypes = this._getDisabledPluginTypes();
   402     var type = this.type;
   403     disabledPluginTypes = disabledPluginTypes.filter(function(v) v != type);
   405     this._prefSvc.setCharPref(PREF_DISABLED_PLUGIN_TYPES,
   406                               disabledPluginTypes.join(","));
   408     // Update the category manager so existing browser windows update.
   409     this._categoryMgr.
   410       addCategoryEntry("Gecko-Content-Viewers",
   411                        this.type,
   412                        "@mozilla.org/content/plugin/document-loader-factory;1",
   413                        false,
   414                        true);
   415   },
   418   //**************************************************************************//
   419   // Storage
   421   store: function() {
   422     this._handlerSvc.store(this.wrappedHandlerInfo);
   423   },
   426   //**************************************************************************//
   427   // Icons
   429   get smallIcon() {
   430     return this._getIcon(16);
   431   },
   433   _getIcon: function(aSize) {
   434     if (this.primaryExtension)
   435       return "moz-icon://goat." + this.primaryExtension + "?size=" + aSize;
   437     if (this.wrappedHandlerInfo instanceof Ci.nsIMIMEInfo)
   438       return "moz-icon://goat?size=" + aSize + "&contentType=" + this.type;
   440     // FIXME: consider returning some generic icon when we can't get a URL for
   441     // one (for example in the case of protocol schemes).  Filed as bug 395141.
   442     return null;
   443   }
   445 };
   448 //****************************************************************************//
   449 // Feed Handler Info
   451 /**
   452  * This object implements nsIHandlerInfo for the feed types.  It's a separate
   453  * object because we currently store handling information for the feed type
   454  * in a set of preferences rather than the nsIHandlerService-managed datastore.
   455  * 
   456  * This object inherits from HandlerInfoWrapper in order to get functionality
   457  * that isn't special to the feed type.
   458  * 
   459  * XXX Should we inherit from HandlerInfoWrapper?  After all, we override
   460  * most of that wrapper's properties and methods, and we have to dance around
   461  * the fact that the wrapper expects to have a wrappedHandlerInfo, which we
   462  * don't provide.
   463  */
   465 function FeedHandlerInfo(aMIMEType) {
   466   HandlerInfoWrapper.call(this, aMIMEType, null);
   467 }
   469 FeedHandlerInfo.prototype = {
   470   __proto__: HandlerInfoWrapper.prototype,
   472   //**************************************************************************//
   473   // Convenience Utils
   475   _converterSvc:
   476     Cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"].
   477     getService(Ci.nsIWebContentConverterService),
   479   _shellSvc:
   480 #ifdef HAVE_SHELL_SERVICE
   481     getShellService(),
   482 #else
   483     null,
   484 #endif
   487   //**************************************************************************//
   488   // nsIHandlerInfo
   490   get description() {
   491     return this.element("bundlePreferences").getString(this._appPrefLabel);
   492   },
   494   get preferredApplicationHandler() {
   495     switch (this.element(this._prefSelectedReader).value) {
   496       case "client":
   497         var file = this.element(this._prefSelectedApp).value;
   498         if (file)
   499           return getLocalHandlerApp(file);
   501         return null;
   503       case "web":
   504         var uri = this.element(this._prefSelectedWeb).value;
   505         if (!uri)
   506           return null;
   507         return this._converterSvc.getWebContentHandlerByURI(this.type, uri);
   509       case "bookmarks":
   510       default:
   511         // When the pref is set to bookmarks, we handle feeds internally,
   512         // we don't forward them to a local or web handler app, so there is
   513         // no preferred handler.
   514         return null;
   515     }
   516   },
   518   set preferredApplicationHandler(aNewValue) {
   519     if (aNewValue instanceof Ci.nsILocalHandlerApp) {
   520       this.element(this._prefSelectedApp).value = aNewValue.executable;
   521       this.element(this._prefSelectedReader).value = "client";
   522     }
   523     else if (aNewValue instanceof Ci.nsIWebContentHandlerInfo) {
   524       this.element(this._prefSelectedWeb).value = aNewValue.uri;
   525       this.element(this._prefSelectedReader).value = "web";
   526       // Make the web handler be the new "auto handler" for feeds.
   527       // Note: we don't have to unregister the auto handler when the user picks
   528       // a non-web handler (local app, Live Bookmarks, etc.) because the service
   529       // only uses the "auto handler" when the selected reader is a web handler.
   530       // We also don't have to unregister it when the user turns on "always ask"
   531       // (i.e. preview in browser), since that also overrides the auto handler.
   532       this._converterSvc.setAutoHandler(this.type, aNewValue);
   533     }
   534   },
   536   _possibleApplicationHandlers: null,
   538   get possibleApplicationHandlers() {
   539     if (this._possibleApplicationHandlers)
   540       return this._possibleApplicationHandlers;
   542     // A minimal implementation of nsIMutableArray.  It only supports the two
   543     // methods its callers invoke, namely appendElement and nsIArray::enumerate.
   544     this._possibleApplicationHandlers = {
   545       _inner: [],
   546       _removed: [],
   548       QueryInterface: function(aIID) {
   549         if (aIID.equals(Ci.nsIMutableArray) ||
   550             aIID.equals(Ci.nsIArray) ||
   551             aIID.equals(Ci.nsISupports))
   552           return this;
   554         throw Cr.NS_ERROR_NO_INTERFACE;
   555       },
   557       get length() {
   558         return this._inner.length;
   559       },
   561       enumerate: function() {
   562         return new ArrayEnumerator(this._inner);
   563       },
   565       appendElement: function(aHandlerApp, aWeak) {
   566         this._inner.push(aHandlerApp);
   567       },
   569       removeElementAt: function(aIndex) {
   570         this._removed.push(this._inner[aIndex]);
   571         this._inner.splice(aIndex, 1);
   572       },
   574       queryElementAt: function(aIndex, aInterface) {
   575         return this._inner[aIndex].QueryInterface(aInterface);
   576       }
   577     };
   579     // Add the selected local app if it's different from the OS default handler.
   580     // Unlike for other types, we can store only one local app at a time for the
   581     // feed type, since we store it in a preference that historically stores
   582     // only a single path.  But we display all the local apps the user chooses
   583     // while the prefpane is open, only dropping the list when the user closes
   584     // the prefpane, for maximum usability and consistency with other types.
   585     var preferredAppFile = this.element(this._prefSelectedApp).value;
   586     if (preferredAppFile) {
   587       let preferredApp = getLocalHandlerApp(preferredAppFile);
   588       let defaultApp = this._defaultApplicationHandler;
   589       if (!defaultApp || !defaultApp.equals(preferredApp))
   590         this._possibleApplicationHandlers.appendElement(preferredApp, false);
   591     }
   593     // Add the registered web handlers.  There can be any number of these.
   594     var webHandlers = this._converterSvc.getContentHandlers(this.type);
   595     for each (let webHandler in webHandlers)
   596       this._possibleApplicationHandlers.appendElement(webHandler, false);
   598     return this._possibleApplicationHandlers;
   599   },
   601   __defaultApplicationHandler: undefined,
   602   get _defaultApplicationHandler() {
   603     if (typeof this.__defaultApplicationHandler != "undefined")
   604       return this.__defaultApplicationHandler;
   606     var defaultFeedReader = null;
   607 #ifdef HAVE_SHELL_SERVICE
   608     try {
   609       defaultFeedReader = this._shellSvc.defaultFeedReader;
   610     }
   611     catch(ex) {
   612       // no default reader or _shellSvc is null
   613     }
   614 #endif
   616     if (defaultFeedReader) {
   617       let handlerApp = Cc["@mozilla.org/uriloader/local-handler-app;1"].
   618                        createInstance(Ci.nsIHandlerApp);
   619       handlerApp.name = getFileDisplayName(defaultFeedReader);
   620       handlerApp.QueryInterface(Ci.nsILocalHandlerApp);
   621       handlerApp.executable = defaultFeedReader;
   623       this.__defaultApplicationHandler = handlerApp;
   624     }
   625     else {
   626       this.__defaultApplicationHandler = null;
   627     }
   629     return this.__defaultApplicationHandler;
   630   },
   632   get hasDefaultHandler() {
   633 #ifdef HAVE_SHELL_SERVICE
   634     try {
   635       if (this._shellSvc.defaultFeedReader)
   636         return true;
   637     }
   638     catch(ex) {
   639       // no default reader or _shellSvc is null
   640     }
   641 #endif
   643     return false;
   644   },
   646   get defaultDescription() {
   647     if (this.hasDefaultHandler)
   648       return this._defaultApplicationHandler.name;
   650     // Should we instead return null?
   651     return "";
   652   },
   654   // What to do with content of this type.
   655   get preferredAction() {
   656     switch (this.element(this._prefSelectedAction).value) {
   658       case "bookmarks":
   659         return Ci.nsIHandlerInfo.handleInternally;
   661       case "reader": {
   662         let preferredApp = this.preferredApplicationHandler;
   663         let defaultApp = this._defaultApplicationHandler;
   665         // If we have a valid preferred app, return useSystemDefault if it's
   666         // the default app; otherwise return useHelperApp.
   667         if (gApplicationsPane.isValidHandlerApp(preferredApp)) {
   668           if (defaultApp && defaultApp.equals(preferredApp))
   669             return Ci.nsIHandlerInfo.useSystemDefault;
   671           return Ci.nsIHandlerInfo.useHelperApp;
   672         }
   674         // The pref is set to "reader", but we don't have a valid preferred app.
   675         // What do we do now?  Not sure this is the best option (perhaps we
   676         // should direct the user to the default app, if any), but for now let's
   677         // direct the user to live bookmarks.
   678         return Ci.nsIHandlerInfo.handleInternally;
   679       }
   681       // If the action is "ask", then alwaysAskBeforeHandling will override
   682       // the action, so it doesn't matter what we say it is, it just has to be
   683       // something that doesn't cause the controller to hide the type.
   684       case "ask":
   685       default:
   686         return Ci.nsIHandlerInfo.handleInternally;
   687     }
   688   },
   690   set preferredAction(aNewValue) {
   691     switch (aNewValue) {
   693       case Ci.nsIHandlerInfo.handleInternally:
   694         this.element(this._prefSelectedReader).value = "bookmarks";
   695         break;
   697       case Ci.nsIHandlerInfo.useHelperApp:
   698         this.element(this._prefSelectedAction).value = "reader";
   699         // The controller has already set preferredApplicationHandler
   700         // to the new helper app.
   701         break;
   703       case Ci.nsIHandlerInfo.useSystemDefault:
   704         this.element(this._prefSelectedAction).value = "reader";
   705         this.preferredApplicationHandler = this._defaultApplicationHandler;
   706         break;
   707     }
   708   },
   710   get alwaysAskBeforeHandling() {
   711     return this.element(this._prefSelectedAction).value == "ask";
   712   },
   714   set alwaysAskBeforeHandling(aNewValue) {
   715     if (aNewValue == true)
   716       this.element(this._prefSelectedAction).value = "ask";
   717     else
   718       this.element(this._prefSelectedAction).value = "reader";
   719   },
   721   // Whether or not we are currently storing the action selected by the user.
   722   // We use this to suppress notification-triggered updates to the list when
   723   // we make changes that may spawn such updates, specifically when we change
   724   // the action for the feed type, which results in feed preference updates,
   725   // which spawn "pref changed" notifications that would otherwise cause us
   726   // to rebuild the view unnecessarily.
   727   _storingAction: false,
   730   //**************************************************************************//
   731   // nsIMIMEInfo
   733   get primaryExtension() {
   734     return "xml";
   735   },
   738   //**************************************************************************//
   739   // Storage
   741   // Changes to the preferred action and handler take effect immediately
   742   // (we write them out to the preferences right as they happen),
   743   // so we when the controller calls store() after modifying the handlers,
   744   // the only thing we need to store is the removal of possible handlers
   745   // XXX Should we hold off on making the changes until this method gets called?
   746   store: function() {
   747     for each (let app in this._possibleApplicationHandlers._removed) {
   748       if (app instanceof Ci.nsILocalHandlerApp) {
   749         let pref = this.element(PREF_FEED_SELECTED_APP);
   750         var preferredAppFile = pref.value;
   751         if (preferredAppFile) {
   752           let preferredApp = getLocalHandlerApp(preferredAppFile);
   753           if (app.equals(preferredApp))
   754             pref.reset();
   755         }
   756       }
   757       else {
   758         app.QueryInterface(Ci.nsIWebContentHandlerInfo);
   759         this._converterSvc.removeContentHandler(app.contentType, app.uri);
   760       }
   761     }
   762     this._possibleApplicationHandlers._removed = [];
   763   },
   766   //**************************************************************************//
   767   // Icons
   769   get smallIcon() {
   770     return this._smallIcon;
   771   }
   773 };
   775 var feedHandlerInfo = {
   776   __proto__: new FeedHandlerInfo(TYPE_MAYBE_FEED),
   777   _prefSelectedApp: PREF_FEED_SELECTED_APP, 
   778   _prefSelectedWeb: PREF_FEED_SELECTED_WEB, 
   779   _prefSelectedAction: PREF_FEED_SELECTED_ACTION, 
   780   _prefSelectedReader: PREF_FEED_SELECTED_READER,
   781   _smallIcon: "chrome://browser/skin/feeds/feedIcon16.png",
   782   _appPrefLabel: "webFeed"
   783 }
   785 var videoFeedHandlerInfo = {
   786   __proto__: new FeedHandlerInfo(TYPE_MAYBE_VIDEO_FEED),
   787   _prefSelectedApp: PREF_VIDEO_FEED_SELECTED_APP, 
   788   _prefSelectedWeb: PREF_VIDEO_FEED_SELECTED_WEB, 
   789   _prefSelectedAction: PREF_VIDEO_FEED_SELECTED_ACTION, 
   790   _prefSelectedReader: PREF_VIDEO_FEED_SELECTED_READER,
   791   _smallIcon: "chrome://browser/skin/feeds/videoFeedIcon16.png",
   792   _appPrefLabel: "videoPodcastFeed"
   793 }
   795 var audioFeedHandlerInfo = {
   796   __proto__: new FeedHandlerInfo(TYPE_MAYBE_AUDIO_FEED),
   797   _prefSelectedApp: PREF_AUDIO_FEED_SELECTED_APP, 
   798   _prefSelectedWeb: PREF_AUDIO_FEED_SELECTED_WEB, 
   799   _prefSelectedAction: PREF_AUDIO_FEED_SELECTED_ACTION, 
   800   _prefSelectedReader: PREF_AUDIO_FEED_SELECTED_READER,
   801   _smallIcon: "chrome://browser/skin/feeds/audioFeedIcon16.png",
   802   _appPrefLabel: "audioPodcastFeed"
   803 }
   805 /**
   806  * InternalHandlerInfoWrapper provides a basic mechanism to create an internal
   807  * mime type handler that can be enabled/disabled in the applications preference
   808  * menu.
   809  */
   810 function InternalHandlerInfoWrapper(aMIMEType) {
   811   var mimeSvc = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
   812   var handlerInfo = mimeSvc.getFromTypeAndExtension(aMIMEType, null);
   814   HandlerInfoWrapper.call(this, aMIMEType, handlerInfo);
   815 }
   817 InternalHandlerInfoWrapper.prototype = {
   818   __proto__: HandlerInfoWrapper.prototype,
   820   // Override store so we so we can notify any code listening for registration
   821   // or unregistration of this handler.
   822   store: function() {
   823     HandlerInfoWrapper.prototype.store.call(this);
   824     Services.obs.notifyObservers(null, this._handlerChanged, null);
   825   },
   827   get enabled() {
   828     throw Cr.NS_ERROR_NOT_IMPLEMENTED;
   829   },
   831   get description() {
   832     return this.element("bundlePreferences").getString(this._appPrefLabel);
   833   }
   834 };
   836 var pdfHandlerInfo = {
   837   __proto__: new InternalHandlerInfoWrapper(TYPE_PDF),
   838   _handlerChanged: TOPIC_PDFJS_HANDLER_CHANGED,
   839   _appPrefLabel: "portableDocumentFormat",
   840   get enabled() {
   841     return !Services.prefs.getBoolPref(PREF_PDFJS_DISABLED);
   842   },
   843 };
   846 //****************************************************************************//
   847 // Prefpane Controller
   849 var gApplicationsPane = {
   850   // The set of types the app knows how to handle.  A hash of HandlerInfoWrapper
   851   // objects, indexed by type.
   852   _handledTypes: {},
   854   // The list of types we can show, sorted by the sort column/direction.
   855   // An array of HandlerInfoWrapper objects.  We build this list when we first
   856   // load the data and then rebuild it when users change a pref that affects
   857   // what types we can show or change the sort column/direction.
   858   // Note: this isn't necessarily the list of types we *will* show; if the user
   859   // provides a filter string, we'll only show the subset of types in this list
   860   // that match that string.
   861   _visibleTypes: [],
   863   // A count of the number of times each visible type description appears.
   864   // We use these counts to determine whether or not to annotate descriptions
   865   // with their types to distinguish duplicate descriptions from each other.
   866   // A hash of integer counts, indexed by string description.
   867   _visibleTypeDescriptionCount: {},
   870   //**************************************************************************//
   871   // Convenience & Performance Shortcuts
   873   // These get defined by init().
   874   _brandShortName : null,
   875   _prefsBundle    : null,
   876   _list           : null,
   877   _filter         : null,
   879   _prefSvc      : Cc["@mozilla.org/preferences-service;1"].
   880                   getService(Ci.nsIPrefBranch),
   882   _mimeSvc      : Cc["@mozilla.org/mime;1"].
   883                   getService(Ci.nsIMIMEService),
   885   _helperAppSvc : Cc["@mozilla.org/uriloader/external-helper-app-service;1"].
   886                   getService(Ci.nsIExternalHelperAppService),
   888   _handlerSvc   : Cc["@mozilla.org/uriloader/handler-service;1"].
   889                   getService(Ci.nsIHandlerService),
   891   _ioSvc        : Cc["@mozilla.org/network/io-service;1"].
   892                   getService(Ci.nsIIOService),
   895   //**************************************************************************//
   896   // Initialization & Destruction
   898   init: function() {
   899     // Initialize shortcuts to some commonly accessed elements & values.
   900     this._brandShortName =
   901       document.getElementById("bundleBrand").getString("brandShortName");
   902     this._prefsBundle = document.getElementById("bundlePreferences");
   903     this._list = document.getElementById("handlersView");
   904     this._filter = document.getElementById("filter");
   906     // Observe preferences that influence what we display so we can rebuild
   907     // the view when they change.
   908     this._prefSvc.addObserver(PREF_SHOW_PLUGINS_IN_LIST, this, false);
   909     this._prefSvc.addObserver(PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS, this, false);
   910     this._prefSvc.addObserver(PREF_FEED_SELECTED_APP, this, false);
   911     this._prefSvc.addObserver(PREF_FEED_SELECTED_WEB, this, false);
   912     this._prefSvc.addObserver(PREF_FEED_SELECTED_ACTION, this, false);
   913     this._prefSvc.addObserver(PREF_FEED_SELECTED_READER, this, false);
   915     this._prefSvc.addObserver(PREF_VIDEO_FEED_SELECTED_APP, this, false);
   916     this._prefSvc.addObserver(PREF_VIDEO_FEED_SELECTED_WEB, this, false);
   917     this._prefSvc.addObserver(PREF_VIDEO_FEED_SELECTED_ACTION, this, false);
   918     this._prefSvc.addObserver(PREF_VIDEO_FEED_SELECTED_READER, this, false);
   920     this._prefSvc.addObserver(PREF_AUDIO_FEED_SELECTED_APP, this, false);
   921     this._prefSvc.addObserver(PREF_AUDIO_FEED_SELECTED_WEB, this, false);
   922     this._prefSvc.addObserver(PREF_AUDIO_FEED_SELECTED_ACTION, this, false);
   923     this._prefSvc.addObserver(PREF_AUDIO_FEED_SELECTED_READER, this, false);
   926     // Listen for window unload so we can remove our preference observers.
   927     window.addEventListener("unload", this, false);
   929     // Figure out how we should be sorting the list.  We persist sort settings
   930     // across sessions, so we can't assume the default sort column/direction.
   931     // XXX should we be using the XUL sort service instead?
   932     if (document.getElementById("actionColumn").hasAttribute("sortDirection")) {
   933       this._sortColumn = document.getElementById("actionColumn");
   934       // The typeColumn element always has a sortDirection attribute,
   935       // either because it was persisted or because the default value
   936       // from the xul file was used.  If we are sorting on the other
   937       // column, we should remove it.
   938       document.getElementById("typeColumn").removeAttribute("sortDirection");
   939     }
   940     else 
   941       this._sortColumn = document.getElementById("typeColumn");
   943     // Load the data and build the list of handlers.
   944     // By doing this in a timeout, we let the preferences dialog resize itself
   945     // to an appropriate size before we add a bunch of items to the list.
   946     // Otherwise, if there are many items, and the Applications prefpane
   947     // is the one that gets displayed when the user first opens the dialog,
   948     // the dialog might stretch too much in an attempt to fit them all in.
   949     // XXX Shouldn't we perhaps just set a max-height on the richlistbox?
   950     var _delayedPaneLoad = function(self) {
   951       self._loadData();
   952       self._rebuildVisibleTypes();
   953       self._sortVisibleTypes();
   954       self._rebuildView();
   956       // Notify observers that the UI is now ready
   957       Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService).
   958       notifyObservers(window, "app-handler-pane-loaded", null);
   959     }
   960     setTimeout(_delayedPaneLoad, 0, this);
   961   },
   963   destroy: function() {
   964     window.removeEventListener("unload", this, false);
   965     this._prefSvc.removeObserver(PREF_SHOW_PLUGINS_IN_LIST, this);
   966     this._prefSvc.removeObserver(PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS, this);
   967     this._prefSvc.removeObserver(PREF_FEED_SELECTED_APP, this);
   968     this._prefSvc.removeObserver(PREF_FEED_SELECTED_WEB, this);
   969     this._prefSvc.removeObserver(PREF_FEED_SELECTED_ACTION, this);
   970     this._prefSvc.removeObserver(PREF_FEED_SELECTED_READER, this);
   972     this._prefSvc.removeObserver(PREF_VIDEO_FEED_SELECTED_APP, this);
   973     this._prefSvc.removeObserver(PREF_VIDEO_FEED_SELECTED_WEB, this);
   974     this._prefSvc.removeObserver(PREF_VIDEO_FEED_SELECTED_ACTION, this);
   975     this._prefSvc.removeObserver(PREF_VIDEO_FEED_SELECTED_READER, this);
   977     this._prefSvc.removeObserver(PREF_AUDIO_FEED_SELECTED_APP, this);
   978     this._prefSvc.removeObserver(PREF_AUDIO_FEED_SELECTED_WEB, this);
   979     this._prefSvc.removeObserver(PREF_AUDIO_FEED_SELECTED_ACTION, this);
   980     this._prefSvc.removeObserver(PREF_AUDIO_FEED_SELECTED_READER, this);
   981   },
   984   //**************************************************************************//
   985   // nsISupports
   987   QueryInterface: function(aIID) {
   988     if (aIID.equals(Ci.nsIObserver) ||
   989         aIID.equals(Ci.nsIDOMEventListener ||
   990         aIID.equals(Ci.nsISupports)))
   991       return this;
   993     throw Cr.NS_ERROR_NO_INTERFACE;
   994   },
   997   //**************************************************************************//
   998   // nsIObserver
  1000   observe: function (aSubject, aTopic, aData) {
  1001     // Rebuild the list when there are changes to preferences that influence
  1002     // whether or not to show certain entries in the list.
  1003     if (aTopic == "nsPref:changed" && !this._storingAction) {
  1004       // These two prefs alter the list of visible types, so we have to rebuild
  1005       // that list when they change.
  1006       if (aData == PREF_SHOW_PLUGINS_IN_LIST ||
  1007           aData == PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS) {
  1008         this._rebuildVisibleTypes();
  1009         this._sortVisibleTypes();
  1012       // All the prefs we observe can affect what we display, so we rebuild
  1013       // the view when any of them changes.
  1014       this._rebuildView();
  1016   },
  1019   //**************************************************************************//
  1020   // nsIDOMEventListener
  1022   handleEvent: function(aEvent) {
  1023     if (aEvent.type == "unload") {
  1024       this.destroy();
  1026   },
  1029   //**************************************************************************//
  1030   // Composed Model Construction
  1032   _loadData: function() {
  1033     this._loadFeedHandler();
  1034     this._loadInternalHandlers();
  1035     this._loadPluginHandlers();
  1036     this._loadApplicationHandlers();
  1037   },
  1039   _loadFeedHandler: function() {
  1040     this._handledTypes[TYPE_MAYBE_FEED] = feedHandlerInfo;
  1041     feedHandlerInfo.handledOnlyByPlugin = false;
  1043     this._handledTypes[TYPE_MAYBE_VIDEO_FEED] = videoFeedHandlerInfo;
  1044     videoFeedHandlerInfo.handledOnlyByPlugin = false;
  1046     this._handledTypes[TYPE_MAYBE_AUDIO_FEED] = audioFeedHandlerInfo;
  1047     audioFeedHandlerInfo.handledOnlyByPlugin = false;
  1048   },
  1050   /**
  1051    * Load higher level internal handlers so they can be turned on/off in the
  1052    * applications menu.
  1053    */
  1054   _loadInternalHandlers: function() {
  1055     var internalHandlers = [pdfHandlerInfo];
  1056     for (let internalHandler of internalHandlers) {
  1057       if (internalHandler.enabled) {
  1058         this._handledTypes[internalHandler.type] = internalHandler;
  1061   },
  1063   /**
  1064    * Load the set of handlers defined by plugins.
  1066    * Note: if there's more than one plugin for a given MIME type, we assume
  1067    * the last one is the one that the application will use.  That may not be
  1068    * correct, but it's how we've been doing it for years.
  1070    * Perhaps we should instead query navigator.mimeTypes for the set of types
  1071    * supported by the application and then get the plugin from each MIME type's
  1072    * enabledPlugin property.  But if there's a plugin for a type, we need
  1073    * to know about it even if it isn't enabled, since we're going to give
  1074    * the user an option to enable it.
  1076    * Also note that enabledPlugin does not get updated when
  1077    * plugin.disable_full_page_plugin_for_types changes, so even if we could use
  1078    * enabledPlugin to get the plugin that would be used, we'd still need to
  1079    * check the pref ourselves to find out if it's enabled.
  1080    */
  1081   _loadPluginHandlers: function() {
  1082     "use strict";
  1084     let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);
  1085     let pluginTags = pluginHost.getPluginTags();
  1087     for (let i = 0; i < pluginTags.length; ++i) {
  1088       let pluginTag = pluginTags[i];
  1090       let mimeTypes = pluginTag.getMimeTypes();
  1091       for (let j = 0; j < mimeTypes.length; ++j) {
  1092         let type = mimeTypes[j];
  1094         let handlerInfoWrapper;
  1095         if (type in this._handledTypes)
  1096           handlerInfoWrapper = this._handledTypes[type];
  1097         else {
  1098           let wrappedHandlerInfo =
  1099             this._mimeSvc.getFromTypeAndExtension(type, null);
  1100           handlerInfoWrapper = new HandlerInfoWrapper(type, wrappedHandlerInfo);
  1101           handlerInfoWrapper.handledOnlyByPlugin = true;
  1102           this._handledTypes[type] = handlerInfoWrapper;
  1105         handlerInfoWrapper.pluginName = pluginTag.name;
  1108   },
  1110   /**
  1111    * Load the set of handlers defined by the application datastore.
  1112    */
  1113   _loadApplicationHandlers: function() {
  1114     var wrappedHandlerInfos = this._handlerSvc.enumerate();
  1115     while (wrappedHandlerInfos.hasMoreElements()) {
  1116       let wrappedHandlerInfo =
  1117         wrappedHandlerInfos.getNext().QueryInterface(Ci.nsIHandlerInfo);
  1118       let type = wrappedHandlerInfo.type;
  1120       let handlerInfoWrapper;
  1121       if (type in this._handledTypes)
  1122         handlerInfoWrapper = this._handledTypes[type];
  1123       else {
  1124         handlerInfoWrapper = new HandlerInfoWrapper(type, wrappedHandlerInfo);
  1125         this._handledTypes[type] = handlerInfoWrapper;
  1128       handlerInfoWrapper.handledOnlyByPlugin = false;
  1130   },
  1133   //**************************************************************************//
  1134   // View Construction
  1136   _rebuildVisibleTypes: function() {
  1137     // Reset the list of visible types and the visible type description counts.
  1138     this._visibleTypes = [];
  1139     this._visibleTypeDescriptionCount = {};
  1141     // Get the preferences that help determine what types to show.
  1142     var showPlugins = this._prefSvc.getBoolPref(PREF_SHOW_PLUGINS_IN_LIST);
  1143     var hidePluginsWithoutExtensions =
  1144       this._prefSvc.getBoolPref(PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS);
  1146     for (let type in this._handledTypes) {
  1147       let handlerInfo = this._handledTypes[type];
  1149       // Hide plugins without associated extensions if so prefed so we don't
  1150       // show a whole bunch of obscure types handled by plugins on Mac.
  1151       // Note: though protocol types don't have extensions, we still show them;
  1152       // the pref is only meant to be applied to MIME types, since plugins are
  1153       // only associated with MIME types.
  1154       // FIXME: should we also check the "suffixes" property of the plugin?
  1155       // Filed as bug 395135.
  1156       if (hidePluginsWithoutExtensions && handlerInfo.handledOnlyByPlugin &&
  1157           handlerInfo.wrappedHandlerInfo instanceof Ci.nsIMIMEInfo &&
  1158           !handlerInfo.primaryExtension)
  1159         continue;
  1161       // Hide types handled only by plugins if so prefed.
  1162       if (handlerInfo.handledOnlyByPlugin && !showPlugins)
  1163         continue;
  1165       // We couldn't find any reason to exclude the type, so include it.
  1166       this._visibleTypes.push(handlerInfo);
  1168       if (handlerInfo.description in this._visibleTypeDescriptionCount)
  1169         this._visibleTypeDescriptionCount[handlerInfo.description]++;
  1170       else
  1171         this._visibleTypeDescriptionCount[handlerInfo.description] = 1;
  1173   },
  1175   _rebuildView: function() {
  1176     // Clear the list of entries.
  1177     while (this._list.childNodes.length > 1)
  1178       this._list.removeChild(this._list.lastChild);
  1180     var visibleTypes = this._visibleTypes;
  1182     // If the user is filtering the list, then only show matching types.
  1183     if (this._filter.value)
  1184       visibleTypes = visibleTypes.filter(this._matchesFilter, this);
  1186     for each (let visibleType in visibleTypes) {
  1187       let item = document.createElement("richlistitem");
  1188       item.setAttribute("type", visibleType.type);
  1189       item.setAttribute("typeDescription", this._describeType(visibleType));
  1190       if (visibleType.smallIcon)
  1191         item.setAttribute("typeIcon", visibleType.smallIcon);
  1192       item.setAttribute("actionDescription",
  1193                         this._describePreferredAction(visibleType));
  1195       if (!this._setIconClassForPreferredAction(visibleType, item)) {
  1196         item.setAttribute("actionIcon",
  1197                           this._getIconURLForPreferredAction(visibleType));
  1200       this._list.appendChild(item);
  1203     this._selectLastSelectedType();
  1204   },
  1206   _matchesFilter: function(aType) {
  1207     var filterValue = this._filter.value.toLowerCase();
  1208     return this._describeType(aType).toLowerCase().indexOf(filterValue) != -1 ||
  1209            this._describePreferredAction(aType).toLowerCase().indexOf(filterValue) != -1;
  1210   },
  1212   /**
  1213    * Describe, in a human-readable fashion, the type represented by the given
  1214    * handler info object.  Normally this is just the description provided by
  1215    * the info object, but if more than one object presents the same description,
  1216    * then we annotate the duplicate descriptions with the type itself to help
  1217    * users distinguish between those types.
  1219    * @param aHandlerInfo {nsIHandlerInfo} the type being described
  1220    * @returns {string} a description of the type
  1221    */
  1222   _describeType: function(aHandlerInfo) {
  1223     if (this._visibleTypeDescriptionCount[aHandlerInfo.description] > 1)
  1224       return this._prefsBundle.getFormattedString("typeDescriptionWithType",
  1225                                                   [aHandlerInfo.description,
  1226                                                    aHandlerInfo.type]);
  1228     return aHandlerInfo.description;
  1229   },
  1231   /**
  1232    * Describe, in a human-readable fashion, the preferred action to take on
  1233    * the type represented by the given handler info object.
  1235    * XXX Should this be part of the HandlerInfoWrapper interface?  It would
  1236    * violate the separation of model and view, but it might make more sense
  1237    * nonetheless (f.e. it would make sortTypes easier).
  1239    * @param aHandlerInfo {nsIHandlerInfo} the type whose preferred action
  1240    *                                      is being described
  1241    * @returns {string} a description of the action
  1242    */
  1243   _describePreferredAction: function(aHandlerInfo) {
  1244     // alwaysAskBeforeHandling overrides the preferred action, so if that flag
  1245     // is set, then describe that behavior instead.  For most types, this is
  1246     // the "alwaysAsk" string, but for the feed type we show something special.
  1247     if (aHandlerInfo.alwaysAskBeforeHandling) {
  1248       if (isFeedType(aHandlerInfo.type))
  1249         return this._prefsBundle.getFormattedString("previewInApp",
  1250                                                     [this._brandShortName]);
  1251       else
  1252         return this._prefsBundle.getString("alwaysAsk");
  1255     switch (aHandlerInfo.preferredAction) {
  1256       case Ci.nsIHandlerInfo.saveToDisk:
  1257         return this._prefsBundle.getString("saveFile");
  1259       case Ci.nsIHandlerInfo.useHelperApp:
  1260         var preferredApp = aHandlerInfo.preferredApplicationHandler;
  1261         var name;
  1262         if (preferredApp instanceof Ci.nsILocalHandlerApp)
  1263           name = getFileDisplayName(preferredApp.executable);
  1264         else
  1265           name = preferredApp.name;
  1266         return this._prefsBundle.getFormattedString("useApp", [name]);
  1268       case Ci.nsIHandlerInfo.handleInternally:
  1269         // For the feed type, handleInternally means live bookmarks.
  1270         if (isFeedType(aHandlerInfo.type)) {
  1271           return this._prefsBundle.getFormattedString("addLiveBookmarksInApp",
  1272                                                       [this._brandShortName]);
  1275         if (aHandlerInfo instanceof InternalHandlerInfoWrapper) {
  1276           return this._prefsBundle.getFormattedString("previewInApp",
  1277                                                       [this._brandShortName]);
  1280         // For other types, handleInternally looks like either useHelperApp
  1281         // or useSystemDefault depending on whether or not there's a preferred
  1282         // handler app.
  1283         if (this.isValidHandlerApp(aHandlerInfo.preferredApplicationHandler))
  1284           return aHandlerInfo.preferredApplicationHandler.name;
  1286         return aHandlerInfo.defaultDescription;
  1288         // XXX Why don't we say the app will handle the type internally?
  1289         // Is it because the app can't actually do that?  But if that's true,
  1290         // then why would a preferredAction ever get set to this value
  1291         // in the first place?
  1293       case Ci.nsIHandlerInfo.useSystemDefault:
  1294         return this._prefsBundle.getFormattedString("useDefault",
  1295                                                     [aHandlerInfo.defaultDescription]);
  1297       case kActionUsePlugin:
  1298         return this._prefsBundle.getFormattedString("usePluginIn",
  1299                                                     [aHandlerInfo.pluginName,
  1300                                                      this._brandShortName]);
  1302   },
  1304   _selectLastSelectedType: function() {
  1305     // If the list is disabled by the pref.downloads.disable_button.edit_actions
  1306     // preference being locked, then don't select the type, as that would cause
  1307     // it to appear selected, with a different background and an actions menu
  1308     // that makes it seem like you can choose an action for the type.
  1309     if (this._list.disabled)
  1310       return;
  1312     var lastSelectedType = this._list.getAttribute("lastSelectedType");
  1313     if (!lastSelectedType)
  1314       return;
  1316     var item = this._list.getElementsByAttribute("type", lastSelectedType)[0];
  1317     if (!item)
  1318       return;
  1320     this._list.selectedItem = item;
  1321   },
  1323   /**
  1324    * Whether or not the given handler app is valid.
  1326    * @param aHandlerApp {nsIHandlerApp} the handler app in question
  1328    * @returns {boolean} whether or not it's valid
  1329    */
  1330   isValidHandlerApp: function(aHandlerApp) {
  1331     if (!aHandlerApp)
  1332       return false;
  1334     if (aHandlerApp instanceof Ci.nsILocalHandlerApp)
  1335       return this._isValidHandlerExecutable(aHandlerApp.executable);
  1337     if (aHandlerApp instanceof Ci.nsIWebHandlerApp)
  1338       return aHandlerApp.uriTemplate;
  1340     if (aHandlerApp instanceof Ci.nsIWebContentHandlerInfo)
  1341       return aHandlerApp.uri;
  1343     return false;
  1344   },
  1346   _isValidHandlerExecutable: function(aExecutable) {
  1347     return aExecutable &&
  1348            aExecutable.exists() &&
  1349            aExecutable.isExecutable() &&
  1350 // XXXben - we need to compare this with the running instance executable
  1351 //          just don't know how to do that via script...
  1352 // XXXmano TBD: can probably add this to nsIShellService
  1353 #ifdef XP_WIN
  1354 #expand    aExecutable.leafName != "__MOZ_APP_NAME__.exe";
  1355 #else
  1356 #ifdef XP_MACOSX
  1357 #expand    aExecutable.leafName != "__MOZ_MACBUNDLE_NAME__";
  1358 #else
  1359 #expand    aExecutable.leafName != "__MOZ_APP_NAME__-bin";
  1360 #endif
  1361 #endif
  1362   },
  1364   /**
  1365    * Rebuild the actions menu for the selected entry.  Gets called by
  1366    * the richlistitem constructor when an entry in the list gets selected.
  1367    */
  1368   rebuildActionsMenu: function() {
  1369     var typeItem = this._list.selectedItem;
  1370     var handlerInfo = this._handledTypes[typeItem.type];
  1371     var menu =
  1372       document.getAnonymousElementByAttribute(typeItem, "class", "actionsMenu");
  1373     var menuPopup = menu.menupopup;
  1375     // Clear out existing items.
  1376     while (menuPopup.hasChildNodes())
  1377       menuPopup.removeChild(menuPopup.lastChild);
  1379     // Add the "Preview in Firefox" option for optional internal handlers.
  1380     if (handlerInfo instanceof InternalHandlerInfoWrapper) {
  1381       var internalMenuItem = document.createElement("menuitem");
  1382       internalMenuItem.setAttribute("action", Ci.nsIHandlerInfo.handleInternally);
  1383       let label = this._prefsBundle.getFormattedString("previewInApp",
  1384                                                        [this._brandShortName]);
  1385       internalMenuItem.setAttribute("label", label);
  1386       internalMenuItem.setAttribute("tooltiptext", label);
  1387       internalMenuItem.setAttribute(APP_ICON_ATTR_NAME, "ask");
  1388       menuPopup.appendChild(internalMenuItem);
  1392       var askMenuItem = document.createElement("menuitem");
  1393       askMenuItem.setAttribute("alwaysAsk", "true");
  1394       let label;
  1395       if (isFeedType(handlerInfo.type))
  1396         label = this._prefsBundle.getFormattedString("previewInApp",
  1397                                                      [this._brandShortName]);
  1398       else
  1399         label = this._prefsBundle.getString("alwaysAsk");
  1400       askMenuItem.setAttribute("label", label);
  1401       askMenuItem.setAttribute("tooltiptext", label);
  1402       askMenuItem.setAttribute(APP_ICON_ATTR_NAME, "ask");
  1403       menuPopup.appendChild(askMenuItem);
  1406     // Create a menu item for saving to disk.
  1407     // Note: this option isn't available to protocol types, since we don't know
  1408     // what it means to save a URL having a certain scheme to disk, nor is it
  1409     // available to feeds, since the feed code doesn't implement the capability.
  1410     if ((handlerInfo.wrappedHandlerInfo instanceof Ci.nsIMIMEInfo) &&
  1411         !isFeedType(handlerInfo.type)) {
  1412       var saveMenuItem = document.createElement("menuitem");
  1413       saveMenuItem.setAttribute("action", Ci.nsIHandlerInfo.saveToDisk);
  1414       let label = this._prefsBundle.getString("saveFile");
  1415       saveMenuItem.setAttribute("label", label);
  1416       saveMenuItem.setAttribute("tooltiptext", label);
  1417       saveMenuItem.setAttribute(APP_ICON_ATTR_NAME, "save");
  1418       menuPopup.appendChild(saveMenuItem);
  1421     // If this is the feed type, add a Live Bookmarks item.
  1422     if (isFeedType(handlerInfo.type)) {
  1423       var internalMenuItem = document.createElement("menuitem");
  1424       internalMenuItem.setAttribute("action", Ci.nsIHandlerInfo.handleInternally);
  1425       let label = this._prefsBundle.getFormattedString("addLiveBookmarksInApp",
  1426                                                        [this._brandShortName]);
  1427       internalMenuItem.setAttribute("label", label);
  1428       internalMenuItem.setAttribute("tooltiptext", label);
  1429       internalMenuItem.setAttribute(APP_ICON_ATTR_NAME, "feed");
  1430       menuPopup.appendChild(internalMenuItem);
  1433     // Add a separator to distinguish these items from the helper app items
  1434     // that follow them.
  1435     let menuItem = document.createElement("menuseparator");
  1436     menuPopup.appendChild(menuItem);
  1438     // Create a menu item for the OS default application, if any.
  1439     if (handlerInfo.hasDefaultHandler) {
  1440       var defaultMenuItem = document.createElement("menuitem");
  1441       defaultMenuItem.setAttribute("action", Ci.nsIHandlerInfo.useSystemDefault);
  1442       let label = this._prefsBundle.getFormattedString("useDefault",
  1443                                                        [handlerInfo.defaultDescription]);
  1444       defaultMenuItem.setAttribute("label", label);
  1445       defaultMenuItem.setAttribute("tooltiptext", handlerInfo.defaultDescription);
  1446       defaultMenuItem.setAttribute("image", this._getIconURLForSystemDefault(handlerInfo));
  1448       menuPopup.appendChild(defaultMenuItem);
  1451     // Create menu items for possible handlers.
  1452     let preferredApp = handlerInfo.preferredApplicationHandler;
  1453     let possibleApps = handlerInfo.possibleApplicationHandlers.enumerate();
  1454     var possibleAppMenuItems = [];
  1455     while (possibleApps.hasMoreElements()) {
  1456       let possibleApp = possibleApps.getNext();
  1457       if (!this.isValidHandlerApp(possibleApp))
  1458         continue;
  1460       let menuItem = document.createElement("menuitem");
  1461       menuItem.setAttribute("action", Ci.nsIHandlerInfo.useHelperApp);
  1462       let label;
  1463       if (possibleApp instanceof Ci.nsILocalHandlerApp)
  1464         label = getFileDisplayName(possibleApp.executable);
  1465       else
  1466         label = possibleApp.name;
  1467       label = this._prefsBundle.getFormattedString("useApp", [label]);
  1468       menuItem.setAttribute("label", label);
  1469       menuItem.setAttribute("tooltiptext", label);
  1470       menuItem.setAttribute("image", this._getIconURLForHandlerApp(possibleApp));
  1472       // Attach the handler app object to the menu item so we can use it
  1473       // to make changes to the datastore when the user selects the item.
  1474       menuItem.handlerApp = possibleApp;
  1476       menuPopup.appendChild(menuItem);
  1477       possibleAppMenuItems.push(menuItem);
  1480     // Create a menu item for the plugin.
  1481     if (handlerInfo.pluginName) {
  1482       var pluginMenuItem = document.createElement("menuitem");
  1483       pluginMenuItem.setAttribute("action", kActionUsePlugin);
  1484       let label = this._prefsBundle.getFormattedString("usePluginIn",
  1485                                                        [handlerInfo.pluginName,
  1486                                                         this._brandShortName]);
  1487       pluginMenuItem.setAttribute("label", label);
  1488       pluginMenuItem.setAttribute("tooltiptext", label);
  1489       pluginMenuItem.setAttribute(APP_ICON_ATTR_NAME, "plugin");
  1490       menuPopup.appendChild(pluginMenuItem);
  1493     // Create a menu item for selecting a local application.
  1494 #ifdef XP_WIN
  1495     // On Windows, selecting an application to open another application
  1496     // would be meaningless so we special case executables.
  1497     var executableType = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService)
  1498                                                   .getTypeFromExtension("exe");
  1499     if (handlerInfo.type != executableType)
  1500 #endif
  1502       let menuItem = document.createElement("menuitem");
  1503       menuItem.setAttribute("oncommand", "gApplicationsPane.chooseApp(event)");
  1504       let label = this._prefsBundle.getString("useOtherApp");
  1505       menuItem.setAttribute("label", label);
  1506       menuItem.setAttribute("tooltiptext", label);
  1507       menuPopup.appendChild(menuItem);
  1510     // Create a menu item for managing applications.
  1511     if (possibleAppMenuItems.length) {
  1512       let menuItem = document.createElement("menuseparator");
  1513       menuPopup.appendChild(menuItem);
  1514       menuItem = document.createElement("menuitem");
  1515       menuItem.setAttribute("oncommand", "gApplicationsPane.manageApp(event)");
  1516       menuItem.setAttribute("label", this._prefsBundle.getString("manageApp"));
  1517       menuPopup.appendChild(menuItem);
  1520     // Select the item corresponding to the preferred action.  If the always
  1521     // ask flag is set, it overrides the preferred action.  Otherwise we pick
  1522     // the item identified by the preferred action (when the preferred action
  1523     // is to use a helper app, we have to pick the specific helper app item).
  1524     if (handlerInfo.alwaysAskBeforeHandling)
  1525       menu.selectedItem = askMenuItem;
  1526     else switch (handlerInfo.preferredAction) {
  1527       case Ci.nsIHandlerInfo.handleInternally:
  1528         menu.selectedItem = internalMenuItem;
  1529         break;
  1530       case Ci.nsIHandlerInfo.useSystemDefault:
  1531         menu.selectedItem = defaultMenuItem;
  1532         break;
  1533       case Ci.nsIHandlerInfo.useHelperApp:
  1534         if (preferredApp)
  1535           menu.selectedItem = 
  1536             possibleAppMenuItems.filter(function(v) v.handlerApp.equals(preferredApp))[0];
  1537         break;
  1538       case kActionUsePlugin:
  1539         menu.selectedItem = pluginMenuItem;
  1540         break;
  1541       case Ci.nsIHandlerInfo.saveToDisk:
  1542         menu.selectedItem = saveMenuItem;
  1543         break;
  1545   },
  1548   //**************************************************************************//
  1549   // Sorting & Filtering
  1551   _sortColumn: null,
  1553   /**
  1554    * Sort the list when the user clicks on a column header.
  1555    */
  1556   sort: function (event) {
  1557     var column = event.target;
  1559     // If the user clicked on a new sort column, remove the direction indicator
  1560     // from the old column.
  1561     if (this._sortColumn && this._sortColumn != column)
  1562       this._sortColumn.removeAttribute("sortDirection");
  1564     this._sortColumn = column;
  1566     // Set (or switch) the sort direction indicator.
  1567     if (column.getAttribute("sortDirection") == "ascending")
  1568       column.setAttribute("sortDirection", "descending");
  1569     else
  1570       column.setAttribute("sortDirection", "ascending");
  1572     this._sortVisibleTypes();
  1573     this._rebuildView();
  1574   },
  1576   /**
  1577    * Sort the list of visible types by the current sort column/direction.
  1578    */
  1579   _sortVisibleTypes: function() {
  1580     if (!this._sortColumn)
  1581       return;
  1583     var t = this;
  1585     function sortByType(a, b) {
  1586       return t._describeType(a).toLowerCase().
  1587              localeCompare(t._describeType(b).toLowerCase());
  1590     function sortByAction(a, b) {
  1591       return t._describePreferredAction(a).toLowerCase().
  1592              localeCompare(t._describePreferredAction(b).toLowerCase());
  1595     switch (this._sortColumn.getAttribute("value")) {
  1596       case "type":
  1597         this._visibleTypes.sort(sortByType);
  1598         break;
  1599       case "action":
  1600         this._visibleTypes.sort(sortByAction);
  1601         break;
  1604     if (this._sortColumn.getAttribute("sortDirection") == "descending")
  1605       this._visibleTypes.reverse();
  1606   },
  1608   /**
  1609    * Filter the list when the user enters a filter term into the filter field.
  1610    */
  1611   filter: function() {
  1612     this._rebuildView();
  1613   },
  1615   focusFilterBox: function() {
  1616     this._filter.focus();
  1617     this._filter.select();
  1618   },
  1621   //**************************************************************************//
  1622   // Changes
  1624   onSelectAction: function(aActionItem) {
  1625     this._storingAction = true;
  1627     try {
  1628       this._storeAction(aActionItem);
  1630     finally {
  1631       this._storingAction = false;
  1633   },
  1635   _storeAction: function(aActionItem) {
  1636     var typeItem = this._list.selectedItem;
  1637     var handlerInfo = this._handledTypes[typeItem.type];
  1639     if (aActionItem.hasAttribute("alwaysAsk")) {
  1640       handlerInfo.alwaysAskBeforeHandling = true;
  1642     else if (aActionItem.hasAttribute("action")) {
  1643       let action = parseInt(aActionItem.getAttribute("action"));
  1645       // Set the plugin state if we're enabling or disabling a plugin.
  1646       if (action == kActionUsePlugin)
  1647         handlerInfo.enablePluginType();
  1648       else if (handlerInfo.pluginName && !handlerInfo.isDisabledPluginType)
  1649         handlerInfo.disablePluginType();
  1651       // Set the preferred application handler.
  1652       // We leave the existing preferred app in the list when we set
  1653       // the preferred action to something other than useHelperApp so that
  1654       // legacy datastores that don't have the preferred app in the list
  1655       // of possible apps still include the preferred app in the list of apps
  1656       // the user can choose to handle the type.
  1657       if (action == Ci.nsIHandlerInfo.useHelperApp)
  1658         handlerInfo.preferredApplicationHandler = aActionItem.handlerApp;
  1660       // Set the "always ask" flag.
  1661       handlerInfo.alwaysAskBeforeHandling = false;
  1663       // Set the preferred action.
  1664       handlerInfo.preferredAction = action;
  1667     handlerInfo.store();
  1669     // Make sure the handler info object is flagged to indicate that there is
  1670     // now some user configuration for the type.
  1671     handlerInfo.handledOnlyByPlugin = false;
  1673     // Update the action label and image to reflect the new preferred action.
  1674     typeItem.setAttribute("actionDescription",
  1675                           this._describePreferredAction(handlerInfo));
  1676     if (!this._setIconClassForPreferredAction(handlerInfo, typeItem)) {
  1677       typeItem.setAttribute("actionIcon",
  1678                             this._getIconURLForPreferredAction(handlerInfo));
  1680   },
  1682   manageApp: function(aEvent) {
  1683     // Don't let the normal "on select action" handler get this event,
  1684     // as we handle it specially ourselves.
  1685     aEvent.stopPropagation();
  1687     var typeItem = this._list.selectedItem;
  1688     var handlerInfo = this._handledTypes[typeItem.type];
  1690     openDialog("chrome://browser/content/preferences/applicationManager.xul",
  1691                "",
  1692                "modal,centerscreen,resizable=no",
  1693                handlerInfo);
  1695     // Rebuild the actions menu so that we revert to the previous selection,
  1696     // or "Always ask" if the previous default application has been removed
  1697     this.rebuildActionsMenu();
  1699     // update the richlistitem too. Will be visible when selecting another row
  1700     typeItem.setAttribute("actionDescription",
  1701                           this._describePreferredAction(handlerInfo));
  1702     if (!this._setIconClassForPreferredAction(handlerInfo, typeItem)) {
  1703       typeItem.setAttribute("actionIcon",
  1704                             this._getIconURLForPreferredAction(handlerInfo));
  1706   },
  1708   chooseApp: function(aEvent) {
  1709     // Don't let the normal "on select action" handler get this event,
  1710     // as we handle it specially ourselves.
  1711     aEvent.stopPropagation();
  1713     var handlerApp;
  1714     let chooseAppCallback = function(aHandlerApp) {
  1715       // Rebuild the actions menu whether the user picked an app or canceled.
  1716       // If they picked an app, we want to add the app to the menu and select it.
  1717       // If they canceled, we want to go back to their previous selection.
  1718       this.rebuildActionsMenu();
  1720       // If the user picked a new app from the menu, select it.
  1721       if (aHandlerApp) {
  1722         let typeItem = this._list.selectedItem;
  1723         let actionsMenu =
  1724           document.getAnonymousElementByAttribute(typeItem, "class", "actionsMenu");
  1725         let menuItems = actionsMenu.menupopup.childNodes;
  1726         for (let i = 0; i < menuItems.length; i++) {
  1727           let menuItem = menuItems[i];
  1728           if (menuItem.handlerApp && menuItem.handlerApp.equals(aHandlerApp)) {
  1729             actionsMenu.selectedIndex = i;
  1730             this.onSelectAction(menuItem);
  1731             break;
  1735     }.bind(this);
  1737 #ifdef XP_WIN
  1738     var params = {};
  1739     var handlerInfo = this._handledTypes[this._list.selectedItem.type];
  1741     if (isFeedType(handlerInfo.type)) {
  1742       // MIME info will be null, create a temp object.
  1743       params.mimeInfo = this._mimeSvc.getFromTypeAndExtension(handlerInfo.type, 
  1744                                                  handlerInfo.primaryExtension);
  1745     } else {
  1746       params.mimeInfo = handlerInfo.wrappedHandlerInfo;
  1749     params.title         = this._prefsBundle.getString("fpTitleChooseApp");
  1750     params.description   = handlerInfo.description;
  1751     params.filename      = null;
  1752     params.handlerApp    = null;
  1754     window.openDialog("chrome://global/content/appPicker.xul", null,
  1755                       "chrome,modal,centerscreen,titlebar,dialog=yes",
  1756                       params);
  1758     if (this.isValidHandlerApp(params.handlerApp)) {
  1759       handlerApp = params.handlerApp;
  1761       // Add the app to the type's list of possible handlers.
  1762       handlerInfo.addPossibleApplicationHandler(handlerApp);
  1765     chooseAppCallback(handlerApp);
  1766 #else
  1767     let winTitle = this._prefsBundle.getString("fpTitleChooseApp");
  1768     let fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
  1769     let fpCallback = function fpCallback_done(aResult) {
  1770       if (aResult == Ci.nsIFilePicker.returnOK && fp.file &&
  1771           this._isValidHandlerExecutable(fp.file)) {
  1772         handlerApp = Cc["@mozilla.org/uriloader/local-handler-app;1"].
  1773                      createInstance(Ci.nsILocalHandlerApp);
  1774         handlerApp.name = getFileDisplayName(fp.file);
  1775         handlerApp.executable = fp.file;
  1777         // Add the app to the type's list of possible handlers.
  1778         let handlerInfo = this._handledTypes[this._list.selectedItem.type];
  1779         handlerInfo.addPossibleApplicationHandler(handlerApp);
  1781         chooseAppCallback(handlerApp);
  1783     }.bind(this);
  1785     // Prompt the user to pick an app.  If they pick one, and it's a valid
  1786     // selection, then add it to the list of possible handlers.
  1787     fp.init(window, winTitle, Ci.nsIFilePicker.modeOpen);
  1788     fp.appendFilters(Ci.nsIFilePicker.filterApps);
  1789     fp.open(fpCallback);
  1790 #endif
  1791   },
  1793   // Mark which item in the list was last selected so we can reselect it
  1794   // when we rebuild the list or when the user returns to the prefpane.
  1795   onSelectionChanged: function() {
  1796     if (this._list.selectedItem)
  1797       this._list.setAttribute("lastSelectedType",
  1798                               this._list.selectedItem.getAttribute("type"));
  1799   },
  1801   _setIconClassForPreferredAction: function(aHandlerInfo, aElement) {
  1802     // If this returns true, the attribute that CSS sniffs for was set to something
  1803     // so you shouldn't manually set an icon URI.
  1804     // This removes the existing actionIcon attribute if any, even if returning false.
  1805     aElement.removeAttribute("actionIcon");
  1807     if (aHandlerInfo.alwaysAskBeforeHandling) {
  1808       aElement.setAttribute(APP_ICON_ATTR_NAME, "ask");
  1809       return true;
  1812     switch (aHandlerInfo.preferredAction) {
  1813       case Ci.nsIHandlerInfo.saveToDisk:
  1814         aElement.setAttribute(APP_ICON_ATTR_NAME, "save");
  1815         return true;
  1817       case Ci.nsIHandlerInfo.handleInternally:
  1818         if (isFeedType(aHandlerInfo.type)) {
  1819           aElement.setAttribute(APP_ICON_ATTR_NAME, "feed");
  1820           return true;
  1821         } else if (aHandlerInfo instanceof InternalHandlerInfoWrapper) {
  1822           aElement.setAttribute(APP_ICON_ATTR_NAME, "ask");
  1823           return true;
  1825         break;
  1827       case kActionUsePlugin:
  1828         aElement.setAttribute(APP_ICON_ATTR_NAME, "plugin");
  1829         return true;
  1831     aElement.removeAttribute(APP_ICON_ATTR_NAME);
  1832     return false;
  1833   },
  1835   _getIconURLForPreferredAction: function(aHandlerInfo) {
  1836     switch (aHandlerInfo.preferredAction) {
  1837       case Ci.nsIHandlerInfo.useSystemDefault:
  1838         return this._getIconURLForSystemDefault(aHandlerInfo);
  1840       case Ci.nsIHandlerInfo.useHelperApp:
  1841         let (preferredApp = aHandlerInfo.preferredApplicationHandler) {
  1842           if (this.isValidHandlerApp(preferredApp))
  1843             return this._getIconURLForHandlerApp(preferredApp);
  1845         break;
  1847       // This should never happen, but if preferredAction is set to some weird
  1848       // value, then fall back to the generic application icon.
  1849       default:
  1850         return ICON_URL_APP;
  1852   },
  1854   _getIconURLForHandlerApp: function(aHandlerApp) {
  1855     if (aHandlerApp instanceof Ci.nsILocalHandlerApp)
  1856       return this._getIconURLForFile(aHandlerApp.executable);
  1858     if (aHandlerApp instanceof Ci.nsIWebHandlerApp)
  1859       return this._getIconURLForWebApp(aHandlerApp.uriTemplate);
  1861     if (aHandlerApp instanceof Ci.nsIWebContentHandlerInfo)
  1862       return this._getIconURLForWebApp(aHandlerApp.uri)
  1864     // We know nothing about other kinds of handler apps.
  1865     return "";
  1866   },
  1868   _getIconURLForFile: function(aFile) {
  1869     var fph = this._ioSvc.getProtocolHandler("file").
  1870               QueryInterface(Ci.nsIFileProtocolHandler);
  1871     var urlSpec = fph.getURLSpecFromFile(aFile);
  1873     return "moz-icon://" + urlSpec + "?size=16";
  1874   },
  1876   _getIconURLForWebApp: function(aWebAppURITemplate) {
  1877     var uri = this._ioSvc.newURI(aWebAppURITemplate, null, null);
  1879     // Unfortunately we can't use the favicon service to get the favicon,
  1880     // because the service looks in the annotations table for a record with
  1881     // the exact URL we give it, and users won't have such records for URLs
  1882     // they don't visit, and users won't visit the web app's URL template,
  1883     // they'll only visit URLs derived from that template (i.e. with %s
  1884     // in the template replaced by the URL of the content being handled).
  1886     if (/^https?$/.test(uri.scheme) && this._prefSvc.getBoolPref("browser.chrome.favicons"))
  1887       return uri.prePath + "/favicon.ico";
  1889     return "";
  1890   },
  1892   _getIconURLForSystemDefault: function(aHandlerInfo) {
  1893     // Handler info objects for MIME types on some OSes implement a property bag
  1894     // interface from which we can get an icon for the default app, so if we're
  1895     // dealing with a MIME type on one of those OSes, then try to get the icon.
  1896     if ("wrappedHandlerInfo" in aHandlerInfo) {
  1897       let wrappedHandlerInfo = aHandlerInfo.wrappedHandlerInfo;
  1899       if (wrappedHandlerInfo instanceof Ci.nsIMIMEInfo &&
  1900           wrappedHandlerInfo instanceof Ci.nsIPropertyBag) {
  1901         try {
  1902           let url = wrappedHandlerInfo.getProperty("defaultApplicationIconURL");
  1903           if (url)
  1904             return url + "?size=16";
  1906         catch(ex) {}
  1910     // If this isn't a MIME type object on an OS that supports retrieving
  1911     // the icon, or if we couldn't retrieve the icon for some other reason,
  1912     // then use a generic icon.
  1913     return ICON_URL_APP;
  1916 };

mercurial