summaryrefslogtreecommitdiffstats
path: root/mobile/android/components/geckoview/GeckoViewPrompter.sys.mjs
blob: f81c155678ae4f8746cc384fcdcf49d634aeafa2 (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
/* 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/. */

import { GeckoViewUtils } from "resource://gre/modules/GeckoViewUtils.sys.mjs";

const { debug, warn } = GeckoViewUtils.initLogging("GeckoViewPrompter");

export class GeckoViewPrompter {
  constructor(aParent) {
    this.id = Services.uuid.generateUUID().toString().slice(1, -1); // Discard surrounding braces

    if (aParent) {
      if (Window.isInstance(aParent)) {
        this._domWin = aParent;
      } else if (aParent.window) {
        this._domWin = aParent.window;
      } else {
        this._domWin =
          aParent.embedderElement && aParent.embedderElement.ownerGlobal;
      }
    }

    if (!this._domWin) {
      this._domWin = Services.wm.getMostRecentWindow("navigator:geckoview");
    }

    this._innerWindowId =
      this._domWin?.browsingContext.currentWindowContext.innerWindowId;
  }

  get domWin() {
    return this._domWin;
  }

  get prompterActor() {
    const actor = this.domWin?.windowGlobalChild.getActor("GeckoViewPrompter");
    return actor;
  }

  _changeModalState(aEntering) {
    if (!this._domWin) {
      // Allow not having a DOM window.
      return true;
    }
    // Accessing the document object can throw if this window no longer exists. See bug 789888.
    try {
      const winUtils = this._domWin.windowUtils;
      if (!aEntering) {
        winUtils.leaveModalState();
      }

      const event = this._domWin.document.createEvent("Events");
      event.initEvent(
        aEntering ? "DOMWillOpenModalDialog" : "DOMModalDialogClosed",
        true,
        true
      );
      winUtils.dispatchEventToChromeOnly(this._domWin, event);

      if (aEntering) {
        winUtils.enterModalState();
      }
      return true;
    } catch (ex) {
      console.error("Failed to change modal state:", ex);
    }
    return false;
  }

  _dismissUi() {
    this.prompterActor?.dismissPrompt(this);
  }

  accept(aInputText = this.inputText) {
    if (this.callback) {
      let acceptMsg = {};
      switch (this.message.type) {
        case "alert":
          acceptMsg = null;
          break;
        case "button":
          acceptMsg.button = 0;
          break;
        case "text":
          acceptMsg.text = aInputText;
          break;
        default:
          acceptMsg = null;
          break;
      }
      this.callback(acceptMsg);
      // Notify the UI that this prompt should be hidden.
      this._dismissUi();
    }
  }

  dismiss() {
    this.callback(null);
    // Notify the UI that this prompt should be hidden.
    this._dismissUi();
  }

  getPromptType() {
    switch (this.message.type) {
      case "alert":
        return this.message.checkValue ? "alertCheck" : "alert";
      case "button":
        return this.message.checkValue ? "confirmCheck" : "confirm";
      case "text":
        return this.message.checkValue ? "promptCheck" : "prompt";
      default:
        return this.message.type;
    }
  }

  getPromptText() {
    return this.message.msg;
  }

  getInputText() {
    return this.inputText;
  }

  setInputText(aInput) {
    this.inputText = aInput;
  }

  /**
   * Shows a native prompt, and then spins the event loop for this thread while we wait
   * for a response
   */
  showPrompt(aMsg) {
    let result = undefined;
    if (!this._domWin || !this._changeModalState(/* aEntering */ true)) {
      return result;
    }
    try {
      this.asyncShowPrompt(aMsg, res => (result = res));

      // Spin this thread while we wait for a result
      Services.tm.spinEventLoopUntil(
        "GeckoViewPrompter.jsm:showPrompt",
        () => this._domWin.closed || result !== undefined
      );
    } finally {
      this._changeModalState(/* aEntering */ false);
    }
    return result;
  }

  checkInnerWindow() {
    // Checks that the innerWindow where this prompt was created still matches
    // the current innerWindow.
    // This checks will fail if the page navigates away, making this prompt
    // obsolete.
    return (
      this._innerWindowId ===
      this._domWin.browsingContext.currentWindowContext.innerWindowId
    );
  }

  asyncShowPromptPromise(aMsg) {
    return new Promise(resolve => {
      this.asyncShowPrompt(aMsg, resolve);
    });
  }

  async asyncShowPrompt(aMsg, aCallback) {
    this.message = aMsg;
    this.inputText = aMsg.value;
    this.callback = aCallback;

    aMsg.id = this.id;

    let response = null;
    try {
      if (this.checkInnerWindow()) {
        response = await this.prompterActor.prompt(this, aMsg);
      }
    } catch (error) {
      // Nothing we can do really, we will treat this as a dismiss.
      warn`Error while prompting: ${error}`;
    }

    if (!this.checkInnerWindow()) {
      // Page has navigated away, let's dismiss the prompt
      aCallback(null);
    } else {
      aCallback(response);
    }
    // This callback object is tied to the Java garbage collector because
    // it is invoked from Java. Manually release the target callback
    // here; otherwise we may hold onto resources for too long, because
    // we would be relying on both the Java and the JS garbage collectors
    // to run.
    aMsg = undefined;
    aCallback = undefined;
  }

  update(aMsg) {
    this.message = aMsg;
    aMsg.id = this.id;
    this.prompterActor?.updatePrompt(aMsg);
  }
}