Expose pageScaleFactor() to Chromium's WebViewImpl
[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 "PopupMenuChromium.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     case WebInputEvent::GestureTap:
1276         handled = gestureEvent(*static_cast<const WebGestureEvent*>(&inputEvent));
1277         break;
1278 #endif
1279
1280 #if ENABLE(TOUCH_EVENTS)
1281     case WebInputEvent::TouchStart:
1282     case WebInputEvent::TouchMove:
1283     case WebInputEvent::TouchEnd:
1284     case WebInputEvent::TouchCancel:
1285         handled = touchEvent(*static_cast<const WebTouchEvent*>(&inputEvent));
1286         break;
1287 #endif
1288
1289     default:
1290         handled = false;
1291     }
1292
1293     m_currentInputEvent = 0;
1294
1295     return handled;
1296 }
1297
1298 void WebViewImpl::mouseCaptureLost()
1299 {
1300     m_mouseCaptureNode = 0;
1301 }
1302
1303 void WebViewImpl::setFocus(bool enable)
1304 {
1305     m_page->focusController()->setFocused(enable);
1306     if (enable) {
1307         // Note that we don't call setActive() when disabled as this cause extra
1308         // focus/blur events to be dispatched.
1309         m_page->focusController()->setActive(true);
1310         RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
1311         if (focusedFrame) {
1312             Node* focusedNode = focusedFrame->document()->focusedNode();
1313             if (focusedNode && focusedNode->isElementNode()
1314                 && focusedFrame->selection()->selection().isNone()) {
1315                 // If the selection was cleared while the WebView was not
1316                 // focused, then the focus element shows with a focus ring but
1317                 // no caret and does respond to keyboard inputs.
1318                 Element* element = static_cast<Element*>(focusedNode);
1319                 if (element->isTextFormControl())
1320                     element->updateFocusAppearance(true);
1321                 else if (focusedNode->isContentEditable()) {
1322                     // updateFocusAppearance() selects all the text of
1323                     // contentseditable DIVs. So we set the selection explicitly
1324                     // instead. Note that this has the side effect of moving the
1325                     // caret back to the beginning of the text.
1326                     Position position(focusedNode, 0,
1327                                       Position::PositionIsOffsetInAnchor);
1328                     focusedFrame->selection()->setSelection(
1329                         VisibleSelection(position, SEL_DEFAULT_AFFINITY));
1330                 }
1331             }
1332         }
1333         m_imeAcceptEvents = true;
1334     } else {
1335         hideAutofillPopup();
1336         hideSelectPopup();
1337
1338         // Clear focus on the currently focused frame if any.
1339         if (!m_page.get())
1340             return;
1341
1342         Frame* frame = m_page->mainFrame();
1343         if (!frame)
1344             return;
1345
1346         RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
1347         if (focusedFrame.get()) {
1348             // Finish an ongoing composition to delete the composition node.
1349             Editor* editor = focusedFrame->editor();
1350             if (editor && editor->hasComposition())
1351                 editor->confirmComposition();
1352             m_imeAcceptEvents = false;
1353         }
1354     }
1355 }
1356
1357 bool WebViewImpl::setComposition(
1358     const WebString& text,
1359     const WebVector<WebCompositionUnderline>& underlines,
1360     int selectionStart,
1361     int selectionEnd)
1362 {
1363     Frame* focused = focusedWebCoreFrame();
1364     if (!focused || !m_imeAcceptEvents)
1365         return false;
1366     Editor* editor = focused->editor();
1367     if (!editor)
1368         return false;
1369
1370     // The input focus has been moved to another WebWidget object.
1371     // We should use this |editor| object only to complete the ongoing
1372     // composition.
1373     if (!editor->canEdit() && !editor->hasComposition())
1374         return false;
1375
1376     // We should verify the parent node of this IME composition node are
1377     // editable because JavaScript may delete a parent node of the composition
1378     // node. In this case, WebKit crashes while deleting texts from the parent
1379     // node, which doesn't exist any longer.
1380     PassRefPtr<Range> range = editor->compositionRange();
1381     if (range) {
1382         Node* node = range->startContainer();
1383         if (!node || !node->isContentEditable())
1384             return false;
1385     }
1386
1387     // If we're not going to fire a keypress event, then the keydown event was
1388     // canceled.  In that case, cancel any existing composition.
1389     if (text.isEmpty() || m_suppressNextKeypressEvent) {
1390         // A browser process sent an IPC message which does not contain a valid
1391         // string, which means an ongoing composition has been canceled.
1392         // If the ongoing composition has been canceled, replace the ongoing
1393         // composition string with an empty string and complete it.
1394         String emptyString;
1395         Vector<CompositionUnderline> emptyUnderlines;
1396         editor->setComposition(emptyString, emptyUnderlines, 0, 0);
1397         return text.isEmpty();
1398     }
1399
1400     // When the range of composition underlines overlap with the range between
1401     // selectionStart and selectionEnd, WebKit somehow won't paint the selection
1402     // at all (see InlineTextBox::paint() function in InlineTextBox.cpp).
1403     // But the selection range actually takes effect.
1404     editor->setComposition(String(text),
1405                            CompositionUnderlineVectorBuilder(underlines),
1406                            selectionStart, selectionEnd);
1407
1408     return editor->hasComposition();
1409 }
1410
1411 bool WebViewImpl::confirmComposition()
1412 {
1413     return confirmComposition(WebString());
1414 }
1415
1416 bool WebViewImpl::confirmComposition(const WebString& text)
1417 {
1418     Frame* focused = focusedWebCoreFrame();
1419     if (!focused || !m_imeAcceptEvents)
1420         return false;
1421     Editor* editor = focused->editor();
1422     if (!editor || (!editor->hasComposition() && !text.length()))
1423         return false;
1424
1425     // We should verify the parent node of this IME composition node are
1426     // editable because JavaScript may delete a parent node of the composition
1427     // node. In this case, WebKit crashes while deleting texts from the parent
1428     // node, which doesn't exist any longer.
1429     PassRefPtr<Range> range = editor->compositionRange();
1430     if (range) {
1431         Node* node = range->startContainer();
1432         if (!node || !node->isContentEditable())
1433             return false;
1434     }
1435
1436     if (editor->hasComposition()) {
1437         if (text.length())
1438             editor->confirmComposition(String(text));
1439         else
1440             editor->confirmComposition();
1441     } else
1442         editor->insertText(String(text), 0);
1443
1444     return true;
1445 }
1446
1447 bool WebViewImpl::compositionRange(size_t* location, size_t* length)
1448 {
1449     Frame* focused = focusedWebCoreFrame();
1450     if (!focused || !m_imeAcceptEvents)
1451         return false;
1452     Editor* editor = focused->editor();
1453     if (!editor || !editor->hasComposition())
1454         return false;
1455
1456     RefPtr<Range> range = editor->compositionRange();
1457     if (!range.get())
1458         return false;
1459
1460     if (TextIterator::locationAndLengthFromRange(range.get(), *location, *length))
1461         return true;
1462     return false;
1463 }
1464
1465 WebTextInputType WebViewImpl::textInputType()
1466 {
1467     Node* node = focusedWebCoreNode();
1468     if (!node)
1469         return WebTextInputTypeNone;
1470
1471     if (node->nodeType() == Node::ELEMENT_NODE) {
1472         Element* element = static_cast<Element*>(node);
1473         if (element->hasLocalName(HTMLNames::inputTag)) {
1474             HTMLInputElement* input = static_cast<HTMLInputElement*>(element);
1475
1476             if (input->readOnly() || input->disabled())
1477                 return WebTextInputTypeNone;
1478
1479             if (input->isPasswordField())
1480                 return WebTextInputTypePassword;
1481             if (input->isSearchField())
1482                 return WebTextInputTypeSearch;
1483             if (input->isEmailField())
1484                 return WebTextInputTypeEmail;
1485             if (input->isNumberField())
1486                 return WebTextInputTypeNumber;
1487             if (input->isTelephoneField())
1488                 return WebTextInputTypeTelephone;
1489             if (input->isURLField())
1490                 return WebTextInputTypeURL;
1491             if (input->isTextField())
1492                 return WebTextInputTypeText;
1493             return WebTextInputTypeNone;
1494         }
1495
1496         if (element->hasLocalName(HTMLNames::textareaTag)) {
1497             HTMLTextAreaElement* textarea = static_cast<HTMLTextAreaElement*>(element);
1498
1499             if (textarea->readOnly() || textarea->disabled())
1500                 return WebTextInputTypeNone;
1501             return WebTextInputTypeText;
1502         }
1503     }
1504
1505     // For other situations.
1506     if (node->shouldUseInputMethod())
1507         return WebTextInputTypeText;
1508
1509     return WebTextInputTypeNone;
1510 }
1511
1512 WebRect WebViewImpl::caretOrSelectionBounds()
1513 {
1514     WebRect rect;
1515     const Frame* focused = focusedWebCoreFrame();
1516     if (!focused)
1517         return rect;
1518
1519     FrameSelection* selection = focused->selection();
1520     if (!selection)
1521         return rect;
1522
1523     const FrameView* view = focused->view();
1524     if (!view)
1525         return rect;
1526
1527     const Node* node = selection->base().containerNode();
1528     if (!node || !node->renderer())
1529         return rect;
1530
1531     if (selection->isCaret())
1532         rect = view->contentsToWindow(selection->absoluteCaretBounds());
1533     else if (selection->isRange()) {
1534         node = selection->extent().containerNode();
1535         RefPtr<Range> range = selection->toNormalizedRange();
1536         if (!node || !node->renderer() || !range)
1537             return rect;
1538         rect = view->contentsToWindow(focused->editor()->firstRectForRange(range.get()));
1539     }
1540     return rect;
1541 }
1542
1543 bool WebViewImpl::selectionRange(WebPoint& start, WebPoint& end) const
1544 {
1545     const Frame* frame = focusedWebCoreFrame();
1546     if (!frame || !frame->selection()->isRange())
1547         return false;
1548     RefPtr<Range> selectedRange = frame->selection()->toNormalizedRange();
1549     if (!selectedRange)
1550         return false;
1551     RefPtr<Range> range(Range::create(selectedRange->startContainer()->document(),
1552                                       selectedRange->startContainer(),
1553                                       selectedRange->startOffset(),
1554                                       selectedRange->startContainer(),
1555                                       selectedRange->startOffset()));
1556
1557     IntRect rect = frame->editor()->firstRectForRange(range.get());
1558     start.x = rect.x();
1559     start.y = rect.y() + rect.height() - 1;
1560
1561     range = Range::create(selectedRange->endContainer()->document(),
1562                           selectedRange->endContainer(),
1563                           selectedRange->endOffset(),
1564                           selectedRange->endContainer(),
1565                           selectedRange->endOffset());
1566
1567     rect = frame->editor()->firstRectForRange(range.get());
1568     end.x = rect.x() + rect.width() - 1;
1569     end.y = rect.y() + rect.height() - 1;
1570
1571     start = frame->view()->contentsToWindow(start);
1572     end = frame->view()->contentsToWindow(end);
1573     return true;
1574 }
1575
1576 bool WebViewImpl::caretOrSelectionRange(size_t* location, size_t* length)
1577 {
1578     const Frame* focused = focusedWebCoreFrame();
1579     if (!focused)
1580         return false;
1581
1582     FrameSelection* selection = focused->selection();
1583     if (!selection)
1584         return false;
1585
1586     RefPtr<Range> range = selection->selection().firstRange();
1587     if (!range.get())
1588         return false;
1589
1590     if (TextIterator::locationAndLengthFromRange(range.get(), *location, *length))
1591         return true;
1592     return false;
1593 }
1594
1595 void WebViewImpl::setTextDirection(WebTextDirection direction)
1596 {
1597     // The Editor::setBaseWritingDirection() function checks if we can change
1598     // the text direction of the selected node and updates its DOM "dir"
1599     // attribute and its CSS "direction" property.
1600     // So, we just call the function as Safari does.
1601     const Frame* focused = focusedWebCoreFrame();
1602     if (!focused)
1603         return;
1604
1605     Editor* editor = focused->editor();
1606     if (!editor || !editor->canEdit())
1607         return;
1608
1609     switch (direction) {
1610     case WebTextDirectionDefault:
1611         editor->setBaseWritingDirection(NaturalWritingDirection);
1612         break;
1613
1614     case WebTextDirectionLeftToRight:
1615         editor->setBaseWritingDirection(LeftToRightWritingDirection);
1616         break;
1617
1618     case WebTextDirectionRightToLeft:
1619         editor->setBaseWritingDirection(RightToLeftWritingDirection);
1620         break;
1621
1622     default:
1623         notImplemented();
1624         break;
1625     }
1626 }
1627
1628 bool WebViewImpl::isAcceleratedCompositingActive() const
1629 {
1630 #if USE(ACCELERATED_COMPOSITING)
1631     return m_isAcceleratedCompositingActive;
1632 #else
1633     return false;
1634 #endif
1635 }
1636
1637 // WebView --------------------------------------------------------------------
1638
1639 WebSettings* WebViewImpl::settings()
1640 {
1641     if (!m_webSettings)
1642         m_webSettings = adoptPtr(new WebSettingsImpl(m_page->settings()));
1643     ASSERT(m_webSettings.get());
1644     return m_webSettings.get();
1645 }
1646
1647 WebString WebViewImpl::pageEncoding() const
1648 {
1649     if (!m_page.get())
1650         return WebString();
1651
1652     return m_page->mainFrame()->document()->loader()->writer()->encoding();
1653 }
1654
1655 void WebViewImpl::setPageEncoding(const WebString& encodingName)
1656 {
1657     if (!m_page.get())
1658         return;
1659
1660     // Only change override encoding, don't change default encoding.
1661     // Note that the new encoding must be 0 if it isn't supposed to be set.
1662     String newEncodingName;
1663     if (!encodingName.isEmpty())
1664         newEncodingName = encodingName;
1665     m_page->mainFrame()->loader()->reloadWithOverrideEncoding(newEncodingName);
1666 }
1667
1668 bool WebViewImpl::dispatchBeforeUnloadEvent()
1669 {
1670     // FIXME: This should really cause a recursive depth-first walk of all
1671     // frames in the tree, calling each frame's onbeforeunload.  At the moment,
1672     // we're consistent with Safari 3.1, not IE/FF.
1673     Frame* frame = m_page->mainFrame();
1674     if (!frame)
1675         return true;
1676
1677     return frame->loader()->shouldClose();
1678 }
1679
1680 void WebViewImpl::dispatchUnloadEvent()
1681 {
1682     // Run unload handlers.
1683     m_page->mainFrame()->loader()->closeURL();
1684 }
1685
1686 WebFrame* WebViewImpl::mainFrame()
1687 {
1688     return mainFrameImpl();
1689 }
1690
1691 WebFrame* WebViewImpl::findFrameByName(
1692     const WebString& name, WebFrame* relativeToFrame)
1693 {
1694     if (!relativeToFrame)
1695         relativeToFrame = mainFrame();
1696     Frame* frame = static_cast<WebFrameImpl*>(relativeToFrame)->frame();
1697     frame = frame->tree()->find(name);
1698     return WebFrameImpl::fromFrame(frame);
1699 }
1700
1701 WebFrame* WebViewImpl::focusedFrame()
1702 {
1703     return WebFrameImpl::fromFrame(focusedWebCoreFrame());
1704 }
1705
1706 void WebViewImpl::setFocusedFrame(WebFrame* frame)
1707 {
1708     if (!frame) {
1709         // Clears the focused frame if any.
1710         Frame* frame = focusedWebCoreFrame();
1711         if (frame)
1712             frame->selection()->setFocused(false);
1713         return;
1714     }
1715     WebFrameImpl* frameImpl = static_cast<WebFrameImpl*>(frame);
1716     Frame* webcoreFrame = frameImpl->frame();
1717     webcoreFrame->page()->focusController()->setFocusedFrame(webcoreFrame);
1718 }
1719
1720 void WebViewImpl::setInitialFocus(bool reverse)
1721 {
1722     if (!m_page.get())
1723         return;
1724
1725     // Since we don't have a keyboard event, we'll create one.
1726     WebKeyboardEvent keyboardEvent;
1727     keyboardEvent.type = WebInputEvent::RawKeyDown;
1728     if (reverse)
1729         keyboardEvent.modifiers = WebInputEvent::ShiftKey;
1730
1731     // VK_TAB which is only defined on Windows.
1732     keyboardEvent.windowsKeyCode = 0x09;
1733     PlatformKeyboardEventBuilder platformEvent(keyboardEvent);
1734     RefPtr<KeyboardEvent> webkitEvent = KeyboardEvent::create(platformEvent, 0);
1735
1736     Frame* frame = page()->focusController()->focusedOrMainFrame();
1737     if (Document* document = frame->document())
1738         document->setFocusedNode(0);
1739     page()->focusController()->setInitialFocus(
1740         reverse ? FocusDirectionBackward : FocusDirectionForward,
1741         webkitEvent.get());
1742 }
1743
1744 void WebViewImpl::clearFocusedNode()
1745 {
1746     if (!m_page.get())
1747         return;
1748
1749     RefPtr<Frame> frame = m_page->mainFrame();
1750     if (!frame.get())
1751         return;
1752
1753     RefPtr<Document> document = frame->document();
1754     if (!document.get())
1755         return;
1756
1757     RefPtr<Node> oldFocusedNode = document->focusedNode();
1758
1759     // Clear the focused node.
1760     document->setFocusedNode(0);
1761
1762     if (!oldFocusedNode.get())
1763         return;
1764
1765     // If a text field has focus, we need to make sure the selection controller
1766     // knows to remove selection from it. Otherwise, the text field is still
1767     // processing keyboard events even though focus has been moved to the page and
1768     // keystrokes get eaten as a result.
1769     if (oldFocusedNode->hasTagName(HTMLNames::textareaTag)
1770         || (oldFocusedNode->hasTagName(HTMLNames::inputTag)
1771             && static_cast<HTMLInputElement*>(oldFocusedNode.get())->isTextField())) {
1772         frame->selection()->clear();
1773     }
1774 }
1775
1776 void WebViewImpl::scrollFocusedNodeIntoView()
1777 {
1778     Node* focusedNode = focusedWebCoreNode();
1779     if (focusedNode && focusedNode->isElementNode()) {
1780         Element* elementNode = static_cast<Element*>(focusedNode);
1781         elementNode->scrollIntoViewIfNeeded(true);
1782     }
1783 }
1784
1785 double WebViewImpl::zoomLevel()
1786 {
1787     return m_zoomLevel;
1788 }
1789
1790 double WebViewImpl::setZoomLevel(bool textOnly, double zoomLevel)
1791 {
1792     if (zoomLevel < m_minimumZoomLevel)
1793         m_zoomLevel = m_minimumZoomLevel;
1794     else if (zoomLevel > m_maximumZoomLevel)
1795         m_zoomLevel = m_maximumZoomLevel;
1796     else
1797         m_zoomLevel = zoomLevel;
1798
1799     Frame* frame = mainFrameImpl()->frame();
1800     WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1801     if (pluginContainer)
1802         pluginContainer->plugin()->setZoomLevel(m_zoomLevel, textOnly);
1803     else {
1804         float zoomFactor = static_cast<float>(zoomLevelToZoomFactor(m_zoomLevel));
1805         if (textOnly)
1806             frame->setPageAndTextZoomFactors(1, zoomFactor);
1807         else
1808             frame->setPageAndTextZoomFactors(zoomFactor, 1);
1809     }
1810     return m_zoomLevel;
1811 }
1812
1813 void WebViewImpl::zoomLimitsChanged(double minimumZoomLevel,
1814                                     double maximumZoomLevel)
1815 {
1816     m_minimumZoomLevel = minimumZoomLevel;
1817     m_maximumZoomLevel = maximumZoomLevel;
1818     m_client->zoomLimitsChanged(m_minimumZoomLevel, m_maximumZoomLevel);
1819 }
1820
1821 void WebViewImpl::fullFramePluginZoomLevelChanged(double zoomLevel)
1822 {
1823     if (zoomLevel == m_zoomLevel)
1824         return;
1825
1826     m_zoomLevel = max(min(zoomLevel, m_maximumZoomLevel), m_minimumZoomLevel);
1827     m_client->zoomLevelChanged();
1828 }
1829
1830 double WebView::zoomLevelToZoomFactor(double zoomLevel)
1831 {
1832     return pow(textSizeMultiplierRatio, zoomLevel);
1833 }
1834
1835 double WebView::zoomFactorToZoomLevel(double factor)
1836 {
1837     // Since factor = 1.2^level, level = log(factor) / log(1.2)
1838     return log(factor) / log(textSizeMultiplierRatio);
1839 }
1840
1841 float WebViewImpl::pageScaleFactor() const
1842 {
1843     if (!page())
1844         return 1.0;
1845
1846     Frame* frame = page()->mainFrame();
1847     if (!frame)
1848         return 1.0;
1849
1850     return frame->pageScaleFactor();
1851 }
1852
1853 void WebViewImpl::scalePage(float scaleFactor, WebPoint origin)
1854 {
1855     if (!page())
1856         return;
1857
1858     Frame* frame = page()->mainFrame();
1859     if (!frame)
1860         return;
1861
1862     frame->scalePage(scaleFactor, origin);
1863 }
1864
1865 void WebViewImpl::performMediaPlayerAction(const WebMediaPlayerAction& action,
1866                                            const WebPoint& location)
1867 {
1868     HitTestResult result = hitTestResultForWindowPos(location);
1869     RefPtr<Node> node = result.innerNonSharedNode();
1870     if (!node->hasTagName(HTMLNames::videoTag) && !node->hasTagName(HTMLNames::audioTag))
1871       return;
1872
1873     RefPtr<HTMLMediaElement> mediaElement =
1874         static_pointer_cast<HTMLMediaElement>(node);
1875     switch (action.type) {
1876     case WebMediaPlayerAction::Play:
1877         if (action.enable)
1878             mediaElement->play();
1879         else
1880             mediaElement->pause();
1881         break;
1882     case WebMediaPlayerAction::Mute:
1883         mediaElement->setMuted(action.enable);
1884         break;
1885     case WebMediaPlayerAction::Loop:
1886         mediaElement->setLoop(action.enable);
1887         break;
1888     case WebMediaPlayerAction::Controls:
1889         mediaElement->setControls(action.enable);
1890         break;
1891     default:
1892         ASSERT_NOT_REACHED();
1893     }
1894 }
1895
1896 void WebViewImpl::copyImageAt(const WebPoint& point)
1897 {
1898     if (!m_page.get())
1899         return;
1900
1901     HitTestResult result = hitTestResultForWindowPos(point);
1902
1903     if (result.absoluteImageURL().isEmpty()) {
1904         // There isn't actually an image at these coordinates.  Might be because
1905         // the window scrolled while the context menu was open or because the page
1906         // changed itself between when we thought there was an image here and when
1907         // we actually tried to retreive the image.
1908         //
1909         // FIXME: implement a cache of the most recent HitTestResult to avoid having
1910         //        to do two hit tests.
1911         return;
1912     }
1913
1914     m_page->mainFrame()->editor()->copyImage(result);
1915 }
1916
1917 void WebViewImpl::dragSourceEndedAt(
1918     const WebPoint& clientPoint,
1919     const WebPoint& screenPoint,
1920     WebDragOperation operation)
1921 {
1922     PlatformMouseEvent pme(clientPoint,
1923                            screenPoint,
1924                            LeftButton, MouseEventMoved, 0, false, false, false,
1925                            false, 0);
1926     m_page->mainFrame()->eventHandler()->dragSourceEndedAt(pme,
1927         static_cast<DragOperation>(operation));
1928     m_dragScrollTimer->stop();
1929 }
1930
1931 void WebViewImpl::dragSourceMovedTo(
1932     const WebPoint& clientPoint,
1933     const WebPoint& screenPoint,
1934     WebDragOperation operation)
1935 {
1936     m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
1937 }
1938
1939 void WebViewImpl::dragSourceSystemDragEnded()
1940 {
1941     // It's possible for us to get this callback while not doing a drag if
1942     // it's from a previous page that got unloaded.
1943     if (m_doingDragAndDrop) {
1944         m_page->dragController()->dragEnded();
1945         m_doingDragAndDrop = false;
1946     }
1947 }
1948
1949 WebDragOperation WebViewImpl::dragTargetDragEnter(
1950     const WebDragData& webDragData,
1951     const WebPoint& clientPoint,
1952     const WebPoint& screenPoint,
1953     WebDragOperationsMask operationsAllowed)
1954 {
1955     ASSERT(!m_currentDragData.get());
1956
1957     m_currentDragData = webDragData;
1958     m_operationsAllowed = operationsAllowed;
1959
1960     return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragEnter);
1961 }
1962
1963 WebDragOperation WebViewImpl::dragTargetDragOver(
1964     const WebPoint& clientPoint,
1965     const WebPoint& screenPoint,
1966     WebDragOperationsMask operationsAllowed)
1967 {
1968     m_operationsAllowed = operationsAllowed;
1969
1970     return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragOver);
1971 }
1972
1973 void WebViewImpl::dragTargetDragLeave()
1974 {
1975     ASSERT(m_currentDragData.get());
1976
1977     DragData dragData(
1978         m_currentDragData.get(),
1979         IntPoint(),
1980         IntPoint(),
1981         static_cast<DragOperation>(m_operationsAllowed));
1982
1983     m_page->dragController()->dragExited(&dragData);
1984
1985     // FIXME: why is the drag scroll timer not stopped here?
1986
1987     m_dragOperation = WebDragOperationNone;
1988     m_currentDragData = 0;
1989 }
1990
1991 void WebViewImpl::dragTargetDrop(const WebPoint& clientPoint,
1992                                  const WebPoint& screenPoint)
1993 {
1994     ASSERT(m_currentDragData.get());
1995
1996     // If this webview transitions from the "drop accepting" state to the "not
1997     // accepting" state, then our IPC message reply indicating that may be in-
1998     // flight, or else delayed by javascript processing in this webview.  If a
1999     // drop happens before our IPC reply has reached the browser process, then
2000     // the browser forwards the drop to this webview.  So only allow a drop to
2001     // proceed if our webview m_dragOperation state is not DragOperationNone.
2002
2003     if (m_dragOperation == WebDragOperationNone) { // IPC RACE CONDITION: do not allow this drop.
2004         dragTargetDragLeave();
2005         return;
2006     }
2007
2008     DragData dragData(
2009         m_currentDragData.get(),
2010         clientPoint,
2011         screenPoint,
2012         static_cast<DragOperation>(m_operationsAllowed));
2013
2014     m_page->dragController()->performDrag(&dragData);
2015
2016     m_dragOperation = WebDragOperationNone;
2017     m_currentDragData = 0;
2018
2019     m_dragScrollTimer->stop();
2020 }
2021
2022 WebDragOperation WebViewImpl::dragTargetDragEnterOrOver(const WebPoint& clientPoint, const WebPoint& screenPoint, DragAction dragAction)
2023 {
2024     ASSERT(m_currentDragData.get());
2025
2026     DragData dragData(
2027         m_currentDragData.get(),
2028         clientPoint,
2029         screenPoint,
2030         static_cast<DragOperation>(m_operationsAllowed));
2031
2032     DragOperation dropEffect;
2033     if (dragAction == DragEnter)
2034         dropEffect = m_page->dragController()->dragEntered(&dragData);
2035     else
2036         dropEffect = m_page->dragController()->dragUpdated(&dragData);
2037
2038     // Mask the drop effect operation against the drag source's allowed operations.
2039     if (!(dropEffect & dragData.draggingSourceOperationMask()))
2040         dropEffect = DragOperationNone;
2041
2042      m_dragOperation = static_cast<WebDragOperation>(dropEffect);
2043
2044     if (dragAction == DragOver)
2045         m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
2046     else
2047         m_dragScrollTimer->stop();
2048
2049     return m_dragOperation;
2050 }
2051
2052 unsigned long WebViewImpl::createUniqueIdentifierForRequest()
2053 {
2054     if (m_page)
2055         return m_page->progress()->createUniqueIdentifier();
2056     return 0;
2057 }
2058
2059 void WebViewImpl::inspectElementAt(const WebPoint& point)
2060 {
2061     if (!m_page.get())
2062         return;
2063
2064     if (point.x == -1 || point.y == -1)
2065         m_page->inspectorController()->inspect(0);
2066     else {
2067         HitTestResult result = hitTestResultForWindowPos(point);
2068
2069         if (!result.innerNonSharedNode())
2070             return;
2071
2072         m_page->inspectorController()->inspect(result.innerNonSharedNode());
2073     }
2074 }
2075
2076 WebString WebViewImpl::inspectorSettings() const
2077 {
2078     return m_inspectorSettings;
2079 }
2080
2081 void WebViewImpl::setInspectorSettings(const WebString& settings)
2082 {
2083     m_inspectorSettings = settings;
2084 }
2085
2086 bool WebViewImpl::inspectorSetting(const WebString& key, WebString* value) const
2087 {
2088     if (!m_inspectorSettingsMap->contains(key))
2089         return false;
2090     *value = m_inspectorSettingsMap->get(key);
2091     return true;
2092 }
2093
2094 void WebViewImpl::setInspectorSetting(const WebString& key,
2095                                       const WebString& value)
2096 {
2097     m_inspectorSettingsMap->set(key, value);
2098     client()->didUpdateInspectorSetting(key, value);
2099 }
2100
2101 WebDevToolsAgent* WebViewImpl::devToolsAgent()
2102 {
2103     return m_devToolsAgent.get();
2104 }
2105
2106 WebAccessibilityObject WebViewImpl::accessibilityObject()
2107 {
2108     if (!mainFrameImpl())
2109         return WebAccessibilityObject();
2110
2111     Document* document = mainFrameImpl()->frame()->document();
2112     return WebAccessibilityObject(
2113         document->axObjectCache()->getOrCreate(document->renderer()));
2114 }
2115
2116 void WebViewImpl::applyAutofillSuggestions(
2117     const WebNode& node,
2118     const WebVector<WebString>& names,
2119     const WebVector<WebString>& labels,
2120     const WebVector<WebString>& icons,
2121     const WebVector<int>& uniqueIDs,
2122     int separatorIndex)
2123 {
2124     ASSERT(names.size() == labels.size());
2125     ASSERT(names.size() == uniqueIDs.size());
2126     ASSERT(separatorIndex < static_cast<int>(names.size()));
2127
2128     if (names.isEmpty()) {
2129         hideAutofillPopup();
2130         return;
2131     }
2132
2133     RefPtr<Node> focusedNode = focusedWebCoreNode();
2134     // If the node for which we queried the Autofill suggestions is not the
2135     // focused node, then we have nothing to do.  FIXME: also check the
2136     // caret is at the end and that the text has not changed.
2137     if (!focusedNode || focusedNode != PassRefPtr<Node>(node)) {
2138         hideAutofillPopup();
2139         return;
2140     }
2141
2142     HTMLInputElement* inputElem =
2143         static_cast<HTMLInputElement*>(focusedNode.get());
2144
2145     // The first time the Autofill popup is shown we'll create the client and
2146     // the popup.
2147     if (!m_autofillPopupClient)
2148         m_autofillPopupClient = adoptPtr(new AutofillPopupMenuClient);
2149
2150     m_autofillPopupClient->initialize(
2151         inputElem, names, labels, icons, uniqueIDs, separatorIndex);
2152
2153     if (!m_autofillPopup.get()) {
2154         m_autofillPopup = PopupContainer::create(m_autofillPopupClient.get(),
2155                                                  PopupContainer::Suggestion,
2156                                                  autofillPopupSettings);
2157     }
2158
2159     if (m_autofillPopupShowing) {
2160         refreshAutofillPopup();
2161     } else {
2162         m_autofillPopup->showInRect(focusedNode->getRect(), focusedNode->ownerDocument()->view(), 0);
2163         m_autofillPopupShowing = true;
2164     }
2165 }
2166
2167 void WebViewImpl::hidePopups()
2168 {
2169     hideSelectPopup();
2170     hideAutofillPopup();
2171 }
2172
2173 void WebViewImpl::performCustomContextMenuAction(unsigned action)
2174 {
2175     if (!m_page)
2176         return;
2177     ContextMenu* menu = m_page->contextMenuController()->contextMenu();
2178     if (!menu)
2179         return;
2180     ContextMenuItem* item = menu->itemWithAction(static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + action));
2181     if (item)
2182         m_page->contextMenuController()->contextMenuItemSelected(item);
2183     m_page->contextMenuController()->clearContextMenu();
2184 }
2185
2186 // WebView --------------------------------------------------------------------
2187
2188 void WebViewImpl::setIsTransparent(bool isTransparent)
2189 {
2190     // Set any existing frames to be transparent.
2191     Frame* frame = m_page->mainFrame();
2192     while (frame) {
2193         frame->view()->setTransparent(isTransparent);
2194         frame = frame->tree()->traverseNext();
2195     }
2196
2197     // Future frames check this to know whether to be transparent.
2198     m_isTransparent = isTransparent;
2199 }
2200
2201 bool WebViewImpl::isTransparent() const
2202 {
2203     return m_isTransparent;
2204 }
2205
2206 void WebViewImpl::setIsActive(bool active)
2207 {
2208     if (page() && page()->focusController())
2209         page()->focusController()->setActive(active);
2210 }
2211
2212 bool WebViewImpl::isActive() const
2213 {
2214     return (page() && page()->focusController()) ? page()->focusController()->isActive() : false;
2215 }
2216
2217 void WebViewImpl::setDomainRelaxationForbidden(bool forbidden, const WebString& scheme)
2218 {
2219     SecurityOrigin::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme));
2220 }
2221
2222 void WebViewImpl::setScrollbarColors(unsigned inactiveColor,
2223                                      unsigned activeColor,
2224                                      unsigned trackColor) {
2225 #if OS(UNIX) && !OS(DARWIN)
2226     PlatformThemeChromiumGtk::setScrollbarColors(inactiveColor,
2227                                                  activeColor,
2228                                                  trackColor);
2229 #endif
2230 }
2231
2232 void WebViewImpl::setSelectionColors(unsigned activeBackgroundColor,
2233                                      unsigned activeForegroundColor,
2234                                      unsigned inactiveBackgroundColor,
2235                                      unsigned inactiveForegroundColor) {
2236 #if OS(UNIX) && !OS(DARWIN)
2237     RenderThemeChromiumLinux::setSelectionColors(activeBackgroundColor,
2238                                                  activeForegroundColor,
2239                                                  inactiveBackgroundColor,
2240                                                  inactiveForegroundColor);
2241     theme()->platformColorsDidChange();
2242 #endif
2243 }
2244
2245 void WebView::addUserScript(const WebString& sourceCode,
2246                             const WebVector<WebString>& patternsIn,
2247                             WebView::UserScriptInjectAt injectAt,
2248                             WebView::UserContentInjectIn injectIn)
2249 {
2250     OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2251     for (size_t i = 0; i < patternsIn.size(); ++i)
2252         patterns->append(patternsIn[i]);
2253
2254     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2255     RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
2256     pageGroup->addUserScriptToWorld(world.get(), sourceCode, WebURL(), patterns.release(), nullptr,
2257                                     static_cast<UserScriptInjectionTime>(injectAt),
2258                                     static_cast<UserContentInjectedFrames>(injectIn));
2259 }
2260
2261 void WebView::addUserStyleSheet(const WebString& sourceCode,
2262                                 const WebVector<WebString>& patternsIn,
2263                                 WebView::UserContentInjectIn injectIn,
2264                                 WebView::UserStyleInjectionTime injectionTime)
2265 {
2266     OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2267     for (size_t i = 0; i < patternsIn.size(); ++i)
2268         patterns->append(patternsIn[i]);
2269
2270     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2271     RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
2272
2273     // FIXME: Current callers always want the level to be "author". It probably makes sense to let
2274     // callers specify this though, since in other cases the caller will probably want "user" level.
2275     //
2276     // FIXME: It would be nice to populate the URL correctly, instead of passing an empty URL.
2277     pageGroup->addUserStyleSheetToWorld(world.get(), sourceCode, WebURL(), patterns.release(), nullptr,
2278                                         static_cast<UserContentInjectedFrames>(injectIn),
2279                                         UserStyleAuthorLevel,
2280                                         static_cast<WebCore::UserStyleInjectionTime>(injectionTime));
2281 }
2282
2283 void WebView::removeAllUserContent()
2284 {
2285     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2286     pageGroup->removeAllUserContent();
2287 }
2288
2289 void WebViewImpl::didCommitLoad(bool* isNewNavigation)
2290 {
2291     if (isNewNavigation)
2292         *isNewNavigation = m_observedNewNavigation;
2293
2294 #ifndef NDEBUG
2295     ASSERT(!m_observedNewNavigation
2296         || m_page->mainFrame()->loader()->documentLoader() == m_newNavigationLoader);
2297     m_newNavigationLoader = 0;
2298 #endif
2299     m_observedNewNavigation = false;
2300 }
2301
2302 bool WebViewImpl::useExternalPopupMenus()
2303 {
2304     return shouldUseExternalPopupMenus;
2305 }
2306
2307 bool WebViewImpl::navigationPolicyFromMouseEvent(unsigned short button,
2308                                                  bool ctrl, bool shift,
2309                                                  bool alt, bool meta,
2310                                                  WebNavigationPolicy* policy)
2311 {
2312 #if OS(DARWIN)
2313     const bool newTabModifier = (button == 1) || meta;
2314 #else
2315     const bool newTabModifier = (button == 1) || ctrl;
2316 #endif
2317     if (!newTabModifier && !shift && !alt)
2318       return false;
2319
2320     ASSERT(policy);
2321     if (newTabModifier) {
2322         if (shift)
2323           *policy = WebNavigationPolicyNewForegroundTab;
2324         else
2325           *policy = WebNavigationPolicyNewBackgroundTab;
2326     } else {
2327         if (shift)
2328           *policy = WebNavigationPolicyNewWindow;
2329         else
2330           *policy = WebNavigationPolicyDownload;
2331     }
2332     return true;
2333 }
2334
2335 void WebViewImpl::startDragging(const WebDragData& dragData,
2336                                 WebDragOperationsMask mask,
2337                                 const WebImage& dragImage,
2338                                 const WebPoint& dragImageOffset)
2339 {
2340     if (!m_client)
2341         return;
2342     ASSERT(!m_doingDragAndDrop);
2343     m_doingDragAndDrop = true;
2344     m_client->startDragging(dragData, mask, dragImage, dragImageOffset);
2345 }
2346
2347 void WebViewImpl::observeNewNavigation()
2348 {
2349     m_observedNewNavigation = true;
2350 #ifndef NDEBUG
2351     m_newNavigationLoader = m_page->mainFrame()->loader()->documentLoader();
2352 #endif
2353 }
2354
2355 void WebViewImpl::setIgnoreInputEvents(bool newValue)
2356 {
2357     ASSERT(m_ignoreInputEvents != newValue);
2358     m_ignoreInputEvents = newValue;
2359 }
2360
2361 void WebViewImpl::setPageOverlayClient(PageOverlay::PageOverlayClient* pageOverlayClient)
2362 {
2363     if (pageOverlayClient) {
2364         if (!m_pageOverlay)
2365             m_pageOverlay = PageOverlay::create(this, pageOverlayClient);
2366         else
2367             m_pageOverlay->setClient(pageOverlayClient);
2368         m_pageOverlay->update();
2369         setRootLayerNeedsDisplay();
2370     } else {
2371         if (m_pageOverlay) {
2372             m_pageOverlay->clear();
2373             m_pageOverlay = nullptr;
2374             setRootLayerNeedsDisplay();
2375         }
2376     }
2377 }
2378
2379 void WebViewImpl::setOverlayLayer(WebCore::GraphicsLayer* layer)
2380 {
2381     if (m_rootGraphicsLayer) {
2382         if (layer->parent() != m_rootGraphicsLayer)
2383             m_rootGraphicsLayer->addChild(layer);
2384     }
2385 }
2386
2387 #if ENABLE(NOTIFICATIONS)
2388 NotificationPresenterImpl* WebViewImpl::notificationPresenterImpl()
2389 {
2390     if (!m_notificationPresenter.isInitialized() && m_client)
2391         m_notificationPresenter.initialize(m_client->notificationPresenter());
2392     return &m_notificationPresenter;
2393 }
2394 #endif
2395
2396 void WebViewImpl::refreshAutofillPopup()
2397 {
2398     ASSERT(m_autofillPopupShowing);
2399
2400     // Hide the popup if it has become empty.
2401     if (!m_autofillPopupClient->listSize()) {
2402         hideAutofillPopup();
2403         return;
2404     }
2405
2406     IntRect oldBounds = m_autofillPopup->frameRect();
2407     m_autofillPopup->refresh(focusedWebCoreNode()->getRect());
2408     IntRect newBounds = m_autofillPopup->frameRect();
2409     // Let's resize the backing window if necessary.
2410     if (oldBounds != newBounds) {
2411         WebPopupMenuImpl* popupMenu =
2412             static_cast<WebPopupMenuImpl*>(m_autofillPopup->client());
2413         if (popupMenu)
2414             popupMenu->client()->setWindowRect(m_chromeClientImpl.windowToScreen(newBounds));
2415     }
2416 }
2417
2418 Node* WebViewImpl::focusedWebCoreNode()
2419 {
2420     Frame* frame = m_page->focusController()->focusedFrame();
2421     if (!frame)
2422         return 0;
2423
2424     Document* document = frame->document();
2425     if (!document)
2426         return 0;
2427
2428     return document->focusedNode();
2429 }
2430
2431 HitTestResult WebViewImpl::hitTestResultForWindowPos(const IntPoint& pos)
2432 {
2433     IntPoint docPoint(m_page->mainFrame()->view()->windowToContents(pos));
2434     return m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(docPoint, false);
2435 }
2436
2437 void WebViewImpl::setTabsToLinks(bool enable)
2438 {
2439     m_tabsToLinks = enable;
2440 }
2441
2442 bool WebViewImpl::tabsToLinks() const
2443 {
2444     return m_tabsToLinks;
2445 }
2446
2447 #if USE(ACCELERATED_COMPOSITING)
2448 bool WebViewImpl::allowsAcceleratedCompositing()
2449 {
2450     return !m_compositorCreationFailed;
2451 }
2452
2453 bool WebViewImpl::pageHasRTLStyle() const
2454 {
2455     if (!page())
2456         return false;
2457     Document* document = page()->mainFrame()->document();
2458     if (!document)
2459         return false;
2460     RenderView* renderView = document->renderView();
2461     if (!renderView)
2462         return false;
2463     RenderStyle* style = renderView->style();
2464     if (!style)
2465         return false;
2466     return (style->direction() == RTL);
2467 }
2468
2469 void WebViewImpl::setRootGraphicsLayer(WebCore::GraphicsLayer* layer)
2470 {
2471     m_rootGraphicsLayer = layer;
2472     setRootPlatformLayer(layer ? layer->platformLayer() : 0);
2473 }
2474
2475 void WebViewImpl::setRootPlatformLayer(WebCore::PlatformLayer* layer)
2476 {
2477     setIsAcceleratedCompositingActive(layer);
2478     if (m_layerTreeHost)
2479         m_layerTreeHost->setRootLayer(layer);
2480
2481     IntRect damagedRect(0, 0, m_size.width, m_size.height);
2482     if (m_isAcceleratedCompositingActive)
2483         invalidateRootLayerRect(damagedRect);
2484     else
2485         m_client->didInvalidateRect(damagedRect);
2486 }
2487
2488 void WebViewImpl::setRootLayerNeedsDisplay()
2489 {
2490 #if USE(THREADED_COMPOSITING)
2491     if (m_layerTreeHost)
2492         m_layerTreeHost->setNeedsCommitAndRedraw();
2493 #else
2494     m_client->scheduleComposite();
2495 #endif
2496 }
2497
2498 void WebViewImpl::scrollRootLayerRect(const IntSize& scrollDelta, const IntRect& clipRect)
2499 {
2500     updateLayerTreeViewport();
2501     setRootLayerNeedsDisplay();
2502 }
2503
2504 void WebViewImpl::invalidateRootLayerRect(const IntRect& rect)
2505 {
2506     ASSERT(m_layerTreeHost);
2507
2508     if (!page())
2509         return;
2510
2511     FrameView* view = page()->mainFrame()->view();
2512     IntRect dirtyRect = view->windowToContents(rect);
2513     updateLayerTreeViewport();
2514     m_layerTreeHost->invalidateRootLayerRect(dirtyRect);
2515     setRootLayerNeedsDisplay();
2516 }
2517
2518 class WebViewImplContentPainter : public LayerPainterChromium {
2519     WTF_MAKE_NONCOPYABLE(WebViewImplContentPainter);
2520 public:
2521     static PassOwnPtr<WebViewImplContentPainter*> create(WebViewImpl* webViewImpl)
2522     {
2523         return adoptPtr(new WebViewImplContentPainter(webViewImpl));
2524     }
2525
2526     virtual void paint(GraphicsContext& context, const IntRect& contentRect)
2527     {
2528         double paintStart = currentTime();
2529         Page* page = m_webViewImpl->page();
2530         if (!page)
2531             return;
2532         FrameView* view = page->mainFrame()->view();
2533         view->paintContents(&context, contentRect);
2534         double paintEnd = currentTime();
2535         double pixelsPerSec = (contentRect.width() * contentRect.height()) / (paintEnd - paintStart);
2536         PlatformBridge::histogramCustomCounts("Renderer4.AccelRootPaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30);
2537         PlatformBridge::histogramCustomCounts("Renderer4.AccelRootPaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30);
2538     }
2539
2540 private:
2541     explicit WebViewImplContentPainter(WebViewImpl* webViewImpl)
2542         : m_webViewImpl(webViewImpl)
2543     {
2544     }
2545
2546     WebViewImpl* m_webViewImpl;
2547 };
2548
2549 void WebViewImpl::setIsAcceleratedCompositingActive(bool active)
2550 {
2551     PlatformBridge::histogramEnumeration("GPU.setIsAcceleratedCompositingActive", active * 2 + m_isAcceleratedCompositingActive, 4);
2552
2553     if (m_isAcceleratedCompositingActive == active)
2554         return;
2555
2556     if (!active) {
2557         m_isAcceleratedCompositingActive = false;
2558         // We need to finish all GL rendering before sending
2559         // didActivateAcceleratedCompositing(false) to prevent
2560         // flickering when compositing turns off.
2561         if (m_layerTreeHost)
2562             m_layerTreeHost->finishAllRendering();
2563         m_client->didActivateAcceleratedCompositing(false);
2564     } else if (m_layerTreeHost) {
2565         m_isAcceleratedCompositingActive = true;
2566         updateLayerTreeViewport();
2567
2568         m_client->didActivateAcceleratedCompositing(true);
2569     } else {
2570         TRACE_EVENT("WebViewImpl::setIsAcceleratedCompositingActive(true)", this, 0);
2571
2572         WebCore::CCSettings ccSettings;
2573         ccSettings.acceleratePainting = page()->settings()->acceleratedDrawingEnabled();
2574         ccSettings.compositeOffscreen = settings()->compositeToTextureEnabled();
2575         ccSettings.showFPSCounter = settings()->showFPSCounter();
2576         ccSettings.showPlatformLayerTree = settings()->showPlatformLayerTree();
2577
2578         m_layerTreeHost = CCLayerTreeHost::create(this, ccSettings);
2579         if (m_layerTreeHost) {
2580             m_client->didActivateAcceleratedCompositing(true);
2581             m_isAcceleratedCompositingActive = true;
2582             m_compositorCreationFailed = false;
2583             if (m_pageOverlay)
2584                 m_pageOverlay->update();
2585         } else {
2586             m_isAcceleratedCompositingActive = false;
2587             m_client->didActivateAcceleratedCompositing(false);
2588             m_compositorCreationFailed = true;
2589         }
2590     }
2591     if (page())
2592         page()->mainFrame()->view()->setClipsRepaints(!m_isAcceleratedCompositingActive);
2593 }
2594
2595 #endif
2596
2597 PassRefPtr<GraphicsContext3D> WebViewImpl::createLayerTreeHostContext3D()
2598 {
2599     RefPtr<GraphicsContext3D> context = m_temporaryOnscreenGraphicsContext3D.release();
2600     if (!context) {
2601         context = GraphicsContext3D::create(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2602         if (context)
2603             context->reshape(max(1, m_size.width), max(1, m_size.height));
2604     }
2605     return context;
2606 }
2607
2608 PassOwnPtr<LayerPainterChromium> WebViewImpl::createRootLayerPainter()
2609 {
2610     return WebViewImplContentPainter::create(this);
2611 }
2612
2613 void WebViewImpl::animateAndLayout(double frameBeginTime)
2614 {
2615     animate(frameBeginTime);
2616     layout();
2617 }
2618
2619 void WebViewImpl::didRecreateGraphicsContext(bool success)
2620 {
2621     setRootPlatformLayer(success ? m_layerTreeHost->rootLayer() : 0);
2622
2623     if (success) {
2624       // Forces ViewHostMsg_DidActivateAcceleratedCompositing to be sent so
2625       // that the browser process can reacquire surfaces.
2626       m_client->didActivateAcceleratedCompositing(true);
2627       if (m_pageOverlay)
2628           m_pageOverlay->update();
2629     }
2630 }
2631
2632 #if !USE(THREADED_COMPOSITING)
2633 void WebViewImpl::scheduleComposite()
2634 {
2635     m_client->scheduleComposite();
2636 }
2637 #endif
2638
2639 void WebViewImpl::updateLayerTreeViewport()
2640 {
2641     if (!page())
2642         return;
2643
2644     FrameView* view = page()->mainFrame()->view();
2645     IntRect contentRect = view->visibleContentRect(false);
2646     IntRect visibleRect = view->visibleContentRect(true);
2647     IntPoint scroll(view->scrollX(), view->scrollY());
2648
2649     m_layerTreeHost->setViewport(visibleRect, contentRect, scroll);
2650 }
2651
2652 WebGraphicsContext3D* WebViewImpl::graphicsContext3D()
2653 {
2654 #if USE(ACCELERATED_COMPOSITING)
2655     if (m_page->settings()->acceleratedCompositingEnabled() && allowsAcceleratedCompositing()) {
2656         if (m_layerTreeHost) {
2657             WebGraphicsContext3D* webContext = GraphicsContext3DInternal::extractWebGraphicsContext3D(m_layerTreeHost->context());
2658             if (webContext && !webContext->isContextLost())
2659                 return webContext;
2660         }
2661         if (m_temporaryOnscreenGraphicsContext3D) {
2662             WebGraphicsContext3D* webContext = GraphicsContext3DInternal::extractWebGraphicsContext3D(m_temporaryOnscreenGraphicsContext3D.get());
2663             if (webContext && !webContext->isContextLost())
2664                 return webContext;
2665         }
2666         m_temporaryOnscreenGraphicsContext3D = GraphicsContext3D::create(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2667         if (m_temporaryOnscreenGraphicsContext3D)
2668             m_temporaryOnscreenGraphicsContext3D->reshape(max(1, m_size.width), max(1, m_size.height));
2669         return GraphicsContext3DInternal::extractWebGraphicsContext3D(m_temporaryOnscreenGraphicsContext3D.get());
2670     }
2671 #endif
2672     return 0;
2673 }
2674
2675
2676 void WebViewImpl::setVisibilityState(WebPageVisibilityState visibilityState,
2677                                      bool isInitialState) {
2678     if (!page())
2679         return;
2680
2681 #if ENABLE(PAGE_VISIBILITY_API)
2682     ASSERT(visibilityState == WebPageVisibilityStateVisible
2683            || visibilityState == WebPageVisibilityStateHidden
2684            || visibilityState == WebPageVisibilityStatePrerender);
2685     m_page->setVisibilityState(static_cast<PageVisibilityState>(static_cast<int>(visibilityState)), isInitialState);
2686 #endif
2687
2688 #if USE(ACCELERATED_COMPOSITING)
2689     if (isAcceleratedCompositingActive())
2690         m_layerTreeHost->setVisible(visibilityState == WebPageVisibilityStateVisible);
2691 #endif
2692 }
2693
2694 #if ENABLE(GESTURE_RECOGNIZER)
2695 void WebViewImpl::resetGestureRecognizer()
2696 {
2697     m_gestureRecognizer->reset();
2698 }
2699 #endif
2700
2701
2702 } // namespace WebKit