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