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