2 * Copyright (C) 2010 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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
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.
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.
32 #include "WebViewImpl.h"
34 #include "AutofillPopupMenuClient.h"
35 #include "AXObjectCache.h"
36 #include "BackForwardListChromium.h"
37 #include "CCThreadImpl.h"
38 #include "CSSStyleSelector.h"
39 #include "CSSValueKeywords.h"
41 #include "ColorSpace.h"
42 #include "CompositionUnderlineVectorBuilder.h"
43 #include "ContextMenu.h"
44 #include "ContextMenuController.h"
45 #include "ContextMenuItem.h"
47 #include "DOMUtilitiesPrivate.h"
48 #include "DeviceOrientationClientProxy.h"
50 #include "DocumentLoader.h"
51 #include "DragController.h"
53 #include "DragScrollTimer.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"
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"
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"
98 #include "SpeechInputClientImpl.h"
99 #include "TextIterator.h"
101 #include "TraceEvent.h"
102 #include "TypingCommand.h"
103 #include "UserGestureIndicator.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"
117 #include "WebKitPlatformSupport.h"
118 #include "WebMediaPlayerAction.h"
120 #include "WebPlugin.h"
121 #include "WebPluginContainerImpl.h"
122 #include "WebPoint.h"
123 #include "WebPopupMenuImpl.h"
124 #include "WebRange.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>
137 #if ENABLE(GESTURE_EVENTS)
138 #include "PlatformGestureEvent.h"
141 #if ENABLE(GESTURE_RECOGNIZER)
142 #include "PlatformGestureRecognizer.h"
146 #include <CoreGraphics/CGBitmapContext.h>
147 #include <CoreGraphics/CGContext.h>
151 #include "RenderThemeChromiumWin.h"
153 #if OS(UNIX) && !OS(DARWIN)
154 #include "RenderThemeChromiumLinux.h"
156 #include "RenderTheme.h"
159 // Get rid of WTF's pow define so we can use std::pow.
161 #include <cmath> // for std::pow
163 using namespace WebCore;
168 GraphicsContext3D::Attributes getCompositorContextAttributes()
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;
186 } // anonymous namespace
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;
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
203 const char* pageGroupName = "default";
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;
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);
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.)
230 static bool shouldUseExternalPopupMenus = false;
232 // WebView ----------------------------------------------------------------
234 WebView* WebView::create(WebViewClient* client)
236 // Keep runtime flag for device motion turned off until it's implemented.
237 WebRuntimeFeatures::enableDeviceMotion(false);
239 // Pass the WebViewImpl's self-reference to the caller.
240 return adoptRef(new WebViewImpl(client)).leakRef();
243 void WebView::setUseExternalPopupMenus(bool useExternalPopupMenus)
245 shouldUseExternalPopupMenus = useExternalPopupMenus;
248 void WebView::updateVisitedLinkState(unsigned long long linkHash)
250 Page::visitedStateChanged(PageGroup::pageGroup(pageGroupName), linkHash);
253 void WebView::resetVisitedLinkState()
255 Page::allVisitedStateChanged(PageGroup::pageGroup(pageGroupName));
258 void WebView::willEnterModalLoop()
260 PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
263 if (pageGroup->pages().isEmpty())
264 pageGroupLoadDeferrerStack.append(static_cast<PageGroupLoadDeferrer*>(0));
266 // Pick any page in the page group since we are deferring all pages.
267 pageGroupLoadDeferrerStack.append(new PageGroupLoadDeferrer(*pageGroup->pages().begin(), true));
271 void WebView::didExitModalLoop()
273 ASSERT(pageGroupLoadDeferrerStack.size());
275 delete pageGroupLoadDeferrerStack.last();
276 pageGroupLoadDeferrerStack.removeLast();
279 void WebViewImpl::initializeMainFrame(WebFrameClient* frameClient)
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);
285 frame->initializeAsMainFrame(this);
287 // Restrict the access to the local file system
288 // (see WebView.mm WebView::_commonInitializationWithFrameName).
289 SecurityOrigin::setLocalLoadPolicy(SecurityOrigin::AllowLocalLoadsForLocalOnly);
292 void WebViewImpl::setAutofillClient(WebAutofillClient* autofillClient)
294 m_autofillClient = autofillClient;
297 void WebViewImpl::setDevToolsAgentClient(WebDevToolsAgentClient* devToolsClient)
300 m_devToolsAgent = adoptPtr(new WebDevToolsAgentImpl(this, devToolsClient));
302 m_devToolsAgent.clear();
305 void WebViewImpl::setPermissionClient(WebPermissionClient* permissionClient)
307 m_permissionClient = permissionClient;
310 void WebViewImpl::setSpellCheckClient(WebSpellCheckClient* spellCheckClient)
312 m_spellCheckClient = spellCheckClient;
315 WebViewImpl::WebViewImpl(WebViewClient* 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)
327 , m_newNavigationLoader(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)
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)
351 #if ENABLE(INPUT_SPEECH)
352 , m_speechInputClient(SpeechInputClientImpl::create(client))
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())
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();
366 // set to impossible point so we always get the first mouse pos
367 m_lastMousePosition = WebPoint(-1, -1);
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();
378 pageClients.deviceOrientationClient = m_deviceOrientationClientProxy.get();
379 pageClients.geolocationClient = m_geolocationClientProxy.get();
380 pageClients.backForwardClient = BackForwardListChromium::create(this);
382 m_page = adoptPtr(new Page(pageClients));
384 m_geolocationClientProxy->setController(m_page->geolocationController());
386 m_page->setGroupName(pageGroupName);
388 #if ENABLE(PAGE_VISIBILITY_API)
390 setVisibilityState(m_client->visibilityState(), true);
393 m_inspectorSettingsMap = adoptPtr(new SettingsMap);
396 WebViewImpl::~WebViewImpl()
401 RenderTheme* WebViewImpl::theme() const
403 return m_page.get() ? m_page->theme() : RenderTheme::defaultTheme().get();
406 WebFrameImpl* WebViewImpl::mainFrameImpl()
408 return m_page.get() ? WebFrameImpl::fromFrame(m_page->mainFrame()) : 0;
411 bool WebViewImpl::tabKeyCyclesThroughElements() const
413 ASSERT(m_page.get());
414 return m_page->tabKeyCyclesThroughElements();
417 void WebViewImpl::setTabKeyCyclesThroughElements(bool value)
420 m_page->setTabKeyCyclesThroughElements(value);
423 void WebViewImpl::mouseMove(const WebMouseEvent& event)
425 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
428 m_lastMousePosition = WebPoint(event.x, event.y);
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));
437 void WebViewImpl::mouseLeave(const WebMouseEvent& event)
439 // This event gets sent as the main frame is closing. In that case, just
441 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
444 m_client->setMouseOverURL(WebURL());
446 mainFrameImpl()->frame()->eventHandler()->handleMouseMoveEvent(
447 PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
450 void WebViewImpl::mouseDown(const WebMouseEvent& event)
452 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
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;
462 ASSERT(!m_selectPopup);
465 m_lastMouseDownPoint = WebPoint(event.x, event.y);
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();
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;
478 mainFrameImpl()->frame()->loader()->resetMultipleFormSubmissionProtection();
480 mainFrameImpl()->frame()->eventHandler()->handleMousePressEvent(
481 PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
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.
491 // Dispatch the contextmenu event regardless of if the click was swallowed.
492 // On Windows, we handle it on mouse up, not down.
494 if (event.button == WebMouseEvent::ButtonRight
495 || (event.button == WebMouseEvent::ButtonLeft
496 && event.modifiers & WebMouseEvent::ControlKey))
497 mouseContextMenu(event);
499 if (event.button == WebMouseEvent::ButtonRight)
500 mouseContextMenu(event);
504 void WebViewImpl::mouseContextMenu(const WebMouseEvent& event)
506 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
509 m_page->contextMenuController()->clearContextMenu();
511 PlatformMouseEventBuilder pme(mainFrameImpl()->frameView(), event);
513 // Find the right target frame. See issue 1186900.
514 HitTestResult result = hitTestResultForWindowPos(pme.pos());
516 if (result.innerNonSharedNode())
517 targetFrame = result.innerNonSharedNode()->document()->frame();
519 targetFrame = m_page->focusController()->focusedOrMainFrame();
522 targetFrame->view()->setCursor(pointerCursor());
525 m_contextMenuAllowed = true;
526 targetFrame->eventHandler()->sendContextMenuEvent(pme);
527 m_contextMenuAllowed = false;
528 // Actually showing the context menu is handled by the ContextMenuClient
532 void WebViewImpl::mouseUp(const WebMouseEvent& event)
534 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
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.
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
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);
574 mainFrameImpl()->frame()->eventHandler()->handleMouseReleaseEvent(
575 PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
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);
585 bool WebViewImpl::mouseWheel(const WebMouseWheelEvent& event)
587 PlatformWheelEventBuilder platformEvent(mainFrameImpl()->frameView(), event);
588 return mainFrameImpl()->frame()->eventHandler()->handleWheelEvent(platformEvent);
591 #if ENABLE(GESTURE_EVENTS)
592 bool WebViewImpl::gestureEvent(const WebGestureEvent& event)
594 PlatformGestureEventBuilder platformEvent(mainFrameImpl()->frameView(), event);
595 bool handled = mainFrameImpl()->frame()->eventHandler()->handleGestureEvent(platformEvent);
597 Frame* frame = mainFrameImpl()->frame();
598 WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
600 handled |= pluginContainer->handleGestureEvent(platformEvent);
606 bool WebViewImpl::keyEvent(const WebKeyboardEvent& event)
608 ASSERT((event.type == WebInputEvent::RawKeyDown)
609 || (event.type == WebInputEvent::KeyDown)
610 || (event.type == WebInputEvent::KeyUp));
612 // Please refer to the comments explaining the m_suppressNextKeypressEvent
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
618 m_suppressNextKeypressEvent = false;
620 // If there is a select popup, it should be the one processing the event,
623 return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
625 // Give Autocomplete a chance to consume the key events it is interested in.
626 if (autocompleteHandleKeyEvent(event))
629 Frame* frame = focusedWebCoreFrame();
633 EventHandler* handler = frame->eventHandler();
635 return keyEventDefault(event);
638 const WebInputEvent::Type contextMenuTriggeringEventType =
640 WebInputEvent::KeyUp;
642 WebInputEvent::RawKeyDown;
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);
651 #endif // !OS(DARWIN)
653 PlatformKeyboardEventBuilder evt(event);
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;
666 return keyEventDefault(event);
669 bool WebViewImpl::autocompleteHandleKeyEvent(const WebKeyboardEvent& event)
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)
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();
685 Element* element = static_cast<Element*>(node);
686 if (!element->hasLocalName(HTMLNames::inputTag)) {
687 ASSERT_NOT_REACHED();
691 int selectedIndex = m_autofillPopup->selectedIndex();
693 if (!m_autofillPopupClient->canRemoveSuggestionAtIndex(selectedIndex))
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
701 m_autofillPopupClient->removeSuggestionAtIndex(selectedIndex);
702 refreshAutofillPopup();
706 if (!m_autofillPopup->isInterestedInEventForKey(event.windowsKeyCode))
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;
720 bool WebViewImpl::charEvent(const WebKeyboardEvent& event)
722 ASSERT(event.type == WebInputEvent::Char);
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;
732 // If there is a select popup, it should be the one processing the event,
735 return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
737 Frame* frame = focusedWebCoreFrame();
741 EventHandler* handler = frame->eventHandler();
743 return suppress || keyEventDefault(event);
745 PlatformKeyboardEventBuilder evt(event);
746 if (!evt.isCharacterKey())
749 // Accesskeys are triggered by char events and can't be suppressed.
750 if (handler->handleAccessKey(evt))
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
757 if (evt.isSystemKey())
760 if (!suppress && !handler->keyEvent(evt))
761 return keyEventDefault(event);
766 #if ENABLE(TOUCH_EVENTS)
767 bool WebViewImpl::touchEvent(const WebTouchEvent& event)
769 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
772 PlatformTouchEventBuilder touchEventBuilder(mainFrameImpl()->frameView(), event);
773 bool defaultPrevented = mainFrameImpl()->frame()->eventHandler()->handleTouchEvent(touchEventBuilder);
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));
781 return defaultPrevented;
786 // Mac has no way to open a context menu based on a keyboard event.
787 bool WebViewImpl::sendContextMenuEvent(const WebKeyboardEvent& event)
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
795 page()->contextMenuController()->clearContextMenu();
797 m_contextMenuAllowed = true;
798 Frame* focusedFrame = page()->focusController()->focusedOrMainFrame();
799 bool handled = focusedFrame->eventHandler()->sendContextMenuEventForKey();
800 m_contextMenuAllowed = false;
805 bool WebViewImpl::keyEventDefault(const WebKeyboardEvent& event)
807 Frame* frame = focusedWebCoreFrame();
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);
818 case WebInputEvent::RawKeyDown:
819 if (event.modifiers == WebInputEvent::ControlKey) {
820 switch (event.windowsKeyCode) {
823 focusedFrame()->executeCommand(WebString::fromUTF8("SelectAll"));
827 focusedFrame()->executeCommand(WebString::fromUTF8("Copy"));
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.
841 if (!event.isSystemKey && !(event.modifiers & WebInputEvent::ShiftKey))
842 return scrollViewWithKeyboard(event.windowsKeyCode, event.modifiers);
850 bool WebViewImpl::scrollViewWithKeyboard(int keyCode, int modifiers)
852 ScrollDirection scrollDirection;
853 ScrollGranularity scrollGranularity;
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)
863 if (!mapKeyCodeForScroll(keyCode, &scrollDirection, &scrollGranularity))
865 return propagateScroll(scrollDirection, scrollGranularity);
868 bool WebViewImpl::mapKeyCodeForScroll(int keyCode,
869 WebCore::ScrollDirection* scrollDirection,
870 WebCore::ScrollGranularity* scrollGranularity)
874 *scrollDirection = ScrollLeft;
875 *scrollGranularity = ScrollByLine;
878 *scrollDirection = ScrollRight;
879 *scrollGranularity = ScrollByLine;
882 *scrollDirection = ScrollUp;
883 *scrollGranularity = ScrollByLine;
886 *scrollDirection = ScrollDown;
887 *scrollGranularity = ScrollByLine;
890 *scrollDirection = ScrollUp;
891 *scrollGranularity = ScrollByDocument;
894 *scrollDirection = ScrollDown;
895 *scrollGranularity = ScrollByDocument;
897 case VKEY_PRIOR: // page up
898 *scrollDirection = ScrollUp;
899 *scrollGranularity = ScrollByPage;
901 case VKEY_NEXT: // page down
902 *scrollDirection = ScrollDown;
903 *scrollGranularity = ScrollByPage;
912 void WebViewImpl::hideSelectPopup()
914 if (m_selectPopup.get())
915 m_selectPopup->hidePopup();
918 bool WebViewImpl::propagateScroll(ScrollDirection scrollDirection,
919 ScrollGranularity scrollGranularity)
921 Frame* frame = focusedWebCoreFrame();
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();
931 return scrollHandled;
934 void WebViewImpl::popupOpened(WebCore::PopupContainer* popupContainer)
936 if (popupContainer->popupType() == WebCore::PopupContainer::Select) {
937 ASSERT(!m_selectPopup);
938 m_selectPopup = popupContainer;
942 void WebViewImpl::popupClosed(WebCore::PopupContainer* popupContainer)
944 if (popupContainer->popupType() == WebCore::PopupContainer::Select) {
945 ASSERT(m_selectPopup.get());
950 void WebViewImpl::hideAutofillPopup()
952 if (m_autofillPopupShowing) {
953 m_autofillPopup->hidePopup();
954 m_autofillPopupShowing = false;
958 Frame* WebViewImpl::focusedWebCoreFrame() const
960 return m_page.get() ? m_page->focusController()->focusedOrMainFrame() : 0;
963 WebViewImpl* WebViewImpl::fromPage(Page* page)
968 ChromeClientImpl* chromeClient = static_cast<ChromeClientImpl*>(page->chrome()->client());
969 return static_cast<WebViewImpl*>(chromeClient->webView());
972 // WebWidget ------------------------------------------------------------------
974 void WebViewImpl::close()
976 RefPtr<WebFrameImpl> mainFrameImpl;
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();
988 // Should happen after m_page.clear().
989 if (m_devToolsAgent.get())
990 m_devToolsAgent.clear();
992 // Reset the delegate to prevent notifications being sent as we're being
996 deref(); // Balances ref() acquired in WebView::create
999 void WebViewImpl::willStartLiveResize()
1001 if (mainFrameImpl() && mainFrameImpl()->frameView())
1002 mainFrameImpl()->frameView()->willStartLiveResize();
1004 Frame* frame = mainFrameImpl()->frame();
1005 WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1006 if (pluginContainer)
1007 pluginContainer->willStartLiveResize();
1010 void WebViewImpl::resize(const WebSize& newSize)
1012 if (m_size == newSize)
1016 if (mainFrameImpl()->frameView()) {
1017 mainFrameImpl()->frameView()->resize(m_size.width, m_size.height);
1018 mainFrameImpl()->frame()->eventHandler()->sendResizeEvent();
1022 if (isAcceleratedCompositingActive()) {
1023 #if USE(ACCELERATED_COMPOSITING)
1024 updateLayerTreeViewport();
1027 WebRect damagedRect(0, 0, m_size.width, m_size.height);
1028 m_client->didInvalidateRect(damagedRect);
1033 void WebViewImpl::willEndLiveResize()
1035 if (mainFrameImpl() && mainFrameImpl()->frameView())
1036 mainFrameImpl()->frameView()->willEndLiveResize();
1038 Frame* frame = mainFrameImpl()->frame();
1039 WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1040 if (pluginContainer)
1041 pluginContainer->willEndLiveResize();
1044 void WebViewImpl::animate(double frameBeginTime)
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();
1054 FrameView* view = webframe->frameView();
1056 #if !USE(THREADED_COMPOSITING)
1057 if (m_layerTreeHost)
1058 m_layerTreeHost->setAnimating(true);
1060 view->serviceScriptedAnimations(convertSecondsToDOMTimeStamp(frameBeginTime));
1061 #if !USE(THREADED_COMPOSITING)
1062 if (m_layerTreeHost)
1063 m_layerTreeHost->setAnimating(false);
1070 void WebViewImpl::layout()
1072 TRACE_EVENT("WebViewImpl::layout", this, 0);
1074 WebFrameImpl* webframe = mainFrameImpl();
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();
1084 view->setFrameRect(view->frameRect());
1086 // setFrameRect may have the side-effect of causing existing page
1087 // layout to be invalidated, so layout needs to be called last.
1093 #if USE(ACCELERATED_COMPOSITING)
1094 void WebViewImpl::doPixelReadbackToCanvas(WebCanvas* canvas, const IntRect& rect)
1097 PlatformContextSkia context(canvas);
1099 // PlatformGraphicsContext is actually a pointer to PlatformContextSkia
1100 GraphicsContext gc(reinterpret_cast<PlatformGraphicsContext*>(&context));
1101 int bitmapHeight = canvas->getDevice()->accessBitmap(false).height();
1103 GraphicsContext gc(canvas);
1104 int bitmapHeight = CGBitmapContextGetHeight(reinterpret_cast<CGContextRef>(canvas));
1108 // Compute rect to sample from inverted GPU buffer.
1109 IntRect invertRect(rect.x(), bitmapHeight - rect.maxY(), rect.width(), rect.height());
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());
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());
1127 void WebViewImpl::paint(WebCanvas* canvas, const WebRect& rect)
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.
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);
1141 double paintStart = currentTime();
1142 WebFrameImpl* webframe = mainFrameImpl();
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);
1152 void WebViewImpl::themeChanged()
1156 FrameView* view = page()->mainFrame()->view();
1158 WebRect damagedRect(0, 0, m_size.width, m_size.height);
1159 view->invalidateRect(damagedRect);
1162 void WebViewImpl::composite(bool)
1164 #if USE(ACCELERATED_COMPOSITING)
1165 #if USE(THREADED_COMPOSITING)
1166 m_layerTreeHost->setNeedsRedraw();
1168 ASSERT(isAcceleratedCompositingActive());
1173 m_pageOverlay->update();
1175 m_layerTreeHost->composite();
1180 void WebViewImpl::loseCompositorContext(int numTimes)
1182 #if USE(ACCELERATED_COMPOSITING)
1183 if (m_layerTreeHost)
1184 m_layerTreeHost->loseCompositorContext(numTimes);
1188 const WebInputEvent* WebViewImpl::m_currentInputEvent = 0;
1190 bool WebViewImpl::handleInputEvent(const WebInputEvent& inputEvent)
1192 UserGestureIndicator gestureIndicator(WebInputEvent::isUserGestureEventType(inputEvent.type) ? DefinitelyProcessingUserGesture : PossiblyProcessingUserGesture);
1194 // If we've started a drag and drop operation, ignore input events until
1196 if (m_doingDragAndDrop)
1199 if (m_ignoreInputEvents)
1202 m_currentInputEvent = &inputEvent;
1204 if (m_mouseCaptureNode.get() && WebInputEvent::isMouseEventType(inputEvent.type)) {
1205 // Save m_mouseCaptureNode since mouseCaptureLost() will clear it.
1206 RefPtr<Node> node = m_mouseCaptureNode;
1208 // Not all platforms call mouseCaptureLost() directly.
1209 if (inputEvent.type == WebInputEvent::MouseUp)
1212 AtomicString eventType;
1213 switch (inputEvent.type) {
1214 case WebInputEvent::MouseMove:
1215 eventType = eventNames().mousemoveEvent;
1217 case WebInputEvent::MouseLeave:
1218 eventType = eventNames().mouseoutEvent;
1220 case WebInputEvent::MouseDown:
1221 eventType = eventNames().mousedownEvent;
1223 case WebInputEvent::MouseUp:
1224 eventType = eventNames().mouseupEvent;
1227 ASSERT_NOT_REACHED();
1230 node->dispatchMouseEvent(
1231 PlatformMouseEventBuilder(mainFrameImpl()->frameView(), *static_cast<const WebMouseEvent*>(&inputEvent)),
1232 eventType, static_cast<const WebMouseEvent*>(&inputEvent)->clickCount);
1233 m_currentInputEvent = 0;
1237 bool handled = true;
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));
1247 case WebInputEvent::MouseLeave:
1248 mouseLeave(*static_cast<const WebMouseEvent*>(&inputEvent));
1251 case WebInputEvent::MouseWheel:
1252 handled = mouseWheel(*static_cast<const WebMouseWheelEvent*>(&inputEvent));
1255 case WebInputEvent::MouseDown:
1256 mouseDown(*static_cast<const WebMouseEvent*>(&inputEvent));
1259 case WebInputEvent::MouseUp:
1260 mouseUp(*static_cast<const WebMouseEvent*>(&inputEvent));
1263 case WebInputEvent::RawKeyDown:
1264 case WebInputEvent::KeyDown:
1265 case WebInputEvent::KeyUp:
1266 handled = keyEvent(*static_cast<const WebKeyboardEvent*>(&inputEvent));
1269 case WebInputEvent::Char:
1270 handled = charEvent(*static_cast<const WebKeyboardEvent*>(&inputEvent));
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));
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));
1294 m_currentInputEvent = 0;
1299 void WebViewImpl::mouseCaptureLost()
1301 m_mouseCaptureNode = 0;
1304 void WebViewImpl::setFocus(bool enable)
1306 m_page->focusController()->setFocused(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();
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));
1334 m_imeAcceptEvents = true;
1336 hideAutofillPopup();
1339 // Clear focus on the currently focused frame if any.
1343 Frame* frame = m_page->mainFrame();
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;
1358 bool WebViewImpl::setComposition(
1359 const WebString& text,
1360 const WebVector<WebCompositionUnderline>& underlines,
1364 Frame* focused = focusedWebCoreFrame();
1365 if (!focused || !m_imeAcceptEvents)
1367 Editor* editor = focused->editor();
1371 // The input focus has been moved to another WebWidget object.
1372 // We should use this |editor| object only to complete the ongoing
1374 if (!editor->canEdit() && !editor->hasComposition())
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();
1383 Node* node = range->startContainer();
1384 if (!node || !node->isContentEditable())
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.
1396 Vector<CompositionUnderline> emptyUnderlines;
1397 editor->setComposition(emptyString, emptyUnderlines, 0, 0);
1398 return text.isEmpty();
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);
1409 return editor->hasComposition();
1412 bool WebViewImpl::confirmComposition()
1414 return confirmComposition(WebString());
1417 bool WebViewImpl::confirmComposition(const WebString& text)
1419 Frame* focused = focusedWebCoreFrame();
1420 if (!focused || !m_imeAcceptEvents)
1422 Editor* editor = focused->editor();
1423 if (!editor || (!editor->hasComposition() && !text.length()))
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();
1432 Node* node = range->startContainer();
1433 if (!node || !node->isContentEditable())
1437 if (editor->hasComposition()) {
1439 editor->confirmComposition(String(text));
1441 editor->confirmComposition();
1443 editor->insertText(String(text), 0);
1448 bool WebViewImpl::compositionRange(size_t* location, size_t* length)
1450 Frame* focused = focusedWebCoreFrame();
1451 if (!focused || !m_imeAcceptEvents)
1453 Editor* editor = focused->editor();
1454 if (!editor || !editor->hasComposition())
1457 RefPtr<Range> range = editor->compositionRange();
1461 if (TextIterator::locationAndLengthFromRange(range.get(), *location, *length))
1466 WebTextInputType WebViewImpl::textInputType()
1468 Node* node = focusedWebCoreNode();
1470 return WebTextInputTypeNone;
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);
1477 if (input->readOnly() || input->disabled())
1478 return WebTextInputTypeNone;
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;
1497 if (element->hasLocalName(HTMLNames::textareaTag)) {
1498 HTMLTextAreaElement* textarea = static_cast<HTMLTextAreaElement*>(element);
1500 if (textarea->readOnly() || textarea->disabled())
1501 return WebTextInputTypeNone;
1502 return WebTextInputTypeText;
1506 // For other situations.
1507 if (node->shouldUseInputMethod())
1508 return WebTextInputTypeText;
1510 return WebTextInputTypeNone;
1513 bool WebViewImpl::getSelectionOffsetsAndTextInEditableContent(WebString& text, size_t& focus, size_t& anchor) const
1515 const Frame* frame = focusedWebCoreFrame();
1519 const FrameSelection* selection = frame->selection();
1520 Element* element = selection->rootEditableElement();
1526 RefPtr<Range> range = selection->selection().firstRange();
1527 if (!range || !TextIterator::locationAndLengthFromRange(range.get(), location, length))
1530 if (selection->selection().isBaseFirst()) {
1532 focus = location + length;
1535 focus = location + length;
1538 text = element->innerText();
1543 WebRect WebViewImpl::caretOrSelectionBounds()
1546 const Frame* focused = focusedWebCoreFrame();
1550 FrameSelection* selection = focused->selection();
1554 const FrameView* view = focused->view();
1558 const Node* node = selection->base().containerNode();
1559 if (!node || !node->renderer())
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)
1569 rect = view->contentsToWindow(focused->editor()->firstRectForRange(range.get()));
1574 bool WebViewImpl::selectionRange(WebPoint& start, WebPoint& end) const
1576 const Frame* frame = focusedWebCoreFrame();
1577 if (!frame || !frame->selection()->isRange())
1579 RefPtr<Range> selectedRange = frame->selection()->toNormalizedRange();
1582 RefPtr<Range> range(Range::create(selectedRange->startContainer()->document(),
1583 selectedRange->startContainer(),
1584 selectedRange->startOffset(),
1585 selectedRange->startContainer(),
1586 selectedRange->startOffset()));
1588 IntRect rect = frame->editor()->firstRectForRange(range.get());
1590 start.y = rect.y() + rect.height() - 1;
1592 range = Range::create(selectedRange->endContainer()->document(),
1593 selectedRange->endContainer(),
1594 selectedRange->endOffset(),
1595 selectedRange->endContainer(),
1596 selectedRange->endOffset());
1598 rect = frame->editor()->firstRectForRange(range.get());
1599 end.x = rect.x() + rect.width() - 1;
1600 end.y = rect.y() + rect.height() - 1;
1602 start = frame->view()->contentsToWindow(start);
1603 end = frame->view()->contentsToWindow(end);
1604 if (!frame->selection()->selection().isBaseFirst())
1605 std::swap(start, end);
1609 bool WebViewImpl::caretOrSelectionRange(size_t* location, size_t* length)
1611 const Frame* focused = focusedWebCoreFrame();
1615 FrameSelection* selection = focused->selection();
1619 RefPtr<Range> range = selection->selection().firstRange();
1623 if (TextIterator::locationAndLengthFromRange(range.get(), *location, *length))
1628 void WebViewImpl::setTextDirection(WebTextDirection direction)
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();
1638 Editor* editor = focused->editor();
1639 if (!editor || !editor->canEdit())
1642 switch (direction) {
1643 case WebTextDirectionDefault:
1644 editor->setBaseWritingDirection(NaturalWritingDirection);
1647 case WebTextDirectionLeftToRight:
1648 editor->setBaseWritingDirection(LeftToRightWritingDirection);
1651 case WebTextDirectionRightToLeft:
1652 editor->setBaseWritingDirection(RightToLeftWritingDirection);
1661 bool WebViewImpl::isAcceleratedCompositingActive() const
1663 #if USE(ACCELERATED_COMPOSITING)
1664 return m_isAcceleratedCompositingActive;
1670 // WebView --------------------------------------------------------------------
1672 WebSettings* WebViewImpl::settings()
1675 m_webSettings = adoptPtr(new WebSettingsImpl(m_page->settings()));
1676 ASSERT(m_webSettings.get());
1677 return m_webSettings.get();
1680 WebString WebViewImpl::pageEncoding() const
1685 // FIXME: Is this check needed?
1686 if (!m_page->mainFrame()->document()->loader())
1689 return m_page->mainFrame()->document()->encoding();
1692 void WebViewImpl::setPageEncoding(const WebString& encodingName)
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);
1705 bool WebViewImpl::dispatchBeforeUnloadEvent()
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();
1714 return frame->loader()->shouldClose();
1717 void WebViewImpl::dispatchUnloadEvent()
1719 // Run unload handlers.
1720 m_page->mainFrame()->loader()->closeURL();
1723 WebFrame* WebViewImpl::mainFrame()
1725 return mainFrameImpl();
1728 WebFrame* WebViewImpl::findFrameByName(
1729 const WebString& name, WebFrame* relativeToFrame)
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);
1738 WebFrame* WebViewImpl::focusedFrame()
1740 return WebFrameImpl::fromFrame(focusedWebCoreFrame());
1743 void WebViewImpl::setFocusedFrame(WebFrame* frame)
1746 // Clears the focused frame if any.
1747 Frame* frame = focusedWebCoreFrame();
1749 frame->selection()->setFocused(false);
1752 WebFrameImpl* frameImpl = static_cast<WebFrameImpl*>(frame);
1753 Frame* webcoreFrame = frameImpl->frame();
1754 webcoreFrame->page()->focusController()->setFocusedFrame(webcoreFrame);
1757 void WebViewImpl::setInitialFocus(bool reverse)
1762 // Since we don't have a keyboard event, we'll create one.
1763 WebKeyboardEvent keyboardEvent;
1764 keyboardEvent.type = WebInputEvent::RawKeyDown;
1766 keyboardEvent.modifiers = WebInputEvent::ShiftKey;
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);
1773 Frame* frame = page()->focusController()->focusedOrMainFrame();
1774 if (Document* document = frame->document())
1775 document->setFocusedNode(0);
1776 page()->focusController()->setInitialFocus(
1777 reverse ? FocusDirectionBackward : FocusDirectionForward,
1781 void WebViewImpl::clearFocusedNode()
1786 RefPtr<Frame> frame = m_page->mainFrame();
1790 RefPtr<Document> document = frame->document();
1791 if (!document.get())
1794 RefPtr<Node> oldFocusedNode = document->focusedNode();
1796 // Clear the focused node.
1797 document->setFocusedNode(0);
1799 if (!oldFocusedNode.get())
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();
1813 void WebViewImpl::scrollFocusedNodeIntoView()
1815 Node* focusedNode = focusedWebCoreNode();
1816 if (focusedNode && focusedNode->isElementNode()) {
1817 Element* elementNode = static_cast<Element*>(focusedNode);
1818 elementNode->scrollIntoViewIfNeeded(true);
1822 double WebViewImpl::zoomLevel()
1827 double WebViewImpl::setZoomLevel(bool textOnly, double zoomLevel)
1829 if (m_layerTreeHost)
1830 m_layerTreeHost->setZoomAnimatorScale(1);
1832 if (zoomLevel < m_minimumZoomLevel)
1833 m_zoomLevel = m_minimumZoomLevel;
1834 else if (zoomLevel > m_maximumZoomLevel)
1835 m_zoomLevel = m_maximumZoomLevel;
1837 m_zoomLevel = zoomLevel;
1839 Frame* frame = mainFrameImpl()->frame();
1840 WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1841 if (pluginContainer)
1842 pluginContainer->plugin()->setZoomLevel(m_zoomLevel, textOnly);
1844 float zoomFactor = static_cast<float>(zoomLevelToZoomFactor(m_zoomLevel));
1846 frame->setPageAndTextZoomFactors(1, zoomFactor);
1848 frame->setPageAndTextZoomFactors(zoomFactor, 1);
1853 void WebViewImpl::zoomLimitsChanged(double minimumZoomLevel,
1854 double maximumZoomLevel)
1856 m_minimumZoomLevel = minimumZoomLevel;
1857 m_maximumZoomLevel = maximumZoomLevel;
1858 m_client->zoomLimitsChanged(m_minimumZoomLevel, m_maximumZoomLevel);
1861 void WebViewImpl::fullFramePluginZoomLevelChanged(double zoomLevel)
1863 if (zoomLevel == m_zoomLevel)
1866 m_zoomLevel = max(min(zoomLevel, m_maximumZoomLevel), m_minimumZoomLevel);
1867 m_client->zoomLevelChanged();
1870 double WebView::zoomLevelToZoomFactor(double zoomLevel)
1872 return pow(textSizeMultiplierRatio, zoomLevel);
1875 double WebView::zoomFactorToZoomLevel(double factor)
1877 // Since factor = 1.2^level, level = log(factor) / log(1.2)
1878 return log(factor) / log(textSizeMultiplierRatio);
1881 float WebViewImpl::pageScaleFactor() const
1886 return page()->pageScaleFactor();
1889 void WebViewImpl::scalePage(float scaleFactor, WebPoint origin)
1894 page()->setPageScaleFactor(scaleFactor, origin);
1897 bool WebViewImpl::isFixedLayoutModeEnabled() const
1902 Frame* frame = page()->mainFrame();
1906 return frame->view()->useFixedLayout();
1909 void WebViewImpl::enableFixedLayoutMode(bool enable)
1914 Frame* frame = page()->mainFrame();
1918 frame->view()->setUseFixedLayout(enable);
1921 WebSize WebViewImpl::fixedLayoutSize() const
1926 Frame* frame = page()->mainFrame();
1930 return frame->view()->fixedLayoutSize();
1933 void WebViewImpl::setFixedLayoutSize(const WebSize& layoutSize)
1938 Frame* frame = page()->mainFrame();
1942 frame->view()->setFixedLayoutSize(layoutSize);
1945 void WebViewImpl::performMediaPlayerAction(const WebMediaPlayerAction& action,
1946 const WebPoint& location)
1948 HitTestResult result = hitTestResultForWindowPos(location);
1949 RefPtr<Node> node = result.innerNonSharedNode();
1950 if (!node->hasTagName(HTMLNames::videoTag) && !node->hasTagName(HTMLNames::audioTag))
1953 RefPtr<HTMLMediaElement> mediaElement =
1954 static_pointer_cast<HTMLMediaElement>(node);
1955 switch (action.type) {
1956 case WebMediaPlayerAction::Play:
1958 mediaElement->play();
1960 mediaElement->pause();
1962 case WebMediaPlayerAction::Mute:
1963 mediaElement->setMuted(action.enable);
1965 case WebMediaPlayerAction::Loop:
1966 mediaElement->setLoop(action.enable);
1968 case WebMediaPlayerAction::Controls:
1969 mediaElement->setControls(action.enable);
1972 ASSERT_NOT_REACHED();
1976 void WebViewImpl::copyImageAt(const WebPoint& point)
1981 HitTestResult result = hitTestResultForWindowPos(point);
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.
1989 // FIXME: implement a cache of the most recent HitTestResult to avoid having
1990 // to do two hit tests.
1994 m_page->mainFrame()->editor()->copyImage(result);
1997 void WebViewImpl::dragSourceEndedAt(
1998 const WebPoint& clientPoint,
1999 const WebPoint& screenPoint,
2000 WebDragOperation operation)
2002 PlatformMouseEvent pme(clientPoint,
2004 LeftButton, MouseEventMoved, 0, false, false, false,
2006 m_page->mainFrame()->eventHandler()->dragSourceEndedAt(pme,
2007 static_cast<DragOperation>(operation));
2008 m_dragScrollTimer->stop();
2011 void WebViewImpl::dragSourceMovedTo(
2012 const WebPoint& clientPoint,
2013 const WebPoint& screenPoint,
2014 WebDragOperation operation)
2016 m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
2019 void WebViewImpl::dragSourceSystemDragEnded()
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;
2029 WebDragOperation WebViewImpl::dragTargetDragEnter(
2030 const WebDragData& webDragData,
2031 const WebPoint& clientPoint,
2032 const WebPoint& screenPoint,
2033 WebDragOperationsMask operationsAllowed)
2035 ASSERT(!m_currentDragData.get());
2037 m_currentDragData = webDragData;
2038 m_operationsAllowed = operationsAllowed;
2040 return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragEnter);
2043 WebDragOperation WebViewImpl::dragTargetDragOver(
2044 const WebPoint& clientPoint,
2045 const WebPoint& screenPoint,
2046 WebDragOperationsMask operationsAllowed)
2048 m_operationsAllowed = operationsAllowed;
2050 return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragOver);
2053 void WebViewImpl::dragTargetDragLeave()
2055 ASSERT(m_currentDragData.get());
2058 m_currentDragData.get(),
2061 static_cast<DragOperation>(m_operationsAllowed));
2063 m_page->dragController()->dragExited(&dragData);
2065 // FIXME: why is the drag scroll timer not stopped here?
2067 m_dragOperation = WebDragOperationNone;
2068 m_currentDragData = 0;
2071 void WebViewImpl::dragTargetDrop(const WebPoint& clientPoint,
2072 const WebPoint& screenPoint)
2074 ASSERT(m_currentDragData.get());
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.
2083 if (m_dragOperation == WebDragOperationNone) { // IPC RACE CONDITION: do not allow this drop.
2084 dragTargetDragLeave();
2089 m_currentDragData.get(),
2092 static_cast<DragOperation>(m_operationsAllowed));
2094 m_page->dragController()->performDrag(&dragData);
2096 m_dragOperation = WebDragOperationNone;
2097 m_currentDragData = 0;
2099 m_dragScrollTimer->stop();
2102 WebDragOperation WebViewImpl::dragTargetDragEnterOrOver(const WebPoint& clientPoint, const WebPoint& screenPoint, DragAction dragAction)
2104 ASSERT(m_currentDragData.get());
2107 m_currentDragData.get(),
2110 static_cast<DragOperation>(m_operationsAllowed));
2112 DragOperation dropEffect;
2113 if (dragAction == DragEnter)
2114 dropEffect = m_page->dragController()->dragEntered(&dragData);
2116 dropEffect = m_page->dragController()->dragUpdated(&dragData);
2118 // Mask the drop effect operation against the drag source's allowed operations.
2119 if (!(dropEffect & dragData.draggingSourceOperationMask()))
2120 dropEffect = DragOperationNone;
2122 m_dragOperation = static_cast<WebDragOperation>(dropEffect);
2124 if (dragAction == DragOver)
2125 m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
2127 m_dragScrollTimer->stop();
2129 return m_dragOperation;
2132 unsigned long WebViewImpl::createUniqueIdentifierForRequest()
2135 return m_page->progress()->createUniqueIdentifier();
2139 void WebViewImpl::inspectElementAt(const WebPoint& point)
2144 if (point.x == -1 || point.y == -1)
2145 m_page->inspectorController()->inspect(0);
2147 HitTestResult result = hitTestResultForWindowPos(point);
2149 if (!result.innerNonSharedNode())
2152 m_page->inspectorController()->inspect(result.innerNonSharedNode());
2156 WebString WebViewImpl::inspectorSettings() const
2158 return m_inspectorSettings;
2161 void WebViewImpl::setInspectorSettings(const WebString& settings)
2163 m_inspectorSettings = settings;
2166 bool WebViewImpl::inspectorSetting(const WebString& key, WebString* value) const
2168 if (!m_inspectorSettingsMap->contains(key))
2170 *value = m_inspectorSettingsMap->get(key);
2174 void WebViewImpl::setInspectorSetting(const WebString& key,
2175 const WebString& value)
2177 m_inspectorSettingsMap->set(key, value);
2178 client()->didUpdateInspectorSetting(key, value);
2181 WebDevToolsAgent* WebViewImpl::devToolsAgent()
2183 return m_devToolsAgent.get();
2186 WebAccessibilityObject WebViewImpl::accessibilityObject()
2188 if (!mainFrameImpl())
2189 return WebAccessibilityObject();
2191 Document* document = mainFrameImpl()->frame()->document();
2192 return WebAccessibilityObject(
2193 document->axObjectCache()->getOrCreate(document->renderer()));
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,
2204 ASSERT(names.size() == labels.size());
2205 ASSERT(names.size() == uniqueIDs.size());
2206 ASSERT(separatorIndex < static_cast<int>(names.size()));
2208 if (names.isEmpty()) {
2209 hideAutofillPopup();
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();
2222 HTMLInputElement* inputElem =
2223 static_cast<HTMLInputElement*>(focusedNode.get());
2225 // The first time the Autofill popup is shown we'll create the client and
2227 if (!m_autofillPopupClient)
2228 m_autofillPopupClient = adoptPtr(new AutofillPopupMenuClient);
2230 m_autofillPopupClient->initialize(
2231 inputElem, names, labels, icons, uniqueIDs, separatorIndex);
2233 if (!m_autofillPopup.get()) {
2234 m_autofillPopup = PopupContainer::create(m_autofillPopupClient.get(),
2235 PopupContainer::Suggestion,
2236 autofillPopupSettings);
2239 if (m_autofillPopupShowing) {
2240 refreshAutofillPopup();
2242 m_autofillPopup->showInRect(focusedNode->getRect(), focusedNode->ownerDocument()->view(), 0);
2243 m_autofillPopupShowing = true;
2247 void WebViewImpl::hidePopups()
2250 hideAutofillPopup();
2253 void WebViewImpl::performCustomContextMenuAction(unsigned action)
2257 ContextMenu* menu = m_page->contextMenuController()->contextMenu();
2260 ContextMenuItem* item = menu->itemWithAction(static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + action));
2262 m_page->contextMenuController()->contextMenuItemSelected(item);
2263 m_page->contextMenuController()->clearContextMenu();
2266 // WebView --------------------------------------------------------------------
2268 void WebViewImpl::setIsTransparent(bool isTransparent)
2270 // Set any existing frames to be transparent.
2271 Frame* frame = m_page->mainFrame();
2273 frame->view()->setTransparent(isTransparent);
2274 frame = frame->tree()->traverseNext();
2277 // Future frames check this to know whether to be transparent.
2278 m_isTransparent = isTransparent;
2281 bool WebViewImpl::isTransparent() const
2283 return m_isTransparent;
2286 void WebViewImpl::setIsActive(bool active)
2288 if (page() && page()->focusController())
2289 page()->focusController()->setActive(active);
2292 bool WebViewImpl::isActive() const
2294 return (page() && page()->focusController()) ? page()->focusController()->isActive() : false;
2297 void WebViewImpl::setDomainRelaxationForbidden(bool forbidden, const WebString& scheme)
2299 SecurityOrigin::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme));
2302 void WebViewImpl::setScrollbarColors(unsigned inactiveColor,
2303 unsigned activeColor,
2304 unsigned trackColor) {
2305 #if OS(UNIX) && !OS(DARWIN)
2306 PlatformThemeChromiumGtk::setScrollbarColors(inactiveColor,
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();
2325 void WebView::addUserScript(const WebString& sourceCode,
2326 const WebVector<WebString>& patternsIn,
2327 WebView::UserScriptInjectAt injectAt,
2328 WebView::UserContentInjectIn injectIn)
2330 OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2331 for (size_t i = 0; i < patternsIn.size(); ++i)
2332 patterns->append(patternsIn[i]);
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));
2341 void WebView::addUserStyleSheet(const WebString& sourceCode,
2342 const WebVector<WebString>& patternsIn,
2343 WebView::UserContentInjectIn injectIn,
2344 WebView::UserStyleInjectionTime injectionTime)
2346 OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2347 for (size_t i = 0; i < patternsIn.size(); ++i)
2348 patterns->append(patternsIn[i]);
2350 PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2351 RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
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.
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));
2363 void WebView::removeAllUserContent()
2365 PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2366 pageGroup->removeAllUserContent();
2369 void WebViewImpl::didCommitLoad(bool* isNewNavigation)
2371 if (isNewNavigation)
2372 *isNewNavigation = m_observedNewNavigation;
2375 ASSERT(!m_observedNewNavigation
2376 || m_page->mainFrame()->loader()->documentLoader() == m_newNavigationLoader);
2377 m_newNavigationLoader = 0;
2379 m_observedNewNavigation = false;
2382 bool WebViewImpl::useExternalPopupMenus()
2384 return shouldUseExternalPopupMenus;
2387 bool WebViewImpl::navigationPolicyFromMouseEvent(unsigned short button,
2388 bool ctrl, bool shift,
2389 bool alt, bool meta,
2390 WebNavigationPolicy* policy)
2393 const bool newTabModifier = (button == 1) || meta;
2395 const bool newTabModifier = (button == 1) || ctrl;
2397 if (!newTabModifier && !shift && !alt)
2401 if (newTabModifier) {
2403 *policy = WebNavigationPolicyNewForegroundTab;
2405 *policy = WebNavigationPolicyNewBackgroundTab;
2408 *policy = WebNavigationPolicyNewWindow;
2410 *policy = WebNavigationPolicyDownload;
2415 void WebViewImpl::startDragging(const WebDragData& dragData,
2416 WebDragOperationsMask mask,
2417 const WebImage& dragImage,
2418 const WebPoint& dragImageOffset)
2422 ASSERT(!m_doingDragAndDrop);
2423 m_doingDragAndDrop = true;
2424 m_client->startDragging(dragData, mask, dragImage, dragImageOffset);
2427 void WebViewImpl::observeNewNavigation()
2429 m_observedNewNavigation = true;
2431 m_newNavigationLoader = m_page->mainFrame()->loader()->documentLoader();
2435 void WebViewImpl::setIgnoreInputEvents(bool newValue)
2437 ASSERT(m_ignoreInputEvents != newValue);
2438 m_ignoreInputEvents = newValue;
2441 void WebViewImpl::setPageOverlayClient(PageOverlay::PageOverlayClient* pageOverlayClient)
2443 if (pageOverlayClient) {
2445 m_pageOverlay = PageOverlay::create(this, pageOverlayClient);
2447 m_pageOverlay->setClient(pageOverlayClient);
2448 m_pageOverlay->update();
2449 setRootLayerNeedsDisplay();
2451 if (m_pageOverlay) {
2452 m_pageOverlay->clear();
2453 m_pageOverlay = nullptr;
2454 setRootLayerNeedsDisplay();
2459 void WebViewImpl::setOverlayLayer(WebCore::GraphicsLayer* layer)
2461 if (m_rootGraphicsLayer) {
2462 if (layer->parent() != m_rootGraphicsLayer)
2463 m_rootGraphicsLayer->addChild(layer);
2467 #if ENABLE(NOTIFICATIONS)
2468 NotificationPresenterImpl* WebViewImpl::notificationPresenterImpl()
2470 if (!m_notificationPresenter.isInitialized() && m_client)
2471 m_notificationPresenter.initialize(m_client->notificationPresenter());
2472 return &m_notificationPresenter;
2476 void WebViewImpl::refreshAutofillPopup()
2478 ASSERT(m_autofillPopupShowing);
2480 // Hide the popup if it has become empty.
2481 if (!m_autofillPopupClient->listSize()) {
2482 hideAutofillPopup();
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());
2494 popupMenu->client()->setWindowRect(m_chromeClientImpl.windowToScreen(newBounds));
2498 Node* WebViewImpl::focusedWebCoreNode()
2500 Frame* frame = m_page->focusController()->focusedFrame();
2504 Document* document = frame->document();
2508 return document->focusedNode();
2511 HitTestResult WebViewImpl::hitTestResultForWindowPos(const IntPoint& pos)
2513 IntPoint docPoint(m_page->mainFrame()->view()->windowToContents(pos));
2514 return m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(docPoint, false);
2517 void WebViewImpl::setTabsToLinks(bool enable)
2519 m_tabsToLinks = enable;
2522 bool WebViewImpl::tabsToLinks() const
2524 return m_tabsToLinks;
2527 #if USE(ACCELERATED_COMPOSITING)
2528 bool WebViewImpl::allowsAcceleratedCompositing()
2530 return !m_compositorCreationFailed;
2533 bool WebViewImpl::pageHasRTLStyle() const
2537 Document* document = page()->mainFrame()->document();
2540 RenderView* renderView = document->renderView();
2543 RenderStyle* style = renderView->style();
2546 return (style->direction() == RTL);
2549 void WebViewImpl::setRootGraphicsLayer(GraphicsLayer* layer)
2551 m_rootGraphicsLayer = layer;
2553 setIsAcceleratedCompositingActive(layer);
2554 if (m_nonCompositedContentHost)
2555 m_nonCompositedContentHost->setRootLayer(layer);
2557 IntRect damagedRect(0, 0, m_size.width, m_size.height);
2558 if (!m_isAcceleratedCompositingActive)
2559 m_client->didInvalidateRect(damagedRect);
2562 void WebViewImpl::setRootLayerNeedsDisplay()
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();
2570 m_client->scheduleComposite();
2574 void WebViewImpl::scrollRootLayerRect(const IntSize& scrollDelta, const IntRect& clipRect)
2576 updateLayerTreeViewport();
2577 setRootLayerNeedsDisplay();
2580 void WebViewImpl::invalidateRootLayerRect(const IntRect& rect)
2582 ASSERT(m_layerTreeHost);
2587 FrameView* view = page()->mainFrame()->view();
2588 IntRect dirtyRect = view->windowToContents(rect);
2589 updateLayerTreeViewport();
2590 m_nonCompositedContentHost->invalidateRect(dirtyRect);
2591 setRootLayerNeedsDisplay();
2594 class WebViewImplContentPainter : public LayerPainterChromium {
2595 WTF_MAKE_NONCOPYABLE(WebViewImplContentPainter);
2597 static PassOwnPtr<WebViewImplContentPainter*> create(WebViewImpl* webViewImpl)
2599 return adoptPtr(new WebViewImplContentPainter(webViewImpl));
2602 virtual void paint(GraphicsContext& context, const IntRect& contentRect)
2604 double paintStart = currentTime();
2605 Page* page = m_webViewImpl->page();
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);
2617 explicit WebViewImplContentPainter(WebViewImpl* webViewImpl)
2618 : m_webViewImpl(webViewImpl)
2622 WebViewImpl* m_webViewImpl;
2625 void WebViewImpl::setIsAcceleratedCompositingActive(bool active)
2627 PlatformSupport::histogramEnumeration("GPU.setIsAcceleratedCompositingActive", active * 2 + m_isAcceleratedCompositingActive, 4);
2629 if (m_isAcceleratedCompositingActive == 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();
2644 m_client->didActivateAcceleratedCompositing(true);
2646 TRACE_EVENT("WebViewImpl::setIsAcceleratedCompositingActive(true)", this, 0);
2648 WebCore::CCSettings ccSettings;
2649 ccSettings.acceleratePainting = page()->settings()->acceleratedDrawingEnabled();
2650 ccSettings.compositeOffscreen = settings()->compositeToTextureEnabled();
2651 #if USE(THREADED_COMPOSITING)
2652 ccSettings.enableCompositorThread = true;
2654 ccSettings.enableCompositorThread = false;
2656 ccSettings.showFPSCounter = settings()->showFPSCounter();
2657 ccSettings.showPlatformLayerTree = settings()->showPlatformLayerTree();
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;
2667 m_pageOverlay->update();
2669 m_isAcceleratedCompositingActive = false;
2670 m_client->didActivateAcceleratedCompositing(false);
2671 m_compositorCreationFailed = true;
2675 page()->mainFrame()->view()->setClipsRepaints(!m_isAcceleratedCompositingActive);
2680 PassOwnPtr<CCThread> WebViewImpl::createCompositorThread()
2682 return CCThreadImpl::create();
2685 PassRefPtr<GraphicsContext3D> WebViewImpl::createLayerTreeHostContext3D()
2687 RefPtr<GraphicsContext3D> context = m_temporaryOnscreenGraphicsContext3D.release();
2689 #if USE(THREADED_COMPOSITING)
2690 context = GraphicsContext3DPrivate::createGraphicsContextForAnotherThread(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2692 context = GraphicsContext3D::create(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2698 PassOwnPtr<LayerPainterChromium> WebViewImpl::createRootLayerPainter()
2700 return WebViewImplContentPainter::create(this);
2703 void WebViewImpl::animateAndLayout(double frameBeginTime)
2705 animate(frameBeginTime);
2709 void WebViewImpl::didRecreateGraphicsContext(bool success)
2712 // Switch back to software rendering mode, if necessary
2714 ASSERT(m_isAcceleratedCompositingActive);
2715 setIsAcceleratedCompositingActive(false);
2716 m_compositorCreationFailed = true;
2717 m_client->didInvalidateRect(IntRect(0, 0, m_size.width, m_size.height));
2719 // Force a style recalc to remove all the composited layers.
2720 m_page->mainFrame()->document()->scheduleForcedStyleRecalc();
2725 m_pageOverlay->update();
2728 #if !USE(THREADED_COMPOSITING)
2729 void WebViewImpl::scheduleComposite()
2731 m_client->scheduleComposite();
2735 void WebViewImpl::updateLayerTreeViewport()
2740 FrameView* view = page()->mainFrame()->view();
2741 IntRect visibleRect = view->visibleContentRect(true /* include scrollbars */);
2742 IntPoint scroll(view->scrollX(), view->scrollY());
2744 m_nonCompositedContentHost->setViewport(visibleRect.size(), view->contentsSize(), scroll);
2745 m_layerTreeHost->setViewport(visibleRect.size());
2748 WebGraphicsContext3D* WebViewImpl::graphicsContext3D()
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())
2757 if (m_temporaryOnscreenGraphicsContext3D) {
2758 WebGraphicsContext3D* webContext = GraphicsContext3DPrivate::extractWebGraphicsContext3D(m_temporaryOnscreenGraphicsContext3D.get());
2759 if (webContext && !webContext->isContextLost())
2762 #if USE(THREADED_COMPOSITING)
2763 m_temporaryOnscreenGraphicsContext3D = GraphicsContext3DPrivate::createGraphicsContextForAnotherThread(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2765 m_temporaryOnscreenGraphicsContext3D = GraphicsContext3D::create(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2767 return GraphicsContext3DPrivate::extractWebGraphicsContext3D(m_temporaryOnscreenGraphicsContext3D.get());
2774 void WebViewImpl::setVisibilityState(WebPageVisibilityState visibilityState,
2775 bool isInitialState) {
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);
2786 #if USE(ACCELERATED_COMPOSITING)
2787 if (isAcceleratedCompositingActive()) {
2788 bool visible = visibilityState == WebPageVisibilityStateVisible;
2790 m_nonCompositedContentHost->protectVisibleTileTextures();
2791 m_layerTreeHost->setVisible(visible);
2796 #if ENABLE(GESTURE_RECOGNIZER)
2797 void WebViewImpl::resetGestureRecognizer()
2799 m_gestureRecognizer->reset();
2803 void WebViewImpl::exitFullscreen()
2805 #if ENABLE(FULLSCREEN_API)
2806 Document* document = page()->mainFrame()->document();
2807 Element* fullscreenElement = document->webkitCurrentFullScreenElement();
2808 if (!fullscreenElement)
2810 document->webkitWillExitFullScreenForElement(fullscreenElement);
2811 document->webkitDidExitFullScreenForElement(fullscreenElement);
2815 } // namespace WebKit