b2d16e51c73edfc64a7c0c03e88a36d9e3fd0a4c
[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::scalePage(float scaleFactor, const WebPoint& origin)
1851 {
1852     setPageScaleFactor(scaleFactor, origin);
1853 }
1854
1855 void WebViewImpl::setPageScaleFactor(float scaleFactor, const WebPoint& origin)
1856 {
1857     if (!page())
1858         return;
1859
1860     page()->setPageScaleFactor(scaleFactor, origin);
1861 }
1862
1863 float WebViewImpl::deviceScaleFactor() const
1864 {
1865     if (!page())
1866         return 1;
1867
1868     return page()->deviceScaleFactor();
1869 }
1870
1871 void WebViewImpl::setDeviceScaleFactor(float scaleFactor)
1872 {
1873     if (!page())
1874         return;
1875
1876     page()->setDeviceScaleFactor(scaleFactor);
1877 }
1878
1879 bool WebViewImpl::isFixedLayoutModeEnabled() const
1880 {
1881     if (!page())
1882         return false;
1883
1884     Frame* frame = page()->mainFrame();
1885     if (!frame || !frame->view())
1886         return false;
1887
1888     return frame->view()->useFixedLayout();
1889 }
1890
1891 void WebViewImpl::enableFixedLayoutMode(bool enable)
1892 {
1893     if (!page())
1894         return;
1895
1896     Frame* frame = page()->mainFrame();
1897     if (!frame || !frame->view())
1898         return;
1899
1900     frame->view()->setUseFixedLayout(enable);
1901 }
1902
1903 WebSize WebViewImpl::fixedLayoutSize() const
1904 {
1905     if (!page())
1906         return WebSize();
1907
1908     Frame* frame = page()->mainFrame();
1909     if (!frame || !frame->view())
1910         return WebSize();
1911
1912     return frame->view()->fixedLayoutSize();
1913 }
1914
1915 void WebViewImpl::setFixedLayoutSize(const WebSize& layoutSize)
1916 {
1917     if (!page())
1918         return;
1919
1920     Frame* frame = page()->mainFrame();
1921     if (!frame || !frame->view())
1922         return;
1923
1924     frame->view()->setFixedLayoutSize(layoutSize);
1925 }
1926
1927 void WebViewImpl::performMediaPlayerAction(const WebMediaPlayerAction& action,
1928                                            const WebPoint& location)
1929 {
1930     HitTestResult result = hitTestResultForWindowPos(location);
1931     RefPtr<Node> node = result.innerNonSharedNode();
1932     if (!node->hasTagName(HTMLNames::videoTag) && !node->hasTagName(HTMLNames::audioTag))
1933       return;
1934
1935     RefPtr<HTMLMediaElement> mediaElement =
1936         static_pointer_cast<HTMLMediaElement>(node);
1937     switch (action.type) {
1938     case WebMediaPlayerAction::Play:
1939         if (action.enable)
1940             mediaElement->play();
1941         else
1942             mediaElement->pause();
1943         break;
1944     case WebMediaPlayerAction::Mute:
1945         mediaElement->setMuted(action.enable);
1946         break;
1947     case WebMediaPlayerAction::Loop:
1948         mediaElement->setLoop(action.enable);
1949         break;
1950     case WebMediaPlayerAction::Controls:
1951         mediaElement->setControls(action.enable);
1952         break;
1953     default:
1954         ASSERT_NOT_REACHED();
1955     }
1956 }
1957
1958 void WebViewImpl::copyImageAt(const WebPoint& point)
1959 {
1960     if (!m_page)
1961         return;
1962
1963     HitTestResult result = hitTestResultForWindowPos(point);
1964
1965     if (result.absoluteImageURL().isEmpty()) {
1966         // There isn't actually an image at these coordinates.  Might be because
1967         // the window scrolled while the context menu was open or because the page
1968         // changed itself between when we thought there was an image here and when
1969         // we actually tried to retreive the image.
1970         //
1971         // FIXME: implement a cache of the most recent HitTestResult to avoid having
1972         //        to do two hit tests.
1973         return;
1974     }
1975
1976     m_page->mainFrame()->editor()->copyImage(result);
1977 }
1978
1979 void WebViewImpl::dragSourceEndedAt(
1980     const WebPoint& clientPoint,
1981     const WebPoint& screenPoint,
1982     WebDragOperation operation)
1983 {
1984     PlatformMouseEvent pme(clientPoint,
1985                            screenPoint,
1986                            LeftButton, MouseEventMoved, 0, false, false, false,
1987                            false, 0);
1988     m_page->mainFrame()->eventHandler()->dragSourceEndedAt(pme,
1989         static_cast<DragOperation>(operation));
1990     m_dragScrollTimer->stop();
1991 }
1992
1993 void WebViewImpl::dragSourceMovedTo(
1994     const WebPoint& clientPoint,
1995     const WebPoint& screenPoint,
1996     WebDragOperation operation)
1997 {
1998     m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
1999 }
2000
2001 void WebViewImpl::dragSourceSystemDragEnded()
2002 {
2003     // It's possible for us to get this callback while not doing a drag if
2004     // it's from a previous page that got unloaded.
2005     if (m_doingDragAndDrop) {
2006         m_page->dragController()->dragEnded();
2007         m_doingDragAndDrop = false;
2008     }
2009 }
2010
2011 WebDragOperation WebViewImpl::dragTargetDragEnter(
2012     const WebDragData& webDragData,
2013     const WebPoint& clientPoint,
2014     const WebPoint& screenPoint,
2015     WebDragOperationsMask operationsAllowed)
2016 {
2017     ASSERT(!m_currentDragData);
2018
2019     m_currentDragData = webDragData;
2020     m_operationsAllowed = operationsAllowed;
2021
2022     return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragEnter);
2023 }
2024
2025 WebDragOperation WebViewImpl::dragTargetDragOver(
2026     const WebPoint& clientPoint,
2027     const WebPoint& screenPoint,
2028     WebDragOperationsMask operationsAllowed)
2029 {
2030     m_operationsAllowed = operationsAllowed;
2031
2032     return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragOver);
2033 }
2034
2035 void WebViewImpl::dragTargetDragLeave()
2036 {
2037     ASSERT(m_currentDragData);
2038
2039     DragData dragData(
2040         m_currentDragData.get(),
2041         IntPoint(),
2042         IntPoint(),
2043         static_cast<DragOperation>(m_operationsAllowed));
2044
2045     m_page->dragController()->dragExited(&dragData);
2046
2047     // FIXME: why is the drag scroll timer not stopped here?
2048
2049     m_dragOperation = WebDragOperationNone;
2050     m_currentDragData = 0;
2051 }
2052
2053 void WebViewImpl::dragTargetDrop(const WebPoint& clientPoint,
2054                                  const WebPoint& screenPoint)
2055 {
2056     ASSERT(m_currentDragData);
2057
2058     // If this webview transitions from the "drop accepting" state to the "not
2059     // accepting" state, then our IPC message reply indicating that may be in-
2060     // flight, or else delayed by javascript processing in this webview.  If a
2061     // drop happens before our IPC reply has reached the browser process, then
2062     // the browser forwards the drop to this webview.  So only allow a drop to
2063     // proceed if our webview m_dragOperation state is not DragOperationNone.
2064
2065     if (m_dragOperation == WebDragOperationNone) { // IPC RACE CONDITION: do not allow this drop.
2066         dragTargetDragLeave();
2067         return;
2068     }
2069
2070     DragData dragData(
2071         m_currentDragData.get(),
2072         clientPoint,
2073         screenPoint,
2074         static_cast<DragOperation>(m_operationsAllowed));
2075
2076     m_page->dragController()->performDrag(&dragData);
2077
2078     m_dragOperation = WebDragOperationNone;
2079     m_currentDragData = 0;
2080
2081     m_dragScrollTimer->stop();
2082 }
2083
2084 WebDragOperation WebViewImpl::dragTargetDragEnterOrOver(const WebPoint& clientPoint, const WebPoint& screenPoint, DragAction dragAction)
2085 {
2086     ASSERT(m_currentDragData);
2087
2088     DragData dragData(
2089         m_currentDragData.get(),
2090         clientPoint,
2091         screenPoint,
2092         static_cast<DragOperation>(m_operationsAllowed));
2093
2094     DragSession dragSession;
2095     if (dragAction == DragEnter)
2096         dragSession = m_page->dragController()->dragEntered(&dragData);
2097     else
2098         dragSession = m_page->dragController()->dragUpdated(&dragData);
2099
2100     DragOperation dropEffect = dragSession.operation;
2101
2102     // Mask the drop effect operation against the drag source's allowed operations.
2103     if (!(dropEffect & dragData.draggingSourceOperationMask()))
2104         dropEffect = DragOperationNone;
2105
2106      m_dragOperation = static_cast<WebDragOperation>(dropEffect);
2107
2108     if (dragAction == DragOver)
2109         m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
2110     else
2111         m_dragScrollTimer->stop();
2112
2113     return m_dragOperation;
2114 }
2115
2116 unsigned long WebViewImpl::createUniqueIdentifierForRequest()
2117 {
2118     if (m_page)
2119         return m_page->progress()->createUniqueIdentifier();
2120     return 0;
2121 }
2122
2123 void WebViewImpl::inspectElementAt(const WebPoint& point)
2124 {
2125     if (!m_page)
2126         return;
2127
2128     if (point.x == -1 || point.y == -1)
2129         m_page->inspectorController()->inspect(0);
2130     else {
2131         HitTestResult result = hitTestResultForWindowPos(point);
2132
2133         if (!result.innerNonSharedNode())
2134             return;
2135
2136         m_page->inspectorController()->inspect(result.innerNonSharedNode());
2137     }
2138 }
2139
2140 WebString WebViewImpl::inspectorSettings() const
2141 {
2142     return m_inspectorSettings;
2143 }
2144
2145 void WebViewImpl::setInspectorSettings(const WebString& settings)
2146 {
2147     m_inspectorSettings = settings;
2148 }
2149
2150 bool WebViewImpl::inspectorSetting(const WebString& key, WebString* value) const
2151 {
2152     if (!m_inspectorSettingsMap->contains(key))
2153         return false;
2154     *value = m_inspectorSettingsMap->get(key);
2155     return true;
2156 }
2157
2158 void WebViewImpl::setInspectorSetting(const WebString& key,
2159                                       const WebString& value)
2160 {
2161     m_inspectorSettingsMap->set(key, value);
2162     client()->didUpdateInspectorSetting(key, value);
2163 }
2164
2165 WebDevToolsAgent* WebViewImpl::devToolsAgent()
2166 {
2167     return m_devToolsAgent.get();
2168 }
2169
2170 WebAccessibilityObject WebViewImpl::accessibilityObject()
2171 {
2172     if (!mainFrameImpl())
2173         return WebAccessibilityObject();
2174
2175     Document* document = mainFrameImpl()->frame()->document();
2176     return WebAccessibilityObject(
2177         document->axObjectCache()->getOrCreate(document->renderer()));
2178 }
2179
2180 void WebViewImpl::applyAutofillSuggestions(
2181     const WebNode& node,
2182     const WebVector<WebString>& names,
2183     const WebVector<WebString>& labels,
2184     const WebVector<WebString>& icons,
2185     const WebVector<int>& uniqueIDs,
2186     int separatorIndex)
2187 {
2188     ASSERT(names.size() == labels.size());
2189     ASSERT(names.size() == uniqueIDs.size());
2190     ASSERT(separatorIndex < static_cast<int>(names.size()));
2191
2192     if (names.isEmpty()) {
2193         hideAutofillPopup();
2194         return;
2195     }
2196
2197     RefPtr<Node> focusedNode = focusedWebCoreNode();
2198     // If the node for which we queried the Autofill suggestions is not the
2199     // focused node, then we have nothing to do.  FIXME: also check the
2200     // caret is at the end and that the text has not changed.
2201     if (!focusedNode || focusedNode != PassRefPtr<Node>(node)) {
2202         hideAutofillPopup();
2203         return;
2204     }
2205
2206     HTMLInputElement* inputElem = focusedNode->toInputElement();
2207     ASSERT(inputElem);
2208
2209     // The first time the Autofill popup is shown we'll create the client and
2210     // the popup.
2211     if (!m_autofillPopupClient)
2212         m_autofillPopupClient = adoptPtr(new AutofillPopupMenuClient);
2213
2214     m_autofillPopupClient->initialize(
2215         inputElem, names, labels, icons, uniqueIDs, separatorIndex);
2216
2217     if (!m_autofillPopup) {
2218         m_autofillPopup = PopupContainer::create(m_autofillPopupClient.get(),
2219                                                  PopupContainer::Suggestion,
2220                                                  autofillPopupSettings);
2221     }
2222
2223     if (m_autofillPopupShowing) {
2224         refreshAutofillPopup();
2225     } else {
2226         m_autofillPopup->showInRect(focusedNode->getRect(), focusedNode->ownerDocument()->view(), 0);
2227         m_autofillPopupShowing = true;
2228     }
2229 }
2230
2231 void WebViewImpl::hidePopups()
2232 {
2233     hideSelectPopup();
2234     hideAutofillPopup();
2235 }
2236
2237 void WebViewImpl::performCustomContextMenuAction(unsigned action)
2238 {
2239     if (!m_page)
2240         return;
2241     ContextMenu* menu = m_page->contextMenuController()->contextMenu();
2242     if (!menu)
2243         return;
2244     ContextMenuItem* item = menu->itemWithAction(static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + action));
2245     if (item)
2246         m_page->contextMenuController()->contextMenuItemSelected(item);
2247     m_page->contextMenuController()->clearContextMenu();
2248 }
2249
2250 // WebView --------------------------------------------------------------------
2251
2252 void WebViewImpl::setIsTransparent(bool isTransparent)
2253 {
2254     // Set any existing frames to be transparent.
2255     Frame* frame = m_page->mainFrame();
2256     while (frame) {
2257         frame->view()->setTransparent(isTransparent);
2258         frame = frame->tree()->traverseNext();
2259     }
2260
2261     // Future frames check this to know whether to be transparent.
2262     m_isTransparent = isTransparent;
2263 }
2264
2265 bool WebViewImpl::isTransparent() const
2266 {
2267     return m_isTransparent;
2268 }
2269
2270 void WebViewImpl::setIsActive(bool active)
2271 {
2272     if (page() && page()->focusController())
2273         page()->focusController()->setActive(active);
2274 }
2275
2276 bool WebViewImpl::isActive() const
2277 {
2278     return (page() && page()->focusController()) ? page()->focusController()->isActive() : false;
2279 }
2280
2281 void WebViewImpl::setDomainRelaxationForbidden(bool forbidden, const WebString& scheme)
2282 {
2283     SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme));
2284 }
2285
2286 void WebViewImpl::setScrollbarColors(unsigned inactiveColor,
2287                                      unsigned activeColor,
2288                                      unsigned trackColor) {
2289 #if OS(UNIX) && !OS(DARWIN)
2290     PlatformThemeChromiumLinux::setScrollbarColors(inactiveColor, activeColor, trackColor);
2291 #endif
2292 }
2293
2294 void WebViewImpl::setSelectionColors(unsigned activeBackgroundColor,
2295                                      unsigned activeForegroundColor,
2296                                      unsigned inactiveBackgroundColor,
2297                                      unsigned inactiveForegroundColor) {
2298 #if OS(UNIX) && !OS(DARWIN)
2299     RenderThemeChromiumLinux::setSelectionColors(activeBackgroundColor,
2300                                                  activeForegroundColor,
2301                                                  inactiveBackgroundColor,
2302                                                  inactiveForegroundColor);
2303     theme()->platformColorsDidChange();
2304 #endif
2305 }
2306
2307 void WebView::addUserScript(const WebString& sourceCode,
2308                             const WebVector<WebString>& patternsIn,
2309                             WebView::UserScriptInjectAt injectAt,
2310                             WebView::UserContentInjectIn injectIn)
2311 {
2312     OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2313     for (size_t i = 0; i < patternsIn.size(); ++i)
2314         patterns->append(patternsIn[i]);
2315
2316     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2317     RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
2318     pageGroup->addUserScriptToWorld(world.get(), sourceCode, WebURL(), patterns.release(), nullptr,
2319                                     static_cast<UserScriptInjectionTime>(injectAt),
2320                                     static_cast<UserContentInjectedFrames>(injectIn));
2321 }
2322
2323 void WebView::addUserStyleSheet(const WebString& sourceCode,
2324                                 const WebVector<WebString>& patternsIn,
2325                                 WebView::UserContentInjectIn injectIn,
2326                                 WebView::UserStyleInjectionTime injectionTime)
2327 {
2328     OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2329     for (size_t i = 0; i < patternsIn.size(); ++i)
2330         patterns->append(patternsIn[i]);
2331
2332     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2333     RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
2334
2335     // FIXME: Current callers always want the level to be "author". It probably makes sense to let
2336     // callers specify this though, since in other cases the caller will probably want "user" level.
2337     //
2338     // FIXME: It would be nice to populate the URL correctly, instead of passing an empty URL.
2339     pageGroup->addUserStyleSheetToWorld(world.get(), sourceCode, WebURL(), patterns.release(), nullptr,
2340                                         static_cast<UserContentInjectedFrames>(injectIn),
2341                                         UserStyleAuthorLevel,
2342                                         static_cast<WebCore::UserStyleInjectionTime>(injectionTime));
2343 }
2344
2345 void WebView::removeAllUserContent()
2346 {
2347     PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2348     pageGroup->removeAllUserContent();
2349 }
2350
2351 void WebViewImpl::didCommitLoad(bool* isNewNavigation)
2352 {
2353     if (isNewNavigation)
2354         *isNewNavigation = m_observedNewNavigation;
2355
2356 #ifndef NDEBUG
2357     ASSERT(!m_observedNewNavigation
2358         || m_page->mainFrame()->loader()->documentLoader() == m_newNavigationLoader);
2359     m_newNavigationLoader = 0;
2360 #endif
2361     m_observedNewNavigation = false;
2362 }
2363
2364 bool WebViewImpl::useExternalPopupMenus()
2365 {
2366     return shouldUseExternalPopupMenus;
2367 }
2368
2369 bool WebViewImpl::navigationPolicyFromMouseEvent(unsigned short button,
2370                                                  bool ctrl, bool shift,
2371                                                  bool alt, bool meta,
2372                                                  WebNavigationPolicy* policy)
2373 {
2374 #if OS(DARWIN)
2375     const bool newTabModifier = (button == 1) || meta;
2376 #else
2377     const bool newTabModifier = (button == 1) || ctrl;
2378 #endif
2379     if (!newTabModifier && !shift && !alt)
2380       return false;
2381
2382     ASSERT(policy);
2383     if (newTabModifier) {
2384         if (shift)
2385           *policy = WebNavigationPolicyNewForegroundTab;
2386         else
2387           *policy = WebNavigationPolicyNewBackgroundTab;
2388     } else {
2389         if (shift)
2390           *policy = WebNavigationPolicyNewWindow;
2391         else
2392           *policy = WebNavigationPolicyDownload;
2393     }
2394     return true;
2395 }
2396
2397 void WebViewImpl::startDragging(const WebDragData& dragData,
2398                                 WebDragOperationsMask mask,
2399                                 const WebImage& dragImage,
2400                                 const WebPoint& dragImageOffset)
2401 {
2402     if (!m_client)
2403         return;
2404     ASSERT(!m_doingDragAndDrop);
2405     m_doingDragAndDrop = true;
2406     m_client->startDragging(dragData, mask, dragImage, dragImageOffset);
2407 }
2408
2409 void WebViewImpl::observeNewNavigation()
2410 {
2411     m_observedNewNavigation = true;
2412 #ifndef NDEBUG
2413     m_newNavigationLoader = m_page->mainFrame()->loader()->documentLoader();
2414 #endif
2415 }
2416
2417 void WebViewImpl::setIgnoreInputEvents(bool newValue)
2418 {
2419     ASSERT(m_ignoreInputEvents != newValue);
2420     m_ignoreInputEvents = newValue;
2421 }
2422
2423 void WebViewImpl::setPageOverlayClient(PageOverlay::PageOverlayClient* pageOverlayClient)
2424 {
2425     if (pageOverlayClient) {
2426         if (!m_pageOverlay)
2427             m_pageOverlay = PageOverlay::create(this, pageOverlayClient);
2428         else
2429             m_pageOverlay->setClient(pageOverlayClient);
2430         m_pageOverlay->update();
2431         setRootLayerNeedsDisplay();
2432     } else {
2433         if (m_pageOverlay) {
2434             m_pageOverlay->clear();
2435             m_pageOverlay = nullptr;
2436             setRootLayerNeedsDisplay();
2437         }
2438     }
2439 }
2440
2441 void WebViewImpl::setOverlayLayer(WebCore::GraphicsLayer* layer)
2442 {
2443     if (m_rootGraphicsLayer) {
2444         if (layer->parent() != m_rootGraphicsLayer)
2445             m_rootGraphicsLayer->addChild(layer);
2446     }
2447 }
2448
2449 #if ENABLE(NOTIFICATIONS)
2450 NotificationPresenterImpl* WebViewImpl::notificationPresenterImpl()
2451 {
2452     if (!m_notificationPresenter.isInitialized() && m_client)
2453         m_notificationPresenter.initialize(m_client->notificationPresenter());
2454     return &m_notificationPresenter;
2455 }
2456 #endif
2457
2458 void WebViewImpl::refreshAutofillPopup()
2459 {
2460     ASSERT(m_autofillPopupShowing);
2461
2462     // Hide the popup if it has become empty.
2463     if (!m_autofillPopupClient->listSize()) {
2464         hideAutofillPopup();
2465         return;
2466     }
2467
2468     IntRect oldBounds = m_autofillPopup->frameRect();
2469     m_autofillPopup->refresh(focusedWebCoreNode()->getRect());
2470     IntRect newBounds = m_autofillPopup->frameRect();
2471     // Let's resize the backing window if necessary.
2472     if (oldBounds != newBounds) {
2473         WebPopupMenuImpl* popupMenu =
2474             static_cast<WebPopupMenuImpl*>(m_autofillPopup->client());
2475         if (popupMenu)
2476             popupMenu->client()->setWindowRect(m_chromeClientImpl.windowToScreen(newBounds));
2477     }
2478 }
2479
2480 Node* WebViewImpl::focusedWebCoreNode()
2481 {
2482     Frame* frame = m_page->focusController()->focusedFrame();
2483     if (!frame)
2484         return 0;
2485
2486     Document* document = frame->document();
2487     if (!document)
2488         return 0;
2489
2490     return document->focusedNode();
2491 }
2492
2493 HitTestResult WebViewImpl::hitTestResultForWindowPos(const IntPoint& pos)
2494 {
2495     IntPoint docPoint(m_page->mainFrame()->view()->windowToContents(pos));
2496     return m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(docPoint, false);
2497 }
2498
2499 void WebViewImpl::setTabsToLinks(bool enable)
2500 {
2501     m_tabsToLinks = enable;
2502 }
2503
2504 bool WebViewImpl::tabsToLinks() const
2505 {
2506     return m_tabsToLinks;
2507 }
2508
2509 #if USE(ACCELERATED_COMPOSITING)
2510 bool WebViewImpl::allowsAcceleratedCompositing()
2511 {
2512     return !m_compositorCreationFailed;
2513 }
2514
2515 bool WebViewImpl::pageHasRTLStyle() const
2516 {
2517     if (!page())
2518         return false;
2519     Document* document = page()->mainFrame()->document();
2520     if (!document)
2521         return false;
2522     RenderView* renderView = document->renderView();
2523     if (!renderView)
2524         return false;
2525     RenderStyle* style = renderView->style();
2526     if (!style)
2527         return false;
2528     return (style->direction() == RTL);
2529 }
2530
2531 void WebViewImpl::setRootGraphicsLayer(GraphicsLayer* layer)
2532 {
2533     m_rootGraphicsLayer = layer;
2534
2535     setIsAcceleratedCompositingActive(layer);
2536     if (m_nonCompositedContentHost) {
2537         GraphicsLayer* scrollLayer = 0;
2538         if (layer) {
2539             Document* document = page()->mainFrame()->document();
2540             RenderView* renderView = document->renderView();
2541             RenderLayerCompositor* compositor = renderView->compositor();
2542             scrollLayer = compositor->scrollLayer();
2543         }
2544         m_nonCompositedContentHost->setScrollLayer(scrollLayer);
2545     }
2546     if (m_layerTreeHost)
2547         m_layerTreeHost->setRootLayer(layer ? layer->platformLayer() : 0);
2548
2549     IntRect damagedRect(0, 0, m_size.width, m_size.height);
2550     if (!m_isAcceleratedCompositingActive)
2551         m_client->didInvalidateRect(damagedRect);
2552 }
2553
2554 void WebViewImpl::setRootLayerNeedsDisplay()
2555 {
2556     if (m_layerTreeHost) {
2557         TransformationMatrix zoomMatrix;
2558         FloatPoint trans = m_page->mainFrame()->view()->scrollAnimator()->zoomTranslation();
2559         zoomMatrix.translate(trans.x(), trans.y());
2560         zoomMatrix.scale(m_page->mainFrame()->view()->scrollAnimator()->zoomScale());
2561         m_layerTreeHost->setZoomAnimatorTransform(zoomMatrix);
2562     }
2563     if (m_layerTreeHost)
2564         m_layerTreeHost->setNeedsCommit();
2565 }
2566
2567 void WebViewImpl::scrollRootLayerRect(const IntSize& scrollDelta, const IntRect& clipRect)
2568 {
2569     updateLayerTreeViewport();
2570     setRootLayerNeedsDisplay();
2571 }
2572
2573 void WebViewImpl::invalidateRootLayerRect(const IntRect& rect)
2574 {
2575     ASSERT(m_layerTreeHost);
2576
2577     if (!page())
2578         return;
2579
2580     FrameView* view = page()->mainFrame()->view();
2581     IntRect dirtyRect = view->windowToContents(rect);
2582     updateLayerTreeViewport();
2583     m_nonCompositedContentHost->invalidateRect(dirtyRect);
2584     setRootLayerNeedsDisplay();
2585 }
2586
2587 WebCore::NonCompositedContentHost* WebViewImpl::nonCompositedContentHost()
2588 {
2589     return m_nonCompositedContentHost.get();
2590 }
2591
2592 #if ENABLE(REQUEST_ANIMATION_FRAME)
2593 void WebViewImpl::scheduleAnimation()
2594 {
2595     if (isAcceleratedCompositingActive()) {
2596         if (settings()->useThreadedCompositor()) {
2597             ASSERT(m_layerTreeHost);
2598             m_layerTreeHost->setNeedsAnimate();
2599         } else
2600             m_client->scheduleAnimation();
2601     } else
2602             m_client->scheduleAnimation();
2603 }
2604 #endif
2605
2606 class WebViewImplContentPainter : public LayerPainterChromium {
2607     WTF_MAKE_NONCOPYABLE(WebViewImplContentPainter);
2608 public:
2609     static PassOwnPtr<WebViewImplContentPainter*> create(WebViewImpl* webViewImpl)
2610     {
2611         return adoptPtr(new WebViewImplContentPainter(webViewImpl));
2612     }
2613
2614     virtual void paint(GraphicsContext& context, const IntRect& contentRect)
2615     {
2616         double paintStart = currentTime();
2617         Page* page = m_webViewImpl->page();
2618         if (!page)
2619             return;
2620         FrameView* view = page->mainFrame()->view();
2621         view->paintContents(&context, contentRect);
2622         double paintEnd = currentTime();
2623         double pixelsPerSec = (contentRect.width() * contentRect.height()) / (paintEnd - paintStart);
2624         PlatformSupport::histogramCustomCounts("Renderer4.AccelRootPaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30);
2625         PlatformSupport::histogramCustomCounts("Renderer4.AccelRootPaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30);
2626
2627         m_webViewImpl->nonCompositedContentHost()->setBackgroundColor(view->documentBackgroundColor());
2628
2629     }
2630
2631 private:
2632     explicit WebViewImplContentPainter(WebViewImpl* webViewImpl)
2633         : m_webViewImpl(webViewImpl)
2634     {
2635     }
2636
2637     WebViewImpl* m_webViewImpl;
2638 };
2639
2640 void WebViewImpl::setIsAcceleratedCompositingActive(bool active)
2641 {
2642     PlatformSupport::histogramEnumeration("GPU.setIsAcceleratedCompositingActive", active * 2 + m_isAcceleratedCompositingActive, 4);
2643
2644     if (m_isAcceleratedCompositingActive == active)
2645         return;
2646
2647     if (!active) {
2648         m_isAcceleratedCompositingActive = false;
2649         // We need to finish all GL rendering before sending didDeactivateCompositor() to prevent
2650         // flickering when compositing turns off.
2651         if (m_layerTreeHost)
2652             m_layerTreeHost->finishAllRendering();
2653         m_client->didDeactivateCompositor();
2654     } else if (m_layerTreeHost) {
2655         m_isAcceleratedCompositingActive = true;
2656         updateLayerTreeViewport();
2657
2658         m_client->didActivateCompositor(m_layerTreeHost->compositorIdentifier());
2659     } else {
2660         TRACE_EVENT("WebViewImpl::setIsAcceleratedCompositingActive(true)", this, 0);
2661
2662         WebCore::CCSettings ccSettings;
2663         ccSettings.acceleratePainting = page()->settings()->acceleratedDrawingEnabled();
2664         ccSettings.compositeOffscreen = settings()->compositeToTextureEnabled();
2665         ccSettings.enableCompositorThread = settings()->useThreadedCompositor();
2666         ccSettings.showFPSCounter = settings()->showFPSCounter();
2667         ccSettings.showPlatformLayerTree = settings()->showPlatformLayerTree();
2668
2669         m_nonCompositedContentHost = NonCompositedContentHost::create(WebViewImplContentPainter::create(this));
2670         m_layerTreeHost = CCLayerTreeHost::create(this, ccSettings);
2671         if (m_layerTreeHost) {
2672             m_layerTreeHost->setHaveWheelEventHandlers(m_haveWheelEventHandlers);
2673             updateLayerTreeViewport();
2674             m_client->didActivateCompositor(m_layerTreeHost->compositorIdentifier());
2675             m_isAcceleratedCompositingActive = true;
2676             m_compositorCreationFailed = false;
2677             if (m_pageOverlay)
2678                 m_pageOverlay->update();
2679         } else {
2680             m_isAcceleratedCompositingActive = false;
2681             m_client->didDeactivateCompositor();
2682             m_compositorCreationFailed = true;
2683         }
2684     }
2685     if (page())
2686         page()->mainFrame()->view()->setClipsRepaints(!m_isAcceleratedCompositingActive);
2687 }
2688
2689 #endif
2690
2691 PassRefPtr<GraphicsContext3D> WebViewImpl::createLayerTreeHostContext3D()
2692 {
2693     RefPtr<GraphicsContext3D> context = m_temporaryOnscreenGraphicsContext3D.release();
2694     if (!context) {
2695         if (settings()->useThreadedCompositor())
2696             context = GraphicsContext3DPrivate::createGraphicsContextForAnotherThread(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2697         else
2698             context = GraphicsContext3D::create(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2699     }
2700     return context;
2701 }
2702
2703 void WebViewImpl::animateAndLayout(double frameBeginTime)
2704 {
2705     animate(frameBeginTime);
2706     layout();
2707 }
2708
2709 void WebViewImpl::applyScrollDelta(const IntSize& scrollDelta)
2710 {
2711     if (!mainFrameImpl() || !mainFrameImpl()->frameView())
2712         return;
2713
2714     mainFrameImpl()->frameView()->scrollBy(scrollDelta);
2715 }
2716
2717 void WebViewImpl::didCommitAndDrawFrame(int frameNumber)
2718 {
2719     // FIXME: route this up to RenderWidget's didFlushPaint.
2720 }
2721
2722 void WebViewImpl::didRecreateGraphicsContext(bool success)
2723 {
2724
2725     // Switch back to software rendering mode, if necessary
2726     if (!success) {
2727         ASSERT(m_isAcceleratedCompositingActive);
2728         setIsAcceleratedCompositingActive(false);
2729         m_compositorCreationFailed = true;
2730         m_client->didInvalidateRect(IntRect(0, 0, m_size.width, m_size.height));
2731
2732         // Force a style recalc to remove all the composited layers.
2733         m_page->mainFrame()->document()->scheduleForcedStyleRecalc();
2734         return;
2735     }
2736
2737     if (m_pageOverlay)
2738         m_pageOverlay->update();
2739 }
2740
2741 void WebViewImpl::scheduleComposite()
2742 {
2743     ASSERT(!settings()->useThreadedCompositor());
2744     m_client->scheduleComposite();
2745 }
2746
2747 void WebViewImpl::updateLayerTreeViewport()
2748 {
2749     if (!page())
2750         return;
2751
2752     FrameView* view = page()->mainFrame()->view();
2753     IntRect visibleRect = view->visibleContentRect(true /* include scrollbars */);
2754     IntPoint scroll(view->scrollX(), view->scrollY());
2755
2756     m_nonCompositedContentHost->setViewport(visibleRect.size(), view->contentsSize(), scroll);
2757     m_layerTreeHost->setViewport(visibleRect.size());
2758 }
2759
2760 WebGraphicsContext3D* WebViewImpl::graphicsContext3D()
2761 {
2762 #if USE(ACCELERATED_COMPOSITING)
2763     if (m_page->settings()->acceleratedCompositingEnabled() && allowsAcceleratedCompositing()) {
2764         if (m_layerTreeHost) {
2765             WebGraphicsContext3D* webContext = GraphicsContext3DPrivate::extractWebGraphicsContext3D(m_layerTreeHost->context());
2766             if (webContext && !webContext->isContextLost())
2767                 return webContext;
2768         }
2769         if (m_temporaryOnscreenGraphicsContext3D) {
2770             WebGraphicsContext3D* webContext = GraphicsContext3DPrivate::extractWebGraphicsContext3D(m_temporaryOnscreenGraphicsContext3D.get());
2771             if (webContext && !webContext->isContextLost())
2772                 return webContext;
2773         }
2774         if (settings()->useThreadedCompositor())
2775             m_temporaryOnscreenGraphicsContext3D = GraphicsContext3DPrivate::createGraphicsContextForAnotherThread(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2776         else
2777             m_temporaryOnscreenGraphicsContext3D = GraphicsContext3D::create(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2778
2779         return GraphicsContext3DPrivate::extractWebGraphicsContext3D(m_temporaryOnscreenGraphicsContext3D.get());
2780     }
2781 #endif
2782     return 0;
2783 }
2784
2785
2786 void WebViewImpl::setVisibilityState(WebPageVisibilityState visibilityState,
2787                                      bool isInitialState) {
2788     if (!page())
2789         return;
2790
2791 #if ENABLE(PAGE_VISIBILITY_API)
2792     ASSERT(visibilityState == WebPageVisibilityStateVisible
2793            || visibilityState == WebPageVisibilityStateHidden
2794            || visibilityState == WebPageVisibilityStatePrerender);
2795     m_page->setVisibilityState(static_cast<PageVisibilityState>(static_cast<int>(visibilityState)), isInitialState);
2796 #endif
2797
2798 #if USE(ACCELERATED_COMPOSITING)
2799     if (isAcceleratedCompositingActive()) {
2800         bool visible = visibilityState == WebPageVisibilityStateVisible;
2801         if (!visible)
2802             m_nonCompositedContentHost->protectVisibleTileTextures();
2803         m_layerTreeHost->setVisible(visible);
2804     }
2805 #endif
2806 }
2807
2808 #if ENABLE(GESTURE_RECOGNIZER)
2809 void WebViewImpl::resetGestureRecognizer()
2810 {
2811     m_gestureRecognizer->reset();
2812 }
2813 #endif
2814
2815 void WebViewImpl::exitFullscreen()
2816 {
2817 #if ENABLE(FULLSCREEN_API)
2818     Document* document = page()->mainFrame()->document();
2819     Element* fullscreenElement = document->webkitCurrentFullScreenElement();
2820     if (!fullscreenElement)
2821         return;
2822     document->webkitWillExitFullScreenForElement(fullscreenElement);
2823     document->webkitDidExitFullScreenForElement(fullscreenElement);
2824 #endif
2825 }
2826
2827 } // namespace WebKit