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