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