summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/active_downloads.js
blob: 590d6396b23c7101022a76592df3425a3239ef7f (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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Wrapper for chrome.send.
 */
function chromeSend(func, arg) {
  if (arg == undefined)
    arg = '';

  // Convert to string.
  if (typeof arg == 'number')
    arg = '' + arg;

  chrome.send(func, [arg]);
};

/**
 * Create a child element.
 *
 * @param {string} type The type - div, span, etc.
 * @param {string} className The class name
 * @param {HTMLElement} parent Parent to append this child to.
 * @param {string} textContent optional text content of child.
 * @param {function(*)} onclick onclick function of child.
 */
function createChild(type, className, parent, textContent, onclick) {
  var elem = document.createElement(type);
  elem.className = className;
  if (textContent !== undefined)
    elem.textContent = textContent;
  elem.onclick = onclick;
  parent.appendChild(elem);
  return elem;
};

var localStrings;
var downloadRowList;

function init() {
  localStrings = new LocalStrings();
  initTestHarness();

  window.onkeydown = function(e) {
    if (e.keyCode == 27)  // Escape.
      menu.clear();
    e.preventDefault();  // Suppress browser shortcuts.
  };

  document.body.addEventListener("blur", menu.clear);
  document.body.addEventListener("click", menu.clear);
  document.body.addEventListener("contextmenu", function (e) {
      e.preventDefault(); });
  document.body.addEventListener("selectstart", function (e) {
      e.preventDefault(); });

  var sadt = $('showallfilestext');
  sadt.textContent = localStrings.getString('showallfiles');
  sadt.addEventListener("click", showAllFiles);

  downloadRowList = new DownloadRowList();
  chromeSend('getDownloads');
}

/**
 * Testing. Allow this page to be loaded in a browser.
 * Create stubs for localStrings and chrome.send.
 */
function initTestHarness() {
  if (location.protocol != 'file:')
    return;

  // Enable right click for dom inspector.
  document.body.oncontextmenu = '';

  // Fix localStrings.
  localStrings = {
    getString: function(name) {
      if (name == 'showallfiles')
        return 'Show all files';
      if (name == 'dangerousextension')
        return 'Extensions, apps, and themes can harm your computer.' +
            ' Are you sure you want to continue?'
      if (name == 'continue')
        return 'Continue';
      if (name == 'discard')
        return 'Discard';
      return name;
    },
    getStringF: function(name, path) {
      return path + ' - Unknown file type.';
    },
  };

  // Log chrome.send calls.
  chrome.send = function(name, ary) {
    console.log('chrome.send ' + name + ' ' + ary);
    if (name == 'getDownloads' ||
        (name == 'openNewFullWindow' &&
        ary[0] == 'chrome://downloads'))
      sendTestResults();
  };

  // Fix resource images.
  var cssRules = document.styleSheets[0].cssRules;
  for (var i = 0; i < cssRules.length; i++) {
    var cssRule = cssRules[i];
    if (cssRule.selectorText.match(/^div\.icon|^\.menuicon/)) {
      cssRule.style.backgroundImage =
          cssRule.style.backgroundImage.replace('chrome://resources', 'shared');
    }
  }
}

/**
 * Create a results array with test data and call downloadsList.
 */
var testElement;
var testId = 0;
var testResults = [];
function sendTestResults() {
  var testState = (testId % 3 == 0 ? 'IN_PROGRESS' :
      (testId % 3 == 1 ? 'DANGEROUS' : 'COMPLETE'));
  state1 = (testId % 3 == 0);
  testResults.push({
      state: testState,
      percent: (testId % 3 == 0 ? 90 : 100),
      id: testId,
      file_name: ' Test' + testId + '.pdf',
      file_path: '/home/achuith/Downloads/Test' + testId + '.pdf',
      progress_status_text : '107 MB/s - 108 MB of 672 MB, 5 secs left',
    });
  testId++;
  downloadsList(testResults);
}

/**
 * Current Menu.
 */
var menu = {
  current_: null,

  /**
   * Close the current menu.
   */
  clear: function() {
    var current = this.current_;
    if (current) {
      current.firstChild.style.display = 'none';
      current.style.opacity = '';
      this.current_ = null;
    }
  },

  /**
   * If it's a second click on an open menu, close the menu.
   * Otherwise, close any other open menu and open the clicked menu.
   */
  clicked: function(row) {
    var menuicon = row.menuicon;
    if (this.current_ === menuicon) {
      this.clear();
      return;
    }
    this.clear();
    if (menuicon.firstChild.style.display != 'block') {
      menuicon.firstChild.style.display = 'block';
      menuicon.style.opacity = '1';
      menuicon.scrollIntoView();
      this.current_ = menuicon;
    }
    window.event.stopPropagation();
  },
};

function DiscardResult(result) {
    return (result.state == 'CANCELLED' ||
            result.state == 'INTERRUPTED' ||
            result.state == 'REMOVING');
};

/**
 * C++ api calls.
 */
function downloadsList(results) {
  downloadRowList.list(results);
}

function downloadUpdated(result) {
  downloadRowList.update(result);
}

function showAllFiles() {
  chromeSend('showAllFiles');
}

/**
 * DownloadRow contains all the elements that go into a row of the downloads
 * list. It represents a single DownloadItem.
 *
 * @param {DownloadRowList} list Global DownloadRowList.
 * @param {Object} result JSON representation of DownloadItem.
 * @constructor
 */
function DownloadRow(list, result) {
  this.path = result.file_path;
  this.name = result.file_name;
  this.fileUrl = result.file_url;
  this.list = list;
  this.id = result.id;

  this.createRow_(list);
  this.createMenu_();
  this.createRowButton_();
  this.setMenuHidden_(true);
}

DownloadRow.prototype = {
  /**
   * Create the row html element and book-keeping for the row.
   * @param {DownloadRowList} list global DownloadRowList instance.
   * @private
   */
  createRow_: function(list) {
    var elem = document.createElement('li');
    elem.className = 'downloadrow';
    elem.id = this.path;
    elem.row = this;
    this.element = elem;

    list.append(this);
  },

  setErrorText_: function(text) {
    this.filename.textContent = text;
  },

  supportsPdf_: function() {
    return 'application/pdf' in navigator.mimeTypes;
  },

  openFilePath_: function() {
    chromeSend('openNewFullWindow', this.fileUrl);
  },

  /**
   * Determine onclick behavior based on filename.
   * @private
   */
  getFunctionForItem_: function() {
    var path = this.path;
    var self = this;

    if (pathIsAudioFile(path)) {
      return function() {
        chromeSend('playMediaFile', path);
      };
    }
    if (pathIsVideoFile(path)) {
      return function() {
        chromeSend('playMediaFile', path);
      };
    }
    if (pathIsImageFile(path)) {
      return function() {
        self.openFilePath_();
      }
    }
    if (pathIsHtmlFile(path)) {
      return function() {
        self.openFilePath_();
      }
    }
    if (pathIsPdfFile(path) && this.supportsPdf_()) {
      return function() {
        self.openFilePath_();
      }
    }

    return function() {
      self.setErrorText_(localStrings.getStringF('error_unknown_file_type',
                          self.name));
    };
  },

  setDangerousIcon_: function(warning) {
    this.icon.className = warning ? 'iconwarning' : 'icon';
    this.icon.style.background = warning ? '' :
        'url(chrome://fileicon' + escape(this.path) +
        '?iconsize=small) no-repeat';
  },

  /**
   * Create the row button for the left of the row.
   * This contains the icon, filename and error elements.
   * @private
   */
  createRowButton_: function () {
    this.rowbutton = createChild('div', 'rowbutton rowbg', this.element);

    // Icon.
    this.icon = createChild('div', 'icon', this.rowbutton);
    this.setDangerousIcon_(false);

    // Filename.
    this.filename = createChild('span', 'title', this.rowbutton, this.name);
  },

  setMenuHidden_: function(hidden) {
    this.menubutton.hidden = hidden;
    if (hidden) {
      this.rowbutton.style.width = '238px';
    } else {
      this.rowbutton.style.width = '';
    }
  },

  /**
   * Create the menu button on the right of the row.
   * This contains the menuicon. The menuicon contains the menu, which
   * contains items for Pause/Resume and Cancel.
   * @private
   */
  createMenu_: function() {
    var self = this;
    this.menubutton = createChild('div', 'menubutton rowbg', this.element, '',
                                  function() {
                                    menu.clicked(self);
                                  });

    this.menuicon = createChild('div', 'menuicon', this.menubutton);

    var menudiv = createChild('div', 'menu', this.menuicon);

    this.pause = createChild('div', 'menuitem', menudiv,
      localStrings.getString('pause'), function() {
                                         self.pauseToggleDownload_();
                                       });

    this.cancel = createChild('div', 'menuitem', menudiv,
      localStrings.getString('cancel'), function() {
                                          self.cancelDownload_();
                                        });
  },

  allowDownload_: function() {
    chromeSend('allowDownload', this.id);
  },

  cancelDownload_: function() {
    chromeSend('cancelDownload', this.id);
  },

  pauseToggleDownload_: function() {
    this.pause.textContent =
      (this.pause.textContent == localStrings.getString('pause')) ?
      localStrings.getString('resume') :
      localStrings.getString('pause');

    chromeSend('pauseToggleDownload', this.id);
  },

  changeElemHeight_: function(elem, x) {
    elem.style.height = elem.clientHeight + x + 'px';
  },

  changeRowHeight_: function(x) {
    this.list.rowsHeight += x;
    this.changeElemHeight_(this.element, x);
    // rowbutton has 5px padding.
    this.changeElemHeight_(this.rowbutton, x - 5);
    this.list.resize();
  },

  DANGEROUS_HEIGHT: 60,
  createDangerousPrompt_: function(dangerType) {
    if (this.dangerous)
      return;

    this.dangerous = createChild('div', 'dangerousprompt', this.rowbutton);

    // Handle dangerous files, extensions and dangerous urls.
    var dangerText;
    if (dangerType == 'DANGEROUS_URL' || dangerType == 'DANGEROUS_CONTENT') {
      dangerText = localStrings.getString('dangerousurl');
    } else if (dangerType == 'DANGEROUS_FILE' && this.path.match(/\.crx$/)) {
      dangerText = localStrings.getString('dangerousextension');
    } else {
      dangerText = localStrings.getStringF('dangerousfile', this.name);
    }
    createChild('span', 'dangerousprompttext', this.dangerous, dangerText);

    var self = this;
    createChild('span', 'confirm', this.dangerous,
        localStrings.getString('discard'),
        function() {
          self.cancelDownload_();
        });
    createChild('span', 'confirm', this.dangerous,
        localStrings.getString('continue'),
        function() {
          self.allowDownload_();
        });

    this.changeRowHeight_(this.DANGEROUS_HEIGHT);
    this.setDangerousIcon_(true);
  },

  removeDangerousPrompt_: function() {
    if (!this.dangerous)
      return;

    this.rowbutton.removeChild(this.dangerous);
    this.dangerous = null;

    this.changeRowHeight_(-this.DANGEROUS_HEIGHT);
    this.setDangerousIcon_(false);
  },

  PROGRESS_HEIGHT: 8,
  createProgress_: function() {
    if (this.progress)
      return;

    this.progress = createChild('div', 'progress', this.rowbutton);

    this.setMenuHidden_(false);
    this.changeRowHeight_(this.PROGRESS_HEIGHT);
  },

  removeProgress_: function() {
    if (!this.progress)
      return;

    this.rowbutton.removeChild(this.progress);
    this.progress = null;

    this.changeRowHeight_(-this.PROGRESS_HEIGHT);
    this.setMenuHidden_(true);
  },

  updatePause_: function(result) {
    var pause = this.pause;
    var pauseStr = localStrings.getString('pause');
    var resumeStr = localStrings.getString('resume');

    if (pause &&
        result.state == 'PAUSED' &&
        pause.textContent != resumeStr) {
      pause.textContent = resumeStr;
    } else if (pause &&
              result.state == 'IN_PROGRESS' &&
              pause.textContent != pauseStr) {
      pause.textContent = pauseStr;
    }
  },

  progressStatusText_: function(progress) {
    if (!progress)
      return progress;

    /* m looks like this:
    ["107 MB/s - 108 MB of 672 MB, 5 secs left",
    "107 MB/s", "108", "MB", "672", "MB", "5 secs left"]
    We want to return progress text like this:
    "108 / 672 MB, 5 secs left"
    or
    "108 kB / 672 MB, 5 secs left"
    */
    var m = progress.match(
      /([^-]*) - ([0-9\.]*) ([a-zA-Z]*) of ([0-9\.]*) ([a-zA-Z]*), (.*)/);
    if (!m || m.length != 7)
      return progress;

    return m[2] + (m[3] == m[5] ? '' : ' ' + m[3]) +
        ' / ' + m[4] + ' ' + m[5] + ', ' + m[6];
  },

  updateProgress_: function(result) {
    this.removeDangerousPrompt_();
    this.createProgress_();
    this.progress.textContent =
        this.progressStatusText_(result.progress_status_text);
    this.updatePause_(result);
  },

  /**
   * Called when the item has finished downloading. Switch the menu
   * and remove the progress bar.
   * @private
   */
  finishedDownloading_: function() {
    // Make rowbutton clickable.
    this.rowbutton.onclick = this.getFunctionForItem_();
    this.rowbutton.style.cursor = 'pointer';

    // Make rowbutton draggable.
    this.rowbutton.setAttribute('draggable', 'true');
    var self = this;
    this.rowbutton.addEventListener('dragstart', function(e) {
      e.dataTransfer.effectAllowed = 'copy';
      e.dataTransfer.setData('Text', self.path);
      e.dataTransfer.setData('URL', self.fileUrl);
    }, false);

    this.removeDangerousPrompt_();
    this.removeProgress_();
  },

  /**
   * One of the DownloadItem we are observing has updated.
   * @param {Object} result JSON representation of DownloadItem.
   */
  update: function(result) {
    this.filename.textContent = result.file_name;
    this.id = result.id;

    if (result.state != 'COMPLETE') {
      this.rowbutton.onclick = '';
      this.rowbutton.style.cursor = '';
    }

    if (DiscardResult(result)) {
      this.list.remove(this);
    } else if (result.state == 'DANGEROUS') {
      this.createDangerousPrompt_(result.danger_type);
    } else if (result.percent < 100) {
      this.updateProgress_(result);
    } else if (result.state == 'COMPLETE') {
      this.finishedDownloading_();
    }
  },
};

/**
 * DownloadRowList is a container for DownloadRows.
 */
function DownloadRowList() {
  this.element = createChild('ul', 'downloadlist', $('main'));

  document.title = localStrings.getString('downloadpath').
      split('/').pop();
}

DownloadRowList.prototype = {

  /**
   * numRows is the current number of rows.
   * rowsHeight is the sum of the heights of all rows.
   * rowListHeight is the height of the container containing the rows.
   * rows is the list of DownloadRows.
   */
  numRows: 0,
  rowsHeight: 0,
  rowListHeight: 72,
  rows: [],

  /**
   * Resize the panel to accomodate all rows.
   */
  resize: function() {
    var diff = this.rowsHeight - this.rowListHeight;
    if (diff != 0 && (this.rowListHeight + diff > 72)) {
      window.resizeBy(0, diff);
      this.rowListHeight += diff;
    }
  },

  /**
   * Remove a row from the list, as when a download is canceled, or
   * the the number of rows has exceeded the max allowed.
   *
   * @param {DownloadRow} row Row to be removed.
   * @private
   */
  remove: function(row) {
    this.rows.splice(this.rows.indexOf(row), 1);

    this.numRows--;
    this.rowsHeight -= row.element.offsetHeight;
    this.resize();

    this.element.removeChild(row.element);
    row.element.row = null;
  },

  removeList: function(rows) {
    for (i = 0; i < rows.length; i++) {
      this.remove(rows[i]);
    }
  },

  updateList: function(results) {
    for (var i = 0; i < results.length; i++) {
      this.update(results[i]);
    }
  },

  /**
   * Append a new row to the list, removing the last row if we exceed the
   * maximum allowed.
   * @param {DownloadRow} row Row to be removed.
   */
  append: function(row) {
    this.rows.push(row);

    var elem = row.element;
    var list = this.element;
    if (list.firstChild) {
      list.insertBefore(elem, list.firstChild);
    } else {
      list.appendChild(elem);
    }

    this.rowsHeight += elem.offsetHeight;

    this.numRows++;
    // We display no more than 5 elements.
    if (this.numRows > 5)
      this.remove(list.lastChild.row);

    this.resize();
  },

  getRow: function(path) {
    for (var i = 0; i < this.rows.length; i++) {
      if (this.rows[i].path == path)
        return this.rows[i];
    }
  },

  /**
   * Returns the list of rows that are not in the results array.
   * @param {Array} results Array of JSONified DownloadItems.
   */
  findMissing: function(results) {
    var removeList = [];

    for (var i = 0; i < this.rows.length; i++) {
      var row = this.rows[i];
      var found = false;
      for (var j = 0; j < results.length; j++) {
        if (row.path == results[j].file_path) {
          found = true;
          break;
        }
      }
      if (!found)
        removeList.push(row);
    }
    return removeList;
  },

  /**
   * Handle list callback with list of DownloadItems.
   * @param {Array} results Array of JSONified DownloadItems.
   */
  list: function(results) {
    var rows = this.findMissing(results);
    this.updateList(results);
    this.removeList(rows);
  },

  /**
   * Handle update of a DownloadItem we're observing.
   * @param {Object} result JSON representation of DownloadItem.
   */
  update: function(result) {
    var row = this.getRow(result.file_path);
    if (!row && !DiscardResult(result))
      row = new DownloadRow(this, result);

    row && row.update(result);
  },
};

document.addEventListener('DOMContentLoaded', init);