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