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