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 case WebInputEvent::GestureTap:
1276 handled = gestureEvent(*static_cast<const WebGestureEvent*>(&inputEvent));
1280 #if ENABLE(TOUCH_EVENTS)
1281 case WebInputEvent::TouchStart:
1282 case WebInputEvent::TouchMove:
1283 case WebInputEvent::TouchEnd:
1284 case WebInputEvent::TouchCancel:
1285 handled = touchEvent(*static_cast<const WebTouchEvent*>(&inputEvent));
1293 m_currentInputEvent = 0;
1298 void WebViewImpl::mouseCaptureLost()
1300 m_mouseCaptureNode = 0;
1303 void WebViewImpl::setFocus(bool enable)
1305 m_page->focusController()->setFocused(enable);
1307 // Note that we don't call setActive() when disabled as this cause extra
1308 // focus/blur events to be dispatched.
1309 m_page->focusController()->setActive(true);
1310 RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
1312 Node* focusedNode = focusedFrame->document()->focusedNode();
1313 if (focusedNode && focusedNode->isElementNode()
1314 && focusedFrame->selection()->selection().isNone()) {
1315 // If the selection was cleared while the WebView was not
1316 // focused, then the focus element shows with a focus ring but
1317 // no caret and does respond to keyboard inputs.
1318 Element* element = static_cast<Element*>(focusedNode);
1319 if (element->isTextFormControl())
1320 element->updateFocusAppearance(true);
1321 else if (focusedNode->isContentEditable()) {
1322 // updateFocusAppearance() selects all the text of
1323 // contentseditable DIVs. So we set the selection explicitly
1324 // instead. Note that this has the side effect of moving the
1325 // caret back to the beginning of the text.
1326 Position position(focusedNode, 0,
1327 Position::PositionIsOffsetInAnchor);
1328 focusedFrame->selection()->setSelection(
1329 VisibleSelection(position, SEL_DEFAULT_AFFINITY));
1333 m_imeAcceptEvents = true;
1335 hideAutofillPopup();
1338 // Clear focus on the currently focused frame if any.
1342 Frame* frame = m_page->mainFrame();
1346 RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
1347 if (focusedFrame.get()) {
1348 // Finish an ongoing composition to delete the composition node.
1349 Editor* editor = focusedFrame->editor();
1350 if (editor && editor->hasComposition())
1351 editor->confirmComposition();
1352 m_imeAcceptEvents = false;
1357 bool WebViewImpl::setComposition(
1358 const WebString& text,
1359 const WebVector<WebCompositionUnderline>& underlines,
1363 Frame* focused = focusedWebCoreFrame();
1364 if (!focused || !m_imeAcceptEvents)
1366 Editor* editor = focused->editor();
1370 // The input focus has been moved to another WebWidget object.
1371 // We should use this |editor| object only to complete the ongoing
1373 if (!editor->canEdit() && !editor->hasComposition())
1376 // We should verify the parent node of this IME composition node are
1377 // editable because JavaScript may delete a parent node of the composition
1378 // node. In this case, WebKit crashes while deleting texts from the parent
1379 // node, which doesn't exist any longer.
1380 PassRefPtr<Range> range = editor->compositionRange();
1382 Node* node = range->startContainer();
1383 if (!node || !node->isContentEditable())
1387 // If we're not going to fire a keypress event, then the keydown event was
1388 // canceled. In that case, cancel any existing composition.
1389 if (text.isEmpty() || m_suppressNextKeypressEvent) {
1390 // A browser process sent an IPC message which does not contain a valid
1391 // string, which means an ongoing composition has been canceled.
1392 // If the ongoing composition has been canceled, replace the ongoing
1393 // composition string with an empty string and complete it.
1395 Vector<CompositionUnderline> emptyUnderlines;
1396 editor->setComposition(emptyString, emptyUnderlines, 0, 0);
1397 return text.isEmpty();
1400 // When the range of composition underlines overlap with the range between
1401 // selectionStart and selectionEnd, WebKit somehow won't paint the selection
1402 // at all (see InlineTextBox::paint() function in InlineTextBox.cpp).
1403 // But the selection range actually takes effect.
1404 editor->setComposition(String(text),
1405 CompositionUnderlineVectorBuilder(underlines),
1406 selectionStart, selectionEnd);
1408 return editor->hasComposition();
1411 bool WebViewImpl::confirmComposition()
1413 return confirmComposition(WebString());
1416 bool WebViewImpl::confirmComposition(const WebString& text)
1418 Frame* focused = focusedWebCoreFrame();
1419 if (!focused || !m_imeAcceptEvents)
1421 Editor* editor = focused->editor();
1422 if (!editor || (!editor->hasComposition() && !text.length()))
1425 // We should verify the parent node of this IME composition node are
1426 // editable because JavaScript may delete a parent node of the composition
1427 // node. In this case, WebKit crashes while deleting texts from the parent
1428 // node, which doesn't exist any longer.
1429 PassRefPtr<Range> range = editor->compositionRange();
1431 Node* node = range->startContainer();
1432 if (!node || !node->isContentEditable())
1436 if (editor->hasComposition()) {
1438 editor->confirmComposition(String(text));
1440 editor->confirmComposition();
1442 editor->insertText(String(text), 0);
1447 bool WebViewImpl::compositionRange(size_t* location, size_t* length)
1449 Frame* focused = focusedWebCoreFrame();
1450 if (!focused || !m_imeAcceptEvents)
1452 Editor* editor = focused->editor();
1453 if (!editor || !editor->hasComposition())
1456 RefPtr<Range> range = editor->compositionRange();
1460 if (TextIterator::locationAndLengthFromRange(range.get(), *location, *length))
1465 WebTextInputType WebViewImpl::textInputType()
1467 Node* node = focusedWebCoreNode();
1469 return WebTextInputTypeNone;
1471 if (node->nodeType() == Node::ELEMENT_NODE) {
1472 Element* element = static_cast<Element*>(node);
1473 if (element->hasLocalName(HTMLNames::inputTag)) {
1474 HTMLInputElement* input = static_cast<HTMLInputElement*>(element);
1476 if (input->readOnly() || input->disabled())
1477 return WebTextInputTypeNone;
1479 if (input->isPasswordField())
1480 return WebTextInputTypePassword;
1481 if (input->isSearchField())
1482 return WebTextInputTypeSearch;
1483 if (input->isEmailField())
1484 return WebTextInputTypeEmail;
1485 if (input->isNumberField())
1486 return WebTextInputTypeNumber;
1487 if (input->isTelephoneField())
1488 return WebTextInputTypeTelephone;
1489 if (input->isURLField())
1490 return WebTextInputTypeURL;
1491 if (input->isTextField())
1492 return WebTextInputTypeText;
1493 return WebTextInputTypeNone;
1496 if (element->hasLocalName(HTMLNames::textareaTag)) {
1497 HTMLTextAreaElement* textarea = static_cast<HTMLTextAreaElement*>(element);
1499 if (textarea->readOnly() || textarea->disabled())
1500 return WebTextInputTypeNone;
1501 return WebTextInputTypeText;
1505 // For other situations.
1506 if (node->shouldUseInputMethod())
1507 return WebTextInputTypeText;
1509 return WebTextInputTypeNone;
1512 WebRect WebViewImpl::caretOrSelectionBounds()
1515 const Frame* focused = focusedWebCoreFrame();
1519 FrameSelection* selection = focused->selection();
1523 const FrameView* view = focused->view();
1527 const Node* node = selection->base().containerNode();
1528 if (!node || !node->renderer())
1531 if (selection->isCaret())
1532 rect = view->contentsToWindow(selection->absoluteCaretBounds());
1533 else if (selection->isRange()) {
1534 node = selection->extent().containerNode();
1535 RefPtr<Range> range = selection->toNormalizedRange();
1536 if (!node || !node->renderer() || !range)
1538 rect = view->contentsToWindow(focused->editor()->firstRectForRange(range.get()));
1543 bool WebViewImpl::selectionRange(WebPoint& start, WebPoint& end) const
1545 const Frame* frame = focusedWebCoreFrame();
1546 if (!frame || !frame->selection()->isRange())
1548 RefPtr<Range> selectedRange = frame->selection()->toNormalizedRange();
1551 RefPtr<Range> range(Range::create(selectedRange->startContainer()->document(),
1552 selectedRange->startContainer(),
1553 selectedRange->startOffset(),
1554 selectedRange->startContainer(),
1555 selectedRange->startOffset()));
1557 IntRect rect = frame->editor()->firstRectForRange(range.get());
1559 start.y = rect.y() + rect.height() - 1;
1561 range = Range::create(selectedRange->endContainer()->document(),
1562 selectedRange->endContainer(),
1563 selectedRange->endOffset(),
1564 selectedRange->endContainer(),
1565 selectedRange->endOffset());
1567 rect = frame->editor()->firstRectForRange(range.get());
1568 end.x = rect.x() + rect.width() - 1;
1569 end.y = rect.y() + rect.height() - 1;
1571 start = frame->view()->contentsToWindow(start);
1572 end = frame->view()->contentsToWindow(end);
1576 bool WebViewImpl::caretOrSelectionRange(size_t* location, size_t* length)
1578 const Frame* focused = focusedWebCoreFrame();
1582 FrameSelection* selection = focused->selection();
1586 RefPtr<Range> range = selection->selection().firstRange();
1590 if (TextIterator::locationAndLengthFromRange(range.get(), *location, *length))
1595 void WebViewImpl::setTextDirection(WebTextDirection direction)
1597 // The Editor::setBaseWritingDirection() function checks if we can change
1598 // the text direction of the selected node and updates its DOM "dir"
1599 // attribute and its CSS "direction" property.
1600 // So, we just call the function as Safari does.
1601 const Frame* focused = focusedWebCoreFrame();
1605 Editor* editor = focused->editor();
1606 if (!editor || !editor->canEdit())
1609 switch (direction) {
1610 case WebTextDirectionDefault:
1611 editor->setBaseWritingDirection(NaturalWritingDirection);
1614 case WebTextDirectionLeftToRight:
1615 editor->setBaseWritingDirection(LeftToRightWritingDirection);
1618 case WebTextDirectionRightToLeft:
1619 editor->setBaseWritingDirection(RightToLeftWritingDirection);
1628 bool WebViewImpl::isAcceleratedCompositingActive() const
1630 #if USE(ACCELERATED_COMPOSITING)
1631 return m_isAcceleratedCompositingActive;
1637 // WebView --------------------------------------------------------------------
1639 WebSettings* WebViewImpl::settings()
1642 m_webSettings = adoptPtr(new WebSettingsImpl(m_page->settings()));
1643 ASSERT(m_webSettings.get());
1644 return m_webSettings.get();
1647 WebString WebViewImpl::pageEncoding() const
1652 return m_page->mainFrame()->document()->loader()->writer()->encoding();
1655 void WebViewImpl::setPageEncoding(const WebString& encodingName)
1660 // Only change override encoding, don't change default encoding.
1661 // Note that the new encoding must be 0 if it isn't supposed to be set.
1662 String newEncodingName;
1663 if (!encodingName.isEmpty())
1664 newEncodingName = encodingName;
1665 m_page->mainFrame()->loader()->reloadWithOverrideEncoding(newEncodingName);
1668 bool WebViewImpl::dispatchBeforeUnloadEvent()
1670 // FIXME: This should really cause a recursive depth-first walk of all
1671 // frames in the tree, calling each frame's onbeforeunload. At the moment,
1672 // we're consistent with Safari 3.1, not IE/FF.
1673 Frame* frame = m_page->mainFrame();
1677 return frame->loader()->shouldClose();
1680 void WebViewImpl::dispatchUnloadEvent()
1682 // Run unload handlers.
1683 m_page->mainFrame()->loader()->closeURL();
1686 WebFrame* WebViewImpl::mainFrame()
1688 return mainFrameImpl();
1691 WebFrame* WebViewImpl::findFrameByName(
1692 const WebString& name, WebFrame* relativeToFrame)
1694 if (!relativeToFrame)
1695 relativeToFrame = mainFrame();
1696 Frame* frame = static_cast<WebFrameImpl*>(relativeToFrame)->frame();
1697 frame = frame->tree()->find(name);
1698 return WebFrameImpl::fromFrame(frame);
1701 WebFrame* WebViewImpl::focusedFrame()
1703 return WebFrameImpl::fromFrame(focusedWebCoreFrame());
1706 void WebViewImpl::setFocusedFrame(WebFrame* frame)
1709 // Clears the focused frame if any.
1710 Frame* frame = focusedWebCoreFrame();
1712 frame->selection()->setFocused(false);
1715 WebFrameImpl* frameImpl = static_cast<WebFrameImpl*>(frame);
1716 Frame* webcoreFrame = frameImpl->frame();
1717 webcoreFrame->page()->focusController()->setFocusedFrame(webcoreFrame);
1720 void WebViewImpl::setInitialFocus(bool reverse)
1725 // Since we don't have a keyboard event, we'll create one.
1726 WebKeyboardEvent keyboardEvent;
1727 keyboardEvent.type = WebInputEvent::RawKeyDown;
1729 keyboardEvent.modifiers = WebInputEvent::ShiftKey;
1731 // VK_TAB which is only defined on Windows.
1732 keyboardEvent.windowsKeyCode = 0x09;
1733 PlatformKeyboardEventBuilder platformEvent(keyboardEvent);
1734 RefPtr<KeyboardEvent> webkitEvent = KeyboardEvent::create(platformEvent, 0);
1736 Frame* frame = page()->focusController()->focusedOrMainFrame();
1737 if (Document* document = frame->document())
1738 document->setFocusedNode(0);
1739 page()->focusController()->setInitialFocus(
1740 reverse ? FocusDirectionBackward : FocusDirectionForward,
1744 void WebViewImpl::clearFocusedNode()
1749 RefPtr<Frame> frame = m_page->mainFrame();
1753 RefPtr<Document> document = frame->document();
1754 if (!document.get())
1757 RefPtr<Node> oldFocusedNode = document->focusedNode();
1759 // Clear the focused node.
1760 document->setFocusedNode(0);
1762 if (!oldFocusedNode.get())
1765 // If a text field has focus, we need to make sure the selection controller
1766 // knows to remove selection from it. Otherwise, the text field is still
1767 // processing keyboard events even though focus has been moved to the page and
1768 // keystrokes get eaten as a result.
1769 if (oldFocusedNode->hasTagName(HTMLNames::textareaTag)
1770 || (oldFocusedNode->hasTagName(HTMLNames::inputTag)
1771 && static_cast<HTMLInputElement*>(oldFocusedNode.get())->isTextField())) {
1772 frame->selection()->clear();
1776 void WebViewImpl::scrollFocusedNodeIntoView()
1778 Node* focusedNode = focusedWebCoreNode();
1779 if (focusedNode && focusedNode->isElementNode()) {
1780 Element* elementNode = static_cast<Element*>(focusedNode);
1781 elementNode->scrollIntoViewIfNeeded(true);
1785 double WebViewImpl::zoomLevel()
1790 double WebViewImpl::setZoomLevel(bool textOnly, double zoomLevel)
1792 if (zoomLevel < m_minimumZoomLevel)
1793 m_zoomLevel = m_minimumZoomLevel;
1794 else if (zoomLevel > m_maximumZoomLevel)
1795 m_zoomLevel = m_maximumZoomLevel;
1797 m_zoomLevel = zoomLevel;
1799 Frame* frame = mainFrameImpl()->frame();
1800 WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1801 if (pluginContainer)
1802 pluginContainer->plugin()->setZoomLevel(m_zoomLevel, textOnly);
1804 float zoomFactor = static_cast<float>(zoomLevelToZoomFactor(m_zoomLevel));
1806 frame->setPageAndTextZoomFactors(1, zoomFactor);
1808 frame->setPageAndTextZoomFactors(zoomFactor, 1);
1813 void WebViewImpl::zoomLimitsChanged(double minimumZoomLevel,
1814 double maximumZoomLevel)
1816 m_minimumZoomLevel = minimumZoomLevel;
1817 m_maximumZoomLevel = maximumZoomLevel;
1818 m_client->zoomLimitsChanged(m_minimumZoomLevel, m_maximumZoomLevel);
1821 void WebViewImpl::fullFramePluginZoomLevelChanged(double zoomLevel)
1823 if (zoomLevel == m_zoomLevel)
1826 m_zoomLevel = max(min(zoomLevel, m_maximumZoomLevel), m_minimumZoomLevel);
1827 m_client->zoomLevelChanged();
1830 double WebView::zoomLevelToZoomFactor(double zoomLevel)
1832 return pow(textSizeMultiplierRatio, zoomLevel);
1835 double WebView::zoomFactorToZoomLevel(double factor)
1837 // Since factor = 1.2^level, level = log(factor) / log(1.2)
1838 return log(factor) / log(textSizeMultiplierRatio);
1841 void WebViewImpl::scalePage(float scaleFactor, WebPoint origin)
1846 Frame* frame = page()->mainFrame();
1850 frame->scalePage(scaleFactor, origin);
1853 void WebViewImpl::performMediaPlayerAction(const WebMediaPlayerAction& action,
1854 const WebPoint& location)
1856 HitTestResult result = hitTestResultForWindowPos(location);
1857 RefPtr<Node> node = result.innerNonSharedNode();
1858 if (!node->hasTagName(HTMLNames::videoTag) && !node->hasTagName(HTMLNames::audioTag))
1861 RefPtr<HTMLMediaElement> mediaElement =
1862 static_pointer_cast<HTMLMediaElement>(node);
1863 switch (action.type) {
1864 case WebMediaPlayerAction::Play:
1866 mediaElement->play();
1868 mediaElement->pause();
1870 case WebMediaPlayerAction::Mute:
1871 mediaElement->setMuted(action.enable);
1873 case WebMediaPlayerAction::Loop:
1874 mediaElement->setLoop(action.enable);
1876 case WebMediaPlayerAction::Controls:
1877 mediaElement->setControls(action.enable);
1880 ASSERT_NOT_REACHED();
1884 void WebViewImpl::copyImageAt(const WebPoint& point)
1889 HitTestResult result = hitTestResultForWindowPos(point);
1891 if (result.absoluteImageURL().isEmpty()) {
1892 // There isn't actually an image at these coordinates. Might be because
1893 // the window scrolled while the context menu was open or because the page
1894 // changed itself between when we thought there was an image here and when
1895 // we actually tried to retreive the image.
1897 // FIXME: implement a cache of the most recent HitTestResult to avoid having
1898 // to do two hit tests.
1902 m_page->mainFrame()->editor()->copyImage(result);
1905 void WebViewImpl::dragSourceEndedAt(
1906 const WebPoint& clientPoint,
1907 const WebPoint& screenPoint,
1908 WebDragOperation operation)
1910 PlatformMouseEvent pme(clientPoint,
1912 LeftButton, MouseEventMoved, 0, false, false, false,
1914 m_page->mainFrame()->eventHandler()->dragSourceEndedAt(pme,
1915 static_cast<DragOperation>(operation));
1916 m_dragScrollTimer->stop();
1919 void WebViewImpl::dragSourceMovedTo(
1920 const WebPoint& clientPoint,
1921 const WebPoint& screenPoint,
1922 WebDragOperation operation)
1924 m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
1927 void WebViewImpl::dragSourceSystemDragEnded()
1929 // It's possible for us to get this callback while not doing a drag if
1930 // it's from a previous page that got unloaded.
1931 if (m_doingDragAndDrop) {
1932 m_page->dragController()->dragEnded();
1933 m_doingDragAndDrop = false;
1937 WebDragOperation WebViewImpl::dragTargetDragEnter(
1938 const WebDragData& webDragData,
1939 const WebPoint& clientPoint,
1940 const WebPoint& screenPoint,
1941 WebDragOperationsMask operationsAllowed)
1943 ASSERT(!m_currentDragData.get());
1945 m_currentDragData = webDragData;
1946 m_operationsAllowed = operationsAllowed;
1948 return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragEnter);
1951 WebDragOperation WebViewImpl::dragTargetDragOver(
1952 const WebPoint& clientPoint,
1953 const WebPoint& screenPoint,
1954 WebDragOperationsMask operationsAllowed)
1956 m_operationsAllowed = operationsAllowed;
1958 return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragOver);
1961 void WebViewImpl::dragTargetDragLeave()
1963 ASSERT(m_currentDragData.get());
1966 m_currentDragData.get(),
1969 static_cast<DragOperation>(m_operationsAllowed));
1971 m_page->dragController()->dragExited(&dragData);
1973 // FIXME: why is the drag scroll timer not stopped here?
1975 m_dragOperation = WebDragOperationNone;
1976 m_currentDragData = 0;
1979 void WebViewImpl::dragTargetDrop(const WebPoint& clientPoint,
1980 const WebPoint& screenPoint)
1982 ASSERT(m_currentDragData.get());
1984 // If this webview transitions from the "drop accepting" state to the "not
1985 // accepting" state, then our IPC message reply indicating that may be in-
1986 // flight, or else delayed by javascript processing in this webview. If a
1987 // drop happens before our IPC reply has reached the browser process, then
1988 // the browser forwards the drop to this webview. So only allow a drop to
1989 // proceed if our webview m_dragOperation state is not DragOperationNone.
1991 if (m_dragOperation == WebDragOperationNone) { // IPC RACE CONDITION: do not allow this drop.
1992 dragTargetDragLeave();
1997 m_currentDragData.get(),
2000 static_cast<DragOperation>(m_operationsAllowed));
2002 m_page->dragController()->performDrag(&dragData);
2004 m_dragOperation = WebDragOperationNone;
2005 m_currentDragData = 0;
2007 m_dragScrollTimer->stop();
2010 WebDragOperation WebViewImpl::dragTargetDragEnterOrOver(const WebPoint& clientPoint, const WebPoint& screenPoint, DragAction dragAction)
2012 ASSERT(m_currentDragData.get());
2015 m_currentDragData.get(),
2018 static_cast<DragOperation>(m_operationsAllowed));
2020 DragOperation dropEffect;
2021 if (dragAction == DragEnter)
2022 dropEffect = m_page->dragController()->dragEntered(&dragData);
2024 dropEffect = m_page->dragController()->dragUpdated(&dragData);
2026 // Mask the drop effect operation against the drag source's allowed operations.
2027 if (!(dropEffect & dragData.draggingSourceOperationMask()))
2028 dropEffect = DragOperationNone;
2030 m_dragOperation = static_cast<WebDragOperation>(dropEffect);
2032 if (dragAction == DragOver)
2033 m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
2035 m_dragScrollTimer->stop();
2037 return m_dragOperation;
2040 unsigned long WebViewImpl::createUniqueIdentifierForRequest()
2043 return m_page->progress()->createUniqueIdentifier();
2047 void WebViewImpl::inspectElementAt(const WebPoint& point)
2052 if (point.x == -1 || point.y == -1)
2053 m_page->inspectorController()->inspect(0);
2055 HitTestResult result = hitTestResultForWindowPos(point);
2057 if (!result.innerNonSharedNode())
2060 m_page->inspectorController()->inspect(result.innerNonSharedNode());
2064 WebString WebViewImpl::inspectorSettings() const
2066 return m_inspectorSettings;
2069 void WebViewImpl::setInspectorSettings(const WebString& settings)
2071 m_inspectorSettings = settings;
2074 bool WebViewImpl::inspectorSetting(const WebString& key, WebString* value) const
2076 if (!m_inspectorSettingsMap->contains(key))
2078 *value = m_inspectorSettingsMap->get(key);
2082 void WebViewImpl::setInspectorSetting(const WebString& key,
2083 const WebString& value)
2085 m_inspectorSettingsMap->set(key, value);
2086 client()->didUpdateInspectorSetting(key, value);
2089 WebDevToolsAgent* WebViewImpl::devToolsAgent()
2091 return m_devToolsAgent.get();
2094 WebAccessibilityObject WebViewImpl::accessibilityObject()
2096 if (!mainFrameImpl())
2097 return WebAccessibilityObject();
2099 Document* document = mainFrameImpl()->frame()->document();
2100 return WebAccessibilityObject(
2101 document->axObjectCache()->getOrCreate(document->renderer()));
2104 void WebViewImpl::applyAutofillSuggestions(
2105 const WebNode& node,
2106 const WebVector<WebString>& names,
2107 const WebVector<WebString>& labels,
2108 const WebVector<WebString>& icons,
2109 const WebVector<int>& uniqueIDs,
2112 ASSERT(names.size() == labels.size());
2113 ASSERT(names.size() == uniqueIDs.size());
2114 ASSERT(separatorIndex < static_cast<int>(names.size()));
2116 if (names.isEmpty()) {
2117 hideAutofillPopup();
2121 RefPtr<Node> focusedNode = focusedWebCoreNode();
2122 // If the node for which we queried the Autofill suggestions is not the
2123 // focused node, then we have nothing to do. FIXME: also check the
2124 // caret is at the end and that the text has not changed.
2125 if (!focusedNode || focusedNode != PassRefPtr<Node>(node)) {
2126 hideAutofillPopup();
2130 HTMLInputElement* inputElem =
2131 static_cast<HTMLInputElement*>(focusedNode.get());
2133 // The first time the Autofill popup is shown we'll create the client and
2135 if (!m_autofillPopupClient)
2136 m_autofillPopupClient = adoptPtr(new AutofillPopupMenuClient);
2138 m_autofillPopupClient->initialize(
2139 inputElem, names, labels, icons, uniqueIDs, separatorIndex);
2141 if (!m_autofillPopup.get()) {
2142 m_autofillPopup = PopupContainer::create(m_autofillPopupClient.get(),
2143 PopupContainer::Suggestion,
2144 autofillPopupSettings);
2147 if (m_autofillPopupShowing) {
2148 refreshAutofillPopup();
2150 m_autofillPopup->showInRect(focusedNode->getRect(), focusedNode->ownerDocument()->view(), 0);
2151 m_autofillPopupShowing = true;
2155 void WebViewImpl::hidePopups()
2158 hideAutofillPopup();
2161 void WebViewImpl::performCustomContextMenuAction(unsigned action)
2165 ContextMenu* menu = m_page->contextMenuController()->contextMenu();
2168 ContextMenuItem* item = menu->itemWithAction(static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + action));
2170 m_page->contextMenuController()->contextMenuItemSelected(item);
2171 m_page->contextMenuController()->clearContextMenu();
2174 // WebView --------------------------------------------------------------------
2176 void WebViewImpl::setIsTransparent(bool isTransparent)
2178 // Set any existing frames to be transparent.
2179 Frame* frame = m_page->mainFrame();
2181 frame->view()->setTransparent(isTransparent);
2182 frame = frame->tree()->traverseNext();
2185 // Future frames check this to know whether to be transparent.
2186 m_isTransparent = isTransparent;
2189 bool WebViewImpl::isTransparent() const
2191 return m_isTransparent;
2194 void WebViewImpl::setIsActive(bool active)
2196 if (page() && page()->focusController())
2197 page()->focusController()->setActive(active);
2200 bool WebViewImpl::isActive() const
2202 return (page() && page()->focusController()) ? page()->focusController()->isActive() : false;
2205 void WebViewImpl::setDomainRelaxationForbidden(bool forbidden, const WebString& scheme)
2207 SecurityOrigin::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme));
2210 void WebViewImpl::setScrollbarColors(unsigned inactiveColor,
2211 unsigned activeColor,
2212 unsigned trackColor) {
2213 #if OS(UNIX) && !OS(DARWIN)
2214 PlatformThemeChromiumGtk::setScrollbarColors(inactiveColor,
2220 void WebViewImpl::setSelectionColors(unsigned activeBackgroundColor,
2221 unsigned activeForegroundColor,
2222 unsigned inactiveBackgroundColor,
2223 unsigned inactiveForegroundColor) {
2224 #if OS(UNIX) && !OS(DARWIN)
2225 RenderThemeChromiumLinux::setSelectionColors(activeBackgroundColor,
2226 activeForegroundColor,
2227 inactiveBackgroundColor,
2228 inactiveForegroundColor);
2229 theme()->platformColorsDidChange();
2233 void WebView::addUserScript(const WebString& sourceCode,
2234 const WebVector<WebString>& patternsIn,
2235 WebView::UserScriptInjectAt injectAt,
2236 WebView::UserContentInjectIn injectIn)
2238 OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2239 for (size_t i = 0; i < patternsIn.size(); ++i)
2240 patterns->append(patternsIn[i]);
2242 PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2243 RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
2244 pageGroup->addUserScriptToWorld(world.get(), sourceCode, WebURL(), patterns.release(), nullptr,
2245 static_cast<UserScriptInjectionTime>(injectAt),
2246 static_cast<UserContentInjectedFrames>(injectIn));
2249 void WebView::addUserStyleSheet(const WebString& sourceCode,
2250 const WebVector<WebString>& patternsIn,
2251 WebView::UserContentInjectIn injectIn,
2252 WebView::UserStyleInjectionTime injectionTime)
2254 OwnPtr<Vector<String> > patterns = adoptPtr(new Vector<String>);
2255 for (size_t i = 0; i < patternsIn.size(); ++i)
2256 patterns->append(patternsIn[i]);
2258 PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2259 RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
2261 // FIXME: Current callers always want the level to be "author". It probably makes sense to let
2262 // callers specify this though, since in other cases the caller will probably want "user" level.
2264 // FIXME: It would be nice to populate the URL correctly, instead of passing an empty URL.
2265 pageGroup->addUserStyleSheetToWorld(world.get(), sourceCode, WebURL(), patterns.release(), nullptr,
2266 static_cast<UserContentInjectedFrames>(injectIn),
2267 UserStyleAuthorLevel,
2268 static_cast<WebCore::UserStyleInjectionTime>(injectionTime));
2271 void WebView::removeAllUserContent()
2273 PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
2274 pageGroup->removeAllUserContent();
2277 void WebViewImpl::didCommitLoad(bool* isNewNavigation)
2279 if (isNewNavigation)
2280 *isNewNavigation = m_observedNewNavigation;
2283 ASSERT(!m_observedNewNavigation
2284 || m_page->mainFrame()->loader()->documentLoader() == m_newNavigationLoader);
2285 m_newNavigationLoader = 0;
2287 m_observedNewNavigation = false;
2290 bool WebViewImpl::useExternalPopupMenus()
2292 return shouldUseExternalPopupMenus;
2295 bool WebViewImpl::navigationPolicyFromMouseEvent(unsigned short button,
2296 bool ctrl, bool shift,
2297 bool alt, bool meta,
2298 WebNavigationPolicy* policy)
2301 const bool newTabModifier = (button == 1) || meta;
2303 const bool newTabModifier = (button == 1) || ctrl;
2305 if (!newTabModifier && !shift && !alt)
2309 if (newTabModifier) {
2311 *policy = WebNavigationPolicyNewForegroundTab;
2313 *policy = WebNavigationPolicyNewBackgroundTab;
2316 *policy = WebNavigationPolicyNewWindow;
2318 *policy = WebNavigationPolicyDownload;
2323 void WebViewImpl::startDragging(const WebDragData& dragData,
2324 WebDragOperationsMask mask,
2325 const WebImage& dragImage,
2326 const WebPoint& dragImageOffset)
2330 ASSERT(!m_doingDragAndDrop);
2331 m_doingDragAndDrop = true;
2332 m_client->startDragging(dragData, mask, dragImage, dragImageOffset);
2335 void WebViewImpl::observeNewNavigation()
2337 m_observedNewNavigation = true;
2339 m_newNavigationLoader = m_page->mainFrame()->loader()->documentLoader();
2343 void WebViewImpl::setIgnoreInputEvents(bool newValue)
2345 ASSERT(m_ignoreInputEvents != newValue);
2346 m_ignoreInputEvents = newValue;
2349 void WebViewImpl::setPageOverlayClient(PageOverlay::PageOverlayClient* pageOverlayClient)
2351 if (pageOverlayClient) {
2353 m_pageOverlay = PageOverlay::create(this, pageOverlayClient);
2355 m_pageOverlay->setClient(pageOverlayClient);
2356 m_pageOverlay->update();
2357 setRootLayerNeedsDisplay();
2359 if (m_pageOverlay) {
2360 m_pageOverlay->clear();
2361 m_pageOverlay = nullptr;
2362 setRootLayerNeedsDisplay();
2367 void WebViewImpl::setOverlayLayer(WebCore::GraphicsLayer* layer)
2369 if (m_rootGraphicsLayer) {
2370 if (layer->parent() != m_rootGraphicsLayer)
2371 m_rootGraphicsLayer->addChild(layer);
2375 #if ENABLE(NOTIFICATIONS)
2376 NotificationPresenterImpl* WebViewImpl::notificationPresenterImpl()
2378 if (!m_notificationPresenter.isInitialized() && m_client)
2379 m_notificationPresenter.initialize(m_client->notificationPresenter());
2380 return &m_notificationPresenter;
2384 void WebViewImpl::refreshAutofillPopup()
2386 ASSERT(m_autofillPopupShowing);
2388 // Hide the popup if it has become empty.
2389 if (!m_autofillPopupClient->listSize()) {
2390 hideAutofillPopup();
2394 IntRect oldBounds = m_autofillPopup->frameRect();
2395 m_autofillPopup->refresh(focusedWebCoreNode()->getRect());
2396 IntRect newBounds = m_autofillPopup->frameRect();
2397 // Let's resize the backing window if necessary.
2398 if (oldBounds != newBounds) {
2399 WebPopupMenuImpl* popupMenu =
2400 static_cast<WebPopupMenuImpl*>(m_autofillPopup->client());
2402 popupMenu->client()->setWindowRect(m_chromeClientImpl.windowToScreen(newBounds));
2406 Node* WebViewImpl::focusedWebCoreNode()
2408 Frame* frame = m_page->focusController()->focusedFrame();
2412 Document* document = frame->document();
2416 return document->focusedNode();
2419 HitTestResult WebViewImpl::hitTestResultForWindowPos(const IntPoint& pos)
2421 IntPoint docPoint(m_page->mainFrame()->view()->windowToContents(pos));
2422 return m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(docPoint, false);
2425 void WebViewImpl::setTabsToLinks(bool enable)
2427 m_tabsToLinks = enable;
2430 bool WebViewImpl::tabsToLinks() const
2432 return m_tabsToLinks;
2435 #if USE(ACCELERATED_COMPOSITING)
2436 bool WebViewImpl::allowsAcceleratedCompositing()
2438 return !m_compositorCreationFailed;
2441 bool WebViewImpl::pageHasRTLStyle() const
2445 Document* document = page()->mainFrame()->document();
2448 RenderView* renderView = document->renderView();
2451 RenderStyle* style = renderView->style();
2454 return (style->direction() == RTL);
2457 void WebViewImpl::setRootGraphicsLayer(WebCore::GraphicsLayer* layer)
2459 m_rootGraphicsLayer = layer;
2460 setRootPlatformLayer(layer ? layer->platformLayer() : 0);
2463 void WebViewImpl::setRootPlatformLayer(WebCore::PlatformLayer* layer)
2465 setIsAcceleratedCompositingActive(layer);
2466 if (m_layerTreeHost)
2467 m_layerTreeHost->setRootLayer(layer);
2469 IntRect damagedRect(0, 0, m_size.width, m_size.height);
2470 if (m_isAcceleratedCompositingActive)
2471 invalidateRootLayerRect(damagedRect);
2473 m_client->didInvalidateRect(damagedRect);
2476 void WebViewImpl::setRootLayerNeedsDisplay()
2478 #if USE(THREADED_COMPOSITING)
2479 if (m_layerTreeHost)
2480 m_layerTreeHost->setNeedsCommitAndRedraw();
2482 m_client->scheduleComposite();
2486 void WebViewImpl::scrollRootLayerRect(const IntSize& scrollDelta, const IntRect& clipRect)
2488 updateLayerTreeViewport();
2489 setRootLayerNeedsDisplay();
2492 void WebViewImpl::invalidateRootLayerRect(const IntRect& rect)
2494 ASSERT(m_layerTreeHost);
2499 FrameView* view = page()->mainFrame()->view();
2500 IntRect dirtyRect = view->windowToContents(rect);
2501 updateLayerTreeViewport();
2502 m_layerTreeHost->invalidateRootLayerRect(dirtyRect);
2503 setRootLayerNeedsDisplay();
2506 class WebViewImplContentPainter : public LayerPainterChromium {
2507 WTF_MAKE_NONCOPYABLE(WebViewImplContentPainter);
2509 static PassOwnPtr<WebViewImplContentPainter*> create(WebViewImpl* webViewImpl)
2511 return adoptPtr(new WebViewImplContentPainter(webViewImpl));
2514 virtual void paint(GraphicsContext& context, const IntRect& contentRect)
2516 double paintStart = currentTime();
2517 Page* page = m_webViewImpl->page();
2520 FrameView* view = page->mainFrame()->view();
2521 view->paintContents(&context, contentRect);
2522 double paintEnd = currentTime();
2523 double pixelsPerSec = (contentRect.width() * contentRect.height()) / (paintEnd - paintStart);
2524 PlatformBridge::histogramCustomCounts("Renderer4.AccelRootPaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30);
2525 PlatformBridge::histogramCustomCounts("Renderer4.AccelRootPaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30);
2529 explicit WebViewImplContentPainter(WebViewImpl* webViewImpl)
2530 : m_webViewImpl(webViewImpl)
2534 WebViewImpl* m_webViewImpl;
2537 void WebViewImpl::setIsAcceleratedCompositingActive(bool active)
2539 PlatformBridge::histogramEnumeration("GPU.setIsAcceleratedCompositingActive", active * 2 + m_isAcceleratedCompositingActive, 4);
2541 if (m_isAcceleratedCompositingActive == active)
2545 m_isAcceleratedCompositingActive = false;
2546 // We need to finish all GL rendering before sending
2547 // didActivateAcceleratedCompositing(false) to prevent
2548 // flickering when compositing turns off.
2549 if (m_layerTreeHost)
2550 m_layerTreeHost->finishAllRendering();
2551 m_client->didActivateAcceleratedCompositing(false);
2552 } else if (m_layerTreeHost) {
2553 m_isAcceleratedCompositingActive = true;
2554 updateLayerTreeViewport();
2556 m_client->didActivateAcceleratedCompositing(true);
2558 TRACE_EVENT("WebViewImpl::setIsAcceleratedCompositingActive(true)", this, 0);
2560 WebCore::CCSettings ccSettings;
2561 ccSettings.acceleratePainting = page()->settings()->acceleratedDrawingEnabled();
2562 ccSettings.compositeOffscreen = settings()->compositeToTextureEnabled();
2563 ccSettings.showFPSCounter = settings()->showFPSCounter();
2564 ccSettings.showPlatformLayerTree = settings()->showPlatformLayerTree();
2566 m_layerTreeHost = CCLayerTreeHost::create(this, ccSettings);
2567 if (m_layerTreeHost) {
2568 m_client->didActivateAcceleratedCompositing(true);
2569 m_isAcceleratedCompositingActive = true;
2570 m_compositorCreationFailed = false;
2572 m_pageOverlay->update();
2574 m_isAcceleratedCompositingActive = false;
2575 m_client->didActivateAcceleratedCompositing(false);
2576 m_compositorCreationFailed = true;
2580 page()->mainFrame()->view()->setClipsRepaints(!m_isAcceleratedCompositingActive);
2585 PassRefPtr<GraphicsContext3D> WebViewImpl::createLayerTreeHostContext3D()
2587 RefPtr<GraphicsContext3D> context = m_temporaryOnscreenGraphicsContext3D.release();
2589 context = GraphicsContext3D::create(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2591 context->reshape(max(1, m_size.width), max(1, m_size.height));
2596 PassOwnPtr<LayerPainterChromium> WebViewImpl::createRootLayerPainter()
2598 return WebViewImplContentPainter::create(this);
2601 void WebViewImpl::animateAndLayout(double frameBeginTime)
2603 animate(frameBeginTime);
2607 void WebViewImpl::didRecreateGraphicsContext(bool success)
2609 setRootPlatformLayer(success ? m_layerTreeHost->rootLayer() : 0);
2612 // Forces ViewHostMsg_DidActivateAcceleratedCompositing to be sent so
2613 // that the browser process can reacquire surfaces.
2614 m_client->didActivateAcceleratedCompositing(true);
2616 m_pageOverlay->update();
2620 #if !USE(THREADED_COMPOSITING)
2621 void WebViewImpl::scheduleComposite()
2623 m_client->scheduleComposite();
2627 void WebViewImpl::updateLayerTreeViewport()
2632 FrameView* view = page()->mainFrame()->view();
2633 IntRect contentRect = view->visibleContentRect(false);
2634 IntRect visibleRect = view->visibleContentRect(true);
2635 IntPoint scroll(view->scrollX(), view->scrollY());
2637 m_layerTreeHost->setViewport(visibleRect, contentRect, scroll);
2640 WebGraphicsContext3D* WebViewImpl::graphicsContext3D()
2642 #if USE(ACCELERATED_COMPOSITING)
2643 if (m_page->settings()->acceleratedCompositingEnabled() && allowsAcceleratedCompositing()) {
2644 if (m_layerTreeHost) {
2645 WebGraphicsContext3D* webContext = GraphicsContext3DInternal::extractWebGraphicsContext3D(m_layerTreeHost->context());
2646 if (webContext && !webContext->isContextLost())
2649 if (m_temporaryOnscreenGraphicsContext3D) {
2650 WebGraphicsContext3D* webContext = GraphicsContext3DInternal::extractWebGraphicsContext3D(m_temporaryOnscreenGraphicsContext3D.get());
2651 if (webContext && !webContext->isContextLost())
2654 m_temporaryOnscreenGraphicsContext3D = GraphicsContext3D::create(getCompositorContextAttributes(), m_page->chrome(), GraphicsContext3D::RenderDirectlyToHostWindow);
2655 if (m_temporaryOnscreenGraphicsContext3D)
2656 m_temporaryOnscreenGraphicsContext3D->reshape(max(1, m_size.width), max(1, m_size.height));
2657 return GraphicsContext3DInternal::extractWebGraphicsContext3D(m_temporaryOnscreenGraphicsContext3D.get());
2664 void WebViewImpl::setVisibilityState(WebPageVisibilityState visibilityState,
2665 bool isInitialState) {
2669 #if ENABLE(PAGE_VISIBILITY_API)
2670 ASSERT(visibilityState == WebPageVisibilityStateVisible
2671 || visibilityState == WebPageVisibilityStateHidden
2672 || visibilityState == WebPageVisibilityStatePrerender);
2673 m_page->setVisibilityState(static_cast<PageVisibilityState>(static_cast<int>(visibilityState)), isInitialState);
2676 #if USE(ACCELERATED_COMPOSITING)
2677 if (isAcceleratedCompositingActive())
2678 m_layerTreeHost->setVisible(visibilityState == WebPageVisibilityStateVisible);
2682 #if ENABLE(GESTURE_RECOGNIZER)
2683 void WebViewImpl::resetGestureRecognizer()
2685 m_gestureRecognizer->reset();
2690 } // namespace WebKit