// Certain functions assume this is loaded into browser window scope. // This is modifiable because certain chrome tests create their own gBrowser. /* global gBrowser:true */
// This file is used both in privileged and unprivileged contexts, so we have to // be careful about our access to Components.interfaces. We also want to avoid // naming collisions with anything that might be defined in the scope that imports // this script. // // Even if the real |Components| doesn't exist, we might shim in a simple JS // placebo for compat. An easy way to differentiate this from the real thing // is whether the property is read-only or not. The real |Components| property // is read-only. /* global _EU_Ci, _EU_Cc, _EU_Cu, _EU_ChromeUtils, _EU_OS */
window.__defineGetter__("_EU_Ci", function () { var c = Object.getOwnPropertyDescriptor(window, "Components"); return c && c.value && !c.writable ? Ci : SpecialPowers.Ci;
});
window.__defineGetter__("_EU_Cc", function () { var c = Object.getOwnPropertyDescriptor(window, "Components"); return c && c.value && !c.writable ? Cc : SpecialPowers.Cc;
});
window.__defineGetter__("_EU_Cu", function () { var c = Object.getOwnPropertyDescriptor(window, "Components"); return c && c.value && !c.writable ? Cu : SpecialPowers.Cu;
});
window.__defineGetter__("_EU_ChromeUtils", function () { var c = Object.getOwnPropertyDescriptor(window, "ChromeUtils"); return c && c.value && !c.writable ? ChromeUtils : SpecialPowers.ChromeUtils;
});
function _EU_isLinux(aWindow = window) { if (window._EU_OS) { return window._EU_OS == "linux";
} if (aWindow) { try { return aWindow.navigator.platform.startsWith("Linux");
} catch (ex) {}
} return navigator.platform.startsWith("Linux");
}
function _EU_isAndroid(aWindow = window) { if (window._EU_OS) { return window._EU_OS == "android";
} if (aWindow) { try { return aWindow.navigator.userAgent.includes("Android");
} catch (ex) {}
} return navigator.userAgent.includes("Android");
}
function _EU_maybeWrap(o) { // We're used in some contexts where there is no SpecialPowers and also in // some where it exists but has no wrap() method. And this is somewhat // independent of whether window.Components is a thing... var haveWrap = false; try {
haveWrap = SpecialPowers.wrap != undefined;
} catch (e) { // Just leave it false.
} if (!haveWrap) { // Not much we can do here. return o;
} var c = Object.getOwnPropertyDescriptor(window, "Components"); return c && c.value && !c.writable ? o : SpecialPowers.wrap(o);
}
function _EU_maybeUnwrap(o) { var haveWrap = false; try {
haveWrap = SpecialPowers.unwrap != undefined;
} catch (e) { // Just leave it false.
} if (!haveWrap) { // Not much we can do here. return o;
} var c = Object.getOwnPropertyDescriptor(window, "Components"); return c && c.value && !c.writable ? o : SpecialPowers.unwrap(o);
}
function _EU_getPlatform() { if (_EU_isWin()) { return"windows";
} if (_EU_isMac()) { return"mac";
} if (_EU_isAndroid()) { return"android";
} if (_EU_isLinux()) { return"linux";
} return"unknown";
}
function _EU_roundDevicePixels(aMaybeFractionalPixels) { return Math.floor(aMaybeFractionalPixels + 0.5);
}
let event =
aEvent.type == "click" || aEvent.type == "contextmenu"
? new aWindow.PointerEvent(aEvent.type, dict)
: new aWindow.MouseEvent(aEvent.type, dict);
// If documentURIObject exists or `window` is a stub object, we're in // a chrome scope, so don't bother trying to go through SpecialPowers. if (!window.document || window.document.documentURIObject) { return aTarget.dispatchEvent(event);
} return SpecialPowers.dispatchEvent(aWindow, aTarget, event);
}
function isHidden(aElement) { var box = aElement.getBoundingClientRect(); return box.width == 0 && box.height == 0;
}
/** *SendthestringaStrtothefocusedelement. * *FornowthismethodonlyworksforASCIIcharactersandemulatestheshift *keystateonUSkeyboardlayout.
*/ function sendString(aStr, aWindow) { for (let i = 0; i < aStr.length; ++i) { // Do not split a surrogate pair to call synthesizeKey. Dispatching two // sets of keydown and keyup caused by two calls of synthesizeKey is not // good behavior. It could happen due to a bug, but a surrogate pair should // be introduced with one key press operation. Therefore, calling it with // a surrogate pair is the right thing. // Note that TextEventDispatcher will consider whether a surrogate pair // should cause one or two keypress events automatically. Therefore, we // don't need to check the related prefs here. if (
(aStr.charCodeAt(i) & 0xfc00) == 0xd800 &&
i + 1 < aStr.length &&
(aStr.charCodeAt(i + 1) & 0xfc00) == 0xdc00
) {
sendChar(aStr.substring(i, i + 2), aWindow);
i++;
} else {
sendChar(aStr.charAt(i), aWindow);
}
}
}
/** *ParsethekeymodifierflagsfromaEvent.Usedtosharecodebetween *synthesizeMouseandsynthesizeKey.
*/ function _parseModifiers(aEvent, aWindow = window) { var nsIDOMWindowUtils = _EU_Ci.nsIDOMWindowUtils; var mval = 0; if (aEvent.shiftKey) {
mval |= nsIDOMWindowUtils.MODIFIER_SHIFT;
} if (aEvent.ctrlKey) {
mval |= nsIDOMWindowUtils.MODIFIER_CONTROL;
} if (aEvent.altKey) {
mval |= nsIDOMWindowUtils.MODIFIER_ALT;
} if (aEvent.metaKey) {
mval |= nsIDOMWindowUtils.MODIFIER_META;
} if (aEvent.accelKey) {
mval |= _EU_isMac(aWindow)
? nsIDOMWindowUtils.MODIFIER_META
: nsIDOMWindowUtils.MODIFIER_CONTROL;
} if (aEvent.altGrKey) {
mval |= nsIDOMWindowUtils.MODIFIER_ALTGRAPH;
} if (aEvent.capsLockKey) {
mval |= nsIDOMWindowUtils.MODIFIER_CAPSLOCK;
} if (aEvent.fnKey) {
mval |= nsIDOMWindowUtils.MODIFIER_FN;
} if (aEvent.fnLockKey) {
mval |= nsIDOMWindowUtils.MODIFIER_FNLOCK;
} if (aEvent.numLockKey) {
mval |= nsIDOMWindowUtils.MODIFIER_NUMLOCK;
} if (aEvent.scrollLockKey) {
mval |= nsIDOMWindowUtils.MODIFIER_SCROLLLOCK;
} if (aEvent.symbolKey) {
mval |= nsIDOMWindowUtils.MODIFIER_SYMBOL;
} if (aEvent.symbolLockKey) {
mval |= nsIDOMWindowUtils.MODIFIER_SYMBOLLOCK;
}
return mval;
}
/** *Returnthedragservice.Notethatifwe'reintheheadlessmode,this *mayreturnnullbecausetheservicemaybeneverinstantiated(e.g.,on *Linux).
*/ function getDragService() { try { return _EU_Cc["@mozilla.org/widget/dragservice;1"].getService(
_EU_Ci.nsIDragService
);
} catch (e) { // If we're in the headless mode, the drag service may be never // instantiated. In this case, an exception is thrown. Let's ignore // any exceptions since without the drag service, nobody can create a // drag session. returnnull;
}
}
/** *Enddragsessionifthereis. * *TODO:Thisshouldsynthesize"drop"ifnecessary. * *@paramleftXoffsetintheviewport *@paramtopYoffsetintheviewport *@paramaEventTheeventdata,themodifiersareappliedtothe *"dragend"event. *@paramaWindowThewindow. *@returntrueifhandled.Inthiscase,thecallershouldnot *synthesizeDOMeventsbasically.
*/ function _maybeEndDragSession(left, top, aEvent, aWindow) {
let utils = _getDOMWindowUtils(aWindow); const dragSession = utils.dragSession; if (!dragSession) { returnfalse;
} // FIXME: If dragSession.dragAction is not // nsIDragService.DRAGDROP_ACTION_NONE nor aEvent.type is not `keydown`, we // need to synthesize a "drop" event or call setDragEndPointForTests here to // set proper left/top to `dragend` event. try {
dragSession.endDragSession(false, _parseModifiers(aEvent, aWindow));
} catch (e) {} returntrue;
}
var utils = _getDOMWindowUtils(aWindow); var defaultPrevented = false;
if (utils) { var button = computeButton(aEvent); var clickCount = aEvent.clickCount || 1; var modifiers = _parseModifiers(aEvent, aWindow);
// aWindow might be cross-origin from us. var MouseEvent = _EU_maybeWrap(aWindow).MouseEvent;
// Default source to mouse. var inputSource = "inputSource" in aEvent
? aEvent.inputSource
: MouseEvent.MOZ_SOURCE_MOUSE; // Compute a pointerId if needed. var id; if ("id" in aEvent) {
id = aEvent.id;
} else { var isFromPen = inputSource === MouseEvent.MOZ_SOURCE_PEN;
id = isFromPen
? utils.DEFAULT_PEN_POINTER_ID
: utils.DEFAULT_MOUSE_POINTER_ID;
}
// FYI: Window.synthesizeMouseEvent takes floats for the coordinates. // Therefore, don't round/truncate the fractional values. const isDOMEventSynthesized = "isSynthesized" in aEvent ? aEvent.isSynthesized : true; const isWidgetEventSynthesized = "isWidgetEventSynthesized" in aEvent
? aEvent.isWidgetEventSynthesized
: false; const isAsyncEnabled = "asyncEnabled" in aEvent ? aEvent.asyncEnabled : false;
function _sendWheelAndPaint(
aTarget,
aOffsetX,
aOffsetY,
aEvent,
aCallback,
aFlushMode = _FlushModes.FLUSH,
aWindow = window
) { var utils = _getDOMWindowUtils(aWindow); if (!utils) { return;
}
if (utils.isMozAfterPaintPending) { // If a paint is pending, then APZ may be waiting for a scroll acknowledgement // from the content thread. If we send a wheel event now, it could be ignored // by APZ (or its scroll offset could be overridden). To avoid problems we // just wait for the paint to complete.
aWindow.waitForAllPaintsFlushed(function () {
_sendWheelAndPaint(
aTarget,
aOffsetX,
aOffsetY,
aEvent,
aCallback,
aFlushMode,
aWindow
);
}); return;
}
var onwheel = function () {
SpecialPowers.wrap(window).removeEventListener("wheel", onwheel, {
mozSystemGroup: true,
});
// Wait one frame since the wheel event has not caused a refresh observer // to be added yet.
setTimeout(function () {
utils.advanceTimeAndRefresh(1000);
if (!aCallback) {
utils.advanceTimeAndRefresh(0); return;
}
var waitForPaints = function () {
SpecialPowers.Services.obs.removeObserver(
waitForPaints, "apz-repaints-flushed"
);
aWindow.waitForAllPaintsFlushed(function () {
utils.restoreNormalRefresh();
aCallback();
});
};
// Listen for the system wheel event, because it happens after all of // the other wheel events, including legacy events.
SpecialPowers.wrap(aWindow).addEventListener("wheel", onwheel, {
mozSystemGroup: true,
}); if (aFlushMode === _FlushModes.FLUSH) {
synthesizeWheel(aTarget, aOffsetX, aOffsetY, aEvent, aWindow);
} else {
synthesizeWheelAtPoint(aOffsetX, aOffsetY, aEvent, aWindow);
}
}
function synthesizeNativeTap(
aTarget,
aOffsetX,
aOffsetY,
aLongTap = false,
aCallback = null,
aWindow = window
) {
let utils = _getDOMWindowUtils(aWindow); if (!utils) { return;
}
let scale = aWindow.devicePixelRatio;
let rect = aTarget.getBoundingClientRect();
let x = _EU_roundDevicePixels(
(aWindow.mozInnerScreenX + rect.left + aOffsetX) * scale
);
let y = _EU_roundDevicePixels(
(aWindow.mozInnerScreenY + rect.top + aOffsetY) * scale
);
utils.sendNativeTouchTap(x, y, aLongTap, aCallback);
}
/** *SimilartosynthesizeMousebutgeneratesanativewidgetlevelevent *(sowillactuallymovethe"real"mousecursoretc.Becarefulbecause *thiscanimpactlatercodeaswell!(e.g.withhoverstatesetc.) * *@descriptionThereare3mutuallyexclusivewaysofindicatingthelocationofthe *mouseevent:set``atCenter``,orpass``offsetX``and``offsetY``, *orpass``screenX``and``screenY``.Donotattempttomixthese. * *@param{object}aParams *@param{string}aParams.type"click","mousedown","mouseup"or"mousemove" *@param{Element}aParams.targetOriginofoffsetXandoffsetY,mustbeanelement *@param{boolean}[aParams.atCenter] *InsteadofoffsetX/Y,synthesizetheeventatcenterof`target`. *@param{number}[aParams.offsetX] *Xoffsetin`target`(inCSSpixelsif`scale`is"screenPixelsPerCSSPixel") *@param{number}[aParams.offsetY] *Yoffsetin`target`(inCSSpixelsif`scale`is"screenPixelsPerCSSPixel") *@param{number}[aParams.screenX] *Xoffsetinscreen(inCSSpixelsif`scale`is"screenPixelsPerCSSPixel"), *NeitheroffsetX/YnoratCentermustbesetifthisisset. *@param{number}[aParams.screenY] *Yoffsetinscreen(inCSSpixelsif`scale`is"screenPixelsPerCSSPixel"), *NeitheroffsetX/YnoratCentermustbesetifthisisset. *@param{string}[aParams.scale="screenPixelsPerCSSPixel"] *Ifscaleis"screenPixelsPerCSSPixel",devicePixelRatiowillbeused. *Ifscaleis"inScreenPixels",clientX/YnorscaleX/YarenotadjustedwithscreenPixelsPerCSSPixel. *@param{number}[aParams.button=0] *Defaultsto0,if"click","mousedown","mouseup",setsamevalueasDOMMouseEvent.button *@param{object}[aParams.modifiers={}] *Activemodifiers,see`_parseNativeModifiers` *@param{DOMWindow}[aParams.win=window] *Thewindowtouseitsutils.DefaultstothewindowinwhichEventUtils.jsisrunning. *@param{Element}[aParams.elementOnWidget=target] *Defaultstotarget.Ifelementunderthepointisinanotherwidgetfromtarget'swidget, *e.g.,whenit'sinaXUL<panel>,specifythis.
*/ function synthesizeNativeMouseEvent(aParams, aCallback = null) { const {
type,
target,
offsetX,
offsetY,
atCenter,
screenX,
screenY,
scale = "screenPixelsPerCSSPixel",
button = 0,
modifiers = {},
win = window,
elementOnWidget = target,
} = aParams; if (atCenter) { if (offsetX != undefined || offsetY != undefined) { throw Error(
`atCenter is specified, but offsetX (${offsetX}) and/or offsetY (${offsetY}) are also specified`
);
} if (screenX != undefined || screenY != undefined) { throw Error(
`atCenter is specified, but screenX (${screenX}) and/or screenY (${screenY}) are also specified`
);
} if (!target) { throw Error("atCenter is specified, but target is not specified");
}
} elseif (offsetX != undefined && offsetY != undefined) { if (screenX != undefined || screenY != undefined) { throw Error(
`offsetX/Y are specified, but screenX (${screenX}) and/or screenY (${screenY}) are also specified`
);
} if (!target) { throw Error( "offsetX and offsetY are specified, but target is not specified"
);
}
} elseif (screenX != undefined && screenY != undefined) { if (offsetX != undefined || offsetY != undefined) { throw Error(
`screenX/Y are specified, but offsetX (${offsetX}) and/or offsetY (${offsetY}) are also specified`
);
}
} const utils = _getDOMWindowUtils(win); if (!utils) { return;
}
const rect = target?.getBoundingClientRect(); const resolution = _getTopWindowResolution(win); const scaleValue = (() => { if (scale === "inScreenPixels") { return1.0;
} if (scale === "screenPixelsPerCSSPixel") { return win.devicePixelRatio;
} throw Error(`invalid scale value (${scale}) is specified`);
})(); // XXX mozInnerScreen might be invalid value on mobile viewport (Bug 1701546), // so use window.top's mozInnerScreen. But this won't work fission+xorigin // with mobile viewport until mozInnerScreen returns valid value with // scale. const x = _EU_roundDevicePixels(
(() => { if (screenX != undefined) { return screenX * scaleValue;
} const winInnerOffsetX = _getScreenXInUnscaledCSSPixels(win); return (
(((atCenter ? rect.width / 2 : offsetX) + rect.left) * resolution +
winInnerOffsetX) *
scaleValue
);
})()
); const y = _EU_roundDevicePixels(
(() => { if (screenY != undefined) { return screenY * scaleValue;
} const winInnerOffsetY = _getScreenYInUnscaledCSSPixels(win); return (
(((atCenter ? rect.height / 2 : offsetY) + rect.top) * resolution +
winInnerOffsetY) *
scaleValue
);
})()
); const modifierFlags = _parseNativeModifiers(modifiers);
if (type === "click") {
utils.sendNativeMouseEvent(
x,
y,
utils.NATIVE_MOUSE_MESSAGE_BUTTON_DOWN,
button,
modifierFlags,
elementOnWidget, function () {
utils.sendNativeMouseEvent(
x,
y,
utils.NATIVE_MOUSE_MESSAGE_BUTTON_UP,
button,
modifierFlags,
elementOnWidget,
aCallback
);
}
); return;
}
utils.sendNativeMouseEvent(
x,
y,
(() => { switch (type) { case"mousedown": return utils.NATIVE_MOUSE_MESSAGE_BUTTON_DOWN; case"mouseup": return utils.NATIVE_MOUSE_MESSAGE_BUTTON_UP; case"mousemove": return utils.NATIVE_MOUSE_MESSAGE_MOVE; default: throw Error(`Invalid type is specified: ${type}`);
}
})(),
button,
modifierFlags,
elementOnWidget,
aCallback
);
}
function promiseNativeMouseEvent(aParams) { returnnew Promise(resolve => synthesizeNativeMouseEvent(aParams, resolve));
}
if (dispatchKeydown && aKey == "KEY_Escape") {
let eventForKeydown = Object.assign({}, JSON.parse(JSON.stringify(event)));
eventForKeydown.type = "keydown"; if (
_maybeEndDragSession( // TODO: We should set the last dragover point instead 0, 0,
eventForKeydown,
aWindow
)
) { if (!dispatchKeyup) { return;
} // We don't need to dispatch only keydown event because it's consumed by // the drag session.
dispatchKeydown = false;
}
}
var TIP = _getTIP(aWindow, aCallback); if (!TIP) { return;
} var KeyboardEvent = _getKeyboardEvent(aWindow); var modifiers = _emulateToActivateModifiers(TIP, event, aWindow); var keyEventDict = _createKeyboardEventDictionary(aKey, event, TIP, aWindow); var keyEvent = new KeyboardEvent("", keyEventDict.dictionary);
try { if (dispatchKeydown) {
TIP.keydown(keyEvent, keyEventDict.flags); if ("repeat" in event && event.repeat > 1) {
keyEventDict.dictionary.repeat = true; var repeatedKeyEvent = new KeyboardEvent("", keyEventDict.dictionary); for (var i = 1; i < event.repeat; i++) {
TIP.keydown(repeatedKeyEvent, keyEventDict.flags);
}
}
} if (dispatchKeyup) {
TIP.keyup(keyEvent, keyEventDict.flags);
}
} finally {
_emulateToInactivateModifiers(TIP, modifiers, aWindow);
}
}
/** *ThisisawrapperaroundsynthesizeKeythatwaitsforthekeyeventtobe *dispatchedtothetargetcontent.Itreturnsapromisewhichisresolved *whenthecontentreceivesthekeyevent. * *ThisAPIissupposedtobeusedinthosetestcasesthatsynthesizesome *inputeventstochromeprocessandhavesomechecksincontent.
*/ function synthesizeAndWaitKey(
aKey,
aEvent,
aWindow = window,
checkBeforeSynthesize,
checkAfterSynthesize
) {
let browser = gBrowser.selectedTab.linkedBrowser;
let mm = browser.messageManager;
let keyCode = _createKeyboardEventDictionary(aKey, aEvent, null, aWindow)
.dictionary.keyCode;
let { ContentTask } = _EU_ChromeUtils.importESModule( "resource://testing-common/ContentTask.sys.mjs"
);
let keyRegisteredPromise = new Promise(resolve => {
mm.addMessageListener("Test:KeyRegistered", function processed() {
mm.removeMessageListener("Test:KeyRegistered", processed);
resolve();
});
}); // eslint-disable-next-line no-shadow // TODO: Switch to SpecialPowers.spawn // eslint-disable-next-line mozilla/reject-contenttask-spawn
let keyReceivedPromise = ContentTask.spawn(browser, keyCode, keyCode => { returnnew Promise(resolve => {
addEventListener("keyup", function onKeyEvent(e) { if (e.keyCode == keyCode) {
removeEventListener("keyup", onKeyEvent);
resolve();
}
});
sendAsyncMessage("Test:KeyRegistered");
});
});
keyRegisteredPromise.then(() => { if (checkBeforeSynthesize) {
checkBeforeSynthesize();
}
synthesizeKey(aKey, aEvent, aWindow); if (checkAfterSynthesize) {
checkAfterSynthesize();
}
}); return keyReceivedPromise;
}
function _parseNativeModifiers(aModifiers, aWindow = window) {
let modifiers = 0; if (aModifiers.capsLockKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_CAPS_LOCK;
} if (aModifiers.numLockKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_NUM_LOCK;
} if (aModifiers.shiftKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_SHIFT_LEFT;
} if (aModifiers.shiftRightKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_SHIFT_RIGHT;
} if (aModifiers.ctrlKey) {
modifiers |=
SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_CONTROL_LEFT;
} if (aModifiers.ctrlRightKey) {
modifiers |=
SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_CONTROL_RIGHT;
} if (aModifiers.altKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_ALT_LEFT;
} if (aModifiers.altRightKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_ALT_RIGHT;
} if (aModifiers.metaKey) {
modifiers |=
SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_COMMAND_LEFT;
} if (aModifiers.metaRightKey) {
modifiers |=
SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_COMMAND_RIGHT;
} if (aModifiers.helpKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_HELP;
} if (aModifiers.fnKey) {
modifiers |= SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_FUNCTION;
} if (aModifiers.numericKeyPadKey) {
modifiers |=
SpecialPowers.Ci.nsIDOMWindowUtils.NATIVE_MODIFIER_NUMERIC_KEY_PAD;
}
// Mac: Any unused number is okay for adding new keyboard layout. // When you add new keyboard layout here, you need to modify // TISInputSourceWrapper::InitByLayoutID(). // Win: These constants can be found by inspecting registry keys under // HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Keyboard Layouts
function disableNonTestMouseEvents(aDisable) { var domutils = _getDOMWindowUtils();
domutils.disableNonTestMouseEvents(aDisable);
}
function _getDOMWindowUtils(aWindow = window) { // Leave this here as something, somewhere, passes a falsy argument // to this, causing the |window| default argument not to get picked up. if (!aWindow) {
aWindow = window;
}
// If documentURIObject exists or `window` is a stub object, we're in // a chrome scope, so don't bother trying to go through SpecialPowers. if (!aWindow.document || aWindow.document.documentURIObject) { return aWindow.windowUtils;
}
// we need parent.SpecialPowers for: // layout/base/tests/test_reftests_with_caret.html // chrome: toolkit/content/tests/chrome/test_findbar.xul // chrome: toolkit/content/tests/chrome/test_popup_anchor.xul if ("SpecialPowers" in aWindow && aWindow.SpecialPowers != undefined) { return aWindow.SpecialPowers.getDOMWindowUtils(aWindow);
} if ( "SpecialPowers" in aWindow.parent &&
aWindow.parent.SpecialPowers != undefined
) { return aWindow.parent.SpecialPowers.getDOMWindowUtils(aWindow);
}
// TODO: this is assuming we are in chrome space return aWindow.windowUtils;
}
/** *@param{DOMWindow}[aWindow]-DOMwindow *@returnsThescalingvalueappliedtothetopwindow.
*/ function _getTopWindowResolution(aWindow) {
let resolution = 1.0; try {
resolution = _getDOMWindowUtils(aWindow.top).getResolution();
} catch (e) { // XXX How to get mobile viewport scale on Fission+xorigin since // window.top access isn't allowed due to cross-origin?
} return resolution;
}
/** *@param{DOMWindow}[aWindow]-TheDOMwindowwhichyouwant *togetitsx-offsetinthescreen. *@returnsThescreenXofaWindowintheunscaledCSSpixels.
*/ function _getScreenXInUnscaledCSSPixels(aWindow) { // XXX mozInnerScreen might be invalid value on mobile viewport (Bug 1701546), // so use window.top's mozInnerScreen. But this won't work fission+xorigin // with mobile viewport until mozInnerScreen returns valid value with // scale.
let winInnerOffsetX = aWindow.mozInnerScreenX; try {
winInnerOffsetX =
aWindow.top.mozInnerScreenX +
(aWindow.mozInnerScreenX - aWindow.top.mozInnerScreenX) *
_getTopWindowResolution(aWindow);
} catch (e) { // XXX fission+xorigin test throws permission denied since win.top is // cross-origin.
} return winInnerOffsetX;
}
/** *@param{DOMWindow}[aWindow]-TheDOMwindowwhichyouwant *togetitsy-offsetinthescreen. *@returnsThescreenYofaWindowintheunscaledCSSpixels.
*/ function _getScreenYInUnscaledCSSPixels(aWindow) { // XXX mozInnerScreen might be invalid value on mobile viewport (Bug 1701546), // so use window.top's mozInnerScreen. But this won't work fission+xorigin // with mobile viewport until mozInnerScreen returns valid value with // scale.
let winInnerOffsetY = aWindow.mozInnerScreenY; try {
winInnerOffsetY =
aWindow.top.mozInnerScreenY +
(aWindow.mozInnerScreenY - aWindow.top.mozInnerScreenY) *
_getTopWindowResolution(aWindow);
} catch (e) { // XXX fission+xorigin test throws permission denied since win.top is // cross-origin.
} return winInnerOffsetY;
}
function _getTIP(aWindow, aCallback) { if (!aWindow) {
aWindow = window;
} var tip; if (TIPMap.has(aWindow)) {
tip = TIPMap.get(aWindow);
} else {
tip = _EU_Cc["@mozilla.org/text-input-processor;1"].createInstance(
_EU_Ci.nsITextInputProcessor
);
TIPMap.set(aWindow, tip);
} if (!tip.beginInputTransactionForTests(aWindow, aCallback)) {
tip = null;
TIPMap.delete(aWindow);
} return tip;
}
function _getKeyboardEvent(aWindow = window) { if (typeof KeyboardEvent != "undefined") { try { // See if the object can be instantiated; sometimes this yields // 'TypeError: can't access dead object' or 'KeyboardEvent is not a constructor'. new KeyboardEvent("", {}); return KeyboardEvent;
} catch (ex) {}
} if (typeof content != "undefined" && "KeyboardEvent" in content) { return content.KeyboardEvent;
} return aWindow.KeyboardEvent;
}
// eslint-disable-next-line complexity function _guessKeyNameFromKeyCode(aKeyCode, aWindow = window) { var KeyboardEvent = _getKeyboardEvent(aWindow); switch (aKeyCode) { case KeyboardEvent.DOM_VK_CANCEL: return"Cancel"; case KeyboardEvent.DOM_VK_HELP: return"Help"; case KeyboardEvent.DOM_VK_BACK_SPACE: return"Backspace"; case KeyboardEvent.DOM_VK_TAB: return"Tab"; case KeyboardEvent.DOM_VK_CLEAR: return"Clear"; case KeyboardEvent.DOM_VK_RETURN: return"Enter"; case KeyboardEvent.DOM_VK_SHIFT: return"Shift"; case KeyboardEvent.DOM_VK_CONTROL: return"Control"; case KeyboardEvent.DOM_VK_ALT: return"Alt"; case KeyboardEvent.DOM_VK_PAUSE: return"Pause"; case KeyboardEvent.DOM_VK_EISU: return"Eisu"; case KeyboardEvent.DOM_VK_ESCAPE: return"Escape"; case KeyboardEvent.DOM_VK_CONVERT: return"Convert"; case KeyboardEvent.DOM_VK_NONCONVERT: return"NonConvert"; case KeyboardEvent.DOM_VK_ACCEPT: return"Accept"; case KeyboardEvent.DOM_VK_MODECHANGE: return"ModeChange"; case KeyboardEvent.DOM_VK_PAGE_UP: return"PageUp"; case KeyboardEvent.DOM_VK_PAGE_DOWN: return"PageDown"; case KeyboardEvent.DOM_VK_END: return"End"; case KeyboardEvent.DOM_VK_HOME: return"Home"; case KeyboardEvent.DOM_VK_LEFT: return"ArrowLeft"; case KeyboardEvent.DOM_VK_UP: return"ArrowUp"; case KeyboardEvent.DOM_VK_RIGHT: return"ArrowRight"; case KeyboardEvent.DOM_VK_DOWN: return"ArrowDown"; case KeyboardEvent.DOM_VK_SELECT: return"Select"; case KeyboardEvent.DOM_VK_PRINT: return"Print"; case KeyboardEvent.DOM_VK_EXECUTE: return"Execute"; case KeyboardEvent.DOM_VK_PRINTSCREEN: return"PrintScreen"; case KeyboardEvent.DOM_VK_INSERT: return"Insert"; case KeyboardEvent.DOM_VK_DELETE: return"Delete"; case KeyboardEvent.DOM_VK_WIN: return"OS"; case KeyboardEvent.DOM_VK_CONTEXT_MENU: return"ContextMenu"; case KeyboardEvent.DOM_VK_SLEEP: return"Standby"; case KeyboardEvent.DOM_VK_F1: return"F1"; case KeyboardEvent.DOM_VK_F2: return"F2"; case KeyboardEvent.DOM_VK_F3: return"F3"; case KeyboardEvent.DOM_VK_F4: return"F4"; case KeyboardEvent.DOM_VK_F5: return"F5"; case KeyboardEvent.DOM_VK_F6: return"F6"; case KeyboardEvent.DOM_VK_F7: return"F7"; case KeyboardEvent.DOM_VK_F8: return"F8"; case KeyboardEvent.DOM_VK_F9: return"F9"; case KeyboardEvent.DOM_VK_F10: return"F10"; case KeyboardEvent.DOM_VK_F11: return"F11"; case KeyboardEvent.DOM_VK_F12: return"F12"; case KeyboardEvent.DOM_VK_F13: return"F13"; case KeyboardEvent.DOM_VK_F14: return"F14"; case KeyboardEvent.DOM_VK_F15: return"F15"; case KeyboardEvent.DOM_VK_F16: return"F16"; case KeyboardEvent.DOM_VK_F17: return"F17"; case KeyboardEvent.DOM_VK_F18: return"F18"; case KeyboardEvent.DOM_VK_F19: return"F19"; case KeyboardEvent.DOM_VK_F20: return"F20"; case KeyboardEvent.DOM_VK_F21: return"F21"; case KeyboardEvent.DOM_VK_F22: return"F22"; case KeyboardEvent.DOM_VK_F23: return"F23"; case KeyboardEvent.DOM_VK_F24: return"F24"; case KeyboardEvent.DOM_VK_NUM_LOCK: return"NumLock"; case KeyboardEvent.DOM_VK_SCROLL_LOCK: return"ScrollLock"; case KeyboardEvent.DOM_VK_VOLUME_MUTE: return"AudioVolumeMute"; case KeyboardEvent.DOM_VK_VOLUME_DOWN: return"AudioVolumeDown"; case KeyboardEvent.DOM_VK_VOLUME_UP: return"AudioVolumeUp"; case KeyboardEvent.DOM_VK_META: return"Meta"; case KeyboardEvent.DOM_VK_ALTGR: return"AltGraph"; case KeyboardEvent.DOM_VK_PROCESSKEY: return"Process"; case KeyboardEvent.DOM_VK_ATTN: return"Attn"; case KeyboardEvent.DOM_VK_CRSEL: return"CrSel"; case KeyboardEvent.DOM_VK_EXSEL: return"ExSel"; case KeyboardEvent.DOM_VK_EREOF: return"EraseEof"; case KeyboardEvent.DOM_VK_PLAY: return"Play"; default: return"Unidentified";
}
}
TIP.setPendingCompositionString(aEvent.composition.string); if (aEvent.composition.clauses[0].length) { for (var i = 0; i < aEvent.composition.clauses.length; i++) { switch (aEvent.composition.clauses[i].attr) { case TIP.ATTR_RAW_CLAUSE: case TIP.ATTR_SELECTED_RAW_CLAUSE: case TIP.ATTR_CONVERTED_CLAUSE: case TIP.ATTR_SELECTED_CLAUSE:
TIP.appendClauseToPendingComposition(
aEvent.composition.clauses[i].length,
aEvent.composition.clauses[i].attr
); break; case0: // Ignore dummy clause for the argument. break; default: thrownew Error("invalid clause attribute specified");
}
}
}
if (aEvent.caret) {
TIP.setCaretInPendingComposition(aEvent.caret.start);
}
/** *Synthesizeaquerycaretrectevent. * *@paramaOffsetThecaretoffset.0meansleftsideofthefirstcharacter *intheselectionroot. *@paramaWindowOptional(Ifnull,current|window|willbeused) *@returnAnnsIQueryContentEventResultobject.Ifthisfailed, *theresultmightbenull.
*/ function synthesizeQueryCaretRect(aOffset, aWindow) { var utils = _getDOMWindowUtils(aWindow); if (!utils) { returnnull;
} return utils.sendQueryContentEvent(utils.QUERY_CARET_RECT, aOffset, 0, 0, 0);
}
/** *Synthesizeaselectionsetevent. * *@paramaOffsetThecharacteroffset.0meansthefirstcharacterinthe *selectionroot. *@paramaLengthThelengthofthetext.Ifthelengthistoolong, *theextralengthisignored. *@paramaReverseIftrue,theselectionisfrom|aOffset+aLength|to *|aOffset|.Otherwise,from|aOffset|to|aOffset+aLength|. *@paramaWindowOptional(Ifnull,current|window|willbeused) *@returnTrue,ifsucceeded.Otherwisefalse.
*/
async function synthesizeSelectionSet(
aOffset,
aLength,
aReverse,
aWindow = window
) { const utils = _getDOMWindowUtils(aWindow); if (!utils) { returnfalse;
} // eSetSelection event will be compared with selection cache in // IMEContentObserver, but it may have not been updated yet. Therefore, we // need to flush pending things of IMEContentObserver.
await new Promise(resolve =>
aWindow.requestAnimationFrame(() => aWindow.requestAnimationFrame(resolve))
); const flags = aReverse ? SELECTION_SET_FLAG_REVERSE : 0; return utils.sendSelectionSetEvent(aOffset, aLength, flags);
}
/** *Synthesizeaquerytextrectevent. * *@paramaOffsetThecharacteroffset.0meansthefirstcharacterinthe *selectionroot. *@paramaLengthThelengthofthetext.Ifthelengthistoolong, *theextralengthisignored. *@paramaIsRelativeOptional(Iftrue,aOffsetisrelativetostartof *compositionifthereis,orstartofselection.) *@paramaWindowOptional(Ifnull,current|window|willbeused) *@returnAnnsIQueryContentEventResultobject.Ifthisfailed, *theresultmightbenull.
*/ function synthesizeQueryTextRect(aOffset, aLength, aIsRelative, aWindow) { if (aIsRelative !== undefined && typeof aIsRelative !== "boolean") { thrownew Error( "Maybe, you set Window object to the 3rd argument, but it should be a boolean value"
);
} var utils = _getDOMWindowUtils(aWindow);
let flags = 0; if (aIsRelative === true) {
flags |= QUERY_CONTENT_FLAG_OFFSET_RELATIVE_TO_INSERTION_POINT;
} return utils.sendQueryContentEvent(
utils.QUERY_TEXT_RECT,
aOffset,
aLength, 0, 0,
flags
);
}
// Wrap only in plain mochitests
let dataTransfer; if (aDataTransfer) {
dataTransfer = _EU_maybeUnwrap(
_EU_maybeWrap(aDataTransfer).mozCloneForEvent(aType)
);
// Copy over the drop effect. This isn't copied over by Clone, as it uses // more complex logic in the actual implementation (see // nsContentUtils::SetDataTransferInEvent for actual impl).
dataTransfer.dropEffect = aDataTransfer.dropEffect;
} return Object.assign(
{
type: aType,
screenX: _EU_roundDevicePixels(destScreenXInDevicePixels),
screenY: _EU_roundDevicePixels(destScreenYInDevicePixels),
clientX: _EU_roundDevicePixels(destClientXInCSSPixels),
clientY: _EU_roundDevicePixels(destClientYInCSSPixels),
dataTransfer,
_domDispatchOnly: aDragEvent._domDispatchOnly,
},
aDragEvent
);
}
// eslint-disable-next-line mozilla/use-services const obs = _EU_Cc["@mozilla.org/observer-service;1"].getService(
_EU_Ci.nsIObserverService
);
let utils = _getDOMWindowUtils(aWindow); var sess = utils.dragSession;
// This method runs before other callbacks, and acts as a way to inject the // initial drag data into the DataTransfer. function fillDrag(event) { if (aDragData) { for (var i = 0; i < aDragData.length; i++) { var item = aDragData[i]; for (var j = 0; j < item.length; j++) {
_EU_maybeWrap(event.dataTransfer).mozSetDataAt(
item[j].type,
item[j].data,
i
);
}
}
}
event.dataTransfer.dropEffect = aDropEffect || "move";
event.preventDefault();
}
function trapDrag(subject, topic) { if (topic == "on-datatransfer-available") {
sess.dataTransfer = _EU_maybeUnwrap(
_EU_maybeWrap(subject).mozCloneForEvent("drop")
);
sess.dataTransfer.dropEffect = subject.dropEffect;
}
}
// need to use real mouse action
aWindow.addEventListener("dragstart", fillDrag, true);
obs.addObserver(trapDrag, "on-datatransfer-available");
synthesizeMouseAtCenter(aSrcElement, { type: "mousedown" }, aWindow);
var rect = aSrcElement.getBoundingClientRect(); var x = rect.width / 2; var y = rect.height / 2;
synthesizeMouse(aSrcElement, x, y, { type: "mousemove" }, aWindow);
synthesizeMouse(aSrcElement, x + 10, y + 10, { type: "mousemove" }, aWindow);
aWindow.removeEventListener("dragstart", fillDrag, true);
obs.removeObserver(trapDrag, "on-datatransfer-available");
var dataTransfer = sess.dataTransfer; if (!dataTransfer) { thrownew Error("No data transfer object after synthesizing the mouse!");
}
// The EventStateManager will fire our dragenter event if it needs to. var event = createDragEventObject( "dragover",
aDestElement,
aDestWindow,
dataTransfer,
aDragEvent
); var result = sendDragEvent(event, aDestElement, aDestWindow);
if (aResult) {
effect = "none";
} elseif (effect != "none") {
event = createDragEventObject( "drop",
aDestElement,
aDestWindow,
aDataTransfer,
aDragEvent
);
sendDragEvent(event, aDestElement, aDestWindow);
} // Don't run accessibility checks for this click, since we're not actually // clicking. It's just generated as part of the drop. // this.AccessibilityUtils might not be set if this isn't a browser test or // if a browser test has loaded its own copy of EventUtils for some reason. // In the latter case, the test probably shouldn't do that. this.AccessibilityUtils?.suppressClickHandling(true);
synthesizeMouse(aDestElement, 2, 2, { type: "mouseup" }, aDestWindow); this.AccessibilityUtils?.suppressClickHandling(false);
let srcWindowUtils = _getDOMWindowUtils(srcWindow);
let destWindowUtils = _getDOMWindowUtils(destWindow);
if (logFunc) {
logFunc("synthesizePlainDragAndDrop() -- START");
}
if (srcSelection) {
srcElement = _computeSrcElementFromSrcSelection(srcSelection);
let srcElementRect = srcElement.getBoundingClientRect(); if (logFunc) {
logFunc(
`srcElement.getBoundingClientRect(): ${rectToString(srcElementRect)}`
);
} // Use last selection client rect because nsIDragSession.sourceNode is // initialized from focus node which is usually in last rect.
let selectionRectList = SpecialPowers.wrap(
srcSelection.getRangeAt(0)
).getAllowCrossShadowBoundaryClientRects();
let lastSelectionRect = selectionRectList[selectionRectList.length - 1]; if (logFunc) {
logFunc(
`srcSelection.getRangeAt(0).getClientRects()[${
selectionRectList.length - 1
}]: ${rectToString(lastSelectionRect)}`
);
} // Click at center of last selection rect.
srcX = Math.floor(lastSelectionRect.left + lastSelectionRect.width / 2);
srcY = Math.floor(lastSelectionRect.top + lastSelectionRect.height / 2); // Then, adjust srcX and srcY for making them offset relative to // srcElementRect because they will be used when we call synthesizeMouse() // with srcElement.
srcX = Math.floor(srcX - srcElementRect.left);
srcY = Math.floor(srcY - srcElementRect.top); // Finally, recalculate finalX and finalY with new srcX and srcY if they // are not specified by the caller. if (aParams.finalX === undefined) {
finalX = srcX + stepX * 2;
} if (aParams.finalY === undefined) {
finalY = srcY + stepY * 2;
}
} elseif (logFunc) {
logFunc(
`srcElement.getBoundingClientRect(): ${rectToString(
srcElement.getBoundingClientRect()
)}`
);
}
const editingHost = (() => { if (!srcElement.matches(":read-write")) { returnnull;
}
let lastEditableElement = srcElement; for (
let inclusiveAncestor =
_getInclusiveFlattenedTreeParentElement(srcElement);
inclusiveAncestor;
inclusiveAncestor = _getInclusiveFlattenedTreeParentElement(
_getFlattenedTreeParentNode(inclusiveAncestor)
)
) { if (inclusiveAncestor.matches(":read-write")) {
lastEditableElement = inclusiveAncestor; if (lastEditableElement == srcElement.ownerDocument.body) { break;
}
}
} return lastEditableElement;
})(); try {
srcWindowUtils.disableNonTestMouseEvents(true);
await new Promise(r => setTimeout(r, 0));
let mouseDownEvent; function onMouseDown(aEvent) {
mouseDownEvent = aEvent; if (logFunc) {
logFunc(
`"${aEvent.type}" event is fired on ${
aEvent.target
} (composedTarget: ${_EU_maybeUnwrap(
_EU_maybeWrap(aEvent).composedTarget
)}`
);
} if (
!_nodeIsFlattenedTreeDescendantOf(
_EU_maybeUnwrap(_EU_maybeWrap(aEvent).composedTarget),
srcElement
)
) { // If srcX and srcY does not point in one of rects in srcElement, // "mousedown" target is not in srcElement. Such case must not // be expected by this API users so that we should throw an exception // for making debugging easier. thrownew Error( 'event target of "mousedown" is not srcElement nor its descendant'
);
}
} try {
srcWindow.addEventListener("mousedown", onMouseDown, { capture: true });
synthesizeMouse(
srcElement,
srcX,
srcY,
{ type: "mousedown", id },
srcWindow
);
if (logFunc) {
logFunc(`mousedown at ${srcX}, ${srcY}`);
}
if (!mouseDownEvent) {
throw new Error('"mousedown" event is not fired');
}
} finally {
srcWindow.removeEventListener("mousedown", onMouseDown, {
capture: true,
});
}
let dragStartEvent;
function onDragStart(aEvent) {
dragStartEvent = aEvent;
if (logFunc) {
logFunc(`"${aEvent.type}" event is fired`);
}
if (
!_nodeIsFlattenedTreeDescendantOf(
_EU_maybeUnwrap(_EU_maybeWrap(aEvent).composedTarget),
srcElement
)
) {
// If srcX and srcY does not point in one of rects in srcElement,
// "dragstart" target is not in srcElement. Such case must not
// be expected by this API users so that we should throw an exception
// for making debugging easier.
throw new Error(
'event target of "dragstart" is not srcElement nor its descendant'
);
}
}
let dragEnterEvent;
function onDragEnterGenerated(aEvent) {
dragEnterEvent = aEvent;
}
srcWindow.addEventListener("dragstart", onDragStart, { capture: true });
srcWindow.addEventListener("dragenter", onDragEnterGenerated, {
capture: true,
});
try {
// Wait for the next event tick after each event dispatch, so that UI
// elements (e.g. menu) work like the real user input.
await new Promise(r => setTimeout(r, 0));
srcX += stepX;
srcY += stepY;
synthesizeMouse(
srcElement,
srcX,
srcY,
{ type: "mousemove", id },
srcWindow
);
if (logFunc) {
logFunc(`first mousemove at ${srcX}, ${srcY}`);
}
await new Promise(r => setTimeout(r, 0));
srcX += stepX;
srcY += stepY;
synthesizeMouse(
srcElement,
srcX,
srcY,
{ type: "mousemove", id },
srcWindow
);
if (logFunc) {
logFunc(`second mousemove at ${srcX}, ${srcY}`);
}
await new Promise(r => setTimeout(r, 0));
if (!dragStartEvent) {
throw new Error('"dragstart" event is not fired');
}
} finally {
srcWindow.removeEventListener("dragstart", onDragStart, {
capture: true,
});
srcWindow.removeEventListener("dragenter", onDragEnterGenerated, {
capture: true,
});
}
let srcSession = srcWindowUtils.dragSession;
if (!srcSession) {
if (expectCancelDragStart) {
synthesizeMouse(
srcElement,
finalX,
finalY,
{ type: "mouseup", id },
srcWindow
);
return;
}
throw new Error("drag hasn't been started by the operation");
} else if (expectCancelDragStart) {
throw new Error("drag has been started by the operation");
}
if (destElement) {
if (
(srcElement != destElement && !dragEnterEvent) ||
destElement != dragEnterEvent.target
) {
if (logFunc) {
logFunc(
`destElement.getBoundingClientRect(): ${rectToString(
destElement.getBoundingClientRect()
)}`
);
}
function onDragEnter(aEvent) {
dragEnterEvent = aEvent;
if (logFunc) {
logFunc(`"${aEvent.type}" event is fired`);
}
if (aEvent.target != destElement) {
throw new Error('event target of "dragenter" is not destElement');
}
}
destWindow.addEventListener("dragenter", onDragEnter, {
capture: true,
});
try {
let event = createDragEventObject(
"dragenter",
destElement,
destWindow,
null,
dragEvent
);
sendDragEvent(event, destElement, destWindow);
if (!dragEnterEvent && !destElement.disabled) {
throw new Error('"dragenter" event is not fired');
}
if (dragEnterEvent && destElement.disabled) {
throw new Error(
'"dragenter" event should not be fired on disable element'
);
}
} finally {
destWindow.removeEventListener("dragenter", onDragEnter, {
capture: true,
});
}
}
let dragOverEvent;
function onDragOver(aEvent) {
dragOverEvent = aEvent;
if (logFunc) {
logFunc(`"${aEvent.type}" event is fired`);
}
if (aEvent.target != destElement) {
throw new Error('event target of "dragover" is not destElement');
}
}
destWindow.addEventListener("dragover", onDragOver, { capture: true });
try {
// dragover and drop are only fired to a valid drop target. If the
// destElement parameter is null, this function is being used to
// simulate a drag'n'drop over an invalid drop target.
let event = createDragEventObject(
"dragover",
destElement,
destWindow,
null,
dragEvent
);
sendDragEvent(event, destElement, destWindow);
if (!dragOverEvent && !destElement.disabled) {
throw new Error('"dragover" event is not fired');
}
if (dragEnterEvent && destElement.disabled) {
throw new Error(
'"dragover" event should not be fired on disable element'
);
}
} finally {
destWindow.removeEventListener("dragover", onDragOver, {
capture: true,
});
}
await new Promise(r => setTimeout(r, 0));
// If there is not accept to drop the data, "drop" event shouldn't be
// fired.
// XXX nsIDragSession.canDrop is different only on Linux. It must be
// a bug of gtk/nsDragService since it manages `mCanDrop` by itself.
// Thus, we should use nsIDragSession.dragAction instead.
let destSession = destWindowUtils.dragSession;
if (
destSession.dragAction != _EU_Ci.nsIDragService.DRAGDROP_ACTION_NONE
) {
let dropEvent;
function onDrop(aEvent) {
dropEvent = aEvent;
if (logFunc) {
logFunc(`"${aEvent.type}" event is fired`);
}
if (
!_nodeIsFlattenedTreeDescendantOf(
_EU_maybeUnwrap(_EU_maybeWrap(aEvent).composedTarget),
destElement
)
) {
throw new Error(
'event target of "drop" is not destElement nor its descendant'
);
}
}
destWindow.addEventListener("drop", onDrop, { capture: true });
try {
let event = createDragEventObject(
"drop",
destElement,
destWindow,
null,
dragEvent
);
sendDragEvent(event, destElement, destWindow);
if (!dropEvent && destSession.canDrop) {
throw new Error('"drop" event is not fired');
}
} finally {
destWindow.removeEventListener("drop", onDrop, { capture: true });
}
return;
}
}
// Since we don't synthesize drop event, we need to set drag end point
// explicitly for "dragEnd" event which will be fired by
// endDragSession().
dragEvent.clientX = srcElement.getBoundingClientRect().x + finalX;
dragEvent.clientY = srcElement.getBoundingClientRect().y + finalY;
let event = createDragEventObject(
"dragend",
srcElement,
srcWindow,
null,
dragEvent
);
srcSession.setDragEndPointForTests(event.screenX, event.screenY);
if (logFunc) {
logFunc(
`dragend event client (X,Y) = (${event.clientX}, ${event.clientY})`
);
logFunc(
`dragend event screen (X,Y) = (${event.screenX}, ${event.screenY})`
);
}
} finally {
await new Promise(r => setTimeout(r, 0));
if (srcWindowUtils.dragSession) {
const sourceNode = srcWindowUtils.dragSession.sourceNode;
let dragEndEvent;
function onDragEnd(aEvent) {
dragEndEvent = aEvent;
if (logFunc) {
logFunc(`"${aEvent.type}" event is fired`);
}
if (
!_nodeIsFlattenedTreeDescendantOf(
_EU_maybeUnwrap(_EU_maybeWrap(aEvent).composedTarget),
srcElement
) &&
_EU_maybeUnwrap(_EU_maybeWrap(aEvent).composedTarget) != editingHost
) {
throw new Error(
'event target of "dragend" is not srcElement nor its descendant'
);
}
if (expectSrcElementDisconnected) {
throw new Error(
`"dragend" event shouldn't be fired when the source node is disconnected (the source node is ${
sourceNode?.isConnected ? "connected" : "null or disconnected"
})`
);
}
}
srcWindow.addEventListener("dragend", onDragEnd, { capture: true });
try {
srcWindowUtils.dragSession.endDragSession(
true,
_parseModifiers(dragEvent)
);
if (!expectSrcElementDisconnected && !dragEndEvent) {
// eslint-disable-next-line no-unsafe-finally
throw new Error(
`"dragend" event is not fired by nsIDragSession.endDragSession()${
srcWindowUtils.dragSession.sourceNode &&
!srcWindowUtils.dragSession.sourceNode.isConnected
? "(sourceNode was disconnected)"
: ""
}`
);
}
} finally {
srcWindow.removeEventListener("dragend", onDragEnd, { capture: true });
}
}
srcWindowUtils.disableNonTestMouseEvents(false);
if (logFunc) {
logFunc("synthesizePlainDragAndDrop() -- END");
}
}
}
function _checkDataTransferItems(aDataTransfer, aExpectedDragData) {
try {
// We must wrap only in plain mochitests, not chrome
let dataTransfer = _EU_maybeWrap(aDataTransfer);
if (!dataTransfer) {
return null;
}
if (
aExpectedDragData == null ||
dataTransfer.mozItemCount != aExpectedDragData.length
) {
return dataTransfer;
}
for (let i = 0; i < dataTransfer.mozItemCount; i++) {
let dtTypes = dataTransfer.mozTypesAt(i);
if (dtTypes.length != aExpectedDragData[i].length) {
return dataTransfer;
}
for (let j = 0; j < dtTypes.length; j++) {
if (dtTypes[j] != aExpectedDragData[i][j].type) {
return dataTransfer;
}
let dtData = dataTransfer.mozGetDataAt(dtTypes[j], i);
if (aExpectedDragData[i][j].eqTest) {
if (
!aExpectedDragData[i][j].eqTest(
dtData,
aExpectedDragData[i][j].data
)
) {
return dataTransfer;
}
} else if (aExpectedDragData[i][j].data != dtData) {
return dataTransfer;
}
}
}
} catch (ex) {
return ex;
}
return true;
}
/**
* @typedef {(actualData: any, expectedData: any) -> boolean} eqTest
* This callback type is used with ``synthesizePlainDragAndCancel()``.
* It should compare ``actualData`` and ``expectedData`` and return
* true if the two should be considered equal, false otherwise.
*/
/**
* synthesizePlainDragAndCancel() synthesizes drag start with
* synthesizePlainDragAndDrop(), but always cancel it with preventing default
* of "dragstart". Additionally, this checks whether the dataTransfer of
* "dragstart" event has only expected items.
*
* @param {object} aParams
* The params which is set to the argument of ``synthesizePlainDragAndDrop()``.
* @param {Array} aExpectedDataTransferItems
* All expected dataTransfer items.
* This data is in the format:
*
* [
* [
* {"type": value, "data": value, "eqTest": eqTest}
* ...,
* ],
* ...
* ]
*
* This can also be null.
* You can optionally provide ``eqTest`` if the
* comparison to the expected data transfer items can't be done
* with x == y;
* @return {boolean}
* true if aExpectedDataTransferItems matches with
* DragEvent.dataTransfer of "dragstart" event.
* Otherwise, the dataTransfer object (may be null) or
* thrown exception, NOT false. Therefore, you shouldn't
* use.
*/
async function synthesizePlainDragAndCancel(
aParams,
aExpectedDataTransferItems
) {
let srcElement = aParams.srcSelection
? _computeSrcElementFromSrcSelection(aParams.srcSelection)
: aParams.srcElement;
let result;
function onDragStart(aEvent) {
aEvent.preventDefault();
result = _checkDataTransferItems(
aEvent.dataTransfer,
aExpectedDataTransferItems
);
}
SpecialPowers.wrap(srcElement.ownerDocument).addEventListener(
"dragstart",
onDragStart,
{ capture: true, mozSystemGroup: true }
);
try {
aParams.expectCancelDragStart = true;
await synthesizePlainDragAndDrop(aParams);
} finally {
SpecialPowers.wrap(srcElement.ownerDocument).removeEventListener(
"dragstart",
onDragStart,
{ capture: true, mozSystemGroup: true }
);
}
return result;
}
async function _synthesizeMockDndFromChild(aParams) {
// Since we know that this is the (only) content process that will be involved
// in the drag, we can set this for the caller.
const ds = SpecialPowers.Cc["@mozilla.org/widget/dragservice;1"].getService(
SpecialPowers.Ci.nsIDragService
);
ds.neverAllowSessionIsSynthesizedForTests = true;
let sourceElt = document.getElementById(aParams.srcElement);
let targetElt = document.getElementById(aParams.targetElement);
// The spawnChrome call below may return before the DND is complete since
// the parent process will not synchronize with the child for child-initiated
// drags. So we need to wait for the dragend here. If the drag motion is
// expected to not result in a drag session then we wait for the mouseup
// instead.
let resolveEndPromise;
let endPromise = new Promise(res => {
resolveEndPromise = res;
});
let endEvent = aParams.expectNoDragEvents ? "mouseup" : "dragend";
sourceElt.addEventListener(
endEvent,
() => {
resolveEndPromise();
},
{ once: true }
);
// The parent call will not get the element positions, so set 'sourceOffset' to
// the screen coordinates for the drag start and 'targetOffset' for the screen
// position to drag to.
const scale = window.devicePixelRatio;
let sourceOffset = [
(window.mozInnerScreenX + sourceElt.offsetLeft) * scale +
aParams.sourceOffset[0],
(window.mozInnerScreenY + sourceElt.offsetTop) * scale +
aParams.sourceOffset[1],
];
let targetOffset = [
(window.mozInnerScreenX + targetElt.offsetLeft) * scale +
aParams.targetOffset[0],
(window.mozInnerScreenY + targetElt.offsetTop) * scale +
aParams.targetOffset[1],
];
let params = {
srcElement: aParams.srcElement,
targetElement: aParams.targetElement,
sourceOffset,
targetOffset,
step: aParams.step,
expectCancelDragStart: aParams.expectCancelDragStart,
cancel: aParams.cancel,
expectSrcElementDisconnected: aParams.expectSrcElementDisconnected,
expectDragLeave: aParams.expectDragLeave,
expectNoDragEvents: aParams.expectNoDragEvents,
expectNoDragTargetEvents: aParams.expectNoDragTargetEvents,
contextLabel: aParams.contextLabel,
throwOnExtraMessage: aParams.throwOnExtraMessage,
};
let record =
aParams.record ||
((cond, msg, _, stack) => {
if (cond) {
console.error(msg + "\n" + stack);
}
});
let info = aParams.info || console.log;
/**
* Emulate a drag and drop by generating a dragstart from mousedown and mousemove,
* then firing events dragover and drop (or dragleave if expectDragLeave is set).
* This does not modify dataTransfer and tries to emulate the plain drag and
* drop as much as possible, compared to synthesizeDrop and
* synthesizePlainDragAndDrop. MockDragService is used in place of the native
* nsIDragService implementation. All coordinates are in client space.
*
* This method can be called from the parent process, in which case it will
* perform checks of DND internals (if 'record' is set). It can also be
* called from content processes, in which case the drag is over the window
* that is in context, and no checks of DND internals will occur.
*
* @param {object} aParams
* @param {Window} aParams.sourceBrowsingCxt
* The BrowsingContext (possibly remote) that contains
* srcElement. Only set in parent process.
* @param {Window} aParams.targetBrowsingCxt
* The BrowsingContext (possibly remote) that contains
* targetElement. Only set in parent process.
* Default is sourceBrowsingCxt.
* @param {Element} aParams.srcElement
* ID of the element to drag.
* @param {Element|null} aParams.targetElement
* ID of the element to drop on.
* @param {number} aParams.sourceOffset
* The 2D offset from the source element at which the drag
* starts. Default is [0,0].
* @param {number} aParams.targetOffset
* The 2D offset from the target element at which the drag ends.
* Default is [0,0].
* @param {number} aParams.step
* The 2D step for intermediate dragging mousemoves.
* Default is [5,5].
* @param {boolean} aParams.expectCancelDragStart
* Set to true if srcElement is set up to cancel "dragstart"
* @param {number} aParams.cancel
* The 2D coord the mouse is moved to as the last step if
* expectCancelDragStart is set
* @param {boolean} aParams.expectSrcElementDisconnected
* Set to true if srcElement will be disconnected and
* "dragend" event won't be fired.
* @param {boolean} aParams.expectDragLeave
* Set to true if the drop event will be converted to a
* dragleave before it is sent (e.g. it was rejected by a
* content analysis check).
* @param {boolean} aParams.expectNoDragEvents
* Set to true if no mouse or drag events should be received
* on the source or target.
* @param {boolean} aParams.expectNoDragTargetEvents
* Set to true if the drag should be blocked from sending
* events to the target.
* @param {boolean} aParams.dropPromise
* A promise that the caller will resolve before we check
* that the drop has happened. Default is a pre-resolved
* promise.
* @param {string} aParms.contextLabel
* Label that will appear in each output message. Useful to
* distinguish between concurrent calls. Default is none.
* @param {boolean} aParams.throwOnExtraMessage
* Throw an exception in child process when an unexpected
* event is received. Used for debugging. Default is false.
* @param {Function} aParams.record
* Four-parameter function that logs the results of a remote
* assertion. The parameters are (condition, message, ignored,
* stack). This is the type of the mochitest report function.
* Pass the empty function, or call this from content, to skip
* testing of DND internals.
* This parameter is required in the parent process and is
* optional in content processes.
* @param {Function} aParams.info
* One-parameter info logging function. This is the type of
* the mochitest info function. Pass the empty function, or
* call this from content, to skip testing of DND internals.
* This parameter is required in the parent process and is
* optional in content processes.
* @param {object} aParams.dragController
* MockDragController that the function should use. This
* function will automatically generate one if none is given.
* This can only be set in the parent process.
*/
// eslint-disable-next-line complexity
async function synthesizeMockDragAndDrop(aParams) {
// eslint-disable-next-line mozilla/use-services
let appinfo = _EU_Cc["@mozilla.org/xre/app-info;1"].getService(
_EU_Ci.nsIXULRuntime
);
if (appinfo.processType !== appinfo.PROCESS_TYPE_DEFAULT) {
await _synthesizeMockDndFromChild(aParams);
return;
}
// Validate parameters
ok(sourceBrowsingCxt, "sourceBrowsingCxt was given");
ok(
sourceBrowsingCxt != targetBrowsingCxt || srcElement != targetElement,
"sourceBrowsingCxt+Element cannot be the same as targetBrowsingCxt+Element"
);
// no drag implies no drag target
expectNoDragTargetEvents |= expectNoDragEvents;
// Returns true if one browsing context is an ancestor of the other.
let browsingContextsAreRelated = function (cxt1, cxt2) {
return cxt1.top == cxt2.top;
};
// The rules for accessing the dataTransfer from internal drags in Gecko
// during drag event handlers are as follows:
//
// dragstart:
// Always grants read-write access
// dragenter/dragover/dragleave:
// If dom.events.dataTransfer.protected.enabled is set:
// Read-only permission is granted if any of these holds:
// * The drag target's browsing context is the same as the drag
// source's (e.g. dragging inside of one frame on a web page).
// * The drag source and target are the same domain/principal and
// one has a browsing context that is an ancestor of the other
// (e.g. one is an iframe nested inside of the other).
// * The principal of the drag target element is privileged (not
// a content principal).
// Otherwise:
// Permission is never granted
// drop:
// Always grants read-only permission
// dragend:
// Read-only permission is granted if
// dom.events.dataTransfer.protected.enabled is set.
//
// dragstart and dragend are special because they target the drag-source,
// not the drag-target.
// eslint-disable-next-line mozilla/use-services
let prefs = _EU_Cc["@mozilla.org/preferences-service;1"].getService(
Ci.nsIPrefBranch
);
let expectProtectedDataTransferAccessSource = !prefs.getBoolPref(
"dom.events.dataTransfer.protected.enabled"
);
let expectProtectedDataTransferAccessTarget =
expectProtectedDataTransferAccessSource &&
browsingContextsAreRelated(targetBrowsingCxt, sourceBrowsingCxt);
// Essentially the entire function is in a try block so that we can make sure
// that the mock drag service is removed and non-test mouse events are
// restored.
const { MockRegistrar } = ChromeUtils.importESModule(
"resource://testing-common/MockRegistrar.sys.mjs"
);
let dragServiceCid;
let sourceCxt;
let targetCxt;
let srcWindowUtils = _getDOMWindowUtils(sourceBrowsingCxt.documentGlobal);
let targetWindowUtils = _getDOMWindowUtils(targetBrowsingCxt.documentGlobal);
try {
// Disable native mouse events to avoid external interference while the test
// runs. One call disables for all windows.
if (srcWindowUtils) {
srcWindowUtils.disableNonTestMouseEvents(true);
}
if (targetWindowUtils) {
targetWindowUtils.disableNonTestMouseEvents(true);
}
// Install mock drag service.
if (!dragController) {
info("No dragController was given so creating mock drag service");
const oldDragService = _EU_Cc[
"@mozilla.org/widget/dragservice;1"
].getService(_EU_Ci.nsIDragService);
dragController = oldDragService.getMockDragController();
dragServiceCid = MockRegistrar.register(
"@mozilla.org/widget/dragservice;1",
dragController.mockDragService
);
ok(dragServiceCid, "MockDragService was registered");
// If the mock failed then don't continue or else we will trigger native
// DND behavior.
if (!dragServiceCid) {
throw new Error("MockDragService failed to register");
}
}
// Get element positions in screen coords
let add2d = (a, b) => {
return [a[0] + b[0], a[1] + b[1]];
};
let srcPos = add2d(
(await sourceCxt.getElementPositions()).screenPos,
sourceOffset
);
let targetPos = add2d(
(await targetCxt.getElementPositions()).screenPos,
targetOffset
);
info(`screenSrcPos: ${srcPos} | screenTargetPos: ${targetPos}`);
// Send and verify the mousedown on src.
if (!expectNoDragEvents) {
sourceCxt.expect("mousedown");
}
// Take ceiling of ccoordinates to make sure that the integer coordinates
// are over the element.
let currentSrcScreenPos = [Math.ceil(srcPos[0]), Math.ceil(srcPos[1])];
info(
`sending mousedown at ${currentSrcScreenPos[0]}, ${currentSrcScreenPos[1]}`
);
dragController.sendEvent(
sourceBrowsingCxt,
Ci.nsIMockDragServiceController.eMouseDown,
currentSrcScreenPos[0],
currentSrcScreenPos[1]
);
info(`mousedown sent`);
await sourceCxt.synchronize();
await sourceCxt.checkMouseDown();
let contentInvokedDragPromise;
info("setting up content-invoked-drag observer and expecting dragstart");
if (!expectNoDragEvents) {
sourceCxt.expect("dragstart");
// Set up observable for content-invoked-drag, which is sent when the
// parent learns that content has begun a drag session.
contentInvokedDragPromise = new Promise(cb => {
Services.obs.addObserver(function observe() {
info("content-invoked-drag observer received message");
Services.obs.removeObserver(observe, "content-invoked-drag");
cb();
}, "content-invoked-drag");
});
}
// It takes two mouse-moves to initiate a drag session.
currentSrcScreenPos = [
currentSrcScreenPos[0] + step[0],
currentSrcScreenPos[1] + step[1],
];
info(
`first mousemove at ${currentSrcScreenPos[0]}, ${currentSrcScreenPos[1]}`
);
dragController.sendEvent(
sourceBrowsingCxt,
Ci.nsIMockDragServiceController.eMouseMove,
currentSrcScreenPos[0],
currentSrcScreenPos[1]
);
info(`first mousemove sent`);
if (!expectNoDragEvents) {
info("waiting for content-invoked-drag observable");
await contentInvokedDragPromise;
ok(true, "content-invoked-drag was received");
}
if (expectNoDragEvents) {
ok(
!mockDragService.getCurrentSession(),
"Drag was properly blocked from starting."
);
dragController.sendEvent(
sourceBrowsingCxt,
Ci.nsIMockDragServiceController.eMouseUp,
cancel[0],
cancel[1]
);
return;
}
// Another move creates the drag session in the parent process (but we need
// to wait for the src process to get there).
currentSrcScreenPos = [
currentSrcScreenPos[0] + step[0],
currentSrcScreenPos[1] + step[1],
];
info(
`third mousemove at ${currentSrcScreenPos[0]}, ${currentSrcScreenPos[1]}`
);
dragController.sendEvent(
sourceBrowsingCxt,
Ci.nsIMockDragServiceController.eMouseMove,
currentSrcScreenPos[0],
currentSrcScreenPos[1]
);
info(`third mousemove sent`);
ok(mockDragService.getCurrentSession(), `Parent process has drag session.`);
// Implementation detail: EventStateManager::GenerateDragDropEnterExit
// expects the source to get at least one dragover before leaving the
// widget or else it fails to send dragenter/dragleave events to the
// browsers.
info("synthesizing dragover inside source");
sourceCxt.expect("dragenter");
sourceCxt.expect("dragover");
currentSrcScreenPos = [
currentSrcScreenPos[0] + step[0],
currentSrcScreenPos[1] + step[1],
];
info(`dragover at ${currentSrcScreenPos[0]}, ${currentSrcScreenPos[1]}`);
dragController.sendEvent(
sourceBrowsingCxt,
Ci.nsIMockDragServiceController.eDragOver,
currentSrcScreenPos[0],
currentSrcScreenPos[1]
);
let currentTargetScreenPos = [
Math.ceil(targetPos[0]),
Math.ceil(targetPos[1]),
];
// The next step is to drag to the target element.
if (!expectNoDragTargetEvents) {
sourceCxt.expect("dragleave");
}
if (
sourceBrowsingCxt.top.embedderElement !==
targetBrowsingCxt.top.embedderElement
) { // Send dragexit and dragenter only if we are dragging to another widget. // If we are dragging in the same widget then dragenter does not involve // the parent process. This mirrors the native behavior. In the // widget-to-widget case, the source gets the dragexit immediately but // the target won't get a dragenter in content until we send a dragover -- // this is because dragenters are generated by the EventStateManager and // are not forwarded remotely. // NB: dragleaves are synthesized by Gecko from dragexits.
info("synthesizing dragexit and dragenter to enter new widget"); if (!expectNoDragTargetEvents) {
info("This will generate dragleave on the source");
}
info( "Synthesizing dragover over target. This will first generate a dragenter."
); if (!expectNoDragTargetEvents) {
targetCxt.expect("dragenter");
targetCxt.expect("dragover");
}
if (!expectSrcElementDisconnected) {
await sourceCxt.checkHasDrag(true);
sourceCxt.expect("dragend");
}
info(
`issuing drop event that should be ` +
`${
!expectNoDragTargetEvents
? `received as a ${expectedMessage} event`
: "ignored"
}, followed by a dragend event`
);
ok(
!mockDragService.getCurrentSession(),
`Parent process does not have a drag session.`
);
} catch (e) { // Any exception is a test failure.
record(false, e.toString(), null, e.stack); throw e;
} finally { if (sourceCxt) {
await sourceCxt.cleanup();
} if (targetCxt) {
await targetCxt.cleanup();
}
if (dragServiceCid) {
MockRegistrar.unregister(dragServiceCid);
}
if (srcWindowUtils) {
srcWindowUtils.disableNonTestMouseEvents(false);
} if (targetWindowUtils) {
targetWindowUtils.disableNonTestMouseEvents(false);
}
this.eventCount = 0; // Bug 1512817: // SpecialPowers is picky and needs to be passed an explicit reference to // the function to be called. To avoid having to bind "this", we therefore // define the method this way, via a property. this.handleEvent = () => { this.eventCount++;
};
¤ Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.0.285Bemerkung:
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.