[iOS] did{Start,Finish}LoadForQuickLookDocumentInMainFrame is never called on WKNavig...
[WebKit-https.git] / Source / WebKit2 / UIProcess / ios / WebPageProxyIOS.mm
1 /*
2  * Copyright (C) 2012 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 #import "config.h"
27 #import "WebPageProxy.h"
28
29 #if PLATFORM(IOS)
30
31 #import "APIUIClient.h"
32 #import "DataReference.h"
33 #import "EditingRange.h"
34 #import "NativeWebKeyboardEvent.h"
35 #import "PageClient.h"
36 #import "RemoteLayerTreeDrawingAreaProxy.h"
37 #import "RemoteLayerTreeDrawingAreaProxyMessages.h"
38 #import "RemoteLayerTreeTransaction.h"
39 #import "UIKitSPI.h"
40 #import "UserData.h"
41 #import "ViewUpdateDispatcherMessages.h"
42 #import "WKBrowsingContextControllerInternal.h"
43 #import "WebKitSystemInterfaceIOS.h"
44 #import "WebPageMessages.h"
45 #import "WebProcessProxy.h"
46 #import "WebVideoFullscreenManagerProxy.h"
47 #import <WebCore/FrameView.h>
48 #import <WebCore/NotImplemented.h>
49 #import <WebCore/SharedBuffer.h>
50 #import <WebCore/UserAgent.h>
51
52 #if USE(QUICK_LOOK)
53 #import "APILoaderClient.h"
54 #import "APINavigationClient.h"
55 #import <wtf/text/WTFString.h>
56 #endif
57
58 using namespace WebCore;
59
60 namespace WebKit {
61
62 void WebPageProxy::platformInitialize()
63 {
64 }
65
66 static String webKitBundleVersionString()
67 {
68     return [[NSBundle bundleForClass:NSClassFromString(@"WKWebView")] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
69 }
70
71 String WebPageProxy::standardUserAgent(const String& applicationNameForUserAgent)
72 {
73     return standardUserAgentWithApplicationName(applicationNameForUserAgent, webKitBundleVersionString());
74 }
75
76 void WebPageProxy::getIsSpeaking(bool&)
77 {
78     notImplemented();
79 }
80
81 void WebPageProxy::speak(const String&)
82 {
83     notImplemented();
84 }
85
86 void WebPageProxy::stopSpeaking()
87 {
88     notImplemented();
89 }
90
91 void WebPageProxy::searchWithSpotlight(const String&)
92 {
93     notImplemented();
94 }
95
96 void WebPageProxy::searchTheWeb(const String&)
97 {
98     notImplemented();
99 }
100
101 void WebPageProxy::windowAndViewFramesChanged(const FloatRect&, const FloatPoint&)
102 {
103     notImplemented();
104 }
105
106 String WebPageProxy::stringSelectionForPasteboard()
107 {
108     notImplemented();
109     return String();
110 }
111
112 RefPtr<WebCore::SharedBuffer> WebPageProxy::dataSelectionForPasteboard(const String&)
113 {
114     notImplemented();
115     return nullptr;
116 }
117
118 bool WebPageProxy::readSelectionFromPasteboard(const String&)
119 {
120     notImplemented();
121     return false;
122 }
123
124 void WebPageProxy::performDictionaryLookupAtLocation(const WebCore::FloatPoint&)
125 {
126     notImplemented();
127 }
128
129 void WebPageProxy::gestureCallback(const WebCore::IntPoint& point, uint32_t gestureType, uint32_t gestureState, uint32_t flags, uint64_t callbackID)
130 {
131     auto callback = m_callbacks.take<GestureCallback>(callbackID);
132     if (!callback) {
133         ASSERT_NOT_REACHED();
134         return;
135     }
136     
137     callback->performCallbackWithReturnValue(point, gestureType, gestureState, flags);
138 }
139
140 void WebPageProxy::touchesCallback(const WebCore::IntPoint& point, uint32_t touches, uint64_t callbackID)
141 {
142     auto callback = m_callbacks.take<TouchesCallback>(callbackID);
143     if (!callback) {
144         ASSERT_NOT_REACHED();
145         return;
146     }
147
148     callback->performCallbackWithReturnValue(point, touches);
149 }
150
151 void WebPageProxy::autocorrectionDataCallback(const Vector<WebCore::FloatRect>& rects, const String& fontName, float fontSize, uint64_t fontTraits, uint64_t callbackID)
152 {
153     auto callback = m_callbacks.take<AutocorrectionDataCallback>(callbackID);
154     if (!callback) {
155         ASSERT_NOT_REACHED();
156         return;
157     }
158
159     callback->performCallbackWithReturnValue(rects, fontName, fontSize, fontTraits);
160 }
161
162 void WebPageProxy::dictationContextCallback(const String& selectedText, const String& beforeText, const String& afterText, uint64_t callbackID)
163 {
164     auto callback = m_callbacks.take<DictationContextCallback>(callbackID);
165     if (!callback) {
166         ASSERT_NOT_REACHED();
167         return;
168     }
169
170     callback->performCallbackWithReturnValue(selectedText, beforeText, afterText);
171 }
172
173 void WebPageProxy::autocorrectionContextCallback(const String& beforeText, const String& markedText, const String& selectedText, const String& afterText, uint64_t location, uint64_t length, uint64_t callbackID)
174 {
175     auto callback = m_callbacks.take<AutocorrectionContextCallback>(callbackID);
176     if (!callback) {
177         ASSERT_NOT_REACHED();
178         return;
179     }
180
181     callback->performCallbackWithReturnValue(beforeText, markedText, selectedText, afterText, location, length);
182 }
183
184 void WebPageProxy::updateVisibleContentRects(const WebCore::FloatRect& exposedRect, const WebCore::FloatRect& unobscuredRect, const WebCore::FloatRect& unobscuredRectInScrollViewCoordinates, const WebCore::FloatRect& customFixedPositionRect, double scale, bool inStableState, bool isChangingObscuredInsetsInteractively, double timestamp, double horizontalVelocity, double verticalVelocity, double scaleChangeRate)
185 {
186     if (!isValid())
187         return;
188
189     VisibleContentRectUpdateInfo visibleContentRectUpdateInfo(exposedRect, unobscuredRect, unobscuredRectInScrollViewCoordinates, customFixedPositionRect, scale, inStableState, isChangingObscuredInsetsInteractively, timestamp, horizontalVelocity, verticalVelocity, scaleChangeRate, downcast<RemoteLayerTreeDrawingAreaProxy>(*drawingArea()).lastCommittedLayerTreeTransactionID());
190
191     if (visibleContentRectUpdateInfo == m_lastVisibleContentRectUpdate)
192         return;
193
194     m_lastVisibleContentRectUpdate = visibleContentRectUpdateInfo;
195     m_process->send(Messages::ViewUpdateDispatcher::VisibleContentRectUpdate(m_pageID, visibleContentRectUpdateInfo), 0);
196 }
197
198 void WebPageProxy::resendLastVisibleContentRects()
199 {
200     m_process->send(Messages::ViewUpdateDispatcher::VisibleContentRectUpdate(m_pageID, m_lastVisibleContentRectUpdate), 0);
201 }
202
203 static inline float adjustedUnexposedEdge(float documentEdge, float exposedRectEdge, float factor)
204 {
205     if (exposedRectEdge < documentEdge)
206         return documentEdge - factor * (documentEdge - exposedRectEdge);
207     
208     return exposedRectEdge;
209 }
210
211 static inline float adjustedUnexposedMaxEdge(float documentEdge, float exposedRectEdge, float factor)
212 {
213     if (exposedRectEdge > documentEdge)
214         return documentEdge + factor * (exposedRectEdge - documentEdge);
215     
216     return exposedRectEdge;
217 }
218
219 WebCore::FloatRect WebPageProxy::computeCustomFixedPositionRect(const FloatRect& unobscuredContentRect, double displayedContentScale, UnobscuredRectConstraint constraint) const
220 {
221     FloatRect constrainedUnobscuredRect = unobscuredContentRect;
222     FloatRect documentRect = m_pageClient.documentRect();
223
224     if (m_pageClient.isAssistingNode())
225         return documentRect;
226
227     if (constraint == UnobscuredRectConstraint::ConstrainedToDocumentRect)
228         constrainedUnobscuredRect.intersect(documentRect);
229
230     double minimumScale = m_pageClient.minimumZoomScale();
231     
232     if (displayedContentScale < minimumScale) {
233         const CGFloat slope = 12;
234         CGFloat factor = std::max<CGFloat>(1 - slope * (minimumScale - displayedContentScale), 0);
235             
236         constrainedUnobscuredRect.setX(adjustedUnexposedEdge(documentRect.x(), constrainedUnobscuredRect.x(), factor));
237         constrainedUnobscuredRect.setY(adjustedUnexposedEdge(documentRect.y(), constrainedUnobscuredRect.y(), factor));
238         constrainedUnobscuredRect.setWidth(adjustedUnexposedMaxEdge(documentRect.maxX(), constrainedUnobscuredRect.maxX(), factor) - constrainedUnobscuredRect.x());
239         constrainedUnobscuredRect.setHeight(adjustedUnexposedMaxEdge(documentRect.maxY(), constrainedUnobscuredRect.maxY(), factor) - constrainedUnobscuredRect.y());
240     }
241     
242     return FrameView::rectForViewportConstrainedObjects(enclosingLayoutRect(constrainedUnobscuredRect), LayoutSize(documentRect.size()), displayedContentScale, false, StickToViewportBounds);
243 }
244
245 void WebPageProxy::overflowScrollViewWillStartPanGesture()
246 {
247     m_pageClient.overflowScrollViewWillStartPanGesture();
248 }
249
250 void WebPageProxy::overflowScrollViewDidScroll()
251 {
252     m_pageClient.overflowScrollViewDidScroll();
253 }
254
255 void WebPageProxy::overflowScrollWillStartScroll()
256 {
257     m_pageClient.overflowScrollWillStartScroll();
258 }
259
260 void WebPageProxy::overflowScrollDidEndScroll()
261 {
262     m_pageClient.overflowScrollDidEndScroll();
263 }
264
265 void WebPageProxy::dynamicViewportSizeUpdate(const FloatSize& minimumLayoutSize, const WebCore::FloatSize& maximumUnobscuredSize, const FloatRect& targetExposedContentRect, const FloatRect& targetUnobscuredRect, const FloatRect& targetUnobscuredRectInScrollViewCoordinates,  double targetScale, int32_t deviceOrientation)
266 {
267     if (!isValid())
268         return;
269
270     m_dynamicViewportSizeUpdateWaitingForTarget = true;
271     m_dynamicViewportSizeUpdateWaitingForLayerTreeCommit = true;
272     m_process->send(Messages::WebPage::DynamicViewportSizeUpdate(minimumLayoutSize, maximumUnobscuredSize, targetExposedContentRect, targetUnobscuredRect, targetUnobscuredRectInScrollViewCoordinates, targetScale, deviceOrientation, ++m_currentDynamicViewportSizeUpdateID), m_pageID);
273 }
274
275 void WebPageProxy::synchronizeDynamicViewportUpdate()
276 {
277     if (!isValid())
278         return;
279
280     if (m_dynamicViewportSizeUpdateWaitingForTarget) {
281         // We do not want the UIProcess to finish animated resize with the old content size, scale, etc.
282         // If that happens, the UIProcess would start pushing new VisibleContentRectUpdateInfo to the WebProcess with
283         // invalid informations.
284         //
285         // Ideally, the animated resize should just be transactional, and the UIProcess would remain in the "resize" state
286         // until both DynamicViewportUpdateChangedTarget and the associated commitLayerTree are finished.
287         // The tricky part with such implementation is if a second animated resize starts before the end of the previous one.
288         // In that case, the values used for the target state needs to be computed from the output of the previous animated resize.
289         //
290         // The following is a workaround to have the UIProcess in a consistent state.
291         // Instead of handling nested resize, we block the UIProcess until the animated resize finishes.
292         double newScale;
293         FloatPoint newScrollPosition;
294         uint64_t nextValidLayerTreeTransactionID;
295         if (m_process->sendSync(Messages::WebPage::SynchronizeDynamicViewportUpdate(), Messages::WebPage::SynchronizeDynamicViewportUpdate::Reply(newScale, newScrollPosition, nextValidLayerTreeTransactionID), m_pageID, std::chrono::seconds(2))) {
296             m_dynamicViewportSizeUpdateWaitingForTarget = false;
297             m_dynamicViewportSizeUpdateLayerTreeTransactionID = nextValidLayerTreeTransactionID;
298             m_pageClient.dynamicViewportUpdateChangedTarget(newScale, newScrollPosition, nextValidLayerTreeTransactionID);
299         }
300
301     }
302
303     // If m_dynamicViewportSizeUpdateWaitingForTarget is false, we are waiting for the next valid frame with the hope it is the one for the new target.
304     // If m_dynamicViewportSizeUpdateWaitingForTarget is still true, this is a desesperate attempt to get the valid frame before finishing the animation.
305     if (m_dynamicViewportSizeUpdateWaitingForLayerTreeCommit)
306         m_process->connection()->waitForAndDispatchImmediately<Messages::RemoteLayerTreeDrawingAreaProxy::CommitLayerTree>(m_pageID, std::chrono::seconds(1), IPC::InterruptWaitingIfSyncMessageArrives);
307
308     m_dynamicViewportSizeUpdateWaitingForTarget = false;
309     m_dynamicViewportSizeUpdateWaitingForLayerTreeCommit = false;
310 }
311
312 void WebPageProxy::setViewportConfigurationMinimumLayoutSize(const WebCore::FloatSize& size)
313 {
314     m_process->send(Messages::WebPage::SetViewportConfigurationMinimumLayoutSize(size), m_pageID);
315 }
316
317 void WebPageProxy::setMaximumUnobscuredSize(const WebCore::FloatSize& size)
318 {
319     m_process->send(Messages::WebPage::SetMaximumUnobscuredSize(size), m_pageID);
320 }
321
322 void WebPageProxy::setDeviceOrientation(int32_t deviceOrientation)
323 {
324     if (deviceOrientation != m_deviceOrientation) {
325         m_deviceOrientation = deviceOrientation;
326         if (isValid())
327             m_process->send(Messages::WebPage::SetDeviceOrientation(deviceOrientation), m_pageID);
328     }
329 }
330
331 static bool exceedsRenderTreeSizeSizeThreshold(uint64_t thresholdSize, uint64_t committedSize)
332 {
333     const double thesholdSizeFraction = 0.5; // Empirically-derived.
334     return committedSize > thresholdSize * thesholdSizeFraction;
335 }
336
337 void WebPageProxy::didCommitLayerTree(const WebKit::RemoteLayerTreeTransaction& layerTreeTransaction)
338 {
339     m_pageExtendedBackgroundColor = layerTreeTransaction.pageExtendedBackgroundColor();
340
341     if (!m_hasReceivedLayerTreeTransactionAfterDidCommitLoad) {
342         if (layerTreeTransaction.transactionID() >= m_firstLayerTreeTransactionIdAfterDidCommitLoad) {
343             m_hasReceivedLayerTreeTransactionAfterDidCommitLoad = true;
344             m_lastVisibleContentRectUpdate = VisibleContentRectUpdateInfo();
345         }
346     }
347
348     if (!m_dynamicViewportSizeUpdateWaitingForTarget && m_dynamicViewportSizeUpdateWaitingForLayerTreeCommit) {
349         if (layerTreeTransaction.transactionID() >= m_dynamicViewportSizeUpdateLayerTreeTransactionID)
350             m_dynamicViewportSizeUpdateWaitingForLayerTreeCommit = false;
351     }
352
353     m_pageClient.didCommitLayerTree(layerTreeTransaction);
354
355     if (m_wantsSessionRestorationRenderTreeSizeThresholdEvent && !m_hitRenderTreeSizeThreshold
356         && exceedsRenderTreeSizeSizeThreshold(m_sessionRestorationRenderTreeSize, layerTreeTransaction.renderTreeSize())) {
357         m_hitRenderTreeSizeThreshold = true;
358         didLayout(WebCore::ReachedSessionRestorationRenderTreeSizeThreshold, UserData());
359     }
360 }
361
362 void WebPageProxy::selectWithGesture(const WebCore::IntPoint point, WebCore::TextGranularity granularity, uint32_t gestureType, uint32_t gestureState, std::function<void (const WebCore::IntPoint&, uint32_t, uint32_t, uint32_t, CallbackBase::Error)> callbackFunction)
363 {
364     if (!isValid()) {
365         callbackFunction(WebCore::IntPoint(), 0, 0, 0, CallbackBase::Error::Unknown);
366         return;
367     }
368
369     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
370     m_process->send(Messages::WebPage::SelectWithGesture(point, (uint32_t)granularity, gestureType, gestureState, callbackID), m_pageID);
371 }
372
373 void WebPageProxy::updateSelectionWithTouches(const WebCore::IntPoint point, uint32_t touches, bool baseIsStart, std::function<void (const WebCore::IntPoint&, uint32_t, CallbackBase::Error)> callbackFunction)
374 {
375     if (!isValid()) {
376         callbackFunction(WebCore::IntPoint(), 0, CallbackBase::Error::Unknown);
377         return;
378     }
379
380     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
381     m_process->send(Messages::WebPage::UpdateSelectionWithTouches(point, touches, baseIsStart, callbackID), m_pageID);
382 }
383     
384 void WebPageProxy::replaceDictatedText(const String& oldText, const String& newText)
385 {
386     m_process->send(Messages::WebPage::ReplaceDictatedText(oldText, newText), m_pageID);
387 }
388
389 void WebPageProxy::replaceSelectedText(const String& oldText, const String& newText)
390 {
391     m_process->send(Messages::WebPage::ReplaceSelectedText(oldText, newText), m_pageID);
392 }
393
394 void WebPageProxy::requestAutocorrectionData(const String& textForAutocorrection, std::function<void (const Vector<WebCore::FloatRect>&, const String&, double, uint64_t, CallbackBase::Error)> callbackFunction)
395 {
396     if (!isValid()) {
397         callbackFunction(Vector<WebCore::FloatRect>(), String(), 0, 0, CallbackBase::Error::Unknown);
398         return;
399     }
400
401     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
402     m_process->send(Messages::WebPage::RequestAutocorrectionData(textForAutocorrection, callbackID), m_pageID);
403 }
404
405 void WebPageProxy::applyAutocorrection(const String& correction, const String& originalText, std::function<void (const String&, CallbackBase::Error)> callbackFunction)
406 {
407     if (!isValid()) {
408         callbackFunction(String(), CallbackBase::Error::Unknown);
409         return;
410     }
411
412     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
413     m_process->send(Messages::WebPage::ApplyAutocorrection(correction, originalText, callbackID), m_pageID);
414 }
415
416 void WebPageProxy::executeEditCommand(const String& commandName, std::function<void (CallbackBase::Error)> callbackFunction)
417 {
418     if (!isValid()) {
419         callbackFunction(CallbackBase::Error::Unknown);
420         return;
421     }
422     
423     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
424     m_process->send(Messages::WebPage::ExecuteEditCommandWithCallback(commandName, callbackID), m_pageID);
425 }
426
427 bool WebPageProxy::applyAutocorrection(const String& correction, const String& originalText)
428 {
429     bool autocorrectionApplied = false;
430     m_process->sendSync(Messages::WebPage::SyncApplyAutocorrection(correction, originalText), Messages::WebPage::SyncApplyAutocorrection::Reply(autocorrectionApplied), m_pageID);
431     return autocorrectionApplied;
432 }
433
434 void WebPageProxy::selectTextWithGranularityAtPoint(const WebCore::IntPoint point, WebCore::TextGranularity granularity, std::function<void (CallbackBase::Error)> callbackFunction)
435 {
436     if (!isValid()) {
437         callbackFunction(CallbackBase::Error::Unknown);
438         return;
439     }
440     
441     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
442     m_process->send(Messages::WebPage::SelectTextWithGranularityAtPoint(point, static_cast<uint32_t>(granularity), callbackID), m_pageID);
443 }
444
445 void WebPageProxy::selectPositionAtBoundaryWithDirection(const WebCore::IntPoint point, WebCore::TextGranularity granularity, WebCore::SelectionDirection direction, std::function<void (CallbackBase::Error)> callbackFunction)
446 {
447     if (!isValid()) {
448         callbackFunction(CallbackBase::Error::Unknown);
449         return;
450     }
451     
452     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
453     m_process->send(Messages::WebPage::SelectPositionAtBoundaryWithDirection(point, static_cast<uint32_t>(granularity), static_cast<uint32_t>(direction), callbackID), m_pageID);
454 }
455
456 void WebPageProxy::moveSelectionAtBoundaryWithDirection(WebCore::TextGranularity granularity, WebCore::SelectionDirection direction, std::function<void(CallbackBase::Error)> callbackFunction)
457 {
458     if (!isValid()) {
459         callbackFunction(CallbackBase::Error::Unknown);
460         return;
461     }
462     
463     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
464     m_process->send(Messages::WebPage::MoveSelectionAtBoundaryWithDirection(static_cast<uint32_t>(granularity), static_cast<uint32_t>(direction), callbackID), m_pageID);
465 }
466     
467 void WebPageProxy::selectPositionAtPoint(const WebCore::IntPoint point, std::function<void (CallbackBase::Error)> callbackFunction)
468 {
469     if (!isValid()) {
470         callbackFunction(CallbackBase::Error::Unknown);
471         return;
472     }
473     
474     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
475     m_process->send(Messages::WebPage::SelectPositionAtPoint(point, callbackID), m_pageID);
476 }
477
478 void WebPageProxy::beginSelectionInDirection(WebCore::SelectionDirection direction, std::function<void (uint64_t, CallbackBase::Error)> callbackFunction)
479 {
480     if (!isValid()) {
481         callbackFunction(0, CallbackBase::Error::Unknown);
482         return;
483     }
484     
485     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
486     m_process->send(Messages::WebPage::BeginSelectionInDirection(direction, callbackID), m_pageID);
487 }
488
489 void WebPageProxy::updateSelectionWithExtentPoint(const WebCore::IntPoint point, std::function<void (uint64_t, CallbackBase::Error)> callbackFunction)
490 {
491     if (!isValid()) {
492         callbackFunction(0, CallbackBase::Error::Unknown);
493         return;
494     }
495     
496     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
497     m_process->send(Messages::WebPage::UpdateSelectionWithExtentPoint(point, callbackID), m_pageID);
498     
499 }
500
501 void WebPageProxy::updateSelectionWithExtentPointAndBoundary(const WebCore::IntPoint point, WebCore::TextGranularity granularity, std::function<void(uint64_t, CallbackBase::Error)> callbackFunction)
502 {
503     if (!isValid()) {
504         callbackFunction(0, CallbackBase::Error::Unknown);
505         return;
506     }
507     
508     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
509     m_process->send(Messages::WebPage::UpdateSelectionWithExtentPointAndBoundary(point, granularity, callbackID), m_pageID);
510     
511 }
512
513 void WebPageProxy::requestDictationContext(std::function<void (const String&, const String&, const String&, CallbackBase::Error)> callbackFunction)
514 {
515     if (!isValid()) {
516         callbackFunction(String(), String(), String(), CallbackBase::Error::Unknown);
517         return;
518     }
519
520     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
521     m_process->send(Messages::WebPage::RequestDictationContext(callbackID), m_pageID);
522 }
523
524 void WebPageProxy::requestAutocorrectionContext(std::function<void (const String&, const String&, const String&, const String&, uint64_t, uint64_t, CallbackBase::Error)> callbackFunction)
525 {
526     if (!isValid()) {
527         callbackFunction(String(), String(), String(), String(), 0, 0, CallbackBase::Error::Unknown);
528         return;
529     }
530
531     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
532     m_process->send(Messages::WebPage::RequestAutocorrectionContext(callbackID), m_pageID);
533 }
534
535 void WebPageProxy::getAutocorrectionContext(String& beforeContext, String& markedText, String& selectedText, String& afterContext, uint64_t& location, uint64_t& length)
536 {
537     m_process->sendSync(Messages::WebPage::GetAutocorrectionContext(), Messages::WebPage::GetAutocorrectionContext::Reply(beforeContext, markedText, selectedText, afterContext, location, length), m_pageID);
538 }
539
540 void WebPageProxy::getLookupContextAtPoint(const WebCore::IntPoint& point, std::function<void(const String&, CallbackBase::Error)> callbackFunction)
541 {
542     if (!isValid()) {
543         callbackFunction(String(), CallbackBase::Error::Unknown);
544         return;
545     }
546     
547     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
548     m_process->send(Messages::WebPage::GetLookupContextAtPoint(point, callbackID), m_pageID);
549 }
550
551 void WebPageProxy::selectWithTwoTouches(const WebCore::IntPoint from, const WebCore::IntPoint to, uint32_t gestureType, uint32_t gestureState, std::function<void (const WebCore::IntPoint&, uint32_t, uint32_t, uint32_t, CallbackBase::Error)> callbackFunction)
552 {
553     if (!isValid()) {
554         callbackFunction(WebCore::IntPoint(), 0, 0, 0, CallbackBase::Error::Unknown);
555         return;
556     }
557
558     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
559     m_process->send(Messages::WebPage::SelectWithTwoTouches(from, to, gestureType, gestureState, callbackID), m_pageID);
560 }
561
562 void WebPageProxy::updateBlockSelectionWithTouch(const WebCore::IntPoint point, uint32_t touch, uint32_t handlePosition)
563 {
564     m_process->send(Messages::WebPage::UpdateBlockSelectionWithTouch(point, touch, handlePosition), m_pageID);
565 }
566
567 void WebPageProxy::didReceivePositionInformation(const InteractionInformationAtPosition& info)
568 {
569     m_pageClient.positionInformationDidChange(info);
570 }
571
572 void WebPageProxy::getPositionInformation(const WebCore::IntPoint& point, InteractionInformationAtPosition& info)
573 {
574     m_process->sendSync(Messages::WebPage::GetPositionInformation(point), Messages::WebPage::GetPositionInformation::Reply(info), m_pageID);
575 }
576
577 void WebPageProxy::requestPositionInformation(const WebCore::IntPoint& point)
578 {
579     m_process->send(Messages::WebPage::RequestPositionInformation(point), m_pageID);
580 }
581
582 void WebPageProxy::startInteractionWithElementAtPosition(const WebCore::IntPoint& point)
583 {
584     m_process->send(Messages::WebPage::StartInteractionWithElementAtPosition(point), m_pageID);
585 }
586
587 void WebPageProxy::stopInteraction()
588 {
589     m_process->send(Messages::WebPage::StopInteraction(), m_pageID);
590 }
591
592 void WebPageProxy::performActionOnElement(uint32_t action)
593 {
594     m_process->send(Messages::WebPage::PerformActionOnElement(action), m_pageID);
595 }
596
597 void WebPageProxy::saveImageToLibrary(const SharedMemory::Handle& imageHandle, uint64_t imageSize)
598 {
599     RefPtr<SharedMemory> sharedMemoryBuffer = SharedMemory::map(imageHandle, SharedMemory::Protection::ReadOnly);
600     RefPtr<SharedBuffer> buffer = SharedBuffer::create(static_cast<unsigned char*>(sharedMemoryBuffer->data()), imageSize);
601     m_pageClient.saveImageToLibrary(buffer);
602 }
603
604 void WebPageProxy::didUpdateBlockSelectionWithTouch(uint32_t touch, uint32_t flags, float growThreshold, float shrinkThreshold)
605 {
606     m_pageClient.didUpdateBlockSelectionWithTouch(touch, flags, growThreshold, shrinkThreshold);
607 }
608
609 void WebPageProxy::applicationDidEnterBackground()
610 {
611     bool isSuspendedUnderLock = [UIApp isSuspendedUnderLock];
612     m_process->send(Messages::WebPage::ApplicationDidEnterBackground(isSuspendedUnderLock), m_pageID);
613 }
614
615 void WebPageProxy::applicationWillEnterForeground()
616 {
617     m_process->send(Messages::WebPage::ApplicationWillEnterForeground(), m_pageID);
618 }
619
620 void WebPageProxy::applicationWillResignActive()
621 {
622     m_process->send(Messages::WebPage::ApplicationWillResignActive(), m_pageID);
623 }
624
625 void WebPageProxy::applicationDidBecomeActive()
626 {
627     m_process->send(Messages::WebPage::ApplicationDidBecomeActive(), m_pageID);
628 }
629
630 void WebPageProxy::extendSelection(WebCore::TextGranularity granularity)
631 {
632     m_process->send(Messages::WebPage::ExtendSelection(static_cast<uint32_t>(granularity)), m_pageID);
633 }
634
635 void WebPageProxy::selectWordBackward()
636 {
637     m_process->send(Messages::WebPage::SelectWordBackward(), m_pageID);
638 }
639
640 void WebPageProxy::moveSelectionByOffset(int32_t offset, std::function<void (CallbackBase::Error)> callbackFunction)
641 {
642     if (!isValid()) {
643         callbackFunction(CallbackBase::Error::Unknown);
644         return;
645     }
646     
647     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
648     m_process->send(Messages::WebPage::MoveSelectionByOffset(offset, callbackID), m_pageID);
649 }
650
651 void WebPageProxy::interpretKeyEvent(const EditorState& state, bool isCharEvent, bool& handled)
652 {
653     m_editorState = state;
654     handled = m_pageClient.interpretKeyEvent(m_keyEventQueue.first(), isCharEvent);
655 }
656
657 // Complex text input support for plug-ins.
658 void WebPageProxy::sendComplexTextInputToPlugin(uint64_t, const String&)
659 {
660     notImplemented();
661 }
662
663 void WebPageProxy::setSmartInsertDeleteEnabled(bool)
664 {
665     notImplemented();
666 }
667
668 void WebPageProxy::registerWebProcessAccessibilityToken(const IPC::DataReference& data)
669 {
670     m_pageClient.accessibilityWebProcessTokenReceived(data);
671 }    
672
673 void WebPageProxy::makeFirstResponder()
674 {
675     notImplemented();
676 }
677
678 void WebPageProxy::registerUIProcessAccessibilityTokens(const IPC::DataReference& elementToken, const IPC::DataReference& windowToken)
679 {
680     if (!isValid())
681         return;
682     
683     process().send(Messages::WebPage::RegisterUIProcessAccessibilityTokens(elementToken, windowToken), m_pageID);
684 }
685
686 void WebPageProxy::pluginFocusOrWindowFocusChanged(uint64_t, bool)
687 {
688     notImplemented();
689 }
690
691 void WebPageProxy::setPluginComplexTextInputState(uint64_t, uint64_t)
692 {
693     notImplemented();
694 }
695
696 void WebPageProxy::executeSavedCommandBySelector(const String&, bool&)
697 {
698     notImplemented();
699 }
700
701 bool WebPageProxy::shouldDelayWindowOrderingForEvent(const WebKit::WebMouseEvent&)
702 {
703     notImplemented();
704     return false;
705 }
706
707 bool WebPageProxy::acceptsFirstMouse(int, const WebKit::WebMouseEvent&)
708 {
709     notImplemented();
710     return false;
711 }
712
713 void WebPageProxy::willStartUserTriggeredZooming()
714 {
715     process().send(Messages::WebPage::WillStartUserTriggeredZooming(), m_pageID);
716 }
717
718 void WebPageProxy::potentialTapAtPosition(const WebCore::FloatPoint& position, uint64_t& requestID)
719 {
720     process().send(Messages::WebPage::PotentialTapAtPosition(requestID, position), m_pageID);
721 }
722
723 void WebPageProxy::commitPotentialTap()
724 {
725     process().send(Messages::WebPage::CommitPotentialTap(m_layerTreeTransactionIdAtLastTouchStart), m_pageID);
726 }
727
728 void WebPageProxy::cancelPotentialTap()
729 {
730     process().send(Messages::WebPage::CancelPotentialTap(), m_pageID);
731 }
732
733 void WebPageProxy::tapHighlightAtPosition(const WebCore::FloatPoint& position, uint64_t& requestID)
734 {
735     process().send(Messages::WebPage::TapHighlightAtPosition(requestID, position), m_pageID);
736 }
737
738 void WebPageProxy::handleTap(const FloatPoint& location)
739 {
740     process().send(Messages::WebPage::HandleTap(roundedIntPoint(location), m_layerTreeTransactionIdAtLastTouchStart), m_pageID);
741 }
742
743 void WebPageProxy::inspectorNodeSearchMovedToPosition(const WebCore::FloatPoint& position)
744 {
745     process().send(Messages::WebPage::InspectorNodeSearchMovedToPosition(position), m_pageID);
746 }
747
748 void WebPageProxy::inspectorNodeSearchEndedAtPosition(const WebCore::FloatPoint& position)
749 {
750     process().send(Messages::WebPage::InspectorNodeSearchEndedAtPosition(position), m_pageID);
751 }
752
753 void WebPageProxy::blurAssistedNode()
754 {
755     process().send(Messages::WebPage::BlurAssistedNode(), m_pageID);
756 }
757
758 FloatSize WebPageProxy::screenSize()
759 {
760     return FloatSize(WKGetScreenSize());
761 }
762
763 FloatSize WebPageProxy::availableScreenSize()
764 {
765     return FloatSize(WKGetAvailableScreenSize());
766 }
767     
768 float WebPageProxy::textAutosizingWidth()
769 {
770     return WKGetScreenSize().width;
771 }
772
773 void WebPageProxy::dynamicViewportUpdateChangedTarget(double newScale, const WebCore::FloatPoint& newScrollPosition, uint64_t dynamicViewportSizeUpdateID)
774 {
775     if (dynamicViewportSizeUpdateID != m_currentDynamicViewportSizeUpdateID)
776         return;
777
778     if (m_dynamicViewportSizeUpdateWaitingForTarget) {
779         m_dynamicViewportSizeUpdateLayerTreeTransactionID = downcast<RemoteLayerTreeDrawingAreaProxy>(*drawingArea()).nextLayerTreeTransactionID();
780         m_dynamicViewportSizeUpdateWaitingForTarget = false;
781         m_pageClient.dynamicViewportUpdateChangedTarget(newScale, newScrollPosition, m_dynamicViewportSizeUpdateLayerTreeTransactionID);
782     }
783 }
784
785 void WebPageProxy::couldNotRestorePageState()
786 {
787     m_pageClient.couldNotRestorePageState();
788 }
789
790 void WebPageProxy::restorePageState(const WebCore::FloatRect& exposedRect, double scale)
791 {
792     m_pageClient.restorePageState(exposedRect, scale);
793 }
794
795 void WebPageProxy::restorePageCenterAndScale(const WebCore::FloatPoint& center, double scale)
796 {
797     m_pageClient.restorePageCenterAndScale(center, scale);
798 }
799
800 void WebPageProxy::didGetTapHighlightGeometries(uint64_t requestID, const WebCore::Color& color, const Vector<WebCore::FloatQuad>& highlightedQuads, const WebCore::IntSize& topLeftRadius, const WebCore::IntSize& topRightRadius, const WebCore::IntSize& bottomLeftRadius, const WebCore::IntSize& bottomRightRadius)
801 {
802     m_pageClient.didGetTapHighlightGeometries(requestID, color, highlightedQuads, topLeftRadius, topRightRadius, bottomLeftRadius, bottomRightRadius);
803 }
804
805 void WebPageProxy::startAssistingNode(const AssistedNodeInformation& information, bool userIsInteracting, bool blurPreviousNode, const UserData& userData)
806 {
807     m_pageClient.startAssistingNode(information, userIsInteracting, blurPreviousNode, process().transformHandlesToObjects(userData.object()).get());
808 }
809
810 void WebPageProxy::stopAssistingNode()
811 {
812     m_pageClient.stopAssistingNode();
813 }
814
815 void WebPageProxy::showInspectorHighlight(const WebCore::Highlight& highlight)
816 {
817     m_pageClient.showInspectorHighlight(highlight);
818 }
819
820 void WebPageProxy::hideInspectorHighlight()
821 {
822     m_pageClient.hideInspectorHighlight();
823 }
824
825 void WebPageProxy::showInspectorIndication()
826 {
827     m_pageClient.showInspectorIndication();
828 }
829
830 void WebPageProxy::hideInspectorIndication()
831 {
832     m_pageClient.hideInspectorIndication();
833 }
834
835 void WebPageProxy::enableInspectorNodeSearch()
836 {
837     m_pageClient.enableInspectorNodeSearch();
838 }
839
840 void WebPageProxy::disableInspectorNodeSearch()
841 {
842     m_pageClient.disableInspectorNodeSearch();
843 }
844
845 void WebPageProxy::focusNextAssistedNode(bool isForward, std::function<void (CallbackBase::Error)> callbackFunction)
846 {
847     if (!isValid()) {
848         callbackFunction(CallbackBase::Error::Unknown);
849         return;
850     }
851     
852     uint64_t callbackID = m_callbacks.put(WTF::move(callbackFunction), m_process->throttler().backgroundActivityToken());
853     process().send(Messages::WebPage::FocusNextAssistedNode(isForward, callbackID), m_pageID);
854 }
855
856 void WebPageProxy::setAssistedNodeValue(const String& value)
857 {
858     process().send(Messages::WebPage::SetAssistedNodeValue(value), m_pageID);
859 }
860
861 void WebPageProxy::setAssistedNodeValueAsNumber(double value)
862 {
863     process().send(Messages::WebPage::SetAssistedNodeValueAsNumber(value), m_pageID);
864 }
865
866 void WebPageProxy::setAssistedNodeSelectedIndex(uint32_t index, bool allowMultipleSelection)
867 {
868     process().send(Messages::WebPage::SetAssistedNodeSelectedIndex(index, allowMultipleSelection), m_pageID);
869 }
870
871 void WebPageProxy::didPerformDictionaryLookup(const DictionaryPopupInfo&)
872 {
873     notImplemented();
874 }
875
876 void WebPageProxy::savePDFToTemporaryFolderAndOpenWithNativeApplication(const String&, const String&, const IPC::DataReference&, const String&)
877 {
878     notImplemented();
879 }
880
881 void WebPageProxy::savePDFToTemporaryFolderAndOpenWithNativeApplicationRaw(const String&, const String&, const uint8_t*, unsigned long, const String&)
882 {
883     notImplemented();
884 }
885
886 void WebPageProxy::openPDFFromTemporaryFolderWithNativeApplication(const String&)
887 {
888     notImplemented();
889 }
890
891 void WebPageProxy::setAcceleratedCompositingRootLayer(LayerOrView* rootLayer)
892 {
893     m_pageClient.setAcceleratedCompositingRootLayer(rootLayer);
894 }
895
896 void WebPageProxy::showPlaybackTargetPicker(bool hasVideo, const IntRect& elementRect)
897 {
898     m_pageClient.showPlaybackTargetPicker(hasVideo, elementRect);
899 }
900
901 void WebPageProxy::zoomToRect(FloatRect rect, double minimumScale, double maximumScale)
902 {
903     m_pageClient.zoomToRect(rect, minimumScale, maximumScale);
904 }
905
906 void WebPageProxy::commitPotentialTapFailed()
907 {
908     m_pageClient.commitPotentialTapFailed();
909 }
910
911 void WebPageProxy::didNotHandleTapAsClick(const WebCore::IntPoint& point)
912 {
913     m_uiClient->didNotHandleTapAsClick(point);
914 }
915
916 void WebPageProxy::viewportMetaTagWidthDidChange(float width)
917 {
918     m_pageClient.didChangeViewportMetaTagWidth(width);
919 }
920
921 void WebPageProxy::didFinishDrawingPagesToPDF(const IPC::DataReference& pdfData)
922 {
923     m_pageClient.didFinishDrawingPagesToPDF(pdfData);
924 }
925
926 void WebPageProxy::contentSizeCategoryDidChange(const String& contentSizeCategory)
927 {
928     process().send(Messages::WebPage::ContentSizeCategoryDidChange(contentSizeCategory), m_pageID);
929 }
930
931 void WebPageProxy::editorStateChanged(const EditorState& editorState)
932 {
933     bool couldChangeSecureInputState = m_editorState.isInPasswordField != editorState.isInPasswordField || m_editorState.selectionIsNone;
934     
935     m_editorState = editorState;
936     
937     // Selection being none is a temporary state when editing. Flipping secure input state too quickly was causing trouble (not fully understood).
938     if (couldChangeSecureInputState && !editorState.selectionIsNone)
939         m_pageClient.updateSecureInputState();
940     
941     if (editorState.shouldIgnoreCompositionSelectionChange)
942         return;
943     
944     // We always need to notify the client on iOS to make sure the selection is redrawn,
945     // even during composition to support phrase boundary gesture.
946     m_pageClient.selectionDidChange();
947 }
948
949 #if USE(QUICK_LOOK)
950     
951 void WebPageProxy::didStartLoadForQuickLookDocumentInMainFrame(const String& fileName, const String& uti)
952 {
953     // Ensure that fileName isn't really a path name
954     static_assert(notFound + 1 == 0, "The following line assumes WTF::notFound equals -1");
955     if (m_navigationClient)
956         m_navigationClient->didStartLoadForQuickLookDocumentInMainFrame(fileName.substring(fileName.reverseFind('/') + 1), uti);
957     else
958         m_loaderClient->didStartLoadForQuickLookDocumentInMainFrame(fileName.substring(fileName.reverseFind('/') + 1), uti);
959 }
960
961 void WebPageProxy::didFinishLoadForQuickLookDocumentInMainFrame(const QuickLookDocumentData& data)
962 {
963     if (m_navigationClient)
964         m_navigationClient->didFinishLoadForQuickLookDocumentInMainFrame(data);
965     else
966         m_loaderClient->didFinishLoadForQuickLookDocumentInMainFrame(data);
967 }
968 #endif
969
970 } // namespace WebKit
971
972 #endif // PLATFORM(IOS)