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