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 (m_selectPopup && m_selectPopup == selectPopup) {
487 // That click triggered a select popup which is the same as the one that
488 // was showing before the click. It means the user clicked the select
489 // while the popup was showing, and as a result we first closed then
490 // immediately reopened the select popup. It needs to be closed.
494 if (m_pagePopup && pagePopup && m_pagePopup->hasSamePopupClient(pagePopup.get())) {
495 // That click triggered a page popup that is the same as the one we just closed.
496 // It needs to be closed.
497 closePagePopup(m_pagePopup.get());
500 // Dispatch the contextmenu event regardless of if the click was swallowed.
502 // On Windows, we handle it on mouse up, not down.
504 if (event.button == WebMouseEvent::ButtonRight
505 || (event.button == WebMouseEvent::ButtonLeft
506 && event.modifiers & WebMouseEvent::ControlKey))
507 mouseContextMenu(event);
509 if (event.button == WebMouseEvent::ButtonRight)
510 mouseContextMenu(event);
514 void WebViewImpl::mouseContextMenu(const WebMouseEvent& event)
516 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
519 m_page->contextMenuController().clearContextMenu();
521 PlatformMouseEventBuilder pme(mainFrameImpl()->frameView(), event);
523 // Find the right target frame. See issue 1186900.
524 HitTestResult result = hitTestResultForWindowPos(pme.position());
525 LocalFrame* targetFrame;
526 if (result.innerNonSharedNode())
527 targetFrame = result.innerNonSharedNode()->document().frame();
529 targetFrame = m_page->focusController().focusedOrMainFrame();
532 targetFrame->view()->setCursor(pointerCursor());
535 m_contextMenuAllowed = true;
536 targetFrame->eventHandler().sendContextMenuEvent(pme);
537 m_contextMenuAllowed = false;
538 // Actually showing the context menu is handled by the ContextMenuClient
542 void WebViewImpl::handleMouseUp(LocalFrame& mainFrame, const WebMouseEvent& event)
544 PageWidgetEventHandler::handleMouseUp(mainFrame, event);
547 // Dispatch the contextmenu event regardless of if the click was swallowed.
548 // On Mac/Linux, we handle it on mouse down, not up.
549 if (event.button == WebMouseEvent::ButtonRight)
550 mouseContextMenu(event);
554 bool WebViewImpl::handleMouseWheel(LocalFrame& mainFrame, const WebMouseWheelEvent& event)
557 return PageWidgetEventHandler::handleMouseWheel(mainFrame, event);
560 void WebViewImpl::scrollBy(const WebFloatSize& delta)
562 if (m_flingSourceDevice == WebGestureEvent::Touchpad) {
563 WebMouseWheelEvent syntheticWheel;
564 const float tickDivisor = WebCore::WheelEvent::TickMultiplier;
566 syntheticWheel.deltaX = delta.width;
567 syntheticWheel.deltaY = delta.height;
568 syntheticWheel.wheelTicksX = delta.width / tickDivisor;
569 syntheticWheel.wheelTicksY = delta.height / tickDivisor;
570 syntheticWheel.hasPreciseScrollingDeltas = true;
571 syntheticWheel.x = m_positionOnFlingStart.x;
572 syntheticWheel.y = m_positionOnFlingStart.y;
573 syntheticWheel.globalX = m_globalPositionOnFlingStart.x;
574 syntheticWheel.globalY = m_globalPositionOnFlingStart.y;
575 syntheticWheel.modifiers = m_flingModifier;
577 if (m_page && m_page->mainFrame() && m_page->mainFrame()->view())
578 handleMouseWheel(*m_page->mainFrame(), syntheticWheel);
580 WebGestureEvent syntheticGestureEvent;
582 syntheticGestureEvent.type = WebInputEvent::GestureScrollUpdateWithoutPropagation;
583 syntheticGestureEvent.data.scrollUpdate.deltaX = delta.width;
584 syntheticGestureEvent.data.scrollUpdate.deltaY = delta.height;
585 syntheticGestureEvent.x = m_positionOnFlingStart.x;
586 syntheticGestureEvent.y = m_positionOnFlingStart.y;
587 syntheticGestureEvent.globalX = m_globalPositionOnFlingStart.x;
588 syntheticGestureEvent.globalY = m_globalPositionOnFlingStart.y;
589 syntheticGestureEvent.modifiers = m_flingModifier;
590 syntheticGestureEvent.sourceDevice = WebGestureEvent::Touchscreen;
592 if (m_page && m_page->mainFrame() && m_page->mainFrame()->view())
593 handleGestureEvent(syntheticGestureEvent);
597 bool WebViewImpl::handleGestureEvent(const WebGestureEvent& event)
599 bool eventSwallowed = false;
600 bool eventCancelled = false; // for disambiguation
602 // Special handling for slow-path fling gestures.
603 switch (event.type) {
604 case WebInputEvent::GestureFlingStart: {
605 if (mainFrameImpl()->frame()->eventHandler().isScrollbarHandlingGestures())
607 m_client->cancelScheduledContentIntents();
608 m_positionOnFlingStart = WebPoint(event.x / pageScaleFactor(), event.y / pageScaleFactor());
609 m_globalPositionOnFlingStart = WebPoint(event.globalX, event.globalY);
610 m_flingModifier = event.modifiers;
611 m_flingSourceDevice = event.sourceDevice;
612 OwnPtr<WebGestureCurve> flingCurve = adoptPtr(Platform::current()->createFlingAnimationCurve(event.sourceDevice, WebFloatPoint(event.data.flingStart.velocityX, event.data.flingStart.velocityY), WebSize()));
613 m_gestureAnimation = WebActiveGestureAnimation::createAtAnimationStart(flingCurve.release(), this);
615 eventSwallowed = true;
617 m_client->didHandleGestureEvent(event, eventCancelled);
618 return eventSwallowed;
620 case WebInputEvent::GestureFlingCancel:
621 if (endActiveFlingAnimation())
622 eventSwallowed = true;
624 m_client->didHandleGestureEvent(event, eventCancelled);
625 return eventSwallowed;
630 PlatformGestureEventBuilder platformEvent(mainFrameImpl()->frameView(), event);
632 // Handle link highlighting outside the main switch to avoid getting lost in the
633 // complicated set of cases handled below.
634 switch (event.type) {
635 case WebInputEvent::GestureShowPress:
636 // Queue a highlight animation, then hand off to regular handler.
637 if (settingsImpl()->gestureTapHighlightEnabled())
638 enableTapHighlightAtPoint(platformEvent);
640 case WebInputEvent::GestureTapCancel:
641 case WebInputEvent::GestureTap:
642 case WebInputEvent::GestureLongPress:
643 for (size_t i = 0; i < m_linkHighlights.size(); ++i)
644 m_linkHighlights[i]->startHighlightAnimationIfNeeded();
650 switch (event.type) {
651 case WebInputEvent::GestureTap: {
652 m_client->cancelScheduledContentIntents();
653 if (detectContentOnTouch(platformEvent.position())) {
654 eventSwallowed = true;
658 RefPtr<PopupContainer> selectPopup;
659 selectPopup = m_selectPopup;
661 ASSERT(!m_selectPopup);
663 // Don't trigger a disambiguation popup on sites designed for mobile devices.
664 // Instead, assume that the page has been designed with big enough buttons and links.
665 if (event.data.tap.width > 0 && !shouldDisableDesktopWorkarounds()) {
666 // FIXME: didTapMultipleTargets should just take a rect instead of
668 WebGestureEvent scaledEvent = event;
669 scaledEvent.x = event.x / pageScaleFactor();
670 scaledEvent.y = event.y / pageScaleFactor();
671 scaledEvent.data.tap.width = event.data.tap.width / pageScaleFactor();
672 scaledEvent.data.tap.height = event.data.tap.height / pageScaleFactor();
673 IntRect boundingBox(scaledEvent.x - scaledEvent.data.tap.width / 2, scaledEvent.y - scaledEvent.data.tap.height / 2, scaledEvent.data.tap.width, scaledEvent.data.tap.height);
674 Vector<IntRect> goodTargets;
675 Vector<Node*> highlightNodes;
676 findGoodTouchTargets(boundingBox, mainFrameImpl()->frame(), goodTargets, highlightNodes);
677 // FIXME: replace touch adjustment code when numberOfGoodTargets == 1?
678 // Single candidate case is currently handled by: https://bugs.webkit.org/show_bug.cgi?id=85101
679 if (goodTargets.size() >= 2 && m_client && m_client->didTapMultipleTargets(scaledEvent, goodTargets)) {
680 if (settingsImpl()->gestureTapHighlightEnabled())
681 enableTapHighlights(highlightNodes);
682 for (size_t i = 0; i < m_linkHighlights.size(); ++i)
683 m_linkHighlights[i]->startHighlightAnimationIfNeeded();
684 eventSwallowed = true;
685 eventCancelled = true;
690 eventSwallowed = mainFrameImpl()->frame()->eventHandler().handleGestureEvent(platformEvent);
692 if (m_selectPopup && m_selectPopup == selectPopup) {
693 // That tap triggered a select popup which is the same as the one that
694 // was showing before the tap. It means the user tapped the select
695 // while the popup was showing, and as a result we first closed then
696 // immediately reopened the select popup. It needs to be closed.
702 case WebInputEvent::GestureTwoFingerTap:
703 case WebInputEvent::GestureLongPress:
704 case WebInputEvent::GestureLongTap: {
705 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
708 m_client->cancelScheduledContentIntents();
709 m_page->contextMenuController().clearContextMenu();
710 m_contextMenuAllowed = true;
711 eventSwallowed = mainFrameImpl()->frame()->eventHandler().handleGestureEvent(platformEvent);
712 m_contextMenuAllowed = false;
716 case WebInputEvent::GestureShowPress: {
717 m_client->cancelScheduledContentIntents();
718 eventSwallowed = mainFrameImpl()->frame()->eventHandler().handleGestureEvent(platformEvent);
721 case WebInputEvent::GestureDoubleTap:
722 if (m_webSettings->doubleTapToZoomEnabled() && minimumPageScaleFactor() != maximumPageScaleFactor()) {
723 m_client->cancelScheduledContentIntents();
724 animateDoubleTapZoom(platformEvent.position());
726 // GestureDoubleTap is currently only used by Android for zooming. For WebCore,
727 // GestureTap with tap count = 2 is used instead. So we drop GestureDoubleTap here.
728 eventSwallowed = true;
730 case WebInputEvent::GestureScrollBegin:
731 case WebInputEvent::GesturePinchBegin:
732 m_client->cancelScheduledContentIntents();
733 case WebInputEvent::GestureTapDown:
734 case WebInputEvent::GestureScrollEnd:
735 case WebInputEvent::GestureScrollUpdate:
736 case WebInputEvent::GestureScrollUpdateWithoutPropagation:
737 case WebInputEvent::GestureTapCancel:
738 case WebInputEvent::GestureTapUnconfirmed:
739 case WebInputEvent::GesturePinchEnd:
740 case WebInputEvent::GesturePinchUpdate:
741 case WebInputEvent::GestureFlingStart: {
742 eventSwallowed = mainFrameImpl()->frame()->eventHandler().handleGestureEvent(platformEvent);
746 ASSERT_NOT_REACHED();
748 m_client->didHandleGestureEvent(event, eventCancelled);
749 return eventSwallowed;
752 void WebViewImpl::transferActiveWheelFlingAnimation(const WebActiveWheelFlingParameters& parameters)
754 TRACE_EVENT0("webkit", "WebViewImpl::transferActiveWheelFlingAnimation");
755 ASSERT(!m_gestureAnimation);
756 m_positionOnFlingStart = parameters.point;
757 m_globalPositionOnFlingStart = parameters.globalPoint;
758 m_flingModifier = parameters.modifiers;
759 OwnPtr<WebGestureCurve> curve = adoptPtr(Platform::current()->createFlingAnimationCurve(parameters.sourceDevice, WebFloatPoint(parameters.delta), parameters.cumulativeScroll));
760 m_gestureAnimation = WebActiveGestureAnimation::createWithTimeOffset(curve.release(), this, parameters.startTime);
764 bool WebViewImpl::endActiveFlingAnimation()
766 if (m_gestureAnimation) {
767 m_gestureAnimation.clear();
769 m_layerTreeView->didStopFlinging();
775 bool WebViewImpl::startPageScaleAnimation(const IntPoint& targetPosition, bool useAnchor, float newScale, double durationInSeconds)
777 WebPoint clampedPoint = targetPosition;
779 clampedPoint = clampOffsetAtScale(targetPosition, newScale);
780 if (!durationInSeconds) {
781 setPageScaleFactor(newScale, clampedPoint);
785 if (useAnchor && newScale == pageScaleFactor())
788 if (m_enableFakePageScaleAnimationForTesting) {
789 m_fakePageScaleAnimationTargetPosition = targetPosition;
790 m_fakePageScaleAnimationUseAnchor = useAnchor;
791 m_fakePageScaleAnimationPageScaleFactor = newScale;
793 if (!m_layerTreeView)
795 m_layerTreeView->startPageScaleAnimation(targetPosition, useAnchor, newScale, durationInSeconds);
800 void WebViewImpl::enableFakePageScaleAnimationForTesting(bool enable)
802 m_enableFakePageScaleAnimationForTesting = enable;
805 void WebViewImpl::setShowFPSCounter(bool show)
807 if (m_layerTreeView) {
808 TRACE_EVENT0("webkit", "WebViewImpl::setShowFPSCounter");
809 m_layerTreeView->setShowFPSCounter(show);
811 m_showFPSCounter = show;
814 void WebViewImpl::setShowPaintRects(bool show)
816 if (m_layerTreeView) {
817 TRACE_EVENT0("webkit", "WebViewImpl::setShowPaintRects");
818 m_layerTreeView->setShowPaintRects(show);
820 m_showPaintRects = show;
823 void WebViewImpl::setShowDebugBorders(bool show)
826 m_layerTreeView->setShowDebugBorders(show);
827 m_showDebugBorders = show;
830 void WebViewImpl::setContinuousPaintingEnabled(bool enabled)
832 if (m_layerTreeView) {
833 TRACE_EVENT0("webkit", "WebViewImpl::setContinuousPaintingEnabled");
834 m_layerTreeView->setContinuousPaintingEnabled(enabled);
836 m_continuousPaintingEnabled = enabled;
837 m_client->scheduleAnimation();
840 void WebViewImpl::setShowScrollBottleneckRects(bool show)
843 m_layerTreeView->setShowScrollBottleneckRects(show);
844 m_showScrollBottleneckRects = show;
847 void WebViewImpl::getSelectionRootBounds(WebRect& bounds) const
849 const LocalFrame* frame = focusedWebCoreFrame();
853 Element* root = frame->selection().rootEditableElementOrDocumentElement();
857 // If the selection is inside a form control, the root will be a <div> that
858 // behaves as the editor but we want to return the actual element's bounds.
859 // In practice, that means <textarea> and <input> controls that behave like
861 Element* shadowHost = root->shadowHost();
863 && (isHTMLTextAreaElement(*shadowHost)
864 || (isHTMLInputElement(*shadowHost)
865 && toHTMLInputElement(*shadowHost).isText())))
868 IntRect boundingBox = root->pixelSnappedBoundingBox();
869 boundingBox = root->document().frame()->view()->contentsToWindow(boundingBox);
870 boundingBox.scale(pageScaleFactor());
871 bounds = boundingBox;
874 bool WebViewImpl::handleKeyEvent(const WebKeyboardEvent& event)
876 ASSERT((event.type == WebInputEvent::RawKeyDown)
877 || (event.type == WebInputEvent::KeyDown)
878 || (event.type == WebInputEvent::KeyUp));
880 // Halt an in-progress fling on a key event.
881 endActiveFlingAnimation();
883 // Please refer to the comments explaining the m_suppressNextKeypressEvent
885 // The m_suppressNextKeypressEvent is set if the KeyDown is handled by
886 // Webkit. A keyDown event is typically associated with a keyPress(char)
887 // event and a keyUp event. We reset this flag here as this is a new keyDown
889 m_suppressNextKeypressEvent = false;
891 // If there is a select popup, it should be the one processing the event,
894 return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
896 m_pagePopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
897 // We need to ignore the next Char event after this otherwise pressing
898 // enter when selecting an item in the popup will go to the page.
899 if (WebInputEvent::RawKeyDown == event.type)
900 m_suppressNextKeypressEvent = true;
904 RefPtr<LocalFrame> frame = focusedWebCoreFrame();
909 const WebInputEvent::Type contextMenuTriggeringEventType =
911 WebInputEvent::KeyUp;
913 WebInputEvent::RawKeyDown;
916 bool isUnmodifiedMenuKey = !(event.modifiers & WebInputEvent::InputModifiers) && event.windowsKeyCode == VKEY_APPS;
917 bool isShiftF10 = event.modifiers == WebInputEvent::ShiftKey && event.windowsKeyCode == VKEY_F10;
918 if ((isUnmodifiedMenuKey || isShiftF10) && event.type == contextMenuTriggeringEventType) {
919 sendContextMenuEvent(event);
922 #endif // !OS(MACOSX)
924 PlatformKeyboardEventBuilder evt(event);
926 if (frame->eventHandler().keyEvent(evt)) {
927 if (WebInputEvent::RawKeyDown == event.type) {
928 // Suppress the next keypress event unless the focused node is a plug-in node.
929 // (Flash needs these keypress events to handle non-US keyboards.)
930 Element* element = focusedElement();
931 if (!element || !element->renderer() || !element->renderer()->isEmbeddedObject())
932 m_suppressNextKeypressEvent = true;
937 return keyEventDefault(event);
940 bool WebViewImpl::handleCharEvent(const WebKeyboardEvent& event)
942 ASSERT(event.type == WebInputEvent::Char);
944 // Please refer to the comments explaining the m_suppressNextKeypressEvent
945 // member. The m_suppressNextKeypressEvent is set if the KeyDown is
946 // handled by Webkit. A keyDown event is typically associated with a
947 // keyPress(char) event and a keyUp event. We reset this flag here as it
948 // only applies to the current keyPress event.
949 bool suppress = m_suppressNextKeypressEvent;
950 m_suppressNextKeypressEvent = false;
952 // If there is a select popup, it should be the one processing the event,
955 return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
957 return m_pagePopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
959 LocalFrame* frame = focusedWebCoreFrame();
963 EventHandler& handler = frame->eventHandler();
965 PlatformKeyboardEventBuilder evt(event);
966 if (!evt.isCharacterKey())
969 // Accesskeys are triggered by char events and can't be suppressed.
970 if (handler.handleAccessKey(evt))
973 // Safari 3.1 does not pass off windows system key messages (WM_SYSCHAR) to
974 // the eventHandler::keyEvent. We mimic this behavior on all platforms since
975 // for now we are converting other platform's key events to windows key
977 if (evt.isSystemKey())
980 if (!suppress && !handler.keyEvent(evt))
981 return keyEventDefault(event);
986 WebRect WebViewImpl::computeBlockBounds(const WebRect& rect, bool ignoreClipping)
988 if (!mainFrameImpl())
991 // Use the rect-based hit test to find the node.
992 IntPoint point = mainFrameImpl()->frameView()->windowToContents(IntPoint(rect.x, rect.y));
993 HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent | (ignoreClipping ? HitTestRequest::IgnoreClipping : 0);
994 HitTestResult result = mainFrameImpl()->frame()->eventHandler().hitTestResultAtPoint(point, hitType, IntSize(rect.width, rect.height));
996 Node* node = result.innerNonSharedNode();
1000 // Find the block type node based on the hit node.
1001 while (node && (!node->renderer() || node->renderer()->isInline()))
1002 node = node->parentNode();
1004 // Return the bounding box in the window coordinate system.
1006 IntRect rect = node->Node::pixelSnappedBoundingBox();
1007 LocalFrame* frame = node->document().frame();
1008 return frame->view()->contentsToWindow(rect);
1013 WebRect WebViewImpl::widenRectWithinPageBounds(const WebRect& source, int targetMargin, int minimumMargin)
1017 maxSize = mainFrame()->contentsSize();
1018 IntSize scrollOffset;
1020 scrollOffset = mainFrame()->scrollOffset();
1021 int leftMargin = targetMargin;
1022 int rightMargin = targetMargin;
1024 const int absoluteSourceX = source.x + scrollOffset.width();
1025 if (leftMargin > absoluteSourceX) {
1026 leftMargin = absoluteSourceX;
1027 rightMargin = max(leftMargin, minimumMargin);
1030 const int maximumRightMargin = maxSize.width - (source.width + absoluteSourceX);
1031 if (rightMargin > maximumRightMargin) {
1032 rightMargin = maximumRightMargin;
1033 leftMargin = min(leftMargin, max(rightMargin, minimumMargin));
1036 const int newWidth = source.width + leftMargin + rightMargin;
1037 const int newX = source.x - leftMargin;
1039 ASSERT(newWidth >= 0);
1040 ASSERT(scrollOffset.width() + newX + newWidth <= maxSize.width);
1042 return WebRect(newX, source.y, newWidth, source.height);
1045 float WebViewImpl::legibleScale() const
1047 // Pages should be as legible as on desktop when at dpi scale, so no
1048 // need to zoom in further when automatically determining zoom level
1049 // (after double tap, find in page, etc), though the user should still
1050 // be allowed to manually pinch zoom in further if they desire.
1051 float legibleScale = 1;
1053 legibleScale *= page()->settings().accessibilityFontScaleFactor();
1054 return legibleScale;
1057 void WebViewImpl::computeScaleAndScrollForBlockRect(const WebPoint& hitPoint, const WebRect& blockRect, float padding, float defaultScaleWhenAlreadyLegible, float& scale, WebPoint& scroll)
1059 scale = pageScaleFactor();
1060 scroll.x = scroll.y = 0;
1062 WebRect rect = blockRect;
1064 if (!rect.isEmpty()) {
1065 float defaultMargin = doubleTapZoomContentDefaultMargin;
1066 float minimumMargin = doubleTapZoomContentMinimumMargin;
1067 // We want the margins to have the same physical size, which means we
1068 // need to express them in post-scale size. To do that we'd need to know
1069 // the scale we're scaling to, but that depends on the margins. Instead
1070 // we express them as a fraction of the target rectangle: this will be
1071 // correct if we end up fully zooming to it, and won't matter if we
1073 rect = widenRectWithinPageBounds(rect,
1074 static_cast<int>(defaultMargin * rect.width / m_size.width),
1075 static_cast<int>(minimumMargin * rect.width / m_size.width));
1076 // Fit block to screen, respecting limits.
1077 scale = static_cast<float>(m_size.width) / rect.width;
1078 scale = min(scale, legibleScale());
1079 if (pageScaleFactor() < defaultScaleWhenAlreadyLegible)
1080 scale = max(scale, defaultScaleWhenAlreadyLegible);
1081 scale = clampPageScaleFactorToLimits(scale);
1084 // FIXME: If this is being called for auto zoom during find in page,
1085 // then if the user manually zooms in it'd be nice to preserve the
1086 // relative increase in zoom they caused (if they zoom out then it's ok
1087 // to zoom them back in again). This isn't compatible with our current
1088 // double-tap zoom strategy (fitting the containing block to the screen)
1091 float screenWidth = m_size.width / scale;
1092 float screenHeight = m_size.height / scale;
1094 // Scroll to vertically align the block.
1095 if (rect.height < screenHeight) {
1096 // Vertically center short blocks.
1097 rect.y -= 0.5 * (screenHeight - rect.height);
1099 // Ensure position we're zooming to (+ padding) isn't off the bottom of
1101 rect.y = max<float>(rect.y, hitPoint.y + padding - screenHeight);
1102 } // Otherwise top align the block.
1104 // Do the same thing for horizontal alignment.
1105 if (rect.width < screenWidth)
1106 rect.x -= 0.5 * (screenWidth - rect.width);
1108 rect.x = max<float>(rect.x, hitPoint.x + padding - screenWidth);
1112 scale = clampPageScaleFactorToLimits(scale);
1113 scroll = mainFrameImpl()->frameView()->windowToContents(scroll);
1114 scroll = clampOffsetAtScale(scroll, scale);
1117 static bool invokesHandCursor(Node* node, bool shiftKey, LocalFrame* frame)
1119 if (!node || !node->renderer())
1122 ECursor cursor = node->renderer()->style()->cursor();
1123 return cursor == CURSOR_POINTER
1124 || (cursor == CURSOR_AUTO && frame->eventHandler().useHandCursor(node, node->isLink(), shiftKey));
1127 Node* WebViewImpl::bestTapNode(const PlatformGestureEvent& tapEvent)
1129 if (!m_page || !m_page->mainFrame())
1132 Node* bestTouchNode = 0;
1134 IntPoint touchEventLocation(tapEvent.position());
1135 m_page->mainFrame()->eventHandler().adjustGesturePosition(tapEvent, touchEventLocation);
1137 IntPoint hitTestPoint = m_page->mainFrame()->view()->windowToContents(touchEventLocation);
1138 HitTestResult result = m_page->mainFrame()->eventHandler().hitTestResultAtPoint(hitTestPoint, HitTestRequest::TouchEvent | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
1139 bestTouchNode = result.targetNode();
1141 // We might hit something like an image map that has no renderer on it
1142 // Walk up the tree until we have a node with an attached renderer
1143 while (bestTouchNode && !bestTouchNode->renderer())
1144 bestTouchNode = bestTouchNode->parentNode();
1146 // Check if we're in the subtree of a node with a hand cursor
1147 // this is the heuristic we use to determine if we show a highlight on tap
1148 while (bestTouchNode && !invokesHandCursor(bestTouchNode, false, m_page->mainFrame()))
1149 bestTouchNode = bestTouchNode->parentNode();
1154 // We should pick the largest enclosing node with hand cursor set.
1155 while (bestTouchNode->parentNode() && invokesHandCursor(bestTouchNode->parentNode(), false, m_page->mainFrame()))
1156 bestTouchNode = bestTouchNode->parentNode();
1158 return bestTouchNode;
1161 void WebViewImpl::enableTapHighlightAtPoint(const PlatformGestureEvent& tapEvent)
1163 Node* touchNode = bestTapNode(tapEvent);
1165 Vector<Node*> highlightNodes;
1166 highlightNodes.append(touchNode);
1168 enableTapHighlights(highlightNodes);
1171 void WebViewImpl::enableTapHighlights(Vector<Node*>& highlightNodes)
1173 if (highlightNodes.isEmpty())
1176 // Always clear any existing highlight when this is invoked, even if we
1177 // don't get a new target to highlight.
1178 m_linkHighlights.clear();
1180 // LinkHighlight reads out layout and compositing state, so we need to make sure that's all up to date.
1183 for (size_t i = 0; i < highlightNodes.size(); ++i) {
1184 Node* node = highlightNodes[i];
1186 if (!node || !node->renderer())
1189 Color highlightColor = node->renderer()->style()->tapHighlightColor();
1190 // Safari documentation for -webkit-tap-highlight-color says if the specified color has 0 alpha,
1191 // then tap highlighting is disabled.
1192 // http://developer.apple.com/library/safari/#documentation/appleapplications/reference/safaricssref/articles/standardcssproperties.html
1193 if (!highlightColor.alpha())
1196 m_linkHighlights.append(LinkHighlight::create(node, this));
1200 void WebViewImpl::animateDoubleTapZoom(const IntPoint& point)
1202 if (!mainFrameImpl())
1205 WebRect rect(point.x(), point.y(), touchPointPadding, touchPointPadding);
1206 WebRect blockBounds = computeBlockBounds(rect, false);
1211 computeScaleAndScrollForBlockRect(point, blockBounds, touchPointPadding, minimumPageScaleFactor() * doubleTapZoomAlreadyLegibleRatio, scale, scroll);
1213 bool stillAtPreviousDoubleTapScale = (pageScaleFactor() == m_doubleTapZoomPageScaleFactor
1214 && m_doubleTapZoomPageScaleFactor != minimumPageScaleFactor())
1215 || m_doubleTapZoomPending;
1217 bool scaleUnchanged = fabs(pageScaleFactor() - scale) < minScaleDifference;
1218 bool shouldZoomOut = blockBounds.isEmpty() || scaleUnchanged || stillAtPreviousDoubleTapScale;
1222 if (shouldZoomOut) {
1223 scale = minimumPageScaleFactor();
1224 isAnimating = startPageScaleAnimation(mainFrameImpl()->frameView()->windowToContents(point), true, scale, doubleTapZoomAnimationDurationInSeconds);
1226 isAnimating = startPageScaleAnimation(scroll, false, scale, doubleTapZoomAnimationDurationInSeconds);
1230 m_doubleTapZoomPageScaleFactor = scale;
1231 m_doubleTapZoomPending = true;
1235 void WebViewImpl::zoomToFindInPageRect(const WebRect& rect)
1237 if (!mainFrameImpl())
1240 WebRect blockBounds = computeBlockBounds(rect, true);
1242 if (blockBounds.isEmpty()) {
1243 // Keep current scale (no need to scroll as x,y will normally already
1244 // be visible). FIXME: Revisit this if it isn't always true.
1251 computeScaleAndScrollForBlockRect(WebPoint(rect.x, rect.y), blockBounds, nonUserInitiatedPointPadding, minimumPageScaleFactor(), scale, scroll);
1253 startPageScaleAnimation(scroll, false, scale, findInPageAnimationDurationInSeconds);
1256 bool WebViewImpl::zoomToMultipleTargetsRect(const WebRect& rect)
1258 if (!mainFrameImpl())
1264 computeScaleAndScrollForBlockRect(WebPoint(rect.x, rect.y), rect, nonUserInitiatedPointPadding, minimumPageScaleFactor(), scale, scroll);
1266 if (scale <= pageScaleFactor())
1269 startPageScaleAnimation(scroll, false, scale, multipleTargetsZoomAnimationDurationInSeconds);
1273 void WebViewImpl::numberOfWheelEventHandlersChanged(unsigned numberOfWheelHandlers)
1276 m_client->numberOfWheelEventHandlersChanged(numberOfWheelHandlers);
1279 void WebViewImpl::hasTouchEventHandlers(bool hasTouchHandlers)
1282 m_client->hasTouchEventHandlers(hasTouchHandlers);
1285 bool WebViewImpl::hasTouchEventHandlersAt(const WebPoint& point)
1287 // FIXME: Implement this. Note that the point must be divided by pageScaleFactor.
1292 // Mac has no way to open a context menu based on a keyboard event.
1293 bool WebViewImpl::sendContextMenuEvent(const WebKeyboardEvent& event)
1295 // The contextMenuController() holds onto the last context menu that was
1296 // popped up on the page until a new one is created. We need to clear
1297 // this menu before propagating the event through the DOM so that we can
1298 // detect if we create a new menu for this event, since we won't create
1299 // a new menu if the DOM swallows the event and the defaultEventHandler does
1301 page()->contextMenuController().clearContextMenu();
1303 m_contextMenuAllowed = true;
1304 LocalFrame* focusedFrame = page()->focusController().focusedOrMainFrame();
1305 bool handled = focusedFrame->eventHandler().sendContextMenuEventForKey();
1306 m_contextMenuAllowed = false;
1311 bool WebViewImpl::keyEventDefault(const WebKeyboardEvent& event)
1313 LocalFrame* frame = focusedWebCoreFrame();
1317 switch (event.type) {
1318 case WebInputEvent::Char:
1319 if (event.windowsKeyCode == VKEY_SPACE) {
1320 int keyCode = ((event.modifiers & WebInputEvent::ShiftKey) ? VKEY_PRIOR : VKEY_NEXT);
1321 return scrollViewWithKeyboard(keyCode, event.modifiers);
1324 case WebInputEvent::RawKeyDown:
1325 if (event.modifiers == WebInputEvent::ControlKey) {
1326 switch (event.windowsKeyCode) {
1329 focusedFrame()->executeCommand(WebString::fromUTF8("SelectAll"));
1333 focusedFrame()->executeCommand(WebString::fromUTF8("Copy"));
1336 // Match FF behavior in the sense that Ctrl+home/end are the only Ctrl
1337 // key combinations which affect scrolling. Safari is buggy in the
1338 // sense that it scrolls the page for all Ctrl+scrolling key
1339 // combinations. For e.g. Ctrl+pgup/pgdn/up/down, etc.
1347 if (!event.isSystemKey && !(event.modifiers & WebInputEvent::ShiftKey))
1348 return scrollViewWithKeyboard(event.windowsKeyCode, event.modifiers);
1356 bool WebViewImpl::scrollViewWithKeyboard(int keyCode, int modifiers)
1358 ScrollDirection scrollDirection;
1359 ScrollGranularity scrollGranularity;
1361 // Control-Up/Down should be PageUp/Down on Mac.
1362 if (modifiers & WebMouseEvent::ControlKey) {
1363 if (keyCode == VKEY_UP)
1364 keyCode = VKEY_PRIOR;
1365 else if (keyCode == VKEY_DOWN)
1366 keyCode = VKEY_NEXT;
1369 if (!mapKeyCodeForScroll(keyCode, &scrollDirection, &scrollGranularity))
1371 return bubblingScroll(scrollDirection, scrollGranularity);
1374 bool WebViewImpl::mapKeyCodeForScroll(int keyCode,
1375 WebCore::ScrollDirection* scrollDirection,
1376 WebCore::ScrollGranularity* scrollGranularity)
1380 *scrollDirection = ScrollLeft;
1381 *scrollGranularity = ScrollByLine;
1384 *scrollDirection = ScrollRight;
1385 *scrollGranularity = ScrollByLine;
1388 *scrollDirection = ScrollUp;
1389 *scrollGranularity = ScrollByLine;
1392 *scrollDirection = ScrollDown;
1393 *scrollGranularity = ScrollByLine;
1396 *scrollDirection = ScrollUp;
1397 *scrollGranularity = ScrollByDocument;
1400 *scrollDirection = ScrollDown;
1401 *scrollGranularity = ScrollByDocument;
1403 case VKEY_PRIOR: // page up
1404 *scrollDirection = ScrollUp;
1405 *scrollGranularity = ScrollByPage;
1407 case VKEY_NEXT: // page down
1408 *scrollDirection = ScrollDown;
1409 *scrollGranularity = ScrollByPage;
1418 void WebViewImpl::hideSelectPopup()
1421 m_selectPopup->hidePopup();
1424 bool WebViewImpl::bubblingScroll(ScrollDirection scrollDirection, ScrollGranularity scrollGranularity)
1426 LocalFrame* frame = focusedWebCoreFrame();
1430 return frame->eventHandler().bubblingScroll(scrollDirection, scrollGranularity);
1433 void WebViewImpl::popupOpened(PopupContainer* popupContainer)
1435 ASSERT(!m_selectPopup);
1436 m_selectPopup = popupContainer;
1437 ASSERT(mainFrameImpl()->frame()->document());
1438 Document& document = *mainFrameImpl()->frame()->document();
1439 WheelController::from(document)->didAddWheelEventHandler(document);
1442 void WebViewImpl::popupClosed(PopupContainer* popupContainer)
1444 ASSERT(m_selectPopup);
1445 m_selectPopup = nullptr;
1446 ASSERT(mainFrameImpl()->frame()->document());
1447 Document& document = *mainFrameImpl()->frame()->document();
1448 WheelController::from(document)->didRemoveWheelEventHandler(document);
1451 PagePopup* WebViewImpl::openPagePopup(PagePopupClient* client, const IntRect& originBoundsInRootView)
1454 if (hasOpenedPopup())
1456 ASSERT(!m_pagePopup);
1458 WebWidget* popupWidget = m_client->createPopupMenu(WebPopupTypePage);
1459 ASSERT(popupWidget);
1460 m_pagePopup = toWebPagePopupImpl(popupWidget);
1461 if (!m_pagePopup->initialize(this, client, originBoundsInRootView)) {
1462 m_pagePopup->closePopup();
1463 m_pagePopup = nullptr;
1465 return m_pagePopup.get();
1468 void WebViewImpl::closePagePopup(PagePopup* popup)
1471 WebPagePopupImpl* popupImpl = toWebPagePopupImpl(popup);
1472 ASSERT(m_pagePopup.get() == popupImpl);
1473 if (m_pagePopup.get() != popupImpl)
1475 m_pagePopup->closePopup();
1476 m_pagePopup = nullptr;
1479 LocalFrame* WebViewImpl::focusedWebCoreFrame() const
1481 return m_page ? m_page->focusController().focusedOrMainFrame() : 0;
1484 WebViewImpl* WebViewImpl::fromPage(Page* page)
1488 return static_cast<WebViewImpl*>(page->chrome().client().webView());
1491 // WebWidget ------------------------------------------------------------------
1493 void WebViewImpl::close()
1496 // Initiate shutdown for the entire frameset. This will cause a lot of
1497 // notifications to be sent.
1498 if (m_page->mainFrame())
1499 m_page->mainFrame()->loader().frameDetached();
1504 // Should happen after m_page.clear().
1505 if (m_devToolsAgent)
1506 m_devToolsAgent.clear();
1508 // Reset the delegate to prevent notifications being sent as we're being
1512 deref(); // Balances ref() acquired in WebView::create
1515 void WebViewImpl::willStartLiveResize()
1517 if (mainFrameImpl() && mainFrameImpl()->frameView())
1518 mainFrameImpl()->frameView()->willStartLiveResize();
1520 LocalFrame* frame = mainFrameImpl()->frame();
1521 WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1522 if (pluginContainer)
1523 pluginContainer->willStartLiveResize();
1526 WebSize WebViewImpl::size()
1531 void WebViewImpl::resize(const WebSize& newSize)
1533 if (m_shouldAutoResize || m_size == newSize)
1536 FrameView* view = mainFrameImpl()->frameView();
1540 WebSize oldSize = m_size;
1541 float oldPageScaleFactor = pageScaleFactor();
1542 int oldContentsWidth = contentsSize().width();
1546 bool shouldAnchorAndRescaleViewport = settings()->mainFrameResizesAreOrientationChanges()
1547 && oldSize.width && oldContentsWidth && newSize.width != oldSize.width;
1549 ViewportAnchor viewportAnchor(&mainFrameImpl()->frame()->eventHandler());
1550 if (shouldAnchorAndRescaleViewport) {
1551 viewportAnchor.setAnchor(view->visibleContentRect(),
1552 FloatSize(viewportAnchorXCoord, viewportAnchorYCoord));
1555 updatePageDefinedViewportConstraints(mainFrameImpl()->frame()->document()->viewportDescription());
1556 updateMainFrameLayoutSize();
1558 WebDevToolsAgentPrivate* agentPrivate = devToolsAgentPrivate();
1560 agentPrivate->webViewResized(newSize);
1561 WebFrameImpl* webFrame = mainFrameImpl();
1562 if (webFrame->frameView()) {
1563 webFrame->frameView()->resize(m_size);
1564 if (page()->settings().pinchVirtualViewportEnabled())
1565 page()->frameHost().pinchViewport().setSize(m_size);
1568 if (settings()->viewportEnabled() && !m_fixedLayoutSizeLock) {
1569 // Relayout immediately to recalculate the minimum scale limit.
1570 if (view->needsLayout())
1573 if (shouldAnchorAndRescaleViewport) {
1574 float viewportWidthRatio = static_cast<float>(newSize.width) / oldSize.width;
1575 float contentsWidthRatio = static_cast<float>(contentsSize().width()) / oldContentsWidth;
1576 float scaleMultiplier = viewportWidthRatio / contentsWidthRatio;
1578 IntSize viewportSize = view->visibleContentRect().size();
1579 if (scaleMultiplier != 1) {
1580 float newPageScaleFactor = oldPageScaleFactor * scaleMultiplier;
1581 viewportSize.scale(pageScaleFactor() / newPageScaleFactor);
1582 IntPoint scrollOffsetAtNewScale = viewportAnchor.computeOrigin(viewportSize);
1583 setPageScaleFactor(newPageScaleFactor, scrollOffsetAtNewScale);
1585 IntPoint scrollOffsetAtNewScale = clampOffsetAtScale(viewportAnchor.computeOrigin(viewportSize), pageScaleFactor());
1586 updateMainFrameScrollPosition(scrollOffsetAtNewScale, false);
1591 sendResizeEventAndRepaint();
1594 void WebViewImpl::willEndLiveResize()
1596 if (mainFrameImpl() && mainFrameImpl()->frameView())
1597 mainFrameImpl()->frameView()->willEndLiveResize();
1599 LocalFrame* frame = mainFrameImpl()->frame();
1600 WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
1601 if (pluginContainer)
1602 pluginContainer->willEndLiveResize();
1605 void WebViewImpl::willEnterFullScreen()
1607 m_fullscreenController->willEnterFullScreen();
1610 void WebViewImpl::didEnterFullScreen()
1612 m_fullscreenController->didEnterFullScreen();
1615 void WebViewImpl::willExitFullScreen()
1617 m_fullscreenController->willExitFullScreen();
1620 void WebViewImpl::didExitFullScreen()
1622 m_fullscreenController->didExitFullScreen();
1625 void WebViewImpl::animate(double monotonicFrameBeginTime)
1627 TRACE_EVENT0("webkit", "WebViewImpl::animate");
1629 if (!monotonicFrameBeginTime)
1630 monotonicFrameBeginTime = monotonicallyIncreasingTime();
1632 // Create synthetic wheel events as necessary for fling.
1633 if (m_gestureAnimation) {
1634 if (m_gestureAnimation->animate(monotonicFrameBeginTime))
1635 scheduleAnimation();
1637 endActiveFlingAnimation();
1639 PlatformGestureEvent endScrollEvent(PlatformEvent::GestureScrollEnd,
1640 m_positionOnFlingStart, m_globalPositionOnFlingStart,
1641 IntSize(), 0, false, false, false, false,
1644 mainFrameImpl()->frame()->eventHandler().handleGestureScrollEnd(endScrollEvent);
1651 PageWidgetDelegate::animate(m_page.get(), monotonicFrameBeginTime);
1653 if (m_continuousPaintingEnabled) {
1654 ContinuousPainter::setNeedsDisplayRecursive(m_rootGraphicsLayer, m_pageOverlays.get());
1655 m_client->scheduleAnimation();
1659 void WebViewImpl::layout()
1661 TRACE_EVENT0("webkit", "WebViewImpl::layout");
1662 PageWidgetDelegate::layout(m_page.get());
1663 updateLayerTreeBackgroundColor();
1665 for (size_t i = 0; i < m_linkHighlights.size(); ++i)
1666 m_linkHighlights[i]->updateGeometry();
1669 void WebViewImpl::enterForceCompositingMode(bool enter)
1671 if (page()->settings().forceCompositingMode() == enter)
1674 TRACE_EVENT1("webkit", "WebViewImpl::enterForceCompositingMode", "enter", enter);
1675 settingsImpl()->setForceCompositingMode(enter);
1679 LocalFrame* mainFrame = m_page->mainFrame();
1682 mainFrame->view()->updateCompositingLayersAfterStyleChange();
1686 void WebViewImpl::doPixelReadbackToCanvas(WebCanvas* canvas, const IntRect& rect)
1688 ASSERT(m_layerTreeView);
1691 target.setConfig(SkBitmap::kARGB_8888_Config, rect.width(), rect.height(), rect.width() * 4);
1692 target.allocPixels();
1693 m_layerTreeView->compositeAndReadback(target.getPixels(), rect);
1694 #if (!SK_R32_SHIFT && SK_B32_SHIFT == 16)
1695 // The compositor readback always gives back pixels in BGRA order, but for
1696 // example Android's Skia uses RGBA ordering so the red and blue channels
1697 // need to be swapped.
1698 uint8_t* pixels = reinterpret_cast<uint8_t*>(target.getPixels());
1699 for (size_t i = 0; i < target.getSize(); i += 4)
1700 std::swap(pixels[i], pixels[i + 2]);
1702 canvas->writePixels(target, rect.x(), rect.y());
1705 void WebViewImpl::paint(WebCanvas* canvas, const WebRect& rect, PaintOptions option)
1708 // ReadbackFromCompositorIfAvailable is the only option available on non-Android.
1709 // Ideally, Android would always use ReadbackFromCompositorIfAvailable as well.
1710 ASSERT(option == ReadbackFromCompositorIfAvailable);
1713 if (option == ReadbackFromCompositorIfAvailable && isAcceleratedCompositingActive()) {
1714 // If a canvas was passed in, we use it to grab a copy of the
1715 // freshly-rendered pixels.
1717 // Clip rect to the confines of the rootLayerTexture.
1718 IntRect resizeRect(rect);
1719 resizeRect.intersect(IntRect(IntPoint(0, 0), m_layerTreeView->deviceViewportSize()));
1720 doPixelReadbackToCanvas(canvas, resizeRect);
1723 FrameView* view = page()->mainFrame()->view();
1724 PaintBehavior oldPaintBehavior = view->paintBehavior();
1725 if (isAcceleratedCompositingActive()) {
1726 ASSERT(option == ForceSoftwareRenderingAndIgnoreGPUResidentContent);
1727 view->setPaintBehavior(oldPaintBehavior | PaintBehaviorFlattenCompositingLayers);
1730 double paintStart = currentTime();
1731 PageWidgetDelegate::paint(m_page.get(), pageOverlays(), canvas, rect, isTransparent() ? PageWidgetDelegate::Translucent : PageWidgetDelegate::Opaque);
1732 double paintEnd = currentTime();
1733 double pixelsPerSec = (rect.width * rect.height) / (paintEnd - paintStart);
1734 blink::Platform::current()->histogramCustomCounts("Renderer4.SoftwarePaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30);
1735 blink::Platform::current()->histogramCustomCounts("Renderer4.SoftwarePaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30);
1737 if (isAcceleratedCompositingActive()) {
1738 ASSERT(option == ForceSoftwareRenderingAndIgnoreGPUResidentContent);
1739 view->setPaintBehavior(oldPaintBehavior);
1744 bool WebViewImpl::isTrackingRepaints() const
1748 FrameView* view = page()->mainFrame()->view();
1749 return view->isTrackingRepaints();
1752 void WebViewImpl::themeChanged()
1756 FrameView* view = page()->mainFrame()->view();
1758 WebRect damagedRect(0, 0, m_size.width, m_size.height);
1759 view->invalidateRect(damagedRect);
1762 void WebViewImpl::enterFullScreenForElement(WebCore::Element* element)
1764 m_fullscreenController->enterFullScreenForElement(element);
1767 void WebViewImpl::exitFullScreenForElement(WebCore::Element* element)
1769 m_fullscreenController->exitFullScreenForElement(element);
1772 bool WebViewImpl::hasHorizontalScrollbar()
1774 return mainFrameImpl()->frameView()->horizontalScrollbar();
1777 bool WebViewImpl::hasVerticalScrollbar()
1779 return mainFrameImpl()->frameView()->verticalScrollbar();
1782 const WebInputEvent* WebViewImpl::m_currentInputEvent = 0;
1784 bool WebViewImpl::handleInputEvent(const WebInputEvent& inputEvent)
1786 TRACE_EVENT0("input", "WebViewImpl::handleInputEvent");
1787 // If we've started a drag and drop operation, ignore input events until
1789 if (m_doingDragAndDrop)
1792 if (m_devToolsAgent && m_devToolsAgent->handleInputEvent(m_page.get(), inputEvent))
1795 // Report the event to be NOT processed by WebKit, so that the browser can handle it appropriately.
1796 if (m_ignoreInputEvents)
1799 TemporaryChange<const WebInputEvent*> currentEventChange(m_currentInputEvent, &inputEvent);
1801 if (isPointerLocked() && WebInputEvent::isMouseEventType(inputEvent.type)) {
1802 pointerLockMouseEvent(inputEvent);
1806 if (m_mouseCaptureNode && WebInputEvent::isMouseEventType(inputEvent.type)) {
1807 TRACE_EVENT1("input", "captured mouse event", "type", inputEvent.type);
1808 // Save m_mouseCaptureNode since mouseCaptureLost() will clear it.
1809 RefPtr<Node> node = m_mouseCaptureNode;
1811 // Not all platforms call mouseCaptureLost() directly.
1812 if (inputEvent.type == WebInputEvent::MouseUp)
1815 AtomicString eventType;
1816 switch (inputEvent.type) {
1817 case WebInputEvent::MouseMove:
1818 eventType = EventTypeNames::mousemove;
1820 case WebInputEvent::MouseLeave:
1821 eventType = EventTypeNames::mouseout;
1823 case WebInputEvent::MouseDown:
1824 eventType = EventTypeNames::mousedown;
1826 case WebInputEvent::MouseUp:
1827 eventType = EventTypeNames::mouseup;
1830 ASSERT_NOT_REACHED();
1833 node->dispatchMouseEvent(
1834 PlatformMouseEventBuilder(mainFrameImpl()->frameView(), *static_cast<const WebMouseEvent*>(&inputEvent)),
1835 eventType, static_cast<const WebMouseEvent*>(&inputEvent)->clickCount);
1839 return PageWidgetDelegate::handleInputEvent(m_page.get(), *this, inputEvent);
1842 void WebViewImpl::setCursorVisibilityState(bool isVisible)
1845 m_page->setIsCursorVisible(isVisible);
1848 void WebViewImpl::mouseCaptureLost()
1850 TRACE_EVENT_ASYNC_END0("input", "capturing mouse", this);
1851 m_mouseCaptureNode = nullptr;
1854 void WebViewImpl::setFocus(bool enable)
1856 m_page->focusController().setFocused(enable);
1858 m_page->focusController().setActive(true);
1859 RefPtr<LocalFrame> focusedFrame = m_page->focusController().focusedFrame();
1861 Element* element = focusedFrame->document()->focusedElement();
1862 if (element && focusedFrame->selection().selection().isNone()) {
1863 // If the selection was cleared while the WebView was not
1864 // focused, then the focus element shows with a focus ring but
1865 // no caret and does respond to keyboard inputs.
1866 if (element->isTextFormControl()) {
1867 element->updateFocusAppearance(true);
1868 } else if (element->isContentEditable()) {
1869 // updateFocusAppearance() selects all the text of
1870 // contentseditable DIVs. So we set the selection explicitly
1871 // instead. Note that this has the side effect of moving the
1872 // caret back to the beginning of the text.
1873 Position position(element, 0, Position::PositionIsOffsetInAnchor);
1874 focusedFrame->selection().setSelection(VisibleSelection(position, SEL_DEFAULT_AFFINITY));
1878 m_imeAcceptEvents = true;
1882 // Clear focus on the currently focused frame if any.
1886 LocalFrame* frame = m_page->mainFrame();
1890 RefPtr<LocalFrame> focusedFrame = m_page->focusController().focusedFrame();
1892 // Finish an ongoing composition to delete the composition node.
1893 if (focusedFrame->inputMethodController().hasComposition()) {
1894 if (m_autofillClient)
1895 m_autofillClient->setIgnoreTextChanges(true);
1897 focusedFrame->inputMethodController().confirmComposition();
1899 if (m_autofillClient)
1900 m_autofillClient->setIgnoreTextChanges(false);
1902 m_imeAcceptEvents = false;
1907 bool WebViewImpl::setComposition(
1908 const WebString& text,
1909 const WebVector<WebCompositionUnderline>& underlines,
1913 LocalFrame* focused = focusedWebCoreFrame();
1914 if (!focused || !m_imeAcceptEvents)
1917 if (WebPlugin* plugin = focusedPluginIfInputMethodSupported(focused))
1918 return plugin->setComposition(text, underlines, selectionStart, selectionEnd);
1920 // The input focus has been moved to another WebWidget object.
1921 // We should use this |editor| object only to complete the ongoing
1923 InputMethodController& inputMethodController = focused->inputMethodController();
1924 if (!focused->editor().canEdit() && !inputMethodController.hasComposition())
1927 // We should verify the parent node of this IME composition node are
1928 // editable because JavaScript may delete a parent node of the composition
1929 // node. In this case, WebKit crashes while deleting texts from the parent
1930 // node, which doesn't exist any longer.
1931 RefPtr<Range> range = inputMethodController.compositionRange();
1933 Node* node = range->startContainer();
1934 if (!node || !node->isContentEditable())
1938 // If we're not going to fire a keypress event, then the keydown event was
1939 // canceled. In that case, cancel any existing composition.
1940 if (text.isEmpty() || m_suppressNextKeypressEvent) {
1941 // A browser process sent an IPC message which does not contain a valid
1942 // string, which means an ongoing composition has been canceled.
1943 // If the ongoing composition has been canceled, replace the ongoing
1944 // composition string with an empty string and complete it.
1946 Vector<CompositionUnderline> emptyUnderlines;
1947 inputMethodController.setComposition(emptyString, emptyUnderlines, 0, 0);
1948 return text.isEmpty();
1951 // When the range of composition underlines overlap with the range between
1952 // selectionStart and selectionEnd, WebKit somehow won't paint the selection
1953 // at all (see InlineTextBox::paint() function in InlineTextBox.cpp).
1954 // But the selection range actually takes effect.
1955 inputMethodController.setComposition(String(text),
1956 CompositionUnderlineVectorBuilder(underlines),
1957 selectionStart, selectionEnd);
1959 return inputMethodController.hasComposition();
1962 bool WebViewImpl::confirmComposition()
1964 return confirmComposition(DoNotKeepSelection);
1967 bool WebViewImpl::confirmComposition(ConfirmCompositionBehavior selectionBehavior)
1969 return confirmComposition(WebString(), selectionBehavior);
1972 bool WebViewImpl::confirmComposition(const WebString& text)
1974 return confirmComposition(text, DoNotKeepSelection);
1977 bool WebViewImpl::confirmComposition(const WebString& text, ConfirmCompositionBehavior selectionBehavior)
1979 LocalFrame* focused = focusedWebCoreFrame();
1980 if (!focused || !m_imeAcceptEvents)
1983 if (WebPlugin* plugin = focusedPluginIfInputMethodSupported(focused))
1984 return plugin->confirmComposition(text, selectionBehavior);
1986 return focused->inputMethodController().confirmCompositionOrInsertText(text, selectionBehavior == KeepSelection ? InputMethodController::KeepSelection : InputMethodController::DoNotKeepSelection);
1989 bool WebViewImpl::compositionRange(size_t* location, size_t* length)
1991 LocalFrame* focused = focusedWebCoreFrame();
1992 if (!focused || !m_imeAcceptEvents)
1995 RefPtr<Range> range = focused->inputMethodController().compositionRange();
1999 Element* editable = focused->selection().rootEditableElementOrDocumentElement();
2001 PlainTextRange plainTextRange(PlainTextRange::create(*editable, *range.get()));
2002 if (plainTextRange.isNull())
2004 *location = plainTextRange.start();
2005 *length = plainTextRange.length();
2009 WebTextInputInfo WebViewImpl::textInputInfo()
2011 WebTextInputInfo info;
2013 LocalFrame* focused = focusedWebCoreFrame();
2017 FrameSelection& selection = focused->selection();
2018 Node* node = selection.selection().rootEditableElement();
2022 info.inputMode = inputModeOfFocusedElement();
2024 info.type = textInputType();
2025 if (info.type == WebTextInputTypeNone)
2028 if (!focused->editor().canEdit())
2031 info.value = plainText(rangeOfContents(node).get());
2033 if (info.value.isEmpty())
2036 if (RefPtr<Range> range = selection.selection().firstRange()) {
2037 PlainTextRange plainTextRange(PlainTextRange::create(*node, *range.get()));
2038 if (plainTextRange.isNotNull()) {
2039 info.selectionStart = plainTextRange.start();
2040 info.selectionEnd = plainTextRange.end();
2044 if (RefPtr<Range> range = focused->inputMethodController().compositionRange()) {
2045 PlainTextRange plainTextRange(PlainTextRange::create(*node, *range.get()));
2046 if (plainTextRange.isNotNull()) {
2047 info.compositionStart = plainTextRange.start();
2048 info.compositionEnd = plainTextRange.end();
2055 WebTextInputType WebViewImpl::textInputType()
2057 Element* element = focusedElement();
2059 return WebTextInputTypeNone;
2061 if (isHTMLInputElement(*element)) {
2062 HTMLInputElement& input = toHTMLInputElement(*element);
2064 if (input.isDisabledOrReadOnly())
2065 return WebTextInputTypeNone;
2067 if (input.isPasswordField())
2068 return WebTextInputTypePassword;
2069 if (input.isSearchField())
2070 return WebTextInputTypeSearch;
2071 if (input.isEmailField())
2072 return WebTextInputTypeEmail;
2073 if (input.isNumberField())
2074 return WebTextInputTypeNumber;
2075 if (input.isTelephoneField())
2076 return WebTextInputTypeTelephone;
2077 if (input.isURLField())
2078 return WebTextInputTypeURL;
2079 if (input.isDateField())
2080 return WebTextInputTypeDate;
2081 if (input.isDateTimeLocalField())
2082 return WebTextInputTypeDateTimeLocal;
2083 if (input.isMonthField())
2084 return WebTextInputTypeMonth;
2085 if (input.isTimeField())
2086 return WebTextInputTypeTime;
2087 if (input.isWeekField())
2088 return WebTextInputTypeWeek;
2089 if (input.isTextField())
2090 return WebTextInputTypeText;
2092 return WebTextInputTypeNone;
2095 if (isHTMLTextAreaElement(*element)) {
2096 if (toHTMLTextAreaElement(*element).isDisabledOrReadOnly())
2097 return WebTextInputTypeNone;
2098 return WebTextInputTypeTextArea;
2101 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
2102 if (element->isHTMLElement()) {
2103 if (toHTMLElement(element)->isDateTimeFieldElement())
2104 return WebTextInputTypeDateTimeField;
2108 if (element->shouldUseInputMethod())
2109 return WebTextInputTypeContentEditable;
2111 return WebTextInputTypeNone;
2114 WebString WebViewImpl::inputModeOfFocusedElement()
2116 if (!RuntimeEnabledFeatures::inputModeAttributeEnabled())
2119 Element* element = focusedElement();
2123 if (isHTMLInputElement(*element)) {
2124 const HTMLInputElement& input = toHTMLInputElement(*element);
2125 if (input.supportsInputModeAttribute())
2126 return input.fastGetAttribute(HTMLNames::inputmodeAttr).lower();
2129 if (isHTMLTextAreaElement(*element)) {
2130 const HTMLTextAreaElement& textarea = toHTMLTextAreaElement(*element);
2131 return textarea.fastGetAttribute(HTMLNames::inputmodeAttr).lower();
2137 bool WebViewImpl::selectionBounds(WebRect& anchor, WebRect& focus) const
2139 const LocalFrame* frame = focusedWebCoreFrame();
2142 FrameSelection& selection = frame->selection();
2144 if (selection.isCaret()) {
2145 anchor = focus = selection.absoluteCaretBounds();
2147 RefPtr<Range> selectedRange = selection.toNormalizedRange();
2151 RefPtr<Range> range(Range::create(selectedRange->startContainer()->document(),
2152 selectedRange->startContainer(),
2153 selectedRange->startOffset(),
2154 selectedRange->startContainer(),
2155 selectedRange->startOffset()));
2156 anchor = frame->editor().firstRectForRange(range.get());
2158 range = Range::create(selectedRange->endContainer()->document(),
2159 selectedRange->endContainer(),
2160 selectedRange->endOffset(),
2161 selectedRange->endContainer(),
2162 selectedRange->endOffset());
2163 focus = frame->editor().firstRectForRange(range.get());
2166 IntRect scaledAnchor(frame->view()->contentsToWindow(anchor));
2167 IntRect scaledFocus(frame->view()->contentsToWindow(focus));
2168 scaledAnchor.scale(pageScaleFactor());
2169 scaledFocus.scale(pageScaleFactor());
2170 anchor = scaledAnchor;
2171 focus = scaledFocus;
2173 if (!selection.selection().isBaseFirst())
2174 std::swap(anchor, focus);
2178 InputMethodContext* WebViewImpl::inputMethodContext()
2180 if (!m_imeAcceptEvents)
2183 LocalFrame* focusedFrame = focusedWebCoreFrame();
2187 Element* target = focusedFrame->document()->focusedElement();
2188 if (target && target->hasInputMethodContext())
2189 return &target->inputMethodContext();
2194 WebPlugin* WebViewImpl::focusedPluginIfInputMethodSupported(LocalFrame* frame)
2196 WebPluginContainerImpl* container = WebFrameImpl::pluginContainerFromNode(frame, WebNode(focusedElement()));
2197 if (container && container->supportsInputMethod())
2198 return container->plugin();
2202 void WebViewImpl::didShowCandidateWindow()
2204 if (InputMethodContext* context = inputMethodContext())
2205 context->dispatchCandidateWindowShowEvent();
2208 void WebViewImpl::didUpdateCandidateWindow()
2210 if (InputMethodContext* context = inputMethodContext())
2211 context->dispatchCandidateWindowUpdateEvent();
2214 void WebViewImpl::didHideCandidateWindow()
2216 if (InputMethodContext* context = inputMethodContext())
2217 context->dispatchCandidateWindowHideEvent();
2220 bool WebViewImpl::selectionTextDirection(WebTextDirection& start, WebTextDirection& end) const
2222 const LocalFrame* frame = focusedWebCoreFrame();
2225 FrameSelection& selection = frame->selection();
2226 if (!selection.toNormalizedRange())
2228 start = selection.start().primaryDirection() == RTL ? WebTextDirectionRightToLeft : WebTextDirectionLeftToRight;
2229 end = selection.end().primaryDirection() == RTL ? WebTextDirectionRightToLeft : WebTextDirectionLeftToRight;
2233 bool WebViewImpl::isSelectionAnchorFirst() const
2235 if (const LocalFrame* frame = focusedWebCoreFrame())
2236 return frame->selection().selection().isBaseFirst();
2240 WebVector<WebCompositionUnderline> WebViewImpl::compositionUnderlines() const
2242 const LocalFrame* focused = focusedWebCoreFrame();
2244 return WebVector<WebCompositionUnderline>();
2245 const Vector<CompositionUnderline>& underlines = focused->inputMethodController().customCompositionUnderlines();
2246 WebVector<WebCompositionUnderline> results(underlines.size());
2247 for (size_t index = 0; index < underlines.size(); ++index) {
2248 CompositionUnderline underline = underlines[index];
2249 results[index] = WebCompositionUnderline(underline.startOffset, underline.endOffset, static_cast<WebColor>(underline.color.rgb()), underline.thick);
2254 WebColor WebViewImpl::backgroundColor() const
2256 if (isTransparent())
2257 return Color::transparent;
2259 return m_baseBackgroundColor;
2260 if (!m_page->mainFrame())
2261 return m_baseBackgroundColor;
2262 FrameView* view = m_page->mainFrame()->view();
2263 return view->documentBackgroundColor().rgb();
2266 bool WebViewImpl::caretOrSelectionRange(size_t* location, size_t* length)
2268 const LocalFrame* focused = focusedWebCoreFrame();
2272 PlainTextRange selectionOffsets = focused->inputMethodController().getSelectionOffsets();
2273 if (selectionOffsets.isNull())
2276 *location = selectionOffsets.start();
2277 *length = selectionOffsets.length();
2281 void WebViewImpl::setTextDirection(WebTextDirection direction)
2283 // The Editor::setBaseWritingDirection() function checks if we can change
2284 // the text direction of the selected node and updates its DOM "dir"
2285 // attribute and its CSS "direction" property.
2286 // So, we just call the function as Safari does.
2287 const LocalFrame* focused = focusedWebCoreFrame();
2291 Editor& editor = focused->editor();
2292 if (!editor.canEdit())
2295 switch (direction) {
2296 case WebTextDirectionDefault:
2297 editor.setBaseWritingDirection(NaturalWritingDirection);
2300 case WebTextDirectionLeftToRight:
2301 editor.setBaseWritingDirection(LeftToRightWritingDirection);
2304 case WebTextDirectionRightToLeft:
2305 editor.setBaseWritingDirection(RightToLeftWritingDirection);
2314 bool WebViewImpl::isAcceleratedCompositingActive() const
2316 return m_isAcceleratedCompositingActive;
2319 void WebViewImpl::willCloseLayerTreeView()
2321 setIsAcceleratedCompositingActive(false);
2322 m_layerTreeView = 0;
2325 void WebViewImpl::didAcquirePointerLock()
2328 page()->pointerLockController().didAcquirePointerLock();
2331 void WebViewImpl::didNotAcquirePointerLock()
2334 page()->pointerLockController().didNotAcquirePointerLock();
2337 void WebViewImpl::didLosePointerLock()
2340 page()->pointerLockController().didLosePointerLock();
2343 void WebViewImpl::didChangeWindowResizerRect()
2345 if (mainFrameImpl()->frameView())
2346 mainFrameImpl()->frameView()->windowResizerRectChanged();
2349 // WebView --------------------------------------------------------------------
2351 WebSettingsImpl* WebViewImpl::settingsImpl()
2354 m_webSettings = adoptPtr(new WebSettingsImpl(&m_page->settings(), &m_page->inspectorController()));
2355 ASSERT(m_webSettings);
2356 return m_webSettings.get();
2359 WebSettings* WebViewImpl::settings()
2361 return settingsImpl();
2364 WebString WebViewImpl::pageEncoding() const
2369 // FIXME: Is this check needed?
2370 if (!m_page->mainFrame()->document()->loader())
2373 return m_page->mainFrame()->document()->encodingName();
2376 void WebViewImpl::setPageEncoding(const WebString& encodingName)
2381 // Only change override encoding, don't change default encoding.
2382 // Note that the new encoding must be 0 if it isn't supposed to be set.
2383 AtomicString newEncodingName;
2384 if (!encodingName.isEmpty())
2385 newEncodingName = encodingName;
2386 m_page->mainFrame()->loader().reload(NormalReload, KURL(), newEncodingName);
2389 bool WebViewImpl::dispatchBeforeUnloadEvent()
2391 // FIXME: This should really cause a recursive depth-first walk of all
2392 // frames in the tree, calling each frame's onbeforeunload. At the moment,
2393 // we're consistent with Safari 3.1, not IE/FF.
2394 LocalFrame* frame = m_page->mainFrame();
2398 return frame->loader().shouldClose();
2401 void WebViewImpl::dispatchUnloadEvent()
2403 // Run unload handlers.
2404 m_page->mainFrame()->loader().closeURL();
2407 WebFrame* WebViewImpl::mainFrame()
2409 return mainFrameImpl();
2412 WebFrame* WebViewImpl::findFrameByName(
2413 const WebString& name, WebFrame* relativeToFrame)
2415 if (!relativeToFrame)
2416 relativeToFrame = mainFrame();
2417 LocalFrame* frame = toWebFrameImpl(relativeToFrame)->frame();
2418 frame = frame->tree().find(name);
2419 return WebFrameImpl::fromFrame(frame);
2422 WebFrame* WebViewImpl::focusedFrame()
2424 return WebFrameImpl::fromFrame(focusedWebCoreFrame());
2427 void WebViewImpl::setFocusedFrame(WebFrame* frame)
2430 // Clears the focused frame if any.
2431 if (LocalFrame* focusedFrame = focusedWebCoreFrame())
2432 focusedFrame->selection().setFocused(false);
2435 LocalFrame* webcoreFrame = toWebFrameImpl(frame)->frame();
2436 webcoreFrame->page()->focusController().setFocusedFrame(webcoreFrame);
2439 void WebViewImpl::setInitialFocus(bool reverse)
2443 LocalFrame* frame = page()->focusController().focusedOrMainFrame();
2444 if (Document* document = frame->document())
2445 document->setFocusedElement(nullptr);
2446 page()->focusController().setInitialFocus(reverse ? FocusTypeBackward : FocusTypeForward);
2449 void WebViewImpl::clearFocusedElement()
2451 RefPtr<LocalFrame> frame = focusedWebCoreFrame();
2455 RefPtr<Document> document = frame->document();
2459 RefPtr<Element> oldFocusedElement = document->focusedElement();
2461 // Clear the focused node.
2462 document->setFocusedElement(nullptr);
2464 if (!oldFocusedElement)
2467 // If a text field has focus, we need to make sure the selection controller
2468 // knows to remove selection from it. Otherwise, the text field is still
2469 // processing keyboard events even though focus has been moved to the page and
2470 // keystrokes get eaten as a result.
2471 if (oldFocusedElement->isContentEditable() || oldFocusedElement->isTextFormControl())
2472 frame->selection().clear();
2475 void WebViewImpl::scrollFocusedNodeIntoView()
2477 if (Element* element = focusedElement())
2478 element->scrollIntoViewIfNeeded(true);
2481 void WebViewImpl::scrollFocusedNodeIntoRect(const WebRect& rect)
2483 LocalFrame* frame = page()->mainFrame();
2484 Element* element = focusedElement();
2485 if (!frame || !frame->view() || !element)
2488 if (!m_webSettings->autoZoomFocusedNodeToLegibleScale()) {
2489 frame->view()->scrollElementToRect(element, IntRect(rect.x, rect.y, rect.width, rect.height));
2496 computeScaleAndScrollForFocusedNode(element, scale, scroll, needAnimation);
2498 startPageScaleAnimation(scroll, false, scale, scrollAndScaleAnimationDurationInSeconds);
2501 void WebViewImpl::computeScaleAndScrollForFocusedNode(Node* focusedNode, float& newScale, IntPoint& newScroll, bool& needAnimation)
2503 focusedNode->document().updateLayoutIgnorePendingStylesheets();
2505 // 'caret' is rect encompassing the blinking cursor.
2506 IntRect textboxRect = focusedNode->document().view()->contentsToWindow(pixelSnappedIntRect(focusedNode->Node::boundingBox()));
2507 WebRect caret, unusedEnd;
2508 selectionBounds(caret, unusedEnd);
2509 IntRect unscaledCaret = caret;
2510 unscaledCaret.scale(1 / pageScaleFactor());
2511 caret = unscaledCaret;
2513 // Pick a scale which is reasonably readable. This is the scale at which
2514 // the caret height will become minReadableCaretHeight (adjusted for dpi
2515 // and font scale factor).
2516 newScale = clampPageScaleFactorToLimits(legibleScale() * minReadableCaretHeight / caret.height);
2517 const float deltaScale = newScale / pageScaleFactor();
2519 // Convert the rects to absolute space in the new scale.
2520 IntRect textboxRectInDocumentCoordinates = textboxRect;
2521 textboxRectInDocumentCoordinates.move(mainFrame()->scrollOffset());
2522 IntRect caretInDocumentCoordinates = caret;
2523 caretInDocumentCoordinates.move(mainFrame()->scrollOffset());
2525 int viewWidth = m_size.width / newScale;
2526 int viewHeight = m_size.height / newScale;
2528 if (textboxRectInDocumentCoordinates.width() <= viewWidth) {
2529 // Field is narrower than screen. Try to leave padding on left so field's
2530 // label is visible, but it's more important to ensure entire field is
2532 int idealLeftPadding = viewWidth * leftBoxRatio;
2533 int maxLeftPaddingKeepingBoxOnscreen = viewWidth - textboxRectInDocumentCoordinates.width();
2534 newScroll.setX(textboxRectInDocumentCoordinates.x() - min<int>(idealLeftPadding, maxLeftPaddingKeepingBoxOnscreen));
2536 // Field is wider than screen. Try to left-align field, unless caret would
2537 // be offscreen, in which case right-align the caret.
2538 newScroll.setX(max<int>(textboxRectInDocumentCoordinates.x(), caretInDocumentCoordinates.x() + caretInDocumentCoordinates.width() + caretPadding - viewWidth));
2540 if (textboxRectInDocumentCoordinates.height() <= viewHeight) {
2541 // Field is shorter than screen. Vertically center it.
2542 newScroll.setY(textboxRectInDocumentCoordinates.y() - (viewHeight - textboxRectInDocumentCoordinates.height()) / 2);
2544 // Field is taller than screen. Try to top align field, unless caret would
2545 // be offscreen, in which case bottom-align the caret.
2546 newScroll.setY(max<int>(textboxRectInDocumentCoordinates.y(), caretInDocumentCoordinates.y() + caretInDocumentCoordinates.height() + caretPadding - viewHeight));
2549 needAnimation = false;
2550 // If we are at less than the target zoom level, zoom in.
2551 if (deltaScale > minScaleChangeToTriggerZoom)
2552 needAnimation = true;
2553 // If the caret is offscreen, then animate.
2554 IntRect sizeRect(0, 0, viewWidth, viewHeight);
2555 if (!sizeRect.contains(caret))
2556 needAnimation = true;
2557 // If the box is partially offscreen and it's possible to bring it fully
2558 // onscreen, then animate.
2559 if (sizeRect.contains(textboxRectInDocumentCoordinates.width(), textboxRectInDocumentCoordinates.height()) && !sizeRect.contains(textboxRect))
2560 needAnimation = true;
2563 void WebViewImpl::advanceFocus(bool reverse)
2565 page()->focusController().advanceFocus(reverse ? FocusTypeBackward : FocusTypeForward);
2568 double WebViewImpl::zoomLevel()
2573 double WebViewImpl::setZoomLevel(double zoomLevel)
2575 if (zoomLevel < m_minimumZoomLevel)
2576 m_zoomLevel = m_minimumZoomLevel;
2577 else if (zoomLevel > m_maximumZoomLevel)
2578 m_zoomLevel = m_maximumZoomLevel;
2580 m_zoomLevel = zoomLevel;
2582 LocalFrame* frame = mainFrameImpl()->frame();
2583 WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
2584 if (pluginContainer)
2585 pluginContainer->plugin()->setZoomLevel(m_zoomLevel, false);
2587 float zoomFactor = m_zoomFactorOverride ? m_zoomFactorOverride : static_cast<float>(zoomLevelToZoomFactor(m_zoomLevel));
2588 frame->setPageZoomFactor(zoomFactor);
2594 void WebViewImpl::zoomLimitsChanged(double minimumZoomLevel,
2595 double maximumZoomLevel)
2597 m_minimumZoomLevel = minimumZoomLevel;
2598 m_maximumZoomLevel = maximumZoomLevel;
2599 m_client->zoomLimitsChanged(m_minimumZoomLevel, m_maximumZoomLevel);
2602 float WebViewImpl::textZoomFactor()
2604 return mainFrameImpl()->frame()->textZoomFactor();
2607 float WebViewImpl::setTextZoomFactor(float textZoomFactor)
2609 LocalFrame* frame = mainFrameImpl()->frame();
2610 if (WebFrameImpl::pluginContainerFromFrame(frame))
2613 frame->setTextZoomFactor(textZoomFactor);
2615 return textZoomFactor;
2618 void WebViewImpl::fullFramePluginZoomLevelChanged(double zoomLevel)
2620 if (zoomLevel == m_zoomLevel)
2623 m_zoomLevel = max(min(zoomLevel, m_maximumZoomLevel), m_minimumZoomLevel);
2624 m_client->zoomLevelChanged();
2627 double WebView::zoomLevelToZoomFactor(double zoomLevel)
2629 return pow(textSizeMultiplierRatio, zoomLevel);
2632 double WebView::zoomFactorToZoomLevel(double factor)
2634 // Since factor = 1.2^level, level = log(factor) / log(1.2)
2635 return log(factor) / log(textSizeMultiplierRatio);
2638 float WebViewImpl::pageScaleFactor() const
2643 return page()->pageScaleFactor();
2646 float WebViewImpl::clampPageScaleFactorToLimits(float scaleFactor) const
2648 return m_pageScaleConstraintsSet.finalConstraints().clampToConstraints(scaleFactor);
2651 IntPoint WebViewImpl::clampOffsetAtScale(const IntPoint& offset, float scale)
2653 FrameView* view = mainFrameImpl()->frameView();
2657 return view->clampOffsetAtScale(offset, scale);
2660 void WebViewImpl::setPageScaleFactor(float scaleFactor, const WebPoint& origin)
2665 IntPoint newScrollOffset = origin;
2666 scaleFactor = clampPageScaleFactorToLimits(scaleFactor);
2667 newScrollOffset = clampOffsetAtScale(newScrollOffset, scaleFactor);
2669 page()->setPageScaleFactor(scaleFactor, newScrollOffset);
2672 void WebViewImpl::setPageScaleFactorPreservingScrollOffset(float scaleFactor)
2674 if (clampPageScaleFactorToLimits(scaleFactor) == pageScaleFactor())
2677 IntPoint scrollOffset(mainFrame()->scrollOffset().width, mainFrame()->scrollOffset().height);
2678 setPageScaleFactor(scaleFactor, scrollOffset);
2681 float WebViewImpl::deviceScaleFactor() const
2686 return page()->deviceScaleFactor();
2689 void WebViewImpl::setDeviceScaleFactor(float scaleFactor)
2694 page()->setDeviceScaleFactor(scaleFactor);
2696 if (m_layerTreeView)
2697 updateLayerTreeDeviceScaleFactor();
2700 void WebViewImpl::enableAutoResizeMode(const WebSize& minSize, const WebSize& maxSize)
2702 m_shouldAutoResize = true;
2703 m_minAutoSize = minSize;
2704 m_maxAutoSize = maxSize;
2705 configureAutoResizeMode();
2708 void WebViewImpl::disableAutoResizeMode()
2710 m_shouldAutoResize = false;
2711 configureAutoResizeMode();
2714 void WebViewImpl::setUserAgentPageScaleConstraints(PageScaleConstraints newConstraints)
2716 if (newConstraints == m_pageScaleConstraintsSet.userAgentConstraints())
2719 m_pageScaleConstraintsSet.setUserAgentConstraints(newConstraints);
2721 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
2724 mainFrameImpl()->frameView()->setNeedsLayout();
2727 void WebViewImpl::setInitialPageScaleOverride(float initialPageScaleFactorOverride)
2729 PageScaleConstraints constraints = m_pageScaleConstraintsSet.userAgentConstraints();
2730 constraints.initialScale = initialPageScaleFactorOverride;
2732 if (constraints == m_pageScaleConstraintsSet.userAgentConstraints())
2735 m_pageScaleConstraintsSet.setNeedsReset(true);
2736 setUserAgentPageScaleConstraints(constraints);
2739 void WebViewImpl::setPageScaleFactorLimits(float minPageScale, float maxPageScale)
2741 PageScaleConstraints constraints = m_pageScaleConstraintsSet.userAgentConstraints();
2742 constraints.minimumScale = minPageScale;
2743 constraints.maximumScale = maxPageScale;
2744 setUserAgentPageScaleConstraints(constraints);
2747 void WebViewImpl::setIgnoreViewportTagScaleLimits(bool ignore)
2749 PageScaleConstraints constraints = m_pageScaleConstraintsSet.userAgentConstraints();
2751 constraints.minimumScale = m_pageScaleConstraintsSet.defaultConstraints().minimumScale;
2752 constraints.maximumScale = m_pageScaleConstraintsSet.defaultConstraints().maximumScale;
2754 constraints.minimumScale = -1;
2755 constraints.maximumScale = -1;
2757 setUserAgentPageScaleConstraints(constraints);
2760 void WebViewImpl::refreshPageScaleFactorAfterLayout()
2762 if (!mainFrame() || !page() || !page()->mainFrame() || !page()->mainFrame()->view())
2764 FrameView* view = page()->mainFrame()->view();
2766 updatePageDefinedViewportConstraints(mainFrameImpl()->frame()->document()->viewportDescription());
2767 m_pageScaleConstraintsSet.computeFinalConstraints();
2769 if (settings()->viewportEnabled() && !m_fixedLayoutSizeLock) {
2770 int verticalScrollbarWidth = 0;
2771 if (view->verticalScrollbar() && !view->verticalScrollbar()->isOverlayScrollbar())
2772 verticalScrollbarWidth = view->verticalScrollbar()->width();
2773 m_pageScaleConstraintsSet.adjustFinalConstraintsToContentsSize(m_size, contentsSize(), verticalScrollbarWidth);
2776 float newPageScaleFactor = pageScaleFactor();
2777 if (m_pageScaleConstraintsSet.needsReset() && m_pageScaleConstraintsSet.finalConstraints().initialScale != -1) {
2778 newPageScaleFactor = m_pageScaleConstraintsSet.finalConstraints().initialScale;
2779 m_pageScaleConstraintsSet.setNeedsReset(false);
2781 setPageScaleFactorPreservingScrollOffset(newPageScaleFactor);
2783 updateLayerTreeViewport();
2785 // Relayout immediately to avoid violating the rule that needsLayout()
2786 // isn't set at the end of a layout.
2787 if (view->needsLayout())
2791 void WebViewImpl::updatePageDefinedViewportConstraints(const ViewportDescription& description)
2793 if (!settings()->viewportEnabled() || !page() || (!m_size.width && !m_size.height))
2796 ViewportDescription adjustedDescription = description;
2797 if (settingsImpl()->viewportMetaLayoutSizeQuirk() && adjustedDescription.type == ViewportDescription::ViewportMeta) {
2798 if (adjustedDescription.maxWidth.type() == ExtendToZoom)
2799 adjustedDescription.maxWidth = Length(); // auto
2800 const int legacyWidthSnappingMagicNumber = 320;
2801 if (adjustedDescription.maxWidth.isFixed() && adjustedDescription.maxWidth.value() <= legacyWidthSnappingMagicNumber)
2802 adjustedDescription.maxWidth = Length(DeviceWidth);
2803 if (adjustedDescription.maxHeight.isFixed() && adjustedDescription.maxHeight.value() <= m_size.height)
2804 adjustedDescription.maxHeight = Length(DeviceHeight);
2805 adjustedDescription.minWidth = adjustedDescription.maxWidth;
2806 adjustedDescription.minHeight = adjustedDescription.maxHeight;
2808 float oldInitialScale = m_pageScaleConstraintsSet.pageDefinedConstraints().initialScale;
2809 m_pageScaleConstraintsSet.updatePageDefinedConstraints(adjustedDescription, m_size);
2811 if (settingsImpl()->clobberUserAgentInitialScaleQuirk()
2812 && m_pageScaleConstraintsSet.userAgentConstraints().initialScale != -1
2813 && m_pageScaleConstraintsSet.userAgentConstraints().initialScale * deviceScaleFactor() <= 1) {
2814 if (description.maxWidth == Length(DeviceWidth)
2815 || (description.maxWidth.type() == ExtendToZoom && m_pageScaleConstraintsSet.pageDefinedConstraints().initialScale == 1.0f))
2816 setInitialPageScaleOverride(-1);
2818 m_pageScaleConstraintsSet.adjustForAndroidWebViewQuirks(adjustedDescription, m_size, page()->settings().layoutFallbackWidth(), deviceScaleFactor(), settingsImpl()->supportDeprecatedTargetDensityDPI(), page()->settings().wideViewportQuirkEnabled(), page()->settings().useWideViewport(), page()->settings().loadWithOverviewMode(), settingsImpl()->viewportMetaNonUserScalableQuirk());
2819 float newInitialScale = m_pageScaleConstraintsSet.pageDefinedConstraints().initialScale;
2820 if (oldInitialScale != newInitialScale && newInitialScale != -1) {
2821 m_pageScaleConstraintsSet.setNeedsReset(true);
2822 if (mainFrameImpl() && mainFrameImpl()->frameView())
2823 mainFrameImpl()->frameView()->setNeedsLayout();
2826 updateMainFrameLayoutSize();
2829 void WebViewImpl::updateMainFrameLayoutSize()
2831 if (m_fixedLayoutSizeLock || !mainFrameImpl())
2834 RefPtr<FrameView> view = mainFrameImpl()->frameView();
2838 WebSize layoutSize = m_size;
2840 if (settings()->viewportEnabled()) {
2841 layoutSize = flooredIntSize(m_pageScaleConstraintsSet.pageDefinedConstraints().layoutSize);
2843 bool textAutosizingEnabled = page()->settings().textAutosizingEnabled();
2844 if (textAutosizingEnabled && layoutSize.width != view->layoutSize().width()) {
2845 TextAutosizer* textAutosizer = page()->mainFrame()->document()->textAutosizer();
2847 textAutosizer->recalculateMultipliers();
2851 view->setLayoutSize(layoutSize);
2854 IntSize WebViewImpl::contentsSize() const
2856 RenderView* root = page()->mainFrame()->contentRenderer();
2859 return root->documentRect().size();
2862 WebSize WebViewImpl::contentsPreferredMinimumSize()
2864 Document* document = m_page->mainFrame()->document();
2865 if (!document || !document->renderView() || !document->documentElement())
2869 FontCachePurgePreventer fontCachePurgePreventer; // Required by minPreferredLogicalWidth().
2870 IntSize preferredMinimumSize(document->renderView()->minPreferredLogicalWidth(), document->documentElement()->scrollHeight());
2871 preferredMinimumSize.scale(zoomLevelToZoomFactor(zoomLevel()));
2872 return preferredMinimumSize;
2875 float WebViewImpl::minimumPageScaleFactor() const
2877 return m_pageScaleConstraintsSet.finalConstraints().minimumScale;
2880 float WebViewImpl::maximumPageScaleFactor() const
2882 return m_pageScaleConstraintsSet.finalConstraints().maximumScale;
2885 void WebViewImpl::saveScrollAndScaleState()
2887 m_savedPageScaleFactor = pageScaleFactor();
2888 m_savedScrollOffset = mainFrame()->scrollOffset();
2891 void WebViewImpl::restoreScrollAndScaleState()
2893 if (!m_savedPageScaleFactor)
2896 startPageScaleAnimation(IntPoint(m_savedScrollOffset), false, m_savedPageScaleFactor, scrollAndScaleAnimationDurationInSeconds);
2897 resetSavedScrollAndScaleState();
2900 void WebViewImpl::resetSavedScrollAndScaleState()
2902 m_savedPageScaleFactor = 0;
2903 m_savedScrollOffset = IntSize();
2906 void WebViewImpl::resetScrollAndScaleState()
2908 page()->setPageScaleFactor(1, IntPoint());
2910 // Clear out the values for the current history item. This will prevent the history item from clobbering the
2911 // value determined during page scale initialization, which may be less than 1.
2912 page()->mainFrame()->loader().clearScrollPositionAndViewState();
2913 m_pageScaleConstraintsSet.setNeedsReset(true);
2915 // Clobber saved scales and scroll offsets.
2916 if (FrameView* view = page()->mainFrame()->document()->view())
2917 view->cacheCurrentScrollPosition();
2918 resetSavedScrollAndScaleState();
2921 void WebViewImpl::setFixedLayoutSize(const WebSize& layoutSize)
2926 LocalFrame* frame = page()->mainFrame();
2930 RefPtr<FrameView> view = frame->view();
2934 m_fixedLayoutSizeLock = layoutSize.width || layoutSize.height;
2936 if (m_fixedLayoutSizeLock)
2937 view->setLayoutSize(layoutSize);
2939 updateMainFrameLayoutSize();
2942 void WebViewImpl::performMediaPlayerAction(const WebMediaPlayerAction& action,
2943 const WebPoint& location)
2945 HitTestResult result = hitTestResultForWindowPos(location);
2946 RefPtr<Node> node = result.innerNonSharedNode();
2947 if (!isHTMLVideoElement(*node) && !isHTMLAudioElement(*node))
2950 RefPtr<HTMLMediaElement> mediaElement =
2951 static_pointer_cast<HTMLMediaElement>(node);
2952 switch (action.type) {
2953 case WebMediaPlayerAction::Play:
2955 mediaElement->play();
2957 mediaElement->pause();
2959 case WebMediaPlayerAction::Mute:
2960 mediaElement->setMuted(action.enable);
2962 case WebMediaPlayerAction::Loop:
2963 mediaElement->setLoop(action.enable);
2965 case WebMediaPlayerAction::Controls:
2966 mediaElement->setControls(action.enable);
2969 ASSERT_NOT_REACHED();
2973 void WebViewImpl::performPluginAction(const WebPluginAction& action,
2974 const WebPoint& location)
2976 HitTestResult result = hitTestResultForWindowPos(location);
2977 RefPtr<Node> node = result.innerNonSharedNode();
2978 if (!isHTMLObjectElement(*node) && !isHTMLEmbedElement(*node))
2981 RenderObject* object = node->renderer();
2982 if (object && object->isWidget()) {
2983 Widget* widget = toRenderWidget(object)->widget();
2984 if (widget && widget->isPluginContainer()) {
2985 WebPluginContainerImpl* plugin = toWebPluginContainerImpl(widget);
2986 switch (action.type) {
2987 case WebPluginAction::Rotate90Clockwise:
2988 plugin->plugin()->rotateView(WebPlugin::RotationType90Clockwise);
2990 case WebPluginAction::Rotate90Counterclockwise:
2991 plugin->plugin()->rotateView(WebPlugin::RotationType90Counterclockwise);
2994 ASSERT_NOT_REACHED();
3000 WebHitTestResult WebViewImpl::hitTestResultAt(const WebPoint& point)
3002 IntPoint scaledPoint = point;
3003 scaledPoint.scale(1 / pageScaleFactor(), 1 / pageScaleFactor());
3004 return hitTestResultForWindowPos(scaledPoint);
3007 void WebViewImpl::copyImageAt(const WebPoint& point)
3012 HitTestResult result = hitTestResultForWindowPos(point);
3014 if (result.absoluteImageURL().isEmpty()) {
3015 // There isn't actually an image at these coordinates. Might be because
3016 // the window scrolled while the context menu was open or because the page
3017 // changed itself between when we thought there was an image here and when
3018 // we actually tried to retreive the image.
3020 // FIXME: implement a cache of the most recent HitTestResult to avoid having
3021 // to do two hit tests.
3025 m_page->mainFrame()->editor().copyImage(result);
3028 void WebViewImpl::dragSourceEndedAt(
3029 const WebPoint& clientPoint,
3030 const WebPoint& screenPoint,
3031 WebDragOperation operation)
3033 PlatformMouseEvent pme(clientPoint,
3035 LeftButton, PlatformEvent::MouseMoved, 0, false, false, false,
3037 m_page->mainFrame()->eventHandler().dragSourceEndedAt(pme,
3038 static_cast<DragOperation>(operation));
3041 void WebViewImpl::dragSourceMovedTo(
3042 const WebPoint& clientPoint,
3043 const WebPoint& screenPoint,
3044 WebDragOperation operation)
3048 void WebViewImpl::dragSourceSystemDragEnded()
3050 // It's possible for us to get this callback while not doing a drag if
3051 // it's from a previous page that got unloaded.
3052 if (m_doingDragAndDrop) {
3053 m_page->dragController().dragEnded();
3054 m_doingDragAndDrop = false;
3058 WebDragOperation WebViewImpl::dragTargetDragEnter(
3059 const WebDragData& webDragData,
3060 const WebPoint& clientPoint,
3061 const WebPoint& screenPoint,
3062 WebDragOperationsMask operationsAllowed,
3065 ASSERT(!m_currentDragData);
3067 m_currentDragData = webDragData.getValue();
3068 m_operationsAllowed = operationsAllowed;
3070 return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragEnter, keyModifiers);
3073 WebDragOperation WebViewImpl::dragTargetDragOver(
3074 const WebPoint& clientPoint,
3075 const WebPoint& screenPoint,
3076 WebDragOperationsMask operationsAllowed,
3079 m_operationsAllowed = operationsAllowed;
3081 return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragOver, keyModifiers);
3084 void WebViewImpl::dragTargetDragLeave()
3086 ASSERT(m_currentDragData);
3089 m_currentDragData.get(),
3092 static_cast<DragOperation>(m_operationsAllowed));
3094 m_page->dragController().dragExited(&dragData);
3096 // FIXME: why is the drag scroll timer not stopped here?
3098 m_dragOperation = WebDragOperationNone;
3099 m_currentDragData = nullptr;
3102 void WebViewImpl::dragTargetDrop(const WebPoint& clientPoint,
3103 const WebPoint& screenPoint,
3106 ASSERT(m_currentDragData);
3108 // If this webview transitions from the "drop accepting" state to the "not
3109 // accepting" state, then our IPC message reply indicating that may be in-
3110 // flight, or else delayed by javascript processing in this webview. If a
3111 // drop happens before our IPC reply has reached the browser process, then
3112 // the browser forwards the drop to this webview. So only allow a drop to
3113 // proceed if our webview m_dragOperation state is not DragOperationNone.
3115 if (m_dragOperation == WebDragOperationNone) { // IPC RACE CONDITION: do not allow this drop.
3116 dragTargetDragLeave();
3120 m_currentDragData->setModifierKeyState(webInputEventKeyStateToPlatformEventKeyState(keyModifiers));
3122 m_currentDragData.get(),
3125 static_cast<DragOperation>(m_operationsAllowed));
3127 UserGestureIndicator gesture(DefinitelyProcessingNewUserGesture);
3128 m_page->dragController().performDrag(&dragData);
3130 m_dragOperation = WebDragOperationNone;
3131 m_currentDragData = nullptr;
3134 void WebViewImpl::spellingMarkers(WebVector<uint32_t>* markers)
3136 Vector<uint32_t> result;
3137 for (LocalFrame* frame = m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
3138 const Vector<DocumentMarker*>& documentMarkers = frame->document()->markers().markers();
3139 for (size_t i = 0; i < documentMarkers.size(); ++i)
3140 result.append(documentMarkers[i]->hash());
3142 markers->assign(result);
3145 WebDragOperation WebViewImpl::dragTargetDragEnterOrOver(const WebPoint& clientPoint, const WebPoint& screenPoint, DragAction dragAction, int keyModifiers)
3147 ASSERT(m_currentDragData);
3149 m_currentDragData->setModifierKeyState(webInputEventKeyStateToPlatformEventKeyState(keyModifiers));
3151 m_currentDragData.get(),
3154 static_cast<DragOperation>(m_operationsAllowed));
3156 DragSession dragSession;
3157 if (dragAction == DragEnter)
3158 dragSession = m_page->dragController().dragEntered(&dragData);
3160 dragSession = m_page->dragController().dragUpdated(&dragData);
3162 DragOperation dropEffect = dragSession.operation;
3164 // Mask the drop effect operation against the drag source's allowed operations.
3165 if (!(dropEffect & dragData.draggingSourceOperationMask()))
3166 dropEffect = DragOperationNone;
3168 m_dragOperation = static_cast<WebDragOperation>(dropEffect);
3170 return m_dragOperation;
3173 void WebViewImpl::sendResizeEventAndRepaint()
3175 // FIXME: This is wrong. The FrameView is responsible sending a resizeEvent
3176 // as part of layout. Layout is also responsible for sending invalidations
3177 // to the embedder. This method and all callers may be wrong. -- eseidel.
3178 if (mainFrameImpl()->frameView()) {
3179 // Enqueues the resize event.
3180 mainFrameImpl()->frame()->document()->enqueueResizeEvent();
3184 if (isAcceleratedCompositingActive()) {
3185 updateLayerTreeViewport();
3187 WebRect damagedRect(0, 0, m_size.width, m_size.height);
3188 m_client->didInvalidateRect(damagedRect);
3192 m_pageOverlays->update();
3195 void WebViewImpl::configureAutoResizeMode()
3197 if (!mainFrameImpl() || !mainFrameImpl()->frame() || !mainFrameImpl()->frame()->view())
3200 mainFrameImpl()->frame()->view()->enableAutoSizeMode(m_shouldAutoResize, m_minAutoSize, m_maxAutoSize);
3203 unsigned long WebViewImpl::createUniqueIdentifierForRequest()
3205 return createUniqueIdentifier();
3208 void WebViewImpl::inspectElementAt(const WebPoint& point)
3213 if (point.x == -1 || point.y == -1) {
3214 m_page->inspectorController().inspect(0);
3216 HitTestRequest::HitTestRequestType hitType = HitTestRequest::Move | HitTestRequest::ReadOnly | HitTestRequest::AllowChildFrameContent | HitTestRequest::IgnorePointerEventsNone;
3217 HitTestRequest request(hitType);
3219 FrameView* frameView = m_page->mainFrame()->view();
3220 IntPoint transformedPoint(point);
3221 transformedPoint = transformedPoint - frameView->inputEventsOffsetForEmulation();
3222 transformedPoint.scale(1 / frameView->inputEventsScaleFactor(), 1 / frameView->inputEventsScaleFactor());
3223 HitTestResult result(m_page->mainFrame()->view()->windowToContents(transformedPoint));
3224 m_page->mainFrame()->contentRenderer()->hitTest(request, result);
3225 Node* node = result.innerNode();
3226 if (!node && m_page->mainFrame()->document())
3227 node = m_page->mainFrame()->document()->documentElement();
3228 m_page->inspectorController().inspect(node);
3232 WebString WebViewImpl::inspectorSettings() const
3234 return m_inspectorSettings;
3237 void WebViewImpl::setInspectorSettings(const WebString& settings)
3239 m_inspectorSettings = settings;
3242 bool WebViewImpl::inspectorSetting(const WebString& key, WebString* value) const
3244 if (!m_inspectorSettingsMap->contains(key))
3246 *value = m_inspectorSettingsMap->get(key);
3250 void WebViewImpl::setInspectorSetting(const WebString& key,
3251 const WebString& value)
3253 m_inspectorSettingsMap->set(key, value);
3254 client()->didUpdateInspectorSetting(key, value);
3257 void WebViewImpl::setCompositorDeviceScaleFactorOverride(float deviceScaleFactor)
3259 m_compositorDeviceScaleFactorOverride = deviceScaleFactor;
3260 if (page() && m_layerTreeView)
3261 updateLayerTreeDeviceScaleFactor();
3264 void WebViewImpl::setRootLayerTransform(const WebSize& rootLayerOffset, float rootLayerScale)
3266 m_rootLayerScale = rootLayerScale;
3267 m_rootLayerOffset = rootLayerOffset;
3268 if (mainFrameImpl())
3269 mainFrameImpl()->setInputEventsTransformForEmulation(m_rootLayerOffset, m_rootLayerScale);
3270 updateRootLayerTransform();
3273 WebDevToolsAgent* WebViewImpl::devToolsAgent()
3275 return m_devToolsAgent.get();
3278 WebAXObject WebViewImpl::accessibilityObject()
3280 if (!mainFrameImpl())
3281 return WebAXObject();
3283 Document* document = mainFrameImpl()->frame()->document();
3285 document->axObjectCache()->getOrCreate(document->renderer()));
3288 void WebViewImpl::performCustomContextMenuAction(unsigned action)
3292 ContextMenu* menu = m_page->contextMenuController().contextMenu();
3295 const ContextMenuItem* item = menu->itemWithAction(static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + action));
3297 m_page->contextMenuController().contextMenuItemSelected(item);
3298 m_page->contextMenuController().clearContextMenu();
3301 void WebViewImpl::showContextMenu()
3306 page()->contextMenuController().clearContextMenu();
3307 m_contextMenuAllowed = true;
3308 if (LocalFrame* focusedFrame = page()->focusController().focusedOrMainFrame())
3309 focusedFrame->eventHandler().sendContextMenuEventForKey();
3310 m_contextMenuAllowed = false;
3313 WebString WebViewImpl::getSmartClipData(WebRect rect)
3315 LocalFrame* frame = focusedWebCoreFrame();
3318 return WebCore::SmartClip(frame).dataForRect(rect).toString();
3321 void WebViewImpl::hidePopups()
3325 closePagePopup(m_pagePopup.get());
3328 void WebViewImpl::setIsTransparent(bool isTransparent)
3330 // Set any existing frames to be transparent.
3331 LocalFrame* frame = m_page->mainFrame();
3333 frame->view()->setTransparent(isTransparent);
3334 frame = frame->tree().traverseNext();
3337 // Future frames check this to know whether to be transparent.
3338 m_isTransparent = isTransparent;
3341 bool WebViewImpl::isTransparent() const
3343 return m_isTransparent;
3346 void WebViewImpl::setBaseBackgroundColor(WebColor color)
3350 if (m_baseBackgroundColor == color)
3353 m_baseBackgroundColor = color;
3355 if (m_page->mainFrame())
3356 m_page->mainFrame()->view()->setBaseBackgroundColor(color);
3358 updateLayerTreeBackgroundColor();
3361 void WebViewImpl::setIsActive(bool active)
3364 page()->focusController().setActive(active);
3367 bool WebViewImpl::isActive() const
3369 return page() ? page()->focusController().isActive() : false;
3372 void WebViewImpl::setDomainRelaxationForbidden(bool forbidden, const WebString& scheme)
3374 SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme));
3377 void WebViewImpl::setWindowFeatures(const WebWindowFeatures& features)
3379 m_page->chrome().setWindowFeatures(features);
3382 void WebViewImpl::setSelectionColors(unsigned activeBackgroundColor,
3383 unsigned activeForegroundColor,
3384 unsigned inactiveBackgroundColor,
3385 unsigned inactiveForegroundColor) {
3386 #if USE(DEFAULT_RENDER_THEME)
3387 RenderThemeChromiumDefault::setSelectionColors(activeBackgroundColor, activeForegroundColor, inactiveBackgroundColor, inactiveForegroundColor);
3388 RenderTheme::theme().platformColorsDidChange();
3392 void WebView::injectStyleSheet(const WebString& sourceCode, const WebVector<WebString>& patternsIn, WebView::StyleInjectionTarget injectIn)
3394 Vector<String> patterns;
3395 for (size_t i = 0; i < patternsIn.size(); ++i)
3396 patterns.append(patternsIn[i]);
3398 InjectedStyleSheets::instance().add(sourceCode, patterns, static_cast<WebCore::StyleInjectionTarget>(injectIn));
3401 void WebView::removeInjectedStyleSheets()
3403 InjectedStyleSheets::instance().removeAll();
3406 void WebViewImpl::didCommitLoad(bool isNewNavigation, bool isNavigationWithinPage)
3408 if (isNewNavigation && !isNavigationWithinPage)
3409 m_pageScaleConstraintsSet.setNeedsReset(true);
3411 // Make sure link highlight from previous page is cleared.
3412 m_linkHighlights.clear();
3413 endActiveFlingAnimation();
3414 resetSavedScrollAndScaleState();
3417 void WebViewImpl::willInsertBody(WebFrameImpl* webframe)
3419 if (webframe != mainFrameImpl())
3422 // If we get to the <body> tag and we have no pending stylesheet loads, we
3423 // can be fairly confident we'll have something sensible to paint soon and
3424 // can turn off deferred commits.
3425 if (m_page->mainFrame()->document()->haveStylesheetsLoaded())
3426 resumeTreeViewCommits();
3429 void WebViewImpl::resumeTreeViewCommits()
3431 if (m_layerTreeViewCommitsDeferred) {
3432 if (m_layerTreeView)
3433 m_layerTreeView->setDeferCommits(false);
3434 m_layerTreeViewCommitsDeferred = false;
3438 void WebViewImpl::layoutUpdated(WebFrameImpl* webframe)
3440 if (!m_client || webframe != mainFrameImpl())
3443 // If we finished a layout while in deferred commit mode,
3444 // that means it's time to start producing frames again so un-defer.
3445 resumeTreeViewCommits();
3447 if (m_shouldAutoResize && mainFrameImpl()->frame() && mainFrameImpl()->frame()->view()) {
3448 WebSize frameSize = mainFrameImpl()->frame()->view()->frameRect().size();
3449 if (frameSize != m_size) {
3451 m_client->didAutoResize(m_size);
3452 sendResizeEventAndRepaint();
3456 if (m_pageScaleConstraintsSet.constraintsDirty())
3457 refreshPageScaleFactorAfterLayout();
3459 m_client->didUpdateLayout();
3462 void WebViewImpl::didChangeContentsSize()
3464 m_pageScaleConstraintsSet.didChangeContentsSize(contentsSize(), pageScaleFactor());
3467 void WebViewImpl::deviceOrPageScaleFactorChanged()
3469 if (pageScaleFactor() && pageScaleFactor() != 1)
3470 enterForceCompositingMode(true);
3471 m_pageScaleConstraintsSet.setNeedsReset(false);
3472 updateLayerTreeViewport();
3475 bool WebViewImpl::useExternalPopupMenus()
3477 return shouldUseExternalPopupMenus;
3480 void WebViewImpl::startDragging(LocalFrame* frame,
3481 const WebDragData& dragData,
3482 WebDragOperationsMask mask,
3483 const WebImage& dragImage,
3484 const WebPoint& dragImageOffset)
3488 ASSERT(!m_doingDragAndDrop);
3489 m_doingDragAndDrop = true;
3490 m_client->startDragging(WebFrameImpl::fromFrame(frame), dragData, mask, dragImage, dragImageOffset);
3493 void WebViewImpl::setIgnoreInputEvents(bool newValue)
3495 ASSERT(m_ignoreInputEvents != newValue);
3496 m_ignoreInputEvents = newValue;
3499 void WebViewImpl::setBackgroundColorOverride(WebColor color)
3501 m_backgroundColorOverride = color;
3502 updateLayerTreeBackgroundColor();
3505 void WebViewImpl::setZoomFactorOverride(float zoomFactor)
3507 m_zoomFactorOverride = zoomFactor;
3508 setZoomLevel(zoomLevel());
3511 void WebViewImpl::addPageOverlay(WebPageOverlay* overlay, int zOrder)
3513 if (!m_pageOverlays)
3514 m_pageOverlays = PageOverlayList::create(this);
3516 m_pageOverlays->add(overlay, zOrder);
3519 void WebViewImpl::removePageOverlay(WebPageOverlay* overlay)
3521 if (m_pageOverlays && m_pageOverlays->remove(overlay) && m_pageOverlays->empty())
3522 m_pageOverlays = nullptr;
3525 void WebViewImpl::setOverlayLayer(WebCore::GraphicsLayer* layer)
3527 if (!m_rootGraphicsLayer)
3530 if (!m_rootTransformLayer)
3531 m_rootTransformLayer = m_page->mainFrame()->view()->renderView()->compositor()->ensureRootTransformLayer();
3533 if (m_rootTransformLayer) {
3534 if (layer->parent() != m_rootTransformLayer)
3535 m_rootTransformLayer->addChild(layer);
3539 NotificationPresenterImpl* WebViewImpl::notificationPresenterImpl()
3541 if (!m_notificationPresenter.isInitialized() && m_client)
3542 m_notificationPresenter.initialize(m_client->notificationPresenter());
3543 return &m_notificationPresenter;
3546 Element* WebViewImpl::focusedElement() const
3548 LocalFrame* frame = m_page->focusController().focusedFrame();
3552 Document* document = frame->document();
3556 return document->focusedElement();
3559 HitTestResult WebViewImpl::hitTestResultForWindowPos(const IntPoint& pos)
3561 IntPoint docPoint(m_page->mainFrame()->view()->windowToContents(pos));
3562 return m_page->mainFrame()->eventHandler().hitTestResultAtPoint(docPoint, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
3565 void WebViewImpl::setTabsToLinks(bool enable)
3567 m_tabsToLinks = enable;
3570 bool WebViewImpl::tabsToLinks() const
3572 return m_tabsToLinks;
3575 void WebViewImpl::suppressInvalidations(bool enable)
3578 m_client->suppressCompositorScheduling(enable);
3581 bool WebViewImpl::allowsAcceleratedCompositing()
3583 return !m_compositorCreationFailed;
3586 void WebViewImpl::setRootGraphicsLayer(GraphicsLayer* layer)
3588 bool pinchVirtualViewportEnabled = page()->settings().pinchVirtualViewportEnabled();
3589 suppressInvalidations(true);
3591 if (pinchVirtualViewportEnabled) {
3592 PinchViewport& pinchViewport = page()->frameHost().pinchViewport();
3593 pinchViewport.attachToLayerTree(layer, graphicsLayerFactory());
3594 pinchViewport.setSize(mainFrameImpl()->frame()->view()->frameRect().size());
3596 m_rootGraphicsLayer = pinchViewport.rootGraphicsLayer();
3597 m_rootLayer = pinchViewport.rootGraphicsLayer()->platformLayer();
3598 m_rootTransformLayer = 0;
3600 m_rootGraphicsLayer = 0;
3602 m_rootTransformLayer = 0;
3605 m_rootGraphicsLayer = layer;
3606 m_rootLayer = layer ? layer->platformLayer() : 0;
3607 m_rootTransformLayer = 0;
3610 setIsAcceleratedCompositingActive(layer);
3612 updateRootLayerTransform();
3614 if (m_layerTreeView) {
3616 m_layerTreeView->setRootLayer(*m_rootLayer);
3617 // We register viewport layers here since there may not be a layer
3618 // tree view prior to this point.
3619 if (pinchVirtualViewportEnabled) {
3620 page()->frameHost().pinchViewport().registerLayersWithTreeView(m_layerTreeView);
3622 GraphicsLayer* rootScrollLayer = compositor()->scrollLayer();
3623 ASSERT(rootScrollLayer);
3624 WebLayer* pageScaleLayer = rootScrollLayer->parent() ? rootScrollLayer->parent()->platformLayer() : 0;
3625 m_layerTreeView->registerViewportLayers(pageScaleLayer, rootScrollLayer->platformLayer(), 0);
3628 m_layerTreeView->clearRootLayer();
3629 if (pinchVirtualViewportEnabled)
3630 page()->frameHost().pinchViewport().clearLayersForTreeView(m_layerTreeView);
3632 m_layerTreeView->clearViewportLayers();
3636 suppressInvalidations(false);
3639 void WebViewImpl::scheduleCompositingLayerSync()
3641 m_layerTreeView->setNeedsAnimate();
3644 void WebViewImpl::scrollRootLayer()
3646 updateLayerTreeViewport();
3649 void WebViewImpl::invalidateRect(const IntRect& rect)
3651 if (m_isAcceleratedCompositingActive) {
3652 ASSERT(m_layerTreeView);
3653 updateLayerTreeViewport();
3654 } else if (m_client)
3655 m_client->didInvalidateRect(rect);
3658 WebCore::GraphicsLayerFactory* WebViewImpl::graphicsLayerFactory() const
3660 return m_graphicsLayerFactory.get();
3663 WebCore::RenderLayerCompositor* WebViewImpl::compositor() const
3666 || !page()->mainFrame()
3667 || !page()->mainFrame()->document()
3668 || !page()->mainFrame()->document()->renderView())
3670 return page()->mainFrame()->document()->renderView()->compositor();
3673 void WebViewImpl::registerForAnimations(WebLayer* layer)
3675 if (m_layerTreeView)
3676 m_layerTreeView->registerForAnimations(layer);
3679 WebCore::GraphicsLayer* WebViewImpl::rootGraphicsLayer()
3681 return m_rootGraphicsLayer;
3684 void WebViewImpl::scheduleAnimation()
3686 if (isAcceleratedCompositingActive()) {
3687 ASSERT(m_layerTreeView);
3688 m_layerTreeView->setNeedsAnimate();
3692 m_client->scheduleAnimation();
3695 void WebViewImpl::setIsAcceleratedCompositingActive(bool active)
3697 blink::Platform::current()->histogramEnumeration("GPU.setIsAcceleratedCompositingActive", active * 2 + m_isAcceleratedCompositingActive, 4);
3699 if (m_isAcceleratedCompositingActive == active)
3703 m_isAcceleratedCompositingActive = false;
3704 // We need to finish all GL rendering before sending didDeactivateCompositor() to prevent
3705 // flickering when compositing turns off. This is only necessary if we're not in
3706 // force-compositing-mode.
3707 if (m_layerTreeView && !page()->settings().forceCompositingMode())
3708 m_layerTreeView->finishAllRendering();
3709 m_client->didDeactivateCompositor();
3710 if (!m_layerTreeViewCommitsDeferred
3711 && blink::Platform::current()->isThreadedCompositingEnabled()) {
3712 ASSERT(m_layerTreeView);
3713 // In threaded compositing mode, force compositing mode is always on so setIsAcceleratedCompositingActive(false)
3714 // means that we're transitioning to a new page. Suppress commits until WebKit generates invalidations so
3715 // we don't attempt to paint too early in the next page load.
3716 m_layerTreeView->setDeferCommits(true);
3717 m_layerTreeViewCommitsDeferred = true;
3719 } else if (m_layerTreeView) {
3720 m_isAcceleratedCompositingActive = true;
3721 updateLayerTreeViewport();
3723 m_pageOverlays->update();
3725 m_client->didActivateCompositor(0);
3727 TRACE_EVENT0("webkit", "WebViewImpl::setIsAcceleratedCompositingActive(true)");
3729 m_client->initializeLayerTreeView();
3730 m_layerTreeView = m_client->layerTreeView();
3731 if (m_layerTreeView) {
3732 m_layerTreeView->setRootLayer(*m_rootLayer);
3734 bool visible = page()->visibilityState() == PageVisibilityStateVisible;
3735 m_layerTreeView->setVisible(visible);
3736 updateLayerTreeDeviceScaleFactor();
3737 m_layerTreeView->setPageScaleFactorAndLimits(pageScaleFactor(), minimumPageScaleFactor(), maximumPageScaleFactor());
3738 updateLayerTreeBackgroundColor();
3739 m_layerTreeView->setHasTransparentBackground(isTransparent());
3740 #if USE(RUBBER_BANDING)
3741 RefPtr<Image> overhangImage = OverscrollTheme::theme()->getOverhangImage();
3743 m_layerTreeView->setOverhangBitmap(overhangImage->nativeImageForCurrentFrame()->bitmap());
3745 updateLayerTreeViewport();
3746 m_client->didActivateCompositor(0);
3747 m_isAcceleratedCompositingActive = true;
3748 m_compositorCreationFailed = false;
3750 m_pageOverlays->update();
3751 m_layerTreeView->setShowFPSCounter(m_showFPSCounter);
3752 m_layerTreeView->setShowPaintRects(m_showPaintRects);
3753 m_layerTreeView->setShowDebugBorders(m_showDebugBorders);
3754 m_layerTreeView->setContinuousPaintingEnabled(m_continuousPaintingEnabled);
3755 m_layerTreeView->setShowScrollBottleneckRects(m_showScrollBottleneckRects);
3757 m_isAcceleratedCompositingActive = false;
3758 m_client->didDeactivateCompositor();
3759 m_compositorCreationFailed = true;
3763 page()->mainFrame()->view()->setClipsRepaints(!m_isAcceleratedCompositingActive);
3766 void WebViewImpl::updateMainFrameScrollPosition(const IntPoint& scrollPosition, bool programmaticScroll)
3768 FrameView* frameView = page()->mainFrame()->view();
3772 if (frameView->scrollPosition() == scrollPosition)
3775 bool oldProgrammaticScroll = frameView->inProgrammaticScroll();
3776 frameView->setInProgrammaticScroll(programmaticScroll);
3777 frameView->notifyScrollPositionChanged(scrollPosition);
3778 frameView->setInProgrammaticScroll(oldProgrammaticScroll);
3781 void WebViewImpl::applyScrollAndScale(const WebSize& scrollDelta, float pageScaleDelta)
3783 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
3786 // With virtual viewport we need only set the scale (see TODO below).
3787 if (page()->settings().pinchVirtualViewportEnabled()) {
3788 WebSize scrollOffset = mainFrame()->scrollOffset();
3789 WebPoint scrollPoint(scrollOffset.width, scrollOffset.height);
3790 setPageScaleFactor(pageScaleFactor() * pageScaleDelta, scrollPoint);
3791 m_doubleTapZoomPending = false;
3795 // TODO(bokan): Old pinch path only - virtual viewport pinch scrolls are automatically updated via GraphicsLayer::DidScroll.
3796 // this should be removed once old pinch is removed.
3797 if (pageScaleDelta == 1) {
3798 TRACE_EVENT_INSTANT2("webkit", "WebViewImpl::applyScrollAndScale::scrollBy", "x", scrollDelta.width, "y", scrollDelta.height);
3799 WebSize webScrollOffset = mainFrame()->scrollOffset();
3800 IntPoint scrollOffset(webScrollOffset.width + scrollDelta.width, webScrollOffset.height + scrollDelta.height);
3801 updateMainFrameScrollPosition(scrollOffset, false);
3803 // The page scale changed, so apply a scale and scroll in a single
3805 WebSize scrollOffset = mainFrame()->scrollOffset();
3806 scrollOffset.width += scrollDelta.width;
3807 scrollOffset.height += scrollDelta.height;
3809 WebPoint scrollPoint(scrollOffset.width, scrollOffset.height);
3810 setPageScaleFactor(pageScaleFactor() * pageScaleDelta, scrollPoint);
3811 m_doubleTapZoomPending = false;
3815 void WebViewImpl::didExitCompositingMode()
3817 ASSERT(m_isAcceleratedCompositingActive);
3818 setIsAcceleratedCompositingActive(false);
3819 m_compositorCreationFailed = true;
3820 m_client->didInvalidateRect(IntRect(0, 0, m_size.width, m_size.height));
3822 // Force a style recalc to remove all the composited layers.
3823 m_page->mainFrame()->document()->setNeedsStyleRecalc(SubtreeStyleChange);
3826 m_pageOverlays->update();
3829 void WebViewImpl::updateLayerTreeViewport()
3831 if (!page() || !m_layerTreeView)
3834 m_layerTreeView->setPageScaleFactorAndLimits(pageScaleFactor(), minimumPageScaleFactor(), maximumPageScaleFactor());
3837 void WebViewImpl::updateLayerTreeBackgroundColor()
3839 if (!m_layerTreeView)
3842 m_layerTreeView->setBackgroundColor(alphaChannel(m_backgroundColorOverride) ? m_backgroundColorOverride : backgroundColor());
3845 void WebViewImpl::updateLayerTreeDeviceScaleFactor()
3848 ASSERT(m_layerTreeView);
3850 float deviceScaleFactor = m_compositorDeviceScaleFactorOverride ? m_compositorDeviceScaleFactorOverride : page()->deviceScaleFactor();
3851 m_layerTreeView->setDeviceScaleFactor(deviceScaleFactor);
3854 void WebViewImpl::updateRootLayerTransform()
3856 // If we don't have a root graphics layer, we won't bother trying to find
3857 // or update the transform layer.
3858 if (!m_rootGraphicsLayer)
3861 if (!m_rootTransformLayer)
3862 m_rootTransformLayer = m_page->mainFrame()->view()->renderView()->compositor()->ensureRootTransformLayer();
3864 if (m_rootTransformLayer) {
3865 WebCore::TransformationMatrix transform;
3866 transform.translate(m_rootLayerOffset.width, m_rootLayerOffset.height);
3867 transform = transform.scale(m_rootLayerScale);
3868 m_rootTransformLayer->setTransform(transform);
3872 bool WebViewImpl::detectContentOnTouch(const WebPoint& position)
3874 HitTestResult touchHit = hitTestResultForWindowPos(position);
3876 if (touchHit.isContentEditable())
3879 Node* node = touchHit.innerNode();
3880 if (!node || !node->isTextNode())
3883 // Ignore when tapping on links or nodes listening to click events, unless the click event is on the
3884 // body element, in which case it's unlikely that the original node itself was intended to be clickable.
3885 for (; node && !isHTMLBodyElement(*node); node = node->parentNode()) {
3886 if (node->isLink() || node->willRespondToTouchEvents() || node->willRespondToMouseClickEvents())
3890 WebContentDetectionResult content = m_client->detectContentAround(touchHit);
3891 if (!content.isValid())
3894 m_client->scheduleContentIntent(content.intent());
3898 void WebViewImpl::setVisibilityState(WebPageVisibilityState visibilityState,
3899 bool isInitialState) {
3903 ASSERT(visibilityState == WebPageVisibilityStateVisible || visibilityState == WebPageVisibilityStateHidden || visibilityState == WebPageVisibilityStatePrerender);
3904 m_page->setVisibilityState(static_cast<PageVisibilityState>(static_cast<int>(visibilityState)), isInitialState);
3906 if (m_layerTreeView) {
3907 bool visible = visibilityState == WebPageVisibilityStateVisible;
3908 m_layerTreeView->setVisible(visible);
3912 bool WebViewImpl::requestPointerLock()
3914 return m_client && m_client->requestPointerLock();
3917 void WebViewImpl::requestPointerUnlock()
3920 m_client->requestPointerUnlock();
3923 bool WebViewImpl::isPointerLocked()
3925 return m_client && m_client->isPointerLocked();
3928 void WebViewImpl::pointerLockMouseEvent(const WebInputEvent& event)
3930 AtomicString eventType;
3931 switch (event.type) {
3932 case WebInputEvent::MouseDown:
3933 eventType = EventTypeNames::mousedown;
3935 case WebInputEvent::MouseUp:
3936 eventType = EventTypeNames::mouseup;
3938 case WebInputEvent::MouseMove:
3939 eventType = EventTypeNames::mousemove;
3942 ASSERT_NOT_REACHED();
3945 const WebMouseEvent& mouseEvent = static_cast<const WebMouseEvent&>(event);
3948 page()->pointerLockController().dispatchLockedMouseEvent(
3949 PlatformMouseEventBuilder(mainFrameImpl()->frameView(), mouseEvent),
3953 bool WebViewImpl::shouldDisableDesktopWorkarounds()
3955 if (!settings()->viewportEnabled())
3958 // A document is considered adapted to small screen UAs if one of these holds:
3959 // 1. The author specified viewport has a constrained width that is equal to
3960 // the initial viewport width.
3961 // 2. The author has disabled viewport zoom.
3963 const PageScaleConstraints& constraints = m_pageScaleConstraintsSet.pageDefinedConstraints();
3965 if (!mainFrameImpl() || !mainFrameImpl()->frameView())
3968 return mainFrameImpl()->frameView()->layoutSize().width() == m_size.width
3969 || (constraints.minimumScale == constraints.maximumScale && constraints.minimumScale != -1);
3972 } // namespace blink