7e19e3b3eda281a5f72dd4a45b9a6f0f79b4cb2d
[WebKit-https.git] / Source / WebKit2 / WebProcess / WebCoreSupport / WebChromeClient.cpp
1 /*
2  * Copyright (C) 2010, 2011, 2012 Apple Inc. All rights reserved.
3  * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "WebChromeClient.h"
29
30 #include "APISecurityOrigin.h"
31 #include "DrawingArea.h"
32 #include "InjectedBundleNavigationAction.h"
33 #include "LayerTreeHost.h"
34 #include "NavigationActionData.h"
35 #include "PageBanner.h"
36 #include "UserData.h"
37 #include "WebColorChooser.h"
38 #include "WebCoreArgumentCoders.h"
39 #include "WebFrame.h"
40 #include "WebFrameLoaderClient.h"
41 #include "WebFullScreenManager.h"
42 #include "WebImage.h"
43 #include "WebOpenPanelParameters.h"
44 #include "WebOpenPanelResultListener.h"
45 #include "WebPage.h"
46 #include "WebPageCreationParameters.h"
47 #include "WebPageProxyMessages.h"
48 #include "WebPopupMenu.h"
49 #include "WebProcess.h"
50 #include "WebProcessProxyMessages.h"
51 #include "WebSearchPopupMenu.h"
52 #include <WebCore/ApplicationCacheStorage.h>
53 #include <WebCore/AXObjectCache.h>
54 #include <WebCore/ColorChooser.h>
55 #include <WebCore/DatabaseManager.h>
56 #include <WebCore/DocumentLoader.h>
57 #include <WebCore/FileChooser.h>
58 #include <WebCore/FileIconLoader.h>
59 #include <WebCore/FrameLoadRequest.h>
60 #include <WebCore/FrameLoader.h>
61 #include <WebCore/FrameView.h>
62 #include <WebCore/HTMLInputElement.h>
63 #include <WebCore/HTMLNames.h>
64 #include <WebCore/HTMLParserIdioms.h>
65 #include <WebCore/HTMLPlugInImageElement.h>
66 #include <WebCore/Icon.h>
67 #include <WebCore/MainFrame.h>
68 #include <WebCore/NotImplemented.h>
69 #include <WebCore/Page.h>
70 #include <WebCore/ScriptController.h>
71 #include <WebCore/SecurityOrigin.h>
72 #include <WebCore/Settings.h>
73
74 #if PLATFORM(IOS)
75 #include "WebVideoFullscreenManager.h"
76 #endif
77
78 #if ENABLE(ASYNC_SCROLLING)
79 #include "RemoteScrollingCoordinator.h"
80 #endif
81
82 #if PLATFORM(GTK)
83 #include "PrinterListGtk.h"
84 #endif
85
86 using namespace WebCore;
87 using namespace HTMLNames;
88
89 namespace WebKit {
90
91 static double area(WebFrame* frame)
92 {
93     IntSize size = frame->visibleContentBoundsExcludingScrollbars().size();
94     return static_cast<double>(size.height()) * size.width();
95 }
96
97
98 static WebFrame* findLargestFrameInFrameSet(WebPage* page)
99 {
100     // Approximate what a user could consider a default target frame for application menu operations.
101
102     WebFrame* mainFrame = page->mainWebFrame();
103     if (!mainFrame || !mainFrame->isFrameSet())
104         return 0;
105
106     WebFrame* largestSoFar = 0;
107
108     RefPtr<API::Array> frameChildren = mainFrame->childFrames();
109     size_t count = frameChildren->size();
110     for (size_t i = 0; i < count; ++i) {
111         WebFrame* childFrame = frameChildren->at<WebFrame>(i);
112         if (!largestSoFar || area(childFrame) > area(largestSoFar))
113             largestSoFar = childFrame;
114     }
115
116     return largestSoFar;
117 }
118
119 void WebChromeClient::chromeDestroyed()
120 {
121     delete this;
122 }
123
124 void WebChromeClient::setWindowRect(const FloatRect& windowFrame)
125 {
126     m_page->sendSetWindowFrame(windowFrame);
127 }
128
129 FloatRect WebChromeClient::windowRect()
130 {
131 #if PLATFORM(COCOA)
132     if (m_page->hasCachedWindowFrame())
133         return m_page->windowFrameInUnflippedScreenCoordinates();
134 #endif
135
136     FloatRect newWindowFrame;
137
138     if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::GetWindowFrame(), Messages::WebPageProxy::GetWindowFrame::Reply(newWindowFrame), m_page->pageID()))
139         return FloatRect();
140
141     return newWindowFrame;
142 }
143
144 FloatRect WebChromeClient::pageRect()
145 {
146     return FloatRect(FloatPoint(), m_page->size());
147 }
148
149 void WebChromeClient::focus()
150 {
151     m_page->send(Messages::WebPageProxy::SetFocus(true));
152 }
153
154 void WebChromeClient::unfocus()
155 {
156     m_page->send(Messages::WebPageProxy::SetFocus(false));
157 }
158
159 #if PLATFORM(COCOA)
160 void WebChromeClient::makeFirstResponder()
161 {
162     m_page->send(Messages::WebPageProxy::MakeFirstResponder());
163 }    
164 #endif    
165
166 bool WebChromeClient::canTakeFocus(FocusDirection)
167 {
168     notImplemented();
169     return true;
170 }
171
172 void WebChromeClient::takeFocus(FocusDirection direction)
173 {
174     m_page->send(Messages::WebPageProxy::TakeFocus(direction));
175 }
176
177 void WebChromeClient::focusedElementChanged(Element* element)
178 {
179     if (!is<HTMLInputElement>(element))
180         return;
181
182     HTMLInputElement& inputElement = downcast<HTMLInputElement>(*element);
183     if (!inputElement.isText())
184         return;
185
186     WebFrame* webFrame = WebFrame::fromCoreFrame(*element->document().frame());
187     ASSERT(webFrame);
188     m_page->injectedBundleFormClient().didFocusTextField(m_page, &inputElement, webFrame);
189 }
190
191 void WebChromeClient::focusedFrameChanged(Frame* frame)
192 {
193     WebFrame* webFrame = frame ? WebFrame::fromCoreFrame(*frame) : nullptr;
194
195     WebProcess::singleton().parentProcessConnection()->send(Messages::WebPageProxy::FocusedFrameChanged(webFrame ? webFrame->frameID() : 0), m_page->pageID());
196 }
197
198 Page* WebChromeClient::createWindow(Frame* frame, const FrameLoadRequest& request, const WindowFeatures& windowFeatures, const NavigationAction& navigationAction)
199 {
200 #if ENABLE(FULLSCREEN_API)
201     if (frame->document() && frame->document()->webkitCurrentFullScreenElement())
202         frame->document()->webkitCancelFullScreen();
203 #endif
204
205     WebFrame* webFrame = WebFrame::fromCoreFrame(*frame);
206
207     NavigationActionData navigationActionData;
208     navigationActionData.navigationType = navigationAction.type();
209     navigationActionData.modifiers = InjectedBundleNavigationAction::modifiersForNavigationAction(navigationAction);
210     navigationActionData.mouseButton = InjectedBundleNavigationAction::mouseButtonForNavigationAction(navigationAction);
211     navigationActionData.isProcessingUserGesture = navigationAction.processingUserGesture();
212     navigationActionData.canHandleRequest = m_page->canHandleRequest(request.resourceRequest());
213
214     uint64_t newPageID = 0;
215     WebPageCreationParameters parameters;
216     auto& webProcess = WebProcess::singleton();
217     if (!webProcess.parentProcessConnection()->sendSync(Messages::WebPageProxy::CreateNewPage(webFrame->frameID(), request.resourceRequest(), windowFeatures, navigationActionData), Messages::WebPageProxy::CreateNewPage::Reply(newPageID, parameters), m_page->pageID()))
218         return nullptr;
219
220     if (!newPageID)
221         return nullptr;
222
223     webProcess.createWebPage(newPageID, parameters);
224     return webProcess.webPage(newPageID)->corePage();
225 }
226
227 void WebChromeClient::show()
228 {
229     m_page->show();
230 }
231
232 bool WebChromeClient::canRunModal()
233 {
234     return m_page->canRunModal();
235 }
236
237 void WebChromeClient::runModal()
238 {
239     m_page->runModal();
240 }
241
242 void WebChromeClient::setToolbarsVisible(bool toolbarsAreVisible)
243 {
244     m_page->send(Messages::WebPageProxy::SetToolbarsAreVisible(toolbarsAreVisible));
245 }
246
247 bool WebChromeClient::toolbarsVisible()
248 {
249     API::InjectedBundle::PageUIClient::UIElementVisibility toolbarsVisibility = m_page->injectedBundleUIClient().toolbarsAreVisible(m_page);
250     if (toolbarsVisibility != API::InjectedBundle::PageUIClient::UIElementVisibility::Unknown)
251         return toolbarsVisibility == API::InjectedBundle::PageUIClient::UIElementVisibility::Visible;
252     
253     bool toolbarsAreVisible = true;
254     if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::GetToolbarsAreVisible(), Messages::WebPageProxy::GetToolbarsAreVisible::Reply(toolbarsAreVisible), m_page->pageID()))
255         return true;
256
257     return toolbarsAreVisible;
258 }
259
260 void WebChromeClient::setStatusbarVisible(bool statusBarIsVisible)
261 {
262     m_page->send(Messages::WebPageProxy::SetStatusBarIsVisible(statusBarIsVisible));
263 }
264
265 bool WebChromeClient::statusbarVisible()
266 {
267     API::InjectedBundle::PageUIClient::UIElementVisibility statusbarVisibility = m_page->injectedBundleUIClient().statusBarIsVisible(m_page);
268     if (statusbarVisibility != API::InjectedBundle::PageUIClient::UIElementVisibility::Unknown)
269         return statusbarVisibility == API::InjectedBundle::PageUIClient::UIElementVisibility::Visible;
270
271     bool statusBarIsVisible = true;
272     if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::GetStatusBarIsVisible(), Messages::WebPageProxy::GetStatusBarIsVisible::Reply(statusBarIsVisible), m_page->pageID()))
273         return true;
274
275     return statusBarIsVisible;
276 }
277
278 void WebChromeClient::setScrollbarsVisible(bool)
279 {
280     notImplemented();
281 }
282
283 bool WebChromeClient::scrollbarsVisible()
284 {
285     notImplemented();
286     return true;
287 }
288
289 void WebChromeClient::setMenubarVisible(bool menuBarVisible)
290 {
291     m_page->send(Messages::WebPageProxy::SetMenuBarIsVisible(menuBarVisible));
292 }
293
294 bool WebChromeClient::menubarVisible()
295 {
296     API::InjectedBundle::PageUIClient::UIElementVisibility menubarVisibility = m_page->injectedBundleUIClient().menuBarIsVisible(m_page);
297     if (menubarVisibility != API::InjectedBundle::PageUIClient::UIElementVisibility::Unknown)
298         return menubarVisibility == API::InjectedBundle::PageUIClient::UIElementVisibility::Visible;
299     
300     bool menuBarIsVisible = true;
301     if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::GetMenuBarIsVisible(), Messages::WebPageProxy::GetMenuBarIsVisible::Reply(menuBarIsVisible), m_page->pageID()))
302         return true;
303
304     return menuBarIsVisible;
305 }
306
307 void WebChromeClient::setResizable(bool resizable)
308 {
309     m_page->send(Messages::WebPageProxy::SetIsResizable(resizable));
310 }
311
312 void WebChromeClient::addMessageToConsole(MessageSource, MessageLevel, const String& message, unsigned lineNumber, unsigned /*columnNumber*/, const String& /*sourceID*/)
313 {
314     // Notify the bundle client.
315     m_page->injectedBundleUIClient().willAddMessageToConsole(m_page, message, lineNumber);
316
317     notImplemented();
318 }
319
320 bool WebChromeClient::canRunBeforeUnloadConfirmPanel()
321 {
322     return m_page->canRunBeforeUnloadConfirmPanel();
323 }
324
325 bool WebChromeClient::runBeforeUnloadConfirmPanel(const String& message, Frame* frame)
326 {
327     WebFrame* webFrame = WebFrame::fromCoreFrame(*frame);
328
329     bool shouldClose = false;
330
331     unsigned syncSendFlags = IPC::InformPlatformProcessWillSuspend;
332     if (WebPage::synchronousMessagesShouldSpinRunLoop())
333         syncSendFlags |= IPC::SpinRunLoopWhileWaitingForReply;
334     
335     if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::RunBeforeUnloadConfirmPanel(message, webFrame->frameID()), Messages::WebPageProxy::RunBeforeUnloadConfirmPanel::Reply(shouldClose), m_page->pageID(), std::chrono::milliseconds::max(), syncSendFlags))
336         return false;
337
338     return shouldClose;
339 }
340
341 void WebChromeClient::closeWindowSoon()
342 {
343     // FIXME: This code assumes that the client will respond to a close page
344     // message by actually closing the page. Safari does this, but there is
345     // no guarantee that other applications will, which will leave this page
346     // half detached. This approach is an inherent limitation making parts of
347     // a close execute synchronously as part of window.close, but other parts
348     // later on.
349
350     m_page->corePage()->setGroupName(String());
351
352     if (WebFrame* frame = m_page->mainWebFrame()) {
353         if (Frame* coreFrame = frame->coreFrame())
354             coreFrame->loader().stopForUserCancel();
355     }
356
357     m_page->sendClose();
358 }
359
360 void WebChromeClient::runJavaScriptAlert(Frame* frame, const String& alertText)
361 {
362     WebFrame* webFrame = WebFrame::fromCoreFrame(*frame);
363     ASSERT(webFrame);
364
365     // Notify the bundle client.
366     m_page->injectedBundleUIClient().willRunJavaScriptAlert(m_page, alertText, webFrame);
367
368     unsigned syncSendFlags = IPC::InformPlatformProcessWillSuspend;
369     if (WebPage::synchronousMessagesShouldSpinRunLoop())
370         syncSendFlags |= IPC::SpinRunLoopWhileWaitingForReply;
371     WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::RunJavaScriptAlert(webFrame->frameID(), alertText), Messages::WebPageProxy::RunJavaScriptAlert::Reply(), m_page->pageID(), std::chrono::milliseconds::max(), syncSendFlags);
372 }
373
374 bool WebChromeClient::runJavaScriptConfirm(Frame* frame, const String& message)
375 {
376     WebFrame* webFrame = WebFrame::fromCoreFrame(*frame);
377     ASSERT(webFrame);
378
379     // Notify the bundle client.
380     m_page->injectedBundleUIClient().willRunJavaScriptConfirm(m_page, message, webFrame);
381
382     unsigned syncSendFlags = IPC::InformPlatformProcessWillSuspend;
383     if (WebPage::synchronousMessagesShouldSpinRunLoop())
384         syncSendFlags |= IPC::SpinRunLoopWhileWaitingForReply;
385     bool result = false;
386     if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::RunJavaScriptConfirm(webFrame->frameID(), message), Messages::WebPageProxy::RunJavaScriptConfirm::Reply(result), m_page->pageID(), std::chrono::milliseconds::max(), syncSendFlags))
387         return false;
388
389     return result;
390 }
391
392 bool WebChromeClient::runJavaScriptPrompt(Frame* frame, const String& message, const String& defaultValue, String& result)
393 {
394     WebFrame* webFrame = WebFrame::fromCoreFrame(*frame);
395     ASSERT(webFrame);
396
397     // Notify the bundle client.
398     m_page->injectedBundleUIClient().willRunJavaScriptPrompt(m_page, message, defaultValue, webFrame);
399
400     unsigned syncSendFlags = IPC::InformPlatformProcessWillSuspend;
401     if (WebPage::synchronousMessagesShouldSpinRunLoop())
402         syncSendFlags |= IPC::SpinRunLoopWhileWaitingForReply;
403     
404     if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::RunJavaScriptPrompt(webFrame->frameID(), message, defaultValue), Messages::WebPageProxy::RunJavaScriptPrompt::Reply(result), m_page->pageID(), std::chrono::milliseconds::max(), syncSendFlags))
405         return false;
406
407     return !result.isNull();
408 }
409
410 void WebChromeClient::setStatusbarText(const String& statusbarText)
411 {
412     // Notify the bundle client.
413     m_page->injectedBundleUIClient().willSetStatusbarText(m_page, statusbarText);
414
415     m_page->send(Messages::WebPageProxy::SetStatusText(statusbarText));
416 }
417
418 bool WebChromeClient::shouldInterruptJavaScript()
419 {
420     bool shouldInterrupt = false;
421     if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::ShouldInterruptJavaScript(), Messages::WebPageProxy::ShouldInterruptJavaScript::Reply(shouldInterrupt), m_page->pageID()))
422         return false;
423
424     return shouldInterrupt;
425 }
426
427 KeyboardUIMode WebChromeClient::keyboardUIMode()
428 {
429     return m_page->keyboardUIMode();
430 }
431
432 IntRect WebChromeClient::windowResizerRect() const
433 {
434     return m_page->windowResizerRect();
435 }
436
437 void WebChromeClient::invalidateRootView(const IntRect&)
438 {
439     // Do nothing here, there's no concept of invalidating the window in the web process.
440 }
441
442 void WebChromeClient::invalidateContentsAndRootView(const IntRect& rect)
443 {
444     if (Document* document = m_page->corePage()->mainFrame().document()) {
445         if (document->printing())
446             return;
447     }
448
449     m_page->drawingArea()->setNeedsDisplayInRect(rect);
450 }
451
452 void WebChromeClient::invalidateContentsForSlowScroll(const IntRect& rect)
453 {
454     if (Document* document = m_page->corePage()->mainFrame().document()) {
455         if (document->printing())
456             return;
457     }
458
459     m_page->pageDidScroll();
460 #if USE(COORDINATED_GRAPHICS)
461     m_page->drawingArea()->scroll(rect, IntSize());
462 #else
463     m_page->drawingArea()->setNeedsDisplayInRect(rect);
464 #endif
465 }
466
467 void WebChromeClient::scroll(const IntSize& scrollDelta, const IntRect& scrollRect, const IntRect& clipRect)
468 {
469     m_page->pageDidScroll();
470     m_page->drawingArea()->scroll(intersection(scrollRect, clipRect), scrollDelta);
471 }
472
473 #if USE(TILED_BACKING_STORE)
474 void WebChromeClient::delegatedScrollRequested(const IntPoint& scrollOffset)
475 {
476     m_page->pageDidRequestScroll(scrollOffset);
477 }
478 #endif
479
480 IntPoint WebChromeClient::screenToRootView(const IntPoint& point) const
481 {
482     return m_page->screenToRootView(point);
483 }
484
485 IntRect WebChromeClient::rootViewToScreen(const IntRect& rect) const
486 {
487     return m_page->rootViewToScreen(rect);
488 }
489     
490 #if PLATFORM(IOS)
491 IntPoint WebChromeClient::accessibilityScreenToRootView(const IntPoint& point) const
492 {
493     return m_page->accessibilityScreenToRootView(point);
494 }
495
496 IntRect WebChromeClient::rootViewToAccessibilityScreen(const IntRect& rect) const
497 {
498     return m_page->rootViewToAccessibilityScreen(rect);
499 }
500 #endif
501
502 PlatformPageClient WebChromeClient::platformPageClient() const
503 {
504     notImplemented();
505     return 0;
506 }
507
508 void WebChromeClient::contentsSizeChanged(Frame* frame, const IntSize& size) const
509 {
510     if (!m_page->corePage()->settings().frameFlatteningEnabled()) {
511         WebFrame* largestFrame = findLargestFrameInFrameSet(m_page);
512         if (largestFrame != m_cachedFrameSetLargestFrame.get()) {
513             m_cachedFrameSetLargestFrame = largestFrame;
514             m_page->send(Messages::WebPageProxy::FrameSetLargestFrameChanged(largestFrame ? largestFrame->frameID() : 0));
515         }
516     }
517
518     if (&frame->page()->mainFrame() != frame)
519         return;
520
521 #if USE(COORDINATED_GRAPHICS)
522     if (m_page->useFixedLayout())
523         m_page->drawingArea()->layerTreeHost()->sizeDidChange(size);
524 #endif
525
526 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
527     m_page->send(Messages::WebPageProxy::DidChangeContentSize(size));
528 #endif
529
530     m_page->drawingArea()->mainFrameContentSizeChanged(size);
531
532     FrameView* frameView = frame->view();
533     if (frameView && !frameView->delegatesScrolling())  {
534         bool hasHorizontalScrollbar = frameView->horizontalScrollbar();
535         bool hasVerticalScrollbar = frameView->verticalScrollbar();
536
537         if (hasHorizontalScrollbar != m_cachedMainFrameHasHorizontalScrollbar || hasVerticalScrollbar != m_cachedMainFrameHasVerticalScrollbar) {
538             m_page->send(Messages::WebPageProxy::DidChangeScrollbarsForMainFrame(hasHorizontalScrollbar, hasVerticalScrollbar));
539
540             m_cachedMainFrameHasHorizontalScrollbar = hasHorizontalScrollbar;
541             m_cachedMainFrameHasVerticalScrollbar = hasVerticalScrollbar;
542         }
543     }
544 }
545
546 void WebChromeClient::scrollRectIntoView(const IntRect&) const
547 {
548     notImplemented();
549 }
550
551 bool WebChromeClient::shouldUnavailablePluginMessageBeButton(RenderEmbeddedObject::PluginUnavailabilityReason pluginUnavailabilityReason) const
552 {
553     switch (pluginUnavailabilityReason) {
554     case RenderEmbeddedObject::PluginMissing:
555         // FIXME: <rdar://problem/8794397> We should only return true when there is a
556         // missingPluginButtonClicked callback defined on the Page UI client.
557     case RenderEmbeddedObject::InsecurePluginVersion:
558         return true;
559
560
561     case RenderEmbeddedObject::PluginCrashed:
562     case RenderEmbeddedObject::PluginBlockedByContentSecurityPolicy:
563         return false;
564     }
565
566     ASSERT_NOT_REACHED();
567     return false;
568 }
569     
570 void WebChromeClient::unavailablePluginButtonClicked(Element* element, RenderEmbeddedObject::PluginUnavailabilityReason pluginUnavailabilityReason) const
571 {
572 #if ENABLE(NETSCAPE_PLUGIN_API)
573     ASSERT(element->hasTagName(objectTag) || element->hasTagName(embedTag) || element->hasTagName(appletTag));
574     ASSERT(pluginUnavailabilityReason == RenderEmbeddedObject::PluginMissing || pluginUnavailabilityReason == RenderEmbeddedObject::InsecurePluginVersion || pluginUnavailabilityReason);
575
576     HTMLPlugInImageElement* pluginElement = static_cast<HTMLPlugInImageElement*>(element);
577
578     String frameURLString = pluginElement->document().frame()->loader().documentLoader()->responseURL().string();
579     String pageURLString = m_page->mainFrame()->loader().documentLoader()->responseURL().string();
580     String pluginURLString = pluginElement->document().completeURL(pluginElement->url()).string();
581     URL pluginspageAttributeURL = element->document().completeURL(stripLeadingAndTrailingHTMLSpaces(pluginElement->getAttribute(pluginspageAttr)));
582     if (!pluginspageAttributeURL.protocolIsInHTTPFamily())
583         pluginspageAttributeURL = URL();
584     m_page->send(Messages::WebPageProxy::UnavailablePluginButtonClicked(pluginUnavailabilityReason, pluginElement->serviceType(), pluginURLString, pluginspageAttributeURL.string(), frameURLString, pageURLString));
585 #else
586     UNUSED_PARAM(element);
587     UNUSED_PARAM(pluginUnavailabilityReason);
588 #endif // ENABLE(NETSCAPE_PLUGIN_API)
589 }
590
591 void WebChromeClient::scrollbarsModeDidChange() const
592 {
593     notImplemented();
594 }
595
596 void WebChromeClient::mouseDidMoveOverElement(const HitTestResult& hitTestResult, unsigned modifierFlags)
597 {
598     RefPtr<API::Object> userData;
599
600     // Notify the bundle client.
601     m_page->injectedBundleUIClient().mouseDidMoveOverElement(m_page, hitTestResult, static_cast<WebEvent::Modifiers>(modifierFlags), userData);
602
603     // Notify the UIProcess.
604     WebHitTestResult::Data webHitTestResultData(hitTestResult);
605     m_page->send(Messages::WebPageProxy::MouseDidMoveOverElement(webHitTestResultData, modifierFlags, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
606 }
607
608 void WebChromeClient::didBeginTrackingPotentialLongMousePress(const IntPoint& mouseDownPosition, const HitTestResult& hitTestResult)
609 {
610     RefPtr<API::Object> userData;
611
612     // Notify the bundle client.
613     m_page->injectedBundleUIClient().didBeginTrackingPotentialLongMousePress(m_page, mouseDownPosition, hitTestResult, userData);
614     
615     // Notify the UIProcess.
616     WebHitTestResult::Data webHitTestResultData(hitTestResult);
617     m_page->send(Messages::WebPageProxy::DidBeginTrackingPotentialLongMousePress(mouseDownPosition, webHitTestResultData, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
618 }
619
620 void WebChromeClient::didRecognizeLongMousePress()
621 {
622     RefPtr<API::Object> userData;
623
624     // Notify the bundle client.
625     m_page->injectedBundleUIClient().didRecognizeLongMousePress(m_page, userData);
626
627     // Notify the UIProcess.
628     m_page->send(Messages::WebPageProxy::DidRecognizeLongMousePress(UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
629 }
630
631 void WebChromeClient::didCancelTrackingPotentialLongMousePress()
632 {
633     RefPtr<API::Object> userData;
634
635     // Notify the bundle client.
636     m_page->injectedBundleUIClient().didCancelTrackingPotentialLongMousePress(m_page, userData);
637
638     // Notify the UIProcess.
639     m_page->send(Messages::WebPageProxy::DidCancelTrackingPotentialLongMousePress(UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())));
640 }
641
642 void WebChromeClient::setToolTip(const String& toolTip, TextDirection)
643 {
644     // Only send a tool tip to the WebProcess if it has changed since the last time this function was called.
645
646     if (toolTip == m_cachedToolTip)
647         return;
648     m_cachedToolTip = toolTip;
649
650     m_page->send(Messages::WebPageProxy::SetToolTip(m_cachedToolTip));
651 }
652
653 void WebChromeClient::print(Frame* frame)
654 {
655     WebFrame* webFrame = WebFrame::fromCoreFrame(*frame);
656     ASSERT(webFrame);
657
658 #if PLATFORM(GTK) && HAVE(GTK_UNIX_PRINTING)
659     // When printing synchronously in GTK+ we need to make sure that we have a list of Printers before starting the print operation.
660     // Getting the list of printers is done synchronously by GTK+, but using a nested main loop that might process IPC messages
661     // comming from the UI process like EndPrinting. When the EndPriting message is received while the printer list is being populated,
662     // the print operation is finished unexpectely and the web process crashes, see https://bugs.webkit.org/show_bug.cgi?id=126979.
663     // The PrinterListGtk class gets the list of printers in the constructor so we just need to ensure there's an instance alive
664     // during the synchronous print operation.
665     RefPtr<PrinterListGtk> printerList = PrinterListGtk::getOrCreate();
666     if (!printerList) {
667         // PrinterListGtk::getOrCreate() returns nullptr when called while a printers enumeration is ongoing.
668         // This can happen if a synchronous print is started by a JavaScript and another one is inmeditaley started
669         // from a JavaScript event listener. The second print operation is handled by the nested main loop used by GTK+
670         // to enumerate the printers, and we end up here trying to get a reference of an object that is being constructed.
671         // It's very unlikely that the user wants to print twice in a row, and other browsers don't do two print operations
672         // in this particular case either. So, the safest solution is to return early here and ignore the second print.
673         // See https://bugs.webkit.org/show_bug.cgi?id=141035
674         return;
675     }
676 #endif
677
678     unsigned syncSendFlags = IPC::InformPlatformProcessWillSuspend;
679     if (WebPage::synchronousMessagesShouldSpinRunLoop())
680         syncSendFlags |= IPC::SpinRunLoopWhileWaitingForReply;
681     
682     m_page->sendSync(Messages::WebPageProxy::PrintFrame(webFrame->frameID()), Messages::WebPageProxy::PrintFrame::Reply(), std::chrono::milliseconds::max(), syncSendFlags);
683 }
684
685 void WebChromeClient::exceededDatabaseQuota(Frame* frame, const String& databaseName, DatabaseDetails details)
686 {
687     WebFrame* webFrame = WebFrame::fromCoreFrame(*frame);
688     ASSERT(webFrame);
689     
690     SecurityOrigin* origin = frame->document()->securityOrigin();
691
692     DatabaseManager& dbManager = DatabaseManager::manager();
693     uint64_t currentQuota = dbManager.quotaForOrigin(origin);
694     uint64_t currentOriginUsage = dbManager.usageForOrigin(origin);
695     uint64_t newQuota = 0;
696     RefPtr<API::SecurityOrigin> securityOrigin = API::SecurityOrigin::create(WebCore::SecurityOrigin::createFromDatabaseIdentifier(origin->databaseIdentifier()));
697     newQuota = m_page->injectedBundleUIClient().didExceedDatabaseQuota(m_page, securityOrigin.get(), databaseName, details.displayName(), currentQuota, currentOriginUsage, details.currentUsage(), details.expectedUsage());
698
699     if (!newQuota) {
700         unsigned syncSendFlags = IPC::InformPlatformProcessWillSuspend;
701         if (WebPage::synchronousMessagesShouldSpinRunLoop())
702             syncSendFlags |= IPC::SpinRunLoopWhileWaitingForReply;
703         
704         WebProcess::singleton().parentProcessConnection()->sendSync(
705             Messages::WebPageProxy::ExceededDatabaseQuota(webFrame->frameID(), origin->databaseIdentifier(), databaseName, details.displayName(), currentQuota, currentOriginUsage, details.currentUsage(), details.expectedUsage()),
706             Messages::WebPageProxy::ExceededDatabaseQuota::Reply(newQuota), m_page->pageID(), std::chrono::milliseconds::max(), syncSendFlags);
707     }
708
709     dbManager.setQuota(origin, newQuota);
710 }
711
712 void WebChromeClient::reachedMaxAppCacheSize(int64_t)
713 {
714     notImplemented();
715 }
716
717 void WebChromeClient::reachedApplicationCacheOriginQuota(SecurityOrigin* origin, int64_t totalBytesNeeded)
718 {
719     RefPtr<API::SecurityOrigin> securityOrigin = API::SecurityOrigin::createFromString(origin->toString());
720     if (m_page->injectedBundleUIClient().didReachApplicationCacheOriginQuota(m_page, securityOrigin.get(), totalBytesNeeded))
721         return;
722
723     unsigned syncSendFlags = IPC::InformPlatformProcessWillSuspend;
724     if (WebPage::synchronousMessagesShouldSpinRunLoop())
725         syncSendFlags |= IPC::SpinRunLoopWhileWaitingForReply;
726
727     int64_t currentQuota = 0;
728     if (!cacheStorage().calculateQuotaForOrigin(origin, currentQuota))
729         return;
730
731     uint64_t newQuota = 0;
732     WebProcess::singleton().parentProcessConnection()->sendSync(
733         Messages::WebPageProxy::ReachedApplicationCacheOriginQuota(origin->databaseIdentifier(), currentQuota, totalBytesNeeded),
734         Messages::WebPageProxy::ReachedApplicationCacheOriginQuota::Reply(newQuota), m_page->pageID(), std::chrono::milliseconds::max(), syncSendFlags);
735
736     cacheStorage().storeUpdatedQuotaForOrigin(origin, newQuota);
737 }
738
739 #if ENABLE(DASHBOARD_SUPPORT)
740 void WebChromeClient::annotatedRegionsChanged()
741 {
742     notImplemented();
743 }
744 #endif
745
746 bool WebChromeClient::shouldReplaceWithGeneratedFileForUpload(const String& path, String& generatedFilename)
747 {
748     generatedFilename = m_page->injectedBundleUIClient().shouldGenerateFileForUpload(m_page, path);
749     return !generatedFilename.isNull();
750 }
751
752 String WebChromeClient::generateReplacementFile(const String& path)
753 {
754     return m_page->injectedBundleUIClient().generateFileForUpload(m_page, path);
755 }
756
757 #if ENABLE(INPUT_TYPE_COLOR)
758 std::unique_ptr<ColorChooser> WebChromeClient::createColorChooser(ColorChooserClient* client, const Color& initialColor)
759 {
760     return std::unique_ptr<WebColorChooser>(new WebColorChooser(m_page, client, initialColor));
761 }
762 #endif
763
764 void WebChromeClient::runOpenPanel(Frame* frame, PassRefPtr<FileChooser> prpFileChooser)
765 {
766     if (m_page->activeOpenPanelResultListener())
767         return;
768
769     RefPtr<FileChooser> fileChooser = prpFileChooser;
770
771     m_page->setActiveOpenPanelResultListener(WebOpenPanelResultListener::create(m_page, fileChooser.get()));
772
773     WebFrame* webFrame = WebFrame::fromCoreFrame(*frame);
774     ASSERT(webFrame);
775
776     m_page->send(Messages::WebPageProxy::RunOpenPanel(webFrame->frameID(), fileChooser->settings()));
777 }
778
779 void WebChromeClient::loadIconForFiles(const Vector<String>& filenames, FileIconLoader* loader)
780 {
781     loader->notifyFinished(Icon::createIconForFiles(filenames));
782 }
783
784 #if !PLATFORM(IOS)
785 void WebChromeClient::setCursor(const WebCore::Cursor& cursor)
786 {
787     m_page->send(Messages::WebPageProxy::SetCursor(cursor));
788 }
789
790 void WebChromeClient::setCursorHiddenUntilMouseMoves(bool hiddenUntilMouseMoves)
791 {
792     m_page->send(Messages::WebPageProxy::SetCursorHiddenUntilMouseMoves(hiddenUntilMouseMoves));
793 }
794 #endif
795
796 #if ENABLE(REQUEST_ANIMATION_FRAME) && !USE(REQUEST_ANIMATION_FRAME_TIMER)
797 void WebChromeClient::scheduleAnimation()
798 {
799 #if USE(COORDINATED_GRAPHICS)
800     m_page->drawingArea()->layerTreeHost()->scheduleAnimation();
801 #endif
802 }
803 #endif
804
805 void WebChromeClient::didAssociateFormControls(const Vector<RefPtr<WebCore::Element>>& elements)
806 {
807     return m_page->injectedBundleFormClient().didAssociateFormControls(m_page, elements);
808 }
809
810 bool WebChromeClient::shouldNotifyOnFormChanges()
811 {
812     return m_page->injectedBundleFormClient().shouldNotifyOnFormChanges(m_page);
813 }
814
815 bool WebChromeClient::selectItemWritingDirectionIsNatural()
816 {
817 #if PLATFORM(EFL)
818     return true;
819 #else
820     return false;
821 #endif
822 }
823
824 bool WebChromeClient::selectItemAlignmentFollowsMenuWritingDirection()
825 {
826     return true;
827 }
828
829 bool WebChromeClient::hasOpenedPopup() const
830 {
831     notImplemented();
832     return false;
833 }
834
835 PassRefPtr<WebCore::PopupMenu> WebChromeClient::createPopupMenu(WebCore::PopupMenuClient* client) const
836 {
837     return WebPopupMenu::create(m_page, client);
838 }
839
840 PassRefPtr<WebCore::SearchPopupMenu> WebChromeClient::createSearchPopupMenu(WebCore::PopupMenuClient* client) const
841 {
842     return WebSearchPopupMenu::create(m_page, client);
843 }
844
845 GraphicsLayerFactory* WebChromeClient::graphicsLayerFactory() const
846 {
847     if (auto drawingArea = m_page->drawingArea())
848         return drawingArea->graphicsLayerFactory();
849     return nullptr;
850 }
851
852 #if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
853 PassRefPtr<WebCore::DisplayRefreshMonitor> WebChromeClient::createDisplayRefreshMonitor(PlatformDisplayID displayID) const
854 {
855     return m_page->drawingArea()->createDisplayRefreshMonitor(displayID);
856 }
857 #endif
858
859 void WebChromeClient::attachRootGraphicsLayer(Frame*, GraphicsLayer* layer)
860 {
861     if (layer)
862         m_page->enterAcceleratedCompositingMode(layer);
863     else
864         m_page->exitAcceleratedCompositingMode();
865 }
866
867 void WebChromeClient::attachViewOverlayGraphicsLayer(Frame* frame, GraphicsLayer* graphicsLayer)
868 {
869     if (auto drawingArea = m_page->drawingArea())
870         drawingArea->attachViewOverlayGraphicsLayer(frame, graphicsLayer);
871 }
872
873 void WebChromeClient::setNeedsOneShotDrawingSynchronization()
874 {
875     notImplemented();
876 }
877
878 void WebChromeClient::scheduleCompositingLayerFlush()
879 {
880     if (m_page->drawingArea())
881         m_page->drawingArea()->scheduleCompositingLayerFlush();
882 }
883
884 bool WebChromeClient::adjustLayerFlushThrottling(WebCore::LayerFlushThrottleState::Flags flags)
885 {
886     return m_page->drawingArea() && m_page->drawingArea()->adjustLayerFlushThrottling(flags);
887 }
888
889 bool WebChromeClient::layerTreeStateIsFrozen() const
890 {
891     if (m_page->drawingArea())
892         return m_page->drawingArea()->layerTreeStateIsFrozen();
893
894     return false;
895 }
896
897 #if ENABLE(ASYNC_SCROLLING)
898 PassRefPtr<ScrollingCoordinator> WebChromeClient::createScrollingCoordinator(Page* page) const
899 {
900     ASSERT(m_page->corePage() == page);
901     if (m_page->drawingArea()->type() == DrawingAreaTypeRemoteLayerTree)
902         return RemoteScrollingCoordinator::create(m_page);
903
904     return 0;
905 }
906 #endif
907
908 #if PLATFORM(IOS)
909 bool WebChromeClient::supportsVideoFullscreen()
910 {
911     return m_page->videoFullscreenManager()->supportsVideoFullscreen();
912 }
913
914 void WebChromeClient::enterVideoFullscreenForVideoElement(WebCore::HTMLVideoElement* videoElement, WebCore::HTMLMediaElement::VideoFullscreenMode mode)
915 {
916     ASSERT(mode != HTMLMediaElement::VideoFullscreenModeNone);
917     m_page->videoFullscreenManager()->enterVideoFullscreenForVideoElement(videoElement, mode);
918 }
919
920 void WebChromeClient::exitVideoFullscreen()
921 {
922     m_page->videoFullscreenManager()->exitVideoFullscreen();
923 }
924 #endif
925     
926 #if ENABLE(FULLSCREEN_API)
927 bool WebChromeClient::supportsFullScreenForElement(const WebCore::Element*, bool withKeyboard)
928 {
929     return m_page->fullScreenManager()->supportsFullScreen(withKeyboard);
930 }
931
932 void WebChromeClient::enterFullScreenForElement(WebCore::Element* element)
933 {
934     m_page->fullScreenManager()->enterFullScreenForElement(element);
935 }
936
937 void WebChromeClient::exitFullScreenForElement(WebCore::Element* element)
938 {
939     m_page->fullScreenManager()->exitFullScreenForElement(element);
940 }
941 #endif
942
943 #if PLATFORM(IOS)
944 FloatSize WebChromeClient::screenSize() const
945 {
946     return m_page->screenSize();
947 }
948
949 FloatSize WebChromeClient::availableScreenSize() const
950 {
951     return m_page->availableScreenSize();
952 }
953 #endif
954
955 void WebChromeClient::dispatchViewportPropertiesDidChange(const ViewportArguments& viewportArguments) const
956 {
957     UNUSED_PARAM(viewportArguments);
958 #if PLATFORM(IOS)
959     m_page->viewportPropertiesDidChange(viewportArguments);
960 #endif
961 #if USE(TILED_BACKING_STORE)
962     if (!m_page->useFixedLayout())
963         return;
964
965     m_page->sendViewportAttributesChanged();
966 #endif
967 }
968
969 void WebChromeClient::notifyScrollerThumbIsVisibleInRect(const IntRect& scrollerThumb)
970 {
971     m_page->send(Messages::WebPageProxy::NotifyScrollerThumbIsVisibleInRect(scrollerThumb));
972 }
973
974 void WebChromeClient::recommendedScrollbarStyleDidChange(int32_t newStyle)
975 {
976     m_page->send(Messages::WebPageProxy::RecommendedScrollbarStyleDidChange(newStyle));
977 }
978
979 Color WebChromeClient::underlayColor() const
980 {
981     return m_page->underlayColor();
982 }
983
984 void WebChromeClient::pageExtendedBackgroundColorDidChange(Color backgroundColor) const
985 {
986 #if PLATFORM(MAC) || PLATFORM(EFL)
987     m_page->send(Messages::WebPageProxy::PageExtendedBackgroundColorDidChange(backgroundColor));
988 #else
989     UNUSED_PARAM(backgroundColor);
990 #endif
991 }
992
993 void WebChromeClient::numWheelEventHandlersChanged(unsigned count)
994 {
995     m_page->numWheelEventHandlersChanged(count);
996 }
997
998 String WebChromeClient::plugInStartLabelTitle(const String& mimeType) const
999 {
1000     return m_page->injectedBundleUIClient().plugInStartLabelTitle(mimeType);
1001 }
1002
1003 String WebChromeClient::plugInStartLabelSubtitle(const String& mimeType) const
1004 {
1005     return m_page->injectedBundleUIClient().plugInStartLabelSubtitle(mimeType);
1006 }
1007
1008 String WebChromeClient::plugInExtraStyleSheet() const
1009 {
1010     return m_page->injectedBundleUIClient().plugInExtraStyleSheet();
1011 }
1012
1013 String WebChromeClient::plugInExtraScript() const
1014 {
1015     return m_page->injectedBundleUIClient().plugInExtraScript();
1016 }
1017
1018 void WebChromeClient::enableSuddenTermination()
1019 {
1020     m_page->send(Messages::WebProcessProxy::EnableSuddenTermination());
1021 }
1022
1023 void WebChromeClient::disableSuddenTermination()
1024 {
1025     m_page->send(Messages::WebProcessProxy::DisableSuddenTermination());
1026 }
1027
1028 void WebChromeClient::didAddHeaderLayer(GraphicsLayer* headerParent)
1029 {
1030 #if ENABLE(RUBBER_BANDING)
1031     if (PageBanner* banner = m_page->headerPageBanner())
1032         banner->didAddParentLayer(headerParent);
1033 #else
1034     UNUSED_PARAM(headerParent);
1035 #endif
1036 }
1037
1038 void WebChromeClient::didAddFooterLayer(GraphicsLayer* footerParent)
1039 {
1040 #if ENABLE(RUBBER_BANDING)
1041     if (PageBanner* banner = m_page->footerPageBanner())
1042         banner->didAddParentLayer(footerParent);
1043 #else
1044     UNUSED_PARAM(footerParent);
1045 #endif
1046 }
1047
1048 bool WebChromeClient::shouldUseTiledBackingForFrameView(const FrameView* frameView) const
1049 {
1050     return m_page->drawingArea()->shouldUseTiledBackingForFrameView(frameView);
1051 }
1052
1053 void WebChromeClient::isPlayingAudioDidChange(bool newIsPlayingAudio)
1054 {
1055     m_page->send(Messages::WebPageProxy::IsPlayingAudioDidChange(newIsPlayingAudio));
1056 }
1057
1058 void WebChromeClient::setPageActivityState(PageActivityState::Flags activityState)
1059 {
1060     m_page->setPageActivityState(activityState);
1061 }
1062
1063 #if ENABLE(SUBTLE_CRYPTO)
1064 bool WebChromeClient::wrapCryptoKey(const Vector<uint8_t>& key, Vector<uint8_t>& wrappedKey) const
1065 {
1066     bool succeeded;
1067     if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::WrapCryptoKey(key), Messages::WebPageProxy::WrapCryptoKey::Reply(succeeded, wrappedKey), m_page->pageID()))
1068         return false;
1069     return succeeded;
1070 }
1071
1072 bool WebChromeClient::unwrapCryptoKey(const Vector<uint8_t>& wrappedKey, Vector<uint8_t>& key) const
1073 {
1074     bool succeeded;
1075     if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::UnwrapCryptoKey(wrappedKey), Messages::WebPageProxy::UnwrapCryptoKey::Reply(succeeded, key), m_page->pageID()))
1076         return false;
1077     return succeeded;
1078 }
1079 #endif
1080
1081 #if ENABLE(TELEPHONE_NUMBER_DETECTION) && PLATFORM(MAC)
1082 void WebChromeClient::handleTelephoneNumberClick(const String& number, const WebCore::IntPoint& point)
1083 {
1084     m_page->handleTelephoneNumberClick(number, point);
1085 }
1086 #endif
1087
1088 #if ENABLE(SERVICE_CONTROLS)
1089 void WebChromeClient::handleSelectionServiceClick(WebCore::FrameSelection& selection, const Vector<String>& telephoneNumbers, const WebCore::IntPoint& point)
1090 {
1091     m_page->handleSelectionServiceClick(selection, telephoneNumbers, point);
1092 }
1093
1094 bool WebChromeClient::hasRelevantSelectionServices(bool isTextOnly) const
1095 {
1096     return (isTextOnly && WebProcess::singleton().hasSelectionServices()) || WebProcess::singleton().hasRichContentServices();
1097 }
1098 #endif
1099
1100 bool WebChromeClient::shouldDispatchFakeMouseMoveEvents() const
1101 {
1102     return m_page->shouldDispatchFakeMouseMoveEvents();
1103 }
1104
1105 } // namespace WebKit