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