Bug 470455 - test_database_sync_embed_visits.js leaks, r=sdwilsh
[wine-gecko.git] / browser / components / preferences / applications.js
blob83c872a6bee7dd30b10a2e2c2bc66f7f3b90d2f6
1 /*
2 # -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
3 # ***** BEGIN LICENSE BLOCK *****
4 # Version: MPL 1.1/GPL 2.0/LGPL 2.1
6 # The contents of this file are subject to the Mozilla Public License Version
7 # 1.1 (the "License"); you may not use this file except in compliance with
8 # the License. You may obtain a copy of the License at
9 # http://www.mozilla.org/MPL/
11 # Software distributed under the License is distributed on an "AS IS" basis,
12 # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 # for the specific language governing rights and limitations under the
14 # License.
16 # The Original Code is the Download Actions Manager.
18 # The Initial Developer of the Original Code is
19 # Ben Goodger.
20 # Portions created by the Initial Developer are Copyright (C) 2000
21 # the Initial Developer. All Rights Reserved.
23 # Contributor(s):
24 # Ben Goodger <ben@mozilla.org>
25 # Jeff Walden <jwalden+code@mit.edu>
26 # Asaf Romano <mozilla.mano@sent.com>
27 # Myk Melez <myk@mozilla.org>
28 # Florian Queze <florian@queze.net>
29 # Will Guaraldi <will.guaraldi@pculture.org>
31 # Alternatively, the contents of this file may be used under the terms of
32 # either the GNU General Public License Version 2 or later (the "GPL"), or
33 # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
34 # in which case the provisions of the GPL or the LGPL are applicable instead
35 # of those above. If you wish to allow use of your version of this file only
36 # under the terms of either the GPL or the LGPL, and not to allow others to
37 # use your version of this file under the terms of the MPL, indicate your
38 # decision by deleting the provisions above and replace them with the notice
39 # and other provisions required by the GPL or the LGPL. If you do not delete
40 # the provisions above, a recipient may use your version of this file under
41 # the terms of any one of the MPL, the GPL or the LGPL.
43 # ***** END LICENSE BLOCK *****
46 //****************************************************************************//
47 // Constants & Enumeration Values
50 #ifndef XP_MACOSX
52 var Cc = Components.classes;
53 var Ci = Components.interfaces;
54 var Cr = Components.results;
56 #endif
59 const TYPE_MAYBE_FEED = "application/vnd.mozilla.maybe.feed";
60 const TYPE_MAYBE_VIDEO_FEED = "application/vnd.mozilla.maybe.video.feed";
61 const TYPE_MAYBE_AUDIO_FEED = "application/vnd.mozilla.maybe.audio.feed";
63 const PREF_DISABLED_PLUGIN_TYPES = "plugin.disable_full_page_plugin_for_types";
65 // Preferences that affect which entries to show in the list.
66 const PREF_SHOW_PLUGINS_IN_LIST = "browser.download.show_plugins_in_list";
67 const PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS =
68 "browser.download.hide_plugins_without_extensions";
71 * Preferences where we store handling information about the feed type.
73 * browser.feeds.handler
74 * - "bookmarks", "reader" (clarified further using the .default preference),
75 * or "ask" -- indicates the default handler being used to process feeds;
76 * "bookmarks" is obsolete; to specify that the handler is bookmarks,
77 * set browser.feeds.handler.default to "bookmarks";
79 * browser.feeds.handler.default
80 * - "bookmarks", "client" or "web" -- indicates the chosen feed reader used
81 * to display feeds, either transiently (i.e., when the "use as default"
82 * checkbox is unchecked, corresponds to when browser.feeds.handler=="ask")
83 * or more permanently (i.e., the item displayed in the dropdown in Feeds
84 * preferences)
86 * browser.feeds.handler.webservice
87 * - the URL of the currently selected web service used to read feeds
89 * browser.feeds.handlers.application
90 * - nsILocalFile, stores the current client-side feed reading app if one has
91 * been chosen
93 const PREF_FEED_SELECTED_APP = "browser.feeds.handlers.application";
94 const PREF_FEED_SELECTED_WEB = "browser.feeds.handlers.webservice";
95 const PREF_FEED_SELECTED_ACTION = "browser.feeds.handler";
96 const PREF_FEED_SELECTED_READER = "browser.feeds.handler.default";
98 const PREF_VIDEO_FEED_SELECTED_APP = "browser.videoFeeds.handlers.application";
99 const PREF_VIDEO_FEED_SELECTED_WEB = "browser.videoFeeds.handlers.webservice";
100 const PREF_VIDEO_FEED_SELECTED_ACTION = "browser.videoFeeds.handler";
101 const PREF_VIDEO_FEED_SELECTED_READER = "browser.videoFeeds.handler.default";
103 const PREF_AUDIO_FEED_SELECTED_APP = "browser.audioFeeds.handlers.application";
104 const PREF_AUDIO_FEED_SELECTED_WEB = "browser.audioFeeds.handlers.webservice";
105 const PREF_AUDIO_FEED_SELECTED_ACTION = "browser.audioFeeds.handler";
106 const PREF_AUDIO_FEED_SELECTED_READER = "browser.audioFeeds.handler.default";
108 // The nsHandlerInfoAction enumeration values in nsIHandlerInfo identify
109 // the actions the application can take with content of various types.
110 // But since nsIHandlerInfo doesn't support plugins, there's no value
111 // identifying the "use plugin" action, so we use this constant instead.
112 const kActionUsePlugin = 5;
114 const ICON_URL_APP = "chrome://browser/skin/preferences/application.png";
116 // For CSS. Can be one of "ask", "save", "plugin" or "feed". If absent, the icon URL
117 // was set by us to a custom handler icon and CSS should not try to override it.
118 const APP_ICON_ATTR_NAME = "appHandlerIcon";
120 //****************************************************************************//
121 // Utilities
123 function getDisplayNameForFile(aFile) {
125 #ifdef XP_WIN
127 if (aFile instanceof Ci.nsILocalFileWin) {
128 try {
129 return aFile.getVersionInfoField("FileDescription");
131 catch(ex) {
132 // fall through to the file name
136 #endif
137 #ifdef XP_MACOSX
139 if (aFile instanceof Ci.nsILocalFileMac) {
140 try {
141 return aFile.bundleDisplayName;
143 catch(ex) {
144 // fall through to the file name
148 #endif
151 return Cc["@mozilla.org/network/io-service;1"].
152 getService(Ci.nsIIOService).
153 newFileURI(aFile).
154 QueryInterface(Ci.nsIURL).
155 fileName;
158 function getLocalHandlerApp(aFile) {
159 var localHandlerApp = Cc["@mozilla.org/uriloader/local-handler-app;1"].
160 createInstance(Ci.nsILocalHandlerApp);
161 localHandlerApp.name = getDisplayNameForFile(aFile);
162 localHandlerApp.executable = aFile;
164 return localHandlerApp;
168 * An enumeration of items in a JS array.
170 * FIXME: use ArrayConverter once it lands (bug 380839).
172 * @constructor
174 function ArrayEnumerator(aItems) {
175 this._index = 0;
176 this._contents = aItems;
179 ArrayEnumerator.prototype = {
180 _index: 0,
182 hasMoreElements: function() {
183 return this._index < this._contents.length;
186 getNext: function() {
187 return this._contents[this._index++];
191 function isFeedType(t) {
192 return t == TYPE_MAYBE_FEED || t == TYPE_MAYBE_VIDEO_FEED || t == TYPE_MAYBE_AUDIO_FEED;
195 //****************************************************************************//
196 // HandlerInfoWrapper
199 * This object wraps nsIHandlerInfo with some additional functionality
200 * the Applications prefpane needs to display and allow modification of
201 * the list of handled types.
203 * We create an instance of this wrapper for each entry we might display
204 * in the prefpane, and we compose the instances from various sources,
205 * including navigator.plugins and the handler service.
207 * We don't implement all the original nsIHandlerInfo functionality,
208 * just the stuff that the prefpane needs.
210 * In theory, all of the custom functionality in this wrapper should get
211 * pushed down into nsIHandlerInfo eventually.
213 function HandlerInfoWrapper(aType, aHandlerInfo) {
214 this._type = aType;
215 this.wrappedHandlerInfo = aHandlerInfo;
218 HandlerInfoWrapper.prototype = {
219 // The wrapped nsIHandlerInfo object. In general, this object is private,
220 // but there are a couple cases where callers access it directly for things
221 // we haven't (yet?) implemented, so we make it a public property.
222 wrappedHandlerInfo: null,
225 //**************************************************************************//
226 // Convenience Utils
228 _handlerSvc: Cc["@mozilla.org/uriloader/handler-service;1"].
229 getService(Ci.nsIHandlerService),
231 // Retrieve this as nsIPrefBranch and then immediately QI to nsIPrefBranch2
232 // so both interfaces are available to callers.
233 _prefSvc: Cc["@mozilla.org/preferences-service;1"].
234 getService(Ci.nsIPrefBranch).
235 QueryInterface(Ci.nsIPrefBranch2),
237 _categoryMgr: Cc["@mozilla.org/categorymanager;1"].
238 getService(Ci.nsICategoryManager),
240 element: function(aID) {
241 return document.getElementById(aID);
245 //**************************************************************************//
246 // nsIHandlerInfo
248 // The MIME type or protocol scheme.
249 _type: null,
250 get type() {
251 return this._type;
254 get description() {
255 if (this.wrappedHandlerInfo.description)
256 return this.wrappedHandlerInfo.description;
258 if (this.primaryExtension) {
259 var extension = this.primaryExtension.toUpperCase();
260 return this.element("bundlePreferences").getFormattedString("fileEnding",
261 [extension]);
264 return this.type;
267 get preferredApplicationHandler() {
268 return this.wrappedHandlerInfo.preferredApplicationHandler;
271 set preferredApplicationHandler(aNewValue) {
272 this.wrappedHandlerInfo.preferredApplicationHandler = aNewValue;
274 // Make sure the preferred handler is in the set of possible handlers.
275 if (aNewValue)
276 this.addPossibleApplicationHandler(aNewValue)
279 get possibleApplicationHandlers() {
280 return this.wrappedHandlerInfo.possibleApplicationHandlers;
283 addPossibleApplicationHandler: function(aNewHandler) {
284 var possibleApps = this.possibleApplicationHandlers.enumerate();
285 while (possibleApps.hasMoreElements()) {
286 if (possibleApps.getNext().equals(aNewHandler))
287 return;
289 this.possibleApplicationHandlers.appendElement(aNewHandler, false);
292 removePossibleApplicationHandler: function(aHandler) {
293 var defaultApp = this.preferredApplicationHandler;
294 if (defaultApp && aHandler.equals(defaultApp)) {
295 // If the app we remove was the default app, we must make sure
296 // it won't be used anymore
297 this.alwaysAskBeforeHandling = true;
298 this.preferredApplicationHandler = null;
301 var handlers = this.possibleApplicationHandlers;
302 for (var i = 0; i < handlers.length; ++i) {
303 var handler = handlers.queryElementAt(i, Ci.nsIHandlerApp);
304 if (handler.equals(aHandler)) {
305 handlers.removeElementAt(i);
306 break;
311 get hasDefaultHandler() {
312 return this.wrappedHandlerInfo.hasDefaultHandler;
315 get defaultDescription() {
316 return this.wrappedHandlerInfo.defaultDescription;
319 // What to do with content of this type.
320 get preferredAction() {
321 // If we have an enabled plugin, then the action is to use that plugin.
322 if (this.plugin && !this.isDisabledPluginType)
323 return kActionUsePlugin;
325 // If the action is to use a helper app, but we don't have a preferred
326 // handler app, then switch to using the system default, if any; otherwise
327 // fall back to saving to disk, which is the default action in nsMIMEInfo.
328 // Note: "save to disk" is an invalid value for protocol info objects,
329 // but the alwaysAskBeforeHandling getter will detect that situation
330 // and always return true in that case to override this invalid value.
331 if (this.wrappedHandlerInfo.preferredAction == Ci.nsIHandlerInfo.useHelperApp &&
332 !gApplicationsPane.isValidHandlerApp(this.preferredApplicationHandler)) {
333 if (this.wrappedHandlerInfo.hasDefaultHandler)
334 return Ci.nsIHandlerInfo.useSystemDefault;
335 else
336 return Ci.nsIHandlerInfo.saveToDisk;
339 return this.wrappedHandlerInfo.preferredAction;
342 set preferredAction(aNewValue) {
343 // We don't modify the preferred action if the new action is to use a plugin
344 // because handler info objects don't understand our custom "use plugin"
345 // value. Also, leaving it untouched means that we can automatically revert
346 // to the old setting if the user ever removes the plugin.
348 if (aNewValue != kActionUsePlugin)
349 this.wrappedHandlerInfo.preferredAction = aNewValue;
352 get alwaysAskBeforeHandling() {
353 // If this type is handled only by a plugin, we can't trust the value
354 // in the handler info object, since it'll be a default based on the absence
355 // of any user configuration, and the default in that case is to always ask,
356 // even though we never ask for content handled by a plugin, so special case
357 // plugin-handled types by returning false here.
358 if (this.plugin && this.handledOnlyByPlugin)
359 return false;
361 // If this is a protocol type and the preferred action is "save to disk",
362 // which is invalid for such types, then return true here to override that
363 // action. This could happen when the preferred action is to use a helper
364 // app, but the preferredApplicationHandler is invalid, and there isn't
365 // a default handler, so the preferredAction getter returns save to disk
366 // instead.
367 if (!(this.wrappedHandlerInfo instanceof Ci.nsIMIMEInfo) &&
368 this.preferredAction == Ci.nsIHandlerInfo.saveToDisk)
369 return true;
371 return this.wrappedHandlerInfo.alwaysAskBeforeHandling;
374 set alwaysAskBeforeHandling(aNewValue) {
375 this.wrappedHandlerInfo.alwaysAskBeforeHandling = aNewValue;
379 //**************************************************************************//
380 // nsIMIMEInfo
382 // The primary file extension associated with this type, if any.
384 // XXX Plugin objects contain an array of MimeType objects with "suffixes"
385 // properties; if this object has an associated plugin, shouldn't we check
386 // those properties for an extension?
387 get primaryExtension() {
388 try {
389 if (this.wrappedHandlerInfo instanceof Ci.nsIMIMEInfo &&
390 this.wrappedHandlerInfo.primaryExtension)
391 return this.wrappedHandlerInfo.primaryExtension
392 } catch(ex) {}
394 return null;
398 //**************************************************************************//
399 // Plugin Handling
401 // A plugin that can handle this type, if any.
403 // Note: just because we have one doesn't mean it *will* handle the type.
404 // That depends on whether or not the type is in the list of types for which
405 // plugin handling is disabled.
406 plugin: null,
408 // Whether or not this type is only handled by a plugin or is also handled
409 // by some user-configured action as specified in the handler info object.
411 // Note: we can't just check if there's a handler info object for this type,
412 // because OS and user configuration is mixed up in the handler info object,
413 // so we always need to retrieve it for the OS info and can't tell whether
414 // it represents only OS-default information or user-configured information.
416 // FIXME: once handler info records are broken up into OS-provided records
417 // and user-configured records, stop using this boolean flag and simply
418 // check for the presence of a user-configured record to determine whether
419 // or not this type is only handled by a plugin. Filed as bug 395142.
420 handledOnlyByPlugin: undefined,
422 get isDisabledPluginType() {
423 return this._getDisabledPluginTypes().indexOf(this.type) != -1;
426 _getDisabledPluginTypes: function() {
427 var types = "";
429 if (this._prefSvc.prefHasUserValue(PREF_DISABLED_PLUGIN_TYPES))
430 types = this._prefSvc.getCharPref(PREF_DISABLED_PLUGIN_TYPES);
432 // Only split if the string isn't empty so we don't end up with an array
433 // containing a single empty string.
434 if (types != "")
435 return types.split(",");
437 return [];
440 disablePluginType: function() {
441 var disabledPluginTypes = this._getDisabledPluginTypes();
443 if (disabledPluginTypes.indexOf(this.type) == -1)
444 disabledPluginTypes.push(this.type);
446 this._prefSvc.setCharPref(PREF_DISABLED_PLUGIN_TYPES,
447 disabledPluginTypes.join(","));
449 // Update the category manager so existing browser windows update.
450 this._categoryMgr.deleteCategoryEntry("Gecko-Content-Viewers",
451 this.type,
452 false);
455 enablePluginType: function() {
456 var disabledPluginTypes = this._getDisabledPluginTypes();
458 var type = this.type;
459 disabledPluginTypes = disabledPluginTypes.filter(function(v) v != type);
461 this._prefSvc.setCharPref(PREF_DISABLED_PLUGIN_TYPES,
462 disabledPluginTypes.join(","));
464 // Update the category manager so existing browser windows update.
465 this._categoryMgr.
466 addCategoryEntry("Gecko-Content-Viewers",
467 this.type,
468 "@mozilla.org/content/plugin/document-loader-factory;1",
469 false,
470 true);
474 //**************************************************************************//
475 // Storage
477 store: function() {
478 this._handlerSvc.store(this.wrappedHandlerInfo);
482 //**************************************************************************//
483 // Icons
485 get smallIcon() {
486 return this._getIcon(16);
489 get largeIcon() {
490 return this._getIcon(32);
493 _getIcon: function(aSize) {
494 if (this.primaryExtension)
495 return "moz-icon://goat." + this.primaryExtension + "?size=" + aSize;
497 if (this.wrappedHandlerInfo instanceof Ci.nsIMIMEInfo)
498 return "moz-icon://goat?size=" + aSize + "&contentType=" + this.type;
500 // FIXME: consider returning some generic icon when we can't get a URL for
501 // one (for example in the case of protocol schemes). Filed as bug 395141.
502 return null;
508 //****************************************************************************//
509 // Feed Handler Info
512 * This object implements nsIHandlerInfo for the feed types. It's a separate
513 * object because we currently store handling information for the feed type
514 * in a set of preferences rather than the nsIHandlerService-managed datastore.
516 * This object inherits from HandlerInfoWrapper in order to get functionality
517 * that isn't special to the feed type.
519 * XXX Should we inherit from HandlerInfoWrapper? After all, we override
520 * most of that wrapper's properties and methods, and we have to dance around
521 * the fact that the wrapper expects to have a wrappedHandlerInfo, which we
522 * don't provide.
525 function FeedHandlerInfo(aMIMEType) {
526 HandlerInfoWrapper.call(this, aMIMEType, null);
529 FeedHandlerInfo.prototype = {
530 __proto__: HandlerInfoWrapper.prototype,
532 //**************************************************************************//
533 // Convenience Utils
535 _converterSvc:
536 Cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"].
537 getService(Ci.nsIWebContentConverterService),
539 _shellSvc:
540 #ifdef HAVE_SHELL_SERVICE
541 getShellService(),
542 #else
543 null,
544 #endif
547 //**************************************************************************//
548 // nsIHandlerInfo
550 get description() {
551 return this.element("bundlePreferences").getString(this._appPrefLabel);
554 get preferredApplicationHandler() {
555 switch (this.element(this._prefSelectedReader).value) {
556 case "client":
557 var file = this.element(this._prefSelectedApp).value;
558 if (file)
559 return getLocalHandlerApp(file);
561 return null;
563 case "web":
564 var uri = this.element(this._prefSelectedWeb).value;
565 if (!uri)
566 return null;
567 return this._converterSvc.getWebContentHandlerByURI(this.type, uri);
569 case "bookmarks":
570 default:
571 // When the pref is set to bookmarks, we handle feeds internally,
572 // we don't forward them to a local or web handler app, so there is
573 // no preferred handler.
574 return null;
578 set preferredApplicationHandler(aNewValue) {
579 if (aNewValue instanceof Ci.nsILocalHandlerApp) {
580 this.element(this._prefSelectedApp).value = aNewValue.executable;
581 this.element(this._prefSelectedReader).value = "client";
583 else if (aNewValue instanceof Ci.nsIWebContentHandlerInfo) {
584 this.element(this._prefSelectedWeb).value = aNewValue.uri;
585 this.element(this._prefSelectedReader).value = "web";
586 // Make the web handler be the new "auto handler" for feeds.
587 // Note: we don't have to unregister the auto handler when the user picks
588 // a non-web handler (local app, Live Bookmarks, etc.) because the service
589 // only uses the "auto handler" when the selected reader is a web handler.
590 // We also don't have to unregister it when the user turns on "always ask"
591 // (i.e. preview in browser), since that also overrides the auto handler.
592 this._converterSvc.setAutoHandler(this.type, aNewValue);
596 _possibleApplicationHandlers: null,
598 get possibleApplicationHandlers() {
599 if (this._possibleApplicationHandlers)
600 return this._possibleApplicationHandlers;
602 // A minimal implementation of nsIMutableArray. It only supports the two
603 // methods its callers invoke, namely appendElement and nsIArray::enumerate.
604 this._possibleApplicationHandlers = {
605 _inner: [],
606 _removed: [],
608 QueryInterface: function(aIID) {
609 if (aIID.equals(Ci.nsIMutableArray) ||
610 aIID.equals(Ci.nsIArray) ||
611 aIID.equals(Ci.nsISupports))
612 return this;
614 throw Cr.NS_ERROR_NO_INTERFACE;
617 get length() {
618 return this._inner.length;
621 enumerate: function() {
622 return new ArrayEnumerator(this._inner);
625 appendElement: function(aHandlerApp, aWeak) {
626 this._inner.push(aHandlerApp);
629 removeElementAt: function(aIndex) {
630 this._removed.push(this._inner[aIndex]);
631 this._inner.splice(aIndex, 1);
634 queryElementAt: function(aIndex, aInterface) {
635 return this._inner[aIndex].QueryInterface(aInterface);
639 // Add the selected local app if it's different from the OS default handler.
640 // Unlike for other types, we can store only one local app at a time for the
641 // feed type, since we store it in a preference that historically stores
642 // only a single path. But we display all the local apps the user chooses
643 // while the prefpane is open, only dropping the list when the user closes
644 // the prefpane, for maximum usability and consistency with other types.
645 var preferredAppFile = this.element(this._prefSelectedApp).value;
646 if (preferredAppFile) {
647 let preferredApp = getLocalHandlerApp(preferredAppFile);
648 let defaultApp = this._defaultApplicationHandler;
649 if (!defaultApp || !defaultApp.equals(preferredApp))
650 this._possibleApplicationHandlers.appendElement(preferredApp, false);
653 // Add the registered web handlers. There can be any number of these.
654 var webHandlers = this._converterSvc.getContentHandlers(this.type, {});
655 for each (let webHandler in webHandlers)
656 this._possibleApplicationHandlers.appendElement(webHandler, false);
658 return this._possibleApplicationHandlers;
661 __defaultApplicationHandler: undefined,
662 get _defaultApplicationHandler() {
663 if (typeof this.__defaultApplicationHandler != "undefined")
664 return this.__defaultApplicationHandler;
666 var defaultFeedReader = null;
667 #ifdef HAVE_SHELL_SERVICE
668 try {
669 defaultFeedReader = this._shellSvc.defaultFeedReader;
671 catch(ex) {
672 // no default reader or _shellSvc is null
674 #endif
676 if (defaultFeedReader) {
677 let handlerApp = Cc["@mozilla.org/uriloader/local-handler-app;1"].
678 createInstance(Ci.nsIHandlerApp);
679 handlerApp.name = getDisplayNameForFile(defaultFeedReader);
680 handlerApp.QueryInterface(Ci.nsILocalHandlerApp);
681 handlerApp.executable = defaultFeedReader;
683 this.__defaultApplicationHandler = handlerApp;
685 else {
686 this.__defaultApplicationHandler = null;
689 return this.__defaultApplicationHandler;
692 get hasDefaultHandler() {
693 #ifdef HAVE_SHELL_SERVICE
694 try {
695 if (this._shellSvc.defaultFeedReader)
696 return true;
698 catch(ex) {
699 // no default reader or _shellSvc is null
701 #endif
703 return false;
706 get defaultDescription() {
707 if (this.hasDefaultHandler)
708 return this._defaultApplicationHandler.name;
710 // Should we instead return null?
711 return "";
714 // What to do with content of this type.
715 get preferredAction() {
716 switch (this.element(this._prefSelectedAction).value) {
718 case "bookmarks":
719 return Ci.nsIHandlerInfo.handleInternally;
721 case "reader": {
722 let preferredApp = this.preferredApplicationHandler;
723 let defaultApp = this._defaultApplicationHandler;
725 // If we have a valid preferred app, return useSystemDefault if it's
726 // the default app; otherwise return useHelperApp.
727 if (gApplicationsPane.isValidHandlerApp(preferredApp)) {
728 if (defaultApp && defaultApp.equals(preferredApp))
729 return Ci.nsIHandlerInfo.useSystemDefault;
731 return Ci.nsIHandlerInfo.useHelperApp;
734 // The pref is set to "reader", but we don't have a valid preferred app.
735 // What do we do now? Not sure this is the best option (perhaps we
736 // should direct the user to the default app, if any), but for now let's
737 // direct the user to live bookmarks.
738 return Ci.nsIHandlerInfo.handleInternally;
741 // If the action is "ask", then alwaysAskBeforeHandling will override
742 // the action, so it doesn't matter what we say it is, it just has to be
743 // something that doesn't cause the controller to hide the type.
744 case "ask":
745 default:
746 return Ci.nsIHandlerInfo.handleInternally;
750 set preferredAction(aNewValue) {
751 switch (aNewValue) {
753 case Ci.nsIHandlerInfo.handleInternally:
754 this.element(this._prefSelectedReader).value = "bookmarks";
755 break;
757 case Ci.nsIHandlerInfo.useHelperApp:
758 this.element(this._prefSelectedAction).value = "reader";
759 // The controller has already set preferredApplicationHandler
760 // to the new helper app.
761 break;
763 case Ci.nsIHandlerInfo.useSystemDefault:
764 this.element(this._prefSelectedAction).value = "reader";
765 this.preferredApplicationHandler = this._defaultApplicationHandler;
766 break;
770 get alwaysAskBeforeHandling() {
771 return this.element(this._prefSelectedAction).value == "ask";
774 set alwaysAskBeforeHandling(aNewValue) {
775 if (aNewValue == true)
776 this.element(this._prefSelectedAction).value = "ask";
777 else
778 this.element(this._prefSelectedAction).value = "reader";
781 // Whether or not we are currently storing the action selected by the user.
782 // We use this to suppress notification-triggered updates to the list when
783 // we make changes that may spawn such updates, specifically when we change
784 // the action for the feed type, which results in feed preference updates,
785 // which spawn "pref changed" notifications that would otherwise cause us
786 // to rebuild the view unnecessarily.
787 _storingAction: false,
790 //**************************************************************************//
791 // nsIMIMEInfo
793 get primaryExtension() {
794 return "xml";
798 //**************************************************************************//
799 // Storage
801 // Changes to the preferred action and handler take effect immediately
802 // (we write them out to the preferences right as they happen),
803 // so we when the controller calls store() after modifying the handlers,
804 // the only thing we need to store is the removal of possible handlers
805 // XXX Should we hold off on making the changes until this method gets called?
806 store: function() {
807 for each (let app in this._possibleApplicationHandlers._removed) {
808 if (app instanceof Ci.nsILocalHandlerApp) {
809 let pref = this.element(PREF_FEED_SELECTED_APP);
810 var preferredAppFile = pref.value;
811 if (preferredAppFile) {
812 let preferredApp = getLocalHandlerApp(preferredAppFile);
813 if (app.equals(preferredApp))
814 pref.reset();
817 else {
818 app.QueryInterface(Ci.nsIWebContentHandlerInfo);
819 this._converterSvc.removeContentHandler(app.contentType, app.uri);
822 this._possibleApplicationHandlers._removed = [];
826 //**************************************************************************//
827 // Icons
829 get smallIcon() {
830 return this._smallIcon;
833 get largeIcon() {
834 return this._largeIcon;
839 var feedHandlerInfo = {
840 __proto__: new FeedHandlerInfo(TYPE_MAYBE_FEED),
841 _prefSelectedApp: PREF_FEED_SELECTED_APP,
842 _prefSelectedWeb: PREF_FEED_SELECTED_WEB,
843 _prefSelectedAction: PREF_FEED_SELECTED_ACTION,
844 _prefSelectedReader: PREF_FEED_SELECTED_READER,
845 _smallIcon: "chrome://browser/skin/feeds/feedIcon16.png",
846 _largeIcon: "chrome://browser/skin/feeds/feedIcon.png",
847 _appPrefLabel: "webFeed"
850 var videoFeedHandlerInfo = {
851 __proto__: new FeedHandlerInfo(TYPE_MAYBE_VIDEO_FEED),
852 _prefSelectedApp: PREF_VIDEO_FEED_SELECTED_APP,
853 _prefSelectedWeb: PREF_VIDEO_FEED_SELECTED_WEB,
854 _prefSelectedAction: PREF_VIDEO_FEED_SELECTED_ACTION,
855 _prefSelectedReader: PREF_VIDEO_FEED_SELECTED_READER,
856 _smallIcon: "chrome://browser/skin/feeds/videoFeedIcon16.png",
857 _largeIcon: "chrome://browser/skin/feeds/videoFeedIcon.png",
858 _appPrefLabel: "videoPodcastFeed"
861 var audioFeedHandlerInfo = {
862 __proto__: new FeedHandlerInfo(TYPE_MAYBE_AUDIO_FEED),
863 _prefSelectedApp: PREF_AUDIO_FEED_SELECTED_APP,
864 _prefSelectedWeb: PREF_AUDIO_FEED_SELECTED_WEB,
865 _prefSelectedAction: PREF_AUDIO_FEED_SELECTED_ACTION,
866 _prefSelectedReader: PREF_AUDIO_FEED_SELECTED_READER,
867 _smallIcon: "chrome://browser/skin/feeds/audioFeedIcon16.png",
868 _largeIcon: "chrome://browser/skin/feeds/audioFeedIcon.png",
869 _appPrefLabel: "audioPodcastFeed"
873 //****************************************************************************//
874 // Prefpane Controller
876 var gApplicationsPane = {
877 // The set of types the app knows how to handle. A hash of HandlerInfoWrapper
878 // objects, indexed by type.
879 _handledTypes: {},
881 // The list of types we can show, sorted by the sort column/direction.
882 // An array of HandlerInfoWrapper objects. We build this list when we first
883 // load the data and then rebuild it when users change a pref that affects
884 // what types we can show or change the sort column/direction.
885 // Note: this isn't necessarily the list of types we *will* show; if the user
886 // provides a filter string, we'll only show the subset of types in this list
887 // that match that string.
888 _visibleTypes: [],
890 // A count of the number of times each visible type description appears.
891 // We use these counts to determine whether or not to annotate descriptions
892 // with their types to distinguish duplicate descriptions from each other.
893 // A hash of integer counts, indexed by string description.
894 _visibleTypeDescriptionCount: {},
897 //**************************************************************************//
898 // Convenience & Performance Shortcuts
900 // These get defined by init().
901 _brandShortName : null,
902 _prefsBundle : null,
903 _list : null,
904 _filter : null,
906 // Retrieve this as nsIPrefBranch and then immediately QI to nsIPrefBranch2
907 // so both interfaces are available to callers.
908 _prefSvc : Cc["@mozilla.org/preferences-service;1"].
909 getService(Ci.nsIPrefBranch).
910 QueryInterface(Ci.nsIPrefBranch2),
912 _mimeSvc : Cc["@mozilla.org/mime;1"].
913 getService(Ci.nsIMIMEService),
915 _helperAppSvc : Cc["@mozilla.org/uriloader/external-helper-app-service;1"].
916 getService(Ci.nsIExternalHelperAppService),
918 _handlerSvc : Cc["@mozilla.org/uriloader/handler-service;1"].
919 getService(Ci.nsIHandlerService),
921 _ioSvc : Cc["@mozilla.org/network/io-service;1"].
922 getService(Ci.nsIIOService),
925 //**************************************************************************//
926 // Initialization & Destruction
928 init: function() {
929 // Initialize shortcuts to some commonly accessed elements & values.
930 this._brandShortName =
931 document.getElementById("bundleBrand").getString("brandShortName");
932 this._prefsBundle = document.getElementById("bundlePreferences");
933 this._list = document.getElementById("handlersView");
934 this._filter = document.getElementById("filter");
936 // Observe preferences that influence what we display so we can rebuild
937 // the view when they change.
938 this._prefSvc.addObserver(PREF_SHOW_PLUGINS_IN_LIST, this, false);
939 this._prefSvc.addObserver(PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS, this, false);
940 this._prefSvc.addObserver(PREF_FEED_SELECTED_APP, this, false);
941 this._prefSvc.addObserver(PREF_FEED_SELECTED_WEB, this, false);
942 this._prefSvc.addObserver(PREF_FEED_SELECTED_ACTION, this, false);
943 this._prefSvc.addObserver(PREF_FEED_SELECTED_READER, this, false);
945 this._prefSvc.addObserver(PREF_VIDEO_FEED_SELECTED_APP, this, false);
946 this._prefSvc.addObserver(PREF_VIDEO_FEED_SELECTED_WEB, this, false);
947 this._prefSvc.addObserver(PREF_VIDEO_FEED_SELECTED_ACTION, this, false);
948 this._prefSvc.addObserver(PREF_VIDEO_FEED_SELECTED_READER, this, false);
950 this._prefSvc.addObserver(PREF_AUDIO_FEED_SELECTED_APP, this, false);
951 this._prefSvc.addObserver(PREF_AUDIO_FEED_SELECTED_WEB, this, false);
952 this._prefSvc.addObserver(PREF_AUDIO_FEED_SELECTED_ACTION, this, false);
953 this._prefSvc.addObserver(PREF_AUDIO_FEED_SELECTED_READER, this, false);
956 // Listen for window unload so we can remove our preference observers.
957 window.addEventListener("unload", this, false);
959 // Figure out how we should be sorting the list. We persist sort settings
960 // across sessions, so we can't assume the default sort column/direction.
961 // XXX should we be using the XUL sort service instead?
962 if (document.getElementById("actionColumn").hasAttribute("sortDirection")) {
963 this._sortColumn = document.getElementById("actionColumn");
964 // The typeColumn element always has a sortDirection attribute,
965 // either because it was persisted or because the default value
966 // from the xul file was used. If we are sorting on the other
967 // column, we should remove it.
968 document.getElementById("typeColumn").removeAttribute("sortDirection");
970 else
971 this._sortColumn = document.getElementById("typeColumn");
973 // Load the data and build the list of handlers.
974 // By doing this in a timeout, we let the preferences dialog resize itself
975 // to an appropriate size before we add a bunch of items to the list.
976 // Otherwise, if there are many items, and the Applications prefpane
977 // is the one that gets displayed when the user first opens the dialog,
978 // the dialog might stretch too much in an attempt to fit them all in.
979 // XXX Shouldn't we perhaps just set a max-height on the richlistbox?
980 var _delayedPaneLoad = function(self) {
981 self._loadData();
982 self._rebuildVisibleTypes();
983 self._sortVisibleTypes();
984 self._rebuildView();
986 // Notify observers that the UI is now ready
987 Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService).
988 notifyObservers(window, "app-handler-pane-loaded", null);
990 setTimeout(_delayedPaneLoad, 0, this);
993 destroy: function() {
994 window.removeEventListener("unload", this, false);
995 this._prefSvc.removeObserver(PREF_SHOW_PLUGINS_IN_LIST, this);
996 this._prefSvc.removeObserver(PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS, this);
997 this._prefSvc.removeObserver(PREF_FEED_SELECTED_APP, this);
998 this._prefSvc.removeObserver(PREF_FEED_SELECTED_WEB, this);
999 this._prefSvc.removeObserver(PREF_FEED_SELECTED_ACTION, this);
1000 this._prefSvc.removeObserver(PREF_FEED_SELECTED_READER, this);
1002 this._prefSvc.removeObserver(PREF_VIDEO_FEED_SELECTED_APP, this);
1003 this._prefSvc.removeObserver(PREF_VIDEO_FEED_SELECTED_WEB, this);
1004 this._prefSvc.removeObserver(PREF_VIDEO_FEED_SELECTED_ACTION, this);
1005 this._prefSvc.removeObserver(PREF_VIDEO_FEED_SELECTED_READER, this);
1007 this._prefSvc.removeObserver(PREF_AUDIO_FEED_SELECTED_APP, this);
1008 this._prefSvc.removeObserver(PREF_AUDIO_FEED_SELECTED_WEB, this);
1009 this._prefSvc.removeObserver(PREF_AUDIO_FEED_SELECTED_ACTION, this);
1010 this._prefSvc.removeObserver(PREF_AUDIO_FEED_SELECTED_READER, this);
1014 //**************************************************************************//
1015 // nsISupports
1017 QueryInterface: function(aIID) {
1018 if (aIID.equals(Ci.nsIObserver) ||
1019 aIID.equals(Ci.nsIDOMEventListener ||
1020 aIID.equals(Ci.nsISupports)))
1021 return this;
1023 throw Cr.NS_ERROR_NO_INTERFACE;
1027 //**************************************************************************//
1028 // nsIObserver
1030 observe: function (aSubject, aTopic, aData) {
1031 // Rebuild the list when there are changes to preferences that influence
1032 // whether or not to show certain entries in the list.
1033 if (aTopic == "nsPref:changed" && !this._storingAction) {
1034 // These two prefs alter the list of visible types, so we have to rebuild
1035 // that list when they change.
1036 if (aData == PREF_SHOW_PLUGINS_IN_LIST ||
1037 aData == PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS) {
1038 this._rebuildVisibleTypes();
1039 this._sortVisibleTypes();
1042 // All the prefs we observe can affect what we display, so we rebuild
1043 // the view when any of them changes.
1044 this._rebuildView();
1049 //**************************************************************************//
1050 // nsIDOMEventListener
1052 handleEvent: function(aEvent) {
1053 if (aEvent.type == "unload") {
1054 this.destroy();
1059 //**************************************************************************//
1060 // Composed Model Construction
1062 _loadData: function() {
1063 this._loadFeedHandler();
1064 this._loadPluginHandlers();
1065 this._loadApplicationHandlers();
1068 _loadFeedHandler: function() {
1069 this._handledTypes[TYPE_MAYBE_FEED] = feedHandlerInfo;
1070 feedHandlerInfo.handledOnlyByPlugin = false;
1072 this._handledTypes[TYPE_MAYBE_VIDEO_FEED] = videoFeedHandlerInfo;
1073 videoFeedHandlerInfo.handledOnlyByPlugin = false;
1075 this._handledTypes[TYPE_MAYBE_AUDIO_FEED] = audioFeedHandlerInfo;
1076 audioFeedHandlerInfo.handledOnlyByPlugin = false;
1080 * Load the set of handlers defined by plugins.
1082 * Note: if there's more than one plugin for a given MIME type, we assume
1083 * the last one is the one that the application will use. That may not be
1084 * correct, but it's how we've been doing it for years.
1086 * Perhaps we should instead query navigator.mimeTypes for the set of types
1087 * supported by the application and then get the plugin from each MIME type's
1088 * enabledPlugin property. But if there's a plugin for a type, we need
1089 * to know about it even if it isn't enabled, since we're going to give
1090 * the user an option to enable it.
1092 * I'll also note that my reading of nsPluginTag::RegisterWithCategoryManager
1093 * suggests that enabledPlugin is only determined during registration
1094 * and does not get updated when plugin.disable_full_page_plugin_for_types
1095 * changes (unless modification of that preference spawns reregistration).
1096 * So even if we could use enabledPlugin to get the plugin that would be used,
1097 * we'd still need to check the pref ourselves to find out if it's enabled.
1099 _loadPluginHandlers: function() {
1100 for (let i = 0; i < navigator.plugins.length; ++i) {
1101 let plugin = navigator.plugins[i];
1102 for (let j = 0; j < plugin.length; ++j) {
1103 let type = plugin[j].type;
1105 let handlerInfoWrapper;
1106 if (type in this._handledTypes)
1107 handlerInfoWrapper = this._handledTypes[type];
1108 else {
1109 let wrappedHandlerInfo =
1110 this._mimeSvc.getFromTypeAndExtension(type, null);
1111 handlerInfoWrapper = new HandlerInfoWrapper(type, wrappedHandlerInfo);
1112 handlerInfoWrapper.handledOnlyByPlugin = true;
1113 this._handledTypes[type] = handlerInfoWrapper;
1116 handlerInfoWrapper.plugin = plugin;
1122 * Load the set of handlers defined by the application datastore.
1124 _loadApplicationHandlers: function() {
1125 var wrappedHandlerInfos = this._handlerSvc.enumerate();
1126 while (wrappedHandlerInfos.hasMoreElements()) {
1127 let wrappedHandlerInfo =
1128 wrappedHandlerInfos.getNext().QueryInterface(Ci.nsIHandlerInfo);
1129 let type = wrappedHandlerInfo.type;
1131 let handlerInfoWrapper;
1132 if (type in this._handledTypes)
1133 handlerInfoWrapper = this._handledTypes[type];
1134 else {
1135 handlerInfoWrapper = new HandlerInfoWrapper(type, wrappedHandlerInfo);
1136 this._handledTypes[type] = handlerInfoWrapper;
1139 handlerInfoWrapper.handledOnlyByPlugin = false;
1144 //**************************************************************************//
1145 // View Construction
1147 _rebuildVisibleTypes: function() {
1148 // Reset the list of visible types and the visible type description counts.
1149 this._visibleTypes = [];
1150 this._visibleTypeDescriptionCount = {};
1152 // Get the preferences that help determine what types to show.
1153 var showPlugins = this._prefSvc.getBoolPref(PREF_SHOW_PLUGINS_IN_LIST);
1154 var hidePluginsWithoutExtensions =
1155 this._prefSvc.getBoolPref(PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS);
1157 for (let type in this._handledTypes) {
1158 let handlerInfo = this._handledTypes[type];
1160 // Hide plugins without associated extensions if so prefed so we don't
1161 // show a whole bunch of obscure types handled by plugins on Mac.
1162 // Note: though protocol types don't have extensions, we still show them;
1163 // the pref is only meant to be applied to MIME types, since plugins are
1164 // only associated with MIME types.
1165 // FIXME: should we also check the "suffixes" property of the plugin?
1166 // Filed as bug 395135.
1167 if (hidePluginsWithoutExtensions && handlerInfo.handledOnlyByPlugin &&
1168 handlerInfo.wrappedHandlerInfo instanceof Ci.nsIMIMEInfo &&
1169 !handlerInfo.primaryExtension)
1170 continue;
1172 // Hide types handled only by plugins if so prefed.
1173 if (handlerInfo.handledOnlyByPlugin && !showPlugins)
1174 continue;
1176 // We couldn't find any reason to exclude the type, so include it.
1177 this._visibleTypes.push(handlerInfo);
1179 if (handlerInfo.description in this._visibleTypeDescriptionCount)
1180 this._visibleTypeDescriptionCount[handlerInfo.description]++;
1181 else
1182 this._visibleTypeDescriptionCount[handlerInfo.description] = 1;
1186 _rebuildView: function() {
1187 // Clear the list of entries.
1188 while (this._list.childNodes.length > 1)
1189 this._list.removeChild(this._list.lastChild);
1191 var visibleTypes = this._visibleTypes;
1193 // If the user is filtering the list, then only show matching types.
1194 if (this._filter.value)
1195 visibleTypes = visibleTypes.filter(this._matchesFilter, this);
1197 for each (let visibleType in visibleTypes) {
1198 let item = document.createElement("richlistitem");
1199 item.setAttribute("type", visibleType.type);
1200 item.setAttribute("typeDescription", this._describeType(visibleType));
1201 if (visibleType.smallIcon)
1202 item.setAttribute("typeIcon", visibleType.smallIcon);
1203 item.setAttribute("actionDescription",
1204 this._describePreferredAction(visibleType));
1206 if (!this._setIconClassForPreferredAction(visibleType, item)) {
1207 item.setAttribute("actionIcon",
1208 this._getIconURLForPreferredAction(visibleType));
1211 this._list.appendChild(item);
1214 this._selectLastSelectedType();
1217 _matchesFilter: function(aType) {
1218 var filterValue = this._filter.value.toLowerCase();
1219 return this._describeType(aType).toLowerCase().indexOf(filterValue) != -1 ||
1220 this._describePreferredAction(aType).toLowerCase().indexOf(filterValue) != -1;
1224 * Describe, in a human-readable fashion, the type represented by the given
1225 * handler info object. Normally this is just the description provided by
1226 * the info object, but if more than one object presents the same description,
1227 * then we annotate the duplicate descriptions with the type itself to help
1228 * users distinguish between those types.
1230 * @param aHandlerInfo {nsIHandlerInfo} the type being described
1231 * @returns {string} a description of the type
1233 _describeType: function(aHandlerInfo) {
1234 if (this._visibleTypeDescriptionCount[aHandlerInfo.description] > 1)
1235 return this._prefsBundle.getFormattedString("typeDescriptionWithType",
1236 [aHandlerInfo.description,
1237 aHandlerInfo.type]);
1239 return aHandlerInfo.description;
1243 * Describe, in a human-readable fashion, the preferred action to take on
1244 * the type represented by the given handler info object.
1246 * XXX Should this be part of the HandlerInfoWrapper interface? It would
1247 * violate the separation of model and view, but it might make more sense
1248 * nonetheless (f.e. it would make sortTypes easier).
1250 * @param aHandlerInfo {nsIHandlerInfo} the type whose preferred action
1251 * is being described
1252 * @returns {string} a description of the action
1254 _describePreferredAction: function(aHandlerInfo) {
1255 // alwaysAskBeforeHandling overrides the preferred action, so if that flag
1256 // is set, then describe that behavior instead. For most types, this is
1257 // the "alwaysAsk" string, but for the feed type we show something special.
1258 if (aHandlerInfo.alwaysAskBeforeHandling) {
1259 if (isFeedType(aHandlerInfo.type))
1260 return this._prefsBundle.getFormattedString("previewInApp",
1261 [this._brandShortName]);
1262 else
1263 return this._prefsBundle.getString("alwaysAsk");
1266 switch (aHandlerInfo.preferredAction) {
1267 case Ci.nsIHandlerInfo.saveToDisk:
1268 return this._prefsBundle.getString("saveFile");
1270 case Ci.nsIHandlerInfo.useHelperApp:
1271 var preferredApp = aHandlerInfo.preferredApplicationHandler;
1272 var name;
1273 if (preferredApp instanceof Ci.nsILocalHandlerApp)
1274 name = getDisplayNameForFile(preferredApp.executable);
1275 else
1276 name = preferredApp.name;
1277 return this._prefsBundle.getFormattedString("useApp", [name]);
1279 case Ci.nsIHandlerInfo.handleInternally:
1280 // For the feed type, handleInternally means live bookmarks.
1281 if (isFeedType(aHandlerInfo.type))
1282 return this._prefsBundle.getFormattedString("addLiveBookmarksInApp",
1283 [this._brandShortName]);
1285 // For other types, handleInternally looks like either useHelperApp
1286 // or useSystemDefault depending on whether or not there's a preferred
1287 // handler app.
1288 if (this.isValidHandlerApp(aHandlerInfo.preferredApplicationHandler))
1289 return aHandlerInfo.preferredApplicationHandler.name;
1291 return aHandlerInfo.defaultDescription;
1293 // XXX Why don't we say the app will handle the type internally?
1294 // Is it because the app can't actually do that? But if that's true,
1295 // then why would a preferredAction ever get set to this value
1296 // in the first place?
1298 case Ci.nsIHandlerInfo.useSystemDefault:
1299 return this._prefsBundle.getFormattedString("useDefault",
1300 [aHandlerInfo.defaultDescription]);
1302 case kActionUsePlugin:
1303 return this._prefsBundle.getFormattedString("usePluginIn",
1304 [aHandlerInfo.plugin.name,
1305 this._brandShortName]);
1309 _selectLastSelectedType: function() {
1310 // If the list is disabled by the pref.downloads.disable_button.edit_actions
1311 // preference being locked, then don't select the type, as that would cause
1312 // it to appear selected, with a different background and an actions menu
1313 // that makes it seem like you can choose an action for the type.
1314 if (this._list.disabled)
1315 return;
1317 var lastSelectedType = this._list.getAttribute("lastSelectedType");
1318 if (!lastSelectedType)
1319 return;
1321 var item = this._list.getElementsByAttribute("type", lastSelectedType)[0];
1322 if (!item)
1323 return;
1325 this._list.selectedItem = item;
1329 * Whether or not the given handler app is valid.
1331 * @param aHandlerApp {nsIHandlerApp} the handler app in question
1333 * @returns {boolean} whether or not it's valid
1335 isValidHandlerApp: function(aHandlerApp) {
1336 if (!aHandlerApp)
1337 return false;
1339 if (aHandlerApp instanceof Ci.nsILocalHandlerApp)
1340 return this._isValidHandlerExecutable(aHandlerApp.executable);
1342 if (aHandlerApp instanceof Ci.nsIWebHandlerApp)
1343 return aHandlerApp.uriTemplate;
1345 if (aHandlerApp instanceof Ci.nsIWebContentHandlerInfo)
1346 return aHandlerApp.uri;
1348 return false;
1351 _isValidHandlerExecutable: function(aExecutable) {
1352 return aExecutable &&
1353 aExecutable.exists() &&
1354 aExecutable.isExecutable() &&
1355 // XXXben - we need to compare this with the running instance executable
1356 // just don't know how to do that via script...
1357 // XXXmano TBD: can probably add this to nsIShellService
1358 #ifdef XP_WIN
1359 #expand aExecutable.leafName != "__MOZ_APP_NAME__.exe";
1360 #else
1361 #ifdef XP_MACOSX
1362 #expand aExecutable.leafName != "__MOZ_APP_DISPLAYNAME__.app";
1363 #else
1364 #expand aExecutable.leafName != "__MOZ_APP_NAME__-bin";
1365 #endif
1366 #endif
1370 * Rebuild the actions menu for the selected entry. Gets called by
1371 * the richlistitem constructor when an entry in the list gets selected.
1373 rebuildActionsMenu: function() {
1374 var typeItem = this._list.selectedItem;
1375 var handlerInfo = this._handledTypes[typeItem.type];
1376 var menu =
1377 document.getAnonymousElementByAttribute(typeItem, "class", "actionsMenu");
1378 var menuPopup = menu.menupopup;
1380 // Clear out existing items.
1381 while (menuPopup.hasChildNodes())
1382 menuPopup.removeChild(menuPopup.lastChild);
1385 var askMenuItem = document.createElement("menuitem");
1386 askMenuItem.setAttribute("alwaysAsk", "true");
1387 let label;
1388 if (isFeedType(handlerInfo.type))
1389 label = this._prefsBundle.getFormattedString("previewInApp",
1390 [this._brandShortName]);
1391 else
1392 label = this._prefsBundle.getString("alwaysAsk");
1393 askMenuItem.setAttribute("label", label);
1394 askMenuItem.setAttribute("tooltiptext", label);
1395 askMenuItem.setAttribute(APP_ICON_ATTR_NAME, "ask");
1396 menuPopup.appendChild(askMenuItem);
1399 // Create a menu item for saving to disk.
1400 // Note: this option isn't available to protocol types, since we don't know
1401 // what it means to save a URL having a certain scheme to disk, nor is it
1402 // available to feeds, since the feed code doesn't implement the capability.
1403 if ((handlerInfo.wrappedHandlerInfo instanceof Ci.nsIMIMEInfo) &&
1404 !isFeedType(handlerInfo.type)) {
1405 var saveMenuItem = document.createElement("menuitem");
1406 saveMenuItem.setAttribute("action", Ci.nsIHandlerInfo.saveToDisk);
1407 let label = this._prefsBundle.getString("saveFile");
1408 saveMenuItem.setAttribute("label", label);
1409 saveMenuItem.setAttribute("tooltiptext", label);
1410 saveMenuItem.setAttribute(APP_ICON_ATTR_NAME, "save");
1411 menuPopup.appendChild(saveMenuItem);
1414 // If this is the feed type, add a Live Bookmarks item.
1415 if (isFeedType(handlerInfo.type)) {
1416 var internalMenuItem = document.createElement("menuitem");
1417 internalMenuItem.setAttribute("action", Ci.nsIHandlerInfo.handleInternally);
1418 let label = this._prefsBundle.getFormattedString("addLiveBookmarksInApp",
1419 [this._brandShortName]);
1420 internalMenuItem.setAttribute("label", label);
1421 internalMenuItem.setAttribute("tooltiptext", label);
1422 internalMenuItem.setAttribute(APP_ICON_ATTR_NAME, "feed");
1423 menuPopup.appendChild(internalMenuItem);
1426 // Add a separator to distinguish these items from the helper app items
1427 // that follow them.
1428 let menuItem = document.createElement("menuseparator");
1429 menuPopup.appendChild(menuItem);
1431 // Create a menu item for the OS default application, if any.
1432 if (handlerInfo.hasDefaultHandler) {
1433 var defaultMenuItem = document.createElement("menuitem");
1434 defaultMenuItem.setAttribute("action", Ci.nsIHandlerInfo.useSystemDefault);
1435 let label = this._prefsBundle.getFormattedString("useDefault",
1436 [handlerInfo.defaultDescription]);
1437 defaultMenuItem.setAttribute("label", label);
1438 defaultMenuItem.setAttribute("tooltiptext", handlerInfo.defaultDescription);
1439 defaultMenuItem.setAttribute("image", this._getIconURLForSystemDefault(handlerInfo));
1441 menuPopup.appendChild(defaultMenuItem);
1444 // Create menu items for possible handlers.
1445 let preferredApp = handlerInfo.preferredApplicationHandler;
1446 let possibleApps = handlerInfo.possibleApplicationHandlers.enumerate();
1447 var possibleAppMenuItems = [];
1448 while (possibleApps.hasMoreElements()) {
1449 let possibleApp = possibleApps.getNext();
1450 if (!this.isValidHandlerApp(possibleApp))
1451 continue;
1453 let menuItem = document.createElement("menuitem");
1454 menuItem.setAttribute("action", Ci.nsIHandlerInfo.useHelperApp);
1455 let label;
1456 if (possibleApp instanceof Ci.nsILocalHandlerApp)
1457 label = getDisplayNameForFile(possibleApp.executable);
1458 else
1459 label = possibleApp.name;
1460 label = this._prefsBundle.getFormattedString("useApp", [label]);
1461 menuItem.setAttribute("label", label);
1462 menuItem.setAttribute("tooltiptext", label);
1463 menuItem.setAttribute("image", this._getIconURLForHandlerApp(possibleApp));
1465 // Attach the handler app object to the menu item so we can use it
1466 // to make changes to the datastore when the user selects the item.
1467 menuItem.handlerApp = possibleApp;
1469 menuPopup.appendChild(menuItem);
1470 possibleAppMenuItems.push(menuItem);
1473 // Create a menu item for the plugin.
1474 if (handlerInfo.plugin) {
1475 var pluginMenuItem = document.createElement("menuitem");
1476 pluginMenuItem.setAttribute("action", kActionUsePlugin);
1477 let label = this._prefsBundle.getFormattedString("usePluginIn",
1478 [handlerInfo.plugin.name,
1479 this._brandShortName]);
1480 pluginMenuItem.setAttribute("label", label);
1481 pluginMenuItem.setAttribute("tooltiptext", label);
1482 pluginMenuItem.setAttribute(APP_ICON_ATTR_NAME, "plugin");
1483 menuPopup.appendChild(pluginMenuItem);
1486 // Create a menu item for selecting a local application.
1487 #ifdef XP_WIN
1488 // On Windows, selecting an application to open another application
1489 // would be meaningless so we special case executables.
1490 var executableType = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService)
1491 .getTypeFromExtension("exe");
1492 if (handlerInfo.type != executableType)
1493 #endif
1495 let menuItem = document.createElement("menuitem");
1496 menuItem.setAttribute("oncommand", "gApplicationsPane.chooseApp(event)");
1497 let label = this._prefsBundle.getString("useOtherApp");
1498 menuItem.setAttribute("label", label);
1499 menuItem.setAttribute("tooltiptext", label);
1500 menuPopup.appendChild(menuItem);
1503 // Create a menu item for managing applications.
1504 if (possibleAppMenuItems.length) {
1505 let menuItem = document.createElement("menuseparator");
1506 menuPopup.appendChild(menuItem);
1507 menuItem = document.createElement("menuitem");
1508 menuItem.setAttribute("oncommand", "gApplicationsPane.manageApp(event)");
1509 menuItem.setAttribute("label", this._prefsBundle.getString("manageApp"));
1510 menuPopup.appendChild(menuItem);
1513 // Select the item corresponding to the preferred action. If the always
1514 // ask flag is set, it overrides the preferred action. Otherwise we pick
1515 // the item identified by the preferred action (when the preferred action
1516 // is to use a helper app, we have to pick the specific helper app item).
1517 if (handlerInfo.alwaysAskBeforeHandling)
1518 menu.selectedItem = askMenuItem;
1519 else switch (handlerInfo.preferredAction) {
1520 case Ci.nsIHandlerInfo.handleInternally:
1521 menu.selectedItem = internalMenuItem;
1522 break;
1523 case Ci.nsIHandlerInfo.useSystemDefault:
1524 menu.selectedItem = defaultMenuItem;
1525 break;
1526 case Ci.nsIHandlerInfo.useHelperApp:
1527 if (preferredApp)
1528 menu.selectedItem =
1529 possibleAppMenuItems.filter(function(v) v.handlerApp.equals(preferredApp))[0];
1530 break;
1531 case kActionUsePlugin:
1532 menu.selectedItem = pluginMenuItem;
1533 break;
1534 case Ci.nsIHandlerInfo.saveToDisk:
1535 menu.selectedItem = saveMenuItem;
1536 break;
1541 //**************************************************************************//
1542 // Sorting & Filtering
1544 _sortColumn: null,
1547 * Sort the list when the user clicks on a column header.
1549 sort: function (event) {
1550 var column = event.target;
1552 // If the user clicked on a new sort column, remove the direction indicator
1553 // from the old column.
1554 if (this._sortColumn && this._sortColumn != column)
1555 this._sortColumn.removeAttribute("sortDirection");
1557 this._sortColumn = column;
1559 // Set (or switch) the sort direction indicator.
1560 if (column.getAttribute("sortDirection") == "ascending")
1561 column.setAttribute("sortDirection", "descending");
1562 else
1563 column.setAttribute("sortDirection", "ascending");
1565 this._sortVisibleTypes();
1566 this._rebuildView();
1570 * Sort the list of visible types by the current sort column/direction.
1572 _sortVisibleTypes: function() {
1573 if (!this._sortColumn)
1574 return;
1576 var t = this;
1578 function sortByType(a, b) {
1579 return t._describeType(a).toLowerCase().
1580 localeCompare(t._describeType(b).toLowerCase());
1583 function sortByAction(a, b) {
1584 return t._describePreferredAction(a).toLowerCase().
1585 localeCompare(t._describePreferredAction(b).toLowerCase());
1588 switch (this._sortColumn.getAttribute("value")) {
1589 case "type":
1590 this._visibleTypes.sort(sortByType);
1591 break;
1592 case "action":
1593 this._visibleTypes.sort(sortByAction);
1594 break;
1597 if (this._sortColumn.getAttribute("sortDirection") == "descending")
1598 this._visibleTypes.reverse();
1602 * Filter the list when the user enters a filter term into the filter field.
1604 filter: function() {
1605 this._rebuildView();
1608 focusFilterBox: function() {
1609 this._filter.focus();
1610 this._filter.select();
1614 //**************************************************************************//
1615 // Changes
1617 onSelectAction: function(aActionItem) {
1618 this._storingAction = true;
1620 try {
1621 this._storeAction(aActionItem);
1623 finally {
1624 this._storingAction = false;
1628 _storeAction: function(aActionItem) {
1629 var typeItem = this._list.selectedItem;
1630 var handlerInfo = this._handledTypes[typeItem.type];
1632 if (aActionItem.hasAttribute("alwaysAsk")) {
1633 handlerInfo.alwaysAskBeforeHandling = true;
1635 else if (aActionItem.hasAttribute("action")) {
1636 let action = parseInt(aActionItem.getAttribute("action"));
1638 // Set the plugin state if we're enabling or disabling a plugin.
1639 if (action == kActionUsePlugin)
1640 handlerInfo.enablePluginType();
1641 else if (handlerInfo.plugin && !handlerInfo.isDisabledPluginType)
1642 handlerInfo.disablePluginType();
1644 // Set the preferred application handler.
1645 // We leave the existing preferred app in the list when we set
1646 // the preferred action to something other than useHelperApp so that
1647 // legacy datastores that don't have the preferred app in the list
1648 // of possible apps still include the preferred app in the list of apps
1649 // the user can choose to handle the type.
1650 if (action == Ci.nsIHandlerInfo.useHelperApp)
1651 handlerInfo.preferredApplicationHandler = aActionItem.handlerApp;
1653 // Set the "always ask" flag.
1654 handlerInfo.alwaysAskBeforeHandling = false;
1656 // Set the preferred action.
1657 handlerInfo.preferredAction = action;
1660 handlerInfo.store();
1662 // Make sure the handler info object is flagged to indicate that there is
1663 // now some user configuration for the type.
1664 handlerInfo.handledOnlyByPlugin = false;
1666 // Update the action label and image to reflect the new preferred action.
1667 typeItem.setAttribute("actionDescription",
1668 this._describePreferredAction(handlerInfo));
1669 if (!this._setIconClassForPreferredAction(handlerInfo, typeItem)) {
1670 typeItem.setAttribute("actionIcon",
1671 this._getIconURLForPreferredAction(handlerInfo));
1675 manageApp: function(aEvent) {
1676 // Don't let the normal "on select action" handler get this event,
1677 // as we handle it specially ourselves.
1678 aEvent.stopPropagation();
1680 var typeItem = this._list.selectedItem;
1681 var handlerInfo = this._handledTypes[typeItem.type];
1683 document.documentElement.openSubDialog("chrome://browser/content/preferences/applicationManager.xul",
1684 "", handlerInfo);
1686 // Rebuild the actions menu so that we revert to the previous selection,
1687 // or "Always ask" if the previous default application has been removed
1688 this.rebuildActionsMenu();
1690 // update the richlistitem too. Will be visible when selecting another row
1691 typeItem.setAttribute("actionDescription",
1692 this._describePreferredAction(handlerInfo));
1693 if (!this._setIconClassForPreferredAction(handlerInfo, typeItem)) {
1694 typeItem.setAttribute("actionIcon",
1695 this._getIconURLForPreferredAction(handlerInfo));
1699 chooseApp: function(aEvent) {
1700 // Don't let the normal "on select action" handler get this event,
1701 // as we handle it specially ourselves.
1702 aEvent.stopPropagation();
1704 var handlerApp;
1706 #ifdef XP_WIN
1707 var params = {};
1708 var handlerInfo = this._handledTypes[this._list.selectedItem.type];
1710 if (isFeedType(handlerInfo.type)) {
1711 // MIME info will be null, create a temp object.
1712 params.mimeInfo = this._mimeSvc.getFromTypeAndExtension(handlerInfo.type,
1713 handlerInfo.primaryExtension);
1714 } else {
1715 params.mimeInfo = handlerInfo.wrappedHandlerInfo;
1718 params.title = this._prefsBundle.getString("fpTitleChooseApp");
1719 params.description = handlerInfo.description;
1720 params.filename = null;
1721 params.handlerApp = null;
1723 window.openDialog("chrome://global/content/appPicker.xul", null,
1724 "chrome,modal,centerscreen,titlebar,dialog=yes",
1725 params);
1727 if (params.handlerApp &&
1728 params.handlerApp.executable &&
1729 params.handlerApp.executable.isFile()) {
1730 handlerApp = params.handlerApp;
1732 // Add the app to the type's list of possible handlers.
1733 handlerInfo.addPossibleApplicationHandler(handlerApp);
1735 #else
1736 var fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
1737 var winTitle = this._prefsBundle.getString("fpTitleChooseApp");
1738 fp.init(window, winTitle, Ci.nsIFilePicker.modeOpen);
1739 fp.appendFilters(Ci.nsIFilePicker.filterApps);
1741 // Prompt the user to pick an app. If they pick one, and it's a valid
1742 // selection, then add it to the list of possible handlers.
1743 if (fp.show() == Ci.nsIFilePicker.returnOK && fp.file &&
1744 this._isValidHandlerExecutable(fp.file)) {
1745 handlerApp = Cc["@mozilla.org/uriloader/local-handler-app;1"].
1746 createInstance(Ci.nsILocalHandlerApp);
1747 handlerApp.name = getDisplayNameForFile(fp.file);
1748 handlerApp.executable = fp.file;
1750 // Add the app to the type's list of possible handlers.
1751 let handlerInfo = this._handledTypes[this._list.selectedItem.type];
1752 handlerInfo.addPossibleApplicationHandler(handlerApp);
1754 #endif
1756 // Rebuild the actions menu whether the user picked an app or canceled.
1757 // If they picked an app, we want to add the app to the menu and select it.
1758 // If they canceled, we want to go back to their previous selection.
1759 this.rebuildActionsMenu();
1761 // If the user picked a new app from the menu, select it.
1762 if (handlerApp) {
1763 let typeItem = this._list.selectedItem;
1764 let actionsMenu =
1765 document.getAnonymousElementByAttribute(typeItem, "class", "actionsMenu");
1766 let menuItems = actionsMenu.menupopup.childNodes;
1767 for (let i = 0; i < menuItems.length; i++) {
1768 let menuItem = menuItems[i];
1769 if (menuItem.handlerApp && menuItem.handlerApp.equals(handlerApp)) {
1770 actionsMenu.selectedIndex = i;
1771 this.onSelectAction(menuItem);
1772 break;
1778 // Mark which item in the list was last selected so we can reselect it
1779 // when we rebuild the list or when the user returns to the prefpane.
1780 onSelectionChanged: function() {
1781 if (this._list.selectedItem)
1782 this._list.setAttribute("lastSelectedType",
1783 this._list.selectedItem.getAttribute("type"));
1786 _setIconClassForPreferredAction: function(aHandlerInfo, aElement) {
1787 // If this returns true, the attribute that CSS sniffs for was set to something
1788 // so you shouldn't manually set an icon URI.
1789 // This removes the existing actionIcon attribute if any, even if returning false.
1790 aElement.removeAttribute("actionIcon");
1792 if (aHandlerInfo.alwaysAskBeforeHandling) {
1793 aElement.setAttribute(APP_ICON_ATTR_NAME, "ask");
1794 return true;
1797 switch (aHandlerInfo.preferredAction) {
1798 case Ci.nsIHandlerInfo.saveToDisk:
1799 aElement.setAttribute(APP_ICON_ATTR_NAME, "save");
1800 return true;
1802 case Ci.nsIHandlerInfo.handleInternally:
1803 if (isFeedType(aHandlerInfo.type)) {
1804 aElement.setAttribute(APP_ICON_ATTR_NAME, "feed");
1805 return true;
1807 break;
1809 case kActionUsePlugin:
1810 aElement.setAttribute(APP_ICON_ATTR_NAME, "plugin");
1811 return true;
1813 aElement.removeAttribute(APP_ICON_ATTR_NAME);
1814 return false;
1817 _getIconURLForPreferredAction: function(aHandlerInfo) {
1818 switch (aHandlerInfo.preferredAction) {
1819 case Ci.nsIHandlerInfo.useSystemDefault:
1820 return this._getIconURLForSystemDefault(aHandlerInfo);
1822 case Ci.nsIHandlerInfo.useHelperApp:
1823 let (preferredApp = aHandlerInfo.preferredApplicationHandler) {
1824 if (this.isValidHandlerApp(preferredApp))
1825 return this._getIconURLForHandlerApp(preferredApp);
1827 break;
1829 // This should never happen, but if preferredAction is set to some weird
1830 // value, then fall back to the generic application icon.
1831 default:
1832 return ICON_URL_APP;
1836 _getIconURLForHandlerApp: function(aHandlerApp) {
1837 if (aHandlerApp instanceof Ci.nsILocalHandlerApp)
1838 return this._getIconURLForFile(aHandlerApp.executable);
1840 if (aHandlerApp instanceof Ci.nsIWebHandlerApp)
1841 return this._getIconURLForWebApp(aHandlerApp.uriTemplate);
1843 if (aHandlerApp instanceof Ci.nsIWebContentHandlerInfo)
1844 return this._getIconURLForWebApp(aHandlerApp.uri)
1846 // We know nothing about other kinds of handler apps.
1847 return "";
1850 _getIconURLForFile: function(aFile) {
1851 var fph = this._ioSvc.getProtocolHandler("file").
1852 QueryInterface(Ci.nsIFileProtocolHandler);
1853 var urlSpec = fph.getURLSpecFromFile(aFile);
1855 return "moz-icon://" + urlSpec + "?size=16";
1858 _getIconURLForWebApp: function(aWebAppURITemplate) {
1859 var uri = this._ioSvc.newURI(aWebAppURITemplate, null, null);
1861 // Unfortunately we can't use the favicon service to get the favicon,
1862 // because the service looks in the annotations table for a record with
1863 // the exact URL we give it, and users won't have such records for URLs
1864 // they don't visit, and users won't visit the web app's URL template,
1865 // they'll only visit URLs derived from that template (i.e. with %s
1866 // in the template replaced by the URL of the content being handled).
1868 if (/^https?/.test(uri.scheme))
1869 return uri.prePath + "/favicon.ico";
1871 return "";
1874 _getIconURLForSystemDefault: function(aHandlerInfo) {
1875 // Handler info objects for MIME types on some OSes implement a property bag
1876 // interface from which we can get an icon for the default app, so if we're
1877 // dealing with a MIME type on one of those OSes, then try to get the icon.
1878 if ("wrappedHandlerInfo" in aHandlerInfo) {
1879 let wrappedHandlerInfo = aHandlerInfo.wrappedHandlerInfo;
1881 if (wrappedHandlerInfo instanceof Ci.nsIMIMEInfo &&
1882 wrappedHandlerInfo instanceof Ci.nsIPropertyBag) {
1883 try {
1884 let url = wrappedHandlerInfo.getProperty("defaultApplicationIconURL");
1885 if (url)
1886 return url + "?size=16";
1888 catch(ex) {}
1892 // If this isn't a MIME type object on an OS that supports retrieving
1893 // the icon, or if we couldn't retrieve the icon for some other reason,
1894 // then use a generic icon.
1895 return ICON_URL_APP;