[chromium] Clean up WebWidget / WebLayerTreeView interactions
[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     TRACE_EVENT0("webkit", "WebViewImpl::animate");
1820
1821     if (!monotonicFrameBeginTime)
1822         monotonicFrameBeginTime = monotonicallyIncreasingTime();
1823
1824     // Create synthetic wheel events as necessary for fling.
1825     if (m_gestureAnimation) {
1826         if (m_gestureAnimation->animate(monotonicFrameBeginTime))
1827             scheduleAnimation();
1828         else {
1829             m_gestureAnimation.clear();
1830             if (m_layerTreeView)
1831                 m_layerTreeView->didStopFlinging();
1832
1833             mainFrameImpl()->frame()->eventHandler()->clearGestureScrollNodes();
1834         }
1835     }
1836
1837     if (!m_page)
1838         return;
1839
1840     PageWidgetDelegate::animate(m_page.get(), monotonicFrameBeginTime);
1841
1842     if (m_continuousPaintingEnabled) {
1843         ContinuousPainter::setNeedsDisplayRecursive(m_rootGraphicsLayer, m_pageOverlays.get());
1844         m_client->scheduleAnimation();
1845     }
1846 }
1847
1848 void WebViewImpl::updateAnimations(double monotonicFrameBeginTime)
1849 {
1850     animate(monotonicFrameBeginTime);
1851 }
1852
1853 void WebViewImpl::layout()
1854 {
1855     TRACE_EVENT0("webkit", "WebViewImpl::layout");
1856     PageWidgetDelegate::layout(m_page.get());
1857
1858     if (m_linkHighlight)
1859         m_linkHighlight->updateGeometry();
1860 }
1861
1862 void WebViewImpl::enterForceCompositingMode(bool enter)
1863 {
1864     TRACE_EVENT1("webkit", "WebViewImpl::enterForceCompositingMode", "enter", enter);
1865     settingsImpl()->setForceCompositingMode(enter);
1866     if (enter) {
1867         if (!m_page)
1868             return;
1869         Frame* mainFrame = m_page->mainFrame();
1870         if (!mainFrame)
1871             return;
1872         mainFrame->view()->updateCompositingLayersAfterStyleChange();
1873     }
1874 }
1875
1876 #if USE(ACCELERATED_COMPOSITING)
1877 void WebViewImpl::doPixelReadbackToCanvas(WebCanvas* canvas, const IntRect& rect)
1878 {
1879     ASSERT(m_layerTreeView);
1880
1881     SkBitmap target;
1882     target.setConfig(SkBitmap::kARGB_8888_Config, rect.width(), rect.height(), rect.width() * 4);
1883     target.allocPixels();
1884     m_layerTreeView->compositeAndReadback(target.getPixels(), rect);
1885 #if (!SK_R32_SHIFT && SK_B32_SHIFT == 16)
1886     // The compositor readback always gives back pixels in BGRA order, but for
1887     // example Android's Skia uses RGBA ordering so the red and blue channels
1888     // need to be swapped.
1889     uint8_t* pixels = reinterpret_cast<uint8_t*>(target.getPixels());
1890     for (size_t i = 0; i < target.getSize(); i += 4)
1891         std::swap(pixels[i], pixels[i + 2]);
1892 #endif
1893     canvas->writePixels(target, rect.x(), rect.y());
1894 }
1895 #endif
1896
1897 void WebViewImpl::paint(WebCanvas* canvas, const WebRect& rect, PaintOptions option)
1898 {
1899 #if !OS(ANDROID)
1900     // ReadbackFromCompositorIfAvailable is the only option available on non-Android.
1901     // Ideally, Android would always use ReadbackFromCompositorIfAvailable as well.
1902     ASSERT(option == ReadbackFromCompositorIfAvailable);
1903 #endif
1904
1905     if (option == ReadbackFromCompositorIfAvailable && isAcceleratedCompositingActive()) {
1906 #if USE(ACCELERATED_COMPOSITING)
1907         // If a canvas was passed in, we use it to grab a copy of the
1908         // freshly-rendered pixels.
1909         if (canvas) {
1910             // Clip rect to the confines of the rootLayerTexture.
1911             IntRect resizeRect(rect);
1912             resizeRect.intersect(IntRect(IntPoint(0, 0), m_layerTreeView->deviceViewportSize()));
1913             doPixelReadbackToCanvas(canvas, resizeRect);
1914         }
1915 #endif
1916     } else {
1917         FrameView* view = page()->mainFrame()->view();
1918         PaintBehavior oldPaintBehavior = view->paintBehavior();
1919         if (isAcceleratedCompositingActive()) {
1920             ASSERT(option == ForceSoftwareRenderingAndIgnoreGPUResidentContent);            
1921             view->setPaintBehavior(oldPaintBehavior | PaintBehaviorFlattenCompositingLayers);
1922         }
1923
1924         double paintStart = currentTime();
1925         PageWidgetDelegate::paint(m_page.get(), pageOverlays(), canvas, rect, isTransparent() ? PageWidgetDelegate::Translucent : PageWidgetDelegate::Opaque, m_webSettings->applyDeviceScaleFactorInCompositor());
1926         double paintEnd = currentTime();
1927         double pixelsPerSec = (rect.width * rect.height) / (paintEnd - paintStart);
1928         WebKit::Platform::current()->histogramCustomCounts("Renderer4.SoftwarePaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30);
1929         WebKit::Platform::current()->histogramCustomCounts("Renderer4.SoftwarePaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30);
1930
1931         if (isAcceleratedCompositingActive()) {
1932             ASSERT(option == ForceSoftwareRenderingAndIgnoreGPUResidentContent);            
1933             view->setPaintBehavior(oldPaintBehavior);
1934         }
1935     }
1936 }
1937
1938 bool WebViewImpl::isTrackingRepaints() const
1939 {
1940     if (!page())
1941         return false;
1942     FrameView* view = page()->mainFrame()->view();
1943     return view->isTrackingRepaints();
1944 }
1945
1946 void WebViewImpl::themeChanged()
1947 {
1948     if (!page())
1949         return;
1950     FrameView* view = page()->mainFrame()->view();
1951
1952     WebRect damagedRect(0, 0, m_size.width, m_size.height);
1953     view->invalidateRect(damagedRect);
1954 }
1955
1956 void WebViewImpl::setNeedsRedraw()
1957 {
1958 #if USE(ACCELERATED_COMPOSITING)
1959     if (m_layerTreeView && isAcceleratedCompositingActive())
1960         m_layerTreeView->setNeedsRedraw();
1961 #endif
1962 }
1963
1964 void WebViewImpl::enterFullScreenForElement(WebCore::Element* element)
1965 {
1966     // We are already transitioning to fullscreen for a different element.
1967     if (m_provisionalFullScreenElement) {
1968         m_provisionalFullScreenElement = element;
1969         return;
1970     }
1971
1972     // We are already in fullscreen mode.
1973     if (m_fullScreenFrame) {
1974         m_provisionalFullScreenElement = element;
1975         willEnterFullScreen();
1976         didEnterFullScreen();
1977         return;
1978     }
1979
1980 #if USE(NATIVE_FULLSCREEN_VIDEO)
1981     if (element && element->isMediaElement()) {
1982         HTMLMediaElement* mediaElement = static_cast<HTMLMediaElement*>(element);
1983         if (mediaElement->player() && mediaElement->player()->canEnterFullscreen()) {
1984             mediaElement->player()->enterFullscreen();
1985             m_provisionalFullScreenElement = element;
1986         }
1987         return;
1988     }
1989 #endif
1990
1991     // We need to transition to fullscreen mode.
1992     if (m_client && m_client->enterFullScreen())
1993         m_provisionalFullScreenElement = element;
1994 }
1995
1996 void WebViewImpl::exitFullScreenForElement(WebCore::Element* element)
1997 {
1998     // The client is exiting full screen, so don't send a notification.
1999     if (m_isCancelingFullScreen)
2000         return;
2001 #if USE(NATIVE_FULLSCREEN_VIDEO)
2002     if (element && element->isMediaElement()) {
2003         HTMLMediaElement* mediaElement = static_cast<HTMLMediaElement*>(element);
2004         if (mediaElement->player())
2005             mediaElement->player()->exitFullscreen();
2006         return;
2007     }
2008 #endif
2009     if (m_client)
2010         m_client->exitFullScreen();
2011 }
2012
2013 bool WebViewImpl::hasHorizontalScrollbar()
2014 {
2015     return mainFrameImpl()->frameView()->horizontalScrollbar();
2016 }
2017
2018 bool WebViewImpl::hasVerticalScrollbar()
2019 {
2020     return mainFrameImpl()->frameView()->verticalScrollbar();
2021 }
2022
2023 const WebInputEvent* WebViewImpl::m_currentInputEvent = 0;
2024
2025 bool WebViewImpl::handleInputEvent(const WebInputEvent& inputEvent)
2026 {
2027     // If we've started a drag and drop operation, ignore input events until
2028     // we're done.
2029     if (m_doingDragAndDrop)
2030         return true;
2031
2032     // Report the event to be NOT processed by WebKit, so that the browser can handle it appropriately.
2033     if (m_ignoreInputEvents)
2034         return false;
2035
2036     TemporaryChange<const WebInputEvent*> currentEventChange(m_currentInputEvent, &inputEvent);
2037
2038 #if ENABLE(POINTER_LOCK)
2039     if (isPointerLocked() && WebInputEvent::isMouseEventType(inputEvent.type)) {
2040       pointerLockMouseEvent(inputEvent);
2041       return true;
2042     }
2043 #endif
2044
2045     if (m_mouseCaptureNode && WebInputEvent::isMouseEventType(inputEvent.type)) {
2046         // Save m_mouseCaptureNode since mouseCaptureLost() will clear it.
2047         RefPtr<Node> node = m_mouseCaptureNode;
2048
2049         // Not all platforms call mouseCaptureLost() directly.
2050         if (inputEvent.type == WebInputEvent::MouseUp)
2051             mouseCaptureLost();
2052
2053         AtomicString eventType;
2054         switch (inputEvent.type) {
2055         case WebInputEvent::MouseMove:
2056             eventType = eventNames().mousemoveEvent;
2057             break;
2058         case WebInputEvent::MouseLeave:
2059             eventType = eventNames().mouseoutEvent;
2060             break;
2061         case WebInputEvent::MouseDown:
2062             eventType = eventNames().mousedownEvent;
2063             break;
2064         case WebInputEvent::MouseUp:
2065             eventType = eventNames().mouseupEvent;
2066             break;
2067         default:
2068             ASSERT_NOT_REACHED();
2069         }
2070
2071         node->dispatchMouseEvent(
2072               PlatformMouseEventBuilder(mainFrameImpl()->frameView(), *static_cast<const WebMouseEvent*>(&inputEvent)),
2073               eventType, static_cast<const WebMouseEvent*>(&inputEvent)->clickCount);
2074         return true;
2075     }
2076
2077     return PageWidgetDelegate::handleInputEvent(m_page.get(), *this, inputEvent);
2078 }
2079
2080 void WebViewImpl::mouseCaptureLost()
2081 {
2082     m_mouseCaptureNode = 0;
2083 }
2084
2085 void WebViewImpl::setFocus(bool enable)
2086 {
2087     m_page->focusController()->setFocused(enable);
2088     if (enable) {
2089         m_page->focusController()->setActive(true);
2090         RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
2091         if (focusedFrame) {
2092             Node* focusedNode = focusedFrame->document()->focusedNode();
2093             if (focusedNode && focusedNode->isElementNode()
2094                 && focusedFrame->selection()->selection().isNone()) {
2095                 // If the selection was cleared while the WebView was not
2096                 // focused, then the focus element shows with a focus ring but
2097                 // no caret and does respond to keyboard inputs.
2098                 Element* element = static_cast<Element*>(focusedNode);
2099                 if (element->isTextFormControl())
2100                     element->updateFocusAppearance(true);
2101                 else if (focusedNode->isContentEditable()) {
2102                     // updateFocusAppearance() selects all the text of
2103                     // contentseditable DIVs. So we set the selection explicitly
2104                     // instead. Note that this has the side effect of moving the
2105                     // caret back to the beginning of the text.
2106                     Position position(focusedNode, 0,
2107                                       Position::PositionIsOffsetInAnchor);
2108                     focusedFrame->selection()->setSelection(
2109                         VisibleSelection(position, SEL_DEFAULT_AFFINITY));
2110                 }
2111             }
2112         }
2113         m_imeAcceptEvents = true;
2114     } else {
2115         hidePopups();
2116
2117         // Clear focus on the currently focused frame if any.
2118         if (!m_page)
2119             return;
2120
2121         Frame* frame = m_page->mainFrame();
2122         if (!frame)
2123             return;
2124
2125         RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
2126         if (focusedFrame) {
2127             // Finish an ongoing composition to delete the composition node.
2128             Editor* editor = focusedFrame->editor();
2129             if (editor && editor->hasComposition()) {
2130                 if (m_autofillClient)
2131                     m_autofillClient->setIgnoreTextChanges(true);
2132
2133                 editor->confirmComposition();
2134
2135                 if (m_autofillClient)
2136                     m_autofillClient->setIgnoreTextChanges(false);
2137             }
2138             m_imeAcceptEvents = false;
2139         }
2140     }
2141 }
2142
2143 bool WebViewImpl::setComposition(
2144     const WebString& text,
2145     const WebVector<WebCompositionUnderline>& underlines,
2146     int selectionStart,
2147     int selectionEnd)
2148 {
2149     Frame* focused = focusedWebCoreFrame();
2150     if (!focused || !m_imeAcceptEvents)
2151         return false;
2152     Editor* editor = focused->editor();
2153     if (!editor)
2154         return false;
2155
2156     // The input focus has been moved to another WebWidget object.
2157     // We should use this |editor| object only to complete the ongoing
2158     // composition.
2159     if (!editor->canEdit() && !editor->hasComposition())
2160         return false;
2161
2162     // We should verify the parent node of this IME composition node are
2163     // editable because JavaScript may delete a parent node of the composition
2164     // node. In this case, WebKit crashes while deleting texts from the parent
2165     // node, which doesn't exist any longer.
2166     PassRefPtr<Range> range = editor->compositionRange();
2167     if (range) {
2168         Node* node = range->startContainer();
2169         if (!node || !node->isContentEditable())
2170             return false;
2171     }
2172
2173     // If we're not going to fire a keypress event, then the keydown event was
2174     // canceled.  In that case, cancel any existing composition.
2175     if (text.isEmpty() || m_suppressNextKeypressEvent) {
2176         // A browser process sent an IPC message which does not contain a valid
2177         // string, which means an ongoing composition has been canceled.
2178         // If the ongoing composition has been canceled, replace the ongoing
2179         // composition string with an empty string and complete it.
2180         String emptyString;
2181         Vector<CompositionUnderline> emptyUnderlines;
2182         editor->setComposition(emptyString, emptyUnderlines, 0, 0);
2183         return text.isEmpty();
2184     }
2185
2186     // When the range of composition underlines overlap with the range between
2187     // selectionStart and selectionEnd, WebKit somehow won't paint the selection
2188     // at all (see InlineTextBox::paint() function in InlineTextBox.cpp).
2189     // But the selection range actually takes effect.
2190     editor->setComposition(String(text),
2191                            CompositionUnderlineVectorBuilder(underlines),
2192                            selectionStart, selectionEnd);
2193
2194     return editor->hasComposition();
2195 }
2196
2197 bool WebViewImpl::confirmComposition()
2198 {
2199     return confirmComposition(WebString());
2200 }
2201
2202 bool WebViewImpl::confirmComposition(const WebString& text)
2203 {
2204     Frame* focused = focusedWebCoreFrame();
2205     if (!focused || !m_imeAcceptEvents)
2206         return false;
2207     Editor* editor = focused->editor();
2208     if (!editor || (!editor->hasComposition() && !text.length()))
2209         return false;
2210
2211     // We should verify the parent node of this IME composition node are
2212     // editable because JavaScript may delete a parent node of the composition
2213     // node. In this case, WebKit crashes while deleting texts from the parent
2214     // node, which doesn't exist any longer.
2215     PassRefPtr<Range> range = editor->compositionRange();
2216     if (range) {
2217         Node* node = range->startContainer();
2218         if (!node || !node->isContentEditable())
2219             return false;
2220     }
2221
2222     if (editor->hasComposition()) {
2223         if (text.length())
2224             editor->confirmComposition(String(text));
2225         else
2226             editor->confirmComposition();
2227     } else
2228         editor->insertText(String(text), 0);
2229
2230     return true;
2231 }
2232
2233 bool WebViewImpl::compositionRange(size_t* location, size_t* length)
2234 {
2235     Frame* focused = focusedWebCoreFrame();
2236     if (!focused || !focused->selection() || !m_imeAcceptEvents)
2237         return false;
2238     Editor* editor = focused->editor();
2239     if (!editor || !editor->hasComposition())
2240         return false;
2241
2242     RefPtr<Range> range = editor->compositionRange();
2243     if (!range)
2244         return false;
2245
2246     if (TextIterator::getLocationAndLengthFromRange(focused->selection()->rootEditableElementOrDocumentElement(), range.get(), *location, *length))
2247         return true;
2248     return false;
2249 }
2250
2251 WebTextInputInfo WebViewImpl::textInputInfo()
2252 {
2253     WebTextInputInfo info;
2254
2255     Frame* focused = focusedWebCoreFrame();
2256     if (!focused)
2257         return info;
2258
2259     FrameSelection* selection = focused->selection();
2260     if (!selection)
2261         return info;
2262
2263     Node* node = selection->selection().rootEditableElement();
2264     if (!node)
2265         return info;
2266
2267     info.type = textInputType();
2268     if (info.type == WebTextInputTypeNone)
2269         return info;
2270
2271     Editor* editor = focused->editor();
2272     if (!editor || !editor->canEdit())
2273         return info;
2274
2275     info.value = plainText(rangeOfContents(node).get());
2276
2277     if (info.value.isEmpty())
2278         return info;
2279
2280     size_t location;
2281     size_t length;
2282     RefPtr<Range> range = selection->selection().firstRange();
2283     if (range && TextIterator::getLocationAndLengthFromRange(selection->rootEditableElement(), range.get(), location, length)) {
2284         info.selectionStart = location;
2285         info.selectionEnd = location + length;
2286     }
2287     range = editor->compositionRange();
2288     if (range && TextIterator::getLocationAndLengthFromRange(selection->rootEditableElement(), range.get(), location, length)) {
2289         info.compositionStart = location;
2290         info.compositionEnd = location + length;
2291     }
2292
2293     return info;
2294 }
2295
2296 WebTextInputType WebViewImpl::textInputType()
2297 {
2298     Node* node = focusedWebCoreNode();
2299     if (!node)
2300         return WebTextInputTypeNone;
2301
2302     if (node->hasTagName(HTMLNames::inputTag)) {
2303         HTMLInputElement* input = static_cast<HTMLInputElement*>(node);
2304
2305         if (input->isDisabledOrReadOnly())
2306             return WebTextInputTypeNone;
2307
2308         if (input->isPasswordField())
2309             return WebTextInputTypePassword;
2310         if (input->isSearchField())
2311             return WebTextInputTypeSearch;
2312         if (input->isEmailField())
2313             return WebTextInputTypeEmail;
2314         if (input->isNumberField())
2315             return WebTextInputTypeNumber;
2316         if (input->isTelephoneField())
2317             return WebTextInputTypeTelephone;
2318         if (input->isURLField())
2319             return WebTextInputTypeURL;
2320         if (input->isDateField())
2321             return WebTextInputTypeDate;
2322         if (input->isDateTimeField())
2323             return WebTextInputTypeDateTime;
2324         if (input->isDateTimeLocalField())
2325             return WebTextInputTypeDateTimeLocal;
2326         if (input->isMonthField())
2327             return WebTextInputTypeMonth;
2328         if (input->isTimeField())
2329             return WebTextInputTypeTime;
2330         if (input->isWeekField())
2331             return WebTextInputTypeWeek;
2332         if (input->isTextField())
2333             return WebTextInputTypeText;
2334
2335         return WebTextInputTypeNone;
2336     }
2337
2338     if (node->hasTagName(HTMLNames::textareaTag)) {
2339         if (static_cast<HTMLTextAreaElement*>(node)->isDisabledOrReadOnly())
2340             return WebTextInputTypeNone;
2341         return WebTextInputTypeTextArea;
2342     }
2343
2344 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
2345     if (node->isHTMLElement()) {
2346         HTMLElement* element = toHTMLElement(node);
2347         if (element->isDateTimeFieldElement())
2348             return WebTextInputTypeDateTimeField;
2349     }
2350 #endif
2351
2352     if (node->shouldUseInputMethod())
2353         return WebTextInputTypeContentEditable;
2354
2355     return WebTextInputTypeNone;
2356 }
2357
2358 bool WebViewImpl::selectionBounds(WebRect& anchor, WebRect& focus) const
2359 {
2360     const Frame* frame = focusedWebCoreFrame();
2361     if (!frame)
2362         return false;
2363     FrameSelection* selection = frame->selection();
2364     if (!selection)
2365         return false;
2366
2367     if (selection->isCaret())
2368         anchor = focus = selection->absoluteCaretBounds();
2369     else {
2370         RefPtr<Range> selectedRange = frame->selection()->toNormalizedRange();
2371         if (!selectedRange)
2372             return false;
2373
2374         RefPtr<Range> range(Range::create(selectedRange->startContainer()->document(),
2375             selectedRange->startContainer(),
2376             selectedRange->startOffset(),
2377             selectedRange->startContainer(),
2378             selectedRange->startOffset()));
2379         anchor = frame->editor()->firstRectForRange(range.get());
2380
2381         range = Range::create(selectedRange->endContainer()->document(),
2382             selectedRange->endContainer(),
2383             selectedRange->endOffset(),
2384             selectedRange->endContainer(),
2385             selectedRange->endOffset());
2386         focus = frame->editor()->firstRectForRange(range.get());
2387     }
2388
2389     IntRect scaledAnchor(frame->view()->contentsToWindow(anchor));
2390     IntRect scaledFocus(frame->view()->contentsToWindow(focus));
2391     if (m_webSettings->applyPageScaleFactorInCompositor()) {
2392         scaledAnchor.scale(pageScaleFactor());
2393         scaledFocus.scale(pageScaleFactor());
2394     }
2395     anchor = scaledAnchor;
2396     focus = scaledFocus;
2397
2398     if (!frame->selection()->selection().isBaseFirst())
2399         std::swap(anchor, focus);
2400     return true;
2401 }
2402
2403 bool WebViewImpl::selectionTextDirection(WebTextDirection& start, WebTextDirection& end) const
2404 {
2405     const Frame* frame = focusedWebCoreFrame();
2406     if (!frame)
2407         return false;
2408     FrameSelection* selection = frame->selection();
2409     if (!selection)
2410         return false;
2411     if (!selection->toNormalizedRange())
2412         return false;
2413     start = selection->start().primaryDirection() == RTL ? WebTextDirectionRightToLeft : WebTextDirectionLeftToRight;
2414     end = selection->end().primaryDirection() == RTL ? WebTextDirectionRightToLeft : WebTextDirectionLeftToRight;
2415     return true;
2416 }
2417
2418 bool WebViewImpl::isSelectionAnchorFirst() const
2419 {
2420     const Frame* frame = focusedWebCoreFrame();
2421     if (!frame)
2422         return false;
2423     FrameSelection* selection = frame->selection();
2424     if (!selection)
2425         return false;
2426     return selection->selection().isBaseFirst();
2427 }
2428
2429 bool WebViewImpl::setEditableSelectionOffsets(int start, int end)
2430 {
2431     const Frame* focused = focusedWebCoreFrame();
2432     if (!focused)
2433         return false;
2434
2435     Editor* editor = focused->editor();
2436     if (!editor || !editor->canEdit())
2437         return false;
2438
2439     return editor->setSelectionOffsets(start, end);
2440 }
2441
2442 bool WebViewImpl::setCompositionFromExistingText(int compositionStart, int compositionEnd, const WebVector<WebCompositionUnderline>& underlines)
2443 {
2444     const Frame* focused = focusedWebCoreFrame();
2445     if (!focused)
2446         return false;
2447
2448     Editor* editor = focused->editor();
2449     if (!editor || !editor->canEdit())
2450         return false;
2451
2452     editor->cancelComposition();
2453
2454     if (compositionStart == compositionEnd)
2455         return true;
2456
2457     size_t location;
2458     size_t length;
2459     caretOrSelectionRange(&location, &length);
2460     editor->setIgnoreCompositionSelectionChange(true);
2461     editor->setSelectionOffsets(compositionStart, compositionEnd);
2462     String text = editor->selectedText();
2463     focused->document()->execCommand("delete", true);
2464     editor->setComposition(text, CompositionUnderlineVectorBuilder(underlines), 0, 0);
2465     // Need to set setIgnoreCompositionSelectionChange(true) again because setComposition resets it to false.
2466     editor->setIgnoreCompositionSelectionChange(true);
2467     editor->setSelectionOffsets(location, location + length);
2468     editor->setIgnoreCompositionSelectionChange(false);
2469
2470     return true;
2471 }
2472
2473 void WebViewImpl::extendSelectionAndDelete(int before, int after)
2474 {
2475     const Frame* focused = focusedWebCoreFrame();
2476     if (!focused)
2477         return;
2478
2479     Editor* editor = focused->editor();
2480     if (!editor || !editor->canEdit())
2481         return;
2482
2483     FrameSelection* selection = focused->selection();
2484     if (!selection)
2485         return;
2486
2487     size_t location;
2488     size_t length;
2489     RefPtr<Range> range = selection->selection().firstRange();
2490     if (range && TextIterator::getLocationAndLengthFromRange(selection->rootEditableElement(), range.get(), location, length)) {
2491         editor->setSelectionOffsets(max(static_cast<int>(location) - before, 0), location + length + after);
2492         focused->document()->execCommand("delete", true);
2493     }
2494 }
2495
2496 bool WebViewImpl::isSelectionEditable() const
2497 {
2498     const Frame* frame = focusedWebCoreFrame();
2499     if (!frame)
2500         return false;
2501     return frame->selection()->isContentEditable();
2502 }
2503
2504 WebColor WebViewImpl::backgroundColor() const
2505 {
2506     if (!m_page)
2507         return Color::white;
2508     FrameView* view = m_page->mainFrame()->view();
2509     Color backgroundColor = view->documentBackgroundColor();
2510     if (!backgroundColor.isValid())
2511         return Color::white;
2512     return backgroundColor.rgb();
2513 }
2514
2515 bool WebViewImpl::caretOrSelectionRange(size_t* location, size_t* length)
2516 {
2517     const Frame* focused = focusedWebCoreFrame();
2518     if (!focused)
2519         return false;
2520
2521     FrameSelection* selection = focused->selection();
2522     if (!selection)
2523         return false;
2524
2525     RefPtr<Range> range = selection->selection().firstRange();
2526     if (!range)
2527         return false;
2528
2529     if (TextIterator::getLocationAndLengthFromRange(selection->rootEditableElementOrTreeScopeRootNode(), range.get(), *location, *length))
2530         return true;
2531     return false;
2532 }
2533
2534 void WebViewImpl::setTextDirection(WebTextDirection direction)
2535 {
2536     // The Editor::setBaseWritingDirection() function checks if we can change
2537     // the text direction of the selected node and updates its DOM "dir"
2538     // attribute and its CSS "direction" property.
2539     // So, we just call the function as Safari does.
2540     const Frame* focused = focusedWebCoreFrame();
2541     if (!focused)
2542         return;
2543
2544     Editor* editor = focused->editor();
2545     if (!editor || !editor->canEdit())
2546         return;
2547
2548     switch (direction) {
2549     case WebTextDirectionDefault:
2550         editor->setBaseWritingDirection(NaturalWritingDirection);
2551         break;
2552
2553     case WebTextDirectionLeftToRight:
2554         editor->setBaseWritingDirection(LeftToRightWritingDirection);
2555         break;
2556
2557     case WebTextDirectionRightToLeft:
2558         editor->setBaseWritingDirection(RightToLeftWritingDirection);
2559         break;
2560
2561     default:
2562         notImplemented();
2563         break;
2564     }
2565 }
2566
2567 bool WebViewImpl::isAcceleratedCompositingActive() const
2568 {
2569 #if USE(ACCELERATED_COMPOSITING)
2570     return m_isAcceleratedCompositingActive;
2571 #else
2572     return false;
2573 #endif
2574 }
2575
2576 void WebViewImpl::willCloseLayerTreeView()
2577 {
2578     setIsAcceleratedCompositingActive(false);
2579     m_layerTreeView = 0;
2580 }
2581
2582 void WebViewImpl::didAcquirePointerLock()
2583 {
2584 #if ENABLE(POINTER_LOCK)
2585     if (page())
2586         page()->pointerLockController()->didAcquirePointerLock();
2587 #endif
2588 }
2589
2590 void WebViewImpl::didNotAcquirePointerLock()
2591 {
2592 #if ENABLE(POINTER_LOCK)
2593     if (page())
2594         page()->pointerLockController()->didNotAcquirePointerLock();
2595 #endif
2596 }
2597
2598 void WebViewImpl::didLosePointerLock()
2599 {
2600 #if ENABLE(POINTER_LOCK)
2601     if (page())
2602         page()->pointerLockController()->didLosePointerLock();
2603 #endif
2604 }
2605
2606 void WebViewImpl::didChangeWindowResizerRect()
2607 {
2608     if (mainFrameImpl()->frameView())
2609         mainFrameImpl()->frameView()->windowResizerRectChanged();
2610 }
2611
2612 // WebView --------------------------------------------------------------------
2613
2614 WebSettingsImpl* WebViewImpl::settingsImpl()
2615 {
2616     if (!m_webSettings)
2617         m_webSettings = adoptPtr(new WebSettingsImpl(m_page->settings()));
2618     ASSERT(m_webSettings);
2619     return m_webSettings.get();
2620 }
2621
2622 WebSettings* WebViewImpl::settings()
2623 {
2624     return settingsImpl();
2625 }
2626
2627 WebString WebViewImpl::pageEncoding() const
2628 {
2629     if (!m_page)
2630         return WebString();
2631
2632     // FIXME: Is this check needed?
2633     if (!m_page->mainFrame()->document()->loader())
2634         return WebString();
2635
2636     return m_page->mainFrame()->document()->encoding();
2637 }
2638
2639 void WebViewImpl::setPageEncoding(const WebString& encodingName)
2640 {
2641     if (!m_page)
2642         return;
2643
2644     // Only change override encoding, don't change default encoding.
2645     // Note that the new encoding must be 0 if it isn't supposed to be set.
2646     String newEncodingName;
2647     if (!encodingName.isEmpty())
2648         newEncodingName = encodingName;
2649     m_page->mainFrame()->loader()->reloadWithOverrideEncoding(newEncodingName);
2650 }
2651
2652 bool WebViewImpl::dispatchBeforeUnloadEvent()
2653 {
2654     // FIXME: This should really cause a recursive depth-first walk of all
2655     // frames in the tree, calling each frame's onbeforeunload.  At the moment,
2656     // we're consistent with Safari 3.1, not IE/FF.
2657     Frame* frame = m_page->mainFrame();
2658     if (!frame)
2659         return true;
2660
2661     return frame->loader()->shouldClose();
2662 }
2663
2664 void WebViewImpl::dispatchUnloadEvent()
2665 {
2666     // Run unload handlers.
2667     m_page->mainFrame()->loader()->closeURL();
2668 }
2669
2670 WebFrame* WebViewImpl::mainFrame()
2671 {
2672     return mainFrameImpl();
2673 }
2674
2675 WebFrame* WebViewImpl::findFrameByName(
2676     const WebString& name, WebFrame* relativeToFrame)
2677 {
2678     if (!relativeToFrame)
2679         relativeToFrame = mainFrame();
2680     Frame* frame = static_cast<WebFrameImpl*>(relativeToFrame)->frame();
2681     frame = frame->tree()->find(name);
2682     return WebFrameImpl::fromFrame(frame);
2683 }
2684
2685 WebFrame* WebViewImpl::focusedFrame()
2686 {
2687     return WebFrameImpl::fromFrame(focusedWebCoreFrame());
2688 }
2689
2690 void WebViewImpl::setFocusedFrame(WebFrame* frame)
2691 {
2692     if (!frame) {
2693         // Clears the focused frame if any.
2694         Frame* frame = focusedWebCoreFrame();
2695         if (frame)
2696             frame->selection()->setFocused(false);
2697         return;
2698     }
2699     WebFrameImpl* frameImpl = static_cast<WebFrameImpl*>(frame);
2700     Frame* webcoreFrame = frameImpl->frame();
2701     webcoreFrame->page()->focusController()->setFocusedFrame(webcoreFrame);
2702 }
2703
2704 void WebViewImpl::setInitialFocus(bool reverse)
2705 {
2706     if (!m_page)
2707         return;
2708
2709     // Since we don't have a keyboard event, we'll create one.
2710     WebKeyboardEvent keyboardEvent;
2711     keyboardEvent.type = WebInputEvent::RawKeyDown;
2712     if (reverse)
2713         keyboardEvent.modifiers = WebInputEvent::ShiftKey;
2714
2715     // VK_TAB which is only defined on Windows.
2716     keyboardEvent.windowsKeyCode = 0x09;
2717     PlatformKeyboardEventBuilder platformEvent(keyboardEvent);
2718     RefPtr<KeyboardEvent> webkitEvent = KeyboardEvent::create(platformEvent, 0);
2719
2720     Frame* frame = page()->focusController()->focusedOrMainFrame();
2721     if (Document* document = frame->document())
2722         document->setFocusedNode(0);
2723     page()->focusController()->setInitialFocus(
2724         reverse ? FocusDirectionBackward : FocusDirectionForward,
2725         webkitEvent.get());
2726 }
2727
2728 void WebViewImpl::clearFocusedNode()
2729 {
2730     RefPtr<Frame> frame = focusedWebCoreFrame();
2731     if (!frame)
2732         return;
2733
2734     RefPtr<Document> document = frame->document();
2735     if (!document)
2736         return;
2737
2738     RefPtr<Node> oldFocusedNode = document->focusedNode();
2739
2740     // Clear the focused node.
2741     document->setFocusedNode(0);
2742
2743     if (!oldFocusedNode)
2744         return;
2745
2746     // If a text field has focus, we need to make sure the selection controller
2747     // knows to remove selection from it. Otherwise, the text field is still
2748     // processing keyboard events even though focus has been moved to the page and
2749     // keystrokes get eaten as a result.
2750     if (oldFocusedNode->isContentEditable()
2751         || (oldFocusedNode->isElementNode()
2752             && static_cast<Element*>(oldFocusedNode.get())->isTextFormControl())) {
2753         frame->selection()->clear();
2754     }
2755 }
2756
2757 void WebViewImpl::scrollFocusedNodeIntoView()
2758 {
2759     Node* focusedNode = focusedWebCoreNode();
2760     if (focusedNode && focusedNode->isElementNode()) {
2761         Element* elementNode = static_cast<Element*>(focusedNode);
2762         elementNode->scrollIntoViewIfNeeded(true);
2763     }
2764 }
2765
2766 void WebViewImpl::scrollFocusedNodeIntoRect(const WebRect& rect)
2767 {
2768     Frame* frame = page()->mainFrame();
2769     Node* focusedNode = focusedWebCoreNode();
2770     if (!frame || !frame->view() || !focusedNode || !focusedNode->isElementNode())
2771         return;
2772
2773     if (!m_webSettings->autoZoomFocusedNodeToLegibleScale()) {
2774         Element* elementNode = static_cast<Element*>(focusedNode);
2775         frame->view()->scrollElementToRect(elementNode, IntRect(rect.x, rect.y, rect.width, rect.height));
2776         return;
2777     }
2778
2779 #if ENABLE(GESTURE_EVENTS)
2780     float scale;
2781     IntPoint scroll;
2782     bool needAnimation;
2783     computeScaleAndScrollForFocusedNode(focusedNode, scale, scroll, needAnimation);
2784     if (needAnimation)
2785         startPageScaleAnimation(scroll, false, scale, scrollAndScaleAnimationDurationInSeconds);
2786 #endif
2787 }
2788
2789 #if ENABLE(GESTURE_EVENTS)
2790 void WebViewImpl::computeScaleAndScrollForFocusedNode(Node* focusedNode, float& newScale, IntPoint& newScroll, bool& needAnimation)
2791 {
2792     focusedNode->document()->updateLayoutIgnorePendingStylesheets();
2793
2794     // 'caret' is rect encompassing the blinking cursor.
2795     IntRect textboxRect = focusedNode->document()->view()->contentsToWindow(pixelSnappedIntRect(focusedNode->Node::boundingBox()));
2796     WebRect caret, unusedEnd;
2797     selectionBounds(caret, unusedEnd);
2798     if (settingsImpl()->applyPageScaleFactorInCompositor()) {
2799         IntRect unscaledCaret = caret;
2800         unscaledCaret.scale(1 / pageScaleFactor());
2801         caret = unscaledCaret;
2802     }
2803
2804     // Pick a scale which is reasonably readable. This is the scale at which
2805     // the caret height will become minReadableCaretHeight (adjusted for dpi
2806     // and font scale factor).
2807     float targetScale = settingsImpl()->applyDeviceScaleFactorInCompositor() ? 1 : deviceScaleFactor();
2808 #if ENABLE(TEXT_AUTOSIZING)
2809     if (page() && page()->settings())
2810         targetScale *= page()->settings()->textAutosizingFontScaleFactor();
2811 #endif
2812     const float caretHeight = settingsImpl()->applyPageScaleFactorInCompositor() ? caret.height : caret.height / pageScaleFactor();
2813     newScale = clampPageScaleFactorToLimits(minReadableCaretHeight * targetScale / caretHeight);
2814     const float deltaScale = newScale / pageScaleFactor();
2815
2816     // Convert the rects to absolute space in the new scale.
2817     IntRect textboxRectInDocumentCoordinates = textboxRect;
2818     textboxRectInDocumentCoordinates.move(mainFrame()->scrollOffset());
2819     IntRect caretInDocumentCoordinates = caret;
2820     caretInDocumentCoordinates.move(mainFrame()->scrollOffset());
2821
2822     int viewWidth = m_size.width;
2823     int viewHeight = m_size.height;
2824     if (settingsImpl()->applyPageScaleFactorInCompositor()) {
2825         viewWidth /= newScale;
2826         viewHeight /= newScale;
2827     } else {
2828         textboxRectInDocumentCoordinates.scale(deltaScale);
2829         caretInDocumentCoordinates.scale(deltaScale);
2830     }
2831
2832     if (textboxRectInDocumentCoordinates.width() <= viewWidth) {
2833         // Field is narrower than screen. Try to leave padding on left so field's
2834         // label is visible, but it's more important to ensure entire field is
2835         // onscreen.
2836         int idealLeftPadding = viewWidth * leftBoxRatio;
2837         int maxLeftPaddingKeepingBoxOnscreen = viewWidth - textboxRectInDocumentCoordinates.width();
2838         newScroll.setX(textboxRectInDocumentCoordinates.x() - min<int>(idealLeftPadding, maxLeftPaddingKeepingBoxOnscreen));
2839     } else {
2840         // Field is wider than screen. Try to left-align field, unless caret would
2841         // be offscreen, in which case right-align the caret.
2842         newScroll.setX(max<int>(textboxRectInDocumentCoordinates.x(), caretInDocumentCoordinates.x() + caretInDocumentCoordinates.width() + caretPadding - viewWidth));
2843     }
2844     if (textboxRectInDocumentCoordinates.height() <= viewHeight) {
2845         // Field is shorter than screen. Vertically center it.
2846         newScroll.setY(textboxRectInDocumentCoordinates.y() - (viewHeight - textboxRectInDocumentCoordinates.height()) / 2);
2847     } else {
2848         // Field is taller than screen. Try to top align field, unless caret would
2849         // be offscreen, in which case bottom-align the caret.
2850         newScroll.setY(max<int>(textboxRectInDocumentCoordinates.y(), caretInDocumentCoordinates.y() + caretInDocumentCoordinates.height() + caretPadding - viewHeight));
2851     }
2852
2853     needAnimation = false;
2854     // If we are at less than the target zoom level, zoom in.
2855     if (deltaScale > minScaleChangeToTriggerZoom)
2856         needAnimation = true;
2857     // If the caret is offscreen, then animate.
2858     IntRect sizeRect(0, 0, viewWidth, viewHeight);
2859     if (!sizeRect.contains(caret))
2860         needAnimation = true;
2861     // If the box is partially offscreen and it's possible to bring it fully
2862     // onscreen, then animate.
2863     if (sizeRect.contains(textboxRectInDocumentCoordinates.width(), textboxRectInDocumentCoordinates.height()) && !sizeRect.contains(textboxRect))
2864         needAnimation = true;
2865 }
2866 #endif
2867
2868 void WebViewImpl::advanceFocus(bool reverse)
2869 {
2870     page()->focusController()->advanceFocus(reverse ? FocusDirectionBackward : FocusDirectionForward, 0);
2871 }
2872
2873 double WebViewImpl::zoomLevel()
2874 {
2875     return m_zoomLevel;
2876 }
2877
2878 double WebViewImpl::setZoomLevel(bool textOnly, double zoomLevel)
2879 {
2880     if (zoomLevel < m_minimumZoomLevel)
2881         m_zoomLevel = m_minimumZoomLevel;
2882     else if (zoomLevel > m_maximumZoomLevel)
2883         m_zoomLevel = m_maximumZoomLevel;
2884     else
2885         m_zoomLevel = zoomLevel;
2886
2887     Frame* frame = mainFrameImpl()->frame();
2888     WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
2889     if (pluginContainer)
2890         pluginContainer->plugin()->setZoomLevel(m_zoomLevel, textOnly);
2891     else {
2892         float zoomFactor = static_cast<float>(zoomLevelToZoomFactor(m_zoomLevel));
2893         if (textOnly)
2894             frame->setPageAndTextZoomFactors(1, zoomFactor * m_emulatedTextZoomFactor);
2895         else
2896             frame->setPageAndTextZoomFactors(zoomFactor, m_emulatedTextZoomFactor);
2897     }
2898     return m_zoomLevel;
2899 }
2900
2901 void WebViewImpl::zoomLimitsChanged(double minimumZoomLevel,
2902                                     double maximumZoomLevel)
2903 {
2904     m_minimumZoomLevel = minimumZoomLevel;
2905     m_maximumZoomLevel = maximumZoomLevel;
2906     m_client->zoomLimitsChanged(m_minimumZoomLevel, m_maximumZoomLevel);
2907 }
2908
2909 void WebViewImpl::fullFramePluginZoomLevelChanged(double zoomLevel)
2910 {
2911     if (zoomLevel == m_zoomLevel)
2912         return;
2913
2914     m_zoomLevel = max(min(zoomLevel, m_maximumZoomLevel), m_minimumZoomLevel);
2915     m_client->zoomLevelChanged();
2916 }
2917
2918 double WebView::zoomLevelToZoomFactor(double zoomLevel)
2919 {
2920     return pow(textSizeMultiplierRatio, zoomLevel);
2921 }
2922
2923 double WebView::zoomFactorToZoomLevel(double factor)
2924 {
2925     // Since factor = 1.2^level, level = log(factor) / log(1.2)
2926     return log(factor) / log(textSizeMultiplierRatio);
2927 }
2928
2929 void WebViewImpl::setInitialPageScaleOverride(float initialPageScaleFactorOverride)
2930 {
2931     if (m_initialPageScaleFactorOverride == initialPageScaleFactorOverride)
2932         return;
2933     m_initialPageScaleFactorOverride = initialPageScaleFactorOverride;
2934     m_pageScaleFactorIsSet = false;
2935     computePageScaleFactorLimits();
2936 }
2937
2938 float WebViewImpl::pageScaleFactor() const
2939 {
2940     if (!page())
2941         return 1;
2942
2943     return page()->pageScaleFactor();
2944 }
2945
2946 bool WebViewImpl::isPageScaleFactorSet() const
2947 {
2948     return m_pageScaleFactorIsSet;
2949 }
2950
2951 float WebViewImpl::clampPageScaleFactorToLimits(float scaleFactor)
2952 {
2953     return min(max(scaleFactor, m_minimumPageScaleFactor), m_maximumPageScaleFactor);
2954 }
2955
2956 IntPoint WebViewImpl::clampOffsetAtScale(const IntPoint& offset, float scale) const
2957 {
2958     IntPoint clampedOffset = offset;
2959     if (!m_page->settings()->applyPageScaleFactorInCompositor()) {
2960         // This is the scaled content size. We need to convert it to the new scale factor.
2961         WebSize contentSize = contentsSize();
2962         int docWidthAtNewScale = contentSize.width * scale;
2963         int docHeightAtNewScale = contentSize.height * scale;
2964         int viewWidth = m_size.width;
2965         int viewHeight = m_size.height;
2966
2967         // Enforce the maximum and minimum scroll positions at the new scale.
2968         clampedOffset = clampedOffset.shrunkTo(IntPoint(docWidthAtNewScale - viewWidth, docHeightAtNewScale - viewHeight));
2969         clampedOffset.clampNegativeToZero();
2970     } else {
2971         clampedOffset = clampedOffset.shrunkTo(IntPoint(contentsSize() - scaledSize(scale)));
2972         clampedOffset.clampNegativeToZero();
2973     }
2974
2975     return clampedOffset;
2976 }
2977
2978 void WebViewImpl::setPageScaleFactorPreservingScrollOffset(float scaleFactor)
2979 {
2980     scaleFactor = clampPageScaleFactorToLimits(scaleFactor);
2981
2982     IntPoint scrollOffset(mainFrame()->scrollOffset().width, mainFrame()->scrollOffset().height);
2983     if (!m_page->settings()->applyPageScaleFactorInCompositor()) {
2984         float deltaScale = scaleFactor / pageScaleFactor();
2985         scrollOffset.scale(deltaScale, deltaScale);
2986     }
2987     scrollOffset = clampOffsetAtScale(scrollOffset, scaleFactor);
2988
2989     setPageScaleFactor(scaleFactor, scrollOffset);
2990 }
2991
2992 void WebViewImpl::setPageScaleFactor(float scaleFactor, const WebPoint& origin)
2993 {
2994     if (!page())
2995         return;
2996
2997     if (!scaleFactor)
2998         scaleFactor = 1;
2999
3000     IntPoint scrollOffset = origin;
3001     scaleFactor = clampPageScaleFactorToLimits(scaleFactor);
3002     scrollOffset = clampOffsetAtScale(scrollOffset, scaleFactor);
3003
3004     page()->setPageScaleFactor(scaleFactor, IntPoint(scrollOffset));
3005
3006     m_pageScaleFactorIsSet = true;
3007
3008 #if USE(ACCELERATED_COMPOSITING)
3009     updateLayerTreeViewport();
3010 #endif
3011 }
3012
3013 float WebViewImpl::deviceScaleFactor() const
3014 {
3015     if (!page())
3016         return 1;
3017
3018     return page()->deviceScaleFactor();
3019 }
3020
3021 void WebViewImpl::setDeviceScaleFactor(float scaleFactor)
3022 {
3023     if (!page())
3024         return;
3025
3026     page()->setDeviceScaleFactor(scaleFactor);
3027
3028     if (m_layerTreeView && m_webSettings->applyDeviceScaleFactorInCompositor())
3029         m_layerTreeView->setDeviceScaleFactor(scaleFactor);
3030 }
3031
3032 bool WebViewImpl::isFixedLayoutModeEnabled() const
3033 {
3034     if (!page())
3035         return false;
3036
3037     Frame* frame = page()->mainFrame();
3038     if (!frame || !frame->view())
3039         return false;
3040
3041     return frame->view()->useFixedLayout();
3042 }
3043
3044 void WebViewImpl::enableFixedLayoutMode(bool enable)
3045 {
3046     if (!page())
3047         return;
3048
3049     Frame* frame = page()->mainFrame();
3050     if (!frame || !frame->view())
3051         return;
3052
3053     frame->view()->setUseFixedLayout(enable);
3054
3055 #if USE(ACCELERATED_COMPOSITING)
3056     // Also notify the base layer, which RenderLayerCompositor does not see.
3057     if (m_nonCompositedContentHost)
3058         updateLayerTreeViewport();
3059 #endif
3060 }
3061
3062
3063 void WebViewImpl::enableAutoResizeMode(const WebSize& minSize, const WebSize& maxSize)
3064 {
3065     m_shouldAutoResize = true;
3066     m_minAutoSize = minSize;
3067     m_maxAutoSize = maxSize;
3068     configureAutoResizeMode();
3069 }
3070
3071 void WebViewImpl::disableAutoResizeMode()
3072 {
3073     m_shouldAutoResize = false;
3074     configureAutoResizeMode();
3075 }
3076
3077 void WebViewImpl::setPageScaleFactorLimits(float minPageScale, float maxPageScale)
3078 {
3079     if (minPageScale == m_pageDefinedMinimumPageScaleFactor && maxPageScale == m_pageDefinedMaximumPageScaleFactor)
3080         return;
3081
3082     m_pageDefinedMinimumPageScaleFactor = minPageScale;
3083     m_pageDefinedMaximumPageScaleFactor = maxPageScale;
3084
3085     if (settings()->viewportEnabled()) {
3086         // If we're in viewport tag mode, we need to layout to obtain the latest
3087         // contents size and compute the final limits.
3088         FrameView* view = mainFrameImpl()->frameView();
3089         if (view)
3090             view->setNeedsLayout();
3091     } else {
3092         // Otherwise just compute the limits immediately.
3093         computePageScaleFactorLimits();
3094     }
3095 }
3096
3097 void WebViewImpl::setIgnoreViewportTagMaximumScale(bool flag)
3098 {
3099     m_ignoreViewportTagMaximumScale = flag;
3100
3101     if (!page() || !page()->mainFrame())
3102         return;
3103
3104     m_page->chrome()->client()->dispatchViewportPropertiesDidChange(page()->mainFrame()->document()->viewportArguments());
3105 }
3106
3107 IntSize WebViewImpl::contentsSize() const
3108 {
3109     Frame* frame = page()->mainFrame();
3110     RenderView* root = frame->contentRenderer();
3111     if (!root)
3112         return IntSize();
3113
3114     // If page scale is not applied by compositor, then the CSS transform will
3115     // scale by an arbitrary amount. Return the unscaled contents size in this
3116     // case.
3117     if (!m_page->settings()->applyPageScaleFactorInCompositor())
3118         return root->unscaledDocumentRect().size();
3119
3120     return root->documentRect().size();
3121 }
3122
3123 void WebViewImpl::computePageScaleFactorLimits()
3124 {
3125     if (!mainFrame() || !page() || !page()->mainFrame() || !page()->mainFrame()->view())
3126         return;
3127
3128     FrameView* view = page()->mainFrame()->view();
3129
3130     if (m_pageDefinedMinimumPageScaleFactor == -1 || m_pageDefinedMaximumPageScaleFactor == -1) {
3131         m_minimumPageScaleFactor = minPageScaleFactor;
3132         m_maximumPageScaleFactor = maxPageScaleFactor;
3133     } else {
3134         m_minimumPageScaleFactor = min(max(m_pageDefinedMinimumPageScaleFactor, minPageScaleFactor), maxPageScaleFactor);
3135         m_maximumPageScaleFactor = max(min(m_pageDefinedMaximumPageScaleFactor, maxPageScaleFactor), minPageScaleFactor);
3136     }
3137
3138     if (settings()->viewportEnabled()) {
3139         if (!contentsSize().width() || !m_size.width)
3140             return;
3141
3142         // When viewport tag is enabled, the scale needed to see the full
3143         // content width is the default minimum.
3144         int viewWidthNotIncludingScrollbars = m_size.width;
3145         if (view->verticalScrollbar() && !view->verticalScrollbar()->isOverlayScrollbar())
3146             viewWidthNotIncludingScrollbars -= view->verticalScrollbar()->width();
3147         m_minimumPageScaleFactor = max(m_minimumPageScaleFactor, static_cast<float>(viewWidthNotIncludingScrollbars) / contentsSize().width());
3148         m_maximumPageScaleFactor = max(m_minimumPageScaleFactor, m_maximumPageScaleFactor);
3149     }
3150     ASSERT(m_minimumPageScaleFactor <= m_maximumPageScaleFactor);
3151
3152     // Initialize and/or clamp the page scale factor if needed.
3153     float initialPageScaleFactor = m_initialPageScaleFactor;
3154     if (!settings()->viewportEnabled())
3155         initialPageScaleFactor = 1;
3156     if (m_initialPageScaleFactorOverride != -1)
3157         initialPageScaleFactor = m_initialPageScaleFactorOverride;
3158     float newPageScaleFactor = pageScaleFactor();
3159     if (!m_pageScaleFactorIsSet && initialPageScaleFactor != -1) {
3160         newPageScaleFactor = initialPageScaleFactor;
3161         m_pageScaleFactorIsSet = true;
3162     }
3163     newPageScaleFactor = clampPageScaleFactorToLimits(newPageScaleFactor);
3164 #if USE(ACCELERATED_COMPOSITING)
3165     if (m_layerTreeView)
3166         m_layerTreeView->setPageScaleFactorAndLimits(newPageScaleFactor, m_minimumPageScaleFactor, m_maximumPageScaleFactor);
3167 #endif
3168     if (newPageScaleFactor != pageScaleFactor())
3169         setPageScaleFactorPreservingScrollOffset(newPageScaleFactor);
3170 }
3171
3172 float WebViewImpl::minimumPageScaleFactor() const
3173 {
3174     return m_minimumPageScaleFactor;
3175 }
3176
3177 float WebViewImpl::maximumPageScaleFactor() const
3178 {
3179     return m_maximumPageScaleFactor;
3180 }
3181
3182 void WebViewImpl::saveScrollAndScaleState()
3183 {
3184     m_savedPageScaleFactor = pageScaleFactor();
3185     m_savedScrollOffset = mainFrame()->scrollOffset();
3186 }
3187
3188 void WebViewImpl::restoreScrollAndScaleState()
3189 {
3190     if (!m_savedPageScaleFactor)
3191         return;
3192
3193 #if ENABLE(GESTURE_EVENTS)
3194     startPageScaleAnimation(IntPoint(m_savedScrollOffset), false, m_savedPageScaleFactor, scrollAndScaleAnimationDurationInSeconds);
3195 #else
3196     setPageScaleFactor(m_savedPageScaleFactor, WebPoint());
3197     mainFrame()->setScrollOffset(m_savedScrollOffset);
3198 #endif
3199
3200     resetSavedScrollAndScaleState();
3201 }
3202
3203 void WebViewImpl::resetSavedScrollAndScaleState()
3204 {
3205     m_savedPageScaleFactor = 0;
3206     m_savedScrollOffset = IntSize();
3207 }
3208
3209 void WebViewImpl::resetScrollAndScaleState()
3210 {
3211     page()->setPageScaleFactor(1, IntPoint());
3212
3213     // Clear out the values for the current history item. This will prevent the history item from clobbering the
3214     // value determined during page scale initialization, which may be less than 1.
3215     page()->mainFrame()->loader()->history()->saveDocumentAndScrollState();
3216     page()->mainFrame()->loader()->history()->clearScrollPositionAndViewState();
3217     m_pageScaleFactorIsSet = false;
3218
3219     // Clobber saved scales and scroll offsets.
3220     if (FrameView* view = page()->mainFrame()->document()->view())
3221         view->cacheCurrentScrollPosition();
3222     resetSavedScrollAndScaleState();
3223 }
3224
3225 WebSize WebViewImpl::fixedLayoutSize() const
3226 {
3227     if (!page())
3228         return WebSize();
3229
3230     Frame* frame = page()->mainFrame();
3231     if (!frame || !frame->view())
3232         return WebSize();
3233
3234     return frame->view()->fixedLayoutSize();
3235 }
3236
3237 void WebViewImpl::setFixedLayoutSize(const WebSize& layoutSize)
3238 {
3239     if (!page())
3240         return;
3241
3242     Frame* frame = page()->mainFrame();
3243     if (!frame || !frame->view())
3244         return;
3245
3246     frame->view()->setFixedLayoutSize(layoutSize);
3247 }
3248
3249 WebCore::IntSize WebViewImpl::dipSize() const
3250 {
3251     IntSize dipSize = m_size;
3252     if (!m_webSettings->applyDeviceScaleFactorInCompositor())
3253         dipSize.scale(1 / m_client->screenInfo().deviceScaleFactor);
3254     return dipSize;
3255 }
3256
3257 void WebViewImpl::performMediaPlayerAction(const WebMediaPlayerAction& action,
3258                                            const WebPoint& location)
3259 {
3260     HitTestResult result = hitTestResultForWindowPos(location);
3261     RefPtr<Node> node = result.innerNonSharedNode();
3262     if (!node->hasTagName(HTMLNames::videoTag) && !node->hasTagName(HTMLNames::audioTag))
3263         return;
3264
3265     RefPtr<HTMLMediaElement> mediaElement =
3266         static_pointer_cast<HTMLMediaElement>(node);
3267     switch (action.type) {
3268     case WebMediaPlayerAction::Play:
3269         if (action.enable)
3270             mediaElement->play();
3271         else
3272             mediaElement->pause();
3273         break;
3274     case WebMediaPlayerAction::Mute:
3275         mediaElement->setMuted(action.enable);
3276         break;
3277     case WebMediaPlayerAction::Loop:
3278         mediaElement->setLoop(action.enable);
3279         break;
3280     case WebMediaPlayerAction::Controls:
3281         mediaElement->setControls(action.enable);
3282         break;
3283     default:
3284         ASSERT_NOT_REACHED();
3285     }
3286 }
3287
3288 void WebViewImpl::performPluginAction(const WebPluginAction& action,
3289                                       const WebPoint& location)
3290 {
3291     HitTestResult result = hitTestResultForWindowPos(location);
3292     RefPtr<Node> node = result.innerNonSharedNode();
3293     if (!node->hasTagName(HTMLNames::objectTag) && !node->hasTagName(HTMLNames::embedTag))
3294         return;
3295
3296     RenderObject* object = node->renderer();
3297     if (object && object->isWidget()) {
3298         Widget* widget = toRenderWidget(object)->widget();
3299         if (widget && widget->isPluginContainer()) {
3300             WebPluginContainerImpl* plugin = static_cast<WebPluginContainerImpl*>(widget);
3301             switch (action.type) {
3302             case WebPluginAction::Rotate90Clockwise:
3303                 plugin->plugin()->rotateView(WebPlugin::RotationType90Clockwise);
3304                 break;
3305             case WebPluginAction::Rotate90Counterclockwise:
3306                 plugin->plugin()->rotateView(WebPlugin::RotationType90Counterclockwise);
3307                 break;
3308             default:
3309                 ASSERT_NOT_REACHED();
3310             }
3311         }
3312     }
3313 }
3314
3315 WebHitTestResult WebViewImpl::hitTestResultAt(const WebPoint& point)
3316 {
3317     return hitTestResultForWindowPos(point);
3318 }
3319
3320 void WebViewImpl::copyImageAt(const WebPoint& point)
3321 {
3322     if (!m_page)
3323         return;
3324
3325     HitTestResult result = hitTestResultForWindowPos(point);
3326
3327     if (result.absoluteImageURL().isEmpty()) {
3328         // There isn't actually an image at these coordinates.  Might be because
3329         // the window scrolled while the context menu was open or because the page
3330         // changed itself between when we thought there was an image here and when
3331         // we actually tried to retreive the image.
3332         //
3333         // FIXME: implement a cache of the most recent HitTestResult to avoid having
3334         //        to do two hit tests.
3335         return;
3336     }
3337
3338     m_page->mainFrame()->editor()->copyImage(result);
3339 }
3340
3341 void WebViewImpl::dragSourceEndedAt(
3342     const WebPoint& clientPoint,
3343     const WebPoint& screenPoint,
3344     WebDragOperation operation)
3345 {
3346     PlatformMouseEvent pme(clientPoint,
3347                            screenPoint,
3348                            LeftButton, PlatformEvent::MouseMoved, 0, false, false, false,
3349                            false, 0);
3350     m_page->mainFrame()->eventHandler()->dragSourceEndedAt(pme,
3351         static_cast<DragOperation>(operation));
3352 }
3353
3354 void WebViewImpl::dragSourceMovedTo(
3355     const WebPoint& clientPoint,
3356     const WebPoint& screenPoint,
3357     WebDragOperation operation)
3358 {
3359 }
3360
3361 void WebViewImpl::dragSourceSystemDragEnded()
3362 {
3363     // It's possible for us to get this callback while not doing a drag if
3364     // it's from a previous page that got unloaded.
3365     if (m_doingDragAndDrop) {
3366         m_page->dragController()->dragEnded();
3367         m_doingDragAndDrop = false;
3368     }
3369 }
3370
3371 WebDragOperation WebViewImpl::dragTargetDragEnter(
3372     const WebDragData& webDragData,
3373     const WebPoint& clientPoint,
3374     const WebPoint& screenPoint,
3375     WebDragOperationsMask operationsAllowed,
3376     int keyModifiers)
3377 {
3378     ASSERT(!m_currentDragData);
3379
3380     m_currentDragData = webDragData;
3381     m_operationsAllowed = operationsAllowed;
3382
3383     return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragEnter, keyModifiers);
3384 }
3385
3386 WebDragOperation WebViewImpl::dragTargetDragOver(
3387     const WebPoint& clientPoint,
3388     const WebPoint& screenPoint,
3389     WebDragOperationsMask operationsAllowed,
3390     int keyModifiers)
3391 {
3392     m_operationsAllowed = operationsAllowed;
3393
3394     return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragOver, keyModifiers);
3395 }
3396
3397 void WebViewImpl::dragTargetDragLeave()
3398 {
3399     ASSERT(m_currentDragData);
3400
3401     DragData dragData(
3402         m_currentDragData.get(),
3403         IntPoint(),
3404         IntPoint(),
3405         static_cast<DragOperation>(m_operationsAllowed));
3406
3407     m_page->dragController()->dragExited(&dragData);
3408
3409     // FIXME: why is the drag scroll timer not stopped here?
3410
3411     m_dragOperation = WebDragOperationNone;
3412     m_currentDragData = 0;
3413 }
3414
3415 void WebViewImpl::dragTargetDrop(const WebPoint& clientPoint,
3416                                  const WebPoint& screenPoint,
3417                                  int keyModifiers)
3418 {
3419     ASSERT(m_currentDragData);
3420
3421     // If this webview transitions from the "drop accepting" state to the "not
3422     // accepting" state, then our IPC message reply indicating that may be in-
3423     // flight, or else delayed by javascript processing in this webview.  If a
3424     // drop happens before our IPC reply has reached the browser process, then
3425     // the browser forwards the drop to this webview.  So only allow a drop to
3426     // proceed if our webview m_dragOperation state is not DragOperationNone.
3427
3428     if (m_dragOperation == WebDragOperationNone) { // IPC RACE CONDITION: do not allow this drop.
3429         dragTargetDragLeave();
3430         return;
3431     }
3432
3433     m_currentDragData->setModifierKeyState(webInputEventKeyStateToPlatformEventKeyState(keyModifiers));
3434     DragData dragData(
3435         m_currentDragData.get(),
3436         clientPoint,
3437         screenPoint,
3438         static_cast<DragOperation>(m_operationsAllowed));
3439
3440     m_page->dragController()->performDrag(&dragData);
3441
3442     m_dragOperation = WebDragOperationNone;
3443     m_currentDragData = 0;
3444 }
3445
3446 WebDragOperation WebViewImpl::dragTargetDragEnterOrOver(const WebPoint& clientPoint, const WebPoint& screenPoint, DragAction dragAction, int keyModifiers)
3447 {
3448     ASSERT(m_currentDragData);
3449
3450     m_currentDragData->setModifierKeyState(webInputEventKeyStateToPlatformEventKeyState(keyModifiers));
3451     DragData dragData(
3452         m_currentDragData.get(),
3453         clientPoint,
3454         screenPoint,
3455         static_cast<DragOperation>(m_operationsAllowed));
3456
3457     DragSession dragSession;
3458     if (dragAction == DragEnter)
3459         dragSession = m_page->dragController()->dragEntered(&dragData);
3460     else
3461         dragSession = m_page->dragController()->dragUpdated(&dragData);
3462
3463     DragOperation dropEffect = dragSession.operation;
3464
3465     // Mask the drop effect operation against the drag source's allowed operations.
3466     if (!(dropEffect & dragData.draggingSourceOperationMask()))
3467         dropEffect = DragOperationNone;
3468
3469      m_dragOperation = static_cast<WebDragOperation>(dropEffect);
3470
3471     return m_dragOperation;
3472 }
3473
3474 void WebViewImpl::sendResizeEventAndRepaint()
3475 {
3476     if (mainFrameImpl()->frameView()) {
3477         // Enqueues the resize event.
3478         mainFrameImpl()->frame()->eventHandler()->sendResizeEvent();
3479     }
3480
3481     if (m_client) {
3482         if (isAcceleratedCompositingActive()) {
3483 #if USE(ACCELERATED_COMPOSITING)
3484             updateLayerTreeViewport();
3485 #endif
3486         } else {
3487             WebRect damagedRect(0, 0, m_size.width, m_size.height);
3488             m_client->didInvalidateRect(damagedRect);
<