[WPE][GTK] Bump minimum versions of GLib, GTK, libsoup, ATK, GStreamer, and Cairo
[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     return gdk_event_is_scroll_stop_event(reinterpret_cast<GdkEvent*>(event));
58 }
59
60 void ViewGestureController::platformTeardown()
61 {
62     m_swipeProgressTracker.reset();
63
64     if (m_activeGestureType == ViewGestureType::Swipe)
65         removeSwipeSnapshot();
66 }
67
68 bool ViewGestureController::PendingSwipeTracker::scrollEventCanStartSwipe(GdkEventScroll*)
69 {
70     return true;
71 }
72
73 bool ViewGestureController::PendingSwipeTracker::scrollEventCanEndSwipe(GdkEventScroll* event)
74 {
75     return isEventStop(event);
76 }
77
78 bool ViewGestureController::PendingSwipeTracker::scrollEventCanInfluenceSwipe(GdkEventScroll* event)
79 {
80     GdkDevice* device = gdk_event_get_source_device(reinterpret_cast<GdkEvent*>(event));
81     GdkInputSource source = gdk_device_get_source(device);
82
83     bool isDeviceAllowed = source == GDK_SOURCE_TOUCHPAD || source == GDK_SOURCE_TOUCHSCREEN || m_viewGestureController.m_isSimulatedSwipe;
84
85     return gdk_event_get_scroll_deltas(reinterpret_cast<GdkEvent*>(event), nullptr, nullptr) && isDeviceAllowed;
86 }
87
88 static bool isTouchEvent(GdkEventScroll* event)
89 {
90     GdkDevice* device = gdk_event_get_source_device(reinterpret_cast<GdkEvent*>(event));
91     GdkInputSource source = gdk_device_get_source(device);
92
93     return source == GDK_SOURCE_TOUCHSCREEN;
94 }
95
96 FloatSize ViewGestureController::PendingSwipeTracker::scrollEventGetScrollingDeltas(GdkEventScroll* event)
97 {
98     double multiplier = isTouchEvent(event) ? Scrollbar::pixelsPerLineStep() : gtkScrollDeltaMultiplier;
99     double xDelta, yDelta;
100     gdk_event_get_scroll_deltas(reinterpret_cast<GdkEvent*>(event), &xDelta, &yDelta);
101
102     // GdkEventScroll deltas are inverted compared to NSEvent, so invert them again
103     return -FloatSize(xDelta, yDelta) * multiplier;
104 }
105
106 bool ViewGestureController::handleScrollWheelEvent(GdkEventScroll* event)
107 {
108     return m_swipeProgressTracker.handleEvent(event) || m_pendingSwipeTracker.handleEvent(event);
109 }
110
111 void ViewGestureController::trackSwipeGesture(PlatformScrollEvent event, SwipeDirection direction, RefPtr<WebBackForwardListItem> targetItem)
112 {
113     m_swipeProgressTracker.startTracking(WTFMove(targetItem), direction);
114     m_swipeProgressTracker.handleEvent(event);
115 }
116
117 ViewGestureController::SwipeProgressTracker::SwipeProgressTracker(WebPageProxy& webPageProxy, ViewGestureController& viewGestureController)
118     : m_viewGestureController(viewGestureController)
119     , m_webPageProxy(webPageProxy)
120 {
121 }
122
123 void ViewGestureController::SwipeProgressTracker::startTracking(RefPtr<WebBackForwardListItem>&& targetItem, SwipeDirection direction)
124 {
125     if (m_state != State::None)
126         return;
127
128     m_targetItem = targetItem;
129     m_direction = direction;
130     m_state = State::Pending;
131 }
132
133 void ViewGestureController::SwipeProgressTracker::reset()
134 {
135     m_targetItem = nullptr;
136     m_state = State::None;
137
138     if (m_tickCallbackID) {
139         GtkWidget* widget = m_webPageProxy.viewWidget();
140         gtk_widget_remove_tick_callback(widget, m_tickCallbackID);
141         m_tickCallbackID = 0;
142     }
143
144     m_progress = 0;
145     m_startProgress = 0;
146     m_endProgress = 0;
147
148     m_startTime = 0_ms;
149     m_endTime = 0_ms;
150     m_prevTime = 0_ms;
151     m_velocity = 0;
152     m_cancelled = false;
153 }
154
155 bool ViewGestureController::SwipeProgressTracker::handleEvent(GdkEventScroll* event)
156 {
157     // Don't allow scrolling while the next page is loading
158     if (m_state == State::Finishing)
159         return true;
160
161     // Stop current animation, if any
162     if (m_state == State::Animating) {
163         GtkWidget* widget = m_webPageProxy.viewWidget();
164         gtk_widget_remove_tick_callback(widget, m_tickCallbackID);
165         m_tickCallbackID = 0;
166
167         m_cancelled = false;
168         m_state = State::Pending;
169     }
170
171     if (m_state == State::Pending) {
172         m_viewGestureController.beginSwipeGesture(m_targetItem.get(), m_direction);
173         m_state = State::Scrolling;
174     }
175
176     if (m_state != State::Scrolling)
177         return false;
178
179     if (isEventStop(event)) {
180         startAnimation();
181         return false;
182     }
183
184     uint32_t eventTime = gdk_event_get_time(reinterpret_cast<GdkEvent*>(event));
185     double eventDeltaX;
186     gdk_event_get_scroll_deltas(reinterpret_cast<GdkEvent*>(event), &eventDeltaX, nullptr);
187
188     double deltaX = -eventDeltaX;
189     if (isTouchEvent(event))
190         deltaX *= (double) Scrollbar::pixelsPerLineStep() / m_webPageProxy.viewSize().width();
191     else
192         deltaX *= gtkScrollDeltaMultiplier / swipeTouchpadBaseWidth;
193
194     Seconds time = Seconds::fromMilliseconds(eventTime);
195     if (time != m_prevTime)
196         m_velocity = deltaX / (time - m_prevTime).milliseconds();
197
198     m_prevTime = time;
199     m_progress += deltaX;
200
201     bool swipingLeft = m_viewGestureController.isPhysicallySwipingLeft(m_direction);
202     float maxProgress = swipingLeft ? 1 : 0;
203     float minProgress = !swipingLeft ? -1 : 0;
204     m_progress = clampTo<float>(m_progress, minProgress, maxProgress);
205
206     m_viewGestureController.handleSwipeGesture(m_targetItem.get(), m_progress, m_direction);
207
208     return true;
209 }
210
211 bool ViewGestureController::SwipeProgressTracker::shouldCancel()
212 {
213     bool swipingLeft = m_viewGestureController.isPhysicallySwipingLeft(m_direction);
214
215     if (swipingLeft && m_velocity < 0)
216         return true;
217
218     if (!swipingLeft && m_velocity > 0)
219         return true;
220
221     return (abs(m_progress) < swipeCancelArea && abs(m_velocity) < swipeCancelVelocityThreshold);
222 }
223
224 void ViewGestureController::SwipeProgressTracker::startAnimation()
225 {
226     m_cancelled = shouldCancel();
227
228     m_state = State::Animating;
229     m_viewGestureController.willEndSwipeGesture(*m_targetItem, m_cancelled);
230
231     m_startProgress = m_progress;
232     if (m_cancelled)
233         m_endProgress = 0;
234     else
235         m_endProgress = m_viewGestureController.isPhysicallySwipingLeft(m_direction) ? 1 : -1;
236
237     double velocity = swipeAnimationBaseVelocity;
238     if ((m_endProgress - m_progress) * m_velocity > 0)
239         velocity = m_velocity;
240
241     Seconds duration = Seconds::fromMilliseconds(std::abs((m_progress - m_endProgress) / velocity * swipeAnimationDurationMultiplier));
242     duration = clampTo<Seconds>(duration, swipeMinAnimationDuration, swipeMaxAnimationDuration);
243
244     GtkWidget* widget = m_webPageProxy.viewWidget();
245     m_startTime = Seconds::fromMicroseconds(gdk_frame_clock_get_frame_time(gtk_widget_get_frame_clock(widget)));
246     m_endTime = m_startTime + duration;
247
248     m_tickCallbackID = gtk_widget_add_tick_callback(widget, [](GtkWidget*, GdkFrameClock* frameClock, gpointer userData) -> gboolean {
249         auto* tracker = static_cast<SwipeProgressTracker*>(userData);
250         return tracker->onAnimationTick(frameClock);
251     }, this, nullptr);
252 }
253
254 static inline double easeOutCubic(double t)
255 {
256     double p = t - 1;
257     return p * p * p + 1;
258 }
259
260 gboolean ViewGestureController::SwipeProgressTracker::onAnimationTick(GdkFrameClock* frameClock)
261 {
262     ASSERT(m_state == State::Animating);
263     ASSERT(m_endTime > m_startTime);
264
265     Seconds frameTime = Seconds::fromMicroseconds(gdk_frame_clock_get_frame_time(frameClock));
266
267     double animationProgress = (frameTime - m_startTime) / (m_endTime - m_startTime);
268     if (animationProgress > 1)
269         animationProgress = 1;
270
271     m_progress = m_startProgress + (m_endProgress - m_startProgress) * easeOutCubic(animationProgress);
272
273     m_viewGestureController.handleSwipeGesture(m_targetItem.get(), m_progress, m_direction);
274     if (frameTime >= m_endTime) {
275         m_tickCallbackID = 0;
276         endAnimation();
277         return G_SOURCE_REMOVE;
278     }
279
280     return G_SOURCE_CONTINUE;
281 }
282
283 void ViewGestureController::SwipeProgressTracker::endAnimation()
284 {
285     m_state = State::Finishing;
286     m_viewGestureController.endSwipeGesture(m_targetItem.get(), m_cancelled);
287 }
288
289 void ViewGestureController::beginSwipeGesture(WebBackForwardListItem* targetItem, SwipeDirection direction)
290 {
291     ASSERT(targetItem);
292
293     m_webPageProxy.navigationGestureDidBegin();
294
295     willBeginGesture(ViewGestureType::Swipe);
296
297     if (auto* snapshot = targetItem->snapshot()) {
298         m_currentSwipeSnapshot = snapshot;
299
300         FloatSize viewSize(m_webPageProxy.viewSize());
301         if (snapshot->hasImage() && shouldUseSnapshotForSize(*snapshot, viewSize, 0))
302             m_currentSwipeSnapshotPattern = adoptRef(cairo_pattern_create_for_surface(snapshot->surface()));
303
304         Color color = snapshot->backgroundColor();
305         if (color.isValid()) {
306             m_backgroundColorForCurrentSnapshot = color;
307             if (!m_currentSwipeSnapshotPattern) {
308                 double red, green, blue, alpha;
309                 color.getRGBA(red, green, blue, alpha);
310                 m_currentSwipeSnapshotPattern = adoptRef(cairo_pattern_create_rgba(red, green, blue, alpha));
311             }
312         }
313     }
314
315     if (!m_currentSwipeSnapshotPattern)
316         m_currentSwipeSnapshotPattern = adoptRef(cairo_pattern_create_rgb(1, 1, 1));
317 }
318
319 void ViewGestureController::handleSwipeGesture(WebBackForwardListItem*, double, SwipeDirection)
320 {
321     gtk_widget_queue_draw(m_webPageProxy.viewWidget());
322 }
323
324 void ViewGestureController::draw(cairo_t* cr, cairo_pattern_t* pageGroup)
325 {
326     bool swipingLeft = isPhysicallySwipingLeft(m_swipeProgressTracker.direction());
327     bool swipingBack = m_swipeProgressTracker.direction() == SwipeDirection::Back;
328     bool isRTL = m_webPageProxy.userInterfaceLayoutDirection() == WebCore::UserInterfaceLayoutDirection::RTL;
329     float progress = m_swipeProgressTracker.progress();
330
331     double width = m_webPageProxy.drawingArea()->size().width();
332     double height = m_webPageProxy.drawingArea()->size().height();
333
334     double swipingLayerOffset = (swipingLeft ? 0 : width) + floor(width * progress);
335
336     double dimmingProgress = swipingLeft ? 1 - progress : -progress;
337     if (isRTL)
338         dimmingProgress = 1 - dimmingProgress;
339
340     double remainingSwipeDistance = dimmingProgress * width;
341     double shadowFadeDistance = swipeOverlayShadowWidth;
342
343     double shadowOpacity = swipeOverlayShadowOpacity;
344     if (remainingSwipeDistance < shadowFadeDistance)
345         shadowOpacity = (remainingSwipeDistance / shadowFadeDistance) * swipeOverlayShadowOpacity;
346
347     RefPtr<cairo_pattern_t> shadowPattern = adoptRef(cairo_pattern_create_linear(0, 0, swipeOverlayShadowWidth, 0));
348     for (int i = 0; i < 16; i++) {
349         double offset = swipeOverlayShadowGradientOffsets[i];
350         double alpha = swipeOverlayShadowGradientAlpha[i] * shadowOpacity;
351         cairo_pattern_add_color_stop_rgba(shadowPattern.get(), offset, 0, 0, 0, alpha);
352     }
353
354     cairo_save(cr);
355
356     if (isRTL)
357         cairo_rectangle(cr, swipingLayerOffset, 0, width - swipingLayerOffset, height);
358     else
359         cairo_rectangle(cr, 0, 0, swipingLayerOffset, height);
360     cairo_set_source(cr, swipingBack ? m_currentSwipeSnapshotPattern.get() : pageGroup);
361     cairo_fill_preserve(cr);
362
363     cairo_set_source_rgba(cr, 0, 0, 0, dimmingProgress * swipeOverlayDimmingOpacity);
364     cairo_fill(cr);
365
366     cairo_translate(cr, swipingLayerOffset, 0);
367
368     if (progress) {
369         cairo_save(cr);
370         if (!isRTL)
371             cairo_scale(cr, -1, 1);
372         cairo_rectangle(cr, 0, 0, swipeOverlayShadowWidth, height);
373         cairo_set_source(cr, shadowPattern.get());
374         cairo_fill(cr);
375         cairo_restore(cr);
376     }
377
378     if (isRTL) {
379         cairo_translate(cr, -width, 0);
380         cairo_rectangle(cr, width - swipingLayerOffset, 0, swipingLayerOffset, height);
381     } else
382         cairo_rectangle(cr, 0, 0, width - swipingLayerOffset, height);
383     cairo_set_source(cr, swipingBack ? pageGroup : m_currentSwipeSnapshotPattern.get());
384     cairo_fill(cr);
385
386     cairo_restore(cr);
387 }
388
389 void ViewGestureController::removeSwipeSnapshot()
390 {
391     m_snapshotRemovalTracker.reset();
392
393     m_hasOutstandingRepaintRequest = false;
394
395     if (m_activeGestureType != ViewGestureType::Swipe)
396         return;
397
398     m_currentSwipeSnapshotPattern = nullptr;
399
400     m_currentSwipeSnapshot = nullptr;
401
402     m_webPageProxy.navigationGestureSnapshotWasRemoved();
403
404     m_backgroundColorForCurrentSnapshot = Color();
405
406     didEndGesture();
407
408     m_swipeProgressTracker.reset();
409 }
410
411 static GUniquePtr<GdkEvent> createScrollEvent(GtkWidget* widget, double xDelta, double yDelta)
412 {
413     GdkWindow* window = gtk_widget_get_window(widget);
414
415     int x, y;
416     gdk_window_get_root_origin(window, &x, &y);
417
418     int width = gdk_window_get_width(window);
419     int height = gdk_window_get_height(window);
420
421     GUniquePtr<GdkEvent> event(gdk_event_new(GDK_SCROLL));
422     event->scroll.time = GDK_CURRENT_TIME;
423     event->scroll.x = width / 2;
424     event->scroll.y = height / 2;
425     event->scroll.x_root = x + width / 2;
426     event->scroll.y_root = y + height / 2;
427     event->scroll.direction = GDK_SCROLL_SMOOTH;
428     event->scroll.delta_x = xDelta;
429     event->scroll.delta_y = yDelta;
430     event->scroll.state = 0;
431     event->scroll.is_stop = !xDelta && !yDelta;
432     event->scroll.window = GDK_WINDOW(g_object_ref(window));
433     gdk_event_set_screen(event.get(), gdk_window_get_screen(window));
434     gdk_event_set_device(event.get(), gdk_device_manager_get_client_pointer(gdk_display_get_device_manager(gdk_window_get_display(window))));
435     gdk_event_set_source_device(event.get(), gdk_device_manager_get_client_pointer(gdk_display_get_device_manager(gdk_window_get_display(window))));
436
437     return event;
438 }
439
440 bool ViewGestureController::beginSimulatedSwipeInDirectionForTesting(SwipeDirection direction)
441 {
442     if (!canSwipeInDirection(direction))
443         return false;
444
445     m_isSimulatedSwipe = true;
446
447     double delta = swipeTouchpadBaseWidth / gtkScrollDeltaMultiplier * 0.75;
448
449     if (isPhysicallySwipingLeft(direction))
450         delta = -delta;
451
452     GUniquePtr<GdkEvent> event = createScrollEvent(m_webPageProxy.viewWidget(), delta, 0);
453     gtk_widget_event(m_webPageProxy.viewWidget(), event.get());
454
455     return true;
456 }
457
458 bool ViewGestureController::completeSimulatedSwipeInDirectionForTesting(SwipeDirection)
459 {
460     GUniquePtr<GdkEvent> event = createScrollEvent(m_webPageProxy.viewWidget(), 0, 0);
461     gtk_widget_event(m_webPageProxy.viewWidget(), event.get());
462
463     m_isSimulatedSwipe = false;
464
465     return true;
466 }
467
468 } // namespace WebKit