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