Need to handle kCACFContextNeedsFlushNotification notifications that arrive after...
[WebKit-https.git] / Source / WebKit / chromium / src / WebViewImpl.cpp
1 /*
2  * Copyright (C) 2010 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 "AutofillPopupMenuClient.h"
35 #include "AXObjectCache.h"
36 #include "BackForwardListChromium.h"
37 #include "CSSStyleSelector.h"
38 #include "CSSValueKeywords.h"
39 #include "Chrome.h"
40 #include "ColorSpace.h"
41 #include "CompositionUnderlineVectorBuilder.h"
42 #include "ContextMenu.h"
43 #include "ContextMenuController.h"
44 #include "ContextMenuItem.h"
45 #include "Cursor.h"
46 #include "DOMUtilitiesPrivate.h"
47 #include "DeviceOrientationClientProxy.h"
48 #include "Document.h"
49 #include "DocumentLoader.h"
50 #include "DragController.h"
51 #include "DragData.h"
52 #include "DragScrollTimer.h"
53 #include "Editor.h"
54 #include "EventHandler.h"
55 #include "Extensions3D.h"
56 #include "FocusController.h"
57 #include "FontDescription.h"
58 #include "FrameLoader.h"
59 #include "FrameSelection.h"
60 #include "FrameTree.h"
61 #include "FrameView.h"
62 #include "GeolocationClientProxy.h"
63 #include "GraphicsContext.h"
64 #include "GraphicsContext3D.h"
65 #include "GraphicsContext3DInternal.h"
66 #include "HTMLInputElement.h"
67 #include "HTMLMediaElement.h"
68 #include "HTMLNames.h"
69 #include "HTMLTextAreaElement.h"
70 #include "HitTestResult.h"
71 #include "Image.h"
72 #include "ImageBuffer.h"
73 #include "InspectorController.h"
74 #include "KeyboardCodes.h"
75 #include "KeyboardEvent.h"
76 #include "LayerPainterChromium.h"
77 #include "MIMETypeRegistry.h"
78 #include "NodeRenderStyle.h"
79 #include "Page.h"
80 #include "PageGroup.h"
81 #include "PageGroupLoadDeferrer.h"
82 #include "Pasteboard.h"
83 #include "PlatformContextSkia.h"
84 #include "PlatformKeyboardEvent.h"
85 #include "PlatformMouseEvent.h"
86 #include "PlatformThemeChromiumGtk.h"
87 #include "PlatformWheelEvent.h"
88 #include "PopupContainer.h"
89 #include "PopupMenuClient.h"
90 #include "ProgressTracker.h"
91 #include "RenderView.h"
92 #include "ResourceHandle.h"
93 #include "SecurityOrigin.h"
94 #include "Settings.h"
95 #include "SpeechInputClientImpl.h"
96 #include "TextIterator.h"
97 #include "Timer.h"
98 #include "TraceEvent.h"
99 #include "TypingCommand.h"
100 #include "UserGestureIndicator.h"
101 #include "Vector.h"
102 #include "WebAccessibilityObject.h"
103 #include "WebAutofillClient.h"
104 #include "WebDevToolsAgentImpl.h"
105 #include "WebDevToolsAgentPrivate.h"
106 #include "WebDragData.h"
107 #include "WebFrameImpl.h"
108 #include "WebGraphicsContext3D.h"
109 #include "WebImage.h"
110 #include "WebInputElement.h"
111 #include "WebInputEvent.h"
112 #include "WebInputEventConversion.h"
113 #include "WebKit.h"
114 #include "WebKitClient.h"
115 #include "WebMediaPlayerAction.h"
116 #include "WebNode.h"
117 #include "WebPlugin.h"
118 #include "WebPluginContainerImpl.h"
119 #include "WebPoint.h"
120 #include "WebPopupMenuImpl.h"
121 #include "WebRange.h"
122 #include "WebRect.h"
123 #include "WebRuntimeFeatures.h"
124 #include "WebSettingsImpl.h"
125 #include "WebString.h"
126 #include "WebVector.h"
127 #include "WebViewClient.h"
128 #include "cc/CCHeadsUpDisplay.h"
129 #include <wtf/ByteArray.h>
130 #include <wtf/CurrentTime.h>
131 #include <wtf/MainThread.h>
132 #include <wtf/RefPtr.h>
133
134 #if ENABLE(GESTURE_EVENTS)
135 #include "PlatformGestureEvent.h"
136 #endif
137
138 #if ENABLE(GESTURE_RECOGNIZER)
139 #include "PlatformGestureRecognizer.h"
140 #endif
141
142 #if USE(CG)
143 #include <CoreGraphics/CGBitmapContext.h>
144 #include <CoreGraphics/CGContext.h>
145 #endif
146
147 #if OS(WINDOWS)
148 #include "RenderThemeChromiumWin.h"
149 #else
150 #if OS(UNIX) && !OS(DARWIN)
151 #include "RenderThemeChromiumLinux.h"
152 #endif
153 #include "RenderTheme.h"
154 #endif
155
156 // Get rid of WTF's pow define so we can use std::pow.
157 #undef pow
158 #include <cmath> // for std::pow
159
160 using namespace WebCore;
161 using namespace std;
162
163 namespace {
164
165 GraphicsContext3D::Attributes getCompositorContextAttributes()
166 {
167     // Explicitly disable antialiasing for the compositor. As of the time of
168     // this writing, the only platform that supported antialiasing for the
169     // compositor was Mac OS X, because the on-screen OpenGL context creation
170     // code paths on Windows and Linux didn't yet have multisampling support.
171     // Mac OS X essentially always behaves as though it's rendering offscreen.
172     // Multisampling has a heavy cost especially on devices with relatively low
173     // fill rate like most notebooks, and the Mac implementation would need to
174     // be optimized to resolve directly into the IOSurface shared between the
175     // GPU and browser processes. For these reasons and to avoid platform
176     // disparities we explicitly disable antialiasing.
177     GraphicsContext3D::Attributes attributes;
178     attributes.antialias = false;
179     return attributes;
180 }
181
182 } // anonymous namespace
183
184 namespace WebKit {
185
186 // Change the text zoom level by kTextSizeMultiplierRatio each time the user
187 // zooms text in or out (ie., change by 20%).  The min and max values limit
188 // text zoom to half and 3x the original text size.  These three values match
189 // those in Apple's port in WebKit/WebKit/WebView/WebView.mm
190 const double WebView::textSizeMultiplierRatio = 1.2;
191 const double WebView::minTextSizeMultiplier = 0.5;
192 const double WebView::maxTextSizeMultiplier = 3.0;
193
194
195 // The group name identifies a namespace of pages.  Page group is used on OSX
196 // for some programs that use HTML views to display things that don't seem like
197 // web pages to the user (so shouldn't have visited link coloring).  We only use
198 // one page group.
199 const char* pageGroupName = "default";
200
201 // Used to defer all page activity in cases where the embedder wishes to run
202 // a nested event loop. Using a stack enables nesting of message loop invocations.
203 static Vector<PageGroupLoadDeferrer*> pageGroupLoadDeferrerStack;
204
205 // Ensure that the WebDragOperation enum values stay in sync with the original
206 // DragOperation constants.
207 #define COMPILE_ASSERT_MATCHING_ENUM(coreName) \
208     COMPILE_ASSERT(int(coreName) == int(Web##coreName), dummy##coreName)
209 COMPILE_ASSERT_MATCHING_ENUM(DragOperationNone);
210 COMPILE_ASSERT_MATCHING_ENUM(DragOperationCopy);
211 COMPILE_ASSERT_MATCHING_ENUM(DragOperationLink);
212 COMPILE_ASSERT_MATCHING_ENUM(DragOperationGeneric);
213 COMPILE_ASSERT_MATCHING_ENUM(DragOperationPrivate);
214 COMPILE_ASSERT_MATCHING_ENUM(DragOperationMove);
215 COMPILE_ASSERT_MATCHING_ENUM(DragOperationDelete);
216 COMPILE_ASSERT_MATCHING_ENUM(DragOperationEvery);
217
218 static const PopupContainerSettings autofillPopupSettings = {
219     false, // setTextOnIndexChange
220     false, // acceptOnAbandon
221     true, // loopSelectionNavigation
222     false // restrictWidthOfListBox (For security reasons show the entire entry
223           // so the user doesn't enter information he did not intend to.)
224 };
225
226 static bool shouldUseExternalPopupMenus = false;
227
228 // WebView ----------------------------------------------------------------
229
230 WebView* WebView::create(WebViewClient* client)
231 {
232     // Keep runtime flag for device motion turned off until it's implemented.
233     WebRuntimeFeatures::enableDeviceMotion(false);
234
235     // Pass the WebViewImpl's self-reference to the caller.
236     return adoptRef(new WebViewImpl(client)).leakRef();
237 }
238
239 void WebView::setUseExternalPopupMenus(bool useExternalPopupMenus)
240 {
241     shouldUseExternalPopupMenus = useExternalPopupMenus;
242 }
243
244 void WebView::updateVisitedLinkState(unsigned long long linkHash)
245 {
246     Page::visitedStateChanged(PageGroup::pageGroup(pageGroupName), linkHash);
247 }
248
249 void WebView::resetVisitedLinkState()
250 {
251     Page::allVisitedStateChanged(PageGroup::pageGroup(pageGroupName));
252 }
253
254 void WebView::willEnterModalLoop()
255 {
256     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
257     ASSERT(pageGroup);
258
259     if (pageGroup->pages().isEmpty())
260         pageGroupLoadDeferrerStack.append(static_cast<PageGroupLoadDeferrer*>(0));
261     else {
262         // Pick any page in the page group since we are deferring all pages.
263         pageGroupLoadDeferrerStack.append(new PageGroupLoadDeferrer(*pageGroup->pages().begin(), true));
264     }
265 }
266
267 void WebView::didExitModalLoop()
268 {
269     ASSERT(pageGroupLoadDeferrerStack.size());
270
271     delete pageGroupLoadDeferrerStack.last();
272     pageGroupLoadDeferrerStack.removeLast();
273 }
274
275 void WebViewImpl::initializeMainFrame(WebFrameClient* frameClient)
276 {
277     // NOTE: The WebFrameImpl takes a reference to itself within InitMainFrame
278     // and releases that reference once the corresponding Frame is destroyed.
279     RefPtr<WebFrameImpl> frame = WebFrameImpl::create(frameClient);
280
281     frame->initializeAsMainFrame(this);
282
283     // Restrict the access to the local file system
284     // (see WebView.mm WebView::_commonInitializationWithFrameName).
285     SecurityOrigin::setLocalLoadPolicy(SecurityOrigin::AllowLocalLoadsForLocalOnly);
286 }
287
288 void WebViewImpl::setAutofillClient(WebAutofillClient* autofillClient)
289 {
290     m_autofillClient = autofillClient;
291 }
292
293 void WebViewImpl::setDevToolsAgentClient(WebDevToolsAgentClient* devToolsClient) 
294 {
295     if (devToolsClient)
296         m_devToolsAgent = adoptPtr(new WebDevToolsAgentImpl(this, devToolsClient));
297     else
298         m_devToolsAgent.clear();
299 }
300
301 void WebViewImpl::setPermissionClient(WebPermissionClient* permissionClient)
302 {
303     m_permissionClient = permissionClient;
304 }
305
306 void WebViewImpl::setSpellCheckClient(WebSpellCheckClient* spellCheckClient)
307 {
308     m_spellCheckClient = spellCheckClient;
309 }
310
311 WebViewImpl::WebViewImpl(WebViewClient* client)
312     : m_client(client)
313     , m_autofillClient(0)
314     , m_permissionClient(0)
315     , m_spellCheckClient(0)
316     , m_chromeClientImpl(this)
317     , m_contextMenuClientImpl(this)
318     , m_dragClientImpl(this)
319     , m_editorClientImpl(this)
320     , m_inspectorClientImpl(this)
321     , m_observedNewNavigation(false)
322 #ifndef NDEBUG
323     , m_newNavigationLoader(0)
324 #endif
325     , m_zoomLevel(0)
326     , m_minimumZoomLevel(zoomFactorToZoomLevel(minTextSizeMultiplier))
327     , m_maximumZoomLevel(zoomFactorToZoomLevel(maxTextSizeMultiplier))
328     , m_contextMenuAllowed(false)
329     , m_doingDragAndDrop(false)
330     , m_ignoreInputEvents(false)
331     , m_suppressNextKeypressEvent(false)
332     , m_initialNavigationPolicy(WebNavigationPolicyIgnore)
333     , m_imeAcceptEvents(true)
334     , m_operationsAllowed(WebDragOperationNone)
335     , m_dragOperation(WebDragOperationNone)
336     , m_autofillPopupShowing(false)
337     , m_autofillPopup(0)
338     , m_isTransparent(false)
339     , m_tabsToLinks(false)
340     , m_dragScrollTimer(adoptPtr(new DragScrollTimer))
341 #if USE(ACCELERATED_COMPOSITING)
342     , m_rootGraphicsLayer(0)
343     , m_isAcceleratedCompositingActive(false)
344     , m_compositorCreationFailed(false)
345     , m_recreatingGraphicsContext(false)
346 #endif
347 #if ENABLE(INPUT_SPEECH)
348     , m_speechInputClient(SpeechInputClientImpl::create(client))
349 #endif
350     , m_deviceOrientationClientProxy(adoptPtr(new DeviceOrientationClientProxy(client ? client->deviceOrientationClient() : 0)))
351     , m_geolocationClientProxy(adoptPtr(new GeolocationClientProxy(client ? client->geolocationClient() : 0)))
352 #if ENABLE(GESTURE_RECOGNIZER)
353     , m_gestureRecognizer(WebCore::PlatformGestureRecognizer::create())
354 #endif
355 {
356     // WebKit/win/WebView.cpp does the same thing, except they call the
357     // KJS specific wrapper around this method. We need to have threading
358     // initialized because CollatorICU requires it.
359     WTF::initializeThreading();
360     WTF::initializeMainThread();
361
362     // set to impossible point so we always get the first mouse pos
363     m_lastMousePosition = WebPoint(-1, -1);
364
365     Page::PageClients pageClients;
366     pageClients.chromeClient = &m_chromeClientImpl;
367     pageClients.contextMenuClient = &m_contextMenuClientImpl;
368     pageClients.editorClient = &m_editorClientImpl;
369     pageClients.dragClient = &m_dragClientImpl;
370     pageClients.inspectorClient = &m_inspectorClientImpl;
371 #if ENABLE(INPUT_SPEECH)
372     pageClients.speechInputClient = m_speechInputClient.get();
373 #endif
374     pageClients.deviceOrientationClient = m_deviceOrientationClientProxy.get();
375     pageClients.geolocationClient = m_geolocationClientProxy.get();
376     pageClients.backForwardClient = BackForwardListChromium::create(this);
377
378     m_page = adoptPtr(new Page(pageClients));
379
380     m_geolocationClientProxy->setController(m_page->geolocationController());
381
382     m_page->setGroupName(pageGroupName);
383
384 #if ENABLE(PAGE_VISIBILITY_API)
385     if (m_client)
386         setVisibilityState(m_client->visibilityState(), true);
387 #endif
388
389     m_inspectorSettingsMap = adoptPtr(new SettingsMap);
390 }
391
392 WebViewImpl::~WebViewImpl()
393 {
394     ASSERT(!m_page);
395 }
396
397 RenderTheme* WebViewImpl::theme() const
398 {
399     return m_page.get() ? m_page->theme() : RenderTheme::defaultTheme().get();
400 }
401
402 WebFrameImpl* WebViewImpl::mainFrameImpl()
403 {
404     return m_page.get() ? WebFrameImpl::fromFrame(m_page->mainFrame()) : 0;
405 }
406
407 bool WebViewImpl::tabKeyCyclesThroughElements() const
408 {
409     ASSERT(m_page.get());
410     return m_page->tabKeyCyclesThroughElements();
411 }
412
413 void WebViewImpl::setTabKeyCyclesThroughElements(bool value)
414 {
415     if (m_page)
416         m_page->setTabKeyCyclesThroughElements(value);
417 }
418
419 void WebViewImpl::mouseMove(const WebMouseEvent& event)
420 {
421     if (!mainFrameImpl() || !mainFrameImpl()->frameView())
422         return;
423
424     m_lastMousePosition = WebPoint(event.x, event.y);
425
426     // We call mouseMoved here instead of handleMouseMovedEvent because we need
427     // our ChromeClientImpl to receive changes to the mouse position and
428     // tooltip text, and mouseMoved handles all of that.
429     mainFrameImpl()->frame()->eventHandler()->mouseMoved(
430         PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
431 }
432
433 void WebViewImpl::mouseLeave(const WebMouseEvent& event)
434 {
435     // This event gets sent as the main frame is closing.  In that case, just
436     // ignore it.
437     if (!mainFrameImpl() || !mainFrameImpl()->frameView())
438         return;
439
440     m_client->setMouseOverURL(WebURL());
441
442     mainFrameImpl()->frame()->eventHandler()->handleMouseMoveEvent(
443         PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
444 }
445
446 void WebViewImpl::mouseDown(const WebMouseEvent& event)
447 {
448     if (!mainFrameImpl() || !mainFrameImpl()->frameView())
449         return;
450
451     // If there is a select popup open, close it as the user is clicking on
452     // the page (outside of the popup).  We also save it so we can prevent a
453     // click on the select element from immediately reopening the popup.
454     RefPtr<WebCore::PopupContainer> selectPopup;
455     if (event.button == WebMouseEvent::ButtonLeft) {
456         selectPopup = m_selectPopup;
457         hideSelectPopup();
458         ASSERT(!m_selectPopup);
459     }
460
461     m_lastMouseDownPoint = WebPoint(event.x, event.y);
462
463     RefPtr<Node> clickedNode;
464     if (event.button == WebMouseEvent::ButtonLeft) {
465         IntPoint point(event.x, event.y);
466         point = m_page->mainFrame()->view()->windowToContents(point);
467         HitTestResult result(m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, false));
468         Node* hitNode = result.innerNonSharedNode();
469
470         // Take capture on a mouse down on a plugin so we can send it mouse events.
471         if (hitNode && hitNode->renderer() && hitNode->renderer()->isEmbeddedObject())
472             m_mouseCaptureNode = hitNode;
473
474         // If a text field that has focus is clicked again, we should display the
475         // Autofill popup.
476         RefPtr<Node> focusedNode = focusedWebCoreNode();
477         if (focusedNode.get() && toHTMLInputElement(focusedNode.get())) {
478             if (hitNode == focusedNode) {
479                 // Already focused text field was clicked, let's remember this.  If
480                 // focus has not changed after the mouse event is processed, we'll
481                 // trigger the autocomplete.
482                 clickedNode = focusedNode;
483             }
484         }
485     }
486
487     mainFrameImpl()->frame()->loader()->resetMultipleFormSubmissionProtection();
488
489     mainFrameImpl()->frame()->eventHandler()->handleMousePressEvent(
490         PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
491
492     if (clickedNode.get() && clickedNode == focusedWebCoreNode()) {
493         // Focus has not changed, show the Autofill popup.
494         static_cast<EditorClientImpl*>(m_page->editorClient())->
495             showFormAutofillForNode(clickedNode.get());
496     }
497     if (m_selectPopup && m_selectPopup == selectPopup) {
498         // That click triggered a select popup which is the same as the one that
499         // was showing before the click.  It means the user clicked the select
500         // while the popup was showing, and as a result we first closed then
501         // immediately reopened the select popup.  It needs to be closed.
502         hideSelectPopup();
503     }
504
505     // Dispatch the contextmenu event regardless of if the click was swallowed.
506     // On Windows, we handle it on mouse up, not down.
507 #if OS(DARWIN)
508     if (event.button == WebMouseEvent::ButtonRight
509         || (event.button == WebMouseEvent::ButtonLeft
510             && event.modifiers & WebMouseEvent::ControlKey))
511         mouseContextMenu(event);
512 #elif OS(UNIX)
513     if (event.button == WebMouseEvent::ButtonRight)
514         mouseContextMenu(event);
515 #endif
516 }
517
518 void WebViewImpl::mouseContextMenu(const WebMouseEvent& event)
519 {
520     if (!mainFrameImpl() || !mainFrameImpl()->frameView())
521         return;
522
523     m_page->contextMenuController()->clearContextMenu();
524
525     PlatformMouseEventBuilder pme(mainFrameImpl()->frameView(), event);
526
527     // Find the right target frame. See issue 1186900.
528     HitTestResult result = hitTestResultForWindowPos(pme.pos());
529     Frame* targetFrame;
530     if (result.innerNonSharedNode())
531         targetFrame = result.innerNonSharedNode()->document()->frame();
532     else
533         targetFrame = m_page->focusController()->focusedOrMainFrame();
534
535 #if OS(WINDOWS)
536     targetFrame->view()->setCursor(pointerCursor());
537 #endif
538
539     m_contextMenuAllowed = true;
540     targetFrame->eventHandler()->sendContextMenuEvent(pme);
541     m_contextMenuAllowed = false;
542     // Actually showing the context menu is handled by the ContextMenuClient
543     // implementation...
544 }
545
546 void WebViewImpl::mouseUp(const WebMouseEvent& event)
547 {
548     if (!mainFrameImpl() || !mainFrameImpl()->frameView())
549         return;
550
551 #if OS(UNIX) && !OS(DARWIN)
552     // If the event was a middle click, attempt to copy text into the focused
553     // frame. We execute this before we let the page have a go at the event
554     // because the page may change what is focused during in its event handler.
555     //
556     // This code is in the mouse up handler. There is some debate about putting
557     // this here, as opposed to the mouse down handler.
558     //   xterm: pastes on up.
559     //   GTK: pastes on down.
560     //   Firefox: pastes on up.
561     //   Midori: couldn't paste at all with 0.1.2
562     //
563     // There is something of a webcompat angle to this well, as highlighted by
564     // crbug.com/14608. Pages can clear text boxes 'onclick' and, if we paste on
565     // down then the text is pasted just before the onclick handler runs and
566     // clears the text box. So it's important this happens after the
567     // handleMouseReleaseEvent() earlier in this function
568     if (event.button == WebMouseEvent::ButtonMiddle) {
569         Frame* focused = focusedWebCoreFrame();
570         FrameView* view = m_page->mainFrame()->view();
571         IntPoint clickPoint(m_lastMouseDownPoint.x, m_lastMouseDownPoint.y);
572         IntPoint contentPoint = view->windowToContents(clickPoint);
573         HitTestResult hitTestResult = focused->eventHandler()->hitTestResultAtPoint(contentPoint, false, false, ShouldHitTestScrollbars);
574         // We don't want to send a paste when middle clicking a scroll bar or a
575         // link (which will navigate later in the code).  The main scrollbars
576         // have to be handled separately.
577         if (!hitTestResult.scrollbar() && !hitTestResult.isLiveLink() && focused && !view->scrollbarAtPoint(clickPoint)) {
578             Editor* editor = focused->editor();
579             Pasteboard* pasteboard = Pasteboard::generalPasteboard();
580             bool oldSelectionMode = pasteboard->isSelectionMode();
581             pasteboard->setSelectionMode(true);
582             editor->command(AtomicString("Paste")).execute();
583             pasteboard->setSelectionMode(oldSelectionMode);
584         }
585     }
586 #endif
587
588     mainFrameImpl()->frame()->eventHandler()->handleMouseReleaseEvent(
589         PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
590
591 #if OS(WINDOWS)
592     // Dispatch the contextmenu event regardless of if the click was swallowed.
593     // On Mac/Linux, we handle it on mouse down, not up.
594     if (event.button == WebMouseEvent::ButtonRight)
595         mouseContextMenu(event);
596 #endif
597 }
598
599 bool WebViewImpl::mouseWheel(const WebMouseWheelEvent& event)
600 {
601     PlatformWheelEventBuilder platformEvent(mainFrameImpl()->frameView(), event);
602     return mainFrameImpl()->frame()->eventHandler()->handleWheelEvent(platformEvent);
603 }
604
605 #if ENABLE(GESTURE_EVENTS)
606 bool WebViewImpl::gestureEvent(const WebGestureEvent& event)
607 {
608     PlatformGestureEventBuilder platformEvent(mainFrameImpl()->frameView(), event);
609     return mainFrameImpl()->frame()->eventHandler()->handleGestureEvent(platformEvent);
610 }
611 #endif
612
613 bool WebViewImpl::keyEvent(const WebKeyboardEvent& event)
614 {
615     ASSERT((event.type == WebInputEvent::RawKeyDown)
616         || (event.type == WebInputEvent::KeyDown)
617         || (event.type == WebInputEvent::KeyUp));
618
619     // Please refer to the comments explaining the m_suppressNextKeypressEvent
620     // member.
621     // The m_suppressNextKeypressEvent is set if the KeyDown is handled by
622     // Webkit. A keyDown event is typically associated with a keyPress(char)
623     // event and a keyUp event. We reset this flag here as this is a new keyDown
624     // event.
625     m_suppressNextKeypressEvent = false;
626
627     // If there is a select popup, it should be the one processing the event,
628     // not the page.
629     if (m_selectPopup)
630         return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
631
632     // Give Autocomplete a chance to consume the key events it is interested in.
633     if (autocompleteHandleKeyEvent(event))
634         return true;
635
636     Frame* frame = focusedWebCoreFrame();
637     if (!frame)
638         return false;
639
640     EventHandler* handler = frame->eventHandler();
641     if (!handler)
642         return keyEventDefault(event);
643
644 #if !OS(DARWIN)
645     const WebInputEvent::Type contextMenuTriggeringEventType =
646 #if OS(WINDOWS)
647         WebInputEvent::KeyUp;
648 #elif OS(UNIX)
649         WebInputEvent::RawKeyDown;
650 #endif
651
652     bool isUnmodifiedMenuKey = !(event.modifiers & WebInputEvent::InputModifiers) && event.windowsKeyCode == VKEY_APPS;
653     bool isShiftF10 = event.modifiers == WebInputEvent::ShiftKey && event.windowsKeyCode == VKEY_F10;
654     if ((isUnmodifiedMenuKey || isShiftF10) && event.type == contextMenuTriggeringEventType) {
655         sendContextMenuEvent(event);
656         return true;
657     }
658 #endif // !OS(DARWIN)
659
660     PlatformKeyboardEventBuilder evt(event);
661
662     if (handler->keyEvent(evt)) {
663         if (WebInputEvent::RawKeyDown == event.type) {
664             // Suppress the next keypress event unless the focused node is a plug-in node.
665             // (Flash needs these keypress events to handle non-US keyboards.)
666             Node* node = frame->document()->focusedNode();
667             if (!node || !node->renderer() || !node->renderer()->isEmbeddedObject())
668                 m_suppressNextKeypressEvent = true;
669         }
670         return true;
671     }
672
673     return keyEventDefault(event);
674 }
675
676 bool WebViewImpl::autocompleteHandleKeyEvent(const WebKeyboardEvent& event)
677 {
678     if (!m_autofillPopupShowing
679         // Home and End should be left to the text field to process.
680         || event.windowsKeyCode == VKEY_HOME
681         || event.windowsKeyCode == VKEY_END)
682       return false;
683
684     // Pressing delete triggers the removal of the selected suggestion from the DB.
685     if (event.windowsKeyCode == VKEY_DELETE
686         && m_autofillPopup->selectedIndex() != -1) {
687         Node* node = focusedWebCoreNode();
688         if (!node || (node->nodeType() != Node::ELEMENT_NODE)) {
689             ASSERT_NOT_REACHED();
690             return false;
691         }
692         Element* element = static_cast<Element*>(node);
693         if (!element->hasLocalName(HTMLNames::inputTag)) {
694             ASSERT_NOT_REACHED();
695             return false;
696         }
697
698         int selectedIndex = m_autofillPopup->selectedIndex();
699
700         if (!m_autofillPopupClient->canRemoveSuggestionAtIndex(selectedIndex))
701             return false;
702
703         WebString name = WebInputElement(static_cast<HTMLInputElement*>(element)).nameForAutofill();
704         WebString value = m_autofillPopupClient->itemText(selectedIndex);
705         m_autofillClient->removeAutocompleteSuggestion(name, value);
706         // Update the entries in the currently showing popup to reflect the
707         // deletion.
708         m_autofillPopupClient->removeSuggestionAtIndex(selectedIndex);
709         refreshAutofillPopup();
710         return false;
711     }
712
713     if (!m_autofillPopup->isInterestedInEventForKey(event.windowsKeyCode))
714         return false;
715
716     if (m_autofillPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event))) {
717         // We need to ignore the next Char event after this otherwise pressing
718         // enter when selecting an item in the menu will go to the page.
719         if (WebInputEvent::RawKeyDown == event.type)
720             m_suppressNextKeypressEvent = true;
721         return true;
722     }
723
724     return false;
725 }
726
727 bool WebViewImpl::charEvent(const WebKeyboardEvent& event)
728 {
729     ASSERT(event.type == WebInputEvent::Char);
730
731     // Please refer to the comments explaining the m_suppressNextKeypressEvent
732     // member.  The m_suppressNextKeypressEvent is set if the KeyDown is
733     // handled by Webkit. A keyDown event is typically associated with a
734     // keyPress(char) event and a keyUp event. We reset this flag here as it
735     // only applies to the current keyPress event.
736     bool suppress = m_suppressNextKeypressEvent;
737     m_suppressNextKeypressEvent = false;
738
739     // If there is a select popup, it should be the one processing the event,
740     // not the page.
741     if (m_selectPopup)
742         return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
743
744     Frame* frame = focusedWebCoreFrame();
745     if (!frame)
746         return suppress;
747
748     EventHandler* handler = frame->eventHandler();
749     if (!handler)
750         return suppress || keyEventDefault(event);
751
752     PlatformKeyboardEventBuilder evt(event);
753     if (!evt.isCharacterKey())
754         return true;
755
756     // Accesskeys are triggered by char events and can't be suppressed.
757     if (handler->handleAccessKey(evt))
758         return true;
759
760     // Safari 3.1 does not pass off windows system key messages (WM_SYSCHAR) to
761     // the eventHandler::keyEvent. We mimic this behavior on all platforms since
762     // for now we are converting other platform's key events to windows key
763     // events.
764     if (evt.isSystemKey())
765         return false;
766
767     if (!suppress && !handler->keyEvent(evt))
768         return keyEventDefault(event);
769
770     return true;
771 }
772
773 #if ENABLE(TOUCH_EVENTS)
774 bool WebViewImpl::touchEvent(const WebTouchEvent& event)
775 {
776     if (!mainFrameImpl() || !mainFrameImpl()->frameView())
777         return false;
778
779     PlatformTouchEventBuilder touchEventBuilder(mainFrameImpl()->frameView(), event);
780     bool defaultPrevented = mainFrameImpl()->frame()->eventHandler()->handleTouchEvent(touchEventBuilder);
781
782 #if ENABLE(GESTURE_RECOGNIZER)
783     OwnPtr<Vector<WebCore::PlatformGestureEvent> > gestureEvents(m_gestureRecognizer->processTouchEventForGestures(touchEventBuilder, defaultPrevented));
784     for (unsigned int  i = 0; i < gestureEvents->size(); i++)
785         mainFrameImpl()->frame()->eventHandler()->handleGestureEvent(gestureEvents->at(i));
786 #endif
787
788     return defaultPrevented;
789 }
790 #endif
791
792 #if !OS(DARWIN)
793 // Mac has no way to open a context menu based on a keyboard event.
794 bool WebViewImpl::sendContextMenuEvent(const WebKeyboardEvent& event)
795 {
796     // The contextMenuController() holds onto the last context menu that was
797     // popped up on the page until a new one is created. We need to clear
798     // this menu before propagating the event through the DOM so that we can
799     // detect if we create a new menu for this event, since we won't create
800     // a new menu if the DOM swallows the event and the defaultEventHandler does
801     // not run.
802     page()->contextMenuController()->clearContextMenu();
803
804     m_contextMenuAllowed = true;
805     Frame* focusedFrame = page()->focusController()->focusedOrMainFrame();
806     bool handled = focusedFrame->eventHandler()->sendContextMenuEventForKey();
807     m_contextMenuAllowed = false;
808     return handled;
809 }
810 #endif
811
812 bool WebViewImpl::keyEventDefault(const WebKeyboardEvent& event)
813 {
814     Frame* frame = focusedWebCoreFrame();
815     if (!frame)
816         return false;
817
818     switch (event.type) {
819     case WebInputEvent::Char:
820         if (event.windowsKeyCode == VKEY_SPACE) {
821             int keyCode = ((event.modifiers & WebInputEvent::ShiftKey) ? VKEY_PRIOR : VKEY_NEXT);
822             return scrollViewWithKeyboard(keyCode, event.modifiers);
823         }
824         break;
825     case WebInputEvent::RawKeyDown:
826         if (event.modifiers == WebInputEvent::ControlKey) {
827             switch (event.windowsKeyCode) {
828 #if !OS(DARWIN)
829             case 'A':
830                 focusedFrame()->executeCommand(WebString::fromUTF8("SelectAll"));
831                 return true;
832             case VKEY_INSERT:
833             case 'C':
834                 focusedFrame()->executeCommand(WebString::fromUTF8("Copy"));
835                 return true;
836 #endif
837             // Match FF behavior in the sense that Ctrl+home/end are the only Ctrl
838             // key combinations which affect scrolling. Safari is buggy in the
839             // sense that it scrolls the page for all Ctrl+scrolling key
840             // combinations. For e.g. Ctrl+pgup/pgdn/up/down, etc.
841             case VKEY_HOME:
842             case VKEY_END:
843                 break;
844             default:
845                 return false;
846             }
847         }
848         if (!event.isSystemKey && !(event.modifiers & WebInputEvent::ShiftKey))
849             return scrollViewWithKeyboard(event.windowsKeyCode, event.modifiers);
850         break;
851     default:
852         break;
853     }
854     return false;
855 }
856
857 bool WebViewImpl::scrollViewWithKeyboard(int keyCode, int modifiers)
858 {
859     ScrollDirection scrollDirection;
860     ScrollGranularity scrollGranularity;
861 #if OS(DARWIN)
862     // Control-Up/Down should be PageUp/Down on Mac.
863     if (modifiers & WebMouseEvent::ControlKey) {
864       if (keyCode == VKEY_UP)
865         keyCode = VKEY_PRIOR;
866       else if (keyCode == VKEY_DOWN)
867         keyCode = VKEY_NEXT;
868     }
869 #endif
870     if (!mapKeyCodeForScroll(keyCode, &scrollDirection, &scrollGranularity))
871         return false;
872     return propagateScroll(scrollDirection, scrollGranularity);
873 }
874
875 bool WebViewImpl::mapKeyCodeForScroll(int keyCode,
876                                       WebCore::ScrollDirection* scrollDirection,
877                                       WebCore::ScrollGranularity* scrollGranularity)
878 {
879     switch (keyCode) {
880     case VKEY_LEFT:
881         *scrollDirection = ScrollLeft;
882         *scrollGranularity = ScrollByLine;
883         break;
884     case VKEY_RIGHT:
885         *scrollDirection = ScrollRight;
886         *scrollGranularity = ScrollByLine;
887         break;
888     case VKEY_UP:
889         *scrollDirection = ScrollUp;
890         *scrollGranularity = ScrollByLine;
891         break;
892     case VKEY_DOWN:
893         *scrollDirection = ScrollDown;
894         *scrollGranularity = ScrollByLine;
895         break;
896     case VKEY_HOME:
897         *scrollDirection = ScrollUp;
898         *scrollGranularity = ScrollByDocument;
899         break;
900     case VKEY_END:
901         *scrollDirection = ScrollDown;
902         *scrollGranularity = ScrollByDocument;
903         break;
904     case VKEY_PRIOR:  // page up
905         *scrollDirection = ScrollUp;
906         *scrollGranularity = ScrollByPage;
907         break;
908     case VKEY_NEXT:  // page down
909         *scrollDirection = ScrollDown;
910         *scrollGranularity = ScrollByPage;
911         break;
912     default:
913         return false;
914     }
915
916     return true;
917 }
918
919 void WebViewImpl::hideSelectPopup()
920 {
921     if (m_selectPopup.get())
922         m_selectPopup->hidePopup();
923 }
924
925 bool WebViewImpl::propagateScroll(ScrollDirection scrollDirection,
926                                   ScrollGranularity scrollGranularity)
927 {
928     Frame* frame = focusedWebCoreFrame();
929     if (!frame)
930         return false;
931
932     bool scrollHandled = frame->eventHandler()->scrollOverflow(scrollDirection, scrollGranularity);
933     Frame* currentFrame = frame;
934     while (!scrollHandled && currentFrame) {
935         scrollHandled = currentFrame->view()->scroll(scrollDirection, scrollGranularity);
936         currentFrame = currentFrame->tree()->parent();
937     }
938     return scrollHandled;
939 }
940
941 void  WebViewImpl::popupOpened(WebCore::PopupContainer* popupContainer)
942 {
943     if (popupContainer->popupType() == WebCore::PopupContainer::Select) {
944         ASSERT(!m_selectPopup);
945         m_selectPopup = popupContainer;
946     }
947 }
948
949 void  WebViewImpl::popupClosed(WebCore::PopupContainer* popupContainer)
950 {
951     if (popupContainer->popupType() == WebCore::PopupContainer::Select) {
952         ASSERT(m_selectPopup.get());
953         m_selectPopup = 0;
954     }
955 }
956
957 void WebViewImpl::hideAutofillPopup()
958 {
959     if (m_autofillPopupShowing) {
960         m_autofillPopup->hidePopup();
961         m_autofillPopupShowing = false;
962     }
963 }
964
965 Frame* WebViewImpl::focusedWebCoreFrame() const
966 {
967     return m_page.get() ? m_page->focusController()->focusedOrMainFrame() : 0;
968 }
969
970 WebViewImpl* WebViewImpl::fromPage(Page* page)
971 {
972     if (!page)
973         return 0;
974
975     ChromeClientImpl* chromeClient = static_cast<ChromeClientImpl*>(page->chrome()->client());
976     return static_cast<WebViewImpl*>(chromeClient->webView());
977 }
978
979 // WebWidget ------------------------------------------------------------------
980
981 void WebViewImpl::close()
982 {
983     RefPtr<WebFrameImpl> mainFrameImpl;
984
985     if (m_page.get()) {
986         // Initiate shutdown for the entire frameset.  This will cause a lot of
987         // notifications to be sent.
988         if (m_page->mainFrame()) {
989             mainFrameImpl = WebFrameImpl::fromFrame(m_page->mainFrame());
990             m_page->mainFrame()->loader()->frameDetached();
991         }
992         m_page.clear();
993     }
994
995     // Should happen after m_page.clear().
996     if (m_devToolsAgent.get())
997         m_devToolsAgent.clear();
998
999     // Reset the delegate to prevent notifications being sent as we're being
1000     // deleted.
1001     m_client = 0;
1002
1003     deref();  // Balances ref() acquired in WebView::create
1004 }
1005
1006 void WebViewImpl::willStartLiveResize()
1007 {
1008     if (mainFrameImpl() && mainFrameImpl()->frameView())
1009         mainFrameImpl()->frameView()->willStartLiveResize();
1010
1011     Frame* frame = mainFrameImpl()->frame();
1012     WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1013     if (pluginContainer)
1014         pluginContainer->willStartLiveResize();
1015 }
1016
1017 void WebViewImpl::resize(const WebSize& newSize)
1018 {
1019     if (m_size == newSize)
1020         return;
1021     m_size = newSize;
1022
1023     if (mainFrameImpl()->frameView()) {
1024         mainFrameImpl()->frameView()->resize(m_size.width, m_size.height);
1025         mainFrameImpl()->frame()->eventHandler()->sendResizeEvent();
1026     }
1027
1028     if (m_client) {
1029         if (isAcceleratedCompositingActive()) {
1030 #if USE(ACCELERATED_COMPOSITING)
1031             updateLayerTreeViewport();
1032 #endif
1033         } else {
1034             WebRect damagedRect(0, 0, m_size.width, m_size.height);
1035             m_client->didInvalidateRect(damagedRect);
1036         }
1037     }
1038 }
1039
1040 void WebViewImpl::willEndLiveResize()
1041 {
1042     if (mainFrameImpl() && mainFrameImpl()->frameView())
1043         mainFrameImpl()->frameView()->willEndLiveResize();
1044
1045     Frame* frame = mainFrameImpl()->frame();
1046     WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1047     if (pluginContainer)
1048         pluginContainer->willEndLiveResize();
1049 }
1050
1051 void WebViewImpl::animate(double frameBeginTime)
1052 {
1053 #if ENABLE(REQUEST_ANIMATION_FRAME)
1054     TRACE_EVENT("WebViewImpl::animate", this, 0);
1055     // FIXME: remove this zero-check once render_widget has been modified to
1056     // pass in a frameBeginTime.
1057     if (!frameBeginTime)
1058         frameBeginTime = currentTime();
1059     WebFrameImpl* webframe = mainFrameImpl();
1060     if (webframe) {
1061         FrameView* view = webframe->frameView();
1062         if (view) {
1063 #if !USE(THREADED_COMPOSITING)
1064             if (m_layerTreeHost)
1065                 m_layerTreeHost->setAnimating(true);
1066 #endif
1067             view->serviceScriptedAnimations(convertSecondsToDOMTimeStamp(frameBeginTime));
1068 #if !USE(THREADED_COMPOSITING)
1069             if (m_layerTreeHost)
1070                 m_layerTreeHost->setAnimating(false);
1071 #endif
1072         }
1073     }
1074 #endif
1075 }
1076
1077 void WebViewImpl::layout()
1078 {
1079     TRACE_EVENT("WebViewImpl::layout", this, 0);
1080
1081     WebFrameImpl* webframe = mainFrameImpl();
1082     if (webframe) {
1083         // In order for our child HWNDs (NativeWindowWidgets) to update properly,
1084         // they need to be told that we are updating the screen.  The problem is
1085         // that the native widgets need to recalculate their clip region and not
1086         // overlap any of our non-native widgets.  To force the resizing, call
1087         // setFrameRect().  This will be a quick operation for most frames, but
1088         // the NativeWindowWidgets will update a proper clipping region.
1089         FrameView* view = webframe->frameView();
1090         if (view)
1091             view->setFrameRect(view->frameRect());
1092
1093         // setFrameRect may have the side-effect of causing existing page
1094         // layout to be invalidated, so layout needs to be called last.
1095
1096         webframe->layout();
1097     }
1098 }
1099
1100 #if USE(ACCELERATED_COMPOSITING)
1101 void WebViewImpl::doPixelReadbackToCanvas(WebCanvas* canvas, const IntRect& rect)
1102 {
1103 #if USE(SKIA)
1104     PlatformContextSkia context(canvas);
1105
1106     // PlatformGraphicsContext is actually a pointer to PlatformContextSkia
1107     GraphicsContext gc(reinterpret_cast<PlatformGraphicsContext*>(&context));
1108     int bitmapHeight = canvas->getDevice()->accessBitmap(false).height();
1109 #elif USE(CG)
1110     GraphicsContext gc(canvas);
1111     int bitmapHeight = CGBitmapContextGetHeight(reinterpret_cast<CGContextRef>(canvas));
1112 #else
1113     notImplemented();
1114 #endif
1115     // Compute rect to sample from inverted GPU buffer.
1116     IntRect invertRect(rect.x(), bitmapHeight - rect.maxY(), rect.width(), rect.height());
1117
1118     OwnPtr<ImageBuffer> imageBuffer(ImageBuffer::create(rect.size()));
1119     RefPtr<ByteArray> pixelArray(ByteArray::create(rect.width() * rect.height() * 4));
1120     if (imageBuffer.get() && pixelArray.get()) {
1121         m_layerTreeHost->compositeAndReadback(pixelArray->data(), invertRect);
1122         imageBuffer->putPremultipliedImageData(pixelArray.get(), rect.size(), IntRect(IntPoint(), rect.size()), IntPoint());
1123         gc.save();
1124         gc.translate(IntSize(0, bitmapHeight));
1125         gc.scale(FloatSize(1.0f, -1.0f));
1126         // Use invertRect in next line, so that transform above inverts it back to
1127         // desired destination rect.
1128         gc.drawImageBuffer(imageBuffer.get(), ColorSpaceDeviceRGB, invertRect.location());
1129         gc.restore();
1130     }
1131 }
1132 #endif
1133
1134 void WebViewImpl::paint(WebCanvas* canvas, const WebRect& rect)
1135 {
1136     if (isAcceleratedCompositingActive()) {
1137 #if USE(ACCELERATED_COMPOSITING)
1138         // If a canvas was passed in, we use it to grab a copy of the
1139         // freshly-rendered pixels.
1140         if (canvas) {
1141             // Clip rect to the confines of the rootLayerTexture.
1142             IntRect resizeRect(rect);
1143             resizeRect.intersect(IntRect(IntPoint(0, 0), m_layerTreeHost->viewportVisibleRect().size()));
1144             doPixelReadbackToCanvas(canvas, resizeRect);
1145         }
1146 #endif
1147     } else {
1148         double paintStart = currentTime();
1149         WebFrameImpl* webframe = mainFrameImpl();
1150         if (webframe)
1151             webframe->paint(canvas, rect);
1152         double paintEnd = currentTime();
1153         double pixelsPerSec = (rect.width * rect.height) / (paintEnd - paintStart);
1154         PlatformBridge::histogramCustomCounts("Renderer4.SoftwarePaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30);
1155         PlatformBridge::histogramCustomCounts("Renderer4.SoftwarePaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30);
1156     }
1157 }
1158
1159 void WebViewImpl::themeChanged()
1160 {
1161     if (!page())
1162         return;
1163     FrameView* view = page()->mainFrame()->view();
1164
1165     WebRect damagedRect(0, 0, m_size.width, m_size.height);
1166     view->invalidateRect(damagedRect);
1167 }
1168
1169 void WebViewImpl::composite(bool finish)
1170 {
1171 #if USE(ACCELERATED_COMPOSITING)
1172 #if USE(THREADED_COMPOSITING)
1173     m_layerTreeHost->setNeedsRedraw();
1174 #else
1175     ASSERT(isAcceleratedCompositingActive());
1176     if (!page())
1177         return;
1178
1179     if (m_pageOverlay)
1180         m_pageOverlay->update();
1181
1182     m_layerTreeHost->composite(finish);
1183 #endif
1184 #endif
1185 }
1186
1187 const WebInputEvent* WebViewImpl::m_currentInputEvent = 0;
1188
1189 bool WebViewImpl::handleInputEvent(const WebInputEvent& inputEvent)
1190 {
1191     UserGestureIndicator gestureIndicator(WebInputEvent::isUserGestureEventType(inputEvent.type) ? DefinitelyProcessingUserGesture : PossiblyProcessingUserGesture);
1192
1193     // If we've started a drag and drop operation, ignore input events until
1194     // we're done.
1195     if (m_doingDragAndDrop)
1196         return true;
1197
1198     if (m_ignoreInputEvents)
1199         return true;
1200
1201     m_currentInputEvent = &inputEvent;
1202
1203     if (m_mouseCaptureNode.get() && WebInputEvent::isMouseEventType(inputEvent.type)) {
1204         // Save m_mouseCaptureNode since mouseCaptureLost() will clear it.
1205         RefPtr<Node> node = m_mouseCaptureNode;
1206
1207         // Not all platforms call mouseCaptureLost() directly.
1208         if (inputEvent.type == WebInputEvent::MouseUp)
1209             mouseCaptureLost();
1210
1211         AtomicString eventType;
1212         switch (inputEvent.type) {
1213         case WebInputEvent::MouseMove:
1214             eventType = eventNames().mousemoveEvent;
1215             break;
1216         case WebInputEvent::MouseLeave:
1217             eventType = eventNames().mouseoutEvent;
1218             break;
1219         case WebInputEvent::MouseDown:
1220             eventType = eventNames().mousedownEvent;
1221             break;
1222         case WebInputEvent::MouseUp:
1223             eventType = eventNames().mouseupEvent;
1224             break;
1225         default:
1226             ASSERT_NOT_REACHED();
1227         }
1228
1229         node->dispatchMouseEvent(
1230               PlatformMouseEventBuilder(mainFrameImpl()->frameView(), *static_cast<const WebMouseEvent*>(&inputEvent)),
1231               eventType, static_cast<const WebMouseEvent*>(&inputEvent)->clickCount);
1232         m_currentInputEvent = 0;
1233         return true;
1234     }
1235
1236     bool handled = true;
1237
1238     // FIXME: WebKit seems to always return false on mouse events processing
1239     // methods. For now we'll assume it has processed them (as we are only
1240     // interested in whether keyboard events are processed).
1241     switch (inputEvent.type) {
1242     case WebInputEvent::MouseMove:
1243         mouseMove(*static_cast<const WebMouseEvent*>(&inputEvent));
1244         break;
1245
1246     case WebInputEvent::MouseLeave:
1247         mouseLeave(*static_cast<const WebMouseEvent*>(&inputEvent));
1248         break;
1249
1250     case WebInputEvent::MouseWheel:
1251         handled = mouseWheel(*static_cast<const WebMouseWheelEvent*>(&inputEvent));
1252         break;
1253
1254     case WebInputEvent::MouseDown:
1255         mouseDown(*static_cast<const WebMouseEvent*>(&inputEvent));
1256         break;
1257
1258     case WebInputEvent::MouseUp:
1259         mouseUp(*static_cast<const WebMouseEvent*>(&inputEvent));
1260         break;
1261
1262     case WebInputEvent::RawKeyDown:
1263     case WebInputEvent::KeyDown:
1264     case WebInputEvent::KeyUp:
1265         handled = keyEvent(*static_cast<const WebKeyboardEvent*>(&inputEvent));
1266         break;
1267
1268     case WebInputEvent::Char:
1269         handled = charEvent(*static_cast<const WebKeyboardEvent*>(&inputEvent));
1270         break;
1271
1272 #if ENABLE(GESTURE_EVENTS)
1273     case WebInputEvent::GestureScrollBegin:
1274     case WebInputEvent::GestureScrollEnd:
1275         handled = gestureEvent(*static_cast<const WebGestureEvent*>(&inputEvent));
1276         break;
1277 #endif
1278
1279 #if ENABLE(TOUCH_EVENTS)
1280     case WebInputEvent::TouchStart:
1281     case WebInputEvent::TouchMove:
1282     case WebInputEvent::TouchEnd:
1283     case WebInputEvent::TouchCancel:
1284         handled = touchEvent(*static_cast<const WebTouchEvent*>(&inputEvent));
1285         break;
1286 #endif
1287
1288     default:
1289         handled = false;
1290     }
1291
1292     m_currentInputEvent = 0;
1293
1294     return handled;
1295 }
1296
1297 void WebViewImpl::mouseCaptureLost()
1298 {
1299     m_mouseCaptureNode = 0;
1300 }
1301
1302 void WebViewImpl::setFocus(bool enable)
1303 {
1304     m_page->focusController()->setFocused(enable);
1305     if (enable) {
1306         // Note that we don't call setActive() when disabled as this cause extra
1307         // focus/blur events to be dispatched.
1308         m_page->focusController()->setActive(true);
1309         RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
1310         if (focusedFrame) {
1311             Node* focusedNode = focusedFrame->document()->focusedNode();
1312             if (focusedNode && focusedNode->isElementNode()
1313                 && focusedFrame->selection()->selection().isNone()) {
1314                 // If the selection was cleared while the WebView was not
1315                 // focused, then the focus element shows with a focus ring but
1316                 // no caret and does respond to keyboard inputs.
1317                 Element* element = static_cast<Element*>(focusedNode);
1318                 if (element->isTextFormControl())
1319                     element->updateFocusAppearance(true);
1320                 else if (focusedNode->isContentEditable()) {
1321                     // updateFocusAppearance() selects all the text of
1322                     // contentseditable DIVs. So we set the selection explicitly
1323                     // instead. Note that this has the side effect of moving the
1324                     // caret back to the beginning of the text.
1325                     Position position(focusedNode, 0,
1326                                       Position::PositionIsOffsetInAnchor);
1327                     focusedFrame->selection()->setSelection(
1328                         VisibleSelection(position, SEL_DEFAULT_AFFINITY));
1329                 }
1330             }
1331         }
1332         m_imeAcceptEvents = true;
1333     } else {
1334         hideAutofillPopup();
1335         hideSelectPopup();
1336
1337         // Clear focus on the currently focused frame if any.
1338         if (!m_page.get())
1339             return;
1340
1341         Frame* frame = m_page->mainFrame();
1342         if (!frame)
1343             return;
1344
1345         RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
1346         if (focusedFrame.get()) {
1347             // Finish an ongoing composition to delete the composition node.
1348             Editor* editor = focusedFrame->editor();
1349             if (editor && editor->hasComposition())
1350                 editor->confirmComposition();
1351             m_imeAcceptEvents = false;
1352         }
1353     }
1354 }
1355
1356 bool WebViewImpl::setComposition(
1357     const WebString& text,
1358     const WebVector<WebCompositionUnderline>& underlines,
1359     int selectionStart,
1360     int selectionEnd)
1361 {
1362     Frame* focused = focusedWebCoreFrame();
1363     if (!focused || !m_imeAcceptEvents)
1364         return false;
1365     Editor* editor = focused->editor();
1366     if (!editor)
1367         return false;
1368
1369     // The input focus has been moved to another WebWidget object.
1370     // We should use this |editor| object only to complete the ongoing
1371     // composition.
1372     if (!editor->canEdit() && !editor->hasComposition())
1373         return false;
1374
1375     // We should verify the parent node of this IME composition node are
1376     // editable because JavaScript may delete a parent node of the composition
1377     // node. In this case, WebKit crashes while deleting texts from the parent
1378     // node, which doesn't exist any longer.
1379     PassRefPtr<Range> range = editor->compositionRange();
1380     if (range) {
1381         Node* node = range->startContainer();
1382         if (!node || !node->isContentEditable())
1383             return false;
1384     }
1385
1386     // If we're not going to fire a keypress event, then the keydown event was
1387     // canceled.  In that case, cancel any existing composition.
1388     if (text.isEmpty() || m_suppressNextKeypressEvent) {
1389         // A browser process sent an IPC message which does not contain a valid
1390         // string, which means an ongoing composition has been canceled.
1391         // If the ongoing composition has been canceled, replace the ongoing
1392         // composition string with an empty string and complete it.
1393         String emptyString;
1394         Vector<CompositionUnderline> emptyUnderlines;
1395         editor->setComposition(emptyString, emptyUnderlines, 0, 0);
1396         return text.isEmpty();
1397     }
1398
1399     // When the range of composition underlines overlap with the range between
1400     // selectionStart and selectionEnd, WebKit somehow won't paint the selection
1401     // at all (see InlineTextBox::paint() function in InlineTextBox.cpp).
1402     // But the selection range actually takes effect.
1403     editor->setComposition(String(text),
1404                            CompositionUnderlineVectorBuilder(underlines),
1405                            selectionStart, selectionEnd);
1406
1407     return editor->hasComposition();
1408 }
1409
1410 bool WebViewImpl::confirmComposition()
1411 {
1412     return confirmComposition(WebString());
1413 }
1414
1415 bool WebViewImpl::confirmComposition(const WebString& text)
1416 {
1417     Frame* focused = focusedWebCoreFrame();
1418     if (!focused || !m_imeAcceptEvents)
1419         return false;
1420     Editor* editor = focused->editor();
1421     if (!editor || (!editor->hasComposition() && !text.length()))
1422         return false;
1423
1424     // We should verify the parent node of this IME composition node are
1425     // editable because JavaScript may delete a parent node of the composition
1426     // node. In this case, WebKit crashes while deleting texts from the parent
1427     // node, which doesn't exist any longer.
1428     PassRefPtr<Range> range = editor->compositionRange();
1429     if (range) {
1430         Node* node = range->startContainer();
1431         if (!node || !node->isContentEditable())
1432             return false;
1433     }
1434
1435     if (editor->hasComposition()) {
1436         if (text.length())
1437             editor->confirmComposition(String(text));
1438         else
1439             editor->confirmComposition();
1440     } else
1441         editor->insertText(String(text), 0);
1442
1443     return true;
1444 }
1445
1446 bool WebViewImpl::compositionRange(size_t* location, size_t* length)
1447 {
1448     Frame* focused = focusedWebCoreFrame();
1449     if (!focused || !m_imeAcceptEvents)
1450         return false;
1451     Editor* editor = focused->editor();
1452     if (!editor || !editor->hasComposition())
1453         return false;
1454
1455     RefPtr<Range> range = editor->compositionRange();
1456     if (!range.get())
1457         return false;
1458
1459     if (TextIterator::locationAndLengthFromRange(range.get(), *location, *length))
1460         return true;
1461     return false;
1462 }
1463
1464 WebTextInputType WebViewImpl::textInputType()
1465 {
1466     Node* node = focusedWebCoreNode();
1467     if (!node)
1468         return WebTextInputTypeNone;
1469
1470     if (node->nodeType() == Node::ELEMENT_NODE) {
1471         Element* element = static_cast<Element*>(node);
1472         if (element->hasLocalName(HTMLNames::inputTag)) {
1473             HTMLInputElement* input = static_cast<HTMLInputElement*>(element);
1474
1475             if (input->readOnly() || input->disabled())
1476                 return WebTextInputTypeNone;
1477
1478             if (input->isPasswordField())
1479                 return WebTextInputTypePassword;
1480             if (input->isSearchField())
1481                 return WebTextInputTypeSearch;
1482             if (input->isEmailField())
1483                 return WebTextInputTypeEmail;
1484             if (input->isNumberField())
1485                 return WebTextInputTypeNumber;
1486             if (input->isTelephoneField())
1487                 return WebTextInputTypeTelephone;
1488             if (input->isURLField())
1489                 return WebTextInputTypeURL;
1490             if (input->isTextField())
1491                 return WebTextInputTypeText;
1492             return WebTextInputTypeNone;
1493         }
1494
1495         if (element->hasLocalName(HTMLNames::textareaTag)) {
1496             HTMLTextAreaElement* textarea = static_cast<HTMLTextAreaElement*>(element);
1497
1498             if (textarea->readOnly() || textarea->disabled())
1499                 return WebTextInputTypeNone;
1500             return WebTextInputTypeText;
1501         }
1502     }
1503
1504     // For other situations.
1505     if (node->shouldUseInputMethod())
1506         return WebTextInputTypeText;
1507
1508     return WebTextInputTypeNone;
1509 }
1510
1511 WebRect WebViewImpl::caretOrSelectionBounds()
1512 {
1513     WebRect rect;
1514     const Frame* focused = focusedWebCoreFrame();
1515     if (!focused)
1516         return rect;
1517
1518     FrameSelection* selection = focused->selection();
1519     if (!selection)
1520         return rect;
1521
1522     const FrameView* view = focused->view();
1523     if (!view)
1524         return rect;
1525
1526     const Node* node = selection->base().containerNode();
1527     if (!node || !node->renderer())
1528         return rect;
1529
1530     if (selection->isCaret())
1531         rect = view->contentsToWindow(selection->absoluteCaretBounds());
1532     else if (selection->isRange()) {
1533         node = selection->extent().containerNode();
1534         RefPtr<Range> range = selection->toNormalizedRange();
1535         if (!node || !node->renderer() || !range)
1536             return rect;
1537         rect = view->contentsToWindow(focused->editor()->firstRectForRange(range.get()));
1538     }
1539     return rect;
1540 }
1541
1542 bool WebViewImpl::selectionRange(WebPoint& start, WebPoint& end) const
1543 {
1544     const Frame* frame = focusedWebCoreFrame();
1545     if (!frame || !frame->selection()->isRange())
1546         return false;
1547     RefPtr<Range> selectedRange = frame->selection()->toNormalizedRange();
1548     if (!selectedRange)
1549         return false;
1550     RefPtr<Range> range(Range::create(selectedRange->startContainer()->document(),
1551                                       selectedRange->startContainer(),
1552                                       selectedRange->startOffset(),
1553                                       selectedRange->startContainer(),
1554                                       selectedRange->startOffset()));
1555
1556     IntRect rect = frame->editor()->firstRectForRange(range.get());
1557     start.x = rect.x();
1558     start.y = rect.y() + rect.height() - 1;
1559
1560     range = Range::create(selectedRange->endContainer()->document(),
1561                           selectedRange->endContainer(),
1562                           selectedRange->endOffset(),
1563                           selectedRange->endContainer(),
1564                           selectedRange->endOffset());
1565
1566     rect = frame->editor()->firstRectForRange(range.get());
1567     end.x = rect.x() + rect.width() - 1;
1568     end.y = rect.y() + rect.height() - 1;
1569
1570     start = frame->view()->contentsToWindow(start);
1571     end = frame->view()->contentsToWindow(end);
1572     return true;
1573 }
1574
1575 bool WebViewImpl::caretOrSelectionRange(size_t* location, size_t* length)
1576 {
1577     const Frame* focused = focusedWebCoreFrame();
1578     if (!focused)
1579         return false;
1580
1581     FrameSelection* selection = focused->selection();
1582     if (!selection)
1583         return false;
1584
1585     RefPtr<Range> range = selection->selection().firstRange();
1586     if (!range.get())
1587         return false;
1588
1589     if (TextIterator::locationAndLengthFromRange(range.get(), *location, *length))
1590         return true;
1591     return false;
1592 }
1593
1594 void WebViewImpl::setTextDirection(WebTextDirection direction)
1595 {
1596     // The Editor::setBaseWritingDirection() function checks if we can change
1597     // the text direction of the selected node and updates its DOM "dir"
1598     // attribute and its CSS "direction" property.
1599     // So, we just call the function as Safari does.
1600     const Frame* focused = focusedWebCoreFrame();
1601     if (!focused)
1602         return;
1603
1604     Editor* editor = focused->editor();
1605     if (!editor || !editor->canEdit())
1606         return;
1607
1608     switch (direction) {
1609     case WebTextDirectionDefault:
1610         editor->setBaseWritingDirection(NaturalWritingDirection);
1611         break;
1612
1613     case WebTextDirectionLeftToRight:
1614         editor->setBaseWritingDirection(LeftToRightWritingDirection);
1615         break;
1616
1617     case WebTextDirectionRightToLeft:
1618         editor->setBaseWritingDirection(RightToLeftWritingDirection);
1619         break;
1620
1621     default:
1622         notImplemented();
1623         break;
1624     }
1625 }
1626
1627 bool WebViewImpl::isAcceleratedCompositingActive() const
1628 {
1629 #if USE(ACCELERATED_COMPOSITING)
1630     return m_isAcceleratedCompositingActive;
1631 #else
1632     return false;
1633 #endif
1634 }
1635
1636 // WebView --------------------------------------------------------------------
1637
1638 WebSettings* WebViewImpl::settings()
1639 {
1640     if (!m_webSettings)
1641         m_webSettings = adoptPtr(new WebSettingsImpl(m_page->settings()));
1642     ASSERT(m_webSettings.get());
1643     return m_webSettings.get();
1644 }
1645
1646 WebString WebViewImpl::pageEncoding() const
1647 {
1648     if (!m_page.get())
1649         return WebString();
1650
1651     return m_page->mainFrame()->document()->loader()->writer()->encoding();
1652 }
1653
1654 void WebViewImpl::setPageEncoding(const WebString& encodingName)
1655 {
1656     if (!m_page.get())
1657         return;
1658
1659     // Only change override encoding, don't change default encoding.
1660     // Note that the new encoding must be 0 if it isn't supposed to be set.
1661     String newEncodingName;
1662     if (!encodingName.isEmpty())
1663         newEncodingName = encodingName;
1664     m_page->mainFrame()->loader()->reloadWithOverrideEncoding(newEncodingName);
1665 }
1666
1667 bool WebViewImpl::dispatchBeforeUnloadEvent()
1668 {
1669     // FIXME: This should really cause a recursive depth-first walk of all
1670     // frames in the tree, calling each frame's onbeforeunload.  At the moment,
1671     // we're consistent with Safari 3.1, not IE/FF.
1672     Frame* frame = m_page->mainFrame();
1673     if (!frame)
1674         return true;
1675
1676     return frame->loader()->shouldClose();
1677 }
1678
1679 void WebViewImpl::dispatchUnloadEvent()
1680 {
1681     // Run unload handlers.
1682     m_page->mainFrame()->loader()->closeURL();
1683 }
1684
1685 WebFrame* WebViewImpl::mainFrame()
1686 {
1687     return mainFrameImpl();
1688 }
1689
1690 WebFrame* WebViewImpl::findFrameByName(
1691     const WebString& name, WebFrame* relativeToFrame)
1692 {
1693     if (!relativeToFrame)
1694         relativeToFrame = mainFrame();
1695     Frame* frame = static_cast<WebFrameImpl*>(relativeToFrame)->frame();
1696     frame = frame->tree()->find(name);
1697     return WebFrameImpl::fromFrame(frame);
1698 }
1699
1700 WebFrame* WebViewImpl::focusedFrame()
1701 {
1702     return WebFrameImpl::fromFrame(focusedWebCoreFrame());
1703 }
1704
1705 void WebViewImpl::setFocusedFrame(WebFrame* frame)
1706 {
1707     if (!frame) {
1708         // Clears the focused frame if any.
1709         Frame* frame = focusedWebCoreFrame();
1710         if (frame)
1711             frame->selection()->setFocused(false);
1712         return;
1713     }
1714     WebFrameImpl* frameImpl = static_cast<WebFrameImpl*>(frame);
1715     Frame* webcoreFrame = frameImpl->frame();
1716     webcoreFrame->page()->focusController()->setFocusedFrame(webcoreFrame);
1717 }
1718
1719 void WebViewImpl::setInitialFocus(bool reverse)
1720 {
1721     if (!m_page.get())
1722         return;
1723
1724     // Since we don't have a keyboard event, we'll create one.
1725     WebKeyboardEvent keyboardEvent;
1726     keyboardEvent.type = WebInputEvent::RawKeyDown;
1727     if (reverse)
1728         keyboardEvent.modifiers = WebInputEvent::ShiftKey;
1729
1730     // VK_TAB which is only defined on Windows.
1731     keyboardEvent.windowsKeyCode = 0x09;
1732     PlatformKeyboardEventBuilder platformEvent(keyboardEvent);
1733     RefPtr<KeyboardEvent> webkitEvent = KeyboardEvent::create(platformEvent, 0);
1734
1735     Frame* frame = page()->focusController()->focusedOrMainFrame();
1736     if (Document* document = frame->document())
1737         document->setFocusedNode(0);
1738     page()->focusController()->setInitialFocus(
1739         reverse ? FocusDirectionBackward : FocusDirectionForward,
1740         webkitEvent.get());
1741 }
1742
1743 void WebViewImpl::clearFocusedNode()
1744 {
1745     if (!m_page.get())
1746         return;
1747
1748     RefPtr<Frame> frame = m_page->mainFrame();
1749     if (!frame.get())
1750         return;
1751
1752     RefPtr<Document> document = frame->document();
1753     if (!document.get())
1754         return;
1755
1756     RefPtr<Node> oldFocusedNode = document->focusedNode();
1757
1758     // Clear the focused node.
1759     document->setFocusedNode(0);
1760
1761     if (!oldFocusedNode.get())
1762         return;
1763
1764     // If a text field has focus, we need to make sure the selection controller
1765     // knows to remove selection from it. Otherwise, the text field is still
1766     // processing keyboard events even though focus has been moved to the page and
1767     // keystrokes get eaten as a result.
1768     if (oldFocusedNode->hasTagName(HTMLNames::textareaTag)
1769         || (oldFocusedNode->hasTagName(HTMLNames::inputTag)
1770             && static_cast<HTMLInputElement*>(oldFocusedNode.get())->isTextField())) {
1771         frame->selection()->clear();
1772     }
1773 }
1774
1775 void WebViewImpl::scrollFocusedNodeIntoView()
1776 {
1777     Node* focusedNode = focusedWebCoreNode();
1778     if (focusedNode && focusedNode->isElementNode()) {
1779         Element* elementNode = static_cast<Element*>(focusedNode);
1780         elementNode->scrollIntoViewIfNeeded(true);
1781     }
1782 }
1783
1784 double WebViewImpl::zoomLevel()
1785 {
1786     return m_zoomLevel;
1787 }
1788
1789 double WebViewImpl::setZoomLevel(bool textOnly, double zoomLevel)
1790 {
1791     if (zoomLevel < m_minimumZoomLevel)
1792         m_zoomLevel = m_minimumZoomLevel;
1793     else if (zoomLevel > m_maximumZoomLevel)
1794         m_zoomLevel = m_maximumZoomLevel;
1795     else
1796         m_zoomLevel = zoomLevel;
1797
1798     Frame* frame = mainFrameImpl()->frame();
1799     WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1800     if (pluginContainer)
1801         pluginContainer->plugin()->setZoomLevel(m_zoomLevel, textOnly);
1802     else {
1803         float zoomFactor = static_cast<float>(zoomLevelToZoomFactor(m_zoomLevel));
1804         if (textOnly)
1805             frame->setPageAndTextZoomFactors(1, zoomFactor);
1806         else
1807             frame->setPageAndTextZoomFactors(zoomFactor, 1);
1808     }
1809     return m_zoomLevel;
1810 }
1811
1812 void WebViewImpl::zoomLimitsChanged(double minimumZoomLevel,
1813                                     double maximumZoomLevel)
1814 {
1815     m_minimumZoomLevel = minimumZoomLevel;
1816     m_maximumZoomLevel = maximumZoomLevel;
1817     m_client->zoomLimitsChanged(m_minimumZoomLevel, m_maximumZoomLevel);
1818 }
1819
1820 void WebViewImpl::fullFramePluginZoomLevelChanged(double zoomLevel)
1821 {
1822     if (zoomLevel == m_zoomLevel)
1823         return;
1824
1825     m_zoomLevel = max(min(zoomLevel, m_maximumZoomLevel), m_minimumZoomLevel);
1826     m_client->zoomLevelChanged();
1827 }
1828
1829 double WebView::zoomLevelToZoomFactor(double zoomLevel)
1830 {
1831     return pow(textSizeMultiplierRatio, zoomLevel);
1832 }
1833
1834 double WebView::zoomFactorToZoomLevel(double factor)
1835 {
1836     // Since factor = 1.2^level, level = log(factor) / log(1.2)
1837     return log(factor) / log(textSizeMultiplierRatio);
1838 }
1839
1840 void WebViewImpl::scalePage(float scaleFactor, WebPoint origin)
1841 {
1842     if (!page())
1843         return;
1844
1845     Frame* frame = page()->mainFrame();
1846     if (!frame)
1847         return;
1848
1849     frame->scalePage(scaleFactor, origin);
1850 }
1851
1852 void WebViewImpl::performMediaPlayerAction(const WebMediaPlayerAction& action,
1853                                            const WebPoint& location)
1854 {
1855     HitTestResult result = hitTestResultForWindowPos(location);
1856     RefPtr<Node> node = result.innerNonSharedNode();
1857     if (!node->hasTagName(HTMLNames::videoTag) && !node->hasTagName(HTMLNames::audioTag))
1858       return;
1859
1860     RefPtr<HTMLMediaElement> mediaElement =
1861         static_pointer_cast<HTMLMediaElement>(node);
1862     switch (action.type) {
1863     case WebMediaPlayerAction::Play:
1864         if (action.enable)
1865             mediaElement->play();
1866         else
1867             mediaElement->pause();
1868         break;
1869     case WebMediaPlayerAction::Mute:
1870         mediaElement->setMuted(action.enable);
1871         break;
1872     case WebMediaPlayerAction::Loop:
1873         mediaElement->setLoop(action.enable);
1874         break;
1875     case WebMediaPlayerAction::Controls:
1876         mediaElement->setControls(action.enable);
1877         break;
1878     default:
1879         ASSERT_NOT_REACHED();
1880     }
1881 }
1882
1883 void WebViewImpl::copyImageAt(const WebPoint& point)
1884 {
1885     if (!m_page.get())
1886         return;
1887
1888     HitTestResult result = hitTestResultForWindowPos(point);
1889
1890     if (result.absoluteImageURL().isEmpty()) {
1891         // There isn't actually an image at these coordinates.  Might be because
1892         // the window scrolled while the context menu was open or because the page
1893         // changed itself between when we thought there was an image here and when
1894         // we actually tried to retreive the image.
1895         //
1896         // FIXME: implement a cache of the most recent HitTestResult to avoid having
1897         //        to do two hit tests.
1898         return;
1899     }
1900
1901     m_page->mainFrame()->editor()->copyImage(result);
1902 }
1903
1904 void WebViewImpl::dragSourceEndedAt(
1905     const WebPoint& clientPoint,
1906     const WebPoint& screenPoint,
1907     WebDragOperation operation)
1908 {
1909     PlatformMouseEvent pme(clientPoint,
1910                            screenPoint,
1911                            LeftButton, MouseEventMoved, 0, false, false, false,
1912                            false, 0);
1913     m_page->mainFrame()->eventHandler()->dragSourceEndedAt(pme,
1914         static_cast<DragOperation>(operation));
1915     m_dragScrollTimer->stop();
1916 }
1917
1918 void WebViewImpl::dragSourceMovedTo(
1919     const WebPoint& clientPoint,
1920     const WebPoint& screenPoint,
1921     WebDragOperation operation)
1922 {
1923     m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
1924 }
1925
1926 void WebViewImpl::dragSourceSystemDragEnded()
1927 {
1928     // It's possible for us to get this callback while not doing a drag if
1929     // it's from a previous page that got unloaded.
1930     if (m_doingDragAndDrop) {
1931         m_page->dragController()->dragEnded();
1932         m_doingDragAndDrop = false;
1933     }
1934 }
1935
1936 WebDragOperation WebViewImpl::dragTargetDragEnter(
1937     const WebDragData& webDragData,
1938     const WebPoint& clientPoint,
1939     const WebPoint& screenPoint,
1940     WebDragOperationsMask operationsAllowed)
1941 {
1942     ASSERT(!m_currentDragData.get());
1943
1944     m_currentDragData = webDragData;
1945     m_operationsAllowed = operationsAllowed;
1946
1947     return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragEnter);
1948 }
1949
1950 WebDragOperation WebViewImpl::dragTargetDragOver(
1951     const WebPoint& clientPoint,
1952     const WebPoint& screenPoint,
1953     WebDragOperationsMask operationsAllowed)
1954 {
1955     m_operationsAllowed = operationsAllowed;
1956
1957     return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragOver);
1958 }
1959
1960 void WebViewImpl::dragTargetDragLeave()
1961 {
1962     ASSERT(m_currentDragData.get());
1963
1964     DragData dragData(
1965         m_currentDragData.get(),
1966         IntPoint(),
1967         IntPoint(),
1968         static_cast<DragOperation>(m_operationsAllowed));
1969
1970     m_page->dragController()->dragExited(&dragData);
1971
1972     // FIXME: why is the drag scroll timer not stopped here?
1973
1974     m_dragOperation = WebDragOperationNone;
1975     m_currentDragData = 0;
1976 }
1977
1978 void WebViewImpl::dragTargetDrop(const WebPoint& clientPoint,
1979                                  const WebPoint& screenPoint)
1980 {
1981     ASSERT(m_currentDragData.get());
1982
1983     // If this webview transitions from the "drop accepting" state to the "not
1984     // accepting" state, then our IPC message reply indicating that may be in-
1985     // flight, or else delayed by javascript processing in this webview.  If a
1986     // drop happens before our IPC reply has reached the browser process, then
1987     // the browser forwards the drop to this webview.  So only allow a drop to
1988     // proceed if our webview m_dragOperation state is not DragOperationNone.
1989
1990     if (m_dragOperation == WebDragOperationNone) { // IPC RACE CONDITION: do not allow this drop.
1991         dragTargetDragLeave();
1992         return;
1993     }
1994
1995     DragData dragData(
1996         m_currentDragData.get(),
1997         clientPoint,
1998         screenPoint,
1999         static_cast<DragOperation>(m_operationsAllowed));
2000
2001     m_page->dragController()->performDrag(&dragData);
2002
2003     m_dragOperation = WebDragOperationNone;
2004     m_currentDragData = 0;
2005
2006     m_dragScrollTimer->stop();
2007 }
2008
2009 WebDragOperation WebViewImpl::dragTargetDragEnterOrOver(const WebPoint& clientPoint, const WebPoint& screenPoint, DragAction dragAction)
2010 {
2011     ASSERT(m_currentDragData.get());
2012
2013     DragData dragData(
2014         m_currentDragData.get(),
2015         clientPoint,
2016         screenPoint,
2017         static_cast<DragOperation>(m_operationsAllowed));
2018
2019     DragOperation dropEffect;
2020     if (dragAction == DragEnter)
2021         dropEffect = m_page->dragController()->dragEntered(&dragData);
2022     else
2023         dropEffect = m_page->dragController()->dragUpdated(&dragData);
2024
2025     // Mask the drop effect operation against the drag source's allowed operations.
2026     if (!(dropEffect & dragData.draggingSourceOperationMask()))
2027         dropEffect = DragOperationNone;
2028
2029      m_dragOperation = static_cast<WebDragOperation>(dropEffect);
2030
2031     if (dragAction == DragOver)
2032         m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
2033     else
2034         m_dragScrollTimer->stop();
2035
2036     return m_dragOperation;
2037 }
2038
2039 unsigned long WebViewImpl::createUniqueIdentifierForRequest()
2040 {
2041     if (m_page)
2042         return m_page->progress()->createUniqueIdentifier();
2043     return 0;
2044 }
2045
2046 void WebViewImpl::inspectElementAt(const WebPoint& point)
2047 {
2048     if (!m_page.get())
2049         return;
2050
2051     if (point.x == -1 || point.y == -1)
2052         m_page->inspectorController()->inspect(0);
2053     else {
2054         HitTestResult result = hitTestResultForWindowPos(point);
2055
2056         if (!result.innerNonSharedNode())
2057             return;
2058
2059         m_page->inspectorController()->inspect(result.innerNonSharedNode());
2060     }
2061 }
2062
2063 WebString WebViewImpl::inspectorSettings() const
2064 {
2065     return m_inspectorSettings;
2066 }
2067
2068 void WebViewImpl::setInspectorSettings(const WebString& settings)
2069 {
2070     m_inspectorSettings = settings;
2071 }
2072
2073 bool WebViewImpl::inspectorSetting(const WebString& key, WebString* value) const
2074 {
2075     if (!m_inspectorSettingsMap->contains(key))
2076         return false;
2077     *value = m_inspectorSettingsMap->get(key);
2078     return true;
2079 }
2080
2081 void WebViewImpl::setInspectorSetting(const WebString& key,
2082                                       const WebString& value)
2083 {
2084     m_inspectorSettingsMap->set(key, value);
2085     client()->didUpdateInspectorSetting(key, value);
2086 }
2087
2088 WebDevToolsAgent* WebViewImpl::devToolsAgent()
2089 {
2090     return m_devToolsAgent.get();
2091 }
2092
2093 WebAccessibilityObject WebViewImpl::accessibilityObject()
2094 {
2095     if (!mainFrameImpl())
2096         return WebAccessibilityObject();
2097
2098     Document* document = mainFrameImpl()->frame()->document();
2099     return WebAccessibilityObject(
2100         document->axObjectCache()->getOrCreate(document->renderer()));
2101 }
2102
2103 void WebViewImpl::applyAutofillSuggestions(
2104     const WebNode& node,
2105     const WebVector<WebString>& names,
2106     const WebVector<WebString>& labels,
2107     const WebVector<WebString>& icons,
2108     const WebVector<int>& uniqueIDs,
2109     int separatorIndex)
2110 {
2111     ASSERT(names.size() == labels.size());
2112     ASSERT(names.size() == uniqueIDs.size());
2113     ASSERT(separatorIndex < static_cast<int>(names.size()));
2114
2115     if (names.isEmpty()) {
2116         hideAutofillPopup();
2117         return;
2118     }
2119
2120     RefPtr<Node> focusedNode = focusedWebCoreNode();
2121     // If the node for which we queried the Autofill suggestions is not the
2122     // focused node, then we have nothing to do.  FIXME: also check the
2123     // caret is at the end and that the text has not changed.
2124     if (!focusedNode || focusedNode != PassRefPtr<Node>(node)) {
2125         hideAutofillPopup();
2126         return;
2127     }
2128
2129     HTMLInputElement* inputElem =
2130         static_cast<HTMLInputElement*>(focusedNode.get());
2131
2132     // The first time the Autofill popup is shown we'll create the client and
2133     // the popup.
2134     if (!m_autofillPopupClient)
2135         m_autofillPopupClient = adoptPtr(new AutofillPopupMenuClient);
2136
2137     m_autofillPopupClient->initialize(
2138         inputElem, names, labels, icons, uniqueIDs, separatorIndex);
2139
2140     if (!m_autofillPopup.get()) {
2141         m_autofillPopup = PopupContainer::create(m_autofillPopupClient.get(),
2142                                                  PopupContainer::Suggestion,
2143                                                  autofillPopupSettings);
2144     }
2145
2146     if (m_autofillPopupShowing) {
2147         refreshAutofillPopup();
2148     } else {
2149         m_autofillPopup->showInRect(focusedNode->getRect(), focusedNode->ownerDocument()->view(), 0);
2150         m_autofillPopupShowing = true;
2151     }
2152 }
2153
2154 void WebViewImpl::hidePopups()
2155 {
2156     hideSelectPopup();
2157     hideAutofillPopup();
2158 }
2159
2160 void WebViewImpl::performCustomContextMenuAction(unsigned action)
2161 {
2162     if (!m_page)
2163         return;
2164     ContextMenu* menu = m_page->contextMenuController()->contextMenu();
2165     if (!menu)
2166         return;
2167     ContextMenuItem* item = menu->itemWithAction(static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + action));
2168     if (item)
2169         m_page->contextMenuController()->contextMenuItemSelected(item);
2170     m_page->contextMenuController()->clearContextMenu();
2171 }
2172
2173 // WebView --------------------------------------------------------------------
2174
2175 void WebViewImpl::setIsTransparent(bool isTransparent)
2176 {
2177     // Set any existing frames to be transparent.
2178     Frame* frame = m_page->mainFrame();
2179     while (frame) {
2180         frame->view()->setTransparent(isTransparent);
2181         frame = frame->tree()->traverseNext();
2182     }
2183
2184     // Future frames check this to know whether to be transparent.
2185     m_isTransparent = isTransparent;
2186 }
2187
2188 bool WebViewImpl::isTransparent() const
2189 {
2190     return m_isTransparent;
2191 }
2192
2193 void WebViewImpl::setIsActive(bool active)
2194 {
2195     if (page() && page()->focusController())
2196         page()->focusController()->setActive(active);
2197 }
2198
2199 bool WebViewImpl::isActive() const
2200 {
2201     return (page() && page()->focusController()) ? page()->focusController()->isActive() : false;
2202 }
2203
2204 void WebViewImpl::setDomainRelaxationForbidden(bool forbidden, const WebString& scheme)
2205 {
2206     SecurityOrigin::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme));
2207 }
2208
2209 void WebViewImpl::setScrollbarColors(unsigned inactiveColor,
2210                                      unsigned activeColor,
2211                                      unsigned trackColor) {
2212 #if OS(UNIX) && !OS(DARWIN)
2213     PlatformThemeChromiumGtk::setScrollbarColors(inactiveColor,
2214                                                  activeColor,
2215                                                  trackColor);
2216 #endif
2217 }
2218
2219 void WebViewImpl::setSelectionColors(unsigned activeBackgroundColor,
2220                                      unsigned activeForegroundColor,
2221                                      unsigned inactiveBackgroundColor,
2222                                      unsigned inactiveForegroundColor) {
2223 #if OS(UNIX) && !OS(DARWIN)
2224     RenderThemeChromiumLinux::setSelectionColors(activeBackgroundColor,
2225                                                  activeForegroundColor,
2226                                                  inactiveBackgroundColor,
2227                                                  inactiveForegroundColor);
2228     theme()->platformColorsDidChange();
2229 #endif
2230 }
2231
2232 void WebView::addUserScript(const WebString& sourceCode,
2233                             const WebVector<WebString>& patternsIn,
2234                             WebView::UserScriptInjectAt injectAt,
2235                             WebView::UserContentInjectIn injectIn)
2236 {
2237     OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2238     for (size_t i = 0; i < patternsIn.size(); ++i)
2239         patterns->append(patternsIn[i]);
2240
2241     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2242     RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
2243     pageGroup->addUserScriptToWorld(world.get(), sourceCode, WebURL(), patterns.release(), nullptr,
2244                                     static_cast<UserScriptInjectionTime>(injectAt),
2245                                     static_cast<UserContentInjectedFrames>(injectIn));
2246 }
2247
2248 void WebView::addUserStyleSheet(const WebString& sourceCode,
2249                                 const WebVector<WebString>& patternsIn,
2250                                 WebView::UserContentInjectIn injectIn,
2251                                 WebView::UserStyleInjectionTime injectionTime)
2252 {
2253     OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2254     for (size_t i = 0; i < patternsIn.size(); ++i)
2255         patterns->append(patternsIn[i]);
2256
2257     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2258     RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
2259
2260     // FIXME: Current callers always want the level to be "author". It probably makes sense to let
2261     // callers specify this though, since in other cases the caller will probably want "user" level.
2262     //
2263     // FIXME: It would be nice to populate the URL correctly, instead of passing an empty URL.
2264     pageGroup->addUserStyleSheetToWorld(world.get(), sourceCode, WebURL(), patterns.release(), nullptr,
2265                                         static_cast<UserContentInjectedFrames>(injectIn),
2266                                         UserStyleAuthorLevel,
2267                                         static_cast<WebCore::UserStyleInjectionTime>(injectionTime));
2268 }
2269
2270 void WebView::removeAllUserContent()
2271 {
2272     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2273     pageGroup->removeAllUserContent();
2274 }
2275
2276 void WebViewImpl::didCommitLoad(bool* isNewNavigation)
2277 {
2278     if (isNewNavigation)
2279         *isNewNavigation = m_observedNewNavigation;
2280
2281 #ifndef NDEBUG
2282     ASSERT(!m_observedNewNavigation
2283         || m_page->mainFrame()->loader()->documentLoader() == m_newNavigationLoader);
2284     m_newNavigationLoader = 0;
2285 #endif
2286     m_observedNewNavigation = false;
2287 }
2288
2289 bool WebViewImpl::useExternalPopupMenus()
2290 {
2291     return shouldUseExternalPopupMenus;
2292 }
2293
2294 bool WebViewImpl::navigationPolicyFromMouseEvent(unsigned short button,
2295                                                  bool ctrl, bool shift,
2296                                                  bool alt, bool meta,
2297                                                  WebNavigationPolicy* policy)
2298 {
2299 #if OS(DARWIN)
2300     const bool newTabModifier = (button == 1) || meta;
2301 #else
2302     const bool newTabModifier = (button == 1) || ctrl;
2303 #endif
2304     if (!newTabModifier && !shift && !alt)
2305       return false;
2306
2307     ASSERT(policy);
2308     if (newTabModifier) {
2309         if (shift)
2310           *policy = WebNavigationPolicyNewForegroundTab;
2311         else
2312           *policy = WebNavigationPolicyNewBackgroundTab;
2313     } else {
2314         if (shift)
2315           *policy = WebNavigationPolicyNewWindow;
2316         else
2317           *policy = WebNavigationPolicyDownload;
2318     }
2319     return true;
2320 }
2321
2322 void WebViewImpl::startDragging(const WebDragData& dragData,
2323                                 WebDragOperationsMask mask,
2324                                 const WebImage& dragImage,
2325                                 const WebPoint& dragImageOffset)
2326 {
2327     if (!m_client)
2328         return;
2329     ASSERT(!m_doingDragAndDrop);
2330     m_doingDragAndDrop = true;
2331     m_client->startDragging(dragData, mask, dragImage, dragImageOffset);
2332 }
2333
2334 void WebViewImpl::observeNewNavigation()
2335 {
2336     m_observedNewNavigation = true;
2337 #ifndef NDEBUG
2338     m_newNavigationLoader = m_page->mainFrame()->loader()->documentLoader();
2339 #endif
2340 }
2341
2342 void WebViewImpl::setIgnoreInputEvents(bool newValue)
2343 {
2344     ASSERT(m_ignoreInputEvents != newValue);
2345     m_ignoreInputEvents = newValue;
2346 }
2347
2348 void WebViewImpl::setPageOverlayClient(PageOverlay::PageOverlayClient* pageOverlayClient)
2349 {
2350     if (pageOverlayClient) {
2351         if (!m_pageOverlay)
2352             m_pageOverlay = PageOverlay::create(this, pageOverlayClient);
2353         else
2354             m_pageOverlay->setClient(pageOverlayClient);
2355         m_pageOverlay->update();
2356         setRootLayerNeedsDisplay();
2357     } else {
2358         if (m_pageOverlay) {
2359             m_pageOverlay->clear();
2360             m_pageOverlay = nullptr;
2361             setRootLayerNeedsDisplay();
2362         }
2363     }
2364 }
2365
2366 void WebViewImpl::setOverlayLayer(WebCore::GraphicsLayer* layer)
2367 {
2368     if (m_rootGraphicsLayer) {
2369         if (layer->parent() != m_rootGraphicsLayer)
2370             m_rootGraphicsLayer->addChild(layer);
2371     }
2372 }
2373
2374 #if ENABLE(NOTIFICATIONS)
2375 NotificationPresenterImpl* WebViewImpl::notificationPresenterImpl()
2376 {
2377     if (!m_notificationPresenter.isInitialized() && m_client)
2378         m_notificationPresenter.initialize(m_client->notificationPresenter());
2379     return &m_notificationPresenter;
2380 }
2381 #endif
2382
2383 void WebViewImpl::refreshAutofillPopup()
2384 {
2385     ASSERT(m_autofillPopupShowing);
2386
2387     // Hide the popup if it has become empty.
2388     if (!m_autofillPopupClient->listSize()) {
2389         hideAutofillPopup();
2390         return;
2391     }
2392
2393     IntRect oldBounds = m_autofillPopup->frameRect();
2394     m_autofillPopup->refresh(focusedWebCoreNode()->getRect());
2395     IntRect newBounds = m_autofillPopup->frameRect();
2396     // Let's resize the backing window if necessary.
2397     if (oldBounds != newBounds) {
2398         WebPopupMenuImpl* popupMenu =
2399             static_cast<WebPopupMenuImpl*>(m_autofillPopup->client());
2400         if (popupMenu)
2401             popupMenu->client()->setWindowRect(m_chromeClientImpl.windowToScreen(newBounds));
2402     }
2403 }
2404
2405 Node* WebViewImpl::focusedWebCoreNode()
2406 {
2407     Frame* frame = m_page->focusController()->focusedFrame();
2408     if (!frame)
2409         return 0;
2410
2411     Document* document = frame->document();
2412     if (!document)
2413         return 0;
2414
2415     return document->focusedNode();
2416 }
2417
2418 HitTestResult WebViewImpl::hitTestResultForWindowPos(const IntPoint& pos)
2419 {
2420     IntPoint docPoint(m_page->mainFrame()->view()->windowToContents(pos));
2421     return m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(docPoint, false);
2422 }
2423
2424 void WebViewImpl::setTabsToLinks(bool enable)
2425 {
2426     m_tabsToLinks = enable;
2427 }
2428
2429 bool WebViewImpl::tabsToLinks() const
2430 {
2431     return m_tabsToLinks;
2432 }
2433
2434 #if USE(ACCELERATED_COMPOSITING)
2435 bool WebViewImpl::allowsAcceleratedCompositing()
2436 {
2437     return !m_compositorCreationFailed;
2438 }
2439
2440 bool WebViewImpl::pageHasRTLStyle() const
2441 {
2442     if (!page())
2443         return false;
2444     Document* document = page()->mainFrame()->document();
2445     if (!document)
2446         return false;
2447     RenderView* renderView = document->renderView();
2448     if (!renderView)
2449         return false;
2450     RenderStyle* style = renderView->style();
2451     if (!style)
2452         return false;
2453     return (style->direction() == RTL);
2454 }
2455
2456 void WebViewImpl::setRootGraphicsLayer(WebCore::GraphicsLayer* layer)
2457 {
2458     m_rootGraphicsLayer = layer;
2459     setRootPlatformLayer(layer ? layer->platformLayer() : 0);
2460 }
2461
2462 void WebViewImpl::setRootPlatformLayer(WebCore::PlatformLayer* layer)
2463 {
2464     setIsAcceleratedCompositingActive(layer);
2465     if (m_layerTreeHost)
2466         m_layerTreeHost->setRootLayer(layer);
2467
2468     IntRect damagedRect(0, 0, m_size.width, m_size.height);
2469     if (m_isAcceleratedCompositingActive)
2470         invalidateRootLayerRect(damagedRect);
2471     else
2472         m_client->didInvalidateRect(damagedRect);
2473 }
2474
2475 void WebViewImpl::setRootLayerNeedsDisplay()
2476 {
2477 #if USE(THREADED_COMPOSITING)
2478     if (m_layerTreeHost)
2479         m_layerTreeHost->setNeedsCommitAndRedraw();
2480 #else
2481     m_client->scheduleComposite();
2482 #endif
2483 }
2484
2485 void WebViewImpl::scrollRootLayerRect(const IntSize& scrollDelta, const IntRect& clipRect)
2486 {
2487     updateLayerTreeViewport();
2488     setRootLayerNeedsDisplay();
2489 }
2490
2491 void WebViewImpl::invalidateRootLayerRect(const IntRect& rect)
2492 {
2493     ASSERT(m_layerTreeHost);
2494
2495     if (!page())
2496         return;
2497
2498     FrameView* view = page()->mainFrame()->view();
2499     IntRect dirtyRect = view->windowToContents(rect);
2500     updateLayerTreeViewport();
2501     m_layerTreeHost->invalidateRootLayerRect(dirtyRect);
2502     setRootLayerNeedsDisplay();
2503 }
2504
2505 class WebViewImplContentPainter : public LayerPainterChromium {
2506     WTF_MAKE_NONCOPYABLE(WebViewImplContentPainter);
2507 public:
2508     static PassOwnPtr<WebViewImplContentPainter*> create(WebViewImpl* webViewImpl)
2509     {
2510         return adoptPtr(new WebViewImplContentPainter(webViewImpl));
2511     }
2512
2513     virtual void paint(GraphicsContext& context, const IntRect& contentRect)
2514     {
2515         double paintStart = currentTime();
2516         Page* page = m_webViewImpl->page();
2517         if (!page)
2518             return;
2519         FrameView* view = page->mainFrame()->view();
2520         view->paintContents(&context, contentRect);
2521         double paintEnd = currentTime();
2522         double pixelsPerSec = (contentRect.width() * contentRect.height()) / (paintEnd - paintStart);
2523         PlatformBridge::histogramCustomCounts("Renderer4.AccelRootPaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30);
2524         PlatformBridge::histogramCustomCounts("Renderer4.AccelRootPaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30);
2525     }
2526
2527 private:
2528     explicit WebViewImplContentPainter(WebViewImpl* webViewImpl)
2529         : m_webViewImpl(webViewImpl)
2530     {
2531     }
2532
2533     WebViewImpl* m_webViewImpl;
2534 };
2535
2536 void WebViewImpl::setIsAcceleratedCompositingActive(bool active)
2537 {
2538     PlatformBridge::histogramEnumeration("GPU.setIsAcceleratedCompositingActive", active * 2 + m_isAcceleratedCompositingActive, 4);
2539
2540     if (m_isAcceleratedCompositingActive == active)
2541         return;
2542
2543     if (!active) {
2544         m_isAcceleratedCompositingActive = false;
2545         // We need to finish all GL rendering before sending
2546         // didActivateAcceleratedCompositing(false) to prevent
2547         // flickering when compositing turns off.
2548         if (m_layerTreeHost)
2549             m_layerTreeHost->finishAllRendering();
2550         m_client->didActivateAcceleratedCompositing(false);
2551     } else if (m_layerTreeHost) {
2552         m_isAcceleratedCompositingActive = true;
2553         updateLayerTreeViewport();
2554
2555         m_client->didActivateAcceleratedCompositing(true);
2556     } else {
2557         TRACE_EVENT("WebViewImpl::setIsAcceleratedCompositingActive(true)", this, 0);
2558
2559         WebCore::CCSettings ccSettings;
2560         ccSettings.acceleratePainting = page()->settings()->acceleratedDrawingEnabled();
2561         ccSettings.compositeOffscreen = settings()->compositeToTextureEnabled();
2562         ccSettings.showFPSCounter = settings()->showFPSCounter();
2563         ccSettings.showPlatformLayerTree = settings()->showPlatformLayerTree();
2564
2565         m_layerTreeHost = CCLayerTreeHost::create(this, ccSettings);
2566         if (m_layerTreeHost) {
2567             m_client->didActivateAcceleratedCompositing(true);
2568             m_isAcceleratedCompositingActive = true;
2569             m_compositorCreationFailed = false;
2570             if (m_pageOverlay)
2571                 m_pageOverlay->update();
2572         } else {
2573             m_isAcceleratedCompositingActive = false;
2574             m_client->didActivateAcceleratedCompositing(false);
2575             m_compositorCreationFailed = true;
2576         }
2577     }
2578     if (page())
2579         page()->mainFrame()->view()->setClipsRepaints(!m_isAcceleratedCompositingActive);
2580 }
2581
2582 #endif
2583
2584 PassRefPtr<GraphicsContext3D> WebViewImpl::createLayerTreeHostContext3D()
2585 {
2586     RefPtr<GraphicsContext3D> context = m_temporaryOnscreenGraphicsContext3D.release();
2587     if (!context) {
2588         context = GraphicsContext3D::create(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2589         if (context)
2590             context->reshape(max(1, m_size.width), max(1, m_size.height));
2591     }
2592     return context;
2593 }
2594
2595 PassOwnPtr<LayerPainterChromium> WebViewImpl::createRootLayerPainter()
2596 {
2597     return WebViewImplContentPainter::create(this);
2598 }
2599
2600 void WebViewImpl::animateAndLayout(double frameBeginTime)
2601 {
2602     animate(frameBeginTime);
2603     layout();
2604 }
2605
2606 void WebViewImpl::didRecreateGraphicsContext(bool success)
2607 {
2608     setRootPlatformLayer(success ? m_layerTreeHost->rootLayer() : 0);
2609
2610     if (success) {
2611       // Forces ViewHostMsg_DidActivateAcceleratedCompositing to be sent so
2612       // that the browser process can reacquire surfaces.
2613       m_client->didActivateAcceleratedCompositing(true);
2614       if (m_pageOverlay)
2615           m_pageOverlay->update();
2616     }
2617 }
2618
2619 #if !USE(THREADED_COMPOSITING)
2620 void WebViewImpl::scheduleComposite()
2621 {
2622     m_client->scheduleComposite();
2623 }
2624 #endif
2625
2626 void WebViewImpl::updateLayerTreeViewport()
2627 {
2628     if (!page())
2629         return;
2630
2631     FrameView* view = page()->mainFrame()->view();
2632     IntRect contentRect = view->visibleContentRect(false);
2633     IntRect visibleRect = view->visibleContentRect(true);
2634     IntPoint scroll(view->scrollX(), view->scrollY());
2635
2636     m_layerTreeHost->setViewport(visibleRect, contentRect, scroll);
2637 }
2638
2639 WebGraphicsContext3D* WebViewImpl::graphicsContext3D()
2640 {
2641 #if USE(ACCELERATED_COMPOSITING)
2642     if (m_page->settings()->acceleratedCompositingEnabled() && allowsAcceleratedCompositing()) {
2643         if (m_layerTreeHost) {
2644             WebGraphicsContext3D* webContext = GraphicsContext3DInternal::extractWebGraphicsContext3D(m_layerTreeHost->context());
2645             if (webContext && !webContext->isContextLost())
2646                 return webContext;
2647         }
2648         if (m_temporaryOnscreenGraphicsContext3D) {
2649             WebGraphicsContext3D* webContext = GraphicsContext3DInternal::extractWebGraphicsContext3D(m_temporaryOnscreenGraphicsContext3D.get());
2650             if (webContext && !webContext->isContextLost())
2651                 return webContext;
2652         }
2653         m_temporaryOnscreenGraphicsContext3D = GraphicsContext3D::create(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2654         if (m_temporaryOnscreenGraphicsContext3D)
2655             m_temporaryOnscreenGraphicsContext3D->reshape(max(1, m_size.width), max(1, m_size.height));
2656         return GraphicsContext3DInternal::extractWebGraphicsContext3D(m_temporaryOnscreenGraphicsContext3D.get());
2657     }
2658 #endif
2659     return 0;
2660 }
2661
2662
2663 void WebViewImpl::setVisibilityState(WebPageVisibilityState visibilityState,
2664                                      bool isInitialState) {
2665     if (!page())
2666         return;
2667
2668 #if ENABLE(PAGE_VISIBILITY_API)
2669     ASSERT(visibilityState == WebPageVisibilityStateVisible
2670            || visibilityState == WebPageVisibilityStateHidden
2671            || visibilityState == WebPageVisibilityStatePrerender);
2672     m_page->setVisibilityState(static_cast<PageVisibilityState>(static_cast<int>(visibilityState)), isInitialState);
2673 #endif
2674
2675 #if USE(ACCELERATED_COMPOSITING)
2676     if (isAcceleratedCompositingActive())
2677         m_layerTreeHost->setVisible(visibilityState == WebPageVisibilityStateVisible);
2678 #endif
2679 }
2680
2681 #if ENABLE(GESTURE_RECOGNIZER)
2682 void WebViewImpl::resetGestureRecognizer()
2683 {
2684     m_gestureRecognizer->reset();
2685 }
2686 #endif
2687
2688
2689 } // namespace WebKit