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