Bug 1776444 [wpt PR 34582] - Revert "Add TimedHTMLParserBudget to fieldtrial_testing_...
[gecko.git] / widget / SwipeTracker.cpp
blob1e109de6cd5d244df03836ef06c92f0796287062
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 file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "SwipeTracker.h"
9 #include "InputData.h"
10 #include "mozilla/FlushType.h"
11 #include "mozilla/PresShell.h"
12 #include "mozilla/StaticPrefs_widget.h"
13 #include "mozilla/TimeStamp.h"
14 #include "mozilla/TouchEvents.h"
15 #include "mozilla/dom/SimpleGestureEventBinding.h"
16 #include "nsAlgorithm.h"
17 #include "nsIWidget.h"
18 #include "nsRefreshDriver.h"
19 #include "UnitTransforms.h"
21 // These values were tweaked to make the physics feel similar to the native
22 // swipe.
23 static const double kSpringForce = 250.0;
24 static const double kSwipeSuccessThreshold = 0.25;
26 namespace mozilla {
28 static already_AddRefed<nsRefreshDriver> GetRefreshDriver(nsIWidget& aWidget) {
29 nsIWidgetListener* widgetListener = aWidget.GetWidgetListener();
30 PresShell* presShell =
31 widgetListener ? widgetListener->GetPresShell() : nullptr;
32 nsPresContext* presContext =
33 presShell ? presShell->GetPresContext() : nullptr;
34 RefPtr<nsRefreshDriver> refreshDriver =
35 presContext ? presContext->RefreshDriver() : nullptr;
36 return refreshDriver.forget();
39 SwipeTracker::SwipeTracker(nsIWidget& aWidget,
40 const PanGestureInput& aSwipeStartEvent,
41 uint32_t aAllowedDirections,
42 uint32_t aSwipeDirection)
43 : mWidget(aWidget),
44 mRefreshDriver(GetRefreshDriver(mWidget)),
45 mAxis(0.0, 0.0, 0.0, kSpringForce, 1.0),
46 mEventPosition(RoundedToInt(ViewAs<LayoutDevicePixel>(
47 aSwipeStartEvent.mPanStartPoint,
48 PixelCastJustification::LayoutDeviceIsScreenForUntransformedEvent))),
49 mLastEventTimeStamp(aSwipeStartEvent.mTimeStamp),
50 mAllowedDirections(aAllowedDirections),
51 mSwipeDirection(aSwipeDirection),
52 mGestureAmount(0.0),
53 mCurrentVelocity(0.0),
54 mEventsAreControllingSwipe(true),
55 mEventsHaveStartedNewGesture(false),
56 mRegisteredWithRefreshDriver(false) {
57 SendSwipeEvent(eSwipeGestureStart, 0, 0.0, aSwipeStartEvent.mTimeStamp);
58 ProcessEvent(aSwipeStartEvent, /* aProcessingFirstEvent = */ true);
61 void SwipeTracker::Destroy() { UnregisterFromRefreshDriver(); }
63 SwipeTracker::~SwipeTracker() {
64 MOZ_ASSERT(!mRegisteredWithRefreshDriver,
65 "Destroy needs to be called before deallocating");
68 double SwipeTracker::SwipeSuccessTargetValue() const {
69 return (mSwipeDirection == dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT)
70 ? -1.0
71 : 1.0;
74 double SwipeTracker::ClampToAllowedRange(double aGestureAmount) const {
75 // gestureAmount needs to stay between -1 and 0 when swiping right and
76 // between 0 and 1 when swiping left.
77 double min =
78 (mSwipeDirection == dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT)
79 ? -1.0
80 : 0.0;
81 double max =
82 (mSwipeDirection == dom::SimpleGestureEvent_Binding::DIRECTION_LEFT)
83 ? 1.0
84 : 0.0;
85 return clamped(aGestureAmount, min, max);
88 bool SwipeTracker::ComputeSwipeSuccess() const {
89 double targetValue = SwipeSuccessTargetValue();
91 // If the fingers were moving away from the target direction when they were
92 // lifted from the touchpad, abort the swipe.
93 if (mCurrentVelocity * targetValue <
94 -StaticPrefs::widget_swipe_velocity_twitch_tolerance()) {
95 return false;
98 return (mGestureAmount * targetValue +
99 mCurrentVelocity * targetValue *
100 StaticPrefs::widget_swipe_success_velocity_contribution()) >=
101 kSwipeSuccessThreshold;
104 nsEventStatus SwipeTracker::ProcessEvent(
105 const PanGestureInput& aEvent, bool aProcessingFirstEvent /* = false */) {
106 // If the fingers have already been lifted or the swipe direction is where
107 // navigation is impossible, don't process this event for swiping.
108 if (!mEventsAreControllingSwipe || !SwipingInAllowedDirection()) {
109 // Return nsEventStatus_eConsumeNoDefault for events from the swipe gesture
110 // and nsEventStatus_eIgnore for events of subsequent scroll gestures.
111 if (aEvent.mType == PanGestureInput::PANGESTURE_MAYSTART ||
112 aEvent.mType == PanGestureInput::PANGESTURE_START) {
113 mEventsHaveStartedNewGesture = true;
115 return mEventsHaveStartedNewGesture ? nsEventStatus_eIgnore
116 : nsEventStatus_eConsumeNoDefault;
119 double delta = -aEvent.mPanDisplacement.x /
120 mWidget.GetDefaultScaleInternal() /
121 StaticPrefs::widget_swipe_whole_page_pixel_size();
122 mGestureAmount = ClampToAllowedRange(mGestureAmount + delta);
123 if (aEvent.mType != PanGestureInput::PANGESTURE_END) {
124 if (!aProcessingFirstEvent) {
125 double elapsedSeconds = std::max(
126 0.008, (aEvent.mTimeStamp - mLastEventTimeStamp).ToSeconds());
127 mCurrentVelocity = delta / elapsedSeconds;
129 mLastEventTimeStamp = aEvent.mTimeStamp;
132 const bool computedSwipeSuccess = ComputeSwipeSuccess();
134 // The velocity component might push us over the success threshold, in which
135 // case we want to pass the success threshold in the event we send so that the
136 // UI draws as 100% opacity to indicate such. We don't want to include the
137 // velocity in the amount we put on the event if we aren't over the success
138 // threshold because that would lead to the opacity decreasing even if the
139 // user continues to increase the swipe distance. If we do compute swipe
140 // success here and the user does not lift their fingers and then decreases
141 // the total swipe so that we go below the success threshold the opacity would
142 // also decrease in that case but that seems okay.
143 double eventAmount = mGestureAmount;
144 if (computedSwipeSuccess) {
145 eventAmount = kSwipeSuccessThreshold;
146 if (mGestureAmount < 0.f) {
147 eventAmount = -eventAmount;
150 SendSwipeEvent(eSwipeGestureUpdate, 0, eventAmount, aEvent.mTimeStamp);
152 if (aEvent.mType == PanGestureInput::PANGESTURE_END) {
153 mEventsAreControllingSwipe = false;
154 if (computedSwipeSuccess) {
155 // Let's use same timestamp as previous event because this is caused by
156 // the preceding event.
157 SendSwipeEvent(eSwipeGesture, mSwipeDirection, 0.0, aEvent.mTimeStamp);
158 UnregisterFromRefreshDriver();
159 NS_DispatchToMainThread(
160 NS_NewRunnableFunction("SwipeTracker::SwipeFinished",
161 [swipeTracker = RefPtr<SwipeTracker>(this),
162 timeStamp = aEvent.mTimeStamp] {
163 swipeTracker->SwipeFinished(timeStamp);
164 }));
165 } else {
166 StartAnimating(0.0);
170 return nsEventStatus_eConsumeNoDefault;
173 void SwipeTracker::StartAnimating(double aTargetValue) {
174 mAxis.SetPosition(mGestureAmount);
175 mAxis.SetDestination(aTargetValue);
176 mAxis.SetVelocity(mCurrentVelocity);
178 mLastAnimationFrameTime = TimeStamp::Now();
180 // Add ourselves as a refresh driver observer. The refresh driver
181 // will call WillRefresh for each animation frame until we
182 // unregister ourselves.
183 MOZ_ASSERT(!mRegisteredWithRefreshDriver);
184 if (mRefreshDriver) {
185 mRefreshDriver->AddRefreshObserver(this, FlushType::Style,
186 "Swipe animation");
187 mRegisteredWithRefreshDriver = true;
191 void SwipeTracker::WillRefresh(mozilla::TimeStamp aTime) {
192 TimeStamp now = TimeStamp::Now();
193 mAxis.Simulate(now - mLastAnimationFrameTime);
194 mLastAnimationFrameTime = now;
196 bool isFinished =
197 mAxis.IsFinished(1.0 / StaticPrefs::widget_swipe_whole_page_pixel_size());
198 mGestureAmount = (isFinished ? mAxis.GetDestination() : mAxis.GetPosition());
199 SendSwipeEvent(eSwipeGestureUpdate, 0, mGestureAmount, now);
201 if (isFinished) {
202 UnregisterFromRefreshDriver();
203 SwipeFinished(now);
207 void SwipeTracker::CancelSwipe(const TimeStamp& aTimeStamp) {
208 SendSwipeEvent(eSwipeGestureEnd, 0, 0.0, aTimeStamp);
211 void SwipeTracker::SwipeFinished(const TimeStamp& aTimeStamp) {
212 SendSwipeEvent(eSwipeGestureEnd, 0, 0.0, aTimeStamp);
213 mWidget.SwipeFinished();
216 void SwipeTracker::UnregisterFromRefreshDriver() {
217 if (mRegisteredWithRefreshDriver) {
218 MOZ_ASSERT(mRefreshDriver, "How were we able to register, then?");
219 mRefreshDriver->RemoveRefreshObserver(this, FlushType::Style);
221 mRegisteredWithRefreshDriver = false;
224 /* static */ WidgetSimpleGestureEvent SwipeTracker::CreateSwipeGestureEvent(
225 EventMessage aMsg, nsIWidget* aWidget,
226 const LayoutDeviceIntPoint& aPosition, const TimeStamp& aTimeStamp) {
227 // XXX Why isn't this initialized with nsCocoaUtils::InitInputEvent()?
228 WidgetSimpleGestureEvent geckoEvent(true, aMsg, aWidget);
229 geckoEvent.mModifiers = 0;
230 // XXX How about geckoEvent.mTime?
231 geckoEvent.mTimeStamp = aTimeStamp;
232 geckoEvent.mRefPoint = aPosition;
233 geckoEvent.mButtons = 0;
234 return geckoEvent;
237 bool SwipeTracker::SendSwipeEvent(EventMessage aMsg, uint32_t aDirection,
238 double aDelta, const TimeStamp& aTimeStamp) {
239 WidgetSimpleGestureEvent geckoEvent =
240 CreateSwipeGestureEvent(aMsg, &mWidget, mEventPosition, aTimeStamp);
241 geckoEvent.mDirection = aDirection;
242 geckoEvent.mDelta = aDelta;
243 geckoEvent.mAllowedDirections = mAllowedDirections;
244 return mWidget.DispatchWindowEvent(geckoEvent);
247 // static
248 bool SwipeTracker::CanTriggerSwipe(const PanGestureInput& aPanInput) {
249 if (StaticPrefs::widget_disable_swipe_tracker()) {
250 return false;
253 if (aPanInput.mType != PanGestureInput::PANGESTURE_START) {
254 return false;
257 // Only initiate horizontal tracking for events whose horizontal element is
258 // at least eight times larger than its vertical element. This minimizes
259 // performance problems with vertical scrolls (by minimizing the possibility
260 // that they'll be misinterpreted as horizontal swipes), while still
261 // tolerating a small vertical element to a true horizontal swipe. The number
262 // '8' was arrived at by trial and error.
263 return std::abs(aPanInput.mPanDisplacement.x) >
264 std::abs(aPanInput.mPanDisplacement.y) * 8;
267 } // namespace mozilla