summaryrefslogtreecommitdiffstats
path: root/toolkit/modules/ClipboardContextMenu.sys.mjs
blob: d66a2f466d5badb6956d6c7cff83d04e5634d60d (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
/* 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/. */

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

export var ClipboardContextMenu = {
  MENU_POPUP_ID: "clipboardReadPasteMenuPopup",

  // EventListener interface.
  handleEvent(aEvent) {
    switch (aEvent.type) {
      case "command": {
        this.onCommand();
        break;
      }
      case "popuphiding": {
        this.onPopupHiding();
        break;
      }
      case "keydown": {
        this.onKeyDown(aEvent);
        break;
      }
    }
  },

  _pasteMenuItemClicked: false,

  onCommand() {
    // onPopupHiding is responsible for returning result by calling onComplete
    // function.
    this._pasteMenuItemClicked = true;
  },

  onPopupHiding() {
    // Remove the listeners before potentially sending the async message
    // below, because that might throw.
    this._removeMenupopupEventListeners();
    this._clearDelayTimer();
    this._stopWatchingForSpammyActivation();

    this._menupopup = null;
    this._menuitem = null;

    let propBag = lazy.PromptUtils.objectToPropBag({
      ok: this._pasteMenuItemClicked,
    });
    this._pendingRequest.resolve(propBag);

    // A result has already been responded to. Reset the state to properly
    // handle further click or dismiss events.
    this._pasteMenuItemClicked = false;
    this._pendingRequest = null;
  },

  _lastBeepTime: 0,

  onKeyDown(aEvent) {
    if (!this._menuitem.disabled) {
      return;
    }

    let accesskey = this._menuitem.getAttribute("accesskey");
    if (
      aEvent.key == accesskey.toLowerCase() ||
      aEvent.key == accesskey.toUpperCase()
    ) {
      if (Date.now() - this._lastBeepTime > 1000) {
        Cc["@mozilla.org/sound;1"].getService(Ci.nsISound).beep();
        this._lastBeepTime = Date.now();
      }
      this._refreshDelayTimer();
    }
  },

  _menupopup: null,
  _menuitem: null,
  _pendingRequest: null,

  confirmUserPaste(aWindowContext) {
    return new Promise((resolve, reject) => {
      if (!aWindowContext) {
        reject(
          Components.Exception("Null window context.", Cr.NS_ERROR_INVALID_ARG)
        );
        return;
      }

      let { document } = aWindowContext.browsingContext.topChromeWindow;
      if (!document) {
        reject(
          Components.Exception(
            "Unable to get chrome document.",
            Cr.NS_ERROR_FAILURE
          )
        );
        return;
      }

      if (this._pendingRequest) {
        reject(
          Components.Exception(
            "There is an ongoing request.",
            Cr.NS_ERROR_FAILURE
          )
        );
        return;
      }

      this._pendingRequest = { resolve, reject };
      this._menupopup = this._getMenupopup(document);
      this._menuitem = this._menupopup.firstElementChild;
      this._addMenupopupEventListeners();

      let mouseXInCSSPixels = {};
      let mouseYInCSSPixels = {};
      document.ownerGlobal.windowUtils.getLastOverWindowPointerLocationInCSSPixels(
        mouseXInCSSPixels,
        mouseYInCSSPixels
      );

      this._menuitem.disabled = true;
      this._startWatchingForSpammyActivation();
      // `openPopup` is a no-op if the popup is already opened.
      // That property is used when `navigator.clipboard.readText()` or
      // `navigator.clipboard.read()`is called from two different frames, e.g.
      // an iframe and the top level frame. In that scenario, the two frames
      // correspond to different `navigator.clipboard` instances. When
      // `readText()` or `read()` is called from both frames, an actor pair is
      // instantiated for each of them. Both actor parents will call `openPopup`
      // on the same `_menupopup` object. If the popup is already open,
      // `openPopup` is a no-op. When the popup is clicked or dismissed both
      // actor parents will receive the corresponding event.
      this._menupopup.openPopup(
        null,
        "overlap" /* options */,
        mouseXInCSSPixels.value,
        mouseYInCSSPixels.value,
        true /* isContextMenu */
      );

      this._refreshDelayTimer(document);
    });
  },

  _addMenupopupEventListeners() {
    this._menupopup.addEventListener("command", this);
    this._menupopup.addEventListener("popuphiding", this);
  },

  _removeMenupopupEventListeners() {
    this._menupopup.removeEventListener("command", this);
    this._menupopup.removeEventListener("popuphiding", this);
  },

  _createMenupopup(aChromeDoc) {
    let menuitem = aChromeDoc.createXULElement("menuitem");
    menuitem.id = "clipboardReadPasteMenuItem";
    aChromeDoc.l10n.setAttributes(menuitem, "text-action-paste");

    let menupopup = aChromeDoc.createXULElement("menupopup");
    menupopup.id = this.MENU_POPUP_ID;
    menupopup.appendChild(menuitem);
    return menupopup;
  },

  _getMenupopup(aChromeDoc) {
    let menupopup = aChromeDoc.getElementById(this.MENU_POPUP_ID);
    if (menupopup == null) {
      menupopup = this._createMenupopup(aChromeDoc);
      const parent =
        aChromeDoc.querySelector("popupset") || aChromeDoc.documentElement;
      parent.appendChild(menupopup);
    }

    return menupopup;
  },

  _startWatchingForSpammyActivation() {
    let doc = this._menuitem.ownerDocument;
    doc.addEventListener("keydown", this, {
      capture: true,
      mozSystemGroup: true,
    });
  },

  _stopWatchingForSpammyActivation() {
    let doc = this._menuitem.ownerDocument;
    doc.removeEventListener("keydown", this, {
      capture: true,
      mozSystemGroup: true,
    });
  },

  _delayTimer: null,

  _clearDelayTimer() {
    if (this._delayTimer) {
      let window = this._menuitem.ownerGlobal;
      window.clearTimeout(this._delayTimer);
      this._delayTimer = null;
    }
  },

  _refreshDelayTimer() {
    this._clearDelayTimer();

    let window = this._menuitem.ownerGlobal;
    let delay = Services.prefs.getIntPref("security.dialog_enable_delay");
    this._delayTimer = window.setTimeout(() => {
      this._menuitem.disabled = false;
      this._stopWatchingForSpammyActivation();
      this._delayTimer = null;
    }, delay);
  },
};