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
|
/* 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 { GeckoViewActorChild } = ChromeUtils.importESModule(
"resource://gre/modules/GeckoViewActorChild.sys.mjs"
);
const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
LayoutUtils: "resource://gre/modules/LayoutUtils.sys.mjs",
});
const EXPORTED_SYMBOLS = ["SelectionActionDelegateChild"];
const MAGNIFIER_PREF = "layout.accessiblecaret.magnifier.enabled";
const ACCESSIBLECARET_HEIGHT_PREF = "layout.accessiblecaret.height";
const PREFS = [MAGNIFIER_PREF, ACCESSIBLECARET_HEIGHT_PREF];
// Dispatches GeckoView:ShowSelectionAction and GeckoView:HideSelectionAction to
// the GeckoSession on accessible caret changes.
class SelectionActionDelegateChild extends GeckoViewActorChild {
constructor(aModuleName, aMessageManager) {
super(aModuleName, aMessageManager);
this._actionCallback = () => {};
this._isActive = false;
this._previousMessage = "";
// Bug 1570744 - JSWindowActorChild's cannot be used as nsIObserver's
// directly, so we create a new function here instead to act as our
// nsIObserver, which forwards the notification to the observe method.
this._observerFunction = (subject, topic, data) => {
this.observe(subject, topic, data);
};
for (const pref of PREFS) {
Services.prefs.addObserver(pref, this._observerFunction);
}
this._magnifierEnabled = Services.prefs.getBoolPref(MAGNIFIER_PREF);
this._accessiblecaretHeight = parseFloat(
Services.prefs.getCharPref(ACCESSIBLECARET_HEIGHT_PREF, "0")
);
}
didDestroy() {
for (const pref of PREFS) {
Services.prefs.removeObserver(pref, this._observerFunction);
}
}
_actions = [
{
id: "org.mozilla.geckoview.HIDE",
predicate: _ => true,
perform: _ => this.handleEvent({ type: "pagehide" }),
},
{
id: "org.mozilla.geckoview.CUT",
predicate: e =>
!e.collapsed && e.selectionEditable && !this._isPasswordField(e),
perform: _ => this.docShell.doCommand("cmd_cut"),
},
{
id: "org.mozilla.geckoview.COPY",
predicate: e => !e.collapsed && !this._isPasswordField(e),
perform: _ => this.docShell.doCommand("cmd_copy"),
},
{
id: "org.mozilla.geckoview.PASTE",
predicate: e =>
e.selectionEditable &&
Services.clipboard.hasDataMatchingFlavors(
["text/unicode"],
Ci.nsIClipboard.kGlobalClipboard
),
perform: _ => this._performPaste(),
},
{
id: "org.mozilla.geckoview.PASTE_AS_PLAIN_TEXT",
predicate: e =>
this._isContentHtmlEditable(e) &&
Services.clipboard.hasDataMatchingFlavors(
["text/html"],
Ci.nsIClipboard.kGlobalClipboard
),
perform: _ => this._performPasteAsPlainText(),
},
{
id: "org.mozilla.geckoview.DELETE",
predicate: e => !e.collapsed && e.selectionEditable,
perform: _ => this.docShell.doCommand("cmd_delete"),
},
{
id: "org.mozilla.geckoview.COLLAPSE_TO_START",
predicate: e => !e.collapsed && e.selectionEditable,
perform: e => this.docShell.doCommand("cmd_moveLeft"),
},
{
id: "org.mozilla.geckoview.COLLAPSE_TO_END",
predicate: e => !e.collapsed && e.selectionEditable,
perform: e => this.docShell.doCommand("cmd_moveRight"),
},
{
id: "org.mozilla.geckoview.UNSELECT",
predicate: e => !e.collapsed && !e.selectionEditable,
perform: e => this.docShell.doCommand("cmd_selectNone"),
},
{
id: "org.mozilla.geckoview.SELECT_ALL",
predicate: e => {
if (e.reason === "longpressonemptycontent") {
return false;
}
// When on design mode, focusedElement will be null.
const element =
Services.focus.focusedElement || e.target?.activeElement;
if (e.selectionEditable && e.target && element) {
let value = "";
if (element.value) {
value = element.value;
} else if (
element.isContentEditable ||
e.target.designMode === "on"
) {
value = element.innerText;
}
// Do not show SELECT_ALL if the editable is empty
// or all the editable text is already selected.
return value !== "" && value !== e.selectedTextContent;
}
return true;
},
perform: e => this.docShell.doCommand("cmd_selectAll"),
},
];
receiveMessage({ name, data }) {
debug`receiveMessage ${name}`;
switch (name) {
case "ExecuteSelectionAction": {
this._actionCallback(data);
}
}
}
_performPaste() {
this.handleEvent({ type: "pagehide" });
this.docShell.doCommand("cmd_paste");
}
_performPasteAsPlainText() {
this.handleEvent({ type: "pagehide" });
this.docShell.doCommand("cmd_pasteNoFormatting");
}
_isPasswordField(aEvent) {
if (!aEvent.selectionEditable) {
return false;
}
const win = aEvent.target.defaultView;
const focus = aEvent.target.activeElement;
return (
win &&
win.HTMLInputElement &&
win.HTMLInputElement.isInstance(focus) &&
!focus.mozIsTextField(/* excludePassword */ true)
);
}
_isContentHtmlEditable(aEvent) {
if (!aEvent.selectionEditable) {
return false;
}
if (aEvent.target.designMode == "on") {
return true;
}
// focused element isn't <input> nor <textarea>
const win = aEvent.target.defaultView;
const focus = Services.focus.focusedElement;
return (
win &&
win.HTMLInputElement &&
win.HTMLTextAreaElement &&
!win.HTMLInputElement.isInstance(focus) &&
!win.HTMLTextAreaElement.isInstance(focus)
);
}
_getFrameOffset(aEvent) {
// Get correct offset in case of nested iframe.
const offset = {
left: 0,
top: 0,
};
let currentWindow = aEvent.target.defaultView;
while (currentWindow.realFrameElement) {
const frameElement = currentWindow.realFrameElement;
currentWindow = frameElement.ownerGlobal;
// The offset of the iframe window relative to the parent window
// includes the iframe's border, and the iframe's origin in its
// containing document.
const currentRect = frameElement.getBoundingClientRect();
const style = currentWindow.getComputedStyle(frameElement);
const borderLeft = parseFloat(style.borderLeftWidth) || 0;
const borderTop = parseFloat(style.borderTopWidth) || 0;
const paddingLeft = parseFloat(style.paddingLeft) || 0;
const paddingTop = parseFloat(style.paddingTop) || 0;
offset.left += currentRect.left + borderLeft + paddingLeft;
offset.top += currentRect.top + borderTop + paddingTop;
const targetDocShell = currentWindow.docShell;
if (targetDocShell.isMozBrowser) {
break;
}
}
// Now we have coordinates relative to the root content document's
// layout viewport. Subtract the offset of the visual viewport
// relative to the layout viewport, to get coordinates relative to
// the visual viewport.
var offsetX = {};
var offsetY = {};
currentWindow.windowUtils.getVisualViewportOffsetRelativeToLayoutViewport(
offsetX,
offsetY
);
offset.left -= offsetX.value;
offset.top -= offsetY.value;
return offset;
}
_getDefaultMagnifierPoint(aEvent) {
const rect = lazy.LayoutUtils.rectToScreenRect(aEvent.target.ownerGlobal, {
left: aEvent.clientX,
top: aEvent.clientY - this._accessiblecaretHeight,
width: 0,
height: 0,
});
return { x: rect.left, y: rect.top };
}
_getBetterMagnifierPoint(aEvent) {
const win = aEvent.target.defaultView;
if (!win) {
return this._getDefaultMagnifierPoint(aEvent);
}
const focus = aEvent.target.activeElement;
if (
win.HTMLInputElement?.isInstance(focus) &&
focus.mozIsTextField(false)
) {
// <input> element. Use vertical center position of input element.
const bounds = focus.getBoundingClientRect();
const rect = lazy.LayoutUtils.rectToScreenRect(
aEvent.target.ownerGlobal,
{
left: aEvent.clientX,
top: bounds.top,
width: 0,
height: bounds.height,
}
);
return { x: rect.left, y: rect.top + rect.height / 2 };
}
if (win.HTMLTextAreaElement?.isInstance(focus)) {
// TODO:
// <textarea> element. How to get better selection bounds?
return this._getDefaultMagnifierPoint(aEvent);
}
const selection = win.getSelection();
if (selection.rangeCount != 1) {
// When selecting text using accessible caret, selection count will be 1.
// This situation means that current selection isn't into text.
return this._getDefaultMagnifierPoint(aEvent);
}
// We are looking for better selection bounds, then use it.
const bounds = (() => {
const range = selection.getRangeAt(0);
let distance = Number.MAX_SAFE_INTEGER;
let y = aEvent.clientY;
const rectList = range.getClientRects();
for (const rect of rectList) {
const newDistance = Math.abs(aEvent.clientY - rect.bottom);
if (distance > newDistance) {
y = rect.top + rect.height / 2;
distance = newDistance;
}
}
return { left: aEvent.clientX, top: y, width: 0, height: 0 };
})();
const rect = lazy.LayoutUtils.rectToScreenRect(
aEvent.target.ownerGlobal,
bounds
);
return { x: rect.left, y: rect.top };
}
_handleMagnifier(aEvent) {
if (["presscaret", "dragcaret"].includes(aEvent.reason)) {
debug`_handleMagnifier: ${aEvent.reason}`;
const screenPoint = this._getBetterMagnifierPoint(aEvent);
this.eventDispatcher.sendRequest({
type: "GeckoView:ShowMagnifier",
screenPoint,
});
} else if (aEvent.reason == "releasecaret") {
debug`_handleMagnifier: ${aEvent.reason}`;
this.eventDispatcher.sendRequest({
type: "GeckoView:HideMagnifier",
});
}
}
/**
* Receive and act on AccessibleCarets caret state-change
* (mozcaretstatechanged and pagehide) events.
*/
handleEvent(aEvent) {
if (aEvent.type === "pagehide" || aEvent.type === "deactivate") {
// Hide any selection actions on page hide or deactivate.
aEvent = {
reason: "visibilitychange",
caretVisibile: false,
selectionVisible: false,
collapsed: true,
selectionEditable: false,
};
}
let reason = aEvent.reason;
if (this._isActive && !aEvent.caretVisible) {
// For mozcaretstatechanged, "visibilitychange" means the caret is hidden.
reason = "visibilitychange";
} else if (!aEvent.collapsed && !aEvent.selectionVisible) {
reason = "invisibleselection";
} else if (
!this._isActive &&
aEvent.selectionEditable &&
aEvent.collapsed &&
reason !== "longpressonemptycontent" &&
reason !== "taponcaret" &&
!Services.prefs.getBoolPref(
"geckoview.selection_action.show_on_focus",
false
)
) {
// Don't show selection actions when merely focusing on an editor or
// repositioning the cursor. Wait until long press or the caret is tapped
// in order to match Android behavior.
reason = "visibilitychange";
}
debug`handleEvent: ${reason}`;
if (this._magnifierEnabled) {
this._handleMagnifier(aEvent);
}
if (
[
"longpressonemptycontent",
"releasecaret",
"taponcaret",
"updateposition",
].includes(reason)
) {
const actions = this._actions.filter(action =>
action.predicate.call(this, aEvent)
);
const screenRect = (() => {
const boundingRect = aEvent.boundingClientRect;
if (!boundingRect) {
return null;
}
const rect = lazy.LayoutUtils.rectToScreenRect(
aEvent.target.ownerGlobal,
boundingRect
);
return {
left: rect.left,
top: rect.top,
right: rect.right,
bottom: rect.bottom + this._accessiblecaretHeight,
};
})();
const clientRect = (() => {
const boundingRect = aEvent.boundingClientRect;
if (!boundingRect) {
return null;
}
const offset = this._getFrameOffset(aEvent);
return {
left: aEvent.boundingClientRect.left + offset.left,
top: aEvent.boundingClientRect.top + offset.top,
right: aEvent.boundingClientRect.right + offset.left,
bottom:
aEvent.boundingClientRect.bottom +
offset.top +
this._accessiblecaretHeight,
};
})();
const password = this._isPasswordField(aEvent);
const msg = {
collapsed: aEvent.collapsed,
editable: aEvent.selectionEditable,
password,
selection: password ? "" : aEvent.selectedTextContent,
// clientRect is deprecated
clientRect,
screenRect,
actions: actions.map(action => action.id),
};
if (this._isActive && JSON.stringify(msg) === this._previousMessage) {
// Don't call again if we're already active and things haven't changed.
return;
}
this._isActive = true;
this._previousMessage = JSON.stringify(msg);
// We can't just listen to the response of the message because we accept
// multiple callbacks.
this._actionCallback = data => {
const action = actions.find(action => action.id === data.id);
if (action) {
debug`Performing ${data.id}`;
action.perform.call(this, aEvent);
} else {
warn`Invalid action ${data.id}`;
}
};
this.sendAsyncMessage("ShowSelectionAction", msg);
} else if (
[
"invisibleselection",
"presscaret",
"scroll",
"visibilitychange",
].includes(reason)
) {
if (!this._isActive) {
return;
}
this._isActive = false;
// Mark previous actions as stale. Don't do this for "invisibleselection"
// or "scroll" because previous actions should still be valid even after
// these events occur.
if (reason !== "invisibleselection" && reason !== "scroll") {
this._seqNo++;
}
this.sendAsyncMessage("HideSelectionAction", { reason });
} else if (reason == "dragcaret") {
// nothing for selection action
} else {
warn`Unknown reason: ${reason}`;
}
}
observe(aSubject, aTopic, aData) {
if (aTopic != "nsPref:changed") {
return;
}
switch (aData) {
case ACCESSIBLECARET_HEIGHT_PREF:
this._accessiblecaretHeight = parseFloat(
Services.prefs.getCharPref(ACCESSIBLECARET_HEIGHT_PREF, "0")
);
break;
case MAGNIFIER_PREF:
this._magnifierEnabled = Services.prefs.getBoolPref(MAGNIFIER_PREF);
break;
}
// Reset magnifier
this.eventDispatcher.sendRequest({
type: "GeckoView:HideMagnifier",
});
}
}
const { debug, warn } = SelectionActionDelegateChild.initLogging(
"SelectionActionDelegate"
);
|