summaryrefslogtreecommitdiffstats
path: root/comm/suite/components/downloads/content/downloadmanager.js
blob: d390e655dd8e96d0ff4773b92b34cfd3f36eefca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");

XPCOMUtils.defineLazyModuleGetters(this, {
  PluralForm: "resource://gre/modules/PluralForm.jsm",
  Downloads: "resource://gre/modules/Downloads.jsm",
  DownloadsCommon: "resource:///modules/DownloadsCommon.jsm",
  PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
  FileUtils: "resource://gre/modules/FileUtils.jsm",
});

var gDownloadTree;
var gDownloadTreeView;
var gDownloadList;
var gDownloadStatus;
var gDownloadListener;
var gSearchBox;

function dmStartup()
{
  Downloads.getList(Downloads.PUBLIC).then(dmAsyncStartup);
}

function dmAsyncStartup(aList)
{
  gDownloadList = aList;

  gDownloadTree = document.getElementById("downloadTree");
  gDownloadStatus = document.getElementById("statusbar-display");
  gSearchBox = document.getElementById("search-box");

  // Insert as first controller on the whole window
  window.controllers.insertControllerAt(0, dlTreeController);

  // We need to keep the view object around globally to access "local"
  // non-nsITreeView methods
  gDownloadTreeView = new DownloadTreeView();
  gDownloadTree.view = gDownloadTreeView;

  // The DownloadProgressListener (DownloadProgressListener.js) handles
  // progress notifications.
  gDownloadListener = new DownloadProgressListener();
  gDownloadList.addView(gDownloadListener);

  // correct keybinding command attributes which don't do our business yet
  var key = document.getElementById("key_delete");
  if (key.hasAttribute("command"))
    key.setAttribute("command", "cmd_stop");
  key = document.getElementById("key_delete2");
  if (key.hasAttribute("command"))
    key.setAttribute("command", "cmd_stop");

  gDownloadTree.focus();

  if (gDownloadTree.view.rowCount > 0)
    gDownloadTree.view.selection.select(0);
}

function dmShutdown()
{
  gDownloadList.removeView(gDownloadListener);
  window.controllers.removeController(dlTreeController);
}

function searchDownloads(aInput)
{
  gDownloadTreeView.searchView(aInput);
}

function sortDownloads(aEventTarget)
{
  var column = aEventTarget;
  var colID = column.id;
  var sortDirection = null;

  // If the target is a menuitem, handle it and forward to a column
  if (/^menu_SortBy/.test(colID)) {
    colID = colID.replace(/^menu_SortBy/, "");
    column = document.getElementById(colID);
    var sortedColumn = gDownloadTree.columns.getSortedColumn();
    if (sortedColumn && sortedColumn.id == colID)
      sortDirection = sortedColumn.element.getAttribute("sortDirection");
    else
      sortDirection = "ascending";
  }
  else if (colID == "menu_Unsorted") {
    // calling .sortView() with an "unsorted" colID returns us to original order
    colID = "unsorted";
    column = null;
    sortDirection = "ascending";
  }
  else if (colID == "menu_SortAscending" || colID == "menu_SortDescending") {
    sortDirection = colID.replace(/^menu_Sort/, "").toLowerCase();
    var sortedColumn = gDownloadTree.columns.getSortedColumn();
    if (sortedColumn) {
      colID = sortedColumn.id;
      column = sortedColumn.element;
    }
  }

  // Abort if this is still no column
  if (column && column.localName != "treecol")
    return;

  // Abort on cyler columns, we don't sort them
  if (column && column.getAttribute("cycler") == "true")
    return;

  if (!sortDirection) {
    // If not set above already, toggle the current direction
    sortDirection = column.getAttribute("sortDirection") == "ascending" ?
                    "descending" : "ascending";
  }

  // Clear attributes on all columns, we're setting them again after sorting
  for (let node = document.getElementById("Name"); node; node = node.nextSibling) {
    node.removeAttribute("sortActive");
    node.removeAttribute("sortDirection");
  }

  // Actually sort the tree view
  gDownloadTreeView.sortView(colID, sortDirection);

  if (column) {
    // Set attributes to the sorting we did
    column.setAttribute("sortActive", "true");
    column.setAttribute("sortDirection", sortDirection);
  }
}

