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