Files
palemoon27/layout/base/PositionedEventTargeting.cpp
T
roytam1 049b3235ac import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1207494 - Part 8: Remove use of expression closure from dom/identity/. r=ferjm (34fac889f8)
- minor crash thing (13fe2827c2)
- Bug 1243359 - initialize mScrollSeriesNumber in all ScrollWheelInput constructors. r=roc (94163d8eca)
- fix misspatch (b380a7bbe4)
- Bug 1207412 - Make SystemTimeConverter use TimeStamp::Now() when converting times; r=karlt (f408549605)
- Bug 1212102 - Drop unnecessary assertion comparing timestamps in SystemTimeConverter; r=karlt (1efaa04b3f)
- Bug 1241302 - Slightly modernize this code. r=jst (c1e97bc069)
- bug 1216916 clean up when InvokeDragSessionWithImage/Selection() fails r=roc (9cdf71b717)
- Bug 1231329 - run ConvertToUnscaledDevPixels if *aPresContext is valid. r=roc (d10f23633b)
- Bug 1245927: Innerize before creating DOM files from the file picker. r=baku (8754128362)
- Bug 1155214 - Mark nsIBidiKeyboard as builtinclass; r=mrbkap (2d00326d2b)
- reorder (c3c1ba92c9)
- Bug 1236566 - add override declarations for widget/windows/GfxInfo.h; r=roc (940b40ed91)
- Bug 1242659: Part 1. More information on the mismatches. r=jrmuizel (78331ddad2)
- Block some Radeon drivers that crash on D3D9. (bug 1213107, r=jrmuizel) (482b66d313)
- Bug 1203199 - Blacklist DXVA on some older intel drivers for causing crashes. r=jrmuizel (f1827d4498)
- Bug 1203199 - Fix driver range with blacklist to avoid blacklisting other OSes. (2c2d547296)
- Bug 1203199 - Bustage fix. CLOSED TREE (3233d407f3)
- Bug 1178385. Enable DXVA on the G45 r=ajones (3c59a58a15)
- Bug 1188442 IMMHandler::GetSelection() should use static Selection instance when IME doesn't have focus and return its or mSelection's reference r=emk (5cc4b30433)
- Bug 1238899 Create hidden native caret for ATOK at composing in windowless plugin r=m_kato (40ef5bb4aa)
- Bug 1257919 part 1. Kill off nsIXSLTException. r=khuey (11f37643f2)
- Bug 1242072 - Change implementation of BaseProxyHandler::get() to follow ES6 [[Get]] specification. r=jorendorff (094a67f284)
- Bug 489636 - Add a GC u-bench test for property tree splitting via deletion; r=sfink (9282fec25f)
- Bug 1257919 part 2. Make nsIException and nsIStackFrame builtinclass, so we can start using [implicit_jscontext] on them. r=khuey (0e65fb8554)
- Bug 1257919 part 3. Make the various toString methods on exceptions take an explicit JSContext. r=khuey (b342fb4930)
- Bug 1257919 part 4. Stop returning StackFrame instances from exceptions::CreateStack. C++ callers of GetCurrentJSStack or exceptions::CreateStack always check for null anyway, and none of them seem to want this non-JS thing. r=khuey (d34036ccf9)
- Bug 1257919 part 5. Get rid of the now-unused StackFrame class. r=khuey (aa13af0dfe)
- Bug 1141222 - Create ScriptError with stack from Cu.reportError. r=bholley (b83ad26aa0)
- Bug 1208641 - Extract stack from DOM/XPC exception. r=bholley (e382b5f48c)
- Bug 1254380 part 1. Find the relevant window when the compartment we've got is an addon sandbox compartment in AutoJSAPI exception/warning reporting code. r=bholley (4b1f6c64a9)
- Bug 1250630 - remove PBackgroundTest and ifdef ENABLE_TEST blocks. r=khuey (d7b36860a3)
- Bug 1250963 part 1. Change NotifyRunnable::Dispatch to not require a JSContext. r=khuey (48e03c2fc2)
- Bug 1250963 part 2. Remove the unused JSContext argument of WorkerPrivate::ModifyBusyCount. r=khuey (0f5ca42be1)
- Bug 1250291 part 1. Stop pretending to report exceptions in MainThreadStopSyncLoopRunnable::PostDispatch. r=khuey (6e1c81cc06)
- Bug 1250291 part 2. Stop pretending to report exceptions in MainThreadWorkerSyncRunnable::PostDispatch. r=khuey (f3d846ea31)
- Bug 1250291 part 3. Stop pretending to report exceptions in WorkerDebuggerRunnable::PostDispatch. r=khuey (10bc1710d1)
- Bug 1250975. Stop passing a JSContext argument to WorkerRunnable::PreDispatch and its overrides. r=khuey (71ab9046f0)
- Bug 1255298. Just pass through the JSContext when passing through the NotificationOptions in notification code. r=wchen (552ae8e33e)
- Bug 1250185 part 2. Remove some JSContext stuff that's no longer needed in Notification code. r=khuey (20b99ef28b)
- Bug 1251045 part 8. Remove the JSContext argument from some nsINotificationStorageCallback methods. r=khuey (170c4afabc)
- Bug 1227015 P7 Supress unused ErrorResult exception if the worker runnable failed to dispatch. r=catalinb (23a3cc6f45)
- Bug 1251045 part 3. Remove the JSContext argument of WorkerRunnable::PostDispatch and its overrides. r=khuey (6a666d1a4a)
- Bug 1251045 part 2. Remove the JSContext argument of ModifyBusyCountFromWorker. r=khuey (105bc4f59e)
- Bug 1252130. Remove unnecessary JSContext argument from NotificationWorkerRunnable::WorkerRunInternal. r=khuey (642727f6f6)
- Bug 1252127. Remove unnecessary JSContext argument from PromiseWorkerProxy::CleanUp. r=khuey (339e1157d1)
- Bug 1251045 part 1. Make it possible to dispatch a ModifyBusyCountRunnable without a JSContext. r=khuey (665c1f81b4)
- Bug 1251045 part 4. Remove the JSContext argument of WorkerRunnable::Dispatch. r=khuey (6c5cdab2b7)
- Bug 1250185 part 1. nsIStructuredCloneContainer.initFromBase64 doesn't need a JSContext argument. r=khuey (d63a219209)
- fix (773c0393aa)
- Bug 1251045 part 5. Remove the JSContext argument from WorkerPrivateParent::Freeze/Thaw. r=khuey (cd419bfd2c)
- Bug 1251045 part 6. Remove the JSContext argument from some worker debugger methods that no longer need it. r=khuey (abcc437cb9)
- Bug 1251045 part 7. Remove the JSContext argument from some worker methods that no longer need it. r=khuey (3ddcbca08c)
- Bug 1249652 part 1. Add a method on ErrorResult to steal an exception, if any, from a JSContext. r=khuey (9c07f5044b)
- Bug 1229071 - importScripts should throw the correct error result in case the loading of one of scripts fails, r=bz (cd37645d76)
- Bug 1229970 Abort script loading start requests if a load has been canceled. r=khuey (a44d9128ca)
- Bug 1233171 Cancel channel when ScriptLoader is aborted during service worker script load. r=khuey (3b6ceafec7)
- Bug 1249351 part 1. When doing importScripts of multiple scripts in a service worker, make sure to track the cache streams per-loadinfo, instead of trying to make them all wait on the same stream. r=bkelly (e1ccea9685)
- Bug 1157544 - Fix a typo in the test; r=baku (8c0bf8f504)
- Bug 1249351 part 2. Clean up test_importscript.html and add multiple-url importScript() case. r=bz (52b0a31032)
- Bug 1249652 part 2. ScriptExecutorRunnable::WorkerRun should immediately move JS exceptions to its ErrorResult instead of allowing them to linger on the JSContext. r=baku,khuey (f628d3c8ba)
- Bug 1249652 part 3. Simplify way we handle canceling when ScriptLoaderRunnable::RunInternal fails by canceling things with its actual failure code, so we don't have to guess which failed loads are actual failures and which are just canceled via this mechanism. r=baku,khuey (388543fbc3)
- Bug 1251369. Use an AutoJSAPI that reports its own exceptions around the main runloop in workers. r=khuey (28b33287cd)
- Bug 1251518. Fix js::ErrorReportToString to make a bit more sense, and change worker code to not use it anyway, so it matches the mainthread code. r=bholley,terrence (a48a40de90)
- Bug 1254380 part 2. Go ahead and log the stack from our exception in AutoJSAPI::ReportException even if we don't have a window. r=bholley (64532b6017)
- Bug 1212328 - Clean up some JSErrorReport-related code. r=Waldo,bz (d5aa611edc)
- Bug 1255192 part 1. Remove the JSContext argument of JS::ExceptionStackOrNull. r=bholley (39b631d5ad)
- bug 1252687 - make the ctor for CycleCollectorStats constexpr r=mccr8 (9e8168d8ac)
- Bug 1254380 part 3. Skip firing error events for mainthread out of memory exceptions via AutoJSAPI::ReportException. r=bholley (d5e4e7dc29)
- Bug 1254230 kinda-fix. Make sure to never send script errors with stacks attached to the console service if the associated windows have already had FreeInnerObjects called on them. r=bholley (8c379fe0e0)
- Bug 1255192 part 2. Clean up the JSContext usage around xpc::FindExceptionStackForConsoleReport now that it just needs a JSContext for rooting. r=bholley (cade862491)
- Bug 1255201. Improve the stack handling in nsXPCComponents_Utils::ReportError for the DOMException case to include the stack from the DOMException. r=bholley (fc6c065284)
- Bug 1257919 part 6. Make the filename getter on JSStackFrame take an explicit JSContext. r=khuey (cde115b789)
- Bug 1257919 part 7. Make the name getter on JSStackFrame take an explicit JSContext. r=khuey (d7466e9eab)
- Bug 1257919 part 8. Make the line/column number getters on JSStackFrame take an explicit JSContext. r=khuey (b8766b98b2)
- Bug 1257919 part 9. Make the asyncCause/asyncCaller getters on JSStackFrame take an explicit JSContext. r=khuey (b776ff9c6d)
- Bug 1257919 part 10. Make the caller and formattedStack getters on JSStackFrame take an explicit JSContext. r=khuey (dc4d3d9091)
- Bug 1252091. Add/RemoveFeature don't need a JSContext argument. r=khuey (5be6253a67)
- Bug 1252123. Remove some unnecessary JSContext arguments from worker ScriptLoader methods. r=khuey (1657a35268)
- Bug 1255181. Remove AutoJSAPI::InitWithLegacyErrorReporting. r=bholley (5ee7ac506e)
- Bug 1254847 part 1. Take ownership of error reporting on the AutoEntryScript in nsXPCWrappedJSClass::DelegatedQueryInterface. r=bholley (62d987b030)
- make style wrong again.... (fa4e6cfbc1)
- Bug 1254847 part 2. Change nsJSNPRuntime to always use AutoEntryScript and always take ownership of error reporting. r=bholley (d24cb80622)
- Bug 1251655 - Remove support for JavaScript-global-constructor-prototype-alias. r=bz. (2b354ea423)
- Bug 1251655 - Remove support for JavaScript-DOM-class and JavaScript-DOM-interface. r=bz. (dd6786ea57)
- Bug 1251275. Switch to using an AutoEntryScript in WorkerPrivate::RunExpiredTimeouts. r=khuey (f10d1b0dec)
- Bug 1072144 part 1. Just release-assert that Promise::Resolve does not fail in service worker code. It can only do that on OOM or overrecursion anyway, and overrecursion is not likely if we're coming right off a runnable. r=khuey (ba4c89a3bc)
- Bug 1072144 part 2. When UnregisterWorker tries to ScheduleWorker and that throws, just suppress the exception: there is no good place to report it anyway. r=khuey (ca563ec5cd)
- Bug 1072144 part 3. Hoist the exception reporting out of WorkerRunnable::PostRun into WorkerRunnable::Run and make it unconditional. r=khuey (9914acd4a6)
- Bug 1252221. When GetOrCreateGlobalScope fails while trying to run a ScriptExecutorRunnable::WorkerRun, just suppress the exception, because there is no way to report it without a compartment to work with. r=khuey (abcc9df148)
- Bug 1072144 part 4. Add a WorkerRunnable::PreRun so that we can move worker global creation to it and always have an AutoEntryScript by the time we're evaluating the main worker script. r=khuey (007b528868)
- Bug 1251276 part 1. Change WorkerPrivate::CancelAllTimeouts to no longer call RunExpiredTimeouts. r=khuey (6b937370a1)
- Bug 1251276 part 2. Remove the JSContext argument of WorkerPrivate::CancelAllTimeouts. r=khuey (336b788e03)
- Bug 1251380. Change things so that WorkerPrivate::NotifyInternal (hopefully) never throws. r=khuey (1d4863f83a)
- Bug 1254846. Add an AutoEntryScript constructor that takes a JSObject instead of an nsIGlobalObject, for convenience. r=bholley (693857f9b0)
- Bug 1255706 part 1. Remove JSContext argument from WorkerPrivate constructor. r=khuey (0486bdb01c)
- Bug 1255706 part 2. Remove JSContext argument from WorkerPrivate::Terminate. r=khuey (f0b62de092)
- Bug 1257568. Remove the JSContext argument of WorkerPrivate::Kill. r=khuey (ebe7d247b5)
- Bug 1252189. Remove the unnecessary JSContext argument from WorkerPrivate::FreezeInternal/ThawInternal. r=khuey (22b137b05e)
- Bug 1119490 - Expose the URL constructor to WorkerDebuggerGlobalScope;r=khuey (6f4fc13e1e)
- Bug 1241841 - Clear the worker's debugger event queue before destroying its context;r=khuey (a1e8dd4b2d)
- Bug 1249950 - Add Performance Markers for MessagePort - patch 1 - remove non-useful 'explicit', r=smaug (8a014b53e6)
- Bug 1249950 - Add Performance Markers for MessagePort - patch 2, r=smaug, r=vporof (560caf0ae1)
- bug 1250486 - make the ComponentsSH ctor constexpr r=bz (1c441dbb0f)
- Bug 1257032: Make files in dom/workers actually build without unification. r=baku (6ab4ae0b65)
- Bug 1241522 - handle OOM in nsExpatDriver::HandleCharacterData; r=hsivonen (b652220cdc)
- Bug 1219482: Replace PRLogModuleInfo with LazyLogModule in various files.r=benjamin (5fd5e8dbc8)
- Bug 1238545 - Remove nsISimpleUnicharStreamFactory; r=froydnj (f0018c5b16)
- Bug 1257335. Replace some AutoSafeJSContext uses with AutoJSAPI or AutoJSContext uses. r=bholley (7baf79deb7)
- Bug 1247635 - Unify PostMessageRunnable and DispatchEventRunnable in MessagePort.cpp, r=smaug (df2765c215)
- Bug 1250572 - Force a parent object in MessagePort/Channel and in StructuredCloneHolder, r=smaug (2a929d59d1)
- Bug 1255375 - MessagePort should not leak if DispatchMessage() fails, r=smaug (0a5cdebfb0)
- Bug 1251272. Remove the dead code in ReportErrorRunnable::ReportError that could fail, and make it infallible. r=khuey (89e80694d0)
- Bug 1072144 part 5. Stop fiddling with compartments on the JSContext before calling PostRun in WorkerRunnable::Run. Add some documentation explaining what's going on. r=khuey (91f4bb6a7c)
- Bug 1072144 part 6. Switch WorkerRunnable::Run to calling TakeOwnershipOfErrorReporting on its AutoJSAPI/AutoEntryScript and remove the remaining JS_ReportPendingException callers in worker code. r=khuey (405d9e0282)
- Bug 1179548 - Close the windows opened in private browsing worker tests; r=baku (acf3430b69)
- Bug 1179753 - Use pushPrefEnv more in worker tests; r=baku (4bfd949c72)
- Bug 1134224 - More test for test_bug1132395.html, r=ehsan (626eb100cd)
- Bug 1134224 - onerror for test_bug1132395.html, r=ehsan (147195f57e)
- Bug 1207635 - get rid of dom.workers.sharedWorkers.enabled pref, r=khuey (22fe2965c6)
- Bug 1252592. JS warnings should not trigger error events on shared workers. r=khuey (7f05c2c00d)
- Bug 1251308; r=luke (3cbec95738)
- Bug 1246838 - Handle const qualifiers and references better in Variant. r=waldo (30da6e3ebf)
- Bug 1254565 - Allow passing matchers as rvalues to Variant::match. r=froydnj (1dd799fb0a)
- Bug 1246841 - Allow construction of Variant values using type inference. r=waldo (6ba3e6704c)
- Bug 1250666 - Forward Variant's move constructor argument correctly to the underlying variant type. r=waldo (7353a53bf0)
- Bug 1252185. Remove the dead "target" variable from CloseEventRunnable::WorkerRun. r=khuey (be172da10b)
- Bug 1253059: Use fallible allocation in the worker error reporter. r=baku (963222bdd4)
- Bug 1253199 - MessagePort should handle the dispatching a message when the parent window is gone, r=smaug (d552e3cd9e)
- Bug 1252839 - Remove some if stmt after allocation with 'new' - patch 2, r=bz (3c7eb959bc)
- Bug 1252839 - Remove some if stmt after allocation with 'new' - patch 1, r=bz (85067dbfb6)
- Bug 1254855. Switch AutoEntryScripts in nsDirectoryViewer to take ownership of error reporting. r=bholley (8c10532323)
- Bug 1252565 part 1. Push the script environment preparer bits up from XPCJSRuntime to CycleCollectedJSRuntime, because we need them on workers to do ctypes on workers properly. r=bholley (aecf2595dd)
- Bug 1252565 part 2. Make dom::WarningOnlyErrorReporter handle workers. r=bholley (f415b8868b)
- Bug 1244222 - Check for function interfaces in DelegatedQueryInterface. r=bz (d213eec83c)
- Bug 1254393. Take ownership of error reporting on the AutoEntryScript in nsXPCWrappedJSClass::CallMethod. r=bholley (4765b501c0)
- Bug 1251769 - Remove remaining references to MOZILLA_XPCOMRT_API from mfbt. r=froydnj (236adc1d4c)
- Bug 1247835 (part 0) - Minor comment and style tweaks in BinarySearch.h. r=luke. (db04793721)
- Bug 1244074 - Part 1: Move SheetParsingMode to a separate file. r=dholbert (290adaadea)
- Bug 1244074 - Part 2: Add HandleRefPtr for refcounting StyleSheetHandles. r=dholbert r=waldo (8549b24392)
- Bug 1244068 - Part 1: Add enum to represent the style system backend type. r=dholbert (c2e53feaf2)
- Bug 1244068 - Part 2: Add skeleton ServoStyleSet and a StyleSetHandle smart pointer. r=dholbert (71a5c28629)
- Bug 1244068 - Part 3: Factor out nsStyleSet getting in RestyleManager/ElementRestyler. r=dholbert (9e9f4f2e80)
- Bug 1245406: In ReflowBlockFrame, use Maybe<> to destroy & reconstruct a stack-allocated object, instead of an explicit call to destructor & placement 'new'. r=dbaron (d36858b818)
- Bug 1244068 - Part 4: Use StyleSetHandle instead of concrete style set class in most places. r=dholbert (93f9bcf799)
- Bug 1244074 - Part 3: Add skeleton ServoStyleSheet and a StyleSheetHandle smart pointer. r=dholbert (5b4fbdce38)
- Bug 1195173 - Apply CSP to preloaded styles within layout/style/Loader.cpp (r=bz) (d1ba920fd3)
- Bug 1245681 - Fix addOverrideStyleSheet. r=bz (64099eac73)
- Bug 1244074 - Part 4: Use StyleSheetHandle instead of concrete style sheet class in most places. r=dholberti (867470ac83)
- Bug 1246013 (part 1) - Store a copy of the ETLDEntry directly in DomainEntry instead of a pointer to it. r=jduell. (587b3a9fb7)
- Bug 1246013 (part 2) - Change "explicit/xpcom/effective-TLD-service" path to the more sensible "explicit/network/effective-TLD-service". r=jduell. (2e0df6f28f)
- Bug 1247835 (part 1) - Use binary search instead of a hash table in nsEffectiveTLDService. r=jduell. (685dae01c0)
- Bug 1257121 part 1 - Use struct for passing some params of font metrics. r=jfkthame (1dfd7a7429)
- Bug 1257121 part 2 - Merge nsFontMetrics::Init to the constructor and remove unused failure handling code. r=jfkthame (0cdc441511)
- Bug 1257121 part 3 - Add GetInflatedFontMetricsForFrame function to simplify a common use pattern. r=jfkthame (d9630ebd1b)
- Bug 1257121 part 4 - Use return value rather than out param to retur font metrics. r=jfkthame (c9a5b1d1dd)
- Bug 1257121 part 5 - Make nsDeviceContext::mFontCache a RefPtr. r=jfkthame (9c53238a6a)
2024-01-29 15:26:23 +08:00

