2 * Copyright (C) 2011, 2012 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 "CSSValueKeywords.h"
35 #include "CompositionUnderlineVectorBuilder.h"
36 #include "ContextFeaturesClientImpl.h"
37 #include "DatabaseClientImpl.h"
38 #include "FullscreenController.h"
39 #include "GeolocationClientProxy.h"
40 #include "GraphicsLayerFactoryChromium.h"
41 #include "HTMLNames.h"
42 #include "LinkHighlight.h"
43 #include "LocalFileSystemClient.h"
44 #include "MIDIClientProxy.h"
45 #include "PopupContainer.h"
46 #include "PrerendererClientImpl.h"
47 #include "RuntimeEnabledFeatures.h"
48 #include "SpeechInputClientImpl.h"
49 #include "SpeechRecognitionClientProxy.h"
50 #include "StorageQuotaClientImpl.h"
51 #include "ValidationMessageClientImpl.h"
52 #include "ViewportAnchor.h"
53 #include "WebAXObject.h"
54 #include "WebActiveWheelFlingParameters.h"
55 #include "WebAutofillClient.h"
56 #include "WebDevToolsAgentImpl.h"
57 #include "WebDevToolsAgentPrivate.h"
58 #include "WebFrameImpl.h"
59 #include "WebHitTestResult.h"
60 #include "WebInputElement.h"
61 #include "WebInputEventConversion.h"
62 #include "WebMediaPlayerAction.h"
64 #include "WebPagePopupImpl.h"
65 #include "WebPlugin.h"
66 #include "WebPluginAction.h"
67 #include "WebPluginContainerImpl.h"
68 #include "WebPopupMenuImpl.h"
70 #include "WebSettingsImpl.h"
71 #include "WebTextInputInfo.h"
72 #include "WebViewClient.h"
73 #include "WebWindowFeatures.h"
74 #include "WorkerGlobalScopeProxyProviderImpl.h"
75 #include "core/accessibility/AXObjectCache.h"
76 #include "core/clipboard/DataObject.h"
77 #include "core/dom/Document.h"
78 #include "core/dom/DocumentMarkerController.h"
79 #include "core/dom/Text.h"
80 #include "core/dom/WheelController.h"
81 #include "core/editing/Editor.h"
82 #include "core/editing/FrameSelection.h"
83 #include "core/editing/InputMethodController.h"
84 #include "core/editing/TextIterator.h"
85 #include "core/events/KeyboardEvent.h"
86 #include "core/events/WheelEvent.h"
87 #include "core/frame/FrameHost.h"
88 #include "core/frame/FrameView.h"
89 #include "core/frame/LocalFrame.h"
90 #include "core/frame/PinchViewport.h"
91 #include "core/frame/Settings.h"
92 #include "core/frame/SmartClip.h"
93 #include "core/html/HTMLInputElement.h"
94 #include "core/html/HTMLMediaElement.h"
95 #include "core/html/HTMLPlugInElement.h"
96 #include "core/html/HTMLTextAreaElement.h"
97 #include "core/html/ime/InputMethodContext.h"
98 #include "core/inspector/InspectorController.h"
99 #include "core/loader/DocumentLoader.h"
100 #include "core/loader/FrameLoader.h"
101 #include "core/loader/UniqueIdentifier.h"
102 #include "core/page/Chrome.h"
103 #include "core/page/ContextMenuController.h"
104 #include "core/page/DragController.h"
105 #include "core/page/DragData.h"
106 #include "core/page/DragSession.h"
107 #include "core/page/EventHandler.h"
108 #include "core/page/FocusController.h"
109 #include "core/page/FrameTree.h"
110 #include "core/page/InjectedStyleSheets.h"
111 #include "core/page/Page.h"
112 #include "core/page/PagePopupClient.h"
113 #include "core/page/PointerLockController.h"
114 #include "core/page/ScopedPageLoadDeferrer.h"
115 #include "core/page/TouchDisambiguation.h"
116 #include "core/rendering/RenderView.h"
117 #include "core/rendering/RenderWidget.h"
118 #include "core/rendering/TextAutosizer.h"
119 #include "core/rendering/compositing/RenderLayerCompositor.h"
120 #include "modules/device_orientation/DeviceOrientationInspectorAgent.h"
121 #include "modules/encryptedmedia/MediaKeysController.h"
122 #include "modules/geolocation/GeolocationController.h"
123 #include "modules/indexeddb/InspectorIndexedDBAgent.h"
124 #include "modules/notifications/NotificationController.h"
125 #include "painting/ContinuousPainter.h"
126 #include "platform/ContextMenu.h"
127 #include "platform/ContextMenuItem.h"
128 #include "platform/Cursor.h"
129 #include "platform/KeyboardCodes.h"
130 #include "platform/NotImplemented.h"
131 #include "platform/OverscrollTheme.h"
132 #include "platform/PlatformGestureEvent.h"
133 #include "platform/PlatformKeyboardEvent.h"
134 #include "platform/PlatformMouseEvent.h"
135 #include "platform/PlatformWheelEvent.h"
136 #include "platform/PopupMenuClient.h"
137 #include "platform/TraceEvent.h"
138 #include "platform/UserGestureIndicator.h"
139 #include "platform/exported/WebActiveGestureAnimation.h"
140 #include "platform/fonts/FontCache.h"
141 #include "platform/graphics/Color.h"
142 #include "platform/graphics/Image.h"
143 #include "platform/graphics/ImageBuffer.h"
144 #include "platform/scroll/ScrollbarTheme.h"
145 #include "platform/weborigin/SchemeRegistry.h"
146 #include "public/platform/Platform.h"
147 #include "public/platform/WebDragData.h"
148 #include "public/platform/WebFloatPoint.h"
149 #include "public/platform/WebGestureCurve.h"
150 #include "public/platform/WebImage.h"
151 #include "public/platform/WebLayerTreeView.h"
152 #include "public/platform/WebVector.h"
153 #include "wtf/CurrentTime.h"
154 #include "wtf/RefPtr.h"
155 #include "wtf/TemporaryChange.h"
157 #if USE(DEFAULT_RENDER_THEME)
158 #include "core/rendering/RenderThemeChromiumDefault.h"
161 // Get rid of WTF's pow define so we can use std::pow.
163 #include <cmath> // for std::pow
165 using namespace WebCore;
168 // The following constants control parameters for automated scaling of webpages
169 // (such as due to a double tap gesture or find in page etc.). These are
170 // experimentally determined.
171 static const int touchPointPadding = 32;
172 static const int nonUserInitiatedPointPadding = 11;
173 static const float minScaleDifference = 0.01f;
174 static const float doubleTapZoomContentDefaultMargin = 5;
175 static const float doubleTapZoomContentMinimumMargin = 2;
176 static const double doubleTapZoomAnimationDurationInSeconds = 0.25;
177 static const float doubleTapZoomAlreadyLegibleRatio = 1.2f;
179 static const double multipleTargetsZoomAnimationDurationInSeconds = 0.25;
180 static const double findInPageAnimationDurationInSeconds = 0;
182 // Constants for viewport anchoring on resize.
183 static const float viewportAnchorXCoord = 0.5f;
184 static const float viewportAnchorYCoord = 0;
186 // Constants for zooming in on a focused text field.
187 static const double scrollAndScaleAnimationDurationInSeconds = 0.2;
188 static const int minReadableCaretHeight = 18;
189 static const float minScaleChangeToTriggerZoom = 1.05f;
190 static const float leftBoxRatio = 0.3f;
191 static const int caretPadding = 10;
195 // Change the text zoom level by kTextSizeMultiplierRatio each time the user
196 // zooms text in or out (ie., change by 20%). The min and max values limit
197 // text zoom to half and 3x the original text size. These three values match
198 // those in Apple's port in WebKit/WebKit/WebView/WebView.mm
199 const double WebView::textSizeMultiplierRatio = 1.2;
200 const double WebView::minTextSizeMultiplier = 0.5;
201 const double WebView::maxTextSizeMultiplier = 3.0;
203 // Used to defer all page activity in cases where the embedder wishes to run
204 // a nested event loop. Using a stack enables nesting of message loop invocations.
205 static Vector<ScopedPageLoadDeferrer*>& pageLoadDeferrerStack()
207 DEFINE_STATIC_LOCAL(Vector<ScopedPageLoadDeferrer*>, deferrerStack, ());
208 return deferrerStack;
211 // Ensure that the WebDragOperation enum values stay in sync with the original
212 // DragOperation constants.
213 #define COMPILE_ASSERT_MATCHING_ENUM(coreName) \
214 COMPILE_ASSERT(int(coreName) == int(Web##coreName), dummy##coreName)
215 COMPILE_ASSERT_MATCHING_ENUM(DragOperationNone);
216 COMPILE_ASSERT_MATCHING_ENUM(DragOperationCopy);
217 COMPILE_ASSERT_MATCHING_ENUM(DragOperationLink);
218 COMPILE_ASSERT_MATCHING_ENUM(DragOperationGeneric);
219 COMPILE_ASSERT_MATCHING_ENUM(DragOperationPrivate);
220 COMPILE_ASSERT_MATCHING_ENUM(DragOperationMove);
221 COMPILE_ASSERT_MATCHING_ENUM(DragOperationDelete);
222 COMPILE_ASSERT_MATCHING_ENUM(DragOperationEvery);
224 static bool shouldUseExternalPopupMenus = false;
226 static int webInputEventKeyStateToPlatformEventKeyState(int webInputEventKeyState)
228 int platformEventKeyState = 0;
229 if (webInputEventKeyState & WebInputEvent::ShiftKey)
230 platformEventKeyState = platformEventKeyState | WebCore::PlatformEvent::ShiftKey;
231 if (webInputEventKeyState & WebInputEvent::ControlKey)
232 platformEventKeyState = platformEventKeyState | WebCore::PlatformEvent::CtrlKey;
233 if (webInputEventKeyState & WebInputEvent::AltKey)
234 platformEventKeyState = platformEventKeyState | WebCore::PlatformEvent::AltKey;
235 if (webInputEventKeyState & WebInputEvent::MetaKey)
236 platformEventKeyState = platformEventKeyState | WebCore::PlatformEvent::MetaKey;
237 return platformEventKeyState;
240 // WebView ----------------------------------------------------------------
242 WebView* WebView::create(WebViewClient* client)
244 // Pass the WebViewImpl's self-reference to the caller.
245 return WebViewImpl::create(client);
248 WebViewImpl* WebViewImpl::create(WebViewClient* client)
250 // Pass the WebViewImpl's self-reference to the caller.
251 return adoptRef(new WebViewImpl(client)).leakRef();
254 void WebView::setUseExternalPopupMenus(bool useExternalPopupMenus)
256 shouldUseExternalPopupMenus = useExternalPopupMenus;
259 void WebView::updateVisitedLinkState(unsigned long long linkHash)
261 Page::visitedStateChanged(linkHash);
264 void WebView::resetVisitedLinkState()
266 Page::allVisitedStateChanged();
269 void WebView::willEnterModalLoop()
271 pageLoadDeferrerStack().append(new ScopedPageLoadDeferrer());
274 void WebView::didExitModalLoop()
276 ASSERT(pageLoadDeferrerStack().size());
278 delete pageLoadDeferrerStack().last();
279 pageLoadDeferrerStack().removeLast();
282 void WebViewImpl::setMainFrame(WebFrame* frame)
284 toWebFrameImpl(frame)->initializeAsMainFrame(page());
287 void WebViewImpl::setAutofillClient(WebAutofillClient* autofillClient)
289 m_autofillClient = autofillClient;
292 void WebViewImpl::setDevToolsAgentClient(WebDevToolsAgentClient* devToolsClient)
295 m_devToolsAgent = adoptPtr(new WebDevToolsAgentImpl(this, devToolsClient));
297 m_devToolsAgent.clear();
300 void WebViewImpl::setPrerendererClient(WebPrerendererClient* prerendererClient)
303 providePrerendererClientTo(*m_page, new PrerendererClientImpl(prerendererClient));
306 void WebViewImpl::setSpellCheckClient(WebSpellCheckClient* spellCheckClient)
308 m_spellCheckClient = spellCheckClient;
311 void WebViewImpl::setPasswordGeneratorClient(WebPasswordGeneratorClient* client)
313 m_passwordGeneratorClient = client;
316 WebViewImpl::WebViewImpl(WebViewClient* client)
318 , m_autofillClient(0)
319 , m_spellCheckClient(0)
320 , m_passwordGeneratorClient(0)
321 , m_chromeClientImpl(this)
322 , m_contextMenuClientImpl(this)
323 , m_dragClientImpl(this)
324 , m_editorClientImpl(this)
325 , m_inspectorClientImpl(this)
326 , m_backForwardClientImpl(this)
327 , m_spellCheckerClientImpl(this)
328 , m_storageClientImpl(this)
329 , m_fixedLayoutSizeLock(false)
330 , m_shouldAutoResize(false)
332 , m_minimumZoomLevel(zoomFactorToZoomLevel(minTextSizeMultiplier))
333 , m_maximumZoomLevel(zoomFactorToZoomLevel(maxTextSizeMultiplier))
334 , m_savedPageScaleFactor(0)
335 , m_doubleTapZoomPageScaleFactor(0)
336 , m_doubleTapZoomPending(false)
337 , m_enableFakePageScaleAnimationForTesting(false)
338 , m_fakePageScaleAnimationPageScaleFactor(0)
339 , m_fakePageScaleAnimationUseAnchor(false)
340 , m_contextMenuAllowed(false)
341 , m_doingDragAndDrop(false)
342 , m_ignoreInputEvents(false)
343 , m_compositorDeviceScaleFactorOverride(0)
344 , m_rootLayerScale(1)
345 , m_suppressNextKeypressEvent(false)
346 , m_imeAcceptEvents(true)
347 , m_operationsAllowed(WebDragOperationNone)
348 , m_dragOperation(WebDragOperationNone)
349 , m_featureSwitchClient(adoptPtr(new ContextFeaturesClientImpl()))
350 , m_isTransparent(false)
351 , m_tabsToLinks(false)
354 , m_rootGraphicsLayer(0)
355 , m_rootTransformLayer(0)
356 , m_graphicsLayerFactory(adoptPtr(new GraphicsLayerFactoryChromium(this)))
357 , m_isAcceleratedCompositingActive(false)
358 , m_layerTreeViewCommitsDeferred(false)
359 , m_compositorCreationFailed(false)
360 , m_recreatingGraphicsContext(false)
361 #if ENABLE(INPUT_SPEECH)
362 , m_speechInputClient(SpeechInputClientImpl::create(client))
364 , m_speechRecognitionClient(SpeechRecognitionClientProxy::create(client ? client->speechRecognizer() : 0))
365 , m_geolocationClientProxy(adoptPtr(new GeolocationClientProxy(client ? client->geolocationClient() : 0)))
366 , m_userMediaClientImpl(this)
367 , m_midiClientProxy(adoptPtr(new MIDIClientProxy(client ? client->webMIDIClient() : 0)))
368 , m_navigatorContentUtilsClient(NavigatorContentUtilsClientImpl::create(this))
370 , m_flingSourceDevice(false)
371 , m_fullscreenController(FullscreenController::create(this))
372 , m_showFPSCounter(false)
373 , m_showPaintRects(false)
374 , m_showDebugBorders(false)
375 , m_continuousPaintingEnabled(false)
376 , m_showScrollBottleneckRects(false)
377 , m_baseBackgroundColor(Color::white)
378 , m_backgroundColorOverride(Color::transparent)
379 , m_zoomFactorOverride(0)
381 Page::PageClients pageClients;
382 pageClients.chromeClient = &m_chromeClientImpl;
383 pageClients.contextMenuClient = &m_contextMenuClientImpl;
384 pageClients.editorClient = &m_editorClientImpl;
385 pageClients.dragClient = &m_dragClientImpl;
386 pageClients.inspectorClient = &m_inspectorClientImpl;
387 pageClients.backForwardClient = &m_backForwardClientImpl;
388 pageClients.spellCheckerClient = &m_spellCheckerClientImpl;
389 pageClients.storageClient = &m_storageClientImpl;
391 m_page = adoptPtr(new Page(pageClients));
392 provideUserMediaTo(*m_page, &m_userMediaClientImpl);
393 MediaKeysController::provideMediaKeysTo(*m_page, &m_mediaKeysClientImpl);
394 provideMIDITo(*m_page, m_midiClientProxy.get());
395 #if ENABLE(INPUT_SPEECH)
396 provideSpeechInputTo(*m_page, m_speechInputClient.get());
398 provideSpeechRecognitionTo(*m_page, m_speechRecognitionClient.get());
399 provideNotification(*m_page, notificationPresenterImpl());
400 provideNavigatorContentUtilsTo(*m_page, m_navigatorContentUtilsClient.get());
402 provideContextFeaturesTo(*m_page, m_featureSwitchClient.get());
403 if (RuntimeEnabledFeatures::deviceOrientationEnabled())
404 DeviceOrientationInspectorAgent::provideTo(*m_page);
405 provideGeolocationTo(*m_page, m_geolocationClientProxy.get());
406 m_geolocationClientProxy->setController(GeolocationController::from(m_page.get()));
408 provideLocalFileSystemTo(*m_page, LocalFileSystemClient::create());
409 provideDatabaseClientTo(*m_page, DatabaseClientImpl::create());
410 InspectorIndexedDBAgent::provideTo(m_page.get());
411 provideStorageQuotaClientTo(*m_page, StorageQuotaClientImpl::create());
412 m_validationMessage = ValidationMessageClientImpl::create(*this);
413 m_page->setValidationMessageClient(m_validationMessage.get());
414 provideWorkerGlobalScopeProxyProviderTo(*m_page, WorkerGlobalScopeProxyProviderImpl::create());
416 m_page->makeOrdinary();
419 setDeviceScaleFactor(m_client->screenInfo().deviceScaleFactor);
420 setVisibilityState(m_client->visibilityState(), true);
423 m_inspectorSettingsMap = adoptPtr(new SettingsMap);
426 WebViewImpl::~WebViewImpl()
431 WebFrameImpl* WebViewImpl::mainFrameImpl()
433 return m_page ? WebFrameImpl::fromFrame(m_page->mainFrame()) : 0;
436 bool WebViewImpl::tabKeyCyclesThroughElements() const
439 return m_page->tabKeyCyclesThroughElements();
442 void WebViewImpl::setTabKeyCyclesThroughElements(bool value)
445 m_page->setTabKeyCyclesThroughElements(value);
448 void WebViewImpl::handleMouseLeave(LocalFrame& mainFrame, const WebMouseEvent& event)
450 m_client->setMouseOverURL(WebURL());
451 PageWidgetEventHandler::handleMouseLeave(mainFrame, event);
454 void WebViewImpl::handleMouseDown(LocalFrame& mainFrame, const WebMouseEvent& event)
456 // If there is a popup open, close it as the user is clicking on the page (outside of the
457 // popup). We also save it so we can prevent a click on an element from immediately
458 // reopening the same popup.
459 RefPtr<PopupContainer> selectPopup;
460 RefPtr<WebPagePopupImpl> pagePopup;
461 if (event.button == WebMouseEvent::ButtonLeft) {
462 selectPopup = m_selectPopup;
463 pagePopup = m_pagePopup;
465 ASSERT(!m_selectPopup);
466 ASSERT(!m_pagePopup);
469 m_lastMouseDownPoint = WebPoint(event.x, event.y);
471 if (event.button == WebMouseEvent::ButtonLeft) {
472 IntPoint point(event.x, event.y);
473 point = m_page->mainFrame()->view()->windowToContents(point);
474 HitTestResult result(m_page->mainFrame()->eventHandler().hitTestResultAtPoint(point));
475 Node* hitNode = result.innerNonSharedNode();
477 // Take capture on a mouse down on a plugin so we can send it mouse events.
478 if (hitNode && hitNode->renderer() && hitNode->renderer()->isEmbeddedObject()) {
479 m_mouseCaptureNode = hitNode;
480 TRACE_EVENT_ASYNC_BEGIN0("input", "capturing mouse", this);
484 PageWidgetEventHandler::handleMouseDown(mainFrame, event);
486 if (event.button == WebMouseEvent::ButtonLeft && m_mouseCaptureNode)
487 m_mouseCaptureGestureToken = mainFrame.eventHandler().takeLastMouseDownGestureToken();
489 if (m_selectPopup && m_selectPopup == selectPopup) {
490 // That click triggered a select popup which is the same as the one that
491 // was showing before the click. It means the user clicked the select
492 // while the popup was showing, and as a result we first closed then
493 // immediately reopened the select popup. It needs to be closed.
497 if (m_pagePopup && pagePopup && m_pagePopup->hasSamePopupClient(pagePopup.get())) {
498 // That click triggered a page popup that is the same as the one we just closed.
499 // It needs to be closed.
500 closePagePopup(m_pagePopup.get());
503 // Dispatch the contextmenu event regardless of if the click was swallowed.
505 // On Windows, we handle it on mouse up, not down.
507 if (event.button == WebMouseEvent::ButtonRight
508 || (event.button == WebMouseEvent::ButtonLeft
509 && event.modifiers & WebMouseEvent::ControlKey))
510 mouseContextMenu(event);
512 if (event.button == WebMouseEvent::ButtonRight)
513 mouseContextMenu(event);
517 void WebViewImpl::mouseContextMenu(const WebMouseEvent& event)
519 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
522 m_page->contextMenuController().clearContextMenu();
524 PlatformMouseEventBuilder pme(mainFrameImpl()->frameView(), event);
526 // Find the right target frame. See issue 1186900.
527 HitTestResult result = hitTestResultForWindowPos(pme.position());
528 LocalFrame* targetFrame;
529 if (result.innerNonSharedNode())
530 targetFrame = result.innerNonSharedNode()->document().frame();
532 targetFrame = m_page->focusController().focusedOrMainFrame();
535 targetFrame->view()->setCursor(pointerCursor());
538 m_contextMenuAllowed = true;
539 targetFrame->eventHandler().sendContextMenuEvent(pme);
540 m_contextMenuAllowed = false;
541 // Actually showing the context menu is handled by the ContextMenuClient
545 void WebViewImpl::handleMouseUp(LocalFrame& mainFrame, const WebMouseEvent& event)
547 PageWidgetEventHandler::handleMouseUp(mainFrame, event);
550 // Dispatch the contextmenu event regardless of if the click was swallowed.
551 // On Mac/Linux, we handle it on mouse down, not up.
552 if (event.button == WebMouseEvent::ButtonRight)
553 mouseContextMenu(event);
557 bool WebViewImpl::handleMouseWheel(LocalFrame& mainFrame, const WebMouseWheelEvent& event)
560 return PageWidgetEventHandler::handleMouseWheel(mainFrame, event);
563 void WebViewImpl::scrollBy(const WebFloatSize& delta)
565 if (m_flingSourceDevice == WebGestureEvent::Touchpad) {
566 WebMouseWheelEvent syntheticWheel;
567 const float tickDivisor = WebCore::WheelEvent::TickMultiplier;
569 syntheticWheel.deltaX = delta.width;
570 syntheticWheel.deltaY = delta.height;
571 syntheticWheel.wheelTicksX = delta.width / tickDivisor;
572 syntheticWheel.wheelTicksY = delta.height / tickDivisor;
573 syntheticWheel.hasPreciseScrollingDeltas = true;
574 syntheticWheel.x = m_positionOnFlingStart.x;
575 syntheticWheel.y = m_positionOnFlingStart.y;
576 syntheticWheel.globalX = m_globalPositionOnFlingStart.x;
577 syntheticWheel.globalY = m_globalPositionOnFlingStart.y;
578 syntheticWheel.modifiers = m_flingModifier;
580 if (m_page && m_page->mainFrame() && m_page->mainFrame()->view())
581 handleMouseWheel(*m_page->mainFrame(), syntheticWheel);
583 WebGestureEvent syntheticGestureEvent;
585 syntheticGestureEvent.type = WebInputEvent::GestureScrollUpdateWithoutPropagation;
586 syntheticGestureEvent.data.scrollUpdate.deltaX = delta.width;
587 syntheticGestureEvent.data.scrollUpdate.deltaY = delta.height;
588 syntheticGestureEvent.x = m_positionOnFlingStart.x;
589 syntheticGestureEvent.y = m_positionOnFlingStart.y;
590 syntheticGestureEvent.globalX = m_globalPositionOnFlingStart.x;
591 syntheticGestureEvent.globalY = m_globalPositionOnFlingStart.y;
592 syntheticGestureEvent.modifiers = m_flingModifier;
593 syntheticGestureEvent.sourceDevice = WebGestureEvent::Touchscreen;
595 if (m_page && m_page->mainFrame() && m_page->mainFrame()->view())
596 handleGestureEvent(syntheticGestureEvent);
600 bool WebViewImpl::handleGestureEvent(const WebGestureEvent& event)
602 bool eventSwallowed = false;
603 bool eventCancelled = false; // for disambiguation
605 // Special handling for slow-path fling gestures.
606 switch (event.type) {
607 case WebInputEvent::GestureFlingStart: {
608 if (mainFrameImpl()->frame()->eventHandler().isScrollbarHandlingGestures())
610 m_client->cancelScheduledContentIntents();
611 m_positionOnFlingStart = WebPoint(event.x / pageScaleFactor(), event.y / pageScaleFactor());
612 m_globalPositionOnFlingStart = WebPoint(event.globalX, event.globalY);
613 m_flingModifier = event.modifiers;
614 m_flingSourceDevice = event.sourceDevice;
615 OwnPtr<WebGestureCurve> flingCurve = adoptPtr(Platform::current()->createFlingAnimationCurve(event.sourceDevice, WebFloatPoint(event.data.flingStart.velocityX, event.data.flingStart.velocityY), WebSize()));
616 m_gestureAnimation = WebActiveGestureAnimation::createAtAnimationStart(flingCurve.release(), this);
618 eventSwallowed = true;
620 m_client->didHandleGestureEvent(event, eventCancelled);
621 return eventSwallowed;
623 case WebInputEvent::GestureFlingCancel:
624 if (endActiveFlingAnimation())
625 eventSwallowed = true;
627 m_client->didHandleGestureEvent(event, eventCancelled);
628 return eventSwallowed;
633 PlatformGestureEventBuilder platformEvent(mainFrameImpl()->frameView(), event);
635 // Handle link highlighting outside the main switch to avoid getting lost in the
636 // complicated set of cases handled below.
637 switch (event.type) {
638 case WebInputEvent::GestureShowPress:
639 // Queue a highlight animation, then hand off to regular handler.
640 if (settingsImpl()->gestureTapHighlightEnabled())
641 enableTapHighlightAtPoint(platformEvent);
643 case WebInputEvent::GestureTapCancel:
644 case WebInputEvent::GestureTap:
645 case WebInputEvent::GestureLongPress:
646 for (size_t i = 0; i < m_linkHighlights.size(); ++i)
647 m_linkHighlights[i]->startHighlightAnimationIfNeeded();
653 switch (event.type) {
654 case WebInputEvent::GestureTap: {
655 m_client->cancelScheduledContentIntents();
656 if (detectContentOnTouch(platformEvent.position())) {
657 eventSwallowed = true;
661 RefPtr<PopupContainer> selectPopup;
662 selectPopup = m_selectPopup;
664 ASSERT(!m_selectPopup);
666 // Don't trigger a disambiguation popup on sites designed for mobile devices.
667 // Instead, assume that the page has been designed with big enough buttons and links.
668 if (event.data.tap.width > 0 && !shouldDisableDesktopWorkarounds()) {
669 // FIXME: didTapMultipleTargets should just take a rect instead of
671 WebGestureEvent scaledEvent = event;
672 scaledEvent.x = event.x / pageScaleFactor();
673 scaledEvent.y = event.y / pageScaleFactor();
674 scaledEvent.data.tap.width = event.data.tap.width / pageScaleFactor();
675 scaledEvent.data.tap.height = event.data.tap.height / pageScaleFactor();
676 IntRect boundingBox(scaledEvent.x - scaledEvent.data.tap.width / 2, scaledEvent.y - scaledEvent.data.tap.height / 2, scaledEvent.data.tap.width, scaledEvent.data.tap.height);
677 Vector<IntRect> goodTargets;
678 Vector<Node*> highlightNodes;
679 findGoodTouchTargets(boundingBox, mainFrameImpl()->frame(), goodTargets, highlightNodes);
680 // FIXME: replace touch adjustment code when numberOfGoodTargets == 1?
681 // Single candidate case is currently handled by: https://bugs.webkit.org/show_bug.cgi?id=85101
682 if (goodTargets.size() >= 2 && m_client && m_client->didTapMultipleTargets(scaledEvent, goodTargets)) {
683 if (settingsImpl()->gestureTapHighlightEnabled())
684 enableTapHighlights(highlightNodes);
685 for (size_t i = 0; i < m_linkHighlights.size(); ++i)
686 m_linkHighlights[i]->startHighlightAnimationIfNeeded();
687 eventSwallowed = true;
688 eventCancelled = true;
693 eventSwallowed = mainFrameImpl()->frame()->eventHandler().handleGestureEvent(platformEvent);
695 if (m_selectPopup && m_selectPopup == selectPopup) {
696 // That tap triggered a select popup which is the same as the one that
697 // was showing before the tap. It means the user tapped the select
698 // while the popup was showing, and as a result we first closed then
699 // immediately reopened the select popup. It needs to be closed.
705 case WebInputEvent::GestureTwoFingerTap:
706 case WebInputEvent::GestureLongPress:
707 case WebInputEvent::GestureLongTap: {
708 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
711 m_client->cancelScheduledContentIntents();
712 m_page->contextMenuController().clearContextMenu();
713 m_contextMenuAllowed = true;
714 eventSwallowed = mainFrameImpl()->frame()->eventHandler().handleGestureEvent(platformEvent);
715 m_contextMenuAllowed = false;
719 case WebInputEvent::GestureShowPress: {
720 m_client->cancelScheduledContentIntents();
721 eventSwallowed = mainFrameImpl()->frame()->eventHandler().handleGestureEvent(platformEvent);
724 case WebInputEvent::GestureDoubleTap:
725 if (m_webSettings->doubleTapToZoomEnabled() && minimumPageScaleFactor() != maximumPageScaleFactor()) {
726 m_client->cancelScheduledContentIntents();
727 animateDoubleTapZoom(platformEvent.position());
729 // GestureDoubleTap is currently only used by Android for zooming. For WebCore,
730 // GestureTap with tap count = 2 is used instead. So we drop GestureDoubleTap here.
731 eventSwallowed = true;
733 case WebInputEvent::GestureScrollBegin:
734 case WebInputEvent::GesturePinchBegin:
735 m_client->cancelScheduledContentIntents();
736 case WebInputEvent::GestureTapDown:
737 case WebInputEvent::GestureScrollEnd:
738 case WebInputEvent::GestureScrollUpdate:
739 case WebInputEvent::GestureScrollUpdateWithoutPropagation:
740 case WebInputEvent::GestureTapCancel:
741 case WebInputEvent::GestureTapUnconfirmed:
742 case WebInputEvent::GesturePinchEnd:
743 case WebInputEvent::GesturePinchUpdate:
744 case WebInputEvent::GestureFlingStart: {
745 eventSwallowed = mainFrameImpl()->frame()->eventHandler().handleGestureEvent(platformEvent);
749 ASSERT_NOT_REACHED();
751 m_client->didHandleGestureEvent(event, eventCancelled);
752 return eventSwallowed;
755 void WebViewImpl::transferActiveWheelFlingAnimation(const WebActiveWheelFlingParameters& parameters)
757 TRACE_EVENT0("webkit", "WebViewImpl::transferActiveWheelFlingAnimation");
758 ASSERT(!m_gestureAnimation);
759 m_positionOnFlingStart = parameters.point;
760 m_globalPositionOnFlingStart = parameters.globalPoint;
761 m_flingModifier = parameters.modifiers;
762 OwnPtr<WebGestureCurve> curve = adoptPtr(Platform::current()->createFlingAnimationCurve(parameters.sourceDevice, WebFloatPoint(parameters.delta), parameters.cumulativeScroll));
763 m_gestureAnimation = WebActiveGestureAnimation::createWithTimeOffset(curve.release(), this, parameters.startTime);
767 bool WebViewImpl::endActiveFlingAnimation()
769 if (m_gestureAnimation) {
770 m_gestureAnimation.clear();
772 m_layerTreeView->didStopFlinging();
778 bool WebViewImpl::startPageScaleAnimation(const IntPoint& targetPosition, bool useAnchor, float newScale, double durationInSeconds)
780 WebPoint clampedPoint = targetPosition;
782 clampedPoint = clampOffsetAtScale(targetPosition, newScale);
783 if (!durationInSeconds) {
784 setPageScaleFactor(newScale, clampedPoint);
788 if (useAnchor && newScale == pageScaleFactor())
791 if (m_enableFakePageScaleAnimationForTesting) {
792 m_fakePageScaleAnimationTargetPosition = targetPosition;
793 m_fakePageScaleAnimationUseAnchor = useAnchor;
794 m_fakePageScaleAnimationPageScaleFactor = newScale;
796 if (!m_layerTreeView)
798 m_layerTreeView->startPageScaleAnimation(targetPosition, useAnchor, newScale, durationInSeconds);
803 void WebViewImpl::enableFakePageScaleAnimationForTesting(bool enable)
805 m_enableFakePageScaleAnimationForTesting = enable;
808 void WebViewImpl::setShowFPSCounter(bool show)
810 if (m_layerTreeView) {
811 TRACE_EVENT0("webkit", "WebViewImpl::setShowFPSCounter");
812 m_layerTreeView->setShowFPSCounter(show);
814 m_showFPSCounter = show;
817 void WebViewImpl::setShowPaintRects(bool show)
819 if (m_layerTreeView) {
820 TRACE_EVENT0("webkit", "WebViewImpl::setShowPaintRects");
821 m_layerTreeView->setShowPaintRects(show);
823 m_showPaintRects = show;
826 void WebViewImpl::setShowDebugBorders(bool show)
829 m_layerTreeView->setShowDebugBorders(show);
830 m_showDebugBorders = show;
833 void WebViewImpl::setContinuousPaintingEnabled(bool enabled)
835 if (m_layerTreeView) {
836 TRACE_EVENT0("webkit", "WebViewImpl::setContinuousPaintingEnabled");
837 m_layerTreeView->setContinuousPaintingEnabled(enabled);
839 m_continuousPaintingEnabled = enabled;
840 m_client->scheduleAnimation();
843 void WebViewImpl::setShowScrollBottleneckRects(bool show)
846 m_layerTreeView->setShowScrollBottleneckRects(show);
847 m_showScrollBottleneckRects = show;
850 void WebViewImpl::getSelectionRootBounds(WebRect& bounds) const
852 const LocalFrame* frame = focusedWebCoreFrame();
856 Element* root = frame->selection().rootEditableElementOrDocumentElement();
860 // If the selection is inside a form control, the root will be a <div> that
861 // behaves as the editor but we want to return the actual element's bounds.
862 // In practice, that means <textarea> and <input> controls that behave like
864 Element* shadowHost = root->shadowHost();
866 && (isHTMLTextAreaElement(*shadowHost)
867 || (isHTMLInputElement(*shadowHost)
868 && toHTMLInputElement(*shadowHost).isText())))
871 IntRect boundingBox = isHTMLHtmlElement(root)
872 ? IntRect(IntPoint(0, 0), root->document().frame()->view()->contentsSize())
873 : root->pixelSnappedBoundingBox();
875 boundingBox = root->document().frame()->view()->contentsToWindow(boundingBox);
876 boundingBox.scale(pageScaleFactor());
877 bounds = boundingBox;
880 bool WebViewImpl::handleKeyEvent(const WebKeyboardEvent& event)
882 ASSERT((event.type == WebInputEvent::RawKeyDown)
883 || (event.type == WebInputEvent::KeyDown)
884 || (event.type == WebInputEvent::KeyUp));
886 // Halt an in-progress fling on a key event.
887 endActiveFlingAnimation();
889 // Please refer to the comments explaining the m_suppressNextKeypressEvent
891 // The m_suppressNextKeypressEvent is set if the KeyDown is handled by
892 // Webkit. A keyDown event is typically associated with a keyPress(char)
893 // event and a keyUp event. We reset this flag here as this is a new keyDown
895 m_suppressNextKeypressEvent = false;
897 // If there is a select popup, it should be the one processing the event,
900 return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
902 m_pagePopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
903 // We need to ignore the next Char event after this otherwise pressing
904 // enter when selecting an item in the popup will go to the page.
905 if (WebInputEvent::RawKeyDown == event.type)
906 m_suppressNextKeypressEvent = true;
910 RefPtr<LocalFrame> frame = focusedWebCoreFrame();
915 const WebInputEvent::Type contextMenuTriggeringEventType =
917 WebInputEvent::KeyUp;
919 WebInputEvent::RawKeyDown;
922 bool isUnmodifiedMenuKey = !(event.modifiers & WebInputEvent::InputModifiers) && event.windowsKeyCode == VKEY_APPS;
923 bool isShiftF10 = event.modifiers == WebInputEvent::ShiftKey && event.windowsKeyCode == VKEY_F10;
924 if ((isUnmodifiedMenuKey || isShiftF10) && event.type == contextMenuTriggeringEventType) {
925 sendContextMenuEvent(event);
928 #endif // !OS(MACOSX)
930 PlatformKeyboardEventBuilder evt(event);
932 if (frame->eventHandler().keyEvent(evt)) {
933 if (WebInputEvent::RawKeyDown == event.type) {
934 // Suppress the next keypress event unless the focused node is a plug-in node.
935 // (Flash needs these keypress events to handle non-US keyboards.)
936 Element* element = focusedElement();
937 if (!element || !element->renderer() || !element->renderer()->isEmbeddedObject())
938 m_suppressNextKeypressEvent = true;
943 return keyEventDefault(event);
946 bool WebViewImpl::handleCharEvent(const WebKeyboardEvent& event)
948 ASSERT(event.type == WebInputEvent::Char);
950 // Please refer to the comments explaining the m_suppressNextKeypressEvent
951 // member. The m_suppressNextKeypressEvent is set if the KeyDown is
952 // handled by Webkit. A keyDown event is typically associated with a
953 // keyPress(char) event and a keyUp event. We reset this flag here as it
954 // only applies to the current keyPress event.
955 bool suppress = m_suppressNextKeypressEvent;
956 m_suppressNextKeypressEvent = false;
958 // If there is a select popup, it should be the one processing the event,
961 return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
963 return m_pagePopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
965 LocalFrame* frame = focusedWebCoreFrame();
969 EventHandler& handler = frame->eventHandler();
971 PlatformKeyboardEventBuilder evt(event);
972 if (!evt.isCharacterKey())
975 // Accesskeys are triggered by char events and can't be suppressed.
976 if (handler.handleAccessKey(evt))
979 // Safari 3.1 does not pass off windows system key messages (WM_SYSCHAR) to
980 // the eventHandler::keyEvent. We mimic this behavior on all platforms since
981 // for now we are converting other platform's key events to windows key
983 if (evt.isSystemKey())
986 if (!suppress && !handler.keyEvent(evt))
987 return keyEventDefault(event);
992 WebRect WebViewImpl::computeBlockBounds(const WebRect& rect, bool ignoreClipping)
994 if (!mainFrameImpl())
997 // Use the rect-based hit test to find the node.
998 IntPoint point = mainFrameImpl()->frameView()->windowToContents(IntPoint(rect.x, rect.y));
999 HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent | (ignoreClipping ? HitTestRequest::IgnoreClipping : 0);
1000 HitTestResult result = mainFrameImpl()->frame()->eventHandler().hitTestResultAtPoint(point, hitType, IntSize(rect.width, rect.height));
1002 Node* node = result.innerNonSharedNode();
1006 // Find the block type node based on the hit node.
1007 while (node && (!node->renderer() || node->renderer()->isInline()))
1008 node = node->parentNode();
1010 // Return the bounding box in the window coordinate system.
1012 IntRect rect = node->Node::pixelSnappedBoundingBox();
1013 LocalFrame* frame = node->document().frame();
1014 return frame->view()->contentsToWindow(rect);
1019 WebRect WebViewImpl::widenRectWithinPageBounds(const WebRect& source, int targetMargin, int minimumMargin)
1023 maxSize = mainFrame()->contentsSize();
1024 IntSize scrollOffset;
1026 scrollOffset = mainFrame()->scrollOffset();
1027 int leftMargin = targetMargin;
1028 int rightMargin = targetMargin;
1030 const int absoluteSourceX = source.x + scrollOffset.width();
1031 if (leftMargin > absoluteSourceX) {
1032 leftMargin = absoluteSourceX;
1033 rightMargin = max(leftMargin, minimumMargin);
1036 const int maximumRightMargin = maxSize.width - (source.width + absoluteSourceX);
1037 if (rightMargin > maximumRightMargin) {
1038 rightMargin = maximumRightMargin;
1039 leftMargin = min(leftMargin, max(rightMargin, minimumMargin));
1042 const int newWidth = source.width + leftMargin + rightMargin;
1043 const int newX = source.x - leftMargin;
1045 ASSERT(newWidth >= 0);
1046 ASSERT(scrollOffset.width() + newX + newWidth <= maxSize.width);
1048 return WebRect(newX, source.y, newWidth, source.height);
1051 float WebViewImpl::legibleScale() const
1053 // Pages should be as legible as on desktop when at dpi scale, so no
1054 // need to zoom in further when automatically determining zoom level
1055 // (after double tap, find in page, etc), though the user should still
1056 // be allowed to manually pinch zoom in further if they desire.
1057 float legibleScale = 1;
1059 legibleScale *= page()->settings().accessibilityFontScaleFactor();
1060 return legibleScale;
1063 void WebViewImpl::computeScaleAndScrollForBlockRect(const WebPoint& hitPoint, const WebRect& blockRect, float padding, float defaultScaleWhenAlreadyLegible, float& scale, WebPoint& scroll)
1065 scale = pageScaleFactor();
1066 scroll.x = scroll.y = 0;
1068 WebRect rect = blockRect;
1070 if (!rect.isEmpty()) {
1071 float defaultMargin = doubleTapZoomContentDefaultMargin;
1072 float minimumMargin = doubleTapZoomContentMinimumMargin;
1073 // We want the margins to have the same physical size, which means we
1074 // need to express them in post-scale size. To do that we'd need to know
1075 // the scale we're scaling to, but that depends on the margins. Instead
1076 // we express them as a fraction of the target rectangle: this will be
1077 // correct if we end up fully zooming to it, and won't matter if we
1079 rect = widenRectWithinPageBounds(rect,
1080 static_cast<int>(defaultMargin * rect.width / m_size.width),
1081 static_cast<int>(minimumMargin * rect.width / m_size.width));
1082 // Fit block to screen, respecting limits.
1083 scale = static_cast<float>(m_size.width) / rect.width;
1084 scale = min(scale, legibleScale());
1085 if (pageScaleFactor() < defaultScaleWhenAlreadyLegible)
1086 scale = max(scale, defaultScaleWhenAlreadyLegible);
1087 scale = clampPageScaleFactorToLimits(scale);
1090 // FIXME: If this is being called for auto zoom during find in page,
1091 // then if the user manually zooms in it'd be nice to preserve the
1092 // relative increase in zoom they caused (if they zoom out then it's ok
1093 // to zoom them back in again). This isn't compatible with our current
1094 // double-tap zoom strategy (fitting the containing block to the screen)
1097 float screenWidth = m_size.width / scale;
1098 float screenHeight = m_size.height / scale;
1100 // Scroll to vertically align the block.
1101 if (rect.height < screenHeight) {
1102 // Vertically center short blocks.
1103 rect.y -= 0.5 * (screenHeight - rect.height);
1105 // Ensure position we're zooming to (+ padding) isn't off the bottom of
1107 rect.y = max<float>(rect.y, hitPoint.y + padding - screenHeight);
1108 } // Otherwise top align the block.
1110 // Do the same thing for horizontal alignment.
1111 if (rect.width < screenWidth)
1112 rect.x -= 0.5 * (screenWidth - rect.width);
1114 rect.x = max<float>(rect.x, hitPoint.x + padding - screenWidth);
1118 scale = clampPageScaleFactorToLimits(scale);
1119 scroll = mainFrameImpl()->frameView()->windowToContents(scroll);
1120 scroll = clampOffsetAtScale(scroll, scale);
1123 static bool invokesHandCursor(Node* node, bool shiftKey, LocalFrame* frame)
1125 if (!node || !node->renderer())
1128 ECursor cursor = node->renderer()->style()->cursor();
1129 return cursor == CURSOR_POINTER
1130 || (cursor == CURSOR_AUTO && frame->eventHandler().useHandCursor(node, node->isLink(), shiftKey));
1133 Node* WebViewImpl::bestTapNode(const PlatformGestureEvent& tapEvent)
1135 if (!m_page || !m_page->mainFrame())
1138 Node* bestTouchNode = 0;
1140 IntPoint touchEventLocation(tapEvent.position());
1141 m_page->mainFrame()->eventHandler().adjustGesturePosition(tapEvent, touchEventLocation);
1143 IntPoint hitTestPoint = m_page->mainFrame()->view()->windowToContents(touchEventLocation);
1144 HitTestResult result = m_page->mainFrame()->eventHandler().hitTestResultAtPoint(hitTestPoint, HitTestRequest::TouchEvent | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
1145 bestTouchNode = result.targetNode();
1147 // We might hit something like an image map that has no renderer on it
1148 // Walk up the tree until we have a node with an attached renderer
1149 while (bestTouchNode && !bestTouchNode->renderer())
1150 bestTouchNode = bestTouchNode->parentNode();
1152 // Check if we're in the subtree of a node with a hand cursor
1153 // this is the heuristic we use to determine if we show a highlight on tap
1154 while (bestTouchNode && !invokesHandCursor(bestTouchNode, false, m_page->mainFrame()))
1155 bestTouchNode = bestTouchNode->parentNode();
1160 // We should pick the largest enclosing node with hand cursor set.
1161 while (bestTouchNode->parentNode() && invokesHandCursor(bestTouchNode->parentNode(), false, m_page->mainFrame()))
1162 bestTouchNode = bestTouchNode->parentNode();
1164 return bestTouchNode;
1167 void WebViewImpl::enableTapHighlightAtPoint(const PlatformGestureEvent& tapEvent)
1169 Node* touchNode = bestTapNode(tapEvent);
1171 Vector<Node*> highlightNodes;
1172 highlightNodes.append(touchNode);
1174 enableTapHighlights(highlightNodes);
1177 void WebViewImpl::enableTapHighlights(Vector<Node*>& highlightNodes)
1179 if (highlightNodes.isEmpty())
1182 // Always clear any existing highlight when this is invoked, even if we
1183 // don't get a new target to highlight.
1184 m_linkHighlights.clear();
1186 // LinkHighlight reads out layout and compositing state, so we need to make sure that's all up to date.
1189 for (size_t i = 0; i < highlightNodes.size(); ++i) {
1190 Node* node = highlightNodes[i];
1192 if (!node || !node->renderer())
1195 Color highlightColor = node->renderer()->style()->tapHighlightColor();
1196 // Safari documentation for -webkit-tap-highlight-color says if the specified color has 0 alpha,
1197 // then tap highlighting is disabled.
1198 // http://developer.apple.com/library/safari/#documentation/appleapplications/reference/safaricssref/articles/standardcssproperties.html
1199 if (!highlightColor.alpha())
1202 m_linkHighlights.append(LinkHighlight::create(node, this));
1206 void WebViewImpl::animateDoubleTapZoom(const IntPoint& point)
1208 if (!mainFrameImpl())
1211 WebRect rect(point.x(), point.y(), touchPointPadding, touchPointPadding);
1212 WebRect blockBounds = computeBlockBounds(rect, false);
1217 computeScaleAndScrollForBlockRect(point, blockBounds, touchPointPadding, minimumPageScaleFactor() * doubleTapZoomAlreadyLegibleRatio, scale, scroll);
1219 bool stillAtPreviousDoubleTapScale = (pageScaleFactor() == m_doubleTapZoomPageScaleFactor
1220 && m_doubleTapZoomPageScaleFactor != minimumPageScaleFactor())
1221 || m_doubleTapZoomPending;
1223 bool scaleUnchanged = fabs(pageScaleFactor() - scale) < minScaleDifference;
1224 bool shouldZoomOut = blockBounds.isEmpty() || scaleUnchanged || stillAtPreviousDoubleTapScale;
1228 if (shouldZoomOut) {
1229 scale = minimumPageScaleFactor();
1230 isAnimating = startPageScaleAnimation(mainFrameImpl()->frameView()->windowToContents(point), true, scale, doubleTapZoomAnimationDurationInSeconds);
1232 isAnimating = startPageScaleAnimation(scroll, false, scale, doubleTapZoomAnimationDurationInSeconds);
1236 m_doubleTapZoomPageScaleFactor = scale;
1237 m_doubleTapZoomPending = true;
1241 void WebViewImpl::zoomToFindInPageRect(const WebRect& rect)
1243 if (!mainFrameImpl())
1246 WebRect blockBounds = computeBlockBounds(rect, true);
1248 if (blockBounds.isEmpty()) {
1249 // Keep current scale (no need to scroll as x,y will normally already
1250 // be visible). FIXME: Revisit this if it isn't always true.
1257 computeScaleAndScrollForBlockRect(WebPoint(rect.x, rect.y), blockBounds, nonUserInitiatedPointPadding, minimumPageScaleFactor(), scale, scroll);
1259 startPageScaleAnimation(scroll, false, scale, findInPageAnimationDurationInSeconds);
1262 bool WebViewImpl::zoomToMultipleTargetsRect(const WebRect& rect)
1264 if (!mainFrameImpl())
1270 computeScaleAndScrollForBlockRect(WebPoint(rect.x, rect.y), rect, nonUserInitiatedPointPadding, minimumPageScaleFactor(), scale, scroll);
1272 if (scale <= pageScaleFactor())
1275 startPageScaleAnimation(scroll, false, scale, multipleTargetsZoomAnimationDurationInSeconds);
1279 void WebViewImpl::numberOfWheelEventHandlersChanged(unsigned numberOfWheelHandlers)
1282 m_client->numberOfWheelEventHandlersChanged(numberOfWheelHandlers);
1285 void WebViewImpl::hasTouchEventHandlers(bool hasTouchHandlers)
1288 m_client->hasTouchEventHandlers(hasTouchHandlers);
1291 bool WebViewImpl::hasTouchEventHandlersAt(const WebPoint& point)
1293 // FIXME: Implement this. Note that the point must be divided by pageScaleFactor.
1298 // Mac has no way to open a context menu based on a keyboard event.
1299 bool WebViewImpl::sendContextMenuEvent(const WebKeyboardEvent& event)
1301 // The contextMenuController() holds onto the last context menu that was
1302 // popped up on the page until a new one is created. We need to clear
1303 // this menu before propagating the event through the DOM so that we can
1304 // detect if we create a new menu for this event, since we won't create
1305 // a new menu if the DOM swallows the event and the defaultEventHandler does
1307 page()->contextMenuController().clearContextMenu();
1309 m_contextMenuAllowed = true;
1310 LocalFrame* focusedFrame = page()->focusController().focusedOrMainFrame();
1311 bool handled = focusedFrame->eventHandler().sendContextMenuEventForKey();
1312 m_contextMenuAllowed = false;
1317 bool WebViewImpl::keyEventDefault(const WebKeyboardEvent& event)
1319 LocalFrame* frame = focusedWebCoreFrame();
1323 switch (event.type) {
1324 case WebInputEvent::Char:
1325 if (event.windowsKeyCode == VKEY_SPACE) {
1326 int keyCode = ((event.modifiers & WebInputEvent::ShiftKey) ? VKEY_PRIOR : VKEY_NEXT);
1327 return scrollViewWithKeyboard(keyCode, event.modifiers);
1330 case WebInputEvent::RawKeyDown:
1331 if (event.modifiers == WebInputEvent::ControlKey) {
1332 switch (event.windowsKeyCode) {
1335 focusedFrame()->executeCommand(WebString::fromUTF8("SelectAll"));
1339 focusedFrame()->executeCommand(WebString::fromUTF8("Copy"));
1342 // Match FF behavior in the sense that Ctrl+home/end are the only Ctrl
1343 // key combinations which affect scrolling. Safari is buggy in the
1344 // sense that it scrolls the page for all Ctrl+scrolling key
1345 // combinations. For e.g. Ctrl+pgup/pgdn/up/down, etc.
1353 if (!event.isSystemKey && !(event.modifiers & WebInputEvent::ShiftKey))
1354 return scrollViewWithKeyboard(event.windowsKeyCode, event.modifiers);
1362 bool WebViewImpl::scrollViewWithKeyboard(int keyCode, int modifiers)
1364 ScrollDirection scrollDirection;
1365 ScrollGranularity scrollGranularity;
1367 // Control-Up/Down should be PageUp/Down on Mac.
1368 if (modifiers & WebMouseEvent::ControlKey) {
1369 if (keyCode == VKEY_UP)
1370 keyCode = VKEY_PRIOR;
1371 else if (keyCode == VKEY_DOWN)
1372 keyCode = VKEY_NEXT;
1375 if (!mapKeyCodeForScroll(keyCode, &scrollDirection, &scrollGranularity))
1377 return bubblingScroll(scrollDirection, scrollGranularity);
1380 bool WebViewImpl::mapKeyCodeForScroll(int keyCode,
1381 WebCore::ScrollDirection* scrollDirection,
1382 WebCore::ScrollGranularity* scrollGranularity)
1386 *scrollDirection = ScrollLeft;
1387 *scrollGranularity = ScrollByLine;
1390 *scrollDirection = ScrollRight;
1391 *scrollGranularity = ScrollByLine;
1394 *scrollDirection = ScrollUp;
1395 *scrollGranularity = ScrollByLine;
1398 *scrollDirection = ScrollDown;
1399 *scrollGranularity = ScrollByLine;
1402 *scrollDirection = ScrollUp;
1403 *scrollGranularity = ScrollByDocument;
1406 *scrollDirection = ScrollDown;
1407 *scrollGranularity = ScrollByDocument;
1409 case VKEY_PRIOR: // page up
1410 *scrollDirection = ScrollUp;
1411 *scrollGranularity = ScrollByPage;
1413 case VKEY_NEXT: // page down
1414 *scrollDirection = ScrollDown;
1415 *scrollGranularity = ScrollByPage;
1424 void WebViewImpl::hideSelectPopup()
1427 m_selectPopup->hidePopup();
1430 bool WebViewImpl::bubblingScroll(ScrollDirection scrollDirection, ScrollGranularity scrollGranularity)
1432 LocalFrame* frame = focusedWebCoreFrame();
1436 return frame->eventHandler().bubblingScroll(scrollDirection, scrollGranularity);
1439 void WebViewImpl::popupOpened(PopupContainer* popupContainer)
1441 ASSERT(!m_selectPopup);
1442 m_selectPopup = popupContainer;
1443 ASSERT(mainFrameImpl()->frame()->document());
1444 Document& document = *mainFrameImpl()->frame()->document();
1445 WheelController::from(document)->didAddWheelEventHandler(document);
1448 void WebViewImpl::popupClosed(PopupContainer* popupContainer)
1450 ASSERT(m_selectPopup);
1451 m_selectPopup = nullptr;
1452 ASSERT(mainFrameImpl()->frame()->document());
1453 Document& document = *mainFrameImpl()->frame()->document();
1454 WheelController::from(document)->didRemoveWheelEventHandler(document);
1457 PagePopup* WebViewImpl::openPagePopup(PagePopupClient* client, const IntRect& originBoundsInRootView)
1460 if (hasOpenedPopup())
1462 ASSERT(!m_pagePopup);
1464 WebWidget* popupWidget = m_client->createPopupMenu(WebPopupTypePage);
1465 ASSERT(popupWidget);
1466 m_pagePopup = toWebPagePopupImpl(popupWidget);
1467 if (!m_pagePopup->initialize(this, client, originBoundsInRootView)) {
1468 m_pagePopup->closePopup();
1469 m_pagePopup = nullptr;
1471 return m_pagePopup.get();
1474 void WebViewImpl::closePagePopup(PagePopup* popup)
1477 WebPagePopupImpl* popupImpl = toWebPagePopupImpl(popup);
1478 ASSERT(m_pagePopup.get() == popupImpl);
1479 if (m_pagePopup.get() != popupImpl)
1481 m_pagePopup->closePopup();
1482 m_pagePopup = nullptr;
1485 LocalFrame* WebViewImpl::focusedWebCoreFrame() const
1487 return m_page ? m_page->focusController().focusedOrMainFrame() : 0;
1490 WebViewImpl* WebViewImpl::fromPage(Page* page)
1494 return static_cast<WebViewImpl*>(page->chrome().client().webView());
1497 // WebWidget ------------------------------------------------------------------
1499 void WebViewImpl::close()
1502 // Initiate shutdown for the entire frameset. This will cause a lot of
1503 // notifications to be sent.
1504 if (m_page->mainFrame())
1505 m_page->mainFrame()->loader().frameDetached();
1510 // Should happen after m_page.clear().
1511 if (m_devToolsAgent)
1512 m_devToolsAgent.clear();
1514 // Reset the delegate to prevent notifications being sent as we're being
1518 deref(); // Balances ref() acquired in WebView::create
1521 void WebViewImpl::willStartLiveResize()
1523 if (mainFrameImpl() && mainFrameImpl()->frameView())
1524 mainFrameImpl()->frameView()->willStartLiveResize();
1526 LocalFrame* frame = mainFrameImpl()->frame();
1527 WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1528 if (pluginContainer)
1529 pluginContainer->willStartLiveResize();
1532 WebSize WebViewImpl::size()
1537 void WebViewImpl::resize(const WebSize& newSize)
1539 if (m_shouldAutoResize || m_size == newSize)
1542 FrameView* view = mainFrameImpl()->frameView();
1546 WebSize oldSize = m_size;
1547 float oldPageScaleFactor = pageScaleFactor();
1548 int oldContentsWidth = contentsSize().width();
1552 bool shouldAnchorAndRescaleViewport = settings()->mainFrameResizesAreOrientationChanges()
1553 && oldSize.width && oldContentsWidth && newSize.width != oldSize.width;
1555 ViewportAnchor viewportAnchor(&mainFrameImpl()->frame()->eventHandler());
1556 if (shouldAnchorAndRescaleViewport) {
1557 viewportAnchor.setAnchor(view->visibleContentRect(),
1558 FloatSize(viewportAnchorXCoord, viewportAnchorYCoord));
1561 updatePageDefinedViewportConstraints(mainFrameImpl()->frame()->document()->viewportDescription());
1562 updateMainFrameLayoutSize();
1564 WebDevToolsAgentPrivate* agentPrivate = devToolsAgentPrivate();
1566 agentPrivate->webViewResized(newSize);
1567 WebFrameImpl* webFrame = mainFrameImpl();
1568 if (webFrame->frameView()) {
1569 webFrame->frameView()->resize(m_size);
1570 if (page()->settings().pinchVirtualViewportEnabled())
1571 page()->frameHost().pinchViewport().setSize(m_size);
1574 if (settings()->viewportEnabled() && !m_fixedLayoutSizeLock) {
1575 // Relayout immediately to recalculate the minimum scale limit.
1576 if (view->needsLayout())
1579 if (shouldAnchorAndRescaleViewport) {
1580 float viewportWidthRatio = static_cast<float>(newSize.width) / oldSize.width;
1581 float contentsWidthRatio = static_cast<float>(contentsSize().width()) / oldContentsWidth;
1582 float scaleMultiplier = viewportWidthRatio / contentsWidthRatio;
1584 IntSize viewportSize = view->visibleContentRect().size();
1585 if (scaleMultiplier != 1) {
1586 float newPageScaleFactor = oldPageScaleFactor * scaleMultiplier;
1587 viewportSize.scale(pageScaleFactor() / newPageScaleFactor);
1588 IntPoint scrollOffsetAtNewScale = viewportAnchor.computeOrigin(viewportSize);
1589 setPageScaleFactor(newPageScaleFactor, scrollOffsetAtNewScale);
1591 IntPoint scrollOffsetAtNewScale = clampOffsetAtScale(viewportAnchor.computeOrigin(viewportSize), pageScaleFactor());
1592 updateMainFrameScrollPosition(scrollOffsetAtNewScale, false);
1597 sendResizeEventAndRepaint();
1600 void WebViewImpl::willEndLiveResize()
1602 if (mainFrameImpl() && mainFrameImpl()->frameView())
1603 mainFrameImpl()->frameView()->willEndLiveResize();
1605 LocalFrame* frame = mainFrameImpl()->frame();
1606 WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1607 if (pluginContainer)
1608 pluginContainer->willEndLiveResize();
1611 void WebViewImpl::willEnterFullScreen()
1613 m_fullscreenController->willEnterFullScreen();
1616 void WebViewImpl::didEnterFullScreen()
1618 m_fullscreenController->didEnterFullScreen();
1621 void WebViewImpl::willExitFullScreen()
1623 m_fullscreenController->willExitFullScreen();
1626 void WebViewImpl::didExitFullScreen()
1628 m_fullscreenController->didExitFullScreen();
1631 void WebViewImpl::animate(double monotonicFrameBeginTime)
1633 TRACE_EVENT0("webkit", "WebViewImpl::animate");
1635 if (!monotonicFrameBeginTime)
1636 monotonicFrameBeginTime = monotonicallyIncreasingTime();
1638 // Create synthetic wheel events as necessary for fling.
1639 if (m_gestureAnimation) {
1640 if (m_gestureAnimation->animate(monotonicFrameBeginTime))
1641 scheduleAnimation();
1643 endActiveFlingAnimation();
1645 PlatformGestureEvent endScrollEvent(PlatformEvent::GestureScrollEnd,
1646 m_positionOnFlingStart, m_globalPositionOnFlingStart,
1647 IntSize(), 0, false, false, false, false,
1650 mainFrameImpl()->frame()->eventHandler().handleGestureScrollEnd(endScrollEvent);
1657 PageWidgetDelegate::animate(m_page.get(), monotonicFrameBeginTime);
1659 if (m_continuousPaintingEnabled) {
1660 ContinuousPainter::setNeedsDisplayRecursive(m_rootGraphicsLayer, m_pageOverlays.get());
1661 m_client->scheduleAnimation();
1665 void WebViewImpl::layout()
1667 TRACE_EVENT0("webkit", "WebViewImpl::layout");
1668 PageWidgetDelegate::layout(m_page.get());
1669 updateLayerTreeBackgroundColor();
1671 for (size_t i = 0; i < m_linkHighlights.size(); ++i)
1672 m_linkHighlights[i]->updateGeometry();
1675 void WebViewImpl::enterForceCompositingMode(bool enter)
1677 if (page()->settings().forceCompositingMode() == enter)
1680 TRACE_EVENT1("webkit", "WebViewImpl::enterForceCompositingMode", "enter", enter);
1681 settingsImpl()->setForceCompositingMode(enter);
1685 LocalFrame* mainFrame = m_page->mainFrame();
1688 mainFrame->view()->updateCompositingLayersAfterStyleChange();
1692 void WebViewImpl::doPixelReadbackToCanvas(WebCanvas* canvas, const IntRect& rect)
1694 ASSERT(m_layerTreeView);
1697 target.setConfig(SkBitmap::kARGB_8888_Config, rect.width(), rect.height(), rect.width() * 4);
1698 target.allocPixels();
1699 m_layerTreeView->compositeAndReadback(target.getPixels(), rect);
1700 #if (!SK_R32_SHIFT && SK_B32_SHIFT == 16)
1701 // The compositor readback always gives back pixels in BGRA order, but for
1702 // example Android's Skia uses RGBA ordering so the red and blue channels
1703 // need to be swapped.
1704 uint8_t* pixels = reinterpret_cast<uint8_t*>(target.getPixels());
1705 for (size_t i = 0; i < target.getSize(); i += 4)
1706 std::swap(pixels[i], pixels[i + 2]);
1708 canvas->writePixels(target, rect.x(), rect.y());
1711 void WebViewImpl::paint(WebCanvas* canvas, const WebRect& rect, PaintOptions option)
1714 // ReadbackFromCompositorIfAvailable is the only option available on non-Android.
1715 // Ideally, Android would always use ReadbackFromCompositorIfAvailable as well.
1716 ASSERT(option == ReadbackFromCompositorIfAvailable);
1719 if (option == ReadbackFromCompositorIfAvailable && isAcceleratedCompositingActive()) {
1720 // If a canvas was passed in, we use it to grab a copy of the
1721 // freshly-rendered pixels.
1723 // Clip rect to the confines of the rootLayerTexture.
1724 IntRect resizeRect(rect);
1725 resizeRect.intersect(IntRect(IntPoint(0, 0), m_layerTreeView->deviceViewportSize()));
1726 doPixelReadbackToCanvas(canvas, resizeRect);
1729 FrameView* view = page()->mainFrame()->view();
1730 PaintBehavior oldPaintBehavior = view->paintBehavior();
1731 if (isAcceleratedCompositingActive()) {
1732 ASSERT(option == ForceSoftwareRenderingAndIgnoreGPUResidentContent);
1733 view->setPaintBehavior(oldPaintBehavior | PaintBehaviorFlattenCompositingLayers);
1736 double paintStart = currentTime();
1737 PageWidgetDelegate::paint(m_page.get(), pageOverlays(), canvas, rect, isTransparent() ? PageWidgetDelegate::Translucent : PageWidgetDelegate::Opaque);
1738 double paintEnd = currentTime();
1739 double pixelsPerSec = (rect.width * rect.height) / (paintEnd - paintStart);
1740 blink::Platform::current()->histogramCustomCounts("Renderer4.SoftwarePaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30);
1741 blink::Platform::current()->histogramCustomCounts("Renderer4.SoftwarePaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30);
1743 if (isAcceleratedCompositingActive()) {
1744 ASSERT(option == ForceSoftwareRenderingAndIgnoreGPUResidentContent);
1745 view->setPaintBehavior(oldPaintBehavior);
1750 bool WebViewImpl::isTrackingRepaints() const
1754 FrameView* view = page()->mainFrame()->view();
1755 return view->isTrackingRepaints();
1758 void WebViewImpl::themeChanged()
1762 FrameView* view = page()->mainFrame()->view();
1764 WebRect damagedRect(0, 0, m_size.width, m_size.height);
1765 view->invalidateRect(damagedRect);
1768 void WebViewImpl::enterFullScreenForElement(WebCore::Element* element)
1770 m_fullscreenController->enterFullScreenForElement(element);
1773 void WebViewImpl::exitFullScreenForElement(WebCore::Element* element)
1775 m_fullscreenController->exitFullScreenForElement(element);
1778 bool WebViewImpl::hasHorizontalScrollbar()
1780 return mainFrameImpl()->frameView()->horizontalScrollbar();
1783 bool WebViewImpl::hasVerticalScrollbar()
1785 return mainFrameImpl()->frameView()->verticalScrollbar();
1788 const WebInputEvent* WebViewImpl::m_currentInputEvent = 0;
1790 bool WebViewImpl::handleInputEvent(const WebInputEvent& inputEvent)
1792 TRACE_EVENT0("input", "WebViewImpl::handleInputEvent");
1793 // If we've started a drag and drop operation, ignore input events until
1795 if (m_doingDragAndDrop)
1798 if (m_devToolsAgent && m_devToolsAgent->handleInputEvent(m_page.get(), inputEvent))
1801 // Report the event to be NOT processed by WebKit, so that the browser can handle it appropriately.
1802 if (m_ignoreInputEvents)
1805 TemporaryChange<const WebInputEvent*> currentEventChange(m_currentInputEvent, &inputEvent);
1807 if (isPointerLocked() && WebInputEvent::isMouseEventType(inputEvent.type)) {
1808 pointerLockMouseEvent(inputEvent);
1812 if (m_mouseCaptureNode && WebInputEvent::isMouseEventType(inputEvent.type)) {
1813 TRACE_EVENT1("input", "captured mouse event", "type", inputEvent.type);
1814 // Save m_mouseCaptureNode since mouseCaptureLost() will clear it.
1815 RefPtr<Node> node = m_mouseCaptureNode;
1817 // Not all platforms call mouseCaptureLost() directly.
1818 if (inputEvent.type == WebInputEvent::MouseUp)
1821 OwnPtr<UserGestureIndicator> gestureIndicator;
1823 AtomicString eventType;
1824 switch (inputEvent.type) {
1825 case WebInputEvent::MouseMove:
1826 eventType = EventTypeNames::mousemove;
1828 case WebInputEvent::MouseLeave:
1829 eventType = EventTypeNames::mouseout;
1831 case WebInputEvent::MouseDown:
1832 eventType = EventTypeNames::mousedown;
1833 gestureIndicator = adoptPtr(new UserGestureIndicator(DefinitelyProcessingNewUserGesture));
1834 m_mouseCaptureGestureToken = gestureIndicator->currentToken();
1836 case WebInputEvent::MouseUp:
1837 eventType = EventTypeNames::mouseup;
1838 gestureIndicator = adoptPtr(new UserGestureIndicator(m_mouseCaptureGestureToken.release()));
1841 ASSERT_NOT_REACHED();
1844 node->dispatchMouseEvent(
1845 PlatformMouseEventBuilder(mainFrameImpl()->frameView(), *static_cast<const WebMouseEvent*>(&inputEvent)),
1846 eventType, static_cast<const WebMouseEvent*>(&inputEvent)->clickCount);
1850 return PageWidgetDelegate::handleInputEvent(m_page.get(), *this, inputEvent);
1853 void WebViewImpl::setCursorVisibilityState(bool isVisible)
1856 m_page->setIsCursorVisible(isVisible);
1859 void WebViewImpl::mouseCaptureLost()
1861 TRACE_EVENT_ASYNC_END0("input", "capturing mouse", this);
1862 m_mouseCaptureNode = nullptr;
1865 void WebViewImpl::setFocus(bool enable)
1867 m_page->focusController().setFocused(enable);
1869 m_page->focusController().setActive(true);
1870 RefPtr<LocalFrame> focusedFrame = m_page->focusController().focusedFrame();
1872 Element* element = focusedFrame->document()->focusedElement();
1873 if (element && focusedFrame->selection().selection().isNone()) {
1874 // If the selection was cleared while the WebView was not
1875 // focused, then the focus element shows with a focus ring but
1876 // no caret and does respond to keyboard inputs.
1877 if (element->isTextFormControl()) {
1878 element->updateFocusAppearance(true);
1879 } else if (element->isContentEditable()) {
1880 // updateFocusAppearance() selects all the text of
1881 // contentseditable DIVs. So we set the selection explicitly
1882 // instead. Note that this has the side effect of moving the
1883 // caret back to the beginning of the text.
1884 Position position(element, 0, Position::PositionIsOffsetInAnchor);
1885 focusedFrame->selection().setSelection(VisibleSelection(position, SEL_DEFAULT_AFFINITY));
1889 m_imeAcceptEvents = true;
1893 // Clear focus on the currently focused frame if any.
1897 LocalFrame* frame = m_page->mainFrame();
1901 RefPtr<LocalFrame> focusedFrame = m_page->focusController().focusedFrame();
1903 // Finish an ongoing composition to delete the composition node.
1904 if (focusedFrame->inputMethodController().hasComposition()) {
1905 if (m_autofillClient)
1906 m_autofillClient->setIgnoreTextChanges(true);
1908 focusedFrame->inputMethodController().confirmComposition();
1910 if (m_autofillClient)
1911 m_autofillClient->setIgnoreTextChanges(false);
1913 m_imeAcceptEvents = false;
1918 bool WebViewImpl::setComposition(
1919 const WebString& text,
1920 const WebVector<WebCompositionUnderline>& underlines,
1924 LocalFrame* focused = focusedWebCoreFrame();
1925 if (!focused || !m_imeAcceptEvents)
1928 if (WebPlugin* plugin = focusedPluginIfInputMethodSupported(focused))
1929 return plugin->setComposition(text, underlines, selectionStart, selectionEnd);
1931 // The input focus has been moved to another WebWidget object.
1932 // We should use this |editor| object only to complete the ongoing
1934 InputMethodController& inputMethodController = focused->inputMethodController();
1935 if (!focused->editor().canEdit() && !inputMethodController.hasComposition())
1938 // We should verify the parent node of this IME composition node are
1939 // editable because JavaScript may delete a parent node of the composition
1940 // node. In this case, WebKit crashes while deleting texts from the parent
1941 // node, which doesn't exist any longer.
1942 RefPtr<Range> range = inputMethodController.compositionRange();
1944 Node* node = range->startContainer();
1945 if (!node || !node->isContentEditable())
1949 // If we're not going to fire a keypress event, then the keydown event was
1950 // canceled. In that case, cancel any existing composition.
1951 if (text.isEmpty() || m_suppressNextKeypressEvent) {
1952 // A browser process sent an IPC message which does not contain a valid
1953 // string, which means an ongoing composition has been canceled.
1954 // If the ongoing composition has been canceled, replace the ongoing
1955 // composition string with an empty string and complete it.
1957 Vector<CompositionUnderline> emptyUnderlines;
1958 inputMethodController.setComposition(emptyString, emptyUnderlines, 0, 0);
1959 return text.isEmpty();
1962 // When the range of composition underlines overlap with the range between
1963 // selectionStart and selectionEnd, WebKit somehow won't paint the selection
1964 // at all (see InlineTextBox::paint() function in InlineTextBox.cpp).
1965 // But the selection range actually takes effect.
1966 inputMethodController.setComposition(String(text),
1967 CompositionUnderlineVectorBuilder(underlines),
1968 selectionStart, selectionEnd);
1970 return inputMethodController.hasComposition();
1973 bool WebViewImpl::confirmComposition()
1975 return confirmComposition(DoNotKeepSelection);
1978 bool WebViewImpl::confirmComposition(ConfirmCompositionBehavior selectionBehavior)
1980 return confirmComposition(WebString(), selectionBehavior);
1983 bool WebViewImpl::confirmComposition(const WebString& text)
1985 return confirmComposition(text, DoNotKeepSelection);
1988 bool WebViewImpl::confirmComposition(const WebString& text, ConfirmCompositionBehavior selectionBehavior)
1990 LocalFrame* focused = focusedWebCoreFrame();
1991 if (!focused || !m_imeAcceptEvents)
1994 if (WebPlugin* plugin = focusedPluginIfInputMethodSupported(focused))
1995 return plugin->confirmComposition(text, selectionBehavior);
1997 return focused->inputMethodController().confirmCompositionOrInsertText(text, selectionBehavior == KeepSelection ? InputMethodController::KeepSelection : InputMethodController::DoNotKeepSelection);
2000 bool WebViewImpl::compositionRange(size_t* location, size_t* length)
2002 LocalFrame* focused = focusedWebCoreFrame();
2003 if (!focused || !m_imeAcceptEvents)
2006 RefPtr<Range> range = focused->inputMethodController().compositionRange();
2010 Element* editable = focused->selection().rootEditableElementOrDocumentElement();
2012 PlainTextRange plainTextRange(PlainTextRange::create(*editable, *range.get()));
2013 if (plainTextRange.isNull())
2015 *location = plainTextRange.start();
2016 *length = plainTextRange.length();
2020 WebTextInputInfo WebViewImpl::textInputInfo()
2022 WebTextInputInfo info;
2024 LocalFrame* focused = focusedWebCoreFrame();
2028 FrameSelection& selection = focused->selection();
2029 Node* node = selection.selection().rootEditableElement();
2033 info.inputMode = inputModeOfFocusedElement();
2035 info.type = textInputType();
2036 if (info.type == WebTextInputTypeNone)
2039 if (!focused->editor().canEdit())
2042 info.value = plainText(rangeOfContents(node).get());
2044 if (info.value.isEmpty())
2047 if (RefPtr<Range> range = selection.selection().firstRange()) {
2048 PlainTextRange plainTextRange(PlainTextRange::create(*node, *range.get()));
2049 if (plainTextRange.isNotNull()) {
2050 info.selectionStart = plainTextRange.start();
2051 info.selectionEnd = plainTextRange.end();
2055 if (RefPtr<Range> range = focused->inputMethodController().compositionRange()) {
2056 PlainTextRange plainTextRange(PlainTextRange::create(*node, *range.get()));
2057 if (plainTextRange.isNotNull()) {
2058 info.compositionStart = plainTextRange.start();
2059 info.compositionEnd = plainTextRange.end();
2066 WebTextInputType WebViewImpl::textInputType()
2068 Element* element = focusedElement();
2070 return WebTextInputTypeNone;
2072 if (isHTMLInputElement(*element)) {
2073 HTMLInputElement& input = toHTMLInputElement(*element);
2075 if (input.isDisabledOrReadOnly())
2076 return WebTextInputTypeNone;
2078 if (input.isPasswordField())
2079 return WebTextInputTypePassword;
2080 if (input.isSearchField())
2081 return WebTextInputTypeSearch;
2082 if (input.isEmailField())
2083 return WebTextInputTypeEmail;
2084 if (input.isNumberField())
2085 return WebTextInputTypeNumber;
2086 if (input.isTelephoneField())
2087 return WebTextInputTypeTelephone;
2088 if (input.isURLField())
2089 return WebTextInputTypeURL;
2090 if (input.isDateField())
2091 return WebTextInputTypeDate;
2092 if (input.isDateTimeLocalField())
2093 return WebTextInputTypeDateTimeLocal;
2094 if (input.isMonthField())
2095 return WebTextInputTypeMonth;
2096 if (input.isTimeField())
2097 return WebTextInputTypeTime;
2098 if (input.isWeekField())
2099 return WebTextInputTypeWeek;
2100 if (input.isTextField())
2101 return WebTextInputTypeText;
2103 return WebTextInputTypeNone;
2106 if (isHTMLTextAreaElement(*element)) {
2107 if (toHTMLTextAreaElement(*element).isDisabledOrReadOnly())
2108 return WebTextInputTypeNone;
2109 return WebTextInputTypeTextArea;
2112 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
2113 if (element->isHTMLElement()) {
2114 if (toHTMLElement(element)->isDateTimeFieldElement())
2115 return WebTextInputTypeDateTimeField;
2119 if (element->shouldUseInputMethod())
2120 return WebTextInputTypeContentEditable;
2122 return WebTextInputTypeNone;
2125 WebString WebViewImpl::inputModeOfFocusedElement()
2127 if (!RuntimeEnabledFeatures::inputModeAttributeEnabled())
2130 Element* element = focusedElement();
2134 if (isHTMLInputElement(*element)) {
2135 const HTMLInputElement& input = toHTMLInputElement(*element);
2136 if (input.supportsInputModeAttribute())
2137 return input.fastGetAttribute(HTMLNames::inputmodeAttr).lower();
2140 if (isHTMLTextAreaElement(*element)) {
2141 const HTMLTextAreaElement& textarea = toHTMLTextAreaElement(*element);
2142 return textarea.fastGetAttribute(HTMLNames::inputmodeAttr).lower();
2148 bool WebViewImpl::selectionBounds(WebRect& anchor, WebRect& focus) const
2150 const LocalFrame* frame = focusedWebCoreFrame();
2153 FrameSelection& selection = frame->selection();
2155 if (selection.isCaret()) {
2156 anchor = focus = selection.absoluteCaretBounds();
2158 RefPtr<Range> selectedRange = selection.toNormalizedRange();
2162 RefPtr<Range> range(Range::create(selectedRange->startContainer()->document(),
2163 selectedRange->startContainer(),
2164 selectedRange->startOffset(),
2165 selectedRange->startContainer(),
2166 selectedRange->startOffset()));
2167 anchor = frame->editor().firstRectForRange(range.get());
2169 range = Range::create(selectedRange->endContainer()->document(),
2170 selectedRange->endContainer(),
2171 selectedRange->endOffset(),
2172 selectedRange->endContainer(),
2173 selectedRange->endOffset());
2174 focus = frame->editor().firstRectForRange(range.get());
2177 IntRect scaledAnchor(frame->view()->contentsToWindow(anchor));
2178 IntRect scaledFocus(frame->view()->contentsToWindow(focus));
2179 scaledAnchor.scale(pageScaleFactor());
2180 scaledFocus.scale(pageScaleFactor());
2181 anchor = scaledAnchor;
2182 focus = scaledFocus;
2184 if (!selection.selection().isBaseFirst())
2185 std::swap(anchor, focus);
2189 InputMethodContext* WebViewImpl::inputMethodContext()
2191 if (!m_imeAcceptEvents)
2194 LocalFrame* focusedFrame = focusedWebCoreFrame();
2198 Element* target = focusedFrame->document()->focusedElement();
2199 if (target && target->hasInputMethodContext())
2200 return &target->inputMethodContext();
2205 WebPlugin* WebViewImpl::focusedPluginIfInputMethodSupported(LocalFrame* frame)
2207 WebPluginContainerImpl* container = WebFrameImpl::pluginContainerFromNode(frame, WebNode(focusedElement()));
2208 if (container && container->supportsInputMethod())
2209 return container->plugin();
2213 void WebViewImpl::didShowCandidateWindow()
2215 if (InputMethodContext* context = inputMethodContext())
2216 context->dispatchCandidateWindowShowEvent();
2219 void WebViewImpl::didUpdateCandidateWindow()
2221 if (InputMethodContext* context = inputMethodContext())
2222 context->dispatchCandidateWindowUpdateEvent();
2225 void WebViewImpl::didHideCandidateWindow()
2227 if (InputMethodContext* context = inputMethodContext())
2228 context->dispatchCandidateWindowHideEvent();
2231 bool WebViewImpl::selectionTextDirection(WebTextDirection& start, WebTextDirection& end) const
2233 const LocalFrame* frame = focusedWebCoreFrame();
2236 FrameSelection& selection = frame->selection();
2237 if (!selection.toNormalizedRange())
2239 start = selection.start().primaryDirection() == RTL ? WebTextDirectionRightToLeft : WebTextDirectionLeftToRight;
2240 end = selection.end().primaryDirection() == RTL ? WebTextDirectionRightToLeft : WebTextDirectionLeftToRight;
2244 bool WebViewImpl::isSelectionAnchorFirst() const
2246 if (const LocalFrame* frame = focusedWebCoreFrame())
2247 return frame->selection().selection().isBaseFirst();
2251 WebVector<WebCompositionUnderline> WebViewImpl::compositionUnderlines() const
2253 const LocalFrame* focused = focusedWebCoreFrame();
2255 return WebVector<WebCompositionUnderline>();
2256 const Vector<CompositionUnderline>& underlines = focused->inputMethodController().customCompositionUnderlines();
2257 WebVector<WebCompositionUnderline> results(underlines.size());
2258 for (size_t index = 0; index < underlines.size(); ++index) {
2259 CompositionUnderline underline = underlines[index];
2260 results[index] = WebCompositionUnderline(underline.startOffset, underline.endOffset, static_cast<WebColor>(underline.color.rgb()), underline.thick);
2265 WebColor WebViewImpl::backgroundColor() const
2267 if (isTransparent())
2268 return Color::transparent;
2270 return m_baseBackgroundColor;
2271 if (!m_page->mainFrame())
2272 return m_baseBackgroundColor;
2273 FrameView* view = m_page->mainFrame()->view();
2274 return view->documentBackgroundColor().rgb();
2277 bool WebViewImpl::caretOrSelectionRange(size_t* location, size_t* length)
2279 const LocalFrame* focused = focusedWebCoreFrame();
2283 PlainTextRange selectionOffsets = focused->inputMethodController().getSelectionOffsets();
2284 if (selectionOffsets.isNull())
2287 *location = selectionOffsets.start();
2288 *length = selectionOffsets.length();
2292 void WebViewImpl::setTextDirection(WebTextDirection direction)
2294 // The Editor::setBaseWritingDirection() function checks if we can change
2295 // the text direction of the selected node and updates its DOM "dir"
2296 // attribute and its CSS "direction" property.
2297 // So, we just call the function as Safari does.
2298 const LocalFrame* focused = focusedWebCoreFrame();
2302 Editor& editor = focused->editor();
2303 if (!editor.canEdit())
2306 switch (direction) {
2307 case WebTextDirectionDefault:
2308 editor.setBaseWritingDirection(NaturalWritingDirection);
2311 case WebTextDirectionLeftToRight:
2312 editor.setBaseWritingDirection(LeftToRightWritingDirection);
2315 case WebTextDirectionRightToLeft:
2316 editor.setBaseWritingDirection(RightToLeftWritingDirection);
2325 bool WebViewImpl::isAcceleratedCompositingActive() const
2327 return m_isAcceleratedCompositingActive;
2330 void WebViewImpl::willCloseLayerTreeView()
2332 setIsAcceleratedCompositingActive(false);
2333 m_layerTreeView = 0;
2336 void WebViewImpl::didAcquirePointerLock()
2339 page()->pointerLockController().didAcquirePointerLock();
2342 void WebViewImpl::didNotAcquirePointerLock()
2345 page()->pointerLockController().didNotAcquirePointerLock();
2348 void WebViewImpl::didLosePointerLock()
2351 page()->pointerLockController().didLosePointerLock();
2354 void WebViewImpl::didChangeWindowResizerRect()
2356 if (mainFrameImpl()->frameView())
2357 mainFrameImpl()->frameView()->windowResizerRectChanged();
2360 // WebView --------------------------------------------------------------------
2362 WebSettingsImpl* WebViewImpl::settingsImpl()
2365 m_webSettings = adoptPtr(new WebSettingsImpl(&m_page->settings(), &m_page->inspectorController()));
2366 ASSERT(m_webSettings);
2367 return m_webSettings.get();
2370 WebSettings* WebViewImpl::settings()
2372 return settingsImpl();
2375 WebString WebViewImpl::pageEncoding() const
2380 // FIXME: Is this check needed?
2381 if (!m_page->mainFrame()->document()->loader())
2384 return m_page->mainFrame()->document()->encodingName();
2387 void WebViewImpl::setPageEncoding(const WebString& encodingName)
2392 // Only change override encoding, don't change default encoding.
2393 // Note that the new encoding must be 0 if it isn't supposed to be set.
2394 AtomicString newEncodingName;
2395 if (!encodingName.isEmpty())
2396 newEncodingName = encodingName;
2397 m_page->mainFrame()->loader().reload(NormalReload, KURL(), newEncodingName);
2400 bool WebViewImpl::dispatchBeforeUnloadEvent()
2402 // FIXME: This should really cause a recursive depth-first walk of all
2403 // frames in the tree, calling each frame's onbeforeunload. At the moment,
2404 // we're consistent with Safari 3.1, not IE/FF.
2405 LocalFrame* frame = m_page->mainFrame();
2409 return frame->loader().shouldClose();
2412 void WebViewImpl::dispatchUnloadEvent()
2414 // Run unload handlers.
2415 m_page->mainFrame()->loader().closeURL();
2418 WebFrame* WebViewImpl::mainFrame()
2420 return mainFrameImpl();
2423 WebFrame* WebViewImpl::findFrameByName(
2424 const WebString& name, WebFrame* relativeToFrame)
2426 if (!relativeToFrame)
2427 relativeToFrame = mainFrame();
2428 LocalFrame* frame = toWebFrameImpl(relativeToFrame)->frame();
2429 frame = frame->tree().find(name);
2430 return WebFrameImpl::fromFrame(frame);
2433 WebFrame* WebViewImpl::focusedFrame()
2435 return WebFrameImpl::fromFrame(focusedWebCoreFrame());
2438 void WebViewImpl::setFocusedFrame(WebFrame* frame)
2441 // Clears the focused frame if any.
2442 if (LocalFrame* focusedFrame = focusedWebCoreFrame())
2443 focusedFrame->selection().setFocused(false);
2446 LocalFrame* webcoreFrame = toWebFrameImpl(frame)->frame();
2447 webcoreFrame->page()->focusController().setFocusedFrame(webcoreFrame);
2450 void WebViewImpl::setInitialFocus(bool reverse)
2454 LocalFrame* frame = page()->focusController().focusedOrMainFrame();
2455 if (Document* document = frame->document())
2456 document->setFocusedElement(nullptr);
2457 page()->focusController().setInitialFocus(reverse ? FocusTypeBackward : FocusTypeForward);
2460 void WebViewImpl::clearFocusedElement()
2462 RefPtr<LocalFrame> frame = focusedWebCoreFrame();
2466 RefPtr<Document> document = frame->document();
2470 RefPtr<Element> oldFocusedElement = document->focusedElement();
2472 // Clear the focused node.
2473 document->setFocusedElement(nullptr);
2475 if (!oldFocusedElement)
2478 // If a text field has focus, we need to make sure the selection controller
2479 // knows to remove selection from it. Otherwise, the text field is still
2480 // processing keyboard events even though focus has been moved to the page and
2481 // keystrokes get eaten as a result.
2482 if (oldFocusedElement->isContentEditable() || oldFocusedElement->isTextFormControl())
2483 frame->selection().clear();
2486 void WebViewImpl::scrollFocusedNodeIntoView()
2488 if (Element* element = focusedElement())
2489 element->scrollIntoViewIfNeeded(true);
2492 void WebViewImpl::scrollFocusedNodeIntoRect(const WebRect& rect)
2494 LocalFrame* frame = page()->mainFrame();
2495 Element* element = focusedElement();
2496 if (!frame || !frame->view() || !element)
2499 if (!m_webSettings->autoZoomFocusedNodeToLegibleScale()) {
2500 frame->view()->scrollElementToRect(element, IntRect(rect.x, rect.y, rect.width, rect.height));
2507 computeScaleAndScrollForFocusedNode(element, scale, scroll, needAnimation);
2509 startPageScaleAnimation(scroll, false, scale, scrollAndScaleAnimationDurationInSeconds);
2512 void WebViewImpl::computeScaleAndScrollForFocusedNode(Node* focusedNode, float& newScale, IntPoint& newScroll, bool& needAnimation)
2514 focusedNode->document().updateLayoutIgnorePendingStylesheets();
2516 // 'caret' is rect encompassing the blinking cursor.
2517 IntRect textboxRect = focusedNode->document().view()->contentsToWindow(pixelSnappedIntRect(focusedNode->Node::boundingBox()));
2518 WebRect caret, unusedEnd;
2519 selectionBounds(caret, unusedEnd);
2520 IntRect unscaledCaret = caret;
2521 unscaledCaret.scale(1 / pageScaleFactor());
2522 caret = unscaledCaret;
2524 // Pick a scale which is reasonably readable. This is the scale at which
2525 // the caret height will become minReadableCaretHeight (adjusted for dpi
2526 // and font scale factor).
2527 newScale = clampPageScaleFactorToLimits(legibleScale() * minReadableCaretHeight / caret.height);
2528 const float deltaScale = newScale / pageScaleFactor();
2530 // Convert the rects to absolute space in the new scale.
2531 IntRect textboxRectInDocumentCoordinates = textboxRect;
2532 textboxRectInDocumentCoordinates.move(mainFrame()->scrollOffset());
2533 IntRect caretInDocumentCoordinates = caret;
2534 caretInDocumentCoordinates.move(mainFrame()->scrollOffset());
2536 int viewWidth = m_size.width / newScale;
2537 int viewHeight = m_size.height / newScale;
2539 if (textboxRectInDocumentCoordinates.width() <= viewWidth) {
2540 // Field is narrower than screen. Try to leave padding on left so field's
2541 // label is visible, but it's more important to ensure entire field is
2543 int idealLeftPadding = viewWidth * leftBoxRatio;
2544 int maxLeftPaddingKeepingBoxOnscreen = viewWidth - textboxRectInDocumentCoordinates.width();
2545 newScroll.setX(textboxRectInDocumentCoordinates.x() - min<int>(idealLeftPadding, maxLeftPaddingKeepingBoxOnscreen));
2547 // Field is wider than screen. Try to left-align field, unless caret would
2548 // be offscreen, in which case right-align the caret.
2549 newScroll.setX(max<int>(textboxRectInDocumentCoordinates.x(), caretInDocumentCoordinates.x() + caretInDocumentCoordinates.width() + caretPadding - viewWidth));
2551 if (textboxRectInDocumentCoordinates.height() <= viewHeight) {
2552 // Field is shorter than screen. Vertically center it.
2553 newScroll.setY(textboxRectInDocumentCoordinates.y() - (viewHeight - textboxRectInDocumentCoordinates.height()) / 2);
2555 // Field is taller than screen. Try to top align field, unless caret would
2556 // be offscreen, in which case bottom-align the caret.
2557 newScroll.setY(max<int>(textboxRectInDocumentCoordinates.y(), caretInDocumentCoordinates.y() + caretInDocumentCoordinates.height() + caretPadding - viewHeight));
2560 needAnimation = false;
2561 // If we are at less than the target zoom level, zoom in.
2562 if (deltaScale > minScaleChangeToTriggerZoom)
2563 needAnimation = true;
2564 // If the caret is offscreen, then animate.
2565 IntRect sizeRect(0, 0, viewWidth, viewHeight);
2566 if (!sizeRect.contains(caret))
2567 needAnimation = true;
2568 // If the box is partially offscreen and it's possible to bring it fully
2569 // onscreen, then animate.
2570 if (sizeRect.contains(textboxRectInDocumentCoordinates.width(), textboxRectInDocumentCoordinates.height()) && !sizeRect.contains(textboxRect))
2571 needAnimation = true;
2574 void WebViewImpl::advanceFocus(bool reverse)
2576 page()->focusController().advanceFocus(reverse ? FocusTypeBackward : FocusTypeForward);
2579 double WebViewImpl::zoomLevel()
2584 double WebViewImpl::setZoomLevel(double zoomLevel)
2586 if (zoomLevel < m_minimumZoomLevel)
2587 m_zoomLevel = m_minimumZoomLevel;
2588 else if (zoomLevel > m_maximumZoomLevel)
2589 m_zoomLevel = m_maximumZoomLevel;
2591 m_zoomLevel = zoomLevel;
2593 LocalFrame* frame = mainFrameImpl()->frame();
2594 WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
2595 if (pluginContainer)
2596 pluginContainer->plugin()->setZoomLevel(m_zoomLevel, false);
2598 float zoomFactor = m_zoomFactorOverride ? m_zoomFactorOverride : static_cast<float>(zoomLevelToZoomFactor(m_zoomLevel));
2599 frame->setPageZoomFactor(zoomFactor);
2605 void WebViewImpl::zoomLimitsChanged(double minimumZoomLevel,
2606 double maximumZoomLevel)
2608 m_minimumZoomLevel = minimumZoomLevel;
2609 m_maximumZoomLevel = maximumZoomLevel;
2610 m_client->zoomLimitsChanged(m_minimumZoomLevel, m_maximumZoomLevel);
2613 float WebViewImpl::textZoomFactor()
2615 return mainFrameImpl()->frame()->textZoomFactor();
2618 float WebViewImpl::setTextZoomFactor(float textZoomFactor)
2620 LocalFrame* frame = mainFrameImpl()->frame();
2621 if (WebFrameImpl::pluginContainerFromFrame(frame))
2624 frame->setTextZoomFactor(textZoomFactor);
2626 return textZoomFactor;
2629 void WebViewImpl::fullFramePluginZoomLevelChanged(double zoomLevel)
2631 if (zoomLevel == m_zoomLevel)
2634 m_zoomLevel = max(min(zoomLevel, m_maximumZoomLevel), m_minimumZoomLevel);
2635 m_client->zoomLevelChanged();
2638 double WebView::zoomLevelToZoomFactor(double zoomLevel)
2640 return pow(textSizeMultiplierRatio, zoomLevel);
2643 double WebView::zoomFactorToZoomLevel(double factor)
2645 // Since factor = 1.2^level, level = log(factor) / log(1.2)
2646 return log(factor) / log(textSizeMultiplierRatio);
2649 float WebViewImpl::pageScaleFactor() const
2654 return page()->pageScaleFactor();
2657 float WebViewImpl::clampPageScaleFactorToLimits(float scaleFactor) const
2659 return m_pageScaleConstraintsSet.finalConstraints().clampToConstraints(scaleFactor);
2662 IntPoint WebViewImpl::clampOffsetAtScale(const IntPoint& offset, float scale)
2664 FrameView* view = mainFrameImpl()->frameView();
2668 return view->clampOffsetAtScale(offset, scale);
2671 void WebViewImpl::setPageScaleFactor(float scaleFactor, const WebPoint& origin)
2676 IntPoint newScrollOffset = origin;
2677 scaleFactor = clampPageScaleFactorToLimits(scaleFactor);
2678 newScrollOffset = clampOffsetAtScale(newScrollOffset, scaleFactor);
2680 page()->setPageScaleFactor(scaleFactor, newScrollOffset);
2683 void WebViewImpl::setPageScaleFactorPreservingScrollOffset(float scaleFactor)
2685 if (clampPageScaleFactorToLimits(scaleFactor) == pageScaleFactor())
2688 IntPoint scrollOffset(mainFrame()->scrollOffset().width, mainFrame()->scrollOffset().height);
2689 setPageScaleFactor(scaleFactor, scrollOffset);
2692 float WebViewImpl::deviceScaleFactor() const
2697 return page()->deviceScaleFactor();
2700 void WebViewImpl::setDeviceScaleFactor(float scaleFactor)
2705 page()->setDeviceScaleFactor(scaleFactor);
2707 if (m_layerTreeView)
2708 updateLayerTreeDeviceScaleFactor();
2711 void WebViewImpl::enableAutoResizeMode(const WebSize& minSize, const WebSize& maxSize)
2713 m_shouldAutoResize = true;
2714 m_minAutoSize = minSize;
2715 m_maxAutoSize = maxSize;
2716 configureAutoResizeMode();
2719 void WebViewImpl::disableAutoResizeMode()
2721 m_shouldAutoResize = false;
2722 configureAutoResizeMode();
2725 void WebViewImpl::setUserAgentPageScaleConstraints(PageScaleConstraints newConstraints)
2727 if (newConstraints == m_pageScaleConstraintsSet.userAgentConstraints())
2730 m_pageScaleConstraintsSet.setUserAgentConstraints(newConstraints);
2732 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
2735 mainFrameImpl()->frameView()->setNeedsLayout();
2738 void WebViewImpl::setInitialPageScaleOverride(float initialPageScaleFactorOverride)
2740 PageScaleConstraints constraints = m_pageScaleConstraintsSet.userAgentConstraints();
2741 constraints.initialScale = initialPageScaleFactorOverride;
2743 if (constraints == m_pageScaleConstraintsSet.userAgentConstraints())
2746 m_pageScaleConstraintsSet.setNeedsReset(true);
2747 setUserAgentPageScaleConstraints(constraints);
2750 void WebViewImpl::setPageScaleFactorLimits(float minPageScale, float maxPageScale)
2752 PageScaleConstraints constraints = m_pageScaleConstraintsSet.userAgentConstraints();
2753 constraints.minimumScale = minPageScale;
2754 constraints.maximumScale = maxPageScale;
2755 setUserAgentPageScaleConstraints(constraints);
2758 void WebViewImpl::setIgnoreViewportTagScaleLimits(bool ignore)
2760 PageScaleConstraints constraints = m_pageScaleConstraintsSet.userAgentConstraints();
2762 constraints.minimumScale = m_pageScaleConstraintsSet.defaultConstraints().minimumScale;
2763 constraints.maximumScale = m_pageScaleConstraintsSet.defaultConstraints().maximumScale;
2765 constraints.minimumScale = -1;
2766 constraints.maximumScale = -1;
2768 setUserAgentPageScaleConstraints(constraints);
2771 void WebViewImpl::refreshPageScaleFactorAfterLayout()
2773 if (!mainFrame() || !page() || !page()->mainFrame() || !page()->mainFrame()->view())
2775 FrameView* view = page()->mainFrame()->view();
2777 updatePageDefinedViewportConstraints(mainFrameImpl()->frame()->document()->viewportDescription());
2778 m_pageScaleConstraintsSet.computeFinalConstraints();
2780 if (settings()->viewportEnabled() && !m_fixedLayoutSizeLock) {
2781 int verticalScrollbarWidth = 0;
2782 if (view->verticalScrollbar() && !view->verticalScrollbar()->isOverlayScrollbar())
2783 verticalScrollbarWidth = view->verticalScrollbar()->width();
2784 m_pageScaleConstraintsSet.adjustFinalConstraintsToContentsSize(m_size, contentsSize(), verticalScrollbarWidth);
2787 float newPageScaleFactor = pageScaleFactor();
2788 if (m_pageScaleConstraintsSet.needsReset() && m_pageScaleConstraintsSet.finalConstraints().initialScale != -1) {
2789 newPageScaleFactor = m_pageScaleConstraintsSet.finalConstraints().initialScale;
2790 m_pageScaleConstraintsSet.setNeedsReset(false);
2792 setPageScaleFactorPreservingScrollOffset(newPageScaleFactor);
2794 updateLayerTreeViewport();
2796 // Relayout immediately to avoid violating the rule that needsLayout()
2797 // isn't set at the end of a layout.
2798 if (view->needsLayout())
2802 void WebViewImpl::updatePageDefinedViewportConstraints(const ViewportDescription& description)
2804 if (!settings()->viewportEnabled() || !page() || (!m_size.width && !m_size.height))
2807 ViewportDescription adjustedDescription = description;
2808 if (settingsImpl()->viewportMetaLayoutSizeQuirk() && adjustedDescription.type == ViewportDescription::ViewportMeta) {
2809 if (adjustedDescription.maxWidth.type() == ExtendToZoom)
2810 adjustedDescription.maxWidth = Length(); // auto
2811 const int legacyWidthSnappingMagicNumber = 320;
2812 if (adjustedDescription.maxWidth.isFixed() && adjustedDescription.maxWidth.value() <= legacyWidthSnappingMagicNumber)
2813 adjustedDescription.maxWidth = Length(DeviceWidth);
2814 if (adjustedDescription.maxHeight.isFixed() && adjustedDescription.maxHeight.value() <= m_size.height)
2815 adjustedDescription.maxHeight = Length(DeviceHeight);
2816 adjustedDescription.minWidth = adjustedDescription.maxWidth;
2817 adjustedDescription.minHeight = adjustedDescription.maxHeight;
2819 float oldInitialScale = m_pageScaleConstraintsSet.pageDefinedConstraints().initialScale;
2820 m_pageScaleConstraintsSet.updatePageDefinedConstraints(adjustedDescription, m_size);
2822 if (settingsImpl()->clobberUserAgentInitialScaleQuirk()
2823 && m_pageScaleConstraintsSet.userAgentConstraints().initialScale != -1
2824 && m_pageScaleConstraintsSet.userAgentConstraints().initialScale * deviceScaleFactor() <= 1) {
2825 if (description.maxWidth == Length(DeviceWidth)
2826 || (description.maxWidth.type() == ExtendToZoom && m_pageScaleConstraintsSet.pageDefinedConstraints().initialScale == 1.0f))
2827 setInitialPageScaleOverride(-1);
2829 m_pageScaleConstraintsSet.adjustForAndroidWebViewQuirks(adjustedDescription, m_size, page()->settings().layoutFallbackWidth(), deviceScaleFactor(), settingsImpl()->supportDeprecatedTargetDensityDPI(), page()->settings().wideViewportQuirkEnabled(), page()->settings().useWideViewport(), page()->settings().loadWithOverviewMode(), settingsImpl()->viewportMetaNonUserScalableQuirk());
2830 float newInitialScale = m_pageScaleConstraintsSet.pageDefinedConstraints().initialScale;
2831 if (oldInitialScale != newInitialScale && newInitialScale != -1) {
2832 m_pageScaleConstraintsSet.setNeedsReset(true);
2833 if (mainFrameImpl() && mainFrameImpl()->frameView())
2834 mainFrameImpl()->frameView()->setNeedsLayout();
2837 updateMainFrameLayoutSize();
2840 void WebViewImpl::updateMainFrameLayoutSize()
2842 if (m_fixedLayoutSizeLock || !mainFrameImpl())
2845 RefPtr<FrameView> view = mainFrameImpl()->frameView();
2849 WebSize layoutSize = m_size;
2851 if (settings()->viewportEnabled()) {
2852 layoutSize = flooredIntSize(m_pageScaleConstraintsSet.pageDefinedConstraints().layoutSize);
2854 bool textAutosizingEnabled = page()->settings().textAutosizingEnabled();
2855 if (textAutosizingEnabled && layoutSize.width != view->layoutSize().width()) {
2856 TextAutosizer* textAutosizer = page()->mainFrame()->document()->textAutosizer();
2858 textAutosizer->recalculateMultipliers();
2862 view->setLayoutSize(layoutSize);
2865 IntSize WebViewImpl::contentsSize() const
2867 RenderView* root = page()->mainFrame()->contentRenderer();
2870 return root->documentRect().size();
2873 WebSize WebViewImpl::contentsPreferredMinimumSize()
2875 Document* document = m_page->mainFrame()->document();
2876 if (!document || !document->renderView() || !document->documentElement())
2880 FontCachePurgePreventer fontCachePurgePreventer; // Required by minPreferredLogicalWidth().
2881 IntSize preferredMinimumSize(document->renderView()->minPreferredLogicalWidth(), document->documentElement()->scrollHeight());
2882 preferredMinimumSize.scale(zoomLevelToZoomFactor(zoomLevel()));
2883 return preferredMinimumSize;
2886 float WebViewImpl::minimumPageScaleFactor() const
2888 return m_pageScaleConstraintsSet.finalConstraints().minimumScale;
2891 float WebViewImpl::maximumPageScaleFactor() const
2893 return m_pageScaleConstraintsSet.finalConstraints().maximumScale;
2896 void WebViewImpl::saveScrollAndScaleState()
2898 m_savedPageScaleFactor = pageScaleFactor();
2899 m_savedScrollOffset = mainFrame()->scrollOffset();
2902 void WebViewImpl::restoreScrollAndScaleState()
2904 if (!m_savedPageScaleFactor)
2907 startPageScaleAnimation(IntPoint(m_savedScrollOffset), false, m_savedPageScaleFactor, scrollAndScaleAnimationDurationInSeconds);
2908 resetSavedScrollAndScaleState();
2911 void WebViewImpl::resetSavedScrollAndScaleState()
2913 m_savedPageScaleFactor = 0;
2914 m_savedScrollOffset = IntSize();
2917 void WebViewImpl::resetScrollAndScaleState()
2919 page()->setPageScaleFactor(1, IntPoint());
2921 // Clear out the values for the current history item. This will prevent the history item from clobbering the
2922 // value determined during page scale initialization, which may be less than 1.
2923 page()->mainFrame()->loader().clearScrollPositionAndViewState();
2924 m_pageScaleConstraintsSet.setNeedsReset(true);
2926 // Clobber saved scales and scroll offsets.
2927 if (FrameView* view = page()->mainFrame()->document()->view())
2928 view->cacheCurrentScrollPosition();
2929 resetSavedScrollAndScaleState();
2932 void WebViewImpl::setFixedLayoutSize(const WebSize& layoutSize)
2937 LocalFrame* frame = page()->mainFrame();
2941 RefPtr<FrameView> view = frame->view();
2945 m_fixedLayoutSizeLock = layoutSize.width || layoutSize.height;
2947 if (m_fixedLayoutSizeLock)
2948 view->setLayoutSize(layoutSize);
2950 updateMainFrameLayoutSize();
2953 void WebViewImpl::performMediaPlayerAction(const WebMediaPlayerAction& action,
2954 const WebPoint& location)
2956 HitTestResult result = hitTestResultForWindowPos(location);
2957 RefPtr<Node> node = result.innerNonSharedNode();
2958 if (!isHTMLVideoElement(*node) && !isHTMLAudioElement(*node))
2961 RefPtr<HTMLMediaElement> mediaElement =
2962 static_pointer_cast<HTMLMediaElement>(node);
2963 switch (action.type) {
2964 case WebMediaPlayerAction::Play:
2966 mediaElement->play();
2968 mediaElement->pause();
2970 case WebMediaPlayerAction::Mute:
2971 mediaElement->setMuted(action.enable);
2973 case WebMediaPlayerAction::Loop:
2974 mediaElement->setLoop(action.enable);
2976 case WebMediaPlayerAction::Controls:
2977 mediaElement->setControls(action.enable);
2980 ASSERT_NOT_REACHED();
2984 void WebViewImpl::performPluginAction(const WebPluginAction& action,
2985 const WebPoint& location)
2987 HitTestResult result = hitTestResultForWindowPos(location);
2988 RefPtr<Node> node = result.innerNonSharedNode();
2989 if (!isHTMLObjectElement(*node) && !isHTMLEmbedElement(*node))
2992 RenderObject* object = node->renderer();
2993 if (object && object->isWidget()) {
2994 Widget* widget = toRenderWidget(object)->widget();
2995 if (widget && widget->isPluginContainer()) {
2996 WebPluginContainerImpl* plugin = toWebPluginContainerImpl(widget);
2997 switch (action.type) {
2998 case WebPluginAction::Rotate90Clockwise:
2999 plugin->plugin()->rotateView(WebPlugin::RotationType90Clockwise);
3001 case WebPluginAction::Rotate90Counterclockwise:
3002 plugin->plugin()->rotateView(WebPlugin::RotationType90Counterclockwise);
3005 ASSERT_NOT_REACHED();
3011 WebHitTestResult WebViewImpl::hitTestResultAt(const WebPoint& point)
3013 IntPoint scaledPoint = point;
3014 scaledPoint.scale(1 / pageScaleFactor(), 1 / pageScaleFactor());
3015 return hitTestResultForWindowPos(scaledPoint);
3018 void WebViewImpl::copyImageAt(const WebPoint& point)
3023 HitTestResult result = hitTestResultForWindowPos(point);
3025 if (result.absoluteImageURL().isEmpty()) {
3026 // There isn't actually an image at these coordinates. Might be because
3027 // the window scrolled while the context menu was open or because the page
3028 // changed itself between when we thought there was an image here and when
3029 // we actually tried to retreive the image.
3031 // FIXME: implement a cache of the most recent HitTestResult to avoid having
3032 // to do two hit tests.
3036 m_page->mainFrame()->editor().copyImage(result);
3039 void WebViewImpl::dragSourceEndedAt(
3040 const WebPoint& clientPoint,
3041 const WebPoint& screenPoint,
3042 WebDragOperation operation)
3044 PlatformMouseEvent pme(clientPoint,
3046 LeftButton, PlatformEvent::MouseMoved, 0, false, false, false,
3048 m_page->mainFrame()->eventHandler().dragSourceEndedAt(pme,
3049 static_cast<DragOperation>(operation));
3052 void WebViewImpl::dragSourceMovedTo(
3053 const WebPoint& clientPoint,
3054 const WebPoint& screenPoint,
3055 WebDragOperation operation)
3059 void WebViewImpl::dragSourceSystemDragEnded()
3061 // It's possible for us to get this callback while not doing a drag if
3062 // it's from a previous page that got unloaded.
3063 if (m_doingDragAndDrop) {
3064 m_page->dragController().dragEnded();
3065 m_doingDragAndDrop = false;
3069 WebDragOperation WebViewImpl::dragTargetDragEnter(
3070 const WebDragData& webDragData,
3071 const WebPoint& clientPoint,
3072 const WebPoint& screenPoint,
3073 WebDragOperationsMask operationsAllowed,
3076 ASSERT(!m_currentDragData);
3078 m_currentDragData = webDragData.getValue();
3079 m_operationsAllowed = operationsAllowed;
3081 return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragEnter, keyModifiers);
3084 WebDragOperation WebViewImpl::dragTargetDragOver(
3085 const WebPoint& clientPoint,
3086 const WebPoint& screenPoint,
3087 WebDragOperationsMask operationsAllowed,
3090 m_operationsAllowed = operationsAllowed;
3092 return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragOver, keyModifiers);
3095 void WebViewImpl::dragTargetDragLeave()
3097 ASSERT(m_currentDragData);
3100 m_currentDragData.get(),
3103 static_cast<DragOperation>(m_operationsAllowed));
3105 m_page->dragController().dragExited(&dragData);
3107 // FIXME: why is the drag scroll timer not stopped here?
3109 m_dragOperation = WebDragOperationNone;
3110 m_currentDragData = nullptr;
3113 void WebViewImpl::dragTargetDrop(const WebPoint& clientPoint,
3114 const WebPoint& screenPoint,
3117 ASSERT(m_currentDragData);
3119 // If this webview transitions from the "drop accepting" state to the "not
3120 // accepting" state, then our IPC message reply indicating that may be in-
3121 // flight, or else delayed by javascript processing in this webview. If a
3122 // drop happens before our IPC reply has reached the browser process, then
3123 // the browser forwards the drop to this webview. So only allow a drop to
3124 // proceed if our webview m_dragOperation state is not DragOperationNone.
3126 if (m_dragOperation == WebDragOperationNone) { // IPC RACE CONDITION: do not allow this drop.
3127 dragTargetDragLeave();
3131 m_currentDragData->setModifierKeyState(webInputEventKeyStateToPlatformEventKeyState(keyModifiers));
3133 m_currentDragData.get(),
3136 static_cast<DragOperation>(m_operationsAllowed));
3138 UserGestureIndicator gesture(DefinitelyProcessingNewUserGesture);
3139 m_page->dragController().performDrag(&dragData);
3141 m_dragOperation = WebDragOperationNone;
3142 m_currentDragData = nullptr;
3145 void WebViewImpl::spellingMarkers(WebVector<uint32_t>* markers)
3147 Vector<uint32_t> result;
3148 for (LocalFrame* frame = m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3149 const Vector<DocumentMarker*>& documentMarkers = frame->document()->markers().markers();
3150 for (size_t i = 0; i < documentMarkers.size(); ++i)
3151 result.append(documentMarkers[i]->hash());
3153 markers->assign(result);
3156 WebDragOperation WebViewImpl::dragTargetDragEnterOrOver(const WebPoint& clientPoint, const WebPoint& screenPoint, DragAction dragAction, int keyModifiers)
3158 ASSERT(m_currentDragData);
3160 m_currentDragData->setModifierKeyState(webInputEventKeyStateToPlatformEventKeyState(keyModifiers));
3162 m_currentDragData.get(),
3165 static_cast<DragOperation>(m_operationsAllowed));
3167 DragSession dragSession;
3168 if (dragAction == DragEnter)
3169 dragSession = m_page->dragController().dragEntered(&dragData);
3171 dragSession = m_page->dragController().dragUpdated(&dragData);
3173 DragOperation dropEffect = dragSession.operation;
3175 // Mask the drop effect operation against the drag source's allowed operations.
3176 if (!(dropEffect & dragData.draggingSourceOperationMask()))
3177 dropEffect = DragOperationNone;
3179 m_dragOperation = static_cast<WebDragOperation>(dropEffect);
3181 return m_dragOperation;
3184 void WebViewImpl::sendResizeEventAndRepaint()
3186 // FIXME: This is wrong. The FrameView is responsible sending a resizeEvent
3187 // as part of layout. Layout is also responsible for sending invalidations
3188 // to the embedder. This method and all callers may be wrong. -- eseidel.
3189 if (mainFrameImpl()->frameView()) {
3190 // Enqueues the resize event.
3191 mainFrameImpl()->frame()->document()->enqueueResizeEvent();
3195 if (isAcceleratedCompositingActive()) {
3196 updateLayerTreeViewport();
3198 WebRect damagedRect(0, 0, m_size.width, m_size.height);
3199 m_client->didInvalidateRect(damagedRect);
3203 m_pageOverlays->update();
3206 void WebViewImpl::configureAutoResizeMode()
3208 if (!mainFrameImpl() || !mainFrameImpl()->frame() || !mainFrameImpl()->frame()->view())
3211 mainFrameImpl()->frame()->view()->enableAutoSizeMode(m_shouldAutoResize, m_minAutoSize, m_maxAutoSize);
3214 unsigned long WebViewImpl::createUniqueIdentifierForRequest()
3216 return createUniqueIdentifier();
3219 void WebViewImpl::inspectElementAt(const WebPoint& point)
3224 if (point.x == -1 || point.y == -1) {
3225 m_page->inspectorController().inspect(0);
3227 HitTestRequest::HitTestRequestType hitType = HitTestRequest::Move | HitTestRequest::ReadOnly | HitTestRequest::AllowChildFrameContent | HitTestRequest::IgnorePointerEventsNone;
3228 HitTestRequest request(hitType);
3230 FrameView* frameView = m_page->mainFrame()->view();
3231 IntPoint transformedPoint(point);
3232 transformedPoint = transformedPoint - frameView->inputEventsOffsetForEmulation();
3233 transformedPoint.scale(1 / frameView->inputEventsScaleFactor(), 1 / frameView->inputEventsScaleFactor());
3234 HitTestResult result(m_page->mainFrame()->view()->windowToContents(transformedPoint));
3235 m_page->mainFrame()->contentRenderer()->hitTest(request, result);
3236 Node* node = result.innerNode();
3237 if (!node && m_page->mainFrame()->document())
3238 node = m_page->mainFrame()->document()->documentElement();
3239 m_page->inspectorController().inspect(node);
3243 WebString WebViewImpl::inspectorSettings() const
3245 return m_inspectorSettings;
3248 void WebViewImpl::setInspectorSettings(const WebString& settings)
3250 m_inspectorSettings = settings;
3253 bool WebViewImpl::inspectorSetting(const WebString& key, WebString* value) const
3255 if (!m_inspectorSettingsMap->contains(key))
3257 *value = m_inspectorSettingsMap->get(key);
3261 void WebViewImpl::setInspectorSetting(const WebString& key,
3262 const WebString& value)
3264 m_inspectorSettingsMap->set(key, value);
3265 client()->didUpdateInspectorSetting(key, value);
3268 void WebViewImpl::setCompositorDeviceScaleFactorOverride(float deviceScaleFactor)
3270 m_compositorDeviceScaleFactorOverride = deviceScaleFactor;
3271 if (page() && m_layerTreeView)
3272 updateLayerTreeDeviceScaleFactor();
3275 void WebViewImpl::setRootLayerTransform(const WebSize& rootLayerOffset, float rootLayerScale)
3277 m_rootLayerScale = rootLayerScale;
3278 m_rootLayerOffset = rootLayerOffset;
3279 if (mainFrameImpl())
3280 mainFrameImpl()->setInputEventsTransformForEmulation(m_rootLayerOffset, m_rootLayerScale);
3281 updateRootLayerTransform();
3284 WebDevToolsAgent* WebViewImpl::devToolsAgent()
3286 return m_devToolsAgent.get();
3289 WebAXObject WebViewImpl::accessibilityObject()
3291 if (!mainFrameImpl())
3292 return WebAXObject();
3294 Document* document = mainFrameImpl()->frame()->document();
3296 document->axObjectCache()->getOrCreate(document->renderer()));
3299 void WebViewImpl::performCustomContextMenuAction(unsigned action)
3303 ContextMenu* menu = m_page->contextMenuController().contextMenu();
3306 const ContextMenuItem* item = menu->itemWithAction(static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + action));
3308 m_page->contextMenuController().contextMenuItemSelected(item);
3309 m_page->contextMenuController().clearContextMenu();
3312 void WebViewImpl::showContextMenu()
3317 page()->contextMenuController().clearContextMenu();
3318 m_contextMenuAllowed = true;
3319 if (LocalFrame* focusedFrame = page()->focusController().focusedOrMainFrame())
3320 focusedFrame->eventHandler().sendContextMenuEventForKey();
3321 m_contextMenuAllowed = false;
3324 WebString WebViewImpl::getSmartClipData(WebRect rect)
3326 LocalFrame* frame = focusedWebCoreFrame();
3329 return WebCore::SmartClip(frame).dataForRect(rect).toString();
3332 void WebViewImpl::hidePopups()
3336 closePagePopup(m_pagePopup.get());
3339 void WebViewImpl::setIsTransparent(bool isTransparent)
3341 // Set any existing frames to be transparent.
3342 LocalFrame* frame = m_page->mainFrame();
3344 frame->view()->setTransparent(isTransparent);
3345 frame = frame->tree().traverseNext();
3348 // Future frames check this to know whether to be transparent.
3349 m_isTransparent = isTransparent;
3352 bool WebViewImpl::isTransparent() const
3354 return m_isTransparent;
3357 void WebViewImpl::setBaseBackgroundColor(WebColor color)
3361 if (m_baseBackgroundColor == color)
3364 m_baseBackgroundColor = color;
3366 if (m_page->mainFrame())
3367 m_page->mainFrame()->view()->setBaseBackgroundColor(color);
3369 updateLayerTreeBackgroundColor();
3372 void WebViewImpl::setIsActive(bool active)
3375 page()->focusController().setActive(active);
3378 bool WebViewImpl::isActive() const
3380 return page() ? page()->focusController().isActive() : false;
3383 void WebViewImpl::setDomainRelaxationForbidden(bool forbidden, const WebString& scheme)
3385 SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme));
3388 void WebViewImpl::setWindowFeatures(const WebWindowFeatures& features)
3390 m_page->chrome().setWindowFeatures(features);
3393 void WebViewImpl::setSelectionColors(unsigned activeBackgroundColor,
3394 unsigned activeForegroundColor,
3395 unsigned inactiveBackgroundColor,
3396 unsigned inactiveForegroundColor) {
3397 #if USE(DEFAULT_RENDER_THEME)
3398 RenderThemeChromiumDefault::setSelectionColors(activeBackgroundColor, activeForegroundColor, inactiveBackgroundColor, inactiveForegroundColor);
3399 RenderTheme::theme().platformColorsDidChange();
3403 void WebView::injectStyleSheet(const WebString& sourceCode, const WebVector<WebString>& patternsIn, WebView::StyleInjectionTarget injectIn)
3405 Vector<String> patterns;
3406 for (size_t i = 0; i < patternsIn.size(); ++i)
3407 patterns.append(patternsIn[i]);
3409 InjectedStyleSheets::instance().add(sourceCode, patterns, static_cast<WebCore::StyleInjectionTarget>(injectIn));
3412 void WebView::removeInjectedStyleSheets()
3414 InjectedStyleSheets::instance().removeAll();
3417 void WebViewImpl::didCommitLoad(bool isNewNavigation, bool isNavigationWithinPage)
3419 if (isNewNavigation && !isNavigationWithinPage)
3420 m_pageScaleConstraintsSet.setNeedsReset(true);
3422 // Make sure link highlight from previous page is cleared.
3423 m_linkHighlights.clear();
3424 endActiveFlingAnimation();
3425 resetSavedScrollAndScaleState();
3428 void WebViewImpl::willInsertBody(WebFrameImpl* webframe)
3430 if (webframe != mainFrameImpl())
3433 // If we get to the <body> tag and we have no pending stylesheet loads, we
3434 // can be fairly confident we'll have something sensible to paint soon and
3435 // can turn off deferred commits.
3436 if (m_page->mainFrame()->document()->haveStylesheetsLoaded())
3437 resumeTreeViewCommits();
3440 void WebViewImpl::resumeTreeViewCommits()
3442 if (m_layerTreeViewCommitsDeferred) {
3443 if (m_layerTreeView)
3444 m_layerTreeView->setDeferCommits(false);
3445 m_layerTreeViewCommitsDeferred = false;
3449 void WebViewImpl::layoutUpdated(WebFrameImpl* webframe)
3451 if (!m_client || webframe != mainFrameImpl())
3454 // If we finished a layout while in deferred commit mode,
3455 // that means it's time to start producing frames again so un-defer.
3456 resumeTreeViewCommits();
3458 if (m_shouldAutoResize && mainFrameImpl()->frame() && mainFrameImpl()->frame()->view()) {
3459 WebSize frameSize = mainFrameImpl()->frame()->view()->frameRect().size();
3460 if (frameSize != m_size) {
3462 m_client->didAutoResize(m_size);
3463 sendResizeEventAndRepaint();
3467 if (m_pageScaleConstraintsSet.constraintsDirty())
3468 refreshPageScaleFactorAfterLayout();
3470 m_client->didUpdateLayout();
3473 void WebViewImpl::didChangeContentsSize()
3475 m_pageScaleConstraintsSet.didChangeContentsSize(contentsSize(), pageScaleFactor());
3478 void WebViewImpl::deviceOrPageScaleFactorChanged()
3480 if (pageScaleFactor() && pageScaleFactor() != 1)
3481 enterForceCompositingMode(true);
3482 m_pageScaleConstraintsSet.setNeedsReset(false);
3483 updateLayerTreeViewport();
3486 bool WebViewImpl::useExternalPopupMenus()
3488 return shouldUseExternalPopupMenus;
3491 void WebViewImpl::startDragging(LocalFrame* frame,
3492 const WebDragData& dragData,
3493 WebDragOperationsMask mask,
3494 const WebImage& dragImage,
3495 const WebPoint& dragImageOffset)
3499 ASSERT(!m_doingDragAndDrop);
3500 m_doingDragAndDrop = true;
3501 m_client->startDragging(WebFrameImpl::fromFrame(frame), dragData, mask, dragImage, dragImageOffset);
3504 void WebViewImpl::setIgnoreInputEvents(bool newValue)
3506 ASSERT(m_ignoreInputEvents != newValue);
3507 m_ignoreInputEvents = newValue;
3510 void WebViewImpl::setBackgroundColorOverride(WebColor color)
3512 m_backgroundColorOverride = color;
3513 updateLayerTreeBackgroundColor();
3516 void WebViewImpl::setZoomFactorOverride(float zoomFactor)
3518 m_zoomFactorOverride = zoomFactor;
3519 setZoomLevel(zoomLevel());
3522 void WebViewImpl::addPageOverlay(WebPageOverlay* overlay, int zOrder)
3524 if (!m_pageOverlays)
3525 m_pageOverlays = PageOverlayList::create(this);
3527 m_pageOverlays->add(overlay, zOrder);
3530 void WebViewImpl::removePageOverlay(WebPageOverlay* overlay)
3532 if (m_pageOverlays && m_pageOverlays->remove(overlay) && m_pageOverlays->empty())
3533 m_pageOverlays = nullptr;
3536 void WebViewImpl::setOverlayLayer(WebCore::GraphicsLayer* layer)
3538 if (!m_rootGraphicsLayer)
3541 if (!m_rootTransformLayer)
3542 m_rootTransformLayer = m_page->mainFrame()->view()->renderView()->compositor()->ensureRootTransformLayer();
3544 if (m_rootTransformLayer) {
3545 if (layer->parent() != m_rootTransformLayer)
3546 m_rootTransformLayer->addChild(layer);
3550 NotificationPresenterImpl* WebViewImpl::notificationPresenterImpl()
3552 if (!m_notificationPresenter.isInitialized() && m_client)
3553 m_notificationPresenter.initialize(m_client->notificationPresenter());
3554 return &m_notificationPresenter;
3557 Element* WebViewImpl::focusedElement() const
3559 LocalFrame* frame = m_page->focusController().focusedFrame();
3563 Document* document = frame->document();
3567 return document->focusedElement();
3570 HitTestResult WebViewImpl::hitTestResultForWindowPos(const IntPoint& pos)
3572 IntPoint docPoint(m_page->mainFrame()->view()->windowToContents(pos));
3573 return m_page->mainFrame()->eventHandler().hitTestResultAtPoint(docPoint, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
3576 void WebViewImpl::setTabsToLinks(bool enable)
3578 m_tabsToLinks = enable;
3581 bool WebViewImpl::tabsToLinks() const
3583 return m_tabsToLinks;
3586 void WebViewImpl::suppressInvalidations(bool enable)
3589 m_client->suppressCompositorScheduling(enable);
3592 bool WebViewImpl::allowsAcceleratedCompositing()
3594 return !m_compositorCreationFailed;
3597 void WebViewImpl::setRootGraphicsLayer(GraphicsLayer* layer)
3599 bool pinchVirtualViewportEnabled = page()->settings().pinchVirtualViewportEnabled();
3600 suppressInvalidations(true);
3602 if (pinchVirtualViewportEnabled) {
3603 PinchViewport& pinchViewport = page()->frameHost().pinchViewport();
3604 pinchViewport.attachToLayerTree(layer, graphicsLayerFactory());
3605 pinchViewport.setSize(mainFrameImpl()->frame()->view()->frameRect().size());
3607 m_rootGraphicsLayer = pinchViewport.rootGraphicsLayer();
3608 m_rootLayer = pinchViewport.rootGraphicsLayer()->platformLayer();
3609 m_rootTransformLayer = 0;
3611 m_rootGraphicsLayer = 0;
3613 m_rootTransformLayer = 0;
3616 m_rootGraphicsLayer = layer;
3617 m_rootLayer = layer ? layer->platformLayer() : 0;
3618 m_rootTransformLayer = 0;
3621 setIsAcceleratedCompositingActive(layer);
3623 updateRootLayerTransform();
3625 if (m_layerTreeView) {
3627 m_layerTreeView->setRootLayer(*m_rootLayer);
3628 // We register viewport layers here since there may not be a layer
3629 // tree view prior to this point.
3630 if (pinchVirtualViewportEnabled) {
3631 page()->frameHost().pinchViewport().registerLayersWithTreeView(m_layerTreeView);
3633 GraphicsLayer* rootScrollLayer = compositor()->scrollLayer();
3634 ASSERT(rootScrollLayer);
3635 WebLayer* pageScaleLayer = rootScrollLayer->parent() ? rootScrollLayer->parent()->platformLayer() : 0;
3636 m_layerTreeView->registerViewportLayers(pageScaleLayer, rootScrollLayer->platformLayer(), 0);
3639 m_layerTreeView->clearRootLayer();
3640 if (pinchVirtualViewportEnabled)
3641 page()->frameHost().pinchViewport().clearLayersForTreeView(m_layerTreeView);
3643 m_layerTreeView->clearViewportLayers();
3647 suppressInvalidations(false);
3650 void WebViewImpl::scheduleCompositingLayerSync()
3652 m_layerTreeView->setNeedsAnimate();
3655 void WebViewImpl::scrollRootLayer()
3657 updateLayerTreeViewport();
3660 void WebViewImpl::invalidateRect(const IntRect& rect)
3662 if (m_isAcceleratedCompositingActive) {
3663 ASSERT(m_layerTreeView);
3664 updateLayerTreeViewport();
3665 } else if (m_client)
3666 m_client->didInvalidateRect(rect);
3669 WebCore::GraphicsLayerFactory* WebViewImpl::graphicsLayerFactory() const
3671 return m_graphicsLayerFactory.get();
3674 WebCore::RenderLayerCompositor* WebViewImpl::compositor() const
3677 || !page()->mainFrame()
3678 || !page()->mainFrame()->document()
3679 || !page()->mainFrame()->document()->renderView())
3681 return page()->mainFrame()->document()->renderView()->compositor();
3684 void WebViewImpl::registerForAnimations(WebLayer* layer)
3686 if (m_layerTreeView)
3687 m_layerTreeView->registerForAnimations(layer);
3690 WebCore::GraphicsLayer* WebViewImpl::rootGraphicsLayer()
3692 return m_rootGraphicsLayer;
3695 void WebViewImpl::scheduleAnimation()
3697 if (isAcceleratedCompositingActive()) {
3698 ASSERT(m_layerTreeView);
3699 m_layerTreeView->setNeedsAnimate();
3703 m_client->scheduleAnimation();
3706 void WebViewImpl::setIsAcceleratedCompositingActive(bool active)
3708 blink::Platform::current()->histogramEnumeration("GPU.setIsAcceleratedCompositingActive", active * 2 + m_isAcceleratedCompositingActive, 4);
3710 if (m_isAcceleratedCompositingActive == active)
3714 m_isAcceleratedCompositingActive = false;
3715 // We need to finish all GL rendering before sending didDeactivateCompositor() to prevent
3716 // flickering when compositing turns off. This is only necessary if we're not in
3717 // force-compositing-mode.
3718 if (m_layerTreeView && !page()->settings().forceCompositingMode())
3719 m_layerTreeView->finishAllRendering();
3720 m_client->didDeactivateCompositor();
3721 if (!m_layerTreeViewCommitsDeferred
3722 && blink::Platform::current()->isThreadedCompositingEnabled()) {
3723 ASSERT(m_layerTreeView);
3724 // In threaded compositing mode, force compositing mode is always on so setIsAcceleratedCompositingActive(false)
3725 // means that we're transitioning to a new page. Suppress commits until WebKit generates invalidations so
3726 // we don't attempt to paint too early in the next page load.
3727 m_layerTreeView->setDeferCommits(true);
3728 m_layerTreeViewCommitsDeferred = true;
3730 } else if (m_layerTreeView) {
3731 m_isAcceleratedCompositingActive = true;
3732 updateLayerTreeViewport();
3734 m_pageOverlays->update();
3736 m_client->didActivateCompositor(0);
3738 TRACE_EVENT0("webkit", "WebViewImpl::setIsAcceleratedCompositingActive(true)");
3740 m_client->initializeLayerTreeView();
3741 m_layerTreeView = m_client->layerTreeView();
3742 if (m_layerTreeView) {
3743 m_layerTreeView->setRootLayer(*m_rootLayer);
3745 bool visible = page()->visibilityState() == PageVisibilityStateVisible;
3746 m_layerTreeView->setVisible(visible);
3747 updateLayerTreeDeviceScaleFactor();
3748 m_layerTreeView->setPageScaleFactorAndLimits(pageScaleFactor(), minimumPageScaleFactor(), maximumPageScaleFactor());
3749 updateLayerTreeBackgroundColor();
3750 m_layerTreeView->setHasTransparentBackground(isTransparent());
3751 #if USE(RUBBER_BANDING)
3752 RefPtr<Image> overhangImage = OverscrollTheme::theme()->getOverhangImage();
3754 m_layerTreeView->setOverhangBitmap(overhangImage->nativeImageForCurrentFrame()->bitmap());
3756 updateLayerTreeViewport();
3757 m_client->didActivateCompositor(0);
3758 m_isAcceleratedCompositingActive = true;
3759 m_compositorCreationFailed = false;
3761 m_pageOverlays->update();
3762 m_layerTreeView->setShowFPSCounter(m_showFPSCounter);
3763 m_layerTreeView->setShowPaintRects(m_showPaintRects);
3764 m_layerTreeView->setShowDebugBorders(m_showDebugBorders);
3765 m_layerTreeView->setContinuousPaintingEnabled(m_continuousPaintingEnabled);
3766 m_layerTreeView->setShowScrollBottleneckRects(m_showScrollBottleneckRects);
3768 m_isAcceleratedCompositingActive = false;
3769 m_client->didDeactivateCompositor();
3770 m_compositorCreationFailed = true;
3774 page()->mainFrame()->view()->setClipsRepaints(!m_isAcceleratedCompositingActive);
3777 void WebViewImpl::updateMainFrameScrollPosition(const IntPoint& scrollPosition, bool programmaticScroll)
3779 FrameView* frameView = page()->mainFrame()->view();
3783 if (frameView->scrollPosition() == scrollPosition)
3786 bool oldProgrammaticScroll = frameView->inProgrammaticScroll();
3787 frameView->setInProgrammaticScroll(programmaticScroll);
3788 frameView->notifyScrollPositionChanged(scrollPosition);
3789 frameView->setInProgrammaticScroll(oldProgrammaticScroll);
3792 void WebViewImpl::applyScrollAndScale(const WebSize& scrollDelta, float pageScaleDelta)
3794 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
3797 // With virtual viewport we need only set the scale (see TODO below).
3798 if (page()->settings().pinchVirtualViewportEnabled()) {
3799 WebSize scrollOffset = mainFrame()->scrollOffset();
3800 WebPoint scrollPoint(scrollOffset.width, scrollOffset.height);
3801 setPageScaleFactor(pageScaleFactor() * pageScaleDelta, scrollPoint);
3802 m_doubleTapZoomPending = false;
3806 // TODO(bokan): Old pinch path only - virtual viewport pinch scrolls are automatically updated via GraphicsLayer::DidScroll.
3807 // this should be removed once old pinch is removed.
3808 if (pageScaleDelta == 1) {
3809 TRACE_EVENT_INSTANT2("webkit", "WebViewImpl::applyScrollAndScale::scrollBy", "x", scrollDelta.width, "y", scrollDelta.height);
3810 WebSize webScrollOffset = mainFrame()->scrollOffset();
3811 IntPoint scrollOffset(webScrollOffset.width + scrollDelta.width, webScrollOffset.height + scrollDelta.height);
3812 updateMainFrameScrollPosition(scrollOffset, false);
3814 // The page scale changed, so apply a scale and scroll in a single
3816 WebSize scrollOffset = mainFrame()->scrollOffset();
3817 scrollOffset.width += scrollDelta.width;
3818 scrollOffset.height += scrollDelta.height;
3820 WebPoint scrollPoint(scrollOffset.width, scrollOffset.height);
3821 setPageScaleFactor(pageScaleFactor() * pageScaleDelta, scrollPoint);
3822 m_doubleTapZoomPending = false;
3826 void WebViewImpl::didExitCompositingMode()
3828 ASSERT(m_isAcceleratedCompositingActive);
3829 setIsAcceleratedCompositingActive(false);
3830 m_compositorCreationFailed = true;
3831 m_client->didInvalidateRect(IntRect(0, 0, m_size.width, m_size.height));
3833 // Force a style recalc to remove all the composited layers.
3834 m_page->mainFrame()->document()->setNeedsStyleRecalc(SubtreeStyleChange);
3837 m_pageOverlays->update();
3840 void WebViewImpl::updateLayerTreeViewport()
3842 if (!page() || !m_layerTreeView)
3845 m_layerTreeView->setPageScaleFactorAndLimits(pageScaleFactor(), minimumPageScaleFactor(), maximumPageScaleFactor());
3848 void WebViewImpl::updateLayerTreeBackgroundColor()
3850 if (!m_layerTreeView)
3853 m_layerTreeView->setBackgroundColor(alphaChannel(m_backgroundColorOverride) ? m_backgroundColorOverride : backgroundColor());
3856 void WebViewImpl::updateLayerTreeDeviceScaleFactor()
3859 ASSERT(m_layerTreeView);
3861 float deviceScaleFactor = m_compositorDeviceScaleFactorOverride ? m_compositorDeviceScaleFactorOverride : page()->deviceScaleFactor();
3862 m_layerTreeView->setDeviceScaleFactor(deviceScaleFactor);
3865 void WebViewImpl::updateRootLayerTransform()
3867 // If we don't have a root graphics layer, we won't bother trying to find
3868 // or update the transform layer.
3869 if (!m_rootGraphicsLayer)
3872 if (!m_rootTransformLayer)
3873 m_rootTransformLayer = m_page->mainFrame()->view()->renderView()->compositor()->ensureRootTransformLayer();
3875 if (m_rootTransformLayer) {
3876 WebCore::TransformationMatrix transform;
3877 transform.translate(m_rootLayerOffset.width, m_rootLayerOffset.height);
3878 transform = transform.scale(m_rootLayerScale);
3879 m_rootTransformLayer->setTransform(transform);
3883 bool WebViewImpl::detectContentOnTouch(const WebPoint& position)
3885 HitTestResult touchHit = hitTestResultForWindowPos(position);
3887 if (touchHit.isContentEditable())
3890 Node* node = touchHit.innerNode();
3891 if (!node || !node->isTextNode())
3894 // Ignore when tapping on links or nodes listening to click events, unless the click event is on the
3895 // body element, in which case it's unlikely that the original node itself was intended to be clickable.
3896 for (; node && !isHTMLBodyElement(*node); node = node->parentNode()) {
3897 if (node->isLink() || node->willRespondToTouchEvents() || node->willRespondToMouseClickEvents())
3901 WebContentDetectionResult content = m_client->detectContentAround(touchHit);
3902 if (!content.isValid())
3905 m_client->scheduleContentIntent(content.intent());
3909 void WebViewImpl::setVisibilityState(WebPageVisibilityState visibilityState,
3910 bool isInitialState) {
3914 ASSERT(visibilityState == WebPageVisibilityStateVisible || visibilityState == WebPageVisibilityStateHidden || visibilityState == WebPageVisibilityStatePrerender);
3915 m_page->setVisibilityState(static_cast<PageVisibilityState>(static_cast<int>(visibilityState)), isInitialState);
3917 if (m_layerTreeView) {
3918 bool visible = visibilityState == WebPageVisibilityStateVisible;
3919 m_layerTreeView->setVisible(visible);
3923 bool WebViewImpl::requestPointerLock()
3925 return m_client && m_client->requestPointerLock();
3928 void WebViewImpl::requestPointerUnlock()
3931 m_client->requestPointerUnlock();
3934 bool WebViewImpl::isPointerLocked()
3936 return m_client && m_client->isPointerLocked();
3939 void WebViewImpl::pointerLockMouseEvent(const WebInputEvent& event)
3941 AtomicString eventType;
3942 switch (event.type) {
3943 case WebInputEvent::MouseDown:
3944 eventType = EventTypeNames::mousedown;
3946 case WebInputEvent::MouseUp:
3947 eventType = EventTypeNames::mouseup;
3949 case WebInputEvent::MouseMove:
3950 eventType = EventTypeNames::mousemove;
3953 ASSERT_NOT_REACHED();
3956 const WebMouseEvent& mouseEvent = static_cast<const WebMouseEvent&>(event);
3959 page()->pointerLockController().dispatchLockedMouseEvent(
3960 PlatformMouseEventBuilder(mainFrameImpl()->frameView(), mouseEvent),
3964 bool WebViewImpl::shouldDisableDesktopWorkarounds()
3966 if (!settings()->viewportEnabled())
3969 // A document is considered adapted to small screen UAs if one of these holds:
3970 // 1. The author specified viewport has a constrained width that is equal to
3971 // the initial viewport width.
3972 // 2. The author has disabled viewport zoom.
3974 const PageScaleConstraints& constraints = m_pageScaleConstraintsSet.pageDefinedConstraints();
3976 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
3979 return mainFrameImpl()->frameView()->layoutSize().width() == m_size.width
3980 || (constraints.minimumScale == constraints.maximumScale && constraints.minimumScale != -1);
3983 } // namespace blink