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