653 lines
25 KiB
C++

/* 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/. */
#include "PositionedEventTargeting.h"
#include "mozilla/EventListenerManager.h"
#include "mozilla/EventStates.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/Preferences.h"
#include "nsLayoutUtils.h"
#include "nsGkAtoms.h"
#include "nsFontMetrics.h"
#include "nsPrintfCString.h"
#include "mozilla/dom/Element.h"
#include "nsRegion.h"
#include "nsDeviceContext.h"
#include "nsIFrame.h"
#include <algorithm>
#include "LayersLogging.h"
// If debugging this code you may wish to enable this logging, and also
// uncomment the DumpFrameTree call near the bottom of the file.
#define PET_LOG(...)
// #define PET_LOG(...) printf_stderr("PET: " __VA_ARGS__);
namespace mozilla {
/*
* The basic goal of FindFrameTargetedByInputEvent() is to find a good
* target element that can respond to mouse events. Both mouse events and touch
* events are targeted at this element. Note that even for touch events, we
* check responsiveness to mouse events. We assume Web authors
* designing for touch events will take their own steps to account for
* inaccurate touch events.
*
* GetClickableAncestor() encapsulates the heuristic that determines whether an
* element is expected to respond to mouse events. An element is deemed
* "clickable" if it has registered listeners for "click", "mousedown" or
* "mouseup", or is on a whitelist of element tags (<a>, <button>, <input>,
* <select>, <textarea>, <label>), or has role="button", or is a link, or
* is a suitable XUL element.
* Any descendant (in the same document) of a clickable element is also
* deemed clickable since events will propagate to the clickable element from its
* descendant.
*
* If the element directly under the event position is clickable (or
* event radii are disabled), we always use that element. Otherwise we collect
* all frames intersecting a rectangle around the event position (taking CSS
* transforms into account) and choose the best candidate in GetClosest().
* Only GetClickableAncestor() candidates are considered; if none are found,
* then we revert to targeting the element under the event position.
* We ignore candidates outside the document subtree rooted by the
* document of the element directly under the event position. This ensures that
* event listeners in ancestor documents don't make it completely impossible
* to target a non-clickable element in a child document.
*
* When both a frame and its ancestor are in the candidate list, we ignore
* the ancestor. Otherwise a large ancestor element with a mouse event listener
* and some descendant elements that need to be individually targetable would
* disable intelligent targeting of those descendants within its bounds.
*
* GetClosest() computes the transformed axis-aligned bounds of each
* candidate frame, then computes the Manhattan distance from the event point
* to the bounds rect (which can be zero). The frame with the
* shortest distance is chosen. For visited links we multiply the distance
* by a specified constant weight; this can be used to make visited links
* more or less likely to be targeted than non-visited links.
*/
struct EventRadiusPrefs
{
uint32_t mVisitedWeight; // in percent, i.e. default is 100
uint32_t mSideRadii[4]; // TRBL order, in millimetres
bool mEnabled;
bool mRegistered;
bool mTouchOnly;
bool mRepositionEventCoords;
bool mTouchClusterDetectionEnabled;
bool mSimplifiedClusterDetection;
uint32_t mLimitReadableSize;
uint32_t mKeepLimitSizeForCluster;
};
static EventRadiusPrefs sMouseEventRadiusPrefs;
static EventRadiusPrefs sTouchEventRadiusPrefs;
static const EventRadiusPrefs*
GetPrefsFor(EventClassID aEventClassID)
{
EventRadiusPrefs* prefs = nullptr;
const char* prefBranch = nullptr;
if (aEventClassID == eTouchEventClass) {
prefBranch = "touch";
prefs = &sTouchEventRadiusPrefs;
} else if (aEventClassID == eMouseEventClass) {
// Mostly for testing purposes
prefBranch = "mouse";
prefs = &sMouseEventRadiusPrefs;
} else {
return nullptr;
}
if (!prefs->mRegistered) {
prefs->mRegistered = true;
nsPrintfCString enabledPref("ui.%s.radius.enabled", prefBranch);
Preferences::AddBoolVarCache(&prefs->mEnabled, enabledPref.get(), false);
nsPrintfCString visitedWeightPref("ui.%s.radius.visitedWeight", prefBranch);
Preferences::AddUintVarCache(&prefs->mVisitedWeight, visitedWeightPref.get(), 100);
static const char prefNames[4][9] =
{ "topmm", "rightmm", "bottommm", "leftmm" };
for (int32_t i = 0; i < 4; ++i) {
nsPrintfCString radiusPref("ui.%s.radius.%s", prefBranch, prefNames[i]);
Preferences::AddUintVarCache(&prefs->mSideRadii[i], radiusPref.get(), 0);
}
if (aEventClassID == eMouseEventClass) {
Preferences::AddBoolVarCache(&prefs->mTouchOnly,
"ui.mouse.radius.inputSource.touchOnly", true);
} else {
prefs->mTouchOnly = false;
}
nsPrintfCString repositionPref("ui.%s.radius.reposition", prefBranch);
Preferences::AddBoolVarCache(&prefs->mRepositionEventCoords, repositionPref.get(), false);
nsPrintfCString touchClusterPref("ui.zoomedview.enabled", prefBranch);
Preferences::AddBoolVarCache(&prefs->mTouchClusterDetectionEnabled, touchClusterPref.get(), false);
nsPrintfCString simplifiedClusterDetectionPref("ui.zoomedview.simplified", prefBranch);
Preferences::AddBoolVarCache(&prefs->mSimplifiedClusterDetection, simplifiedClusterDetectionPref.get(), false);
nsPrintfCString limitReadableSizePref("ui.zoomedview.limitReadableSize", prefBranch);
Preferences::AddUintVarCache(&prefs->mLimitReadableSize, limitReadableSizePref.get(), 8);
nsPrintfCString keepLimitSize("ui.zoomedview.keepLimitSize", prefBranch);
Preferences::AddUintVarCache(&prefs->mKeepLimitSizeForCluster, keepLimitSize.get(), 16);
}
return prefs;
}
static bool
HasMouseListener(nsIContent* aContent)
{
if (EventListenerManager* elm = aContent->GetExistingListenerManager()) {
return elm->HasListenersFor(nsGkAtoms::onclick) ||
elm->HasListenersFor(nsGkAtoms::onmousedown) ||
elm->HasListenersFor(nsGkAtoms::onmouseup);
}
return false;
}
static bool gTouchEventsRegistered = false;
static int32_t gTouchEventsEnabled = 0;
static bool
HasTouchListener(nsIContent* aContent)
{
EventListenerManager* elm = aContent->GetExistingListenerManager();
if (!elm) {
return false;
}
if (!gTouchEventsRegistered) {
Preferences::AddIntVarCache(&gTouchEventsEnabled,
"dom.w3c_touch_events.enabled", gTouchEventsEnabled);
gTouchEventsRegistered = true;
}
if (!gTouchEventsEnabled) {
return false;
}
return elm->HasListenersFor(nsGkAtoms::ontouchstart) ||
elm->HasListenersFor(nsGkAtoms::ontouchend);
}
static bool
IsDescendant(nsIFrame* aFrame, nsIContent* aAncestor, nsAutoString* aLabelTargetId)
{
for (nsIContent* content = aFrame->GetContent(); content;
content = content->GetFlattenedTreeParent()) {
if (aLabelTargetId && content->IsHTMLElement(nsGkAtoms::label)) {
content->GetAttr(kNameSpaceID_None, nsGkAtoms::_for, *aLabelTargetId);
}
if (content == aAncestor) {
return true;
}
}
return false;
}
static nsIContent*
GetClickableAncestor(nsIFrame* aFrame, nsIAtom* stopAt = nullptr, nsAutoString* aLabelTargetId = nullptr)
{
// Input events propagate up the content tree so we'll follow the content
// ancestors to look for elements accepting the click.
for (nsIContent* content = aFrame->GetContent(); content;
content = content->GetFlattenedTreeParent()) {
if (stopAt && content->IsHTMLElement(stopAt)) {
break;
}
if (HasTouchListener(content) || HasMouseListener(content)) {
return content;
}
if (content->IsAnyOfHTMLElements(nsGkAtoms::button,
nsGkAtoms::input,
nsGkAtoms::select,
nsGkAtoms::textarea)) {
return content;
}
if (content->IsHTMLElement(nsGkAtoms::label)) {
if (aLabelTargetId) {
content->GetAttr(kNameSpaceID_None, nsGkAtoms::_for, *aLabelTargetId);
}
return content;
}
// Bug 921928: we don't have access to the content of remote iframe.
// So fluffing won't go there. We do an optimistic assumption here:
// that the content of the remote iframe needs to be a target.
if (content->IsHTMLElement(nsGkAtoms::iframe) &&
content->AttrValueIs(kNameSpaceID_None, nsGkAtoms::mozbrowser,
nsGkAtoms::_true, eIgnoreCase) &&
content->AttrValueIs(kNameSpaceID_None, nsGkAtoms::Remote,
nsGkAtoms::_true, eIgnoreCase)) {
return content;
}
// See nsCSSFrameConstructor::FindXULTagData. This code is not
// really intended to be used with XUL, though.
if (content->IsAnyOfXULElements(nsGkAtoms::button,
nsGkAtoms::checkbox,
nsGkAtoms::radio,
nsGkAtoms::autorepeatbutton,
nsGkAtoms::menu,
nsGkAtoms::menubutton,
nsGkAtoms::menuitem,
nsGkAtoms::menulist,
nsGkAtoms::scrollbarbutton,
nsGkAtoms::resizer)) {
return content;
}
static nsIContent::AttrValuesArray clickableRoles[] =
{ &nsGkAtoms::button, &nsGkAtoms::key, nullptr };
if (content->FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::role,
clickableRoles, eIgnoreCase) >= 0) {
return content;
}
if (content->IsEditable()) {
return content;
}
nsCOMPtr<nsIURI> linkURI;
if (content->IsLink(getter_AddRefs(linkURI))) {
return content;
}
}
return nullptr;
}
static nscoord
AppUnitsFromMM(nsIFrame* aFrame, uint32_t aMM)
{
nsPresContext* pc = aFrame->PresContext();
float result = float(aMM) *
(pc->DeviceContext()->AppUnitsPerPhysicalInch() / MM_PER_INCH_FLOAT);
return NSToCoordRound(result);
}
/**
* Clip aRect with the bounds of aFrame in the coordinate system of
* aRootFrame. aRootFrame is an ancestor of aFrame.
*/
static nsRect
ClipToFrame(nsIFrame* aRootFrame, nsIFrame* aFrame, nsRect& aRect)
{
nsRect bound = nsLayoutUtils::TransformFrameRectToAncestor(
aFrame, nsRect(nsPoint(0, 0), aFrame->GetSize()), aRootFrame);
nsRect result = bound.Intersect(aRect);
return result;
}
static nsRect
GetTargetRect(nsIFrame* aRootFrame, const nsPoint& aPointRelativeToRootFrame,
nsIFrame* aRestrictToDescendants, const EventRadiusPrefs* aPrefs,
uint32_t aFlags)
{
nsMargin m(AppUnitsFromMM(aRootFrame, aPrefs->mSideRadii[0]),
AppUnitsFromMM(aRootFrame, aPrefs->mSideRadii[1]),
AppUnitsFromMM(aRootFrame, aPrefs->mSideRadii[2]),
AppUnitsFromMM(aRootFrame, aPrefs->mSideRadii[3]));
nsRect r(aPointRelativeToRootFrame, nsSize(0,0));
r.Inflate(m);
if (!(aFlags & INPUT_IGNORE_ROOT_SCROLL_FRAME)) {
// Don't clip this rect to the root scroll frame if the flag to ignore the
// root scroll frame is set. Note that the GetClosest code will still enforce
// that the target found is a descendant of aRestrictToDescendants.
r = ClipToFrame(aRootFrame, aRestrictToDescendants, r);
}
return r;
}
static float
ComputeDistanceFromRect(const nsPoint& aPoint, const nsRect& aRect)
{
nscoord dx = std::max(0, std::max(aRect.x - aPoint.x, aPoint.x - aRect.XMost()));
nscoord dy = std::max(0, std::max(aRect.y - aPoint.y, aPoint.y - aRect.YMost()));
return float(NS_hypot(dx, dy));
}
static float
ComputeDistanceFromRegion(const nsPoint& aPoint, const nsRegion& aRegion)
{
MOZ_ASSERT(!aRegion.IsEmpty(), "can't compute distance between point and empty region");
float minDist = -1;
for (auto iter = aRegion.RectIter(); !iter.Done(); iter.Next()) {
float dist = ComputeDistanceFromRect(aPoint, iter.Get());
if (dist < minDist || minDist < 0) {
minDist = dist;
}
}
return minDist;
}
// Subtract aRegion from aExposedRegion as long as that doesn't make the
// exposed region get too complex or removes a big chunk of the exposed region.
static void
SubtractFromExposedRegion(nsRegion* aExposedRegion, const nsRegion& aRegion)
{
if (aRegion.IsEmpty())
return;
nsRegion tmp;
tmp.Sub(*aExposedRegion, aRegion);
// Don't let *aExposedRegion get too complex, but don't let it fluff out to
// its bounds either. Do let aExposedRegion get more complex if by doing so
// we reduce its area by at least half.
if (tmp.GetNumRects() <= 15 || tmp.Area() <= aExposedRegion->Area()/2) {
*aExposedRegion = tmp;
}
}
// Search in the list of frames aCandidates if the element with the id "aLabelTargetId"
// is present.
static bool IsElementPresent(nsTArray<nsIFrame*>& aCandidates, const nsAutoString& aLabelTargetId)
{
for (uint32_t i = 0; i < aCandidates.Length(); ++i) {
nsIFrame* f = aCandidates[i];
nsIContent* aContent = f->GetContent();
if (aContent && aContent->IsElement()) {
if (aContent->GetID() && aLabelTargetId == nsAtomString(aContent->GetID())) {
return true;
}
}
}
return false;
}
static bool
IsLargeElement(nsIFrame* aFrame, const EventRadiusPrefs* aPrefs)
{
uint32_t keepLimitSizeForCluster = aPrefs->mKeepLimitSizeForCluster;
nsSize frameSize = aFrame->GetSize();
nsPresContext* pc = aFrame->PresContext();
nsIPresShell* presShell = pc->PresShell();
float cumulativeResolution = presShell->GetCumulativeResolution();
if ((pc->AppUnitsToGfxUnits(frameSize.height) * cumulativeResolution) > keepLimitSizeForCluster &&
(pc->AppUnitsToGfxUnits(frameSize.width) * cumulativeResolution) > keepLimitSizeForCluster) {
return true;
}
return false;
}
static nsIFrame*
GetClosest(nsIFrame* aRoot, const nsPoint& aPointRelativeToRootFrame,
const nsRect& aTargetRect, const EventRadiusPrefs* aPrefs,
nsIFrame* aRestrictToDescendants, nsIContent* aClickableAncestor,
nsTArray<nsIFrame*>& aCandidates, int32_t* aElementsInCluster)
{
std::vector<nsIContent*> mContentsInCluster; // List of content elements in the cluster without duplicate
nsIFrame* bestTarget = nullptr;
// Lower is better; distance is in appunits
float bestDistance = 1e6f;
nsRegion exposedRegion(aTargetRect);
for (uint32_t i = 0; i < aCandidates.Length(); ++i) {
nsIFrame* f = aCandidates[i];
PET_LOG("Checking candidate %p\n", f);
bool preservesAxisAlignedRectangles = false;
nsRect borderBox = nsLayoutUtils::TransformFrameRectToAncestor(f,
nsRect(nsPoint(0, 0), f->GetSize()), aRoot, &preservesAxisAlignedRectangles);
nsRegion region;
region.And(exposedRegion, borderBox);
if (region.IsEmpty()) {
PET_LOG(" candidate %p had empty hit region\n", f);
continue;
}
if (preservesAxisAlignedRectangles) {
// Subtract from the exposed region if we have a transform that won't make
// the bounds include a bunch of area that we don't actually cover.
SubtractFromExposedRegion(&exposedRegion, region);
}
nsAutoString labelTargetId;
if (aClickableAncestor && !IsDescendant(f, aClickableAncestor, &labelTargetId)) {
PET_LOG(" candidate %p is not a descendant of required ancestor\n", f);
continue;
}
nsIContent* clickableContent = GetClickableAncestor(f, nsGkAtoms::body, &labelTargetId);
if (!aClickableAncestor && !clickableContent) {
PET_LOG(" candidate %p was not clickable\n", f);
continue;
}
// If our current closest frame is a descendant of 'f', skip 'f' (prefer
// the nested frame).
if (bestTarget && nsLayoutUtils::IsProperAncestorFrameCrossDoc(f, bestTarget, aRoot)) {
PET_LOG(" candidate %p was ancestor for bestTarget %p\n", f, bestTarget);
continue;
}
if (!aClickableAncestor && !nsLayoutUtils::IsAncestorFrameCrossDoc(aRestrictToDescendants, f, aRoot)) {
PET_LOG(" candidate %p was not descendant of restrictroot %p\n", f, aRestrictToDescendants);
continue;
}
// If the first clickable ancestor of f is a label element
// and "for" attribute is present in label element, search the frame list for the "for" element
// If this element is present in the current list, do not count the frame in
// the cluster elements counter
if ((labelTargetId.IsEmpty() || !IsElementPresent(aCandidates, labelTargetId)) &&
!IsLargeElement(f, aPrefs)) {
if (std::find(mContentsInCluster.begin(), mContentsInCluster.end(), clickableContent) == mContentsInCluster.end()) {
mContentsInCluster.push_back(clickableContent);
}
}
// distance is in appunits
float distance = ComputeDistanceFromRegion(aPointRelativeToRootFrame, region);
nsIContent* content = f->GetContent();
if (content && content->IsElement() &&
content->AsElement()->State().HasState(
EventStates(NS_EVENT_STATE_VISITED))) {
distance *= aPrefs->mVisitedWeight / 100.0f;
}
if (distance < bestDistance) {
PET_LOG(" candidate %p is the new best\n", f);
bestDistance = distance;
bestTarget = f;
}
}
*aElementsInCluster = mContentsInCluster.size();
return bestTarget;
}
/*
* Return always true when touch cluster detection is OFF.
* When cluster detection is ON, return true:
* if the text inside the frame is readable (by human eyes)
* or
* if the structure is too complex to determine the size.
* In both cases, the frame is considered as clickable.
*
* Frames with a too small size will return false.
* In this case, the frame is considered not clickable.
*/
static bool
IsElementClickableAndReadable(nsIFrame* aFrame, WidgetGUIEvent* aEvent, const EventRadiusPrefs* aPrefs)
{
if (!aPrefs->mTouchClusterDetectionEnabled) {
return true;
}
if (aPrefs->mSimplifiedClusterDetection) {
return true;
}
if (aEvent->mClass != eMouseEventClass) {
return true;
}
uint32_t limitReadableSize = aPrefs->mLimitReadableSize;
nsSize frameSize = aFrame->GetSize();
nsPresContext* pc = aFrame->PresContext();
nsIPresShell* presShell = pc->PresShell();
float cumulativeResolution = presShell->GetCumulativeResolution();
if ((pc->AppUnitsToGfxUnits(frameSize.height) * cumulativeResolution) < limitReadableSize ||
(pc->AppUnitsToGfxUnits(frameSize.width) * cumulativeResolution) < limitReadableSize) {
return false;
}
// We want to detect small clickable text elements using the font size.
// Two common cases are supported for now:
// 1. text node
// 2. any element with only one child of type text node
// All the other cases are currently ignored.
nsIContent *content = aFrame->GetContent();
bool testFontSize = false;
if (content) {
nsINodeList* childNodes = content->ChildNodes();
uint32_t childNodeCount = childNodes->Length();
if ((content->IsNodeOfType(nsINode::eTEXT)) ||
// click occurs on the text inside <a></a> or other clickable tags with text inside
(childNodeCount == 1 && childNodes->Item(0) &&
childNodes->Item(0)->IsNodeOfType(nsINode::eTEXT))) {
// The click occurs on an element with only one text node child. In this case, the font size
// can be tested.
// The number of child nodes is tested to avoid the following cases (See bug 1172488):
// Some jscript libraries transform text elements into Canvas elements but keep the text nodes
// with a very small size (1px) to handle the selection of text.
// With such libraries, the font size of the text elements is not relevant to detect small elements.
testFontSize = true;
}
}
if (testFontSize) {
RefPtr<nsFontMetrics> fm =
nsLayoutUtils::GetInflatedFontMetricsForFrame(aFrame);
if (fm && fm->EmHeight() > 0 && // See bug 1171731
(pc->AppUnitsToGfxUnits(fm->EmHeight()) * cumulativeResolution) < limitReadableSize) {
return false;
}
}
return true;
}
nsIFrame*
FindFrameTargetedByInputEvent(WidgetGUIEvent* aEvent,
nsIFrame* aRootFrame,
const nsPoint& aPointRelativeToRootFrame,
uint32_t aFlags)
{
uint32_t flags = (aFlags & INPUT_IGNORE_ROOT_SCROLL_FRAME) ?
nsLayoutUtils::IGNORE_ROOT_SCROLL_FRAME : 0;
nsIFrame* target =
nsLayoutUtils::GetFrameForPoint(aRootFrame, aPointRelativeToRootFrame, flags);
PET_LOG("Found initial target %p for event class %s point %s relative to root frame %p\n",
target, (aEvent->mClass == eMouseEventClass ? "mouse" :
(aEvent->mClass == eTouchEventClass ? "touch" : "other")),
mozilla::layers::Stringify(aPointRelativeToRootFrame).c_str(), aRootFrame);
const EventRadiusPrefs* prefs = GetPrefsFor(aEvent->mClass);
if (!prefs || !prefs->mEnabled) {
PET_LOG("Retargeting disabled\n");
return target;
}
nsIContent* clickableAncestor = nullptr;
if (target) {
clickableAncestor = GetClickableAncestor(target, nsGkAtoms::body);
if (clickableAncestor) {
if (!IsElementClickableAndReadable(target, aEvent, prefs)) {
aEvent->AsMouseEventBase()->hitCluster = true;
}
PET_LOG("Target %p is clickable\n", target);
// If the target that was directly hit has a clickable ancestor, that
// means it too is clickable. And since it is the same as or a descendant
// of clickableAncestor, it should become the root for the GetClosest
// search.
clickableAncestor = target->GetContent();
}
}
// Do not modify targeting for actual mouse hardware; only for mouse
// events generated by touch-screen hardware.
if (aEvent->mClass == eMouseEventClass &&
prefs->mTouchOnly &&
aEvent->AsMouseEvent()->inputSource !=
nsIDOMMouseEvent::MOZ_SOURCE_TOUCH) {
PET_LOG("Mouse input event is not from a touch source\n");
return target;
}
// If the exact target is non-null, only consider candidate targets in the same
// document as the exact target. Otherwise, if an ancestor document has
// a mouse event handler for example, targets that are !GetClickableAncestor can
// never be targeted --- something nsSubDocumentFrame in an ancestor document
// would be targeted instead.
nsIFrame* restrictToDescendants = target ?
target->PresContext()->PresShell()->GetRootFrame() : aRootFrame;
nsRect targetRect = GetTargetRect(aRootFrame, aPointRelativeToRootFrame,
restrictToDescendants, prefs, aFlags);
PET_LOG("Expanded point to target rect %s\n",
mozilla::layers::Stringify(targetRect).c_str());
AutoTArray<nsIFrame*,8> candidates;
nsresult rv = nsLayoutUtils::GetFramesForArea(aRootFrame, targetRect, candidates, flags);
if (NS_FAILED(rv)) {
return target;
}
int32_t elementsInCluster = 0;
nsIFrame* closestClickable =
GetClosest(aRootFrame, aPointRelativeToRootFrame, targetRect, prefs,
restrictToDescendants, clickableAncestor, candidates,
&elementsInCluster);
if (closestClickable) {
if ((prefs->mTouchClusterDetectionEnabled && elementsInCluster > 1) ||
(!IsElementClickableAndReadable(closestClickable, aEvent, prefs))) {
if (aEvent->mClass == eMouseEventClass) {
WidgetMouseEventBase* mouseEventBase = aEvent->AsMouseEventBase();
mouseEventBase->hitCluster = true;
}
}
target = closestClickable;
}
PET_LOG("Final target is %p\n", target);
// Uncomment this to dump the frame tree to help with debugging.
// Note that dumping the frame tree at the top of the function may flood
// logcat on Android devices and cause the PET_LOGs to get dropped.
// aRootFrame->DumpFrameTree();
if (!target || !prefs->mRepositionEventCoords) {
// No repositioning required for this event
return target;
}
// Take the point relative to the root frame, make it relative to the target,
// clamp it to the bounds, and then make it relative to the root frame again.
nsPoint point = aPointRelativeToRootFrame;
if (nsLayoutUtils::TRANSFORM_SUCCEEDED != nsLayoutUtils::TransformPoint(aRootFrame, target, point)) {
return target;
}
point = target->GetRectRelativeToSelf().ClampPoint(point);
if (nsLayoutUtils::TRANSFORM_SUCCEEDED != nsLayoutUtils::TransformPoint(target, aRootFrame, point)) {
return target;
}
// Now we basically undo the operations in GetEventCoordinatesRelativeTo, to
// get back the (now-clamped) coordinates in the event's widget's space.
nsView* view = aRootFrame->GetView();
if (!view) {
return target;
}
LayoutDeviceIntPoint widgetPoint = nsLayoutUtils::TranslateViewToWidget(
aRootFrame->PresContext(), view, point, aEvent->widget);
if (widgetPoint.x != NS_UNCONSTRAINEDSIZE) {
// If that succeeded, we update the point in the event
aEvent->refPoint = widgetPoint;
}
return target;
}
} // namespace mozilla