async function removeDownload(aDownload)
{
  // Remove the associated history element first, if any, so that the views
  // that combine history and session downloads won't resurrect the history
  // download into the view just before it is deleted permanently.
  try {
    await PlacesUtils.history.remove(aDownload.source.url);
  } catch (ex) {
    Cu.reportError(ex);
  }
  let list = await Downloads.getList(Downloads.ALL);
  await list.remove(aDownload);
  await aDownload.finalize(true);
}

function cancelDownload(aDownload)
{
  // This is the correct way to avoid race conditions when cancelling.
  aDownload.cancel().catch(() => {});
  aDownload.removePartialData().catch(Cu.reportError);
}

function openDownload(aDownload)
{
  let file = new FileUtils.File(aDownload.target.path);
  DownloadsCommon.openDownloadedFile(file, null, window);
}

function showDownload(aDownload)
{
  let file;

  if (aDownload.succeeded &&
      aDownload.target.exists) {
    file = new FileUtils.File(aDownload.target.path);
  } else {
    file = new FileUtils.File(aDownload.target.partFilePath);
  }
  DownloadsCommon.showDownloadedFile(file);
}

function showProperties(aDownload)
{
  openDialog("chrome://communicator/content/downloads/progressDialog.xul",
             null, "chrome,titlebar,centerscreen,minimizable=yes,dialog=no",
             { wrappedJSObject: aDownload }, true);
}

function onTreeSelect(aEvent)
{
  var selectionCount = gDownloadTreeView.selection.count;
  if (selectionCount == 1) {
    var selItemData = gDownloadTreeView.getRowData(gDownloadTree.currentIndex);
    gDownloadStatus.label = selItemData.target.path;
  } else {
    gDownloadStatus.label = "";
  }

  window.updateCommands("tree-select");
}

function onUpdateViewColumns(aMenuItem)
{
  while (aMenuItem) {
    // Each menuitem should be checked if its column is not hidden.
    var colID = aMenuItem.id.replace(/^menu_Toggle/, "");
    var column = document.getElementById(colID);
    aMenuItem.setAttribute("checked", !column.hidden);
    aMenuItem = aMenuItem.nextSibling;
  }
}

function toggleColumn(aMenuItem)
{
  var colID = aMenuItem.id.replace(/^menu_Toggle/, "");
  var column = document.getElementById(colID);
  column.setAttribute("hidden", !column.hidden);
}

function onUpdateViewSort(aMenuItem)
{
  var unsorted = true;
  var ascending = true;
  while (aMenuItem) {
    switch (aMenuItem.id) {
      case "": // separator
        break;
      case "menu_Unsorted":
        if (unsorted) // this would work even if Unsorted was last
          aMenuItem.setAttribute("checked", "true");
        break;
      case "menu_SortAscending":
        aMenuItem.setAttribute("disabled", unsorted);
        if (!unsorted && ascending)
          aMenuItem.setAttribute("checked", "true");
        break;
      case "menu_SortDescending":
        aMenuItem.setAttribute("disabled", unsorted);
        if (!unsorted && !ascending)
          aMenuItem.setAttribute("checked", "true");
        break;
      default:
        var colID = aMenuItem.id.replace(/^menu_SortBy/, "");
        var column = document.getElementById(colID);
        var direction = column.getAttribute("sortDirection");
        if (column.getAttribute("sortActive") == "true" && direction) {
          // We've found a sorted column. Remember its direction.
          ascending = direction == "ascending";
          unsorted = false;
          aMenuItem.setAttribute("checked", "true");
        }
    }
    aMenuItem = aMenuItem.nextSibling;
  }
}

