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