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 "CSSStyleSelector.h"
38 #include "CSSValueKeywords.h"
40 #include "ColorSpace.h"
41 #include "CompositionUnderlineVectorBuilder.h"
42 #include "ContextMenu.h"
43 #include "ContextMenuController.h"
44 #include "ContextMenuItem.h"
46 #include "DOMUtilitiesPrivate.h"
47 #include "DeviceOrientationClientProxy.h"
49 #include "DocumentLoader.h"
50 #include "DragController.h"
52 #include "DragScrollTimer.h"
54 #include "EventHandler.h"
55 #include "Extensions3D.h"
56 #include "FocusController.h"
57 #include "FontDescription.h"
58 #include "FrameLoader.h"
59 #include "FrameSelection.h"
60 #include "FrameTree.h"
61 #include "FrameView.h"
62 #include "GeolocationClientProxy.h"
63 #include "GraphicsContext.h"
64 #include "GraphicsContext3D.h"
65 #include "GraphicsContext3DInternal.h"
66 #include "HTMLInputElement.h"
67 #include "HTMLMediaElement.h"
68 #include "HTMLNames.h"
69 #include "HTMLTextAreaElement.h"
70 #include "HitTestResult.h"
72 #include "ImageBuffer.h"
73 #include "InspectorController.h"
74 #include "KeyboardCodes.h"
75 #include "KeyboardEvent.h"
76 #include "LayerPainterChromium.h"
77 #include "MIMETypeRegistry.h"
78 #include "NodeRenderStyle.h"
80 #include "PageGroup.h"
81 #include "PageGroupLoadDeferrer.h"
82 #include "Pasteboard.h"
83 #include "PlatformContextSkia.h"
84 #include "PlatformKeyboardEvent.h"
85 #include "PlatformMouseEvent.h"
86 #include "PlatformThemeChromiumGtk.h"
87 #include "PlatformWheelEvent.h"
88 #include "PopupMenuChromium.h"
89 #include "PopupMenuClient.h"
90 #include "ProgressTracker.h"
91 #include "RenderView.h"
92 #include "ResourceHandle.h"
93 #include "SecurityOrigin.h"
95 #include "SpeechInputClientImpl.h"
96 #include "TextIterator.h"
98 #include "TraceEvent.h"
99 #include "TypingCommand.h"
100 #include "UserGestureIndicator.h"
102 #include "WebAccessibilityObject.h"
103 #include "WebAutofillClient.h"
104 #include "WebDevToolsAgentImpl.h"
105 #include "WebDevToolsAgentPrivate.h"
106 #include "WebDragData.h"
107 #include "WebFrameImpl.h"
108 #include "WebGraphicsContext3D.h"
109 #include "WebImage.h"
110 #include "WebInputElement.h"
111 #include "WebInputEvent.h"
112 #include "WebInputEventConversion.h"
114 #include "WebKitClient.h"
115 #include "WebMediaPlayerAction.h"
117 #include "WebPlugin.h"
118 #include "WebPluginContainerImpl.h"
119 #include "WebPoint.h"
120 #include "WebPopupMenuImpl.h"
121 #include "WebRange.h"
123 #include "WebRuntimeFeatures.h"
124 #include "WebSettingsImpl.h"
125 #include "WebString.h"
126 #include "WebVector.h"
127 #include "WebViewClient.h"
128 #include "cc/CCHeadsUpDisplay.h"
129 #include <wtf/ByteArray.h>
130 #include <wtf/CurrentTime.h>
131 #include <wtf/MainThread.h>
132 #include <wtf/RefPtr.h>
134 #if ENABLE(GESTURE_EVENTS)
135 #include "PlatformGestureEvent.h"
138 #if ENABLE(GESTURE_RECOGNIZER)
139 #include "PlatformGestureRecognizer.h"
143 #include <CoreGraphics/CGBitmapContext.h>
144 #include <CoreGraphics/CGContext.h>
148 #include "RenderThemeChromiumWin.h"
150 #if OS(UNIX) && !OS(DARWIN)
151 #include "RenderThemeChromiumLinux.h"
153 #include "RenderTheme.h"
156 // Get rid of WTF's pow define so we can use std::pow.
158 #include <cmath> // for std::pow
160 using namespace WebCore;
165 GraphicsContext3D::Attributes getCompositorContextAttributes()
167 // Explicitly disable antialiasing for the compositor. As of the time of
168 // this writing, the only platform that supported antialiasing for the
169 // compositor was Mac OS X, because the on-screen OpenGL context creation
170 // code paths on Windows and Linux didn't yet have multisampling support.
171 // Mac OS X essentially always behaves as though it's rendering offscreen.
172 // Multisampling has a heavy cost especially on devices with relatively low
173 // fill rate like most notebooks, and the Mac implementation would need to
174 // be optimized to resolve directly into the IOSurface shared between the
175 // GPU and browser processes. For these reasons and to avoid platform
176 // disparities we explicitly disable antialiasing.
177 GraphicsContext3D::Attributes attributes;
178 attributes.antialias = false;
182 } // anonymous namespace
186 // Change the text zoom level by kTextSizeMultiplierRatio each time the user
187 // zooms text in or out (ie., change by 20%). The min and max values limit
188 // text zoom to half and 3x the original text size. These three values match
189 // those in Apple's port in WebKit/WebKit/WebView/WebView.mm
190 const double WebView::textSizeMultiplierRatio = 1.2;
191 const double WebView::minTextSizeMultiplier = 0.5;
192 const double WebView::maxTextSizeMultiplier = 3.0;
195 // The group name identifies a namespace of pages. Page group is used on OSX
196 // for some programs that use HTML views to display things that don't seem like
197 // web pages to the user (so shouldn't have visited link coloring). We only use
199 const char* pageGroupName = "default";
201 // Used to defer all page activity in cases where the embedder wishes to run
202 // a nested event loop. Using a stack enables nesting of message loop invocations.
203 static Vector<PageGroupLoadDeferrer*> pageGroupLoadDeferrerStack;
205 // Ensure that the WebDragOperation enum values stay in sync with the original
206 // DragOperation constants.
207 #define COMPILE_ASSERT_MATCHING_ENUM(coreName) \
208 COMPILE_ASSERT(int(coreName) == int(Web##coreName), dummy##coreName)
209 COMPILE_ASSERT_MATCHING_ENUM(DragOperationNone);
210 COMPILE_ASSERT_MATCHING_ENUM(DragOperationCopy);
211 COMPILE_ASSERT_MATCHING_ENUM(DragOperationLink);
212 COMPILE_ASSERT_MATCHING_ENUM(DragOperationGeneric);
213 COMPILE_ASSERT_MATCHING_ENUM(DragOperationPrivate);
214 COMPILE_ASSERT_MATCHING_ENUM(DragOperationMove);
215 COMPILE_ASSERT_MATCHING_ENUM(DragOperationDelete);
216 COMPILE_ASSERT_MATCHING_ENUM(DragOperationEvery);
218 static const PopupContainerSettings autofillPopupSettings = {
219 false, // setTextOnIndexChange
220 false, // acceptOnAbandon
221 true, // loopSelectionNavigation
222 false // restrictWidthOfListBox (For security reasons show the entire entry
223 // so the user doesn't enter information he did not intend to.)
226 static bool shouldUseExternalPopupMenus = false;
228 // WebView ----------------------------------------------------------------
230 WebView* WebView::create(WebViewClient* client)
232 // Keep runtime flag for device motion turned off until it's implemented.
233 WebRuntimeFeatures::enableDeviceMotion(false);
235 // Pass the WebViewImpl's self-reference to the caller.
236 return adoptRef(new WebViewImpl(client)).leakRef();
239 void WebView::setUseExternalPopupMenus(bool useExternalPopupMenus)
241 shouldUseExternalPopupMenus = useExternalPopupMenus;
244 void WebView::updateVisitedLinkState(unsigned long long linkHash)
246 Page::visitedStateChanged(PageGroup::pageGroup(pageGroupName), linkHash);
249 void WebView::resetVisitedLinkState()
251 Page::allVisitedStateChanged(PageGroup::pageGroup(pageGroupName));
254 void WebView::willEnterModalLoop()
256 PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
259 if (pageGroup->pages().isEmpty())
260 pageGroupLoadDeferrerStack.append(static_cast<PageGroupLoadDeferrer*>(0));
262 // Pick any page in the page group since we are deferring all pages.
263 pageGroupLoadDeferrerStack.append(new PageGroupLoadDeferrer(*pageGroup->pages().begin(), true));
267 void WebView::didExitModalLoop()
269 ASSERT(pageGroupLoadDeferrerStack.size());
271 delete pageGroupLoadDeferrerStack.last();
272 pageGroupLoadDeferrerStack.removeLast();
275 void WebViewImpl::initializeMainFrame(WebFrameClient* frameClient)
277 // NOTE: The WebFrameImpl takes a reference to itself within InitMainFrame
278 // and releases that reference once the corresponding Frame is destroyed.
279 RefPtr<WebFrameImpl> frame = WebFrameImpl::create(frameClient);
281 frame->initializeAsMainFrame(this);
283 // Restrict the access to the local file system
284 // (see WebView.mm WebView::_commonInitializationWithFrameName).
285 SecurityOrigin::setLocalLoadPolicy(SecurityOrigin::AllowLocalLoadsForLocalOnly);
288 void WebViewImpl::setAutofillClient(WebAutofillClient* autofillClient)
290 m_autofillClient = autofillClient;
293 void WebViewImpl::setDevToolsAgentClient(WebDevToolsAgentClient* devToolsClient)
296 m_devToolsAgent = adoptPtr(new WebDevToolsAgentImpl(this, devToolsClient));
298 m_devToolsAgent.clear();
301 void WebViewImpl::setPermissionClient(WebPermissionClient* permissionClient)
303 m_permissionClient = permissionClient;
306 void WebViewImpl::setSpellCheckClient(WebSpellCheckClient* spellCheckClient)
308 m_spellCheckClient = spellCheckClient;
311 WebViewImpl::WebViewImpl(WebViewClient* client)
313 , m_autofillClient(0)
314 , m_permissionClient(0)
315 , m_spellCheckClient(0)
316 , m_chromeClientImpl(this)
317 , m_contextMenuClientImpl(this)
318 , m_dragClientImpl(this)
319 , m_editorClientImpl(this)
320 , m_inspectorClientImpl(this)
321 , m_observedNewNavigation(false)
323 , m_newNavigationLoader(0)
326 , m_minimumZoomLevel(zoomFactorToZoomLevel(minTextSizeMultiplier))
327 , m_maximumZoomLevel(zoomFactorToZoomLevel(maxTextSizeMultiplier))
328 , m_contextMenuAllowed(false)
329 , m_doingDragAndDrop(false)
330 , m_ignoreInputEvents(false)
331 , m_suppressNextKeypressEvent(false)
332 , m_initialNavigationPolicy(WebNavigationPolicyIgnore)
333 , m_imeAcceptEvents(true)
334 , m_operationsAllowed(WebDragOperationNone)
335 , m_dragOperation(WebDragOperationNone)
336 , m_autofillPopupShowing(false)
338 , m_isTransparent(false)
339 , m_tabsToLinks(false)
340 , m_dragScrollTimer(adoptPtr(new DragScrollTimer))
341 #if USE(ACCELERATED_COMPOSITING)
342 , m_rootGraphicsLayer(0)
343 , m_isAcceleratedCompositingActive(false)
344 , m_compositorCreationFailed(false)
345 , m_recreatingGraphicsContext(false)
347 #if ENABLE(INPUT_SPEECH)
348 , m_speechInputClient(SpeechInputClientImpl::create(client))
350 , m_deviceOrientationClientProxy(adoptPtr(new DeviceOrientationClientProxy(client ? client->deviceOrientationClient() : 0)))
351 , m_geolocationClientProxy(adoptPtr(new GeolocationClientProxy(client ? client->geolocationClient() : 0)))
352 #if ENABLE(GESTURE_RECOGNIZER)
353 , m_gestureRecognizer(WebCore::PlatformGestureRecognizer::create())
356 // WebKit/win/WebView.cpp does the same thing, except they call the
357 // KJS specific wrapper around this method. We need to have threading
358 // initialized because CollatorICU requires it.
359 WTF::initializeThreading();
360 WTF::initializeMainThread();
362 // set to impossible point so we always get the first mouse pos
363 m_lastMousePosition = WebPoint(-1, -1);
365 Page::PageClients pageClients;
366 pageClients.chromeClient = &m_chromeClientImpl;
367 pageClients.contextMenuClient = &m_contextMenuClientImpl;
368 pageClients.editorClient = &m_editorClientImpl;
369 pageClients.dragClient = &m_dragClientImpl;
370 pageClients.inspectorClient = &m_inspectorClientImpl;
371 #if ENABLE(INPUT_SPEECH)
372 pageClients.speechInputClient = m_speechInputClient.get();
374 pageClients.deviceOrientationClient = m_deviceOrientationClientProxy.get();
375 pageClients.geolocationClient = m_geolocationClientProxy.get();
376 pageClients.backForwardClient = BackForwardListChromium::create(this);
378 m_page = adoptPtr(new Page(pageClients));
380 m_geolocationClientProxy->setController(m_page->geolocationController());
382 m_page->setGroupName(pageGroupName);
384 #if ENABLE(PAGE_VISIBILITY_API)
386 setVisibilityState(m_client->visibilityState(), true);
389 m_inspectorSettingsMap = adoptPtr(new SettingsMap);
392 WebViewImpl::~WebViewImpl()
397 RenderTheme* WebViewImpl::theme() const
399 return m_page.get() ? m_page->theme() : RenderTheme::defaultTheme().get();
402 WebFrameImpl* WebViewImpl::mainFrameImpl()
404 return m_page.get() ? WebFrameImpl::fromFrame(m_page->mainFrame()) : 0;
407 bool WebViewImpl::tabKeyCyclesThroughElements() const
409 ASSERT(m_page.get());
410 return m_page->tabKeyCyclesThroughElements();
413 void WebViewImpl::setTabKeyCyclesThroughElements(bool value)
416 m_page->setTabKeyCyclesThroughElements(value);
419 void WebViewImpl::mouseMove(const WebMouseEvent& event)
421 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
424 m_lastMousePosition = WebPoint(event.x, event.y);
426 // We call mouseMoved here instead of handleMouseMovedEvent because we need
427 // our ChromeClientImpl to receive changes to the mouse position and
428 // tooltip text, and mouseMoved handles all of that.
429 mainFrameImpl()->frame()->eventHandler()->mouseMoved(
430 PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
433 void WebViewImpl::mouseLeave(const WebMouseEvent& event)
435 // This event gets sent as the main frame is closing. In that case, just
437 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
440 m_client->setMouseOverURL(WebURL());
442 mainFrameImpl()->frame()->eventHandler()->handleMouseMoveEvent(
443 PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
446 void WebViewImpl::mouseDown(const WebMouseEvent& event)
448 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
451 // If there is a select popup open, close it as the user is clicking on
452 // the page (outside of the popup). We also save it so we can prevent a
453 // click on the select element from immediately reopening the popup.
454 RefPtr<WebCore::PopupContainer> selectPopup;
455 if (event.button == WebMouseEvent::ButtonLeft) {
456 selectPopup = m_selectPopup;
458 ASSERT(!m_selectPopup);
461 m_lastMouseDownPoint = WebPoint(event.x, event.y);
463 RefPtr<Node> clickedNode;
464 if (event.button == WebMouseEvent::ButtonLeft) {
465 IntPoint point(event.x, event.y);
466 point = m_page->mainFrame()->view()->windowToContents(point);
467 HitTestResult result(m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, false));
468 Node* hitNode = result.innerNonSharedNode();
470 // Take capture on a mouse down on a plugin so we can send it mouse events.
471 if (hitNode && hitNode->renderer() && hitNode->renderer()->isEmbeddedObject())
472 m_mouseCaptureNode = hitNode;
474 // If a text field that has focus is clicked again, we should display the
476 RefPtr<Node> focusedNode = focusedWebCoreNode();
477 if (focusedNode.get() && toHTMLInputElement(focusedNode.get())) {
478 if (hitNode == focusedNode) {
479 // Already focused text field was clicked, let's remember this. If
480 // focus has not changed after the mouse event is processed, we'll
481 // trigger the autocomplete.
482 clickedNode = focusedNode;
487 mainFrameImpl()->frame()->loader()->resetMultipleFormSubmissionProtection();
489 mainFrameImpl()->frame()->eventHandler()->handleMousePressEvent(
490 PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
492 if (clickedNode.get() && clickedNode == focusedWebCoreNode()) {
493 // Focus has not changed, show the Autofill popup.
494 static_cast<EditorClientImpl*>(m_page->editorClient())->
495 showFormAutofillForNode(clickedNode.get());
497 if (m_selectPopup && m_selectPopup == selectPopup) {
498 // That click triggered a select popup which is the same as the one that
499 // was showing before the click. It means the user clicked the select
500 // while the popup was showing, and as a result we first closed then
501 // immediately reopened the select popup. It needs to be closed.
505 // Dispatch the contextmenu event regardless of if the click was swallowed.
506 // On Windows, we handle it on mouse up, not down.
508 if (event.button == WebMouseEvent::ButtonRight
509 || (event.button == WebMouseEvent::ButtonLeft
510 && event.modifiers & WebMouseEvent::ControlKey))
511 mouseContextMenu(event);
513 if (event.button == WebMouseEvent::ButtonRight)
514 mouseContextMenu(event);
518 void WebViewImpl::mouseContextMenu(const WebMouseEvent& event)
520 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
523 m_page->contextMenuController()->clearContextMenu();
525 PlatformMouseEventBuilder pme(mainFrameImpl()->frameView(), event);
527 // Find the right target frame. See issue 1186900.
528 HitTestResult result = hitTestResultForWindowPos(pme.pos());
530 if (result.innerNonSharedNode())
531 targetFrame = result.innerNonSharedNode()->document()->frame();
533 targetFrame = m_page->focusController()->focusedOrMainFrame();
536 targetFrame->view()->setCursor(pointerCursor());
539 m_contextMenuAllowed = true;
540 targetFrame->eventHandler()->sendContextMenuEvent(pme);
541 m_contextMenuAllowed = false;
542 // Actually showing the context menu is handled by the ContextMenuClient
546 void WebViewImpl::mouseUp(const WebMouseEvent& event)
548 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
551 #if OS(UNIX) && !OS(DARWIN)
552 // If the event was a middle click, attempt to copy text into the focused
553 // frame. We execute this before we let the page have a go at the event
554 // because the page may change what is focused during in its event handler.
556 // This code is in the mouse up handler. There is some debate about putting
557 // this here, as opposed to the mouse down handler.
558 // xterm: pastes on up.
559 // GTK: pastes on down.
560 // Firefox: pastes on up.
561 // Midori: couldn't paste at all with 0.1.2
563 // There is something of a webcompat angle to this well, as highlighted by
564 // crbug.com/14608. Pages can clear text boxes 'onclick' and, if we paste on
565 // down then the text is pasted just before the onclick handler runs and
566 // clears the text box. So it's important this happens after the
567 // handleMouseReleaseEvent() earlier in this function
568 if (event.button == WebMouseEvent::ButtonMiddle) {
569 Frame* focused = focusedWebCoreFrame();
570 FrameView* view = m_page->mainFrame()->view();
571 IntPoint clickPoint(m_lastMouseDownPoint.x, m_lastMouseDownPoint.y);
572 IntPoint contentPoint = view->windowToContents(clickPoint);
573 HitTestResult hitTestResult = focused->eventHandler()->hitTestResultAtPoint(contentPoint, false, false, ShouldHitTestScrollbars);
574 // We don't want to send a paste when middle clicking a scroll bar or a
575 // link (which will navigate later in the code). The main scrollbars
576 // have to be handled separately.
577 if (!hitTestResult.scrollbar() && !hitTestResult.isLiveLink() && focused && !view->scrollbarAtPoint(clickPoint)) {
578 Editor* editor = focused->editor();
579 Pasteboard* pasteboard = Pasteboard::generalPasteboard();
580 bool oldSelectionMode = pasteboard->isSelectionMode();
581 pasteboard->setSelectionMode(true);
582 editor->command(AtomicString("Paste")).execute();
583 pasteboard->setSelectionMode(oldSelectionMode);
588 mainFrameImpl()->frame()->eventHandler()->handleMouseReleaseEvent(
589 PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
592 // Dispatch the contextmenu event regardless of if the click was swallowed.
593 // On Mac/Linux, we handle it on mouse down, not up.
594 if (event.button == WebMouseEvent::ButtonRight)
595 mouseContextMenu(event);
599 bool WebViewImpl::mouseWheel(const WebMouseWheelEvent& event)
601 PlatformWheelEventBuilder platformEvent(mainFrameImpl()->frameView(), event);
602 return mainFrameImpl()->frame()->eventHandler()->handleWheelEvent(platformEvent);
605 #if ENABLE(GESTURE_EVENTS)
606 bool WebViewImpl::gestureEvent(const WebGestureEvent& event)
608 PlatformGestureEventBuilder platformEvent(mainFrameImpl()->frameView(), event);
609 return mainFrameImpl()->frame()->eventHandler()->handleGestureEvent(platformEvent);
613 bool WebViewImpl::keyEvent(const WebKeyboardEvent& event)
615 ASSERT((event.type == WebInputEvent::RawKeyDown)
616 || (event.type == WebInputEvent::KeyDown)
617 || (event.type == WebInputEvent::KeyUp));
619 // Please refer to the comments explaining the m_suppressNextKeypressEvent
621 // The m_suppressNextKeypressEvent is set if the KeyDown is handled by
622 // Webkit. A keyDown event is typically associated with a keyPress(char)
623 // event and a keyUp event. We reset this flag here as this is a new keyDown
625 m_suppressNextKeypressEvent = false;
627 // If there is a select popup, it should be the one processing the event,
630 return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
632 // Give Autocomplete a chance to consume the key events it is interested in.
633 if (autocompleteHandleKeyEvent(event))
636 Frame* frame = focusedWebCoreFrame();
640 EventHandler* handler = frame->eventHandler();
642 return keyEventDefault(event);
645 const WebInputEvent::Type contextMenuTriggeringEventType =
647 WebInputEvent::KeyUp;
649 WebInputEvent::RawKeyDown;
652 bool isUnmodifiedMenuKey = !(event.modifiers & WebInputEvent::InputModifiers) && event.windowsKeyCode == VKEY_APPS;
653 bool isShiftF10 = event.modifiers == WebInputEvent::ShiftKey && event.windowsKeyCode == VKEY_F10;
654 if ((isUnmodifiedMenuKey || isShiftF10) && event.type == contextMenuTriggeringEventType) {
655 sendContextMenuEvent(event);
658 #endif // !OS(DARWIN)
660 PlatformKeyboardEventBuilder evt(event);
662 if (handler->keyEvent(evt)) {
663 if (WebInputEvent::RawKeyDown == event.type) {
664 // Suppress the next keypress event unless the focused node is a plug-in node.
665 // (Flash needs these keypress events to handle non-US keyboards.)
666 Node* node = frame->document()->focusedNode();
667 if (!node || !node->renderer() || !node->renderer()->isEmbeddedObject())
668 m_suppressNextKeypressEvent = true;
673 return keyEventDefault(event);
676 bool WebViewImpl::autocompleteHandleKeyEvent(const WebKeyboardEvent& event)
678 if (!m_autofillPopupShowing
679 // Home and End should be left to the text field to process.
680 || event.windowsKeyCode == VKEY_HOME
681 || event.windowsKeyCode == VKEY_END)
684 // Pressing delete triggers the removal of the selected suggestion from the DB.
685 if (event.windowsKeyCode == VKEY_DELETE
686 && m_autofillPopup->selectedIndex() != -1) {
687 Node* node = focusedWebCoreNode();
688 if (!node || (node->nodeType() != Node::ELEMENT_NODE)) {
689 ASSERT_NOT_REACHED();
692 Element* element = static_cast<Element*>(node);
693 if (!element->hasLocalName(HTMLNames::inputTag)) {
694 ASSERT_NOT_REACHED();
698 int selectedIndex = m_autofillPopup->selectedIndex();
700 if (!m_autofillPopupClient->canRemoveSuggestionAtIndex(selectedIndex))
703 WebString name = WebInputElement(static_cast<HTMLInputElement*>(element)).nameForAutofill();
704 WebString value = m_autofillPopupClient->itemText(selectedIndex);
705 m_autofillClient->removeAutocompleteSuggestion(name, value);
706 // Update the entries in the currently showing popup to reflect the
708 m_autofillPopupClient->removeSuggestionAtIndex(selectedIndex);
709 refreshAutofillPopup();
713 if (!m_autofillPopup->isInterestedInEventForKey(event.windowsKeyCode))
716 if (m_autofillPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event))) {
717 // We need to ignore the next Char event after this otherwise pressing
718 // enter when selecting an item in the menu will go to the page.
719 if (WebInputEvent::RawKeyDown == event.type)
720 m_suppressNextKeypressEvent = true;
727 bool WebViewImpl::charEvent(const WebKeyboardEvent& event)
729 ASSERT(event.type == WebInputEvent::Char);
731 // Please refer to the comments explaining the m_suppressNextKeypressEvent
732 // member. The m_suppressNextKeypressEvent is set if the KeyDown is
733 // handled by Webkit. A keyDown event is typically associated with a
734 // keyPress(char) event and a keyUp event. We reset this flag here as it
735 // only applies to the current keyPress event.
736 bool suppress = m_suppressNextKeypressEvent;
737 m_suppressNextKeypressEvent = false;
739 // If there is a select popup, it should be the one processing the event,
742 return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
744 Frame* frame = focusedWebCoreFrame();
748 EventHandler* handler = frame->eventHandler();
750 return suppress || keyEventDefault(event);
752 PlatformKeyboardEventBuilder evt(event);
753 if (!evt.isCharacterKey())
756 // Accesskeys are triggered by char events and can't be suppressed.
757 if (handler->handleAccessKey(evt))
760 // Safari 3.1 does not pass off windows system key messages (WM_SYSCHAR) to
761 // the eventHandler::keyEvent. We mimic this behavior on all platforms since
762 // for now we are converting other platform's key events to windows key
764 if (evt.isSystemKey())
767 if (!suppress && !handler->keyEvent(evt))
768 return keyEventDefault(event);
773 #if ENABLE(TOUCH_EVENTS)
774 bool WebViewImpl::touchEvent(const WebTouchEvent& event)
776 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
779 PlatformTouchEventBuilder touchEventBuilder(mainFrameImpl()->frameView(), event);
780 bool defaultPrevented = mainFrameImpl()->frame()->eventHandler()->handleTouchEvent(touchEventBuilder);
782 #if ENABLE(GESTURE_RECOGNIZER)
783 OwnPtr<Vector<WebCore::PlatformGestureEvent> > gestureEvents(m_gestureRecognizer->processTouchEventForGestures(touchEventBuilder, defaultPrevented));
784 for (unsigned int i = 0; i < gestureEvents->size(); i++)
785 mainFrameImpl()->frame()->eventHandler()->handleGestureEvent(gestureEvents->at(i));
788 return defaultPrevented;
793 // Mac has no way to open a context menu based on a keyboard event.
794 bool WebViewImpl::sendContextMenuEvent(const WebKeyboardEvent& event)
796 // The contextMenuController() holds onto the last context menu that was
797 // popped up on the page until a new one is created. We need to clear
798 // this menu before propagating the event through the DOM so that we can
799 // detect if we create a new menu for this event, since we won't create
800 // a new menu if the DOM swallows the event and the defaultEventHandler does
802 page()->contextMenuController()->clearContextMenu();
804 m_contextMenuAllowed = true;
805 Frame* focusedFrame = page()->focusController()->focusedOrMainFrame();
806 bool handled = focusedFrame->eventHandler()->sendContextMenuEventForKey();
807 m_contextMenuAllowed = false;
812 bool WebViewImpl::keyEventDefault(const WebKeyboardEvent& event)
814 Frame* frame = focusedWebCoreFrame();
818 switch (event.type) {
819 case WebInputEvent::Char:
820 if (event.windowsKeyCode == VKEY_SPACE) {
821 int keyCode = ((event.modifiers & WebInputEvent::ShiftKey) ? VKEY_PRIOR : VKEY_NEXT);
822 return scrollViewWithKeyboard(keyCode, event.modifiers);
825 case WebInputEvent::RawKeyDown:
826 if (event.modifiers == WebInputEvent::ControlKey) {
827 switch (event.windowsKeyCode) {
830 focusedFrame()->executeCommand(WebString::fromUTF8("SelectAll"));
834 focusedFrame()->executeCommand(WebString::fromUTF8("Copy"));
837 // Match FF behavior in the sense that Ctrl+home/end are the only Ctrl
838 // key combinations which affect scrolling. Safari is buggy in the
839 // sense that it scrolls the page for all Ctrl+scrolling key
840 // combinations. For e.g. Ctrl+pgup/pgdn/up/down, etc.
848 if (!event.isSystemKey && !(event.modifiers & WebInputEvent::ShiftKey))
849 return scrollViewWithKeyboard(event.windowsKeyCode, event.modifiers);
857 bool WebViewImpl::scrollViewWithKeyboard(int keyCode, int modifiers)
859 ScrollDirection scrollDirection;
860 ScrollGranularity scrollGranularity;
862 // Control-Up/Down should be PageUp/Down on Mac.
863 if (modifiers & WebMouseEvent::ControlKey) {
864 if (keyCode == VKEY_UP)
865 keyCode = VKEY_PRIOR;
866 else if (keyCode == VKEY_DOWN)
870 if (!mapKeyCodeForScroll(keyCode, &scrollDirection, &scrollGranularity))
872 return propagateScroll(scrollDirection, scrollGranularity);
875 bool WebViewImpl::mapKeyCodeForScroll(int keyCode,
876 WebCore::ScrollDirection* scrollDirection,
877 WebCore::ScrollGranularity* scrollGranularity)
881 *scrollDirection = ScrollLeft;
882 *scrollGranularity = ScrollByLine;
885 *scrollDirection = ScrollRight;
886 *scrollGranularity = ScrollByLine;
889 *scrollDirection = ScrollUp;
890 *scrollGranularity = ScrollByLine;
893 *scrollDirection = ScrollDown;
894 *scrollGranularity = ScrollByLine;
897 *scrollDirection = ScrollUp;
898 *scrollGranularity = ScrollByDocument;
901 *scrollDirection = ScrollDown;
902 *scrollGranularity = ScrollByDocument;
904 case VKEY_PRIOR: // page up
905 *scrollDirection = ScrollUp;
906 *scrollGranularity = ScrollByPage;
908 case VKEY_NEXT: // page down
909 *scrollDirection = ScrollDown;
910 *scrollGranularity = ScrollByPage;
919 void WebViewImpl::hideSelectPopup()
921 if (m_selectPopup.get())
922 m_selectPopup->hidePopup();
925 bool WebViewImpl::propagateScroll(ScrollDirection scrollDirection,
926 ScrollGranularity scrollGranularity)
928 Frame* frame = focusedWebCoreFrame();
932 bool scrollHandled = frame->eventHandler()->scrollOverflow(scrollDirection, scrollGranularity);
933 Frame* currentFrame = frame;
934 while (!scrollHandled && currentFrame) {
935 scrollHandled = currentFrame->view()->scroll(scrollDirection, scrollGranularity);
936 currentFrame = currentFrame->tree()->parent();
938 return scrollHandled;
941 void WebViewImpl::popupOpened(WebCore::PopupContainer* popupContainer)
943 if (popupContainer->popupType() == WebCore::PopupContainer::Select) {
944 ASSERT(!m_selectPopup);
945 m_selectPopup = popupContainer;
949 void WebViewImpl::popupClosed(WebCore::PopupContainer* popupContainer)
951 if (popupContainer->popupType() == WebCore::PopupContainer::Select) {
952 ASSERT(m_selectPopup.get());
957 void WebViewImpl::hideAutofillPopup()
959 if (m_autofillPopupShowing) {
960 m_autofillPopup->hidePopup();
961 m_autofillPopupShowing = false;
965 Frame* WebViewImpl::focusedWebCoreFrame() const
967 return m_page.get() ? m_page->focusController()->focusedOrMainFrame() : 0;
970 WebViewImpl* WebViewImpl::fromPage(Page* page)
975 ChromeClientImpl* chromeClient = static_cast<ChromeClientImpl*>(page->chrome()->client());
976 return static_cast<WebViewImpl*>(chromeClient->webView());
979 // WebWidget ------------------------------------------------------------------
981 void WebViewImpl::close()
983 RefPtr<WebFrameImpl> mainFrameImpl;
986 // Initiate shutdown for the entire frameset. This will cause a lot of
987 // notifications to be sent.
988 if (m_page->mainFrame()) {
989 mainFrameImpl = WebFrameImpl::fromFrame(m_page->mainFrame());
990 m_page->mainFrame()->loader()->frameDetached();
995 // Should happen after m_page.clear().
996 if (m_devToolsAgent.get())
997 m_devToolsAgent.clear();
999 // Reset the delegate to prevent notifications being sent as we're being
1003 deref(); // Balances ref() acquired in WebView::create
1006 void WebViewImpl::willStartLiveResize()
1008 if (mainFrameImpl() && mainFrameImpl()->frameView())
1009 mainFrameImpl()->frameView()->willStartLiveResize();
1011 Frame* frame = mainFrameImpl()->frame();
1012 WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1013 if (pluginContainer)
1014 pluginContainer->willStartLiveResize();
1017 void WebViewImpl::resize(const WebSize& newSize)
1019 if (m_size == newSize)
1023 if (mainFrameImpl()->frameView()) {
1024 mainFrameImpl()->frameView()->resize(m_size.width, m_size.height);
1025 mainFrameImpl()->frame()->eventHandler()->sendResizeEvent();
1029 if (isAcceleratedCompositingActive()) {
1030 #if USE(ACCELERATED_COMPOSITING)
1031 updateLayerTreeViewport();
1034 WebRect damagedRect(0, 0, m_size.width, m_size.height);
1035 m_client->didInvalidateRect(damagedRect);
1040 void WebViewImpl::willEndLiveResize()
1042 if (mainFrameImpl() && mainFrameImpl()->frameView())
1043 mainFrameImpl()->frameView()->willEndLiveResize();
1045 Frame* frame = mainFrameImpl()->frame();
1046 WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1047 if (pluginContainer)
1048 pluginContainer->willEndLiveResize();
1051 void WebViewImpl::animate(double frameBeginTime)
1053 #if ENABLE(REQUEST_ANIMATION_FRAME)
1054 TRACE_EVENT("WebViewImpl::animate", this, 0);
1055 // FIXME: remove this zero-check once render_widget has been modified to
1056 // pass in a frameBeginTime.
1057 if (!frameBeginTime)
1058 frameBeginTime = currentTime();
1059 WebFrameImpl* webframe = mainFrameImpl();
1061 FrameView* view = webframe->frameView();
1063 #if !USE(THREADED_COMPOSITING)
1064 if (m_layerTreeHost)
1065 m_layerTreeHost->setAnimating(true);
1067 view->serviceScriptedAnimations(convertSecondsToDOMTimeStamp(frameBeginTime));
1068 #if !USE(THREADED_COMPOSITING)
1069 if (m_layerTreeHost)
1070 m_layerTreeHost->setAnimating(false);
1077 void WebViewImpl::layout()
1079 TRACE_EVENT("WebViewImpl::layout", this, 0);
1081 WebFrameImpl* webframe = mainFrameImpl();
1083 // In order for our child HWNDs (NativeWindowWidgets) to update properly,
1084 // they need to be told that we are updating the screen. The problem is
1085 // that the native widgets need to recalculate their clip region and not
1086 // overlap any of our non-native widgets. To force the resizing, call
1087 // setFrameRect(). This will be a quick operation for most frames, but
1088 // the NativeWindowWidgets will update a proper clipping region.
1089 FrameView* view = webframe->frameView();
1091 view->setFrameRect(view->frameRect());
1093 // setFrameRect may have the side-effect of causing existing page
1094 // layout to be invalidated, so layout needs to be called last.
1100 #if USE(ACCELERATED_COMPOSITING)
1101 void WebViewImpl::doPixelReadbackToCanvas(WebCanvas* canvas, const IntRect& rect)
1104 PlatformContextSkia context(canvas);
1106 // PlatformGraphicsContext is actually a pointer to PlatformContextSkia
1107 GraphicsContext gc(reinterpret_cast<PlatformGraphicsContext*>(&context));
1108 int bitmapHeight = canvas->getDevice()->accessBitmap(false).height();
1110 GraphicsContext gc(canvas);
1111 int bitmapHeight = CGBitmapContextGetHeight(reinterpret_cast<CGContextRef>(canvas));
1115 // Compute rect to sample from inverted GPU buffer.
1116 IntRect invertRect(rect.x(), bitmapHeight - rect.maxY(), rect.width(), rect.height());
1118 OwnPtr<ImageBuffer> imageBuffer(ImageBuffer::create(rect.size()));
1119 RefPtr<ByteArray> pixelArray(ByteArray::create(rect.width() * rect.height() * 4));
1120 if (imageBuffer.get() && pixelArray.get()) {
1121 m_layerTreeHost->compositeAndReadback(pixelArray->data(), invertRect);
1122 imageBuffer->putPremultipliedImageData(pixelArray.get(), rect.size(), IntRect(IntPoint(), rect.size()), IntPoint());
1124 gc.translate(IntSize(0, bitmapHeight));
1125 gc.scale(FloatSize(1.0f, -1.0f));
1126 // Use invertRect in next line, so that transform above inverts it back to
1127 // desired destination rect.
1128 gc.drawImageBuffer(imageBuffer.get(), ColorSpaceDeviceRGB, invertRect.location());
1134 void WebViewImpl::paint(WebCanvas* canvas, const WebRect& rect)
1136 if (isAcceleratedCompositingActive()) {
1137 #if USE(ACCELERATED_COMPOSITING)
1138 // If a canvas was passed in, we use it to grab a copy of the
1139 // freshly-rendered pixels.
1141 // Clip rect to the confines of the rootLayerTexture.
1142 IntRect resizeRect(rect);
1143 resizeRect.intersect(IntRect(IntPoint(0, 0), m_layerTreeHost->viewportVisibleRect().size()));
1144 doPixelReadbackToCanvas(canvas, resizeRect);
1148 double paintStart = currentTime();
1149 WebFrameImpl* webframe = mainFrameImpl();
1151 webframe->paint(canvas, rect);
1152 double paintEnd = currentTime();
1153 double pixelsPerSec = (rect.width * rect.height) / (paintEnd - paintStart);
1154 PlatformBridge::histogramCustomCounts("Renderer4.SoftwarePaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30);
1155 PlatformBridge::histogramCustomCounts("Renderer4.SoftwarePaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30);
1159 void WebViewImpl::themeChanged()
1163 FrameView* view = page()->mainFrame()->view();
1165 WebRect damagedRect(0, 0, m_size.width, m_size.height);
1166 view->invalidateRect(damagedRect);
1169 void WebViewImpl::composite(bool finish)
1171 #if USE(ACCELERATED_COMPOSITING)
1172 #if USE(THREADED_COMPOSITING)
1173 m_layerTreeHost->setNeedsRedraw();
1175 ASSERT(isAcceleratedCompositingActive());
1180 m_pageOverlay->update();
1182 m_layerTreeHost->composite(finish);
1187 const WebInputEvent* WebViewImpl::m_currentInputEvent = 0;
1189 bool WebViewImpl::handleInputEvent(const WebInputEvent& inputEvent)
1191 UserGestureIndicator gestureIndicator(WebInputEvent::isUserGestureEventType(inputEvent.type) ? DefinitelyProcessingUserGesture : PossiblyProcessingUserGesture);
1193 // If we've started a drag and drop operation, ignore input events until
1195 if (m_doingDragAndDrop)
1198 if (m_ignoreInputEvents)
1201 m_currentInputEvent = &inputEvent;
1203 if (m_mouseCaptureNode.get() && WebInputEvent::isMouseEventType(inputEvent.type)) {
1204 // Save m_mouseCaptureNode since mouseCaptureLost() will clear it.
1205 RefPtr<Node> node = m_mouseCaptureNode;
1207 // Not all platforms call mouseCaptureLost() directly.
1208 if (inputEvent.type == WebInputEvent::MouseUp)
1211 AtomicString eventType;
1212 switch (inputEvent.type) {
1213 case WebInputEvent::MouseMove:
1214 eventType = eventNames().mousemoveEvent;
1216 case WebInputEvent::MouseLeave:
1217 eventType = eventNames().mouseoutEvent;
1219 case WebInputEvent::MouseDown:
1220 eventType = eventNames().mousedownEvent;
1222 case WebInputEvent::MouseUp:
1223 eventType = eventNames().mouseupEvent;
1226 ASSERT_NOT_REACHED();
1229 node->dispatchMouseEvent(
1230 PlatformMouseEventBuilder(mainFrameImpl()->frameView(), *static_cast<const WebMouseEvent*>(&inputEvent)),
1231 eventType, static_cast<const WebMouseEvent*>(&inputEvent)->clickCount);
1232 m_currentInputEvent = 0;
1236 bool handled = true;
1238 // FIXME: WebKit seems to always return false on mouse events processing
1239 // methods. For now we'll assume it has processed them (as we are only
1240 // interested in whether keyboard events are processed).
1241 switch (inputEvent.type) {
1242 case WebInputEvent::MouseMove:
1243 mouseMove(*static_cast<const WebMouseEvent*>(&inputEvent));
1246 case WebInputEvent::MouseLeave:
1247 mouseLeave(*static_cast<const WebMouseEvent*>(&inputEvent));
1250 case WebInputEvent::MouseWheel:
1251 handled = mouseWheel(*static_cast<const WebMouseWheelEvent*>(&inputEvent));
1254 case WebInputEvent::MouseDown:
1255 mouseDown(*static_cast<const WebMouseEvent*>(&inputEvent));
1258 case WebInputEvent::MouseUp:
1259 mouseUp(*static_cast<const WebMouseEvent*>(&inputEvent));
1262 case WebInputEvent::RawKeyDown:
1263 case WebInputEvent::KeyDown:
1264 case WebInputEvent::KeyUp:
1265 handled = keyEvent(*static_cast<const WebKeyboardEvent*>(&inputEvent));
1268 case WebInputEvent::Char:
1269 handled = charEvent(*static_cast<const WebKeyboardEvent*>(&inputEvent));
1272 #if ENABLE(GESTURE_EVENTS)
1273 case WebInputEvent::GestureScrollBegin:
1274 case WebInputEvent::GestureScrollEnd:
1275 handled = gestureEvent(*static_cast<const WebGestureEvent*>(&inputEvent));
1279 #if ENABLE(TOUCH_EVENTS)
1280 case WebInputEvent::TouchStart:
1281 case WebInputEvent::TouchMove:
1282 case WebInputEvent::TouchEnd:
1283 case WebInputEvent::TouchCancel:
1284 handled = touchEvent(*static_cast<const WebTouchEvent*>(&inputEvent));
1292 m_currentInputEvent = 0;
1297 void WebViewImpl::mouseCaptureLost()
1299 m_mouseCaptureNode = 0;
1302 void WebViewImpl::setFocus(bool enable)
1304 m_page->focusController()->setFocused(enable);
1306 // Note that we don't call setActive() when disabled as this cause extra
1307 // focus/blur events to be dispatched.
1308 m_page->focusController()->setActive(true);
1309 RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
1311 Node* focusedNode = focusedFrame->document()->focusedNode();
1312 if (focusedNode && focusedNode->isElementNode()
1313 && focusedFrame->selection()->selection().isNone()) {
1314 // If the selection was cleared while the WebView was not
1315 // focused, then the focus element shows with a focus ring but
1316 // no caret and does respond to keyboard inputs.
1317 Element* element = static_cast<Element*>(focusedNode);
1318 if (element->isTextFormControl())
1319 element->updateFocusAppearance(true);
1320 else if (focusedNode->isContentEditable()) {
1321 // updateFocusAppearance() selects all the text of
1322 // contentseditable DIVs. So we set the selection explicitly
1323 // instead. Note that this has the side effect of moving the
1324 // caret back to the beginning of the text.
1325 Position position(focusedNode, 0,
1326 Position::PositionIsOffsetInAnchor);
1327 focusedFrame->selection()->setSelection(
1328 VisibleSelection(position, SEL_DEFAULT_AFFINITY));
1332 m_imeAcceptEvents = true;
1334 hideAutofillPopup();
1337 // Clear focus on the currently focused frame if any.
1341 Frame* frame = m_page->mainFrame();
1345 RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
1346 if (focusedFrame.get()) {
1347 // Finish an ongoing composition to delete the composition node.
1348 Editor* editor = focusedFrame->editor();
1349 if (editor && editor->hasComposition())
1350 editor->confirmComposition();
1351 m_imeAcceptEvents = false;
1356 bool WebViewImpl::setComposition(
1357 const WebString& text,
1358 const WebVector<WebCompositionUnderline>& underlines,
1362 Frame* focused = focusedWebCoreFrame();
1363 if (!focused || !m_imeAcceptEvents)
1365 Editor* editor = focused->editor();
1369 // The input focus has been moved to another WebWidget object.
1370 // We should use this |editor| object only to complete the ongoing
1372 if (!editor->canEdit() && !editor->hasComposition())
1375 // We should verify the parent node of this IME composition node are
1376 // editable because JavaScript may delete a parent node of the composition
1377 // node. In this case, WebKit crashes while deleting texts from the parent
1378 // node, which doesn't exist any longer.
1379 PassRefPtr<Range> range = editor->compositionRange();
1381 Node* node = range->startContainer();
1382 if (!node || !node->isContentEditable())
1386 // If we're not going to fire a keypress event, then the keydown event was
1387 // canceled. In that case, cancel any existing composition.
1388 if (text.isEmpty() || m_suppressNextKeypressEvent) {
1389 // A browser process sent an IPC message which does not contain a valid
1390 // string, which means an ongoing composition has been canceled.
1391 // If the ongoing composition has been canceled, replace the ongoing
1392 // composition string with an empty string and complete it.
1394 Vector<CompositionUnderline> emptyUnderlines;
1395 editor->setComposition(emptyString, emptyUnderlines, 0, 0);
1396 return text.isEmpty();
1399 // When the range of composition underlines overlap with the range between
1400 // selectionStart and selectionEnd, WebKit somehow won't paint the selection
1401 // at all (see InlineTextBox::paint() function in InlineTextBox.cpp).
1402 // But the selection range actually takes effect.
1403 editor->setComposition(String(text),
1404 CompositionUnderlineVectorBuilder(underlines),
1405 selectionStart, selectionEnd);
1407 return editor->hasComposition();
1410 bool WebViewImpl::confirmComposition()
1412 return confirmComposition(WebString());
1415 bool WebViewImpl::confirmComposition(const WebString& text)
1417 Frame* focused = focusedWebCoreFrame();
1418 if (!focused || !m_imeAcceptEvents)
1420 Editor* editor = focused->editor();
1421 if (!editor || (!editor->hasComposition() && !text.length()))
1424 // We should verify the parent node of this IME composition node are
1425 // editable because JavaScript may delete a parent node of the composition
1426 // node. In this case, WebKit crashes while deleting texts from the parent
1427 // node, which doesn't exist any longer.
1428 PassRefPtr<Range> range = editor->compositionRange();
1430 Node* node = range->startContainer();
1431 if (!node || !node->isContentEditable())
1435 if (editor->hasComposition()) {
1437 editor->confirmComposition(String(text));
1439 editor->confirmComposition();
1441 editor->insertText(String(text), 0);
1446 bool WebViewImpl::compositionRange(size_t* location, size_t* length)
1448 Frame* focused = focusedWebCoreFrame();
1449 if (!focused || !m_imeAcceptEvents)
1451 Editor* editor = focused->editor();
1452 if (!editor || !editor->hasComposition())
1455 RefPtr<Range> range = editor->compositionRange();
1459 if (TextIterator::locationAndLengthFromRange(range.get(), *location, *length))
1464 WebTextInputType WebViewImpl::textInputType()
1466 Node* node = focusedWebCoreNode();
1468 return WebTextInputTypeNone;
1470 if (node->nodeType() == Node::ELEMENT_NODE) {
1471 Element* element = static_cast<Element*>(node);
1472 if (element->hasLocalName(HTMLNames::inputTag)) {
1473 HTMLInputElement* input = static_cast<HTMLInputElement*>(element);
1475 if (input->readOnly() || input->disabled())
1476 return WebTextInputTypeNone;
1478 if (input->isPasswordField())
1479 return WebTextInputTypePassword;
1480 if (input->isSearchField())
1481 return WebTextInputTypeSearch;
1482 if (input->isEmailField())
1483 return WebTextInputTypeEmail;
1484 if (input->isNumberField())
1485 return WebTextInputTypeNumber;
1486 if (input->isTelephoneField())
1487 return WebTextInputTypeTelephone;
1488 if (input->isURLField())
1489 return WebTextInputTypeURL;
1490 if (input->isTextField())
1491 return WebTextInputTypeText;
1492 return WebTextInputTypeNone;
1495 if (element->hasLocalName(HTMLNames::textareaTag)) {
1496 HTMLTextAreaElement* textarea = static_cast<HTMLTextAreaElement*>(element);
1498 if (textarea->readOnly() || textarea->disabled())
1499 return WebTextInputTypeNone;
1500 return WebTextInputTypeText;
1504 // For other situations.
1505 if (node->shouldUseInputMethod())
1506 return WebTextInputTypeText;
1508 return WebTextInputTypeNone;
1511 WebRect WebViewImpl::caretOrSelectionBounds()
1514 const Frame* focused = focusedWebCoreFrame();
1518 FrameSelection* selection = focused->selection();
1522 const FrameView* view = focused->view();
1526 const Node* node = selection->base().containerNode();
1527 if (!node || !node->renderer())
1530 if (selection->isCaret())
1531 rect = view->contentsToWindow(selection->absoluteCaretBounds());
1532 else if (selection->isRange()) {
1533 node = selection->extent().containerNode();
1534 RefPtr<Range> range = selection->toNormalizedRange();
1535 if (!node || !node->renderer() || !range)
1537 rect = view->contentsToWindow(focused->editor()->firstRectForRange(range.get()));
1542 bool WebViewImpl::selectionRange(WebPoint& start, WebPoint& end) const
1544 const Frame* frame = focusedWebCoreFrame();
1545 if (!frame || !frame->selection()->isRange())
1547 RefPtr<Range> selectedRange = frame->selection()->toNormalizedRange();
1550 RefPtr<Range> range(Range::create(selectedRange->startContainer()->document(),
1551 selectedRange->startContainer(),
1552 selectedRange->startOffset(),
1553 selectedRange->startContainer(),
1554 selectedRange->startOffset()));
1556 IntRect rect = frame->editor()->firstRectForRange(range.get());
1558 start.y = rect.y() + rect.height() - 1;
1560 range = Range::create(selectedRange->endContainer()->document(),
1561 selectedRange->endContainer(),
1562 selectedRange->endOffset(),
1563 selectedRange->endContainer(),
1564 selectedRange->endOffset());
1566 rect = frame->editor()->firstRectForRange(range.get());
1567 end.x = rect.x() + rect.width() - 1;
1568 end.y = rect.y() + rect.height() - 1;
1570 start = frame->view()->contentsToWindow(start);
1571 end = frame->view()->contentsToWindow(end);
1575 bool WebViewImpl::caretOrSelectionRange(size_t* location, size_t* length)
1577 const Frame* focused = focusedWebCoreFrame();
1581 FrameSelection* selection = focused->selection();
1585 RefPtr<Range> range = selection->selection().firstRange();
1589 if (TextIterator::locationAndLengthFromRange(range.get(), *location, *length))
1594 void WebViewImpl::setTextDirection(WebTextDirection direction)
1596 // The Editor::setBaseWritingDirection() function checks if we can change
1597 // the text direction of the selected node and updates its DOM "dir"
1598 // attribute and its CSS "direction" property.
1599 // So, we just call the function as Safari does.
1600 const Frame* focused = focusedWebCoreFrame();
1604 Editor* editor = focused->editor();
1605 if (!editor || !editor->canEdit())
1608 switch (direction) {
1609 case WebTextDirectionDefault:
1610 editor->setBaseWritingDirection(NaturalWritingDirection);
1613 case WebTextDirectionLeftToRight:
1614 editor->setBaseWritingDirection(LeftToRightWritingDirection);
1617 case WebTextDirectionRightToLeft:
1618 editor->setBaseWritingDirection(RightToLeftWritingDirection);
1627 bool WebViewImpl::isAcceleratedCompositingActive() const
1629 #if USE(ACCELERATED_COMPOSITING)
1630 return m_isAcceleratedCompositingActive;
1636 // WebView --------------------------------------------------------------------
1638 WebSettings* WebViewImpl::settings()
1641 m_webSettings = adoptPtr(new WebSettingsImpl(m_page->settings()));
1642 ASSERT(m_webSettings.get());
1643 return m_webSettings.get();
1646 WebString WebViewImpl::pageEncoding() const
1651 return m_page->mainFrame()->document()->loader()->writer()->encoding();
1654 void WebViewImpl::setPageEncoding(const WebString& encodingName)
1659 // Only change override encoding, don't change default encoding.
1660 // Note that the new encoding must be 0 if it isn't supposed to be set.
1661 String newEncodingName;
1662 if (!encodingName.isEmpty())
1663 newEncodingName = encodingName;
1664 m_page->mainFrame()->loader()->reloadWithOverrideEncoding(newEncodingName);
1667 bool WebViewImpl::dispatchBeforeUnloadEvent()
1669 // FIXME: This should really cause a recursive depth-first walk of all
1670 // frames in the tree, calling each frame's onbeforeunload. At the moment,
1671 // we're consistent with Safari 3.1, not IE/FF.
1672 Frame* frame = m_page->mainFrame();
1676 return frame->loader()->shouldClose();
1679 void WebViewImpl::dispatchUnloadEvent()
1681 // Run unload handlers.
1682 m_page->mainFrame()->loader()->closeURL();
1685 WebFrame* WebViewImpl::mainFrame()
1687 return mainFrameImpl();
1690 WebFrame* WebViewImpl::findFrameByName(
1691 const WebString& name, WebFrame* relativeToFrame)
1693 if (!relativeToFrame)
1694 relativeToFrame = mainFrame();
1695 Frame* frame = static_cast<WebFrameImpl*>(relativeToFrame)->frame();
1696 frame = frame->tree()->find(name);
1697 return WebFrameImpl::fromFrame(frame);
1700 WebFrame* WebViewImpl::focusedFrame()
1702 return WebFrameImpl::fromFrame(focusedWebCoreFrame());
1705 void WebViewImpl::setFocusedFrame(WebFrame* frame)
1708 // Clears the focused frame if any.
1709 Frame* frame = focusedWebCoreFrame();
1711 frame->selection()->setFocused(false);
1714 WebFrameImpl* frameImpl = static_cast<WebFrameImpl*>(frame);
1715 Frame* webcoreFrame = frameImpl->frame();
1716 webcoreFrame->page()->focusController()->setFocusedFrame(webcoreFrame);
1719 void WebViewImpl::setInitialFocus(bool reverse)
1724 // Since we don't have a keyboard event, we'll create one.
1725 WebKeyboardEvent keyboardEvent;
1726 keyboardEvent.type = WebInputEvent::RawKeyDown;
1728 keyboardEvent.modifiers = WebInputEvent::ShiftKey;
1730 // VK_TAB which is only defined on Windows.
1731 keyboardEvent.windowsKeyCode = 0x09;
1732 PlatformKeyboardEventBuilder platformEvent(keyboardEvent);
1733 RefPtr<KeyboardEvent> webkitEvent = KeyboardEvent::create(platformEvent, 0);
1735 Frame* frame = page()->focusController()->focusedOrMainFrame();
1736 if (Document* document = frame->document())
1737 document->setFocusedNode(0);
1738 page()->focusController()->setInitialFocus(
1739 reverse ? FocusDirectionBackward : FocusDirectionForward,
1743 void WebViewImpl::clearFocusedNode()
1748 RefPtr<Frame> frame = m_page->mainFrame();
1752 RefPtr<Document> document = frame->document();
1753 if (!document.get())
1756 RefPtr<Node> oldFocusedNode = document->focusedNode();
1758 // Clear the focused node.
1759 document->setFocusedNode(0);
1761 if (!oldFocusedNode.get())
1764 // If a text field has focus, we need to make sure the selection controller
1765 // knows to remove selection from it. Otherwise, the text field is still
1766 // processing keyboard events even though focus has been moved to the page and
1767 // keystrokes get eaten as a result.
1768 if (oldFocusedNode->hasTagName(HTMLNames::textareaTag)
1769 || (oldFocusedNode->hasTagName(HTMLNames::inputTag)
1770 && static_cast<HTMLInputElement*>(oldFocusedNode.get())->isTextField())) {
1771 frame->selection()->clear();
1775 void WebViewImpl::scrollFocusedNodeIntoView()
1777 Node* focusedNode = focusedWebCoreNode();
1778 if (focusedNode && focusedNode->isElementNode()) {
1779 Element* elementNode = static_cast<Element*>(focusedNode);
1780 elementNode->scrollIntoViewIfNeeded(true);
1784 double WebViewImpl::zoomLevel()
1789 double WebViewImpl::setZoomLevel(bool textOnly, double zoomLevel)
1791 if (zoomLevel < m_minimumZoomLevel)
1792 m_zoomLevel = m_minimumZoomLevel;
1793 else if (zoomLevel > m_maximumZoomLevel)
1794 m_zoomLevel = m_maximumZoomLevel;
1796 m_zoomLevel = zoomLevel;
1798 Frame* frame = mainFrameImpl()->frame();
1799 WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1800 if (pluginContainer)
1801 pluginContainer->plugin()->setZoomLevel(m_zoomLevel, textOnly);
1803 float zoomFactor = static_cast<float>(zoomLevelToZoomFactor(m_zoomLevel));
1805 frame->setPageAndTextZoomFactors(1, zoomFactor);
1807 frame->setPageAndTextZoomFactors(zoomFactor, 1);
1812 void WebViewImpl::zoomLimitsChanged(double minimumZoomLevel,
1813 double maximumZoomLevel)
1815 m_minimumZoomLevel = minimumZoomLevel;
1816 m_maximumZoomLevel = maximumZoomLevel;
1817 m_client->zoomLimitsChanged(m_minimumZoomLevel, m_maximumZoomLevel);
1820 void WebViewImpl::fullFramePluginZoomLevelChanged(double zoomLevel)
1822 if (zoomLevel == m_zoomLevel)
1825 m_zoomLevel = max(min(zoomLevel, m_maximumZoomLevel), m_minimumZoomLevel);
1826 m_client->zoomLevelChanged();
1829 double WebView::zoomLevelToZoomFactor(double zoomLevel)
1831 return pow(textSizeMultiplierRatio, zoomLevel);
1834 double WebView::zoomFactorToZoomLevel(double factor)
1836 // Since factor = 1.2^level, level = log(factor) / log(1.2)
1837 return log(factor) / log(textSizeMultiplierRatio);
1840 void WebViewImpl::scalePage(float scaleFactor, WebPoint origin)
1845 Frame* frame = page()->mainFrame();
1849 frame->scalePage(scaleFactor, origin);
1852 void WebViewImpl::performMediaPlayerAction(const WebMediaPlayerAction& action,
1853 const WebPoint& location)
1855 HitTestResult result = hitTestResultForWindowPos(location);
1856 RefPtr<Node> node = result.innerNonSharedNode();
1857 if (!node->hasTagName(HTMLNames::videoTag) && !node->hasTagName(HTMLNames::audioTag))
1860 RefPtr<HTMLMediaElement> mediaElement =
1861 static_pointer_cast<HTMLMediaElement>(node);
1862 switch (action.type) {
1863 case WebMediaPlayerAction::Play:
1865 mediaElement->play();
1867 mediaElement->pause();
1869 case WebMediaPlayerAction::Mute:
1870 mediaElement->setMuted(action.enable);
1872 case WebMediaPlayerAction::Loop:
1873 mediaElement->setLoop(action.enable);
1875 case WebMediaPlayerAction::Controls:
1876 mediaElement->setControls(action.enable);
1879 ASSERT_NOT_REACHED();
1883 void WebViewImpl::copyImageAt(const WebPoint& point)
1888 HitTestResult result = hitTestResultForWindowPos(point);
1890 if (result.absoluteImageURL().isEmpty()) {
1891 // There isn't actually an image at these coordinates. Might be because
1892 // the window scrolled while the context menu was open or because the page
1893 // changed itself between when we thought there was an image here and when
1894 // we actually tried to retreive the image.
1896 // FIXME: implement a cache of the most recent HitTestResult to avoid having
1897 // to do two hit tests.
1901 m_page->mainFrame()->editor()->copyImage(result);
1904 void WebViewImpl::dragSourceEndedAt(
1905 const WebPoint& clientPoint,
1906 const WebPoint& screenPoint,
1907 WebDragOperation operation)
1909 PlatformMouseEvent pme(clientPoint,
1911 LeftButton, MouseEventMoved, 0, false, false, false,
1913 m_page->mainFrame()->eventHandler()->dragSourceEndedAt(pme,
1914 static_cast<DragOperation>(operation));
1915 m_dragScrollTimer->stop();
1918 void WebViewImpl::dragSourceMovedTo(
1919 const WebPoint& clientPoint,
1920 const WebPoint& screenPoint,
1921 WebDragOperation operation)
1923 m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
1926 void WebViewImpl::dragSourceSystemDragEnded()
1928 // It's possible for us to get this callback while not doing a drag if
1929 // it's from a previous page that got unloaded.
1930 if (m_doingDragAndDrop) {
1931 m_page->dragController()->dragEnded();
1932 m_doingDragAndDrop = false;
1936 WebDragOperation WebViewImpl::dragTargetDragEnter(
1937 const WebDragData& webDragData,
1938 const WebPoint& clientPoint,
1939 const WebPoint& screenPoint,
1940 WebDragOperationsMask operationsAllowed)
1942 ASSERT(!m_currentDragData.get());
1944 m_currentDragData = webDragData;
1945 m_operationsAllowed = operationsAllowed;
1947 return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragEnter);
1950 WebDragOperation WebViewImpl::dragTargetDragOver(
1951 const WebPoint& clientPoint,
1952 const WebPoint& screenPoint,
1953 WebDragOperationsMask operationsAllowed)
1955 m_operationsAllowed = operationsAllowed;
1957 return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragOver);
1960 void WebViewImpl::dragTargetDragLeave()
1962 ASSERT(m_currentDragData.get());
1965 m_currentDragData.get(),
1968 static_cast<DragOperation>(m_operationsAllowed));
1970 m_page->dragController()->dragExited(&dragData);
1972 // FIXME: why is the drag scroll timer not stopped here?
1974 m_dragOperation = WebDragOperationNone;
1975 m_currentDragData = 0;
1978 void WebViewImpl::dragTargetDrop(const WebPoint& clientPoint,
1979 const WebPoint& screenPoint)
1981 ASSERT(m_currentDragData.get());
1983 // If this webview transitions from the "drop accepting" state to the "not
1984 // accepting" state, then our IPC message reply indicating that may be in-
1985 // flight, or else delayed by javascript processing in this webview. If a
1986 // drop happens before our IPC reply has reached the browser process, then
1987 // the browser forwards the drop to this webview. So only allow a drop to
1988 // proceed if our webview m_dragOperation state is not DragOperationNone.
1990 if (m_dragOperation == WebDragOperationNone) { // IPC RACE CONDITION: do not allow this drop.
1991 dragTargetDragLeave();
1996 m_currentDragData.get(),
1999 static_cast<DragOperation>(m_operationsAllowed));
2001 m_page->dragController()->performDrag(&dragData);
2003 m_dragOperation = WebDragOperationNone;
2004 m_currentDragData = 0;
2006 m_dragScrollTimer->stop();
2009 WebDragOperation WebViewImpl::dragTargetDragEnterOrOver(const WebPoint& clientPoint, const WebPoint& screenPoint, DragAction dragAction)
2011 ASSERT(m_currentDragData.get());
2014 m_currentDragData.get(),
2017 static_cast<DragOperation>(m_operationsAllowed));
2019 DragOperation dropEffect;
2020 if (dragAction == DragEnter)
2021 dropEffect = m_page->dragController()->dragEntered(&dragData);
2023 dropEffect = m_page->dragController()->dragUpdated(&dragData);
2025 // Mask the drop effect operation against the drag source's allowed operations.
2026 if (!(dropEffect & dragData.draggingSourceOperationMask()))
2027 dropEffect = DragOperationNone;
2029 m_dragOperation = static_cast<WebDragOperation>(dropEffect);
2031 if (dragAction == DragOver)
2032 m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
2034 m_dragScrollTimer->stop();
2036 return m_dragOperation;
2039 unsigned long WebViewImpl::createUniqueIdentifierForRequest()
2042 return m_page->progress()->createUniqueIdentifier();
2046 void WebViewImpl::inspectElementAt(const WebPoint& point)
2051 if (point.x == -1 || point.y == -1)
2052 m_page->inspectorController()->inspect(0);
2054 HitTestResult result = hitTestResultForWindowPos(point);
2056 if (!result.innerNonSharedNode())
2059 m_page->inspectorController()->inspect(result.innerNonSharedNode());
2063 WebString WebViewImpl::inspectorSettings() const
2065 return m_inspectorSettings;
2068 void WebViewImpl::setInspectorSettings(const WebString& settings)
2070 m_inspectorSettings = settings;
2073 bool WebViewImpl::inspectorSetting(const WebString& key, WebString* value) const
2075 if (!m_inspectorSettingsMap->contains(key))
2077 *value = m_inspectorSettingsMap->get(key);
2081 void WebViewImpl::setInspectorSetting(const WebString& key,
2082 const WebString& value)
2084 m_inspectorSettingsMap->set(key, value);
2085 client()->didUpdateInspectorSetting(key, value);
2088 WebDevToolsAgent* WebViewImpl::devToolsAgent()
2090 return m_devToolsAgent.get();
2093 WebAccessibilityObject WebViewImpl::accessibilityObject()
2095 if (!mainFrameImpl())
2096 return WebAccessibilityObject();
2098 Document* document = mainFrameImpl()->frame()->document();
2099 return WebAccessibilityObject(
2100 document->axObjectCache()->getOrCreate(document->renderer()));
2103 void WebViewImpl::applyAutofillSuggestions(
2104 const WebNode& node,
2105 const WebVector<WebString>& names,
2106 const WebVector<WebString>& labels,
2107 const WebVector<WebString>& icons,
2108 const WebVector<int>& uniqueIDs,
2111 ASSERT(names.size() == labels.size());
2112 ASSERT(names.size() == uniqueIDs.size());
2113 ASSERT(separatorIndex < static_cast<int>(names.size()));
2115 if (names.isEmpty()) {
2116 hideAutofillPopup();
2120 RefPtr<Node> focusedNode = focusedWebCoreNode();
2121 // If the node for which we queried the Autofill suggestions is not the
2122 // focused node, then we have nothing to do. FIXME: also check the
2123 // caret is at the end and that the text has not changed.
2124 if (!focusedNode || focusedNode != PassRefPtr<Node>(node)) {
2125 hideAutofillPopup();
2129 HTMLInputElement* inputElem =
2130 static_cast<HTMLInputElement*>(focusedNode.get());
2132 // The first time the Autofill popup is shown we'll create the client and
2134 if (!m_autofillPopupClient)
2135 m_autofillPopupClient = adoptPtr(new AutofillPopupMenuClient);
2137 m_autofillPopupClient->initialize(
2138 inputElem, names, labels, icons, uniqueIDs, separatorIndex);
2140 if (!m_autofillPopup.get()) {
2141 m_autofillPopup = PopupContainer::create(m_autofillPopupClient.get(),
2142 PopupContainer::Suggestion,
2143 autofillPopupSettings);
2146 if (m_autofillPopupShowing) {
2147 refreshAutofillPopup();
2149 m_autofillPopup->showInRect(focusedNode->getRect(), focusedNode->ownerDocument()->view(), 0);
2150 m_autofillPopupShowing = true;
2154 void WebViewImpl::hidePopups()
2157 hideAutofillPopup();
2160 void WebViewImpl::performCustomContextMenuAction(unsigned action)
2164 ContextMenu* menu = m_page->contextMenuController()->contextMenu();
2167 ContextMenuItem* item = menu->itemWithAction(static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + action));
2169 m_page->contextMenuController()->contextMenuItemSelected(item);
2170 m_page->contextMenuController()->clearContextMenu();
2173 // WebView --------------------------------------------------------------------
2175 void WebViewImpl::setIsTransparent(bool isTransparent)
2177 // Set any existing frames to be transparent.
2178 Frame* frame = m_page->mainFrame();
2180 frame->view()->setTransparent(isTransparent);
2181 frame = frame->tree()->traverseNext();
2184 // Future frames check this to know whether to be transparent.
2185 m_isTransparent = isTransparent;
2188 bool WebViewImpl::isTransparent() const
2190 return m_isTransparent;
2193 void WebViewImpl::setIsActive(bool active)
2195 if (page() && page()->focusController())
2196 page()->focusController()->setActive(active);
2199 bool WebViewImpl::isActive() const
2201 return (page() && page()->focusController()) ? page()->focusController()->isActive() : false;
2204 void WebViewImpl::setDomainRelaxationForbidden(bool forbidden, const WebString& scheme)
2206 SecurityOrigin::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme));
2209 void WebViewImpl::setScrollbarColors(unsigned inactiveColor,
2210 unsigned activeColor,
2211 unsigned trackColor) {
2212 #if OS(UNIX) && !OS(DARWIN)
2213 PlatformThemeChromiumGtk::setScrollbarColors(inactiveColor,
2219 void WebViewImpl::setSelectionColors(unsigned activeBackgroundColor,
2220 unsigned activeForegroundColor,
2221 unsigned inactiveBackgroundColor,
2222 unsigned inactiveForegroundColor) {
2223 #if OS(UNIX) && !OS(DARWIN)
2224 RenderThemeChromiumLinux::setSelectionColors(activeBackgroundColor,
2225 activeForegroundColor,
2226 inactiveBackgroundColor,
2227 inactiveForegroundColor);
2228 theme()->platformColorsDidChange();
2232 void WebView::addUserScript(const WebString& sourceCode,
2233 const WebVector<WebString>& patternsIn,
2234 WebView::UserScriptInjectAt injectAt,
2235 WebView::UserContentInjectIn injectIn)
2237 OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2238 for (size_t i = 0; i < patternsIn.size(); ++i)
2239 patterns->append(patternsIn[i]);
2241 PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2242 RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
2243 pageGroup->addUserScriptToWorld(world.get(), sourceCode, WebURL(), patterns.release(), nullptr,
2244 static_cast<UserScriptInjectionTime>(injectAt),
2245 static_cast<UserContentInjectedFrames>(injectIn));
2248 void WebView::addUserStyleSheet(const WebString& sourceCode,
2249 const WebVector<WebString>& patternsIn,
2250 WebView::UserContentInjectIn injectIn,
2251 WebView::UserStyleInjectionTime injectionTime)
2253 OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2254 for (size_t i = 0; i < patternsIn.size(); ++i)
2255 patterns->append(patternsIn[i]);
2257 PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2258 RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
2260 // FIXME: Current callers always want the level to be "author". It probably makes sense to let
2261 // callers specify this though, since in other cases the caller will probably want "user" level.
2263 // FIXME: It would be nice to populate the URL correctly, instead of passing an empty URL.
2264 pageGroup->addUserStyleSheetToWorld(world.get(), sourceCode, WebURL(), patterns.release(), nullptr,
2265 static_cast<UserContentInjectedFrames>(injectIn),
2266 UserStyleAuthorLevel,
2267 static_cast<WebCore::UserStyleInjectionTime>(injectionTime));
2270 void WebView::removeAllUserContent()
2272 PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2273 pageGroup->removeAllUserContent();
2276 void WebViewImpl::didCommitLoad(bool* isNewNavigation)
2278 if (isNewNavigation)
2279 *isNewNavigation = m_observedNewNavigation;
2282 ASSERT(!m_observedNewNavigation
2283 || m_page->mainFrame()->loader()->documentLoader() == m_newNavigationLoader);
2284 m_newNavigationLoader = 0;
2286 m_observedNewNavigation = false;
2289 bool WebViewImpl::useExternalPopupMenus()
2291 return shouldUseExternalPopupMenus;
2294 bool WebViewImpl::navigationPolicyFromMouseEvent(unsigned short button,
2295 bool ctrl, bool shift,
2296 bool alt, bool meta,
2297 WebNavigationPolicy* policy)
2300 const bool newTabModifier = (button == 1) || meta;
2302 const bool newTabModifier = (button == 1) || ctrl;
2304 if (!newTabModifier && !shift && !alt)
2308 if (newTabModifier) {
2310 *policy = WebNavigationPolicyNewForegroundTab;
2312 *policy = WebNavigationPolicyNewBackgroundTab;
2315 *policy = WebNavigationPolicyNewWindow;
2317 *policy = WebNavigationPolicyDownload;
2322 void WebViewImpl::startDragging(const WebDragData& dragData,
2323 WebDragOperationsMask mask,
2324 const WebImage& dragImage,
2325 const WebPoint& dragImageOffset)
2329 ASSERT(!m_doingDragAndDrop);
2330 m_doingDragAndDrop = true;
2331 m_client->startDragging(dragData, mask, dragImage, dragImageOffset);
2334 void WebViewImpl::observeNewNavigation()
2336 m_observedNewNavigation = true;
2338 m_newNavigationLoader = m_page->mainFrame()->loader()->documentLoader();
2342 void WebViewImpl::setIgnoreInputEvents(bool newValue)
2344 ASSERT(m_ignoreInputEvents != newValue);
2345 m_ignoreInputEvents = newValue;
2348 void WebViewImpl::setPageOverlayClient(PageOverlay::PageOverlayClient* pageOverlayClient)
2350 if (pageOverlayClient) {
2352 m_pageOverlay = PageOverlay::create(this, pageOverlayClient);
2354 m_pageOverlay->setClient(pageOverlayClient);
2355 m_pageOverlay->update();
2356 setRootLayerNeedsDisplay();
2358 if (m_pageOverlay) {
2359 m_pageOverlay->clear();
2360 m_pageOverlay = nullptr;
2361 setRootLayerNeedsDisplay();
2366 void WebViewImpl::setOverlayLayer(WebCore::GraphicsLayer* layer)
2368 if (m_rootGraphicsLayer) {
2369 if (layer->parent() != m_rootGraphicsLayer)
2370 m_rootGraphicsLayer->addChild(layer);
2374 #if ENABLE(NOTIFICATIONS)
2375 NotificationPresenterImpl* WebViewImpl::notificationPresenterImpl()
2377 if (!m_notificationPresenter.isInitialized() && m_client)
2378 m_notificationPresenter.initialize(m_client->notificationPresenter());
2379 return &m_notificationPresenter;
2383 void WebViewImpl::refreshAutofillPopup()
2385 ASSERT(m_autofillPopupShowing);
2387 // Hide the popup if it has become empty.
2388 if (!m_autofillPopupClient->listSize()) {
2389 hideAutofillPopup();
2393 IntRect oldBounds = m_autofillPopup->frameRect();
2394 m_autofillPopup->refresh(focusedWebCoreNode()->getRect());
2395 IntRect newBounds = m_autofillPopup->frameRect();
2396 // Let's resize the backing window if necessary.
2397 if (oldBounds != newBounds) {
2398 WebPopupMenuImpl* popupMenu =
2399 static_cast<WebPopupMenuImpl*>(m_autofillPopup->client());
2401 popupMenu->client()->setWindowRect(m_chromeClientImpl.windowToScreen(newBounds));
2405 Node* WebViewImpl::focusedWebCoreNode()
2407 Frame* frame = m_page->focusController()->focusedFrame();
2411 Document* document = frame->document();
2415 return document->focusedNode();
2418 HitTestResult WebViewImpl::hitTestResultForWindowPos(const IntPoint& pos)
2420 IntPoint docPoint(m_page->mainFrame()->view()->windowToContents(pos));
2421 return m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(docPoint, false);
2424 void WebViewImpl::setTabsToLinks(bool enable)
2426 m_tabsToLinks = enable;
2429 bool WebViewImpl::tabsToLinks() const
2431 return m_tabsToLinks;
2434 #if USE(ACCELERATED_COMPOSITING)
2435 bool WebViewImpl::allowsAcceleratedCompositing()
2437 return !m_compositorCreationFailed;
2440 bool WebViewImpl::pageHasRTLStyle() const
2444 Document* document = page()->mainFrame()->document();
2447 RenderView* renderView = document->renderView();
2450 RenderStyle* style = renderView->style();
2453 return (style->direction() == RTL);
2456 void WebViewImpl::setRootGraphicsLayer(WebCore::GraphicsLayer* layer)
2458 m_rootGraphicsLayer = layer;
2459 setRootPlatformLayer(layer ? layer->platformLayer() : 0);
2462 void WebViewImpl::setRootPlatformLayer(WebCore::PlatformLayer* layer)
2464 setIsAcceleratedCompositingActive(layer);
2465 if (m_layerTreeHost)
2466 m_layerTreeHost->setRootLayer(layer);
2468 IntRect damagedRect(0, 0, m_size.width, m_size.height);
2469 if (m_isAcceleratedCompositingActive)
2470 invalidateRootLayerRect(damagedRect);
2472 m_client->didInvalidateRect(damagedRect);
2475 void WebViewImpl::setRootLayerNeedsDisplay()
2477 #if USE(THREADED_COMPOSITING)
2478 if (m_layerTreeHost)
2479 m_layerTreeHost->setNeedsCommitAndRedraw();
2481 m_client->scheduleComposite();
2485 void WebViewImpl::scrollRootLayerRect(const IntSize& scrollDelta, const IntRect& clipRect)
2487 updateLayerTreeViewport();
2488 setRootLayerNeedsDisplay();
2491 void WebViewImpl::invalidateRootLayerRect(const IntRect& rect)
2493 ASSERT(m_layerTreeHost);
2498 FrameView* view = page()->mainFrame()->view();
2499 IntRect dirtyRect = view->windowToContents(rect);
2500 updateLayerTreeViewport();
2501 m_layerTreeHost->invalidateRootLayerRect(dirtyRect);
2502 setRootLayerNeedsDisplay();
2505 class WebViewImplContentPainter : public LayerPainterChromium {
2506 WTF_MAKE_NONCOPYABLE(WebViewImplContentPainter);
2508 static PassOwnPtr<WebViewImplContentPainter*> create(WebViewImpl* webViewImpl)
2510 return adoptPtr(new WebViewImplContentPainter(webViewImpl));
2513 virtual void paint(GraphicsContext& context, const IntRect& contentRect)
2515 double paintStart = currentTime();
2516 Page* page = m_webViewImpl->page();
2519 FrameView* view = page->mainFrame()->view();
2520 view->paintContents(&context, contentRect);
2521 double paintEnd = currentTime();
2522 double pixelsPerSec = (contentRect.width() * contentRect.height()) / (paintEnd - paintStart);
2523 PlatformBridge::histogramCustomCounts("Renderer4.AccelRootPaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30);
2524 PlatformBridge::histogramCustomCounts("Renderer4.AccelRootPaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30);
2528 explicit WebViewImplContentPainter(WebViewImpl* webViewImpl)
2529 : m_webViewImpl(webViewImpl)
2533 WebViewImpl* m_webViewImpl;
2536 void WebViewImpl::setIsAcceleratedCompositingActive(bool active)
2538 PlatformBridge::histogramEnumeration("GPU.setIsAcceleratedCompositingActive", active * 2 + m_isAcceleratedCompositingActive, 4);
2540 if (m_isAcceleratedCompositingActive == active)
2544 m_isAcceleratedCompositingActive = false;
2545 // We need to finish all GL rendering before sending
2546 // didActivateAcceleratedCompositing(false) to prevent
2547 // flickering when compositing turns off.
2548 if (m_layerTreeHost)
2549 m_layerTreeHost->finishAllRendering();
2550 m_client->didActivateAcceleratedCompositing(false);
2551 } else if (m_layerTreeHost) {
2552 m_isAcceleratedCompositingActive = true;
2553 updateLayerTreeViewport();
2555 m_client->didActivateAcceleratedCompositing(true);
2557 TRACE_EVENT("WebViewImpl::setIsAcceleratedCompositingActive(true)", this, 0);
2559 WebCore::CCSettings ccSettings;
2560 ccSettings.acceleratePainting = page()->settings()->acceleratedDrawingEnabled();
2561 ccSettings.compositeOffscreen = settings()->compositeToTextureEnabled();
2562 ccSettings.showFPSCounter = settings()->showFPSCounter();
2563 ccSettings.showPlatformLayerTree = settings()->showPlatformLayerTree();
2565 m_layerTreeHost = CCLayerTreeHost::create(this, ccSettings);
2566 if (m_layerTreeHost) {
2567 m_client->didActivateAcceleratedCompositing(true);
2568 m_isAcceleratedCompositingActive = true;
2569 m_compositorCreationFailed = false;
2571 m_pageOverlay->update();
2573 m_isAcceleratedCompositingActive = false;
2574 m_client->didActivateAcceleratedCompositing(false);
2575 m_compositorCreationFailed = true;
2579 page()->mainFrame()->view()->setClipsRepaints(!m_isAcceleratedCompositingActive);
2584 PassRefPtr<GraphicsContext3D> WebViewImpl::createLayerTreeHostContext3D()
2586 RefPtr<GraphicsContext3D> context = m_temporaryOnscreenGraphicsContext3D.release();
2588 context = GraphicsContext3D::create(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2590 context->reshape(max(1, m_size.width), max(1, m_size.height));
2595 PassOwnPtr<LayerPainterChromium> WebViewImpl::createRootLayerPainter()
2597 return WebViewImplContentPainter::create(this);
2600 void WebViewImpl::animateAndLayout(double frameBeginTime)
2602 animate(frameBeginTime);
2606 void WebViewImpl::didRecreateGraphicsContext(bool success)
2608 setRootPlatformLayer(success ? m_layerTreeHost->rootLayer() : 0);
2611 // Forces ViewHostMsg_DidActivateAcceleratedCompositing to be sent so
2612 // that the browser process can reacquire surfaces.
2613 m_client->didActivateAcceleratedCompositing(true);
2615 m_pageOverlay->update();
2619 #if !USE(THREADED_COMPOSITING)
2620 void WebViewImpl::scheduleComposite()
2622 m_client->scheduleComposite();
2626 void WebViewImpl::updateLayerTreeViewport()
2631 FrameView* view = page()->mainFrame()->view();
2632 IntRect contentRect = view->visibleContentRect(false);
2633 IntRect visibleRect = view->visibleContentRect(true);
2634 IntPoint scroll(view->scrollX(), view->scrollY());
2636 m_layerTreeHost->setViewport(visibleRect, contentRect, scroll);
2639 WebGraphicsContext3D* WebViewImpl::graphicsContext3D()
2641 #if USE(ACCELERATED_COMPOSITING)
2642 if (m_page->settings()->acceleratedCompositingEnabled() && allowsAcceleratedCompositing()) {
2643 if (m_layerTreeHost) {
2644 WebGraphicsContext3D* webContext = GraphicsContext3DInternal::extractWebGraphicsContext3D(m_layerTreeHost->context());
2645 if (webContext && !webContext->isContextLost())
2648 if (m_temporaryOnscreenGraphicsContext3D) {
2649 WebGraphicsContext3D* webContext = GraphicsContext3DInternal::extractWebGraphicsContext3D(m_temporaryOnscreenGraphicsContext3D.get());
2650 if (webContext && !webContext->isContextLost())
2653 m_temporaryOnscreenGraphicsContext3D = GraphicsContext3D::create(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2654 if (m_temporaryOnscreenGraphicsContext3D)
2655 m_temporaryOnscreenGraphicsContext3D->reshape(max(1, m_size.width), max(1, m_size.height));
2656 return GraphicsContext3DInternal::extractWebGraphicsContext3D(m_temporaryOnscreenGraphicsContext3D.get());
2663 void WebViewImpl::setVisibilityState(WebPageVisibilityState visibilityState,
2664 bool isInitialState) {
2668 #if ENABLE(PAGE_VISIBILITY_API)
2669 ASSERT(visibilityState == WebPageVisibilityStateVisible
2670 || visibilityState == WebPageVisibilityStateHidden
2671 || visibilityState == WebPageVisibilityStatePrerender);
2672 m_page->setVisibilityState(static_cast<PageVisibilityState>(static_cast<int>(visibilityState)), isInitialState);
2675 #if USE(ACCELERATED_COMPOSITING)
2676 if (isAcceleratedCompositingActive())
2677 m_layerTreeHost->setVisible(visibilityState == WebPageVisibilityStateVisible);
2681 #if ENABLE(GESTURE_RECOGNIZER)
2682 void WebViewImpl::resetGestureRecognizer()
2684 m_gestureRecognizer->reset();
2689 } // namespace WebKit