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