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