browser/components/downloads/content/allDownloadsViewOverlay.js

Wed, 31 Dec 2014 06:55:50 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:55:50 +0100
changeset 2
7e26c7da4463
permissions
-rw-r--r--

Added tag UPSTREAM_283F7C6 for changeset ca08bd8f51b2

     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  * THE PLACES VIEW IMPLEMENTED IN THIS FILE HAS A VERY PARTICULAR USE CASE.
     7  * IT IS HIGHLY RECOMMENDED NOT TO EXTEND IT FOR ANY OTHER USE CASES OR RELY
     8  * ON IT AS AN API.
     9  */
    11 let Cu = Components.utils;
    12 let Ci = Components.interfaces;
    13 let Cc = Components.classes;
    15 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
    16 Cu.import("resource://gre/modules/Services.jsm");
    17 Cu.import("resource://gre/modules/NetUtil.jsm");
    18 Cu.import("resource://gre/modules/DownloadUtils.jsm");
    19 Cu.import("resource:///modules/DownloadsCommon.jsm");
    20 Cu.import("resource://gre/modules/PlacesUtils.jsm");
    21 Cu.import("resource://gre/modules/osfile.jsm");
    23 XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
    24                                   "resource://gre/modules/PrivateBrowsingUtils.jsm");
    25 XPCOMUtils.defineLazyModuleGetter(this, "RecentWindow",
    26                                   "resource:///modules/RecentWindow.jsm");
    27 XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
    28                                   "resource://gre/modules/FileUtils.jsm");
    30 const nsIDM = Ci.nsIDownloadManager;
    32 const DESTINATION_FILE_URI_ANNO  = "downloads/destinationFileURI";
    33 const DOWNLOAD_META_DATA_ANNO    = "downloads/metaData";
    35 const DOWNLOAD_VIEW_SUPPORTED_COMMANDS =
    36  ["cmd_delete", "cmd_copy", "cmd_paste", "cmd_selectAll",
    37   "downloadsCmd_pauseResume", "downloadsCmd_cancel",
    38   "downloadsCmd_open", "downloadsCmd_show", "downloadsCmd_retry",
    39   "downloadsCmd_openReferrer", "downloadsCmd_clearDownloads"];
    41 const NOT_AVAILABLE = Number.MAX_VALUE;
    43 /**
    44  * A download element shell is responsible for handling the commands and the
    45  * displayed data for a single download view element. The download element
    46  * could represent either a past download (for which we get data from places)  or
    47  * a "session" download (using a data-item object. See DownloadsCommon.jsm), or both.
    48  *
    49  * Once initialized with either a data item or a places node, the created richlistitem
    50  * can be accessed through the |element| getter, and can then be inserted/removed from
    51  * a richlistbox.
    52  *
    53  * The shell doesn't take care of inserting the item, or removing it when it's no longer
    54  * valid. That's the caller (a DownloadsPlacesView object) responsibility.
    55  *
    56  * The caller is also responsible for "passing over" notification from both the
    57  * download-view and the places-result-observer, in the following manner:
    58  *  - The DownloadsPlacesView object implements getViewItem of the download-view
    59  *    pseudo interface.  It returns this object (therefore we implement
    60  *    onStateChangea and onProgressChange here).
    61  *  - The DownloadsPlacesView object adds itself as a places result observer and
    62  *    calls this object's placesNodeIconChanged, placesNodeTitleChanged and
    63  *    placeNodeAnnotationChanged from its callbacks.
    64  *
    65  * @param [optional] aDataItem
    66  *        The data item of a the session download. Required if aPlacesNode is not set
    67  * @param [optional] aPlacesNode
    68  *        The places node for a past download. Required if aDataItem is not set.
    69  * @param [optional] aAnnotations
    70  *        Map containing annotations values, to speed up the initial loading.
    71  */
    72 function DownloadElementShell(aDataItem, aPlacesNode, aAnnotations) {
    73   this._element = document.createElement("richlistitem");
    74   this._element._shell = this;
    76   this._element.classList.add("download");
    77   this._element.classList.add("download-state");
    79   if (aAnnotations)
    80     this._annotations = aAnnotations;
    81   if (aDataItem)
    82     this.dataItem = aDataItem;
    83   if (aPlacesNode)
    84     this.placesNode = aPlacesNode;
    85 }
    87 DownloadElementShell.prototype = {
    88   // The richlistitem for the download
    89   get element() this._element,
    91   /**
    92    * Manages the "active" state of the shell.  By default all the shells
    93    * without a dataItem are inactive, thus their UI is not updated.  They must
    94    * be activated when entering the visible area.  Session downloads are
    95    * always active since they always have a dataItem.
    96    */
    97   ensureActive: function DES_ensureActive() {
    98     if (!this._active) {
    99       this._active = true;
   100       this._element.setAttribute("active", true);
   101       this._updateUI();
   102     }
   103   },
   104   get active() !!this._active,
   106   // The data item for the download
   107   _dataItem: null,
   108   get dataItem() this._dataItem,
   110   set dataItem(aValue) {
   111     if (this._dataItem != aValue) {
   112       if (!aValue && !this._placesNode)
   113         throw new Error("Should always have either a dataItem or a placesNode");
   115       this._dataItem = aValue;
   116       if (!this.active)
   117         this.ensureActive();
   118       else
   119         this._updateUI();
   120     }
   121     return aValue;
   122   },
   124   _placesNode: null,
   125   get placesNode() this._placesNode,
   126   set placesNode(aValue) {
   127     if (this._placesNode != aValue) {
   128       if (!aValue && !this._dataItem)
   129         throw new Error("Should always have either a dataItem or a placesNode");
   131       // Preserve the annotations map if this is the first loading and we got
   132       // cached values.
   133       if (this._placesNode || !this._annotations) {
   134         this._annotations = new Map();
   135       }
   137       this._placesNode = aValue;
   139       // We don't need to update the UI if we had a data item, because
   140       // the places information isn't used in this case.
   141       if (!this._dataItem && this.active)
   142         this._updateUI();
   143     }
   144     return aValue;
   145   },
   147   // The download uri (as a string)
   148   get downloadURI() {
   149     if (this._dataItem)
   150      return this._dataItem.uri;
   151     if (this._placesNode)
   152       return this._placesNode.uri;
   153     throw new Error("Unexpected download element state");
   154   },
   156   get _downloadURIObj() {
   157     if (!("__downloadURIObj" in this))
   158       this.__downloadURIObj = NetUtil.newURI(this.downloadURI);
   159     return this.__downloadURIObj;
   160   },
   162   _getIcon: function DES__getIcon() {
   163     let metaData = this.getDownloadMetaData();
   164     if ("filePath" in metaData)
   165       return "moz-icon://" + metaData.filePath + "?size=32";
   167     if (this._placesNode) {
   168       // Try to extract an extension from the uri.
   169       let ext = this._downloadURIObj.QueryInterface(Ci.nsIURL).fileExtension;
   170       if (ext)
   171         return "moz-icon://." + ext + "?size=32";
   172       return this._placesNode.icon || "moz-icon://.unknown?size=32";
   173     }
   174     if (this._dataItem)
   175       throw new Error("Session-download items should always have a target file uri");
   177     throw new Error("Unexpected download element state");
   178   },
   180   // Helper for getting a places annotation set for the download.
   181   _getAnnotation: function DES__getAnnotation(aAnnotation, aDefaultValue) {
   182     let value;
   183     if (this._annotations.has(aAnnotation))
   184       value = this._annotations.get(aAnnotation);
   186     // If the value is cached, or we know it doesn't exist, avoid a database
   187     // lookup.
   188     if (value === undefined) {
   189       try {
   190         value = PlacesUtils.annotations.getPageAnnotation(
   191           this._downloadURIObj, aAnnotation);
   192       }
   193       catch(ex) {
   194         value = NOT_AVAILABLE;
   195       }
   196     }
   198     if (value === NOT_AVAILABLE) {
   199       if (aDefaultValue === undefined) {
   200         throw new Error("Could not get required annotation '" + aAnnotation +
   201                         "' for download with url '" + this.downloadURI + "'");
   202       }
   203       value = aDefaultValue;
   204     }
   206     this._annotations.set(aAnnotation, value);
   207     return value;
   208   },
   210   _fetchTargetFileInfo: function DES__fetchTargetFileInfo(aUpdateMetaDataAndStatusUI = false) {
   211     if (this._targetFileInfoFetched)
   212       throw new Error("_fetchTargetFileInfo should not be called if the information was already fetched");
   213     if (!this.active)
   214       throw new Error("Trying to _fetchTargetFileInfo on an inactive download shell");
   216     let path = this.getDownloadMetaData().filePath;
   218     // In previous version, the target file annotations were not set,
   219     // so we cannot tell where is the file.
   220     if (path === undefined) {
   221       this._targetFileInfoFetched = true;
   222       this._targetFileExists = false;
   223       if (aUpdateMetaDataAndStatusUI) {
   224         this._metaData = null;
   225         this._updateDownloadStatusUI();
   226       }
   227       // Here we don't need to update the download commands,
   228       // as the state is unknown as it was.
   229       return;
   230     }
   232     OS.File.stat(path).then(
   233       function onSuccess(fileInfo) {
   234         this._targetFileInfoFetched = true;
   235         this._targetFileExists = true;
   236         this._targetFileSize = fileInfo.size;
   237         if (aUpdateMetaDataAndStatusUI) {
   238           this._metaData = null;
   239           this._updateDownloadStatusUI();
   240         }
   241         if (this._element.selected)
   242           goUpdateDownloadCommands();
   243       }.bind(this),
   245       function onFailure(aReason) {
   246         if (aReason instanceof OS.File.Error && aReason.becauseNoSuchFile) {
   247           this._targetFileInfoFetched = true;
   248           this._targetFileExists = false;
   249         }
   250         else {
   251           Cu.reportError("Could not fetch info for target file (reason: " +
   252                          aReason + ")");
   253         }
   255         if (aUpdateMetaDataAndStatusUI) {
   256           this._metaData = null;
   257           this._updateDownloadStatusUI();
   258         }
   260         if (this._element.selected)
   261           goUpdateDownloadCommands();
   262       }.bind(this)
   263     );
   264   },
   266   _getAnnotatedMetaData: function DES__getAnnotatedMetaData()
   267     JSON.parse(this._getAnnotation(DOWNLOAD_META_DATA_ANNO)),
   269   _extractFilePathAndNameFromFileURI:
   270   function DES__extractFilePathAndNameFromFileURI(aFileURI) {
   271     let file = Cc["@mozilla.org/network/protocol;1?name=file"]
   272                 .getService(Ci.nsIFileProtocolHandler)
   273                 .getFileFromURLSpec(aFileURI);
   274     return [file.path, file.leafName];
   275   },
   277   /**
   278    * Retrieve the meta data object for the download.  The following fields
   279    * may be set.
   280    *
   281    * - state - any download state defined in nsIDownloadManager.  If this field
   282    *   is not set, the download state is unknown.
   283    * - endTime: the end time of the download.
   284    * - filePath: the downloaded file path on the file system, when it
   285    *   was downloaded.  The file may not exist.  This is set for session
   286    *   downloads that have a local file set, and for history downloads done
   287    *   after the landing of bug 591289.
   288    * - fileName: the downloaded file name on the file system. Set if filePath
   289    *   is set.
   290    * - displayName: the user-facing label for the download.  This is always
   291    *   set.  If available, it's set to the downloaded file name.  If not,
   292    *   the places title for the download uri is used it's set.  As a last
   293    *   resort, we fallback to the download uri.
   294    * - fileSize (only set for downloads which completed succesfully):
   295    *   the downloaded file size.  For downloads done after the landing of
   296    *   bug 826991, this value is "static" - that is, it does not necessarily
   297    *   mean that the file is in place and has this size.
   298    */
   299   getDownloadMetaData: function DES_getDownloadMetaData() {
   300     if (!this._metaData) {
   301       if (this._dataItem) {
   302         this._metaData = {
   303           state:       this._dataItem.state,
   304           endTime:     this._dataItem.endTime,
   305           fileName:    this._dataItem.target,
   306           displayName: this._dataItem.target
   307         };
   308         if (this._dataItem.done)
   309           this._metaData.fileSize = this._dataItem.maxBytes;
   310         if (this._dataItem.localFile)
   311           this._metaData.filePath = this._dataItem.localFile.path;
   312       }
   313       else {
   314         try {
   315           this._metaData = this._getAnnotatedMetaData();
   316         }
   317         catch(ex) {
   318           this._metaData = { };
   319           if (this._targetFileInfoFetched && this._targetFileExists) {
   320             this._metaData.state = this._targetFileSize > 0 ?
   321               nsIDM.DOWNLOAD_FINISHED : nsIDM.DOWNLOAD_FAILED;
   322             this._metaData.fileSize = this._targetFileSize;
   323           }
   325           // This is actually the start-time, but it's the best we can get.
   326           this._metaData.endTime = this._placesNode.time / 1000;
   327         }
   329         try {
   330           let targetFileURI = this._getAnnotation(DESTINATION_FILE_URI_ANNO);
   331           [this._metaData.filePath, this._metaData.fileName] =
   332             this._extractFilePathAndNameFromFileURI(targetFileURI);
   333           this._metaData.displayName = this._metaData.fileName;
   334         }
   335         catch(ex) {
   336           this._metaData.displayName = this._placesNode.title || this.downloadURI;
   337         }
   338       }
   339     }
   340     return this._metaData;
   341   },
   343   // The status text for the download
   344   _getStatusText: function DES__getStatusText() {
   345     let s = DownloadsCommon.strings;
   346     if (this._dataItem && this._dataItem.inProgress) {
   347       if (this._dataItem.paused) {
   348         let transfer =
   349           DownloadUtils.getTransferTotal(this._dataItem.currBytes,
   350                                          this._dataItem.maxBytes);
   352          // We use the same XUL label to display both the state and the amount
   353          // transferred, for example "Paused -  1.1 MB".
   354          return s.statusSeparatorBeforeNumber(s.statePaused, transfer);
   355       }
   356       if (this._dataItem.state == nsIDM.DOWNLOAD_DOWNLOADING) {
   357         let [status, newEstimatedSecondsLeft] =
   358           DownloadUtils.getDownloadStatus(this.dataItem.currBytes,
   359                                           this.dataItem.maxBytes,
   360                                           this.dataItem.speed,
   361                                           this._lastEstimatedSecondsLeft || Infinity);
   362         this._lastEstimatedSecondsLeft = newEstimatedSecondsLeft;
   363         return status;
   364       }
   365       if (this._dataItem.starting) {
   366         return s.stateStarting;
   367       }
   368       if (this._dataItem.state == nsIDM.DOWNLOAD_SCANNING) {
   369         return s.stateScanning;
   370       }
   372       throw new Error("_getStatusText called with a bogus download state");
   373     }
   375     // This is a not-in-progress or history download.
   376     let stateLabel = "";
   377     let state = this.getDownloadMetaData().state;
   378     switch (state) {
   379       case nsIDM.DOWNLOAD_FAILED:
   380         stateLabel = s.stateFailed;
   381         break;
   382       case nsIDM.DOWNLOAD_CANCELED:
   383         stateLabel = s.stateCanceled;
   384         break;
   385       case nsIDM.DOWNLOAD_BLOCKED_PARENTAL:
   386         stateLabel = s.stateBlockedParentalControls;
   387         break;
   388       case nsIDM.DOWNLOAD_BLOCKED_POLICY:
   389         stateLabel = s.stateBlockedPolicy;
   390         break;
   391       case nsIDM.DOWNLOAD_DIRTY:
   392         stateLabel = s.stateDirty;
   393         break;
   394       case nsIDM.DOWNLOAD_FINISHED:{
   395         // For completed downloads, show the file size (e.g. "1.5 MB")
   396         let metaData = this.getDownloadMetaData();
   397         if ("fileSize" in metaData) {
   398           let [size, unit] = DownloadUtils.convertByteUnits(metaData.fileSize);
   399           stateLabel = s.sizeWithUnits(size, unit);
   400           break;
   401         }
   402         // Fallback to default unknown state.
   403       }
   404       default:
   405         stateLabel = s.sizeUnknown;
   406         break;
   407     }
   409     // TODO (bug 829201): history downloads should get the referrer from Places.
   410     let referrer = this._dataItem && this._dataItem.referrer ||
   411                    this.downloadURI;
   412     let [displayHost, fullHost] = DownloadUtils.getURIHost(referrer);
   414     let date = new Date(this.getDownloadMetaData().endTime);
   415     let [displayDate, fullDate] = DownloadUtils.getReadableDates(date);
   417     // We use the same XUL label to display the state, the host name, and the
   418     // end time.
   419     let firstPart = s.statusSeparator(stateLabel, displayHost);
   420     return s.statusSeparator(firstPart, displayDate);
   421   },
   423   // The progressmeter element for the download
   424   get _progressElement() {
   425     if (!("__progressElement" in this)) {
   426       this.__progressElement =
   427         document.getAnonymousElementByAttribute(this._element, "anonid",
   428                                                 "progressmeter");
   429     }
   430     return this.__progressElement;
   431   },
   433   // Updates the download state attribute (and by that hide/unhide the
   434   // appropriate buttons and context menu items), the status text label,
   435   // and the progress meter.
   436   _updateDownloadStatusUI: function  DES__updateDownloadStatusUI() {
   437     if (!this.active)
   438       throw new Error("_updateDownloadStatusUI called for an inactive item.");
   440     let state = this.getDownloadMetaData().state;
   441     if (state !== undefined)
   442       this._element.setAttribute("state", state);
   444     this._element.setAttribute("status", this._getStatusText());
   446     // For past-downloads, we're done. For session-downloads, we may also need
   447     // to update the progress-meter.
   448     if (!this._dataItem)
   449       return;
   451     // Copied from updateProgress in downloads.js.
   452     if (this._dataItem.starting) {
   453       // Before the download starts, the progress meter has its initial value.
   454       this._element.setAttribute("progressmode", "normal");
   455       this._element.setAttribute("progress", "0");
   456     }
   457     else if (this._dataItem.state == nsIDM.DOWNLOAD_SCANNING ||
   458              this._dataItem.percentComplete == -1) {
   459       // We might not know the progress of a running download, and we don't know
   460       // the remaining time during the malware scanning phase.
   461       this._element.setAttribute("progressmode", "undetermined");
   462     }
   463     else {
   464       // This is a running download of which we know the progress.
   465       this._element.setAttribute("progressmode", "normal");
   466       this._element.setAttribute("progress", this._dataItem.percentComplete);
   467     }
   469     // Dispatch the ValueChange event for accessibility, if possible.
   470     if (this._progressElement) {
   471       let event = document.createEvent("Events");
   472       event.initEvent("ValueChange", true, true);
   473       this._progressElement.dispatchEvent(event);
   474     }
   475   },
   477   _updateDisplayNameAndIcon: function DES__updateDisplayNameAndIcon() {
   478     let metaData = this.getDownloadMetaData();
   479     this._element.setAttribute("displayName", metaData.displayName);
   480     this._element.setAttribute("image", this._getIcon());
   481   },
   483   _updateUI: function DES__updateUI() {
   484     if (!this.active)
   485       throw new Error("Trying to _updateUI on an inactive download shell");
   487     this._metaData = null;
   488     this._targetFileInfoFetched = false;
   490     this._updateDisplayNameAndIcon();
   492     // For history downloads done in past releases, the downloads/metaData
   493     // annotation is not set, and therefore we cannot tell the download
   494     // state without the target file information.
   495     if (this._dataItem || this.getDownloadMetaData().state !== undefined)
   496       this._updateDownloadStatusUI();
   497     else
   498       this._fetchTargetFileInfo(true);
   499   },
   501   placesNodeIconChanged: function DES_placesNodeIconChanged() {
   502     if (!this._dataItem)
   503       this._element.setAttribute("image", this._getIcon());
   504   },
   506   placesNodeTitleChanged: function DES_placesNodeTitleChanged() {
   507     // If there's a file path, we use the leaf name for the title.
   508     if (!this._dataItem && this.active && !this.getDownloadMetaData().filePath) {
   509       this._metaData = null;
   510       this._updateDisplayNameAndIcon();
   511     }
   512   },
   514   placesNodeAnnotationChanged: function DES_placesNodeAnnotationChanged(aAnnoName) {
   515     this._annotations.delete(aAnnoName);
   516     if (!this._dataItem && this.active) {
   517       if (aAnnoName == DOWNLOAD_META_DATA_ANNO) {
   518         let metaData = this.getDownloadMetaData();
   519         let annotatedMetaData = this._getAnnotatedMetaData();
   520         metaData.endTme = annotatedMetaData.endTime;
   521         if ("fileSize" in annotatedMetaData)
   522           metaData.fileSize = annotatedMetaData.fileSize;
   523         else
   524           delete metaData.fileSize;
   526         if (metaData.state != annotatedMetaData.state) {
   527           metaData.state = annotatedMetaData.state;
   528           if (this._element.selected)
   529             goUpdateDownloadCommands();
   530         }
   532         this._updateDownloadStatusUI();
   533       }
   534       else if (aAnnoName == DESTINATION_FILE_URI_ANNO) {
   535         let metaData = this.getDownloadMetaData();
   536         let targetFileURI = this._getAnnotation(DESTINATION_FILE_URI_ANNO);
   537         [metaData.filePath, metaData.fileName] =
   538             this._extractFilePathAndNameFromFileURI(targetFileURI);
   539         metaData.displayName = metaData.fileName;
   540         this._updateDisplayNameAndIcon();
   542         if (this._targetFileInfoFetched) {
   543           // This will also update the download commands if necessary.
   544           this._targetFileInfoFetched = false;
   545           this._fetchTargetFileInfo();
   546         }
   547       }
   548     }
   549   },
   551   /* DownloadView */
   552   onStateChange: function DES_onStateChange(aOldState) {
   553     let metaData = this.getDownloadMetaData();
   554     metaData.state = this.dataItem.state;
   555     if (aOldState != nsIDM.DOWNLOAD_FINISHED && aOldState != metaData.state) {
   556       // See comment in DVI_onStateChange in downloads.js (the panel-view)
   557       this._element.setAttribute("image", this._getIcon() + "&state=normal");
   558       metaData.fileSize = this._dataItem.maxBytes;
   559       if (this._targetFileInfoFetched) {
   560         this._targetFileInfoFetched = false;
   561         this._fetchTargetFileInfo();
   562       }
   563     }
   565     this._updateDownloadStatusUI();
   566     if (this._element.selected)
   567       goUpdateDownloadCommands();
   568     else
   569       goUpdateCommand("downloadsCmd_clearDownloads");
   570   },
   572   /* DownloadView */
   573   onProgressChange: function DES_onProgressChange() {
   574     this._updateDownloadStatusUI();
   575   },
   577   /* nsIController */
   578   isCommandEnabled: function DES_isCommandEnabled(aCommand) {
   579     // The only valid command for inactive elements is cmd_delete.
   580     if (!this.active && aCommand != "cmd_delete")
   581       return false;
   582     switch (aCommand) {
   583       case "downloadsCmd_open": {
   584         // We cannot open a session dowload file unless it's done ("openable").
   585         // If it's finished, we need to make sure the file was not removed,
   586         // as we do for past downloads.
   587         if (this._dataItem && !this._dataItem.openable)
   588           return false;
   590         if (this._targetFileInfoFetched)
   591           return this._targetFileExists;
   593         // If the target file information is not yet fetched,
   594         // temporarily assume that the file is in place.
   595         return this.getDownloadMetaData().state == nsIDM.DOWNLOAD_FINISHED;
   596       }
   597       case "downloadsCmd_show": {
   598         // TODO: Bug 827010 - Handle part-file asynchronously.
   599         if (this._dataItem &&
   600             this._dataItem.partFile && this._dataItem.partFile.exists())
   601           return true;
   603         if (this._targetFileInfoFetched)
   604           return this._targetFileExists;
   606         // If the target file information is not yet fetched,
   607         // temporarily assume that the file is in place.
   608         return this.getDownloadMetaData().state == nsIDM.DOWNLOAD_FINISHED;
   609       }
   610       case "downloadsCmd_pauseResume":
   611         return this._dataItem && this._dataItem.inProgress && this._dataItem.resumable;
   612       case "downloadsCmd_retry":
   613         // An history download can always be retried.
   614         return !this._dataItem || this._dataItem.canRetry;
   615       case "downloadsCmd_openReferrer":
   616         return this._dataItem && !!this._dataItem.referrer;
   617       case "cmd_delete":
   618         // The behavior in this case is somewhat unexpected, so we disallow that.
   619         if (this._placesNode && this._dataItem && this._dataItem.inProgress)
   620           return false;
   621         return true;
   622       case "downloadsCmd_cancel":
   623         return this._dataItem != null;
   624     }
   625     return false;
   626   },
   628   _retryAsHistoryDownload: function DES__retryAsHistoryDownload() {
   629     // In future we may try to download into the same original target uri, when
   630     // we have it.  Though that requires verifying the path is still valid and
   631     // may surprise the user if he wants to be requested every time.
   632     let browserWin = RecentWindow.getMostRecentBrowserWindow();
   633     let initiatingDoc = browserWin ? browserWin.document : document;
   634     DownloadURL(this.downloadURI, this.getDownloadMetaData().fileName,
   635                 initiatingDoc);
   636   },
   638   /* nsIController */
   639   doCommand: function DES_doCommand(aCommand) {
   640     switch (aCommand) {
   641       case "downloadsCmd_open": {
   642         let file = this._dataItem ?
   643           this.dataItem.localFile :
   644           new FileUtils.File(this.getDownloadMetaData().filePath);
   646         DownloadsCommon.openDownloadedFile(file, null, window);
   647         break;
   648       }
   649       case "downloadsCmd_show": {
   650         if (this._dataItem) {
   651           this._dataItem.showLocalFile();
   652         }
   653         else {
   654           let file = new FileUtils.File(this.getDownloadMetaData().filePath);
   655           DownloadsCommon.showDownloadedFile(file);
   656         }
   657         break;
   658       }
   659       case "downloadsCmd_openReferrer": {
   660         openURL(this._dataItem.referrer);
   661         break;
   662       }
   663       case "downloadsCmd_cancel": {
   664         this._dataItem.cancel();
   665         break;
   666       }
   667       case "cmd_delete": {
   668         if (this._dataItem)
   669           this._dataItem.remove();
   670         if (this._placesNode)
   671           PlacesUtils.bhistory.removePage(this._downloadURIObj);
   672         break;
   673        }
   674       case "downloadsCmd_retry": {
   675         if (this._dataItem)
   676           this._dataItem.retry();
   677         else
   678           this._retryAsHistoryDownload();
   679         break;
   680       }
   681       case "downloadsCmd_pauseResume": {
   682         this._dataItem.togglePauseResume();
   683         break;
   684       }
   685     }
   686   },
   688   // Returns whether or not the download handled by this shell should
   689   // show up in the search results for the given term.  Both the display
   690   // name for the download and the url are searched.
   691   matchesSearchTerm: function DES_matchesSearchTerm(aTerm) {
   692     if (!aTerm)
   693       return true;
   694     aTerm = aTerm.toLowerCase();
   695     return this.getDownloadMetaData().displayName.toLowerCase().contains(aTerm) ||
   696            this.downloadURI.toLowerCase().contains(aTerm);
   697   },
   699   // Handles return kepress on the element (the keypress listener is
   700   // set in the DownloadsPlacesView object).
   701   doDefaultCommand: function DES_doDefaultCommand() {
   702     function getDefaultCommandForState(aState) {
   703       switch (aState) {
   704         case nsIDM.DOWNLOAD_FINISHED:
   705           return "downloadsCmd_open";
   706         case nsIDM.DOWNLOAD_PAUSED:
   707           return "downloadsCmd_pauseResume";
   708         case nsIDM.DOWNLOAD_NOTSTARTED:
   709         case nsIDM.DOWNLOAD_QUEUED:
   710           return "downloadsCmd_cancel";
   711         case nsIDM.DOWNLOAD_FAILED:
   712         case nsIDM.DOWNLOAD_CANCELED:
   713           return "downloadsCmd_retry";
   714         case nsIDM.DOWNLOAD_SCANNING:
   715           return "downloadsCmd_show";
   716         case nsIDM.DOWNLOAD_BLOCKED_PARENTAL:
   717         case nsIDM.DOWNLOAD_DIRTY:
   718         case nsIDM.DOWNLOAD_BLOCKED_POLICY:
   719           return "downloadsCmd_openReferrer";
   720       }
   721       return "";
   722     }
   723     let command = getDefaultCommandForState(this.getDownloadMetaData().state);
   724     if (command && this.isCommandEnabled(command))
   725       this.doCommand(command);
   726   },
   728   /**
   729    * At the first time an item is selected, we don't yet have
   730    * the target file information.  Thus the call to goUpdateDownloadCommands
   731    * in DPV_onSelect would result in best-guess enabled/disabled result.
   732    * That way we let the user perform command immediately. However, once
   733    * we have the target file information, we can update the commands
   734    * appropriately (_fetchTargetFileInfo() calls goUpdateDownloadCommands).
   735    */
   736   onSelect: function DES_onSelect() {
   737     if (!this.active)
   738       return;
   739     if (!this._targetFileInfoFetched)
   740       this._fetchTargetFileInfo();
   741   }
   742 };
   744 /**
   745  * A Downloads Places View is a places view designed to show a places query
   746  * for history donwloads alongside the current "session"-downloads.
   747  *
   748  * As we don't use the places controller, some methods implemented by other
   749  * places views are not implemented by this view.
   750  *
   751  * A richlistitem in this view can represent either a past download or a session
   752  * download, or both. Session downloads are shown first in the view, and as long
   753  * as they exist they "collapses" their history "counterpart" (So we don't show two
   754  * items for every download).
   755  */
   756 function DownloadsPlacesView(aRichListBox, aActive = true) {
   757   this._richlistbox = aRichListBox;
   758   this._richlistbox._placesView = this;
   759   window.controllers.insertControllerAt(0, this);
   761   // Map download URLs to download element shells regardless of their type
   762   this._downloadElementsShellsForURI = new Map();
   764   // Map download data items to their element shells.
   765   this._viewItemsForDataItems = new WeakMap();
   767   // Points to the last session download element. We keep track of this
   768   // in order to keep all session downloads above past downloads.
   769   this._lastSessionDownloadElement = null;
   771   this._searchTerm = "";
   773   this._active = aActive;
   775   // Register as a downloads view. The places data will be initialized by
   776   // the places setter.
   777   this._initiallySelectedElement = null;
   778   this._downloadsData = DownloadsCommon.getData(window.opener || window);
   779   this._downloadsData.addView(this);
   781   // Get the Download button out of the attention state since we're about to
   782   // view all downloads.
   783   DownloadsCommon.getIndicatorData(window).attention = false;
   785   // Make sure to unregister the view if the window is closed.
   786   window.addEventListener("unload", function() {
   787     window.controllers.removeController(this);
   788     this._downloadsData.removeView(this);
   789     this.result = null;
   790   }.bind(this), true);
   791   // Resizing the window may change items visibility.
   792   window.addEventListener("resize", function() {
   793     this._ensureVisibleElementsAreActive();
   794   }.bind(this), true);
   795 }
   797 DownloadsPlacesView.prototype = {
   798   get associatedElement() this._richlistbox,
   800   get active() this._active,
   801   set active(val) {
   802     this._active = val;
   803     if (this._active)
   804       this._ensureVisibleElementsAreActive();
   805     return this._active;
   806   },
   808   _forEachDownloadElementShellForURI:
   809   function DPV__forEachDownloadElementShellForURI(aURI, aCallback) {
   810     if (this._downloadElementsShellsForURI.has(aURI)) {
   811       let downloadElementShells = this._downloadElementsShellsForURI.get(aURI);
   812       for (let des of downloadElementShells) {
   813         aCallback(des);
   814       }
   815     }
   816   },
   818   _getAnnotationsFor: function DPV_getAnnotationsFor(aURI) {
   819     if (!this._cachedAnnotations) {
   820       this._cachedAnnotations = new Map();
   821       for (let name of [ DESTINATION_FILE_URI_ANNO,
   822                          DOWNLOAD_META_DATA_ANNO ]) {
   823         let results = PlacesUtils.annotations.getAnnotationsWithName(name);
   824         for (let result of results) {
   825           let url = result.uri.spec;
   826           if (!this._cachedAnnotations.has(url))
   827             this._cachedAnnotations.set(url, new Map());
   828           let m = this._cachedAnnotations.get(url);
   829           m.set(result.annotationName, result.annotationValue);
   830         }
   831       }
   832     }
   834     let annotations = this._cachedAnnotations.get(aURI);
   835     if (!annotations) {
   836       // There are no annotations for this entry, that means it is quite old.
   837       // Make up a fake annotations entry with default values.
   838       annotations = new Map();
   839       annotations.set(DESTINATION_FILE_URI_ANNO, NOT_AVAILABLE);
   840     }
   841     // The meta-data annotation has been added recently, so it's likely missing.
   842     if (!annotations.has(DOWNLOAD_META_DATA_ANNO)) {
   843       annotations.set(DOWNLOAD_META_DATA_ANNO, NOT_AVAILABLE);
   844     }
   845     return annotations;
   846   },
   848   /**
   849    * Given a data item for a session download, or a places node for a past
   850    * download, updates the view as necessary.
   851    *  1. If the given data is a places node, we check whether there are any
   852    *     elements for the same download url. If there are, then we just reset
   853    *     their places node. Otherwise we add a new download element.
   854    *  2. If the given data is a data item, we first check if there's a history
   855    *     download in the list that is not associated with a data item. If we
   856    *     found one, we use it for the data item as well and reposition it
   857    *     alongside the other session downloads. If we don't, then we go ahead
   858    *     and create a new element for the download.
   859    *
   860    * @param aDataItem
   861    *        The data item of a session download. Set to null for history
   862    *        downloads data.
   863    * @param [optional] aPlacesNode
   864    *        The places node for a history download. Required if there's no data
   865    *        item.
   866    * @param [optional] aNewest
   867    *        @see onDataItemAdded. Ignored for history downlods.
   868    * @param [optional] aDocumentFragment
   869    *        To speed up the appending of multiple elements to the end of the
   870    *        list which are coming in a single batch (i.e. invalidateContainer),
   871    *        a document fragment may be passed to which the new elements would
   872    *        be appended. It's the caller's job to ensure the fragment is merged
   873    *        to the richlistbox at the end.
   874    */
   875   _addDownloadData:
   876   function DPV_addDownloadData(aDataItem, aPlacesNode, aNewest = false,
   877                                aDocumentFragment = null) {
   878     let downloadURI = aPlacesNode ? aPlacesNode.uri : aDataItem.uri;
   879     let shellsForURI = this._downloadElementsShellsForURI.get(downloadURI);
   880     if (!shellsForURI) {
   881       shellsForURI = new Set();
   882       this._downloadElementsShellsForURI.set(downloadURI, shellsForURI);
   883     }
   885     let newOrUpdatedShell = null;
   887     // Trivial: if there are no shells for this download URI, we always
   888     // need to create one.
   889     let shouldCreateShell = shellsForURI.size == 0;
   891     // However, if we do have shells for this download uri, there are
   892     // few options:
   893     // 1) There's only one shell and it's for a history download (it has
   894     //    no data item). In this case, we update this shell and move it
   895     //    if necessary
   896     // 2) There are multiple shells, indicicating multiple downloads for
   897     //    the same download uri are running. In this case we create
   898     //    anoter shell for the download (so we have one shell for each data
   899     //    item).
   900     //
   901     // Note: If a cancelled session download is already in the list, and the
   902     // download is retired, onDataItemAdded is called again for the same
   903     // data item. Thus, we also check that we make sure we don't have a view item
   904     // already.
   905     if (!shouldCreateShell &&
   906         aDataItem && this.getViewItem(aDataItem) == null) {
   907       // If there's a past-download-only shell for this download-uri with no
   908       // associated data item, use it for the new data item. Otherwise, go ahead
   909       // and create another shell.
   910       shouldCreateShell = true;
   911       for (let shell of shellsForURI) {
   912         if (!shell.dataItem) {
   913           shouldCreateShell = false;
   914           shell.dataItem = aDataItem;
   915           newOrUpdatedShell = shell;
   916           this._viewItemsForDataItems.set(aDataItem, shell);
   917           break;
   918         }
   919       }
   920     }
   922     if (shouldCreateShell) {
   923       // Bug 836271: The annotations for a url should be cached only when the
   924       // places node is available, i.e. when we know we we'd be notified for
   925       // annoation changes. 
   926       // Otherwise we may cache NOT_AVILABLE values first for a given session
   927       // download, and later use these NOT_AVILABLE values when a history
   928       // download for the same URL is added.
   929       let cachedAnnotations = aPlacesNode ? this._getAnnotationsFor(downloadURI) : null;
   930       let shell = new DownloadElementShell(aDataItem, aPlacesNode, cachedAnnotations);
   931       newOrUpdatedShell = shell;
   932       shellsForURI.add(shell);
   933       if (aDataItem)
   934         this._viewItemsForDataItems.set(aDataItem, shell);
   935     }
   936     else if (aPlacesNode) {
   937       for (let shell of shellsForURI) {
   938         if (shell.placesNode != aPlacesNode)
   939           shell.placesNode = aPlacesNode;
   940       }
   941     }
   943     if (newOrUpdatedShell) {
   944       if (aNewest) {
   945         this._richlistbox.insertBefore(newOrUpdatedShell.element,
   946                                        this._richlistbox.firstChild);
   947         if (!this._lastSessionDownloadElement) {
   948           this._lastSessionDownloadElement = newOrUpdatedShell.element;
   949         }
   950         // Some operations like retrying an history download move an element to
   951         // the top of the richlistbox, along with other session downloads.
   952         // More generally, if a new download is added, should be made visible.
   953         this._richlistbox.ensureElementIsVisible(newOrUpdatedShell.element);
   954       }
   955       else if (aDataItem) {
   956         let before = this._lastSessionDownloadElement ?
   957           this._lastSessionDownloadElement.nextSibling : this._richlistbox.firstChild;
   958         this._richlistbox.insertBefore(newOrUpdatedShell.element, before);
   959         this._lastSessionDownloadElement = newOrUpdatedShell.element;
   960       }
   961       else {
   962         let appendTo = aDocumentFragment || this._richlistbox;
   963         appendTo.appendChild(newOrUpdatedShell.element);
   964       }
   966       if (this.searchTerm) {
   967         newOrUpdatedShell.element.hidden =
   968           !newOrUpdatedShell.element._shell.matchesSearchTerm(this.searchTerm);
   969       }
   970     }
   972     // If aDocumentFragment is defined this is a batch change, so it's up to
   973     // the caller to append the fragment and activate the visible shells.
   974     if (!aDocumentFragment) {
   975       this._ensureVisibleElementsAreActive();
   976       goUpdateCommand("downloadsCmd_clearDownloads");
   977     }
   978   },
   980   _removeElement: function DPV__removeElement(aElement) {
   981     // If the element was selected exclusively, select its next
   982     // sibling first, if not, try for previous sibling, if any.
   983     if ((aElement.nextSibling || aElement.previousSibling) &&
   984         this._richlistbox.selectedItems &&
   985         this._richlistbox.selectedItems.length == 1 &&
   986         this._richlistbox.selectedItems[0] == aElement) {
   987       this._richlistbox.selectItem(aElement.nextSibling ||
   988                                    aElement.previousSibling);
   989     }
   991     if (this._lastSessionDownloadElement == aElement)
   992       this._lastSessionDownloadElement = aElement.previousSibling;
   994     this._richlistbox.removeItemFromSelection(aElement);
   995     this._richlistbox.removeChild(aElement);
   996     this._ensureVisibleElementsAreActive();
   997     goUpdateCommand("downloadsCmd_clearDownloads");
   998   },
  1000   _removeHistoryDownloadFromView:
  1001   function DPV__removeHistoryDownloadFromView(aPlacesNode) {
  1002     let downloadURI = aPlacesNode.uri;
  1003     let shellsForURI = this._downloadElementsShellsForURI.get(downloadURI);
  1004     if (shellsForURI) {
  1005       for (let shell of shellsForURI) {
  1006         if (shell.dataItem) {
  1007           shell.placesNode = null;
  1009         else {
  1010           this._removeElement(shell.element);
  1011           shellsForURI.delete(shell);
  1012           if (shellsForURI.size == 0)
  1013             this._downloadElementsShellsForURI.delete(downloadURI);
  1017   },
  1019   _removeSessionDownloadFromView:
  1020   function DPV__removeSessionDownloadFromView(aDataItem) {
  1021     let shells = this._downloadElementsShellsForURI.get(aDataItem.uri);
  1022     if (shells.size == 0)
  1023       throw new Error("Should have had at leaat one shell for this uri");
  1025     let shell = this.getViewItem(aDataItem);
  1026     if (!shells.has(shell))
  1027       throw new Error("Missing download element shell in shells list for url");
  1029     // If there's more than one item for this download uri, we can let the
  1030     // view item for this this particular data item go away.
  1031     // If there's only one item for this download uri, we should only
  1032     // keep it if it is associated with a history download.
  1033     if (shells.size > 1 || !shell.placesNode) {
  1034       this._removeElement(shell.element);
  1035       shells.delete(shell);
  1036       if (shells.size == 0)
  1037         this._downloadElementsShellsForURI.delete(aDataItem.uri);
  1039     else {
  1040       shell.dataItem = null;
  1041       // Move it below the session-download items;
  1042       if (this._lastSessionDownloadElement == shell.element) {
  1043         this._lastSessionDownloadElement = shell.element.previousSibling;
  1045       else {
  1046         let before = this._lastSessionDownloadElement ?
  1047           this._lastSessionDownloadElement.nextSibling : this._richlistbox.firstChild;
  1048         this._richlistbox.insertBefore(shell.element, before);
  1051   },
  1053   _ensureVisibleElementsAreActive:
  1054   function DPV__ensureVisibleElementsAreActive() {
  1055     if (!this.active || this._ensureVisibleTimer || !this._richlistbox.firstChild)
  1056       return;
  1058     this._ensureVisibleTimer = setTimeout(function() {
  1059       delete this._ensureVisibleTimer;
  1060       if (!this._richlistbox.firstChild)
  1061         return;
  1063       let rlbRect = this._richlistbox.getBoundingClientRect();
  1064       let winUtils = window.QueryInterface(Ci.nsIInterfaceRequestor)
  1065                            .getInterface(Ci.nsIDOMWindowUtils);
  1066       let nodes = winUtils.nodesFromRect(rlbRect.left, rlbRect.top,
  1067                                          0, rlbRect.width, rlbRect.height, 0,
  1068                                          true, false);
  1069       // nodesFromRect returns nodes in z-index order, and for the same z-index
  1070       // sorts them in inverted DOM order, thus starting from the one that would
  1071       // be on top.
  1072       let firstVisibleNode, lastVisibleNode;
  1073       for (let node of nodes) {
  1074         if (node.localName === "richlistitem" && node._shell) {
  1075           node._shell.ensureActive();
  1076           // The first visible node is the last match.
  1077           firstVisibleNode = node;
  1078           // While the last visible node is the first match.
  1079           if (!lastVisibleNode)
  1080             lastVisibleNode = node;
  1084       // Also activate the first invisible nodes in both boundaries (that is,
  1085       // above and below the visible area) to ensure proper keyboard navigation
  1086       // in both directions.
  1087       let nodeBelowVisibleArea = lastVisibleNode && lastVisibleNode.nextSibling;
  1088       if (nodeBelowVisibleArea && nodeBelowVisibleArea._shell)
  1089         nodeBelowVisibleArea._shell.ensureActive();
  1091       let nodeABoveVisibleArea =
  1092         firstVisibleNode && firstVisibleNode.previousSibling;
  1093       if (nodeABoveVisibleArea && nodeABoveVisibleArea._shell)
  1094         nodeABoveVisibleArea._shell.ensureActive();
  1095     }.bind(this), 10);
  1096   },
  1098   _place: "",
  1099   get place() this._place,
  1100   set place(val) {
  1101     // Don't reload everything if we don't have to.
  1102     if (this._place == val) {
  1103       // XXXmano: places.js relies on this behavior (see Bug 822203).
  1104       this.searchTerm = "";
  1105       return val;
  1108     this._place = val;
  1110     let history = PlacesUtils.history;
  1111     let queries = { }, options = { };
  1112     history.queryStringToQueries(val, queries, { }, options);
  1113     if (!queries.value.length)
  1114       queries.value = [history.getNewQuery()];
  1116     let result = history.executeQueries(queries.value, queries.value.length,
  1117                                         options.value);
  1118     result.addObserver(this, false);
  1119     return val;
  1120   },
  1122   _result: null,
  1123   get result() this._result,
  1124   set result(val) {
  1125     if (this._result == val)
  1126       return val;
  1128     if (this._result) {
  1129       this._result.removeObserver(this);
  1130       this._resultNode.containerOpen = false;
  1133     if (val) {
  1134       this._result = val;
  1135       this._resultNode = val.root;
  1136       this._resultNode.containerOpen = true;
  1137       this._ensureInitialSelection();
  1139     else {
  1140       delete this._resultNode;
  1141       delete this._result;
  1144     return val;
  1145   },
  1147   get selectedNodes() {
  1148     let placesNodes = [];
  1149     let selectedElements = this._richlistbox.selectedItems;
  1150     for (let elt of selectedElements) {
  1151       if (elt._shell.placesNode)
  1152         placesNodes.push(elt._shell.placesNode);
  1154     return placesNodes;
  1155   },
  1157   get selectedNode() {
  1158     let selectedNodes = this.selectedNodes;
  1159     return selectedNodes.length == 1 ? selectedNodes[0] : null;
  1160   },
  1162   get hasSelection() this.selectedNodes.length > 0,
  1164   containerStateChanged:
  1165   function DPV_containerStateChanged(aNode, aOldState, aNewState) {
  1166     this.invalidateContainer(aNode)
  1167   },
  1169   invalidateContainer:
  1170   function DPV_invalidateContainer(aContainer) {
  1171     if (aContainer != this._resultNode)
  1172       throw new Error("Unexpected container node");
  1173     if (!aContainer.containerOpen)
  1174       throw new Error("Root container for the downloads query cannot be closed");
  1176     let suppressOnSelect = this._richlistbox.suppressOnSelect;
  1177     this._richlistbox.suppressOnSelect = true;
  1178     try {
  1179       // Remove the invalidated history downloads from the list and unset the
  1180       // places node for data downloads.
  1181       // Loop backwards since _removeHistoryDownloadFromView may removeChild().
  1182       for (let i = this._richlistbox.childNodes.length - 1; i >= 0; --i) {
  1183         let element = this._richlistbox.childNodes[i];
  1184         if (element._shell.placesNode)
  1185           this._removeHistoryDownloadFromView(element._shell.placesNode);
  1188     finally {
  1189       this._richlistbox.suppressOnSelect = suppressOnSelect;
  1192     if (aContainer.childCount > 0) {
  1193       let elementsToAppendFragment = document.createDocumentFragment();
  1194       for (let i = 0; i < aContainer.childCount; i++) {
  1195         try {
  1196           this._addDownloadData(null, aContainer.getChild(i), false,
  1197                                 elementsToAppendFragment);
  1199         catch(ex) {
  1200           Cu.reportError(ex);
  1204       // _addDownloadData may not add new elements if there were already
  1205       // data items in place.
  1206       if (elementsToAppendFragment.firstChild) {
  1207         this._appendDownloadsFragment(elementsToAppendFragment);
  1208         this._ensureVisibleElementsAreActive();
  1212     goUpdateDownloadCommands();
  1213   },
  1215   _appendDownloadsFragment: function DPV__appendDownloadsFragment(aDOMFragment) {
  1216     // Workaround multiple reflows hang by removing the richlistbox
  1217     // and adding it back when we're done.
  1219     // Hack for bug 836283: reset xbl fields to their old values after the
  1220     // binding is reattached to avoid breaking the selection state
  1221     let xblFields = new Map();
  1222     for (let [key, value] in Iterator(this._richlistbox)) {
  1223       xblFields.set(key, value);
  1226     let parentNode = this._richlistbox.parentNode;
  1227     let nextSibling = this._richlistbox.nextSibling;
  1228     parentNode.removeChild(this._richlistbox);
  1229     this._richlistbox.appendChild(aDOMFragment);
  1230     parentNode.insertBefore(this._richlistbox, nextSibling);
  1232     for (let [key, value] of xblFields) {
  1233       this._richlistbox[key] = value;
  1235   },
  1237   nodeInserted: function DPV_nodeInserted(aParent, aPlacesNode) {
  1238     this._addDownloadData(null, aPlacesNode);
  1239   },
  1241   nodeRemoved: function DPV_nodeRemoved(aParent, aPlacesNode, aOldIndex) {
  1242     this._removeHistoryDownloadFromView(aPlacesNode);
  1243   },
  1245   nodeIconChanged: function DPV_nodeIconChanged(aNode) {
  1246     this._forEachDownloadElementShellForURI(aNode.uri, function(aDownloadElementShell) {
  1247       aDownloadElementShell.placesNodeIconChanged();
  1248     });
  1249   },
  1251   nodeAnnotationChanged: function DPV_nodeAnnotationChanged(aNode, aAnnoName) {
  1252     this._forEachDownloadElementShellForURI(aNode.uri, function(aDownloadElementShell) {
  1253       aDownloadElementShell.placesNodeAnnotationChanged(aAnnoName);
  1254     });
  1255   },
  1257   nodeTitleChanged: function DPV_nodeTitleChanged(aNode, aNewTitle) {
  1258     this._forEachDownloadElementShellForURI(aNode.uri, function(aDownloadElementShell) {
  1259       aDownloadElementShell.placesNodeTitleChanged();
  1260     });
  1261   },
  1263   nodeKeywordChanged: function() {},
  1264   nodeDateAddedChanged: function() {},
  1265   nodeLastModifiedChanged: function() {},
  1266   nodeHistoryDetailsChanged: function() {},
  1267   nodeTagsChanged: function() {},
  1268   sortingChanged: function() {},
  1269   nodeMoved: function() {},
  1270   nodeURIChanged: function() {},
  1271   batching: function() {},
  1273   get controller() this._richlistbox.controller,
  1275   get searchTerm() this._searchTerm,
  1276   set searchTerm(aValue) {
  1277     if (this._searchTerm != aValue) {
  1278       for (let element of this._richlistbox.childNodes) {
  1279         element.hidden = !element._shell.matchesSearchTerm(aValue);
  1281       this._ensureVisibleElementsAreActive();
  1283     return this._searchTerm = aValue;
  1284   },
  1286   /**
  1287    * When the view loads, we want to select the first item.
  1288    * However, because session downloads, for which the data is loaded
  1289    * asynchronously, always come first in the list, and because the list
  1290    * may (or may not) already contain history downloads at that point, it
  1291    * turns out that by the time we can select the first item, the user may
  1292    * have already started using the view.
  1293    * To make things even more complicated, in other cases, the places data
  1294    * may be loaded after the session downloads data.  Thus we cannot rely on
  1295    * the order in which the data comes in.
  1296    * We work around this by attempting to select the first element twice,
  1297    * once after the places data is loaded and once when the session downloads
  1298    * data is done loading.  However, if the selection has changed in-between,
  1299    * we assume the user has already started using the view and give up.
  1300    */
  1301   _ensureInitialSelection: function DPV__ensureInitialSelection() {
  1302     // Either they're both null, or the selection has not changed in between.
  1303     if (this._richlistbox.selectedItem == this._initiallySelectedElement) {
  1304       let firstDownloadElement = this._richlistbox.firstChild;
  1305       if (firstDownloadElement != this._initiallySelectedElement) {
  1306         // We may be called before _ensureVisibleElementsAreActive,
  1307         // or before the download binding is attached. Therefore, ensure the
  1308         // first item is activated, and pass the item to the richlistbox
  1309         // setters only at a point we know for sure the binding is attached.
  1310         firstDownloadElement._shell.ensureActive();
  1311         Services.tm.mainThread.dispatch(function() {
  1312           this._richlistbox.selectedItem = firstDownloadElement;
  1313           this._richlistbox.currentItem = firstDownloadElement;
  1314           this._initiallySelectedElement = firstDownloadElement;
  1315         }.bind(this), Ci.nsIThread.DISPATCH_NORMAL);
  1318   },
  1320   onDataLoadStarting: function() { },
  1321   onDataLoadCompleted: function DPV_onDataLoadCompleted() {
  1322     this._ensureInitialSelection();
  1323   },
  1325   onDataItemAdded: function DPV_onDataItemAdded(aDataItem, aNewest) {
  1326     this._addDownloadData(aDataItem, null, aNewest);
  1327   },
  1329   onDataItemRemoved: function DPV_onDataItemRemoved(aDataItem) {
  1330     this._removeSessionDownloadFromView(aDataItem);
  1331   },
  1333   getViewItem: function(aDataItem)
  1334     this._viewItemsForDataItems.get(aDataItem, null),
  1336   supportsCommand: function DPV_supportsCommand(aCommand) {
  1337     if (DOWNLOAD_VIEW_SUPPORTED_COMMANDS.indexOf(aCommand) != -1) {
  1338       // The clear-downloads command may be performed by the toolbar-button,
  1339       // which can be focused on OS X.  Thus enable this command even if the
  1340       // richlistbox is not focused.
  1341       // For other commands, be prudent and disable them unless the richlistview
  1342       // is focused. It's important to make the decision here rather than in
  1343       // isCommandEnabled.  Otherwise our controller may "steal" commands from
  1344       // other controls in the window (see goUpdateCommand &
  1345       // getControllerForCommand).
  1346       if (document.activeElement == this._richlistbox ||
  1347           aCommand == "downloadsCmd_clearDownloads") {
  1348         return true;
  1351     return false;
  1352   },
  1354   isCommandEnabled: function DPV_isCommandEnabled(aCommand) {
  1355     switch (aCommand) {
  1356       case "cmd_copy":
  1357         return this._richlistbox.selectedItems.length > 0;
  1358       case "cmd_selectAll":
  1359         return true;
  1360       case "cmd_paste":
  1361         return this._canDownloadClipboardURL();
  1362       case "downloadsCmd_clearDownloads":
  1363         return this._canClearDownloads();
  1364       default:
  1365         return Array.every(this._richlistbox.selectedItems, function(element) {
  1366           return element._shell.isCommandEnabled(aCommand);
  1367         });
  1369   },
  1371   _canClearDownloads: function DPV__canClearDownloads() {
  1372     // Downloads can be cleared if there's at least one removeable download in
  1373     // the list (either a history download or a completed session download).
  1374     // Because history downloads are always removable and are listed after the
  1375     // session downloads, check from bottom to top.
  1376     for (let elt = this._richlistbox.lastChild; elt; elt = elt.previousSibling) {
  1377       if (elt._shell.placesNode || !elt._shell.dataItem.inProgress)
  1378         return true;
  1380     return false;
  1381   },
  1383   _copySelectedDownloadsToClipboard:
  1384   function DPV__copySelectedDownloadsToClipboard() {
  1385     let selectedElements = this._richlistbox.selectedItems;
  1386     let urls = [e._shell.downloadURI for each (e in selectedElements)];
  1388     Cc["@mozilla.org/widget/clipboardhelper;1"].
  1389     getService(Ci.nsIClipboardHelper).copyString(urls.join("\n"), document);
  1390   },
  1392   _getURLFromClipboardData: function DPV__getURLFromClipboardData() {
  1393     let trans = Cc["@mozilla.org/widget/transferable;1"].
  1394                 createInstance(Ci.nsITransferable);
  1395     trans.init(null);
  1397     let flavors = ["text/x-moz-url", "text/unicode"];
  1398     flavors.forEach(trans.addDataFlavor);
  1400     Services.clipboard.getData(trans, Services.clipboard.kGlobalClipboard);
  1402     // Getting the data or creating the nsIURI might fail.
  1403     try {
  1404       let data = {};
  1405       trans.getAnyTransferData({}, data, {});
  1406       let [url, name] = data.value.QueryInterface(Ci.nsISupportsString)
  1407                             .data.split("\n");
  1408       if (url)
  1409         return [NetUtil.newURI(url, null, null).spec, name];
  1411     catch(ex) { }
  1413     return ["", ""];
  1414   },
  1416   _canDownloadClipboardURL: function DPV__canDownloadClipboardURL() {
  1417     let [url, name] = this._getURLFromClipboardData();
  1418     return url != "";
  1419   },
  1421   _downloadURLFromClipboard: function DPV__downloadURLFromClipboard() {
  1422     let [url, name] = this._getURLFromClipboardData();
  1423     let browserWin = RecentWindow.getMostRecentBrowserWindow();
  1424     let initiatingDoc = browserWin ? browserWin.document : document;
  1425     DownloadURL(url, name, initiatingDoc);
  1426   },
  1428   doCommand: function DPV_doCommand(aCommand) {
  1429     switch (aCommand) {
  1430       case "cmd_copy":
  1431         this._copySelectedDownloadsToClipboard();
  1432         break;
  1433       case "cmd_selectAll":
  1434         this._richlistbox.selectAll();
  1435         break;
  1436       case "cmd_paste":
  1437         this._downloadURLFromClipboard();
  1438         break;
  1439       case "downloadsCmd_clearDownloads":
  1440         this._downloadsData.removeFinished();
  1441         if (this.result) {
  1442           Cc["@mozilla.org/browser/download-history;1"]
  1443             .getService(Ci.nsIDownloadHistory)
  1444             .removeAllDownloads();
  1446         // There may be no selection or focus change as a result
  1447         // of these change, and we want the command updated immediately.
  1448         goUpdateCommand("downloadsCmd_clearDownloads");
  1449         break;
  1450       default: {
  1451         // Slicing the array to get a freezed list of selected items. Otherwise,
  1452         // the selectedItems array is live and doCommand may alter the selection
  1453         // while we are trying to do one particular action, like removing items
  1454         // from history.
  1455         let selectedElements = this._richlistbox.selectedItems.slice();
  1456         for (let element of selectedElements) {
  1457           element._shell.doCommand(aCommand);
  1461   },
  1463   onEvent: function() { },
  1465   onContextMenu: function DPV_onContextMenu(aEvent)
  1467     let element = this._richlistbox.selectedItem;
  1468     if (!element || !element._shell)
  1469       return false;
  1471     // Set the state attribute so that only the appropriate items are displayed.
  1472     let contextMenu = document.getElementById("downloadsContextMenu");
  1473     let state = element._shell.getDownloadMetaData().state;
  1474     if (state !== undefined)
  1475       contextMenu.setAttribute("state", state);
  1476     else
  1477       contextMenu.removeAttribute("state");
  1479     if (state == nsIDM.DOWNLOAD_DOWNLOADING) {
  1480       // The resumable property of a download may change at any time, so
  1481       // ensure we update the related command now.
  1482       goUpdateCommand("downloadsCmd_pauseResume");
  1484     return true;
  1485   },
  1487   onKeyPress: function DPV_onKeyPress(aEvent) {
  1488     let selectedElements = this._richlistbox.selectedItems;
  1489     if (aEvent.keyCode == KeyEvent.DOM_VK_RETURN) {
  1490       // In the content tree, opening bookmarks by pressing return is only
  1491       // supported when a single item is selected. To be consistent, do the
  1492       // same here.
  1493       if (selectedElements.length == 1) {
  1494         let element = selectedElements[0];
  1495         if (element._shell)
  1496           element._shell.doDefaultCommand();
  1499     else if (aEvent.charCode == " ".charCodeAt(0)) {
  1500       // Pausue/Resume every selected download
  1501       for (let element of selectedElements) {
  1502         if (element._shell.isCommandEnabled("downloadsCmd_pauseResume"))
  1503           element._shell.doCommand("downloadsCmd_pauseResume");
  1506   },
  1508   onDoubleClick: function DPV_onDoubleClick(aEvent) {
  1509     if (aEvent.button != 0)
  1510       return;
  1512     let selectedElements = this._richlistbox.selectedItems;
  1513     if (selectedElements.length != 1)
  1514       return;
  1516     let element = selectedElements[0];
  1517     if (element._shell)
  1518       element._shell.doDefaultCommand();
  1519   },
  1521   onScroll: function DPV_onScroll() {
  1522     this._ensureVisibleElementsAreActive();
  1523   },
  1525   onSelect: function DPV_onSelect() {
  1526     goUpdateDownloadCommands();
  1528     let selectedElements = this._richlistbox.selectedItems;
  1529     for (let elt of selectedElements) {
  1530       if (elt._shell)
  1531         elt._shell.onSelect();
  1533   },
  1535   onDragStart: function DPV_onDragStart(aEvent) {
  1536     // TODO Bug 831358: Support d&d for multiple selection.
  1537     // For now, we just drag the first element.
  1538     let selectedItem = this._richlistbox.selectedItem;
  1539     if (!selectedItem)
  1540       return;
  1542     let metaData = selectedItem._shell.getDownloadMetaData();
  1543     if (!("filePath" in metaData))
  1544       return;
  1545     let file = new FileUtils.File(metaData.filePath);
  1546     if (!file.exists())
  1547       return;
  1549     let dt = aEvent.dataTransfer;
  1550     dt.mozSetDataAt("application/x-moz-file", file, 0);
  1551     let url = Services.io.newFileURI(file).spec;
  1552     dt.setData("text/uri-list", url);
  1553     dt.setData("text/plain", url);
  1554     dt.effectAllowed = "copyMove";
  1555     dt.addElement(selectedItem);
  1556   },
  1558   onDragOver: function DPV_onDragOver(aEvent) {
  1559     let types = aEvent.dataTransfer.types;
  1560     if (types.contains("text/uri-list") ||
  1561         types.contains("text/x-moz-url") ||
  1562         types.contains("text/plain")) {
  1563       aEvent.preventDefault();
  1565   },
  1567   onDrop: function DPV_onDrop(aEvent) {
  1568     let dt = aEvent.dataTransfer;
  1569     // If dragged item is from our source, do not try to
  1570     // redownload already downloaded file.
  1571     if (dt.mozGetDataAt("application/x-moz-file", 0))
  1572       return;
  1574     let name = { };
  1575     let url = Services.droppedLinkHandler.dropLink(aEvent, name);
  1576     if (url) {
  1577       let browserWin = RecentWindow.getMostRecentBrowserWindow();
  1578       let initiatingDoc = browserWin ? browserWin.document : document;
  1579       DownloadURL(url, name.value, initiatingDoc);
  1582 };
  1584 for (let methodName of ["load", "applyFilter", "selectNode", "selectItems"]) {
  1585   DownloadsPlacesView.prototype[methodName] = function() {
  1586     throw new Error("|" + methodName + "| is not implemented by the downloads view.");
  1590 function goUpdateDownloadCommands() {
  1591   for (let command of DOWNLOAD_VIEW_SUPPORTED_COMMANDS) {
  1592     goUpdateCommand(command);

mercurial