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