// This is called by the progress listener.
var gLastComputedMean = -1;
var gLastActiveDownloads = 0;
function onUpdateProgress()
{
  var dls = gDownloadTreeView.getActiveDownloads();
  var numActiveDownloads = dls.length;

  // Use the default title and reset "last" values if there's no downloads
  if (numActiveDownloads == 0) {
    document.title = document.documentElement.getAttribute("statictitle");
    gLastComputedMean = -1;
    gLastActiveDownloads = 0;

    return;
  }

  // Establish the mean transfer speed and amount downloaded.
  var mean = 0;
  var base = 0;
  for (var dl of dls) {
    if (dl.totalBytes > 0) {
      mean += dl.currentBytes;
      base += dl.totalBytes;
    }
  }

  // Calculate the percent transferred, unless we don't have a total file size
  var dlbundle = document.getElementById("dmBundle");
  if (base != 0)
    mean = Math.floor((mean / base) * 100);

  // Update title of window
  if (mean != gLastComputedMean || gLastActiveDownloads != numActiveDownloads) {
    gLastComputedMean = mean;
    gLastActiveDownloads = numActiveDownloads;

    var title;
    if (base == 0)
      title = dlbundle.getFormattedString("downloadsTitleFiles",
                                          [numActiveDownloads]);
    else
      title = dlbundle.getFormattedString("downloadsTitlePercent",
                                          [numActiveDownloads, mean]);

    // Get the correct plural form and insert number of downloads and percent
    title = PluralForm.get(numActiveDownloads, title);

    document.title = title;
  }
}

function handlePaste() {
  let trans = Cc["@mozilla.org/widget/transferable;1"]
                .createInstance(Ci.nsITransferable);
  trans.init(null);

  let flavors = ["text/x-moz-url", "text/unicode"];
  flavors.forEach(trans.addDataFlavor);

  Services.clipboard.getData(trans, Services.clipboard.kGlobalClipboard);

  // Getting the data or creating the nsIURI might fail
  try {
    let data = {};
    trans.getAnyTransferData({}, data, {});
    let [url, name] = data.value.QueryInterface(Ci
                                .nsISupportsString).data.split("\n");

    if (!url)
      return;

    DownloadURL(url, name || url, document);
  } catch (ex) {}
}

