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