0b1d2b112a2b6d7e8a608ec0b30cb38f9404e8d2
[WebKit-https.git] / Source / WebKit2 / UIProcess / Cocoa / UIDelegate.mm
1 /*
2  * Copyright (C) 2014-2016 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 "UIDelegate.h"
28
29 #if WK_API_ENABLED
30
31 #import "APIFrameInfo.h"
32 #import "CompletionHandlerCallChecker.h"
33 #import "NavigationActionData.h"
34 #import "UserMediaPermissionCheckProxy.h"
35 #import "UserMediaPermissionRequestProxy.h"
36 #import "WKFrameInfoInternal.h"
37 #import "WKNavigationActionInternal.h"
38 #import "WKOpenPanelParametersInternal.h"
39 #import "WKSecurityOriginInternal.h"
40 #import "WKUIDelegatePrivate.h"
41 #import "WKWebViewConfigurationInternal.h"
42 #import "WKWebViewInternal.h"
43 #import "WKWindowFeaturesInternal.h"
44 #import "WebOpenPanelResultListenerProxy.h"
45 #import "WebProcessProxy.h"
46 #import "_WKContextMenuElementInfo.h"
47 #import "_WKFrameHandleInternal.h"
48 #import <WebCore/SecurityOriginData.h>
49 #import <WebCore/URL.h>
50 #import <wtf/BlockPtr.h>
51
52 #if PLATFORM(IOS)
53 #import <AVFoundation/AVCaptureDevice.h>
54 #import <AVFoundation/AVMediaFormat.h>
55 #import <WebCore/SoftLinking.h>
56
57 SOFT_LINK_FRAMEWORK(AVFoundation);
58 SOFT_LINK_CLASS(AVFoundation, AVCaptureDevice);
59 SOFT_LINK_CONSTANT(AVFoundation, AVMediaTypeAudio, NSString *);
60 SOFT_LINK_CONSTANT(AVFoundation, AVMediaTypeVideo, NSString *);
61 #endif
62
63 namespace WebKit {
64
65 UIDelegate::UIDelegate(WKWebView *webView)
66     : m_webView(webView)
67 {
68 }
69
70 UIDelegate::~UIDelegate()
71 {
72 }
73
74 #if ENABLE(CONTEXT_MENUS)
75 std::unique_ptr<API::ContextMenuClient> UIDelegate::createContextMenuClient()
76 {
77     return std::make_unique<ContextMenuClient>(*this);
78 }
79 #endif
80
81 std::unique_ptr<API::UIClient> UIDelegate::createUIClient()
82 {
83     return std::make_unique<UIClient>(*this);
84 }
85
86 RetainPtr<id <WKUIDelegate> > UIDelegate::delegate()
87 {
88     return m_delegate.get();
89 }
90
91 void UIDelegate::setDelegate(id <WKUIDelegate> delegate)
92 {
93     m_delegate = delegate;
94
95     m_delegateMethods.webViewCreateWebViewWithConfigurationForNavigationActionWindowFeatures = [delegate respondsToSelector:@selector(webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:)];
96     m_delegateMethods.webViewCreateWebViewWithConfigurationForNavigationActionWindowFeaturesAsync = [delegate respondsToSelector:@selector(_webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:completionHandler:)];
97     m_delegateMethods.webViewRunJavaScriptAlertPanelWithMessageInitiatedByFrameCompletionHandler = [delegate respondsToSelector:@selector(webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:)];
98     m_delegateMethods.webViewRunJavaScriptConfirmPanelWithMessageInitiatedByFrameCompletionHandler = [delegate respondsToSelector:@selector(webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:)];
99     m_delegateMethods.webViewRunJavaScriptTextInputPanelWithPromptDefaultTextInitiatedByFrameCompletionHandler = [delegate respondsToSelector:@selector(webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:completionHandler:)];
100     m_delegateMethods.webViewRunBeforeUnloadConfirmPanelWithMessageInitiatedByFrameCompletionHandler = [delegate respondsToSelector:@selector(_webView:runBeforeUnloadConfirmPanelWithMessage:initiatedByFrame:completionHandler:)];
101
102 #if PLATFORM(MAC)
103     m_delegateMethods.webViewRunOpenPanelWithParametersInitiatedByFrameCompletionHandler = [delegate respondsToSelector:@selector(webView:runOpenPanelWithParameters:initiatedByFrame:completionHandler:)];
104 #endif
105
106     m_delegateMethods.webViewDecideDatabaseQuotaForSecurityOriginCurrentQuotaCurrentOriginUsageCurrentDatabaseUsageExpectedUsageDecisionHandler = [delegate respondsToSelector:@selector(_webView:decideDatabaseQuotaForSecurityOrigin:currentQuota:currentOriginUsage:currentDatabaseUsage:expectedUsage:decisionHandler:)];
107     m_delegateMethods.webViewDecideWebApplicationCacheQuotaForSecurityOriginCurrentQuotaTotalBytesNeeded = [delegate respondsToSelector:@selector(_webView:decideWebApplicationCacheQuotaForSecurityOrigin:currentQuota:totalBytesNeeded:decisionHandler:)];
108     m_delegateMethods.webViewPrintFrame = [delegate respondsToSelector:@selector(_webView:printFrame:)];
109     m_delegateMethods.webViewDidClose = [delegate respondsToSelector:@selector(webViewDidClose:)];
110     m_delegateMethods.webViewClose = [delegate respondsToSelector:@selector(_webViewClose:)];
111     m_delegateMethods.webViewFullscreenMayReturnToInline = [delegate respondsToSelector:@selector(_webViewFullscreenMayReturnToInline:)];
112     m_delegateMethods.webViewDidEnterFullscreen = [delegate respondsToSelector:@selector(_webViewDidEnterFullscreen:)];
113     m_delegateMethods.webViewDidExitFullscreen = [delegate respondsToSelector:@selector(_webViewDidExitFullscreen:)];
114 #if PLATFORM(IOS)
115 #if HAVE(APP_LINKS)
116     m_delegateMethods.webViewShouldIncludeAppLinkActionsForElement = [delegate respondsToSelector:@selector(_webView:shouldIncludeAppLinkActionsForElement:)];
117 #endif
118     m_delegateMethods.webViewActionsForElementDefaultActions = [delegate respondsToSelector:@selector(_webView:actionsForElement:defaultActions:)];
119     m_delegateMethods.webViewDidNotHandleTapAsClickAtPoint = [delegate respondsToSelector:@selector(_webView:didNotHandleTapAsClickAtPoint:)];
120     m_delegateMethods.presentingViewControllerForWebView = [delegate respondsToSelector:@selector(_presentingViewControllerForWebView:)];
121 #endif
122     m_delegateMethods.webViewRequestUserMediaAuthorizationForDevicesURLMainFrameURLDecisionHandler = [delegate respondsToSelector:@selector(_webView:requestUserMediaAuthorizationForDevices:url:mainFrameURL:decisionHandler:)];
123     m_delegateMethods.webViewCheckUserMediaPermissionForURLMainFrameURLFrameIdentifierDecisionHandler = [delegate respondsToSelector:@selector(_webView:checkUserMediaPermissionForURL:mainFrameURL:frameIdentifier:decisionHandler:)];
124     m_delegateMethods.webViewMediaCaptureStateDidChange = [delegate respondsToSelector:@selector(_webView:mediaCaptureStateDidChange:)];
125     m_delegateMethods.dataDetectionContextForWebView = [delegate respondsToSelector:@selector(_dataDetectionContextForWebView:)];
126     m_delegateMethods.webViewImageOrMediaDocumentSizeChanged = [delegate respondsToSelector:@selector(_webView:imageOrMediaDocumentSizeChanged:)];
127
128 #if ENABLE(POINTER_LOCK)
129     m_delegateMethods.webViewRequestPointerLock = [delegate respondsToSelector:@selector(_webViewRequestPointerLock:)];
130     m_delegateMethods.webViewDidLosePointerLock = [delegate respondsToSelector:@selector(_webViewDidLosePointerLock:)];
131 #endif
132 #if ENABLE(CONTEXT_MENUS)
133     m_delegateMethods.webViewContextMenuForElement = [delegate respondsToSelector:@selector(_webView:contextMenu:forElement:)];
134     m_delegateMethods.webViewContextMenuForElementUserInfo = [delegate respondsToSelector:@selector(_webView:contextMenu:forElement:userInfo:)];
135 #endif
136     
137     m_delegateMethods.webViewHasVideoInPictureInPictureDidChange = [delegate respondsToSelector:@selector(_webView:hasVideoInPictureInPictureDidChange:)];
138 }
139
140 #if ENABLE(CONTEXT_MENUS)
141 UIDelegate::ContextMenuClient::ContextMenuClient(UIDelegate& uiDelegate)
142     : m_uiDelegate(uiDelegate)
143 {
144 }
145
146 UIDelegate::ContextMenuClient::~ContextMenuClient()
147 {
148 }
149
150 RetainPtr<NSMenu> UIDelegate::ContextMenuClient::menuFromProposedMenu(WebKit::WebPageProxy&, NSMenu *menu, const WebKit::WebHitTestResultData&, API::Object* userInfo)
151 {
152     if (!m_uiDelegate.m_delegateMethods.webViewContextMenuForElement && !m_uiDelegate.m_delegateMethods.webViewContextMenuForElementUserInfo)
153         return menu;
154
155     auto delegate = m_uiDelegate.m_delegate.get();
156     if (!delegate)
157         return menu;
158
159     auto contextMenuElementInfo = adoptNS([[_WKContextMenuElementInfo alloc] init]);
160
161     if (m_uiDelegate.m_delegateMethods.webViewContextMenuForElement)
162         return [(id <WKUIDelegatePrivate>)delegate _webView:m_uiDelegate.m_webView contextMenu:menu forElement:contextMenuElementInfo.get()];
163
164     return [(id <WKUIDelegatePrivate>)delegate _webView:m_uiDelegate.m_webView contextMenu:menu forElement:contextMenuElementInfo.get() userInfo:static_cast<id <NSSecureCoding>>(userInfo->wrapper())];
165 }
166 #endif
167
168 UIDelegate::UIClient::UIClient(UIDelegate& uiDelegate)
169     : m_uiDelegate(uiDelegate)
170 {
171 }
172
173 UIDelegate::UIClient::~UIClient()
174 {
175 }
176
177 RefPtr<WebKit::WebPageProxy> UIDelegate::UIClient::createNewPageCommon(WebKit::WebPageProxy* page, API::FrameInfo& sourceFrameInfo, const WebCore::ResourceRequest& request, const WebCore::WindowFeatures& windowFeatures, const WebKit::NavigationActionData& navigationActionData, WTF::Function<void (RefPtr<WebKit::WebPageProxy>)>&& completionHandler)
178 {
179     auto delegate = m_uiDelegate.m_delegate.get();
180     ASSERT(delegate);
181
182     auto configuration = adoptNS([m_uiDelegate.m_webView->_configuration copy]);
183     [configuration _setRelatedWebView:m_uiDelegate.m_webView];
184
185     auto userInitiatedActivity = page->process().userInitiatedActivity(navigationActionData.userGestureTokenIdentifier);
186     bool shouldOpenAppLinks = !hostsAreEqual(sourceFrameInfo.request().url(), request.url());
187     auto apiNavigationAction = API::NavigationAction::create(navigationActionData, &sourceFrameInfo, nullptr, request, WebCore::URL(), shouldOpenAppLinks, userInitiatedActivity);
188
189     auto apiWindowFeatures = API::WindowFeatures::create(windowFeatures);
190
191     if (completionHandler) {
192         RefPtr<CompletionHandlerCallChecker> checker = CompletionHandlerCallChecker::create(delegate.get(), @selector(_webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:completionHandler:));
193
194         [(id <WKUIDelegatePrivate>)delegate _webView:m_uiDelegate.m_webView createWebViewWithConfiguration:configuration.get() forNavigationAction:wrapper(apiNavigationAction) windowFeatures:wrapper(apiWindowFeatures) completionHandler:BlockPtr<void (WKWebView *)>::fromCallable([completionHandler = WTFMove(completionHandler), checker = WTFMove(checker), relatedWebView = RetainPtr<WKWebView>(m_uiDelegate.m_webView)](WKWebView *webView) {
195             if (checker->completionHandlerHasBeenCalled())
196                 return;
197             checker->didCallCompletionHandler();
198
199             if (!webView) {
200                 completionHandler(nullptr);
201                 return;
202             }
203
204             if ([webView->_configuration _relatedWebView] != relatedWebView.get())
205                 [NSException raise:NSInternalInconsistencyException format:@"Returned WKWebView was not created with the given configuration."];
206
207             completionHandler(webView->_page.get());
208         }).get()];
209
210         return nullptr;
211     }
212
213     RetainPtr<WKWebView> webView = [delegate webView:m_uiDelegate.m_webView createWebViewWithConfiguration:configuration.get() forNavigationAction:wrapper(apiNavigationAction) windowFeatures:wrapper(apiWindowFeatures)];
214
215     if (!webView)
216         return nullptr;
217
218     if ([webView->_configuration _relatedWebView] != m_uiDelegate.m_webView)
219         [NSException raise:NSInternalInconsistencyException format:@"Returned WKWebView was not created with the given configuration."];
220
221     return webView->_page.get();
222 }
223
224 RefPtr<WebKit::WebPageProxy> UIDelegate::UIClient::createNewPage(WebKit::WebPageProxy* page, API::FrameInfo& originatingFrameInfo, const WebCore::ResourceRequest& request, const WebCore::WindowFeatures& windowFeatures, const WebKit::NavigationActionData& navigationActionData)
225 {
226     if (!m_uiDelegate.m_delegateMethods.webViewCreateWebViewWithConfigurationForNavigationActionWindowFeatures)
227         return nullptr;
228
229     auto delegate = m_uiDelegate.m_delegate.get();
230     if (!delegate)
231         return nullptr;
232
233     return createNewPageCommon(page, originatingFrameInfo, request, windowFeatures, navigationActionData, nullptr);
234 }
235
236 bool UIDelegate::UIClient::createNewPageAsync(WebKit::WebPageProxy* page, API::FrameInfo& originatingFrameInfo, const WebCore::ResourceRequest& request, const WebCore::WindowFeatures& windowFeatures, const WebKit::NavigationActionData& navigationActionData, WTF::Function<void (RefPtr<WebKit::WebPageProxy>)>&& completionHandler)
237 {
238     if (!m_uiDelegate.m_delegateMethods.webViewCreateWebViewWithConfigurationForNavigationActionWindowFeaturesAsync)
239         return false;
240
241     auto delegate = m_uiDelegate.m_delegate.get();
242     if (!delegate)
243         return false;
244
245     createNewPageCommon(page, originatingFrameInfo, request, windowFeatures, navigationActionData, WTFMove(completionHandler));
246
247     return true;
248 }
249
250 void UIDelegate::UIClient::runJavaScriptAlert(WebKit::WebPageProxy*, const WTF::String& message, WebKit::WebFrameProxy* webFrameProxy, const WebCore::SecurityOriginData& securityOriginData, Function<void ()>&& completionHandler)
251 {
252     if (!m_uiDelegate.m_delegateMethods.webViewRunJavaScriptAlertPanelWithMessageInitiatedByFrameCompletionHandler) {
253         completionHandler();
254         return;
255     }
256
257     auto delegate = m_uiDelegate.m_delegate.get();
258     if (!delegate) {
259         completionHandler();
260         return;
261     }
262
263     RefPtr<CompletionHandlerCallChecker> checker = CompletionHandlerCallChecker::create(delegate.get(), @selector(webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:));
264     [delegate webView:m_uiDelegate.m_webView runJavaScriptAlertPanelWithMessage:message initiatedByFrame:wrapper(API::FrameInfo::create(*webFrameProxy, securityOriginData.securityOrigin())) completionHandler:BlockPtr<void ()>::fromCallable([completionHandler = WTFMove(completionHandler), checker = WTFMove(checker)] {
265         if (checker->completionHandlerHasBeenCalled())
266             return;
267         completionHandler();
268         checker->didCallCompletionHandler();
269     }).get()];
270 }
271
272 void UIDelegate::UIClient::runJavaScriptConfirm(WebKit::WebPageProxy*, const WTF::String& message, WebKit::WebFrameProxy* webFrameProxy, const WebCore::SecurityOriginData& securityOriginData, Function<void (bool)>&& completionHandler)
273 {
274     if (!m_uiDelegate.m_delegateMethods.webViewRunJavaScriptConfirmPanelWithMessageInitiatedByFrameCompletionHandler) {
275         completionHandler(false);
276         return;
277     }
278
279     auto delegate = m_uiDelegate.m_delegate.get();
280     if (!delegate) {
281         completionHandler(false);
282         return;
283     }
284
285     RefPtr<CompletionHandlerCallChecker> checker = CompletionHandlerCallChecker::create(delegate.get(), @selector(webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:));
286     [delegate webView:m_uiDelegate.m_webView runJavaScriptConfirmPanelWithMessage:message initiatedByFrame:wrapper(API::FrameInfo::create(*webFrameProxy, securityOriginData.securityOrigin())) completionHandler:BlockPtr<void (BOOL)>::fromCallable([completionHandler = WTFMove(completionHandler), checker = WTFMove(checker)](BOOL result) {
287         if (checker->completionHandlerHasBeenCalled())
288             return;
289         completionHandler(result);
290         checker->didCallCompletionHandler();
291     }).get()];
292 }
293
294 void UIDelegate::UIClient::runJavaScriptPrompt(WebKit::WebPageProxy*, const WTF::String& message, const WTF::String& defaultValue, WebKit::WebFrameProxy* webFrameProxy, const WebCore::SecurityOriginData& securityOriginData, Function<void (const WTF::String&)>&& completionHandler)
295 {
296     if (!m_uiDelegate.m_delegateMethods.webViewRunJavaScriptTextInputPanelWithPromptDefaultTextInitiatedByFrameCompletionHandler) {
297         completionHandler(String());
298         return;
299     }
300
301     auto delegate = m_uiDelegate.m_delegate.get();
302     if (!delegate) {
303         completionHandler(String());
304         return;
305     }
306
307     RefPtr<CompletionHandlerCallChecker> checker = CompletionHandlerCallChecker::create(delegate.get(), @selector(webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:completionHandler:));
308     [delegate webView:m_uiDelegate.m_webView runJavaScriptTextInputPanelWithPrompt:message defaultText:defaultValue initiatedByFrame:wrapper(API::FrameInfo::create(*webFrameProxy, securityOriginData.securityOrigin())) completionHandler:BlockPtr<void (NSString *)>::fromCallable([completionHandler = WTFMove(completionHandler), checker = WTFMove(checker)](NSString *result) {
309         if (checker->completionHandlerHasBeenCalled())
310             return;
311         completionHandler(result);
312         checker->didCallCompletionHandler();
313     }).get()];
314 }
315
316 bool UIDelegate::UIClient::canRunBeforeUnloadConfirmPanel() const
317 {
318     return m_uiDelegate.m_delegateMethods.webViewRunBeforeUnloadConfirmPanelWithMessageInitiatedByFrameCompletionHandler;
319 }
320
321 void UIDelegate::UIClient::runBeforeUnloadConfirmPanel(WebKit::WebPageProxy*, const WTF::String& message, WebKit::WebFrameProxy* webFrameProxy, const WebCore::SecurityOriginData& securityOriginData, Function<void (bool)>&& completionHandler)
322 {
323     if (!m_uiDelegate.m_delegateMethods.webViewRunBeforeUnloadConfirmPanelWithMessageInitiatedByFrameCompletionHandler) {
324         completionHandler(false);
325         return;
326     }
327
328     auto delegate = m_uiDelegate.m_delegate.get();
329     if (!delegate) {
330         completionHandler(false);
331         return;
332     }
333
334     RefPtr<CompletionHandlerCallChecker> checker = CompletionHandlerCallChecker::create(delegate.get(), @selector(_webView:runBeforeUnloadConfirmPanelWithMessage:initiatedByFrame:completionHandler:));
335     [(id <WKUIDelegatePrivate>)delegate _webView:m_uiDelegate.m_webView runBeforeUnloadConfirmPanelWithMessage:message initiatedByFrame:wrapper(API::FrameInfo::create(*webFrameProxy, securityOriginData.securityOrigin())) completionHandler:BlockPtr<void (BOOL)>::fromCallable([completionHandler = WTFMove(completionHandler), checker = WTFMove(checker)](BOOL result) {
336         if (checker->completionHandlerHasBeenCalled())
337             return;
338         completionHandler(result);
339         checker->didCallCompletionHandler();
340     }).get()];
341 }
342
343 void UIDelegate::UIClient::exceededDatabaseQuota(WebPageProxy*, WebFrameProxy*, API::SecurityOrigin* securityOrigin, const WTF::String& databaseName, const WTF::String& displayName, unsigned long long currentQuota, unsigned long long currentOriginUsage, unsigned long long currentUsage, unsigned long long expectedUsage, Function<void (unsigned long long)>&& completionHandler)
344 {
345     if (!m_uiDelegate.m_delegateMethods.webViewDecideDatabaseQuotaForSecurityOriginCurrentQuotaCurrentOriginUsageCurrentDatabaseUsageExpectedUsageDecisionHandler) {
346
347         // Use 50 MB as the default database quota.
348         unsigned long long defaultPerOriginDatabaseQuota = 50 * 1024 * 1024;
349
350         completionHandler(defaultPerOriginDatabaseQuota);
351         return;
352     }
353
354     auto delegate = m_uiDelegate.m_delegate.get();
355     if (!delegate) {
356         completionHandler(currentQuota);
357         return;
358     }
359
360     ASSERT(securityOrigin);
361     RefPtr<CompletionHandlerCallChecker> checker = CompletionHandlerCallChecker::create(delegate.get(), @selector(_webView:decideDatabaseQuotaForSecurityOrigin:currentQuota:currentOriginUsage:currentDatabaseUsage:expectedUsage:decisionHandler:));
362     [(id <WKUIDelegatePrivate>)delegate _webView:m_uiDelegate.m_webView decideDatabaseQuotaForSecurityOrigin:wrapper(*securityOrigin) currentQuota:currentQuota currentOriginUsage:currentOriginUsage currentDatabaseUsage:currentUsage expectedUsage:expectedUsage decisionHandler:BlockPtr<void (unsigned long long newQuota)>::fromCallable([completionHandler = WTFMove(completionHandler), checker = WTFMove(checker)](unsigned long long newQuota) {
363         if (checker->completionHandlerHasBeenCalled())
364             return;
365         checker->didCallCompletionHandler();
366         completionHandler(newQuota);
367     }).get()];
368 }
369
370 #if PLATFORM(MAC)
371 bool UIDelegate::UIClient::runOpenPanel(WebPageProxy*, WebFrameProxy* webFrameProxy, const WebCore::SecurityOriginData& securityOriginData, API::OpenPanelParameters* openPanelParameters, WebOpenPanelResultListenerProxy* listener)
372 {
373     if (!m_uiDelegate.m_delegateMethods.webViewRunOpenPanelWithParametersInitiatedByFrameCompletionHandler)
374         return false;
375
376     auto delegate = m_uiDelegate.m_delegate.get();
377     if (!delegate)
378         return false;
379
380     auto frame = API::FrameInfo::create(*webFrameProxy, securityOriginData.securityOrigin());
381     RefPtr<WebOpenPanelResultListenerProxy> resultListener = listener;
382
383     RefPtr<CompletionHandlerCallChecker> checker = CompletionHandlerCallChecker::create(delegate.get(), @selector(webView:runOpenPanelWithParameters:initiatedByFrame:completionHandler:));
384
385     [delegate webView:m_uiDelegate.m_webView runOpenPanelWithParameters:wrapper(*openPanelParameters) initiatedByFrame:wrapper(frame) completionHandler:[checker, resultListener](NSArray *URLs) {
386         if (checker->completionHandlerHasBeenCalled())
387             return;
388         checker->didCallCompletionHandler();
389
390         if (!URLs) {
391             resultListener->cancel();
392             return;
393         }
394
395         Vector<String> filenames;
396         for (NSURL *url in URLs)
397             filenames.append(url.path);
398
399         resultListener->chooseFiles(filenames);
400     }];
401
402     return true;
403 }
404 #endif
405
406 static void requestUserMediaAuthorizationForDevices(const WebKit::WebFrameProxy& frame, WebKit::UserMediaPermissionRequestProxy& request, id <WKUIDelegatePrivate> delegate, WKWebView& webView)
407 {
408     auto decisionHandler = BlockPtr<void(BOOL)>::fromCallable([protectedRequest = makeRef(request)](BOOL authorized) {
409         if (!authorized) {
410             protectedRequest->deny(UserMediaPermissionRequestProxy::UserMediaAccessDenialReason::PermissionDenied);
411             return;
412         }
413         const String& videoDeviceUID = protectedRequest->requiresVideo() ? protectedRequest->videoDeviceUIDs().first() : String();
414         const String& audioDeviceUID = protectedRequest->requiresAudio() ? protectedRequest->audioDeviceUIDs().first() : String();
415         protectedRequest->allow(audioDeviceUID, videoDeviceUID);
416     });
417
418     const WebFrameProxy* mainFrame = frame.page()->mainFrame();
419     WebCore::URL requestFrameURL(WebCore::URL(), frame.url());
420     WebCore::URL mainFrameURL(WebCore::URL(), mainFrame->url());
421
422     _WKCaptureDevices devices = 0;
423     if (request.requiresAudio())
424         devices |= _WKCaptureDeviceMicrophone;
425     if (request.requiresVideo())
426         devices |= _WKCaptureDeviceCamera;
427
428     auto protectedWebView = RetainPtr<WKWebView>(&webView);
429     [delegate _webView:protectedWebView.get() requestUserMediaAuthorizationForDevices:devices url:requestFrameURL mainFrameURL:mainFrameURL decisionHandler:decisionHandler.get()];
430 }
431
432 bool UIDelegate::UIClient::decidePolicyForUserMediaPermissionRequest(WebKit::WebPageProxy& page, WebKit::WebFrameProxy& frame, API::SecurityOrigin& userMediaOrigin, API::SecurityOrigin& topLevelOrigin, WebKit::UserMediaPermissionRequestProxy& request)
433 {
434     auto delegate = m_uiDelegate.m_delegate.get();
435     if (!delegate || !m_uiDelegate.m_delegateMethods.webViewRequestUserMediaAuthorizationForDevicesURLMainFrameURLDecisionHandler) {
436         request.deny(UserMediaPermissionRequestProxy::UserMediaAccessDenialReason::UserMediaDisabled);
437         return true;
438     }
439
440     bool requiresAudio = request.requiresAudio();
441     bool requiresVideo = request.requiresVideo();
442     if (!requiresAudio && !requiresVideo) {
443         request.deny(UserMediaPermissionRequestProxy::UserMediaAccessDenialReason::NoConstraints);
444         return true;
445     }
446
447 #if PLATFORM(IOS)
448     auto requestCameraAuthorization = BlockPtr<void()>::fromCallable([this, &frame, protectedRequest = makeRef(request), webView = RetainPtr<WKWebView>(m_uiDelegate.m_webView)]() {
449
450         if (!protectedRequest->requiresVideo()) {
451             requestUserMediaAuthorizationForDevices(frame, protectedRequest, (id <WKUIDelegatePrivate>)m_uiDelegate.m_delegate.get(), *webView.get());
452             return;
453         }
454         AVAuthorizationStatus cameraAuthorizationStatus = [getAVCaptureDeviceClass() authorizationStatusForMediaType:getAVMediaTypeVideo()];
455         switch (cameraAuthorizationStatus) {
456         case AVAuthorizationStatusAuthorized:
457             requestUserMediaAuthorizationForDevices(frame, protectedRequest, (id <WKUIDelegatePrivate>)m_uiDelegate.m_delegate.get(), *webView.get());
458             break;
459         case AVAuthorizationStatusDenied:
460         case AVAuthorizationStatusRestricted:
461             protectedRequest->deny(UserMediaPermissionRequestProxy::UserMediaAccessDenialReason::PermissionDenied);
462             return;
463         case AVAuthorizationStatusNotDetermined:
464             auto decisionHandler = BlockPtr<void(BOOL)>::fromCallable([this, &frame, protectedRequest = makeRef(protectedRequest.get()), webView = RetainPtr<WKWebView>(m_uiDelegate.m_webView)](BOOL authorized) {
465                 if (!authorized) {
466                     protectedRequest->deny(UserMediaPermissionRequestProxy::UserMediaAccessDenialReason::PermissionDenied);
467                     return;
468                 }
469                 requestUserMediaAuthorizationForDevices(frame, protectedRequest, (id <WKUIDelegatePrivate>)m_uiDelegate.m_delegate.get(), *webView.get());
470             });
471
472             [getAVCaptureDeviceClass() requestAccessForMediaType:getAVMediaTypeVideo() completionHandler:decisionHandler.get()];
473             break;
474         }
475     });
476
477     if (requiresAudio) {
478         AVAuthorizationStatus microphoneAuthorizationStatus = [getAVCaptureDeviceClass() authorizationStatusForMediaType:getAVMediaTypeAudio()];
479         switch (microphoneAuthorizationStatus) {
480         case AVAuthorizationStatusAuthorized:
481             requestCameraAuthorization();
482             break;
483         case AVAuthorizationStatusDenied:
484         case AVAuthorizationStatusRestricted:
485             request.deny(UserMediaPermissionRequestProxy::UserMediaAccessDenialReason::PermissionDenied);
486             return true;
487         case AVAuthorizationStatusNotDetermined:
488             auto decisionHandler = BlockPtr<void(BOOL)>::fromCallable([protectedRequest = makeRef(request), requestCameraAuthorization](BOOL authorized) {
489                 if (!authorized) {
490                     protectedRequest->deny(UserMediaPermissionRequestProxy::UserMediaAccessDenialReason::PermissionDenied);
491                     return;
492                 }
493                 requestCameraAuthorization();
494             });
495
496             [getAVCaptureDeviceClass() requestAccessForMediaType:getAVMediaTypeAudio() completionHandler:decisionHandler.get()];
497             break;
498         }
499     } else
500         requestCameraAuthorization();
501 #else
502     requestUserMediaAuthorizationForDevices(frame, request, (id <WKUIDelegatePrivate>)m_uiDelegate.m_delegate.get(), *m_uiDelegate.m_webView);
503 #endif
504
505     return true;
506 }
507
508 bool UIDelegate::UIClient::checkUserMediaPermissionForOrigin(WebKit::WebPageProxy& page, WebKit::WebFrameProxy& frame, API::SecurityOrigin& userMediaOrigin, API::SecurityOrigin& topLevelOrigin, WebKit::UserMediaPermissionCheckProxy& request)
509 {
510     auto delegate = m_uiDelegate.m_delegate.get();
511     if (!delegate || !m_uiDelegate.m_delegateMethods.webViewCheckUserMediaPermissionForURLMainFrameURLFrameIdentifierDecisionHandler) {
512         request.setUserMediaAccessInfo(String(), false);
513         return true;
514     }
515
516     WKWebView *webView = m_uiDelegate.m_webView;
517     const WebFrameProxy* mainFrame = frame.page()->mainFrame();
518     WebCore::URL requestFrameURL(WebCore::URL(), frame.url());
519     WebCore::URL mainFrameURL(WebCore::URL(), mainFrame->url());
520
521     auto decisionHandler = BlockPtr<void(NSString *, BOOL)>::fromCallable([protectedRequest = makeRef(request)](NSString *salt, BOOL authorized) {
522         protectedRequest->setUserMediaAccessInfo(String(salt), authorized);
523     });
524
525     [(id <WKUIDelegatePrivate>)delegate _webView:webView checkUserMediaPermissionForURL:requestFrameURL mainFrameURL:mainFrameURL frameIdentifier:frame.frameID() decisionHandler:decisionHandler.get()];
526
527     return true;
528 }
529
530 void UIDelegate::UIClient::mediaCaptureStateDidChange(WebCore::MediaProducer::MediaStateFlags state)
531 {
532     WKWebView *webView = m_uiDelegate.m_webView;
533     auto delegate = m_uiDelegate.m_delegate.get();
534     if (!delegate || !m_uiDelegate.m_delegateMethods.webViewMediaCaptureStateDidChange)
535         return;
536
537     _WKMediaCaptureState mediaCaptureState = _WKMediaCaptureStateNone;
538     if (state & WebCore::MediaProducer::HasActiveAudioCaptureDevice)
539         mediaCaptureState |= _WKMediaCaptureStateActiveMicrophone;
540     if (state & WebCore::MediaProducer::HasActiveVideoCaptureDevice)
541         mediaCaptureState |= _WKMediaCaptureStateActiveCamera;
542     if (state & WebCore::MediaProducer::HasMutedAudioCaptureDevice)
543         mediaCaptureState |= _WKMediaCaptureStateMutedMicrophone;
544     if (state & WebCore::MediaProducer::HasMutedVideoCaptureDevice)
545         mediaCaptureState |= _WKMediaCaptureStateMutedCamera;
546
547     [(id <WKUIDelegatePrivate>)delegate _webView:webView mediaCaptureStateDidChange:mediaCaptureState];
548 }
549
550 void UIDelegate::UIClient::reachedApplicationCacheOriginQuota(WebPageProxy*, const WebCore::SecurityOrigin& securityOrigin, uint64_t currentQuota, uint64_t totalBytesNeeded, Function<void (unsigned long long)>&& completionHandler)
551 {
552     if (!m_uiDelegate.m_delegateMethods.webViewDecideWebApplicationCacheQuotaForSecurityOriginCurrentQuotaTotalBytesNeeded) {
553         completionHandler(currentQuota);
554         return;
555     }
556
557     auto delegate = m_uiDelegate.m_delegate.get();
558     if (!delegate) {
559         completionHandler(currentQuota);
560         return;
561     }
562
563     RefPtr<CompletionHandlerCallChecker> checker = CompletionHandlerCallChecker::create(delegate.get(), @selector(_webView:decideWebApplicationCacheQuotaForSecurityOrigin:currentQuota:totalBytesNeeded:decisionHandler:));
564     RefPtr<API::SecurityOrigin> apiOrigin = API::SecurityOrigin::create(securityOrigin);
565     
566     [(id <WKUIDelegatePrivate>)delegate _webView:m_uiDelegate.m_webView decideWebApplicationCacheQuotaForSecurityOrigin:wrapper(*apiOrigin) currentQuota:currentQuota totalBytesNeeded:totalBytesNeeded decisionHandler:BlockPtr<void (unsigned long long)>::fromCallable([completionHandler = WTFMove(completionHandler), checker = WTFMove(checker)](unsigned long long newQuota) {
567         if (checker->completionHandlerHasBeenCalled())
568             return;
569         checker->didCallCompletionHandler();
570         completionHandler(newQuota);
571     }).get()];
572 }
573
574 void UIDelegate::UIClient::printFrame(WebKit::WebPageProxy*, WebKit::WebFrameProxy* webFrameProxy)
575 {
576     ASSERT_ARG(webFrameProxy, webFrameProxy);
577
578     if (!m_uiDelegate.m_delegateMethods.webViewPrintFrame)
579         return;
580
581     auto delegate = m_uiDelegate.m_delegate.get();
582     if (!delegate)
583         return;
584
585     [(id <WKUIDelegatePrivate>)delegate _webView:m_uiDelegate.m_webView printFrame:wrapper(API::FrameHandle::create(webFrameProxy->frameID()))];
586 }
587
588 void UIDelegate::UIClient::close(WebKit::WebPageProxy*)
589 {
590     if (m_uiDelegate.m_delegateMethods.webViewClose) {
591         auto delegate = m_uiDelegate.m_delegate.get();
592         if (!delegate)
593             return;
594
595         [(id <WKUIDelegatePrivate>)delegate _webViewClose:m_uiDelegate.m_webView];
596         return;
597     }
598
599     if (!m_uiDelegate.m_delegateMethods.webViewDidClose)
600         return;
601
602     auto delegate = m_uiDelegate.m_delegate.get();
603     if (!delegate)
604         return;
605
606     [delegate webViewDidClose:m_uiDelegate.m_webView];
607 }
608
609 void UIDelegate::UIClient::fullscreenMayReturnToInline(WebKit::WebPageProxy*)
610 {
611     if (!m_uiDelegate.m_delegateMethods.webViewFullscreenMayReturnToInline)
612         return;
613     
614     auto delegate = m_uiDelegate.m_delegate.get();
615     if (!delegate)
616         return;
617     
618     [(id <WKUIDelegatePrivate>)delegate _webViewFullscreenMayReturnToInline:m_uiDelegate.m_webView];
619 }
620
621 void UIDelegate::UIClient::didEnterFullscreen(WebKit::WebPageProxy*)
622 {
623     if (!m_uiDelegate.m_delegateMethods.webViewDidEnterFullscreen)
624         return;
625
626     auto delegate = m_uiDelegate.m_delegate.get();
627     if (!delegate)
628         return;
629
630     [(id <WKUIDelegatePrivate>)delegate _webViewDidEnterFullscreen:m_uiDelegate.m_webView];
631 }
632
633 void UIDelegate::UIClient::didExitFullscreen(WebKit::WebPageProxy*)
634 {
635     if (!m_uiDelegate.m_delegateMethods.webViewDidExitFullscreen)
636         return;
637
638     auto delegate = m_uiDelegate.m_delegate.get();
639     if (!delegate)
640         return;
641
642     [(id <WKUIDelegatePrivate>)delegate _webViewDidExitFullscreen:m_uiDelegate.m_webView];
643 }
644     
645 #if PLATFORM(IOS)
646 #if HAVE(APP_LINKS)
647 bool UIDelegate::UIClient::shouldIncludeAppLinkActionsForElement(_WKActivatedElementInfo *elementInfo)
648 {
649     if (!m_uiDelegate.m_delegateMethods.webViewShouldIncludeAppLinkActionsForElement)
650         return true;
651
652     auto delegate = m_uiDelegate.m_delegate.get();
653     if (!delegate)
654         return true;
655
656     return [(id <WKUIDelegatePrivate>)delegate _webView:m_uiDelegate.m_webView shouldIncludeAppLinkActionsForElement:elementInfo];
657 }
658 #endif
659
660 RetainPtr<NSArray> UIDelegate::UIClient::actionsForElement(_WKActivatedElementInfo *elementInfo, RetainPtr<NSArray> defaultActions)
661 {
662     if (!m_uiDelegate.m_delegateMethods.webViewActionsForElementDefaultActions)
663         return defaultActions;
664
665     auto delegate = m_uiDelegate.m_delegate.get();
666     if (!delegate)
667         return defaultActions;
668
669     return [(id <WKUIDelegatePrivate>)delegate _webView:m_uiDelegate.m_webView actionsForElement:elementInfo defaultActions:defaultActions.get()];
670 }
671
672 void UIDelegate::UIClient::didNotHandleTapAsClick(const WebCore::IntPoint& point)
673 {
674     if (!m_uiDelegate.m_delegateMethods.webViewDidNotHandleTapAsClickAtPoint)
675         return;
676
677     auto delegate = m_uiDelegate.m_delegate.get();
678     if (!delegate)
679         return;
680
681     [static_cast<id <WKUIDelegatePrivate>>(delegate) _webView:m_uiDelegate.m_webView didNotHandleTapAsClickAtPoint:point];
682 }
683
684 UIViewController *UIDelegate::UIClient::presentingViewController()
685 {
686     if (!m_uiDelegate.m_delegateMethods.presentingViewControllerForWebView)
687         return nullptr;
688
689     auto delegate = m_uiDelegate.m_delegate.get();
690     if (!delegate)
691         return nullptr;
692
693     return [static_cast<id <WKUIDelegatePrivate>>(delegate) _presentingViewControllerForWebView:m_uiDelegate.m_webView];
694 }
695
696 #endif
697
698 NSDictionary *UIDelegate::UIClient::dataDetectionContext()
699 {
700     if (!m_uiDelegate.m_delegateMethods.dataDetectionContextForWebView)
701         return nullptr;
702
703     auto delegate = m_uiDelegate.m_delegate.get();
704     if (!delegate)
705         return nullptr;
706
707     return [static_cast<id <WKUIDelegatePrivate>>(delegate) _dataDetectionContextForWebView:m_uiDelegate.m_webView];
708 }
709
710 #if ENABLE(POINTER_LOCK)
711
712 void UIDelegate::UIClient::requestPointerLock(WebKit::WebPageProxy*)
713 {
714     if (!m_uiDelegate.m_delegateMethods.webViewRequestPointerLock)
715         return;
716
717     auto delegate = m_uiDelegate.m_delegate.get();
718     if (!delegate)
719         return;
720
721     [static_cast<id <WKUIDelegatePrivate>>(delegate) _webViewRequestPointerLock:m_uiDelegate.m_webView];
722 }
723
724 void UIDelegate::UIClient::didLosePointerLock(WebKit::WebPageProxy*)
725 {
726     if (!m_uiDelegate.m_delegateMethods.webViewDidLosePointerLock)
727         return;
728
729     auto delegate = m_uiDelegate.m_delegate.get();
730     if (!delegate)
731         return;
732
733     [static_cast<id <WKUIDelegatePrivate>>(delegate) _webViewDidLosePointerLock:m_uiDelegate.m_webView];
734 }
735
736 #endif
737     
738 void UIDelegate::UIClient::hasVideoInPictureInPictureDidChange(WebKit::WebPageProxy*, bool hasVideoInPictureInPicture)
739 {
740     if (!m_uiDelegate.m_delegateMethods.webViewHasVideoInPictureInPictureDidChange)
741         return;
742     
743     auto delegate = m_uiDelegate.m_delegate.get();
744     if (!delegate)
745         return;
746     
747     [static_cast<id <WKUIDelegatePrivate>>(delegate) _webView:m_uiDelegate.m_webView hasVideoInPictureInPictureDidChange:hasVideoInPictureInPicture];
748 }
749
750 void UIDelegate::UIClient::imageOrMediaDocumentSizeChanged(const WebCore::IntSize& newSize)
751 {
752     if (!m_uiDelegate.m_delegateMethods.webViewImageOrMediaDocumentSizeChanged)
753         return;
754
755     auto delegate = m_uiDelegate.m_delegate.get();
756     if (!delegate)
757         return;
758
759     [static_cast<id <WKUIDelegatePrivate>>(delegate) _webView:m_uiDelegate.m_webView imageOrMediaDocumentSizeChanged:newSize];
760 }
761
762 } // namespace WebKit
763
764 #endif // WK_API_ENABLED