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