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