summaryrefslogtreecommitdiffstats
path: root/browser/components/downloads/DownloadsMacFinderProgress.sys.mjs
blob: 64e1dc4b8d3442514d721a4ab29f53ebf04e8ae4 (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
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80 filetype=javascript: */
/* 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/. */

/**
 * Handles the download progress indicator of the macOS Finder.
 */

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  Downloads: "resource://gre/modules/Downloads.sys.mjs",
});

export var DownloadsMacFinderProgress = {
  /**
   * Maps the path of the download, to the according progress indicator instance.
   */
  _finderProgresses: null,

  /**
   * This method is called after a new browser window on macOS is opened, it
   * registers for receiving download events for the progressbar of the Finder.
   */
  register() {
    // Ensure to register only once per process and not for every window.
    if (!this._finderProgresses) {
      this._finderProgresses = new Map();
      lazy.Downloads.getList(lazy.Downloads.ALL).then(list =>
        list.addView(this)
      );
    }
  },

  onDownloadAdded(download) {
    if (download.stopped) {
      return;
    }

    let finderProgress = Cc[
      "@mozilla.org/widget/macfinderprogress;1"
    ].createInstance(Ci.nsIMacFinderProgress);

    let path = download.target.path;

    finderProgress.init(path, () => {
      download.cancel().catch(console.error);
      download.removePartialData().catch(console.error);
    });

    if (download.hasProgress) {
      finderProgress.updateProgress(download.currentBytes, download.totalBytes);
    } else {
      finderProgress.updateProgress(0, 0);
    }
    this._finderProgresses.set(path, finderProgress);
  },

  onDownloadChanged(download) {
    let path = download.target.path;
    let finderProgress = this._finderProgresses.get(path);
    if (!finderProgress) {
      // The download is not tracked, it may have been restarted,
      // thus forward the call to onDownloadAdded to check if it should be tracked.
      this.onDownloadAdded(download);
    } else if (download.stopped) {
      finderProgress.end();
      this._finderProgresses.delete(path);
    } else {
      finderProgress.updateProgress(download.currentBytes, download.totalBytes);
    }
  },

  onDownloadRemoved(download) {
    let path = download.target.path;
    let finderProgress = this._finderProgresses.get(path);
    if (finderProgress) {
      finderProgress.end();
      this._finderProgresses.delete(path);
    }
  },
};