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