1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "PositionedEventTargeting.h"
8
9 #include "mozilla/EventListenerManager.h"
10 #include "mozilla/EventStates.h"
11 #include "mozilla/MouseEvents.h"
12 #include "mozilla/Preferences.h"
13 #include "mozilla/PresShell.h"
14 #include "mozilla/StaticPrefs_dom.h"
15 #include "mozilla/StaticPrefs_ui.h"
16 #include "mozilla/ToString.h"
17 #include "mozilla/dom/MouseEventBinding.h"
18 #include "nsContainerFrame.h"
19 #include "nsFrameList.h" // for DEBUG_FRAME_DUMP
20 #include "nsHTMLParts.h"
21 #include "nsLayoutUtils.h"
22 #include "nsGkAtoms.h"
23 #include "nsFontMetrics.h"
24 #include "nsPrintfCString.h"
25 #include "mozilla/dom/Element.h"
26 #include "nsRegion.h"
27 #include "nsDeviceContext.h"
28 #include "nsIContentInlines.h"
29 #include "nsIFrame.h"
30 #include <algorithm>
31
32 using namespace mozilla;
33 using namespace mozilla::dom;
34
35 // If debugging this code you may wish to enable this logging, via
36 // the env var MOZ_LOG="event.retarget:4". For extra logging (getting
37 // frame dumps, use MOZ_LOG="event.retarget:5".
38 static mozilla::LazyLogModule sEvtTgtLog("event.retarget");
39 #define PET_LOG(...) MOZ_LOG(sEvtTgtLog, LogLevel::Debug, (__VA_ARGS__))
40
41 namespace mozilla {
42
43 /*
44 * The basic goal of FindFrameTargetedByInputEvent() is to find a good
45 * target element that can respond to mouse events. Both mouse events and touch
46 * events are targeted at this element. Note that even for touch events, we
47 * check responsiveness to mouse events. We assume Web authors
48 * designing for touch events will take their own steps to account for
49 * inaccurate touch events.
50 *
51 * GetClickableAncestor() encapsulates the heuristic that determines whether an
52 * element is expected to respond to mouse events. An element is deemed
53 * "clickable" if it has registered listeners for "click", "mousedown" or
54 * "mouseup", or is on a whitelist of element tags (<a>, <button>, <input>,
55 * <select>, <textarea>, <label>), or has role="button", or is a link, or
56 * is a suitable XUL element.
57 * Any descendant (in the same document) of a clickable element is also
58 * deemed clickable since events will propagate to the clickable element from
59 * its descendant.
60 *
61 * If the element directly under the event position is clickable (or
62 * event radii are disabled), we always use that element. Otherwise we collect
63 * all frames intersecting a rectangle around the event position (taking CSS
64 * transforms into account) and choose the best candidate in GetClosest().
65 * Only GetClickableAncestor() candidates are considered; if none are found,
66 * then we revert to targeting the element under the event position.
67 * We ignore candidates outside the document subtree rooted by the
68 * document of the element directly under the event position. This ensures that
69 * event listeners in ancestor documents don't make it completely impossible
70 * to target a non-clickable element in a child document.
71 *
72 * When both a frame and its ancestor are in the candidate list, we ignore
73 * the ancestor. Otherwise a large ancestor element with a mouse event listener
74 * and some descendant elements that need to be individually targetable would
75 * disable intelligent targeting of those descendants within its bounds.
76 *
77 * GetClosest() computes the transformed axis-aligned bounds of each
78 * candidate frame, then computes the Manhattan distance from the event point
79 * to the bounds rect (which can be zero). The frame with the
80 * shortest distance is chosen. For visited links we multiply the distance
81 * by a specified constant weight; this can be used to make visited links
82 * more or less likely to be targeted than non-visited links.
83 */
84
85 // Enum that determines which type of elements to count as targets in the
86 // search. Clickable elements are generally ones that respond to click events,
87 // like form inputs and links and things with click event listeners.
88 // Touchable elements are a much narrower set of elements; ones with touchstart
89 // and touchend listeners.
90 enum class SearchType {
91 None,
92 Clickable,
93 Touchable,
94 };
95
96 struct EventRadiusPrefs {
97 bool mEnabled; // other fields are valid iff this field is true
98 uint32_t mVisitedWeight; // in percent, i.e. default is 100
99 uint32_t mRadiusTopmm;
100 uint32_t mRadiusRightmm;
101 uint32_t mRadiusBottommm;
102 uint32_t mRadiusLeftmm;
103 bool mTouchOnly;
104 bool mReposition;
105 SearchType mSearchType;
106
EventRadiusPrefsmozilla::EventRadiusPrefs107 explicit EventRadiusPrefs(EventClassID aEventClassID) {
108 if (aEventClassID == eTouchEventClass) {
109 mEnabled = StaticPrefs::ui_touch_radius_enabled();
110 mVisitedWeight = StaticPrefs::ui_touch_radius_visitedWeight();
111 mRadiusTopmm = StaticPrefs::ui_touch_radius_topmm();
112 mRadiusRightmm = StaticPrefs::ui_touch_radius_rightmm();
113 mRadiusBottommm = StaticPrefs::ui_touch_radius_bottommm();
114 mRadiusLeftmm = StaticPrefs::ui_touch_radius_leftmm();
115 mTouchOnly = false; // Always false, unlike mouse events.
116 mReposition = false; // Always false, unlike mouse events.
117 mSearchType = SearchType::Touchable;
118
119 } else if (aEventClassID == eMouseEventClass) {
120 mEnabled = StaticPrefs::ui_mouse_radius_enabled();
121 mVisitedWeight = StaticPrefs::ui_mouse_radius_visitedWeight();
122 mRadiusTopmm = StaticPrefs::ui_mouse_radius_topmm();
123 mRadiusRightmm = StaticPrefs::ui_mouse_radius_rightmm();
124 mRadiusBottommm = StaticPrefs::ui_mouse_radius_bottommm();
125 mRadiusLeftmm = StaticPrefs::ui_mouse_radius_leftmm();
126 mTouchOnly = StaticPrefs::ui_mouse_radius_inputSource_touchOnly();
127 mReposition = StaticPrefs::ui_mouse_radius_reposition();
128 mSearchType = SearchType::Clickable;
129
130 } else {
131 mEnabled = false;
132 mVisitedWeight = 0;
133 mRadiusTopmm = 0;
134 mRadiusRightmm = 0;
135 mRadiusBottommm = 0;
136 mRadiusLeftmm = 0;
137 mTouchOnly = false;
138 mReposition = false;
139 mSearchType = SearchType::None;
140 }
141 }
142 };
143
HasMouseListener(nsIContent * aContent)144 static bool HasMouseListener(nsIContent* aContent) {
145 if (EventListenerManager* elm = aContent->GetExistingListenerManager()) {
146 return elm->HasListenersFor(nsGkAtoms::onclick) ||
147 elm->HasListenersFor(nsGkAtoms::onmousedown) ||
148 elm->HasListenersFor(nsGkAtoms::onmouseup);
149 }
150
151 return false;
152 }
153
HasTouchListener(nsIContent * aContent)154 static bool HasTouchListener(nsIContent* aContent) {
155 EventListenerManager* elm = aContent->GetExistingListenerManager();
156 if (!elm) {
157 return false;
158 }
159
160 // FIXME: Should this really use the pref rather than TouchEvent::PrefEnabled
161 // or such?
162 if (!StaticPrefs::dom_w3c_touch_events_enabled()) {
163 return false;
164 }
165
166 return elm->HasNonSystemGroupListenersFor(nsGkAtoms::ontouchstart) ||
167 elm->HasNonSystemGroupListenersFor(nsGkAtoms::ontouchend);
168 }
169
HasPointerListener(nsIContent * aContent)170 static bool HasPointerListener(nsIContent* aContent) {
171 EventListenerManager* elm = aContent->GetExistingListenerManager();
172 if (!elm) {
173 return false;
174 }
175
176 return elm->HasListenersFor(nsGkAtoms::onpointerdown) ||
177 elm->HasListenersFor(nsGkAtoms::onpointerup);
178 }
179
IsDescendant(nsIFrame * aFrame,nsIContent * aAncestor,nsAutoString * aLabelTargetId)180 static bool IsDescendant(nsIFrame* aFrame, nsIContent* aAncestor,
181 nsAutoString* aLabelTargetId) {
182 for (nsIContent* content = aFrame->GetContent(); content;
183 content = content->GetFlattenedTreeParent()) {
184 if (aLabelTargetId && content->IsHTMLElement(nsGkAtoms::label)) {
185 content->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::_for,
186 *aLabelTargetId);
187 }
188 if (content == aAncestor) {
189 return true;
190 }
191 }
192 return false;
193 }
194
GetTouchableAncestor(nsIFrame * aFrame,nsAtom * aStopAt=nullptr)195 static nsIContent* GetTouchableAncestor(nsIFrame* aFrame,
196 nsAtom* aStopAt = nullptr) {
197 // Input events propagate up the content tree so we'll follow the content
198 // ancestors to look for elements accepting the touch event.
199 for (nsIContent* content = aFrame->GetContent(); content;
200 content = content->GetFlattenedTreeParent()) {
201 if (aStopAt && content->IsHTMLElement(aStopAt)) {
202 break;
203 }
204 if (HasTouchListener(content)) {
205 return content;
206 }
207 }
208 return nullptr;
209 }
210
GetClickableAncestor(nsIFrame * aFrame,nsAtom * aStopAt=nullptr,nsAutoString * aLabelTargetId=nullptr)211 static nsIContent* GetClickableAncestor(
212 nsIFrame* aFrame, nsAtom* aStopAt = nullptr,
213 nsAutoString* aLabelTargetId = nullptr) {
214 // If the frame is `cursor:pointer` or inherits `cursor:pointer` from an
215 // ancestor, treat it as clickable. This is a heuristic to deal with pages
216 // where the click event listener is on the <body> or <html> element but it
217 // triggers an action on some specific element. We want the specific element
218 // to be considered clickable, and at least some pages that do this indicate
219 // the clickability by setting `cursor:pointer`, so we use that here.
220 // Note that descendants of `cursor:pointer` elements that override the
221 // inherited `pointer` to `auto` or any other value are NOT treated as
222 // clickable, because it seems like the content author is trying to express
223 // non-clickability on that sub-element.
224 // In the future depending on real-world cases it might make sense to expand
225 // this check to any non-auto cursor. Such a change would also pick up things
226 // like contenteditable or input fields, which can then be removed from the
227 // loop below, and would have better performance.
228 if (aFrame->StyleUI()->mCursor.keyword == StyleCursorKind::Pointer) {
229 return aFrame->GetContent();
230 }
231
232 // Input events propagate up the content tree so we'll follow the content
233 // ancestors to look for elements accepting the click.
234 for (nsIContent* content = aFrame->GetContent(); content;
235 content = content->GetFlattenedTreeParent()) {
236 if (aStopAt && content->IsHTMLElement(aStopAt)) {
237 break;
238 }
239 if (HasTouchListener(content) || HasMouseListener(content) ||
240 HasPointerListener(content)) {
241 return content;
242 }
243 if (content->IsAnyOfHTMLElements(nsGkAtoms::button, nsGkAtoms::input,
244 nsGkAtoms::select, nsGkAtoms::textarea)) {
245 return content;
246 }
247 if (content->IsHTMLElement(nsGkAtoms::label)) {
248 if (aLabelTargetId) {
249 content->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::_for,
250 *aLabelTargetId);
251 }
252 return content;
253 }
254
255 // Bug 921928: we don't have access to the content of remote iframe.
256 // So fluffing won't go there. We do an optimistic assumption here:
257 // that the content of the remote iframe needs to be a target.
258 if (content->IsHTMLElement(nsGkAtoms::iframe) &&
259 content->AsElement()->AttrValueIs(kNameSpaceID_None,
260 nsGkAtoms::mozbrowser,
261 nsGkAtoms::_true, eIgnoreCase) &&
262 content->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::remote,
263 nsGkAtoms::_true, eIgnoreCase)) {
264 return content;
265 }
266
267 // See nsCSSFrameConstructor::FindXULTagData. This code is not
268 // really intended to be used with XUL, though.
269 if (content->IsAnyOfXULElements(
270 nsGkAtoms::button, nsGkAtoms::checkbox, nsGkAtoms::radio,
271 nsGkAtoms::menu, nsGkAtoms::menuitem, nsGkAtoms::menulist,
272 nsGkAtoms::scrollbarbutton, nsGkAtoms::resizer)) {
273 return content;
274 }
275
276 static Element::AttrValuesArray clickableRoles[] = {
277 nsGkAtoms::button, nsGkAtoms::key, nullptr};
278 if (content->IsElement() && content->AsElement()->FindAttrValueIn(
279 kNameSpaceID_None, nsGkAtoms::role,
280 clickableRoles, eIgnoreCase) >= 0) {
281 return content;
282 }
283 if (content->IsEditable()) {
284 return content;
285 }
286 nsCOMPtr<nsIURI> linkURI;
287 if (content->IsLink(getter_AddRefs(linkURI))) {
288 return content;
289 }
290 }
291 return nullptr;
292 }
293
AppUnitsFromMM(RelativeTo aFrame,uint32_t aMM)294 static nscoord AppUnitsFromMM(RelativeTo aFrame, uint32_t aMM) {
295 nsPresContext* pc = aFrame.mFrame->PresContext();
296 float result = float(aMM) * (pc->DeviceContext()->AppUnitsPerPhysicalInch() /
297 MM_PER_INCH_FLOAT);
298 if (aFrame.mViewportType == ViewportType::Layout) {
299 PresShell* presShell = pc->PresShell();
300 result = result / presShell->GetResolution();
301 }
302 return NSToCoordRound(result);
303 }
304
305 /**
306 * Clip aRect with the bounds of aFrame in the coordinate system of
307 * aRootFrame. aRootFrame is an ancestor of aFrame.
308 */
ClipToFrame(RelativeTo aRootFrame,const nsIFrame * aFrame,nsRect & aRect)309 static nsRect ClipToFrame(RelativeTo aRootFrame, const nsIFrame* aFrame,
310 nsRect& aRect) {
311 nsRect bound = nsLayoutUtils::TransformFrameRectToAncestor(
312 aFrame, nsRect(nsPoint(0, 0), aFrame->GetSize()), aRootFrame);
313 nsRect result = bound.Intersect(aRect);
314 return result;
315 }
316
GetTargetRect(RelativeTo aRootFrame,const nsPoint & aPointRelativeToRootFrame,const nsIFrame * aRestrictToDescendants,const EventRadiusPrefs & aPrefs,uint32_t aFlags)317 static nsRect GetTargetRect(RelativeTo aRootFrame,
318 const nsPoint& aPointRelativeToRootFrame,
319 const nsIFrame* aRestrictToDescendants,
320 const EventRadiusPrefs& aPrefs, uint32_t aFlags) {
321 nsMargin m(AppUnitsFromMM(aRootFrame, aPrefs.mRadiusTopmm),
322 AppUnitsFromMM(aRootFrame, aPrefs.mRadiusRightmm),
323 AppUnitsFromMM(aRootFrame, aPrefs.mRadiusBottommm),
324 AppUnitsFromMM(aRootFrame, aPrefs.mRadiusLeftmm));
325 nsRect r(aPointRelativeToRootFrame, nsSize(0, 0));
326 r.Inflate(m);
327 if (!(aFlags & INPUT_IGNORE_ROOT_SCROLL_FRAME)) {
328 // Don't clip this rect to the root scroll frame if the flag to ignore the
329 // root scroll frame is set. Note that the GetClosest code will still
330 // enforce that the target found is a descendant of aRestrictToDescendants.
331 r = ClipToFrame(aRootFrame, aRestrictToDescendants, r);
332 }
333 return r;
334 }
335
ComputeDistanceFromRect(const nsPoint & aPoint,const nsRect & aRect)336 static float ComputeDistanceFromRect(const nsPoint& aPoint,
337 const nsRect& aRect) {
338 nscoord dx =
339 std::max(0, std::max(aRect.x - aPoint.x, aPoint.x - aRect.XMost()));
340 nscoord dy =
341 std::max(0, std::max(aRect.y - aPoint.y, aPoint.y - aRect.YMost()));
342 return float(NS_hypot(dx, dy));
343 }
344
ComputeDistanceFromRegion(const nsPoint & aPoint,const nsRegion & aRegion)345 static float ComputeDistanceFromRegion(const nsPoint& aPoint,
346 const nsRegion& aRegion) {
347 MOZ_ASSERT(!aRegion.IsEmpty(),
348 "can't compute distance between point and empty region");
349 float minDist = -1;
350 for (auto iter = aRegion.RectIter(); !iter.Done(); iter.Next()) {
351 float dist = ComputeDistanceFromRect(aPoint, iter.Get());
352 if (dist < minDist || minDist < 0) {
353 minDist = dist;
354 }
355 }
356 return minDist;
357 }
358
359 // Subtract aRegion from aExposedRegion as long as that doesn't make the
360 // exposed region get too complex or removes a big chunk of the exposed region.
SubtractFromExposedRegion(nsRegion * aExposedRegion,const nsRegion & aRegion)361 static void SubtractFromExposedRegion(nsRegion* aExposedRegion,
362 const nsRegion& aRegion) {
363 if (aRegion.IsEmpty()) {
364 return;
365 }
366
367 nsRegion tmp;
368 tmp.Sub(*aExposedRegion, aRegion);
369 // Don't let *aExposedRegion get too complex, but don't let it fluff out to
370 // its bounds either. Do let aExposedRegion get more complex if by doing so
371 // we reduce its area by at least half.
372 if (tmp.GetNumRects() <= 15 || tmp.Area() <= aExposedRegion->Area() / 2) {
373 *aExposedRegion = tmp;
374 }
375 }
376
GetClosest(RelativeTo aRoot,const nsPoint & aPointRelativeToRootFrame,const nsRect & aTargetRect,const EventRadiusPrefs & aPrefs,const nsIFrame * aRestrictToDescendants,nsIContent * aClickableAncestor,nsTArray<nsIFrame * > & aCandidates)377 static nsIFrame* GetClosest(RelativeTo aRoot,
378 const nsPoint& aPointRelativeToRootFrame,
379 const nsRect& aTargetRect,
380 const EventRadiusPrefs& aPrefs,
381 const nsIFrame* aRestrictToDescendants,
382 nsIContent* aClickableAncestor,
383 nsTArray<nsIFrame*>& aCandidates) {
384 nsIFrame* bestTarget = nullptr;
385 // Lower is better; distance is in appunits
386 float bestDistance = 1e6f;
387 nsRegion exposedRegion(aTargetRect);
388 for (uint32_t i = 0; i < aCandidates.Length(); ++i) {
389 nsIFrame* f = aCandidates[i];
390
391 bool preservesAxisAlignedRectangles = false;
392 nsRect borderBox = nsLayoutUtils::TransformFrameRectToAncestor(
393 f, nsRect(nsPoint(0, 0), f->GetSize()), aRoot,
394 &preservesAxisAlignedRectangles);
395 PET_LOG("Checking candidate %p with border box %s\n", f,
396 ToString(borderBox).c_str());
397 nsRegion region;
398 region.And(exposedRegion, borderBox);
399 if (region.IsEmpty()) {
400 PET_LOG(" candidate %p had empty hit region\n", f);
401 continue;
402 }
403
404 if (preservesAxisAlignedRectangles) {
405 // Subtract from the exposed region if we have a transform that won't make
406 // the bounds include a bunch of area that we don't actually cover.
407 SubtractFromExposedRegion(&exposedRegion, region);
408 }
409
410 nsAutoString labelTargetId;
411 if (aClickableAncestor &&
412 !IsDescendant(f, aClickableAncestor, &labelTargetId)) {
413 PET_LOG(" candidate %p is not a descendant of required ancestor\n", f);
414 continue;
415 }
416
417 if (aPrefs.mSearchType == SearchType::Clickable) {
418 nsIContent* clickableContent =
419 GetClickableAncestor(f, nsGkAtoms::body, &labelTargetId);
420 if (!aClickableAncestor && !clickableContent) {
421 PET_LOG(" candidate %p was not clickable\n", f);
422 continue;
423 }
424 } else if (aPrefs.mSearchType == SearchType::Touchable) {
425 nsIContent* touchableContent = GetTouchableAncestor(f, nsGkAtoms::body);
426 if (!touchableContent) {
427 PET_LOG(" candidate %p was not touchable\n", f);
428 continue;
429 }
430 }
431
432 // If our current closest frame is a descendant of 'f', skip 'f' (prefer
433 // the nested frame).
434 if (bestTarget && nsLayoutUtils::IsProperAncestorFrameCrossDoc(
435 f, bestTarget, aRoot.mFrame)) {
436 PET_LOG(" candidate %p was ancestor for bestTarget %p\n", f, bestTarget);
437 continue;
438 }
439 if (!aClickableAncestor && !nsLayoutUtils::IsAncestorFrameCrossDoc(
440 aRestrictToDescendants, f, aRoot.mFrame)) {
441 PET_LOG(" candidate %p was not descendant of restrictroot %p\n", f,
442 aRestrictToDescendants);
443 continue;
444 }
445
446 // distance is in appunits
447 float distance =
448 ComputeDistanceFromRegion(aPointRelativeToRootFrame, region);
449 nsIContent* content = f->GetContent();
450 if (content && content->IsElement() &&
451 content->AsElement()->State().HasState(
452 EventStates(NS_EVENT_STATE_VISITED))) {
453 distance *= aPrefs.mVisitedWeight / 100.0f;
454 }
455 if (distance < bestDistance) {
456 PET_LOG(" candidate %p is the new best\n", f);
457 bestDistance = distance;
458 bestTarget = f;
459 }
460 }
461 return bestTarget;
462 }
463
464 // Walk from aTarget up to aRoot, and return the first frame found with an
465 // explicit z-index set on it. If no such frame is found, aRoot is returned.
FindZIndexAncestor(const nsIFrame * aTarget,const nsIFrame * aRoot)466 static const nsIFrame* FindZIndexAncestor(const nsIFrame* aTarget,
467 const nsIFrame* aRoot) {
468 const nsIFrame* candidate = aTarget;
469 while (candidate && candidate != aRoot) {
470 if (candidate->ZIndex().valueOr(0) > 0) {
471 PET_LOG("Restricting search to z-index root %p\n", candidate);
472 return candidate;
473 }
474 candidate = candidate->GetParent();
475 }
476 return aRoot;
477 }
478
FindFrameTargetedByInputEvent(WidgetGUIEvent * aEvent,RelativeTo aRootFrame,const nsPoint & aPointRelativeToRootFrame,uint32_t aFlags)479 nsIFrame* FindFrameTargetedByInputEvent(
480 WidgetGUIEvent* aEvent, RelativeTo aRootFrame,
481 const nsPoint& aPointRelativeToRootFrame, uint32_t aFlags) {
482 using FrameForPointOption = nsLayoutUtils::FrameForPointOption;
483 EnumSet<FrameForPointOption> options;
484 if (aFlags & INPUT_IGNORE_ROOT_SCROLL_FRAME) {
485 options += FrameForPointOption::IgnoreRootScrollFrame;
486 }
487 nsIFrame* target = nsLayoutUtils::GetFrameForPoint(
488 aRootFrame, aPointRelativeToRootFrame, options);
489 PET_LOG(
490 "Found initial target %p for event class %s message %s point %s "
491 "relative to root frame %s\n",
492 target, ToChar(aEvent->mClass), ToChar(aEvent->mMessage),
493 ToString(aPointRelativeToRootFrame).c_str(),
494 ToString(aRootFrame).c_str());
495
496 EventRadiusPrefs prefs(aEvent->mClass);
497 if (!prefs.mEnabled || EventRetargetSuppression::IsActive()) {
498 PET_LOG("Retargeting disabled\n");
499 return target;
500 }
501
502 // Do not modify targeting for actual mouse hardware; only for mouse
503 // events generated by touch-screen hardware.
504 if (aEvent->mClass == eMouseEventClass && prefs.mTouchOnly &&
505 aEvent->AsMouseEvent()->mInputSource !=
506 MouseEvent_Binding::MOZ_SOURCE_TOUCH) {
507 PET_LOG("Mouse input event is not from a touch source\n");
508 return target;
509 }
510
511 // If the exact target is non-null, only consider candidate targets in the
512 // same document as the exact target. Otherwise, if an ancestor document has
513 // a mouse event handler for example, targets that are !GetClickableAncestor
514 // can never be targeted --- something nsSubDocumentFrame in an ancestor
515 // document would be targeted instead.
516 const nsIFrame* restrictToDescendants = [&]() -> const nsIFrame* {
517 if (target && target->PresContext() != aRootFrame.mFrame->PresContext()) {
518 return target->PresShell()->GetRootFrame();
519 }
520 return aRootFrame.mFrame;
521 }();
522
523 // If the target element inside an element with a z-index, restrict the
524 // search to other elements inside that z-index. This is a heuristic
525 // intended to help with a class of scenarios involving web modals or
526 // web popup type things. In particular it helps alleviate bug 1666792.
527 restrictToDescendants = FindZIndexAncestor(target, restrictToDescendants);
528
529 nsRect targetRect = GetTargetRect(aRootFrame, aPointRelativeToRootFrame,
530 restrictToDescendants, prefs, aFlags);
531 PET_LOG("Expanded point to target rect %s\n", ToString(targetRect).c_str());
532 AutoTArray<nsIFrame*, 8> candidates;
533 nsresult rv = nsLayoutUtils::GetFramesForArea(aRootFrame, targetRect,
534 candidates, options);
535 if (NS_FAILED(rv)) {
536 return target;
537 }
538
539 nsIContent* clickableAncestor = nullptr;
540 if (target) {
541 clickableAncestor = GetClickableAncestor(target, nsGkAtoms::body);
542 if (clickableAncestor) {
543 PET_LOG("Target %p is clickable\n", target);
544 // If the target that was directly hit has a clickable ancestor, that
545 // means it too is clickable. And since it is the same as or a
546 // descendant of clickableAncestor, it should become the root for the
547 // GetClosest search.
548 clickableAncestor = target->GetContent();
549 }
550 }
551
552 nsIFrame* closest =
553 GetClosest(aRootFrame, aPointRelativeToRootFrame, targetRect, prefs,
554 restrictToDescendants, clickableAncestor, candidates);
555 if (closest) {
556 target = closest;
557 }
558
559 PET_LOG("Final target is %p\n", target);
560
561 #ifdef DEBUG_FRAME_DUMP
562 // At verbose logging level, dump the frame tree to help with debugging.
563 // Note that dumping the frame tree at the top of the function may flood
564 // logcat on Android devices and cause the PET_LOGs to get dropped.
565 if (MOZ_LOG_TEST(sEvtTgtLog, LogLevel::Verbose)) {
566 if (target) {
567 target->DumpFrameTree();
568 } else {
569 aRootFrame.mFrame->DumpFrameTree();
570 }
571 }
572 #endif
573
574 if (!target || !prefs.mReposition) {
575 // No repositioning required for this event
576 return target;
577 }
578
579 // Take the point relative to the root frame, make it relative to the target,
580 // clamp it to the bounds, and then make it relative to the root frame again.
581 nsPoint point = aPointRelativeToRootFrame;
582 if (nsLayoutUtils::TRANSFORM_SUCCEEDED !=
583 nsLayoutUtils::TransformPoint(aRootFrame, RelativeTo{target}, point)) {
584 return target;
585 }
586 point = target->GetRectRelativeToSelf().ClampPoint(point);
587 if (nsLayoutUtils::TRANSFORM_SUCCEEDED !=
588 nsLayoutUtils::TransformPoint(RelativeTo{target}, aRootFrame, point)) {
589 return target;
590 }
591 // Now we basically undo the operations in GetEventCoordinatesRelativeTo, to
592 // get back the (now-clamped) coordinates in the event's widget's space.
593 nsView* view = aRootFrame.mFrame->GetView();
594 if (!view) {
595 return target;
596 }
597 LayoutDeviceIntPoint widgetPoint = nsLayoutUtils::TranslateViewToWidget(
598 aRootFrame.mFrame->PresContext(), view, point, aRootFrame.mViewportType,
599 aEvent->mWidget);
600 if (widgetPoint.x != NS_UNCONSTRAINEDSIZE) {
601 // If that succeeded, we update the point in the event
602 aEvent->mRefPoint = widgetPoint;
603 }
604 return target;
605 }
606
607 uint32_t EventRetargetSuppression::sSuppressionCount = 0;
608
EventRetargetSuppression()609 EventRetargetSuppression::EventRetargetSuppression() { sSuppressionCount++; }
610
~EventRetargetSuppression()611 EventRetargetSuppression::~EventRetargetSuppression() { sSuppressionCount--; }
612
IsActive()613 bool EventRetargetSuppression::IsActive() { return sSuppressionCount > 0; }
614
615 } // namespace mozilla
616