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