4c709a0756d61894627c9282605d72f58d9eef4f
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / web / WebViewImpl.cpp
1 /*
2  * Copyright (C) 2011, 2012 Google 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 are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "WebViewImpl.h"
33
34 #include "CSSValueKeywords.h"
35 #include "CompositionUnderlineVectorBuilder.h"
36 #include "ContextFeaturesClientImpl.h"
37 #include "DatabaseClientImpl.h"
38 #include "FullscreenController.h"
39 #include "GeolocationClientProxy.h"
40 #include "GraphicsLayerFactoryChromium.h"
41 #include "HTMLNames.h"
42 #include "LinkHighlight.h"
43 #include "LocalFileSystemClient.h"
44 #include "MIDIClientProxy.h"
45 #include "PopupContainer.h"
46 #include "PrerendererClientImpl.h"
47 #include "RuntimeEnabledFeatures.h"
48 #include "SpeechInputClientImpl.h"
49 #include "SpeechRecognitionClientProxy.h"
50 #include "StorageQuotaClientImpl.h"
51 #include "ValidationMessageClientImpl.h"
52 #include "ViewportAnchor.h"
53 #include "WebAXObject.h"
54 #include "WebActiveWheelFlingParameters.h"
55 #include "WebAutofillClient.h"
56 #include "WebDevToolsAgentImpl.h"
57 #include "WebDevToolsAgentPrivate.h"
58 #include "WebFrameImpl.h"
59 #include "WebHitTestResult.h"
60 #include "WebInputElement.h"
61 #include "WebInputEventConversion.h"
62 #include "WebMediaPlayerAction.h"
63 #include "WebNode.h"
64 #include "WebPagePopupImpl.h"
65 #include "WebPlugin.h"
66 #include "WebPluginAction.h"
67 #include "WebPluginContainerImpl.h"
68 #include "WebPopupMenuImpl.h"
69 #include "WebRange.h"
70 #include "WebSettingsImpl.h"
71 #include "WebTextInputInfo.h"
72 #include "WebViewClient.h"
73 #include "WebWindowFeatures.h"
74 #include "WorkerGlobalScopeProxyProviderImpl.h"
75 #include "core/accessibility/AXObjectCache.h"
76 #include "core/clipboard/DataObject.h"
77 #include "core/dom/Document.h"
78 #include "core/dom/DocumentMarkerController.h"
79 #include "core/dom/Text.h"
80 #include "core/dom/WheelController.h"
81 #include "core/editing/Editor.h"
82 #include "core/editing/FrameSelection.h"
83 #include "core/editing/InputMethodController.h"
84 #include "core/editing/TextIterator.h"
85 #include "core/events/KeyboardEvent.h"
86 #include "core/events/WheelEvent.h"
87 #include "core/frame/FrameHost.h"
88 #include "core/frame/FrameView.h"
89 #include "core/frame/LocalFrame.h"
90 #include "core/frame/PinchViewport.h"
91 #include "core/frame/Settings.h"
92 #include "core/frame/SmartClip.h"
93 #include "core/html/HTMLInputElement.h"
94 #include "core/html/HTMLMediaElement.h"
95 #include "core/html/HTMLPlugInElement.h"
96 #include "core/html/HTMLTextAreaElement.h"
97 #include "core/html/ime/InputMethodContext.h"
98 #include "core/inspector/InspectorController.h"
99 #include "core/loader/DocumentLoader.h"
100 #include "core/loader/FrameLoader.h"
101 #include "core/loader/UniqueIdentifier.h"
102 #include "core/page/Chrome.h"
103 #include "core/page/ContextMenuController.h"
104 #include "core/page/DragController.h"
105 #include "core/page/DragData.h"
106 #include "core/page/DragSession.h"
107 #include "core/page/EventHandler.h"
108 #include "core/page/FocusController.h"
109 #include "core/page/FrameTree.h"
110 #include "core/page/InjectedStyleSheets.h"
111 #include "core/page/Page.h"
112 #include "core/page/PagePopupClient.h"
113 #include "core/page/PointerLockController.h"
114 #include "core/page/ScopedPageLoadDeferrer.h"
115 #include "core/page/TouchDisambiguation.h"
116 #include "core/rendering/RenderView.h"
117 #include "core/rendering/RenderWidget.h"
118 #include "core/rendering/TextAutosizer.h"
119 #include "core/rendering/compositing/RenderLayerCompositor.h"
120 #include "modules/device_orientation/DeviceOrientationInspectorAgent.h"
121 #include "modules/encryptedmedia/MediaKeysController.h"
122 #include "modules/geolocation/GeolocationController.h"
123 #include "modules/indexeddb/InspectorIndexedDBAgent.h"
124 #include "modules/notifications/NotificationController.h"
125 #include "painting/ContinuousPainter.h"
126 #include "platform/ContextMenu.h"
127 #include "platform/ContextMenuItem.h"
128 #include "platform/Cursor.h"
129 #include "platform/KeyboardCodes.h"
130 #include "platform/NotImplemented.h"
131 #include "platform/OverscrollTheme.h"
132 #include "platform/PlatformGestureEvent.h"
133 #include "platform/PlatformKeyboardEvent.h"
134 #include "platform/PlatformMouseEvent.h"
135 #include "platform/PlatformWheelEvent.h"
136 #include "platform/PopupMenuClient.h"
137 #include "platform/TraceEvent.h"
138 #include "platform/UserGestureIndicator.h"
139 #include "platform/exported/WebActiveGestureAnimation.h"
140 #include "platform/fonts/FontCache.h"
141 #include "platform/graphics/Color.h"
142 #include "platform/graphics/Image.h"
143 #include "platform/graphics/ImageBuffer.h"
144 #include "platform/scroll/ScrollbarTheme.h"
145 #include "platform/weborigin/SchemeRegistry.h"
146 #include "public/platform/Platform.h"
147 #include "public/platform/WebDragData.h"
148 #include "public/platform/WebFloatPoint.h"
149 #include "public/platform/WebGestureCurve.h"
150 #include "public/platform/WebImage.h"
151 #include "public/platform/WebLayerTreeView.h"
152 #include "public/platform/WebVector.h"
153 #include "wtf/CurrentTime.h"
154 #include "wtf/RefPtr.h"
155 #include "wtf/TemporaryChange.h"
156
157 #if USE(DEFAULT_RENDER_THEME)
158 #include "core/rendering/RenderThemeChromiumDefault.h"
159 #endif
160
161 // Get rid of WTF's pow define so we can use std::pow.
162 #undef pow
163 #include <cmath> // for std::pow
164
165 using namespace WebCore;
166 using namespace std;
167
168 // The following constants control parameters for automated scaling of webpages
169 // (such as due to a double tap gesture or find in page etc.). These are
170 // experimentally determined.
171 static const int touchPointPadding = 32;
172 static const int nonUserInitiatedPointPadding = 11;
173 static const float minScaleDifference = 0.01f;
174 static const float doubleTapZoomContentDefaultMargin = 5;
175 static const float doubleTapZoomContentMinimumMargin = 2;
176 static const double doubleTapZoomAnimationDurationInSeconds = 0.25;
177 static const float doubleTapZoomAlreadyLegibleRatio = 1.2f;
178
179 static const double multipleTargetsZoomAnimationDurationInSeconds = 0.25;
180 static const double findInPageAnimationDurationInSeconds = 0;
181
182 // Constants for viewport anchoring on resize.
183 static const float viewportAnchorXCoord = 0.5f;
184 static const float viewportAnchorYCoord = 0;
185
186 // Constants for zooming in on a focused text field.
187 static const double scrollAndScaleAnimationDurationInSeconds = 0.2;
188 static const int minReadableCaretHeight = 18;
189 static const float minScaleChangeToTriggerZoom = 1.05f;
190 static const float leftBoxRatio = 0.3f;
191 static const int caretPadding = 10;
192
193 namespace blink {
194
195 // Change the text zoom level by kTextSizeMultiplierRatio each time the user
196 // zooms text in or out (ie., change by 20%).  The min and max values limit
197 // text zoom to half and 3x the original text size.  These three values match
198 // those in Apple's port in WebKit/WebKit/WebView/WebView.mm
199 const double WebView::textSizeMultiplierRatio = 1.2;
200 const double WebView::minTextSizeMultiplier = 0.5;
201 const double WebView::maxTextSizeMultiplier = 3.0;
202
203 // Used to defer all page activity in cases where the embedder wishes to run
204 // a nested event loop. Using a stack enables nesting of message loop invocations.
205 static Vector<ScopedPageLoadDeferrer*>& pageLoadDeferrerStack()
206 {
207     DEFINE_STATIC_LOCAL(Vector<ScopedPageLoadDeferrer*>, deferrerStack, ());
208     return deferrerStack;
209 }
210
211 // Ensure that the WebDragOperation enum values stay in sync with the original
212 // DragOperation constants.
213 #define COMPILE_ASSERT_MATCHING_ENUM(coreName) \
214     COMPILE_ASSERT(int(coreName) == int(Web##coreName), dummy##coreName)
215 COMPILE_ASSERT_MATCHING_ENUM(DragOperationNone);
216 COMPILE_ASSERT_MATCHING_ENUM(DragOperationCopy);
217 COMPILE_ASSERT_MATCHING_ENUM(DragOperationLink);
218 COMPILE_ASSERT_MATCHING_ENUM(DragOperationGeneric);
219 COMPILE_ASSERT_MATCHING_ENUM(DragOperationPrivate);
220 COMPILE_ASSERT_MATCHING_ENUM(DragOperationMove);
221 COMPILE_ASSERT_MATCHING_ENUM(DragOperationDelete);
222 COMPILE_ASSERT_MATCHING_ENUM(DragOperationEvery);
223
224 static bool shouldUseExternalPopupMenus = false;
225
226 static int webInputEventKeyStateToPlatformEventKeyState(int webInputEventKeyState)
227 {
228     int platformEventKeyState = 0;
229     if (webInputEventKeyState & WebInputEvent::ShiftKey)
230         platformEventKeyState = platformEventKeyState | WebCore::PlatformEvent::ShiftKey;
231     if (webInputEventKeyState & WebInputEvent::ControlKey)
232         platformEventKeyState = platformEventKeyState | WebCore::PlatformEvent::CtrlKey;
233     if (webInputEventKeyState & WebInputEvent::AltKey)
234         platformEventKeyState = platformEventKeyState | WebCore::PlatformEvent::AltKey;
235     if (webInputEventKeyState & WebInputEvent::MetaKey)
236         platformEventKeyState = platformEventKeyState | WebCore::PlatformEvent::MetaKey;
237     return platformEventKeyState;
238 }
239
240 // WebView ----------------------------------------------------------------
241
242 WebView* WebView::create(WebViewClient* client)
243 {
244     // Pass the WebViewImpl's self-reference to the caller.
245     return WebViewImpl::create(client);
246 }
247
248 WebViewImpl* WebViewImpl::create(WebViewClient* client)
249 {
250     // Pass the WebViewImpl's self-reference to the caller.
251     return adoptRef(new WebViewImpl(client)).leakRef();
252 }
253
254 void WebView::setUseExternalPopupMenus(bool useExternalPopupMenus)
255 {
256     shouldUseExternalPopupMenus = useExternalPopupMenus;
257 }
258
259 void WebView::updateVisitedLinkState(unsigned long long linkHash)
260 {
261     Page::visitedStateChanged(linkHash);
262 }
263
264 void WebView::resetVisitedLinkState()
265 {
266     Page::allVisitedStateChanged();
267 }
268
269 void WebView::willEnterModalLoop()
270 {
271     pageLoadDeferrerStack().append(new ScopedPageLoadDeferrer());
272 }
273
274 void WebView::didExitModalLoop()
275 {
276     ASSERT(pageLoadDeferrerStack().size());
277
278     delete pageLoadDeferrerStack().last();
279     pageLoadDeferrerStack().removeLast();
280 }
281
282 void WebViewImpl::setMainFrame(WebFrame* frame)
283 {
284     toWebFrameImpl(frame)->initializeAsMainFrame(page());
285 }
286
287 void WebViewImpl::setAutofillClient(WebAutofillClient* autofillClient)
288 {
289     m_autofillClient = autofillClient;
290 }
291
292 void WebViewImpl::setDevToolsAgentClient(WebDevToolsAgentClient* devToolsClient)
293 {
294     if (devToolsClient)
295         m_devToolsAgent = adoptPtr(new WebDevToolsAgentImpl(this, devToolsClient));
296     else
297         m_devToolsAgent.clear();
298 }
299
300 void WebViewImpl::setPrerendererClient(WebPrerendererClient* prerendererClient)
301 {
302     ASSERT(m_page);
303     providePrerendererClientTo(*m_page, new PrerendererClientImpl(prerendererClient));
304 }
305
306 void WebViewImpl::setSpellCheckClient(WebSpellCheckClient* spellCheckClient)
307 {
308     m_spellCheckClient = spellCheckClient;
309 }
310
311 void WebViewImpl::setPasswordGeneratorClient(WebPasswordGeneratorClient* client)
312 {
313     m_passwordGeneratorClient = client;
314 }
315
316 WebViewImpl::WebViewImpl(WebViewClient* client)
317     : m_client(client)
318     , m_autofillClient(0)
319     , m_spellCheckClient(0)
320     , m_passwordGeneratorClient(0)
321     , m_chromeClientImpl(this)
322     , m_contextMenuClientImpl(this)
323     , m_dragClientImpl(this)
324     , m_editorClientImpl(this)
325     , m_inspectorClientImpl(this)
326     , m_backForwardClientImpl(this)
327     , m_spellCheckerClientImpl(this)
328     , m_storageClientImpl(this)
329     , m_fixedLayoutSizeLock(false)
330     , m_shouldAutoResize(false)
331     , m_zoomLevel(0)
332     , m_minimumZoomLevel(zoomFactorToZoomLevel(minTextSizeMultiplier))
333     , m_maximumZoomLevel(zoomFactorToZoomLevel(maxTextSizeMultiplier))
334     , m_savedPageScaleFactor(0)
335     , m_doubleTapZoomPageScaleFactor(0)
336     , m_doubleTapZoomPending(false)
337     , m_enableFakePageScaleAnimationForTesting(false)
338     , m_fakePageScaleAnimationPageScaleFactor(0)
339     , m_fakePageScaleAnimationUseAnchor(false)
340     , m_contextMenuAllowed(false)
341     , m_doingDragAndDrop(false)
342     , m_ignoreInputEvents(false)
343     , m_compositorDeviceScaleFactorOverride(0)
344     , m_rootLayerScale(1)
345     , m_suppressNextKeypressEvent(false)
346     , m_imeAcceptEvents(true)
347     , m_operationsAllowed(WebDragOperationNone)
348     , m_dragOperation(WebDragOperationNone)
349     , m_featureSwitchClient(adoptPtr(new ContextFeaturesClientImpl()))
350     , m_isTransparent(false)
351     , m_tabsToLinks(false)
352     , m_layerTreeView(0)
353     , m_rootLayer(0)
354     , m_rootGraphicsLayer(0)
355     , m_rootTransformLayer(0)
356     , m_graphicsLayerFactory(adoptPtr(new GraphicsLayerFactoryChromium(this)))
357     , m_isAcceleratedCompositingActive(false)
358     , m_layerTreeViewCommitsDeferred(false)
359     , m_compositorCreationFailed(false)
360     , m_recreatingGraphicsContext(false)
361 #if ENABLE(INPUT_SPEECH)
362     , m_speechInputClient(SpeechInputClientImpl::create(client))
363 #endif
364     , m_speechRecognitionClient(SpeechRecognitionClientProxy::create(client ? client->speechRecognizer() : 0))
365     , m_geolocationClientProxy(adoptPtr(new GeolocationClientProxy(client ? client->geolocationClient() : 0)))
366     , m_userMediaClientImpl(this)
367     , m_midiClientProxy(adoptPtr(new MIDIClientProxy(client ? client->webMIDIClient() : 0)))
368     , m_navigatorContentUtilsClient(NavigatorContentUtilsClientImpl::create(this))
369     , m_flingModifier(0)
370     , m_flingSourceDevice(false)
371     , m_fullscreenController(FullscreenController::create(this))
372     , m_showFPSCounter(false)
373     , m_showPaintRects(false)
374     , m_showDebugBorders(false)
375     , m_continuousPaintingEnabled(false)
376     , m_showScrollBottleneckRects(false)
377     , m_baseBackgroundColor(Color::white)
378     , m_backgroundColorOverride(Color::transparent)
379     , m_zoomFactorOverride(0)
380 {
381     Page::PageClients pageClients;
382     pageClients.chromeClient = &m_chromeClientImpl;
383     pageClients.contextMenuClient = &m_contextMenuClientImpl;
384     pageClients.editorClient = &m_editorClientImpl;
385     pageClients.dragClient = &m_dragClientImpl;
386     pageClients.inspectorClient = &m_inspectorClientImpl;
387     pageClients.backForwardClient = &m_backForwardClientImpl;
388     pageClients.spellCheckerClient = &m_spellCheckerClientImpl;
389     pageClients.storageClient = &m_storageClientImpl;
390
391     m_page = adoptPtr(new Page(pageClients));
392     provideUserMediaTo(*m_page, &m_userMediaClientImpl);
393     MediaKeysController::provideMediaKeysTo(*m_page, &m_mediaKeysClientImpl);
394     provideMIDITo(*m_page, m_midiClientProxy.get());
395 #if ENABLE(INPUT_SPEECH)
396     provideSpeechInputTo(*m_page, m_speechInputClient.get());
397 #endif
398     provideSpeechRecognitionTo(*m_page, m_speechRecognitionClient.get());
399     provideNotification(*m_page, notificationPresenterImpl());
400     provideNavigatorContentUtilsTo(*m_page, m_navigatorContentUtilsClient.get());
401
402     provideContextFeaturesTo(*m_page, m_featureSwitchClient.get());
403     if (RuntimeEnabledFeatures::deviceOrientationEnabled())
404         DeviceOrientationInspectorAgent::provideTo(*m_page);
405     provideGeolocationTo(*m_page, m_geolocationClientProxy.get());
406     m_geolocationClientProxy->setController(GeolocationController::from(m_page.get()));
407
408     provideLocalFileSystemTo(*m_page, LocalFileSystemClient::create());
409     provideDatabaseClientTo(*m_page, DatabaseClientImpl::create());
410     InspectorIndexedDBAgent::provideTo(m_page.get());
411     provideStorageQuotaClientTo(*m_page, StorageQuotaClientImpl::create());
412     m_validationMessage = ValidationMessageClientImpl::create(*this);
413     m_page->setValidationMessageClient(m_validationMessage.get());
414     provideWorkerGlobalScopeProxyProviderTo(*m_page, WorkerGlobalScopeProxyProviderImpl::create());
415
416     m_page->makeOrdinary();
417
418     if (m_client) {
419         setDeviceScaleFactor(m_client->screenInfo().deviceScaleFactor);
420         setVisibilityState(m_client->visibilityState(), true);
421     }
422
423     m_inspectorSettingsMap = adoptPtr(new SettingsMap);
424 }
425
426 WebViewImpl::~WebViewImpl()
427 {
428     ASSERT(!m_page);
429 }
430
431 WebFrameImpl* WebViewImpl::mainFrameImpl()
432 {
433     return m_page ? WebFrameImpl::fromFrame(m_page->mainFrame()) : 0;
434 }
435
436 bool WebViewImpl::tabKeyCyclesThroughElements() const
437 {
438     ASSERT(m_page);
439     return m_page->tabKeyCyclesThroughElements();
440 }
441
442 void WebViewImpl::setTabKeyCyclesThroughElements(bool value)
443 {
444     if (m_page)
445         m_page->setTabKeyCyclesThroughElements(value);
446 }
447
448 void WebViewImpl::handleMouseLeave(LocalFrame& mainFrame, const WebMouseEvent& event)
449 {
450     m_client->setMouseOverURL(WebURL());
451     PageWidgetEventHandler::handleMouseLeave(mainFrame, event);
452 }
453
454 void WebViewImpl::handleMouseDown(LocalFrame& mainFrame, const WebMouseEvent& event)
455 {
456     // If there is a popup open, close it as the user is clicking on the page (outside of the
457     // popup). We also save it so we can prevent a click on an element from immediately
458     // reopening the same popup.
459     RefPtr<PopupContainer> selectPopup;
460     RefPtr<WebPagePopupImpl> pagePopup;
461     if (event.button == WebMouseEvent::ButtonLeft) {
462         selectPopup = m_selectPopup;
463         pagePopup = m_pagePopup;
464         hidePopups();
465         ASSERT(!m_selectPopup);
466         ASSERT(!m_pagePopup);
467     }
468
469     m_lastMouseDownPoint = WebPoint(event.x, event.y);
470
471     if (event.button == WebMouseEvent::ButtonLeft) {
472         IntPoint point(event.x, event.y);
473         point = m_page->mainFrame()->view()->windowToContents(point);
474         HitTestResult result(m_page->mainFrame()->eventHandler().hitTestResultAtPoint(point));
475         Node* hitNode = result.innerNonSharedNode();
476
477         // Take capture on a mouse down on a plugin so we can send it mouse events.
478         if (hitNode && hitNode->renderer() && hitNode->renderer()->isEmbeddedObject()) {
479             m_mouseCaptureNode = hitNode;
480             TRACE_EVENT_ASYNC_BEGIN0("input", "capturing mouse", this);
481         }
482     }
483
484     PageWidgetEventHandler::handleMouseDown(mainFrame, event);
485
486     if (event.button == WebMouseEvent::ButtonLeft && m_mouseCaptureNode)
487         m_mouseCaptureGestureToken = mainFrame.eventHandler().takeLastMouseDownGestureToken();
488
489     if (m_selectPopup && m_selectPopup == selectPopup) {
490         // That click triggered a select popup which is the same as the one that
491         // was showing before the click.  It means the user clicked the select
492         // while the popup was showing, and as a result we first closed then
493         // immediately reopened the select popup.  It needs to be closed.
494         hideSelectPopup();
495     }
496
497     if (m_pagePopup && pagePopup && m_pagePopup->hasSamePopupClient(pagePopup.get())) {
498         // That click triggered a page popup that is the same as the one we just closed.
499         // It needs to be closed.
500         closePagePopup(m_pagePopup.get());
501     }
502
503     // Dispatch the contextmenu event regardless of if the click was swallowed.
504 #if OS(WIN)
505     // On Windows, we handle it on mouse up, not down.
506 #elif OS(MACOSX)
507     if (event.button == WebMouseEvent::ButtonRight
508         || (event.button == WebMouseEvent::ButtonLeft
509             && event.modifiers & WebMouseEvent::ControlKey))
510         mouseContextMenu(event);
511 #else
512     if (event.button == WebMouseEvent::ButtonRight)
513         mouseContextMenu(event);
514 #endif
515 }
516
517 void WebViewImpl::mouseContextMenu(const WebMouseEvent& event)
518 {
519     if (!mainFrameImpl() || !mainFrameImpl()->frameView())
520         return;
521
522     m_page->contextMenuController().clearContextMenu();
523
524     PlatformMouseEventBuilder pme(mainFrameImpl()->frameView(), event);
525
526     // Find the right target frame. See issue 1186900.
527     HitTestResult result = hitTestResultForWindowPos(pme.position());
528     LocalFrame* targetFrame;
529     if (result.innerNonSharedNode())
530         targetFrame = result.innerNonSharedNode()->document().frame();
531     else
532         targetFrame = m_page->focusController().focusedOrMainFrame();
533
534 #if OS(WIN)
535     targetFrame->view()->setCursor(pointerCursor());
536 #endif
537
538     m_contextMenuAllowed = true;
539     targetFrame->eventHandler().sendContextMenuEvent(pme);
540     m_contextMenuAllowed = false;
541     // Actually showing the context menu is handled by the ContextMenuClient
542     // implementation...
543 }
544
545 void WebViewImpl::handleMouseUp(LocalFrame& mainFrame, const WebMouseEvent& event)
546 {
547     PageWidgetEventHandler::handleMouseUp(mainFrame, event);
548
549 #if OS(WIN)
550     // Dispatch the contextmenu event regardless of if the click was swallowed.
551     // On Mac/Linux, we handle it on mouse down, not up.
552     if (event.button == WebMouseEvent::ButtonRight)
553         mouseContextMenu(event);
554 #endif
555 }
556
557 bool WebViewImpl::handleMouseWheel(LocalFrame& mainFrame, const WebMouseWheelEvent& event)
558 {
559     hidePopups();
560     return PageWidgetEventHandler::handleMouseWheel(mainFrame, event);
561 }
562
563 void WebViewImpl::scrollBy(const WebFloatSize& delta)
564 {
565     if (m_flingSourceDevice == WebGestureEvent::Touchpad) {
566         WebMouseWheelEvent syntheticWheel;
567         const float tickDivisor = WebCore::WheelEvent::TickMultiplier;
568
569         syntheticWheel.deltaX = delta.width;
570         syntheticWheel.deltaY = delta.height;
571         syntheticWheel.wheelTicksX = delta.width / tickDivisor;
572         syntheticWheel.wheelTicksY = delta.height / tickDivisor;
573         syntheticWheel.hasPreciseScrollingDeltas = true;
574         syntheticWheel.x = m_positionOnFlingStart.x;
575         syntheticWheel.y = m_positionOnFlingStart.y;
576         syntheticWheel.globalX = m_globalPositionOnFlingStart.x;
577         syntheticWheel.globalY = m_globalPositionOnFlingStart.y;
578         syntheticWheel.modifiers = m_flingModifier;
579
580         if (m_page && m_page->mainFrame() && m_page->mainFrame()->view())
581             handleMouseWheel(*m_page->mainFrame(), syntheticWheel);
582     } else {
583         WebGestureEvent syntheticGestureEvent;
584
585         syntheticGestureEvent.type = WebInputEvent::GestureScrollUpdateWithoutPropagation;
586         syntheticGestureEvent.data.scrollUpdate.deltaX = delta.width;
587         syntheticGestureEvent.data.scrollUpdate.deltaY = delta.height;
588         syntheticGestureEvent.x = m_positionOnFlingStart.x;
589         syntheticGestureEvent.y = m_positionOnFlingStart.y;
590         syntheticGestureEvent.globalX = m_globalPositionOnFlingStart.x;
591         syntheticGestureEvent.globalY = m_globalPositionOnFlingStart.y;
592         syntheticGestureEvent.modifiers = m_flingModifier;
593         syntheticGestureEvent.sourceDevice = WebGestureEvent::Touchscreen;
594
595         if (m_page && m_page->mainFrame() && m_page->mainFrame()->view())
596             handleGestureEvent(syntheticGestureEvent);
597     }
598 }
599
600 bool WebViewImpl::handleGestureEvent(const WebGestureEvent& event)
601 {
602     bool eventSwallowed = false;
603     bool eventCancelled = false; // for disambiguation
604
605     // Special handling for slow-path fling gestures.
606     switch (event.type) {
607     case WebInputEvent::GestureFlingStart: {
608         if (mainFrameImpl()->frame()->eventHandler().isScrollbarHandlingGestures())
609             break;
610         m_client->cancelScheduledContentIntents();
611         m_positionOnFlingStart = WebPoint(event.x / pageScaleFactor(), event.y / pageScaleFactor());
612         m_globalPositionOnFlingStart = WebPoint(event.globalX, event.globalY);
613         m_flingModifier = event.modifiers;
614         m_flingSourceDevice = event.sourceDevice;
615         OwnPtr<WebGestureCurve> flingCurve = adoptPtr(Platform::current()->createFlingAnimationCurve(event.sourceDevice, WebFloatPoint(event.data.flingStart.velocityX, event.data.flingStart.velocityY), WebSize()));
616         m_gestureAnimation = WebActiveGestureAnimation::createAtAnimationStart(flingCurve.release(), this);
617         scheduleAnimation();
618         eventSwallowed = true;
619
620         m_client->didHandleGestureEvent(event, eventCancelled);
621         return eventSwallowed;
622     }
623     case WebInputEvent::GestureFlingCancel:
624         if (endActiveFlingAnimation())
625             eventSwallowed = true;
626
627         m_client->didHandleGestureEvent(event, eventCancelled);
628         return eventSwallowed;
629     default:
630         break;
631     }
632
633     PlatformGestureEventBuilder platformEvent(mainFrameImpl()->frameView(), event);
634
635     // Handle link highlighting outside the main switch to avoid getting lost in the
636     // complicated set of cases handled below.
637     switch (event.type) {
638     case WebInputEvent::GestureShowPress:
639         // Queue a highlight animation, then hand off to regular handler.
640         if (settingsImpl()->gestureTapHighlightEnabled())
641             enableTapHighlightAtPoint(platformEvent);
642         break;
643     case WebInputEvent::GestureTapCancel:
644     case WebInputEvent::GestureTap:
645     case WebInputEvent::GestureLongPress:
646         for (size_t i = 0; i < m_linkHighlights.size(); ++i)
647             m_linkHighlights[i]->startHighlightAnimationIfNeeded();
648         break;
649     default:
650         break;
651     }
652
653     switch (event.type) {
654     case WebInputEvent::GestureTap: {
655         m_client->cancelScheduledContentIntents();
656         if (detectContentOnTouch(platformEvent.position())) {
657             eventSwallowed = true;
658             break;
659         }
660
661         RefPtr<PopupContainer> selectPopup;
662         selectPopup = m_selectPopup;
663         hideSelectPopup();
664         ASSERT(!m_selectPopup);
665
666         // Don't trigger a disambiguation popup on sites designed for mobile devices.
667         // Instead, assume that the page has been designed with big enough buttons and links.
668         if (event.data.tap.width > 0 && !shouldDisableDesktopWorkarounds()) {
669             // FIXME: didTapMultipleTargets should just take a rect instead of
670             // an event.
671             WebGestureEvent scaledEvent = event;
672             scaledEvent.x = event.x / pageScaleFactor();
673             scaledEvent.y = event.y / pageScaleFactor();
674             scaledEvent.data.tap.width = event.data.tap.width / pageScaleFactor();
675             scaledEvent.data.tap.height = event.data.tap.height / pageScaleFactor();
676             IntRect boundingBox(scaledEvent.x - scaledEvent.data.tap.width / 2, scaledEvent.y - scaledEvent.data.tap.height / 2, scaledEvent.data.tap.width, scaledEvent.data.tap.height);
677             Vector<IntRect> goodTargets;
678             Vector<Node*> highlightNodes;
679             findGoodTouchTargets(boundingBox, mainFrameImpl()->frame(), goodTargets, highlightNodes);
680             // FIXME: replace touch adjustment code when numberOfGoodTargets == 1?
681             // Single candidate case is currently handled by: https://bugs.webkit.org/show_bug.cgi?id=85101
682             if (goodTargets.size() >= 2 && m_client && m_client->didTapMultipleTargets(scaledEvent, goodTargets)) {
683                 if (settingsImpl()->gestureTapHighlightEnabled())
684                     enableTapHighlights(highlightNodes);
685                 for (size_t i = 0; i < m_linkHighlights.size(); ++i)
686                     m_linkHighlights[i]->startHighlightAnimationIfNeeded();
687                 eventSwallowed = true;
688                 eventCancelled = true;
689                 break;
690             }
691         }
692
693         eventSwallowed = mainFrameImpl()->frame()->eventHandler().handleGestureEvent(platformEvent);
694
695         if (m_selectPopup && m_selectPopup == selectPopup) {
696             // That tap triggered a select popup which is the same as the one that
697             // was showing before the tap. It means the user tapped the select
698             // while the popup was showing, and as a result we first closed then
699             // immediately reopened the select popup. It needs to be closed.
700             hideSelectPopup();
701         }
702
703         break;
704     }
705     case WebInputEvent::GestureTwoFingerTap:
706     case WebInputEvent::GestureLongPress:
707     case WebInputEvent::GestureLongTap: {
708         if (!mainFrameImpl() || !mainFrameImpl()->frameView())
709             break;
710
711         m_client->cancelScheduledContentIntents();
712         m_page->contextMenuController().clearContextMenu();
713         m_contextMenuAllowed = true;
714         eventSwallowed = mainFrameImpl()->frame()->eventHandler().handleGestureEvent(platformEvent);
715         m_contextMenuAllowed = false;
716
717         break;
718     }
719     case WebInputEvent::GestureShowPress: {
720         m_client->cancelScheduledContentIntents();
721         eventSwallowed = mainFrameImpl()->frame()->eventHandler().handleGestureEvent(platformEvent);
722         break;
723     }
724     case WebInputEvent::GestureDoubleTap:
725         if (m_webSettings->doubleTapToZoomEnabled() && minimumPageScaleFactor() != maximumPageScaleFactor()) {
726             m_client->cancelScheduledContentIntents();
727             animateDoubleTapZoom(platformEvent.position());
728         }
729         // GestureDoubleTap is currently only used by Android for zooming. For WebCore,
730         // GestureTap with tap count = 2 is used instead. So we drop GestureDoubleTap here.
731         eventSwallowed = true;
732         break;
733     case WebInputEvent::GestureScrollBegin:
734     case WebInputEvent::GesturePinchBegin:
735         m_client->cancelScheduledContentIntents();
736     case WebInputEvent::GestureTapDown:
737     case WebInputEvent::GestureScrollEnd:
738     case WebInputEvent::GestureScrollUpdate:
739     case WebInputEvent::GestureScrollUpdateWithoutPropagation:
740     case WebInputEvent::GestureTapCancel:
741     case WebInputEvent::GestureTapUnconfirmed:
742     case WebInputEvent::GesturePinchEnd:
743     case WebInputEvent::GesturePinchUpdate:
744     case WebInputEvent::GestureFlingStart: {
745         eventSwallowed = mainFrameImpl()->frame()->eventHandler().handleGestureEvent(platformEvent);
746         break;
747     }
748     default:
749         ASSERT_NOT_REACHED();
750     }
751     m_client->didHandleGestureEvent(event, eventCancelled);
752     return eventSwallowed;
753 }
754
755 void WebViewImpl::transferActiveWheelFlingAnimation(const WebActiveWheelFlingParameters& parameters)
756 {
757     TRACE_EVENT0("webkit", "WebViewImpl::transferActiveWheelFlingAnimation");
758     ASSERT(!m_gestureAnimation);
759     m_positionOnFlingStart = parameters.point;
760     m_globalPositionOnFlingStart = parameters.globalPoint;
761     m_flingModifier = parameters.modifiers;
762     OwnPtr<WebGestureCurve> curve = adoptPtr(Platform::current()->createFlingAnimationCurve(parameters.sourceDevice, WebFloatPoint(parameters.delta), parameters.cumulativeScroll));
763     m_gestureAnimation = WebActiveGestureAnimation::createWithTimeOffset(curve.release(), this, parameters.startTime);
764     scheduleAnimation();
765 }
766
767 bool WebViewImpl::endActiveFlingAnimation()
768 {
769     if (m_gestureAnimation) {
770         m_gestureAnimation.clear();
771         if (m_layerTreeView)
772             m_layerTreeView->didStopFlinging();
773         return true;
774     }
775     return false;
776 }
777
778 bool WebViewImpl::startPageScaleAnimation(const IntPoint& targetPosition, bool useAnchor, float newScale, double durationInSeconds)
779 {
780     WebPoint clampedPoint = targetPosition;
781     if (!useAnchor) {
782         clampedPoint = clampOffsetAtScale(targetPosition, newScale);
783         if (!durationInSeconds) {
784             setPageScaleFactor(newScale, clampedPoint);
785             return false;
786         }
787     }
788     if (useAnchor && newScale == pageScaleFactor())
789         return false;
790
791     if (m_enableFakePageScaleAnimationForTesting) {
792         m_fakePageScaleAnimationTargetPosition = targetPosition;
793         m_fakePageScaleAnimationUseAnchor = useAnchor;
794         m_fakePageScaleAnimationPageScaleFactor = newScale;
795     } else {
796         if (!m_layerTreeView)
797             return false;
798         m_layerTreeView->startPageScaleAnimation(targetPosition, useAnchor, newScale, durationInSeconds);
799     }
800     return true;
801 }
802
803 void WebViewImpl::enableFakePageScaleAnimationForTesting(bool enable)
804 {
805     m_enableFakePageScaleAnimationForTesting = enable;
806 }
807
808 void WebViewImpl::setShowFPSCounter(bool show)
809 {
810     if (m_layerTreeView) {
811         TRACE_EVENT0("webkit", "WebViewImpl::setShowFPSCounter");
812         m_layerTreeView->setShowFPSCounter(show);
813     }
814     m_showFPSCounter = show;
815 }
816
817 void WebViewImpl::setShowPaintRects(bool show)
818 {
819     if (m_layerTreeView) {
820         TRACE_EVENT0("webkit", "WebViewImpl::setShowPaintRects");
821         m_layerTreeView->setShowPaintRects(show);
822     }
823     m_showPaintRects = show;
824 }
825
826 void WebViewImpl::setShowDebugBorders(bool show)
827 {
828     if (m_layerTreeView)
829         m_layerTreeView->setShowDebugBorders(show);
830     m_showDebugBorders = show;
831 }
832
833 void WebViewImpl::setContinuousPaintingEnabled(bool enabled)
834 {
835     if (m_layerTreeView) {
836         TRACE_EVENT0("webkit", "WebViewImpl::setContinuousPaintingEnabled");
837         m_layerTreeView->setContinuousPaintingEnabled(enabled);
838     }
839     m_continuousPaintingEnabled = enabled;
840     m_client->scheduleAnimation();
841 }
842
843 void WebViewImpl::setShowScrollBottleneckRects(bool show)
844 {
845     if (m_layerTreeView)
846         m_layerTreeView->setShowScrollBottleneckRects(show);
847     m_showScrollBottleneckRects = show;
848 }
849
850 void WebViewImpl::getSelectionRootBounds(WebRect& bounds) const
851 {
852     const LocalFrame* frame = focusedWebCoreFrame();
853     if (!frame)
854         return;
855
856     Element* root = frame->selection().rootEditableElementOrDocumentElement();
857     if (!root)
858         return;
859
860     // If the selection is inside a form control, the root will be a <div> that
861     // behaves as the editor but we want to return the actual element's bounds.
862     // In practice, that means <textarea> and <input> controls that behave like
863     // a text field.
864     Element* shadowHost = root->shadowHost();
865     if (shadowHost
866         && (isHTMLTextAreaElement(*shadowHost)
867             || (isHTMLInputElement(*shadowHost)
868                 && toHTMLInputElement(*shadowHost).isText())))
869         root = shadowHost;
870
871     IntRect boundingBox = isHTMLHtmlElement(root)
872         ? IntRect(IntPoint(0, 0), root->document().frame()->view()->contentsSize())
873         : root->pixelSnappedBoundingBox();
874
875     boundingBox = root->document().frame()->view()->contentsToWindow(boundingBox);
876     boundingBox.scale(pageScaleFactor());
877     bounds = boundingBox;
878 }
879
880 bool WebViewImpl::handleKeyEvent(const WebKeyboardEvent& event)
881 {
882     ASSERT((event.type == WebInputEvent::RawKeyDown)
883         || (event.type == WebInputEvent::KeyDown)
884         || (event.type == WebInputEvent::KeyUp));
885
886     // Halt an in-progress fling on a key event.
887     endActiveFlingAnimation();
888
889     // Please refer to the comments explaining the m_suppressNextKeypressEvent
890     // member.
891     // The m_suppressNextKeypressEvent is set if the KeyDown is handled by
892     // Webkit. A keyDown event is typically associated with a keyPress(char)
893     // event and a keyUp event. We reset this flag here as this is a new keyDown
894     // event.
895     m_suppressNextKeypressEvent = false;
896
897     // If there is a select popup, it should be the one processing the event,
898     // not the page.
899     if (m_selectPopup)
900         return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
901     if (m_pagePopup) {
902         m_pagePopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
903         // We need to ignore the next Char event after this otherwise pressing
904         // enter when selecting an item in the popup will go to the page.
905         if (WebInputEvent::RawKeyDown == event.type)
906             m_suppressNextKeypressEvent = true;
907         return true;
908     }
909
910     RefPtr<LocalFrame> frame = focusedWebCoreFrame();
911     if (!frame)
912         return false;
913
914 #if !OS(MACOSX)
915     const WebInputEvent::Type contextMenuTriggeringEventType =
916 #if OS(WIN)
917         WebInputEvent::KeyUp;
918 #else
919         WebInputEvent::RawKeyDown;
920 #endif
921
922     bool isUnmodifiedMenuKey = !(event.modifiers & WebInputEvent::InputModifiers) && event.windowsKeyCode == VKEY_APPS;
923     bool isShiftF10 = event.modifiers == WebInputEvent::ShiftKey && event.windowsKeyCode == VKEY_F10;
924     if ((isUnmodifiedMenuKey || isShiftF10) && event.type == contextMenuTriggeringEventType) {
925         sendContextMenuEvent(event);
926         return true;
927     }
928 #endif // !OS(MACOSX)
929
930     PlatformKeyboardEventBuilder evt(event);
931
932     if (frame->eventHandler().keyEvent(evt)) {
933         if (WebInputEvent::RawKeyDown == event.type) {
934             // Suppress the next keypress event unless the focused node is a plug-in node.
935             // (Flash needs these keypress events to handle non-US keyboards.)
936             Element* element = focusedElement();
937             if (!element || !element->renderer() || !element->renderer()->isEmbeddedObject())
938                 m_suppressNextKeypressEvent = true;
939         }
940         return true;
941     }
942
943     return keyEventDefault(event);
944 }
945
946 bool WebViewImpl::handleCharEvent(const WebKeyboardEvent& event)
947 {
948     ASSERT(event.type == WebInputEvent::Char);
949
950     // Please refer to the comments explaining the m_suppressNextKeypressEvent
951     // member.  The m_suppressNextKeypressEvent is set if the KeyDown is
952     // handled by Webkit. A keyDown event is typically associated with a
953     // keyPress(char) event and a keyUp event. We reset this flag here as it
954     // only applies to the current keyPress event.
955     bool suppress = m_suppressNextKeypressEvent;
956     m_suppressNextKeypressEvent = false;
957
958     // If there is a select popup, it should be the one processing the event,
959     // not the page.
960     if (m_selectPopup)
961         return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
962     if (m_pagePopup)
963         return m_pagePopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
964
965     LocalFrame* frame = focusedWebCoreFrame();
966     if (!frame)
967         return suppress;
968
969     EventHandler& handler = frame->eventHandler();
970
971     PlatformKeyboardEventBuilder evt(event);
972     if (!evt.isCharacterKey())
973         return true;
974
975     // Accesskeys are triggered by char events and can't be suppressed.
976     if (handler.handleAccessKey(evt))
977         return true;
978
979     // Safari 3.1 does not pass off windows system key messages (WM_SYSCHAR) to
980     // the eventHandler::keyEvent. We mimic this behavior on all platforms since
981     // for now we are converting other platform's key events to windows key
982     // events.
983     if (evt.isSystemKey())
984         return false;
985
986     if (!suppress && !handler.keyEvent(evt))
987         return keyEventDefault(event);
988
989     return true;
990 }
991
992 WebRect WebViewImpl::computeBlockBounds(const WebRect& rect, bool ignoreClipping)
993 {
994     if (!mainFrameImpl())
995         return WebRect();
996
997     // Use the rect-based hit test to find the node.
998     IntPoint point = mainFrameImpl()->frameView()->windowToContents(IntPoint(rect.x, rect.y));
999     HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent | (ignoreClipping ? HitTestRequest::IgnoreClipping : 0);
1000     HitTestResult result = mainFrameImpl()->frame()->eventHandler().hitTestResultAtPoint(point, hitType, IntSize(rect.width, rect.height));
1001
1002     Node* node = result.innerNonSharedNode();
1003     if (!node)
1004         return WebRect();
1005
1006     // Find the block type node based on the hit node.
1007     while (node && (!node->renderer() || node->renderer()->isInline()))
1008         node = node->parentNode();
1009
1010     // Return the bounding box in the window coordinate system.
1011     if (node) {
1012         IntRect rect = node->Node::pixelSnappedBoundingBox();
1013         LocalFrame* frame = node->document().frame();
1014         return frame->view()->contentsToWindow(rect);
1015     }
1016     return WebRect();
1017 }
1018
1019 WebRect WebViewImpl::widenRectWithinPageBounds(const WebRect& source, int targetMargin, int minimumMargin)
1020 {
1021     WebSize maxSize;
1022     if (mainFrame())
1023         maxSize = mainFrame()->contentsSize();
1024     IntSize scrollOffset;
1025     if (mainFrame())
1026         scrollOffset = mainFrame()->scrollOffset();
1027     int leftMargin = targetMargin;
1028     int rightMargin = targetMargin;
1029
1030     const int absoluteSourceX = source.x + scrollOffset.width();
1031     if (leftMargin > absoluteSourceX) {
1032         leftMargin = absoluteSourceX;
1033         rightMargin = max(leftMargin, minimumMargin);
1034     }
1035
1036     const int maximumRightMargin = maxSize.width - (source.width + absoluteSourceX);
1037     if (rightMargin > maximumRightMargin) {
1038         rightMargin = maximumRightMargin;
1039         leftMargin = min(leftMargin, max(rightMargin, minimumMargin));
1040     }
1041
1042     const int newWidth = source.width + leftMargin + rightMargin;
1043     const int newX = source.x - leftMargin;
1044
1045     ASSERT(newWidth >= 0);
1046     ASSERT(scrollOffset.width() + newX + newWidth <= maxSize.width);
1047
1048     return WebRect(newX, source.y, newWidth, source.height);
1049 }
1050
1051 float WebViewImpl::legibleScale() const
1052 {
1053     // Pages should be as legible as on desktop when at dpi scale, so no
1054     // need to zoom in further when automatically determining zoom level
1055     // (after double tap, find in page, etc), though the user should still
1056     // be allowed to manually pinch zoom in further if they desire.
1057     float legibleScale = 1;
1058     if (page())
1059         legibleScale *= page()->settings().accessibilityFontScaleFactor();
1060     return legibleScale;
1061 }
1062
1063 void WebViewImpl::computeScaleAndScrollForBlockRect(const WebPoint& hitPoint, const WebRect& blockRect, float padding, float defaultScaleWhenAlreadyLegible, float& scale, WebPoint& scroll)
1064 {
1065     scale = pageScaleFactor();
1066     scroll.x = scroll.y = 0;
1067
1068     WebRect rect = blockRect;
1069
1070     if (!rect.isEmpty()) {
1071         float defaultMargin = doubleTapZoomContentDefaultMargin;
1072         float minimumMargin = doubleTapZoomContentMinimumMargin;
1073         // We want the margins to have the same physical size, which means we
1074         // need to express them in post-scale size. To do that we'd need to know
1075         // the scale we're scaling to, but that depends on the margins. Instead
1076         // we express them as a fraction of the target rectangle: this will be
1077         // correct if we end up fully zooming to it, and won't matter if we
1078         // don't.
1079         rect = widenRectWithinPageBounds(rect,
1080                 static_cast<int>(defaultMargin * rect.width / m_size.width),
1081                 static_cast<int>(minimumMargin * rect.width / m_size.width));
1082         // Fit block to screen, respecting limits.
1083         scale = static_cast<float>(m_size.width) / rect.width;
1084         scale = min(scale, legibleScale());
1085         if (pageScaleFactor() < defaultScaleWhenAlreadyLegible)
1086             scale = max(scale, defaultScaleWhenAlreadyLegible);
1087         scale = clampPageScaleFactorToLimits(scale);
1088     }
1089
1090     // FIXME: If this is being called for auto zoom during find in page,
1091     // then if the user manually zooms in it'd be nice to preserve the
1092     // relative increase in zoom they caused (if they zoom out then it's ok
1093     // to zoom them back in again). This isn't compatible with our current
1094     // double-tap zoom strategy (fitting the containing block to the screen)
1095     // though.
1096
1097     float screenWidth = m_size.width / scale;
1098     float screenHeight = m_size.height / scale;
1099
1100     // Scroll to vertically align the block.
1101     if (rect.height < screenHeight) {
1102         // Vertically center short blocks.
1103         rect.y -= 0.5 * (screenHeight - rect.height);
1104     } else {
1105         // Ensure position we're zooming to (+ padding) isn't off the bottom of
1106         // the screen.
1107         rect.y = max<float>(rect.y, hitPoint.y + padding - screenHeight);
1108     } // Otherwise top align the block.
1109
1110     // Do the same thing for horizontal alignment.
1111     if (rect.width < screenWidth)
1112         rect.x -= 0.5 * (screenWidth - rect.width);
1113     else
1114         rect.x = max<float>(rect.x, hitPoint.x + padding - screenWidth);
1115     scroll.x = rect.x;
1116     scroll.y = rect.y;
1117
1118     scale = clampPageScaleFactorToLimits(scale);
1119     scroll = mainFrameImpl()->frameView()->windowToContents(scroll);
1120     scroll = clampOffsetAtScale(scroll, scale);
1121 }
1122
1123 static bool invokesHandCursor(Node* node, bool shiftKey, LocalFrame* frame)
1124 {
1125     if (!node || !node->renderer())
1126         return false;
1127
1128     ECursor cursor = node->renderer()->style()->cursor();
1129     return cursor == CURSOR_POINTER
1130         || (cursor == CURSOR_AUTO && frame->eventHandler().useHandCursor(node, node->isLink(), shiftKey));
1131 }
1132
1133 Node* WebViewImpl::bestTapNode(const PlatformGestureEvent& tapEvent)
1134 {
1135     if (!m_page || !m_page->mainFrame())
1136         return 0;
1137
1138     Node* bestTouchNode = 0;
1139
1140     IntPoint touchEventLocation(tapEvent.position());
1141     m_page->mainFrame()->eventHandler().adjustGesturePosition(tapEvent, touchEventLocation);
1142
1143     IntPoint hitTestPoint = m_page->mainFrame()->view()->windowToContents(touchEventLocation);
1144     HitTestResult result = m_page->mainFrame()->eventHandler().hitTestResultAtPoint(hitTestPoint, HitTestRequest::TouchEvent | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
1145     bestTouchNode = result.targetNode();
1146
1147     // We might hit something like an image map that has no renderer on it
1148     // Walk up the tree until we have a node with an attached renderer
1149     while (bestTouchNode && !bestTouchNode->renderer())
1150         bestTouchNode = bestTouchNode->parentNode();
1151
1152     // Check if we're in the subtree of a node with a hand cursor
1153     // this is the heuristic we use to determine if we show a highlight on tap
1154     while (bestTouchNode && !invokesHandCursor(bestTouchNode, false, m_page->mainFrame()))
1155         bestTouchNode = bestTouchNode->parentNode();
1156
1157     if (!bestTouchNode)
1158         return 0;
1159
1160     // We should pick the largest enclosing node with hand cursor set.
1161     while (bestTouchNode->parentNode() && invokesHandCursor(bestTouchNode->parentNode(), false, m_page->mainFrame()))
1162         bestTouchNode = bestTouchNode->parentNode();
1163
1164     return bestTouchNode;
1165 }
1166
1167 void WebViewImpl::enableTapHighlightAtPoint(const PlatformGestureEvent& tapEvent)
1168 {
1169     Node* touchNode = bestTapNode(tapEvent);
1170
1171     Vector<Node*> highlightNodes;
1172     highlightNodes.append(touchNode);
1173
1174     enableTapHighlights(highlightNodes);
1175 }
1176
1177 void WebViewImpl::enableTapHighlights(Vector<Node*>& highlightNodes)
1178 {
1179     if (highlightNodes.isEmpty())
1180         return;
1181
1182     // Always clear any existing highlight when this is invoked, even if we
1183     // don't get a new target to highlight.
1184     m_linkHighlights.clear();
1185
1186     // LinkHighlight reads out layout and compositing state, so we need to make sure that's all up to date.
1187     layout();
1188
1189     for (size_t i = 0; i < highlightNodes.size(); ++i) {
1190         Node* node = highlightNodes[i];
1191
1192         if (!node || !node->renderer())
1193             continue;
1194
1195         Color highlightColor = node->renderer()->style()->tapHighlightColor();
1196         // Safari documentation for -webkit-tap-highlight-color says if the specified color has 0 alpha,
1197         // then tap highlighting is disabled.
1198         // http://developer.apple.com/library/safari/#documentation/appleapplications/reference/safaricssref/articles/standardcssproperties.html
1199         if (!highlightColor.alpha())
1200             continue;
1201
1202         m_linkHighlights.append(LinkHighlight::create(node, this));
1203     }
1204 }
1205
1206 void WebViewImpl::animateDoubleTapZoom(const IntPoint& point)
1207 {
1208     if (!mainFrameImpl())
1209         return;
1210
1211     WebRect rect(point.x(), point.y(), touchPointPadding, touchPointPadding);
1212     WebRect blockBounds = computeBlockBounds(rect, false);
1213
1214     float scale;
1215     WebPoint scroll;
1216
1217     computeScaleAndScrollForBlockRect(point, blockBounds, touchPointPadding, minimumPageScaleFactor() * doubleTapZoomAlreadyLegibleRatio, scale, scroll);
1218
1219     bool stillAtPreviousDoubleTapScale = (pageScaleFactor() == m_doubleTapZoomPageScaleFactor
1220         && m_doubleTapZoomPageScaleFactor != minimumPageScaleFactor())
1221         || m_doubleTapZoomPending;
1222
1223     bool scaleUnchanged = fabs(pageScaleFactor() - scale) < minScaleDifference;
1224     bool shouldZoomOut = blockBounds.isEmpty() || scaleUnchanged || stillAtPreviousDoubleTapScale;
1225
1226     bool isAnimating;
1227
1228     if (shouldZoomOut) {
1229         scale = minimumPageScaleFactor();
1230         isAnimating = startPageScaleAnimation(mainFrameImpl()->frameView()->windowToContents(point), true, scale, doubleTapZoomAnimationDurationInSeconds);
1231     } else {
1232         isAnimating = startPageScaleAnimation(scroll, false, scale, doubleTapZoomAnimationDurationInSeconds);
1233     }
1234
1235     if (isAnimating) {
1236         m_doubleTapZoomPageScaleFactor = scale;
1237         m_doubleTapZoomPending = true;
1238     }
1239 }
1240
1241 void WebViewImpl::zoomToFindInPageRect(const WebRect& rect)
1242 {
1243     if (!mainFrameImpl())
1244         return;
1245
1246     WebRect blockBounds = computeBlockBounds(rect, true);
1247
1248     if (blockBounds.isEmpty()) {
1249         // Keep current scale (no need to scroll as x,y will normally already
1250         // be visible). FIXME: Revisit this if it isn't always true.
1251         return;
1252     }
1253
1254     float scale;
1255     WebPoint scroll;
1256
1257     computeScaleAndScrollForBlockRect(WebPoint(rect.x, rect.y), blockBounds, nonUserInitiatedPointPadding, minimumPageScaleFactor(), scale, scroll);
1258
1259     startPageScaleAnimation(scroll, false, scale, findInPageAnimationDurationInSeconds);
1260 }
1261
1262 bool WebViewImpl::zoomToMultipleTargetsRect(const WebRect& rect)
1263 {
1264     if (!mainFrameImpl())
1265         return false;
1266
1267     float scale;
1268     WebPoint scroll;
1269
1270     computeScaleAndScrollForBlockRect(WebPoint(rect.x, rect.y), rect, nonUserInitiatedPointPadding, minimumPageScaleFactor(), scale, scroll);
1271
1272     if (scale <= pageScaleFactor())
1273         return false;
1274
1275     startPageScaleAnimation(scroll, false, scale, multipleTargetsZoomAnimationDurationInSeconds);
1276     return true;
1277 }
1278
1279 void WebViewImpl::numberOfWheelEventHandlersChanged(unsigned numberOfWheelHandlers)
1280 {
1281     if (m_client)
1282         m_client->numberOfWheelEventHandlersChanged(numberOfWheelHandlers);
1283 }
1284
1285 void WebViewImpl::hasTouchEventHandlers(bool hasTouchHandlers)
1286 {
1287     if (m_client)
1288         m_client->hasTouchEventHandlers(hasTouchHandlers);
1289 }
1290
1291 bool WebViewImpl::hasTouchEventHandlersAt(const WebPoint& point)
1292 {
1293     // FIXME: Implement this. Note that the point must be divided by pageScaleFactor.
1294     return true;
1295 }
1296
1297 #if !OS(MACOSX)
1298 // Mac has no way to open a context menu based on a keyboard event.
1299 bool WebViewImpl::sendContextMenuEvent(const WebKeyboardEvent& event)
1300 {
1301     // The contextMenuController() holds onto the last context menu that was
1302     // popped up on the page until a new one is created. We need to clear
1303     // this menu before propagating the event through the DOM so that we can
1304     // detect if we create a new menu for this event, since we won't create
1305     // a new menu if the DOM swallows the event and the defaultEventHandler does
1306     // not run.
1307     page()->contextMenuController().clearContextMenu();
1308
1309     m_contextMenuAllowed = true;
1310     LocalFrame* focusedFrame = page()->focusController().focusedOrMainFrame();
1311     bool handled = focusedFrame->eventHandler().sendContextMenuEventForKey();
1312     m_contextMenuAllowed = false;
1313     return handled;
1314 }
1315 #endif
1316
1317 bool WebViewImpl::keyEventDefault(const WebKeyboardEvent& event)
1318 {
1319     LocalFrame* frame = focusedWebCoreFrame();
1320     if (!frame)
1321         return false;
1322
1323     switch (event.type) {
1324     case WebInputEvent::Char:
1325         if (event.windowsKeyCode == VKEY_SPACE) {
1326             int keyCode = ((event.modifiers & WebInputEvent::ShiftKey) ? VKEY_PRIOR : VKEY_NEXT);
1327             return scrollViewWithKeyboard(keyCode, event.modifiers);
1328         }
1329         break;
1330     case WebInputEvent::RawKeyDown:
1331         if (event.modifiers == WebInputEvent::ControlKey) {
1332             switch (event.windowsKeyCode) {
1333 #if !OS(MACOSX)
1334             case 'A':
1335                 focusedFrame()->executeCommand(WebString::fromUTF8("SelectAll"));
1336                 return true;
1337             case VKEY_INSERT:
1338             case 'C':
1339                 focusedFrame()->executeCommand(WebString::fromUTF8("Copy"));
1340                 return true;
1341 #endif
1342             // Match FF behavior in the sense that Ctrl+home/end are the only Ctrl
1343             // key combinations which affect scrolling. Safari is buggy in the
1344             // sense that it scrolls the page for all Ctrl+scrolling key
1345             // combinations. For e.g. Ctrl+pgup/pgdn/up/down, etc.
1346             case VKEY_HOME:
1347             case VKEY_END:
1348                 break;
1349             default:
1350                 return false;
1351             }
1352         }
1353         if (!event.isSystemKey && !(event.modifiers & WebInputEvent::ShiftKey))
1354             return scrollViewWithKeyboard(event.windowsKeyCode, event.modifiers);
1355         break;
1356     default:
1357         break;
1358     }
1359     return false;
1360 }
1361
1362 bool WebViewImpl::scrollViewWithKeyboard(int keyCode, int modifiers)
1363 {
1364     ScrollDirection scrollDirection;
1365     ScrollGranularity scrollGranularity;
1366 #if OS(MACOSX)
1367     // Control-Up/Down should be PageUp/Down on Mac.
1368     if (modifiers & WebMouseEvent::ControlKey) {
1369       if (keyCode == VKEY_UP)
1370         keyCode = VKEY_PRIOR;
1371       else if (keyCode == VKEY_DOWN)
1372         keyCode = VKEY_NEXT;
1373     }
1374 #endif
1375     if (!mapKeyCodeForScroll(keyCode, &scrollDirection, &scrollGranularity))
1376         return false;
1377     return bubblingScroll(scrollDirection, scrollGranularity);
1378 }
1379
1380 bool WebViewImpl::mapKeyCodeForScroll(int keyCode,
1381                                       WebCore::ScrollDirection* scrollDirection,
1382                                       WebCore::ScrollGranularity* scrollGranularity)
1383 {
1384     switch (keyCode) {
1385     case VKEY_LEFT:
1386         *scrollDirection = ScrollLeft;
1387         *scrollGranularity = ScrollByLine;
1388         break;
1389     case VKEY_RIGHT:
1390         *scrollDirection = ScrollRight;
1391         *scrollGranularity = ScrollByLine;
1392         break;
1393     case VKEY_UP:
1394         *scrollDirection = ScrollUp;
1395         *scrollGranularity = ScrollByLine;
1396         break;
1397     case VKEY_DOWN:
1398         *scrollDirection = ScrollDown;
1399         *scrollGranularity = ScrollByLine;
1400         break;
1401     case VKEY_HOME:
1402         *scrollDirection = ScrollUp;
1403         *scrollGranularity = ScrollByDocument;
1404         break;
1405     case VKEY_END:
1406         *scrollDirection = ScrollDown;
1407         *scrollGranularity = ScrollByDocument;
1408         break;
1409     case VKEY_PRIOR:  // page up
1410         *scrollDirection = ScrollUp;
1411         *scrollGranularity = ScrollByPage;
1412         break;
1413     case VKEY_NEXT:  // page down
1414         *scrollDirection = ScrollDown;
1415         *scrollGranularity = ScrollByPage;
1416         break;
1417     default:
1418         return false;
1419     }
1420
1421     return true;
1422 }
1423
1424 void WebViewImpl::hideSelectPopup()
1425 {
1426     if (m_selectPopup)
1427         m_selectPopup->hidePopup();
1428 }
1429
1430 bool WebViewImpl::bubblingScroll(ScrollDirection scrollDirection, ScrollGranularity scrollGranularity)
1431 {
1432     LocalFrame* frame = focusedWebCoreFrame();
1433     if (!frame)
1434         return false;
1435
1436     return frame->eventHandler().bubblingScroll(scrollDirection, scrollGranularity);
1437 }
1438
1439 void WebViewImpl::popupOpened(PopupContainer* popupContainer)
1440 {
1441     ASSERT(!m_selectPopup);
1442     m_selectPopup = popupContainer;
1443     ASSERT(mainFrameImpl()->frame()->document());
1444     Document& document = *mainFrameImpl()->frame()->document();
1445     WheelController::from(document)->didAddWheelEventHandler(document);
1446 }
1447
1448 void WebViewImpl::popupClosed(PopupContainer* popupContainer)
1449 {
1450     ASSERT(m_selectPopup);
1451     m_selectPopup = nullptr;
1452     ASSERT(mainFrameImpl()->frame()->document());
1453     Document& document = *mainFrameImpl()->frame()->document();
1454     WheelController::from(document)->didRemoveWheelEventHandler(document);
1455 }
1456
1457 PagePopup* WebViewImpl::openPagePopup(PagePopupClient* client, const IntRect& originBoundsInRootView)
1458 {
1459     ASSERT(client);
1460     if (hasOpenedPopup())
1461         hidePopups();
1462     ASSERT(!m_pagePopup);
1463
1464     WebWidget* popupWidget = m_client->createPopupMenu(WebPopupTypePage);
1465     ASSERT(popupWidget);
1466     m_pagePopup = toWebPagePopupImpl(popupWidget);
1467     if (!m_pagePopup->initialize(this, client, originBoundsInRootView)) {
1468         m_pagePopup->closePopup();
1469         m_pagePopup = nullptr;
1470     }
1471     return m_pagePopup.get();
1472 }
1473
1474 void WebViewImpl::closePagePopup(PagePopup* popup)
1475 {
1476     ASSERT(popup);
1477     WebPagePopupImpl* popupImpl = toWebPagePopupImpl(popup);
1478     ASSERT(m_pagePopup.get() == popupImpl);
1479     if (m_pagePopup.get() != popupImpl)
1480         return;
1481     m_pagePopup->closePopup();
1482     m_pagePopup = nullptr;
1483 }
1484
1485 LocalFrame* WebViewImpl::focusedWebCoreFrame() const
1486 {
1487     return m_page ? m_page->focusController().focusedOrMainFrame() : 0;
1488 }
1489
1490 WebViewImpl* WebViewImpl::fromPage(Page* page)
1491 {
1492     if (!page)
1493         return 0;
1494     return static_cast<WebViewImpl*>(page->chrome().client().webView());
1495 }
1496
1497 // WebWidget ------------------------------------------------------------------
1498
1499 void WebViewImpl::close()
1500 {
1501     if (m_page) {
1502         // Initiate shutdown for the entire frameset.  This will cause a lot of
1503         // notifications to be sent.
1504         if (m_page->mainFrame())
1505             m_page->mainFrame()->loader().frameDetached();
1506
1507         m_page.clear();
1508     }
1509
1510     // Should happen after m_page.clear().
1511     if (m_devToolsAgent)
1512         m_devToolsAgent.clear();
1513
1514     // Reset the delegate to prevent notifications being sent as we're being
1515     // deleted.
1516     m_client = 0;
1517
1518     deref();  // Balances ref() acquired in WebView::create
1519 }
1520
1521 void WebViewImpl::willStartLiveResize()
1522 {
1523     if (mainFrameImpl() && mainFrameImpl()->frameView())
1524         mainFrameImpl()->frameView()->willStartLiveResize();
1525
1526     LocalFrame* frame = mainFrameImpl()->frame();
1527     WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1528     if (pluginContainer)
1529         pluginContainer->willStartLiveResize();
1530 }
1531
1532 WebSize WebViewImpl::size()
1533 {
1534     return m_size;
1535 }
1536
1537 void WebViewImpl::resize(const WebSize& newSize)
1538 {
1539     if (m_shouldAutoResize || m_size == newSize)
1540         return;
1541
1542     FrameView* view = mainFrameImpl()->frameView();
1543     if (!view)
1544         return;
1545
1546     WebSize oldSize = m_size;
1547     float oldPageScaleFactor = pageScaleFactor();
1548     int oldContentsWidth = contentsSize().width();
1549
1550     m_size = newSize;
1551
1552     bool shouldAnchorAndRescaleViewport = settings()->mainFrameResizesAreOrientationChanges()
1553         && oldSize.width && oldContentsWidth && newSize.width != oldSize.width;
1554
1555     ViewportAnchor viewportAnchor(&mainFrameImpl()->frame()->eventHandler());
1556     if (shouldAnchorAndRescaleViewport) {
1557         viewportAnchor.setAnchor(view->visibleContentRect(),
1558                                  FloatSize(viewportAnchorXCoord, viewportAnchorYCoord));
1559     }
1560
1561     updatePageDefinedViewportConstraints(mainFrameImpl()->frame()->document()->viewportDescription());
1562     updateMainFrameLayoutSize();
1563
1564     WebDevToolsAgentPrivate* agentPrivate = devToolsAgentPrivate();
1565     if (agentPrivate)
1566         agentPrivate->webViewResized(newSize);
1567     WebFrameImpl* webFrame = mainFrameImpl();
1568     if (webFrame->frameView()) {
1569         webFrame->frameView()->resize(m_size);
1570         if (page()->settings().pinchVirtualViewportEnabled())
1571             page()->frameHost().pinchViewport().setSize(m_size);
1572     }
1573
1574     if (settings()->viewportEnabled() && !m_fixedLayoutSizeLock) {
1575         // Relayout immediately to recalculate the minimum scale limit.
1576         if (view->needsLayout())
1577             view->layout();
1578
1579         if (shouldAnchorAndRescaleViewport) {
1580             float viewportWidthRatio = static_cast<float>(newSize.width) / oldSize.width;
1581             float contentsWidthRatio = static_cast<float>(contentsSize().width()) / oldContentsWidth;
1582             float scaleMultiplier = viewportWidthRatio / contentsWidthRatio;
1583
1584             IntSize viewportSize = view->visibleContentRect().size();
1585             if (scaleMultiplier != 1) {
1586                 float newPageScaleFactor = oldPageScaleFactor * scaleMultiplier;
1587                 viewportSize.scale(pageScaleFactor() / newPageScaleFactor);
1588                 IntPoint scrollOffsetAtNewScale = viewportAnchor.computeOrigin(viewportSize);
1589                 setPageScaleFactor(newPageScaleFactor, scrollOffsetAtNewScale);
1590             } else {
1591                 IntPoint scrollOffsetAtNewScale = clampOffsetAtScale(viewportAnchor.computeOrigin(viewportSize), pageScaleFactor());
1592                 updateMainFrameScrollPosition(scrollOffsetAtNewScale, false);
1593             }
1594         }
1595     }
1596
1597     sendResizeEventAndRepaint();
1598 }
1599
1600 void WebViewImpl::willEndLiveResize()
1601 {
1602     if (mainFrameImpl() && mainFrameImpl()->frameView())
1603         mainFrameImpl()->frameView()->willEndLiveResize();
1604
1605     LocalFrame* frame = mainFrameImpl()->frame();
1606     WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1607     if (pluginContainer)
1608         pluginContainer->willEndLiveResize();
1609 }
1610
1611 void WebViewImpl::willEnterFullScreen()
1612 {
1613     m_fullscreenController->willEnterFullScreen();
1614 }
1615
1616 void WebViewImpl::didEnterFullScreen()
1617 {
1618     m_fullscreenController->didEnterFullScreen();
1619 }
1620
1621 void WebViewImpl::willExitFullScreen()
1622 {
1623     m_fullscreenController->willExitFullScreen();
1624 }
1625
1626 void WebViewImpl::didExitFullScreen()
1627 {
1628     m_fullscreenController->didExitFullScreen();
1629 }
1630
1631 void WebViewImpl::animate(double monotonicFrameBeginTime)
1632 {
1633     TRACE_EVENT0("webkit", "WebViewImpl::animate");
1634
1635     if (!monotonicFrameBeginTime)
1636         monotonicFrameBeginTime = monotonicallyIncreasingTime();
1637
1638     // Create synthetic wheel events as necessary for fling.
1639     if (m_gestureAnimation) {
1640         if (m_gestureAnimation->animate(monotonicFrameBeginTime))
1641             scheduleAnimation();
1642         else {
1643             endActiveFlingAnimation();
1644
1645             PlatformGestureEvent endScrollEvent(PlatformEvent::GestureScrollEnd,
1646                 m_positionOnFlingStart, m_globalPositionOnFlingStart,
1647                 IntSize(), 0, false, false, false, false,
1648                 0, 0, 0, 0);
1649
1650             mainFrameImpl()->frame()->eventHandler().handleGestureScrollEnd(endScrollEvent);
1651         }
1652     }
1653
1654     if (!m_page)
1655         return;
1656
1657     PageWidgetDelegate::animate(m_page.get(), monotonicFrameBeginTime);
1658
1659     if (m_continuousPaintingEnabled) {
1660         ContinuousPainter::setNeedsDisplayRecursive(m_rootGraphicsLayer, m_pageOverlays.get());
1661         m_client->scheduleAnimation();
1662     }
1663 }
1664
1665 void WebViewImpl::layout()
1666 {
1667     TRACE_EVENT0("webkit", "WebViewImpl::layout");
1668     PageWidgetDelegate::layout(m_page.get());
1669     updateLayerTreeBackgroundColor();
1670
1671     for (size_t i = 0; i < m_linkHighlights.size(); ++i)
1672         m_linkHighlights[i]->updateGeometry();
1673 }
1674
1675 void WebViewImpl::enterForceCompositingMode(bool enter)
1676 {
1677     if (page()->settings().forceCompositingMode() == enter)
1678         return;
1679
1680     TRACE_EVENT1("webkit", "WebViewImpl::enterForceCompositingMode", "enter", enter);
1681     settingsImpl()->setForceCompositingMode(enter);
1682     if (enter) {
1683         if (!m_page)
1684             return;
1685         LocalFrame* mainFrame = m_page->mainFrame();
1686         if (!mainFrame)
1687             return;
1688         mainFrame->view()->updateCompositingLayersAfterStyleChange();
1689     }
1690 }
1691
1692 void WebViewImpl::doPixelReadbackToCanvas(WebCanvas* canvas, const IntRect& rect)
1693 {
1694     ASSERT(m_layerTreeView);
1695
1696     SkBitmap target;
1697     target.setConfig(SkBitmap::kARGB_8888_Config, rect.width(), rect.height(), rect.width() * 4);
1698     target.allocPixels();
1699     m_layerTreeView->compositeAndReadback(target.getPixels(), rect);
1700 #if (!SK_R32_SHIFT && SK_B32_SHIFT == 16)
1701     // The compositor readback always gives back pixels in BGRA order, but for
1702     // example Android's Skia uses RGBA ordering so the red and blue channels
1703     // need to be swapped.
1704     uint8_t* pixels = reinterpret_cast<uint8_t*>(target.getPixels());
1705     for (size_t i = 0; i < target.getSize(); i += 4)
1706         std::swap(pixels[i], pixels[i + 2]);
1707 #endif
1708     canvas->writePixels(target, rect.x(), rect.y());
1709 }
1710
1711 void WebViewImpl::paint(WebCanvas* canvas, const WebRect& rect, PaintOptions option)
1712 {
1713 #if !OS(ANDROID)
1714     // ReadbackFromCompositorIfAvailable is the only option available on non-Android.
1715     // Ideally, Android would always use ReadbackFromCompositorIfAvailable as well.
1716     ASSERT(option == ReadbackFromCompositorIfAvailable);
1717 #endif
1718
1719     if (option == ReadbackFromCompositorIfAvailable && isAcceleratedCompositingActive()) {
1720         // If a canvas was passed in, we use it to grab a copy of the
1721         // freshly-rendered pixels.
1722         if (canvas) {
1723             // Clip rect to the confines of the rootLayerTexture.
1724             IntRect resizeRect(rect);
1725             resizeRect.intersect(IntRect(IntPoint(0, 0), m_layerTreeView->deviceViewportSize()));
1726             doPixelReadbackToCanvas(canvas, resizeRect);
1727         }
1728     } else {
1729         FrameView* view = page()->mainFrame()->view();
1730         PaintBehavior oldPaintBehavior = view->paintBehavior();
1731         if (isAcceleratedCompositingActive()) {
1732             ASSERT(option == ForceSoftwareRenderingAndIgnoreGPUResidentContent);
1733             view->setPaintBehavior(oldPaintBehavior | PaintBehaviorFlattenCompositingLayers);
1734         }
1735
1736         double paintStart = currentTime();
1737         PageWidgetDelegate::paint(m_page.get(), pageOverlays(), canvas, rect, isTransparent() ? PageWidgetDelegate::Translucent : PageWidgetDelegate::Opaque);
1738         double paintEnd = currentTime();
1739         double pixelsPerSec = (rect.width * rect.height) / (paintEnd - paintStart);
1740         blink::Platform::current()->histogramCustomCounts("Renderer4.SoftwarePaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30);
1741         blink::Platform::current()->histogramCustomCounts("Renderer4.SoftwarePaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30);
1742
1743         if (isAcceleratedCompositingActive()) {
1744             ASSERT(option == ForceSoftwareRenderingAndIgnoreGPUResidentContent);
1745             view->setPaintBehavior(oldPaintBehavior);
1746         }
1747     }
1748 }
1749
1750 bool WebViewImpl::isTrackingRepaints() const
1751 {
1752     if (!page())
1753         return false;
1754     FrameView* view = page()->mainFrame()->view();
1755     return view->isTrackingRepaints();
1756 }
1757
1758 void WebViewImpl::themeChanged()
1759 {
1760     if (!page())
1761         return;
1762     FrameView* view = page()->mainFrame()->view();
1763
1764     WebRect damagedRect(0, 0, m_size.width, m_size.height);
1765     view->invalidateRect(damagedRect);
1766 }
1767
1768 void WebViewImpl::enterFullScreenForElement(WebCore::Element* element)
1769 {
1770     m_fullscreenController->enterFullScreenForElement(element);
1771 }
1772
1773 void WebViewImpl::exitFullScreenForElement(WebCore::Element* element)
1774 {
1775     m_fullscreenController->exitFullScreenForElement(element);
1776 }
1777
1778 bool WebViewImpl::hasHorizontalScrollbar()
1779 {
1780     return mainFrameImpl()->frameView()->horizontalScrollbar();
1781 }
1782
1783 bool WebViewImpl::hasVerticalScrollbar()
1784 {
1785     return mainFrameImpl()->frameView()->verticalScrollbar();
1786 }
1787
1788 const WebInputEvent* WebViewImpl::m_currentInputEvent = 0;
1789
1790 bool WebViewImpl::handleInputEvent(const WebInputEvent& inputEvent)
1791 {
1792     TRACE_EVENT0("input", "WebViewImpl::handleInputEvent");
1793     // If we've started a drag and drop operation, ignore input events until
1794     // we're done.
1795     if (m_doingDragAndDrop)
1796         return true;
1797
1798     if (m_devToolsAgent && m_devToolsAgent->handleInputEvent(m_page.get(), inputEvent))
1799         return true;
1800
1801     // Report the event to be NOT processed by WebKit, so that the browser can handle it appropriately.
1802     if (m_ignoreInputEvents)
1803         return false;
1804
1805     TemporaryChange<const WebInputEvent*> currentEventChange(m_currentInputEvent, &inputEvent);
1806
1807     if (isPointerLocked() && WebInputEvent::isMouseEventType(inputEvent.type)) {
1808       pointerLockMouseEvent(inputEvent);
1809       return true;
1810     }
1811
1812     if (m_mouseCaptureNode && WebInputEvent::isMouseEventType(inputEvent.type)) {
1813         TRACE_EVENT1("input", "captured mouse event", "type", inputEvent.type);
1814         // Save m_mouseCaptureNode since mouseCaptureLost() will clear it.
1815         RefPtr<Node> node = m_mouseCaptureNode;
1816
1817         // Not all platforms call mouseCaptureLost() directly.
1818         if (inputEvent.type == WebInputEvent::MouseUp)
1819             mouseCaptureLost();
1820
1821         OwnPtr<UserGestureIndicator> gestureIndicator;
1822
1823         AtomicString eventType;
1824         switch (inputEvent.type) {
1825         case WebInputEvent::MouseMove:
1826             eventType = EventTypeNames::mousemove;
1827             break;
1828         case WebInputEvent::MouseLeave:
1829             eventType = EventTypeNames::mouseout;
1830             break;
1831         case WebInputEvent::MouseDown:
1832             eventType = EventTypeNames::mousedown;
1833             gestureIndicator = adoptPtr(new UserGestureIndicator(DefinitelyProcessingNewUserGesture));
1834             m_mouseCaptureGestureToken = gestureIndicator->currentToken();
1835             break;
1836         case WebInputEvent::MouseUp:
1837             eventType = EventTypeNames::mouseup;
1838             gestureIndicator = adoptPtr(new UserGestureIndicator(m_mouseCaptureGestureToken.release()));
1839             break;
1840         default:
1841             ASSERT_NOT_REACHED();
1842         }
1843
1844         node->dispatchMouseEvent(
1845               PlatformMouseEventBuilder(mainFrameImpl()->frameView(), *static_cast<const WebMouseEvent*>(&inputEvent)),
1846               eventType, static_cast<const WebMouseEvent*>(&inputEvent)->clickCount);
1847         return true;
1848     }
1849
1850     return PageWidgetDelegate::handleInputEvent(m_page.get(), *this, inputEvent);
1851 }
1852
1853 void WebViewImpl::setCursorVisibilityState(bool isVisible)
1854 {
1855     if (m_page)
1856         m_page->setIsCursorVisible(isVisible);
1857 }
1858
1859 void WebViewImpl::mouseCaptureLost()
1860 {
1861     TRACE_EVENT_ASYNC_END0("input", "capturing mouse", this);
1862     m_mouseCaptureNode = nullptr;
1863 }
1864
1865 void WebViewImpl::setFocus(bool enable)
1866 {
1867     m_page->focusController().setFocused(enable);
1868     if (enable) {
1869         m_page->focusController().setActive(true);
1870         RefPtr<LocalFrame> focusedFrame = m_page->focusController().focusedFrame();
1871         if (focusedFrame) {
1872             Element* element = focusedFrame->document()->focusedElement();
1873             if (element && focusedFrame->selection().selection().isNone()) {
1874                 // If the selection was cleared while the WebView was not
1875                 // focused, then the focus element shows with a focus ring but
1876                 // no caret and does respond to keyboard inputs.
1877                 if (element->isTextFormControl()) {
1878                     element->updateFocusAppearance(true);
1879                 } else if (element->isContentEditable()) {
1880                     // updateFocusAppearance() selects all the text of
1881                     // contentseditable DIVs. So we set the selection explicitly
1882                     // instead. Note that this has the side effect of moving the
1883                     // caret back to the beginning of the text.
1884                     Position position(element, 0, Position::PositionIsOffsetInAnchor);
1885                     focusedFrame->selection().setSelection(VisibleSelection(position, SEL_DEFAULT_AFFINITY));
1886                 }
1887             }
1888         }
1889         m_imeAcceptEvents = true;
1890     } else {
1891         hidePopups();
1892
1893         // Clear focus on the currently focused frame if any.
1894         if (!m_page)
1895             return;
1896
1897         LocalFrame* frame = m_page->mainFrame();
1898         if (!frame)
1899             return;
1900
1901         RefPtr<LocalFrame> focusedFrame = m_page->focusController().focusedFrame();
1902         if (focusedFrame) {
1903             // Finish an ongoing composition to delete the composition node.
1904             if (focusedFrame->inputMethodController().hasComposition()) {
1905                 if (m_autofillClient)
1906                     m_autofillClient->setIgnoreTextChanges(true);
1907
1908                 focusedFrame->inputMethodController().confirmComposition();
1909
1910                 if (m_autofillClient)
1911                     m_autofillClient->setIgnoreTextChanges(false);
1912             }
1913             m_imeAcceptEvents = false;
1914         }
1915     }
1916 }
1917
1918 bool WebViewImpl::setComposition(
1919     const WebString& text,
1920     const WebVector<WebCompositionUnderline>& underlines,
1921     int selectionStart,
1922     int selectionEnd)
1923 {
1924     LocalFrame* focused = focusedWebCoreFrame();
1925     if (!focused || !m_imeAcceptEvents)
1926         return false;
1927
1928     if (WebPlugin* plugin = focusedPluginIfInputMethodSupported(focused))
1929         return plugin->setComposition(text, underlines, selectionStart, selectionEnd);
1930
1931     // The input focus has been moved to another WebWidget object.
1932     // We should use this |editor| object only to complete the ongoing
1933     // composition.
1934     InputMethodController& inputMethodController = focused->inputMethodController();
1935     if (!focused->editor().canEdit() && !inputMethodController.hasComposition())
1936         return false;
1937
1938     // We should verify the parent node of this IME composition node are
1939     // editable because JavaScript may delete a parent node of the composition
1940     // node. In this case, WebKit crashes while deleting texts from the parent
1941     // node, which doesn't exist any longer.
1942     RefPtr<Range> range = inputMethodController.compositionRange();
1943     if (range) {
1944         Node* node = range->startContainer();
1945         if (!node || !node->isContentEditable())
1946             return false;
1947     }
1948
1949     // If we're not going to fire a keypress event, then the keydown event was
1950     // canceled.  In that case, cancel any existing composition.
1951     if (text.isEmpty() || m_suppressNextKeypressEvent) {
1952         // A browser process sent an IPC message which does not contain a valid
1953         // string, which means an ongoing composition has been canceled.
1954         // If the ongoing composition has been canceled, replace the ongoing
1955         // composition string with an empty string and complete it.
1956         String emptyString;
1957         Vector<CompositionUnderline> emptyUnderlines;
1958         inputMethodController.setComposition(emptyString, emptyUnderlines, 0, 0);
1959         return text.isEmpty();
1960     }
1961
1962     // When the range of composition underlines overlap with the range between
1963     // selectionStart and selectionEnd, WebKit somehow won't paint the selection
1964     // at all (see InlineTextBox::paint() function in InlineTextBox.cpp).
1965     // But the selection range actually takes effect.
1966     inputMethodController.setComposition(String(text),
1967                            CompositionUnderlineVectorBuilder(underlines),
1968                            selectionStart, selectionEnd);
1969
1970     return inputMethodController.hasComposition();
1971 }
1972
1973 bool WebViewImpl::confirmComposition()
1974 {
1975     return confirmComposition(DoNotKeepSelection);
1976 }
1977
1978 bool WebViewImpl::confirmComposition(ConfirmCompositionBehavior selectionBehavior)
1979 {
1980     return confirmComposition(WebString(), selectionBehavior);
1981 }
1982
1983 bool WebViewImpl::confirmComposition(const WebString& text)
1984 {
1985     return confirmComposition(text, DoNotKeepSelection);
1986 }
1987
1988 bool WebViewImpl::confirmComposition(const WebString& text, ConfirmCompositionBehavior selectionBehavior)
1989 {
1990     LocalFrame* focused = focusedWebCoreFrame();
1991     if (!focused || !m_imeAcceptEvents)
1992         return false;
1993
1994     if (WebPlugin* plugin = focusedPluginIfInputMethodSupported(focused))
1995         return plugin->confirmComposition(text, selectionBehavior);
1996
1997     return focused->inputMethodController().confirmCompositionOrInsertText(text, selectionBehavior == KeepSelection ? InputMethodController::KeepSelection : InputMethodController::DoNotKeepSelection);
1998 }
1999
2000 bool WebViewImpl::compositionRange(size_t* location, size_t* length)
2001 {
2002     LocalFrame* focused = focusedWebCoreFrame();
2003     if (!focused || !m_imeAcceptEvents)
2004         return false;
2005
2006     RefPtr<Range> range = focused->inputMethodController().compositionRange();
2007     if (!range)
2008         return false;
2009
2010     Element* editable = focused->selection().rootEditableElementOrDocumentElement();
2011     ASSERT(editable);
2012     PlainTextRange plainTextRange(PlainTextRange::create(*editable, *range.get()));
2013     if (plainTextRange.isNull())
2014         return false;
2015     *location = plainTextRange.start();
2016     *length = plainTextRange.length();
2017     return true;
2018 }
2019
2020 WebTextInputInfo WebViewImpl::textInputInfo()
2021 {
2022     WebTextInputInfo info;
2023
2024     LocalFrame* focused = focusedWebCoreFrame();
2025     if (!focused)
2026         return info;
2027
2028     FrameSelection& selection = focused->selection();
2029     Node* node = selection.selection().rootEditableElement();
2030     if (!node)
2031         return info;
2032
2033     info.inputMode = inputModeOfFocusedElement();
2034
2035     info.type = textInputType();
2036     if (info.type == WebTextInputTypeNone)
2037         return info;
2038
2039     if (!focused->editor().canEdit())
2040         return info;
2041
2042     info.value = plainText(rangeOfContents(node).get());
2043
2044     if (info.value.isEmpty())
2045         return info;
2046
2047     if (RefPtr<Range> range = selection.selection().firstRange()) {
2048         PlainTextRange plainTextRange(PlainTextRange::create(*node, *range.get()));
2049         if (plainTextRange.isNotNull()) {
2050             info.selectionStart = plainTextRange.start();
2051             info.selectionEnd = plainTextRange.end();
2052         }
2053     }
2054
2055     if (RefPtr<Range> range = focused->inputMethodController().compositionRange()) {
2056         PlainTextRange plainTextRange(PlainTextRange::create(*node, *range.get()));
2057         if (plainTextRange.isNotNull()) {
2058             info.compositionStart = plainTextRange.start();
2059             info.compositionEnd = plainTextRange.end();
2060         }
2061     }
2062
2063     return info;
2064 }
2065
2066 WebTextInputType WebViewImpl::textInputType()
2067 {
2068     Element* element = focusedElement();
2069     if (!element)
2070         return WebTextInputTypeNone;
2071
2072     if (isHTMLInputElement(*element)) {
2073         HTMLInputElement& input = toHTMLInputElement(*element);
2074
2075         if (input.isDisabledOrReadOnly())
2076             return WebTextInputTypeNone;
2077
2078         if (input.isPasswordField())
2079             return WebTextInputTypePassword;
2080         if (input.isSearchField())
2081             return WebTextInputTypeSearch;
2082         if (input.isEmailField())
2083             return WebTextInputTypeEmail;
2084         if (input.isNumberField())
2085             return WebTextInputTypeNumber;
2086         if (input.isTelephoneField())
2087             return WebTextInputTypeTelephone;
2088         if (input.isURLField())
2089             return WebTextInputTypeURL;
2090         if (input.isDateField())
2091             return WebTextInputTypeDate;
2092         if (input.isDateTimeLocalField())
2093             return WebTextInputTypeDateTimeLocal;
2094         if (input.isMonthField())
2095             return WebTextInputTypeMonth;
2096         if (input.isTimeField())
2097             return WebTextInputTypeTime;
2098         if (input.isWeekField())
2099             return WebTextInputTypeWeek;
2100         if (input.isTextField())
2101             return WebTextInputTypeText;
2102
2103         return WebTextInputTypeNone;
2104     }
2105
2106     if (isHTMLTextAreaElement(*element)) {
2107         if (toHTMLTextAreaElement(*element).isDisabledOrReadOnly())
2108             return WebTextInputTypeNone;
2109         return WebTextInputTypeTextArea;
2110     }
2111
2112 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
2113     if (element->isHTMLElement()) {
2114         if (toHTMLElement(element)->isDateTimeFieldElement())
2115             return WebTextInputTypeDateTimeField;
2116     }
2117 #endif
2118
2119     if (element->shouldUseInputMethod())
2120         return WebTextInputTypeContentEditable;
2121
2122     return WebTextInputTypeNone;
2123 }
2124
2125 WebString WebViewImpl::inputModeOfFocusedElement()
2126 {
2127     if (!RuntimeEnabledFeatures::inputModeAttributeEnabled())
2128         return WebString();
2129
2130     Element* element = focusedElement();
2131     if (!element)
2132         return WebString();
2133
2134     if (isHTMLInputElement(*element)) {
2135         const HTMLInputElement& input = toHTMLInputElement(*element);
2136         if (input.supportsInputModeAttribute())
2137             return input.fastGetAttribute(HTMLNames::inputmodeAttr).lower();
2138         return WebString();
2139     }
2140     if (isHTMLTextAreaElement(*element)) {
2141         const HTMLTextAreaElement& textarea = toHTMLTextAreaElement(*element);
2142         return textarea.fastGetAttribute(HTMLNames::inputmodeAttr).lower();
2143     }
2144
2145     return WebString();
2146 }
2147
2148 bool WebViewImpl::selectionBounds(WebRect& anchor, WebRect& focus) const
2149 {
2150     const LocalFrame* frame = focusedWebCoreFrame();
2151     if (!frame)
2152         return false;
2153     FrameSelection& selection = frame->selection();
2154
2155     if (selection.isCaret()) {
2156         anchor = focus = selection.absoluteCaretBounds();
2157     } else {
2158         RefPtr<Range> selectedRange = selection.toNormalizedRange();
2159         if (!selectedRange)
2160             return false;
2161
2162         RefPtr<Range> range(Range::create(selectedRange->startContainer()->document(),
2163             selectedRange->startContainer(),
2164             selectedRange->startOffset(),
2165             selectedRange->startContainer(),
2166             selectedRange->startOffset()));
2167         anchor = frame->editor().firstRectForRange(range.get());
2168
2169         range = Range::create(selectedRange->endContainer()->document(),
2170             selectedRange->endContainer(),
2171             selectedRange->endOffset(),
2172             selectedRange->endContainer(),
2173             selectedRange->endOffset());
2174         focus = frame->editor().firstRectForRange(range.get());
2175     }
2176
2177     IntRect scaledAnchor(frame->view()->contentsToWindow(anchor));
2178     IntRect scaledFocus(frame->view()->contentsToWindow(focus));
2179     scaledAnchor.scale(pageScaleFactor());
2180     scaledFocus.scale(pageScaleFactor());
2181     anchor = scaledAnchor;
2182     focus = scaledFocus;
2183
2184     if (!selection.selection().isBaseFirst())
2185         std::swap(anchor, focus);
2186     return true;
2187 }
2188
2189 InputMethodContext* WebViewImpl::inputMethodContext()
2190 {
2191     if (!m_imeAcceptEvents)
2192         return 0;
2193
2194     LocalFrame* focusedFrame = focusedWebCoreFrame();
2195     if (!focusedFrame)
2196         return 0;
2197
2198     Element* target = focusedFrame->document()->focusedElement();
2199     if (target && target->hasInputMethodContext())
2200         return &target->inputMethodContext();
2201
2202     return 0;
2203 }
2204
2205 WebPlugin* WebViewImpl::focusedPluginIfInputMethodSupported(LocalFrame* frame)
2206 {
2207     WebPluginContainerImpl* container = WebFrameImpl::pluginContainerFromNode(frame, WebNode(focusedElement()));
2208     if (container && container->supportsInputMethod())
2209         return container->plugin();
2210     return 0;
2211 }
2212
2213 void WebViewImpl::didShowCandidateWindow()
2214 {
2215     if (InputMethodContext* context = inputMethodContext())
2216         context->dispatchCandidateWindowShowEvent();
2217 }
2218
2219 void WebViewImpl::didUpdateCandidateWindow()
2220 {
2221     if (InputMethodContext* context = inputMethodContext())
2222         context->dispatchCandidateWindowUpdateEvent();
2223 }
2224
2225 void WebViewImpl::didHideCandidateWindow()
2226 {
2227     if (InputMethodContext* context = inputMethodContext())
2228         context->dispatchCandidateWindowHideEvent();
2229 }
2230
2231 bool WebViewImpl::selectionTextDirection(WebTextDirection& start, WebTextDirection& end) const
2232 {
2233     const LocalFrame* frame = focusedWebCoreFrame();
2234     if (!frame)
2235         return false;
2236     FrameSelection& selection = frame->selection();
2237     if (!selection.toNormalizedRange())
2238         return false;
2239     start = selection.start().primaryDirection() == RTL ? WebTextDirectionRightToLeft : WebTextDirectionLeftToRight;
2240     end = selection.end().primaryDirection() == RTL ? WebTextDirectionRightToLeft : WebTextDirectionLeftToRight;
2241     return true;
2242 }
2243
2244 bool WebViewImpl::isSelectionAnchorFirst() const
2245 {
2246     if (const LocalFrame* frame = focusedWebCoreFrame())
2247         return frame->selection().selection().isBaseFirst();
2248     return false;
2249 }
2250
2251 WebVector<WebCompositionUnderline> WebViewImpl::compositionUnderlines() const
2252 {
2253     const LocalFrame* focused = focusedWebCoreFrame();
2254     if (!focused)
2255         return WebVector<WebCompositionUnderline>();
2256     const Vector<CompositionUnderline>& underlines = focused->inputMethodController().customCompositionUnderlines();
2257     WebVector<WebCompositionUnderline> results(underlines.size());
2258     for (size_t index = 0; index < underlines.size(); ++index) {
2259         CompositionUnderline underline = underlines[index];
2260         results[index] = WebCompositionUnderline(underline.startOffset, underline.endOffset, static_cast<WebColor>(underline.color.rgb()), underline.thick);
2261     }
2262     return results;
2263 }
2264
2265 WebColor WebViewImpl::backgroundColor() const
2266 {
2267     if (isTransparent())
2268         return Color::transparent;
2269     if (!m_page)
2270         return m_baseBackgroundColor;
2271     if (!m_page->mainFrame())
2272         return m_baseBackgroundColor;
2273     FrameView* view = m_page->mainFrame()->view();
2274     return view->documentBackgroundColor().rgb();
2275 }
2276
2277 bool WebViewImpl::caretOrSelectionRange(size_t* location, size_t* length)
2278 {
2279     const LocalFrame* focused = focusedWebCoreFrame();
2280     if (!focused)
2281         return false;
2282
2283     PlainTextRange selectionOffsets = focused->inputMethodController().getSelectionOffsets();
2284     if (selectionOffsets.isNull())
2285         return false;
2286
2287     *location = selectionOffsets.start();
2288     *length = selectionOffsets.length();
2289     return true;
2290 }
2291
2292 void WebViewImpl::setTextDirection(WebTextDirection direction)
2293 {
2294     // The Editor::setBaseWritingDirection() function checks if we can change
2295     // the text direction of the selected node and updates its DOM "dir"
2296     // attribute and its CSS "direction" property.
2297     // So, we just call the function as Safari does.
2298     const LocalFrame* focused = focusedWebCoreFrame();
2299     if (!focused)
2300         return;
2301
2302     Editor& editor = focused->editor();
2303     if (!editor.canEdit())
2304         return;
2305
2306     switch (direction) {
2307     case WebTextDirectionDefault:
2308         editor.setBaseWritingDirection(NaturalWritingDirection);
2309         break;
2310
2311     case WebTextDirectionLeftToRight:
2312         editor.setBaseWritingDirection(LeftToRightWritingDirection);
2313         break;
2314
2315     case WebTextDirectionRightToLeft:
2316         editor.setBaseWritingDirection(RightToLeftWritingDirection);
2317         break;
2318
2319     default:
2320         notImplemented();
2321         break;
2322     }
2323 }
2324
2325 bool WebViewImpl::isAcceleratedCompositingActive() const
2326 {
2327     return m_isAcceleratedCompositingActive;
2328 }
2329
2330 void WebViewImpl::willCloseLayerTreeView()
2331 {
2332     setIsAcceleratedCompositingActive(false);
2333     m_layerTreeView = 0;
2334 }
2335
2336 void WebViewImpl::didAcquirePointerLock()
2337 {
2338     if (page())
2339         page()->pointerLockController().didAcquirePointerLock();
2340 }
2341
2342 void WebViewImpl::didNotAcquirePointerLock()
2343 {
2344     if (page())
2345         page()->pointerLockController().didNotAcquirePointerLock();
2346 }
2347
2348 void WebViewImpl::didLosePointerLock()
2349 {
2350     if (page())
2351         page()->pointerLockController().didLosePointerLock();
2352 }
2353
2354 void WebViewImpl::didChangeWindowResizerRect()
2355 {
2356     if (mainFrameImpl()->frameView())
2357         mainFrameImpl()->frameView()->windowResizerRectChanged();
2358 }
2359
2360 // WebView --------------------------------------------------------------------
2361
2362 WebSettingsImpl* WebViewImpl::settingsImpl()
2363 {
2364     if (!m_webSettings)
2365         m_webSettings = adoptPtr(new WebSettingsImpl(&m_page->settings(), &m_page->inspectorController()));
2366     ASSERT(m_webSettings);
2367     return m_webSettings.get();
2368 }
2369
2370 WebSettings* WebViewImpl::settings()
2371 {
2372     return settingsImpl();
2373 }
2374
2375 WebString WebViewImpl::pageEncoding() const
2376 {
2377     if (!m_page)
2378         return WebString();
2379
2380     // FIXME: Is this check needed?
2381     if (!m_page->mainFrame()->document()->loader())
2382         return WebString();
2383
2384     return m_page->mainFrame()->document()->encodingName();
2385 }
2386
2387 void WebViewImpl::setPageEncoding(const WebString& encodingName)
2388 {
2389     if (!m_page)
2390         return;
2391
2392     // Only change override encoding, don't change default encoding.
2393     // Note that the new encoding must be 0 if it isn't supposed to be set.
2394     AtomicString newEncodingName;
2395     if (!encodingName.isEmpty())
2396         newEncodingName = encodingName;
2397     m_page->mainFrame()->loader().reload(NormalReload, KURL(), newEncodingName);
2398 }
2399
2400 bool WebViewImpl::dispatchBeforeUnloadEvent()
2401 {
2402     // FIXME: This should really cause a recursive depth-first walk of all
2403     // frames in the tree, calling each frame's onbeforeunload.  At the moment,
2404     // we're consistent with Safari 3.1, not IE/FF.
2405     LocalFrame* frame = m_page->mainFrame();
2406     if (!frame)
2407         return true;
2408
2409     return frame->loader().shouldClose();
2410 }
2411
2412 void WebViewImpl::dispatchUnloadEvent()
2413 {
2414     // Run unload handlers.
2415     m_page->mainFrame()->loader().closeURL();
2416 }
2417
2418 WebFrame* WebViewImpl::mainFrame()
2419 {
2420     return mainFrameImpl();
2421 }
2422
2423 WebFrame* WebViewImpl::findFrameByName(
2424     const WebString& name, WebFrame* relativeToFrame)
2425 {
2426     if (!relativeToFrame)
2427         relativeToFrame = mainFrame();
2428     LocalFrame* frame = toWebFrameImpl(relativeToFrame)->frame();
2429     frame = frame->tree().find(name);
2430     return WebFrameImpl::fromFrame(frame);
2431 }
2432
2433 WebFrame* WebViewImpl::focusedFrame()
2434 {
2435     return WebFrameImpl::fromFrame(focusedWebCoreFrame());
2436 }
2437
2438 void WebViewImpl::setFocusedFrame(WebFrame* frame)
2439 {
2440     if (!frame) {
2441         // Clears the focused frame if any.
2442         if (LocalFrame* focusedFrame = focusedWebCoreFrame())
2443             focusedFrame->selection().setFocused(false);
2444         return;
2445     }
2446     LocalFrame* webcoreFrame = toWebFrameImpl(frame)->frame();
2447     webcoreFrame->page()->focusController().setFocusedFrame(webcoreFrame);
2448 }
2449
2450 void WebViewImpl::setInitialFocus(bool reverse)
2451 {
2452     if (!m_page)
2453         return;
2454     LocalFrame* frame = page()->focusController().focusedOrMainFrame();
2455     if (Document* document = frame->document())
2456         document->setFocusedElement(nullptr);
2457     page()->focusController().setInitialFocus(reverse ? FocusTypeBackward : FocusTypeForward);
2458 }
2459
2460 void WebViewImpl::clearFocusedElement()
2461 {
2462     RefPtr<LocalFrame> frame = focusedWebCoreFrame();
2463     if (!frame)
2464         return;
2465
2466     RefPtr<Document> document = frame->document();
2467     if (!document)
2468         return;
2469
2470     RefPtr<Element> oldFocusedElement = document->focusedElement();
2471
2472     // Clear the focused node.
2473     document->setFocusedElement(nullptr);
2474
2475     if (!oldFocusedElement)
2476         return;
2477
2478     // If a text field has focus, we need to make sure the selection controller
2479     // knows to remove selection from it. Otherwise, the text field is still
2480     // processing keyboard events even though focus has been moved to the page and
2481     // keystrokes get eaten as a result.
2482     if (oldFocusedElement->isContentEditable() || oldFocusedElement->isTextFormControl())
2483         frame->selection().clear();
2484 }
2485
2486 void WebViewImpl::scrollFocusedNodeIntoView()
2487 {
2488     if (Element* element = focusedElement())
2489         element->scrollIntoViewIfNeeded(true);
2490 }
2491
2492 void WebViewImpl::scrollFocusedNodeIntoRect(const WebRect& rect)
2493 {
2494     LocalFrame* frame = page()->mainFrame();
2495     Element* element = focusedElement();
2496     if (!frame || !frame->view() || !element)
2497         return;
2498
2499     if (!m_webSettings->autoZoomFocusedNodeToLegibleScale()) {
2500         frame->view()->scrollElementToRect(element, IntRect(rect.x, rect.y, rect.width, rect.height));
2501         return;
2502     }
2503
2504     float scale;
2505     IntPoint scroll;
2506     bool needAnimation;
2507     computeScaleAndScrollForFocusedNode(element, scale, scroll, needAnimation);
2508     if (needAnimation)
2509         startPageScaleAnimation(scroll, false, scale, scrollAndScaleAnimationDurationInSeconds);
2510 }
2511
2512 void WebViewImpl::computeScaleAndScrollForFocusedNode(Node* focusedNode, float& newScale, IntPoint& newScroll, bool& needAnimation)
2513 {
2514     focusedNode->document().updateLayoutIgnorePendingStylesheets();
2515
2516     // 'caret' is rect encompassing the blinking cursor.
2517     IntRect textboxRect = focusedNode->document().view()->contentsToWindow(pixelSnappedIntRect(focusedNode->Node::boundingBox()));
2518     WebRect caret, unusedEnd;
2519     selectionBounds(caret, unusedEnd);
2520     IntRect unscaledCaret = caret;
2521     unscaledCaret.scale(1 / pageScaleFactor());
2522     caret = unscaledCaret;
2523
2524     // Pick a scale which is reasonably readable. This is the scale at which
2525     // the caret height will become minReadableCaretHeight (adjusted for dpi
2526     // and font scale factor).
2527     newScale = clampPageScaleFactorToLimits(legibleScale() * minReadableCaretHeight / caret.height);
2528     const float deltaScale = newScale / pageScaleFactor();
2529
2530     // Convert the rects to absolute space in the new scale.
2531     IntRect textboxRectInDocumentCoordinates = textboxRect;
2532     textboxRectInDocumentCoordinates.move(mainFrame()->scrollOffset());
2533     IntRect caretInDocumentCoordinates = caret;
2534     caretInDocumentCoordinates.move(mainFrame()->scrollOffset());
2535
2536     int viewWidth = m_size.width / newScale;
2537     int viewHeight = m_size.height / newScale;
2538
2539     if (textboxRectInDocumentCoordinates.width() <= viewWidth) {
2540         // Field is narrower than screen. Try to leave padding on left so field's
2541         // label is visible, but it's more important to ensure entire field is
2542         // onscreen.
2543         int idealLeftPadding = viewWidth * leftBoxRatio;
2544         int maxLeftPaddingKeepingBoxOnscreen = viewWidth - textboxRectInDocumentCoordinates.width();
2545         newScroll.setX(textboxRectInDocumentCoordinates.x() - min<int>(idealLeftPadding, maxLeftPaddingKeepingBoxOnscreen));
2546     } else {
2547         // Field is wider than screen. Try to left-align field, unless caret would
2548         // be offscreen, in which case right-align the caret.
2549         newScroll.setX(max<int>(textboxRectInDocumentCoordinates.x(), caretInDocumentCoordinates.x() + caretInDocumentCoordinates.width() + caretPadding - viewWidth));
2550     }
2551     if (textboxRectInDocumentCoordinates.height() <= viewHeight) {
2552         // Field is shorter than screen. Vertically center it.
2553         newScroll.setY(textboxRectInDocumentCoordinates.y() - (viewHeight - textboxRectInDocumentCoordinates.height()) / 2);
2554     } else {
2555         // Field is taller than screen. Try to top align field, unless caret would
2556         // be offscreen, in which case bottom-align the caret.
2557         newScroll.setY(max<int>(textboxRectInDocumentCoordinates.y(), caretInDocumentCoordinates.y() + caretInDocumentCoordinates.height() + caretPadding - viewHeight));
2558     }
2559
2560     needAnimation = false;
2561     // If we are at less than the target zoom level, zoom in.
2562     if (deltaScale > minScaleChangeToTriggerZoom)
2563         needAnimation = true;
2564     // If the caret is offscreen, then animate.
2565     IntRect sizeRect(0, 0, viewWidth, viewHeight);
2566     if (!sizeRect.contains(caret))
2567         needAnimation = true;
2568     // If the box is partially offscreen and it's possible to bring it fully
2569     // onscreen, then animate.
2570     if (sizeRect.contains(textboxRectInDocumentCoordinates.width(), textboxRectInDocumentCoordinates.height()) && !sizeRect.contains(textboxRect))
2571         needAnimation = true;
2572 }
2573
2574 void WebViewImpl::advanceFocus(bool reverse)
2575 {
2576     page()->focusController().advanceFocus(reverse ? FocusTypeBackward : FocusTypeForward);
2577 }
2578
2579 double WebViewImpl::zoomLevel()
2580 {
2581     return m_zoomLevel;
2582 }
2583
2584 double WebViewImpl::setZoomLevel(double zoomLevel)
2585 {
2586     if (zoomLevel < m_minimumZoomLevel)
2587         m_zoomLevel = m_minimumZoomLevel;
2588     else if (zoomLevel > m_maximumZoomLevel)
2589         m_zoomLevel = m_maximumZoomLevel;
2590     else
2591         m_zoomLevel = zoomLevel;
2592
2593     LocalFrame* frame = mainFrameImpl()->frame();
2594     WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
2595     if (pluginContainer)
2596         pluginContainer->plugin()->setZoomLevel(m_zoomLevel, false);
2597     else {
2598         float zoomFactor = m_zoomFactorOverride ? m_zoomFactorOverride : static_cast<float>(zoomLevelToZoomFactor(m_zoomLevel));
2599         frame->setPageZoomFactor(zoomFactor);
2600     }
2601
2602     return m_zoomLevel;
2603 }
2604
2605 void WebViewImpl::zoomLimitsChanged(double minimumZoomLevel,
2606                                     double maximumZoomLevel)
2607 {
2608     m_minimumZoomLevel = minimumZoomLevel;
2609     m_maximumZoomLevel = maximumZoomLevel;
2610     m_client->zoomLimitsChanged(m_minimumZoomLevel, m_maximumZoomLevel);
2611 }
2612
2613 float WebViewImpl::textZoomFactor()
2614 {
2615     return mainFrameImpl()->frame()->textZoomFactor();
2616 }
2617
2618 float WebViewImpl::setTextZoomFactor(float textZoomFactor)
2619 {
2620     LocalFrame* frame = mainFrameImpl()->frame();
2621     if (WebFrameImpl::pluginContainerFromFrame(frame))
2622         return 1;
2623
2624     frame->setTextZoomFactor(textZoomFactor);
2625
2626     return textZoomFactor;
2627 }
2628
2629 void WebViewImpl::fullFramePluginZoomLevelChanged(double zoomLevel)
2630 {
2631     if (zoomLevel == m_zoomLevel)
2632         return;
2633
2634     m_zoomLevel = max(min(zoomLevel, m_maximumZoomLevel), m_minimumZoomLevel);
2635     m_client->zoomLevelChanged();
2636 }
2637
2638 double WebView::zoomLevelToZoomFactor(double zoomLevel)
2639 {
2640     return pow(textSizeMultiplierRatio, zoomLevel);
2641 }
2642
2643 double WebView::zoomFactorToZoomLevel(double factor)
2644 {
2645     // Since factor = 1.2^level, level = log(factor) / log(1.2)
2646     return log(factor) / log(textSizeMultiplierRatio);
2647 }
2648
2649 float WebViewImpl::pageScaleFactor() const
2650 {
2651     if (!page())
2652         return 1;
2653
2654     return page()->pageScaleFactor();
2655 }
2656
2657 float WebViewImpl::clampPageScaleFactorToLimits(float scaleFactor) const
2658 {
2659     return m_pageScaleConstraintsSet.finalConstraints().clampToConstraints(scaleFactor);
2660 }
2661
2662 IntPoint WebViewImpl::clampOffsetAtScale(const IntPoint& offset, float scale)
2663 {
2664     FrameView* view = mainFrameImpl()->frameView();
2665     if (!view)
2666         return offset;
2667
2668     return view->clampOffsetAtScale(offset, scale);
2669 }
2670
2671 void WebViewImpl::setPageScaleFactor(float scaleFactor, const WebPoint& origin)
2672 {
2673     if (!page())
2674         return;
2675
2676     IntPoint newScrollOffset = origin;
2677     scaleFactor = clampPageScaleFactorToLimits(scaleFactor);
2678     newScrollOffset = clampOffsetAtScale(newScrollOffset, scaleFactor);
2679
2680     page()->setPageScaleFactor(scaleFactor, newScrollOffset);
2681 }
2682
2683 void WebViewImpl::setPageScaleFactorPreservingScrollOffset(float scaleFactor)
2684 {
2685     if (clampPageScaleFactorToLimits(scaleFactor) == pageScaleFactor())
2686         return;
2687
2688     IntPoint scrollOffset(mainFrame()->scrollOffset().width, mainFrame()->scrollOffset().height);
2689     setPageScaleFactor(scaleFactor, scrollOffset);
2690 }
2691
2692 float WebViewImpl::deviceScaleFactor() const
2693 {
2694     if (!page())
2695         return 1;
2696
2697     return page()->deviceScaleFactor();
2698 }
2699
2700 void WebViewImpl::setDeviceScaleFactor(float scaleFactor)
2701 {
2702     if (!page())
2703         return;
2704
2705     page()->setDeviceScaleFactor(scaleFactor);
2706
2707     if (m_layerTreeView)
2708         updateLayerTreeDeviceScaleFactor();
2709 }
2710
2711 void WebViewImpl::enableAutoResizeMode(const WebSize& minSize, const WebSize& maxSize)
2712 {
2713     m_shouldAutoResize = true;
2714     m_minAutoSize = minSize;
2715     m_maxAutoSize = maxSize;
2716     configureAutoResizeMode();
2717 }
2718
2719 void WebViewImpl::disableAutoResizeMode()
2720 {
2721     m_shouldAutoResize = false;
2722     configureAutoResizeMode();
2723 }
2724
2725 void WebViewImpl::setUserAgentPageScaleConstraints(PageScaleConstraints newConstraints)
2726 {
2727     if (newConstraints == m_pageScaleConstraintsSet.userAgentConstraints())
2728         return;
2729
2730     m_pageScaleConstraintsSet.setUserAgentConstraints(newConstraints);
2731
2732     if (!mainFrameImpl() || !mainFrameImpl()->frameView())
2733         return;
2734
2735     mainFrameImpl()->frameView()->setNeedsLayout();
2736 }
2737
2738 void WebViewImpl::setInitialPageScaleOverride(float initialPageScaleFactorOverride)
2739 {
2740     PageScaleConstraints constraints = m_pageScaleConstraintsSet.userAgentConstraints();
2741     constraints.initialScale = initialPageScaleFactorOverride;
2742
2743     if (constraints == m_pageScaleConstraintsSet.userAgentConstraints())
2744         return;
2745
2746     m_pageScaleConstraintsSet.setNeedsReset(true);
2747     setUserAgentPageScaleConstraints(constraints);
2748 }
2749
2750 void WebViewImpl::setPageScaleFactorLimits(float minPageScale, float maxPageScale)
2751 {
2752     PageScaleConstraints constraints = m_pageScaleConstraintsSet.userAgentConstraints();
2753     constraints.minimumScale = minPageScale;
2754     constraints.maximumScale = maxPageScale;
2755     setUserAgentPageScaleConstraints(constraints);
2756 }
2757
2758 void WebViewImpl::setIgnoreViewportTagScaleLimits(bool ignore)
2759 {
2760     PageScaleConstraints constraints = m_pageScaleConstraintsSet.userAgentConstraints();
2761     if (ignore) {
2762         constraints.minimumScale = m_pageScaleConstraintsSet.defaultConstraints().minimumScale;
2763         constraints.maximumScale = m_pageScaleConstraintsSet.defaultConstraints().maximumScale;
2764     } else {
2765         constraints.minimumScale = -1;
2766         constraints.maximumScale = -1;
2767     }
2768     setUserAgentPageScaleConstraints(constraints);
2769 }
2770
2771 void WebViewImpl::refreshPageScaleFactorAfterLayout()
2772 {
2773     if (!mainFrame() || !page() || !page()->mainFrame() || !page()->mainFrame()->view())
2774         return;
2775     FrameView* view = page()->mainFrame()->view();
2776
2777     updatePageDefinedViewportConstraints(mainFrameImpl()->frame()->document()->viewportDescription());
2778     m_pageScaleConstraintsSet.computeFinalConstraints();
2779
2780     if (settings()->viewportEnabled() && !m_fixedLayoutSizeLock) {
2781         int verticalScrollbarWidth = 0;
2782         if (view->verticalScrollbar() && !view->verticalScrollbar()->isOverlayScrollbar())
2783             verticalScrollbarWidth = view->verticalScrollbar()->width();
2784         m_pageScaleConstraintsSet.adjustFinalConstraintsToContentsSize(m_size, contentsSize(), verticalScrollbarWidth);
2785     }
2786
2787     float newPageScaleFactor = pageScaleFactor();
2788     if (m_pageScaleConstraintsSet.needsReset() && m_pageScaleConstraintsSet.finalConstraints().initialScale != -1) {
2789         newPageScaleFactor = m_pageScaleConstraintsSet.finalConstraints().initialScale;
2790         m_pageScaleConstraintsSet.setNeedsReset(false);
2791     }
2792     setPageScaleFactorPreservingScrollOffset(newPageScaleFactor);
2793
2794     updateLayerTreeViewport();
2795
2796     // Relayout immediately to avoid violating the rule that needsLayout()
2797     // isn't set at the end of a layout.
2798     if (view->needsLayout())
2799         view->layout();
2800 }
2801
2802 void WebViewImpl::updatePageDefinedViewportConstraints(const ViewportDescription& description)
2803 {
2804     if (!settings()->viewportEnabled() || !page() || (!m_size.width && !m_size.height))
2805         return;
2806
2807     ViewportDescription adjustedDescription = description;
2808     if (settingsImpl()->viewportMetaLayoutSizeQuirk() && adjustedDescription.type == ViewportDescription::ViewportMeta) {
2809         if (adjustedDescription.maxWidth.type() == ExtendToZoom)
2810             adjustedDescription.maxWidth = Length(); // auto
2811         const int legacyWidthSnappingMagicNumber = 320;
2812         if (adjustedDescription.maxWidth.isFixed() && adjustedDescription.maxWidth.value() <= legacyWidthSnappingMagicNumber)
2813             adjustedDescription.maxWidth = Length(DeviceWidth);
2814         if (adjustedDescription.maxHeight.isFixed() && adjustedDescription.maxHeight.value() <= m_size.height)
2815             adjustedDescription.maxHeight = Length(DeviceHeight);
2816         adjustedDescription.minWidth = adjustedDescription.maxWidth;
2817         adjustedDescription.minHeight = adjustedDescription.maxHeight;
2818     }
2819     float oldInitialScale = m_pageScaleConstraintsSet.pageDefinedConstraints().initialScale;
2820     m_pageScaleConstraintsSet.updatePageDefinedConstraints(adjustedDescription, m_size);
2821
2822     if (settingsImpl()->clobberUserAgentInitialScaleQuirk()
2823         && m_pageScaleConstraintsSet.userAgentConstraints().initialScale != -1
2824         && m_pageScaleConstraintsSet.userAgentConstraints().initialScale * deviceScaleFactor() <= 1) {
2825         if (description.maxWidth == Length(DeviceWidth)
2826             || (description.maxWidth.type() == ExtendToZoom && m_pageScaleConstraintsSet.pageDefinedConstraints().initialScale == 1.0f))
2827             setInitialPageScaleOverride(-1);
2828     }
2829     m_pageScaleConstraintsSet.adjustForAndroidWebViewQuirks(adjustedDescription, m_size, page()->settings().layoutFallbackWidth(), deviceScaleFactor(), settingsImpl()->supportDeprecatedTargetDensityDPI(), page()->settings().wideViewportQuirkEnabled(), page()->settings().useWideViewport(), page()->settings().loadWithOverviewMode(), settingsImpl()->viewportMetaNonUserScalableQuirk());
2830     float newInitialScale = m_pageScaleConstraintsSet.pageDefinedConstraints().initialScale;
2831     if (oldInitialScale != newInitialScale && newInitialScale != -1) {
2832         m_pageScaleConstraintsSet.setNeedsReset(true);
2833         if (mainFrameImpl() && mainFrameImpl()->frameView())
2834             mainFrameImpl()->frameView()->setNeedsLayout();
2835     }
2836
2837     updateMainFrameLayoutSize();
2838 }
2839
2840 void WebViewImpl::updateMainFrameLayoutSize()
2841 {
2842     if (m_fixedLayoutSizeLock || !mainFrameImpl())
2843         return;
2844
2845     RefPtr<FrameView> view = mainFrameImpl()->frameView();
2846     if (!view)
2847         return;
2848
2849     WebSize layoutSize = m_size;
2850
2851     if (settings()->viewportEnabled()) {
2852         layoutSize = flooredIntSize(m_pageScaleConstraintsSet.pageDefinedConstraints().layoutSize);
2853
2854         bool textAutosizingEnabled = page()->settings().textAutosizingEnabled();
2855         if (textAutosizingEnabled && layoutSize.width != view->layoutSize().width()) {
2856             TextAutosizer* textAutosizer = page()->mainFrame()->document()->textAutosizer();
2857             if (textAutosizer)
2858                 textAutosizer->recalculateMultipliers();
2859         }
2860     }
2861
2862     view->setLayoutSize(layoutSize);
2863 }
2864
2865 IntSize WebViewImpl::contentsSize() const
2866 {
2867     RenderView* root = page()->mainFrame()->contentRenderer();
2868     if (!root)
2869         return IntSize();
2870     return root->documentRect().size();
2871 }
2872
2873 WebSize WebViewImpl::contentsPreferredMinimumSize()
2874 {
2875     Document* document = m_page->mainFrame()->document();
2876     if (!document || !document->renderView() || !document->documentElement())
2877         return WebSize();
2878
2879     layout();
2880     FontCachePurgePreventer fontCachePurgePreventer; // Required by minPreferredLogicalWidth().
2881     IntSize preferredMinimumSize(document->renderView()->minPreferredLogicalWidth(), document->documentElement()->scrollHeight());
2882     preferredMinimumSize.scale(zoomLevelToZoomFactor(zoomLevel()));
2883     return preferredMinimumSize;
2884 }
2885
2886 float WebViewImpl::minimumPageScaleFactor() const
2887 {
2888     return m_pageScaleConstraintsSet.finalConstraints().minimumScale;
2889 }
2890
2891 float WebViewImpl::maximumPageScaleFactor() const
2892 {
2893     return m_pageScaleConstraintsSet.finalConstraints().maximumScale;
2894 }
2895
2896 void WebViewImpl::saveScrollAndScaleState()
2897 {
2898     m_savedPageScaleFactor = pageScaleFactor();
2899     m_savedScrollOffset = mainFrame()->scrollOffset();
2900 }
2901
2902 void WebViewImpl::restoreScrollAndScaleState()
2903 {
2904     if (!m_savedPageScaleFactor)
2905         return;
2906
2907     startPageScaleAnimation(IntPoint(m_savedScrollOffset), false, m_savedPageScaleFactor, scrollAndScaleAnimationDurationInSeconds);
2908     resetSavedScrollAndScaleState();
2909 }
2910
2911 void WebViewImpl::resetSavedScrollAndScaleState()
2912 {
2913     m_savedPageScaleFactor = 0;
2914     m_savedScrollOffset = IntSize();
2915 }
2916
2917 void WebViewImpl::resetScrollAndScaleState()
2918 {
2919     page()->setPageScaleFactor(1, IntPoint());
2920
2921     // Clear out the values for the current history item. This will prevent the history item from clobbering the
2922     // value determined during page scale initialization, which may be less than 1.
2923     page()->mainFrame()->loader().clearScrollPositionAndViewState();
2924     m_pageScaleConstraintsSet.setNeedsReset(true);
2925
2926     // Clobber saved scales and scroll offsets.
2927     if (FrameView* view = page()->mainFrame()->document()->view())
2928         view->cacheCurrentScrollPosition();
2929     resetSavedScrollAndScaleState();
2930 }
2931
2932 void WebViewImpl::setFixedLayoutSize(const WebSize& layoutSize)
2933 {
2934     if (!page())
2935         return;
2936
2937     LocalFrame* frame = page()->mainFrame();
2938     if (!frame)
2939         return;
2940
2941     RefPtr<FrameView> view = frame->view();
2942     if (!view)
2943         return;
2944
2945     m_fixedLayoutSizeLock = layoutSize.width || layoutSize.height;
2946
2947     if (m_fixedLayoutSizeLock)
2948         view->setLayoutSize(layoutSize);
2949     else
2950         updateMainFrameLayoutSize();
2951 }
2952
2953 void WebViewImpl::performMediaPlayerAction(const WebMediaPlayerAction& action,
2954                                            const WebPoint& location)
2955 {
2956     HitTestResult result = hitTestResultForWindowPos(location);
2957     RefPtr<Node> node = result.innerNonSharedNode();
2958     if (!isHTMLVideoElement(*node) && !isHTMLAudioElement(*node))
2959         return;
2960
2961     RefPtr<HTMLMediaElement> mediaElement =
2962         static_pointer_cast<HTMLMediaElement>(node);
2963     switch (action.type) {
2964     case WebMediaPlayerAction::Play:
2965         if (action.enable)
2966             mediaElement->play();
2967         else
2968             mediaElement->pause();
2969         break;
2970     case WebMediaPlayerAction::Mute:
2971         mediaElement->setMuted(action.enable);
2972         break;
2973     case WebMediaPlayerAction::Loop:
2974         mediaElement->setLoop(action.enable);
2975         break;
2976     case WebMediaPlayerAction::Controls:
2977         mediaElement->setControls(action.enable);
2978         break;
2979     default:
2980         ASSERT_NOT_REACHED();
2981     }
2982 }
2983
2984 void WebViewImpl::performPluginAction(const WebPluginAction& action,
2985                                       const WebPoint& location)
2986 {
2987     HitTestResult result = hitTestResultForWindowPos(location);
2988     RefPtr<Node> node = result.innerNonSharedNode();
2989     if (!isHTMLObjectElement(*node) && !isHTMLEmbedElement(*node))
2990         return;
2991
2992     RenderObject* object = node->renderer();
2993     if (object && object->isWidget()) {
2994         Widget* widget = toRenderWidget(object)->widget();
2995         if (widget && widget->isPluginContainer()) {
2996             WebPluginContainerImpl* plugin = toWebPluginContainerImpl(widget);
2997             switch (action.type) {
2998             case WebPluginAction::Rotate90Clockwise:
2999                 plugin->plugin()->rotateView(WebPlugin::RotationType90Clockwise);
3000                 break;
3001             case WebPluginAction::Rotate90Counterclockwise:
3002                 plugin->plugin()->rotateView(WebPlugin::RotationType90Counterclockwise);
3003                 break;
3004             default:
3005                 ASSERT_NOT_REACHED();
3006             }
3007         }
3008     }
3009 }
3010
3011 WebHitTestResult WebViewImpl::hitTestResultAt(const WebPoint& point)
3012 {
3013     IntPoint scaledPoint = point;
3014     scaledPoint.scale(1 / pageScaleFactor(), 1 / pageScaleFactor());
3015     return hitTestResultForWindowPos(scaledPoint);
3016 }
3017
3018 void WebViewImpl::copyImageAt(const WebPoint& point)
3019 {
3020     if (!m_page)
3021         return;
3022
3023     HitTestResult result = hitTestResultForWindowPos(point);
3024
3025     if (result.absoluteImageURL().isEmpty()) {
3026         // There isn't actually an image at these coordinates.  Might be because
3027         // the window scrolled while the context menu was open or because the page
3028         // changed itself between when we thought there was an image here and when
3029         // we actually tried to retreive the image.
3030         //
3031         // FIXME: implement a cache of the most recent HitTestResult to avoid having
3032         //        to do two hit tests.
3033         return;
3034     }
3035
3036     m_page->mainFrame()->editor().copyImage(result);
3037 }
3038
3039 void WebViewImpl::dragSourceEndedAt(
3040     const WebPoint& clientPoint,
3041     const WebPoint& screenPoint,
3042     WebDragOperation operation)
3043 {
3044     PlatformMouseEvent pme(clientPoint,
3045                            screenPoint,
3046                            LeftButton, PlatformEvent::MouseMoved, 0, false, false, false,
3047                            false, 0);
3048     m_page->mainFrame()->eventHandler().dragSourceEndedAt(pme,
3049         static_cast<DragOperation>(operation));
3050 }
3051
3052 void WebViewImpl::dragSourceMovedTo(
3053     const WebPoint& clientPoint,
3054     const WebPoint& screenPoint,
3055     WebDragOperation operation)
3056 {
3057 }
3058
3059 void WebViewImpl::dragSourceSystemDragEnded()
3060 {
3061     // It's possible for us to get this callback while not doing a drag if
3062     // it's from a previous page that got unloaded.
3063     if (m_doingDragAndDrop) {
3064         m_page->dragController().dragEnded();
3065         m_doingDragAndDrop = false;
3066     }
3067 }
3068
3069 WebDragOperation WebViewImpl::dragTargetDragEnter(
3070     const WebDragData& webDragData,
3071     const WebPoint& clientPoint,
3072     const WebPoint& screenPoint,
3073     WebDragOperationsMask operationsAllowed,
3074     int keyModifiers)
3075 {
3076     ASSERT(!m_currentDragData);
3077
3078     m_currentDragData = webDragData.getValue();
3079     m_operationsAllowed = operationsAllowed;
3080
3081     return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragEnter, keyModifiers);
3082 }
3083
3084 WebDragOperation WebViewImpl::dragTargetDragOver(
3085     const WebPoint& clientPoint,
3086     const WebPoint& screenPoint,
3087     WebDragOperationsMask operationsAllowed,
3088     int keyModifiers)
3089 {
3090     m_operationsAllowed = operationsAllowed;
3091
3092     return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragOver, keyModifiers);
3093 }
3094
3095 void WebViewImpl::dragTargetDragLeave()
3096 {
3097     ASSERT(m_currentDragData);
3098
3099     DragData dragData(
3100         m_currentDragData.get(),
3101         IntPoint(),
3102         IntPoint(),
3103         static_cast<DragOperation>(m_operationsAllowed));
3104
3105     m_page->dragController().dragExited(&dragData);
3106
3107     // FIXME: why is the drag scroll timer not stopped here?
3108
3109     m_dragOperation = WebDragOperationNone;
3110     m_currentDragData = nullptr;
3111 }
3112
3113 void WebViewImpl::dragTargetDrop(const WebPoint& clientPoint,
3114                                  const WebPoint& screenPoint,
3115                                  int keyModifiers)
3116 {
3117     ASSERT(m_currentDragData);
3118
3119     // If this webview transitions from the "drop accepting" state to the "not
3120     // accepting" state, then our IPC message reply indicating that may be in-
3121     // flight, or else delayed by javascript processing in this webview.  If a
3122     // drop happens before our IPC reply has reached the browser process, then
3123     // the browser forwards the drop to this webview.  So only allow a drop to
3124     // proceed if our webview m_dragOperation state is not DragOperationNone.
3125
3126     if (m_dragOperation == WebDragOperationNone) { // IPC RACE CONDITION: do not allow this drop.
3127         dragTargetDragLeave();
3128         return;
3129     }
3130
3131     m_currentDragData->setModifierKeyState(webInputEventKeyStateToPlatformEventKeyState(keyModifiers));
3132     DragData dragData(
3133         m_currentDragData.get(),
3134         clientPoint,
3135         screenPoint,
3136         static_cast<DragOperation>(m_operationsAllowed));
3137
3138     UserGestureIndicator gesture(DefinitelyProcessingNewUserGesture);
3139     m_page->dragController().performDrag(&dragData);
3140
3141     m_dragOperation = WebDragOperationNone;
3142     m_currentDragData = nullptr;
3143 }
3144
3145 void WebViewImpl::spellingMarkers(WebVector<uint32_t>* markers)
3146 {
3147     Vector<uint32_t> result;
3148     for (LocalFrame* frame = m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3149         const Vector<DocumentMarker*>& documentMarkers = frame->document()->markers().markers();
3150         for (size_t i = 0; i < documentMarkers.size(); ++i)
3151             result.append(documentMarkers[i]->hash());
3152     }
3153     markers->assign(result);
3154 }
3155
3156 WebDragOperation WebViewImpl::dragTargetDragEnterOrOver(const WebPoint& clientPoint, const WebPoint& screenPoint, DragAction dragAction, int keyModifiers)
3157 {
3158     ASSERT(m_currentDragData);
3159
3160     m_currentDragData->setModifierKeyState(webInputEventKeyStateToPlatformEventKeyState(keyModifiers));
3161     DragData dragData(
3162         m_currentDragData.get(),
3163         clientPoint,
3164         screenPoint,
3165         static_cast<DragOperation>(m_operationsAllowed));
3166
3167     DragSession dragSession;
3168     if (dragAction == DragEnter)
3169         dragSession = m_page->dragController().dragEntered(&dragData);
3170     else
3171         dragSession = m_page->dragController().dragUpdated(&dragData);
3172
3173     DragOperation dropEffect = dragSession.operation;
3174
3175     // Mask the drop effect operation against the drag source's allowed operations.
3176     if (!(dropEffect & dragData.draggingSourceOperationMask()))
3177         dropEffect = DragOperationNone;
3178
3179      m_dragOperation = static_cast<WebDragOperation>(dropEffect);
3180
3181     return m_dragOperation;
3182 }
3183
3184 void WebViewImpl::sendResizeEventAndRepaint()
3185 {
3186     // FIXME: This is wrong. The FrameView is responsible sending a resizeEvent
3187     // as part of layout. Layout is also responsible for sending invalidations
3188     // to the embedder. This method and all callers may be wrong. -- eseidel.
3189     if (mainFrameImpl()->frameView()) {
3190         // Enqueues the resize event.
3191         mainFrameImpl()->frame()->document()->enqueueResizeEvent();
3192     }
3193
3194     if (m_client) {
3195         if (isAcceleratedCompositingActive()) {
3196             updateLayerTreeViewport();
3197         } else {
3198             WebRect damagedRect(0, 0, m_size.width, m_size.height);
3199             m_client->didInvalidateRect(damagedRect);
3200         }
3201     }
3202     if (m_pageOverlays)
3203         m_pageOverlays->update();
3204 }
3205
3206 void WebViewImpl::configureAutoResizeMode()
3207 {
3208     if (!mainFrameImpl() || !mainFrameImpl()->frame() || !mainFrameImpl()->frame()->view())
3209         return;
3210
3211     mainFrameImpl()->frame()->view()->enableAutoSizeMode(m_shouldAutoResize, m_minAutoSize, m_maxAutoSize);
3212 }
3213
3214 unsigned long WebViewImpl::createUniqueIdentifierForRequest()
3215 {
3216     return createUniqueIdentifier();
3217 }
3218
3219 void WebViewImpl::inspectElementAt(const WebPoint& point)
3220 {
3221     if (!m_page)
3222         return;
3223
3224     if (point.x == -1 || point.y == -1) {
3225         m_page->inspectorController().inspect(0);
3226     } else {
3227         HitTestRequest::HitTestRequestType hitType = HitTestRequest::Move | HitTestRequest::ReadOnly | HitTestRequest::AllowChildFrameContent | HitTestRequest::IgnorePointerEventsNone;
3228         HitTestRequest request(hitType);
3229
3230         FrameView* frameView = m_page->mainFrame()->view();
3231         IntPoint transformedPoint(point);
3232         transformedPoint = transformedPoint - frameView->inputEventsOffsetForEmulation();
3233         transformedPoint.scale(1 / frameView->inputEventsScaleFactor(), 1 / frameView->inputEventsScaleFactor());
3234         HitTestResult result(m_page->mainFrame()->view()->windowToContents(transformedPoint));
3235         m_page->mainFrame()->contentRenderer()->hitTest(request, result);
3236         Node* node = result.innerNode();
3237         if (!node && m_page->mainFrame()->document())
3238             node = m_page->mainFrame()->document()->documentElement();
3239         m_page->inspectorController().inspect(node);
3240     }
3241 }
3242
3243 WebString WebViewImpl::inspectorSettings() const
3244 {
3245     return m_inspectorSettings;
3246 }
3247
3248 void WebViewImpl::setInspectorSettings(const WebString& settings)
3249 {
3250     m_inspectorSettings = settings;
3251 }
3252
3253 bool WebViewImpl::inspectorSetting(const WebString& key, WebString* value) const
3254 {
3255     if (!m_inspectorSettingsMap->contains(key))
3256         return false;
3257     *value = m_inspectorSettingsMap->get(key);
3258     return true;
3259 }
3260
3261 void WebViewImpl::setInspectorSetting(const WebString& key,
3262                                       const WebString& value)
3263 {
3264     m_inspectorSettingsMap->set(key, value);
3265     client()->didUpdateInspectorSetting(key, value);
3266 }
3267
3268 void WebViewImpl::setCompositorDeviceScaleFactorOverride(float deviceScaleFactor)
3269 {
3270     m_compositorDeviceScaleFactorOverride = deviceScaleFactor;
3271     if (page() && m_layerTreeView)
3272         updateLayerTreeDeviceScaleFactor();
3273 }
3274
3275 void WebViewImpl::setRootLayerTransform(const WebSize& rootLayerOffset, float rootLayerScale)
3276 {
3277     m_rootLayerScale = rootLayerScale;
3278     m_rootLayerOffset = rootLayerOffset;
3279     if (mainFrameImpl())
3280         mainFrameImpl()->setInputEventsTransformForEmulation(m_rootLayerOffset, m_rootLayerScale);
3281     updateRootLayerTransform();
3282 }
3283
3284 WebDevToolsAgent* WebViewImpl::devToolsAgent()
3285 {
3286     return m_devToolsAgent.get();
3287 }
3288
3289 WebAXObject WebViewImpl::accessibilityObject()
3290 {
3291     if (!mainFrameImpl())
3292         return WebAXObject();
3293
3294     Document* document = mainFrameImpl()->frame()->document();
3295     return WebAXObject(
3296         document->axObjectCache()->getOrCreate(document->renderer()));
3297 }
3298
3299 void WebViewImpl::performCustomContextMenuAction(unsigned action)
3300 {
3301     if (!m_page)
3302         return;
3303     ContextMenu* menu = m_page->contextMenuController().contextMenu();
3304     if (!menu)
3305         return;
3306     const ContextMenuItem* item = menu->itemWithAction(static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + action));
3307     if (item)
3308         m_page->contextMenuController().contextMenuItemSelected(item);
3309     m_page->contextMenuController().clearContextMenu();
3310 }
3311
3312 void WebViewImpl::showContextMenu()
3313 {
3314     if (!page())
3315         return;
3316
3317     page()->contextMenuController().clearContextMenu();
3318     m_contextMenuAllowed = true;
3319     if (LocalFrame* focusedFrame = page()->focusController().focusedOrMainFrame())
3320         focusedFrame->eventHandler().sendContextMenuEventForKey();
3321     m_contextMenuAllowed = false;
3322 }
3323
3324 WebString WebViewImpl::getSmartClipData(WebRect rect)
3325 {
3326     LocalFrame* frame = focusedWebCoreFrame();
3327     if (!frame)
3328         return WebString();
3329     return WebCore::SmartClip(frame).dataForRect(rect).toString();
3330 }
3331
3332 void WebViewImpl::hidePopups()
3333 {
3334     hideSelectPopup();
3335     if (m_pagePopup)
3336         closePagePopup(m_pagePopup.get());
3337 }
3338
3339 void WebViewImpl::setIsTransparent(bool isTransparent)
3340 {
3341     // Set any existing frames to be transparent.
3342     LocalFrame* frame = m_page->mainFrame();
3343     while (frame) {
3344         frame->view()->setTransparent(isTransparent);
3345         frame = frame->tree().traverseNext();
3346     }
3347
3348     // Future frames check this to know whether to be transparent.
3349     m_isTransparent = isTransparent;
3350 }
3351
3352 bool WebViewImpl::isTransparent() const
3353 {
3354     return m_isTransparent;
3355 }
3356
3357 void WebViewImpl::setBaseBackgroundColor(WebColor color)
3358 {
3359     layout();
3360
3361     if (m_baseBackgroundColor == color)
3362         return;
3363
3364     m_baseBackgroundColor = color;
3365
3366     if (m_page->mainFrame())
3367         m_page->mainFrame()->view()->setBaseBackgroundColor(color);
3368
3369     updateLayerTreeBackgroundColor();
3370 }
3371
3372 void WebViewImpl::setIsActive(bool active)
3373 {
3374     if (page())
3375         page()->focusController().setActive(active);
3376 }
3377
3378 bool WebViewImpl::isActive() const
3379 {
3380     return page() ? page()->focusController().isActive() : false;
3381 }
3382
3383 void WebViewImpl::setDomainRelaxationForbidden(bool forbidden, const WebString& scheme)
3384 {
3385     SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme));
3386 }
3387
3388 void WebViewImpl::setWindowFeatures(const WebWindowFeatures& features)
3389 {
3390     m_page->chrome().setWindowFeatures(features);
3391 }
3392
3393 void WebViewImpl::setSelectionColors(unsigned activeBackgroundColor,
3394                                      unsigned activeForegroundColor,
3395                                      unsigned inactiveBackgroundColor,
3396                                      unsigned inactiveForegroundColor) {
3397 #if USE(DEFAULT_RENDER_THEME)
3398     RenderThemeChromiumDefault::setSelectionColors(activeBackgroundColor, activeForegroundColor, inactiveBackgroundColor, inactiveForegroundColor);
3399     RenderTheme::theme().platformColorsDidChange();
3400 #endif
3401 }
3402
3403 void WebView::injectStyleSheet(const WebString& sourceCode, const WebVector<WebString>& patternsIn, WebView::StyleInjectionTarget injectIn)
3404 {
3405     Vector<String> patterns;
3406     for (size_t i = 0; i < patternsIn.size(); ++i)
3407         patterns.append(patternsIn[i]);
3408
3409     InjectedStyleSheets::instance().add(sourceCode, patterns, static_cast<WebCore::StyleInjectionTarget>(injectIn));
3410 }
3411
3412 void WebView::removeInjectedStyleSheets()
3413 {
3414     InjectedStyleSheets::instance().removeAll();
3415 }
3416
3417 void WebViewImpl::didCommitLoad(bool isNewNavigation, bool isNavigationWithinPage)
3418 {
3419     if (isNewNavigation && !isNavigationWithinPage)
3420         m_pageScaleConstraintsSet.setNeedsReset(true);
3421
3422     // Make sure link highlight from previous page is cleared.
3423     m_linkHighlights.clear();
3424     endActiveFlingAnimation();
3425     resetSavedScrollAndScaleState();
3426 }
3427
3428 void WebViewImpl::willInsertBody(WebFrameImpl* webframe)
3429 {
3430     if (webframe != mainFrameImpl())
3431         return;
3432
3433     // If we get to the <body> tag and we have no pending stylesheet loads, we
3434     // can be fairly confident we'll have something sensible to paint soon and
3435     // can turn off deferred commits.
3436     if (m_page->mainFrame()->document()->haveStylesheetsLoaded())
3437         resumeTreeViewCommits();
3438 }
3439
3440 void WebViewImpl::resumeTreeViewCommits()
3441 {
3442     if (m_layerTreeViewCommitsDeferred) {
3443         if (m_layerTreeView)
3444             m_layerTreeView->setDeferCommits(false);
3445         m_layerTreeViewCommitsDeferred = false;
3446     }
3447 }
3448
3449 void WebViewImpl::layoutUpdated(WebFrameImpl* webframe)
3450 {
3451     if (!m_client || webframe != mainFrameImpl())
3452         return;
3453
3454     // If we finished a layout while in deferred commit mode,
3455     // that means it's time to start producing frames again so un-defer.
3456     resumeTreeViewCommits();
3457
3458     if (m_shouldAutoResize && mainFrameImpl()->frame() && mainFrameImpl()->frame()->view()) {
3459         WebSize frameSize = mainFrameImpl()->frame()->view()->frameRect().size();
3460         if (frameSize != m_size) {
3461             m_size = frameSize;
3462             m_client->didAutoResize(m_size);
3463             sendResizeEventAndRepaint();
3464         }
3465     }
3466
3467     if (m_pageScaleConstraintsSet.constraintsDirty())
3468         refreshPageScaleFactorAfterLayout();
3469
3470     m_client->didUpdateLayout();
3471 }
3472
3473 void WebViewImpl::didChangeContentsSize()
3474 {
3475     m_pageScaleConstraintsSet.didChangeContentsSize(contentsSize(), pageScaleFactor());
3476 }
3477
3478 void WebViewImpl::deviceOrPageScaleFactorChanged()
3479 {
3480     if (pageScaleFactor() && pageScaleFactor() != 1)
3481         enterForceCompositingMode(true);
3482     m_pageScaleConstraintsSet.setNeedsReset(false);
3483     updateLayerTreeViewport();
3484 }
3485
3486 bool WebViewImpl::useExternalPopupMenus()
3487 {
3488     return shouldUseExternalPopupMenus;
3489 }
3490
3491 void WebViewImpl::startDragging(LocalFrame* frame,
3492                                 const WebDragData& dragData,
3493                                 WebDragOperationsMask mask,
3494                                 const WebImage& dragImage,
3495                                 const WebPoint& dragImageOffset)
3496 {
3497     if (!m_client)
3498         return;
3499     ASSERT(!m_doingDragAndDrop);
3500     m_doingDragAndDrop = true;
3501     m_client->startDragging(WebFrameImpl::fromFrame(frame), dragData, mask, dragImage, dragImageOffset);
3502 }
3503
3504 void WebViewImpl::setIgnoreInputEvents(bool newValue)
3505 {
3506     ASSERT(m_ignoreInputEvents != newValue);
3507     m_ignoreInputEvents = newValue;
3508 }
3509
3510 void WebViewImpl::setBackgroundColorOverride(WebColor color)
3511 {
3512     m_backgroundColorOverride = color;
3513     updateLayerTreeBackgroundColor();
3514 }
3515
3516 void WebViewImpl::setZoomFactorOverride(float zoomFactor)
3517 {
3518     m_zoomFactorOverride = zoomFactor;
3519     setZoomLevel(zoomLevel());
3520 }
3521
3522 void WebViewImpl::addPageOverlay(WebPageOverlay* overlay, int zOrder)
3523 {
3524     if (!m_pageOverlays)
3525         m_pageOverlays = PageOverlayList::create(this);
3526
3527     m_pageOverlays->add(overlay, zOrder);
3528 }
3529
3530 void WebViewImpl::removePageOverlay(WebPageOverlay* overlay)
3531 {
3532     if (m_pageOverlays && m_pageOverlays->remove(overlay) && m_pageOverlays->empty())
3533         m_pageOverlays = nullptr;
3534 }
3535
3536 void WebViewImpl::setOverlayLayer(WebCore::GraphicsLayer* layer)
3537 {
3538     if (!m_rootGraphicsLayer)
3539         return;
3540
3541     if (!m_rootTransformLayer)
3542         m_rootTransformLayer = m_page->mainFrame()->view()->renderView()->compositor()->ensureRootTransformLayer();
3543
3544     if (m_rootTransformLayer) {
3545         if (layer->parent() != m_rootTransformLayer)
3546             m_rootTransformLayer->addChild(layer);
3547     }
3548 }
3549
3550 NotificationPresenterImpl* WebViewImpl::notificationPresenterImpl()
3551 {
3552     if (!m_notificationPresenter.isInitialized() && m_client)
3553         m_notificationPresenter.initialize(m_client->notificationPresenter());
3554     return &m_notificationPresenter;
3555 }
3556
3557 Element* WebViewImpl::focusedElement() const
3558 {
3559     LocalFrame* frame = m_page->focusController().focusedFrame();
3560     if (!frame)
3561         return 0;
3562
3563     Document* document = frame->document();
3564     if (!document)
3565         return 0;
3566
3567     return document->focusedElement();
3568 }
3569
3570 HitTestResult WebViewImpl::hitTestResultForWindowPos(const IntPoint& pos)
3571 {
3572     IntPoint docPoint(m_page->mainFrame()->view()->windowToContents(pos));
3573     return m_page->mainFrame()->eventHandler().hitTestResultAtPoint(docPoint, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
3574 }
3575
3576 void WebViewImpl::setTabsToLinks(bool enable)
3577 {
3578     m_tabsToLinks = enable;
3579 }
3580
3581 bool WebViewImpl::tabsToLinks() const
3582 {
3583     return m_tabsToLinks;
3584 }
3585
3586 void WebViewImpl::suppressInvalidations(bool enable)
3587 {
3588     if (m_client)
3589         m_client->suppressCompositorScheduling(enable);
3590 }
3591
3592 bool WebViewImpl::allowsAcceleratedCompositing()
3593 {
3594     return !m_compositorCreationFailed;
3595 }
3596
3597 void WebViewImpl::setRootGraphicsLayer(GraphicsLayer* layer)
3598 {
3599     bool pinchVirtualViewportEnabled = page()->settings().pinchVirtualViewportEnabled();
3600     suppressInvalidations(true);
3601
3602     if (pinchVirtualViewportEnabled) {
3603         PinchViewport& pinchViewport = page()->frameHost().pinchViewport();
3604         pinchViewport.attachToLayerTree(layer, graphicsLayerFactory());
3605         pinchViewport.setSize(mainFrameImpl()->frame()->view()->frameRect().size());
3606         if (layer) {
3607             m_rootGraphicsLayer = pinchViewport.rootGraphicsLayer();
3608             m_rootLayer = pinchViewport.rootGraphicsLayer()->platformLayer();
3609             m_rootTransformLayer = 0;
3610         } else {
3611             m_rootGraphicsLayer = 0;
3612             m_rootLayer = 0;
3613             m_rootTransformLayer = 0;
3614         }
3615     } else {
3616         m_rootGraphicsLayer = layer;
3617         m_rootLayer = layer ? layer->platformLayer() : 0;
3618         m_rootTransformLayer = 0;
3619     }
3620
3621     setIsAcceleratedCompositingActive(layer);
3622
3623     updateRootLayerTransform();
3624
3625     if (m_layerTreeView) {
3626         if (m_rootLayer) {
3627             m_layerTreeView->setRootLayer(*m_rootLayer);
3628             // We register viewport layers here since there may not be a layer
3629             // tree view prior to this point.
3630             if (pinchVirtualViewportEnabled) {
3631                 page()->frameHost().pinchViewport().registerLayersWithTreeView(m_layerTreeView);
3632             } else {
3633                 GraphicsLayer* rootScrollLayer = compositor()->scrollLayer();
3634                 ASSERT(rootScrollLayer);
3635                 WebLayer* pageScaleLayer = rootScrollLayer->parent() ? rootScrollLayer->parent()->platformLayer() : 0;
3636                 m_layerTreeView->registerViewportLayers(pageScaleLayer, rootScrollLayer->platformLayer(), 0);
3637             }
3638         } else {
3639             m_layerTreeView->clearRootLayer();
3640             if (pinchVirtualViewportEnabled)
3641                 page()->frameHost().pinchViewport().clearLayersForTreeView(m_layerTreeView);
3642             else
3643                 m_layerTreeView->clearViewportLayers();
3644         }
3645     }
3646
3647     suppressInvalidations(false);
3648 }
3649
3650 void WebViewImpl::scheduleCompositingLayerSync()
3651 {
3652     m_layerTreeView->setNeedsAnimate();
3653 }
3654
3655 void WebViewImpl::scrollRootLayer()
3656 {
3657     updateLayerTreeViewport();
3658 }
3659
3660 void WebViewImpl::invalidateRect(const IntRect& rect)
3661 {
3662     if (m_isAcceleratedCompositingActive) {
3663         ASSERT(m_layerTreeView);
3664         updateLayerTreeViewport();
3665     } else if (m_client)
3666         m_client->didInvalidateRect(rect);
3667 }
3668
3669 WebCore::GraphicsLayerFactory* WebViewImpl::graphicsLayerFactory() const
3670 {
3671     return m_graphicsLayerFactory.get();
3672 }
3673
3674 WebCore::RenderLayerCompositor* WebViewImpl::compositor() const
3675 {
3676     if (!page()
3677         || !page()->mainFrame()
3678         || !page()->mainFrame()->document()
3679         || !page()->mainFrame()->document()->renderView())
3680         return 0;
3681     return page()->mainFrame()->document()->renderView()->compositor();
3682 }
3683
3684 void WebViewImpl::registerForAnimations(WebLayer* layer)
3685 {
3686     if (m_layerTreeView)
3687         m_layerTreeView->registerForAnimations(layer);
3688 }
3689
3690 WebCore::GraphicsLayer* WebViewImpl::rootGraphicsLayer()
3691 {
3692     return m_rootGraphicsLayer;
3693 }
3694
3695 void WebViewImpl::scheduleAnimation()
3696 {
3697     if (isAcceleratedCompositingActive()) {
3698         ASSERT(m_layerTreeView);
3699         m_layerTreeView->setNeedsAnimate();
3700         return;
3701     }
3702     if (m_client)
3703         m_client->scheduleAnimation();
3704 }
3705
3706 void WebViewImpl::setIsAcceleratedCompositingActive(bool active)
3707 {
3708     blink::Platform::current()->histogramEnumeration("GPU.setIsAcceleratedCompositingActive", active * 2 + m_isAcceleratedCompositingActive, 4);
3709
3710     if (m_isAcceleratedCompositingActive == active)
3711         return;
3712
3713     if (!active) {
3714         m_isAcceleratedCompositingActive = false;
3715         // We need to finish all GL rendering before sending didDeactivateCompositor() to prevent
3716         // flickering when compositing turns off. This is only necessary if we're not in
3717         // force-compositing-mode.
3718         if (m_layerTreeView && !page()->settings().forceCompositingMode())
3719             m_layerTreeView->finishAllRendering();
3720         m_client->didDeactivateCompositor();
3721         if (!m_layerTreeViewCommitsDeferred
3722             && blink::Platform::current()->isThreadedCompositingEnabled()) {
3723             ASSERT(m_layerTreeView);
3724             // In threaded compositing mode, force compositing mode is always on so setIsAcceleratedCompositingActive(false)
3725             // means that we're transitioning to a new page. Suppress commits until WebKit generates invalidations so
3726             // we don't attempt to paint too early in the next page load.
3727             m_layerTreeView->setDeferCommits(true);
3728             m_layerTreeViewCommitsDeferred = true;
3729         }
3730     } else if (m_layerTreeView) {
3731         m_isAcceleratedCompositingActive = true;
3732         updateLayerTreeViewport();
3733         if (m_pageOverlays)
3734             m_pageOverlays->update();
3735
3736         m_client->didActivateCompositor(0);
3737     } else {
3738         TRACE_EVENT0("webkit", "WebViewImpl::setIsAcceleratedCompositingActive(true)");
3739
3740         m_client->initializeLayerTreeView();
3741         m_layerTreeView = m_client->layerTreeView();
3742         if (m_layerTreeView) {
3743             m_layerTreeView->setRootLayer(*m_rootLayer);
3744
3745             bool visible = page()->visibilityState() == PageVisibilityStateVisible;
3746             m_layerTreeView->setVisible(visible);
3747             updateLayerTreeDeviceScaleFactor();
3748             m_layerTreeView->setPageScaleFactorAndLimits(pageScaleFactor(), minimumPageScaleFactor(), maximumPageScaleFactor());
3749             updateLayerTreeBackgroundColor();
3750             m_layerTreeView->setHasTransparentBackground(isTransparent());
3751 #if USE(RUBBER_BANDING)
3752             RefPtr<Image> overhangImage = OverscrollTheme::theme()->getOverhangImage();
3753             if (overhangImage)
3754                 m_layerTreeView->setOverhangBitmap(overhangImage->nativeImageForCurrentFrame()->bitmap());
3755 #endif
3756             updateLayerTreeViewport();
3757             m_client->didActivateCompositor(0);
3758             m_isAcceleratedCompositingActive = true;
3759             m_compositorCreationFailed = false;
3760             if (m_pageOverlays)
3761                 m_pageOverlays->update();
3762             m_layerTreeView->setShowFPSCounter(m_showFPSCounter);
3763             m_layerTreeView->setShowPaintRects(m_showPaintRects);
3764             m_layerTreeView->setShowDebugBorders(m_showDebugBorders);
3765             m_layerTreeView->setContinuousPaintingEnabled(m_continuousPaintingEnabled);
3766             m_layerTreeView->setShowScrollBottleneckRects(m_showScrollBottleneckRects);
3767         } else {
3768             m_isAcceleratedCompositingActive = false;
3769             m_client->didDeactivateCompositor();
3770             m_compositorCreationFailed = true;
3771         }
3772     }
3773     if (page())
3774         page()->mainFrame()->view()->setClipsRepaints(!m_isAcceleratedCompositingActive);
3775 }
3776
3777 void WebViewImpl::updateMainFrameScrollPosition(const IntPoint& scrollPosition, bool programmaticScroll)
3778 {
3779     FrameView* frameView = page()->mainFrame()->view();
3780     if (!frameView)
3781         return;
3782
3783     if (frameView->scrollPosition() == scrollPosition)
3784         return;
3785
3786     bool oldProgrammaticScroll = frameView->inProgrammaticScroll();
3787     frameView->setInProgrammaticScroll(programmaticScroll);
3788     frameView->notifyScrollPositionChanged(scrollPosition);
3789     frameView->setInProgrammaticScroll(oldProgrammaticScroll);
3790 }
3791
3792 void WebViewImpl::applyScrollAndScale(const WebSize& scrollDelta, float pageScaleDelta)
3793 {
3794     if (!mainFrameImpl() || !mainFrameImpl()->frameView())
3795         return;
3796
3797     // With virtual viewport we need only set the scale (see TODO below).
3798     if (page()->settings().pinchVirtualViewportEnabled()) {
3799         WebSize scrollOffset = mainFrame()->scrollOffset();
3800         WebPoint scrollPoint(scrollOffset.width, scrollOffset.height);
3801         setPageScaleFactor(pageScaleFactor() * pageScaleDelta, scrollPoint);
3802         m_doubleTapZoomPending = false;
3803         return;
3804     }
3805
3806     // TODO(bokan): Old pinch path only - virtual viewport pinch scrolls are automatically updated via GraphicsLayer::DidScroll.
3807     // this should be removed once old pinch is removed.
3808     if (pageScaleDelta == 1) {
3809         TRACE_EVENT_INSTANT2("webkit", "WebViewImpl::applyScrollAndScale::scrollBy", "x", scrollDelta.width, "y", scrollDelta.height);
3810         WebSize webScrollOffset = mainFrame()->scrollOffset();
3811         IntPoint scrollOffset(webScrollOffset.width + scrollDelta.width, webScrollOffset.height + scrollDelta.height);
3812         updateMainFrameScrollPosition(scrollOffset, false);
3813     } else {
3814         // The page scale changed, so apply a scale and scroll in a single
3815         // operation.
3816         WebSize scrollOffset = mainFrame()->scrollOffset();
3817         scrollOffset.width += scrollDelta.width;
3818         scrollOffset.height += scrollDelta.height;
3819
3820         WebPoint scrollPoint(scrollOffset.width, scrollOffset.height);
3821         setPageScaleFactor(pageScaleFactor() * pageScaleDelta, scrollPoint);
3822         m_doubleTapZoomPending = false;
3823     }
3824 }
3825
3826 void WebViewImpl::didExitCompositingMode()
3827 {
3828     ASSERT(m_isAcceleratedCompositingActive);
3829     setIsAcceleratedCompositingActive(false);
3830     m_compositorCreationFailed = true;
3831     m_client->didInvalidateRect(IntRect(0, 0, m_size.width, m_size.height));
3832
3833     // Force a style recalc to remove all the composited layers.
3834     m_page->mainFrame()->document()->setNeedsStyleRecalc(SubtreeStyleChange);
3835
3836     if (m_pageOverlays)
3837         m_pageOverlays->update();
3838 }
3839
3840 void WebViewImpl::updateLayerTreeViewport()
3841 {
3842     if (!page() || !m_layerTreeView)
3843         return;
3844
3845     m_layerTreeView->setPageScaleFactorAndLimits(pageScaleFactor(), minimumPageScaleFactor(), maximumPageScaleFactor());
3846 }
3847
3848 void WebViewImpl::updateLayerTreeBackgroundColor()
3849 {
3850     if (!m_layerTreeView)
3851         return;
3852
3853     m_layerTreeView->setBackgroundColor(alphaChannel(m_backgroundColorOverride) ? m_backgroundColorOverride : backgroundColor());
3854 }
3855
3856 void WebViewImpl::updateLayerTreeDeviceScaleFactor()
3857 {
3858     ASSERT(page());
3859     ASSERT(m_layerTreeView);
3860
3861     float deviceScaleFactor = m_compositorDeviceScaleFactorOverride ? m_compositorDeviceScaleFactorOverride : page()->deviceScaleFactor();
3862     m_layerTreeView->setDeviceScaleFactor(deviceScaleFactor);
3863 }
3864
3865 void WebViewImpl::updateRootLayerTransform()
3866 {
3867     // If we don't have a root graphics layer, we won't bother trying to find
3868     // or update the transform layer.
3869     if (!m_rootGraphicsLayer)
3870         return;
3871
3872     if (!m_rootTransformLayer)
3873         m_rootTransformLayer = m_page->mainFrame()->view()->renderView()->compositor()->ensureRootTransformLayer();
3874
3875     if (m_rootTransformLayer) {
3876         WebCore::TransformationMatrix transform;
3877         transform.translate(m_rootLayerOffset.width, m_rootLayerOffset.height);
3878         transform = transform.scale(m_rootLayerScale);
3879         m_rootTransformLayer->setTransform(transform);
3880     }
3881 }
3882
3883 bool WebViewImpl::detectContentOnTouch(const WebPoint& position)
3884 {
3885     HitTestResult touchHit = hitTestResultForWindowPos(position);
3886
3887     if (touchHit.isContentEditable())
3888         return false;
3889
3890     Node* node = touchHit.innerNode();
3891     if (!node || !node->isTextNode())
3892         return false;
3893
3894     // Ignore when tapping on links or nodes listening to click events, unless the click event is on the
3895     // body element, in which case it's unlikely that the original node itself was intended to be clickable.
3896     for (; node && !isHTMLBodyElement(*node); node = node->parentNode()) {
3897         if (node->isLink() || node->willRespondToTouchEvents() || node->willRespondToMouseClickEvents())
3898             return false;
3899     }
3900
3901     WebContentDetectionResult content = m_client->detectContentAround(touchHit);
3902     if (!content.isValid())
3903         return false;
3904
3905     m_client->scheduleContentIntent(content.intent());
3906     return true;
3907 }
3908
3909 void WebViewImpl::setVisibilityState(WebPageVisibilityState visibilityState,
3910                                      bool isInitialState) {
3911     if (!page())
3912         return;
3913
3914     ASSERT(visibilityState == WebPageVisibilityStateVisible || visibilityState == WebPageVisibilityStateHidden || visibilityState == WebPageVisibilityStatePrerender);
3915     m_page->setVisibilityState(static_cast<PageVisibilityState>(static_cast<int>(visibilityState)), isInitialState);
3916
3917     if (m_layerTreeView) {
3918         bool visible = visibilityState == WebPageVisibilityStateVisible;
3919         m_layerTreeView->setVisible(visible);
3920     }
3921 }
3922
3923 bool WebViewImpl::requestPointerLock()
3924 {
3925     return m_client && m_client->requestPointerLock();
3926 }
3927
3928 void WebViewImpl::requestPointerUnlock()
3929 {
3930     if (m_client)
3931         m_client->requestPointerUnlock();
3932 }
3933
3934 bool WebViewImpl::isPointerLocked()
3935 {
3936     return m_client && m_client->isPointerLocked();
3937 }
3938
3939 void WebViewImpl::pointerLockMouseEvent(const WebInputEvent& event)
3940 {
3941     AtomicString eventType;
3942     switch (event.type) {
3943     case WebInputEvent::MouseDown:
3944         eventType = EventTypeNames::mousedown;
3945         break;
3946     case WebInputEvent::MouseUp:
3947         eventType = EventTypeNames::mouseup;
3948         break;
3949     case WebInputEvent::MouseMove:
3950         eventType = EventTypeNames::mousemove;
3951         break;
3952     default:
3953         ASSERT_NOT_REACHED();
3954     }
3955
3956     const WebMouseEvent& mouseEvent = static_cast<const WebMouseEvent&>(event);
3957
3958     if (page())
3959         page()->pointerLockController().dispatchLockedMouseEvent(
3960             PlatformMouseEventBuilder(mainFrameImpl()->frameView(), mouseEvent),
3961             eventType);
3962 }
3963
3964 bool WebViewImpl::shouldDisableDesktopWorkarounds()
3965 {
3966     if (!settings()->viewportEnabled())
3967         return false;
3968
3969     // A document is considered adapted to small screen UAs if one of these holds:
3970     // 1. The author specified viewport has a constrained width that is equal to
3971     //    the initial viewport width.
3972     // 2. The author has disabled viewport zoom.
3973
3974     const PageScaleConstraints& constraints = m_pageScaleConstraintsSet.pageDefinedConstraints();
3975
3976     if (!mainFrameImpl() || !mainFrameImpl()->frameView())
3977         return false;
3978
3979     return mainFrameImpl()->frameView()->layoutSize().width() == m_size.width
3980         || (constraints.minimumScale == constraints.maximumScale && constraints.minimumScale != -1);
3981 }
3982
3983 } // namespace blink