f902376410955d2c5fd184e9427572ff640088ab
[WebKit-https.git] / Source / WebKit / UIProcess / Cocoa / ViewGestureController.h
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 #ifndef ViewGestureController_h
27 #define ViewGestureController_h
28
29 #include "MessageReceiver.h"
30 #include "SameDocumentNavigationType.h"
31 #include <WebCore/Color.h>
32 #include <WebCore/FloatRect.h>
33 #include <wtf/BlockPtr.h>
34 #include <wtf/MonotonicTime.h>
35 #include <wtf/RetainPtr.h>
36 #include <wtf/RunLoop.h>
37 #include <wtf/WeakPtr.h>
38
39 OBJC_CLASS CALayer;
40
41 #if PLATFORM(IOS_FAMILY)
42 OBJC_CLASS UIGestureRecognizer;
43 OBJC_CLASS UIView;
44 OBJC_CLASS WKSwipeTransitionController;
45 OBJC_CLASS _UINavigationInteractiveTransitionBase;
46 OBJC_CLASS _UIViewControllerOneToOneTransitionContext;
47 OBJC_CLASS _UIViewControllerTransitionContext;
48 #else
49 OBJC_CLASS CAGradientLayer;
50 OBJC_CLASS NSEvent;
51 OBJC_CLASS NSView;
52 OBJC_CLASS WKSwipeCancellationTracker;
53 #endif
54
55 namespace WebCore {
56 class IOSurface;
57 }
58
59 namespace WebKit {
60
61 class ViewSnapshot;
62 class WebBackForwardListItem;
63 class WebPageProxy;
64 class WebProcessProxy;
65
66 class ViewGestureController : private IPC::MessageReceiver {
67     WTF_MAKE_NONCOPYABLE(ViewGestureController);
68 public:
69     ViewGestureController(WebPageProxy&);
70     ~ViewGestureController();
71     void platformTeardown();
72
73     void disconnectFromProcess();
74     void connectToProcess();
75     
76     enum class ViewGestureType {
77         None,
78 #if PLATFORM(MAC)
79         Magnification,
80         SmartMagnification,
81 #endif
82         Swipe
83     };
84
85     enum class SwipeDirection {
86         Back,
87         Forward
88     };
89
90     typedef uint64_t GestureID;
91
92 #if PLATFORM(MAC)
93     double magnification() const;
94
95     void handleMagnificationGestureEvent(NSEvent *, WebCore::FloatPoint origin);
96
97     bool hasActiveMagnificationGesture() const { return m_activeGestureType == ViewGestureType::Magnification; }
98
99     void handleSmartMagnificationGesture(WebCore::FloatPoint origin);
100
101     bool handleScrollWheelEvent(NSEvent *);
102     void wheelEventWasNotHandledByWebCore(NSEvent *event) { m_pendingSwipeTracker.eventWasNotHandledByWebCore(event); }
103     void gestureEventWasNotHandledByWebCore(NSEvent *, WebCore::FloatPoint origin);
104
105     void setCustomSwipeViews(Vector<RetainPtr<NSView>> views) { m_customSwipeViews = WTFMove(views); }
106     void setCustomSwipeViewsTopContentInset(float topContentInset) { m_customSwipeViewsTopContentInset = topContentInset; }
107     WebCore::FloatRect windowRelativeBoundsForCustomSwipeViews() const;
108     void setDidMoveSwipeSnapshotCallback(BlockPtr<void (CGRect)>&& callback) { m_didMoveSwipeSnapshotCallback = WTFMove(callback); }
109
110     bool shouldIgnorePinnedState() { return m_pendingSwipeTracker.shouldIgnorePinnedState(); }
111     void setShouldIgnorePinnedState(bool ignore) { m_pendingSwipeTracker.setShouldIgnorePinnedState(ignore); }
112
113     bool isPhysicallySwipingLeft(SwipeDirection) const;
114 #else
115     bool isNavigationSwipeGestureRecognizer(UIGestureRecognizer *) const;
116     void installSwipeHandler(UIView *gestureRecognizerView, UIView *swipingView);
117     void beginSwipeGesture(_UINavigationInteractiveTransitionBase *, SwipeDirection);
118     void endSwipeGesture(WebBackForwardListItem* targetItem, _UIViewControllerTransitionContext *, bool cancelled);
119     void willCommitPostSwipeTransitionLayerTree(bool);
120     void setRenderTreeSize(uint64_t);
121 #endif
122     
123     void setAlternateBackForwardListSourcePage(WebPageProxy*);
124     
125     bool canSwipeInDirection(SwipeDirection) const;
126
127     WebCore::Color backgroundColorForCurrentSnapshot() const { return m_backgroundColorForCurrentSnapshot; }
128
129     void didStartProvisionalLoadForMainFrame();
130     void didFinishLoadForMainFrame() { didReachMainFrameLoadTerminalState(); }
131     void didFailLoadForMainFrame() { didReachMainFrameLoadTerminalState(); }
132     void didFirstVisuallyNonEmptyLayoutForMainFrame();
133     void didRepaintAfterNavigation();
134     void didHitRenderTreeSizeThreshold();
135     void didRestoreScrollPosition();
136     void didReachMainFrameLoadTerminalState();
137     void didSameDocumentNavigationForMainFrame(SameDocumentNavigationType);
138
139     void checkForActiveLoads();
140
141     void removeSwipeSnapshot();
142
143     void setSwipeGestureEnabled(bool enabled) { m_swipeGestureEnabled = enabled; }
144     bool isSwipeGestureEnabled() { return m_swipeGestureEnabled; }
145
146     // Testing
147     bool beginSimulatedSwipeInDirectionForTesting(SwipeDirection);
148     bool completeSimulatedSwipeInDirectionForTesting(SwipeDirection);
149
150 private:
151     // IPC::MessageReceiver.
152     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
153
154     static ViewGestureController* controllerForGesture(uint64_t pageID, GestureID);
155
156     static GestureID takeNextGestureID();
157     void willBeginGesture(ViewGestureType);
158     void didEndGesture();
159
160     void didStartProvisionalOrSameDocumentLoadForMainFrame();
161
162     class SnapshotRemovalTracker {
163     public:
164         enum Event : uint8_t {
165             VisuallyNonEmptyLayout = 1 << 0,
166             RenderTreeSizeThreshold = 1 << 1,
167             RepaintAfterNavigation = 1 << 2,
168             MainFrameLoad = 1 << 3,
169             SubresourceLoads = 1 << 4,
170             ScrollPositionRestoration = 1 << 5
171         };
172         typedef uint8_t Events;
173
174         SnapshotRemovalTracker();
175
176         void start(Events, WTF::Function<void()>&&);
177         void reset();
178         
179         void pause() { m_paused = true; }
180         void resume();
181         bool isPaused() const { return m_paused; }
182
183         bool eventOccurred(Events);
184         bool cancelOutstandingEvent(Events);
185         bool hasOutstandingEvent(Event);
186
187         void startWatchdog(Seconds);
188
189         uint64_t renderTreeSizeThreshold() const { return m_renderTreeSizeThreshold; }
190         void setRenderTreeSizeThreshold(uint64_t threshold) { m_renderTreeSizeThreshold = threshold; }
191
192     private:
193         static String eventsDescription(Events);
194         void log(const String&) const;
195
196         void fireRemovalCallbackImmediately();
197         void fireRemovalCallbackIfPossible();
198         void watchdogTimerFired();
199
200         bool stopWaitingForEvent(Events, const String& logReason);
201
202         Events m_outstandingEvents { 0 };
203         WTF::Function<void()> m_removalCallback;
204         MonotonicTime m_startTime;
205
206         uint64_t m_renderTreeSizeThreshold { 0 };
207
208         RunLoop::Timer<SnapshotRemovalTracker> m_watchdogTimer;
209         
210         bool m_paused { true };
211     };
212
213 #if PLATFORM(MAC)
214     // Message handlers.
215     void didCollectGeometryForMagnificationGesture(WebCore::FloatRect visibleContentBounds, bool frameHandlesMagnificationGesture);
216     void didCollectGeometryForSmartMagnificationGesture(WebCore::FloatPoint origin, WebCore::FloatRect renderRect, WebCore::FloatRect visibleContentBounds, bool fitEntireRect, double viewportMinimumScale, double viewportMaximumScale);
217
218     void endMagnificationGesture();
219
220     WebCore::FloatPoint scaledMagnificationOrigin(WebCore::FloatPoint origin, double scale);
221
222     void trackSwipeGesture(NSEvent *, SwipeDirection);
223     void beginSwipeGesture(WebBackForwardListItem* targetItem, SwipeDirection);
224     void handleSwipeGesture(WebBackForwardListItem* targetItem, double progress, SwipeDirection);
225     void willEndSwipeGesture(WebBackForwardListItem& targetItem, bool cancelled);
226     void endSwipeGesture(WebBackForwardListItem* targetItem, bool cancelled);
227     bool shouldUseSnapshotForSize(ViewSnapshot&, WebCore::FloatSize swipeLayerSize, float topContentInset);
228
229     CALayer *determineSnapshotLayerParent() const;
230     CALayer *determineLayerAdjacentToSnapshotForParent(SwipeDirection, CALayer *snapshotLayerParent) const;
231     void applyDebuggingPropertiesToSwipeViews();
232     void didMoveSwipeSnapshotLayer();
233
234     void forceRepaintIfNeeded();
235
236     void requestRenderTreeSizeNotificationIfNeeded();
237
238     class PendingSwipeTracker {
239     public:
240         PendingSwipeTracker(WebPageProxy&, ViewGestureController&);
241         bool handleEvent(NSEvent *);
242         void eventWasNotHandledByWebCore(NSEvent *);
243
244         void reset(const char* resetReasonForLogging);
245
246         bool shouldIgnorePinnedState() { return m_shouldIgnorePinnedState; }
247         void setShouldIgnorePinnedState(bool ignore) { m_shouldIgnorePinnedState = ignore; }
248
249     private:
250         bool tryToStartSwipe(NSEvent *);
251         bool scrollEventCanBecomeSwipe(NSEvent *, SwipeDirection&);
252
253         enum class State {
254             None,
255             WaitingForWebCore,
256             InsufficientMagnitude
257         };
258
259         State m_state { State::None };
260         SwipeDirection m_direction;
261         WebCore::FloatSize m_cumulativeDelta;
262
263         bool m_shouldIgnorePinnedState { false };
264
265         ViewGestureController& m_viewGestureController;
266         WebPageProxy& m_webPageProxy;
267     };
268 #endif
269
270     WebPageProxy& m_webPageProxy;
271     ViewGestureType m_activeGestureType { ViewGestureType::None };
272
273     bool m_swipeGestureEnabled { true };
274
275     RunLoop::Timer<ViewGestureController> m_swipeActiveLoadMonitoringTimer;
276
277     WebCore::Color m_backgroundColorForCurrentSnapshot;
278     
279     WeakPtr<WebPageProxy> m_alternateBackForwardListSourcePage;
280     RefPtr<WebPageProxy> m_webPageProxyForBackForwardListForCurrentSwipe;
281
282     GestureID m_currentGestureID;
283
284 #if PLATFORM(MAC)
285     RefPtr<ViewSnapshot> m_currentSwipeSnapshot;
286
287     double m_magnification;
288     WebCore::FloatPoint m_magnificationOrigin;
289
290     WebCore::FloatRect m_lastSmartMagnificationUnscaledTargetRect;
291     bool m_lastMagnificationGestureWasSmartMagnification { false };
292     WebCore::FloatPoint m_lastSmartMagnificationOrigin;
293
294     WebCore::FloatRect m_visibleContentRect;
295     bool m_visibleContentRectIsValid { false };
296     bool m_frameHandlesMagnificationGesture { false };
297
298     RetainPtr<WKSwipeCancellationTracker> m_swipeCancellationTracker;
299     RetainPtr<CALayer> m_swipeLayer;
300     RetainPtr<CALayer> m_swipeSnapshotLayer;
301     RetainPtr<CAGradientLayer> m_swipeShadowLayer;
302     RetainPtr<CALayer> m_swipeDimmingLayer;
303     Vector<RetainPtr<CALayer>> m_currentSwipeLiveLayers;
304
305     Vector<RetainPtr<NSView>> m_customSwipeViews;
306     float m_customSwipeViewsTopContentInset { 0 };
307     WebCore::FloatRect m_currentSwipeCustomViewBounds;
308
309     PendingSwipeTracker m_pendingSwipeTracker;
310
311     BlockPtr<void (CGRect)> m_didMoveSwipeSnapshotCallback;
312
313     bool m_hasOutstandingRepaintRequest { false };
314 #else    
315     UIView *m_liveSwipeView { nullptr };
316     RetainPtr<UIView> m_liveSwipeViewClippingView;
317     RetainPtr<UIView> m_snapshotView;
318     RetainPtr<UIView> m_transitionContainerView;
319     RetainPtr<WKSwipeTransitionController> m_swipeInteractiveTransitionDelegate;
320     RetainPtr<_UIViewControllerOneToOneTransitionContext> m_swipeTransitionContext;
321     uint64_t m_snapshotRemovalTargetRenderTreeSize { 0 };
322 #endif
323     bool m_isConnectedToProcess { false };
324
325     SnapshotRemovalTracker m_snapshotRemovalTracker;
326     WTF::Function<void()> m_loadCallback;
327 };
328
329 } // namespace WebKit
330
331 #endif // ViewGestureController_h