32c61a25ee8e78822f47aa3cb6106887815ad7b9
[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     // We need to transition to fullscreen mode.
1585     if (m_client && m_client->enterFullScreen())
1586         m_provisionalFullScreenElement = element;
1587 }
1588
1589 void WebViewImpl::exitFullScreenForElement(WebCore::Element* element)
1590 {
1591     // The client is exiting full screen, so don't send a notification.
1592     if (m_isCancelingFullScreen)
1593         return;
1594     if (m_client)
1595         m_client->exitFullScreen();
1596 }
1597
1598 bool WebViewImpl::hasHorizontalScrollbar()
1599 {
1600     return mainFrameImpl()->frameView()->horizontalScrollbar();
1601 }
1602
1603 bool WebViewImpl::hasVerticalScrollbar()
1604 {
1605     return mainFrameImpl()->frameView()->verticalScrollbar();
1606 }
1607
1608 const WebInputEvent* WebViewImpl::m_currentInputEvent = 0;
1609
1610 bool WebViewImpl::handleInputEvent(const WebInputEvent& inputEvent)
1611 {
1612     UserGestureIndicator gestureIndicator(WebInputEvent::isUserGestureEventType(inputEvent.type) ? DefinitelyProcessingUserGesture : PossiblyProcessingUserGesture);
1613
1614     // If we've started a drag and drop operation, ignore input events until
1615     // we're done.
1616     if (m_doingDragAndDrop)
1617         return true;
1618
1619     if (m_ignoreInputEvents)
1620         return true;
1621
1622     m_currentInputEvent = &inputEvent;
1623
1624 #if ENABLE(POINTER_LOCK)
1625     if (isPointerLocked() && WebInputEvent::isMouseEventType(inputEvent.type)) {
1626       pointerLockMouseEvent(inputEvent);
1627       return true;
1628     }
1629 #endif
1630
1631     if (m_mouseCaptureNode && WebInputEvent::isMouseEventType(inputEvent.type)) {
1632         // Save m_mouseCaptureNode since mouseCaptureLost() will clear it.
1633         RefPtr<Node> node = m_mouseCaptureNode;
1634
1635         // Not all platforms call mouseCaptureLost() directly.
1636         if (inputEvent.type == WebInputEvent::MouseUp)
1637             mouseCaptureLost();
1638
1639         AtomicString eventType;
1640         switch (inputEvent.type) {
1641         case WebInputEvent::MouseMove:
1642             eventType = eventNames().mousemoveEvent;
1643             break;
1644         case WebInputEvent::MouseLeave:
1645             eventType = eventNames().mouseoutEvent;
1646             break;
1647         case WebInputEvent::MouseDown:
1648             eventType = eventNames().mousedownEvent;
1649             break;
1650         case WebInputEvent::MouseUp:
1651             eventType = eventNames().mouseupEvent;
1652             break;
1653         default:
1654             ASSERT_NOT_REACHED();
1655         }
1656
1657         node->dispatchMouseEvent(
1658               PlatformMouseEventBuilder(mainFrameImpl()->frameView(), *static_cast<const WebMouseEvent*>(&inputEvent)),
1659               eventType, static_cast<const WebMouseEvent*>(&inputEvent)->clickCount);
1660         m_currentInputEvent = 0;
1661         return true;
1662     }
1663
1664     bool handled = PageWidgetDelegate::handleInputEvent(m_page.get(), *this, inputEvent);
1665     m_currentInputEvent = 0;
1666     return handled;
1667 }
1668
1669 void WebViewImpl::mouseCaptureLost()
1670 {
1671     m_mouseCaptureNode = 0;
1672 }
1673
1674 void WebViewImpl::setFocus(bool enable)
1675 {
1676     m_page->focusController()->setFocused(enable);
1677     if (enable) {
1678         m_page->focusController()->setActive(true);
1679         RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
1680         if (focusedFrame) {
1681             Node* focusedNode = focusedFrame->document()->focusedNode();
1682             if (focusedNode && focusedNode->isElementNode()
1683                 && focusedFrame->selection()->selection().isNone()) {
1684                 // If the selection was cleared while the WebView was not
1685                 // focused, then the focus element shows with a focus ring but
1686                 // no caret and does respond to keyboard inputs.
1687                 Element* element = static_cast<Element*>(focusedNode);
1688                 if (element->isTextFormControl())
1689                     element->updateFocusAppearance(true);
1690                 else if (focusedNode->isContentEditable()) {
1691                     // updateFocusAppearance() selects all the text of
1692                     // contentseditable DIVs. So we set the selection explicitly
1693                     // instead. Note that this has the side effect of moving the
1694                     // caret back to the beginning of the text.
1695                     Position position(focusedNode, 0,
1696                                       Position::PositionIsOffsetInAnchor);
1697                     focusedFrame->selection()->setSelection(
1698                         VisibleSelection(position, SEL_DEFAULT_AFFINITY));
1699                 }
1700             }
1701         }
1702         m_imeAcceptEvents = true;
1703     } else {
1704         hidePopups();
1705
1706         // Clear focus on the currently focused frame if any.
1707         if (!m_page)
1708             return;
1709
1710         Frame* frame = m_page->mainFrame();
1711         if (!frame)
1712             return;
1713
1714         RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
1715         if (focusedFrame) {
1716             // Finish an ongoing composition to delete the composition node.
1717             Editor* editor = focusedFrame->editor();
1718             if (editor && editor->hasComposition())
1719                 editor->confirmComposition();
1720             m_imeAcceptEvents = false;
1721         }
1722     }
1723 }
1724
1725 bool WebViewImpl::setComposition(
1726     const WebString& text,
1727     const WebVector<WebCompositionUnderline>& underlines,
1728     int selectionStart,
1729     int selectionEnd)
1730 {
1731     Frame* focused = focusedWebCoreFrame();
1732     if (!focused || !m_imeAcceptEvents)
1733         return false;
1734     Editor* editor = focused->editor();
1735     if (!editor)
1736         return false;
1737
1738     // The input focus has been moved to another WebWidget object.
1739     // We should use this |editor| object only to complete the ongoing
1740     // composition.
1741     if (!editor->canEdit() && !editor->hasComposition())
1742         return false;
1743
1744     // We should verify the parent node of this IME composition node are
1745     // editable because JavaScript may delete a parent node of the composition
1746     // node. In this case, WebKit crashes while deleting texts from the parent
1747     // node, which doesn't exist any longer.
1748     PassRefPtr<Range> range = editor->compositionRange();
1749     if (range) {
1750         Node* node = range->startContainer();
1751         if (!node || !node->isContentEditable())
1752             return false;
1753     }
1754
1755     // If we're not going to fire a keypress event, then the keydown event was
1756     // canceled.  In that case, cancel any existing composition.
1757     if (text.isEmpty() || m_suppressNextKeypressEvent) {
1758         // A browser process sent an IPC message which does not contain a valid
1759         // string, which means an ongoing composition has been canceled.
1760         // If the ongoing composition has been canceled, replace the ongoing
1761         // composition string with an empty string and complete it.
1762         String emptyString;
1763         Vector<CompositionUnderline> emptyUnderlines;
1764         editor->setComposition(emptyString, emptyUnderlines, 0, 0);
1765         return text.isEmpty();
1766     }
1767
1768     // When the range of composition underlines overlap with the range between
1769     // selectionStart and selectionEnd, WebKit somehow won't paint the selection
1770     // at all (see InlineTextBox::paint() function in InlineTextBox.cpp).
1771     // But the selection range actually takes effect.
1772     editor->setComposition(String(text),
1773                            CompositionUnderlineVectorBuilder(underlines),
1774                            selectionStart, selectionEnd);
1775
1776     return editor->hasComposition();
1777 }
1778
1779 bool WebViewImpl::confirmComposition()
1780 {
1781     return confirmComposition(WebString());
1782 }
1783
1784 bool WebViewImpl::confirmComposition(const WebString& text)
1785 {
1786     Frame* focused = focusedWebCoreFrame();
1787     if (!focused || !m_imeAcceptEvents)
1788         return false;
1789     Editor* editor = focused->editor();
1790     if (!editor || (!editor->hasComposition() && !text.length()))
1791         return false;
1792
1793     // We should verify the parent node of this IME composition node are
1794     // editable because JavaScript may delete a parent node of the composition
1795     // node. In this case, WebKit crashes while deleting texts from the parent
1796     // node, which doesn't exist any longer.
1797     PassRefPtr<Range> range = editor->compositionRange();
1798     if (range) {
1799         Node* node = range->startContainer();
1800         if (!node || !node->isContentEditable())
1801             return false;
1802     }
1803
1804     if (editor->hasComposition()) {
1805         if (text.length())
1806             editor->confirmComposition(String(text));
1807         else
1808             editor->confirmComposition();
1809     } else
1810         editor->insertText(String(text), 0);
1811
1812     return true;
1813 }
1814
1815 bool WebViewImpl::compositionRange(size_t* location, size_t* length)
1816 {
1817     Frame* focused = focusedWebCoreFrame();
1818     if (!focused || !focused->selection() || !m_imeAcceptEvents)
1819         return false;
1820     Editor* editor = focused->editor();
1821     if (!editor || !editor->hasComposition())
1822         return false;
1823
1824     RefPtr<Range> range = editor->compositionRange();
1825     if (!range)
1826         return false;
1827
1828     if (TextIterator::getLocationAndLengthFromRange(focused->selection()->rootEditableElementOrDocumentElement(), range.get(), *location, *length))
1829         return true;
1830     return false;
1831 }
1832
1833 WebTextInputType WebViewImpl::textInputType()
1834 {
1835     Node* node = focusedWebCoreNode();
1836     if (!node)
1837         return WebTextInputTypeNone;
1838
1839     if (node->nodeType() == Node::ELEMENT_NODE) {
1840         Element* element = static_cast<Element*>(node);
1841         if (element->hasLocalName(HTMLNames::inputTag)) {
1842             HTMLInputElement* input = static_cast<HTMLInputElement*>(element);
1843
1844             if (input->readOnly() || input->disabled())
1845                 return WebTextInputTypeNone;
1846
1847             if (input->isPasswordField())
1848                 return WebTextInputTypePassword;
1849             if (input->isSearchField())
1850                 return WebTextInputTypeSearch;
1851             if (input->isEmailField())
1852                 return WebTextInputTypeEmail;
1853             if (input->isNumberField())
1854                 return WebTextInputTypeNumber;
1855             if (input->isTelephoneField())
1856                 return WebTextInputTypeTelephone;
1857             if (input->isURLField())
1858                 return WebTextInputTypeURL;
1859             if (input->isTextField())
1860                 return WebTextInputTypeText;
1861             return WebTextInputTypeNone;
1862         }
1863
1864         if (element->hasLocalName(HTMLNames::textareaTag)) {
1865             HTMLTextAreaElement* textarea = static_cast<HTMLTextAreaElement*>(element);
1866
1867             if (textarea->readOnly() || textarea->disabled())
1868                 return WebTextInputTypeNone;
1869             return WebTextInputTypeText;
1870         }
1871     }
1872
1873     // For other situations.
1874     if (node->shouldUseInputMethod())
1875         return WebTextInputTypeText;
1876
1877     return WebTextInputTypeNone;
1878 }
1879
1880 bool WebViewImpl::selectionBounds(WebRect& start, WebRect& end) const
1881 {
1882     const Frame* frame = focusedWebCoreFrame();
1883     if (!frame)
1884         return false;
1885     FrameSelection* selection = frame->selection();
1886     if (!selection)
1887         return false;
1888
1889     if (selection->isCaret()) {
1890         start = end = frame->view()->contentsToWindow(selection->absoluteCaretBounds());
1891         return true;
1892     }
1893
1894     RefPtr<Range> selectedRange = frame->selection()->toNormalizedRange();
1895     if (!selectedRange)
1896         return false;
1897
1898     RefPtr<Range> range(Range::create(selectedRange->startContainer()->document(),
1899                                       selectedRange->startContainer(),
1900                                       selectedRange->startOffset(),
1901                                       selectedRange->startContainer(),
1902                                       selectedRange->startOffset()));
1903     start = frame->editor()->firstRectForRange(range.get());
1904
1905     range = Range::create(selectedRange->endContainer()->document(),
1906                           selectedRange->endContainer(),
1907                           selectedRange->endOffset(),
1908                           selectedRange->endContainer(),
1909                           selectedRange->endOffset());
1910     end = frame->editor()->firstRectForRange(range.get());
1911
1912     start = frame->view()->contentsToWindow(start);
1913     end = frame->view()->contentsToWindow(end);
1914
1915     if (!frame->selection()->selection().isBaseFirst())
1916         std::swap(start, end);
1917     return true;
1918 }
1919
1920 bool WebViewImpl::caretOrSelectionRange(size_t* location, size_t* length)
1921 {
1922     const Frame* focused = focusedWebCoreFrame();
1923     if (!focused)
1924         return false;
1925
1926     FrameSelection* selection = focused->selection();
1927     if (!selection)
1928         return false;
1929
1930     RefPtr<Range> range = selection->selection().firstRange();
1931     if (!range)
1932         return false;
1933
1934     if (TextIterator::getLocationAndLengthFromRange(selection->rootEditableElementOrDocumentElement(), range.get(), *location, *length))
1935         return true;
1936     return false;
1937 }
1938
1939 void WebViewImpl::setTextDirection(WebTextDirection direction)
1940 {
1941     // The Editor::setBaseWritingDirection() function checks if we can change
1942     // the text direction of the selected node and updates its DOM "dir"
1943     // attribute and its CSS "direction" property.
1944     // So, we just call the function as Safari does.
1945     const Frame* focused = focusedWebCoreFrame();
1946     if (!focused)
1947         return;
1948
1949     Editor* editor = focused->editor();
1950     if (!editor || !editor->canEdit())
1951         return;
1952
1953     switch (direction) {
1954     case WebTextDirectionDefault:
1955         editor->setBaseWritingDirection(NaturalWritingDirection);
1956         break;
1957
1958     case WebTextDirectionLeftToRight:
1959         editor->setBaseWritingDirection(LeftToRightWritingDirection);
1960         break;
1961
1962     case WebTextDirectionRightToLeft:
1963         editor->setBaseWritingDirection(RightToLeftWritingDirection);
1964         break;
1965
1966     default:
1967         notImplemented();
1968         break;
1969     }
1970 }
1971
1972 bool WebViewImpl::isAcceleratedCompositingActive() const
1973 {
1974 #if USE(ACCELERATED_COMPOSITING)
1975     return m_isAcceleratedCompositingActive;
1976 #else
1977     return false;
1978 #endif
1979 }
1980
1981 void WebViewImpl::didAcquirePointerLock()
1982 {
1983 #if ENABLE(POINTER_LOCK)
1984     if (page())
1985         page()->pointerLockController()->didAcquirePointerLock();
1986 #endif
1987 }
1988
1989 void WebViewImpl::didNotAcquirePointerLock()
1990 {
1991 #if ENABLE(POINTER_LOCK)
1992     if (page())
1993         page()->pointerLockController()->didNotAcquirePointerLock();
1994 #endif
1995 }
1996
1997 void WebViewImpl::didLosePointerLock()
1998 {
1999 #if ENABLE(POINTER_LOCK)
2000     if (page())
2001         page()->pointerLockController()->didLosePointerLock();
2002 #endif
2003 }
2004
2005 void WebViewImpl::didChangeWindowResizerRect()
2006 {
2007     if (mainFrameImpl()->frameView())
2008         mainFrameImpl()->frameView()->windowResizerRectChanged();
2009 }
2010
2011 // WebView --------------------------------------------------------------------
2012
2013 WebSettings* WebViewImpl::settings()
2014 {
2015     if (!m_webSettings)
2016         m_webSettings = adoptPtr(new WebSettingsImpl(m_page->settings()));
2017     ASSERT(m_webSettings);
2018     return m_webSettings.get();
2019 }
2020
2021 WebString WebViewImpl::pageEncoding() const
2022 {
2023     if (!m_page)
2024         return WebString();
2025
2026     // FIXME: Is this check needed?
2027     if (!m_page->mainFrame()->document()->loader())
2028         return WebString();
2029
2030     return m_page->mainFrame()->document()->encoding();
2031 }
2032
2033 void WebViewImpl::setPageEncoding(const WebString& encodingName)
2034 {
2035     if (!m_page)
2036         return;
2037
2038     // Only change override encoding, don't change default encoding.
2039     // Note that the new encoding must be 0 if it isn't supposed to be set.
2040     String newEncodingName;
2041     if (!encodingName.isEmpty())
2042         newEncodingName = encodingName;
2043     m_page->mainFrame()->loader()->reloadWithOverrideEncoding(newEncodingName);
2044 }
2045
2046 bool WebViewImpl::dispatchBeforeUnloadEvent()
2047 {
2048     // FIXME: This should really cause a recursive depth-first walk of all
2049     // frames in the tree, calling each frame's onbeforeunload.  At the moment,
2050     // we're consistent with Safari 3.1, not IE/FF.
2051     Frame* frame = m_page->mainFrame();
2052     if (!frame)
2053         return true;
2054
2055     return frame->loader()->shouldClose();
2056 }
2057
2058 void WebViewImpl::dispatchUnloadEvent()
2059 {
2060     // Run unload handlers.
2061     m_page->mainFrame()->loader()->closeURL();
2062 }
2063
2064 WebFrame* WebViewImpl::mainFrame()
2065 {
2066     return mainFrameImpl();
2067 }
2068
2069 WebFrame* WebViewImpl::findFrameByName(
2070     const WebString& name, WebFrame* relativeToFrame)
2071 {
2072     if (!relativeToFrame)
2073         relativeToFrame = mainFrame();
2074     Frame* frame = static_cast<WebFrameImpl*>(relativeToFrame)->frame();
2075     frame = frame->tree()->find(name);
2076     return WebFrameImpl::fromFrame(frame);
2077 }
2078
2079 WebFrame* WebViewImpl::focusedFrame()
2080 {
2081     return WebFrameImpl::fromFrame(focusedWebCoreFrame());
2082 }
2083
2084 void WebViewImpl::setFocusedFrame(WebFrame* frame)
2085 {
2086     if (!frame) {
2087         // Clears the focused frame if any.
2088         Frame* frame = focusedWebCoreFrame();
2089         if (frame)
2090             frame->selection()->setFocused(false);
2091         return;
2092     }
2093     WebFrameImpl* frameImpl = static_cast<WebFrameImpl*>(frame);
2094     Frame* webcoreFrame = frameImpl->frame();
2095     webcoreFrame->page()->focusController()->setFocusedFrame(webcoreFrame);
2096 }
2097
2098 void WebViewImpl::setInitialFocus(bool reverse)
2099 {
2100     if (!m_page)
2101         return;
2102
2103     // Since we don't have a keyboard event, we'll create one.
2104     WebKeyboardEvent keyboardEvent;
2105     keyboardEvent.type = WebInputEvent::RawKeyDown;
2106     if (reverse)
2107         keyboardEvent.modifiers = WebInputEvent::ShiftKey;
2108
2109     // VK_TAB which is only defined on Windows.
2110     keyboardEvent.windowsKeyCode = 0x09;
2111     PlatformKeyboardEventBuilder platformEvent(keyboardEvent);
2112     RefPtr<KeyboardEvent> webkitEvent = KeyboardEvent::create(platformEvent, 0);
2113
2114     Frame* frame = page()->focusController()->focusedOrMainFrame();
2115     if (Document* document = frame->document())
2116         document->setFocusedNode(0);
2117     page()->focusController()->setInitialFocus(
2118         reverse ? FocusDirectionBackward : FocusDirectionForward,
2119         webkitEvent.get());
2120 }
2121
2122 void WebViewImpl::clearFocusedNode()
2123 {
2124     RefPtr<Frame> frame = focusedWebCoreFrame();
2125     if (!frame)
2126         return;
2127
2128     RefPtr<Document> document = frame->document();
2129     if (!document)
2130         return;
2131
2132     RefPtr<Node> oldFocusedNode = document->focusedNode();
2133
2134     // Clear the focused node.
2135     document->setFocusedNode(0);
2136
2137     if (!oldFocusedNode)
2138         return;
2139
2140     // If a text field has focus, we need to make sure the selection controller
2141     // knows to remove selection from it. Otherwise, the text field is still
2142     // processing keyboard events even though focus has been moved to the page and
2143     // keystrokes get eaten as a result.
2144     if (oldFocusedNode->isContentEditable()
2145         || (oldFocusedNode->isElementNode()
2146             && static_cast<Element*>(oldFocusedNode.get())->isTextFormControl())) {
2147         frame->selection()->clear();
2148     }
2149 }
2150
2151 void WebViewImpl::scrollFocusedNodeIntoView()
2152 {
2153     Node* focusedNode = focusedWebCoreNode();
2154     if (focusedNode && focusedNode->isElementNode()) {
2155         Element* elementNode = static_cast<Element*>(focusedNode);
2156         elementNode->scrollIntoViewIfNeeded(true);
2157     }
2158 }
2159
2160 void WebViewImpl::scrollFocusedNodeIntoRect(const WebRect& rect)
2161 {
2162     Frame* frame = page()->mainFrame();
2163     Node* focusedNode = focusedWebCoreNode();
2164     if (!frame || !frame->view() || !focusedNode || !focusedNode->isElementNode())
2165         return;
2166     Element* elementNode = static_cast<Element*>(focusedNode);
2167     frame->view()->scrollElementToRect(elementNode, IntRect(rect.x, rect.y, rect.width, rect.height));
2168 }
2169
2170 double WebViewImpl::zoomLevel()
2171 {
2172     return m_zoomLevel;
2173 }
2174
2175 double WebViewImpl::setZoomLevel(bool textOnly, double zoomLevel)
2176 {
2177     if (zoomLevel < m_minimumZoomLevel)
2178         m_zoomLevel = m_minimumZoomLevel;
2179     else if (zoomLevel > m_maximumZoomLevel)
2180         m_zoomLevel = m_maximumZoomLevel;
2181     else
2182         m_zoomLevel = zoomLevel;
2183
2184     Frame* frame = mainFrameImpl()->frame();
2185     WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
2186     if (pluginContainer)
2187         pluginContainer->plugin()->setZoomLevel(m_zoomLevel, textOnly);
2188     else {
2189         float zoomFactor = static_cast<float>(zoomLevelToZoomFactor(m_zoomLevel));
2190         if (textOnly)
2191             frame->setPageAndTextZoomFactors(1, zoomFactor * m_emulatedTextZoomFactor);
2192         else
2193             frame->setPageAndTextZoomFactors(zoomFactor, m_emulatedTextZoomFactor);
2194     }
2195     return m_zoomLevel;
2196 }
2197
2198 void WebViewImpl::zoomLimitsChanged(double minimumZoomLevel,
2199                                     double maximumZoomLevel)
2200 {
2201     m_minimumZoomLevel = minimumZoomLevel;
2202     m_maximumZoomLevel = maximumZoomLevel;
2203     m_client->zoomLimitsChanged(m_minimumZoomLevel, m_maximumZoomLevel);
2204 }
2205
2206 void WebViewImpl::fullFramePluginZoomLevelChanged(double zoomLevel)
2207 {
2208     if (zoomLevel == m_zoomLevel)
2209         return;
2210
2211     m_zoomLevel = max(min(zoomLevel, m_maximumZoomLevel), m_minimumZoomLevel);
2212     m_client->zoomLevelChanged();
2213 }
2214
2215 double WebView::zoomLevelToZoomFactor(double zoomLevel)
2216 {
2217     return pow(textSizeMultiplierRatio, zoomLevel);
2218 }
2219
2220 double WebView::zoomFactorToZoomLevel(double factor)
2221 {
2222     // Since factor = 1.2^level, level = log(factor) / log(1.2)
2223     return log(factor) / log(textSizeMultiplierRatio);
2224 }
2225
2226 float WebViewImpl::pageScaleFactor() const
2227 {
2228     if (!page())
2229         return 1;
2230
2231     return page()->pageScaleFactor();
2232 }
2233
2234 bool WebViewImpl::isPageScaleFactorSet() const
2235 {
2236     return m_pageScaleFactorIsSet;
2237 }
2238
2239 float WebViewImpl::clampPageScaleFactorToLimits(float scaleFactor)
2240 {
2241     return min(max(scaleFactor, m_minimumPageScaleFactor), m_maximumPageScaleFactor);
2242 }
2243
2244 WebPoint WebViewImpl::clampOffsetAtScale(const WebPoint& offset, float scale)
2245 {
2246     // This is the scaled content size. We need to convert it to the new scale factor.
2247     WebSize contentSize = mainFrame()->contentsSize();
2248     float deltaScale = scale / pageScaleFactor();
2249     int docWidthAtNewScale = contentSize.width * deltaScale;
2250     int docHeightAtNewScale = contentSize.height * deltaScale;
2251     int viewWidth = m_size.width;
2252     int viewHeight = m_size.height;
2253
2254     // Enforce the maximum and minimum scroll positions at the new scale.
2255     IntPoint clampedOffset = offset;
2256     clampedOffset = clampedOffset.shrunkTo(IntPoint(docWidthAtNewScale - viewWidth, docHeightAtNewScale - viewHeight));
2257     clampedOffset.clampNegativeToZero();
2258     return clampedOffset;
2259 }
2260
2261 void WebViewImpl::setPageScaleFactorPreservingScrollOffset(float scaleFactor)
2262 {
2263     // Pick a scale factor that is within the expected limits
2264     scaleFactor = clampPageScaleFactorToLimits(scaleFactor);
2265
2266     IntPoint scrollOffsetAtNewScale(mainFrame()->scrollOffset().width, mainFrame()->scrollOffset().height);
2267     float deltaScale = scaleFactor / pageScaleFactor();
2268     scrollOffsetAtNewScale.scale(deltaScale, deltaScale);
2269
2270     WebPoint clampedOffsetAtNewScale = clampOffsetAtScale(scrollOffsetAtNewScale, scaleFactor);
2271     setPageScaleFactor(scaleFactor, clampedOffsetAtNewScale);
2272 }
2273
2274 void WebViewImpl::setPageScaleFactor(float scaleFactor, const WebPoint& origin)
2275 {
2276     if (!page())
2277         return;
2278
2279     if (!scaleFactor)
2280         scaleFactor = 1;
2281
2282     scaleFactor = clampPageScaleFactorToLimits(scaleFactor);
2283     WebPoint clampedOrigin = clampOffsetAtScale(origin, scaleFactor);
2284     page()->setPageScaleFactor(scaleFactor, clampedOrigin);
2285     m_pageScaleFactorIsSet = true;
2286 }
2287
2288 float WebViewImpl::deviceScaleFactor() const
2289 {
2290     if (!page())
2291         return 1;
2292
2293     return page()->deviceScaleFactor();
2294 }
2295
2296 void WebViewImpl::setDeviceScaleFactor(float scaleFactor)
2297 {
2298     if (!page())
2299         return;
2300
2301     page()->setDeviceScaleFactor(scaleFactor);
2302 }
2303
2304 bool WebViewImpl::isFixedLayoutModeEnabled() const
2305 {
2306     if (!page())
2307         return false;
2308
2309     Frame* frame = page()->mainFrame();
2310     if (!frame || !frame->view())
2311         return false;
2312
2313     return frame->view()->useFixedLayout();
2314 }
2315
2316 void WebViewImpl::enableFixedLayoutMode(bool enable)
2317 {
2318     if (!page())
2319         return;
2320
2321     Frame* frame = page()->mainFrame();
2322     if (!frame || !frame->view())
2323         return;
2324
2325     frame->view()->setUseFixedLayout(enable);
2326
2327 #if USE(ACCELERATED_COMPOSITING)
2328     // Also notify the base layer, which RenderLayerCompositor does not see.
2329     if (m_nonCompositedContentHost) {
2330         m_nonCompositedContentHost->topLevelRootLayer()->deviceOrPageScaleFactorChanged();
2331         updateLayerTreeViewport();
2332     }
2333 #endif
2334 }
2335
2336
2337 void WebViewImpl::enableAutoResizeMode(const WebSize& minSize, const WebSize& maxSize)
2338 {
2339     m_shouldAutoResize = true;
2340     m_minAutoSize = minSize;
2341     m_maxAutoSize = maxSize;
2342     configureAutoResizeMode();
2343 }
2344
2345 void WebViewImpl::disableAutoResizeMode()
2346 {
2347     m_shouldAutoResize = false;
2348     configureAutoResizeMode();
2349 }
2350
2351 void WebViewImpl::setPageScaleFactorLimits(float minPageScale, float maxPageScale)
2352 {
2353     m_pageDefinedMinimumPageScaleFactor = minPageScale;
2354     m_pageDefinedMaximumPageScaleFactor = maxPageScale;
2355     computePageScaleFactorLimits();
2356 }
2357
2358 bool WebViewImpl::computePageScaleFactorLimits()
2359 {
2360     if (m_pageDefinedMinimumPageScaleFactor == -1 || m_pageDefinedMaximumPageScaleFactor == -1)
2361         return false;
2362
2363     if (!mainFrame() || !page() || !page()->mainFrame() || !page()->mainFrame()->view())
2364         return false;
2365
2366     m_minimumPageScaleFactor = min(max(m_pageDefinedMinimumPageScaleFactor, minPageScaleFactor), maxPageScaleFactor) * deviceScaleFactor();
2367     m_maximumPageScaleFactor = max(min(m_pageDefinedMaximumPageScaleFactor, maxPageScaleFactor), minPageScaleFactor) * deviceScaleFactor();
2368
2369     int viewWidthNotIncludingScrollbars = page()->mainFrame()->view()->visibleContentRect(false).width();
2370     int contentsWidth = mainFrame()->contentsSize().width;
2371     if (viewWidthNotIncludingScrollbars && contentsWidth) {
2372         // Limit page scaling down to the document width.
2373         int unscaledContentWidth = contentsWidth / pageScaleFactor();
2374         m_minimumPageScaleFactor = max(m_minimumPageScaleFactor, static_cast<float>(viewWidthNotIncludingScrollbars) / unscaledContentWidth);
2375         m_maximumPageScaleFactor = max(m_minimumPageScaleFactor, m_maximumPageScaleFactor);
2376     }
2377     ASSERT(m_minimumPageScaleFactor <= m_maximumPageScaleFactor);
2378
2379     float clampedScale = clampPageScaleFactorToLimits(pageScaleFactor());
2380 #if USE(ACCELERATED_COMPOSITING)
2381     if (!m_layerTreeView.isNull())
2382         m_layerTreeView.setPageScaleFactorAndLimits(clampedScale, m_minimumPageScaleFactor, m_maximumPageScaleFactor);
2383 #endif
2384     if (clampedScale != pageScaleFactor()) {
2385         setPageScaleFactorPreservingScrollOffset(clampedScale);
2386         return true;
2387     }
2388
2389     return false;
2390 }
2391
2392 float WebViewImpl::minimumPageScaleFactor() const
2393 {
2394     return m_minimumPageScaleFactor;
2395 }
2396
2397 float WebViewImpl::maximumPageScaleFactor() const
2398 {
2399     return m_maximumPageScaleFactor;
2400 }
2401
2402 WebSize WebViewImpl::fixedLayoutSize() const
2403 {
2404     if (!page())
2405         return WebSize();
2406
2407     Frame* frame = page()->mainFrame();
2408     if (!frame || !frame->view())
2409         return WebSize();
2410
2411     return frame->view()->fixedLayoutSize();
2412 }
2413
2414 void WebViewImpl::setFixedLayoutSize(const WebSize& layoutSize)
2415 {
2416     if (!page())
2417         return;
2418
2419     Frame* frame = page()->mainFrame();
2420     if (!frame || !frame->view())
2421         return;
2422
2423     frame->view()->setFixedLayoutSize(layoutSize);
2424 }
2425
2426 void WebViewImpl::performMediaPlayerAction(const WebMediaPlayerAction& action,
2427                                            const WebPoint& location)
2428 {
2429     HitTestResult result = hitTestResultForWindowPos(location);
2430     RefPtr<Node> node = result.innerNonSharedNode();
2431     if (!node->hasTagName(HTMLNames::videoTag) && !node->hasTagName(HTMLNames::audioTag))
2432         return;
2433
2434     RefPtr<HTMLMediaElement> mediaElement =
2435         static_pointer_cast<HTMLMediaElement>(node);
2436     switch (action.type) {
2437     case WebMediaPlayerAction::Play:
2438         if (action.enable)
2439             mediaElement->play();
2440         else
2441             mediaElement->pause();
2442         break;
2443     case WebMediaPlayerAction::Mute:
2444         mediaElement->setMuted(action.enable);
2445         break;
2446     case WebMediaPlayerAction::Loop:
2447         mediaElement->setLoop(action.enable);
2448         break;
2449     case WebMediaPlayerAction::Controls:
2450         mediaElement->setControls(action.enable);
2451         break;
2452     default:
2453         ASSERT_NOT_REACHED();
2454     }
2455 }
2456
2457 void WebViewImpl::performPluginAction(const WebPluginAction& action,
2458                                       const WebPoint& location)
2459 {
2460     HitTestResult result = hitTestResultForWindowPos(location);
2461     RefPtr<Node> node = result.innerNonSharedNode();
2462     if (!node->hasTagName(HTMLNames::objectTag) && !node->hasTagName(HTMLNames::embedTag))
2463         return;
2464
2465     RenderObject* object = node->renderer();
2466     if (object && object->isWidget()) {
2467         Widget* widget = toRenderWidget(object)->widget();
2468         if (widget && widget->isPluginContainer()) {
2469             WebPluginContainerImpl* plugin = static_cast<WebPluginContainerImpl*>(widget);
2470             switch (action.type) {
2471             case WebPluginAction::Rotate90Clockwise:
2472                 plugin->plugin()->rotateView(WebPlugin::RotationType90Clockwise);
2473                 break;
2474             case WebPluginAction::Rotate90Counterclockwise:
2475                 plugin->plugin()->rotateView(WebPlugin::RotationType90Counterclockwise);
2476                 break;
2477             default:
2478                 ASSERT_NOT_REACHED();
2479             }
2480         }
2481     }
2482 }
2483
2484 void WebViewImpl::copyImageAt(const WebPoint& point)
2485 {
2486     if (!m_page)
2487         return;
2488
2489     HitTestResult result = hitTestResultForWindowPos(point);
2490
2491     if (result.absoluteImageURL().isEmpty()) {
2492         // There isn't actually an image at these coordinates.  Might be because
2493         // the window scrolled while the context menu was open or because the page
2494         // changed itself between when we thought there was an image here and when
2495         // we actually tried to retreive the image.
2496         //
2497         // FIXME: implement a cache of the most recent HitTestResult to avoid having
2498         //        to do two hit tests.
2499         return;
2500     }
2501
2502     m_page->mainFrame()->editor()->copyImage(result);
2503 }
2504
2505 void WebViewImpl::dragSourceEndedAt(
2506     const WebPoint& clientPoint,
2507     const WebPoint& screenPoint,
2508     WebDragOperation operation)
2509 {
2510     PlatformMouseEvent pme(clientPoint,
2511                            screenPoint,
2512                            LeftButton, PlatformEvent::MouseMoved, 0, false, false, false,
2513                            false, 0);
2514     m_page->mainFrame()->eventHandler()->dragSourceEndedAt(pme,
2515         static_cast<DragOperation>(operation));
2516     m_dragScrollTimer->stop();
2517 }
2518
2519 void WebViewImpl::dragSourceMovedTo(
2520     const WebPoint& clientPoint,
2521     const WebPoint& screenPoint,
2522     WebDragOperation operation)
2523 {
2524     m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
2525 }
2526
2527 void WebViewImpl::dragSourceSystemDragEnded()
2528 {
2529     // It's possible for us to get this callback while not doing a drag if
2530     // it's from a previous page that got unloaded.
2531     if (m_doingDragAndDrop) {
2532         m_page->dragController()->dragEnded();
2533         m_doingDragAndDrop = false;
2534     }
2535 }
2536
2537 WebDragOperation WebViewImpl::dragTargetDragEnter(
2538     const WebDragData& webDragData,
2539     const WebPoint& clientPoint,
2540     const WebPoint& screenPoint,
2541     WebDragOperationsMask operationsAllowed)
2542 {
2543     ASSERT(!m_currentDragData);
2544
2545     m_currentDragData = webDragData;
2546     m_operationsAllowed = operationsAllowed;
2547
2548     return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragEnter);
2549 }
2550
2551 WebDragOperation WebViewImpl::dragTargetDragOver(
2552     const WebPoint& clientPoint,
2553     const WebPoint& screenPoint,
2554     WebDragOperationsMask operationsAllowed)
2555 {
2556     m_operationsAllowed = operationsAllowed;
2557
2558     return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragOver);
2559 }
2560
2561 void WebViewImpl::dragTargetDragLeave()
2562 {
2563     ASSERT(m_currentDragData);
2564
2565     DragData dragData(
2566         m_currentDragData.get(),
2567         IntPoint(),
2568         IntPoint(),
2569         static_cast<DragOperation>(m_operationsAllowed));
2570
2571     m_page->dragController()->dragExited(&dragData);
2572
2573     // FIXME: why is the drag scroll timer not stopped here?
2574
2575     m_dragOperation = WebDragOperationNone;
2576     m_currentDragData = 0;
2577 }
2578
2579 void WebViewImpl::dragTargetDrop(const WebPoint& clientPoint,
2580                                  const WebPoint& screenPoint)
2581 {
2582     ASSERT(m_currentDragData);
2583
2584     // If this webview transitions from the "drop accepting" state to the "not
2585     // accepting" state, then our IPC message reply indicating that may be in-
2586     // flight, or else delayed by javascript processing in this webview.  If a
2587     // drop happens before our IPC reply has reached the browser process, then
2588     // the browser forwards the drop to this webview.  So only allow a drop to
2589     // proceed if our webview m_dragOperation state is not DragOperationNone.
2590
2591     if (m_dragOperation == WebDragOperationNone) { // IPC RACE CONDITION: do not allow this drop.
2592         dragTargetDragLeave();
2593         return;
2594     }
2595
2596     DragData dragData(
2597         m_currentDragData.get(),
2598         clientPoint,
2599         screenPoint,
2600         static_cast<DragOperation>(m_operationsAllowed));
2601
2602     m_page->dragController()->performDrag(&dragData);
2603
2604     m_dragOperation = WebDragOperationNone;
2605     m_currentDragData = 0;
2606
2607     m_dragScrollTimer->stop();
2608 }
2609
2610 WebDragOperation WebViewImpl::dragTargetDragEnterOrOver(const WebPoint& clientPoint, const WebPoint& screenPoint, DragAction dragAction)
2611 {
2612     ASSERT(m_currentDragData);
2613
2614     DragData dragData(
2615         m_currentDragData.get(),
2616         clientPoint,
2617         screenPoint,
2618         static_cast<DragOperation>(m_operationsAllowed));
2619
2620     DragSession dragSession;
2621     if (dragAction == DragEnter)
2622         dragSession = m_page->dragController()->dragEntered(&dragData);
2623     else
2624         dragSession = m_page->dragController()->dragUpdated(&dragData);
2625
2626     DragOperation dropEffect = dragSession.operation;
2627
2628     // Mask the drop effect operation against the drag source's allowed operations.
2629     if (!(dropEffect & dragData.draggingSourceOperationMask()))
2630         dropEffect = DragOperationNone;
2631
2632      m_dragOperation = static_cast<WebDragOperation>(dropEffect);
2633
2634     if (dragAction == DragOver)
2635         m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
2636     else
2637         m_dragScrollTimer->stop();
2638
2639     return m_dragOperation;
2640 }
2641
2642 void WebViewImpl::sendResizeEventAndRepaint()
2643 {
2644     if (mainFrameImpl()->frameView()) {
2645         // Enqueues the resize event.
2646         mainFrameImpl()->frame()->eventHandler()->sendResizeEvent();
2647     }
2648
2649     if (m_client) {
2650         if (isAcceleratedCompositingActive()) {
2651 #if USE(ACCELERATED_COMPOSITING)
2652             updateLayerTreeViewport();
2653 #endif
2654         } else {
2655             WebRect damagedRect(0, 0, m_size.width, m_size.height);
2656             m_client->didInvalidateRect(damagedRect);
2657         }
2658     }
2659 }
2660
2661 void WebViewImpl::configureAutoResizeMode()
2662 {
2663     if (!mainFrameImpl() || !mainFrameImpl()->frame() || !mainFrameImpl()->frame()->view())
2664         return;
2665
2666     mainFrameImpl()->frame()->view()->enableAutoSizeMode(m_shouldAutoResize, m_minAutoSize, m_maxAutoSize);
2667 }
2668
2669 unsigned long WebViewImpl::createUniqueIdentifierForRequest()
2670 {
2671     if (m_page)
2672         return m_page->progress()->createUniqueIdentifier();
2673     return 0;
2674 }
2675
2676 void WebViewImpl::inspectElementAt(const WebPoint& point)
2677 {
2678     if (!m_page)
2679         return;
2680
2681     if (point.x == -1 || point.y == -1)
2682         m_page->inspectorController()->inspect(0);
2683     else {
2684         HitTestResult result = hitTestResultForWindowPos(point);
2685
2686         if (!result.innerNonSharedNode())
2687             return;
2688
2689         m_page->inspectorController()->inspect(result.innerNonSharedNode());
2690     }
2691 }
2692
2693 WebString WebViewImpl::inspectorSettings() const
2694 {
2695     return m_inspectorSettings;
2696 }
2697
2698 void WebViewImpl::setInspectorSettings(const WebString& settings)
2699 {
2700     m_inspectorSettings = settings;
2701 }
2702
2703 bool WebViewImpl::inspectorSetting(const WebString& key, WebString* value) const
2704 {
2705     if (!m_inspectorSettingsMap->contains(key))
2706         return false;
2707     *value = m_inspectorSettingsMap->get(key);
2708     return true;
2709 }
2710
2711 void WebViewImpl::setInspectorSetting(const WebString& key,
2712                                       const WebString& value)
2713 {
2714     m_inspectorSettingsMap->set(key, value);
2715     client()->didUpdateInspectorSetting(key, value);
2716 }
2717
2718 WebDevToolsAgent* WebViewImpl::devToolsAgent()
2719 {
2720     return m_devToolsAgent.get();
2721 }
2722
2723 WebAccessibilityObject WebViewImpl::accessibilityObject()
2724 {
2725     if (!mainFrameImpl())
2726         return WebAccessibilityObject();
2727
2728     Document* document = mainFrameImpl()->frame()->document();
2729     return WebAccessibilityObject(
2730         document->axObjectCache()->getOrCreate(document->renderer()));
2731 }
2732
2733 void WebViewImpl::applyAutofillSuggestions(
2734     const WebNode& node,
2735     const WebVector<WebString>& names,
2736     const WebVector<WebString>& labels,
2737     const WebVector<WebString>& icons,
2738     const WebVector<int>& itemIDs,
2739     int separatorIndex)
2740 {
2741     ASSERT(names.size() == labels.size());
2742     ASSERT(names.size() == itemIDs.size());
2743
2744     if (names.isEmpty()) {
2745         hideAutofillPopup();
2746         return;
2747     }
2748
2749     RefPtr<Node> focusedNode = focusedWebCoreNode();
2750     // If the node for which we queried the Autofill suggestions is not the
2751     // focused node, then we have nothing to do.  FIXME: also check the
2752     // caret is at the end and that the text has not changed.
2753     if (!focusedNode || focusedNode != PassRefPtr<Node>(node)) {
2754         hideAutofillPopup();
2755         return;
2756     }
2757
2758     HTMLInputElement* inputElem = focusedNode->toInputElement();
2759     ASSERT(inputElem);
2760
2761     // The first time the Autofill popup is shown we'll create the client and
2762     // the popup.
2763     if (!m_autofillPopupClient)
2764         m_autofillPopupClient = adoptPtr(new AutofillPopupMenuClient);
2765
2766     m_autofillPopupClient->initialize(
2767         inputElem, names, labels, icons, itemIDs, separatorIndex);
2768
2769     if (!m_autofillPopup) {
2770         PopupContainerSettings popupSettings = autofillPopupSettings;
2771         popupSettings.defaultDeviceScaleFactor =
2772             m_page->settings()->defaultDeviceScaleFactor();
2773         if (!popupSettings.defaultDeviceScaleFactor)
2774             popupSettings.defaultDeviceScaleFactor = 1;
2775         m_autofillPopup = PopupContainer::create(m_autofillPopupClient.get(),
2776                                                  PopupContainer::Suggestion,
2777                                                  popupSettings);
2778     }
2779
2780     if (m_autofillPopupShowing) {
2781         refreshAutofillPopup();
2782     } else {
2783         m_autofillPopup->showInRect(focusedNode->getPixelSnappedRect(), focusedNode->ownerDocument()->view(), 0);
2784         m_autofillPopupShowing = true;
2785     }
2786 }
2787
2788 void WebViewImpl::hidePopups()
2789 {
2790     hideSelectPopup();
2791     hideAutofillPopup();
2792 #if ENABLE(PAGE_POPUP)
2793     if (m_pagePopup)
2794         closePagePopup(m_pagePopup.get());
2795 #endif
2796 }
2797
2798 void WebViewImpl::performCustomContextMenuAction(unsigned action)
2799 {
2800     if (!m_page)
2801         return;
2802     ContextMenu* menu = m_page->contextMenuController()->contextMenu();
2803     if (!menu)
2804         return;
2805     ContextMenuItem* item = menu->itemWithAction(static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + action));
2806     if (item)
2807         m_page->contextMenuController()->contextMenuItemSelected(item);
2808     m_page->contextMenuController()->clearContextMenu();
2809 }
2810
2811 // WebView --------------------------------------------------------------------
2812
2813 void WebViewImpl::setIsTransparent(bool isTransparent)
2814 {
2815     // Set any existing frames to be transparent.
2816     Frame* frame = m_page->mainFrame();
2817     while (frame) {
2818         frame->view()->setTransparent(isTransparent);
2819         frame = frame->tree()->traverseNext();
2820     }
2821
2822     // Future frames check this to know whether to be transparent.
2823     m_isTransparent = isTransparent;
2824 }
2825
2826 bool WebViewImpl::isTransparent() const
2827 {
2828     return m_isTransparent;
2829 }
2830
2831 void WebViewImpl::setIsActive(bool active)
2832 {
2833     if (page() && page()->focusController())
2834         page()->focusController()->setActive(active);
2835 }
2836
2837 bool WebViewImpl::isActive() const
2838 {
2839     return (page() && page()->focusController()) ? page()->focusController()->isActive() : false;
2840 }
2841
2842 void WebViewImpl::setDomainRelaxationForbidden(bool forbidden, const WebString& scheme)
2843 {
2844     SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme));
2845 }
2846
2847 void WebViewImpl::setScrollbarColors(unsigned inactiveColor,
2848                                      unsigned activeColor,
2849                                      unsigned trackColor) {
2850 #if OS(UNIX) && !OS(DARWIN) && !OS(ANDROID)
2851     PlatformThemeChromiumLinux::setScrollbarColors(inactiveColor, activeColor, trackColor);
2852 #endif
2853 }
2854
2855 void WebViewImpl::setSelectionColors(unsigned activeBackgroundColor,
2856                                      unsigned activeForegroundColor,
2857                                      unsigned inactiveBackgroundColor,
2858                                      unsigned inactiveForegroundColor) {
2859 #if OS(UNIX) && !OS(DARWIN) && !OS(ANDROID)
2860     RenderThemeChromiumLinux::setSelectionColors(activeBackgroundColor,
2861                                                  activeForegroundColor,
2862                                                  inactiveBackgroundColor,
2863                                                  inactiveForegroundColor);
2864     theme()->platformColorsDidChange();
2865 #endif
2866 }
2867
2868 void WebView::addUserScript(const WebString& sourceCode,
2869                             const WebVector<WebString>& patternsIn,
2870                             WebView::UserScriptInjectAt injectAt,
2871                             WebView::UserContentInjectIn injectIn)
2872 {
2873     OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2874     for (size_t i = 0; i < patternsIn.size(); ++i)
2875         patterns->append(patternsIn[i]);
2876
2877     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2878     RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
2879     pageGroup->addUserScriptToWorld(world.get(), sourceCode, WebURL(), patterns.release(), nullptr,
2880                                     static_cast<UserScriptInjectionTime>(injectAt),
2881                                     static_cast<UserContentInjectedFrames>(injectIn));
2882 }
2883
2884 void WebView::addUserStyleSheet(const WebString& sourceCode,
2885                                 const WebVector<WebString>& patternsIn,
2886                                 WebView::UserContentInjectIn injectIn,
2887                                 WebView::UserStyleInjectionTime injectionTime)
2888 {
2889     OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2890     for (size_t i = 0; i < patternsIn.size(); ++i)
2891         patterns->append(patternsIn[i]);
2892
2893     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2894     RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
2895
2896     // FIXME: Current callers always want the level to be "author". It probably makes sense to let
2897     // callers specify this though, since in other cases the caller will probably want "user" level.
2898     //
2899     // FIXME: It would be nice to populate the URL correctly, instead of passing an empty URL.
2900     pageGroup->addUserStyleSheetToWorld(world.get(), sourceCode, WebURL(), patterns.release(), nullptr,
2901                                         static_cast<UserContentInjectedFrames>(injectIn),
2902                                         UserStyleAuthorLevel,
2903                                         static_cast<WebCore::UserStyleInjectionTime>(injectionTime));
2904 }
2905
2906 void WebView::removeAllUserContent()
2907 {
2908     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2909     pageGroup->removeAllUserContent();
2910 }
2911
2912 void WebViewImpl::didCommitLoad(bool* isNewNavigation, bool isNavigationWithinPage)
2913 {
2914     if (isNewNavigation)
2915         *isNewNavigation = m_observedNewNavigation;
2916
2917 #ifndef NDEBUG
2918     ASSERT(!m_observedNewNavigation
2919         || m_page->mainFrame()->loader()->documentLoader() == m_newNavigationLoader);
2920     m_newNavigationLoader = 0;
2921 #endif
2922     m_observedNewNavigation = false;
2923     if (!isNavigationWithinPage)
2924         m_pageScaleFactorIsSet = false;
2925
2926     m_gestureAnimation.clear();
2927 }
2928
2929 void WebViewImpl::layoutUpdated(WebFrameImpl* webframe)
2930 {
2931     if (!m_client || webframe != mainFrameImpl())
2932         return;
2933
2934     if (m_shouldAutoResize && mainFrameImpl()->frame() && mainFrameImpl()->frame()->view()) {
2935         WebSize frameSize = mainFrameImpl()->frame()->view()->frameRect().size();
2936         if (frameSize != m_size) {
2937             m_size = frameSize;
2938             m_client->didAutoResize(m_size);
2939             sendResizeEventAndRepaint();
2940         }
2941     }
2942
2943     m_client->didUpdateLayout();
2944 }
2945
2946 void WebViewImpl::didChangeContentsSize()
2947 {
2948     bool didClampScale = computePageScaleFactorLimits();
2949
2950     if (!didClampScale)
2951         return;
2952
2953     if (!mainFrameImpl())
2954         return;
2955
2956     FrameView* view = mainFrameImpl()->frameView();
2957     if (view && view->needsLayout())
2958         view->layout();
2959 }
2960
2961 bool WebViewImpl::useExternalPopupMenus()
2962 {
2963     return shouldUseExternalPopupMenus;
2964 }
2965
2966 void WebViewImpl::setEmulatedTextZoomFactor(float textZoomFactor)
2967 {
2968     m_emulatedTextZoomFactor = textZoomFactor;
2969     Frame* frame = mainFrameImpl()->frame();
2970     if (frame)
2971         frame->setPageAndTextZoomFactors(frame->pageZoomFactor(), m_emulatedTextZoomFactor);
2972 }
2973
2974 bool WebViewImpl::navigationPolicyFromMouseEvent(unsigned short button,
2975                                                  bool ctrl, bool shift,
2976                                                  bool alt, bool meta,
2977                                                  WebNavigationPolicy* policy)
2978 {
2979 #if OS(DARWIN)
2980     const bool newTabModifier = (button == 1) || meta;
2981 #else
2982     const bool newTabModifier = (button == 1) || ctrl;
2983 #endif
2984     if (!newTabModifier && !shift && !alt)
2985       return false;
2986
2987     ASSERT(policy);
2988     if (newTabModifier) {
2989         if (shift)
2990           *policy = WebNavigationPolicyNewForegroundTab;
2991         else
2992           *policy = WebNavigationPolicyNewBackgroundTab;
2993     } else {
2994         if (shift)
2995           *policy = WebNavigationPolicyNewWindow;
2996         else
2997           *policy = WebNavigationPolicyDownload;
2998     }
2999     return true;
3000 }
3001
3002 void WebViewImpl::startDragging(const WebDragData& dragData,
3003                                 WebDragOperationsMask mask,
3004                                 const WebImage& dragImage,
3005                                 const WebPoint& dragImageOffset)
3006 {
3007     if (!m_client)
3008         return;
3009     ASSERT(!m_doingDragAndDrop);
3010     m_doingDragAndDrop = true;
3011     m_client->startDragging(dragData, mask, dragImage, dragImageOffset);
3012 }
3013
3014 void WebViewImpl::observeNewNavigation()
3015 {
3016     m_observedNewNavigation = true;
3017 #ifndef NDEBUG
3018     m_newNavigationLoader = m_page->mainFrame()->loader()->documentLoader();
3019 #endif
3020 }
3021
3022 void WebViewImpl::setIgnoreInputEvents(bool newValue)
3023 {
3024     ASSERT(m_ignoreInputEvents != newValue);
3025     m_ignoreInputEvents = newValue;
3026 }
3027
3028 void WebViewImpl::addPageOverlay(WebPageOverlay* overlay, int zOrder)
3029 {
3030     if (!m_pageOverlays)
3031         m_pageOverlays = PageOverlayList::create(this);
3032
3033     m_pageOverlays->add(overlay, zOrder);
3034 }
3035
3036 void WebViewImpl::removePageOverlay(WebPageOverlay* overlay)
3037 {
3038     if (m_pageOverlays && m_pageOverlays->remove(overlay) && m_pageOverlays->empty())
3039         m_pageOverlays = nullptr;
3040 }
3041
3042 void WebViewImpl::setOverlayLayer(WebCore::GraphicsLayer* layer)
3043 {
3044     if (m_rootGraphicsLayer) {
3045         if (layer->parent() != m_rootGraphicsLayer)
3046             m_rootGraphicsLayer->addChild(layer);
3047     }
3048 }
3049
3050 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
3051 NotificationPresenterImpl* WebViewImpl::notificationPresenterImpl()
3052 {
3053     if (!m_notificationPresenter.isInitialized() && m_client)
3054         m_notificationPresenter.initialize(m_client->notificationPresenter());
3055     return &m_notificationPresenter;
3056 }
3057 #endif
3058
3059 void WebViewImpl::refreshAutofillPopup()
3060 {
3061     ASSERT(m_autofillPopupShowing);
3062
3063     // Hide the popup if it has become empty.
3064     if (!m_autofillPopupClient->listSize()) {
3065         hideAutofillPopup();
3066         return;
3067     }
3068
3069     WebRect newWidgetRect = m_autofillPopup->refresh(focusedWebCoreNode()->getPixelSnappedRect());
3070     // Let's resize the backing window if necessary.
3071     WebPopupMenuImpl* popupMenu = static_cast<WebPopupMenuImpl*>(m_autofillPopup->client());
3072     if (popupMenu && popupMenu->client()->windowRect() != newWidgetRect)
3073         popupMenu->client()->setWindowRect(newWidgetRect);
3074 }
3075
3076 Node* WebViewImpl::focusedWebCoreNode()
3077 {
3078     Frame* frame = m_page->focusController()->focusedFrame();
3079     if (!frame)
3080         return 0;
3081
3082     Document* document = frame->document();
3083     if (!document)
3084         return 0;
3085
3086     return document->focusedNode();
3087 }
3088
3089 HitTestResult WebViewImpl::hitTestResultForWindowPos(const IntPoint& pos)
3090 {
3091     IntPoint docPoint(m_page->mainFrame()->view()->windowToContents(pos));
3092     return m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(docPoint, false);
3093 }
3094
3095 void WebViewImpl::setTabsToLinks(bool enable)
3096 {
3097     m_tabsToLinks = enable;
3098 }
3099
3100 bool WebViewImpl::tabsToLinks() const
3101 {
3102     return m_tabsToLinks;
3103 }
3104
3105 #if USE(ACCELERATED_COMPOSITING)
3106 bool WebViewImpl::allowsAcceleratedCompositing()
3107 {
3108     return !m_compositorCreationFailed;
3109 }
3110
3111 bool WebViewImpl::pageHasRTLStyle() const
3112 {
3113     if (!page())
3114         return false;
3115     Document* document = page()->mainFrame()->document();
3116     if (!document)
3117         return false;
3118     RenderView* renderView = document->renderView();
3119     if (!renderView)
3120         return false;
3121     RenderStyle* style = renderView->style();
3122     if (!style)
3123         return false;
3124     return (style->direction() == RTL);
3125 }
3126
3127 void WebViewImpl::setRootGraphicsLayer(GraphicsLayer* layer)
3128 {
3129     m_rootGraphicsLayer = layer;
3130
3131     setIsAcceleratedCompositingActive(layer);
3132     if (m_nonCompositedContentHost) {
3133         GraphicsLayer* scrollLayer = 0;
3134         if (layer) {
3135             Document* document = page()->mainFrame()->document();
3136             RenderView* renderView = document->renderView();
3137             RenderLayerCompositor* compositor = renderView->compositor();
3138             scrollLayer = compositor->scrollLayer();
3139         }
3140         m_nonCompositedContentHost->setScrollLayer(scrollLayer);
3141     }
3142
3143     if (layer)
3144         m_rootLayer = WebLayer(layer->platformLayer());
3145
3146     if (!m_layerTreeView.isNull())
3147         m_layerTreeView.setRootLayer(layer ? &m_rootLayer : 0);
3148
3149     IntRect damagedRect(0, 0, m_size.width, m_size.height);
3150     if (!m_isAcceleratedCompositingActive)
3151         m_client->didInvalidateRect(damagedRect);
3152 }
3153
3154 void WebViewImpl::scheduleCompositingLayerSync()
3155 {
3156     m_layerTreeView.setNeedsRedraw();
3157 }
3158
3159 void WebViewImpl::scrollRootLayerRect(const IntSize&, const IntRect&)
3160 {
3161     updateLayerTreeViewport();
3162 }
3163
3164 void WebViewImpl::invalidateRootLayerRect(const IntRect& rect)
3165 {
3166     ASSERT(!m_layerTreeView.isNull());
3167
3168     if (!page())
3169         return;
3170
3171     FrameView* view = page()->mainFrame()->view();
3172     IntRect dirtyRect = view->windowToContents(rect);
3173     updateLayerTreeViewport();
3174     m_nonCompositedContentHost->invalidateRect(dirtyRect);
3175 }
3176
3177 NonCompositedContentHost* WebViewImpl::nonCompositedContentHost()
3178 {
3179     return m_nonCompositedContentHost.get();
3180 }
3181
3182 void WebViewImpl::setBackgroundColor(const WebCore::Color& color)
3183 {
3184     WebCore::Color documentBackgroundColor = color.isValid() ? color : WebCore::Color::white;
3185     WebColor webDocumentBackgroundColor = documentBackgroundColor.rgb();
3186     m_nonCompositedContentHost->setBackgroundColor(documentBackgroundColor);
3187     m_layerTreeView.setBackgroundColor(webDocumentBackgroundColor);
3188 }
3189
3190 #if ENABLE(REQUEST_ANIMATION_FRAME)
3191 void WebViewImpl::scheduleAnimation()
3192 {
3193     if (isAcceleratedCompositingActive()) {
3194         if (CCProxy::hasImplThread()) {
3195             ASSERT(!m_layerTreeView.isNull());
3196             m_layerTreeView.setNeedsAnimate();
3197         } else
3198             m_client->scheduleAnimation();
3199     } else
3200             m_client->scheduleAnimation();
3201 }
3202 #endif
3203
3204 class WebViewImplContentPainter : public LayerPainterChromium {
3205     WTF_MAKE_NONCOPYABLE(WebViewImplContentPainter);
3206 public:
3207     static PassOwnPtr<WebViewImplContentPainter*> create(WebViewImpl* webViewImpl)
3208     {
3209         return adoptPtr(new WebViewImplContentPainter(webViewImpl));
3210     }
3211
3212     virtual void paint(GraphicsContext& context, const IntRect& contentRect)
3213     {
3214         double paintStart = currentTime();
3215         Page* page = m_webViewImpl->page();
3216         if (!page)
3217             return;
3218         FrameView* view = page->mainFrame()->view();
3219         view->paintContents(&context, contentRect);
3220         double paintEnd = currentTime();
3221         double pixelsPerSec = (contentRect.width() * contentRect.height()) / (paintEnd - paintStart);
3222         WebKit::Platform::current()->histogramCustomCounts("Renderer4.AccelRootPaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30);
3223         WebKit::Platform::current()->histogramCustomCounts("Renderer4.AccelRootPaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30);
3224
3225         m_webViewImpl->setBackgroundColor(view->documentBackgroundColor());
3226     }
3227
3228 private:
3229     explicit WebViewImplContentPainter(WebViewImpl* webViewImpl)
3230         : m_webViewImpl(webViewImpl)
3231     {
3232     }
3233
3234     WebViewImpl* m_webViewImpl;
3235 };
3236
3237 void WebViewImpl::setIsAcceleratedCompositingActive(bool active)
3238 {
3239     WebKit::Platform::current()->histogramEnumeration("GPU.setIsAcceleratedCompositingActive", active * 2 + m_isAcceleratedCompositingActive, 4);
3240
3241     if (m_isAcceleratedCompositingActive == active)
3242         return;
3243
3244     if (!active) {
3245         m_isAcceleratedCompositingActive = false;
3246         // We need to finish all GL rendering before sending didDeactivateCompositor() to prevent
3247         // flickering when compositing turns off.
3248         if (!m_layerTreeView.isNull())
3249             m_layerTreeView.finishAllRendering();
3250         m_client->didDeactivateCompositor();
3251     } else if (!m_layerTreeView.isNull()) {
3252         m_isAcceleratedCompositingActive = true;
3253         updateLayerTreeViewport();
3254
3255         m_client->didActivateCompositor(m_layerTreeView.compositorIdentifier());
3256     } else {
3257         TRACE_EVENT("WebViewImpl::setIsAcceleratedCompositingActive(true)", this, 0);
3258
3259         WebLayerTreeView::Settings layerTreeViewSettings;
3260         layerTreeViewSettings.acceleratePainting = page()->settings()->acceleratedDrawingEnabled();
3261         layerTreeViewSettings.showFPSCounter = settings()->showFPSCounter();
3262         layerTreeViewSettings.showPlatformLayerTree = settings()->showPlatformLayerTree();
3263
3264         layerTreeViewSettings.perTilePainting = page()->settings()->perTileDrawingEnabled();
3265         layerTreeViewSettings.partialSwapEnabled = page()->settings()->partialSwapEnabled();
3266         layerTreeViewSettings.threadedAnimationEnabled = page()->settings()->threadedAnimationEnabled();
3267
3268         m_nonCompositedContentHost = NonCompositedContentHost::create(WebViewImplContentPainter::create(this));
3269         m_nonCompositedContentHost->setShowDebugBorders(page()->settings()->showDebugBorders());
3270
3271         m_layerTreeView.initialize(this, m_rootLayer, layerTreeViewSettings);
3272         if (!m_layerTreeView.isNull()) {
3273             m_layerTreeView.setPageScaleFactorAndLimits(pageScaleFactor(), m_minimumPageScaleFactor, m_maximumPageScaleFactor);
3274             if (m_compositorSurfaceReady)
3275                 m_layerTreeView.setSurfaceReady();
3276             updateLayerTreeViewport();
3277             m_client->didActivateCompositor(m_layerTreeView.compositorIdentifier());
3278             m_isAcceleratedCompositingActive = true;
3279             m_compositorCreationFailed = false;
3280             if (m_pageOverlays)
3281                 m_pageOverlays->update();
3282         } else {
3283             m_nonCompositedContentHost.clear();
3284             m_isAcceleratedCompositingActive = false;
3285             m_client->didDeactivateCompositor();
3286             m_compositorCreationFailed = true;
3287         }
3288     }
3289     if (page())
3290         page()->mainFrame()->view()->setClipsRepaints(!m_isAcceleratedCompositingActive);
3291 }
3292
3293 #endif
3294
3295 PassOwnPtr<WebKit::WebGraphicsContext3D> WebViewImpl::createCompositorGraphicsContext3D()
3296 {
3297     // Explicitly disable antialiasing for the compositor. As of the time of
3298     // this writing, the only platform that supported antialiasing for the
3299     // compositor was Mac OS X, because the on-screen OpenGL context creation
3300     // code paths on Windows and Linux didn't yet have multisampling support.
3301     // Mac OS X essentially always behaves as though it's rendering offscreen.
3302     // Multisampling has a heavy cost especially on devices with relatively low
3303     // fill rate like most notebooks, and the Mac implementation would need to
3304     // be optimized to resolve directly into the IOSurface shared between the
3305     // GPU and browser processes. For these reasons and to avoid platform
3306     // disparities we explicitly disable antialiasing.
3307     WebKit::WebGraphicsContext3D::Attributes attributes;
3308     attributes.antialias = false;
3309     attributes.shareResources = true;
3310
3311     OwnPtr<WebGraphicsContext3D> webContext = adoptPtr(client()->createGraphicsContext3D(attributes));
3312     if (!webContext)
3313         return nullptr;
3314
3315     return webContext.release();
3316 }
3317
3318 WebKit::WebGraphicsContext3D* WebViewImpl::createContext3D()
3319 {
3320     OwnPtr<WebKit::WebGraphicsContext3D> webContext;
3321
3322     // If we've already created an onscreen context for this view, return that.
3323     if (m_temporaryOnscreenGraphicsContext3D)
3324         webContext = m_temporaryOnscreenGraphicsContext3D.release();
3325     else // Otherwise make a new one.
3326         webContext = createCompositorGraphicsContext3D();
3327     // The caller takes ownership of this object, but since there's no equivalent of PassOwnPtr<> in the WebKit API
3328     // we return a raw pointer.
3329     return webContext.leakPtr();
3330 }
3331
3332 void WebViewImpl::applyScrollAndScale(const WebSize& scrollDelta, float pageScaleDelta)
3333 {
3334     if (!mainFrameImpl() || !mainFrameImpl()->frameView())
3335         return;
3336
3337     if (pageScaleDelta == 1) {
3338         TRACE_EVENT_INSTANT2("webkit", "WebViewImpl::applyScrollAndScale::scrollBy", "x", scrollDelta.width, "y", scrollDelta.height);
3339         mainFrameImpl()->frameView()->scrollBy(scrollDelta);
3340     } else {
3341         // The page scale changed, so apply a scale and scroll in a single
3342         // operation. The old scroll offset (and passed-in delta) are
3343         // in the old coordinate space, so we first need to multiply them
3344         // by the page scale delta.
3345         WebSize scrollOffset = mainFrame()->scrollOffset();
3346         scrollOffset.width += scrollDelta.width;
3347         scrollOffset.height += scrollDelta.height;
3348         WebPoint scaledScrollOffset(scrollOffset.width * pageScaleDelta,
3349                                     scrollOffset.height * pageScaleDelta);
3350         setPageScaleFactor(pageScaleFactor() * pageScaleDelta, scaledScrollOffset);
3351     }
3352 }
3353
3354 void WebViewImpl::didCommit()
3355 {
3356     if (m_client)
3357         m_client->didBecomeReadyForAdditionalInput();
3358 }
3359
3360 void WebViewImpl::didCommitAndDrawFrame()
3361 {
3362     if (m_client)
3363         m_client->didCommitAndDrawCompositorFrame();
3364 }
3365
3366 void WebViewImpl::didCompleteSwapBuffers()
3367 {
3368     if (m_client)
3369         m_client->didCompleteSwapBuffers();
3370 }
3371
3372 void WebViewImpl::didRebindGraphicsContext(bool success)
3373 {
3374
3375     // Switch back to software rendering mode, if necessary
3376     if (!success) {
3377         ASSERT(m_isAcceleratedCompositingActive);
3378         setIsAcceleratedCompositingActive(false);
3379         m_compositorCreationFailed = true;
3380         m_client->didInvalidateRect(IntRect(0, 0, m_size.width, m_size.height));
3381
3382         // Force a style recalc to remove all the composited layers.
3383         m_page->mainFrame()->document()->scheduleForcedStyleRecalc();
3384         return;
3385     }
3386
3387     if (m_pageOverlays)
3388         m_pageOverlays->update();
3389 }
3390
3391 void WebViewImpl::scheduleComposite()
3392 {
3393     ASSERT(!CCProxy::hasImplThread());
3394     m_client->scheduleComposite();
3395 }
3396
3397 void WebViewImpl::updateLayerTreeViewport()
3398 {
3399     if (!page() || !m_nonCompositedContentHost || m_layerTreeView.isNull())
3400         return;
3401
3402     FrameView* view = page()->mainFrame()->view();
3403     IntRect visibleRect = view->visibleContentRect(true /* include scrollbars */);
3404     IntPoint scroll(view->scrollX(), view->scrollY());
3405
3406     int layerAdjustX = 0;
3407     if (pageHasRTLStyle()) {
3408         // The origin of the initial containing block for RTL root layers is not
3409         // at the far left side of the layer bounds. Instead, it's one viewport
3410         // width (not including scrollbars) to the left of the right side of the
3411         // layer.
3412         layerAdjustX = -view->contentsSize().width() + view->visibleContentRect(false).width();
3413     }
3414     m_nonCompositedContentHost->setViewport(visibleRect.size(), view->contentsSize(), scroll, pageScaleFactor(), layerAdjustX);
3415     m_layerTreeView.setViewportSize(size());
3416     m_layerTreeView.setPageScaleFactorAndLimits(pageScaleFactor(), m_minimumPageScaleFactor, m_maximumPageScaleFactor);
3417 }
3418
3419 WebGraphicsContext3D* WebViewImpl::graphicsContext3D()
3420 {
3421 #if USE(ACCELERATED_COMPOSITING)
3422     if (m_page->settings()->acceleratedCompositingEnabled() && allowsAcceleratedCompositing()) {
3423         if (!m_layerTreeView.isNull()) {
3424             WebGraphicsContext3D* context = m_layerTreeView.context();
3425             if (context && !context->isContextLost())
3426                 return context;
3427         }
3428         // If we get here it means that some system needs access to the context the compositor will use but the compositor itself
3429         // hasn't requested a context or it was unable to successfully instantiate a context.
3430         // We need to return the context that the compositor will later use so we allocate a new context (if needed) and stash it
3431         // until the compositor requests and takes ownership of the context via createLayerTreeHost3D().
3432         if (!m_temporaryOnscreenGraphicsContext3D)
3433             m_temporaryOnscreenGraphicsContext3D = createCompositorGraphicsContext3D();
3434
3435         WebGraphicsContext3D* webContext = m_temporaryOnscreenGraphicsContext3D.get();
3436         if (webContext && !webContext->isContextLost())
3437             return webContext;
3438     }
3439 #endif
3440     return 0;
3441 }
3442
3443 WebGraphicsContext3D* WebViewImpl::sharedGraphicsContext3D()
3444 {
3445     if (!m_page->settings()->acceleratedCompositingEnabled() || !allowsAcceleratedCompositing())
3446         return 0;
3447
3448     return GraphicsContext3DPrivate::extractWebGraphicsContext3D(SharedGraphicsContext3D::get().get());
3449 }
3450
3451 void WebViewImpl::setVisibilityState(WebPageVisibilityState visibilityState,
3452                                      bool isInitialState) {
3453     if (!page())
3454         return;
3455
3456 #if ENABLE(PAGE_VISIBILITY_API)
3457     ASSERT(visibilityState == WebPageVisibilityStateVisible
3458            || visibilityState == WebPageVisibilityStateHidden
3459            || visibilityState == WebPageVisibilityStatePrerender
3460            || visibilityState == WebPageVisibilityStatePreview);
3461     m_page->setVisibilityState(static_cast<PageVisibilityState>(static_cast<int>(visibilityState)), isInitialState);
3462 #endif
3463
3464 #if USE(ACCELERATED_COMPOSITING)
3465     if (!m_layerTreeView.isNull()) {
3466         bool visible = visibilityState == WebPageVisibilityStateVisible;
3467         if (!visible && isAcceleratedCompositingActive())
3468             m_nonCompositedContentHost->protectVisibleTileTextures();
3469         m_layerTreeView.setVisible(visible);
3470     }
3471 #endif
3472 }
3473
3474 #if ENABLE(POINTER_LOCK)
3475 bool WebViewImpl::requestPointerLock()
3476 {
3477     return m_client && m_client->requestPointerLock();
3478 }
3479
3480 void WebViewImpl::requestPointerUnlock()
3481 {
3482     if (m_client)
3483         m_client->requestPointerUnlock();
3484 }
3485
3486 bool WebViewImpl::isPointerLocked()
3487 {
3488     return m_client && m_client->isPointerLocked();
3489 }
3490
3491 void WebViewImpl::pointerLockMouseEvent(const WebInputEvent& event)
3492 {
3493     AtomicString eventType;
3494     switch (event.type) {
3495     case WebInputEvent::MouseDown:
3496         eventType = eventNames().mousedownEvent;
3497         break;
3498     case WebInputEvent::MouseUp:
3499         eventType = eventNames().mouseupEvent;
3500         break;
3501     case WebInputEvent::MouseMove:
3502         eventType = eventNames().mousemoveEvent;
3503         break;
3504     default:
3505         ASSERT_NOT_REACHED();
3506     }
3507
3508     const WebMouseEvent& mouseEvent = static_cast<const WebMouseEvent&>(event);
3509
3510     if (page())
3511         page()->pointerLockController()->dispatchLockedMouseEvent(
3512             PlatformMouseEventBuilder(mainFrameImpl()->frameView(), mouseEvent),
3513             eventType);
3514 }
3515 #endif
3516
3517 } // namespace WebKit