[chromium] Resize requests at the view level should be ignored when in autoresize...
[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     if (m_shouldAutoResize || m_size == newSize)
1050         return;
1051     m_size = newSize;
1052
1053     if (mainFrameImpl()->frameView())
1054         mainFrameImpl()->frameView()->resize(m_size.width, m_size.height);
1055
1056     sendResizeEventAndRepaint();
1057 }
1058
1059 void WebViewImpl::willEndLiveResize()
1060 {
1061     if (mainFrameImpl() && mainFrameImpl()->frameView())
1062         mainFrameImpl()->frameView()->willEndLiveResize();
1063
1064     Frame* frame = mainFrameImpl()->frame();
1065     WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1066     if (pluginContainer)
1067         pluginContainer->willEndLiveResize();
1068 }
1069
1070 void WebViewImpl::willEnterFullScreen()
1071 {
1072 #if ENABLE(FULLSCREEN_API)
1073     if (!m_provisionalFullScreenElement)
1074         return;
1075
1076     // Ensure that this element's document is still attached.
1077     Document* doc = m_provisionalFullScreenElement->document();
1078     if (doc->frame()) {
1079         doc->webkitWillEnterFullScreenForElement(m_provisionalFullScreenElement.get());
1080         m_fullScreenFrame = doc->frame();
1081     }
1082     m_provisionalFullScreenElement.clear();
1083 #endif
1084 }
1085
1086 void WebViewImpl::didEnterFullScreen()
1087 {
1088 #if ENABLE(FULLSCREEN_API)
1089     if (!m_fullScreenFrame)
1090         return;
1091
1092     if (Document* doc = m_fullScreenFrame->document()) {
1093         if (doc->webkitIsFullScreen())
1094             doc->webkitDidEnterFullScreenForElement(0);
1095     }
1096 #endif
1097 }
1098
1099 void WebViewImpl::willExitFullScreen()
1100 {
1101 #if ENABLE(FULLSCREEN_API)
1102     if (!m_fullScreenFrame)
1103         return;
1104
1105     if (Document* doc = m_fullScreenFrame->document()) {
1106         if (doc->webkitIsFullScreen())
1107             doc->webkitWillExitFullScreenForElement(0);
1108     }
1109 #endif
1110 }
1111
1112 void WebViewImpl::didExitFullScreen()
1113 {
1114 #if ENABLE(FULLSCREEN_API)
1115     if (!m_fullScreenFrame)
1116         return;
1117
1118     if (Document* doc = m_fullScreenFrame->document()) {
1119         if (doc->webkitIsFullScreen())
1120             doc->webkitDidExitFullScreenForElement(0);
1121     }
1122
1123     m_fullScreenFrame.clear();
1124 #endif
1125 }
1126
1127 void WebViewImpl::animate(double frameBeginTime)
1128 {
1129 #if ENABLE(REQUEST_ANIMATION_FRAME)
1130     TRACE_EVENT("WebViewImpl::animate", this, 0);
1131     // FIXME: remove this zero-check once render_widget has been modified to
1132     // pass in a frameBeginTime.
1133     if (!frameBeginTime)
1134         frameBeginTime = currentTime();
1135     WebFrameImpl* webframe = mainFrameImpl();
1136     if (webframe) {
1137         FrameView* view = webframe->frameView();
1138         if (view) {
1139             if (!CCProxy::hasImplThread() && m_layerTreeHost)
1140                 m_layerTreeHost->setAnimating(true);
1141
1142             view->serviceScriptedAnimations(convertSecondsToDOMTimeStamp(frameBeginTime));
1143
1144             if (!CCProxy::hasImplThread() && m_layerTreeHost)
1145                 m_layerTreeHost->setAnimating(false);
1146         }
1147     }
1148 #endif
1149 }
1150
1151 void WebViewImpl::layout()
1152 {
1153     TRACE_EVENT("WebViewImpl::layout", this, 0);
1154
1155     WebFrameImpl* webframe = mainFrameImpl();
1156     if (webframe) {
1157         // In order for our child HWNDs (NativeWindowWidgets) to update properly,
1158         // they need to be told that we are updating the screen.  The problem is
1159         // that the native widgets need to recalculate their clip region and not
1160         // overlap any of our non-native widgets.  To force the resizing, call
1161         // setFrameRect().  This will be a quick operation for most frames, but
1162         // the NativeWindowWidgets will update a proper clipping region.
1163         FrameView* view = webframe->frameView();
1164         if (view)
1165             view->setFrameRect(view->frameRect());
1166
1167         // setFrameRect may have the side-effect of causing existing page
1168         // layout to be invalidated, so layout needs to be called last.
1169
1170         webframe->layout();
1171     }
1172 }
1173
1174 #if USE(ACCELERATED_COMPOSITING)
1175 void WebViewImpl::doPixelReadbackToCanvas(WebCanvas* canvas, const IntRect& rect)
1176 {
1177 #if USE(SKIA)
1178     PlatformContextSkia context(canvas);
1179
1180     // PlatformGraphicsContext is actually a pointer to PlatformContextSkia
1181     GraphicsContext gc(reinterpret_cast<PlatformGraphicsContext*>(&context));
1182     int bitmapHeight = canvas->getDevice()->accessBitmap(false).height();
1183 #elif USE(CG)
1184     GraphicsContext gc(canvas);
1185     int bitmapHeight = CGBitmapContextGetHeight(reinterpret_cast<CGContextRef>(canvas));
1186 #else
1187     notImplemented();
1188 #endif
1189     // Compute rect to sample from inverted GPU buffer.
1190     IntRect invertRect(rect.x(), bitmapHeight - rect.maxY(), rect.width(), rect.height());
1191
1192     OwnPtr<ImageBuffer> imageBuffer(ImageBuffer::create(rect.size()));
1193     RefPtr<ByteArray> pixelArray(ByteArray::create(rect.width() * rect.height() * 4));
1194     if (imageBuffer && pixelArray) {
1195         m_layerTreeHost->compositeAndReadback(pixelArray->data(), invertRect);
1196         imageBuffer->putPremultipliedImageData(pixelArray.get(), rect.size(), IntRect(IntPoint(), rect.size()), IntPoint());
1197         gc.save();
1198         gc.translate(IntSize(0, bitmapHeight));
1199         gc.scale(FloatSize(1.0f, -1.0f));
1200         // Use invertRect in next line, so that transform above inverts it back to
1201         // desired destination rect.
1202         gc.drawImageBuffer(imageBuffer.get(), ColorSpaceDeviceRGB, invertRect.location());
1203         gc.restore();
1204     }
1205 }
1206 #endif
1207
1208 void WebViewImpl::paint(WebCanvas* canvas, const WebRect& rect)
1209 {
1210     if (isAcceleratedCompositingActive()) {
1211 #if USE(ACCELERATED_COMPOSITING)
1212         // If a canvas was passed in, we use it to grab a copy of the
1213         // freshly-rendered pixels.
1214         if (canvas) {
1215             // Clip rect to the confines of the rootLayerTexture.
1216             IntRect resizeRect(rect);
1217             resizeRect.intersect(IntRect(IntPoint(0, 0), m_layerTreeHost->viewportSize()));
1218             doPixelReadbackToCanvas(canvas, resizeRect);
1219         }
1220 #endif
1221     } else {
1222         double paintStart = currentTime();
1223         WebFrameImpl* webframe = mainFrameImpl();
1224         if (webframe)
1225             webframe->paint(canvas, rect);
1226         double paintEnd = currentTime();
1227         double pixelsPerSec = (rect.width * rect.height) / (paintEnd - paintStart);
1228         PlatformSupport::histogramCustomCounts("Renderer4.SoftwarePaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30);
1229         PlatformSupport::histogramCustomCounts("Renderer4.SoftwarePaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30);
1230     }
1231 }
1232
1233 void WebViewImpl::themeChanged()
1234 {
1235     if (!page())
1236         return;
1237     FrameView* view = page()->mainFrame()->view();
1238
1239     WebRect damagedRect(0, 0, m_size.width, m_size.height);
1240     view->invalidateRect(damagedRect);
1241 }
1242
1243 void WebViewImpl::composite(bool)
1244 {
1245 #if USE(ACCELERATED_COMPOSITING)
1246     if (CCProxy::hasImplThread())
1247         m_layerTreeHost->setNeedsRedraw();
1248     else {
1249         ASSERT(isAcceleratedCompositingActive());
1250         if (!page())
1251             return;
1252
1253         if (m_pageOverlays)
1254             m_pageOverlays->update();
1255
1256         m_layerTreeHost->composite();
1257     }
1258 #endif
1259 }
1260
1261 void WebViewImpl::loseCompositorContext(int numTimes)
1262 {
1263 #if USE(ACCELERATED_COMPOSITING)
1264     if (m_layerTreeHost)
1265         m_layerTreeHost->loseCompositorContext(numTimes);
1266 #endif
1267 }
1268
1269 void WebViewImpl::enterFullScreenForElement(WebCore::Element* element)
1270 {
1271     // We are already transitioning to fullscreen for a different element.
1272     if (m_provisionalFullScreenElement) {
1273         m_provisionalFullScreenElement = element;
1274         return;
1275     }
1276
1277     // We are already in fullscreen mode.
1278     if (m_fullScreenFrame) {
1279         m_provisionalFullScreenElement = element;
1280         willEnterFullScreen();
1281         didEnterFullScreen();
1282         return;
1283     }
1284
1285     // We need to transition to fullscreen mode.
1286     if (m_client && m_client->enterFullScreen())
1287         m_provisionalFullScreenElement = element;
1288 }
1289
1290 void WebViewImpl::exitFullScreenForElement(WebCore::Element* element)
1291 {
1292     if (m_client)
1293         m_client->exitFullScreen();
1294 }
1295
1296 bool WebViewImpl::hasHorizontalScrollbar()
1297 {
1298     return mainFrameImpl()->frameView()->horizontalScrollbar();
1299 }
1300
1301 bool WebViewImpl::hasVerticalScrollbar()
1302 {
1303     return mainFrameImpl()->frameView()->verticalScrollbar();
1304 }
1305
1306 const WebInputEvent* WebViewImpl::m_currentInputEvent = 0;
1307
1308 bool WebViewImpl::handleInputEvent(const WebInputEvent& inputEvent)
1309 {
1310     UserGestureIndicator gestureIndicator(WebInputEvent::isUserGestureEventType(inputEvent.type) ? DefinitelyProcessingUserGesture : PossiblyProcessingUserGesture);
1311
1312     // If we've started a drag and drop operation, ignore input events until
1313     // we're done.
1314     if (m_doingDragAndDrop)
1315         return true;
1316
1317     if (m_ignoreInputEvents)
1318         return true;
1319
1320     m_currentInputEvent = &inputEvent;
1321
1322     if (m_mouseCaptureNode && WebInputEvent::isMouseEventType(inputEvent.type)) {
1323         // Save m_mouseCaptureNode since mouseCaptureLost() will clear it.
1324         RefPtr<Node> node = m_mouseCaptureNode;
1325
1326         // Not all platforms call mouseCaptureLost() directly.
1327         if (inputEvent.type == WebInputEvent::MouseUp)
1328             mouseCaptureLost();
1329
1330         AtomicString eventType;
1331         switch (inputEvent.type) {
1332         case WebInputEvent::MouseMove:
1333             eventType = eventNames().mousemoveEvent;
1334             break;
1335         case WebInputEvent::MouseLeave:
1336             eventType = eventNames().mouseoutEvent;
1337             break;
1338         case WebInputEvent::MouseDown:
1339             eventType = eventNames().mousedownEvent;
1340             break;
1341         case WebInputEvent::MouseUp:
1342             eventType = eventNames().mouseupEvent;
1343             break;
1344         default:
1345             ASSERT_NOT_REACHED();
1346         }
1347
1348         node->dispatchMouseEvent(
1349               PlatformMouseEventBuilder(mainFrameImpl()->frameView(), *static_cast<const WebMouseEvent*>(&inputEvent)),
1350               eventType, static_cast<const WebMouseEvent*>(&inputEvent)->clickCount);
1351         m_currentInputEvent = 0;
1352         return true;
1353     }
1354
1355     bool handled = true;
1356
1357     // FIXME: WebKit seems to always return false on mouse events processing
1358     // methods. For now we'll assume it has processed them (as we are only
1359     // interested in whether keyboard events are processed).
1360     switch (inputEvent.type) {
1361     case WebInputEvent::MouseMove:
1362         mouseMove(*static_cast<const WebMouseEvent*>(&inputEvent));
1363         break;
1364
1365     case WebInputEvent::MouseLeave:
1366         mouseLeave(*static_cast<const WebMouseEvent*>(&inputEvent));
1367         break;
1368
1369     case WebInputEvent::MouseWheel:
1370         handled = mouseWheel(*static_cast<const WebMouseWheelEvent*>(&inputEvent));
1371         break;
1372
1373     case WebInputEvent::MouseDown:
1374         mouseDown(*static_cast<const WebMouseEvent*>(&inputEvent));
1375         break;
1376
1377     case WebInputEvent::MouseUp:
1378         mouseUp(*static_cast<const WebMouseEvent*>(&inputEvent));
1379         break;
1380
1381     case WebInputEvent::RawKeyDown:
1382     case WebInputEvent::KeyDown:
1383     case WebInputEvent::KeyUp:
1384         handled = keyEvent(*static_cast<const WebKeyboardEvent*>(&inputEvent));
1385         break;
1386
1387     case WebInputEvent::Char:
1388         handled = charEvent(*static_cast<const WebKeyboardEvent*>(&inputEvent));
1389         break;
1390
1391 #if ENABLE(GESTURE_EVENTS)
1392     case WebInputEvent::GestureScrollBegin:
1393     case WebInputEvent::GestureScrollEnd:
1394     case WebInputEvent::GestureScrollUpdate:
1395     case WebInputEvent::GestureFlingStart:
1396     case WebInputEvent::GestureFlingCancel:
1397     case WebInputEvent::GestureTap:
1398         handled = gestureEvent(*static_cast<const WebGestureEvent*>(&inputEvent));
1399         break;
1400 #endif
1401
1402 #if ENABLE(TOUCH_EVENTS)
1403     case WebInputEvent::TouchStart:
1404     case WebInputEvent::TouchMove:
1405     case WebInputEvent::TouchEnd:
1406     case WebInputEvent::TouchCancel:
1407         handled = touchEvent(*static_cast<const WebTouchEvent*>(&inputEvent));
1408         break;
1409 #endif
1410
1411     default:
1412         handled = false;
1413     }
1414
1415     m_currentInputEvent = 0;
1416
1417     return handled;
1418 }
1419
1420 void WebViewImpl::mouseCaptureLost()
1421 {
1422     m_mouseCaptureNode = 0;
1423 }
1424
1425 void WebViewImpl::setFocus(bool enable)
1426 {
1427     m_page->focusController()->setFocused(enable);
1428     if (enable) {
1429         m_page->focusController()->setActive(true);
1430         RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
1431         if (focusedFrame) {
1432             Node* focusedNode = focusedFrame->document()->focusedNode();
1433             if (focusedNode && focusedNode->isElementNode()
1434                 && focusedFrame->selection()->selection().isNone()) {
1435                 // If the selection was cleared while the WebView was not
1436                 // focused, then the focus element shows with a focus ring but
1437                 // no caret and does respond to keyboard inputs.
1438                 Element* element = static_cast<Element*>(focusedNode);
1439                 if (element->isTextFormControl())
1440                     element->updateFocusAppearance(true);
1441                 else if (focusedNode->isContentEditable()) {
1442                     // updateFocusAppearance() selects all the text of
1443                     // contentseditable DIVs. So we set the selection explicitly
1444                     // instead. Note that this has the side effect of moving the
1445                     // caret back to the beginning of the text.
1446                     Position position(focusedNode, 0,
1447                                       Position::PositionIsOffsetInAnchor);
1448                     focusedFrame->selection()->setSelection(
1449                         VisibleSelection(position, SEL_DEFAULT_AFFINITY));
1450                 }
1451             }
1452         }
1453         m_imeAcceptEvents = true;
1454     } else {
1455         hideAutofillPopup();
1456         hideSelectPopup();
1457
1458         // Clear focus on the currently focused frame if any.
1459         if (!m_page)
1460             return;
1461
1462         Frame* frame = m_page->mainFrame();
1463         if (!frame)
1464             return;
1465
1466         RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
1467         if (focusedFrame) {
1468             // Finish an ongoing composition to delete the composition node.
1469             Editor* editor = focusedFrame->editor();
1470             if (editor && editor->hasComposition())
1471                 editor->confirmComposition();
1472             m_imeAcceptEvents = false;
1473         }
1474     }
1475 }
1476
1477 bool WebViewImpl::setComposition(
1478     const WebString& text,
1479     const WebVector<WebCompositionUnderline>& underlines,
1480     int selectionStart,
1481     int selectionEnd)
1482 {
1483     Frame* focused = focusedWebCoreFrame();
1484     if (!focused || !m_imeAcceptEvents)
1485         return false;
1486     Editor* editor = focused->editor();
1487     if (!editor)
1488         return false;
1489
1490     // The input focus has been moved to another WebWidget object.
1491     // We should use this |editor| object only to complete the ongoing
1492     // composition.
1493     if (!editor->canEdit() && !editor->hasComposition())
1494         return false;
1495
1496     // We should verify the parent node of this IME composition node are
1497     // editable because JavaScript may delete a parent node of the composition
1498     // node. In this case, WebKit crashes while deleting texts from the parent
1499     // node, which doesn't exist any longer.
1500     PassRefPtr<Range> range = editor->compositionRange();
1501     if (range) {
1502         Node* node = range->startContainer();
1503         if (!node || !node->isContentEditable())
1504             return false;
1505     }
1506
1507     // If we're not going to fire a keypress event, then the keydown event was
1508     // canceled.  In that case, cancel any existing composition.
1509     if (text.isEmpty() || m_suppressNextKeypressEvent) {
1510         // A browser process sent an IPC message which does not contain a valid
1511         // string, which means an ongoing composition has been canceled.
1512         // If the ongoing composition has been canceled, replace the ongoing
1513         // composition string with an empty string and complete it.
1514         String emptyString;
1515         Vector<CompositionUnderline> emptyUnderlines;
1516         editor->setComposition(emptyString, emptyUnderlines, 0, 0);
1517         return text.isEmpty();
1518     }
1519
1520     // When the range of composition underlines overlap with the range between
1521     // selectionStart and selectionEnd, WebKit somehow won't paint the selection
1522     // at all (see InlineTextBox::paint() function in InlineTextBox.cpp).
1523     // But the selection range actually takes effect.
1524     editor->setComposition(String(text),
1525                            CompositionUnderlineVectorBuilder(underlines),
1526                            selectionStart, selectionEnd);
1527
1528     return editor->hasComposition();
1529 }
1530
1531 bool WebViewImpl::confirmComposition()
1532 {
1533     return confirmComposition(WebString());
1534 }
1535
1536 bool WebViewImpl::confirmComposition(const WebString& text)
1537 {
1538     Frame* focused = focusedWebCoreFrame();
1539     if (!focused || !m_imeAcceptEvents)
1540         return false;
1541     Editor* editor = focused->editor();
1542     if (!editor || (!editor->hasComposition() && !text.length()))
1543         return false;
1544
1545     // We should verify the parent node of this IME composition node are
1546     // editable because JavaScript may delete a parent node of the composition
1547     // node. In this case, WebKit crashes while deleting texts from the parent
1548     // node, which doesn't exist any longer.
1549     PassRefPtr<Range> range = editor->compositionRange();
1550     if (range) {
1551         Node* node = range->startContainer();
1552         if (!node || !node->isContentEditable())
1553             return false;
1554     }
1555
1556     if (editor->hasComposition()) {
1557         if (text.length())
1558             editor->confirmComposition(String(text));
1559         else
1560             editor->confirmComposition();
1561     } else
1562         editor->insertText(String(text), 0);
1563
1564     return true;
1565 }
1566
1567 bool WebViewImpl::compositionRange(size_t* location, size_t* length)
1568 {
1569     Frame* focused = focusedWebCoreFrame();
1570     if (!focused || !focused->selection() || !m_imeAcceptEvents)
1571         return false;
1572     Editor* editor = focused->editor();
1573     if (!editor || !editor->hasComposition())
1574         return false;
1575
1576     RefPtr<Range> range = editor->compositionRange();
1577     if (!range)
1578         return false;
1579
1580     if (TextIterator::getLocationAndLengthFromRange(focused->selection()->rootEditableElementOrDocumentElement(), range.get(), *location, *length))
1581         return true;
1582     return false;
1583 }
1584
1585 WebTextInputType WebViewImpl::textInputType()
1586 {
1587     Node* node = focusedWebCoreNode();
1588     if (!node)
1589         return WebTextInputTypeNone;
1590
1591     if (node->nodeType() == Node::ELEMENT_NODE) {
1592         Element* element = static_cast<Element*>(node);
1593         if (element->hasLocalName(HTMLNames::inputTag)) {
1594             HTMLInputElement* input = static_cast<HTMLInputElement*>(element);
1595
1596             if (input->readOnly() || input->disabled())
1597                 return WebTextInputTypeNone;
1598
1599             if (input->isPasswordField())
1600                 return WebTextInputTypePassword;
1601             if (input->isSearchField())
1602                 return WebTextInputTypeSearch;
1603             if (input->isEmailField())
1604                 return WebTextInputTypeEmail;
1605             if (input->isNumberField())
1606                 return WebTextInputTypeNumber;
1607             if (input->isTelephoneField())
1608                 return WebTextInputTypeTelephone;
1609             if (input->isURLField())
1610                 return WebTextInputTypeURL;
1611             if (input->isTextField())
1612                 return WebTextInputTypeText;
1613             return WebTextInputTypeNone;
1614         }
1615
1616         if (element->hasLocalName(HTMLNames::textareaTag)) {
1617             HTMLTextAreaElement* textarea = static_cast<HTMLTextAreaElement*>(element);
1618
1619             if (textarea->readOnly() || textarea->disabled())
1620                 return WebTextInputTypeNone;
1621             return WebTextInputTypeText;
1622         }
1623     }
1624
1625     // For other situations.
1626     if (node->shouldUseInputMethod())
1627         return WebTextInputTypeText;
1628
1629     return WebTextInputTypeNone;
1630 }
1631
1632 bool WebViewImpl::selectionBounds(WebRect& start, WebRect& end) const
1633 {
1634     const Frame* frame = focusedWebCoreFrame();
1635     if (!frame)
1636         return false;
1637     FrameSelection* selection = frame->selection();
1638     if (!selection)
1639         return false;
1640
1641     if (selection->isCaret()) {
1642         start = end = frame->view()->contentsToWindow(selection->absoluteCaretBounds());
1643         return true;
1644     }
1645
1646     RefPtr<Range> selectedRange = frame->selection()->toNormalizedRange();
1647     if (!selectedRange)
1648         return false;
1649
1650     RefPtr<Range> range(Range::create(selectedRange->startContainer()->document(),
1651                                       selectedRange->startContainer(),
1652                                       selectedRange->startOffset(),
1653                                       selectedRange->startContainer(),
1654                                       selectedRange->startOffset()));
1655     start = frame->editor()->firstRectForRange(range.get());
1656
1657     range = Range::create(selectedRange->endContainer()->document(),
1658                           selectedRange->endContainer(),
1659                           selectedRange->endOffset(),
1660                           selectedRange->endContainer(),
1661                           selectedRange->endOffset());
1662     end = frame->editor()->firstRectForRange(range.get());
1663
1664     start = frame->view()->contentsToWindow(start);
1665     end = frame->view()->contentsToWindow(end);
1666
1667     if (!frame->selection()->selection().isBaseFirst())
1668         std::swap(start, end);
1669     return true;
1670 }
1671
1672 bool WebViewImpl::caretOrSelectionRange(size_t* location, size_t* length)
1673 {
1674     const Frame* focused = focusedWebCoreFrame();
1675     if (!focused)
1676         return false;
1677
1678     FrameSelection* selection = focused->selection();
1679     if (!selection)
1680         return false;
1681
1682     RefPtr<Range> range = selection->selection().firstRange();
1683     if (!range)
1684         return false;
1685
1686     if (TextIterator::getLocationAndLengthFromRange(selection->rootEditableElementOrDocumentElement(), range.get(), *location, *length))
1687         return true;
1688     return false;
1689 }
1690
1691 void WebViewImpl::setTextDirection(WebTextDirection direction)
1692 {
1693     // The Editor::setBaseWritingDirection() function checks if we can change
1694     // the text direction of the selected node and updates its DOM "dir"
1695     // attribute and its CSS "direction" property.
1696     // So, we just call the function as Safari does.
1697     const Frame* focused = focusedWebCoreFrame();
1698     if (!focused)
1699         return;
1700
1701     Editor* editor = focused->editor();
1702     if (!editor || !editor->canEdit())
1703         return;
1704
1705     switch (direction) {
1706     case WebTextDirectionDefault:
1707         editor->setBaseWritingDirection(NaturalWritingDirection);
1708         break;
1709
1710     case WebTextDirectionLeftToRight:
1711         editor->setBaseWritingDirection(LeftToRightWritingDirection);
1712         break;
1713
1714     case WebTextDirectionRightToLeft:
1715         editor->setBaseWritingDirection(RightToLeftWritingDirection);
1716         break;
1717
1718     default:
1719         notImplemented();
1720         break;
1721     }
1722 }
1723
1724 bool WebViewImpl::isAcceleratedCompositingActive() const
1725 {
1726 #if USE(ACCELERATED_COMPOSITING)
1727     return m_isAcceleratedCompositingActive;
1728 #else
1729     return false;
1730 #endif
1731 }
1732
1733 // WebView --------------------------------------------------------------------
1734
1735 WebSettings* WebViewImpl::settings()
1736 {
1737     if (!m_webSettings)
1738         m_webSettings = adoptPtr(new WebSettingsImpl(m_page->settings()));
1739     ASSERT(m_webSettings);
1740     return m_webSettings.get();
1741 }
1742
1743 WebString WebViewImpl::pageEncoding() const
1744 {
1745     if (!m_page)
1746         return WebString();
1747
1748     // FIXME: Is this check needed?
1749     if (!m_page->mainFrame()->document()->loader())
1750         return WebString();
1751
1752     return m_page->mainFrame()->document()->encoding();
1753 }
1754
1755 void WebViewImpl::setPageEncoding(const WebString& encodingName)
1756 {
1757     if (!m_page)
1758         return;
1759
1760     // Only change override encoding, don't change default encoding.
1761     // Note that the new encoding must be 0 if it isn't supposed to be set.
1762     String newEncodingName;
1763     if (!encodingName.isEmpty())
1764         newEncodingName = encodingName;
1765     m_page->mainFrame()->loader()->reloadWithOverrideEncoding(newEncodingName);
1766 }
1767
1768 bool WebViewImpl::dispatchBeforeUnloadEvent()
1769 {
1770     // FIXME: This should really cause a recursive depth-first walk of all
1771     // frames in the tree, calling each frame's onbeforeunload.  At the moment,
1772     // we're consistent with Safari 3.1, not IE/FF.
1773     Frame* frame = m_page->mainFrame();
1774     if (!frame)
1775         return true;
1776
1777     return frame->loader()->shouldClose();
1778 }
1779
1780 void WebViewImpl::dispatchUnloadEvent()
1781 {
1782     // Run unload handlers.
1783     m_page->mainFrame()->loader()->closeURL();
1784 }
1785
1786 WebFrame* WebViewImpl::mainFrame()
1787 {
1788     return mainFrameImpl();
1789 }
1790
1791 WebFrame* WebViewImpl::findFrameByName(
1792     const WebString& name, WebFrame* relativeToFrame)
1793 {
1794     if (!relativeToFrame)
1795         relativeToFrame = mainFrame();
1796     Frame* frame = static_cast<WebFrameImpl*>(relativeToFrame)->frame();
1797     frame = frame->tree()->find(name);
1798     return WebFrameImpl::fromFrame(frame);
1799 }
1800
1801 WebFrame* WebViewImpl::focusedFrame()
1802 {
1803     return WebFrameImpl::fromFrame(focusedWebCoreFrame());
1804 }
1805
1806 void WebViewImpl::setFocusedFrame(WebFrame* frame)
1807 {
1808     if (!frame) {
1809         // Clears the focused frame if any.
1810         Frame* frame = focusedWebCoreFrame();
1811         if (frame)
1812             frame->selection()->setFocused(false);
1813         return;
1814     }
1815     WebFrameImpl* frameImpl = static_cast<WebFrameImpl*>(frame);
1816     Frame* webcoreFrame = frameImpl->frame();
1817     webcoreFrame->page()->focusController()->setFocusedFrame(webcoreFrame);
1818 }
1819
1820 void WebViewImpl::setInitialFocus(bool reverse)
1821 {
1822     if (!m_page)
1823         return;
1824
1825     // Since we don't have a keyboard event, we'll create one.
1826     WebKeyboardEvent keyboardEvent;
1827     keyboardEvent.type = WebInputEvent::RawKeyDown;
1828     if (reverse)
1829         keyboardEvent.modifiers = WebInputEvent::ShiftKey;
1830
1831     // VK_TAB which is only defined on Windows.
1832     keyboardEvent.windowsKeyCode = 0x09;
1833     PlatformKeyboardEventBuilder platformEvent(keyboardEvent);
1834     RefPtr<KeyboardEvent> webkitEvent = KeyboardEvent::create(platformEvent, 0);
1835
1836     Frame* frame = page()->focusController()->focusedOrMainFrame();
1837     if (Document* document = frame->document())
1838         document->setFocusedNode(0);
1839     page()->focusController()->setInitialFocus(
1840         reverse ? FocusDirectionBackward : FocusDirectionForward,
1841         webkitEvent.get());
1842 }
1843
1844 void WebViewImpl::clearFocusedNode()
1845 {
1846     RefPtr<Frame> frame = focusedWebCoreFrame();
1847     if (!frame)
1848         return;
1849
1850     RefPtr<Document> document = frame->document();
1851     if (!document)
1852         return;
1853
1854     RefPtr<Node> oldFocusedNode = document->focusedNode();
1855
1856     // Clear the focused node.
1857     document->setFocusedNode(0);
1858
1859     if (!oldFocusedNode)
1860         return;
1861
1862     // If a text field has focus, we need to make sure the selection controller
1863     // knows to remove selection from it. Otherwise, the text field is still
1864     // processing keyboard events even though focus has been moved to the page and
1865     // keystrokes get eaten as a result.
1866     if (oldFocusedNode->isContentEditable()
1867         || (oldFocusedNode->isElementNode()
1868             && static_cast<Element*>(oldFocusedNode.get())->isTextFormControl())) {
1869         frame->selection()->clear();
1870     }
1871 }
1872
1873 void WebViewImpl::scrollFocusedNodeIntoView()
1874 {
1875     Node* focusedNode = focusedWebCoreNode();
1876     if (focusedNode && focusedNode->isElementNode()) {
1877         Element* elementNode = static_cast<Element*>(focusedNode);
1878         elementNode->scrollIntoViewIfNeeded(true);
1879     }
1880 }
1881
1882 void WebViewImpl::scrollFocusedNodeIntoRect(const WebRect& rect)
1883 {
1884     Frame* frame = page()->mainFrame();
1885     Node* focusedNode = focusedWebCoreNode();
1886     if (!frame || !frame->view() || !focusedNode || !focusedNode->isElementNode())
1887         return;
1888     Element* elementNode = static_cast<Element*>(focusedNode);
1889     frame->view()->scrollElementToRect(elementNode, IntRect(rect.x, rect.y, rect.width, rect.height));
1890 }
1891
1892 double WebViewImpl::zoomLevel()
1893 {
1894     return m_zoomLevel;
1895 }
1896
1897 double WebViewImpl::setZoomLevel(bool textOnly, double zoomLevel)
1898 {
1899     if (zoomLevel < m_minimumZoomLevel)
1900         m_zoomLevel = m_minimumZoomLevel;
1901     else if (zoomLevel > m_maximumZoomLevel)
1902         m_zoomLevel = m_maximumZoomLevel;
1903     else
1904         m_zoomLevel = zoomLevel;
1905
1906     Frame* frame = mainFrameImpl()->frame();
1907     WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1908     if (pluginContainer)
1909         pluginContainer->plugin()->setZoomLevel(m_zoomLevel, textOnly);
1910     else {
1911         float zoomFactor = static_cast<float>(zoomLevelToZoomFactor(m_zoomLevel));
1912         if (textOnly)
1913             frame->setPageAndTextZoomFactors(1, zoomFactor);
1914         else
1915             frame->setPageAndTextZoomFactors(zoomFactor, 1);
1916     }
1917     return m_zoomLevel;
1918 }
1919
1920 void WebViewImpl::zoomLimitsChanged(double minimumZoomLevel,
1921                                     double maximumZoomLevel)
1922 {
1923     m_minimumZoomLevel = minimumZoomLevel;
1924     m_maximumZoomLevel = maximumZoomLevel;
1925     m_client->zoomLimitsChanged(m_minimumZoomLevel, m_maximumZoomLevel);
1926 }
1927
1928 void WebViewImpl::fullFramePluginZoomLevelChanged(double zoomLevel)
1929 {
1930     if (zoomLevel == m_zoomLevel)
1931         return;
1932
1933     m_zoomLevel = max(min(zoomLevel, m_maximumZoomLevel), m_minimumZoomLevel);
1934     m_client->zoomLevelChanged();
1935 }
1936
1937 double WebView::zoomLevelToZoomFactor(double zoomLevel)
1938 {
1939     return pow(textSizeMultiplierRatio, zoomLevel);
1940 }
1941
1942 double WebView::zoomFactorToZoomLevel(double factor)
1943 {
1944     // Since factor = 1.2^level, level = log(factor) / log(1.2)
1945     return log(factor) / log(textSizeMultiplierRatio);
1946 }
1947
1948 float WebViewImpl::pageScaleFactor() const
1949 {
1950     if (!page())
1951         return 1;
1952
1953     return page()->pageScaleFactor();
1954 }
1955
1956 bool WebViewImpl::isPageScaleFactorSet() const
1957 {
1958     return m_pageScaleFactorIsSet;
1959 }
1960
1961 float WebViewImpl::clampPageScaleFactorToLimits(float scaleFactor)
1962 {
1963     return min(max(scaleFactor, m_minimumPageScaleFactor), m_maximumPageScaleFactor);
1964 }
1965
1966 WebPoint WebViewImpl::clampOffsetAtScale(const WebPoint& offset, float scale)
1967 {
1968     // This is the scaled content size. We need to convert it to the new scale factor.
1969     WebSize contentSize = mainFrame()->contentsSize();
1970     float deltaScale = scale / pageScaleFactor();
1971     int docWidthAtNewScale = contentSize.width * deltaScale;
1972     int docHeightAtNewScale = contentSize.height * deltaScale;
1973     int viewWidth = m_size.width;
1974     int viewHeight = m_size.height;
1975
1976     // Enforce the maximum and minimum scroll positions at the new scale.
1977     IntPoint clampedOffset = offset;
1978     clampedOffset = clampedOffset.shrunkTo(IntPoint(docWidthAtNewScale - viewWidth, docHeightAtNewScale - viewHeight));
1979     clampedOffset.clampNegativeToZero();
1980     return clampedOffset;
1981 }
1982
1983 void WebViewImpl::setPageScaleFactorPreservingScrollOffset(float scaleFactor)
1984 {
1985     // Pick a scale factor that is within the expected limits
1986     scaleFactor = clampPageScaleFactorToLimits(scaleFactor);
1987     if (scaleFactor == pageScaleFactor())
1988         return;
1989
1990     IntPoint scrollOffsetAtNewScale(mainFrame()->scrollOffset().width, mainFrame()->scrollOffset().height);
1991     float deltaScale = scaleFactor / pageScaleFactor();
1992     scrollOffsetAtNewScale.scale(deltaScale, deltaScale);
1993
1994     WebPoint clampedOffsetAtNewScale = clampOffsetAtScale(scrollOffsetAtNewScale, scaleFactor);
1995     setPageScaleFactor(scaleFactor, clampedOffsetAtNewScale);
1996 }
1997
1998 void WebViewImpl::setPageScaleFactor(float scaleFactor, const WebPoint& origin)
1999 {
2000     if (!page())
2001         return;
2002
2003     if (!scaleFactor)
2004         scaleFactor = 1;
2005
2006     scaleFactor = clampPageScaleFactorToLimits(scaleFactor);
2007     WebPoint clampedOrigin = clampOffsetAtScale(origin, scaleFactor);
2008     page()->setPageScaleFactor(scaleFactor, clampedOrigin);
2009     m_pageScaleFactorIsSet = true;
2010 }
2011
2012 float WebViewImpl::deviceScaleFactor() const
2013 {
2014     if (!page())
2015         return 1;
2016
2017     return page()->deviceScaleFactor();
2018 }
2019
2020 void WebViewImpl::setDeviceScaleFactor(float scaleFactor)
2021 {
2022     if (!page())
2023         return;
2024
2025     page()->setDeviceScaleFactor(scaleFactor);
2026 }
2027
2028 bool WebViewImpl::shouldLayoutFixedElementsRelativeToFrame() const
2029 {
2030     if (!page())
2031         return false;
2032
2033     Frame* frame = page()->mainFrame();
2034     if (!frame || !frame->view())
2035         return false;
2036
2037     return frame->view()->shouldLayoutFixedElementsRelativeToFrame();
2038 }
2039
2040 void WebViewImpl::setShouldLayoutFixedElementsRelativeToFrame(bool enable)
2041 {
2042     if (!page())
2043         return;
2044
2045     Frame* frame = page()->mainFrame();
2046     if (!frame || !frame->view())
2047         return;
2048
2049     frame->view()->setShouldLayoutFixedElementsRelativeToFrame(enable);
2050 }
2051
2052 bool WebViewImpl::isFixedLayoutModeEnabled() const
2053 {
2054     if (!page())
2055         return false;
2056
2057     Frame* frame = page()->mainFrame();
2058     if (!frame || !frame->view())
2059         return false;
2060
2061     return frame->view()->useFixedLayout();
2062 }
2063
2064 void WebViewImpl::enableFixedLayoutMode(bool enable)
2065 {
2066     if (!page())
2067         return;
2068
2069     Frame* frame = page()->mainFrame();
2070     if (!frame || !frame->view())
2071         return;
2072
2073     frame->view()->setUseFixedLayout(enable);
2074
2075 #if USE(ACCELERATED_COMPOSITING)
2076     // Also notify the base layer, which RenderLayerCompositor does not see.
2077     if (m_nonCompositedContentHost) {
2078         m_nonCompositedContentHost->topLevelRootLayer()->deviceOrPageScaleFactorChanged();
2079         updateLayerTreeViewport();
2080     }
2081 #endif
2082 }
2083
2084 void WebViewImpl::enableAutoResizeMode(bool enable, const WebSize& minSize, const WebSize& maxSize)
2085 {
2086     m_shouldAutoResize = enable;
2087     m_minAutoSize = minSize;
2088     m_maxAutoSize = maxSize;
2089     if (!mainFrameImpl() || !mainFrameImpl()->frame() || !mainFrameImpl()->frame()->view())
2090         return;
2091
2092     mainFrameImpl()->frame()->view()->enableAutoSizeMode(m_shouldAutoResize, m_minAutoSize, m_maxAutoSize);
2093 }
2094
2095 void WebViewImpl::setPageScaleFactorLimits(float minPageScale, float maxPageScale)
2096 {
2097     m_pageDefinedMinimumPageScaleFactor = minPageScale;
2098     m_pageDefinedMaximumPageScaleFactor = maxPageScale;
2099     computePageScaleFactorLimits();
2100 }
2101
2102 bool WebViewImpl::computePageScaleFactorLimits()
2103 {
2104     if (m_pageDefinedMinimumPageScaleFactor == -1 || m_pageDefinedMaximumPageScaleFactor == -1)
2105         return false;
2106
2107     if (!mainFrame() || !page() || !page()->mainFrame() || !page()->mainFrame()->view())
2108         return false;
2109
2110     m_minimumPageScaleFactor = min(max(m_pageDefinedMinimumPageScaleFactor, minPageScaleFactor), maxPageScaleFactor) * deviceScaleFactor();
2111     m_maximumPageScaleFactor = max(min(m_pageDefinedMaximumPageScaleFactor, maxPageScaleFactor), minPageScaleFactor) * deviceScaleFactor();
2112
2113     int viewWidthNotIncludingScrollbars = page()->mainFrame()->view()->visibleContentRect(false).width();
2114     int contentsWidth = mainFrame()->contentsSize().width;
2115     if (viewWidthNotIncludingScrollbars && contentsWidth) {
2116         // Limit page scaling down to the document width.
2117         int unscaledContentWidth = contentsWidth / pageScaleFactor();
2118         m_minimumPageScaleFactor = max(m_minimumPageScaleFactor, static_cast<float>(viewWidthNotIncludingScrollbars) / unscaledContentWidth);
2119         m_maximumPageScaleFactor = max(m_minimumPageScaleFactor, m_maximumPageScaleFactor);
2120     }
2121     ASSERT(m_minimumPageScaleFactor <= m_maximumPageScaleFactor);
2122 #if USE(ACCELERATED_COMPOSITING)
2123     if (m_layerTreeHost)
2124         m_layerTreeHost->setPageScaleFactorLimits(m_minimumPageScaleFactor, m_maximumPageScaleFactor);
2125 #endif
2126
2127     float clampedScale = clampPageScaleFactorToLimits(pageScaleFactor());
2128     if (clampedScale != pageScaleFactor()) {
2129         setPageScaleFactorPreservingScrollOffset(clampedScale);
2130         return true;
2131     }
2132
2133     return false;
2134 }
2135
2136 float WebViewImpl::minimumPageScaleFactor() const
2137 {
2138     return m_minimumPageScaleFactor;
2139 }
2140
2141 float WebViewImpl::maximumPageScaleFactor() const
2142 {
2143     return m_maximumPageScaleFactor;
2144 }
2145
2146 WebSize WebViewImpl::fixedLayoutSize() const
2147 {
2148     if (!page())
2149         return WebSize();
2150
2151     Frame* frame = page()->mainFrame();
2152     if (!frame || !frame->view())
2153         return WebSize();
2154
2155     return frame->view()->fixedLayoutSize();
2156 }
2157
2158 void WebViewImpl::setFixedLayoutSize(const WebSize& layoutSize)
2159 {
2160     if (!page())
2161         return;
2162
2163     Frame* frame = page()->mainFrame();
2164     if (!frame || !frame->view())
2165         return;
2166
2167     frame->view()->setFixedLayoutSize(layoutSize);
2168 }
2169
2170 void WebViewImpl::performMediaPlayerAction(const WebMediaPlayerAction& action,
2171                                            const WebPoint& location)
2172 {
2173     HitTestResult result = hitTestResultForWindowPos(location);
2174     RefPtr<Node> node = result.innerNonSharedNode();
2175     if (!node->hasTagName(HTMLNames::videoTag) && !node->hasTagName(HTMLNames::audioTag))
2176       return;
2177
2178     RefPtr<HTMLMediaElement> mediaElement =
2179         static_pointer_cast<HTMLMediaElement>(node);
2180     switch (action.type) {
2181     case WebMediaPlayerAction::Play:
2182         if (action.enable)
2183             mediaElement->play();
2184         else
2185             mediaElement->pause();
2186         break;
2187     case WebMediaPlayerAction::Mute:
2188         mediaElement->setMuted(action.enable);
2189         break;
2190     case WebMediaPlayerAction::Loop:
2191         mediaElement->setLoop(action.enable);
2192         break;
2193     case WebMediaPlayerAction::Controls:
2194         mediaElement->setControls(action.enable);
2195         break;
2196     default:
2197         ASSERT_NOT_REACHED();
2198     }
2199 }
2200
2201 void WebViewImpl::copyImageAt(const WebPoint& point)
2202 {
2203     if (!m_page)
2204         return;
2205
2206     HitTestResult result = hitTestResultForWindowPos(point);
2207
2208     if (result.absoluteImageURL().isEmpty()) {
2209         // There isn't actually an image at these coordinates.  Might be because
2210         // the window scrolled while the context menu was open or because the page
2211         // changed itself between when we thought there was an image here and when
2212         // we actually tried to retreive the image.
2213         //
2214         // FIXME: implement a cache of the most recent HitTestResult to avoid having
2215         //        to do two hit tests.
2216         return;
2217     }
2218
2219     m_page->mainFrame()->editor()->copyImage(result);
2220 }
2221
2222 void WebViewImpl::dragSourceEndedAt(
2223     const WebPoint& clientPoint,
2224     const WebPoint& screenPoint,
2225     WebDragOperation operation)
2226 {
2227     PlatformMouseEvent pme(clientPoint,
2228                            screenPoint,
2229                            LeftButton, PlatformEvent::MouseMoved, 0, false, false, false,
2230                            false, 0);
2231     m_page->mainFrame()->eventHandler()->dragSourceEndedAt(pme,
2232         static_cast<DragOperation>(operation));
2233     m_dragScrollTimer->stop();
2234 }
2235
2236 void WebViewImpl::dragSourceMovedTo(
2237     const WebPoint& clientPoint,
2238     const WebPoint& screenPoint,
2239     WebDragOperation operation)
2240 {
2241     m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
2242 }
2243
2244 void WebViewImpl::dragSourceSystemDragEnded()
2245 {
2246     // It's possible for us to get this callback while not doing a drag if
2247     // it's from a previous page that got unloaded.
2248     if (m_doingDragAndDrop) {
2249         m_page->dragController()->dragEnded();
2250         m_doingDragAndDrop = false;
2251     }
2252 }
2253
2254 WebDragOperation WebViewImpl::dragTargetDragEnter(
2255     const WebDragData& webDragData,
2256     const WebPoint& clientPoint,
2257     const WebPoint& screenPoint,
2258     WebDragOperationsMask operationsAllowed)
2259 {
2260     ASSERT(!m_currentDragData);
2261
2262     m_currentDragData = webDragData;
2263     m_operationsAllowed = operationsAllowed;
2264
2265     return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragEnter);
2266 }
2267
2268 WebDragOperation WebViewImpl::dragTargetDragOver(
2269     const WebPoint& clientPoint,
2270     const WebPoint& screenPoint,
2271     WebDragOperationsMask operationsAllowed)
2272 {
2273     m_operationsAllowed = operationsAllowed;
2274
2275     return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragOver);
2276 }
2277
2278 void WebViewImpl::dragTargetDragLeave()
2279 {
2280     ASSERT(m_currentDragData);
2281
2282     DragData dragData(
2283         m_currentDragData.get(),
2284         IntPoint(),
2285         IntPoint(),
2286         static_cast<DragOperation>(m_operationsAllowed));
2287
2288     m_page->dragController()->dragExited(&dragData);
2289
2290     // FIXME: why is the drag scroll timer not stopped here?
2291
2292     m_dragOperation = WebDragOperationNone;
2293     m_currentDragData = 0;
2294 }
2295
2296 void WebViewImpl::dragTargetDrop(const WebPoint& clientPoint,
2297                                  const WebPoint& screenPoint)
2298 {
2299     ASSERT(m_currentDragData);
2300
2301     // If this webview transitions from the "drop accepting" state to the "not
2302     // accepting" state, then our IPC message reply indicating that may be in-
2303     // flight, or else delayed by javascript processing in this webview.  If a
2304     // drop happens before our IPC reply has reached the browser process, then
2305     // the browser forwards the drop to this webview.  So only allow a drop to
2306     // proceed if our webview m_dragOperation state is not DragOperationNone.
2307
2308     if (m_dragOperation == WebDragOperationNone) { // IPC RACE CONDITION: do not allow this drop.
2309         dragTargetDragLeave();
2310         return;
2311     }
2312
2313     DragData dragData(
2314         m_currentDragData.get(),
2315         clientPoint,
2316         screenPoint,
2317         static_cast<DragOperation>(m_operationsAllowed));
2318
2319     m_page->dragController()->performDrag(&dragData);
2320
2321     m_dragOperation = WebDragOperationNone;
2322     m_currentDragData = 0;
2323
2324     m_dragScrollTimer->stop();
2325 }
2326
2327 WebDragOperation WebViewImpl::dragTargetDragEnterOrOver(const WebPoint& clientPoint, const WebPoint& screenPoint, DragAction dragAction)
2328 {
2329     ASSERT(m_currentDragData);
2330
2331     DragData dragData(
2332         m_currentDragData.get(),
2333         clientPoint,
2334         screenPoint,
2335         static_cast<DragOperation>(m_operationsAllowed));
2336
2337     DragSession dragSession;
2338     if (dragAction == DragEnter)
2339         dragSession = m_page->dragController()->dragEntered(&dragData);
2340     else
2341         dragSession = m_page->dragController()->dragUpdated(&dragData);
2342
2343     DragOperation dropEffect = dragSession.operation;
2344
2345     // Mask the drop effect operation against the drag source's allowed operations.
2346     if (!(dropEffect & dragData.draggingSourceOperationMask()))
2347         dropEffect = DragOperationNone;
2348
2349      m_dragOperation = static_cast<WebDragOperation>(dropEffect);
2350
2351     if (dragAction == DragOver)
2352         m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
2353     else
2354         m_dragScrollTimer->stop();
2355
2356     return m_dragOperation;
2357 }
2358
2359 void WebViewImpl::sendResizeEventAndRepaint()
2360 {
2361     if (mainFrameImpl()->frameView()) {
2362         // Enqueues the resize event.
2363         mainFrameImpl()->frame()->eventHandler()->sendResizeEvent();
2364     }
2365
2366     if (m_client) {
2367         if (isAcceleratedCompositingActive()) {
2368 #if USE(ACCELERATED_COMPOSITING)
2369             updateLayerTreeViewport();
2370 #endif
2371         } else {
2372             WebRect damagedRect(0, 0, m_size.width, m_size.height);
2373             m_client->didInvalidateRect(damagedRect);
2374         }
2375     }
2376 }
2377
2378 unsigned long WebViewImpl::createUniqueIdentifierForRequest()
2379 {
2380     if (m_page)
2381         return m_page->progress()->createUniqueIdentifier();
2382     return 0;
2383 }
2384
2385 void WebViewImpl::inspectElementAt(const WebPoint& point)
2386 {
2387     if (!m_page)
2388         return;
2389
2390     if (point.x == -1 || point.y == -1)
2391         m_page->inspectorController()->inspect(0);
2392     else {
2393         HitTestResult result = hitTestResultForWindowPos(point);
2394
2395         if (!result.innerNonSharedNode())
2396             return;
2397
2398         m_page->inspectorController()->inspect(result.innerNonSharedNode());
2399     }
2400 }
2401
2402 WebString WebViewImpl::inspectorSettings() const
2403 {
2404     return m_inspectorSettings;
2405 }
2406
2407 void WebViewImpl::setInspectorSettings(const WebString& settings)
2408 {
2409     m_inspectorSettings = settings;
2410 }
2411
2412 bool WebViewImpl::inspectorSetting(const WebString& key, WebString* value) const
2413 {
2414     if (!m_inspectorSettingsMap->contains(key))
2415         return false;
2416     *value = m_inspectorSettingsMap->get(key);
2417     return true;
2418 }
2419
2420 void WebViewImpl::setInspectorSetting(const WebString& key,
2421                                       const WebString& value)
2422 {
2423     m_inspectorSettingsMap->set(key, value);
2424     client()->didUpdateInspectorSetting(key, value);
2425 }
2426
2427 WebDevToolsAgent* WebViewImpl::devToolsAgent()
2428 {
2429     return m_devToolsAgent.get();
2430 }
2431
2432 WebAccessibilityObject WebViewImpl::accessibilityObject()
2433 {
2434     if (!mainFrameImpl())
2435         return WebAccessibilityObject();
2436
2437     Document* document = mainFrameImpl()->frame()->document();
2438     return WebAccessibilityObject(
2439         document->axObjectCache()->getOrCreate(document->renderer()));
2440 }
2441
2442 void WebViewImpl::applyAutofillSuggestions(
2443     const WebNode& node,
2444     const WebVector<WebString>& names,
2445     const WebVector<WebString>& labels,
2446     const WebVector<WebString>& icons,
2447     const WebVector<int>& uniqueIDs,
2448     int separatorIndex)
2449 {
2450     ASSERT(names.size() == labels.size());
2451     ASSERT(names.size() == uniqueIDs.size());
2452     ASSERT(separatorIndex < static_cast<int>(names.size()));
2453
2454     if (names.isEmpty()) {
2455         hideAutofillPopup();
2456         return;
2457     }
2458
2459     RefPtr<Node> focusedNode = focusedWebCoreNode();
2460     // If the node for which we queried the Autofill suggestions is not the
2461     // focused node, then we have nothing to do.  FIXME: also check the
2462     // caret is at the end and that the text has not changed.
2463     if (!focusedNode || focusedNode != PassRefPtr<Node>(node)) {
2464         hideAutofillPopup();
2465         return;
2466     }
2467
2468     HTMLInputElement* inputElem = focusedNode->toInputElement();
2469     ASSERT(inputElem);
2470
2471     // The first time the Autofill popup is shown we'll create the client and
2472     // the popup.
2473     if (!m_autofillPopupClient)
2474         m_autofillPopupClient = adoptPtr(new AutofillPopupMenuClient);
2475
2476     m_autofillPopupClient->initialize(
2477         inputElem, names, labels, icons, uniqueIDs, separatorIndex);
2478
2479     if (!m_autofillPopup) {
2480         m_autofillPopup = PopupContainer::create(m_autofillPopupClient.get(),
2481                                                  PopupContainer::Suggestion,
2482                                                  autofillPopupSettings);
2483     }
2484
2485     if (m_autofillPopupShowing) {
2486         refreshAutofillPopup();
2487     } else {
2488         m_autofillPopup->showInRect(focusedNode->getRect(), focusedNode->ownerDocument()->view(), 0);
2489         m_autofillPopupShowing = true;
2490     }
2491 }
2492
2493 void WebViewImpl::hidePopups()
2494 {
2495     hideSelectPopup();
2496     hideAutofillPopup();
2497 }
2498
2499 void WebViewImpl::performCustomContextMenuAction(unsigned action)
2500 {
2501     if (!m_page)
2502         return;
2503     ContextMenu* menu = m_page->contextMenuController()->contextMenu();
2504     if (!menu)
2505         return;
2506     ContextMenuItem* item = menu->itemWithAction(static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + action));
2507     if (item)
2508         m_page->contextMenuController()->contextMenuItemSelected(item);
2509     m_page->contextMenuController()->clearContextMenu();
2510 }
2511
2512 // WebView --------------------------------------------------------------------
2513
2514 void WebViewImpl::setIsTransparent(bool isTransparent)
2515 {
2516     // Set any existing frames to be transparent.
2517     Frame* frame = m_page->mainFrame();
2518     while (frame) {
2519         frame->view()->setTransparent(isTransparent);
2520         frame = frame->tree()->traverseNext();
2521     }
2522
2523     // Future frames check this to know whether to be transparent.
2524     m_isTransparent = isTransparent;
2525 }
2526
2527 bool WebViewImpl::isTransparent() const
2528 {
2529     return m_isTransparent;
2530 }
2531
2532 void WebViewImpl::setIsActive(bool active)
2533 {
2534     if (page() && page()->focusController())
2535         page()->focusController()->setActive(active);
2536 }
2537
2538 bool WebViewImpl::isActive() const
2539 {
2540     return (page() && page()->focusController()) ? page()->focusController()->isActive() : false;
2541 }
2542
2543 void WebViewImpl::setDomainRelaxationForbidden(bool forbidden, const WebString& scheme)
2544 {
2545     SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme));
2546 }
2547
2548 void WebViewImpl::setScrollbarColors(unsigned inactiveColor,
2549                                      unsigned activeColor,
2550                                      unsigned trackColor) {
2551 #if OS(UNIX) && !OS(DARWIN) && !OS(ANDROID)
2552     PlatformThemeChromiumLinux::setScrollbarColors(inactiveColor, activeColor, trackColor);
2553 #endif
2554 }
2555
2556 void WebViewImpl::setSelectionColors(unsigned activeBackgroundColor,
2557                                      unsigned activeForegroundColor,
2558                                      unsigned inactiveBackgroundColor,
2559                                      unsigned inactiveForegroundColor) {
2560 #if OS(UNIX) && !OS(DARWIN) && !OS(ANDROID)
2561     RenderThemeChromiumLinux::setSelectionColors(activeBackgroundColor,
2562                                                  activeForegroundColor,
2563                                                  inactiveBackgroundColor,
2564                                                  inactiveForegroundColor);
2565     theme()->platformColorsDidChange();
2566 #endif
2567 }
2568
2569 void WebView::addUserScript(const WebString& sourceCode,
2570                             const WebVector<WebString>& patternsIn,
2571                             WebView::UserScriptInjectAt injectAt,
2572                             WebView::UserContentInjectIn injectIn)
2573 {
2574     OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2575     for (size_t i = 0; i < patternsIn.size(); ++i)
2576         patterns->append(patternsIn[i]);
2577
2578     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2579     RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
2580     pageGroup->addUserScriptToWorld(world.get(), sourceCode, WebURL(), patterns.release(), nullptr,
2581                                     static_cast<UserScriptInjectionTime>(injectAt),
2582                                     static_cast<UserContentInjectedFrames>(injectIn));
2583 }
2584
2585 void WebView::addUserStyleSheet(const WebString& sourceCode,
2586                                 const WebVector<WebString>& patternsIn,
2587                                 WebView::UserContentInjectIn injectIn,
2588                                 WebView::UserStyleInjectionTime injectionTime)
2589 {
2590     OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2591     for (size_t i = 0; i < patternsIn.size(); ++i)
2592         patterns->append(patternsIn[i]);
2593
2594     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2595     RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
2596
2597     // FIXME: Current callers always want the level to be "author". It probably makes sense to let
2598     // callers specify this though, since in other cases the caller will probably want "user" level.
2599     //
2600     // FIXME: It would be nice to populate the URL correctly, instead of passing an empty URL.
2601     pageGroup->addUserStyleSheetToWorld(world.get(), sourceCode, WebURL(), patterns.release(), nullptr,
2602                                         static_cast<UserContentInjectedFrames>(injectIn),
2603                                         UserStyleAuthorLevel,
2604                                         static_cast<WebCore::UserStyleInjectionTime>(injectionTime));
2605 }
2606
2607 void WebView::removeAllUserContent()
2608 {
2609     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2610     pageGroup->removeAllUserContent();
2611 }
2612
2613 void WebViewImpl::didCommitLoad(bool* isNewNavigation)
2614 {
2615     if (isNewNavigation)
2616         *isNewNavigation = m_observedNewNavigation;
2617
2618 #ifndef NDEBUG
2619     ASSERT(!m_observedNewNavigation
2620         || m_page->mainFrame()->loader()->documentLoader() == m_newNavigationLoader);
2621     m_newNavigationLoader = 0;
2622 #endif
2623     m_observedNewNavigation = false;
2624 }
2625
2626 void WebViewImpl::layoutUpdated(WebFrameImpl* webframe)
2627 {
2628     if (!m_client || webframe != mainFrameImpl())
2629         return;
2630
2631     if (m_shouldAutoResize && mainFrameImpl()->frame() && mainFrameImpl()->frame()->view()) {
2632         WebSize frameSize = mainFrameImpl()->frame()->view()->frameRect().size();
2633         if (frameSize != m_size) {
2634             m_size = frameSize;
2635             m_client->didAutoResize(m_size);
2636             sendResizeEventAndRepaint();
2637         }
2638     }
2639
2640     m_client->didUpdateLayout();
2641 }
2642
2643 void WebViewImpl::didChangeContentsSize()
2644 {
2645     bool didClampScale = computePageScaleFactorLimits();
2646
2647     if (!didClampScale)
2648         return;
2649
2650     if (!mainFrameImpl())
2651         return;
2652
2653     FrameView* view = mainFrameImpl()->frameView();
2654     if (view && view->needsLayout())
2655         view->layout();
2656 }
2657
2658 bool WebViewImpl::useExternalPopupMenus()
2659 {
2660     return shouldUseExternalPopupMenus;
2661 }
2662
2663 bool WebViewImpl::navigationPolicyFromMouseEvent(unsigned short button,
2664                                                  bool ctrl, bool shift,
2665                                                  bool alt, bool meta,
2666                                                  WebNavigationPolicy* policy)
2667 {
2668 #if OS(DARWIN)
2669     const bool newTabModifier = (button == 1) || meta;
2670 #else
2671     const bool newTabModifier = (button == 1) || ctrl;
2672 #endif
2673     if (!newTabModifier && !shift && !alt)
2674       return false;
2675
2676     ASSERT(policy);
2677     if (newTabModifier) {
2678         if (shift)
2679           *policy = WebNavigationPolicyNewForegroundTab;
2680         else
2681           *policy = WebNavigationPolicyNewBackgroundTab;
2682     } else {
2683         if (shift)
2684           *policy = WebNavigationPolicyNewWindow;
2685         else
2686           *policy = WebNavigationPolicyDownload;
2687     }
2688     return true;
2689 }
2690
2691 void WebViewImpl::startDragging(const WebDragData& dragData,
2692                                 WebDragOperationsMask mask,
2693                                 const WebImage& dragImage,
2694                                 const WebPoint& dragImageOffset)
2695 {
2696     if (!m_client)
2697         return;
2698     ASSERT(!m_doingDragAndDrop);
2699     m_doingDragAndDrop = true;
2700     m_client->startDragging(dragData, mask, dragImage, dragImageOffset);
2701 }
2702
2703 void WebViewImpl::observeNewNavigation()
2704 {
2705     m_observedNewNavigation = true;
2706     // FIXME: We need to make sure that m_pageScaleFactorIsSet is not reset
2707     // on same page navigations.
2708     m_pageScaleFactorIsSet = false;
2709 #ifndef NDEBUG
2710     m_newNavigationLoader = m_page->mainFrame()->loader()->documentLoader();
2711 #endif
2712 }
2713
2714 void WebViewImpl::setIgnoreInputEvents(bool newValue)
2715 {
2716     ASSERT(m_ignoreInputEvents != newValue);
2717     m_ignoreInputEvents = newValue;
2718 }
2719
2720 void WebViewImpl::addPageOverlay(WebPageOverlay* overlay, int zOrder)
2721 {
2722     if (!m_pageOverlays)
2723         m_pageOverlays = PageOverlayList::create(this);
2724
2725     m_pageOverlays->add(overlay, zOrder);
2726     setRootLayerNeedsDisplay();
2727 }
2728
2729 void WebViewImpl::removePageOverlay(WebPageOverlay* overlay)
2730 {
2731     if (m_pageOverlays && m_pageOverlays->remove(overlay)) {
2732         setRootLayerNeedsDisplay();
2733
2734         if (m_pageOverlays->empty())
2735             m_pageOverlays = nullptr;
2736     }
2737 }
2738
2739 void WebViewImpl::setOverlayLayer(WebCore::GraphicsLayer* layer)
2740 {
2741     if (m_rootGraphicsLayer) {
2742         if (layer->parent() != m_rootGraphicsLayer)
2743             m_rootGraphicsLayer->addChild(layer);
2744     }
2745 }
2746
2747 #if ENABLE(NOTIFICATIONS)
2748 NotificationPresenterImpl* WebViewImpl::notificationPresenterImpl()
2749 {
2750     if (!m_notificationPresenter.isInitialized() && m_client)
2751         m_notificationPresenter.initialize(m_client->notificationPresenter());
2752     return &m_notificationPresenter;
2753 }
2754 #endif
2755
2756 void WebViewImpl::refreshAutofillPopup()
2757 {
2758     ASSERT(m_autofillPopupShowing);
2759
2760     // Hide the popup if it has become empty.
2761     if (!m_autofillPopupClient->listSize()) {
2762         hideAutofillPopup();
2763         return;
2764     }
2765
2766     IntRect oldBounds = m_autofillPopup->frameRect();
2767     m_autofillPopup->refresh(focusedWebCoreNode()->getRect());
2768     IntRect newBounds = m_autofillPopup->frameRect();
2769     // Let's resize the backing window if necessary.
2770     if (oldBounds != newBounds) {
2771         WebPopupMenuImpl* popupMenu =
2772             static_cast<WebPopupMenuImpl*>(m_autofillPopup->client());
2773         if (popupMenu)
2774             popupMenu->client()->setWindowRect(m_chromeClientImpl.rootViewToScreen(newBounds));
2775     }
2776 }
2777
2778 Node* WebViewImpl::focusedWebCoreNode()
2779 {
2780     Frame* frame = m_page->focusController()->focusedFrame();
2781     if (!frame)
2782         return 0;
2783
2784     Document* document = frame->document();
2785     if (!document)
2786         return 0;
2787
2788     return document->focusedNode();
2789 }
2790
2791 HitTestResult WebViewImpl::hitTestResultForWindowPos(const IntPoint& pos)
2792 {
2793     IntPoint docPoint(m_page->mainFrame()->view()->windowToContents(pos));
2794     return m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(docPoint, false);
2795 }
2796
2797 void WebViewImpl::setTabsToLinks(bool enable)
2798 {
2799     m_tabsToLinks = enable;
2800 }
2801
2802 bool WebViewImpl::tabsToLinks() const
2803 {
2804     return m_tabsToLinks;
2805 }
2806
2807 #if USE(ACCELERATED_COMPOSITING)
2808 bool WebViewImpl::allowsAcceleratedCompositing()
2809 {
2810     return !m_compositorCreationFailed;
2811 }
2812
2813 bool WebViewImpl::pageHasRTLStyle() const
2814 {
2815     if (!page())
2816         return false;
2817     Document* document = page()->mainFrame()->document();
2818     if (!document)
2819         return false;
2820     RenderView* renderView = document->renderView();
2821     if (!renderView)
2822         return false;
2823     RenderStyle* style = renderView->style();
2824     if (!style)
2825         return false;
2826     return (style->direction() == RTL);
2827 }
2828
2829 void WebViewImpl::setRootGraphicsLayer(GraphicsLayer* layer)
2830 {
2831     m_rootGraphicsLayer = layer;
2832
2833     setIsAcceleratedCompositingActive(layer);
2834     if (m_nonCompositedContentHost) {
2835         GraphicsLayer* scrollLayer = 0;
2836         if (layer) {
2837             Document* document = page()->mainFrame()->document();
2838             RenderView* renderView = document->renderView();
2839             RenderLayerCompositor* compositor = renderView->compositor();
2840             scrollLayer = compositor->scrollLayer();
2841         }
2842         m_nonCompositedContentHost->setScrollLayer(scrollLayer);
2843     }
2844     if (m_layerTreeHost)
2845         m_layerTreeHost->setRootLayer(layer ? layer->platformLayer() : 0);
2846
2847     IntRect damagedRect(0, 0, m_size.width, m_size.height);
2848     if (!m_isAcceleratedCompositingActive)
2849         m_client->didInvalidateRect(damagedRect);
2850 }
2851
2852 void WebViewImpl::setRootLayerNeedsDisplay()
2853 {
2854     if (m_layerTreeHost)
2855         m_layerTreeHost->setNeedsCommit();
2856 }
2857
2858 void WebViewImpl::scrollRootLayerRect(const IntSize& scrollDelta, const IntRect& clipRect)
2859 {
2860     updateLayerTreeViewport();
2861     setRootLayerNeedsDisplay();
2862 }
2863
2864 void WebViewImpl::invalidateRootLayerRect(const IntRect& rect)
2865 {
2866     ASSERT(m_layerTreeHost);
2867
2868     if (!page())
2869         return;
2870
2871     FrameView* view = page()->mainFrame()->view();
2872     IntRect dirtyRect = view->windowToContents(rect);
2873     updateLayerTreeViewport();
2874     m_nonCompositedContentHost->invalidateRect(dirtyRect);
2875     setRootLayerNeedsDisplay();
2876 }
2877
2878 NonCompositedContentHost* WebViewImpl::nonCompositedContentHost()
2879 {
2880     return m_nonCompositedContentHost.get();
2881 }
2882
2883 #if ENABLE(REQUEST_ANIMATION_FRAME)
2884 void WebViewImpl::scheduleAnimation()
2885 {
2886     if (isAcceleratedCompositingActive()) {
2887         if (CCProxy::hasImplThread()) {
2888             ASSERT(m_layerTreeHost);
2889             m_layerTreeHost->setNeedsAnimate();
2890         } else
2891             m_client->scheduleAnimation();
2892     } else
2893             m_client->scheduleAnimation();
2894 }
2895 #endif
2896
2897 class WebViewImplContentPainter : public LayerPainterChromium {
2898     WTF_MAKE_NONCOPYABLE(WebViewImplContentPainter);
2899 public:
2900     static PassOwnPtr<WebViewImplContentPainter*> create(WebViewImpl* webViewImpl)
2901     {
2902         return adoptPtr(new WebViewImplContentPainter(webViewImpl));
2903     }
2904
2905     virtual void paint(GraphicsContext& context, const IntRect& contentRect)
2906     {
2907         double paintStart = currentTime();
2908         Page* page = m_webViewImpl->page();
2909         if (!page)
2910             return;
2911         FrameView* view = page->mainFrame()->view();
2912         view->paintContents(&context, contentRect);
2913         double paintEnd = currentTime();
2914         double pixelsPerSec = (contentRect.width() * contentRect.height()) / (paintEnd - paintStart);
2915         PlatformSupport::histogramCustomCounts("Renderer4.AccelRootPaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30);
2916         PlatformSupport::histogramCustomCounts("Renderer4.AccelRootPaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30);
2917
2918         m_webViewImpl->nonCompositedContentHost()->setBackgroundColor(view->documentBackgroundColor());
2919
2920     }
2921
2922 private:
2923     explicit WebViewImplContentPainter(WebViewImpl* webViewImpl)
2924         : m_webViewImpl(webViewImpl)
2925     {
2926     }
2927
2928     WebViewImpl* m_webViewImpl;
2929 };
2930
2931 void WebViewImpl::setIsAcceleratedCompositingActive(bool active)
2932 {
2933     PlatformSupport::histogramEnumeration("GPU.setIsAcceleratedCompositingActive", active * 2 + m_isAcceleratedCompositingActive, 4);
2934
2935     if (m_isAcceleratedCompositingActive == active)
2936         return;
2937
2938     if (!active) {
2939         m_isAcceleratedCompositingActive = false;
2940         // We need to finish all GL rendering before sending didDeactivateCompositor() to prevent
2941         // flickering when compositing turns off.
2942         if (m_layerTreeHost)
2943             m_layerTreeHost->finishAllRendering();
2944         m_client->didDeactivateCompositor();
2945     } else if (m_layerTreeHost) {
2946         m_isAcceleratedCompositingActive = true;
2947         updateLayerTreeViewport();
2948
2949         m_client->didActivateCompositor(m_layerTreeHost->compositorIdentifier());
2950     } else {
2951         TRACE_EVENT("WebViewImpl::setIsAcceleratedCompositingActive(true)", this, 0);
2952
2953         static const double defaultRefreshRate = 60.0;
2954
2955         WebCore::CCSettings ccSettings;
2956         ccSettings.acceleratePainting = page()->settings()->acceleratedDrawingEnabled();
2957         ccSettings.compositeOffscreen = settings()->compositeToTextureEnabled();
2958         ccSettings.showFPSCounter = settings()->showFPSCounter();
2959         ccSettings.showPlatformLayerTree = settings()->showPlatformLayerTree();
2960         ccSettings.refreshRate = screenRefreshRate(page()->mainFrame()->view());
2961
2962         ASSERT(ccSettings.refreshRate >= 0);
2963         if (!ccSettings.refreshRate)
2964             ccSettings.refreshRate = defaultRefreshRate;
2965
2966         ccSettings.perTilePainting = page()->settings()->perTileDrawingEnabled();
2967         ccSettings.partialSwapEnabled = page()->settings()->partialSwapEnabled();
2968
2969         m_nonCompositedContentHost = NonCompositedContentHost::create(WebViewImplContentPainter::create(this));
2970         m_layerTreeHost = CCLayerTreeHost::create(this, ccSettings);
2971         if (m_layerTreeHost) {
2972             m_layerTreeHost->setHaveWheelEventHandlers(m_haveWheelEventHandlers);
2973             m_layerTreeHost->setPageScaleFactorLimits(m_minimumPageScaleFactor, m_maximumPageScaleFactor);
2974             updateLayerTreeViewport();
2975             m_client->didActivateCompositor(m_layerTreeHost->compositorIdentifier());
2976             m_isAcceleratedCompositingActive = true;
2977             m_compositorCreationFailed = false;
2978             if (m_pageOverlays)
2979                 m_pageOverlays->update();
2980         } else {
2981             m_layerTreeHost.clear();
2982             m_nonCompositedContentHost.clear();
2983             m_isAcceleratedCompositingActive = false;
2984             m_client->didDeactivateCompositor();
2985             m_compositorCreationFailed = true;
2986         }
2987     }
2988     if (page())
2989         page()->mainFrame()->view()->setClipsRepaints(!m_isAcceleratedCompositingActive);
2990 }
2991
2992 #endif
2993
2994 PassRefPtr<GraphicsContext3D> WebViewImpl::createLayerTreeHostContext3D()
2995 {
2996     RefPtr<GraphicsContext3D> context = m_temporaryOnscreenGraphicsContext3D.release();
2997     if (!context) {
2998         if (CCProxy::hasImplThread())
2999             context = GraphicsContext3DPrivate::createGraphicsContextForAnotherThread(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
3000         else
3001             context = GraphicsContext3D::create(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
3002     }
3003     return context;
3004 }
3005
3006 void WebViewImpl::animateAndLayout(double frameBeginTime)
3007 {
3008     animate(frameBeginTime);
3009     layout();
3010 }
3011
3012 void WebViewImpl::applyScrollAndScale(const IntSize& scrollDelta, float pageScaleDelta)
3013 {
3014     if (!mainFrameImpl() || !mainFrameImpl()->frameView())
3015         return;
3016
3017     if (pageScaleDelta == 1)
3018         mainFrameImpl()->frameView()->scrollBy(scrollDelta);
3019     else {
3020         // The page scale changed, so apply a scale and scroll in a single
3021         // operation. The old scroll offset (and passed-in delta) are
3022         // in the old coordinate space, so we first need to multiply them
3023         // by the page scale delta.
3024         WebSize scrollOffset = mainFrame()->scrollOffset();
3025         scrollOffset.width += scrollDelta.width();
3026         scrollOffset.height += scrollDelta.height();
3027         WebPoint scaledScrollOffset(scrollOffset.width * pageScaleDelta,
3028                                     scrollOffset.height * pageScaleDelta);
3029         setPageScaleFactor(pageScaleFactor() * pageScaleDelta, scaledScrollOffset);
3030     }
3031 }
3032
3033 void WebViewImpl::didCommitAndDrawFrame()
3034 {
3035     if (m_client)
3036         m_client->didCommitAndDrawCompositorFrame();
3037 }
3038
3039 void WebViewImpl::didCompleteSwapBuffers()
3040 {
3041     if (m_client)
3042         m_client->didCompleteSwapBuffers();
3043 }
3044
3045 void WebViewImpl::didRecreateGraphicsContext(bool success)
3046 {
3047
3048     // Switch back to software rendering mode, if necessary
3049     if (!success) {
3050         ASSERT(m_isAcceleratedCompositingActive);
3051         setIsAcceleratedCompositingActive(false);
3052         m_compositorCreationFailed = true;
3053         m_client->didInvalidateRect(IntRect(0, 0, m_size.width, m_size.height));
3054
3055         // Force a style recalc to remove all the composited layers.
3056         m_page->mainFrame()->document()->scheduleForcedStyleRecalc();
3057         return;
3058     }
3059
3060     if (m_pageOverlays)
3061         m_pageOverlays->update();
3062 }
3063
3064 void WebViewImpl::scheduleComposite()
3065 {
3066     ASSERT(!CCProxy::hasImplThread());
3067     m_client->scheduleComposite();
3068 }
3069
3070 void WebViewImpl::updateLayerTreeViewport()
3071 {
3072     if (!page() || !m_nonCompositedContentHost || !m_layerTreeHost)
3073         return;
3074
3075     FrameView* view = page()->mainFrame()->view();
3076     IntRect visibleRect = view->visibleContentRect(true /* include scrollbars */);
3077     IntPoint scroll(view->scrollX(), view->scrollY());
3078
3079     int layerAdjustX = 0;
3080     if (pageHasRTLStyle()) {
3081         // The origin of the initial containing block for RTL root layers is not
3082         // at the far left side of the layer bounds. Instead, it's one viewport
3083         // width (not including scrollbars) to the left of the right side of the
3084         // layer.
3085         layerAdjustX = -view->contentsSize().width() + view->visibleContentRect(false).width();
3086     }
3087     m_nonCompositedContentHost->setViewport(visibleRect.size(), view->contentsSize(), scroll, pageScaleFactor(), layerAdjustX);
3088     m_layerTreeHost->setViewport(visibleRect.size());
3089     m_layerTreeHost->setPageScale(pageScaleFactor());
3090 }
3091
3092 WebGraphicsContext3D* WebViewImpl::graphicsContext3D()
3093 {
3094 #if USE(ACCELERATED_COMPOSITING)
3095     if (m_page->settings()->acceleratedCompositingEnabled() && allowsAcceleratedCompositing()) {
3096         if (m_layerTreeHost) {
3097             WebGraphicsContext3D* webContext = GraphicsContext3DPrivate::extractWebGraphicsContext3D(m_layerTreeHost->context());
3098             if (webContext && !webContext->isContextLost())
3099                 return webContext;
3100         }
3101         if (m_temporaryOnscreenGraphicsContext3D) {
3102             WebGraphicsContext3D* webContext = GraphicsContext3DPrivate::extractWebGraphicsContext3D(m_temporaryOnscreenGraphicsContext3D.get());
3103             if (webContext && !webContext->isContextLost())
3104                 return webContext;
3105         }
3106         if (CCProxy::hasImplThread())
3107             m_temporaryOnscreenGraphicsContext3D = GraphicsContext3DPrivate::createGraphicsContextForAnotherThread(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
3108         else
3109             m_temporaryOnscreenGraphicsContext3D = GraphicsContext3D::create(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
3110
3111         return GraphicsContext3DPrivate::extractWebGraphicsContext3D(m_temporaryOnscreenGraphicsContext3D.get());
3112     }
3113 #endif
3114     return 0;
3115 }
3116
3117 void WebViewImpl::setVisibilityState(WebPageVisibilityState visibilityState,
3118                                      bool isInitialState) {
3119     if (!page())
3120         return;
3121
3122 #if ENABLE(PAGE_VISIBILITY_API)
3123     ASSERT(visibilityState == WebPageVisibilityStateVisible
3124            || visibilityState == WebPageVisibilityStateHidden
3125            || visibilityState == WebPageVisibilityStatePrerender);
3126     m_page->setVisibilityState(static_cast<PageVisibilityState>(static_cast<int>(visibilityState)), isInitialState);
3127 #endif
3128
3129 #if USE(ACCELERATED_COMPOSITING)
3130     if (isAcceleratedCompositingActive()) {
3131         bool visible = visibilityState == WebPageVisibilityStateVisible;
3132         if (!visible)
3133             m_nonCompositedContentHost->protectVisibleTileTextures();
3134         m_layerTreeHost->setVisible(visible);
3135     }
3136 #endif
3137 }
3138
3139 #if ENABLE(GESTURE_RECOGNIZER)
3140 void WebViewImpl::resetGestureRecognizer()
3141 {
3142     m_gestureRecognizer->reset();
3143 }
3144 #endif
3145
3146 } // namespace WebKit