aeae32bbbe911f265cc4c3e4bc96ba182066b4cf
[WebKit-https.git] / Source / WebKit / UIProcess / gtk / ViewGestureControllerGtk.cpp
1 /*
2  * Copyright (C) 2013, 2014 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "ViewGestureController.h"
28
29 #include "DrawingAreaProxy.h"
30 #include "WebBackForwardList.h"
31
32 namespace WebKit {
33 using namespace WebCore;
34
35 static const Seconds swipeMinAnimationDuration = 100_ms;
36 static const Seconds swipeMaxAnimationDuration = 400_ms;
37 static const double swipeAnimationBaseVelocity = 0.002;
38
39 // GTK divides all scroll deltas by 10, compensate for that
40 static const double gtkScrollDeltaMultiplier = 10;
41 static const double swipeTouchpadBaseWidth = 400;
42
43 // This is derivative of the easing function at t=0
44 static const double swipeAnimationDurationMultiplier = 3;
45
46 static const double swipeCancelArea = 0.5;
47 static const double swipeCancelVelocityThreshold = 0.001;
48
49 static const double swipeOverlayShadowOpacity = 0.06;
50 static const double swipeOverlayDimmingOpacity = 0.12;
51 static const double swipeOverlayShadowWidth = 81;
52 static const double swipeOverlayShadowGradientOffsets[] = { 0, 0.03125, 0.0625, 0.0938, 0.125, 0.1875, 0.25, 0.375, 0.4375, 0.5, 0.5625, 0.625, 0.6875, 0.75, 0.875, 1. };
53 static const double swipeOverlayShadowGradientAlpha[] = { 1, 0.99, 0.98, 0.95, 0.92, 0.82, 0.71, 0.46, 0.35, 0.25, 0.17, 0.11, 0.07, 0.04, 0.01, 0. };
54
55 static bool isEventStop(GdkEventScroll* event)
56 {
57 #if GTK_CHECK_VERSION(3, 20, 0)
58     return gdk_event_is_scroll_stop_event(reinterpret_cast<GdkEvent*>(event));
59 #else
60     return !event->delta_x && !event->delta_y;
61 #endif
62 }
63
64 void ViewGestureController::platformTeardown()
65 {
66     m_swipeProgressTracker.reset();
67
68     if (m_activeGestureType == ViewGestureType::Swipe)
69         removeSwipeSnapshot();
70 }
71
72 bool ViewGestureController::PendingSwipeTracker::scrollEventCanStartSwipe(GdkEventScroll*)
73 {
74     return true;
75 }
76
77 bool ViewGestureController::PendingSwipeTracker::scrollEventCanEndSwipe(GdkEventScroll* event)
78 {
79     return isEventStop(event);
80 }
81
82 bool ViewGestureController::PendingSwipeTracker::scrollEventCanInfluenceSwipe(GdkEventScroll* event)
83 {
84     GdkDevice* device = gdk_event_get_source_device(reinterpret_cast<GdkEvent*>(event));
85     GdkInputSource source = gdk_device_get_source(device);
86
87     bool isDeviceAllowed = source == GDK_SOURCE_TOUCHPAD || source == GDK_SOURCE_TOUCHSCREEN || m_viewGestureController.m_isSimulatedSwipe;
88
89     return gdk_event_get_scroll_deltas(reinterpret_cast<GdkEvent*>(event), nullptr, nullptr) && isDeviceAllowed;
90 }
91
92 static bool isTouchEvent(GdkEventScroll* event)
93 {
94     GdkDevice* device = gdk_event_get_source_device(reinterpret_cast<GdkEvent*>(event));
95     GdkInputSource source = gdk_device_get_source(device);
96
97     return source == GDK_SOURCE_TOUCHSCREEN;
98 }
99
100 FloatSize ViewGestureController::PendingSwipeTracker::scrollEventGetScrollingDeltas(GdkEventScroll* event)
101 {
102     double multiplier = isTouchEvent(event) ? Scrollbar::pixelsPerLineStep() : gtkScrollDeltaMultiplier;
103     double xDelta, yDelta;
104     gdk_event_get_scroll_deltas(reinterpret_cast<GdkEvent*>(event), &xDelta, &yDelta);
105
106     // GdkEventScroll deltas are inverted compared to NSEvent, so invert them again
107     return -FloatSize(xDelta, yDelta) * multiplier;
108 }
109
110 bool ViewGestureController::handleScrollWheelEvent(GdkEventScroll* event)
111 {
112     return m_swipeProgressTracker.handleEvent(event) || m_pendingSwipeTracker.handleEvent(event);
113 }
114
115 void ViewGestureController::trackSwipeGesture(PlatformScrollEvent event, SwipeDirection direction, RefPtr<WebBackForwardListItem> targetItem)
116 {
117     m_swipeProgressTracker.startTracking(WTFMove(targetItem), direction);
118     m_swipeProgressTracker.handleEvent(event);
119 }
120
121 ViewGestureController::SwipeProgressTracker::SwipeProgressTracker(WebPageProxy& webPageProxy, ViewGestureController& viewGestureController)
122     : m_viewGestureController(viewGestureController)
123     , m_webPageProxy(webPageProxy)
124 {
125 }
126
127 void ViewGestureController::SwipeProgressTracker::startTracking(RefPtr<WebBackForwardListItem>&& targetItem, SwipeDirection direction)
128 {
129     if (m_state != State::None)
130         return;
131
132     m_targetItem = targetItem;
133     m_direction = direction;
134     m_state = State::Pending;
135 }
136
137 void ViewGestureController::SwipeProgressTracker::reset()
138 {
139     m_targetItem = nullptr;
140     m_state = State::None;
141
142     if (m_tickCallbackID) {
143         GtkWidget* widget = m_webPageProxy.viewWidget();
144         gtk_widget_remove_tick_callback(widget, m_tickCallbackID);
145         m_tickCallbackID = 0;
146     }
147
148     m_progress = 0;
149     m_startProgress = 0;
150     m_endProgress = 0;
151
152     m_startTime = 0_ms;
153     m_endTime = 0_ms;
154     m_prevTime = 0_ms;
155     m_velocity = 0;
156     m_cancelled = false;
157 }
158
159 bool ViewGestureController::SwipeProgressTracker::handleEvent(GdkEventScroll* event)
160 {
161     // Don't allow scrolling while the next page is loading
162     if (m_state == State::Finishing)
163         return true;
164
165     // Stop current animation, if any
166     if (m_state == State::Animating) {
167         GtkWidget* widget = m_webPageProxy.viewWidget();
168         gtk_widget_remove_tick_callback(widget, m_tickCallbackID);
169         m_tickCallbackID = 0;
170
171         m_cancelled = false;
172         m_state = State::Pending;
173     }
174
175     if (m_state == State::Pending) {
176         m_viewGestureController.beginSwipeGesture(m_targetItem.get(), m_direction);
177         m_state = State::Scrolling;
178     }
179
180     if (m_state != State::Scrolling)
181         return false;
182
183     if (isEventStop(event)) {
184         startAnimation();
185         return false;
186     }
187
188     uint32_t eventTime = gdk_event_get_time(reinterpret_cast<GdkEvent*>(event));
189     double eventDeltaX;
190     gdk_event_get_scroll_deltas(reinterpret_cast<GdkEvent*>(event), &eventDeltaX, nullptr);
191
192     double deltaX = -eventDeltaX;
193     if (isTouchEvent(event))
194         deltaX *= (double) Scrollbar::pixelsPerLineStep() / m_webPageProxy.viewSize().width();
195     else
196         deltaX *= gtkScrollDeltaMultiplier / swipeTouchpadBaseWidth;
197
198     Seconds time = Seconds::fromMilliseconds(eventTime);
199     if (time != m_prevTime)
200         m_velocity = deltaX / (time - m_prevTime).milliseconds();
201
202     m_prevTime = time;
203     m_progress += deltaX;
204
205     bool swipingLeft = m_viewGestureController.isPhysicallySwipingLeft(m_direction);
206     float maxProgress = swipingLeft ? 1 : 0;
207     float minProgress = !swipingLeft ? -1 : 0;
208     m_progress = clampTo<float>(m_progress, minProgress, maxProgress);
209
210     m_viewGestureController.handleSwipeGesture(m_targetItem.get(), m_progress, m_direction);
211
212     return true;
213 }
214
215 bool ViewGestureController::SwipeProgressTracker::shouldCancel()
216 {
217     bool swipingLeft = m_viewGestureController.isPhysicallySwipingLeft(m_direction);
218
219     if (swipingLeft && m_velocity < 0)
220         return true;
221
222     if (!swipingLeft && m_velocity > 0)
223         return true;
224
225     return (abs(m_progress) < swipeCancelArea && abs(m_velocity) < swipeCancelVelocityThreshold);
226 }
227
228 void ViewGestureController::SwipeProgressTracker::startAnimation()
229 {
230     m_cancelled = shouldCancel();
231
232     m_state = State::Animating;
233     m_viewGestureController.willEndSwipeGesture(*m_targetItem, m_cancelled);
234
235     m_startProgress = m_progress;
236     if (m_cancelled)
237         m_endProgress = 0;
238     else
239         m_endProgress = m_viewGestureController.isPhysicallySwipingLeft(m_direction) ? 1 : -1;
240
241     double velocity = swipeAnimationBaseVelocity;
242     if ((m_endProgress - m_progress) * m_velocity > 0)
243         velocity = m_velocity;
244
245     Seconds duration = Seconds::fromMilliseconds(std::abs((m_progress - m_endProgress) / velocity * swipeAnimationDurationMultiplier));
246     duration = clampTo<Seconds>(duration, swipeMinAnimationDuration, swipeMaxAnimationDuration);
247
248     GtkWidget* widget = m_webPageProxy.viewWidget();
249     m_startTime = Seconds::fromMicroseconds(gdk_frame_clock_get_frame_time(gtk_widget_get_frame_clock(widget)));
250     m_endTime = m_startTime + duration;
251
252     m_tickCallbackID = gtk_widget_add_tick_callback(widget, [](GtkWidget*, GdkFrameClock* frameClock, gpointer userData) -> gboolean {
253         auto* tracker = static_cast<SwipeProgressTracker*>(userData);
254         return tracker->onAnimationTick(frameClock);
255     }, this, nullptr);
256 }
257
258 static inline double easeOutCubic(double t)
259 {
260     double p = t - 1;
261     return p * p * p + 1;
262 }
263
264 gboolean ViewGestureController::SwipeProgressTracker::onAnimationTick(GdkFrameClock* frameClock)
265 {
266     ASSERT(m_state == State::Animating);
267     ASSERT(m_endTime > m_startTime);
268
269     Seconds frameTime = Seconds::fromMicroseconds(gdk_frame_clock_get_frame_time(frameClock));
270
271     double animationProgress = (frameTime - m_startTime) / (m_endTime - m_startTime);
272     if (animationProgress > 1)
273         animationProgress = 1;
274
275     m_progress = m_startProgress + (m_endProgress - m_startProgress) * easeOutCubic(animationProgress);
276
277     m_viewGestureController.handleSwipeGesture(m_targetItem.get(), m_progress, m_direction);
278     if (frameTime >= m_endTime) {
279         m_tickCallbackID = 0;
280         endAnimation();
281         return G_SOURCE_REMOVE;
282     }
283
284     return G_SOURCE_CONTINUE;
285 }
286
287 void ViewGestureController::SwipeProgressTracker::endAnimation()
288 {
289     m_state = State::Finishing;
290     m_viewGestureController.endSwipeGesture(m_targetItem.get(), m_cancelled);
291 }
292
293 void ViewGestureController::beginSwipeGesture(WebBackForwardListItem* targetItem, SwipeDirection direction)
294 {
295     ASSERT(targetItem);
296
297     m_webPageProxy.navigationGestureDidBegin();
298
299     willBeginGesture(ViewGestureType::Swipe);
300
301     if (auto* snapshot = targetItem->snapshot()) {
302         m_currentSwipeSnapshot = snapshot;
303
304         FloatSize viewSize(m_webPageProxy.viewSize());
305         if (snapshot->hasImage() && shouldUseSnapshotForSize(*snapshot, viewSize, 0))
306             m_currentSwipeSnapshotPattern = adoptRef(cairo_pattern_create_for_surface(snapshot->surface()));
307
308         Color color = snapshot->backgroundColor();
309         if (color.isValid()) {
310             m_backgroundColorForCurrentSnapshot = color;
311             if (!m_currentSwipeSnapshotPattern) {
312                 double red, green, blue, alpha;
313                 color.getRGBA(red, green, blue, alpha);
314                 m_currentSwipeSnapshotPattern = adoptRef(cairo_pattern_create_rgba(red, green, blue, alpha));
315             }
316         }
317     }
318
319     if (!m_currentSwipeSnapshotPattern)
320         m_currentSwipeSnapshotPattern = adoptRef(cairo_pattern_create_rgb(1, 1, 1));
321 }
322
323 void ViewGestureController::handleSwipeGesture(WebBackForwardListItem*, double, SwipeDirection)
324 {
325     gtk_widget_queue_draw(m_webPageProxy.viewWidget());
326 }
327
328 void ViewGestureController::draw(cairo_t* cr, cairo_pattern_t* pageGroup)
329 {
330     bool swipingLeft = isPhysicallySwipingLeft(m_swipeProgressTracker.direction());
331     bool swipingBack = m_swipeProgressTracker.direction() == SwipeDirection::Back;
332     bool isRTL = m_webPageProxy.userInterfaceLayoutDirection() == WebCore::UserInterfaceLayoutDirection::RTL;
333     float progress = m_swipeProgressTracker.progress();
334
335     double width = m_webPageProxy.drawingArea()->size().width();
336     double height = m_webPageProxy.drawingArea()->size().height();
337
338     double swipingLayerOffset = (swipingLeft ? 0 : width) + floor(width * progress);
339
340     double dimmingProgress = swipingLeft ? 1 - progress : -progress;
341     if (isRTL)
342         dimmingProgress = 1 - dimmingProgress;
343
344     double remainingSwipeDistance = dimmingProgress * width;
345     double shadowFadeDistance = swipeOverlayShadowWidth;
346
347     double shadowOpacity = swipeOverlayShadowOpacity;
348     if (remainingSwipeDistance < shadowFadeDistance)
349         shadowOpacity = (remainingSwipeDistance / shadowFadeDistance) * swipeOverlayShadowOpacity;
350
351     RefPtr<cairo_pattern_t> shadowPattern = adoptRef(cairo_pattern_create_linear(0, 0, swipeOverlayShadowWidth, 0));
352     for (int i = 0; i < 16; i++) {
353         double offset = swipeOverlayShadowGradientOffsets[i];
354         double alpha = swipeOverlayShadowGradientAlpha[i] * shadowOpacity;
355         cairo_pattern_add_color_stop_rgba(shadowPattern.get(), offset, 0, 0, 0, alpha);
356     }
357
358     cairo_save(cr);
359
360     if (isRTL)
361         cairo_rectangle(cr, swipingLayerOffset, 0, width - swipingLayerOffset, height);
362     else
363         cairo_rectangle(cr, 0, 0, swipingLayerOffset, height);
364     cairo_set_source(cr, swipingBack ? m_currentSwipeSnapshotPattern.get() : pageGroup);
365     cairo_fill_preserve(cr);
366
367     cairo_set_source_rgba(cr, 0, 0, 0, dimmingProgress * swipeOverlayDimmingOpacity);
368     cairo_fill(cr);
369
370     cairo_translate(cr, swipingLayerOffset, 0);
371
372     if (progress) {
373         cairo_save(cr);
374         if (!isRTL)
375             cairo_scale(cr, -1, 1);
376         cairo_rectangle(cr, 0, 0, swipeOverlayShadowWidth, height);
377         cairo_set_source(cr, shadowPattern.get());
378         cairo_fill(cr);
379         cairo_restore(cr);
380     }
381
382     if (isRTL) {
383         cairo_translate(cr, -width, 0);
384         cairo_rectangle(cr, width - swipingLayerOffset, 0, swipingLayerOffset, height);
385     } else
386         cairo_rectangle(cr, 0, 0, width - swipingLayerOffset, height);
387     cairo_set_source(cr, swipingBack ? pageGroup : m_currentSwipeSnapshotPattern.get());
388     cairo_fill(cr);
389
390     cairo_restore(cr);
391 }
392
393 void ViewGestureController::removeSwipeSnapshot()
394 {
395     m_snapshotRemovalTracker.reset();
396
397     m_hasOutstandingRepaintRequest = false;
398
399     if (m_activeGestureType != ViewGestureType::Swipe)
400         return;
401
402     m_currentSwipeSnapshotPattern = nullptr;
403
404     m_currentSwipeSnapshot = nullptr;
405
406     m_webPageProxy.navigationGestureSnapshotWasRemoved();
407
408     m_backgroundColorForCurrentSnapshot = Color();
409
410     didEndGesture();
411
412     m_swipeProgressTracker.reset();
413 }
414
415 static GUniquePtr<GdkEvent> createScrollEvent(GtkWidget* widget, double xDelta, double yDelta)
416 {
417     GdkWindow* window = gtk_widget_get_window(widget);
418
419     int x, y;
420     gdk_window_get_root_origin(window, &x, &y);
421
422     int width = gdk_window_get_width(window);
423     int height = gdk_window_get_height(window);
424
425     GUniquePtr<GdkEvent> event(gdk_event_new(GDK_SCROLL));
426     event->scroll.time = GDK_CURRENT_TIME;
427     event->scroll.x = width / 2;
428     event->scroll.y = height / 2;
429     event->scroll.x_root = x + width / 2;
430     event->scroll.y_root = y + height / 2;
431     event->scroll.direction = GDK_SCROLL_SMOOTH;
432     event->scroll.delta_x = xDelta;
433     event->scroll.delta_y = yDelta;
434     event->scroll.state = 0;
435 #if GTK_CHECK_VERSION(3, 20, 0)
436     event->scroll.is_stop = !xDelta && !yDelta;
437 #endif
438     event->scroll.window = GDK_WINDOW(g_object_ref(window));
439     gdk_event_set_screen(event.get(), gdk_window_get_screen(window));
440     gdk_event_set_device(event.get(), gdk_device_manager_get_client_pointer(gdk_display_get_device_manager(gdk_window_get_display(window))));
441     gdk_event_set_source_device(event.get(), gdk_device_manager_get_client_pointer(gdk_display_get_device_manager(gdk_window_get_display(window))));
442
443     return event;
444 }
445
446 bool ViewGestureController::beginSimulatedSwipeInDirectionForTesting(SwipeDirection direction)
447 {
448     if (!canSwipeInDirection(direction))
449         return false;
450
451     m_isSimulatedSwipe = true;
452
453     double delta = swipeTouchpadBaseWidth / gtkScrollDeltaMultiplier * 0.75;
454
455     if (isPhysicallySwipingLeft(direction))
456         delta = -delta;
457
458     GUniquePtr<GdkEvent> event = createScrollEvent(m_webPageProxy.viewWidget(), delta, 0);
459     gtk_widget_event(m_webPageProxy.viewWidget(), event.get());
460
461     return true;
462 }
463
464 bool ViewGestureController::completeSimulatedSwipeInDirectionForTesting(SwipeDirection)
465 {
466     GUniquePtr<GdkEvent> event = createScrollEvent(m_webPageProxy.viewWidget(), 0, 0);
467     gtk_widget_event(m_webPageProxy.viewWidget(), event.get());
468
469     m_isSimulatedSwipe = false;
470
471     return true;
472 }
473
474 } // namespace WebKit