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