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