var dlTreeController = {
  supportsCommand: function(aCommand)
  {
    switch (aCommand) {
      case "cmd_play":
      case "cmd_pause":
      case "cmd_resume":
      case "cmd_retry":
      case "cmd_cancel":
      case "cmd_remove":
      case "cmd_stop":
      case "cmd_open":
      case "cmd_show":
      case "cmd_openReferrer":
      case "cmd_copyLocation":
      case "cmd_properties":
      case "cmd_paste":
      case "cmd_selectAll":
      case "cmd_clearList":
        return true;
    }
    return false;
  },

  isCommandEnabled: function(aCommand)
  {
    var selectionCount = 0;
    if (gDownloadTreeView && gDownloadTreeView.selection)
      selectionCount = gDownloadTreeView.selection.count;

    var selItemData = [];
    if (selectionCount) {
      // walk all selected rows
      let start = {};
      let end = {};
      let numRanges = gDownloadTreeView.selection.getRangeCount();
      for (let rg = 0; rg < numRanges; rg++) {
        gDownloadTreeView.selection.getRangeAt(rg, start, end);
        for (let row = start.value; row <= end.value; row++)
          selItemData.push(gDownloadTreeView.getRowData(row));
      }
    }

    switch (aCommand) {
      case "cmd_play":
        if (!selectionCount)
          return false;
        for (let dldata of selItemData) {
          if (dldata.succeeded || (!dldata.stopped && !dldata.hasPartialData))
            return false;
        }
        return true;
      case "cmd_pause":
        if (!selectionCount)
          return false;
        for (let dldata of selItemData) {
          if (dldata.stopped || !dldata.hasPartialData)
            return false;
        }
        return true;
      case "cmd_resume":
        if (!selectionCount)
          return false;
        for (let dldata of selItemData) {
          if (!dldata.stopped || !dldata.hasPartialData)
            return false;
        }
        return true;
      case "cmd_open":
        return selectionCount == 1 &&
               selItemData[0].succeeded &&
               selItemData[0].target.exists;
      case "cmd_show":
        // target.exists is only set if the download finished and the target
        // is still located there.
        // For simplicity we just assume the target is there if the download
        // has not succeeded e.g. is still in progress. This might be wrong
        // but showDownload will deal with it.
        return selectionCount == 1 &&
               ((selItemData[0].succeeded &&
                 selItemData[0].target.exists) ||
                 !selItemData[0].succeeded);
      case "cmd_cancel":
        if (!selectionCount)
          return false;
        for (let dldata of selItemData) {
          if (dldata.stopped && !dldata.hasPartialData)
            return false;
        }
        return true;
      case "cmd_retry":
        if (!selectionCount)
          return false;
        for (let dldata of selItemData) {
          if (dldata.succeeded || !dldata.stopped || dldata.hasPartialData)
            return false;
        }
        return true;
      case "cmd_remove":
        if (!selectionCount)
          return false;
        for (let dldata of selItemData) {
          if (!dldata.stopped)
            return false;
        }
        return true;
      case "cmd_openReferrer":
        return selectionCount == 1 && !!selItemData[0].source.referrer;
      case "cmd_stop":
      case "cmd_copyLocation":
        return selectionCount > 0;
      case "cmd_properties":
        return selectionCount == 1;
      case "cmd_selectAll":
        return gDownloadTreeView.rowCount != selectionCount;
      case "cmd_clearList":
        // Since active downloads always sort before removable downloads,
        // we only need to check that the last download has stopped.
        return gDownloadTreeView.rowCount &&
               !gDownloadTreeView.getRowData(gDownloadTreeView.rowCount - 1).isActive;
      case "cmd_paste":
        return true;
      default:
        return false;
    }
  },

  doCommand: function(aCommand) {
    var selectionCount = 0;
    if (gDownloadTreeView && gDownloadTreeView.selection)
      selectionCount = gDownloadTreeView.selection.count;

    var selItemData = [];
    if (selectionCount) {
      // walk all selected rows
      let start = {};
      let end = {};
      let numRanges = gDownloadTreeView.selection.getRangeCount();
      for (let rg = 0; rg < numRanges; rg++) {
        gDownloadTreeView.selection.getRangeAt(rg, start, end);
        for (let row = start.value; row <= end.value; row++)
          selItemData.push(gDownloadTreeView.getRowData(row));
      }
    }

    switch (aCommand) {
      case "cmd_play":
        for (let dldata of selItemData) {
          if (!dldata.stopped)
            dldata.cancel();
          else if (!dldata.succeeded)
            dldata.start();
        }
        break;
      case "cmd_pause":
        for (let dldata of selItemData)
          dldata.cancel();
        break;
      case "cmd_resume":
      case "cmd_retry":
        for (let dldata of selItemData) {
         // Errors when retrying are already reported as download failures.
         dldata.start();
        }
        break;
      case "cmd_cancel":
        for (let dldata of selItemData)
          cancelDownload(dldata);
        break;
      case "cmd_remove":
        for (let dldata of selItemData)
          removeDownload(dldata).catch(Cu.reportError);
        break;
      case "cmd_stop":
        for (let dldata of selItemData) {
          if (dldata.isActive)
            cancelDownload(dldata);
          else
            gDownloadList.remove(dldata);
        }
        break;
      case "cmd_open":
        openDownload(selItemData[0]);
        break;
      case "cmd_show":
        showDownload(selItemData[0]);
        break;
      case "cmd_openReferrer":
        openUILink(selItemData[0].source.referrer);
        break;
      case "cmd_copyLocation":
        var clipboard = Cc["@mozilla.org/widget/clipboardhelper;1"]
                          .getService(Ci.nsIClipboardHelper);
        var uris = [];
        for (let dldata of selItemData)
          uris.push(dldata.source.url);
          clipboard.copyString(uris.join("\n"), document);
        break;
      case "cmd_properties":
        showProperties(selItemData[0]);
        break;
      case "cmd_selectAll":
        gDownloadTreeView.selection.selectAll();
        break;
      case "cmd_clearList":
        // Remove each download starting from the end until we hit a download
        // that is in progress
        for (let idx = gDownloadTreeView.rowCount - 1; idx >= 0; idx--) {
          let dldata = gDownloadTreeView.getRowData(idx);
          if (!dldata.isActive) {
            gDownloadList.remove(dldata);
          }
        }

        if (!gSearchBox.value)
          break;

        // Clear the input as if the user did it and move focus to the list
        gSearchBox.value = "";
        searchDownloads("");
        gDownloadTree.focus();
        break;
      case "cmd_paste":
        handlePaste();
        break;
    }
  },

  onEvent: function(aEvent){
    switch (aEvent) {
    case "tree-select":
      this.onCommandUpdate();
    }
  },

  onCommandUpdate: function() {
    var cmds = ["cmd_play", "cmd_pause", "cmd_resume", "cmd_retry",
                "cmd_cancel", "cmd_remove", "cmd_stop", "cmd_open", "cmd_show",
                "cmd_openReferrer", "cmd_copyLocation", "cmd_properties",
                "cmd_selectAll", "cmd_clearList"];
    for (let command in cmds)
      goUpdateCommand(cmds[command]);
  }
};

