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