var gDownloadDNDObserver = {
  onDragStart: function (aEvent)
  {
    if (!gDownloadTreeView ||
        !gDownloadTreeView.selection ||
        !gDownloadTreeView.selection.count)
      return;

    var selItemData = gDownloadTreeView.getRowData(gDownloadTree.currentIndex);
    var file = new FileUtils.File(selItemData.target.path);

    if (!file.exists())
      return;

    var url = Services.io.newFileURI(file).spec;
    var dt = aEvent.dataTransfer;
    dt.mozSetDataAt("application/x-moz-file", file, 0);
    dt.setData("text/uri-list", url + "\r\n");
    dt.setData("text/plain", url + "\n");
    dt.effectAllowed = "copyMove";
    if (gDownloadTreeView.selection.count == 1)
      dt.setDragImage(gDownloadStatus, 16, 16);
  },

  onDragOver: function (aEvent)
  {
    if (disallowDrop(aEvent))
      return;

    var types = aEvent.dataTransfer.types;
    if (types.includes("text/uri-list") ||
        types.includes("text/x-moz-url") ||
        types.includes("text/plain"))
      aEvent.preventDefault();
    aEvent.stopPropagation();
  },

  onDrop: function(aEvent)
  {
    if (disallowDrop(aEvent))
      return;

    var dt = aEvent.dataTransfer;
    var url = dt.getData("URL");
    var name;
    if (!url) {
      url = dt.getData("text/x-moz-url") || dt.getData("text/plain");
      [url, name] = url.split("\n");
    }
    if (url) {
      let doc = dt.mozSourceNode ? dt.mozSourceNode.ownerDocument : document;
      saveURL(url, name || url, null, true, true, null, doc);
    }
  }
};

function disallowDrop(aEvent)
{
  var dt = aEvent.dataTransfer;
  var file = dt.mozGetDataAt("application/x-moz-file", 0);
  // If this is a local file, Don't try to download it again.
  return file && file instanceof Ci.nsIFile;
}