diff options
| author | Lorry Tar Creator <lorry-tar-importer@lorry> | 2016-04-10 09:28:39 +0000 |
|---|---|---|
| committer | Lorry Tar Creator <lorry-tar-importer@lorry> | 2016-04-10 09:28:39 +0000 |
| commit | 32761a6cee1d0dee366b885b7b9c777e67885688 (patch) | |
| tree | d6bec92bebfb216f4126356e55518842c2f476a1 /Source/WebKit2/WebProcess/WebPage | |
| parent | a4e969f4965059196ca948db781e52f7cfebf19e (diff) | |
| download | WebKitGtk-tarball-32761a6cee1d0dee366b885b7b9c777e67885688.tar.gz | |
webkitgtk-2.4.11webkitgtk-2.4.11
Diffstat (limited to 'Source/WebKit2/WebProcess/WebPage')
76 files changed, 2951 insertions, 7060 deletions
diff --git a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedDrawingArea.cpp b/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedDrawingArea.cpp deleted file mode 100644 index 9da31d6ab..000000000 --- a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedDrawingArea.cpp +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies). - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#if USE(COORDINATED_GRAPHICS) -#include "CoordinatedDrawingArea.h" - -#include "CoordinatedLayerTreeHost.h" -#include "DrawingAreaProxyMessages.h" -#include "LayerTreeContext.h" -#include "PageOverlayController.h" -#include "ShareableBitmap.h" -#include "UpdateInfo.h" -#include "WebPage.h" -#include "WebPageCreationParameters.h" -#include "WebPreferencesKeys.h" -#include "WebProcess.h" -#include <WebCore/GraphicsContext.h> -#include <WebCore/MainFrame.h> -#include <WebCore/Page.h> -#include <WebCore/PageOverlayController.h> -#include <WebCore/Settings.h> - -using namespace WebCore; - -namespace WebKit { - -CoordinatedDrawingArea::~CoordinatedDrawingArea() -{ - m_layerTreeHost->invalidate(); -} - -CoordinatedDrawingArea::CoordinatedDrawingArea(WebPage& webPage, const WebPageCreationParameters& parameters) - : DrawingArea(DrawingAreaTypeCoordinated, webPage) - , m_backingStoreStateID(0) - , m_isPaintingEnabled(true) - , m_inUpdateBackingStoreState(false) - , m_shouldSendDidUpdateBackingStoreState(false) - , m_compositingAccordingToProxyMessages(false) - , m_layerTreeStateIsFrozen(false) - , m_wantsToExitAcceleratedCompositingMode(false) - , m_isPaintingSuspended(false) - , m_exitCompositingTimer(RunLoop::main(), this, &CoordinatedDrawingArea::exitAcceleratedCompositingMode) -{ - // Always use compositing in CoordinatedGraphics - enterAcceleratedCompositingMode(0); - - if (!(parameters.viewState & ViewState::IsVisible)) - suspendPainting(); -} - -void CoordinatedDrawingArea::setNeedsDisplay() -{ - if (!m_isPaintingEnabled) - return; - - m_layerTreeHost->setNonCompositedContentsNeedDisplay(); -} - -void CoordinatedDrawingArea::setNeedsDisplayInRect(const IntRect& rect) -{ - if (!m_isPaintingEnabled) - return; - - m_layerTreeHost->setNonCompositedContentsNeedDisplayInRect(rect); -} - -void CoordinatedDrawingArea::scroll(const IntRect& scrollRect, const IntSize& scrollDelta) -{ - if (!m_isPaintingEnabled) - return; - - m_layerTreeHost->scrollNonCompositedContents(scrollRect); -} - -void CoordinatedDrawingArea::pageBackgroundTransparencyChanged() -{ - m_layerTreeHost->pageBackgroundTransparencyChanged(); -} - -void CoordinatedDrawingArea::setLayerTreeStateIsFrozen(bool isFrozen) -{ - if (m_layerTreeStateIsFrozen == isFrozen) - return; - - m_layerTreeStateIsFrozen = isFrozen; - - m_layerTreeHost->setLayerFlushSchedulingEnabled(!isFrozen); - - if (isFrozen) - m_exitCompositingTimer.stop(); - else if (m_wantsToExitAcceleratedCompositingMode) - exitAcceleratedCompositingModeSoon(); -} - -void CoordinatedDrawingArea::forceRepaint() -{ - setNeedsDisplay(); - - m_webPage.layoutIfNeeded(); - - // FIXME: We need to do the same work as the layerHostDidFlushLayers function here, - // but clearly it doesn't make sense to call the function with that name. - // Consider refactoring and renaming it. - if (m_compositingAccordingToProxyMessages) - m_layerTreeHost->forceRepaint(); - else { - // Call setShouldNotifyAfterNextScheduledLayerFlush(false) here to - // prevent layerHostDidFlushLayers() from being called a second time. - m_layerTreeHost->setShouldNotifyAfterNextScheduledLayerFlush(false); - layerHostDidFlushLayers(); - } -} - -bool CoordinatedDrawingArea::forceRepaintAsync(uint64_t callbackID) -{ - return m_layerTreeHost->forceRepaintAsync(callbackID); -} - -void CoordinatedDrawingArea::setPaintingEnabled(bool paintingEnabled) -{ - m_isPaintingEnabled = paintingEnabled; -} - -void CoordinatedDrawingArea::updatePreferences(const WebPreferencesStore& store) -{ - m_webPage.corePage()->settings().setForceCompositingMode(store.getBoolValueForKey(WebPreferencesKey::forceCompositingModeKey())); -} - -void CoordinatedDrawingArea::mainFrameContentSizeChanged(const WebCore::IntSize&) -{ - m_webPage.mainFrame()->pageOverlayController().didChangeDocumentSize(); -} - -void CoordinatedDrawingArea::layerHostDidFlushLayers() -{ - m_layerTreeHost->forceRepaint(); - - if (m_shouldSendDidUpdateBackingStoreState && !exitAcceleratedCompositingModePending()) { - sendDidUpdateBackingStoreState(); - return; - } - - ASSERT(!m_compositingAccordingToProxyMessages); - if (!exitAcceleratedCompositingModePending()) { - m_webPage.send(Messages::DrawingAreaProxy::EnterAcceleratedCompositingMode(m_backingStoreStateID, m_layerTreeHost->layerTreeContext())); - m_compositingAccordingToProxyMessages = true; - } -} - -GraphicsLayerFactory* CoordinatedDrawingArea::graphicsLayerFactory() -{ - return m_layerTreeHost->graphicsLayerFactory(); -} - -void CoordinatedDrawingArea::setRootCompositingLayer(GraphicsLayer* graphicsLayer) -{ - // FIXME: Instead of using nested if statements, we should keep a compositing state - // enum in the CoordinatedDrawingArea object and have a changeAcceleratedCompositingState function - // that takes the new state. - - if (graphicsLayer) { - // We're already in accelerated compositing mode, but the root compositing layer changed. - - m_exitCompositingTimer.stop(); - m_wantsToExitAcceleratedCompositingMode = false; - - // If we haven't sent the EnterAcceleratedCompositingMode message, make sure that the - // layer tree host calls us back after the next layer flush so we can send it then. - if (!m_compositingAccordingToProxyMessages) - m_layerTreeHost->setShouldNotifyAfterNextScheduledLayerFlush(true); - } - m_layerTreeHost->setRootCompositingLayer(graphicsLayer); -} - -void CoordinatedDrawingArea::scheduleCompositingLayerFlush() -{ - m_layerTreeHost->scheduleLayerFlush(); -} - -void CoordinatedDrawingArea::scheduleCompositingLayerFlushImmediately() -{ - scheduleCompositingLayerFlush(); -} - -void CoordinatedDrawingArea::updateBackingStoreState(uint64_t stateID, bool respondImmediately, float deviceScaleFactor, const WebCore::IntSize& size, const WebCore::IntSize& scrollOffset) -{ - ASSERT(!m_inUpdateBackingStoreState); - m_inUpdateBackingStoreState = true; - - ASSERT_ARG(stateID, stateID >= m_backingStoreStateID); - if (stateID != m_backingStoreStateID) { - m_backingStoreStateID = stateID; - m_shouldSendDidUpdateBackingStoreState = true; - - m_webPage.setDeviceScaleFactor(deviceScaleFactor); - m_webPage.setSize(size); - m_webPage.layoutIfNeeded(); - m_webPage.scrollMainFrameIfNotAtMaxScrollPosition(scrollOffset); - - // Coordinated Graphics sets the size of the root layer to contents size. - if (!m_webPage.useFixedLayout()) - m_layerTreeHost->sizeDidChange(m_webPage.size()); - } else { - ASSERT(size == m_webPage.size()); - if (!m_shouldSendDidUpdateBackingStoreState) { - // We've already sent a DidUpdateBackingStoreState message for this state. We have nothing more to do. - m_inUpdateBackingStoreState = false; - return; - } - } - - if (respondImmediately) { - // Make sure to resume painting if we're supposed to respond immediately, otherwise we'll just - // send back an empty UpdateInfo struct. - if (m_isPaintingSuspended) - resumePainting(); - - sendDidUpdateBackingStoreState(); - } - - m_inUpdateBackingStoreState = false; -} - -void CoordinatedDrawingArea::sendDidUpdateBackingStoreState() -{ - ASSERT(m_shouldSendDidUpdateBackingStoreState); - - m_shouldSendDidUpdateBackingStoreState = false; - - UpdateInfo updateInfo; - - LayerTreeContext layerTreeContext; - - updateInfo.viewSize = m_webPage.size(); - updateInfo.deviceScaleFactor = m_webPage.corePage()->deviceScaleFactor(); - - layerTreeContext = m_layerTreeHost->layerTreeContext(); - - // We don't want the layer tree host to notify after the next scheduled - // layer flush because that might end up sending an EnterAcceleratedCompositingMode - // message back to the UI process, but the updated layer tree context - // will be sent back in the DidUpdateBackingStoreState message. - m_layerTreeHost->setShouldNotifyAfterNextScheduledLayerFlush(false); - m_layerTreeHost->forceRepaint(); - - m_webPage.send(Messages::DrawingAreaProxy::DidUpdateBackingStoreState(m_backingStoreStateID, updateInfo, layerTreeContext)); - m_compositingAccordingToProxyMessages = !layerTreeContext.isEmpty(); -} - -void CoordinatedDrawingArea::suspendPainting() -{ - ASSERT(!m_isPaintingSuspended); - - m_layerTreeHost->pauseRendering(); - - m_isPaintingSuspended = true; - - m_webPage.corePage()->suspendScriptedAnimations(); -} - -void CoordinatedDrawingArea::resumePainting() -{ - if (!m_isPaintingSuspended) { - // FIXME: We can get a call to resumePainting when painting is not suspended. - // This happens when sending a synchronous message to create a new page. See <rdar://problem/8976531>. - return; - } - - m_layerTreeHost->resumeRendering(); - - m_isPaintingSuspended = false; - - // FIXME: We shouldn't always repaint everything here. - setNeedsDisplay(); - - m_webPage.corePage()->resumeScriptedAnimations(); -} - -void CoordinatedDrawingArea::enterAcceleratedCompositingMode(GraphicsLayer* graphicsLayer) -{ - m_exitCompositingTimer.stop(); - m_wantsToExitAcceleratedCompositingMode = false; - - m_layerTreeHost = LayerTreeHost::create(&m_webPage); - if (!m_inUpdateBackingStoreState) - m_layerTreeHost->setShouldNotifyAfterNextScheduledLayerFlush(true); - - m_layerTreeHost->setRootCompositingLayer(graphicsLayer); -} - -void CoordinatedDrawingArea::exitAcceleratedCompositingModeSoon() -{ - if (m_layerTreeStateIsFrozen) { - m_wantsToExitAcceleratedCompositingMode = true; - return; - } - - if (exitAcceleratedCompositingModePending()) - return; - - m_exitCompositingTimer.startOneShot(0); -} - -void CoordinatedDrawingArea::didReceiveCoordinatedLayerTreeHostMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder) -{ - m_layerTreeHost->didReceiveCoordinatedLayerTreeHostMessage(connection, decoder); -} - -void CoordinatedDrawingArea::viewStateDidChange(ViewState::Flags changed, bool, const Vector<uint64_t>&) -{ - if (changed & ViewState::IsVisible) { - if (m_webPage.isVisible()) - resumePainting(); - else - suspendPainting(); - } -} - -void CoordinatedDrawingArea::attachViewOverlayGraphicsLayer(WebCore::Frame* frame, WebCore::GraphicsLayer* viewOverlayRootLayer) -{ - if (!frame->isMainFrame()) - return; - - CoordinatedLayerTreeHost* coordinatedLayerTreeHost = static_cast<CoordinatedLayerTreeHost*>(m_layerTreeHost.get()); - coordinatedLayerTreeHost->setViewOverlayRootLayer(viewOverlayRootLayer); -} - -} // namespace WebKit -#endif // USE(COORDINATED_GRAPHICS) diff --git a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedDrawingArea.h b/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedDrawingArea.h deleted file mode 100644 index a92bf0f9e..000000000 --- a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedDrawingArea.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies). - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef CoordinatedDrawingArea_h -#define CoordinatedDrawingArea_h - -#if USE(COORDINATED_GRAPHICS) - -#include "DrawingArea.h" -#include "LayerTreeHost.h" -#include <WebCore/Region.h> -#include <wtf/RunLoop.h> - -namespace WebKit { - -class CoordinatedDrawingArea : public DrawingArea { -public: - CoordinatedDrawingArea(WebPage&, const WebPageCreationParameters&); - virtual ~CoordinatedDrawingArea(); - - void layerHostDidFlushLayers(); - -private: - // DrawingArea - virtual void setNeedsDisplay() override; - virtual void setNeedsDisplayInRect(const WebCore::IntRect&) override; - virtual void scroll(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollDelta) override; - virtual void pageBackgroundTransparencyChanged() override; - virtual void setLayerTreeStateIsFrozen(bool) override; - virtual bool layerTreeStateIsFrozen() const override { return m_layerTreeStateIsFrozen; } - virtual LayerTreeHost* layerTreeHost() const override { return m_layerTreeHost.get(); } - virtual void forceRepaint() override; - virtual bool forceRepaintAsync(uint64_t callbackID) override; - - virtual void setPaintingEnabled(bool) override; - virtual void updatePreferences(const WebPreferencesStore&) override; - virtual void mainFrameContentSizeChanged(const WebCore::IntSize&) override; - - virtual WebCore::GraphicsLayerFactory* graphicsLayerFactory() override; - virtual void setRootCompositingLayer(WebCore::GraphicsLayer*) override; - virtual void scheduleCompositingLayerFlush() override; - virtual void scheduleCompositingLayerFlushImmediately() override; - - virtual void didReceiveCoordinatedLayerTreeHostMessage(IPC::Connection&, IPC::MessageDecoder&) override; - - virtual void viewStateDidChange(WebCore::ViewState::Flags, bool /* wantsDidUpdateViewState */, const Vector<uint64_t>& /* callbackIDs */) override; - virtual void attachViewOverlayGraphicsLayer(WebCore::Frame*, WebCore::GraphicsLayer*) override; - - // IPC message handlers. - virtual void updateBackingStoreState(uint64_t backingStoreStateID, bool respondImmediately, float deviceScaleFactor, const WebCore::IntSize&, const WebCore::IntSize& scrollOffset) override; - virtual void suspendPainting(); - virtual void resumePainting(); - - void sendDidUpdateBackingStoreState(); - - void enterAcceleratedCompositingMode(WebCore::GraphicsLayer*); - void exitAcceleratedCompositingModeSoon(); - bool exitAcceleratedCompositingModePending() const { return m_exitCompositingTimer.isActive(); } - void exitAcceleratedCompositingMode() { } - - uint64_t m_backingStoreStateID; - - // Whether painting is enabled. If painting is disabled, any calls to setNeedsDisplay and scroll are ignored. - bool m_isPaintingEnabled; - - // Whether we're currently processing an UpdateBackingStoreState message. - bool m_inUpdateBackingStoreState; - - // When true, we should send an UpdateBackingStoreState message instead of any other messages - // we normally send to the UI process. - bool m_shouldSendDidUpdateBackingStoreState; - - // True between sending the 'enter compositing' messages, and the 'exit compositing' message. - bool m_compositingAccordingToProxyMessages; - - // When true, we maintain the layer tree in its current state by not leaving accelerated compositing mode - // and not scheduling layer flushes. - bool m_layerTreeStateIsFrozen; - - // True when we were asked to exit accelerated compositing mode but couldn't because layer tree - // state was frozen. - bool m_wantsToExitAcceleratedCompositingMode; - - // Whether painting is suspended. We'll still keep track of the dirty region but we - // won't paint until painting has resumed again. - bool m_isPaintingSuspended; - - RunLoop::Timer<CoordinatedDrawingArea> m_exitCompositingTimer; - - // The layer tree host that handles accelerated compositing. - RefPtr<LayerTreeHost> m_layerTreeHost; -}; - -} // namespace WebKit - -#endif // USE(COORDINATED_GRAPHICS) - -#endif // CoordinatedDrawingArea_h diff --git a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedLayerTreeHost.cpp b/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedLayerTreeHost.cpp deleted file mode 100644 index d7c90a606..000000000 --- a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedLayerTreeHost.cpp +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). - * Copyright (C) 2012 Company 100, Inc. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#if USE(COORDINATED_GRAPHICS) -#include "CoordinatedLayerTreeHost.h" - -#include "CoordinatedDrawingArea.h" -#include "CoordinatedGraphicsArgumentCoders.h" -#include "CoordinatedLayerTreeHostProxyMessages.h" -#include "GraphicsContext.h" -#include "WebCoordinatedSurface.h" -#include "WebCoreArgumentCoders.h" -#include "WebPage.h" -#include "WebPageProxyMessages.h" -#include <WebCore/Frame.h> -#include <WebCore/FrameView.h> -#include <WebCore/MainFrame.h> -#include <WebCore/PageOverlayController.h> -#include <WebCore/Settings.h> -#include <wtf/CurrentTime.h> - -using namespace WebCore; - -namespace WebKit { - -Ref<CoordinatedLayerTreeHost> CoordinatedLayerTreeHost::create(WebPage* webPage) -{ - return adoptRef(*new CoordinatedLayerTreeHost(webPage)); -} - -CoordinatedLayerTreeHost::~CoordinatedLayerTreeHost() -{ -} - -CoordinatedLayerTreeHost::CoordinatedLayerTreeHost(WebPage* webPage) - : LayerTreeHost(webPage) - , m_notifyAfterScheduledLayerFlush(false) - , m_isValid(true) - , m_isSuspended(false) - , m_isWaitingForRenderer(true) - , m_layerFlushTimer(*this, &CoordinatedLayerTreeHost::layerFlushTimerFired) - , m_layerFlushSchedulingEnabled(true) - , m_forceRepaintAsyncCallbackID(0) - , m_contentLayer(nullptr) - , m_viewOverlayRootLayer(nullptr) -{ - m_coordinator = std::make_unique<CompositingCoordinator>(webPage->corePage(), this); - - m_coordinator->createRootLayer(webPage->size()); - m_layerTreeContext.contextID = toCoordinatedGraphicsLayer(m_coordinator->rootLayer())->id(); - - CoordinatedSurface::setFactory(createCoordinatedSurface); - - scheduleLayerFlush(); -} - -void CoordinatedLayerTreeHost::setLayerFlushSchedulingEnabled(bool layerFlushingEnabled) -{ - if (m_layerFlushSchedulingEnabled == layerFlushingEnabled) - return; - - m_layerFlushSchedulingEnabled = layerFlushingEnabled; - - if (m_layerFlushSchedulingEnabled) { - scheduleLayerFlush(); - return; - } - - cancelPendingLayerFlush(); -} - -void CoordinatedLayerTreeHost::scheduleLayerFlush() -{ - if (!m_layerFlushSchedulingEnabled) - return; - - if (!m_layerFlushTimer.isActive() || m_layerFlushTimer.nextFireInterval() > 0) - m_layerFlushTimer.startOneShot(0); -} - -void CoordinatedLayerTreeHost::cancelPendingLayerFlush() -{ - m_layerFlushTimer.stop(); -} - -void CoordinatedLayerTreeHost::setShouldNotifyAfterNextScheduledLayerFlush(bool notifyAfterScheduledLayerFlush) -{ - m_notifyAfterScheduledLayerFlush = notifyAfterScheduledLayerFlush; -} - -void CoordinatedLayerTreeHost::updateRootLayers() -{ - if (!m_contentLayer && !m_viewOverlayRootLayer) - return; - - m_coordinator->setRootCompositingLayer(m_contentLayer, m_viewOverlayRootLayer); -} - -void CoordinatedLayerTreeHost::setViewOverlayRootLayer(WebCore::GraphicsLayer* viewOverlayRootLayer) -{ - m_viewOverlayRootLayer = viewOverlayRootLayer; - updateRootLayers(); -} - -void CoordinatedLayerTreeHost::setRootCompositingLayer(WebCore::GraphicsLayer* graphicsLayer) -{ - m_contentLayer = graphicsLayer; - updateRootLayers(); -} - -void CoordinatedLayerTreeHost::invalidate() -{ - cancelPendingLayerFlush(); - - ASSERT(m_isValid); - m_coordinator->clearRootLayer(); - m_isValid = false; -} - -void CoordinatedLayerTreeHost::forceRepaint() -{ - // This is necessary for running layout tests. Since in this case we are not waiting for a UIProcess to reply nicely. - // Instead we are just triggering forceRepaint. But we still want to have the scripted animation callbacks being executed. - m_coordinator->syncDisplayState(); - - // We need to schedule another flush, otherwise the forced paint might cancel a later expected flush. - // This is aligned with LayerTreeHostCA. - scheduleLayerFlush(); - - if (m_isWaitingForRenderer) - return; - - m_coordinator->flushPendingLayerChanges(); -} - -bool CoordinatedLayerTreeHost::forceRepaintAsync(uint64_t callbackID) -{ - // We expect the UI process to not require a new repaint until the previous one has finished. - ASSERT(!m_forceRepaintAsyncCallbackID); - m_forceRepaintAsyncCallbackID = callbackID; - scheduleLayerFlush(); - return true; -} - -void CoordinatedLayerTreeHost::sizeDidChange(const WebCore::IntSize& newSize) -{ - m_coordinator->sizeDidChange(newSize); - scheduleLayerFlush(); -} - -void CoordinatedLayerTreeHost::setVisibleContentsRect(const FloatRect& rect, const FloatPoint& trajectoryVector) -{ - m_coordinator->setVisibleContentsRect(rect, trajectoryVector); - scheduleLayerFlush(); -} - -void CoordinatedLayerTreeHost::renderNextFrame() -{ - m_isWaitingForRenderer = false; - scheduleLayerFlush(); - m_coordinator->renderNextFrame(); -} - -void CoordinatedLayerTreeHost::purgeBackingStores() -{ - m_coordinator->purgeBackingStores(); -} - -void CoordinatedLayerTreeHost::didFlushRootLayer(const FloatRect& visibleContentRect) -{ - // Because our view-relative overlay root layer is not attached to the FrameView's GraphicsLayer tree, we need to flush it manually. - if (m_viewOverlayRootLayer) - m_viewOverlayRootLayer->flushCompositingState(visibleContentRect, m_webPage->mainFrame()->view()->viewportIsStable()); -} - -void CoordinatedLayerTreeHost::performScheduledLayerFlush() -{ - if (m_isSuspended || m_isWaitingForRenderer) - return; - - m_coordinator->syncDisplayState(); - - if (!m_isValid) - return; - - bool didSync = m_coordinator->flushPendingLayerChanges(); - - if (m_forceRepaintAsyncCallbackID) { - m_webPage->send(Messages::WebPageProxy::VoidCallback(m_forceRepaintAsyncCallbackID)); - m_forceRepaintAsyncCallbackID = 0; - } - - if (m_notifyAfterScheduledLayerFlush && didSync) { - static_cast<CoordinatedDrawingArea*>(m_webPage->drawingArea())->layerHostDidFlushLayers(); - m_notifyAfterScheduledLayerFlush = false; - } -} - -void CoordinatedLayerTreeHost::layerFlushTimerFired() -{ - performScheduledLayerFlush(); -} - -void CoordinatedLayerTreeHost::paintLayerContents(const GraphicsLayer*, GraphicsContext&, const IntRect&) -{ -} - -void CoordinatedLayerTreeHost::commitSceneState(const WebCore::CoordinatedGraphicsState& state) -{ - m_webPage->send(Messages::CoordinatedLayerTreeHostProxy::CommitCoordinatedGraphicsState(state)); - m_isWaitingForRenderer = true; -} - -PassRefPtr<CoordinatedSurface> CoordinatedLayerTreeHost::createCoordinatedSurface(const IntSize& size, CoordinatedSurface::Flags flags) -{ - return WebCoordinatedSurface::create(size, flags); -} - -void CoordinatedLayerTreeHost::deviceOrPageScaleFactorChanged() -{ - m_coordinator->deviceOrPageScaleFactorChanged(); - m_webPage->mainFrame()->pageOverlayController().didChangeDeviceScaleFactor(); -} - -void CoordinatedLayerTreeHost::pageBackgroundTransparencyChanged() -{ -} - -GraphicsLayerFactory* CoordinatedLayerTreeHost::graphicsLayerFactory() -{ - return m_coordinator.get(); -} - -#if ENABLE(REQUEST_ANIMATION_FRAME) -void CoordinatedLayerTreeHost::scheduleAnimation() -{ - if (m_isWaitingForRenderer) - return; - - if (m_layerFlushTimer.isActive()) - return; - - scheduleLayerFlush(); - m_layerFlushTimer.startOneShot(m_coordinator->nextAnimationServiceTime()); -} -#endif - -void CoordinatedLayerTreeHost::commitScrollOffset(uint32_t layerID, const WebCore::IntSize& offset) -{ - m_coordinator->commitScrollOffset(layerID, offset); -} - -} // namespace WebKit -#endif // USE(COORDINATED_GRAPHICS) diff --git a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedLayerTreeHost.h b/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedLayerTreeHost.h deleted file mode 100644 index 1c72e2e73..000000000 --- a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedLayerTreeHost.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) - Copyright (C) 2013 Company 100, Inc. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef CoordinatedLayerTreeHost_h -#define CoordinatedLayerTreeHost_h - -#if USE(COORDINATED_GRAPHICS) - -#include "LayerTreeContext.h" -#include "LayerTreeHost.h" -#include <WebCore/CompositingCoordinator.h> -#include <WebCore/GraphicsLayerFactory.h> -#include <wtf/HashSet.h> - -namespace WebCore { -class CoordinatedSurface; -} - -namespace WebKit { - -class WebPage; - -class CoordinatedLayerTreeHost : public LayerTreeHost, public WebCore::CompositingCoordinator::Client -{ -public: - static Ref<CoordinatedLayerTreeHost> create(WebPage*); - virtual ~CoordinatedLayerTreeHost(); - - virtual const LayerTreeContext& layerTreeContext() override { return m_layerTreeContext; } - virtual void setLayerFlushSchedulingEnabled(bool) override; - virtual void scheduleLayerFlush() override; - virtual void setShouldNotifyAfterNextScheduledLayerFlush(bool) override; - virtual void setRootCompositingLayer(WebCore::GraphicsLayer*) override; - virtual void invalidate() override; - - virtual void setNonCompositedContentsNeedDisplay() override { } - virtual void setNonCompositedContentsNeedDisplayInRect(const WebCore::IntRect&) override { } - virtual void scrollNonCompositedContents(const WebCore::IntRect&) override { } - virtual void forceRepaint() override; - virtual bool forceRepaintAsync(uint64_t callbackID) override; - virtual void sizeDidChange(const WebCore::IntSize& newSize) override; - - virtual void pauseRendering() override { m_isSuspended = true; } - virtual void resumeRendering() override { m_isSuspended = false; scheduleLayerFlush(); } - virtual void deviceOrPageScaleFactorChanged() override; - virtual void pageBackgroundTransparencyChanged() override; - - virtual void didReceiveCoordinatedLayerTreeHostMessage(IPC::Connection&, IPC::MessageDecoder&) override; - virtual WebCore::GraphicsLayerFactory* graphicsLayerFactory() override; - WebCore::CoordinatedGraphicsLayer* mainContentsLayer(); - -#if ENABLE(REQUEST_ANIMATION_FRAME) - virtual void scheduleAnimation() override; -#endif - - virtual void setViewOverlayRootLayer(WebCore::GraphicsLayer*) override; - - static PassRefPtr<WebCore::CoordinatedSurface> createCoordinatedSurface(const WebCore::IntSize&, WebCore::CoordinatedSurface::Flags); - -protected: - explicit CoordinatedLayerTreeHost(WebPage*); - -private: - // CoordinatedLayerTreeHost - void cancelPendingLayerFlush(); - void performScheduledLayerFlush(); - void setVisibleContentsRect(const WebCore::FloatRect&, const WebCore::FloatPoint&); - void renderNextFrame(); - void purgeBackingStores(); - void commitScrollOffset(uint32_t layerID, const WebCore::IntSize& offset); - - void layerFlushTimerFired(); - - void updateRootLayers(); - - // CompositingCoordinator::Client - virtual void didFlushRootLayer(const WebCore::FloatRect& visibleContentRect) override; - virtual void notifyFlushRequired() override { scheduleLayerFlush(); }; - virtual void commitSceneState(const WebCore::CoordinatedGraphicsState&) override; - virtual void paintLayerContents(const WebCore::GraphicsLayer*, WebCore::GraphicsContext&, const WebCore::IntRect& clipRect) override; - - std::unique_ptr<WebCore::CompositingCoordinator> m_coordinator; - - bool m_notifyAfterScheduledLayerFlush; - bool m_isValid; - bool m_isSuspended; - bool m_isWaitingForRenderer; - - LayerTreeContext m_layerTreeContext; - - WebCore::Timer m_layerFlushTimer; - bool m_layerFlushSchedulingEnabled; - uint64_t m_forceRepaintAsyncCallbackID; - - WebCore::GraphicsLayer* m_contentLayer; - WebCore::GraphicsLayer* m_viewOverlayRootLayer; -}; - -} // namespace WebKit - -#endif // USE(COORDINATED_GRAPHICS) - -#endif // CoordinatedLayerTreeHost_h diff --git a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedLayerTreeHost.messages.in b/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedLayerTreeHost.messages.in deleted file mode 100644 index e1705b7ed..000000000 --- a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedLayerTreeHost.messages.in +++ /dev/null @@ -1,29 +0,0 @@ -# -# Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) -# Copyright (C) 2012 Intel Corporation. All rights reserved. -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Library General Public -# License as published by the Free Software Foundation; either -# version 2 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Library General Public License for more details. -# -# You should have received a copy of the GNU Library General Public License -# along with this library; see the file COPYING.LIB. If not, write to -# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -# Boston, MA 02110-1301, USA. -# - - -#if USE(COORDINATED_GRAPHICS) -messages -> CoordinatedLayerTreeHost LegacyReceiver { - SetVisibleContentsRect(WebCore::FloatRect visibleContentsRect, WebCore::FloatPoint trajectoryVectory) - RenderNextFrame() - PurgeBackingStores() - CommitScrollOffset(uint32_t layerID, WebCore::IntSize offset) -} -#endif diff --git a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/ThreadedCoordinatedLayerTreeHost.cpp b/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/ThreadedCoordinatedLayerTreeHost.cpp deleted file mode 100644 index 2741059d3..000000000 --- a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/ThreadedCoordinatedLayerTreeHost.cpp +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). - * Copyright (C) 2012 Company 100, Inc. - * Copyright (C) 2014 Igalia S.L. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ThreadedCoordinatedLayerTreeHost.h" - -#if USE(COORDINATED_GRAPHICS_THREADED) - -#include "DrawingAreaImpl.h" -#include "NotImplemented.h" -#include "ThreadSafeCoordinatedSurface.h" -#include "WebPage.h" -#include <WebCore/CoordinatedGraphicsLayer.h> -#include <WebCore/CoordinatedGraphicsState.h> -#include <WebCore/Frame.h> -#include <WebCore/FrameView.h> -#include <WebCore/GraphicsContext.h> -#include <WebCore/MainFrame.h> -#include <WebCore/Page.h> -#include <wtf/CurrentTime.h> - -using namespace WebCore; - -namespace WebKit { - -Ref<ThreadedCoordinatedLayerTreeHost> ThreadedCoordinatedLayerTreeHost::create(WebPage* webPage) -{ - return adoptRef(*new ThreadedCoordinatedLayerTreeHost(webPage)); -} - -ThreadedCoordinatedLayerTreeHost::~ThreadedCoordinatedLayerTreeHost() -{ -} - -ThreadedCoordinatedLayerTreeHost::ThreadedCoordinatedLayerTreeHost(WebPage* webPage) - : LayerTreeHost(webPage) - , m_forceRepaintAsyncCallbackID(0) - , m_contentLayer(nullptr) - , m_viewOverlayRootLayer(nullptr) - , m_notifyAfterScheduledLayerFlush(false) - , m_isSuspended(false) - , m_isWaitingForRenderer(false) - , m_layerFlushTimer(RunLoop::main(), this, &ThreadedCoordinatedLayerTreeHost::performScheduledLayerFlush) - , m_layerFlushSchedulingEnabled(true) -{ - m_coordinator = std::make_unique<CompositingCoordinator>(m_webPage->corePage(), this); - - m_coordinator->createRootLayer(m_webPage->size()); - - CoordinatedSurface::setFactory(createCoordinatedSurface); - - m_compositor = ThreadedCompositor::create(this); - scheduleLayerFlush(); -} - -PassRefPtr<CoordinatedSurface> ThreadedCoordinatedLayerTreeHost::createCoordinatedSurface(const IntSize& size, CoordinatedSurface::Flags flags) -{ - return ThreadSafeCoordinatedSurface::create(size, flags); -} - -void ThreadedCoordinatedLayerTreeHost::scheduleLayerFlush() -{ - if (!m_layerFlushSchedulingEnabled) - return; - - if (!m_layerFlushTimer.isActive()) - m_layerFlushTimer.startOneShot(0); -} - -void ThreadedCoordinatedLayerTreeHost::setLayerFlushSchedulingEnabled(bool layerFlushingEnabled) -{ - if (m_layerFlushSchedulingEnabled == layerFlushingEnabled) - return; - - m_layerFlushSchedulingEnabled = layerFlushingEnabled; - - if (m_layerFlushSchedulingEnabled) { - scheduleLayerFlush(); - return; - } - - cancelPendingLayerFlush(); -} - -void ThreadedCoordinatedLayerTreeHost::setShouldNotifyAfterNextScheduledLayerFlush(bool notifyAfterScheduledLayerFlush) -{ - m_notifyAfterScheduledLayerFlush = notifyAfterScheduledLayerFlush; -} - -void ThreadedCoordinatedLayerTreeHost::setRootCompositingLayer(WebCore::GraphicsLayer* graphicsLayer) -{ - m_contentLayer = graphicsLayer; - updateRootLayers(); -} - -void ThreadedCoordinatedLayerTreeHost::invalidate() -{ - notImplemented(); -} - -void ThreadedCoordinatedLayerTreeHost::scrollNonCompositedContents(const WebCore::IntRect& rect) -{ - m_compositor->scrollTo(rect.location()); - scheduleLayerFlush(); -} - -void ThreadedCoordinatedLayerTreeHost::forceRepaint() -{ - notImplemented(); -} - -bool ThreadedCoordinatedLayerTreeHost::forceRepaintAsync(uint64_t callbackID) -{ - // We expect the UI process to not require a new repaint until the previous one has finished. - ASSERT(!m_forceRepaintAsyncCallbackID); - m_forceRepaintAsyncCallbackID = callbackID; - scheduleLayerFlush(); - return true; -} - -void ThreadedCoordinatedLayerTreeHost::sizeDidChange(const WebCore::IntSize& newSize) -{ - m_coordinator->sizeDidChange(newSize); - m_compositor->didChangeContentsSize(newSize); -} - -void ThreadedCoordinatedLayerTreeHost::deviceOrPageScaleFactorChanged() -{ - m_coordinator->deviceOrPageScaleFactorChanged(); - m_compositor->setDeviceScaleFactor(m_webPage->deviceScaleFactor()); -} - -void ThreadedCoordinatedLayerTreeHost::pauseRendering() -{ - m_isSuspended = true; -} - -void ThreadedCoordinatedLayerTreeHost::resumeRendering() -{ - m_isSuspended = false; - scheduleLayerFlush(); -} - -GraphicsLayerFactory* ThreadedCoordinatedLayerTreeHost::graphicsLayerFactory() -{ - return m_coordinator.get(); -} - -void ThreadedCoordinatedLayerTreeHost::viewportSizeChanged(const WebCore::IntSize& size) -{ - m_compositor->didChangeViewportSize(size); -} - -void ThreadedCoordinatedLayerTreeHost::didChangeViewportProperties(const WebCore::ViewportAttributes& attr) -{ - m_compositor->didChangeViewportAttribute(attr); -} - -void ThreadedCoordinatedLayerTreeHost::compositorDidFlushLayers() -{ - static_cast<DrawingAreaImpl*>(m_webPage->drawingArea())->layerHostDidFlushLayers(); -} - -void ThreadedCoordinatedLayerTreeHost::didScaleFactorChanged(float scale, const IntPoint& origin) -{ - m_webPage->scalePage(scale, origin); -} - -void ThreadedCoordinatedLayerTreeHost::updateRootLayers() -{ - if (!m_contentLayer && !m_viewOverlayRootLayer) - return; - - m_coordinator->setRootCompositingLayer(m_contentLayer, m_viewOverlayRootLayer); -} - -void ThreadedCoordinatedLayerTreeHost::setViewOverlayRootLayer(GraphicsLayer* viewOverlayRootLayer) -{ - m_viewOverlayRootLayer = viewOverlayRootLayer; - updateRootLayers(); -} - -#if PLATFORM(GTK) -void ThreadedCoordinatedLayerTreeHost::setNativeSurfaceHandleForCompositing(uint64_t handle) -{ - m_layerTreeContext.contextID = handle; - m_compositor->setNativeSurfaceHandleForCompositing(handle); -} -#endif - -#if ENABLE(REQUEST_ANIMATION_FRAME) -void ThreadedCoordinatedLayerTreeHost::scheduleAnimation() -{ - if (m_isWaitingForRenderer) - return; - - if (m_layerFlushTimer.isActive()) - return; - - m_layerFlushTimer.startOneShot(m_coordinator->nextAnimationServiceTime()); - scheduleLayerFlush(); -} -#endif - -void ThreadedCoordinatedLayerTreeHost::setVisibleContentsRect(const FloatRect& rect, const FloatPoint& trajectoryVector, float scale) -{ - m_coordinator->setVisibleContentsRect(rect, trajectoryVector); - if (m_lastScrollPosition != roundedIntPoint(rect.location())) { - m_lastScrollPosition = roundedIntPoint(rect.location()); - - if (!m_webPage->corePage()->mainFrame().view()->useFixedLayout()) - m_webPage->corePage()->mainFrame().view()->notifyScrollPositionChanged(m_lastScrollPosition); - } - - if (m_lastScaleFactor != scale) { - m_lastScaleFactor = scale; - didScaleFactorChanged(m_lastScaleFactor, m_lastScrollPosition); - } - - scheduleLayerFlush(); -} - -void ThreadedCoordinatedLayerTreeHost::cancelPendingLayerFlush() -{ - m_layerFlushTimer.stop(); -} - -void ThreadedCoordinatedLayerTreeHost::performScheduledLayerFlush() -{ - if (m_isSuspended || m_isWaitingForRenderer) - return; - - m_coordinator->syncDisplayState(); - bool didSync = m_coordinator->flushPendingLayerChanges(); - - if (m_notifyAfterScheduledLayerFlush && didSync) { - compositorDidFlushLayers(); - m_notifyAfterScheduledLayerFlush = false; - } -} - -void ThreadedCoordinatedLayerTreeHost::purgeBackingStores() -{ - m_coordinator->purgeBackingStores(); -} - -void ThreadedCoordinatedLayerTreeHost::renderNextFrame() -{ - m_isWaitingForRenderer = false; - m_coordinator->renderNextFrame(); - scheduleLayerFlush(); -} - -void ThreadedCoordinatedLayerTreeHost::commitScrollOffset(uint32_t layerID, const IntSize& offset) -{ - m_coordinator->commitScrollOffset(layerID, offset); -} - -void ThreadedCoordinatedLayerTreeHost::notifyFlushRequired() -{ - scheduleLayerFlush(); -} - -void ThreadedCoordinatedLayerTreeHost::commitSceneState(const CoordinatedGraphicsState& state) -{ - m_isWaitingForRenderer = true; - m_compositor->updateSceneState(state); -} - -void ThreadedCoordinatedLayerTreeHost::paintLayerContents(const GraphicsLayer*, GraphicsContext&, const IntRect&) -{ -} - -} // namespace WebKit - -#endif // USE(COORDINATED_GRAPHICS) diff --git a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/ThreadedCoordinatedLayerTreeHost.h b/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/ThreadedCoordinatedLayerTreeHost.h deleted file mode 100644 index 77e2e1205..000000000 --- a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/ThreadedCoordinatedLayerTreeHost.h +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) - * Copyright (C) 2013 Company 100, Inc. - * Copyright (C) 2014 Igalia S.L. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ThreadedCoordinatedLayerTreeHost_h -#define ThreadedCoordinatedLayerTreeHost_h - -#if USE(COORDINATED_GRAPHICS_THREADED) - -#include "LayerTreeContext.h" -#include "LayerTreeHost.h" -#include "ThreadedCompositor.h" -#include <WebCore/CompositingCoordinator.h> -#include <WebCore/FloatPoint.h> -#include <WebCore/FloatRect.h> -#include <WebCore/IntPoint.h> -#include <WebCore/IntRect.h> -#include <WebCore/IntSize.h> -#include <WebCore/PageOverlay.h> -#include <WebCore/Timer.h> -#include <wtf/RunLoop.h> -#include <wtf/Threading.h> - -namespace WebCore { -class CoordinatedSurface; -class GraphicsContext; -class GraphicsLayer; -class GraphicsLayerFactory; -class GraphicsLayerFactory; -struct CoordinatedGraphicsLayerState; -struct CoordinatedGraphicsState; -} - -namespace WebKit { - -class WebPage; - -class ThreadedCoordinatedLayerTreeHost : public LayerTreeHost, public WebCore::CompositingCoordinator::Client, public ThreadedCompositor::Client { - WTF_MAKE_NONCOPYABLE(ThreadedCoordinatedLayerTreeHost); WTF_MAKE_FAST_ALLOCATED; -public: - static Ref<ThreadedCoordinatedLayerTreeHost> create(WebPage*); - virtual ~ThreadedCoordinatedLayerTreeHost(); - - virtual const LayerTreeContext& layerTreeContext() override { return m_layerTreeContext; }; - - virtual void scheduleLayerFlush() override; - virtual void setLayerFlushSchedulingEnabled(bool) override; - virtual void setShouldNotifyAfterNextScheduledLayerFlush(bool) override; - virtual void setRootCompositingLayer(WebCore::GraphicsLayer*) override; - virtual void invalidate() override; - - virtual void setNonCompositedContentsNeedDisplay() override { }; - virtual void setNonCompositedContentsNeedDisplayInRect(const WebCore::IntRect&) override { }; - virtual void scrollNonCompositedContents(const WebCore::IntRect& scrollRect) override; - virtual void forceRepaint() override; - virtual bool forceRepaintAsync(uint64_t /*callbackID*/) override; - virtual void sizeDidChange(const WebCore::IntSize& newSize) override; - virtual void deviceOrPageScaleFactorChanged() override; - - virtual void pauseRendering() override; - virtual void resumeRendering() override; - - virtual WebCore::GraphicsLayerFactory* graphicsLayerFactory() override; - virtual void pageBackgroundTransparencyChanged() override { }; - - virtual void viewportSizeChanged(const WebCore::IntSize&) override; - virtual void didChangeViewportProperties(const WebCore::ViewportAttributes&) override; - -#if PLATFORM(GTK) - virtual void setNativeSurfaceHandleForCompositing(uint64_t) override; -#endif - -#if ENABLE(REQUEST_ANIMATION_FRAME) - virtual void scheduleAnimation() override; -#endif - - void setViewOverlayRootLayer(WebCore::GraphicsLayer*); - static PassRefPtr<WebCore::CoordinatedSurface> createCoordinatedSurface(const WebCore::IntSize&, WebCore::CoordinatedSurface::Flags); - -protected: - explicit ThreadedCoordinatedLayerTreeHost(WebPage*); - -private: - - void compositorDidFlushLayers(); - void didScaleFactorChanged(float scale, const WebCore::IntPoint& origin); - - void updateRootLayers(); - - void cancelPendingLayerFlush(); - void performScheduledLayerFlush(); - - WebCore::GraphicsLayer* rootLayer() { return m_coordinator->rootLayer(); } - - // ThreadedCompositor::Client - virtual void setVisibleContentsRect(const WebCore::FloatRect&, const WebCore::FloatPoint&, float) override; - virtual void purgeBackingStores() override; - virtual void renderNextFrame() override; - virtual void commitScrollOffset(uint32_t layerID, const WebCore::IntSize& offset) override; - - // CompositingCoordinator::Client - virtual void didFlushRootLayer(const WebCore::FloatRect&) override { } - virtual void notifyFlushRequired() override; - virtual void commitSceneState(const WebCore::CoordinatedGraphicsState&) override; - virtual void paintLayerContents(const WebCore::GraphicsLayer*, WebCore::GraphicsContext&, const WebCore::IntRect& clipRect) override; - - LayerTreeContext m_layerTreeContext; - uint64_t m_forceRepaintAsyncCallbackID; - - WebCore::IntPoint m_prevScrollPosition; - - WebCore::GraphicsLayer* m_contentLayer; - WebCore::GraphicsLayer* m_viewOverlayRootLayer; - - std::unique_ptr<WebCore::CompositingCoordinator> m_coordinator; - RefPtr<ThreadedCompositor> m_compositor; - - bool m_notifyAfterScheduledLayerFlush; - bool m_isSuspended; - bool m_isWaitingForRenderer; - - float m_lastScaleFactor; - WebCore::IntPoint m_lastScrollPosition; - - RunLoop::Timer<ThreadedCoordinatedLayerTreeHost> m_layerFlushTimer; - bool m_layerFlushSchedulingEnabled; -}; - -} // namespace WebKit - -#endif // USE(COORDINATED_GRAPHICS_THREADED) - -#endif // ThreadedCoordinatedLayerTreeHost_h diff --git a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/WebPageCoordinatedGraphics.cpp b/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/WebPageCoordinatedGraphics.cpp deleted file mode 100644 index 345648baa..000000000 --- a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/WebPageCoordinatedGraphics.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies) - * Copyright (C) 2013 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#if USE(COORDINATED_GRAPHICS) - -#include "WebPage.h" - -#include "HitTestResult.h" -#include "WebCoreArgumentCoders.h" -#include "WebFrame.h" -#include "WebPageProxyMessages.h" -#include <WebCore/Document.h> -#include <WebCore/EventHandler.h> -#include <WebCore/Frame.h> -#include <WebCore/FrameView.h> -#include <WebCore/RenderObject.h> -#include <WebCore/ScrollView.h> - -using namespace WebCore; - -namespace WebKit { - -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) -void WebPage::findZoomableAreaForPoint(const IntPoint& point, const IntSize& area) -{ - UNUSED_PARAM(area); - Frame* mainframe = m_mainFrame->coreFrame(); - HitTestResult result = mainframe->eventHandler().hitTestResultAtPoint(mainframe->view()->windowToContents(point), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::IgnoreClipping | HitTestRequest::DisallowShadowContent); - - Node* node = result.innerNode(); - - if (!node) - return; - - IntRect zoomableArea; - if (RenderObject* renderer = node->renderer()) - zoomableArea = renderer->absoluteBoundingBoxRect(); - - while (true) { - bool found = !node->isTextNode() && !node->isShadowRoot(); - - // No candidate found, bail out. - if (!found && !node->parentNode()) - return; - - // Candidate found, and it is a better candidate than its parent. - // NB: A parent is considered a better candidate if the node is - // contained by it and it is the only child. - if (found && (!node->parentNode() || !node->parentNode()->hasOneChild())) - break; - - node = node->parentNode(); - if (RenderObject* renderer = node->renderer()) - zoomableArea.unite(renderer->absoluteBoundingBoxRect()); - } - - if (node->document().frame() && node->document().frame()->view()) { - const ScrollView* view = node->document().frame()->view(); - zoomableArea = view->contentsToWindow(zoomableArea); - } - - send(Messages::WebPageProxy::DidFindZoomableArea(point, zoomableArea)); -} -#endif - -} // namespace WebKit - -#endif // USE(COORDINATED_GRAPHICS) diff --git a/Source/WebKit2/WebProcess/WebPage/DecoderAdapter.cpp b/Source/WebKit2/WebProcess/WebPage/DecoderAdapter.cpp new file mode 100644 index 000000000..9cdcb2b45 --- /dev/null +++ b/Source/WebKit2/WebProcess/WebPage/DecoderAdapter.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "DecoderAdapter.h" + +#include "DataReference.h" +#include "WebCoreArgumentCoders.h" +#include <wtf/text/WTFString.h> + +namespace WebKit { + +DecoderAdapter::DecoderAdapter(const uint8_t* buffer, size_t bufferSize) + : m_decoder(buffer, bufferSize) +{ + // Keep format compatibility by decoding an unused uint64_t value + // that used to be encoded by the argument encoder. + uint64_t value; + m_decoder.decode(value); + ASSERT(!value); +} + +bool DecoderAdapter::decodeBytes(Vector<uint8_t>& bytes) +{ + IPC::DataReference dataReference; + if (!m_decoder.decode(dataReference)) + return false; + + bytes = dataReference.vector(); + return true; +} + +bool DecoderAdapter::decodeBool(bool& value) +{ + return m_decoder.decode(value); +} + +bool DecoderAdapter::decodeUInt16(uint16_t& value) +{ + return m_decoder.decode(value); +} + +bool DecoderAdapter::decodeUInt32(uint32_t& value) +{ + return m_decoder.decode(value); +} + +bool DecoderAdapter::decodeUInt64(uint64_t& value) +{ + return m_decoder.decode(value); +} + +bool DecoderAdapter::decodeInt32(int32_t& value) +{ + return m_decoder.decode(value); +} + +bool DecoderAdapter::decodeInt64(int64_t& value) +{ + return m_decoder.decode(value); +} + +bool DecoderAdapter::decodeFloat(float& value) +{ + return m_decoder.decode(value); +} + +bool DecoderAdapter::decodeDouble(double& value) +{ + return m_decoder.decode(value); +} + +bool DecoderAdapter::decodeString(String& value) +{ + // This mimics the IPC binary encoding of Strings prior to r88886. + // Whenever the IPC binary encoding changes, we'll have to "undo" the changes here. + // FIXME: We shouldn't use the IPC binary encoding format for history, + // and we should come up with a migration strategy so we can actually bump the version number + // without breaking encoding/decoding of the history tree. + + uint32_t length; + if (!m_decoder.decode(length)) + return false; + + if (length == std::numeric_limits<uint32_t>::max()) { + // This is the null string. + value = String(); + return true; + } + + uint64_t lengthInBytes; + if (!m_decoder.decode(lengthInBytes)) + return false; + + if (lengthInBytes % sizeof(UChar) || lengthInBytes / sizeof(UChar) != length) { + m_decoder.markInvalid(); + return false; + } + + if (!m_decoder.bufferIsLargeEnoughToContain<UChar>(length)) { + m_decoder.markInvalid(); + return false; + } + + UChar* buffer; + String string = String::createUninitialized(length, buffer); + if (!m_decoder.decodeFixedLengthData(reinterpret_cast<uint8_t*>(buffer), length * sizeof(UChar), alignof(UChar))) + return false; + + value = string; + return true; +} + +} // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/WebInspectorFrontendAPIDispatcher.h b/Source/WebKit2/WebProcess/WebPage/DecoderAdapter.h index 97b73d181..a0e4c40b9 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebInspectorFrontendAPIDispatcher.h +++ b/Source/WebKit2/WebProcess/WebPage/DecoderAdapter.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. + * Copyright (C) 2011 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,36 +23,34 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebInspectorFrontendAPIDispatcher_h -#define WebInspectorFrontendAPIDispatcher_h +#ifndef DecoderAdapter_h +#define DecoderAdapter_h -#include <wtf/Deque.h> -#include <wtf/text/WTFString.h> +#include "ArgumentDecoder.h" +#include <wtf/Decoder.h> +#include <wtf/Forward.h> namespace WebKit { -class WebPage; - -class WebInspectorFrontendAPIDispatcher { +class DecoderAdapter : public Decoder { public: - WebInspectorFrontendAPIDispatcher(WebPage& page); - - void reset(); - void frontendLoaded(); - - void dispatchCommand(const String& command); - void dispatchCommand(const String& command, const String& argument); - void dispatchCommand(const String& command, bool argument); - void dispatchMessageAsync(const String& message); + DecoderAdapter(const uint8_t* buffer, size_t bufferSize); private: - void evaluateExpressionOnLoad(const String& expression); - - WebPage& m_page; - Deque<String> m_queue; - bool m_frontendLoaded { false }; + virtual bool decodeBytes(Vector<uint8_t>&); + virtual bool decodeBool(bool&); + virtual bool decodeUInt16(uint16_t&); + virtual bool decodeUInt32(uint32_t&); + virtual bool decodeUInt64(uint64_t&); + virtual bool decodeInt32(int32_t&); + virtual bool decodeInt64(int64_t&); + virtual bool decodeFloat(float&); + virtual bool decodeDouble(double&); + virtual bool decodeString(String&); + + IPC::ArgumentDecoder m_decoder; }; } // namespace WebKit -#endif // WebInspectorFrontendAPIDispatcher_h +#endif // DecoderAdapter_h diff --git a/Source/WebKit2/WebProcess/WebPage/DrawingArea.cpp b/Source/WebKit2/WebProcess/WebPage/DrawingArea.cpp index c103e3fff..e4750e6c2 100644 --- a/Source/WebKit2/WebProcess/WebPage/DrawingArea.cpp +++ b/Source/WebKit2/WebProcess/WebPage/DrawingArea.cpp @@ -25,34 +25,28 @@ #include "config.h" #include "DrawingArea.h" - -#include "DrawingAreaMessages.h" -#include "WebPage.h" -#include "WebPageCreationParameters.h" -#include "WebProcess.h" -#include <WebCore/DisplayRefreshMonitor.h> -#include <WebCore/TransformationMatrix.h> +#include <wtf/Functional.h> // Subclasses -#if PLATFORM(COCOA) +#if PLATFORM(MAC) #include "RemoteLayerTreeDrawingArea.h" #include "TiledCoreAnimationDrawingArea.h" #else -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) +#if USE(COORDINATED_GRAPHICS) #include "CoordinatedDrawingArea.h" #else #include "DrawingAreaImpl.h" #endif #endif -using namespace WebCore; +#include "WebPageCreationParameters.h" namespace WebKit { -std::unique_ptr<DrawingArea> DrawingArea::create(WebPage& webPage, const WebPageCreationParameters& parameters) +std::unique_ptr<DrawingArea> DrawingArea::create(WebPage* webPage, const WebPageCreationParameters& parameters) { switch (parameters.drawingAreaType) { -#if PLATFORM(COCOA) +#if PLATFORM(MAC) #if !PLATFORM(IOS) case DrawingAreaTypeTiledCoreAnimation: return std::make_unique<TiledCoreAnimationDrawingArea>(webPage, parameters); @@ -60,7 +54,7 @@ std::unique_ptr<DrawingArea> DrawingArea::create(WebPage& webPage, const WebPage case DrawingAreaTypeRemoteLayerTree: return std::make_unique<RemoteLayerTreeDrawingArea>(webPage, parameters); #else -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) +#if USE(COORDINATED_GRAPHICS) case DrawingAreaTypeCoordinated: return std::make_unique<CoordinatedDrawingArea>(webPage, parameters); #else @@ -73,19 +67,14 @@ std::unique_ptr<DrawingArea> DrawingArea::create(WebPage& webPage, const WebPage return nullptr; } -DrawingArea::DrawingArea(DrawingAreaType type, WebPage& webPage) +DrawingArea::DrawingArea(DrawingAreaType type, WebPage* webPage) : m_type(type) , m_webPage(webPage) -#if USE(TEXTURE_MAPPER) && PLATFORM(GTK) - , m_nativeSurfaceHandleForCompositing(0) -#endif { - WebProcess::singleton().addMessageReceiver(Messages::DrawingArea::messageReceiverName(), m_webPage.pageID(), *this); } DrawingArea::~DrawingArea() { - WebProcess::singleton().removeMessageReceiver(Messages::DrawingArea::messageReceiverName(), m_webPage.pageID()); } void DrawingArea::dispatchAfterEnsuringUpdatedScrollPosition(std::function<void ()> function) @@ -94,11 +83,4 @@ void DrawingArea::dispatchAfterEnsuringUpdatedScrollPosition(std::function<void function(); } -#if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR) -RefPtr<WebCore::DisplayRefreshMonitor> DrawingArea::createDisplayRefreshMonitor(PlatformDisplayID) -{ - return nullptr; -} -#endif - } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/DrawingArea.h b/Source/WebKit2/WebProcess/WebPage/DrawingArea.h index 3cea535d2..adf7c5cc8 100644 --- a/Source/WebKit2/WebProcess/WebPage/DrawingArea.h +++ b/Source/WebKit2/WebProcess/WebPage/DrawingArea.h @@ -28,17 +28,12 @@ #include "DrawingAreaInfo.h" #include "LayerTreeContext.h" -#include "MessageReceiver.h" #include <WebCore/FloatRect.h> #include <WebCore/IntRect.h> -#include <WebCore/LayerFlushThrottleState.h> -#include <WebCore/LayoutMilestones.h> -#include <WebCore/PlatformScreen.h> #include <WebCore/ViewState.h> #include <functional> #include <wtf/Forward.h> #include <wtf/Noncopyable.h> -#include <wtf/TypeCasts.h> namespace IPC { class Connection; @@ -46,30 +41,30 @@ class MessageDecoder; } namespace WebCore { -class DisplayRefreshMonitor; -class Frame; class FrameView; class GraphicsLayer; class GraphicsLayerFactory; -class MachSendRight; } namespace WebKit { struct ColorSpaceData; class LayerTreeHost; +class PageOverlay; class WebPage; struct WebPageCreationParameters; struct WebPreferencesStore; -class DrawingArea : public IPC::MessageReceiver { +class DrawingArea { WTF_MAKE_NONCOPYABLE(DrawingArea); public: - static std::unique_ptr<DrawingArea> create(WebPage&, const WebPageCreationParameters&); + static std::unique_ptr<DrawingArea> create(WebPage*, const WebPageCreationParameters&); virtual ~DrawingArea(); DrawingAreaType type() const { return m_type; } + + void didReceiveDrawingAreaMessage(IPC::Connection*, IPC::MessageDecoder&); virtual void setNeedsDisplay() = 0; virtual void setNeedsDisplayInRect(const WebCore::IntRect&) = 0; @@ -83,103 +78,71 @@ public: virtual bool layerTreeStateIsFrozen() const { return false; } virtual LayerTreeHost* layerTreeHost() const { return 0; } + virtual void didInstallPageOverlay(PageOverlay*) { } + virtual void didUninstallPageOverlay(PageOverlay*) { } + virtual void setPageOverlayNeedsDisplay(PageOverlay*, const WebCore::IntRect&) { } + virtual void setPageOverlayOpacity(PageOverlay*, float) { } + virtual void clearPageOverlay(PageOverlay*) { } + virtual void setPaintingEnabled(bool) { } virtual void updatePreferences(const WebPreferencesStore&) { } virtual void mainFrameContentSizeChanged(const WebCore::IntSize&) { } -#if PLATFORM(COCOA) +#if PLATFORM(MAC) virtual void setExposedRect(const WebCore::FloatRect&) = 0; virtual WebCore::FloatRect exposedRect() const = 0; - virtual void acceleratedAnimationDidStart(uint64_t /*layerID*/, const String& /*key*/, double /*startTime*/) { } - virtual void acceleratedAnimationDidEnd(uint64_t /*layerID*/, const String& /*key*/) { } - virtual void addFence(const WebCore::MachSendRight&) { } -#endif -#if PLATFORM(IOS) - virtual WebCore::FloatRect exposedContentRect() const = 0; - virtual void setExposedContentRect(const WebCore::FloatRect&) = 0; + virtual void setCustomFixedPositionRect(const WebCore::FloatRect&) = 0; #endif virtual void mainFrameScrollabilityChanged(bool) { } virtual bool supportsAsyncScrolling() { return false; } + virtual void didChangeScrollOffsetForAnyFrame() { } + virtual bool shouldUseTiledBackingForFrameView(const WebCore::FrameView*) { return false; } - virtual WebCore::GraphicsLayerFactory* graphicsLayerFactory() { return nullptr; } +#if USE(ACCELERATED_COMPOSITING) + virtual WebCore::GraphicsLayerFactory* graphicsLayerFactory() { return 0; } virtual void setRootCompositingLayer(WebCore::GraphicsLayer*) = 0; virtual void scheduleCompositingLayerFlush() = 0; - virtual void scheduleCompositingLayerFlushImmediately() = 0; - -#if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR) - virtual RefPtr<WebCore::DisplayRefreshMonitor> createDisplayRefreshMonitor(PlatformDisplayID); #endif -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) - virtual void didReceiveCoordinatedLayerTreeHostMessage(IPC::Connection&, IPC::MessageDecoder&) = 0; +#if USE(COORDINATED_GRAPHICS) + virtual void didReceiveCoordinatedLayerTreeHostMessage(IPC::Connection*, IPC::MessageDecoder&) = 0; #endif virtual void dispatchAfterEnsuringUpdatedScrollPosition(std::function<void ()>); - virtual void viewStateDidChange(WebCore::ViewState::Flags, bool /* wantsDidUpdateViewState */, const Vector<uint64_t>& /* callbackIDs */) { } + virtual void viewStateDidChange(WebCore::ViewState::Flags) { } virtual void setLayerHostingMode(LayerHostingMode) { } - virtual bool markLayersVolatileImmediatelyIfPossible() { return true; } - - virtual bool adjustLayerFlushThrottling(WebCore::LayerFlushThrottleState::Flags) { return false; } - - virtual void attachViewOverlayGraphicsLayer(WebCore::Frame*, WebCore::GraphicsLayer*) { } - - virtual void setShouldScaleViewToFitDocument(bool) { } - - virtual bool dispatchDidLayout(WebCore::LayoutMilestones) { return false; } - -#if PLATFORM(COCOA) - // Used by TiledCoreAnimationDrawingArea. - virtual void updateGeometry(const WebCore::IntSize& viewSize, const WebCore::IntSize& layerPosition, bool flushSynchronously, const WebCore::MachSendRight& fencePort) { } -#endif - protected: - DrawingArea(DrawingAreaType, WebPage&); + DrawingArea(DrawingAreaType, WebPage*); DrawingAreaType m_type; - WebPage& m_webPage; - -#if USE(TEXTURE_MAPPER) && PLATFORM(GTK) - uint64_t m_nativeSurfaceHandleForCompositing; -#endif + WebPage* m_webPage; private: - // IPC::MessageReceiver. - virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; - virtual void didReceiveSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&) override; - // Message handlers. // FIXME: These should be pure virtual. virtual void updateBackingStoreState(uint64_t /*backingStoreStateID*/, bool /*respondImmediately*/, float /*deviceScaleFactor*/, const WebCore::IntSize& /*size*/, const WebCore::IntSize& /*scrollOffset*/) { } virtual void didUpdate() { } -#if PLATFORM(COCOA) +#if PLATFORM(MAC) // Used by TiledCoreAnimationDrawingArea. + virtual void updateGeometry(const WebCore::IntSize& viewSize, const WebCore::IntSize& layerPosition) { } virtual void setDeviceScaleFactor(float) { } virtual void setColorSpace(const ColorSpaceData&) { } virtual void adjustTransientZoom(double scale, WebCore::FloatPoint origin) { } virtual void commitTransientZoom(double scale, WebCore::FloatPoint origin) { } - - virtual void addTransactionCallbackID(uint64_t callbackID) { ASSERT_NOT_REACHED(); } -#endif - -#if USE(TEXTURE_MAPPER) && PLATFORM(GTK) - virtual void setNativeSurfaceHandleForCompositing(uint64_t) = 0; - virtual void destroyNativeSurfaceHandleForCompositing(bool&) = 0; #endif }; -} // namespace WebKit +#define DRAWING_AREA_TYPE_CASTS(ToValueTypeName, predicate) \ + TYPE_CASTS_BASE(ToValueTypeName, DrawingArea, value, value->predicate, value.predicate) -#define SPECIALIZE_TYPE_TRAITS_DRAWING_AREA(ToValueTypeName, AreaType) \ -SPECIALIZE_TYPE_TRAITS_BEGIN(WebKit::ToValueTypeName) \ - static bool isType(const WebKit::DrawingArea& area) { return area.type() == WebKit::AreaType; } \ -SPECIALIZE_TYPE_TRAITS_END() +} // namespace WebKit #endif // DrawingArea_h diff --git a/Source/WebKit2/WebProcess/WebPage/DrawingArea.messages.in b/Source/WebKit2/WebProcess/WebPage/DrawingArea.messages.in index 909771d62..f4b8286a5 100644 --- a/Source/WebKit2/WebProcess/WebPage/DrawingArea.messages.in +++ b/Source/WebKit2/WebProcess/WebPage/DrawingArea.messages.in @@ -20,28 +20,19 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -messages -> DrawingArea { +messages -> DrawingArea LegacyReceiver { UpdateBackingStoreState(uint64_t backingStoreStateID, bool respondImmediately, float deviceScaleFactor, WebCore::IntSize size, WebCore::IntSize scrollOffset) DidUpdate() -#if PLATFORM(COCOA) +#if PLATFORM(MAC) // Used by TiledCoreAnimationDrawingArea. - UpdateGeometry(WebCore::IntSize viewSize, WebCore::IntSize layerPosition, bool flushSynchronously, WebCore::MachSendRight fencePort) + UpdateGeometry(WebCore::IntSize viewSize, WebCore::IntSize layerPosition) SetDeviceScaleFactor(float deviceScaleFactor) - SetColorSpace(struct WebKit::ColorSpaceData colorSpace) + SetColorSpace(WebKit::ColorSpaceData colorSpace) SetExposedRect(WebCore::FloatRect exposedRect) + SetCustomFixedPositionRect(WebCore::FloatRect fixedPositionRect) AdjustTransientZoom(double scale, WebCore::FloatPoint origin) CommitTransientZoom(double scale, WebCore::FloatPoint origin) - - AcceleratedAnimationDidStart(uint64_t layerID, String key, double startTime) - AcceleratedAnimationDidEnd(uint64_t layerID, String key) - - AddTransactionCallbackID(uint64_t callbackID) -#endif - -#if USE(TEXTURE_MAPPER) && PLATFORM(GTK) - SetNativeSurfaceHandleForCompositing(uint64_t handle) - DestroyNativeSurfaceHandleForCompositing() -> (bool handled) #endif } diff --git a/Source/WebKit2/WebProcess/WebPage/DrawingAreaImpl.cpp b/Source/WebKit2/WebProcess/WebPage/DrawingAreaImpl.cpp index 825c76585..0abead9b7 100644 --- a/Source/WebKit2/WebProcess/WebPage/DrawingAreaImpl.cpp +++ b/Source/WebKit2/WebProcess/WebPage/DrawingAreaImpl.cpp @@ -32,10 +32,8 @@ #include "UpdateInfo.h" #include "WebPage.h" #include "WebPageCreationParameters.h" -#include "WebPreferencesKeys.h" #include "WebProcess.h" #include <WebCore/GraphicsContext.h> -#include <WebCore/MainFrame.h> #include <WebCore/Page.h> #include <WebCore/Settings.h> @@ -49,12 +47,8 @@ DrawingAreaImpl::~DrawingAreaImpl() m_layerTreeHost->invalidate(); } -DrawingAreaImpl::DrawingAreaImpl(WebPage& webPage, const WebPageCreationParameters& parameters) -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) - : DrawingArea(DrawingAreaTypeCoordinated, webPage) -#else +DrawingAreaImpl::DrawingAreaImpl(WebPage* webPage, const WebPageCreationParameters& parameters) : DrawingArea(DrawingAreaTypeImpl, webPage) -#endif , m_backingStoreStateID(0) , m_isPaintingEnabled(true) , m_inUpdateBackingStoreState(false) @@ -68,6 +62,11 @@ DrawingAreaImpl::DrawingAreaImpl(WebPage& webPage, const WebPageCreationParamete , m_displayTimer(RunLoop::main(), this, &DrawingAreaImpl::displayTimerFired) , m_exitCompositingTimer(RunLoop::main(), this, &DrawingAreaImpl::exitAcceleratedCompositingMode) { + if (webPage->corePage()->settings().acceleratedDrawingEnabled() || webPage->corePage()->settings().forceCompositingMode()) + m_alwaysUseCompositing = true; + + if (m_alwaysUseCompositing) + enterAcceleratedCompositingMode(0); } void DrawingAreaImpl::setNeedsDisplay() @@ -81,7 +80,7 @@ void DrawingAreaImpl::setNeedsDisplay() return; } - setNeedsDisplayInRect(m_webPage.bounds()); + setNeedsDisplayInRect(m_webPage->bounds()); } void DrawingAreaImpl::setNeedsDisplayInRect(const IntRect& rect) @@ -96,7 +95,7 @@ void DrawingAreaImpl::setNeedsDisplayInRect(const IntRect& rect) } IntRect dirtyRect = rect; - dirtyRect.intersect(m_webPage.bounds()); + dirtyRect.intersect(m_webPage->bounds()); if (dirtyRect.isEmpty()) return; @@ -187,15 +186,9 @@ void DrawingAreaImpl::setLayerTreeStateIsFrozen(bool isFrozen) void DrawingAreaImpl::forceRepaint() { - if (m_inUpdateBackingStoreState) { - m_forceRepaintAfterBackingStoreStateUpdate = true; - return; - } - - m_forceRepaintAfterBackingStoreStateUpdate = false; setNeedsDisplay(); - m_webPage.layoutIfNeeded(); + m_webPage->layoutIfNeeded(); if (m_layerTreeHost) { // FIXME: We need to do the same work as the layerHostDidFlushLayers function here, @@ -221,36 +214,44 @@ bool DrawingAreaImpl::forceRepaintAsync(uint64_t callbackID) return m_layerTreeHost && m_layerTreeHost->forceRepaintAsync(callbackID); } -void DrawingAreaImpl::setPaintingEnabled(bool paintingEnabled) +void DrawingAreaImpl::didInstallPageOverlay(PageOverlay* pageOverlay) { - m_isPaintingEnabled = paintingEnabled; + if (m_layerTreeHost) + m_layerTreeHost->didInstallPageOverlay(pageOverlay); } -void DrawingAreaImpl::mainFrameContentSizeChanged(const WebCore::IntSize& newSize) +void DrawingAreaImpl::didUninstallPageOverlay(PageOverlay* pageOverlay) { -#if USE(COORDINATED_GRAPHICS_THREADED) if (m_layerTreeHost) - m_layerTreeHost->sizeDidChange(newSize); -#else - UNUSED_PARAM(newSize); -#endif + m_layerTreeHost->didUninstallPageOverlay(pageOverlay); + + setNeedsDisplay(); } -void DrawingAreaImpl::updatePreferences(const WebPreferencesStore& store) +void DrawingAreaImpl::setPageOverlayNeedsDisplay(PageOverlay* pageOverlay, const IntRect& rect) { - Settings& settings = m_webPage.corePage()->settings(); - settings.setForceCompositingMode(store.getBoolValueForKey(WebPreferencesKey::forceCompositingModeKey())); + if (m_layerTreeHost) { + m_layerTreeHost->setPageOverlayNeedsDisplay(pageOverlay, rect); + return; + } -#if USE(COORDINATED_GRAPHICS_THREADED) - // Fixed position elements need to be composited and create stacking contexts - // in order to be scrolled by the ScrollingCoordinator. - settings.setAcceleratedCompositingForFixedPositionEnabled(true); - settings.setFixedPositionCreatesStackingContext(true); -#endif + setNeedsDisplayInRect(rect); +} - m_alwaysUseCompositing = settings.acceleratedDrawingEnabled() && settings.forceCompositingMode(); - if (m_alwaysUseCompositing && !m_layerTreeHost) - enterAcceleratedCompositingMode(nullptr); +void DrawingAreaImpl::setPageOverlayOpacity(PageOverlay* pageOverlay, float value) +{ + if (m_layerTreeHost) + m_layerTreeHost->setPageOverlayOpacity(pageOverlay, value); +} + +void DrawingAreaImpl::setPaintingEnabled(bool paintingEnabled) +{ + m_isPaintingEnabled = paintingEnabled; +} + +void DrawingAreaImpl::updatePreferences(const WebPreferencesStore& store) +{ + m_webPage->corePage()->settings().setForceCompositingMode(store.getBoolValueForKey(WebPreferencesKey::forceCompositingModeKey()) && LayerTreeHost::supportsAcceleratedCompositing()); } void DrawingAreaImpl::layerHostDidFlushLayers() @@ -267,13 +268,16 @@ void DrawingAreaImpl::layerHostDidFlushLayers() if (!m_layerTreeHost) return; +#if USE(ACCELERATED_COMPOSITING) ASSERT(!m_compositingAccordingToProxyMessages); if (!exitAcceleratedCompositingModePending()) { - m_webPage.send(Messages::DrawingAreaProxy::EnterAcceleratedCompositingMode(m_backingStoreStateID, m_layerTreeHost->layerTreeContext())); + m_webPage->send(Messages::DrawingAreaProxy::EnterAcceleratedCompositingMode(m_backingStoreStateID, m_layerTreeHost->layerTreeContext())); m_compositingAccordingToProxyMessages = true; } +#endif } +#if USE(ACCELERATED_COMPOSITING) GraphicsLayerFactory* DrawingAreaImpl::graphicsLayerFactory() { if (m_layerTreeHost) @@ -328,11 +332,7 @@ void DrawingAreaImpl::scheduleCompositingLayerFlush() return; m_layerTreeHost->scheduleLayerFlush(); } - -void DrawingAreaImpl::scheduleCompositingLayerFlushImmediately() -{ - scheduleCompositingLayerFlush(); -} +#endif void DrawingAreaImpl::updateBackingStoreState(uint64_t stateID, bool respondImmediately, float deviceScaleFactor, const WebCore::IntSize& size, const WebCore::IntSize& scrollOffset) { @@ -344,21 +344,17 @@ void DrawingAreaImpl::updateBackingStoreState(uint64_t stateID, bool respondImme m_backingStoreStateID = stateID; m_shouldSendDidUpdateBackingStoreState = true; - m_webPage.setDeviceScaleFactor(deviceScaleFactor); - m_webPage.setSize(size); - m_webPage.layoutIfNeeded(); - m_webPage.scrollMainFrameIfNotAtMaxScrollPosition(scrollOffset); + m_webPage->setDeviceScaleFactor(deviceScaleFactor); + m_webPage->setSize(size); + m_webPage->layoutIfNeeded(); + m_webPage->scrollMainFrameIfNotAtMaxScrollPosition(scrollOffset); if (m_layerTreeHost) { -#if USE(COORDINATED_GRAPHICS_THREADED) - m_layerTreeHost->viewportSizeChanged(m_webPage.size()); -#else - m_layerTreeHost->sizeDidChange(m_webPage.size()); -#endif + m_layerTreeHost->sizeDidChange(m_webPage->size()); } else - m_dirtyRegion = m_webPage.bounds(); + m_dirtyRegion = m_webPage->bounds(); } else { - ASSERT(size == m_webPage.size()); + ASSERT(size == m_webPage->size()); if (!m_shouldSendDidUpdateBackingStoreState) { // We've already sent a DidUpdateBackingStoreState message for this state. We have nothing more to do. m_inUpdateBackingStoreState = false; @@ -383,8 +379,6 @@ void DrawingAreaImpl::updateBackingStoreState(uint64_t stateID, bool respondImme } m_inUpdateBackingStoreState = false; - if (m_forceRepaintAfterBackingStoreStateUpdate) - forceRepaint(); } void DrawingAreaImpl::sendDidUpdateBackingStoreState() @@ -402,8 +396,8 @@ void DrawingAreaImpl::sendDidUpdateBackingStoreState() LayerTreeContext layerTreeContext; if (m_isPaintingSuspended || m_layerTreeHost) { - updateInfo.viewSize = m_webPage.size(); - updateInfo.deviceScaleFactor = m_webPage.corePage()->deviceScaleFactor(); + updateInfo.viewSize = m_webPage->size(); + updateInfo.deviceScaleFactor = m_webPage->corePage()->deviceScaleFactor(); if (m_layerTreeHost) { layerTreeContext = m_layerTreeHost->layerTreeContext(); @@ -417,7 +411,7 @@ void DrawingAreaImpl::sendDidUpdateBackingStoreState() } } - m_webPage.send(Messages::DrawingAreaProxy::DidUpdateBackingStoreState(m_backingStoreStateID, updateInfo, layerTreeContext)); + m_webPage->send(Messages::DrawingAreaProxy::DidUpdateBackingStoreState(m_backingStoreStateID, updateInfo, layerTreeContext)); m_compositingAccordingToProxyMessages = !layerTreeContext.isEmpty(); } @@ -467,15 +461,9 @@ void DrawingAreaImpl::enterAcceleratedCompositingMode(GraphicsLayer* graphicsLay m_exitCompositingTimer.stop(); m_wantsToExitAcceleratedCompositingMode = false; - m_webPage.send(Messages::DrawingAreaProxy::WillEnterAcceleratedCompositingMode(m_backingStoreStateID)); - ASSERT(!m_layerTreeHost); - m_layerTreeHost = LayerTreeHost::create(&m_webPage); -#if USE(TEXTURE_MAPPER) && PLATFORM(GTK) - if (m_nativeSurfaceHandleForCompositing) - m_layerTreeHost->setNativeSurfaceHandleForCompositing(m_nativeSurfaceHandleForCompositing); -#endif + m_layerTreeHost = LayerTreeHost::create(m_webPage); if (!m_inUpdateBackingStoreState) m_layerTreeHost->setShouldNotifyAfterNextScheduledLayerFlush(true); @@ -503,7 +491,7 @@ void DrawingAreaImpl::exitAcceleratedCompositingMode() m_layerTreeHost->invalidate(); m_layerTreeHost = nullptr; - m_dirtyRegion = m_webPage.bounds(); + m_dirtyRegion = m_webPage->bounds(); if (m_inUpdateBackingStoreState) return; @@ -515,21 +503,23 @@ void DrawingAreaImpl::exitAcceleratedCompositingMode() UpdateInfo updateInfo; if (m_isPaintingSuspended) { - updateInfo.viewSize = m_webPage.size(); - updateInfo.deviceScaleFactor = m_webPage.corePage()->deviceScaleFactor(); + updateInfo.viewSize = m_webPage->size(); + updateInfo.deviceScaleFactor = m_webPage->corePage()->deviceScaleFactor(); } else display(updateInfo); +#if USE(ACCELERATED_COMPOSITING) // Send along a complete update of the page so we can paint the contents right after we exit the // accelerated compositing mode, eliminiating flicker. if (m_compositingAccordingToProxyMessages) { - m_webPage.send(Messages::DrawingAreaProxy::ExitAcceleratedCompositingMode(m_backingStoreStateID, updateInfo)); + m_webPage->send(Messages::DrawingAreaProxy::ExitAcceleratedCompositingMode(m_backingStoreStateID, updateInfo)); m_compositingAccordingToProxyMessages = false; } else { // If we left accelerated compositing mode before we sent an EnterAcceleratedCompositingMode message to the // UI process, we still need to let it know about the new contents, so send an Update message. - m_webPage.send(Messages::DrawingAreaProxy::Update(m_backingStoreStateID, updateInfo)); + m_webPage->send(Messages::DrawingAreaProxy::Update(m_backingStoreStateID, updateInfo)); } +#endif } void DrawingAreaImpl::exitAcceleratedCompositingModeSoon() @@ -595,7 +585,7 @@ void DrawingAreaImpl::display() return; } - m_webPage.send(Messages::DrawingAreaProxy::Update(m_backingStoreStateID, updateInfo)); + m_webPage->send(Messages::DrawingAreaProxy::Update(m_backingStoreStateID, updateInfo)); m_isWaitingForDidUpdate = true; } @@ -624,24 +614,23 @@ void DrawingAreaImpl::display(UpdateInfo& updateInfo) { ASSERT(!m_isPaintingSuspended); ASSERT(!m_layerTreeHost); - ASSERT(!m_webPage.size().isEmpty()); + ASSERT(!m_webPage->size().isEmpty()); - m_webPage.layoutIfNeeded(); + m_webPage->layoutIfNeeded(); // The layout may have put the page into accelerated compositing mode. If the LayerTreeHost is // in charge of displaying, we have nothing more to do. if (m_layerTreeHost) return; - updateInfo.viewSize = m_webPage.size(); - updateInfo.deviceScaleFactor = m_webPage.corePage()->deviceScaleFactor(); + updateInfo.viewSize = m_webPage->size(); + updateInfo.deviceScaleFactor = m_webPage->corePage()->deviceScaleFactor(); - // Always render the whole page when we don't render the background. - IntRect bounds = m_webPage.drawsBackground() ? m_dirtyRegion.bounds() : m_webPage.bounds(); - ASSERT(m_webPage.bounds().contains(bounds)); + IntRect bounds = m_dirtyRegion.bounds(); + ASSERT(m_webPage->bounds().contains(bounds)); IntSize bitmapSize = bounds.size(); - float deviceScaleFactor = m_webPage.corePage()->deviceScaleFactor(); + float deviceScaleFactor = m_webPage->corePage()->deviceScaleFactor(); bitmapSize.scale(deviceScaleFactor); RefPtr<ShareableBitmap> bitmap = ShareableBitmap::createShareable(bitmapSize, ShareableBitmap::SupportsAlpha); if (!bitmap) @@ -650,16 +639,12 @@ void DrawingAreaImpl::display(UpdateInfo& updateInfo) if (!bitmap->createHandle(updateInfo.bitmapHandle)) return; - Vector<IntRect> rects; - if (m_webPage.drawsBackground()) { - rects = m_dirtyRegion.rects(); + Vector<IntRect> rects = m_dirtyRegion.rects(); - if (shouldPaintBoundsRect(bounds, rects)) { - rects.clear(); - rects.append(bounds); - } - } else + if (shouldPaintBoundsRect(bounds, rects)) { + rects.clear(); rects.append(bounds); + } updateInfo.scrollRect = m_scrollRect; updateInfo.scrollOffset = m_scrollOffset; @@ -675,9 +660,17 @@ void DrawingAreaImpl::display(UpdateInfo& updateInfo) graphicsContext->translate(-bounds.x(), -bounds.y()); - for (const auto& rect : rects) { - m_webPage.drawRect(*graphicsContext, rect); - updateInfo.updateRects.append(rect); + for (size_t i = 0; i < rects.size(); ++i) { + m_webPage->drawRect(*graphicsContext, rects[i]); + + if (m_webPage->hasPageOverlay()) { + PageOverlayList& pageOverlays = m_webPage->pageOverlays(); + PageOverlayList::iterator end = pageOverlays.end(); + for (PageOverlayList::iterator it = pageOverlays.begin(); it != end; ++it) + m_webPage->drawPageOverlay(it->get(), *graphicsContext, rects[i]); + } + + updateInfo.updateRects.append(rects[i]); } // Layout can trigger more calls to setNeedsDisplay and we don't want to process them @@ -685,33 +678,4 @@ void DrawingAreaImpl::display(UpdateInfo& updateInfo) m_displayTimer.stop(); } -void DrawingAreaImpl::attachViewOverlayGraphicsLayer(WebCore::Frame* frame, WebCore::GraphicsLayer* viewOverlayRootLayer) -{ - if (!frame->isMainFrame()) - return; - - if (!m_layerTreeHost) - return; - - m_layerTreeHost->setViewOverlayRootLayer(viewOverlayRootLayer); -} - -#if USE(TEXTURE_MAPPER) && PLATFORM(GTK) -void DrawingAreaImpl::setNativeSurfaceHandleForCompositing(uint64_t handle) -{ - m_nativeSurfaceHandleForCompositing = handle; - - if (m_layerTreeHost) { - m_webPage.corePage()->settings().setAcceleratedCompositingEnabled(true); - m_layerTreeHost->setNativeSurfaceHandleForCompositing(handle); - } -} - -void DrawingAreaImpl::destroyNativeSurfaceHandleForCompositing(bool& handled) -{ - handled = true; - setNativeSurfaceHandleForCompositing(0); -} -#endif - } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/DrawingAreaImpl.h b/Source/WebKit2/WebProcess/WebPage/DrawingAreaImpl.h index 52a333412..f327e2074 100644 --- a/Source/WebKit2/WebProcess/WebPage/DrawingAreaImpl.h +++ b/Source/WebKit2/WebProcess/WebPage/DrawingAreaImpl.h @@ -42,7 +42,7 @@ class UpdateInfo; class DrawingAreaImpl : public DrawingArea { public: - DrawingAreaImpl(WebPage&, const WebPageCreationParameters&); + DrawingAreaImpl(WebPage*, const WebPageCreationParameters&); virtual ~DrawingAreaImpl(); void layerHostDidFlushLayers(); @@ -51,33 +51,31 @@ private: // DrawingArea virtual void setNeedsDisplay() override; virtual void setNeedsDisplayInRect(const WebCore::IntRect&) override; - virtual void scroll(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollDelta) override; + virtual void scroll(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollDelta); virtual void pageBackgroundTransparencyChanged() override; - virtual void setLayerTreeStateIsFrozen(bool) override; - virtual bool layerTreeStateIsFrozen() const override { return m_layerTreeStateIsFrozen; } - virtual LayerTreeHost* layerTreeHost() const override { return m_layerTreeHost.get(); } - virtual void forceRepaint() override; - virtual bool forceRepaintAsync(uint64_t callbackID) override; - - virtual void setPaintingEnabled(bool) override; - virtual void mainFrameContentSizeChanged(const WebCore::IntSize&) override; + virtual void setLayerTreeStateIsFrozen(bool); + virtual bool layerTreeStateIsFrozen() const { return m_layerTreeStateIsFrozen; } + virtual LayerTreeHost* layerTreeHost() const { return m_layerTreeHost.get(); } + virtual void forceRepaint(); + virtual bool forceRepaintAsync(uint64_t callbackID); + + virtual void didInstallPageOverlay(PageOverlay*); + virtual void didUninstallPageOverlay(PageOverlay*); + virtual void setPageOverlayNeedsDisplay(PageOverlay*, const WebCore::IntRect&); + virtual void setPageOverlayOpacity(PageOverlay*, float); + + virtual void setPaintingEnabled(bool); virtual void updatePreferences(const WebPreferencesStore&) override; +#if USE(ACCELERATED_COMPOSITING) virtual WebCore::GraphicsLayerFactory* graphicsLayerFactory() override; virtual void setRootCompositingLayer(WebCore::GraphicsLayer*) override; virtual void scheduleCompositingLayerFlush() override; - virtual void scheduleCompositingLayerFlushImmediately() override; - - virtual void attachViewOverlayGraphicsLayer(WebCore::Frame*, WebCore::GraphicsLayer*) override; - -#if USE(TEXTURE_MAPPER) && PLATFORM(GTK) - virtual void setNativeSurfaceHandleForCompositing(uint64_t) override; - virtual void destroyNativeSurfaceHandleForCompositing(bool&) override; #endif // IPC message handlers. - virtual void updateBackingStoreState(uint64_t backingStoreStateID, bool respondImmediately, float deviceScaleFactor, const WebCore::IntSize&, const WebCore::IntSize& scrollOffset) override; - virtual void didUpdate() override; + virtual void updateBackingStoreState(uint64_t backingStoreStateID, bool respondImmediately, float deviceScaleFactor, const WebCore::IntSize&, const WebCore::IntSize& scrollOffset); + virtual void didUpdate(); virtual void suspendPainting(); virtual void resumePainting(); @@ -129,8 +127,6 @@ private: bool m_isPaintingSuspended; bool m_alwaysUseCompositing; - bool m_forceRepaintAfterBackingStoreStateUpdate { false }; - RunLoop::Timer<DrawingAreaImpl> m_displayTimer; RunLoop::Timer<DrawingAreaImpl> m_exitCompositingTimer; diff --git a/Source/WebKit2/WebProcess/WebPage/EncoderAdapter.cpp b/Source/WebKit2/WebProcess/WebPage/EncoderAdapter.cpp new file mode 100644 index 000000000..38ec1dc81 --- /dev/null +++ b/Source/WebKit2/WebProcess/WebPage/EncoderAdapter.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "EncoderAdapter.h" + +#include "DataReference.h" +#include "WebCoreArgumentCoders.h" +#include <wtf/text/WTFString.h> + +namespace WebKit { + +EncoderAdapter::EncoderAdapter() +{ + // Keep format compatibility by decoding an unused uint64_t value + // that used to be encoded by the argument encoder. + m_encoder << static_cast<uint64_t>(0); +} + +IPC::DataReference EncoderAdapter::dataReference() const +{ + return IPC::DataReference(m_encoder.buffer(), m_encoder.bufferSize()); +} + +void EncoderAdapter::encodeBytes(const uint8_t* bytes, size_t size) +{ + m_encoder << IPC::DataReference(bytes, size); +} + +void EncoderAdapter::encodeBool(bool value) +{ + m_encoder << value; +} + +void EncoderAdapter::encodeUInt16(uint16_t value) +{ + m_encoder << value; +} + +void EncoderAdapter::encodeUInt32(uint32_t value) +{ + m_encoder << value; +} + +void EncoderAdapter::encodeUInt64(uint64_t value) +{ + m_encoder << value; +} + +void EncoderAdapter::encodeInt32(int32_t value) +{ + m_encoder << value; +} + +void EncoderAdapter::encodeInt64(int64_t value) +{ + m_encoder << value; +} + +void EncoderAdapter::encodeFloat(float value) +{ + m_encoder << value; +} + +void EncoderAdapter::encodeDouble(double value) +{ + m_encoder << value; +} + +void EncoderAdapter::encodeString(const String& value) +{ + // This mimics the IPC binary encoding of Strings prior to r88886. + // Whenever the IPC binary encoding changes, we'll have to "undo" the changes here. + // FIXME: We shouldn't use the IPC binary encoding format for history, + // and we should come up with a migration strategy so we can actually bump the version number + // without breaking encoding/decoding of the history tree. + + // Special case the null string. + if (value.isNull()) { + m_encoder << std::numeric_limits<uint32_t>::max(); + return; + } + + uint32_t length = value.length(); + m_encoder << length; + + uint64_t lengthInBytes = length * sizeof(UChar); + m_encoder << lengthInBytes; + m_encoder.encodeFixedLengthData(reinterpret_cast<const uint8_t*>(value.deprecatedCharacters()), length * sizeof(UChar), alignof(UChar)); +} + +} diff --git a/Source/WebKit2/WebProcess/WebPage/WKAccessibilityWebPageObjectIOS.h b/Source/WebKit2/WebProcess/WebPage/EncoderAdapter.h index da2c6be92..ccddaaaf7 100644 --- a/Source/WebKit2/WebProcess/WebPage/WKAccessibilityWebPageObjectIOS.h +++ b/Source/WebKit2/WebProcess/WebPage/EncoderAdapter.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014 Apple Inc. All rights reserved. + * Copyright (C) 2011 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,19 +23,41 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKAccessibilityWebPageObjectIOS_h -#define WKAccessibilityWebPageObjectIOS_h +#ifndef EncoderAdapter_h +#define EncoderAdapter_h -#if PLATFORM(IOS) +#include "ArgumentEncoder.h" +#include <wtf/Encoder.h> +#include <wtf/Forward.h> -#include "WKAccessibilityWebPageObjectBase.h" +namespace IPC { + class ArgumentEncoder; + class DataReference; +} -@interface WKAccessibilityWebPageObject : WKAccessibilityWebPageObjectBase +namespace WebKit { -@property(nonatomic, retain) NSData *remoteTokenData; +class EncoderAdapter : public Encoder { +public: + EncoderAdapter(); -@end + IPC::DataReference dataReference() const; -#endif // PLATFORM(IOS) +private: + virtual void encodeBytes(const uint8_t*, size_t); + virtual void encodeBool(bool); + virtual void encodeUInt16(uint16_t value); + virtual void encodeUInt32(uint32_t); + virtual void encodeUInt64(uint64_t); + virtual void encodeInt32(int32_t); + virtual void encodeInt64(int64_t); + virtual void encodeFloat(float); + virtual void encodeDouble(double); + virtual void encodeString(const String&); -#endif // WKAccessibilityWebPageObjectIOS_h + IPC::ArgumentEncoder m_encoder; +}; + +} // namespace WebKit + +#endif // EncoderAdapter_h diff --git a/Source/WebKit2/WebProcess/WebPage/EventDispatcher.cpp b/Source/WebKit2/WebProcess/WebPage/EventDispatcher.cpp index b96398ed3..2dc475856 100644 --- a/Source/WebKit2/WebProcess/WebPage/EventDispatcher.cpp +++ b/Source/WebKit2/WebProcess/WebPage/EventDispatcher.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011, 2014-2015 Apple Inc. All rights reserved. + * Copyright (C) 2011 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -33,7 +33,6 @@ #include "WebPageProxyMessages.h" #include "WebProcess.h" #include <WebCore/Page.h> -#include <WebCore/WheelEventTestTrigger.h> #include <wtf/MainThread.h> #include <wtf/RunLoop.h> @@ -47,14 +46,13 @@ using namespace WebCore; namespace WebKit { -Ref<EventDispatcher> EventDispatcher::create() +PassRefPtr<EventDispatcher> EventDispatcher::create() { - return adoptRef(*new EventDispatcher); + return adoptRef(new EventDispatcher); } EventDispatcher::EventDispatcher() - : m_queue(WorkQueue::create("com.apple.WebKit.EventDispatcher", WorkQueue::Type::Serial, WorkQueue::QOS::UserInteractive)) - , m_recentWheelEventDeltaFilter(WheelEventDeltaFilter::create()) + : m_queue(WorkQueue::create("com.apple.WebKit.EventDispatcher")) { } @@ -65,18 +63,18 @@ EventDispatcher::~EventDispatcher() #if ENABLE(ASYNC_SCROLLING) void EventDispatcher::addScrollingTreeForPage(WebPage* webPage) { - LockHolder locker(m_scrollingTreesMutex); + MutexLocker locker(m_scrollingTreesMutex); ASSERT(webPage->corePage()->scrollingCoordinator()); ASSERT(!m_scrollingTrees.contains(webPage->pageID())); - AsyncScrollingCoordinator& scrollingCoordinator = downcast<AsyncScrollingCoordinator>(*webPage->corePage()->scrollingCoordinator()); - m_scrollingTrees.set(webPage->pageID(), downcast<ThreadedScrollingTree>(scrollingCoordinator.scrollingTree())); + AsyncScrollingCoordinator* scrollingCoordinator = toAsyncScrollingCoordinator(webPage->corePage()->scrollingCoordinator()); + m_scrollingTrees.set(webPage->pageID(), toThreadedScrollingTree(scrollingCoordinator->scrollingTree())); } void EventDispatcher::removeScrollingTreeForPage(WebPage* webPage) { - LockHolder locker(m_scrollingTreesMutex); + MutexLocker locker(m_scrollingTreesMutex); ASSERT(m_scrollingTrees.contains(webPage->pageID())); m_scrollingTrees.remove(webPage->pageID()); @@ -85,47 +83,24 @@ void EventDispatcher::removeScrollingTreeForPage(WebPage* webPage) void EventDispatcher::initializeConnection(IPC::Connection* connection) { - connection->addWorkQueueMessageReceiver(Messages::EventDispatcher::messageReceiverName(), &m_queue.get(), this); + connection->addWorkQueueMessageReceiver(Messages::EventDispatcher::messageReceiverName(), m_queue.get(), this); } void EventDispatcher::wheelEvent(uint64_t pageID, const WebWheelEvent& wheelEvent, bool canRubberBandAtLeft, bool canRubberBandAtRight, bool canRubberBandAtTop, bool canRubberBandAtBottom) { - PlatformWheelEvent platformWheelEvent = platform(wheelEvent); - -#if PLATFORM(COCOA) - switch (wheelEvent.phase()) { - case PlatformWheelEventPhaseBegan: - m_recentWheelEventDeltaFilter->beginFilteringDeltas(); - break; - case PlatformWheelEventPhaseEnded: - m_recentWheelEventDeltaFilter->endFilteringDeltas(); - break; - default: - break; - } - - if (m_recentWheelEventDeltaFilter->isFilteringDeltas()) { - m_recentWheelEventDeltaFilter->updateFromDelta(FloatSize(platformWheelEvent.deltaX(), platformWheelEvent.deltaY())); - FloatSize filteredDelta = m_recentWheelEventDeltaFilter->filteredDelta(); - platformWheelEvent = platformWheelEvent.copyWithDeltas(filteredDelta.width(), filteredDelta.height()); - } -#endif - #if ENABLE(ASYNC_SCROLLING) - LockHolder locker(m_scrollingTreesMutex); - if (RefPtr<ThreadedScrollingTree> scrollingTree = m_scrollingTrees.get(pageID)) { + MutexLocker locker(m_scrollingTreesMutex); + if (ThreadedScrollingTree* scrollingTree = m_scrollingTrees.get(pageID)) { + PlatformWheelEvent platformWheelEvent = platform(wheelEvent); + // FIXME: It's pretty horrible that we're updating the back/forward state here. // WebCore should always know the current state and know when it changes so the // scrolling tree can be notified. // We only need to do this at the beginning of the gesture. - if (platformWheelEvent.phase() == PlatformWheelEventPhaseBegan) { - ScrollingThread::dispatch([scrollingTree, canRubberBandAtLeft, canRubberBandAtRight, canRubberBandAtTop, canRubberBandAtBottom] { - scrollingTree->setCanRubberBandState(canRubberBandAtLeft, canRubberBandAtRight, canRubberBandAtTop, canRubberBandAtBottom); - }); - } + if (platformWheelEvent.phase() == PlatformWheelEventPhaseBegan) + ScrollingThread::dispatch(bind(&ThreadedScrollingTree::setCanRubberBandState, scrollingTree, canRubberBandAtLeft, canRubberBandAtRight, canRubberBandAtTop, canRubberBandAtBottom)); ScrollingTree::EventResult result = scrollingTree->tryToHandleWheelEvent(platformWheelEvent); - if (result == ScrollingTree::DidHandleEvent || result == ScrollingTree::DidNotHandleEvent) { sendDidReceiveEvent(pageID, wheelEvent, result == ScrollingTree::DidHandleEvent); return; @@ -138,109 +113,24 @@ void EventDispatcher::wheelEvent(uint64_t pageID, const WebWheelEvent& wheelEven UNUSED_PARAM(canRubberBandAtBottom); #endif - RefPtr<EventDispatcher> eventDispatcher = this; - RunLoop::main().dispatch([eventDispatcher, pageID, wheelEvent] { - eventDispatcher->dispatchWheelEvent(pageID, wheelEvent); - }); -} - -#if ENABLE(MAC_GESTURE_EVENTS) -void EventDispatcher::gestureEvent(uint64_t pageID, const WebKit::WebGestureEvent& gestureEvent) -{ - RefPtr<EventDispatcher> eventDispatcher = this; - RunLoop::main().dispatch([eventDispatcher, pageID, gestureEvent] { - eventDispatcher->dispatchGestureEvent(pageID, gestureEvent); - }); -} -#endif - -#if ENABLE(IOS_TOUCH_EVENTS) -void EventDispatcher::clearQueuedTouchEventsForPage(const WebPage& webPage) -{ - LockHolder locker(&m_touchEventsLock); - m_touchEvents.remove(webPage.pageID()); -} - -void EventDispatcher::getQueuedTouchEventsForPage(const WebPage& webPage, TouchEventQueue& destinationQueue) -{ - LockHolder locker(&m_touchEventsLock); - destinationQueue = m_touchEvents.take(webPage.pageID()); -} - -void EventDispatcher::touchEvent(uint64_t pageID, const WebKit::WebTouchEvent& touchEvent) -{ - bool updateListWasEmpty; - { - LockHolder locker(&m_touchEventsLock); - updateListWasEmpty = m_touchEvents.isEmpty(); - auto addResult = m_touchEvents.add(pageID, TouchEventQueue()); - if (addResult.isNewEntry) - addResult.iterator->value.append(touchEvent); - else { - TouchEventQueue& queuedEvents = addResult.iterator->value; - ASSERT(!queuedEvents.isEmpty()); - const WebTouchEvent& lastTouchEvent = queuedEvents.last(); - - // Coalesce touch move events. - WebEvent::Type type = lastTouchEvent.type(); - if (type == WebEvent::TouchMove) - queuedEvents.last() = touchEvent; - else - queuedEvents.append(touchEvent); - } - } - - if (updateListWasEmpty) { - RefPtr<EventDispatcher> eventDispatcher = this; - RunLoop::main().dispatch([eventDispatcher] { - eventDispatcher->dispatchTouchEvents(); - }); - } -} - -void EventDispatcher::dispatchTouchEvents() -{ - HashMap<uint64_t, TouchEventQueue> localCopy; - { - LockHolder locker(&m_touchEventsLock); - localCopy.swap(m_touchEvents); - } - - for (auto& slot : localCopy) { - if (WebPage* webPage = WebProcess::singleton().webPage(slot.key)) - webPage->dispatchAsynchronousTouchEvents(slot.value); - } + RunLoop::main()->dispatch(bind(&EventDispatcher::dispatchWheelEvent, this, pageID, wheelEvent)); } -#endif void EventDispatcher::dispatchWheelEvent(uint64_t pageID, const WebWheelEvent& wheelEvent) { - ASSERT(RunLoop::isMain()); + ASSERT(isMainThread()); - WebPage* webPage = WebProcess::singleton().webPage(pageID); + WebPage* webPage = WebProcess::shared().webPage(pageID); if (!webPage) return; webPage->wheelEvent(wheelEvent); } -#if ENABLE(MAC_GESTURE_EVENTS) -void EventDispatcher::dispatchGestureEvent(uint64_t pageID, const WebGestureEvent& gestureEvent) -{ - ASSERT(RunLoop::isMain()); - - WebPage* webPage = WebProcess::singleton().webPage(pageID); - if (!webPage) - return; - - webPage->gestureEvent(gestureEvent); -} -#endif - #if ENABLE(ASYNC_SCROLLING) void EventDispatcher::sendDidReceiveEvent(uint64_t pageID, const WebEvent& event, bool didHandleEvent) { - WebProcess::singleton().parentProcessConnection()->send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(event.type()), didHandleEvent), pageID); + WebProcess::shared().parentProcessConnection()->send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(event.type()), didHandleEvent), pageID); } #endif diff --git a/Source/WebKit2/WebProcess/WebPage/EventDispatcher.h b/Source/WebKit2/WebProcess/WebPage/EventDispatcher.h index 8374a83fe..b9998f17e 100644 --- a/Source/WebKit2/WebProcess/WebPage/EventDispatcher.h +++ b/Source/WebKit2/WebProcess/WebPage/EventDispatcher.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011, 2014 Apple Inc. All rights reserved. + * Copyright (C) 2011 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -27,20 +27,11 @@ #define EventDispatcher_h #include "Connection.h" - -#include "WebEvent.h" -#include <WebCore/WheelEventDeltaFilter.h> -#include <memory> #include <wtf/HashMap.h> -#include <wtf/Lock.h> #include <wtf/Noncopyable.h> #include <wtf/RefPtr.h> #include <wtf/ThreadingPrimitives.h> -#if ENABLE(MAC_GESTURE_EVENTS) -#include "WebGestureEvent.h" -#endif - namespace WebCore { class ThreadedScrollingTree; } @@ -53,7 +44,7 @@ class WebWheelEvent; class EventDispatcher : public IPC::Connection::WorkQueueMessageReceiver { public: - static Ref<EventDispatcher> create(); + static PassRefPtr<EventDispatcher> create(); ~EventDispatcher(); #if ENABLE(ASYNC_SCROLLING) @@ -61,55 +52,30 @@ public: void removeScrollingTreeForPage(WebPage*); #endif -#if ENABLE(IOS_TOUCH_EVENTS) - typedef Vector<WebTouchEvent, 1> TouchEventQueue; - - void clearQueuedTouchEventsForPage(const WebPage&); - void getQueuedTouchEventsForPage(const WebPage&, TouchEventQueue&); -#endif - void initializeConnection(IPC::Connection*); private: EventDispatcher(); // IPC::Connection::WorkQueueMessageReceiver. - virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; + virtual void didReceiveMessage(IPC::Connection*, IPC::MessageDecoder&) override; // Message handlers void wheelEvent(uint64_t pageID, const WebWheelEvent&, bool canRubberBandAtLeft, bool canRubberBandAtRight, bool canRubberBandAtTop, bool canRubberBandAtBottom); -#if ENABLE(IOS_TOUCH_EVENTS) - void touchEvent(uint64_t pageID, const WebTouchEvent&); -#endif -#if ENABLE(MAC_GESTURE_EVENTS) - void gestureEvent(uint64_t pageID, const WebGestureEvent&); -#endif - // This is called on the main thread. void dispatchWheelEvent(uint64_t pageID, const WebWheelEvent&); -#if ENABLE(IOS_TOUCH_EVENTS) - void dispatchTouchEvents(); -#endif -#if ENABLE(MAC_GESTURE_EVENTS) - void dispatchGestureEvent(uint64_t pageID, const WebGestureEvent&); -#endif #if ENABLE(ASYNC_SCROLLING) void sendDidReceiveEvent(uint64_t pageID, const WebEvent&, bool didHandleEvent); #endif - Ref<WorkQueue> m_queue; + RefPtr<WorkQueue> m_queue; #if ENABLE(ASYNC_SCROLLING) - Lock m_scrollingTreesMutex; + Mutex m_scrollingTreesMutex; HashMap<uint64_t, RefPtr<WebCore::ThreadedScrollingTree>> m_scrollingTrees; #endif - std::unique_ptr<WebCore::WheelEventDeltaFilter> m_recentWheelEventDeltaFilter; -#if ENABLE(IOS_TOUCH_EVENTS) - Lock m_touchEventsLock; - HashMap<uint64_t, TouchEventQueue> m_touchEvents; -#endif }; } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/EventDispatcher.messages.in b/Source/WebKit2/WebProcess/WebPage/EventDispatcher.messages.in index 5e1543c98..dbcf4bd5c 100644 --- a/Source/WebKit2/WebProcess/WebPage/EventDispatcher.messages.in +++ b/Source/WebKit2/WebProcess/WebPage/EventDispatcher.messages.in @@ -22,10 +22,4 @@ messages -> EventDispatcher { WheelEvent(uint64_t pageID, WebKit::WebWheelEvent event, bool canRubberBandAtLeft, bool canRubberBandAtRight, bool canRubberBandAtTop, bool canRubberBandAtBottom) -#if ENABLE(IOS_TOUCH_EVENTS) - TouchEvent(uint64_t pageID, WebKit::WebTouchEvent event) -#endif -#if ENABLE(MAC_GESTURE_EVENTS) - GestureEvent(uint64_t pageID, WebKit::WebGestureEvent event) -#endif } diff --git a/Source/WebKit2/WebProcess/WebPage/FindController.cpp b/Source/WebKit2/WebProcess/WebPage/FindController.cpp index bf5cd17c2..ccd03cc92 100644 --- a/Source/WebKit2/WebProcess/WebPage/FindController.cpp +++ b/Source/WebKit2/WebProcess/WebPage/FindController.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010, 2015 Apple Inc. All rights reserved. + * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,7 +26,6 @@ #include "config.h" #include "FindController.h" -#include "DrawingArea.h" #include "PluginView.h" #include "ShareableBitmap.h" #include "WKPage.h" @@ -40,14 +39,8 @@ #include <WebCore/GraphicsContext.h> #include <WebCore/MainFrame.h> #include <WebCore/Page.h> -#include <WebCore/PageOverlayController.h> -#include <WebCore/PlatformMouseEvent.h> #include <WebCore/PluginDocument.h> -#if PLATFORM(COCOA) -#include <WebCore/TextIndicatorWindow.h> -#endif - using namespace WebCore; namespace WebKit { @@ -63,9 +56,8 @@ static WebCore::FindOptions core(FindOptions options) FindController::FindController(WebPage* webPage) : m_webPage(webPage) - , m_findPageOverlay(nullptr) + , m_findPageOverlay(0) , m_isShowingFindIndicator(false) - , m_foundStringMatchIndex(-1) { } @@ -130,29 +122,19 @@ void FindController::updateFindUIAfterPageScroll(bool found, const String& strin selectedFrame->selection().clear(); hideFindIndicator(); - didFailToFindString(); m_webPage->send(Messages::WebPageProxy::DidFailToFindString(string)); } else { shouldShowOverlay = options & FindOptionsShowOverlay; bool shouldShowHighlight = options & FindOptionsShowHighlight; - bool shouldDetermineMatchIndex = options & FindOptionsDetermineMatchIndex; unsigned matchCount = 1; - if (shouldDetermineMatchIndex) { - if (pluginView) - matchCount = pluginView->countFindMatches(string, core(options), maxMatchCount + 1); - else - matchCount = m_webPage->corePage()->countFindMatches(string, core(options), maxMatchCount + 1); - } - if (shouldShowOverlay || shouldShowHighlight) { if (maxMatchCount == std::numeric_limits<unsigned>::max()) --maxMatchCount; if (pluginView) { - if (!shouldDetermineMatchIndex) - matchCount = pluginView->countFindMatches(string, core(options), maxMatchCount + 1); + matchCount = pluginView->countFindMatches(string, core(options), maxMatchCount + 1); shouldShowOverlay = false; } else { m_webPage->corePage()->unmarkAllTextMatches(); @@ -165,93 +147,39 @@ void FindController::updateFindUIAfterPageScroll(bool found, const String& strin matchCount = static_cast<unsigned>(kWKMoreThanMaximumMatchCount); } } - if (matchCount == static_cast<unsigned>(kWKMoreThanMaximumMatchCount)) - m_foundStringMatchIndex = -1; - else { - if (m_foundStringMatchIndex < 0) - m_foundStringMatchIndex += matchCount; - if (m_foundStringMatchIndex >= (int) matchCount) - m_foundStringMatchIndex -= matchCount; - } - m_findMatches.clear(); - Vector<IntRect> matchRects; - if (auto range = m_webPage->corePage()->selection().firstRange()) { - range->absoluteTextRects(matchRects); - m_findMatches.append(range); - } - - m_webPage->send(Messages::WebPageProxy::DidFindString(string, matchRects, matchCount, m_foundStringMatchIndex)); + m_webPage->send(Messages::WebPageProxy::DidFindString(string, matchCount)); - if (!(options & FindOptionsShowFindIndicator) || !selectedFrame || !updateFindIndicator(*selectedFrame, shouldShowOverlay)) + if (!(options & FindOptionsShowFindIndicator) || !updateFindIndicator(selectedFrame, shouldShowOverlay)) hideFindIndicator(); } if (!shouldShowOverlay) { if (m_findPageOverlay) - m_webPage->mainFrame()->pageOverlayController().uninstallPageOverlay(m_findPageOverlay, PageOverlay::FadeMode::Fade); + m_webPage->uninstallPageOverlay(m_findPageOverlay, true); } else { if (!m_findPageOverlay) { - RefPtr<PageOverlay> findPageOverlay = PageOverlay::create(*this, PageOverlay::OverlayType::Document); + RefPtr<PageOverlay> findPageOverlay = PageOverlay::create(this); m_findPageOverlay = findPageOverlay.get(); - m_webPage->mainFrame()->pageOverlayController().installPageOverlay(findPageOverlay.release(), PageOverlay::FadeMode::Fade); - } - m_findPageOverlay->setNeedsDisplay(); + m_webPage->installPageOverlay(findPageOverlay.release(), true); + m_findPageOverlay->setNeedsDisplay(); + } else + m_findPageOverlay->setNeedsDisplay(); } } void FindController::findString(const String& string, FindOptions options, unsigned maxMatchCount) { PluginView* pluginView = pluginViewForFrame(m_webPage->mainFrame()); - - WebCore::FindOptions coreOptions = core(options); - - // iOS will reveal the selection through a different mechanism, and - // we need to avoid sending the non-painted selection change to the UI process - // so that it does not clear the selection out from under us. -#if PLATFORM(IOS) - coreOptions = static_cast<FindOptions>(coreOptions | DoNotRevealSelection); -#endif - - willFindString(); - - bool foundStringStartsAfterSelection = false; - if (!pluginView) { - if (Frame* selectedFrame = frameWithSelection(m_webPage->corePage())) { - FrameSelection& fs = selectedFrame->selection(); - if (fs.selectionBounds().isEmpty()) { - m_findMatches.clear(); - int indexForSelection; - m_webPage->corePage()->findStringMatchingRanges(string, coreOptions, maxMatchCount, m_findMatches, indexForSelection); - m_foundStringMatchIndex = indexForSelection; - foundStringStartsAfterSelection = true; - } - } - } - - m_findMatches.clear(); - + bool found; + if (pluginView) - found = pluginView->findString(string, coreOptions, maxMatchCount); + found = pluginView->findString(string, core(options), maxMatchCount); else - found = m_webPage->corePage()->findString(string, coreOptions); - - if (found) { - didFindString(); - - if (!foundStringStartsAfterSelection) { - if (options & FindOptionsBackwards) - m_foundStringMatchIndex--; - else - m_foundStringMatchIndex++; - } - } + found = m_webPage->corePage()->findString(string, core(options)); - RefPtr<WebPage> protectedWebPage = m_webPage; - m_webPage->drawingArea()->dispatchAfterEnsuringUpdatedScrollPosition([protectedWebPage, found, string, options, maxMatchCount] () { - protectedWebPage->findController().updateFindUIAfterPageScroll(found, string, options, maxMatchCount); - }); + m_webPage->drawingArea()->dispatchAfterEnsuringUpdatedScrollPosition(WTF::bind(&FindController::updateFindUIAfterPageScroll, this, found, string, options, maxMatchCount)); } void FindController::findStringMatches(const String& string, FindOptions options, unsigned maxMatchCount) @@ -259,39 +187,70 @@ void FindController::findStringMatches(const String& string, FindOptions options m_findMatches.clear(); int indexForSelection; - m_webPage->corePage()->findStringMatchingRanges(string, core(options), maxMatchCount, m_findMatches, indexForSelection); + m_webPage->corePage()->findStringMatchingRanges(string, core(options), maxMatchCount, &m_findMatches, indexForSelection); Vector<Vector<IntRect>> matchRects; for (size_t i = 0; i < m_findMatches.size(); ++i) { Vector<IntRect> rects; - m_findMatches[i]->absoluteTextRects(rects); - matchRects.append(WTFMove(rects)); + m_findMatches[i]->textRects(rects); + matchRects.append(rects); } m_webPage->send(Messages::WebPageProxy::DidFindStringMatches(string, matchRects, indexForSelection)); } +bool FindController::getFindIndicatorBitmapAndRect(Frame* frame, ShareableBitmap::Handle& handle, IntRect& selectionRect) +{ + selectionRect = enclosingIntRect(frame->selection().bounds()); + + // Selection rect can be empty for matches that are currently obscured from view. + if (selectionRect.isEmpty()) + return false; + + IntSize backingStoreSize = selectionRect.size(); + backingStoreSize.scale(m_webPage->corePage()->deviceScaleFactor()); + + // Create a backing store and paint the find indicator text into it. + RefPtr<ShareableBitmap> findIndicatorTextBackingStore = ShareableBitmap::createShareable(backingStoreSize, ShareableBitmap::SupportsAlpha); + if (!findIndicatorTextBackingStore) + return false; + + auto graphicsContext = findIndicatorTextBackingStore->createGraphicsContext(); + graphicsContext->scale(FloatSize(m_webPage->corePage()->deviceScaleFactor(), m_webPage->corePage()->deviceScaleFactor())); + + IntRect paintRect = selectionRect; + paintRect.move(frame->view()->frameRect().x(), frame->view()->frameRect().y()); + paintRect.move(-frame->view()->scrollOffset()); + + graphicsContext->translate(-paintRect.x(), -paintRect.y()); + frame->view()->setPaintBehavior(PaintBehaviorSelectionOnly | PaintBehaviorForceBlackText | PaintBehaviorFlattenCompositingLayers); + frame->document()->updateLayout(); + + frame->view()->paint(graphicsContext.get(), paintRect); + frame->view()->setPaintBehavior(PaintBehaviorNormal); + + if (!findIndicatorTextBackingStore->createHandle(handle)) + return false; + return true; +} + void FindController::getImageForFindMatch(uint32_t matchIndex) { if (matchIndex >= m_findMatches.size()) return; - Frame* frame = m_findMatches[matchIndex]->startContainer().document().frame(); + Frame* frame = m_findMatches[matchIndex]->startContainer()->document().frame(); if (!frame) return; VisibleSelection oldSelection = frame->selection().selection(); - frame->selection().setSelection(VisibleSelection(*m_findMatches[matchIndex])); + frame->selection().setSelection(VisibleSelection(m_findMatches[matchIndex].get())); - RefPtr<ShareableBitmap> selectionSnapshot = WebFrame::fromCoreFrame(*frame)->createSelectionSnapshot(); + IntRect selectionRect; + ShareableBitmap::Handle handle; + getFindIndicatorBitmapAndRect(frame, handle, selectionRect); frame->selection().setSelection(oldSelection); - if (!selectionSnapshot) - return; - - ShareableBitmap::Handle handle; - selectionSnapshot->createHandle(handle); - if (handle.isNull()) return; @@ -302,17 +261,17 @@ void FindController::selectFindMatch(uint32_t matchIndex) { if (matchIndex >= m_findMatches.size()) return; - Frame* frame = m_findMatches[matchIndex]->startContainer().document().frame(); + Frame* frame = m_findMatches[matchIndex]->startContainer()->document().frame(); if (!frame) return; - frame->selection().setSelection(VisibleSelection(*m_findMatches[matchIndex])); + frame->selection().setSelection(VisibleSelection(m_findMatches[matchIndex].get())); } void FindController::hideFindUI() { m_findMatches.clear(); if (m_findPageOverlay) - m_webPage->mainFrame()->pageOverlayController().uninstallPageOverlay(m_findPageOverlay, PageOverlay::FadeMode::Fade); + m_webPage->uninstallPageOverlay(m_findPageOverlay, true); PluginView* pluginView = pluginViewForFrame(m_webPage->mainFrame()); @@ -324,17 +283,34 @@ void FindController::hideFindUI() hideFindIndicator(); } -#if !PLATFORM(IOS) -bool FindController::updateFindIndicator(Frame& selectedFrame, bool isShowingOverlay, bool shouldAnimate) +bool FindController::updateFindIndicator(Frame* selectedFrame, bool isShowingOverlay, bool shouldAnimate) { - RefPtr<TextIndicator> indicator = TextIndicator::createWithSelectionInFrame(selectedFrame, TextIndicatorOptionIncludeMarginIfRangeMatchesSelection, shouldAnimate ? TextIndicatorPresentationTransition::Bounce : TextIndicatorPresentationTransition::None); - if (!indicator) + if (!selectedFrame) + return false; + + IntRect selectionRect; + ShareableBitmap::Handle handle; + if (!getFindIndicatorBitmapAndRect(selectedFrame, handle, selectionRect)) return false; - m_findIndicatorRect = enclosingIntRect(indicator->selectionRectInRootViewCoordinates()); -#if PLATFORM(COCOA) - m_webPage->send(Messages::WebPageProxy::SetTextIndicator(indicator->data(), static_cast<uint64_t>(isShowingOverlay ? TextIndicatorWindowLifetime::Permanent : TextIndicatorWindowLifetime::Temporary))); -#endif + // We want the selection rect in window coordinates. + IntRect selectionRectInWindowCoordinates = selectedFrame->view()->contentsToWindow(selectionRect); + + Vector<FloatRect> textRects; + selectedFrame->selection().getClippedVisibleTextRectangles(textRects); + + // We want the text rects in selection rect coordinates. + Vector<FloatRect> textRectsInSelectionRectCoordinates; + + for (size_t i = 0; i < textRects.size(); ++i) { + IntRect textRectInSelectionRectCoordinates = selectedFrame->view()->contentsToWindow(enclosingIntRect(textRects[i])); + textRectInSelectionRectCoordinates.move(-selectionRectInWindowCoordinates.x(), -selectionRectInWindowCoordinates.y()); + + textRectsInSelectionRectCoordinates.append(textRectInSelectionRectCoordinates); + } + + m_webPage->send(Messages::WebPageProxy::SetFindIndicator(selectionRectInWindowCoordinates, textRectsInSelectionRectCoordinates, m_webPage->corePage()->deviceScaleFactor(), handle, !isShowingOverlay, shouldAnimate)); + m_findIndicatorRect = selectionRectInWindowCoordinates; m_isShowingFindIndicator = true; return true; @@ -345,33 +321,15 @@ void FindController::hideFindIndicator() if (!m_isShowingFindIndicator) return; - m_webPage->send(Messages::WebPageProxy::ClearTextIndicator()); + ShareableBitmap::Handle handle; + m_webPage->send(Messages::WebPageProxy::SetFindIndicator(FloatRect(), Vector<FloatRect>(), m_webPage->corePage()->deviceScaleFactor(), handle, false, true)); m_isShowingFindIndicator = false; - m_foundStringMatchIndex = -1; - didHideFindIndicator(); -} - -void FindController::willFindString() -{ -} - -void FindController::didFindString() -{ -} - -void FindController::didFailToFindString() -{ -} - -void FindController::didHideFindIndicator() -{ } -#endif void FindController::showFindIndicatorInSelection() { Frame& selectedFrame = m_webPage->corePage()->focusController().focusedOrMainFrame(); - updateFindIndicator(selectedFrame, false); + updateFindIndicator(&selectedFrame, false); } void FindController::deviceScaleFactorDidChange() @@ -382,123 +340,106 @@ void FindController::deviceScaleFactorDidChange() if (!selectedFrame) return; - updateFindIndicator(*selectedFrame, true, false); -} - -void FindController::redraw() -{ - if (!m_isShowingFindIndicator) - return; - - Frame* selectedFrame = frameWithSelection(m_webPage->corePage()); - if (!selectedFrame) - return; - - updateFindIndicator(*selectedFrame, isShowingOverlay(), false); + updateFindIndicator(selectedFrame, true, false); } -Vector<IntRect> FindController::rectsForTextMatchesInRect(IntRect clipRect) +Vector<IntRect> FindController::rectsForTextMatches() { Vector<IntRect> rects; - FrameView* mainFrameView = m_webPage->corePage()->mainFrame().view(); - for (Frame* frame = &m_webPage->corePage()->mainFrame(); frame; frame = frame->tree().traverseNext()) { Document* document = frame->document(); if (!document) continue; - for (FloatRect rect : document->markers().renderedRectsForMarkers(DocumentMarker::TextMatch)) { - if (!frame->isMainFrame()) - rect = mainFrameView->windowToContents(frame->view()->contentsToWindow(enclosingIntRect(rect))); - rect.intersect(clipRect); - - if (rect.isEmpty()) - continue; + IntRect visibleRect = frame->view()->visibleContentRect(); + Vector<IntRect> frameRects = document->markers().renderedRectsForMarkers(DocumentMarker::TextMatch); + IntPoint frameOffset(-frame->view()->scrollOffsetRelativeToDocument().width(), -frame->view()->scrollOffsetRelativeToDocument().height()); + frameOffset = frame->view()->convertToContainingWindow(frameOffset); - rects.append(rect); + for (Vector<IntRect>::iterator it = frameRects.begin(), end = frameRects.end(); it != end; ++it) { + it->intersect(visibleRect); + it->move(frameOffset.x(), frameOffset.y()); + rects.append(*it); } } return rects; } -void FindController::pageOverlayDestroyed(PageOverlay&) +void FindController::pageOverlayDestroyed(PageOverlay*) { } -void FindController::willMoveToPage(PageOverlay&, Page* page) +void FindController::willMoveToWebPage(PageOverlay*, WebPage* webPage) { - if (page) + if (webPage) return; ASSERT(m_findPageOverlay); m_findPageOverlay = 0; } -void FindController::didMoveToPage(PageOverlay&, Page*) +void FindController::didMoveToWebPage(PageOverlay*, WebPage*) { } -const float shadowOffsetX = 0; -const float shadowOffsetY = 0; -const float shadowBlurRadius = 1; -const float shadowColorAlpha = 0.5; +static const float shadowOffsetX = 0.0; +static const float shadowOffsetY = 1.0; +static const float shadowBlurRadius = 2.0; -void FindController::drawRect(PageOverlay&, GraphicsContext& graphicsContext, const IntRect& dirtyRect) -{ - const int borderWidth = 1; +static const float overlayBackgroundRed = 0.1; +static const float overlayBackgroundGreen = 0.1; +static const float overlayBackgroundBlue = 0.1; +static const float overlayBackgroundAlpha = 0.25; - Color overlayBackgroundColor(0.1f, 0.1f, 0.1f, 0.25f); +void FindController::drawRect(PageOverlay* /*pageOverlay*/, GraphicsContext& graphicsContext, const IntRect& dirtyRect) +{ + Color overlayBackgroundColor(overlayBackgroundRed, overlayBackgroundGreen, overlayBackgroundBlue, overlayBackgroundAlpha); - IntRect borderInflatedDirtyRect = dirtyRect; - borderInflatedDirtyRect.inflate(borderWidth); - Vector<IntRect> rects = rectsForTextMatchesInRect(borderInflatedDirtyRect); + Vector<IntRect> rects = rectsForTextMatches(); // Draw the background. - graphicsContext.fillRect(dirtyRect, overlayBackgroundColor); + graphicsContext.fillRect(dirtyRect, overlayBackgroundColor, ColorSpaceSRGB); { GraphicsContextStateSaver stateSaver(graphicsContext); - graphicsContext.setShadow(FloatSize(shadowOffsetX, shadowOffsetY), shadowBlurRadius, Color(0.0f, 0.0f, 0.0f, shadowColorAlpha)); - graphicsContext.setFillColor(Color::white); + graphicsContext.setShadow(FloatSize(shadowOffsetX, shadowOffsetY), shadowBlurRadius, Color::black, ColorSpaceSRGB); + graphicsContext.setFillColor(Color::white, ColorSpaceSRGB); // Draw white frames around the holes. - for (auto& rect : rects) { - IntRect whiteFrameRect = rect; - whiteFrameRect.inflate(borderWidth); + for (size_t i = 0; i < rects.size(); ++i) { + IntRect whiteFrameRect = rects[i]; + whiteFrameRect.inflate(1); + graphicsContext.fillRect(whiteFrameRect); } } + graphicsContext.setFillColor(Color::transparent, ColorSpaceSRGB); + // Clear out the holes. - for (auto& rect : rects) - graphicsContext.clearRect(rect); + for (size_t i = 0; i < rects.size(); ++i) + graphicsContext.fillRect(rects[i]); if (!m_isShowingFindIndicator) return; if (Frame* selectedFrame = frameWithSelection(m_webPage->corePage())) { - IntRect findIndicatorRect = selectedFrame->view()->contentsToRootView(enclosingIntRect(selectedFrame->selection().selectionBounds())); + IntRect findIndicatorRect = selectedFrame->view()->contentsToWindow(enclosingIntRect(selectedFrame->selection().bounds())); if (findIndicatorRect != m_findIndicatorRect) hideFindIndicator(); } } -bool FindController::mouseEvent(PageOverlay&, const PlatformMouseEvent& mouseEvent) +bool FindController::mouseEvent(PageOverlay*, const WebMouseEvent& mouseEvent) { - if (mouseEvent.type() == PlatformEvent::MousePressed) + if (mouseEvent.type() == WebEvent::MouseDown) hideFindUI(); return false; } -void FindController::didInvalidateDocumentMarkerRects() -{ - if (m_findPageOverlay) - m_findPageOverlay->setNeedsDisplay(); -} - } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/FindController.h b/Source/WebKit2/WebProcess/WebPage/FindController.h index 924af5330..af0c0a1c4 100644 --- a/Source/WebKit2/WebProcess/WebPage/FindController.h +++ b/Source/WebKit2/WebProcess/WebPage/FindController.h @@ -26,28 +26,24 @@ #ifndef FindController_h #define FindController_h +#include "PageOverlay.h" #include "ShareableBitmap.h" #include "WebFindOptions.h" #include <WebCore/IntRect.h> -#include <WebCore/PageOverlay.h> #include <wtf/Forward.h> #include <wtf/Noncopyable.h> #include <wtf/Vector.h> -#if PLATFORM(IOS) -#include "FindIndicatorOverlayClientIOS.h" -#endif - namespace WebCore { -class Frame; -class Range; + class Frame; + class Range; } namespace WebKit { class WebPage; -class FindController : private WebCore::PageOverlay::Client { +class FindController : private PageOverlay::Client { WTF_MAKE_NONCOPYABLE(FindController); public: @@ -67,43 +63,29 @@ public: bool isShowingOverlay() const { return m_isShowingFindIndicator && m_findPageOverlay; } void deviceScaleFactorDidChange(); - void didInvalidateDocumentMarkerRects(); - - void redraw(); private: // PageOverlay::Client. - virtual void pageOverlayDestroyed(WebCore::PageOverlay&); - virtual void willMoveToPage(WebCore::PageOverlay&, WebCore::Page*); - virtual void didMoveToPage(WebCore::PageOverlay&, WebCore::Page*); - virtual bool mouseEvent(WebCore::PageOverlay&, const WebCore::PlatformMouseEvent&); - virtual void drawRect(WebCore::PageOverlay&, WebCore::GraphicsContext&, const WebCore::IntRect& dirtyRect); + virtual void pageOverlayDestroyed(PageOverlay*); + virtual void willMoveToWebPage(PageOverlay*, WebPage*); + virtual void didMoveToWebPage(PageOverlay*, WebPage*); + virtual bool mouseEvent(PageOverlay*, const WebMouseEvent&); + virtual void drawRect(PageOverlay*, WebCore::GraphicsContext&, const WebCore::IntRect& dirtyRect); - Vector<WebCore::IntRect> rectsForTextMatchesInRect(WebCore::IntRect clipRect); - bool updateFindIndicator(WebCore::Frame& selectedFrame, bool isShowingOverlay, bool shouldAnimate = true); + Vector<WebCore::IntRect> rectsForTextMatches(); + bool getFindIndicatorBitmapAndRect(WebCore::Frame*, ShareableBitmap::Handle&, WebCore::IntRect& selectionRect); + bool updateFindIndicator(WebCore::Frame* selectedFrame, bool isShowingOverlay, bool shouldAnimate = true); void updateFindUIAfterPageScroll(bool found, const String&, FindOptions, unsigned maxMatchCount); - void willFindString(); - void didFindString(); - void didFailToFindString(); - void didHideFindIndicator(); - WebPage* m_webPage; - WebCore::PageOverlay* m_findPageOverlay; + PageOverlay* m_findPageOverlay; // Whether the UI process is showing the find indicator. Note that this can be true even if // the find indicator isn't showing, but it will never be false when it is showing. bool m_isShowingFindIndicator; WebCore::IntRect m_findIndicatorRect; Vector<RefPtr<WebCore::Range>> m_findMatches; - // Index value is -1 if not found or if number of matches exceeds provided maximum. - int m_foundStringMatchIndex; - -#if PLATFORM(IOS) - RefPtr<WebCore::PageOverlay> m_findIndicatorOverlay; - std::unique_ptr<FindIndicatorOverlayClientIOS> m_findIndicatorOverlayClient; -#endif }; } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/LayerTreeHost.cpp b/Source/WebKit2/WebProcess/WebPage/LayerTreeHost.cpp index e50b00855..593a1ca45 100644 --- a/Source/WebKit2/WebProcess/WebPage/LayerTreeHost.cpp +++ b/Source/WebKit2/WebProcess/WebPage/LayerTreeHost.cpp @@ -24,16 +24,13 @@ */ #include "config.h" - -#if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER) - #include "LayerTreeHost.h" -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) +#if USE(COORDINATED_GRAPHICS) #include "CoordinatedLayerTreeHost.h" -#elif USE(COORDINATED_GRAPHICS_THREADED) -#include "ThreadedCoordinatedLayerTreeHost.h" -#elif PLATFORM(GTK) && USE(TEXTURE_MAPPER_GL) +#endif + +#if PLATFORM(GTK) && USE(TEXTURE_MAPPER_GL) #include "LayerTreeHostGtk.h" #endif @@ -43,9 +40,7 @@ namespace WebKit { PassRefPtr<LayerTreeHost> LayerTreeHost::create(WebPage* webPage) { -#if USE(COORDINATED_GRAPHICS_THREADED) - return ThreadedCoordinatedLayerTreeHost::create(webPage); -#elif USE(COORDINATED_GRAPHICS_MULTIPROCESS) +#if USE(COORDINATED_GRAPHICS) return CoordinatedLayerTreeHost::create(webPage); #elif PLATFORM(GTK) && USE(TEXTURE_MAPPER_GL) return LayerTreeHostGtk::create(webPage); @@ -65,5 +60,3 @@ LayerTreeHost::~LayerTreeHost() } } // namespace WebKit - -#endif // USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER) diff --git a/Source/WebKit2/WebProcess/WebPage/LayerTreeHost.h b/Source/WebKit2/WebProcess/WebPage/LayerTreeHost.h index 486454026..c059c4534 100644 --- a/Source/WebKit2/WebProcess/WebPage/LayerTreeHost.h +++ b/Source/WebKit2/WebProcess/WebPage/LayerTreeHost.h @@ -26,8 +26,6 @@ #ifndef LayerTreeHost_h #define LayerTreeHost_h -#if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER) - #include "LayerTreeContext.h" #include <WebCore/Color.h> #include <wtf/PassRefPtr.h> @@ -45,13 +43,11 @@ class IntRect; class IntSize; class GraphicsLayer; class GraphicsLayerFactory; -#if USE(COORDINATED_GRAPHICS_THREADED) -struct ViewportAttributes; -#endif } namespace WebKit { +class PageOverlay; class UpdateInfo; class WebPage; @@ -60,6 +56,8 @@ public: static PassRefPtr<LayerTreeHost> create(WebPage*); virtual ~LayerTreeHost(); + static bool supportsAcceleratedCompositing(); + virtual const LayerTreeContext& layerTreeContext() = 0; virtual void scheduleLayerFlush() = 0; virtual void setLayerFlushSchedulingEnabled(bool) = 0; @@ -76,38 +74,40 @@ public: virtual void deviceOrPageScaleFactorChanged() = 0; virtual void pageBackgroundTransparencyChanged() = 0; + virtual void didInstallPageOverlay(PageOverlay*) = 0; + virtual void didUninstallPageOverlay(PageOverlay*) = 0; + virtual void setPageOverlayNeedsDisplay(PageOverlay*, const WebCore::IntRect&) = 0; + virtual void setPageOverlayOpacity(PageOverlay*, float) { } + virtual void pauseRendering() { } virtual void resumeRendering() { } virtual WebCore::GraphicsLayerFactory* graphicsLayerFactory() { return 0; } + virtual void setBackgroundColor(const WebCore::Color&) { } -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) - virtual void didReceiveCoordinatedLayerTreeHostMessage(IPC::Connection&, IPC::MessageDecoder&) = 0; +#if USE(COORDINATED_GRAPHICS) + virtual void didReceiveCoordinatedLayerTreeHostMessage(IPC::Connection*, IPC::MessageDecoder&) = 0; #endif -#if USE(COORDINATED_GRAPHICS_THREADED) - virtual void viewportSizeChanged(const WebCore::IntSize&) = 0; - virtual void didChangeViewportProperties(const WebCore::ViewportAttributes&) = 0; +#if PLATFORM(MAC) + virtual void setLayerHostingMode(LayerHostingMode) { } #endif #if USE(COORDINATED_GRAPHICS) && ENABLE(REQUEST_ANIMATION_FRAME) virtual void scheduleAnimation() = 0; #endif -#if USE(TEXTURE_MAPPER) && PLATFORM(GTK) - virtual void setNativeSurfaceHandleForCompositing(uint64_t) = 0; -#endif - - virtual void setViewOverlayRootLayer(WebCore::GraphicsLayer*) = 0; - protected: explicit LayerTreeHost(WebPage*); WebPage* m_webPage; }; -} // namespace WebKit +inline bool LayerTreeHost::supportsAcceleratedCompositing() +{ + return true; +} -#endif // USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER) +} // namespace WebKit #endif // LayerTreeHost_h diff --git a/Source/WebKit2/WebProcess/WebPage/PageBanner.cpp b/Source/WebKit2/WebProcess/WebPage/PageBanner.cpp index 6b2fecac7..8dc53b745 100644 --- a/Source/WebKit2/WebProcess/WebPage/PageBanner.cpp +++ b/Source/WebKit2/WebProcess/WebPage/PageBanner.cpp @@ -33,9 +33,7 @@ namespace WebKit { PageBanner::~PageBanner() { -#if PLATFORM(MAC) ASSERT(!m_webPage); -#endif m_client->pageBannerDestroyed(this); } diff --git a/Source/WebKit2/WebProcess/WebPage/PageBanner.h b/Source/WebKit2/WebProcess/WebPage/PageBanner.h index 88aa7d938..8d9181493 100644 --- a/Source/WebKit2/WebProcess/WebPage/PageBanner.h +++ b/Source/WebKit2/WebProcess/WebPage/PageBanner.h @@ -61,7 +61,7 @@ public: }; #if PLATFORM(MAC) - static Ref<PageBanner> create(CALayer *, int height, Client*); + static PassRefPtr<PageBanner> create(CALayer *, int height, Client*); CALayer *layer(); #endif @@ -83,14 +83,14 @@ private: explicit PageBanner(CALayer *, int height, Client*); #endif + Type m_type; Client* m_client; + WebPage* m_webPage; -#if PLATFORM(MAC) - Type m_type = NotSet; - WebPage* m_webPage = 0; - bool m_mouseDownInBanner = false; - bool m_isHidden = false; + bool m_mouseDownInBanner; + bool m_isHidden; +#if PLATFORM(MAC) RetainPtr<CALayer> m_layer; int m_height; #endif diff --git a/Source/WebKit2/WebProcess/WebPage/PageOverlay.cpp b/Source/WebKit2/WebProcess/WebPage/PageOverlay.cpp new file mode 100644 index 000000000..35b982543 --- /dev/null +++ b/Source/WebKit2/WebProcess/WebPage/PageOverlay.cpp @@ -0,0 +1,199 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PageOverlay.h" + +#include "WebPage.h" +#include "WebProcess.h" +#include <WebCore/FrameView.h> +#include <WebCore/GraphicsContext.h> +#include <WebCore/MainFrame.h> +#include <WebCore/Page.h> +#include <WebCore/ScrollbarTheme.h> +#include <wtf/CurrentTime.h> + +using namespace WebCore; + +namespace WebKit { + +static const double fadeAnimationDuration = 0.2; +static const double fadeAnimationFrameRate = 30; + +PassRefPtr<PageOverlay> PageOverlay::create(Client* client) +{ + return adoptRef(new PageOverlay(client)); +} + +PageOverlay::PageOverlay(Client* client) + : m_client(client) + , m_webPage(0) + , m_fadeAnimationTimer(RunLoop::main(), this, &PageOverlay::fadeAnimationTimerFired) + , m_fadeAnimationStartTime(0.0) + , m_fadeAnimationDuration(fadeAnimationDuration) + , m_fadeAnimationType(NoAnimation) + , m_fractionFadedIn(1.0) +{ +} + +PageOverlay::~PageOverlay() +{ +} + +IntRect PageOverlay::bounds() const +{ + FrameView* frameView = m_webPage->corePage()->mainFrame().view(); + + int width = frameView->width(); + int height = frameView->height(); + + if (!ScrollbarTheme::theme()->usesOverlayScrollbars()) { + if (frameView->verticalScrollbar()) + width -= frameView->verticalScrollbar()->width(); + if (frameView->horizontalScrollbar()) + height -= frameView->horizontalScrollbar()->height(); + } + return IntRect(0, 0, width, height); +} + +void PageOverlay::setPage(WebPage* webPage) +{ + m_client->willMoveToWebPage(this, webPage); + m_webPage = webPage; + m_client->didMoveToWebPage(this, webPage); + + m_fadeAnimationTimer.stop(); +} + +void PageOverlay::setNeedsDisplay(const IntRect& dirtyRect) +{ + if (m_webPage) { + m_webPage->drawingArea()->setPageOverlayOpacity(this, m_fractionFadedIn); + m_webPage->drawingArea()->setPageOverlayNeedsDisplay(this, dirtyRect); + } +} + +void PageOverlay::setNeedsDisplay() +{ + setNeedsDisplay(bounds()); +} + +void PageOverlay::drawRect(GraphicsContext& graphicsContext, const IntRect& dirtyRect) +{ + // If the dirty rect is outside the bounds, ignore it. + IntRect paintRect = intersection(dirtyRect, bounds()); + if (paintRect.isEmpty()) + return; + + GraphicsContextStateSaver stateSaver(graphicsContext); + graphicsContext.beginTransparencyLayer(1); + graphicsContext.setCompositeOperation(CompositeCopy); + + m_client->drawRect(this, graphicsContext, paintRect); + + graphicsContext.endTransparencyLayer(); +} + +bool PageOverlay::mouseEvent(const WebMouseEvent& mouseEvent) +{ + // Ignore events outside the bounds. + if (!bounds().contains(mouseEvent.position())) + return false; + + return m_client->mouseEvent(this, mouseEvent); +} + +WKTypeRef PageOverlay::copyAccessibilityAttributeValue(WKStringRef attribute, WKTypeRef parameter) +{ + return m_client->copyAccessibilityAttributeValue(this, attribute, parameter); +} + +WKArrayRef PageOverlay::copyAccessibilityAttributeNames(bool parameterizedNames) +{ + return m_client->copyAccessibilityAttributeNames(this, parameterizedNames); +} + +void PageOverlay::startFadeInAnimation() +{ + m_fractionFadedIn = 0.0; + m_fadeAnimationType = FadeInAnimation; + + startFadeAnimation(); +} + +void PageOverlay::startFadeOutAnimation() +{ + m_fractionFadedIn = 1.0; + m_fadeAnimationType = FadeOutAnimation; + + startFadeAnimation(); +} + +void PageOverlay::stopFadeOutAnimation() +{ + m_fractionFadedIn = 1.0; + m_fadeAnimationTimer.stop(); +} + +void PageOverlay::startFadeAnimation() +{ + m_fadeAnimationStartTime = currentTime(); + + // Start the timer + m_fadeAnimationTimer.startRepeating(1 / fadeAnimationFrameRate); +} + +void PageOverlay::fadeAnimationTimerFired() +{ + float animationProgress = (currentTime() - m_fadeAnimationStartTime) / m_fadeAnimationDuration; + + if (animationProgress >= 1.0) + animationProgress = 1.0; + + double sine = sin(piOverTwoFloat * animationProgress); + float fadeAnimationValue = sine * sine; + + m_fractionFadedIn = (m_fadeAnimationType == FadeInAnimation) ? fadeAnimationValue : 1 - fadeAnimationValue; + m_webPage->drawingArea()->setPageOverlayOpacity(this, m_fractionFadedIn); + + if (animationProgress == 1.0) { + m_fadeAnimationTimer.stop(); + + bool wasFadingOut = m_fadeAnimationType == FadeOutAnimation; + m_fadeAnimationType = NoAnimation; + + if (wasFadingOut) { + // If this was a fade out, go ahead and uninstall the page overlay. + m_webPage->uninstallPageOverlay(this, false); + } + } +} + +void PageOverlay::clear() +{ + m_webPage->drawingArea()->clearPageOverlay(this); +} + +} // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/PageOverlay.h b/Source/WebKit2/WebProcess/WebPage/PageOverlay.h new file mode 100644 index 000000000..295f1e816 --- /dev/null +++ b/Source/WebKit2/WebProcess/WebPage/PageOverlay.h @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef PageOverlay_h +#define PageOverlay_h + +#include "APIObject.h" +#include "WKBase.h" +#include <wtf/PassRefPtr.h> +#include <wtf/RunLoop.h> + +namespace WebCore { + class GraphicsContext; + class IntPoint; + class IntRect; +} + +namespace WebKit { + +class WebMouseEvent; +class WebPage; + +class PageOverlay : public API::ObjectImpl<API::Object::Type::BundlePageOverlay> { +public: + class Client { + protected: + virtual ~Client() { } + + public: + virtual void pageOverlayDestroyed(PageOverlay*) = 0; + virtual void willMoveToWebPage(PageOverlay*, WebPage*) = 0; + virtual void didMoveToWebPage(PageOverlay*, WebPage*) = 0; + virtual void drawRect(PageOverlay*, WebCore::GraphicsContext&, const WebCore::IntRect& dirtyRect) = 0; + virtual bool mouseEvent(PageOverlay*, const WebMouseEvent&) = 0; + + virtual WKTypeRef copyAccessibilityAttributeValue(PageOverlay*, WKStringRef /* attribute */, WKTypeRef /* parameter */) { return 0; } + virtual WKArrayRef copyAccessibilityAttributeNames(PageOverlay*, bool /* parameterizedNames */) { return 0; } + }; + + static PassRefPtr<PageOverlay> create(Client*); + virtual ~PageOverlay(); + + void setPage(WebPage*); + void setNeedsDisplay(const WebCore::IntRect& dirtyRect); + void setNeedsDisplay(); + + void drawRect(WebCore::GraphicsContext&, const WebCore::IntRect& dirtyRect); + bool mouseEvent(const WebMouseEvent&); + + WKTypeRef copyAccessibilityAttributeValue(WKStringRef attribute, WKTypeRef parameter); + WKArrayRef copyAccessibilityAttributeNames(bool parameterizedNames); + + void startFadeInAnimation(); + void startFadeOutAnimation(); + void stopFadeOutAnimation(); + + void clear(); + + Client* client() const { return m_client; } + +protected: + explicit PageOverlay(Client*); + +private: + WebCore::IntRect bounds() const; + + void startFadeAnimation(); + void fadeAnimationTimerFired(); + + Client* m_client; + WebPage* m_webPage; + + RunLoop::Timer<PageOverlay> m_fadeAnimationTimer; + double m_fadeAnimationStartTime; + double m_fadeAnimationDuration; + + enum FadeAnimationType { + NoAnimation, + FadeInAnimation, + FadeOutAnimation, + }; + + FadeAnimationType m_fadeAnimationType; + float m_fractionFadedIn; +}; + +} // namespace WebKit + +#endif // PageOverlay_h diff --git a/Source/WebKit2/WebProcess/WebPage/TapHighlightController.cpp b/Source/WebKit2/WebProcess/WebPage/TapHighlightController.cpp new file mode 100644 index 000000000..df9ab32f4 --- /dev/null +++ b/Source/WebKit2/WebProcess/WebPage/TapHighlightController.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this program; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * + */ + +#include "config.h" +#include "TapHighlightController.h" + +#if ENABLE(TOUCH_EVENTS) + +#include "ShareableBitmap.h" +#include "WKPage.h" +#include "WebCoreArgumentCoders.h" +#include "WebPage.h" +#include "WebPageProxyMessages.h" +#include "WebProcess.h" +#include <WebCore/FocusController.h> +#include <WebCore/Frame.h> +#include <WebCore/FrameView.h> +#include <WebCore/GestureTapHighlighter.h> +#include <WebCore/GraphicsContext.h> +#include <WebCore/Page.h> + +#include <WebCore/RenderObject.h> + +using namespace std; +using namespace WebCore; + +namespace WebKit { + +TapHighlightController::TapHighlightController(WebPage* webPage) + : m_webPage(webPage) + , m_overlay(0) +{ +} + +TapHighlightController::~TapHighlightController() +{ +} + +void TapHighlightController::highlight(Node* node) +{ + ASSERT(node); + + m_path = GestureTapHighlighter::pathForNodeHighlight(node); + m_color = node->renderer()->style().tapHighlightColor(); + + if (!m_overlay) { + RefPtr<PageOverlay> overlay = PageOverlay::create(this); + m_overlay = overlay.get(); + m_webPage->installPageOverlay(overlay.release()); + } else + m_overlay->setNeedsDisplay(); +} + +void TapHighlightController::hideHighlight() +{ + if (m_overlay) + m_webPage->uninstallPageOverlay(m_overlay, /* fadeout */ true); +} + +void TapHighlightController::pageOverlayDestroyed(PageOverlay*) +{ +} + +void TapHighlightController::willMoveToWebPage(PageOverlay*, WebPage* webPage) +{ + if (webPage) + return; + + // The page overlay is moving away from the web page, reset it. + ASSERT(m_overlay); + m_overlay = 0; +} + +void TapHighlightController::didMoveToWebPage(PageOverlay*, WebPage*) +{ +} + +static Color highlightColor(Color baseColor, float fractionFadedIn) +{ + return Color(baseColor.red(), baseColor.green(), baseColor.blue(), int(baseColor.alpha() * fractionFadedIn)); +} + +void TapHighlightController::drawRect(PageOverlay* /*pageOverlay*/, GraphicsContext& context, const IntRect& /*dirtyRect*/) +{ + if (m_path.isEmpty()) + return; + + { + GraphicsContextStateSaver stateSaver(context); + context.setFillColor(highlightColor(m_color, 0.5f), ColorSpaceSRGB); + context.fillPath(m_path); + } +} + +bool TapHighlightController::mouseEvent(PageOverlay*, const WebMouseEvent&) +{ + return false; +} + +} // namespace WebKit + +#endif // ENABLE(TOUCH_EVENTS) diff --git a/Source/WebKit2/WebProcess/WebPage/TapHighlightController.h b/Source/WebKit2/WebProcess/WebPage/TapHighlightController.h new file mode 100644 index 000000000..cb20858c6 --- /dev/null +++ b/Source/WebKit2/WebProcess/WebPage/TapHighlightController.h @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this program; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * + */ + +#ifndef TapHighlightController_h +#define TapHighlightController_h + +#if ENABLE(TOUCH_EVENTS) + +#include "PageOverlay.h" +#include <WebCore/Color.h> +#include <WebCore/Path.h> +#include <wtf/Forward.h> +#include <wtf/Noncopyable.h> +#include <wtf/Vector.h> + +namespace WebCore { +class Frame; +class IntRect; +class Node; +} + +namespace WebKit { + +class WebPage; + +class TapHighlightController : private PageOverlay::Client { + WTF_MAKE_NONCOPYABLE(TapHighlightController); + +public: + explicit TapHighlightController(WebPage*); + virtual ~TapHighlightController(); + + void highlight(WebCore::Node*); + void hideHighlight(); + +private: + // PageOverlay::Client. + virtual void pageOverlayDestroyed(PageOverlay*); + virtual void willMoveToWebPage(PageOverlay*, WebPage*); + virtual void didMoveToWebPage(PageOverlay*, WebPage*); + virtual bool mouseEvent(PageOverlay*, const WebMouseEvent&); + virtual void drawRect(PageOverlay*, WebCore::GraphicsContext&, const WebCore::IntRect& dirtyRect); + +private: + WebPage* m_webPage; + PageOverlay* m_overlay; + + WebCore::Path m_path; + WebCore::Color m_color; +}; + +} // namespace WebKit + +#endif // ENABLE(TOUCH_EVENTS) + +#endif // TapHighlightController_h diff --git a/Source/WebKit2/WebProcess/WebPage/ViewGestureGeometryCollector.cpp b/Source/WebKit2/WebProcess/WebPage/ViewGestureGeometryCollector.cpp deleted file mode 100644 index 3a4a6a1a7..000000000 --- a/Source/WebKit2/WebProcess/WebPage/ViewGestureGeometryCollector.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (C) 2013, 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ViewGestureGeometryCollector.h" - -#include "ViewGestureGeometryCollectorMessages.h" -#include "WebCoreArgumentCoders.h" -#include "WebFrame.h" -#include "WebPage.h" -#include "WebProcess.h" -#include <WebCore/Frame.h> -#include <WebCore/FrameView.h> -#include <WebCore/HTMLImageElement.h> -#include <WebCore/HitTestResult.h> -#include <WebCore/ImageDocument.h> -#include <WebCore/RenderView.h> - -#if PLATFORM(IOS) -#include "SmartMagnificationControllerMessages.h" -#endif - -#if PLATFORM(MAC) -#include "ViewGestureControllerMessages.h" -#endif - -using namespace WebCore; - -namespace WebKit { - -ViewGestureGeometryCollector::ViewGestureGeometryCollector(WebPage& webPage) - : m_webPage(webPage) -#if PLATFORM(MAC) - , m_renderTreeSizeNotificationThreshold(0) -#endif -{ - WebProcess::singleton().addMessageReceiver(Messages::ViewGestureGeometryCollector::messageReceiverName(), m_webPage.pageID(), *this); -} - -ViewGestureGeometryCollector::~ViewGestureGeometryCollector() -{ - WebProcess::singleton().removeMessageReceiver(Messages::ViewGestureGeometryCollector::messageReceiverName(), m_webPage.pageID()); -} - -void ViewGestureGeometryCollector::dispatchDidCollectGeometryForSmartMagnificationGesture(FloatPoint origin, FloatRect targetRect, FloatRect visibleContentRect, bool isReplacedElement, double viewportMinimumScale, double viewportMaximumScale) -{ -#if PLATFORM(MAC) - m_webPage.send(Messages::ViewGestureController::DidCollectGeometryForSmartMagnificationGesture(origin, targetRect, visibleContentRect, isReplacedElement, viewportMinimumScale, viewportMaximumScale)); -#endif -#if PLATFORM(IOS) - m_webPage.send(Messages::SmartMagnificationController::DidCollectGeometryForSmartMagnificationGesture(origin, targetRect, visibleContentRect, isReplacedElement, viewportMinimumScale, viewportMaximumScale)); -#endif -} - -void ViewGestureGeometryCollector::collectGeometryForSmartMagnificationGesture(FloatPoint origin) -{ - FloatRect visibleContentRect = m_webPage.mainFrameView()->unobscuredContentRectIncludingScrollbars(); - - if (m_webPage.mainWebFrame()->handlesPageScaleGesture()) - return; - - IntPoint originInContentsSpace = m_webPage.mainFrameView()->windowToContents(roundedIntPoint(origin)); - HitTestResult hitTestResult = HitTestResult(originInContentsSpace); - - m_webPage.mainFrameView()->renderView()->hitTest(HitTestRequest(), hitTestResult); - Node* node = hitTestResult.innerNode(); - if (!node) { - dispatchDidCollectGeometryForSmartMagnificationGesture(FloatPoint(), FloatRect(), FloatRect(), false, 0, 0); - return; - } - - bool isReplaced; - FloatRect renderRect; - double viewportMinimumScale; - double viewportMaximumScale; - - computeZoomInformationForNode(*node, origin, renderRect, isReplaced, viewportMinimumScale, viewportMaximumScale); - dispatchDidCollectGeometryForSmartMagnificationGesture(origin, renderRect, visibleContentRect, isReplaced, viewportMinimumScale, viewportMaximumScale); -} - -void ViewGestureGeometryCollector::computeZoomInformationForNode(Node& node, FloatPoint& origin, FloatRect& renderRect, bool& isReplaced, double& viewportMinimumScale, double& viewportMaximumScale) -{ - renderRect = node.renderRect(&isReplaced); - if (node.document().isImageDocument()) { - if (HTMLImageElement* imageElement = static_cast<ImageDocument&>(node.document()).imageElement()) { - if (&node != imageElement) { - renderRect = imageElement->renderRect(&isReplaced); - FloatPoint newOrigin = origin; - if (origin.x() < renderRect.x() || origin.x() > renderRect.maxX()) - newOrigin.setX(renderRect.x() + renderRect.width() / 2); - if (origin.y() < renderRect.y() || origin.y() > renderRect.maxY()) - newOrigin.setY(renderRect.y() + renderRect.height() / 2); - origin = newOrigin; - } - isReplaced = true; - } - } -#if PLATFORM(MAC) - viewportMinimumScale = 0; - viewportMaximumScale = std::numeric_limits<double>::max(); -#else - viewportMinimumScale = m_webPage.minimumPageScaleFactor(); - viewportMaximumScale = m_webPage.maximumPageScaleFactor(); -#endif -} - -#if PLATFORM(MAC) -void ViewGestureGeometryCollector::collectGeometryForMagnificationGesture() -{ - FloatRect visibleContentRect = m_webPage.mainFrameView()->unobscuredContentRectIncludingScrollbars(); - bool frameHandlesMagnificationGesture = m_webPage.mainWebFrame()->handlesPageScaleGesture(); - m_webPage.send(Messages::ViewGestureController::DidCollectGeometryForMagnificationGesture(visibleContentRect, frameHandlesMagnificationGesture)); -} - -void ViewGestureGeometryCollector::mainFrameDidLayout() -{ - if (m_renderTreeSizeNotificationThreshold && m_webPage.renderTreeSize() >= m_renderTreeSizeNotificationThreshold) { - m_webPage.send(Messages::ViewGestureController::DidHitRenderTreeSizeThreshold()); - m_renderTreeSizeNotificationThreshold = 0; - } -} -#endif - -} // namespace WebKit - diff --git a/Source/WebKit2/WebProcess/WebPage/ViewGestureGeometryCollector.h b/Source/WebKit2/WebProcess/WebPage/ViewGestureGeometryCollector.h deleted file mode 100644 index 3b43cb71b..000000000 --- a/Source/WebKit2/WebProcess/WebPage/ViewGestureGeometryCollector.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ViewGestureGeometryCollector_h -#define ViewGestureGeometryCollector_h - -#include "MessageReceiver.h" -#include <wtf/RunLoop.h> - -namespace WebCore { -class FloatPoint; -class FloatRect; -class Node; -} - -namespace WebKit { - -class WebPage; - -class ViewGestureGeometryCollector : private IPC::MessageReceiver { -public: - ViewGestureGeometryCollector(WebPage&); - ~ViewGestureGeometryCollector(); - - void mainFrameDidLayout(); - -private: - // IPC::MessageReceiver. - virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; - - // Message handlers. - void collectGeometryForSmartMagnificationGesture(WebCore::FloatPoint origin); - -#if PLATFORM(MAC) - void collectGeometryForMagnificationGesture(); - void setRenderTreeSizeNotificationThreshold(uint64_t size) { m_renderTreeSizeNotificationThreshold = size; } - - void renderTreeSizeNotificationTimerFired(); -#endif - - void dispatchDidCollectGeometryForSmartMagnificationGesture(WebCore::FloatPoint origin, WebCore::FloatRect targetRect, WebCore::FloatRect visibleContentRect, bool isReplacedElement, double viewportMinimumScale, double viewportMaximumScale); - void computeZoomInformationForNode(WebCore::Node&, WebCore::FloatPoint& origin, WebCore::FloatRect& renderRect, bool& isReplaced, double& viewportMinimumScale, double& viewportMaximumScale); - - WebPage& m_webPage; - -#if PLATFORM(MAC) - uint64_t m_renderTreeSizeNotificationThreshold; -#endif -}; - -} // namespace WebKit - -#endif // ViewGestureGeometryCollector diff --git a/Source/WebKit2/WebProcess/WebPage/ViewGestureGeometryCollector.messages.in b/Source/WebKit2/WebProcess/WebPage/ViewGestureGeometryCollector.messages.in index 047209abe..efd051f80 100644 --- a/Source/WebKit2/WebProcess/WebPage/ViewGestureGeometryCollector.messages.in +++ b/Source/WebKit2/WebProcess/WebPage/ViewGestureGeometryCollector.messages.in @@ -20,12 +20,14 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#if !PLATFORM(IOS) + messages -> ViewGestureGeometryCollector { - CollectGeometryForSmartMagnificationGesture(WebCore::FloatPoint origin) -#if !PLATFORM(IOS) - CollectGeometryForMagnificationGesture() +CollectGeometryForMagnificationGesture() +CollectGeometryForSmartMagnificationGesture(WebCore::FloatPoint origin) - SetRenderTreeSizeNotificationThreshold(uint64_t size) -#endif +SetRenderTreeSizeNotificationThreshold(uint64_t size) } + +#endif diff --git a/Source/WebKit2/WebProcess/WebPage/ViewUpdateDispatcher.cpp b/Source/WebKit2/WebProcess/WebPage/ViewUpdateDispatcher.cpp deleted file mode 100644 index f65b02f42..000000000 --- a/Source/WebKit2/WebProcess/WebPage/ViewUpdateDispatcher.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ViewUpdateDispatcher.h" - -#if PLATFORM(IOS) - -#include "ViewUpdateDispatcherMessages.h" -#include "WebPage.h" -#include "WebProcess.h" -#include <wtf/RunLoop.h> - -namespace WebKit { - -Ref<ViewUpdateDispatcher> ViewUpdateDispatcher::create() -{ - return adoptRef(*new ViewUpdateDispatcher); -} - -ViewUpdateDispatcher::ViewUpdateDispatcher() - : m_queue(WorkQueue::create("com.apple.WebKit.ViewUpdateDispatcher")) -{ -} - -ViewUpdateDispatcher::~ViewUpdateDispatcher() -{ -} - -void ViewUpdateDispatcher::initializeConnection(IPC::Connection* connection) -{ - connection->addWorkQueueMessageReceiver(Messages::ViewUpdateDispatcher::messageReceiverName(), &m_queue.get(), this); -} - -void ViewUpdateDispatcher::visibleContentRectUpdate(uint64_t pageID, const VisibleContentRectUpdateInfo& visibleContentRectUpdateInfo) -{ - bool updateListWasEmpty; - { - LockHolder locker(&m_dataMutex); - updateListWasEmpty = m_latestUpdate.isEmpty(); - auto iterator = m_latestUpdate.find(pageID); - if (iterator == m_latestUpdate.end()) - m_latestUpdate.set<UpdateData>(pageID, { visibleContentRectUpdateInfo, visibleContentRectUpdateInfo.timestamp() }); - else - iterator->value.visibleContentRectUpdateInfo = visibleContentRectUpdateInfo; - } - if (updateListWasEmpty) { - RefPtr<ViewUpdateDispatcher> protector(this); - RunLoop::main().dispatch([protector] { - protector->dispatchVisibleContentRectUpdate(); - }); - } -} - -void ViewUpdateDispatcher::dispatchVisibleContentRectUpdate() -{ - HashMap<uint64_t, UpdateData> update; - { - LockHolder locker(&m_dataMutex); - update = WTFMove(m_latestUpdate); - } - - for (auto& slot : update) { - if (WebPage* webPage = WebProcess::singleton().webPage(slot.key)) - webPage->updateVisibleContentRects(slot.value.visibleContentRectUpdateInfo, slot.value.oldestTimestamp); - } -} - -} // namespace WebKit - -#endif // PLATFORM(IOS) diff --git a/Source/WebKit2/WebProcess/WebPage/ViewUpdateDispatcher.h b/Source/WebKit2/WebProcess/WebPage/ViewUpdateDispatcher.h deleted file mode 100644 index a4d02e76f..000000000 --- a/Source/WebKit2/WebProcess/WebPage/ViewUpdateDispatcher.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ViewUpdateDispatcher_h -#define ViewUpdateDispatcher_h - -#include "Connection.h" - -#include "VisibleContentRectUpdateInfo.h" -#include <wtf/HashMap.h> -#include <wtf/Lock.h> -#include <wtf/Ref.h> - -namespace WebKit { - -class ViewUpdateDispatcher : public IPC::Connection::WorkQueueMessageReceiver { -public: - static Ref<ViewUpdateDispatcher> create(); - ~ViewUpdateDispatcher(); - - void initializeConnection(IPC::Connection*); - -private: - ViewUpdateDispatcher(); - // IPC::Connection::WorkQueueMessageReceiver. - virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; - - void visibleContentRectUpdate(uint64_t pageID, const VisibleContentRectUpdateInfo&); - - void dispatchVisibleContentRectUpdate(); - - struct UpdateData { - VisibleContentRectUpdateInfo visibleContentRectUpdateInfo; - double oldestTimestamp; - }; - - Ref<WorkQueue> m_queue; - Lock m_dataMutex; - HashMap<uint64_t, UpdateData> m_latestUpdate; -}; - -} // namespace WebKit - -#endif // ViewportUpdateDispatcher_h diff --git a/Source/WebKit2/WebProcess/WebPage/ViewUpdateDispatcher.messages.in b/Source/WebKit2/WebProcess/WebPage/ViewUpdateDispatcher.messages.in deleted file mode 100644 index 17e2c8dd1..000000000 --- a/Source/WebKit2/WebProcess/WebPage/ViewUpdateDispatcher.messages.in +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright (C) 2014 Apple Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -messages -> ViewUpdateDispatcher { - VisibleContentRectUpdate(uint64_t pageID, WebKit::VisibleContentRectUpdateInfo visibleContentRectUpdateInfo) -} diff --git a/Source/WebKit2/WebProcess/WebPage/VisitedLinkTableController.cpp b/Source/WebKit2/WebProcess/WebPage/VisitedLinkTableController.cpp deleted file mode 100644 index 80e350a9e..000000000 --- a/Source/WebKit2/WebProcess/WebPage/VisitedLinkTableController.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "VisitedLinkTableController.h" - -#include "VisitedLinkStoreMessages.h" -#include "VisitedLinkTableControllerMessages.h" -#include "WebPage.h" -#include "WebProcess.h" -#include <WebCore/PageCache.h> -#include <wtf/NeverDestroyed.h> - -using namespace WebCore; - -namespace WebKit { - -static HashMap<uint64_t, VisitedLinkTableController*>& visitedLinkTableControllers() -{ - static NeverDestroyed<HashMap<uint64_t, VisitedLinkTableController*>> visitedLinkTableControllers; - - return visitedLinkTableControllers; -} - -PassRefPtr<VisitedLinkTableController> VisitedLinkTableController::getOrCreate(uint64_t identifier) -{ - auto& visitedLinkTableControllerPtr = visitedLinkTableControllers().add(identifier, nullptr).iterator->value; - if (visitedLinkTableControllerPtr) - return visitedLinkTableControllerPtr; - - RefPtr<VisitedLinkTableController> visitedLinkTableController = adoptRef(new VisitedLinkTableController(identifier)); - visitedLinkTableControllerPtr = visitedLinkTableController.get(); - - return visitedLinkTableController.release(); -} - -VisitedLinkTableController::VisitedLinkTableController(uint64_t identifier) - : m_identifier(identifier) -{ - WebProcess::singleton().addMessageReceiver(Messages::VisitedLinkTableController::messageReceiverName(), m_identifier, *this); -} - -VisitedLinkTableController::~VisitedLinkTableController() -{ - ASSERT(visitedLinkTableControllers().contains(m_identifier)); - - WebProcess::singleton().removeMessageReceiver(Messages::VisitedLinkTableController::messageReceiverName(), m_identifier); - - visitedLinkTableControllers().remove(m_identifier); -} - -bool VisitedLinkTableController::isLinkVisited(Page&, LinkHash linkHash, const URL&, const AtomicString&) -{ - return m_visitedLinkTable.isLinkVisited(linkHash); -} - -void VisitedLinkTableController::addVisitedLink(Page& page, LinkHash linkHash) -{ - if (m_visitedLinkTable.isLinkVisited(linkHash)) - return; - - WebPage* webPage = WebPage::fromCorePage(&page); - if (!webPage) - return; - - WebProcess::singleton().parentProcessConnection()->send(Messages::VisitedLinkStore::AddVisitedLinkHashFromPage(webPage->pageID(), linkHash), m_identifier); -} - -void VisitedLinkTableController::setVisitedLinkTable(const SharedMemory::Handle& handle) -{ - RefPtr<SharedMemory> sharedMemory = SharedMemory::map(handle, SharedMemory::Protection::ReadOnly); - if (!sharedMemory) - return; - - m_visitedLinkTable.setSharedMemory(sharedMemory.release()); - - invalidateStylesForAllLinks(); -} - -void VisitedLinkTableController::visitedLinkStateChanged(const Vector<WebCore::LinkHash>& linkHashes) -{ - for (auto linkHash : linkHashes) - invalidateStylesForLink(linkHash); -} - -void VisitedLinkTableController::allVisitedLinkStateChanged() -{ - invalidateStylesForAllLinks(); -} - -void VisitedLinkTableController::removeAllVisitedLinks() -{ - m_visitedLinkTable.clear(); - - invalidateStylesForAllLinks(); -} - -} // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/VisitedLinkTableController.h b/Source/WebKit2/WebProcess/WebPage/VisitedLinkTableController.h deleted file mode 100644 index bbfc8493c..000000000 --- a/Source/WebKit2/WebProcess/WebPage/VisitedLinkTableController.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef VisitedLinkTableController_h -#define VisitedLinkTableController_h - -#include "MessageReceiver.h" -#include "SharedMemory.h" -#include "VisitedLinkTable.h" -#include <WebCore/VisitedLinkStore.h> - -namespace WebKit { - -class VisitedLinkTableController final : public WebCore::VisitedLinkStore , private IPC::MessageReceiver { -public: - static PassRefPtr<VisitedLinkTableController> getOrCreate(uint64_t identifier); - virtual ~VisitedLinkTableController(); - -private: - explicit VisitedLinkTableController(uint64_t identifier); - - // WebCore::VisitedLinkStore. - virtual bool isLinkVisited(WebCore::Page&, WebCore::LinkHash, const WebCore::URL& baseURL, const AtomicString& attributeURL) override; - virtual void addVisitedLink(WebCore::Page&, WebCore::LinkHash) override; - - // IPC::MessageReceiver. - virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; - - void setVisitedLinkTable(const SharedMemory::Handle&); - void visitedLinkStateChanged(const Vector<WebCore::LinkHash>&); - void allVisitedLinkStateChanged(); - void removeAllVisitedLinks(); - - uint64_t m_identifier; - VisitedLinkTable m_visitedLinkTable; -}; - -} // namespace WebKit - -#endif // VisitedLinkTableController_h diff --git a/Source/WebKit2/WebProcess/WebPage/VisitedLinkTableController.messages.in b/Source/WebKit2/WebProcess/WebPage/VisitedLinkTableController.messages.in deleted file mode 100644 index 039dd3022..000000000 --- a/Source/WebKit2/WebProcess/WebPage/VisitedLinkTableController.messages.in +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright (C) 2014 Apple Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -messages -> VisitedLinkTableController { - SetVisitedLinkTable(WebKit::SharedMemory::Handle handle) - VisitedLinkStateChanged(Vector<WebCore::LinkHash> linkHashes) - AllVisitedLinkStateChanged() - RemoveAllVisitedLinks() -} diff --git a/Source/WebKit2/WebProcess/WebPage/WebBackForwardListProxy.cpp b/Source/WebKit2/WebProcess/WebPage/WebBackForwardListProxy.cpp index 76b29b238..11bb1a18f 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebBackForwardListProxy.cpp +++ b/Source/WebKit2/WebProcess/WebPage/WebBackForwardListProxy.cpp @@ -26,16 +26,14 @@ #include "config.h" #include "WebBackForwardListProxy.h" -#include "SessionState.h" -#include "SessionStateConversion.h" +#include "DataReference.h" +#include "EncoderAdapter.h" #include "WebCoreArgumentCoders.h" #include "WebPage.h" #include "WebPageProxyMessages.h" #include "WebProcess.h" #include "WebProcessProxyMessages.h" -#include <WebCore/HistoryController.h> #include <WebCore/HistoryItem.h> -#include <WebCore/MainFrame.h> #include <WebCore/PageCache.h> #include <wtf/HashMap.h> #include <wtf/NeverDestroyed.h> @@ -47,25 +45,20 @@ namespace WebKit { // FIXME <rdar://problem/8819268>: This leaks all HistoryItems that go into these maps. // We need to clear up the life time of these objects. -typedef HashMap<uint64_t, RefPtr<HistoryItem>> IDToHistoryItemMap; // "ID" here is the item ID. - -struct ItemAndPageID { - uint64_t itemID; - uint64_t pageID; -}; -typedef HashMap<RefPtr<HistoryItem>, ItemAndPageID> HistoryItemToIDMap; +typedef HashMap<uint64_t, RefPtr<HistoryItem>> IDToHistoryItemMap; +typedef HashMap<RefPtr<HistoryItem>, uint64_t> HistoryItemToIDMap; static IDToHistoryItemMap& idToHistoryItemMap() { - static NeverDestroyed<IDToHistoryItemMap> map; + static NeverDestroyed<IDToHistoryItemMap> map;; return map; -} +} static HistoryItemToIDMap& historyItemToIDMap() { static NeverDestroyed<HistoryItemToIDMap> map; return map; -} +} static uint64_t uniqueHistoryItemID = 1; @@ -89,28 +82,33 @@ void WebBackForwardListProxy::setHighestItemIDFromUIProcess(uint64_t itemID) uniqueHistoryItemID = itemID + 1; } -static void updateBackForwardItem(uint64_t itemID, uint64_t pageID, HistoryItem* item) +static void updateBackForwardItem(uint64_t itemID, HistoryItem* item) { - WebProcess::singleton().parentProcessConnection()->send(Messages::WebProcessProxy::AddBackForwardItem(itemID, pageID, toPageState(*item)), 0); + EncoderAdapter encoder; + item->encodeBackForwardTree(encoder); + + WebProcess::shared().parentProcessConnection()->send(Messages::WebProcessProxy::AddBackForwardItem(itemID, item->originalURLString(), item->urlString(), item->title(), encoder.dataReference()), 0); } -void WebBackForwardListProxy::addItemFromUIProcess(uint64_t itemID, Ref<HistoryItem>&& item, uint64_t pageID) +void WebBackForwardListProxy::addItemFromUIProcess(uint64_t itemID, PassRefPtr<WebCore::HistoryItem> prpItem) { + RefPtr<HistoryItem> item = prpItem; + // This item/itemID pair should not already exist in our maps. - ASSERT(!historyItemToIDMap().contains(item.ptr())); + ASSERT(!historyItemToIDMap().contains(item.get())); ASSERT(!idToHistoryItemMap().contains(itemID)); - - historyItemToIDMap().set<ItemAndPageID>(item.ptr(), { .itemID = itemID, .pageID = pageID }); - idToHistoryItemMap().set(itemID, item.ptr()); + + historyItemToIDMap().set(item, itemID); + idToHistoryItemMap().set(itemID, item); } static void WK2NotifyHistoryItemChanged(HistoryItem* item) { - ItemAndPageID ids = historyItemToIDMap().get(item); - if (!ids.itemID) + uint64_t itemID = historyItemToIDMap().get(item); + if (!itemID) return; - updateBackForwardItem(ids.itemID, ids.pageID, item); + updateBackForwardItem(itemID, item); } HistoryItem* WebBackForwardListProxy::itemForID(uint64_t itemID) @@ -121,7 +119,7 @@ HistoryItem* WebBackForwardListProxy::itemForID(uint64_t itemID) uint64_t WebBackForwardListProxy::idForItem(HistoryItem* item) { ASSERT(item); - return historyItemToIDMap().get(item).itemID; + return historyItemToIDMap().get(item); } void WebBackForwardListProxy::removeItem(uint64_t itemID) @@ -130,8 +128,7 @@ void WebBackForwardListProxy::removeItem(uint64_t itemID) if (!item) return; - PageCache::singleton().remove(*item); - WebCore::Page::clearPreviousItemFromAllPages(item.get()); + pageCache()->remove(item.get()); historyItemToIDMap().remove(item); } @@ -141,9 +138,11 @@ WebBackForwardListProxy::WebBackForwardListProxy(WebPage* page) WebCore::notifyHistoryItemChanged = WK2NotifyHistoryItemChanged; } -void WebBackForwardListProxy::addItem(Ref<HistoryItem>&& item) +void WebBackForwardListProxy::addItem(PassRefPtr<HistoryItem> prpItem) { - ASSERT(!historyItemToIDMap().contains(item.ptr())); + RefPtr<HistoryItem> item = prpItem; + + ASSERT(!historyItemToIDMap().contains(item)); if (!m_page) return; @@ -154,10 +153,10 @@ void WebBackForwardListProxy::addItem(Ref<HistoryItem>&& item) m_associatedItemIDs.add(itemID); - historyItemToIDMap().set<ItemAndPageID>(item.ptr(), { .itemID = itemID, .pageID = m_page->pageID() }); - idToHistoryItemMap().set(itemID, item.ptr()); + historyItemToIDMap().set(item, itemID); + idToHistoryItemMap().set(itemID, item); - updateBackForwardItem(itemID, m_page->pageID(), item.ptr()); + updateBackForwardItem(itemID, item.get()); m_page->send(Messages::WebPageProxy::BackForwardAddItem(itemID)); } @@ -167,7 +166,7 @@ void WebBackForwardListProxy::goToItem(HistoryItem* item) return; SandboxExtension::Handle sandboxExtensionHandle; - m_page->sendSync(Messages::WebPageProxy::BackForwardGoToItem(historyItemToIDMap().get(item).itemID), Messages::WebPageProxy::BackForwardGoToItem::Reply(sandboxExtensionHandle)); + m_page->sendSync(Messages::WebPageProxy::BackForwardGoToItem(historyItemToIDMap().get(item)), Messages::WebPageProxy::BackForwardGoToItem::Reply(sandboxExtensionHandle)); m_page->sandboxExtensionTracker().beginLoad(m_page->mainWebFrame(), sandboxExtensionHandle); } @@ -177,7 +176,7 @@ HistoryItem* WebBackForwardListProxy::itemAtIndex(int itemIndex) return 0; uint64_t itemID = 0; - if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::BackForwardItemAtIndex(itemIndex), Messages::WebPageProxy::BackForwardItemAtIndex::Reply(itemID), m_page->pageID())) + if (!WebProcess::shared().parentProcessConnection()->sendSync(Messages::WebPageProxy::BackForwardItemAtIndex(itemIndex), Messages::WebPageProxy::BackForwardItemAtIndex::Reply(itemID), m_page->pageID())) return 0; if (!itemID) @@ -192,7 +191,7 @@ int WebBackForwardListProxy::backListCount() return 0; int backListCount = 0; - if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::BackForwardBackListCount(), Messages::WebPageProxy::BackForwardBackListCount::Reply(backListCount), m_page->pageID())) + if (!WebProcess::shared().parentProcessConnection()->sendSync(Messages::WebPageProxy::BackForwardBackListCount(), Messages::WebPageProxy::BackForwardBackListCount::Reply(backListCount), m_page->pageID())) return 0; return backListCount; @@ -204,7 +203,7 @@ int WebBackForwardListProxy::forwardListCount() return 0; int forwardListCount = 0; - if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::BackForwardForwardListCount(), Messages::WebPageProxy::BackForwardForwardListCount::Reply(forwardListCount), m_page->pageID())) + if (!WebProcess::shared().parentProcessConnection()->sendSync(Messages::WebPageProxy::BackForwardForwardListCount(), Messages::WebPageProxy::BackForwardForwardListCount::Reply(forwardListCount), m_page->pageID())) return 0; return forwardListCount; @@ -212,13 +211,13 @@ int WebBackForwardListProxy::forwardListCount() void WebBackForwardListProxy::close() { - for (auto& itemID : m_associatedItemIDs) { - if (HistoryItem* item = itemForID(itemID)) - WebCore::PageCache::singleton().remove(*item); - } + HashSet<uint64_t>::iterator end = m_associatedItemIDs.end(); + for (HashSet<uint64_t>::iterator i = m_associatedItemIDs.begin(); i != end; ++i) + WebCore::pageCache()->remove(itemForID(*i)); m_associatedItemIDs.clear(); - m_page = nullptr; + + m_page = 0; } bool WebBackForwardListProxy::isActive() diff --git a/Source/WebKit2/WebProcess/WebPage/WebBackForwardListProxy.h b/Source/WebKit2/WebProcess/WebPage/WebBackForwardListProxy.h index 5136bb946..e47eed74f 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebBackForwardListProxy.h +++ b/Source/WebKit2/WebProcess/WebPage/WebBackForwardListProxy.h @@ -36,13 +36,13 @@ class WebPage; class WebBackForwardListProxy : public WebCore::BackForwardClient { public: - static Ref<WebBackForwardListProxy> create(WebPage* page) { return adoptRef(*new WebBackForwardListProxy(page)); } + static PassRefPtr<WebBackForwardListProxy> create(WebPage* page) { return adoptRef(new WebBackForwardListProxy(page)); } static WebCore::HistoryItem* itemForID(uint64_t); static uint64_t idForItem(WebCore::HistoryItem*); static void removeItem(uint64_t itemID); - static void addItemFromUIProcess(uint64_t itemID, Ref<WebCore::HistoryItem>&&, uint64_t pageID); + static void addItemFromUIProcess(uint64_t itemID, PassRefPtr<WebCore::HistoryItem>); static void setHighestItemIDFromUIProcess(uint64_t itemID); void clear(); @@ -50,17 +50,17 @@ public: private: WebBackForwardListProxy(WebPage*); - virtual void addItem(Ref<WebCore::HistoryItem>&&) override; + virtual void addItem(PassRefPtr<WebCore::HistoryItem>); - virtual void goToItem(WebCore::HistoryItem*) override; + virtual void goToItem(WebCore::HistoryItem*); - virtual WebCore::HistoryItem* itemAtIndex(int) override; - virtual int backListCount() override; - virtual int forwardListCount() override; + virtual WebCore::HistoryItem* itemAtIndex(int); + virtual int backListCount(); + virtual int forwardListCount(); virtual bool isActive(); - virtual void close() override; + virtual void close(); #if PLATFORM(IOS) virtual unsigned current() override; diff --git a/Source/WebKit2/WebProcess/WebPage/WebContextMenu.cpp b/Source/WebKit2/WebProcess/WebPage/WebContextMenu.cpp index 4a663d295..f6c940e7a 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebContextMenu.cpp +++ b/Source/WebKit2/WebProcess/WebPage/WebContextMenu.cpp @@ -25,12 +25,12 @@ #include "WebContextMenu.h" -#include "ContextMenuContextData.h" -#include "UserData.h" +#include "InjectedBundleHitTestResult.h" +#include "InjectedBundleUserMessageCoders.h" #include "WebCoreArgumentCoders.h" +#include "WebHitTestResult.h" #include "WebPage.h" #include "WebPageProxyMessages.h" -#include "WebProcess.h" #include <WebCore/ContextMenu.h> #include <WebCore/ContextMenuController.h> #include <WebCore/Frame.h> @@ -53,6 +53,9 @@ WebContextMenu::~WebContextMenu() void WebContextMenu::show() { ContextMenuController& controller = m_page->corePage()->contextMenuController(); + ContextMenu* menu = controller.contextMenu(); + if (!menu) + return; Frame* frame = controller.hitTestResult().innerNodeFrame(); if (!frame) return; @@ -63,19 +66,17 @@ void WebContextMenu::show() Vector<WebContextMenuItemData> menuItems; RefPtr<API::Object> userData; menuItemsWithUserData(menuItems, userData); - - auto menuLocation = view->contentsToRootView(controller.hitTestResult().roundedPointInInnerNodeFrame()); - - ContextMenuContextData contextMenuContextData(menuLocation, menuItems, controller.context()); + WebHitTestResult::Data webHitTestResultData(controller.hitTestResult()); // Mark the WebPage has having a shown context menu then notify the UIProcess. m_page->contextMenuShowing(); - m_page->send(Messages::WebPageProxy::ShowContextMenu(contextMenuContextData, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get()))); + m_page->send(Messages::WebPageProxy::ShowContextMenu(view->contentsToWindow(controller.hitTestResult().roundedPointInInnerNodeFrame()), webHitTestResultData, menuItems, InjectedBundleUserMessageEncoder(userData.get()))); } void WebContextMenu::itemSelected(const WebContextMenuItemData& item) { - m_page->corePage()->contextMenuController().contextMenuItemSelected(static_cast<ContextMenuAction>(item.action()), item.title()); + ContextMenuItem coreItem(ActionType, static_cast<ContextMenuAction>(item.action()), item.title()); + m_page->corePage()->contextMenuController().contextMenuItemSelected(&coreItem); } void WebContextMenu::menuItemsWithUserData(Vector<WebContextMenuItemData> &menuItems, RefPtr<API::Object>& userData) const @@ -87,11 +88,17 @@ void WebContextMenu::menuItemsWithUserData(Vector<WebContextMenuItemData> &menuI return; // Give the bundle client a chance to process the menu. +#if USE(CROSS_PLATFORM_CONTEXT_MENUS) const Vector<ContextMenuItem>& coreItems = menu->items(); - - if (m_page->injectedBundleContextMenuClient().getCustomMenuFromDefaultItems(*m_page, controller.hitTestResult(), coreItems, menuItems, userData)) - return; - menuItems = kitItems(coreItems); +#else + Vector<ContextMenuItem> coreItems = contextMenuItemVector(menu->platformDescription()); +#endif + Vector<WebContextMenuItemData> proposedMenu = kitItems(coreItems, menu); + Vector<WebContextMenuItemData> newMenu; + RefPtr<InjectedBundleHitTestResult> hitTestResult = InjectedBundleHitTestResult::create(controller.hitTestResult()); + if (m_page->injectedBundleContextMenuClient().getCustomMenuFromDefaultItems(m_page, hitTestResult.get(), proposedMenu, newMenu, userData)) + proposedMenu = newMenu; + menuItems = proposedMenu; } Vector<WebContextMenuItemData> WebContextMenu::items() const diff --git a/Source/WebKit2/WebProcess/WebPage/WebContextMenu.h b/Source/WebKit2/WebProcess/WebPage/WebContextMenu.h index 9015ffe15..75ed7e69a 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebContextMenu.h +++ b/Source/WebKit2/WebProcess/WebPage/WebContextMenu.h @@ -28,20 +28,15 @@ #include <wtf/PassRefPtr.h> #include <wtf/RefCounted.h> -namespace WebCore { -class Image; -} - namespace WebKit { -class ShareableBitmap; class WebPage; class WebContextMenu : public RefCounted<WebContextMenu> { public: - static Ref<WebContextMenu> create(WebPage* page) + static PassRefPtr<WebContextMenu> create(WebPage* page) { - return adoptRef(*new WebContextMenu(page)); + return adoptRef(new WebContextMenu(page)); } ~WebContextMenu(); diff --git a/Source/WebKit2/WebProcess/WebPage/WebDocumentLoader.cpp b/Source/WebKit2/WebProcess/WebPage/WebDocumentLoader.cpp index 56fea2208..4b6a1633c 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebDocumentLoader.cpp +++ b/Source/WebKit2/WebProcess/WebPage/WebDocumentLoader.cpp @@ -26,8 +26,6 @@ #include "config.h" #include "WebDocumentLoader.h" -#include "WebFrame.h" - using namespace WebCore; namespace WebKit { @@ -38,16 +36,6 @@ WebDocumentLoader::WebDocumentLoader(const ResourceRequest& request, const Subst { } -void WebDocumentLoader::detachFromFrame() -{ - if (m_navigationID) - WebFrame::fromCoreFrame(*frame())->documentLoaderDetached(m_navigationID); - - m_navigationID = 0; - - DocumentLoader::detachFromFrame(); -} - void WebDocumentLoader::setNavigationID(uint64_t navigationID) { ASSERT(navigationID); diff --git a/Source/WebKit2/WebProcess/WebPage/WebDocumentLoader.h b/Source/WebKit2/WebProcess/WebPage/WebDocumentLoader.h index ac3916c8e..90476107a 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebDocumentLoader.h +++ b/Source/WebKit2/WebProcess/WebPage/WebDocumentLoader.h @@ -32,9 +32,9 @@ namespace WebKit { class WebDocumentLoader : public WebCore::DocumentLoader { public: - static Ref<WebDocumentLoader> create(const WebCore::ResourceRequest& request, const WebCore::SubstituteData& data) + static PassRefPtr<WebDocumentLoader> create(const WebCore::ResourceRequest& request, const WebCore::SubstituteData& data) { - return adoptRef(*new WebDocumentLoader(request, data)); + return adoptRef(new WebDocumentLoader(request, data)); } uint64_t navigationID() const { return m_navigationID; } @@ -43,8 +43,6 @@ public: private: WebDocumentLoader(const WebCore::ResourceRequest&, const WebCore::SubstituteData&); - virtual void detachFromFrame() override; - uint64_t m_navigationID; }; diff --git a/Source/WebKit2/WebProcess/WebPage/WebFrame.cpp b/Source/WebKit2/WebProcess/WebPage/WebFrame.cpp index a22192d95..4b9845d86 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebFrame.cpp +++ b/Source/WebKit2/WebProcess/WebPage/WebFrame.cpp @@ -28,19 +28,14 @@ #include "APIArray.h" #include "DownloadManager.h" -#include "InjectedBundleFileHandle.h" #include "InjectedBundleHitTestResult.h" #include "InjectedBundleNodeHandle.h" #include "InjectedBundleRangeHandle.h" #include "InjectedBundleScriptWorld.h" -#include "NetworkConnectionToWebProcessMessages.h" -#include "NetworkProcessConnection.h" #include "PluginView.h" #include "WKAPICast.h" #include "WKBundleAPICast.h" #include "WebChromeClient.h" -#include "WebCoreArgumentCoders.h" -#include "WebDocumentLoader.h" #include "WebPage.h" #include "WebPageProxyMessages.h" #include "WebProcess.h" @@ -49,23 +44,18 @@ #include <JavaScriptCore/JSLock.h> #include <JavaScriptCore/JSValueRef.h> #include <WebCore/ArchiveResource.h> -#include <WebCore/CertificateInfo.h> #include <WebCore/Chrome.h> #include <WebCore/DocumentLoader.h> #include <WebCore/EventHandler.h> -#include <WebCore/File.h> #include <WebCore/Frame.h> -#include <WebCore/FrameSnapshotting.h> #include <WebCore/FrameView.h> #include <WebCore/HTMLFormElement.h> #include <WebCore/HTMLFrameOwnerElement.h> #include <WebCore/HTMLInputElement.h> #include <WebCore/HTMLNames.h> #include <WebCore/HTMLTextAreaElement.h> -#include <WebCore/ImageBuffer.h> #include <WebCore/JSCSSStyleDeclaration.h> #include <WebCore/JSElement.h> -#include <WebCore/JSFile.h> #include <WebCore/JSRange.h> #include <WebCore/MainFrame.h> #include <WebCore/NetworkingContext.h> @@ -73,17 +63,24 @@ #include <WebCore/Page.h> #include <WebCore/PluginDocument.h> #include <WebCore/RenderTreeAsText.h> +#include <WebCore/ResourceBuffer.h> +#include <WebCore/ResourceLoader.h> #include <WebCore/ScriptController.h> #include <WebCore/SecurityOrigin.h> -#include <WebCore/SubresourceLoader.h> #include <WebCore/TextIterator.h> #include <WebCore/TextResourceDecoder.h> #include <wtf/text/StringBuilder.h> -#if PLATFORM(COCOA) +#if PLATFORM(MAC) #include <WebCore/LegacyWebArchive.h> #endif +#if ENABLE(NETWORK_PROCESS) +#include "NetworkConnectionToWebProcessMessages.h" +#include "NetworkProcessConnection.h" +#include "WebCoreArgumentCoders.h" +#endif + #ifndef NDEBUG #include <wtf/RefCountedLeakCounter.h> #endif @@ -110,7 +107,7 @@ static uint64_t generateListenerID() PassRefPtr<WebFrame> WebFrame::createWithCoreMainFrame(WebPage* page, WebCore::Frame* coreFrame) { RefPtr<WebFrame> frame = create(std::unique_ptr<WebFrameLoaderClient>(static_cast<WebFrameLoaderClient*>(&coreFrame->loader().client()))); - page->send(Messages::WebPageProxy::DidCreateMainFrame(frame->frameID()), page->pageID(), IPC::DispatchMessageEvenWhenWaitingForSyncReply); + page->send(Messages::WebPageProxy::DidCreateMainFrame(frame->frameID())); frame->m_coreFrame = coreFrame; frame->m_coreFrame->tree().setName(String()); @@ -121,14 +118,14 @@ PassRefPtr<WebFrame> WebFrame::createWithCoreMainFrame(WebPage* page, WebCore::F PassRefPtr<WebFrame> WebFrame::createSubframe(WebPage* page, const String& frameName, HTMLFrameOwnerElement* ownerElement) { RefPtr<WebFrame> frame = create(std::make_unique<WebFrameLoaderClient>()); - page->send(Messages::WebPageProxy::DidCreateSubframe(frame->frameID()), page->pageID(), IPC::DispatchMessageEvenWhenWaitingForSyncReply); + page->send(Messages::WebPageProxy::DidCreateSubframe(frame->frameID())); - Ref<WebCore::Frame> coreFrame = Frame::create(page->corePage(), ownerElement, frame->m_frameLoaderClient.get()); - frame->m_coreFrame = coreFrame.ptr(); + RefPtr<Frame> coreFrame = Frame::create(page->corePage(), ownerElement, frame->m_frameLoaderClient.get()); + frame->m_coreFrame = coreFrame.get(); frame->m_coreFrame->tree().setName(frameName); if (ownerElement) { ASSERT(ownerElement->document().frame()); - ownerElement->document().frame()->tree().appendChild(WTFMove(coreFrame)); + ownerElement->document().frame()->tree().appendChild(coreFrame.release()); } frame->m_coreFrame->init(); return frame.release(); @@ -136,7 +133,7 @@ PassRefPtr<WebFrame> WebFrame::createSubframe(WebPage* page, const String& frame PassRefPtr<WebFrame> WebFrame::create(std::unique_ptr<WebFrameLoaderClient> frameLoaderClient) { - RefPtr<WebFrame> frame = adoptRef(new WebFrame(WTFMove(frameLoaderClient))); + RefPtr<WebFrame> frame = adoptRef(new WebFrame(std::move(frameLoaderClient))); // Add explict ref() that will be balanced in WebFrameLoaderClient::frameLoaderDestroyed(). frame->ref(); @@ -149,15 +146,12 @@ WebFrame::WebFrame(std::unique_ptr<WebFrameLoaderClient> frameLoaderClient) , m_policyListenerID(0) , m_policyFunction(0) , m_policyDownloadID(0) - , m_frameLoaderClient(WTFMove(frameLoaderClient)) + , m_frameLoaderClient(std::move(frameLoaderClient)) , m_loadListener(0) , m_frameID(generateFrameID()) -#if PLATFORM(IOS) - , m_firstLayerTreeTransactionIDAfterDidCommitLoad(0) -#endif { m_frameLoaderClient->setWebFrame(this); - WebProcess::singleton().addWebFrame(m_frameID, this); + WebProcess::shared().addWebFrame(m_frameID, this); #ifndef NDEBUG webFrameCounter.increment(); @@ -184,18 +178,9 @@ WebPage* WebFrame::page() const return 0; } -WebFrame* WebFrame::fromCoreFrame(Frame& frame) -{ - auto* webFrameLoaderClient = toWebFrameLoaderClient(frame.loader().client()); - if (!webFrameLoaderClient) - return nullptr; - - return webFrameLoaderClient->webFrame(); -} - void WebFrame::invalidate() { - WebProcess::singleton().removeWebFrame(m_frameID); + WebProcess::shared().removeWebFrame(m_frameID); m_coreFrame = 0; } @@ -215,12 +200,12 @@ void WebFrame::invalidatePolicyListener() if (!m_policyListenerID) return; - m_policyDownloadID = { }; + m_policyDownloadID = 0; m_policyListenerID = 0; m_policyFunction = 0; } -void WebFrame::didReceivePolicyDecision(uint64_t listenerID, PolicyAction action, uint64_t navigationID, DownloadID downloadID) +void WebFrame::didReceivePolicyDecision(uint64_t listenerID, PolicyAction action, uint64_t downloadID) { if (!m_coreFrame) return; @@ -233,54 +218,65 @@ void WebFrame::didReceivePolicyDecision(uint64_t listenerID, PolicyAction action ASSERT(m_policyFunction); - FramePolicyFunction function = WTFMove(m_policyFunction); + FramePolicyFunction function = std::move(m_policyFunction); invalidatePolicyListener(); m_policyDownloadID = downloadID; - if (navigationID) { - if (WebDocumentLoader* documentLoader = static_cast<WebDocumentLoader*>(m_coreFrame->loader().policyDocumentLoader())) - documentLoader->setNavigationID(navigationID); - } - function(action); } void WebFrame::startDownload(const WebCore::ResourceRequest& request) { - ASSERT(m_policyDownloadID.downloadID()); + ASSERT(m_policyDownloadID); + + uint64_t policyDownloadID = m_policyDownloadID; + m_policyDownloadID = 0; - auto policyDownloadID = m_policyDownloadID; - m_policyDownloadID = { }; +#if ENABLE(NETWORK_PROCESS) + if (WebProcess::shared().usesNetworkProcess()) { + WebProcess::shared().networkConnection()->connection()->send(Messages::NetworkConnectionToWebProcess::StartDownload(page()->sessionID(), policyDownloadID, request), 0); + return; + } +#endif - auto& webProcess = WebProcess::singleton(); - SessionID sessionID = page() ? page()->sessionID() : SessionID::defaultSessionID(); - webProcess.networkConnection()->connection()->send(Messages::NetworkConnectionToWebProcess::StartDownload(sessionID, policyDownloadID, request), 0); + WebProcess::shared().downloadManager().startDownload(policyDownloadID, request); } -void WebFrame::convertMainResourceLoadToDownload(DocumentLoader* documentLoader, SessionID sessionID, const ResourceRequest& request, const ResourceResponse& response) +void WebFrame::convertMainResourceLoadToDownload(DocumentLoader* documentLoader, const ResourceRequest& request, const ResourceResponse& response) { - ASSERT(m_policyDownloadID.downloadID()); + ASSERT(m_policyDownloadID); - auto policyDownloadID = m_policyDownloadID; - m_policyDownloadID = { }; + uint64_t policyDownloadID = m_policyDownloadID; + m_policyDownloadID = 0; - SubresourceLoader* mainResourceLoader = documentLoader->mainResourceLoader(); + ResourceLoader* mainResourceLoader = documentLoader->mainResourceLoader(); - auto& webProcess = WebProcess::singleton(); - // Use 0 to indicate that the resource load can't be converted and a new download must be started. - // This can happen if there is no loader because the main resource is in the WebCore memory cache, - // or because the conversion was attempted when not calling SubresourceLoader::didReceiveResponse(). - uint64_t mainResourceLoadIdentifier; - if (mainResourceLoader) - mainResourceLoadIdentifier = mainResourceLoader->identifier(); - else - mainResourceLoadIdentifier = 0; +#if ENABLE(NETWORK_PROCESS) + if (WebProcess::shared().usesNetworkProcess()) { + // Use 0 to indicate that there is no main resource loader. + // This can happen if the main resource is in the WebCore memory cache. + uint64_t mainResourceLoadIdentifier; + if (mainResourceLoader) + mainResourceLoadIdentifier = mainResourceLoader->identifier(); + else + mainResourceLoadIdentifier = 0; - webProcess.networkConnection()->connection()->send(Messages::NetworkConnectionToWebProcess::ConvertMainResourceLoadToDownload(sessionID, mainResourceLoadIdentifier, policyDownloadID, request, response), 0); + WebProcess::shared().networkConnection()->connection()->send(Messages::NetworkConnectionToWebProcess::ConvertMainResourceLoadToDownload(mainResourceLoadIdentifier, policyDownloadID, request, response), 0); + return; + } +#endif + + if (!mainResourceLoader) { + // The main resource has already been loaded. Start a new download instead. + WebProcess::shared().downloadManager().startDownload(policyDownloadID, request); + return; + } + + WebProcess::shared().downloadManager().convertHandleToDownload(policyDownloadID, documentLoader->mainResourceLoader()->handle(), request, response); } -String WebFrame::source() const +String WebFrame::source() const { if (!m_coreFrame) return String(); @@ -293,7 +289,7 @@ String WebFrame::source() const DocumentLoader* documentLoader = m_coreFrame->loader().activeDocumentLoader(); if (!documentLoader) return String(); - RefPtr<SharedBuffer> mainResourceData = documentLoader->mainResourceData(); + RefPtr<ResourceBuffer> mainResourceData = documentLoader->mainResourceData(); if (!mainResourceData) return String(); return decoder->encoding().decode(mainResourceData->data(), mainResourceData->size()); @@ -310,7 +306,8 @@ String WebFrame::contentsAsString() const if (!builder.isEmpty()) builder.append(' '); - WebFrame* webFrame = WebFrame::fromCoreFrame(*child); + WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(child->loader().client()); + WebFrame* webFrame = webFrameLoaderClient ? webFrameLoaderClient->webFrame() : 0; ASSERT(webFrame); builder.append(webFrame->contentsAsString()); @@ -396,18 +393,6 @@ String WebFrame::url() const return documentLoader->url().string(); } -WebCore::CertificateInfo WebFrame::certificateInfo() const -{ - if (!m_coreFrame) - return CertificateInfo(); - - DocumentLoader* documentLoader = m_coreFrame->loader().documentLoader(); - if (!documentLoader) - return CertificateInfo(); - - return documentLoader->response().certificateInfo(); -} - String WebFrame::innerText() const { if (!m_coreFrame) @@ -424,10 +409,11 @@ WebFrame* WebFrame::parentFrame() const if (!m_coreFrame || !m_coreFrame->ownerElement()) return 0; - return WebFrame::fromCoreFrame(*m_coreFrame->ownerElement()->document().frame()); + WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(m_coreFrame->ownerElement()->document().frame()->loader().client()); + return webFrameLoaderClient ? webFrameLoaderClient->webFrame() : 0; } -Ref<API::Array> WebFrame::childFrames() +PassRefPtr<API::Array> WebFrame::childFrames() { if (!m_coreFrame) return API::Array::create(); @@ -440,12 +426,13 @@ Ref<API::Array> WebFrame::childFrames() vector.reserveInitialCapacity(size); for (Frame* child = m_coreFrame->tree().firstChild(); child; child = child->tree().nextSibling()) { - WebFrame* webFrame = WebFrame::fromCoreFrame(*child); + WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(child->loader().client()); + WebFrame* webFrame = webFrameLoaderClient ? webFrameLoaderClient->webFrame() : 0; ASSERT(webFrame); vector.uncheckedAppend(webFrame); } - return API::Array::create(WTFMove(vector)); + return API::Array::create(std::move(vector)); } String WebFrame::layerTreeAsText() const @@ -492,35 +479,6 @@ bool WebFrame::handlesPageScaleGesture() const return pluginView && pluginView->handlesPageScaleFactor(); } -bool WebFrame::requiresUnifiedScaleFactor() const -{ - if (!m_coreFrame->document()->isPluginDocument()) - return 0; - - PluginDocument* pluginDocument = static_cast<PluginDocument*>(m_coreFrame->document()); - PluginView* pluginView = static_cast<PluginView*>(pluginDocument->pluginWidget()); - return pluginView && pluginView->requiresUnifiedScaleFactor(); -} - -void WebFrame::setAccessibleName(const String& accessibleName) -{ - if (!AXObjectCache::accessibilityEnabled()) - return; - - if (!m_coreFrame) - return; - - auto* document = m_coreFrame->document(); - if (!document) - return; - - auto* rootObject = document->axObjectCache()->rootObject(); - if (!rootObject) - return; - - rootObject->setAccessibleName(accessibleName); -} - IntRect WebFrame::contentBounds() const { if (!m_coreFrame) @@ -568,7 +526,7 @@ IntSize WebFrame::scrollOffset() const if (!view) return IntSize(); - return toIntSize(view->scrollPosition()); + return view->scrollOffset(); } bool WebFrame::hasHorizontalScrollbar() const @@ -629,10 +587,10 @@ bool WebFrame::containsAnyFormElements() const if (!document) return false; - for (Node* node = document->documentElement(); node; node = NodeTraversal::next(*node)) { - if (!is<Element>(*node)) + for (Node* node = document->documentElement(); node; node = NodeTraversal::next(node)) { + if (!node->isElementNode()) continue; - if (is<HTMLFormElement>(*node)) + if (isHTMLFormElement(node)) return true; } return false; @@ -647,10 +605,10 @@ bool WebFrame::containsAnyFormControls() const if (!document) return false; - for (Node* node = document->documentElement(); node; node = NodeTraversal::next(*node)) { - if (!is<Element>(*node)) + for (Node* node = document->documentElement(); node; node = NodeTraversal::next(node)) { + if (!node->isElementNode()) continue; - if (is<HTMLInputElement>(*node) || is<HTMLSelectElement>(*node) || is<HTMLTextAreaElement>(*node)) + if (isHTMLInputElement(node) || isHTMLSelectElement(node) || isHTMLTextAreaElement(node)) return true; } return false; @@ -671,8 +629,10 @@ WebFrame* WebFrame::frameForContext(JSContextRef context) if (strcmp(globalObjectObj->classInfo()->className, "JSDOMWindowShell") != 0) return 0; - Frame* frame = static_cast<JSDOMWindowShell*>(globalObjectObj)->window()->wrapped().frame(); - return WebFrame::fromCoreFrame(*frame); + Frame* coreFrame = static_cast<JSDOMWindowShell*>(globalObjectObj)->window()->impl().frame(); + + WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(coreFrame->loader().client()); + return webFrameLoaderClient ? webFrameLoaderClient->webFrame() : 0; } JSValueRef WebFrame::jsWrapperForWorld(InjectedBundleNodeHandle* nodeHandle, InjectedBundleScriptWorld* world) @@ -699,24 +659,12 @@ JSValueRef WebFrame::jsWrapperForWorld(InjectedBundleRangeHandle* rangeHandle, I return toRef(exec, toJS(exec, globalObject, rangeHandle->coreRange())); } -JSValueRef WebFrame::jsWrapperForWorld(InjectedBundleFileHandle* fileHandle, InjectedBundleScriptWorld* world) -{ - if (!m_coreFrame) - return nullptr; - - JSDOMWindow* globalObject = m_coreFrame->script().globalObject(world->coreWorld()); - ExecState* exec = globalObject->globalExec(); - - JSLockHolder lock(exec); - return toRef(exec, toJS(exec, globalObject, fileHandle->coreFile())); -} - String WebFrame::counterValue(JSObjectRef element) { if (!toJS(element)->inherits(JSElement::info())) return String(); - return counterValueForElement(&jsCast<JSElement*>(toJS(element))->wrapped()); + return counterValueForElement(&jsCast<JSElement*>(toJS(element))->impl()); } String WebFrame::provisionalURL() const @@ -786,19 +734,15 @@ void WebFrame::setTextDirection(const String& direction) m_coreFrame->editor().setBaseWritingDirection(RightToLeftWritingDirection); } -void WebFrame::documentLoaderDetached(uint64_t navigationID) -{ - page()->send(Messages::WebPageProxy::DidDestroyNavigation(navigationID)); -} - -#if PLATFORM(COCOA) +#if PLATFORM(MAC) RetainPtr<CFDataRef> WebFrame::webArchiveData(FrameFilterFunction callback, void* context) { RefPtr<LegacyWebArchive> archive = LegacyWebArchive::create(coreFrame()->document(), [this, callback, context](Frame& frame) -> bool { if (!callback) return true; - WebFrame* webFrame = WebFrame::fromCoreFrame(frame); + WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame.loader().client()); + WebFrame* webFrame = webFrameLoaderClient ? webFrameLoaderClient->webFrame() : 0; ASSERT(webFrame); return callback(toAPI(this), toAPI(webFrame), context); @@ -810,25 +754,5 @@ RetainPtr<CFDataRef> WebFrame::webArchiveData(FrameFilterFunction callback, void return archive->rawDataRepresentation(); } #endif - -PassRefPtr<ShareableBitmap> WebFrame::createSelectionSnapshot() const -{ - std::unique_ptr<ImageBuffer> snapshot = snapshotSelection(*coreFrame(), WebCore::SnapshotOptionsForceBlackText); - if (!snapshot) - return nullptr; - - RefPtr<ShareableBitmap> sharedSnapshot = ShareableBitmap::createShareable(snapshot->internalSize(), ShareableBitmap::SupportsAlpha); - if (!sharedSnapshot) - return nullptr; - - // FIXME: We should consider providing a way to use subpixel antialiasing for the snapshot - // if we're compositing this image onto a solid color (e.g. the modern find indicator style). - auto graphicsContext = sharedSnapshot->createGraphicsContext(); - float deviceScaleFactor = coreFrame()->page()->deviceScaleFactor(); - graphicsContext->scale(FloatSize(deviceScaleFactor, deviceScaleFactor)); - graphicsContext->drawConsumingImageBuffer(WTFMove(snapshot), FloatPoint()); - - return sharedSnapshot.release(); -} } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/WebFrame.h b/Source/WebKit2/WebProcess/WebPage/WebFrame.h index 4e3a0b7a4..e337f1e92 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebFrame.h +++ b/Source/WebKit2/WebProcess/WebPage/WebFrame.h @@ -27,8 +27,6 @@ #define WebFrame_h #include "APIObject.h" -#include "DownloadID.h" -#include "ShareableBitmap.h" #include "WKBase.h" #include "WebFrameLoaderClient.h" #include <JavaScriptCore/JSBase.h> @@ -45,18 +43,15 @@ class Array; } namespace WebCore { -class CertificateInfo; class Frame; class HTMLFrameOwnerElement; class IntPoint; class IntRect; -class SessionID; class URL; } namespace WebKit { -class InjectedBundleFileHandle; class InjectedBundleHitTestResult; class InjectedBundleNodeHandle; class InjectedBundleRangeHandle; @@ -73,18 +68,16 @@ public: void invalidate(); WebPage* page() const; - - static WebFrame* fromCoreFrame(WebCore::Frame&); WebCore::Frame* coreFrame() const { return m_coreFrame; } uint64_t frameID() const { return m_frameID; } uint64_t setUpPolicyListener(WebCore::FramePolicyFunction); void invalidatePolicyListener(); - void didReceivePolicyDecision(uint64_t listenerID, WebCore::PolicyAction, uint64_t navigationID, DownloadID); + void didReceivePolicyDecision(uint64_t listenerID, WebCore::PolicyAction, uint64_t downloadID); void startDownload(const WebCore::ResourceRequest&); - void convertMainResourceLoadToDownload(WebCore::DocumentLoader*, WebCore::SessionID, const WebCore::ResourceRequest&, const WebCore::ResourceResponse&); + void convertMainResourceLoadToDownload(WebCore::DocumentLoader*, const WebCore::ResourceRequest&, const WebCore::ResourceResponse&); String source() const; String contentsAsString() const; @@ -96,11 +89,10 @@ public: bool isMainFrame() const; String name() const; String url() const; - WebCore::CertificateInfo certificateInfo() const; String innerText() const; bool isFrameSet() const; WebFrame* parentFrame() const; - Ref<API::Array> childFrames(); + PassRefPtr<API::Array> childFrames(); JSGlobalContextRef jsContext(); JSGlobalContextRef jsContextForWorld(InjectedBundleScriptWorld*); WebCore::IntRect contentBounds() const; @@ -115,14 +107,11 @@ public: bool containsAnyFormControls() const; void stopLoading(); bool handlesPageScaleGesture() const; - bool requiresUnifiedScaleFactor() const; - void setAccessibleName(const String&); static WebFrame* frameForContext(JSContextRef); JSValueRef jsWrapperForWorld(InjectedBundleNodeHandle*, InjectedBundleScriptWorld*); JSValueRef jsWrapperForWorld(InjectedBundleRangeHandle*, InjectedBundleScriptWorld*); - JSValueRef jsWrapperForWorld(InjectedBundleFileHandle*, InjectedBundleScriptWorld*); static String counterValue(JSObjectRef element); @@ -138,8 +127,6 @@ public: void setTextDirection(const String&); - void documentLoaderDetached(uint64_t navigationID); - // Simple listener class used by plug-ins to know when frames finish or fail loading. class LoadListener { public: @@ -151,18 +138,11 @@ public: void setLoadListener(LoadListener* loadListener) { m_loadListener = loadListener; } LoadListener* loadListener() const { return m_loadListener; } -#if PLATFORM(COCOA) +#if PLATFORM(MAC) typedef bool (*FrameFilterFunction)(WKBundleFrameRef, WKBundleFrameRef subframe, void* context); RetainPtr<CFDataRef> webArchiveData(FrameFilterFunction, void* context); #endif - PassRefPtr<ShareableBitmap> createSelectionSnapshot() const; - -#if PLATFORM(IOS) - uint64_t firstLayerTreeTransactionIDAfterDidCommitLoad() const { return m_firstLayerTreeTransactionIDAfterDidCommitLoad; } - void setFirstLayerTreeTransactionIDAfterDidCommitLoad(uint64_t transactionID) { m_firstLayerTreeTransactionIDAfterDidCommitLoad = transactionID; } -#endif - private: static PassRefPtr<WebFrame> create(std::unique_ptr<WebFrameLoaderClient>); WebFrame(std::unique_ptr<WebFrameLoaderClient>); @@ -171,16 +151,12 @@ private: uint64_t m_policyListenerID; WebCore::FramePolicyFunction m_policyFunction; - DownloadID m_policyDownloadID; + uint64_t m_policyDownloadID; std::unique_ptr<WebFrameLoaderClient> m_frameLoaderClient; LoadListener* m_loadListener; uint64_t m_frameID; - -#if PLATFORM(IOS) - uint64_t m_firstLayerTreeTransactionIDAfterDidCommitLoad; -#endif }; } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/WebInspector.cpp b/Source/WebKit2/WebProcess/WebPage/WebInspector.cpp index 7337ac414..91c13455b 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebInspector.cpp +++ b/Source/WebKit2/WebProcess/WebPage/WebInspector.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010, 2014, 2015 Apple Inc. All rights reserved. + * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,258 +26,302 @@ #include "config.h" #include "WebInspector.h" +#if ENABLE(INSPECTOR) #include "WebFrame.h" -#include "WebInspectorMessages.h" +#include "WebInspectorFrontendClient.h" #include "WebInspectorProxyMessages.h" -#include "WebInspectorUIMessages.h" #include "WebPage.h" +#include "WebPageCreationParameters.h" #include "WebProcess.h" -#include <WebCore/Chrome.h> -#include <WebCore/Document.h> -#include <WebCore/FrameLoadRequest.h> -#include <WebCore/FrameView.h> #include <WebCore/InspectorController.h> #include <WebCore/InspectorFrontendClient.h> -#include <WebCore/InspectorPageAgent.h> #include <WebCore/MainFrame.h> -#include <WebCore/NotImplemented.h> #include <WebCore/Page.h> #include <WebCore/ScriptController.h> -#include <WebCore/WindowFeatures.h> +#include <inspector/InspectorAgentBase.h> +#include <bindings/ScriptValue.h> +#include <wtf/text/StringConcatenate.h> using namespace WebCore; -static const float minimumAttachedHeight = 250; -static const float maximumAttachedHeightRatio = 0.75; -static const float minimumAttachedWidth = 500; - namespace WebKit { -Ref<WebInspector> WebInspector::create(WebPage* page) +PassRefPtr<WebInspector> WebInspector::create(WebPage* page, InspectorFrontendChannel* frontendChannel) { - return adoptRef(*new WebInspector(page)); + return adoptRef(new WebInspector(page, frontendChannel)); } -WebInspector::WebInspector(WebPage* page) +WebInspector::WebInspector(WebPage* page, InspectorFrontendChannel* frontendChannel) : m_page(page) + , m_inspectorPage(0) + , m_frontendClient(0) + , m_frontendChannel(frontendChannel) +#if PLATFORM(MAC) + , m_hasLocalizedStringsURL(false) +#endif +#if ENABLE(INSPECTOR_SERVER) + , m_remoteFrontendConnected(false) +#endif { } -WebInspector::~WebInspector() +// Called from WebInspectorClient +WebPage* WebInspector::createInspectorPage() { - if (m_frontendConnection) - m_frontendConnection->invalidate(); + if (!m_page) + return 0; + + ASSERT(!m_inspectorPage); + ASSERT(!m_frontendClient); + + uint64_t inspectorPageID = 0; + WebPageCreationParameters parameters; + + if (!WebProcess::shared().parentProcessConnection()->sendSync(Messages::WebInspectorProxy::CreateInspectorPage(), + Messages::WebInspectorProxy::CreateInspectorPage::Reply(inspectorPageID, parameters), + m_page->pageID(), std::chrono::milliseconds::max())) { + return 0; + } + + if (!inspectorPageID) + return 0; + + WebProcess::shared().createWebPage(inspectorPageID, parameters); + m_inspectorPage = WebProcess::shared().webPage(inspectorPageID); + ASSERT(m_inspectorPage); + + auto frontendClient = std::make_unique<WebInspectorFrontendClient>(m_page, m_inspectorPage); + m_frontendClient = frontendClient.get(); + m_inspectorPage->corePage()->inspectorController().setInspectorFrontendClient(std::move(frontendClient)); + return m_inspectorPage; } -// Called from WebInspectorClient -void WebInspector::openFrontendConnection(bool underTest) -{ -#if USE(UNIX_DOMAIN_SOCKETS) - IPC::Connection::SocketPair socketPair = IPC::Connection::createPlatformConnection(); - IPC::Connection::Identifier connectionIdentifier(socketPair.server); - IPC::Attachment connectionClientPort(socketPair.client); -#elif OS(DARWIN) - mach_port_t listeningPort; - mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort); - - IPC::Connection::Identifier connectionIdentifier(listeningPort); - IPC::Attachment connectionClientPort(listeningPort, MACH_MSG_TYPE_MAKE_SEND); -#else - notImplemented(); - return; -#endif +void WebInspector::destroyInspectorPage() +{ + m_inspectorPage = 0; + m_frontendClient = 0; + m_frontendChannel = 0; +} + +// Called from WebInspectorFrontendClient +void WebInspector::didClose() +{ + WebProcess::shared().parentProcessConnection()->send(Messages::WebInspectorProxy::DidClose(), m_page->pageID()); + destroyInspectorPage(); +} - m_frontendConnection = IPC::Connection::createServerConnection(connectionIdentifier, *this); - m_frontendConnection->open(); +void WebInspector::bringToFront() +{ + WebProcess::shared().parentProcessConnection()->send(Messages::WebInspectorProxy::BringToFront(), m_page->pageID()); +} - WebProcess::singleton().parentProcessConnection()->send(Messages::WebInspectorProxy::CreateInspectorPage(connectionClientPort, canAttachWindow(), underTest), m_page->pageID()); +void WebInspector::inspectedURLChanged(const String& urlString) +{ + WebProcess::shared().parentProcessConnection()->send(Messages::WebInspectorProxy::InspectedURLChanged(urlString), m_page->pageID()); } -void WebInspector::closeFrontendConnection() +void WebInspector::save(const String& filename, const String& content, bool base64Encoded, bool forceSaveAs) { - WebProcess::singleton().parentProcessConnection()->send(Messages::WebInspectorProxy::DidClose(), m_page->pageID()); + WebProcess::shared().parentProcessConnection()->send(Messages::WebInspectorProxy::Save(filename, content, base64Encoded, forceSaveAs), m_page->pageID()); +} - // If we tried to close the frontend before it was created, then no connection exists yet. - if (m_frontendConnection) { - m_frontendConnection->invalidate(); - m_frontendConnection = nullptr; - } +void WebInspector::append(const String& filename, const String& content) +{ + WebProcess::shared().parentProcessConnection()->send(Messages::WebInspectorProxy::Append(filename, content), m_page->pageID()); +} - m_attached = false; - m_previousCanAttach = false; +void WebInspector::attachBottom() +{ + WebProcess::shared().parentProcessConnection()->send(Messages::WebInspectorProxy::AttachBottom(), m_page->pageID()); } -void WebInspector::bringToFront() +void WebInspector::attachRight() +{ + WebProcess::shared().parentProcessConnection()->send(Messages::WebInspectorProxy::AttachRight(), m_page->pageID()); +} + +void WebInspector::detach() +{ + WebProcess::shared().parentProcessConnection()->send(Messages::WebInspectorProxy::Detach(), m_page->pageID()); +} + +void WebInspector::setAttachedWindowHeight(unsigned height) +{ + WebProcess::shared().parentProcessConnection()->send(Messages::WebInspectorProxy::SetAttachedWindowHeight(height), m_page->pageID()); +} + +void WebInspector::setAttachedWindowWidth(unsigned width) { - WebProcess::singleton().parentProcessConnection()->send(Messages::WebInspectorProxy::BringToFront(), m_page->pageID()); + WebProcess::shared().parentProcessConnection()->send(Messages::WebInspectorProxy::SetAttachedWindowWidth(width), m_page->pageID()); +} + +void WebInspector::setToolbarHeight(unsigned height) +{ + WebProcess::shared().parentProcessConnection()->send(Messages::WebInspectorProxy::SetToolbarHeight(height), m_page->pageID()); } // Called by WebInspector messages void WebInspector::show() { - if (!m_page->corePage()) - return; - m_page->corePage()->inspectorController().show(); } void WebInspector::close() { - if (!m_page->corePage()) - return; - - // Close could be called multiple times during teardown. - if (!m_frontendConnection) - return; - - m_page->corePage()->inspectorController().disconnectFrontend(this); - closeFrontendConnection(); + m_page->corePage()->inspectorController().close(); } -void WebInspector::openInNewTab(const String& urlString) +void WebInspector::didSave(const String& url) { - Page* inspectedPage = m_page->corePage(); - if (!inspectedPage) - return; + ASSERT(m_inspectorPage); + m_inspectorPage->corePage()->mainFrame().script().executeScript(makeString("InspectorFrontendAPI.savedURL(\"", url, "\")")); +} - Frame& inspectedMainFrame = inspectedPage->mainFrame(); - FrameLoadRequest request(inspectedMainFrame.document()->securityOrigin(), ResourceRequest(urlString), "_blank", LockHistory::No, LockBackForwardList::No, MaybeSendReferrer, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Allow, ReplaceDocumentIfJavaScriptURL, ShouldOpenExternalURLsPolicy::ShouldNotAllow); +void WebInspector::didAppend(const String& url) +{ + ASSERT(m_inspectorPage); + m_inspectorPage->corePage()->mainFrame().script().executeScript(makeString("InspectorFrontendAPI.appendedToURL(\"", url, "\")")); +} - Page* newPage = inspectedPage->chrome().createWindow(&inspectedMainFrame, request, WindowFeatures(), NavigationAction(request.resourceRequest(), NavigationType::LinkClicked)); - if (!newPage) - return; +void WebInspector::attachedBottom() +{ + if (m_frontendClient) + m_frontendClient->setAttachedWindow(InspectorFrontendClient::DOCKED_TO_BOTTOM); +} - newPage->mainFrame().loader().load(request); +void WebInspector::attachedRight() +{ + if (m_frontendClient) + m_frontendClient->setAttachedWindow(InspectorFrontendClient::DOCKED_TO_RIGHT); } -void WebInspector::evaluateScriptForTest(const String& script) +void WebInspector::detached() { - if (!m_page->corePage()) - return; + if (m_frontendClient) + m_frontendClient->setAttachedWindow(InspectorFrontendClient::UNDOCKED); +} - m_page->corePage()->inspectorController().evaluateForTestInFrontend(script); +void WebInspector::evaluateScriptForTest(long callID, const String& script) +{ + m_page->corePage()->inspectorController().evaluateForTestInFrontend(callID, script); } void WebInspector::showConsole() { - if (!m_page->corePage()) - return; - m_page->corePage()->inspectorController().show(); - m_frontendConnection->send(Messages::WebInspectorUI::ShowConsole(), 0); + if (m_frontendClient) + m_frontendClient->showConsole(); } void WebInspector::showResources() { - if (!m_page->corePage()) - return; - m_page->corePage()->inspectorController().show(); - m_frontendConnection->send(Messages::WebInspectorUI::ShowResources(), 0); + if (m_frontendClient) + m_frontendClient->showResources(); } -void WebInspector::showMainResourceForFrame(uint64_t frameIdentifier) +void WebInspector::showMainResourceForFrame(uint64_t frameID) { - WebFrame* frame = WebProcess::singleton().webFrame(frameIdentifier); + WebFrame* frame = WebProcess::shared().webFrame(frameID); if (!frame) return; - if (!m_page->corePage()) - return; - m_page->corePage()->inspectorController().show(); - - String inspectorFrameIdentifier = m_page->corePage()->inspectorController().pageAgent()->frameId(frame->coreFrame()); - m_frontendConnection->send(Messages::WebInspectorUI::ShowMainResourceForFrame(inspectorFrameIdentifier), 0); + if (m_frontendClient) + m_frontendClient->showMainResourceForFrame(frame->coreFrame()); } -void WebInspector::startPageProfiling() +void WebInspector::startJavaScriptDebugging() { - if (!m_page->corePage()) - return; + m_page->corePage()->inspectorController().show(); + if (m_frontendClient) + m_frontendClient->setDebuggingEnabled(true); +} +void WebInspector::stopJavaScriptDebugging() +{ m_page->corePage()->inspectorController().show(); - m_frontendConnection->send(Messages::WebInspectorUI::StartPageProfiling(), 0); + if (m_frontendClient) + m_frontendClient->setDebuggingEnabled(false); } -void WebInspector::stopPageProfiling() +void WebInspector::setJavaScriptProfilingEnabled(bool enabled) { - if (!m_page->corePage()) + m_page->corePage()->inspectorController().show(); + if (!m_frontendClient) return; - m_page->corePage()->inspectorController().show(); - m_frontendConnection->send(Messages::WebInspectorUI::StopPageProfiling(), 0); + m_page->corePage()->inspectorController().setProfilerEnabled(enabled); } -bool WebInspector::canAttachWindow() +void WebInspector::startJavaScriptProfiling() { - if (!m_page->corePage()) - return false; + m_page->corePage()->inspectorController().show(); + if (m_frontendClient) + m_frontendClient->startProfilingJavaScript(); +} - // Don't allow attaching to another inspector -- two inspectors in one window is too much! - if (m_page->isInspectorPage()) - return false; +void WebInspector::stopJavaScriptProfiling() +{ + m_page->corePage()->inspectorController().show(); + if (m_frontendClient) + m_frontendClient->stopProfilingJavaScript(); +} - // If we are already attached, allow attaching again to allow switching sides. - if (m_attached) - return true; +void WebInspector::startPageProfiling() +{ + m_page->corePage()->inspectorController().show(); + if (m_frontendClient) + m_frontendClient->setTimelineProfilingEnabled(true); +} - // Don't allow the attach if the window would be too small to accommodate the minimum inspector size. - unsigned inspectedPageHeight = m_page->corePage()->mainFrame().view()->visibleHeight(); - unsigned inspectedPageWidth = m_page->corePage()->mainFrame().view()->visibleWidth(); - unsigned maximumAttachedHeight = inspectedPageHeight * maximumAttachedHeightRatio; - return minimumAttachedHeight <= maximumAttachedHeight && minimumAttachedWidth <= inspectedPageWidth; +void WebInspector::stopPageProfiling() +{ + m_page->corePage()->inspectorController().show(); + if (m_frontendClient) + m_frontendClient->setTimelineProfilingEnabled(false); } void WebInspector::updateDockingAvailability() { - if (m_attached) - return; - - bool canAttachWindow = this->canAttachWindow(); - if (m_previousCanAttach == canAttachWindow) + if (!m_frontendClient) return; - m_previousCanAttach = canAttachWindow; - - WebProcess::singleton().parentProcessConnection()->send(Messages::WebInspectorProxy::AttachAvailabilityChanged(canAttachWindow), m_page->pageID()); + bool canAttachWindow = m_frontendClient->canAttachWindow(); + WebProcess::shared().parentProcessConnection()->send(Messages::WebInspectorProxy::AttachAvailabilityChanged(canAttachWindow), m_page->pageID()); + m_frontendClient->setDockingUnavailable(!canAttachWindow); } -void WebInspector::sendMessageToBackend(const String& message) +#if ENABLE(INSPECTOR_SERVER) +void WebInspector::sendMessageToRemoteFrontend(const String& message) { - if (!m_page->corePage()) - return; - - m_page->corePage()->inspectorController().dispatchMessageFromFrontend(message); + ASSERT(m_remoteFrontendConnected); + WebProcess::shared().parentProcessConnection()->send(Messages::WebInspectorProxy::SendMessageToRemoteFrontend(message), m_page->pageID()); } -bool WebInspector::sendMessageToFrontend(const String& message) +void WebInspector::dispatchMessageFromRemoteFrontend(const String& message) { -#if ENABLE(INSPECTOR_SERVER) - if (m_remoteFrontendConnected) - WebProcess::singleton().parentProcessConnection()->send(Messages::WebInspectorProxy::SendMessageToRemoteFrontend(message), m_page->pageID()); - else -#endif - m_frontendConnection->send(Messages::WebInspectorUI::SendMessageToFrontend(message), 0); - return true; + m_page->corePage()->inspectorController().dispatchMessageFromFrontend(message); } -#if ENABLE(INSPECTOR_SERVER) void WebInspector::remoteFrontendConnected() { - if (m_page->corePage()) { - m_remoteFrontendConnected = true; - m_page->corePage()->inspectorController().connectFrontend(this); - } + ASSERT(!m_remoteFrontendConnected); + // Switching between in-process and remote inspectors isn't supported yet. + ASSERT(!m_inspectorPage); + + m_page->corePage()->inspectorController().connectFrontend(m_frontendChannel); + m_remoteFrontendConnected = true; } void WebInspector::remoteFrontendDisconnected() { + ASSERT(m_remoteFrontendConnected); + m_page->corePage()->inspectorController().disconnectFrontend(Inspector::InspectorDisconnectReason::InspectorDestroyed); m_remoteFrontendConnected = false; - - if (m_page->corePage()) - m_page->corePage()->inspectorController().disconnectFrontend(this); } #endif } // namespace WebKit + +#endif // ENABLE(INSPECTOR) diff --git a/Source/WebKit2/WebProcess/WebPage/WebInspector.h b/Source/WebKit2/WebProcess/WebPage/WebInspector.h index 8dbf66104..14f5a3ba6 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebInspector.h +++ b/Source/WebKit2/WebProcess/WebPage/WebInspector.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010, 2014, 2015 Apple Inc. All rights reserved. + * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,93 +26,113 @@ #ifndef WebInspector_h #define WebInspector_h +#if ENABLE(INSPECTOR) + #include "APIObject.h" #include "Connection.h" -#include "MessageReceiver.h" -#include <inspector/InspectorFrontendChannel.h> +#include <WebCore/InspectorForwarding.h> #include <wtf/Noncopyable.h> #include <wtf/text/WTFString.h> namespace WebKit { +class WebInspectorFrontendClient; class WebPage; -class WebInspector : public API::ObjectImpl<API::Object::Type::BundleInspector>, public IPC::Connection::Client, public Inspector::FrontendChannel { +class WebInspector : public API::ObjectImpl<API::Object::Type::BundleInspector> { public: - static Ref<WebInspector> create(WebPage*); + static PassRefPtr<WebInspector> create(WebPage*, WebCore::InspectorFrontendChannel*); WebPage* page() const { return m_page; } - - void updateDockingAvailability(); - - virtual bool sendMessageToFrontend(const String& message) override; - virtual ConnectionType connectionType() const override { return ConnectionType::Local; } + WebPage* inspectorPage() const { return m_inspectorPage; } // Implemented in generated WebInspectorMessageReceiver.cpp - void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; - - // IPC::Connection::Client - void didClose(IPC::Connection&) override { close(); } - void didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference, IPC::StringReference) override { close(); } - virtual IPC::ProcessType localProcessType() override { return IPC::ProcessType::Web; } - virtual IPC::ProcessType remoteProcessType() override { return IPC::ProcessType::UI; } + void didReceiveWebInspectorMessage(IPC::Connection*, IPC::MessageDecoder&); // Called by WebInspector messages - void connectionEstablished(); - void show(); void close(); - void openInNewTab(const String& urlString); + void didSave(const String& url); + void didAppend(const String& url); - void canAttachWindow(bool& result); + void attachedBottom(); + void attachedRight(); + void detached(); - void showConsole(); - void showResources(); - - void showMainResourceForFrame(uint64_t frameIdentifier); - - void setAttached(bool attached) { m_attached = attached; } - - void evaluateScriptForTest(const String& script); + void evaluateScriptForTest(long callID, const String& script); + void setJavaScriptProfilingEnabled(bool); void startPageProfiling(); void stopPageProfiling(); - void sendMessageToBackend(const String&); - #if ENABLE(INSPECTOR_SERVER) + bool hasRemoteFrontendConnected() const { return m_remoteFrontendConnected; } + void sendMessageToRemoteFrontend(const String& message); + void dispatchMessageFromRemoteFrontend(const String& message); void remoteFrontendConnected(); void remoteFrontendDisconnected(); #endif - void disconnectFromPage() { close(); } - private: friend class WebInspectorClient; + friend class WebInspectorFrontendClient; - explicit WebInspector(WebPage*); - virtual ~WebInspector(); - - bool canAttachWindow(); + explicit WebInspector(WebPage*, WebCore::InspectorFrontendChannel*); // Called from WebInspectorClient - void openFrontendConnection(bool underTest); - void closeFrontendConnection(); + WebPage* createInspectorPage(); + void destroyInspectorPage(); + // Called from WebInspectorFrontendClient + void didClose(); void bringToFront(); + void inspectedURLChanged(const String&); - WebPage* m_page; + bool canSave() const; + void save(const String& filename, const String& content, bool base64Encoded, bool forceSaveAs); + void append(const String& filename, const String& content); - RefPtr<IPC::Connection> m_frontendConnection; + void attachBottom(); + void attachRight(); + void detach(); - bool m_attached { false }; - bool m_previousCanAttach { false }; + void setAttachedWindowHeight(unsigned); + void setAttachedWindowWidth(unsigned); + void setToolbarHeight(unsigned); + + // Implemented in platform WebInspector file + String localizedStringsURL() const; + + void showConsole(); + + void showResources(); + + void showMainResourceForFrame(uint64_t frameID); + + void startJavaScriptDebugging(); + void stopJavaScriptDebugging(); + + void startJavaScriptProfiling(); + void stopJavaScriptProfiling(); + + void updateDockingAvailability(); + + WebPage* m_page; + WebPage* m_inspectorPage; + WebInspectorFrontendClient* m_frontendClient; + WebCore::InspectorFrontendChannel* m_frontendChannel; +#if PLATFORM(MAC) + mutable String m_localizedStringsURL; + mutable bool m_hasLocalizedStringsURL; +#endif #if ENABLE(INSPECTOR_SERVER) - bool m_remoteFrontendConnected { false }; + bool m_remoteFrontendConnected; #endif }; } // namespace WebKit +#endif // ENABLE(INSPECTOR) + #endif // WebInspector_h diff --git a/Source/WebKit2/WebProcess/WebPage/WebInspector.messages.in b/Source/WebKit2/WebProcess/WebPage/WebInspector.messages.in index fe4e0ac40..c23b86f21 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebInspector.messages.in +++ b/Source/WebKit2/WebProcess/WebPage/WebInspector.messages.in @@ -1,4 +1,4 @@ -# Copyright (C) 2010, 2014 Apple Inc. All rights reserved. +# Copyright (C) 2010 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions @@ -20,26 +20,31 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -messages -> WebInspector { +#if ENABLE(INSPECTOR) + +messages -> WebInspector LegacyReceiver { Show() Close() - - SetAttached(bool attached) - + AttachedBottom() + AttachedRight() + Detached() + DidSave(String url) + DidAppend(String url) ShowConsole() ShowResources() - - ShowMainResourceForFrame(uint64_t frameIdentifier) - - OpenInNewTab(String url) - + ShowMainResourceForFrame(uint64_t frameID) + StartJavaScriptDebugging() + StopJavaScriptDebugging() + StartJavaScriptProfiling() + StopJavaScriptProfiling() StartPageProfiling() StopPageProfiling() - SendMessageToBackend(String message) - #if ENABLE(INSPECTOR_SERVER) + DispatchMessageFromRemoteFrontend(String message) RemoteFrontendConnected() RemoteFrontendDisconnected() #endif } + +#endif diff --git a/Source/WebKit2/WebProcess/WebPage/WebInspectorFrontendAPIDispatcher.cpp b/Source/WebKit2/WebProcess/WebPage/WebInspectorFrontendAPIDispatcher.cpp deleted file mode 100644 index 932c1ac68..000000000 --- a/Source/WebKit2/WebProcess/WebPage/WebInspectorFrontendAPIDispatcher.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebInspectorFrontendAPIDispatcher.h" - -#include "WebPage.h" -#include <JavaScriptCore/ScriptValue.h> -#include <WebCore/MainFrame.h> -#include <WebCore/ScriptController.h> -#include <WebCore/ScriptState.h> - -namespace WebKit { - -WebInspectorFrontendAPIDispatcher::WebInspectorFrontendAPIDispatcher(WebPage& page) - : m_page(page) -{ -} - -void WebInspectorFrontendAPIDispatcher::reset() -{ - m_frontendLoaded = false; - - m_queue.clear(); -} - -void WebInspectorFrontendAPIDispatcher::frontendLoaded() -{ - m_frontendLoaded = true; - - for (const String& expression : m_queue) - m_page.corePage()->mainFrame().script().executeScript(expression); - - m_queue.clear(); -} - -void WebInspectorFrontendAPIDispatcher::dispatchCommand(const String& command) -{ - evaluateExpressionOnLoad(makeString("InspectorFrontendAPI.dispatch([\"", command, "\"])")); -} - -void WebInspectorFrontendAPIDispatcher::dispatchCommand(const String& command, const String& argument) -{ - evaluateExpressionOnLoad(makeString("InspectorFrontendAPI.dispatch([\"", command, "\", \"", argument, "\"])")); -} - -void WebInspectorFrontendAPIDispatcher::dispatchCommand(const String& command, bool argument) -{ - evaluateExpressionOnLoad(makeString("InspectorFrontendAPI.dispatch([\"", command, "\", ", argument ? "true" : "false", "])")); -} - -void WebInspectorFrontendAPIDispatcher::dispatchMessageAsync(const String& message) -{ - evaluateExpressionOnLoad(makeString("InspectorFrontendAPI.dispatchMessageAsync(", message, ")")); -} - -void WebInspectorFrontendAPIDispatcher::evaluateExpressionOnLoad(const String& expression) -{ - if (m_frontendLoaded) { - ASSERT(m_queue.isEmpty()); - m_page.corePage()->mainFrame().script().executeScript(expression); - return; - } - - m_queue.append(expression); -} - -} // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/WebInspectorUI.cpp b/Source/WebKit2/WebProcess/WebPage/WebInspectorUI.cpp deleted file mode 100644 index 7dbefe7f2..000000000 --- a/Source/WebKit2/WebProcess/WebPage/WebInspectorUI.cpp +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebInspectorUI.h" - -#include "WebInspectorMessages.h" -#include "WebInspectorProxyMessages.h" -#include "WebPage.h" -#include "WebProcess.h" -#include <WebCore/Chrome.h> -#include <WebCore/DOMWrapperWorld.h> -#include <WebCore/InspectorController.h> -#include <WebCore/NotImplemented.h> -#include <WebCore/ScriptGlobalObject.h> -#include <WebCore/ScriptState.h> - -using namespace WebCore; - -namespace WebKit { - -Ref<WebInspectorUI> WebInspectorUI::create(WebPage& page) -{ - return adoptRef(*new WebInspectorUI(page)); -} - -WebInspectorUI::WebInspectorUI(WebPage& page) - : m_page(page) - , m_frontendAPIDispatcher(page) -{ -} - -void WebInspectorUI::establishConnection(IPC::Attachment encodedConnectionIdentifier, uint64_t inspectedPageIdentifier, bool underTest, unsigned inspectionLevel) -{ -#if USE(UNIX_DOMAIN_SOCKETS) - IPC::Connection::Identifier connectionIdentifier(encodedConnectionIdentifier.releaseFileDescriptor()); -#elif OS(DARWIN) - IPC::Connection::Identifier connectionIdentifier(encodedConnectionIdentifier.port()); -#else - notImplemented(); - return; -#endif - - if (IPC::Connection::identifierIsNull(connectionIdentifier)) - return; - - m_inspectedPageIdentifier = inspectedPageIdentifier; - m_frontendAPIDispatcher.reset(); - m_underTest = underTest; - m_inspectionLevel = inspectionLevel; - - m_frontendController = &m_page.corePage()->inspectorController(); - m_frontendController->setInspectorFrontendClient(this); - - m_backendConnection = IPC::Connection::createClientConnection(connectionIdentifier, *this); - m_backendConnection->open(); -} - -void WebInspectorUI::windowObjectCleared() -{ - if (m_frontendHost) - m_frontendHost->disconnectClient(); - - m_frontendHost = InspectorFrontendHost::create(this, m_page.corePage()); - ScriptGlobalObject::set(execStateFromPage(mainThreadNormalWorld(), m_page.corePage()), ASCIILiteral("InspectorFrontendHost"), m_frontendHost.get()); -} - -void WebInspectorUI::frontendLoaded() -{ - m_frontendAPIDispatcher.frontendLoaded(); - - // Tell the new frontend about the current dock state. If the window object - // cleared due to a reload, the dock state won't be resent from UIProcess. - setDockingUnavailable(m_dockingUnavailable); - setDockSide(m_dockSide); - - bringToFront(); -} - -void WebInspectorUI::startWindowDrag() -{ - WebProcess::singleton().parentProcessConnection()->send(Messages::WebInspectorProxy::StartWindowDrag(), m_inspectedPageIdentifier); -} - -void WebInspectorUI::moveWindowBy(float x, float y) -{ - FloatRect frameRect = m_page.corePage()->chrome().windowRect(); - frameRect.move(x, y); - m_page.corePage()->chrome().setWindowRect(frameRect); -} - -void WebInspectorUI::bringToFront() -{ - WebProcess::singleton().parentProcessConnection()->send(Messages::WebInspectorProxy::BringToFront(), m_inspectedPageIdentifier); -} - -void WebInspectorUI::closeWindow() -{ - WebProcess::singleton().parentProcessConnection()->send(Messages::WebInspectorProxy::DidClose(), m_inspectedPageIdentifier); - - if (m_backendConnection) - m_backendConnection->invalidate(); - m_backendConnection = nullptr; - - if (m_frontendController) - m_frontendController->setInspectorFrontendClient(nullptr); - m_frontendController = nullptr; - - m_inspectedPageIdentifier = 0; - m_underTest = false; -} - -void WebInspectorUI::requestSetDockSide(DockSide side) -{ - auto& webProcess = WebProcess::singleton(); - switch (side) { - case DockSide::Undocked: - webProcess.parentProcessConnection()->send(Messages::WebInspectorProxy::Detach(), m_inspectedPageIdentifier); - break; - case DockSide::Right: - webProcess.parentProcessConnection()->send(Messages::WebInspectorProxy::AttachRight(), m_inspectedPageIdentifier); - break; - case DockSide::Bottom: - webProcess.parentProcessConnection()->send(Messages::WebInspectorProxy::AttachBottom(), m_inspectedPageIdentifier); - break; - } -} - -void WebInspectorUI::setDockSide(DockSide side) -{ - const char* sideString; - - switch (side) { - case DockSide::Undocked: - sideString = "undocked"; - break; - - case DockSide::Right: - sideString = "right"; - break; - - case DockSide::Bottom: - sideString = "bottom"; - break; - } - - m_dockSide = side; - - m_frontendAPIDispatcher.dispatchCommand(ASCIILiteral("setDockSide"), String(ASCIILiteral(sideString))); -} - -void WebInspectorUI::setDockingUnavailable(bool unavailable) -{ - m_frontendAPIDispatcher.dispatchCommand(ASCIILiteral("setDockingUnavailable"), unavailable); - m_dockingUnavailable = unavailable; -} - -void WebInspectorUI::changeAttachedWindowHeight(unsigned height) -{ - WebProcess::singleton().parentProcessConnection()->send(Messages::WebInspectorProxy::SetAttachedWindowHeight(height), m_inspectedPageIdentifier); -} - -void WebInspectorUI::changeAttachedWindowWidth(unsigned width) -{ - WebProcess::singleton().parentProcessConnection()->send(Messages::WebInspectorProxy::SetAttachedWindowWidth(width), m_inspectedPageIdentifier); -} - -void WebInspectorUI::openInNewTab(const String& url) -{ - if (m_backendConnection) - m_backendConnection->send(Messages::WebInspector::OpenInNewTab(url), 0); -} - -void WebInspectorUI::save(const WTF::String& filename, const WTF::String& content, bool base64Encoded, bool forceSaveAs) -{ - WebProcess::singleton().parentProcessConnection()->send(Messages::WebInspectorProxy::Save(filename, content, base64Encoded, forceSaveAs), m_inspectedPageIdentifier); -} - -void WebInspectorUI::append(const WTF::String& filename, const WTF::String& content) -{ - WebProcess::singleton().parentProcessConnection()->send(Messages::WebInspectorProxy::Append(filename, content), m_inspectedPageIdentifier); -} - -void WebInspectorUI::inspectedURLChanged(const String& urlString) -{ - WebProcess::singleton().parentProcessConnection()->send(Messages::WebInspectorProxy::InspectedURLChanged(urlString), m_inspectedPageIdentifier); -} - -void WebInspectorUI::showConsole() -{ - m_frontendAPIDispatcher.dispatchCommand(ASCIILiteral("showConsole")); -} - -void WebInspectorUI::showResources() -{ - m_frontendAPIDispatcher.dispatchCommand(ASCIILiteral("showResources")); -} - -void WebInspectorUI::showMainResourceForFrame(const String& frameIdentifier) -{ - m_frontendAPIDispatcher.dispatchCommand(ASCIILiteral("showMainResourceForFrame"), frameIdentifier); -} - -void WebInspectorUI::startPageProfiling() -{ - m_frontendAPIDispatcher.dispatchCommand(ASCIILiteral("setTimelineProfilingEnabled"), true); -} - -void WebInspectorUI::stopPageProfiling() -{ - m_frontendAPIDispatcher.dispatchCommand(ASCIILiteral("setTimelineProfilingEnabled"), false); -} - -void WebInspectorUI::didSave(const String& url) -{ - m_frontendAPIDispatcher.dispatchCommand(ASCIILiteral("savedURL"), url); -} - -void WebInspectorUI::didAppend(const String& url) -{ - m_frontendAPIDispatcher.dispatchCommand(ASCIILiteral("appendedToURL"), url); -} - -void WebInspectorUI::sendMessageToFrontend(const String& message) -{ - m_frontendAPIDispatcher.dispatchMessageAsync(message); -} - -void WebInspectorUI::sendMessageToBackend(const String& message) -{ - if (m_backendConnection) - m_backendConnection->send(Messages::WebInspector::SendMessageToBackend(message), 0); -} - -} // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/WebInspectorUI.h b/Source/WebKit2/WebProcess/WebPage/WebInspectorUI.h deleted file mode 100644 index d6fad8318..000000000 --- a/Source/WebKit2/WebProcess/WebPage/WebInspectorUI.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebInspectorUI_h -#define WebInspectorUI_h - -#include "Connection.h" -#include "WebInspectorFrontendAPIDispatcher.h" -#include <WebCore/InspectorFrontendClient.h> -#include <WebCore/InspectorFrontendHost.h> - -namespace WebCore { -class InspectorController; -} - -namespace WebKit { - -class WebPage; - -class WebInspectorUI : public RefCounted<WebInspectorUI>, public IPC::Connection::Client, public WebCore::InspectorFrontendClient { -public: - static Ref<WebInspectorUI> create(WebPage&); - - // Implemented in generated WebInspectorUIMessageReceiver.cpp - void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; - - // IPC::Connection::Client - void didClose(IPC::Connection&) override { closeWindow(); } - void didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference, IPC::StringReference) override { closeWindow(); } - virtual IPC::ProcessType localProcessType() override { return IPC::ProcessType::Web; } - virtual IPC::ProcessType remoteProcessType() override { return IPC::ProcessType::Web; } - - // Called by WebInspectorUI messages - void establishConnection(IPC::Attachment connectionIdentifier, uint64_t inspectedPageIdentifier, bool underTest, unsigned inspectionLevel); - - void showConsole(); - void showResources(); - - void showMainResourceForFrame(const String& frameIdentifier); - - void startPageProfiling(); - void stopPageProfiling(); - - void attachedBottom() { setDockSide(DockSide::Bottom); } - void attachedRight() { setDockSide(DockSide::Right); } - void detached() { setDockSide(DockSide::Undocked); } - - void setDockSide(DockSide); - void setDockingUnavailable(bool); - - void didSave(const String& url); - void didAppend(const String& url); - - void sendMessageToFrontend(const String&); - - // WebCore::InspectorFrontendClient - void windowObjectCleared() override; - void frontendLoaded() override; - - void startWindowDrag() override; - void moveWindowBy(float x, float y) override; - - String localizedStringsURL() override; - - void bringToFront() override; - void closeWindow() override; - - void requestSetDockSide(DockSide) override; - void changeAttachedWindowHeight(unsigned) override; - void changeAttachedWindowWidth(unsigned) override; - - void openInNewTab(const String& url) override; - - bool canSave() override; - void save(const WTF::String& url, const WTF::String& content, bool base64Encoded, bool forceSaveAs) override; - void append(const WTF::String& url, const WTF::String& content) override; - - void inspectedURLChanged(const String&) override; - - void sendMessageToBackend(const String&) override; - - bool isUnderTest() override { return m_underTest; } - unsigned inspectionLevel() const override { return m_inspectionLevel; } - -private: - explicit WebInspectorUI(WebPage&); - - WebPage& m_page; - WebInspectorFrontendAPIDispatcher m_frontendAPIDispatcher; - RefPtr<WebCore::InspectorFrontendHost> m_frontendHost; - RefPtr<IPC::Connection> m_backendConnection; - - // Keep a pointer to the frontend's inspector controller rather than going through - // corePage(), since we may need it after the frontend's page has started destruction. - WebCore::InspectorController* m_frontendController { nullptr }; - - uint64_t m_inspectedPageIdentifier { 0 }; - bool m_underTest { false }; - bool m_dockingUnavailable { false }; - DockSide m_dockSide { DockSide::Undocked }; - unsigned m_inspectionLevel { 1 }; - -#if PLATFORM(COCOA) - mutable String m_localizedStringsURL; - mutable bool m_hasLocalizedStringsURL { false }; -#endif -}; - -} // namespace WebKit - -#endif // WebInspectorUI_h diff --git a/Source/WebKit2/WebProcess/WebPage/WebInspectorUI.messages.in b/Source/WebKit2/WebProcess/WebPage/WebInspectorUI.messages.in deleted file mode 100644 index cc09f9a26..000000000 --- a/Source/WebKit2/WebProcess/WebPage/WebInspectorUI.messages.in +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (C) 2014 Apple Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -messages -> WebInspectorUI { - EstablishConnection(IPC::Attachment connectionIdentifier, uint64_t inspectedPageIdentifier, bool underTest, unsigned inspectionLevel) - - AttachedBottom() - AttachedRight() - Detached() - SetDockingUnavailable(bool unavailable) - - ShowConsole() - ShowResources() - - ShowMainResourceForFrame(String frameIdentifier) - - StartPageProfiling() - StopPageProfiling() - - DidSave(String url) - DidAppend(String url) - - SendMessageToFrontend(String message) -} diff --git a/Source/WebKit2/WebProcess/WebPage/WebOpenPanelResultListener.cpp b/Source/WebKit2/WebProcess/WebPage/WebOpenPanelResultListener.cpp index 6866c7984..bcf3e8024 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebOpenPanelResultListener.cpp +++ b/Source/WebKit2/WebProcess/WebPage/WebOpenPanelResultListener.cpp @@ -26,13 +26,11 @@ #include "config.h" #include "WebOpenPanelResultListener.h" -#include <WebCore/Icon.h> - namespace WebKit { -Ref<WebOpenPanelResultListener> WebOpenPanelResultListener::create(WebPage* page, PassRefPtr<WebCore::FileChooser> fileChooser) +PassRefPtr<WebOpenPanelResultListener> WebOpenPanelResultListener::create(WebPage* page, PassRefPtr<WebCore::FileChooser> fileChooser) { - return adoptRef(*new WebOpenPanelResultListener(page, fileChooser)); + return adoptRef(new WebOpenPanelResultListener(page, fileChooser)); } WebOpenPanelResultListener::WebOpenPanelResultListener(WebPage* page, PassRefPtr<WebCore::FileChooser> fileChooser) @@ -50,11 +48,4 @@ void WebOpenPanelResultListener::didChooseFiles(const Vector<String>& files) m_fileChooser->chooseFiles(files); } -#if PLATFORM(IOS) -void WebOpenPanelResultListener::didChooseFilesWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, WebCore::Icon* displayIcon) -{ - m_fileChooser->chooseMediaFiles(files, displayString, displayIcon); -} -#endif - } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/WebOpenPanelResultListener.h b/Source/WebKit2/WebProcess/WebPage/WebOpenPanelResultListener.h index 69330d237..073d66adb 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebOpenPanelResultListener.h +++ b/Source/WebKit2/WebProcess/WebPage/WebOpenPanelResultListener.h @@ -29,24 +29,17 @@ #include <wtf/RefCounted.h> #include <WebCore/FileChooser.h> -namespace WebCore { -class Icon; -} - namespace WebKit { class WebPage; class WebOpenPanelResultListener : public RefCounted<WebOpenPanelResultListener> { public: - static Ref<WebOpenPanelResultListener> create(WebPage*, PassRefPtr<WebCore::FileChooser>); + static PassRefPtr<WebOpenPanelResultListener> create(WebPage*, PassRefPtr<WebCore::FileChooser>); ~WebOpenPanelResultListener(); void disconnectFromPage() { m_page = 0; } void didChooseFiles(const Vector<String>&); -#if PLATFORM(IOS) - void didChooseFilesWithDisplayStringAndIcon(const Vector<String>&, const String& displayString, WebCore::Icon*); -#endif private: WebOpenPanelResultListener(WebPage*, PassRefPtr<WebCore::FileChooser>); diff --git a/Source/WebKit2/WebProcess/WebPage/WebPage.cpp b/Source/WebKit2/WebProcess/WebPage/WebPage.cpp index aebd9a05b..c7da0d9d2 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebPage.cpp +++ b/Source/WebKit2/WebProcess/WebPage/WebPage.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010, 2011, 2012, 2013-2015 Apple Inc. All rights reserved. + * Copyright (C) 2010, 2011, 2012, 2013 Apple Inc. All rights reserved. * Copyright (C) 2012 Intel Corporation. All rights reserved. * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) * @@ -28,10 +28,9 @@ #include "config.h" #include "WebPage.h" -#include "APIArray.h" -#include "APIGeometry.h" #include "Arguments.h" #include "DataReference.h" +#include "DecoderAdapter.h" #include "DragControllerAction.h" #include "DrawingArea.h" #include "DrawingAreaMessages.h" @@ -39,21 +38,19 @@ #include "EventDispatcher.h" #include "InjectedBundle.h" #include "InjectedBundleBackForwardList.h" +#include "InjectedBundleUserMessageCoders.h" +#include "LayerTreeHost.h" #include "Logging.h" #include "NetscapePlugin.h" #include "NotificationPermissionRequestManager.h" #include "PageBanner.h" +#include "PageOverlay.h" #include "PluginProcessAttributes.h" #include "PluginProxy.h" #include "PluginView.h" #include "PrintInfo.h" #include "SessionState.h" -#include "SessionStateConversion.h" -#include "SessionTracker.h" #include "ShareableBitmap.h" -#include "VisitedLinkTableController.h" -#include "WKBundleAPICast.h" -#include "WKRetainPtr.h" #include "WKSharedAPICast.h" #include "WebAlternativeTextClient.h" #include "WebBackForwardListItem.h" @@ -62,15 +59,13 @@ #include "WebColorChooser.h" #include "WebContextMenu.h" #include "WebContextMenuClient.h" +#include "WebContextMessages.h" #include "WebCoreArgumentCoders.h" -#include "WebDatabaseProvider.h" -#include "WebDiagnosticLoggingClient.h" #include "WebDocumentLoader.h" #include "WebDragClient.h" #include "WebEditorClient.h" #include "WebEvent.h" #include "WebEventConversion.h" -#include "WebEventFactory.h" #include "WebFrame.h" #include "WebFrameLoaderClient.h" #include "WebFullScreenManager.h" @@ -80,41 +75,29 @@ #include "WebInspector.h" #include "WebInspectorClient.h" #include "WebInspectorMessages.h" -#include "WebInspectorUI.h" -#include "WebInspectorUIMessages.h" -#include "WebMediaKeyStorageManager.h" #include "WebNotificationClient.h" #include "WebOpenPanelResultListener.h" #include "WebPageCreationParameters.h" #include "WebPageGroupProxy.h" #include "WebPageMessages.h" -#include "WebPageOverlay.h" #include "WebPageProxyMessages.h" #include "WebPlugInClient.h" #include "WebPopupMenu.h" -#include "WebPreferencesDefinitions.h" -#include "WebPreferencesKeys.h" #include "WebPreferencesStore.h" #include "WebProcess.h" -#include "WebProcessPoolMessages.h" #include "WebProcessProxyMessages.h" #include "WebProgressTrackerClient.h" -#include "WebStorageNamespaceProvider.h" -#include "WebUndoStep.h" -#include "WebUserContentController.h" -#include "WebUserMediaClient.h" #include <JavaScriptCore/APICast.h> #include <WebCore/ArchiveResource.h> #include <WebCore/Chrome.h> #include <WebCore/ContextMenuController.h> -#include <WebCore/DataTransfer.h> #include <WebCore/DatabaseManager.h> #include <WebCore/DocumentFragment.h> #include <WebCore/DocumentLoader.h> #include <WebCore/DocumentMarkerController.h> #include <WebCore/DragController.h> #include <WebCore/DragData.h> -#include <WebCore/ElementIterator.h> +#include <WebCore/DragSession.h> #include <WebCore/EventHandler.h> #include <WebCore/FocusController.h> #include <WebCore/FormState.h> @@ -134,8 +117,6 @@ #include <WebCore/MainFrame.h> #include <WebCore/MouseEvent.h> #include <WebCore/Page.h> -#include <WebCore/PageConfiguration.h> -#include <WebCore/PageThrottler.h> #include <WebCore/PlatformKeyboardEvent.h> #include <WebCore/PluginDocument.h> #include <WebCore/PrintContext.h> @@ -143,44 +124,44 @@ #include <WebCore/RenderLayer.h> #include <WebCore/RenderTreeAsText.h> #include <WebCore/RenderView.h> +#include <WebCore/ResourceBuffer.h> #include <WebCore/ResourceRequest.h> #include <WebCore/ResourceResponse.h> #include <WebCore/RuntimeEnabledFeatures.h> #include <WebCore/SchemeRegistry.h> #include <WebCore/ScriptController.h> #include <WebCore/SerializedScriptValue.h> -#include <WebCore/SessionID.h> #include <WebCore/Settings.h> #include <WebCore/ShadowRoot.h> #include <WebCore/SharedBuffer.h> -#include <WebCore/StyleProperties.h> #include <WebCore/SubframeLoader.h> #include <WebCore/SubstituteData.h> #include <WebCore/TextIterator.h> -#include <WebCore/UserInputBridge.h> #include <WebCore/VisiblePosition.h> #include <WebCore/VisibleUnits.h> #include <WebCore/markup.h> #include <bindings/ScriptValue.h> -#include <profiler/ProfilerDatabase.h> -#include <runtime/JSCInlines.h> #include <runtime/JSCJSValue.h> #include <runtime/JSLock.h> +#include <runtime/Operations.h> #include <wtf/RunLoop.h> -#include <wtf/TemporaryChange.h> - -#if ENABLE(DATA_DETECTION) -#include "DataDetectionResult.h" -#endif #if ENABLE(MHTML) #include <WebCore/MHTMLArchive.h> #endif +#if PLATFORM(MAC) +#include "MachPort.h" +#endif + #if ENABLE(BATTERY_STATUS) #include "WebBatteryClient.h" #endif +#if ENABLE(NETWORK_INFO) +#include "WebNetworkInfoClient.h" +#endif + #if ENABLE(VIBRATION) #include "WebVibrationClient.h" #endif @@ -189,11 +170,8 @@ #include "WebDeviceProximityClient.h" #endif -#if PLATFORM(COCOA) +#if PLATFORM(MAC) #include "PDFPlugin.h" -#include "RemoteLayerTreeTransaction.h" -#include "WKStringCF.h" -#include "WebVideoFullscreenManager.h" #include <WebCore/LegacyWebArchive.h> #endif @@ -203,44 +181,19 @@ #include "WebPrintOperationGtk.h" #endif -#if PLATFORM(IOS) -#include "RemoteLayerTreeDrawingArea.h" -#include <CoreGraphics/CoreGraphics.h> -#include <WebCore/CoreTextSPI.h> -#include <WebCore/Icon.h> -#endif - #ifndef NDEBUG #include <wtf/RefCountedLeakCounter.h> #endif -#if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER) -#include "LayerTreeHost.h" -#endif - -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) +#if USE(COORDINATED_GRAPHICS) #include "CoordinatedLayerTreeHostMessages.h" #endif -#if ENABLE(DATA_DETECTION) -#include <WebCore/DataDetection.h> -#endif - -#if ENABLE(VIDEO) && USE(GSTREAMER) -#include <WebCore/MediaPlayerRequestInstallMissingPluginsCallback.h> -#endif - -#if USE(APPLE_INTERNAL_SDK) -#include <WebKitAdditions/WebPageIncludes.h> -#endif - using namespace JSC; using namespace WebCore; namespace WebKit { -static const double pageScrollHysteresisSeconds = 0.3; - class SendStopResponsivenessTimer { public: SendStopResponsivenessTimer(WebPage* page) @@ -259,22 +212,24 @@ private: DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage")); -Ref<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters) +PassRefPtr<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters) { - Ref<WebPage> page = adoptRef(*new WebPage(pageID, parameters)); + RefPtr<WebPage> page = adoptRef(new WebPage(pageID, parameters)); - if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle()) - WebProcess::singleton().injectedBundle()->didCreatePage(page.ptr()); + if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle()) + WebProcess::shared().injectedBundle()->didCreatePage(page.get()); - return page; + return page.release(); } WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters) : m_pageID(pageID) + , m_sessionID(0) , m_viewSize(parameters.viewSize) , m_hasSeenPlugin(false) , m_useFixedLayout(false) , m_drawsBackground(true) + , m_drawsTransparentBackground(false) , m_isInRedo(false) , m_isClosed(false) , m_tabToLinks(false) @@ -290,123 +245,80 @@ WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters) , m_determinePrimarySnapshottedPlugInTimer(RunLoop::main(), this, &WebPage::determinePrimarySnapshottedPlugInTimerFired) #endif , m_layerHostingMode(parameters.layerHostingMode) -#if PLATFORM(COCOA) +#if PLATFORM(MAC) , m_pdfPluginEnabled(false) , m_hasCachedWindowFrame(false) + , m_keyboardEventBeingInterpreted(0) +#if !PLATFORM(IOS) , m_viewGestureGeometryCollector(*this) -#elif HAVE(ACCESSIBILITY) && (PLATFORM(GTK) || PLATFORM(EFL)) - , m_accessibilityObject(nullptr) #endif - , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired) -#if ENABLE(CONTEXT_MENUS) - , m_contextMenuClient(std::make_unique<API::InjectedBundle::PageContextMenuClient>()) +#elif PLATFORM(GTK) && HAVE(ACCESSIBILITY) + , m_accessibilityObject(0) #endif - , m_formClient(std::make_unique<API::InjectedBundle::FormClient>()) - , m_uiClient(std::make_unique<API::InjectedBundle::PageUIClient>()) + , m_setCanStartMediaTimer(RunLoop::main(), this, &WebPage::setCanStartMediaTimerFired) + , m_sendDidUpdateViewStateTimer(RunLoop::main(), this, &WebPage::didUpdateViewStateTimerFired) , m_findController(this) #if ENABLE(INPUT_TYPE_COLOR) , m_activeColorChooser(0) #endif - , m_userContentController(parameters.userContentControllerID ? WebUserContentController::getOrCreate(parameters.userContentControllerID) : nullptr) #if ENABLE(GEOLOCATION) , m_geolocationPermissionRequestManager(this) #endif -#if ENABLE(MEDIA_STREAM) - , m_userMediaPermissionRequestManager(*this) -#endif - , m_pageScrolledHysteresis([this](HysteresisState state) { if (state == HysteresisState::Stopped) pageStoppedScrolling(); }, pageScrollHysteresisSeconds) , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel) , m_canRunModal(parameters.canRunModal) , m_isRunningModal(false) -#if ENABLE(DRAG_SUPPORT) - , m_isStartingDrag(false) -#endif - , m_cachedMainFrameIsPinnedToLeftSide(true) - , m_cachedMainFrameIsPinnedToRightSide(true) - , m_cachedMainFrameIsPinnedToTopSide(true) - , m_cachedMainFrameIsPinnedToBottomSide(true) + , m_cachedMainFrameIsPinnedToLeftSide(false) + , m_cachedMainFrameIsPinnedToRightSide(false) + , m_cachedMainFrameIsPinnedToTopSide(false) + , m_cachedMainFrameIsPinnedToBottomSide(false) , m_canShortCircuitHorizontalWheelEvents(false) - , m_hasWheelEventHandlers(false) + , m_numWheelEventHandlers(0) , m_cachedPageCount(0) , m_autoSizingShouldExpandToViewHeight(false) #if ENABLE(CONTEXT_MENUS) , m_isShowingContextMenu(false) #endif #if PLATFORM(IOS) - , m_selectionAnchor(Start) - , m_hasReceivedVisibleContentRectsAfterDidCommitLoad(false) - , m_scaleWasSetByUIProcess(false) - , m_userHasChangedPageScaleFactor(false) - , m_hasStablePageScaleFactor(true) - , m_userIsInteracting(false) - , m_hasPendingBlurNotification(false) - , m_useTestingViewportConfiguration(false) - , m_isInStableState(true) - , m_oldestNonStableUpdateVisibleContentRectsTimestamp(std::chrono::milliseconds::zero()) - , m_estimatedLatency(std::chrono::milliseconds::zero()) - , m_screenSize(parameters.screenSize) - , m_availableScreenSize(parameters.availableScreenSize) - , m_deviceOrientation(0) - , m_inDynamicSizeUpdate(false) - , m_volatilityTimer(*this, &WebPage::volatilityTimerFired) + , m_shouldReturnWordAtSelection(false) #endif + , m_inspectorClient(0) , m_backgroundColor(Color::white) , m_maximumRenderingSuppressionToken(0) , m_scrollPinningBehavior(DoNotPin) , m_useAsyncScrolling(false) , m_viewState(parameters.viewState) - , m_processSuppressionEnabled(true) - , m_userActivity("Process suppression disabled for page.") - , m_pendingNavigationID(0) -#if ENABLE(WEBGL) - , m_systemWebGLPolicy(WebGLAllowCreation) -#endif - , m_mainFrameProgressCompleted(false) - , m_shouldDispatchFakeMouseMoveEvents(true) + , m_processSuppressionDisabledByWebPreference("Process suppression is disabled.") { ASSERT(m_pageID); + // FIXME: This is a non-ideal location for this Setting and + // 4ms should be adopted project-wide now, https://bugs.webkit.org/show_bug.cgi?id=61214 + Settings::setDefaultMinDOMTimerInterval(0.004); - m_pageGroup = WebProcess::singleton().webPageGroup(parameters.pageGroupData); - -#if PLATFORM(IOS) - Settings::setShouldManageAudioSessionCategory(true); -#endif - - PageConfiguration pageConfiguration; - pageConfiguration.chromeClient = new WebChromeClient(this); + Page::PageClients pageClients; + pageClients.chromeClient = new WebChromeClient(this); #if ENABLE(CONTEXT_MENUS) - pageConfiguration.contextMenuClient = new WebContextMenuClient(this); + pageClients.contextMenuClient = new WebContextMenuClient(this); #endif - pageConfiguration.editorClient = new WebEditorClient(this); + pageClients.editorClient = new WebEditorClient(this); #if ENABLE(DRAG_SUPPORT) - pageConfiguration.dragClient = new WebDragClient(this); + pageClients.dragClient = new WebDragClient(this); #endif - pageConfiguration.backForwardClient = WebBackForwardListProxy::create(this); - pageConfiguration.inspectorClient = new WebInspectorClient(this); -#if USE(AUTOCORRECTION_PANEL) - pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(this); + pageClients.backForwardClient = WebBackForwardListProxy::create(this); +#if ENABLE(INSPECTOR) + m_inspectorClient = new WebInspectorClient(this); + pageClients.inspectorClient = m_inspectorClient; #endif - - pageConfiguration.plugInClient = new WebPlugInClient(*this); - pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient; - pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(*this); - pageConfiguration.diagnosticLoggingClient = new WebDiagnosticLoggingClient(*this); - - pageConfiguration.databaseProvider = WebDatabaseProvider::getOrCreate(m_pageGroup->pageGroupID()); - pageConfiguration.storageNamespaceProvider = WebStorageNamespaceProvider::getOrCreate(m_pageGroup->pageGroupID()); - pageConfiguration.userContentController = m_userContentController ? &m_userContentController->userContentController() : &m_pageGroup->userContentController(); - pageConfiguration.visitedLinkStore = VisitedLinkTableController::getOrCreate(parameters.visitedLinkTableID); - -#if USE(APPLE_INTERNAL_SDK) -#include <WebKitAdditions/WebPageInitialization.h> +#if USE(AUTOCORRECTION_PANEL) + pageClients.alternativeTextClient = new WebAlternativeTextClient(this); #endif + pageClients.plugInClient = new WebPlugInClient(this); + pageClients.loaderClientForMainFrame = new WebFrameLoaderClient; + pageClients.progressTrackerClient = new WebProgressTrackerClient(*this); - m_page = std::make_unique<Page>(pageConfiguration); - updatePreferences(parameters.store); + m_page = adoptPtr(new Page(pageClients)); - m_drawingArea = DrawingArea::create(*this, parameters); + m_drawingArea = DrawingArea::create(this, parameters); m_drawingArea->setPaintingEnabled(false); - m_drawingArea->setShouldScaleViewToFitDocument(parameters.shouldScaleViewToFitDocument); #if ENABLE(ASYNC_SCROLLING) m_useAsyncScrolling = parameters.store.getBoolValueForKey(WebPreferencesKey::threadedScrollingEnabledKey()); @@ -416,7 +328,6 @@ WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters) #endif m_mainFrame = WebFrame::createWithCoreMainFrame(this, &m_page->mainFrame()); - m_drawingArea->updatePreferences(parameters.store); #if ENABLE(BATTERY_STATUS) WebCore::provideBatteryTo(m_page.get(), new WebBatteryClient(this)); @@ -424,6 +335,9 @@ WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters) #if ENABLE(GEOLOCATION) WebCore::provideGeolocationTo(m_page.get(), new WebGeolocationClient(this)); #endif +#if ENABLE(NETWORK_INFO) + WebCore::provideNetworkInfoTo(m_page.get(), new WebNetworkInfoClient(this)); +#endif #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS) WebCore::provideNotification(m_page.get(), new WebNotificationClient(this)); #endif @@ -433,29 +347,25 @@ WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters) #if ENABLE(PROXIMITY_EVENTS) WebCore::provideDeviceProximityTo(m_page.get(), new WebDeviceProximityClient(this)); #endif -#if ENABLE(MEDIA_STREAM) - WebCore::provideUserMediaTo(m_page.get(), new WebUserMediaClient(*this)); -#endif #if ENABLE(REMOTE_INSPECTOR) - m_page->setRemoteInspectionAllowed(parameters.allowsRemoteInspection); - m_page->setRemoteInspectionNameOverride(parameters.remoteInspectionNameOverride); + m_page->setRemoteInspectionAllowed(true); #endif m_page->setCanStartMedia(false); m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow; + m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData); m_page->setGroupName(m_pageGroup->identifier()); m_page->setDeviceScaleFactor(parameters.deviceScaleFactor); -#if PLATFORM(IOS) - m_page->setTextAutosizingWidth(parameters.textAutosizingWidth); -#endif + updatePreferences(parameters.store); platformInitialize(); setUseFixedLayout(parameters.useFixedLayout); setDrawsBackground(parameters.drawsBackground); + setDrawsTransparentBackground(parameters.drawsTransparentBackground); setUnderlayColor(parameters.underlayColor); @@ -463,59 +373,53 @@ WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters) setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns); setPageLength(parameters.pageLength); setGapBetweenPages(parameters.gapBetweenPages); - setPaginationLineGridEnabled(parameters.paginationLineGridEnabled); - - // If the page is created off-screen, its visibilityState should be prerender. - m_page->setViewState(m_viewState); - if (!isVisible()) - m_page->setIsPrerender(); - updateUserActivity(); - updateIsInWindow(true); + setMemoryCacheMessagesEnabled(parameters.areMemoryCacheClientCallsEnabled); + + setActive(parameters.viewState & ViewState::WindowIsActive); + setFocused(parameters.viewState & ViewState::IsFocused); + + // Page defaults to in-window, but setIsInWindow depends on it being a valid indicator of actually having been put into a window. + bool isInWindow = parameters.viewState & ViewState::IsInWindow; + if (!isInWindow) + m_page->setIsInWindow(false); + else + WebProcess::shared().pageDidEnterWindow(m_pageID); + + setIsInWindow(isInWindow); setMinimumLayoutSize(parameters.minimumLayoutSize); setAutoSizingShouldExpandToViewHeight(parameters.autoSizingShouldExpandToViewHeight); setScrollPinningBehavior(parameters.scrollPinningBehavior); - if (parameters.scrollbarOverlayStyle) - m_scrollbarOverlayStyle = static_cast<ScrollbarOverlayStyle>(parameters.scrollbarOverlayStyle.value()); - else - m_scrollbarOverlayStyle = WTF::Optional<ScrollbarOverlayStyle>(); - setBackgroundExtendsBeyondPage(parameters.backgroundExtendsBeyondPage); - setTopContentInset(parameters.topContentInset); - m_userAgent = parameters.userAgent; WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID); - if (!parameters.itemStates.isEmpty()) - restoreSessionInternal(parameters.itemStates, WasRestoredByAPIRequest::No); - - if (parameters.sessionID.isValid()) - setSessionID(parameters.sessionID); + if (!parameters.sessionState.isEmpty()) + restoreSession(parameters.sessionState); m_drawingArea->setPaintingEnabled(true); setMediaVolume(parameters.mediaVolume); - setMuted(parameters.muted); - - // We use the DidFirstVisuallyNonEmptyLayout milestone to determine when to unfreeze the layer tree. - m_page->addLayoutMilestones(DidFirstLayout | DidFirstVisuallyNonEmptyLayout); + // We use the DidFirstLayout milestone to determine when to unfreeze the layer tree. + m_page->addLayoutMilestones(DidFirstLayout); - auto& webProcess = WebProcess::singleton(); - webProcess.addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this); + WebProcess::shared().addMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID, *this); // FIXME: This should be done in the object constructors, and the objects themselves should be message receivers. -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) - webProcess.addMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID, *this); + WebProcess::shared().addMessageReceiver(Messages::DrawingArea::messageReceiverName(), m_pageID, *this); +#if USE(COORDINATED_GRAPHICS) + WebProcess::shared().addMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID, *this); +#endif +#if ENABLE(INSPECTOR) + WebProcess::shared().addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this); #endif - webProcess.addMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID, *this); - webProcess.addMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID, *this); #if ENABLE(FULLSCREEN_API) - webProcess.addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this); + WebProcess::shared().addMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID, *this); #endif #ifndef NDEBUG @@ -524,52 +428,19 @@ WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters) #if ENABLE(ASYNC_SCROLLING) if (m_useAsyncScrolling) - webProcess.eventDispatcher().addScrollingTreeForPage(this); -#endif - - for (auto& mimeType : parameters.mimeTypesWithCustomContentProviders) - m_mimeTypesWithCustomContentProviders.add(mimeType); - - -#if ENABLE(ENCRYPTED_MEDIA_V2) - if (WebMediaKeyStorageManager* manager = webProcess.supplement<WebMediaKeyStorageManager>()) - m_page->settings().setMediaKeysStorageDirectory(manager->mediaKeyStorageDirectory()); + WebProcess::shared().eventDispatcher().addScrollingTreeForPage(this); #endif - m_page->settings().setAppleMailPaginationQuirkEnabled(parameters.appleMailPaginationQuirkEnabled); - if (parameters.viewScaleFactor != 1) - scaleView(parameters.viewScaleFactor); - -#if PLATFORM(IOS) - m_page->settings().setContentDispositionAttachmentSandboxEnabled(true); -#endif + m_page->setIsVisible(m_viewState & ViewState::IsVisible, true); + setIsVisuallyIdle(m_viewState & ViewState::IsVisuallyIdle); } void WebPage::reinitializeWebPage(const WebPageCreationParameters& parameters) { if (m_viewState != parameters.viewState) - setViewState(parameters.viewState, false, Vector<uint64_t>()); + setViewStateInternal(parameters.viewState, true); if (m_layerHostingMode != parameters.layerHostingMode) - setLayerHostingMode(static_cast<unsigned>(parameters.layerHostingMode)); -} - -void WebPage::setPageActivityState(PageActivityState::Flags activityState) -{ - PageActivityState::Flags changed = m_activityState ^ activityState; - m_activityState = activityState; - - if (changed) - updateUserActivity(); -} - -void WebPage::updateUserActivity() -{ - // Start the activity to prevent AppNap if the page activity is in progress, - // the page is visible and non-idle, or process suppression is disabled. - if (m_activityState || !(m_viewState & ViewState::IsVisuallyIdle) || !m_processSuppressionEnabled) - m_userActivity.start(); - else - m_userActivity.stop(); + setLayerHostingMode(parameters.layerHostingMode); } WebPage::~WebPage() @@ -579,14 +450,11 @@ WebPage::~WebPage() ASSERT(!m_page); - auto& webProcess = WebProcess::singleton(); #if ENABLE(ASYNC_SCROLLING) if (m_useAsyncScrolling) - webProcess.eventDispatcher().removeScrollingTreeForPage(this); + WebProcess::shared().eventDispatcher().removeScrollingTreeForPage(this); #endif - platformDetach(); - m_sandboxExtensionTracker.invalidate(); for (auto* pluginView : m_pluginViews) @@ -599,16 +467,18 @@ WebPage::~WebPage() m_footerBanner->detachFromPage(); #endif // !PLATFORM(IOS) - webProcess.removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID); + WebProcess::shared().removeMessageReceiver(Messages::WebPage::messageReceiverName(), m_pageID); // FIXME: This should be done in the object destructors, and the objects themselves should be message receivers. -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) - webProcess.removeMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID); + WebProcess::shared().removeMessageReceiver(Messages::DrawingArea::messageReceiverName(), m_pageID); +#if USE(COORDINATED_GRAPHICS) + WebProcess::shared().removeMessageReceiver(Messages::CoordinatedLayerTreeHost::messageReceiverName(), m_pageID); +#endif +#if ENABLE(INSPECTOR) + WebProcess::shared().removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID); #endif - webProcess.removeMessageReceiver(Messages::WebInspector::messageReceiverName(), m_pageID); - webProcess.removeMessageReceiver(Messages::WebInspectorUI::messageReceiverName(), m_pageID); #if ENABLE(FULLSCREEN_API) - webProcess.removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID); + WebProcess::shared().removeMessageReceiver(Messages::WebFullScreenManager::messageReceiverName(), m_pageID); #endif #ifndef NDEBUG @@ -622,7 +492,7 @@ void WebPage::dummy(bool&) IPC::Connection* WebPage::messageSenderConnection() { - return WebProcess::singleton().parentProcessConnection(); + return WebProcess::shared().parentProcessConnection(); } uint64_t WebPage::messageSenderDestinationID() @@ -631,14 +501,9 @@ uint64_t WebPage::messageSenderDestinationID() } #if ENABLE(CONTEXT_MENUS) -void WebPage::setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient> contextMenuClient) +void WebPage::initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClientBase* client) { - if (!contextMenuClient) { - m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>(); - return; - } - - m_contextMenuClient = WTFMove(contextMenuClient); + m_contextMenuClient.initialize(client); } #endif @@ -647,14 +512,9 @@ void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClientBase* m_editorClient.initialize(client); } -void WebPage::setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient> formClient) +void WebPage::initializeInjectedBundleFormClient(WKBundlePageFormClientBase* client) { - if (!formClient) { - m_formClient = std::make_unique<API::InjectedBundle::FormClient>(); - return; - } - - m_formClient = WTFMove(formClient); + m_formClient.initialize(client); } void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClientBase* client) @@ -686,14 +546,9 @@ void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoa m_resourceLoadClient.initialize(client); } -void WebPage::setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient> uiClient) +void WebPage::initializeInjectedBundleUIClient(WKBundlePageUIClientBase* client) { - if (!uiClient) { - m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>(); - return; - } - - m_uiClient = WTFMove(uiClient); + m_uiClient.initialize(client); } #if ENABLE(FULLSCREEN_API) @@ -713,16 +568,9 @@ PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* plu { String frameURLString = frame->coreFrame()->loader().documentLoader()->responseURL().string(); String pageURLString = m_page->mainFrame().loader().documentLoader()->responseURL().string(); - -#if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC) - HTMLPlugInImageElement& pluginImageElement = downcast<HTMLPlugInImageElement>(*pluginElement); - unsigned pluginArea = 0; - PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot && !(plugInIsPrimarySize(pluginImageElement, pluginArea) && !plugInIntersectsSearchRect(pluginImageElement)) ? PluginProcessTypeSnapshot : PluginProcessTypeNormal; -#else PluginProcessType processType = pluginElement->displayState() == HTMLPlugInElement::WaitingForSnapshot ? PluginProcessTypeSnapshot : PluginProcessTypeNormal; -#endif - bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins(); + bool allowOnlyApplicationPlugins = !frame->coreFrame()->loader().subframeLoader().allowPlugins(NotAboutToInstantiatePlugin); uint64_t pluginProcessToken; uint32_t pluginLoadPolicy; @@ -730,8 +578,7 @@ PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* plu if (!sendSync(Messages::WebPageProxy::FindPlugin(parameters.mimeType, static_cast<uint32_t>(processType), parameters.url.string(), frameURLString, pageURLString, allowOnlyApplicationPlugins), Messages::WebPageProxy::FindPlugin::Reply(pluginProcessToken, newMIMEType, pluginLoadPolicy, unavailabilityDescription))) return nullptr; - PluginModuleLoadPolicy loadPolicy = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy); - bool isBlockedPlugin = (loadPolicy == PluginModuleBlockedForSecurity) || (loadPolicy == PluginModuleBlockedForCompatibility); + bool isBlockedPlugin = static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy) == PluginModuleBlocked; if (isBlockedPlugin || !pluginProcessToken) { #if ENABLE(PDFKIT_PLUGIN) @@ -747,11 +594,11 @@ PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* plu if (isBlockedPlugin) { bool replacementObscured = false; - if (is<RenderEmbeddedObject>(*pluginElement->renderer())) { - auto& renderObject = downcast<RenderEmbeddedObject>(*pluginElement->renderer()); - renderObject.setPluginUnavailabilityReasonWithDescription(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription); - replacementObscured = renderObject.isReplacementObscured(); - renderObject.setUnavailablePluginIndicatorIsHidden(replacementObscured); + if (pluginElement->renderer()->isEmbeddedObject()) { + RenderEmbeddedObject* renderObject = toRenderEmbeddedObject(pluginElement->renderer()); + renderObject->setPluginUnavailabilityReasonWithDescription(RenderEmbeddedObject::InsecurePluginVersion, unavailabilityDescription); + replacementObscured = renderObject->isReplacementObscured(); + renderObject->setUnavailablePluginIndicatorIsHidden(replacementObscured); } send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string(), frameURLString, pageURLString, replacementObscured)); @@ -767,19 +614,19 @@ PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* plu #endif // ENABLE(NETSCAPE_PLUGIN_API) -#if ENABLE(WEBGL) && !PLATFORM(COCOA) -WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame*, const String& /* url */) +#if ENABLE(WEBGL) +WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame* frame, const String& url) { - return WebGLAllowCreation; -} + uint32_t policyResult = 0; -WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame*, const String& /* url */) -{ - return WebGLAllowCreation; + if (sendSync(Messages::WebPageProxy::WebGLPolicyForURL(url), Messages::WebPageProxy::WebGLPolicyForURL::Reply(policyResult))) + return static_cast<WebGLLoadPolicy>(policyResult); + + return WebGLAllow; } -#endif +#endif // ENABLE(WEBGL) -EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayoutData) const +EditorState WebPage::editorState() const { Frame& frame = m_page->focusController().focusedOrMainFrame(); @@ -794,17 +641,45 @@ EditorState WebPage::editorState(IncludePostLayoutDataHint shouldIncludePostLayo } } - const VisibleSelection& selection = frame.selection().selection(); - - result.selectionIsNone = selection.isNone(); - result.selectionIsRange = selection.isRange(); - result.isContentEditable = selection.isContentEditable(); - result.isContentRichlyEditable = selection.isContentRichlyEditable(); - result.isInPasswordField = selection.isInPasswordField(); + result.selectionIsNone = frame.selection().isNone(); + result.selectionIsRange = frame.selection().isRange(); + result.isContentEditable = frame.selection().isContentEditable(); + result.isContentRichlyEditable = frame.selection().isContentRichlyEditable(); + result.isInPasswordField = frame.selection().isInPasswordField(); result.hasComposition = frame.editor().hasComposition(); result.shouldIgnoreCompositionSelectionChange = frame.editor().ignoreCompositionSelectionChange(); - - platformEditorState(frame, result, shouldIncludePostLayoutData); + +#if PLATFORM(IOS) + FrameSelection& selection = frame.selection(); + if (frame.editor().hasComposition()) { + RefPtr<Range> compositionRange = frame.editor().compositionRange(); + Vector<WebCore::SelectionRect> compositionRects; + compositionRange->collectSelectionRects(compositionRects); + if (compositionRects.size()) + result.firstMarkedRect = compositionRects[0].rect(); + if (compositionRects.size() > 1) + result.lastMarkedRect = compositionRects.last().rect(); + else + result.lastMarkedRect = result.firstMarkedRect; + result.markedText = plainText(compositionRange.get()); + } + if (selection.isCaret()) { + result.caretRectAtStart = selection.absoluteCaretBounds(); + result.caretRectAtEnd = result.caretRectAtStart; + if (m_shouldReturnWordAtSelection) + result.wordAtSelection = plainText(wordRangeFromPosition(selection.start()).get()); + } else if (selection.isRange()) { + result.caretRectAtStart = VisiblePosition(selection.start()).absoluteCaretBounds(); + result.caretRectAtEnd = VisiblePosition(selection.end()).absoluteCaretBounds(); + RefPtr<Range> selectedRange = selection.toNormalizedRange(); + selectedRange->collectSelectionRects(result.selectionRects); + result.selectedTextLength = plainText(selectedRange.get(), TextIteratorDefaultBehavior, true).length(); + } +#endif + +#if PLATFORM(GTK) + result.cursorRect = frame.selection().absoluteCaretBounds(); +#endif return result; } @@ -846,7 +721,7 @@ void WebPage::resetTrackedRepaints() view->resetTrackedRepaints(); } -Ref<API::Array> WebPage::trackedRepaintRects() +PassRefPtr<API::Array> WebPage::trackedRepaintRects() { FrameView* view = mainFrameView(); if (!view) @@ -858,7 +733,7 @@ Ref<API::Array> WebPage::trackedRepaintRects() for (const auto& repaintRect : view->trackedRepaintRects()) repaintRects.uncheckedAppend(API::Rect::create(toAPI(repaintRect))); - return API::Array::create(WTFMove(repaintRects)); + return API::Array::create(std::move(repaintRects)); } PluginView* WebPage::focusedPluginViewForFrame(Frame& frame) @@ -897,19 +772,6 @@ void WebPage::executeEditingCommand(const String& commandName, const String& arg frame.editor().command(commandName).execute(argument); } -void WebPage::setEditable(bool editable) -{ - m_page->setEditable(editable); - m_page->setTabKeyCyclesThroughElements(!editable); - Frame& frame = m_page->focusController().focusedOrMainFrame(); - if (editable) { - frame.editor().applyEditingStyleToBodyElement(); - // If the page is made editable and the selection is empty, set it to something. - if (frame.selection().isNone()) - frame.selection().setSelectionFromNone(); - } -} - bool WebPage::isEditingCommandEnabled(const String& commandName) { Frame& frame = m_page->focusController().focusedOrMainFrame(); @@ -927,6 +789,7 @@ void WebPage::clearMainFrameName() frame->tree().clearName(); } +#if USE(ACCELERATED_COMPOSITING) void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer) { m_drawingArea->setRootCompositingLayer(layer); @@ -936,6 +799,7 @@ void WebPage::exitAcceleratedCompositingMode() { m_drawingArea->setRootCompositingLayer(0); } +#endif void WebPage::close() { @@ -948,32 +812,30 @@ void WebPage::close() if (!mainWebFrame()->url().isEmpty()) reportUsedFeatures(); - if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle()) - WebProcess::singleton().injectedBundle()->willDestroyPage(this); - - if (m_inspector) { - m_inspector->disconnectFromPage(); - m_inspector = nullptr; - } + if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle()) + WebProcess::shared().injectedBundle()->willDestroyPage(this); +#if ENABLE(INSPECTOR) + m_inspector = 0; +#endif #if ENABLE(FULLSCREEN_API) - m_fullScreenManager = nullptr; + m_fullScreenManager = 0; #endif if (m_activePopupMenu) { m_activePopupMenu->disconnectFromPage(); - m_activePopupMenu = nullptr; + m_activePopupMenu = 0; } if (m_activeOpenPanelResultListener) { m_activeOpenPanelResultListener->disconnectFromPage(); - m_activeOpenPanelResultListener = nullptr; + m_activeOpenPanelResultListener = 0; } #if ENABLE(INPUT_TYPE_COLOR) if (m_activeColorChooser) { m_activeColorChooser->disconnectFromPage(); - m_activeColorChooser = nullptr; + m_activeColorChooser = 0; } #endif @@ -984,13 +846,6 @@ void WebPage::close() } #endif -#if ENABLE(VIDEO) && USE(GSTREAMER) - if (m_installMediaPluginsCallback) { - m_installMediaPluginsCallback->invalidate(); - m_installMediaPluginsCallback = nullptr; - } -#endif - m_sandboxExtensionTracker.invalidate(); #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC) @@ -998,14 +853,14 @@ void WebPage::close() #endif #if ENABLE(CONTEXT_MENUS) - m_contextMenuClient = std::make_unique<API::InjectedBundle::PageContextMenuClient>(); + m_contextMenuClient.initialize(0); #endif m_editorClient.initialize(0); - m_formClient = std::make_unique<API::InjectedBundle::FormClient>(); + m_formClient.initialize(0); m_loaderClient.initialize(0); m_policyClient.initialize(0); m_resourceLoadClient.initialize(0); - m_uiClient = std::make_unique<API::InjectedBundle::PageUIClient>(); + m_uiClient.initialize(0); #if ENABLE(FULLSCREEN_API) m_fullScreenClient.initialize(0); #endif @@ -1020,19 +875,17 @@ void WebPage::close() m_isRunningModal = false; // The WebPage can be destroyed by this call. - WebProcess::singleton().removeWebPage(m_pageID); - - WebProcess::singleton().updateActivePages(); + WebProcess::shared().removeWebPage(m_pageID); if (isRunningModal) - RunLoop::main().stop(); + RunLoop::main()->stop(); } void WebPage::tryClose() { SendStopResponsivenessTimer stopper(this); - if (!corePage()->userInputBridge().tryClosePage()) { + if (!m_mainFrame->coreFrame()->loader().shouldClose()) { send(Messages::WebPageProxy::StopResponsivenessTimer()); return; } @@ -1047,134 +900,108 @@ void WebPage::sendClose() void WebPage::loadURLInFrame(const String& url, uint64_t frameID) { - WebFrame* frame = WebProcess::singleton().webFrame(frameID); + WebFrame* frame = WebProcess::shared().webFrame(frameID); if (!frame) return; - frame->coreFrame()->loader().load(FrameLoadRequest(frame->coreFrame(), ResourceRequest(URL(URL(), url)), ShouldOpenExternalURLsPolicy::ShouldNotAllow)); + frame->coreFrame()->loader().load(FrameLoadRequest(frame->coreFrame(), ResourceRequest(URL(URL(), url)))); } -void WebPage::loadRequest(uint64_t navigationID, const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle, uint64_t shouldOpenExternalURLsPolicy, const UserData& userData) +void WebPage::loadRequest(const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle, IPC::MessageDecoder& decoder) { SendStopResponsivenessTimer stopper(this); - m_pendingNavigationID = navigationID; + RefPtr<API::Object> userData; + InjectedBundleUserMessageDecoder userMessageDecoder(userData); + if (!decoder.decode(userMessageDecoder)) + return; m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle); // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess // to all the client to set up any needed state. - m_loaderClient.willLoadURLRequest(this, request, WebProcess::singleton().transformHandlesToObjects(userData.object()).get()); + m_loaderClient.willLoadURLRequest(this, request, userData.get()); // Initate the load in WebCore. - FrameLoadRequest frameLoadRequest(m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow); - ShouldOpenExternalURLsPolicy externalURLsPolicy = static_cast<ShouldOpenExternalURLsPolicy>(shouldOpenExternalURLsPolicy); - frameLoadRequest.setShouldOpenExternalURLsPolicy(externalURLsPolicy); - - corePage()->userInputBridge().loadRequest(frameLoadRequest); - - ASSERT(!m_pendingNavigationID); + m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(m_mainFrame->coreFrame(), request)); } -void WebPage::loadDataImpl(uint64_t navigationID, PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, const UserData& userData) +void WebPage::loadDataImpl(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const URL& baseURL, const URL& unreachableURL, IPC::MessageDecoder& decoder) { SendStopResponsivenessTimer stopper(this); - m_pendingNavigationID = navigationID; + RefPtr<API::Object> userData; + InjectedBundleUserMessageDecoder userMessageDecoder(userData); + if (!decoder.decode(userMessageDecoder)) + return; ResourceRequest request(baseURL); - ResourceResponse response(URL(), MIMEType, sharedBuffer->size(), encodingName); - SubstituteData substituteData(sharedBuffer, unreachableURL, response, SubstituteData::SessionHistoryVisibility::Hidden); + SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL); // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess // to all the client to set up any needed state. - m_loaderClient.willLoadDataRequest(this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get()); + m_loaderClient.willLoadDataRequest(this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), userData.get()); // Initate the load in WebCore. - m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(m_mainFrame->coreFrame(), request, ShouldOpenExternalURLsPolicy::ShouldNotAllow, substituteData)); + m_mainFrame->coreFrame()->loader().load(FrameLoadRequest(m_mainFrame->coreFrame(), request, substituteData)); } -void WebPage::loadString(uint64_t navigationID, const String& htmlString, const String& MIMEType, const URL& baseURL, const URL& unreachableURL, const UserData& userData) +void WebPage::loadString(const String& htmlString, const String& MIMEType, const URL& baseURL, const URL& unreachableURL, IPC::MessageDecoder& decoder) { if (!htmlString.isNull() && htmlString.is8Bit()) { RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters8()), htmlString.length() * sizeof(LChar)); - loadDataImpl(navigationID, sharedBuffer, MIMEType, ASCIILiteral("latin1"), baseURL, unreachableURL, userData); + loadDataImpl(sharedBuffer, MIMEType, ASCIILiteral("latin1"), baseURL, unreachableURL, decoder); } else { RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters16()), htmlString.length() * sizeof(UChar)); - loadDataImpl(navigationID, sharedBuffer, MIMEType, ASCIILiteral("utf-16"), baseURL, unreachableURL, userData); + loadDataImpl(sharedBuffer, MIMEType, ASCIILiteral("utf-16"), baseURL, unreachableURL, decoder); } } -void WebPage::loadData(uint64_t navigationID, const IPC::DataReference& data, const String& MIMEType, const String& encodingName, const String& baseURLString, const UserData& userData) +void WebPage::loadData(const IPC::DataReference& data, const String& MIMEType, const String& encodingName, const String& baseURLString, IPC::MessageDecoder& decoder) { RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(data.data()), data.size()); URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString); - loadDataImpl(navigationID, sharedBuffer, MIMEType, encodingName, baseURL, URL(), userData); + loadDataImpl(sharedBuffer, MIMEType, encodingName, baseURL, URL(), decoder); } -void WebPage::loadHTMLString(uint64_t navigationID, const String& htmlString, const String& baseURLString, const UserData& userData) +void WebPage::loadHTMLString(const String& htmlString, const String& baseURLString, IPC::MessageDecoder& decoder) { URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString); - loadString(navigationID, htmlString, ASCIILiteral("text/html"), baseURL, URL(), userData); + loadString(htmlString, ASCIILiteral("text/html"), baseURL, URL(), decoder); } -void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString, const String& provisionalLoadErrorURLString, const UserData& userData) +void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString, IPC::MessageDecoder& decoder) { URL baseURL = baseURLString.isEmpty() ? blankURL() : URL(URL(), baseURLString); URL unreachableURL = unreachableURLString.isEmpty() ? URL() : URL(URL(), unreachableURLString); - URL provisionalLoadErrorURL = provisionalLoadErrorURLString.isEmpty() ? URL() : URL(URL(), provisionalLoadErrorURLString); - m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL(provisionalLoadErrorURL); - loadString(0, htmlString, ASCIILiteral("text/html"), baseURL, unreachableURL, userData); - m_mainFrame->coreFrame()->loader().setProvisionalLoadErrorBeingHandledURL({ }); + loadString(htmlString, ASCIILiteral("text/html"), baseURL, unreachableURL, decoder); } -void WebPage::loadPlainTextString(const String& string, const UserData& userData) +void WebPage::loadPlainTextString(const String& string, IPC::MessageDecoder& decoder) { - loadString(0, string, ASCIILiteral("text/plain"), blankURL(), URL(), userData); + loadString(string, ASCIILiteral("text/plain"), blankURL(), URL(), decoder); } -void WebPage::loadWebArchiveData(const IPC::DataReference& webArchiveData, const UserData& userData) +void WebPage::loadWebArchiveData(const IPC::DataReference& webArchiveData, IPC::MessageDecoder& decoder) { RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(webArchiveData.data()), webArchiveData.size() * sizeof(uint8_t)); - loadDataImpl(0, sharedBuffer, ASCIILiteral("application/x-webarchive"), ASCIILiteral("utf-16"), blankURL(), URL(), userData); -} - -void WebPage::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint) -{ - Frame* mainFrame = m_mainFrame->coreFrame(); - Document* mainFrameDocument = mainFrame->document(); - if (!mainFrameDocument) - return; - - const int singleClick = 1; - RefPtr<MouseEvent> mouseEvent = MouseEvent::create(eventNames().clickEvent, true, true, currentTime(), nullptr, singleClick, screenPoint.x(), screenPoint.y(), documentPoint.x(), documentPoint.y(), -#if ENABLE(POINTER_LOCK) - 0, 0, -#endif - false, false, false, false, 0, nullptr, 0, nullptr); - - mainFrame->loader().urlSelected(mainFrameDocument->completeURL(url), emptyString(), mouseEvent.get(), LockHistory::No, LockBackForwardList::No, ShouldSendReferrer::MaybeSendReferrer, ShouldOpenExternalURLsPolicy::ShouldNotAllow); + loadDataImpl(sharedBuffer, ASCIILiteral("application/x-webarchive"), ASCIILiteral("utf-16"), blankURL(), URL(), decoder); } void WebPage::stopLoadingFrame(uint64_t frameID) { - WebFrame* frame = WebProcess::singleton().webFrame(frameID); + WebFrame* frame = WebProcess::shared().webFrame(frameID); if (!frame) return; - corePage()->userInputBridge().stopLoadingFrame(frame->coreFrame()); + frame->coreFrame()->loader().stopForUserCancel(); } void WebPage::stopLoading() { SendStopResponsivenessTimer stopper(this); - corePage()->userInputBridge().stopLoadingFrame(m_mainFrame->coreFrame()); -} - -bool WebPage::defersLoading() const -{ - return m_page->defersLoading(); + m_mainFrame->coreFrame()->loader().stopForUserCancel(); } void WebPage::setDefersLoading(bool defersLoading) @@ -1182,18 +1009,15 @@ void WebPage::setDefersLoading(bool defersLoading) m_page->setDefersLoading(defersLoading); } -void WebPage::reload(uint64_t navigationID, bool reloadFromOrigin, bool contentBlockersEnabled, const SandboxExtension::Handle& sandboxExtensionHandle) +void WebPage::reload(bool reloadFromOrigin, const SandboxExtension::Handle& sandboxExtensionHandle) { SendStopResponsivenessTimer stopper(this); - ASSERT(!m_mainFrame->coreFrame()->loader().frameHasLoaded() || !m_pendingNavigationID); - m_pendingNavigationID = navigationID; - m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle); - corePage()->userInputBridge().reloadFrame(m_mainFrame->coreFrame(), reloadFromOrigin, contentBlockersEnabled); + m_mainFrame->coreFrame()->loader().reload(reloadFromOrigin); } -void WebPage::goForward(uint64_t navigationID, uint64_t backForwardItemID) +void WebPage::goForward(uint64_t backForwardItemID) { SendStopResponsivenessTimer stopper(this); @@ -1202,13 +1026,10 @@ void WebPage::goForward(uint64_t navigationID, uint64_t backForwardItemID) if (!item) return; - ASSERT(!m_pendingNavigationID); - m_pendingNavigationID = navigationID; - - m_page->goToItem(*item, FrameLoadType::Forward); + m_page->goToItem(item, FrameLoadTypeForward); } -void WebPage::goBack(uint64_t navigationID, uint64_t backForwardItemID) +void WebPage::goBack(uint64_t backForwardItemID) { SendStopResponsivenessTimer stopper(this); @@ -1217,13 +1038,10 @@ void WebPage::goBack(uint64_t navigationID, uint64_t backForwardItemID) if (!item) return; - ASSERT(!m_pendingNavigationID); - m_pendingNavigationID = navigationID; - - m_page->goToItem(*item, FrameLoadType::Back); + m_page->goToItem(item, FrameLoadTypeBack); } -void WebPage::goToBackForwardItem(uint64_t navigationID, uint64_t backForwardItemID) +void WebPage::goToBackForwardItem(uint64_t backForwardItemID) { SendStopResponsivenessTimer stopper(this); @@ -1232,10 +1050,7 @@ void WebPage::goToBackForwardItem(uint64_t navigationID, uint64_t backForwardIte if (!item) return; - ASSERT(!m_pendingNavigationID); - m_pendingNavigationID = navigationID; - - m_page->goToItem(*item, FrameLoadType::IndexedBackForward); + m_page->goToItem(item, FrameLoadTypeIndexedBackForward); } void WebPage::tryRestoreScrollPosition() @@ -1265,13 +1080,13 @@ void WebPage::setSize(const WebCore::IntSize& viewSize) m_viewSize = viewSize; -#if USE(COORDINATED_GRAPHICS) +#if USE(TILED_BACKING_STORE) if (view->useFixedLayout()) sendViewportAttributesChanged(); #endif } -#if USE(COORDINATED_GRAPHICS) +#if USE(TILED_BACKING_STORE) void WebPage::setFixedVisibleContentRect(const IntRect& rect) { ASSERT(m_useFixedLayout); @@ -1321,12 +1136,7 @@ void WebPage::sendViewportAttributesChanged() // This also takes care of the relayout. setFixedLayoutSize(roundedIntSize(attr.layoutSize)); -#if USE(COORDINATED_GRAPHICS_THREADED) - if (m_drawingArea->layerTreeHost()) - m_drawingArea->layerTreeHost()->didChangeViewportProperties(attr); -#else send(Messages::WebPageProxy::DidChangeViewportProperties(attr)); -#endif } #endif @@ -1334,8 +1144,8 @@ void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffse { FrameView* frameView = m_page->mainFrame().view(); - ScrollPosition scrollPosition = frameView->scrollPosition(); - ScrollPosition maximumScrollPosition = frameView->maximumScrollPosition(); + IntPoint scrollPosition = frameView->scrollPosition(); + IntPoint maximumScrollPosition = frameView->maximumScrollPosition(); // If the current scroll position in a direction is the max scroll position // we don't want to scroll at all. @@ -1356,18 +1166,20 @@ void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect) GraphicsContextStateSaver stateSaver(graphicsContext); graphicsContext.clip(rect); - m_mainFrame->coreFrame()->view()->paint(graphicsContext, rect); + m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect); } -double WebPage::textZoomFactor() const +void WebPage::drawPageOverlay(PageOverlay* pageOverlay, GraphicsContext& graphicsContext, const IntRect& rect) { - PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame()); - if (pluginView && pluginView->requiresUnifiedScaleFactor()) { - if (pluginView->handlesPageScaleFactor()) - return pluginView->pageScaleFactor(); - return pageScaleFactor(); - } + ASSERT(pageOverlay); + + GraphicsContextStateSaver stateSaver(graphicsContext); + graphicsContext.clip(rect); + pageOverlay->drawRect(graphicsContext, rect); +} +double WebPage::textZoomFactor() const +{ Frame* frame = m_mainFrame->coreFrame(); if (!frame) return 1; @@ -1377,13 +1189,8 @@ double WebPage::textZoomFactor() const void WebPage::setTextZoomFactor(double zoomFactor) { PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame()); - if (pluginView && pluginView->requiresUnifiedScaleFactor()) { - if (pluginView->handlesPageScaleFactor()) - pluginView->setPageScaleFactor(zoomFactor, IntPoint()); - else - scalePage(zoomFactor, IntPoint()); + if (pluginView && pluginView->handlesPageScaleFactor()) return; - } Frame* frame = m_mainFrame->coreFrame(); if (!frame) @@ -1394,11 +1201,8 @@ void WebPage::setTextZoomFactor(double zoomFactor) double WebPage::pageZoomFactor() const { PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame()); - if (pluginView && pluginView->requiresUnifiedScaleFactor()) { - if (pluginView->handlesPageScaleFactor()) - return pluginView->pageScaleFactor(); - return pageScaleFactor(); - } + if (pluginView && pluginView->handlesPageScaleFactor()) + return pluginView->pageScaleFactor(); Frame* frame = m_mainFrame->coreFrame(); if (!frame) @@ -1409,11 +1213,8 @@ double WebPage::pageZoomFactor() const void WebPage::setPageZoomFactor(double zoomFactor) { PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame()); - if (pluginView && pluginView->requiresUnifiedScaleFactor()) { - if (pluginView->handlesPageScaleFactor()) - pluginView->setPageScaleFactor(zoomFactor, IntPoint()); - else - scalePage(zoomFactor, IntPoint()); + if (pluginView && pluginView->handlesPageScaleFactor()) { + pluginView->setPageScaleFactor(zoomFactor, IntPoint()); return; } @@ -1426,11 +1227,8 @@ void WebPage::setPageZoomFactor(double zoomFactor) void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor) { PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame()); - if (pluginView && pluginView->requiresUnifiedScaleFactor()) { - if (pluginView->handlesPageScaleFactor()) - pluginView->setPageScaleFactor(pageZoomFactor, IntPoint()); - else - scalePage(pageZoomFactor, IntPoint()); + if (pluginView && pluginView->handlesPageScaleFactor()) { + pluginView->setPageScaleFactor(pageZoomFactor, IntPoint()); return; } @@ -1440,103 +1238,39 @@ void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFa return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor)); } -void WebPage::windowScreenDidChange(uint32_t displayID) +void WebPage::windowScreenDidChange(uint64_t displayID) { m_page->chrome().windowScreenDidChange(static_cast<PlatformDisplayID>(displayID)); } void WebPage::scalePage(double scale, const IntPoint& origin) { - double totalScale = scale * viewScaleFactor(); - bool willChangeScaleFactor = totalScale != totalScaleFactor(); - -#if PLATFORM(IOS) - if (willChangeScaleFactor) { - if (!m_inDynamicSizeUpdate) - m_dynamicSizeUpdateHistory.clear(); - m_scaleWasSetByUIProcess = false; - } -#endif PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame()); if (pluginView && pluginView->handlesPageScaleFactor()) { - // If the main-frame plugin wants to handle the page scale factor, make sure to reset WebCore's page scale. - // Otherwise, we can end up with an immutable but non-1 page scale applied by WebCore on top of whatever the plugin does. - if (m_page->pageScaleFactor() != 1) { - m_page->setPageScaleFactor(1, origin); - for (auto* pluginView : m_pluginViews) - pluginView->pageScaleFactorDidChange(); - } - - pluginView->setPageScaleFactor(totalScale, origin); + pluginView->setPageScaleFactor(scale, origin); return; } - m_page->setPageScaleFactor(totalScale, origin); - - // We can't early return before setPageScaleFactor because the origin might be different. - if (!willChangeScaleFactor) - return; + m_page->setPageScaleFactor(scale, origin); for (auto* pluginView : m_pluginViews) pluginView->pageScaleFactorDidChange(); -#if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER) if (m_drawingArea->layerTreeHost()) m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged(); -#endif send(Messages::WebPageProxy::PageScaleFactorDidChange(scale)); } -void WebPage::scalePageInViewCoordinates(double scale, IntPoint centerInViewCoordinates) -{ - double totalScale = scale * viewScaleFactor(); - if (totalScale == totalScaleFactor()) - return; - - IntPoint scrollPositionAtNewScale = mainFrameView()->rootViewToContents(-centerInViewCoordinates); - double scaleRatio = scale / pageScaleFactor(); - scrollPositionAtNewScale.scale(scaleRatio, scaleRatio); - scalePage(scale, scrollPositionAtNewScale); -} - -double WebPage::totalScaleFactor() const +double WebPage::pageScaleFactor() const { PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame()); if (pluginView && pluginView->handlesPageScaleFactor()) return pluginView->pageScaleFactor(); - + return m_page->pageScaleFactor(); } -double WebPage::pageScaleFactor() const -{ - return totalScaleFactor() / viewScaleFactor(); -} - -double WebPage::viewScaleFactor() const -{ - return m_page->viewScaleFactor(); -} - -void WebPage::scaleView(double scale) -{ - if (viewScaleFactor() == scale) - return; - - float pageScale = pageScaleFactor(); - - IntPoint scrollPositionAtNewScale; - if (FrameView* mainFrameView = m_page->mainFrame().view()) { - double scaleRatio = scale / viewScaleFactor(); - scrollPositionAtNewScale = mainFrameView->scrollPosition(); - scrollPositionAtNewScale.scale(scaleRatio, scaleRatio); - } - - m_page->setViewScaleFactor(scale); - scalePage(pageScale, scrollPositionAtNewScale); -} - void WebPage::setDeviceScaleFactor(float scaleFactor) { if (scaleFactor == m_page->deviceScaleFactor()) @@ -1545,7 +1279,7 @@ void WebPage::setDeviceScaleFactor(float scaleFactor) m_page->setDeviceScaleFactor(scaleFactor); // Tell all our plug-in views that the device scale factor changed. -#if PLATFORM(MAC) +#if PLATFORM(MAC) && !PLATFORM(IOS) for (auto* pluginView : m_pluginViews) pluginView->setDeviceScaleFactor(scaleFactor); @@ -1558,10 +1292,8 @@ void WebPage::setDeviceScaleFactor(float scaleFactor) m_findController.deviceScaleFactorDidChange(); } -#if USE(COORDINATED_GRAPHICS) || USE(TEXTURE_MAPPER) if (m_drawingArea->layerTreeHost()) m_drawingArea->layerTreeHost()->deviceOrPageScaleFactorChanged(); -#endif } float WebPage::deviceScaleFactor() const @@ -1576,9 +1308,7 @@ void WebPage::setUseFixedLayout(bool fixed) return; m_useFixedLayout = fixed; -#if !PLATFORM(IOS) m_page->settings().setFixedElementsLayoutRelativeToFrame(fixed); -#endif #if USE(COORDINATED_GRAPHICS) m_page->settings().setAcceleratedCompositingForFixedPositionEnabled(fixed); m_page->settings().setFixedPositionCreatesStackingContext(fixed); @@ -1586,7 +1316,7 @@ void WebPage::setUseFixedLayout(bool fixed) m_page->settings().setScrollingCoordinatorEnabled(fixed); #endif -#if USE(COORDINATED_GRAPHICS) && ENABLE(SMOOTH_SCROLLING) +#if USE(TILED_BACKING_STORE) && ENABLE(SMOOTH_SCROLLING) // Delegated scrolling will be enabled when the FrameView is created if fixed layout is enabled. // Ensure we don't do animated scrolling in the WebProcess in that case. m_page->settings().setScrollAnimatorEnabled(!fixed); @@ -1596,15 +1326,13 @@ void WebPage::setUseFixedLayout(bool fixed) if (!view) return; -#if USE(COORDINATED_GRAPHICS) +#if USE(TILED_BACKING_STORE) view->setDelegatesScrolling(fixed); view->setPaintsEntireContents(fixed); #endif view->setUseFixedLayout(fixed); if (!fixed) setFixedLayoutSize(IntSize()); - - send(Messages::WebPageProxy::UseFixedLayoutDidChange(fixed)); } void WebPage::setFixedLayoutSize(const IntSize& size) @@ -1614,16 +1342,9 @@ void WebPage::setFixedLayoutSize(const IntSize& size) return; view->setFixedLayoutSize(size); - - send(Messages::WebPageProxy::FixedLayoutSizeDidChange(size)); -} - -IntSize WebPage::fixedLayoutSize() const -{ - FrameView* view = mainFrameView(); - if (!view) - return IntSize(); - return view->fixedLayoutSize(); + // Do not force it until the first layout, this would then become our first layout prematurely. + if (view->didFirstLayout()) + view->forceLayout(); } void WebPage::listenForLayoutMilestones(uint32_t milestones) @@ -1637,16 +1358,6 @@ void WebPage::setSuppressScrollbarAnimations(bool suppressAnimations) { m_page->setShouldSuppressScrollbarAnimations(suppressAnimations); } - -void WebPage::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding) -{ - m_page->setVerticalScrollElasticity(enableVerticalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone); -} - -void WebPage::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding) -{ - m_page->setHorizontalScrollElasticity(enableHorizontalRubberBanding ? ScrollElasticityAllowed : ScrollElasticityNone); -} void WebPage::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage) { @@ -1682,19 +1393,51 @@ void WebPage::setGapBetweenPages(double gap) m_page->setPagination(pagination); } -void WebPage::setPaginationLineGridEnabled(bool lineGridEnabled) +void WebPage::postInjectedBundleMessage(const String& messageName, IPC::MessageDecoder& decoder) { - m_page->setPaginationLineGridEnabled(lineGridEnabled); + InjectedBundle* injectedBundle = WebProcess::shared().injectedBundle(); + if (!injectedBundle) + return; + + RefPtr<API::Object> messageBody; + InjectedBundleUserMessageDecoder messageBodyDecoder(messageBody); + if (!decoder.decode(messageBodyDecoder)) + return; + + injectedBundle->didReceiveMessageToPage(this, messageName, messageBody.get()); } -void WebPage::postInjectedBundleMessage(const String& messageName, const UserData& userData) +void WebPage::installPageOverlay(PassRefPtr<PageOverlay> pageOverlay, bool shouldFadeIn) { - auto& webProcess = WebProcess::singleton(); - InjectedBundle* injectedBundle = webProcess.injectedBundle(); - if (!injectedBundle) + RefPtr<PageOverlay> overlay = pageOverlay; + + if (m_pageOverlays.contains(overlay.get())) + return; + + m_pageOverlays.append(overlay); + overlay->setPage(this); + + if (shouldFadeIn) + overlay->startFadeInAnimation(); + + m_drawingArea->didInstallPageOverlay(overlay.get()); +} + +void WebPage::uninstallPageOverlay(PageOverlay* pageOverlay, bool shouldFadeOut) +{ + size_t existingOverlayIndex = m_pageOverlays.find(pageOverlay); + if (existingOverlayIndex == notFound) + return; + + if (shouldFadeOut) { + pageOverlay->startFadeOutAnimation(); return; + } - injectedBundle->didReceiveMessageToPage(this, messageName, webProcess.transformHandlesToObjects(userData.object()).get()); + pageOverlay->setPage(0); + m_pageOverlays.remove(existingOverlayIndex); + + m_drawingArea->didUninstallPageOverlay(pageOverlay); } #if !PLATFORM(IOS) @@ -1747,78 +1490,30 @@ void WebPage::showPageBanners() } #endif // !PLATFORM(IOS) -void WebPage::takeSnapshot(IntRect snapshotRect, IntSize bitmapSize, uint32_t options, uint64_t callbackID) -{ - SnapshotOptions snapshotOptions = static_cast<SnapshotOptions>(options); - snapshotOptions |= SnapshotOptionsShareable; - - RefPtr<WebImage> image = snapshotAtSize(snapshotRect, bitmapSize, snapshotOptions); - - ShareableBitmap::Handle handle; - if (image) - image->bitmap()->createHandle(handle, SharedMemory::Protection::ReadOnly); - - send(Messages::WebPageProxy::ImageCallback(handle, callbackID)); -} - -PassRefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double additionalScaleFactor, SnapshotOptions options) -{ - IntRect snapshotRect = rect; - IntSize bitmapSize = snapshotRect.size(); - if (options & SnapshotOptionsPrinting) { - ASSERT(additionalScaleFactor == 1); - Frame* coreFrame = m_mainFrame->coreFrame(); - if (!coreFrame) - return nullptr; - bitmapSize.setHeight(PrintContext::numberOfPages(*coreFrame, bitmapSize) * (bitmapSize.height() + 1) - 1); - } else { - double scaleFactor = additionalScaleFactor; - if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) - scaleFactor *= corePage()->deviceScaleFactor(); - bitmapSize.scale(scaleFactor); - } - - return snapshotAtSize(rect, bitmapSize, options); -} - -PassRefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& bitmapSize, SnapshotOptions options) +PassRefPtr<WebImage> WebPage::scaledSnapshotWithOptions(const IntRect& rect, double scaleFactor, SnapshotOptions options) { Frame* coreFrame = m_mainFrame->coreFrame(); if (!coreFrame) - return nullptr; + return 0; FrameView* frameView = coreFrame->view(); if (!frameView) - return nullptr; + return 0; - IntRect snapshotRect = rect; - float horizontalScaleFactor = static_cast<float>(bitmapSize.width()) / rect.width(); - float verticalScaleFactor = static_cast<float>(bitmapSize.height()) / rect.height(); - float scaleFactor = std::max(horizontalScaleFactor, verticalScaleFactor); + IntSize bitmapSize = rect.size(); + float combinedScaleFactor = scaleFactor * corePage()->deviceScaleFactor(); + bitmapSize.scale(combinedScaleFactor); RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, snapshotOptionsToImageOptions(options)); if (!snapshot->bitmap()) - return nullptr; + return 0; auto graphicsContext = snapshot->bitmap()->createGraphicsContext(); - if (options & SnapshotOptionsPrinting) { - PrintContext::spoolAllPagesWithBoundaries(*coreFrame, *graphicsContext, snapshotRect.size()); - return snapshot.release(); - } - - Color documentBackgroundColor = frameView->documentBackgroundColor(); - Color backgroundColor = (coreFrame->settings().backgroundShouldExtendBeyondPage() && documentBackgroundColor.isValid()) ? documentBackgroundColor : frameView->baseBackgroundColor(); - graphicsContext->fillRect(IntRect(IntPoint(), bitmapSize), backgroundColor); - - if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) { - double deviceScaleFactor = corePage()->deviceScaleFactor(); - graphicsContext->applyDeviceScaleFactor(deviceScaleFactor); - scaleFactor /= deviceScaleFactor; - } + graphicsContext->clearRect(IntRect(IntPoint(), bitmapSize)); - graphicsContext->scale(FloatSize(scaleFactor, scaleFactor)); - graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y()); + graphicsContext->applyDeviceScaleFactor(combinedScaleFactor); + graphicsContext->translate(-rect.x(), -rect.y()); FrameView::SelectionInSnapshot shouldPaintSelection = FrameView::IncludeSelection; if (options & SnapshotOptionsExcludeSelectionHighlighting) @@ -1828,98 +1523,28 @@ PassRefPtr<WebImage> WebPage::snapshotAtSize(const IntRect& rect, const IntSize& if (options & SnapshotOptionsInViewCoordinates) coordinateSpace = FrameView::ViewCoordinates; - frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, shouldPaintSelection, coordinateSpace); + frameView->paintContentsForSnapshot(graphicsContext.get(), rect, shouldPaintSelection, coordinateSpace); if (options & SnapshotOptionsPaintSelectionRectangle) { - FloatRect selectionRectangle = m_mainFrame->coreFrame()->selection().selectionBounds(); - graphicsContext->setStrokeColor(Color(0xFF, 0, 0)); + FloatRect selectionRectangle = m_mainFrame->coreFrame()->selection().bounds(); + graphicsContext->setStrokeColor(Color(0xFF, 0, 0), ColorSpaceDeviceRGB); graphicsContext->strokeRect(selectionRectangle, 1); } - - return snapshot.release(); -} - -PassRefPtr<WebImage> WebPage::snapshotNode(WebCore::Node& node, SnapshotOptions options, unsigned maximumPixelCount) -{ - Frame* coreFrame = m_mainFrame->coreFrame(); - if (!coreFrame) - return nullptr; - - FrameView* frameView = coreFrame->view(); - if (!frameView) - return nullptr; - - if (!node.renderer()) - return nullptr; - - LayoutRect topLevelRect; - IntRect snapshotRect = snappedIntRect(node.renderer()->paintingRootRect(topLevelRect)); - if (snapshotRect.isEmpty()) - return nullptr; - - double scaleFactor = 1; - IntSize snapshotSize = snapshotRect.size(); - unsigned maximumHeight = maximumPixelCount / snapshotSize.width(); - if (maximumHeight < static_cast<unsigned>(snapshotSize.height())) { - scaleFactor = static_cast<double>(maximumHeight) / snapshotSize.height(); - snapshotSize = IntSize(snapshotSize.width() * scaleFactor, maximumHeight); - } - - RefPtr<WebImage> snapshot = WebImage::create(snapshotSize, snapshotOptionsToImageOptions(options)); - if (!snapshot->bitmap()) - return nullptr; - - auto graphicsContext = snapshot->bitmap()->createGraphicsContext(); - - if (!(options & SnapshotOptionsExcludeDeviceScaleFactor)) { - double deviceScaleFactor = corePage()->deviceScaleFactor(); - graphicsContext->applyDeviceScaleFactor(deviceScaleFactor); - scaleFactor /= deviceScaleFactor; - } - - graphicsContext->scale(FloatSize(scaleFactor, scaleFactor)); - graphicsContext->translate(-snapshotRect.x(), -snapshotRect.y()); - - Color savedBackgroundColor = frameView->baseBackgroundColor(); - frameView->setBaseBackgroundColor(Color::transparent); - frameView->setNodeToDraw(&node); - - frameView->paintContentsForSnapshot(*graphicsContext, snapshotRect, FrameView::ExcludeSelection, FrameView::DocumentCoordinates); - - frameView->setBaseBackgroundColor(savedBackgroundColor); - frameView->setNodeToDraw(nullptr); return snapshot.release(); } void WebPage::pageDidScroll() { -#if PLATFORM(IOS) - if (!m_inDynamicSizeUpdate) - m_dynamicSizeUpdateHistory.clear(); -#endif - m_uiClient->pageDidScroll(this); - - m_pageScrolledHysteresis.impulse(); + m_uiClient.pageDidScroll(this); send(Messages::WebPageProxy::PageDidScroll()); } -void WebPage::pageStoppedScrolling() -{ - // Maintain the current history item's scroll position up-to-date. - if (Frame* frame = m_mainFrame->coreFrame()) - frame->loader().history().saveScrollPositionAndViewStateToItem(frame->loader().history().currentItem()); -} - -#if USE(COORDINATED_GRAPHICS) +#if USE(TILED_BACKING_STORE) void WebPage::pageDidRequestScroll(const IntPoint& point) { -#if USE(COORDINATED_GRAPHICS_THREADED) - drawingArea()->scroll(IntRect(point, IntSize()), IntSize()); -#elif USE(COORDINATED_GRAPHICS_MULTIPROCESS) send(Messages::WebPageProxy::PageDidRequestScroll(point)); -#endif } #endif @@ -1936,8 +1561,8 @@ WebContextMenu* WebPage::contextMenuAtPointInWindow(const IntPoint& point) corePage()->contextMenuController().clearContextMenu(); // Simulate a mouse click to generate the correct menu. - PlatformMouseEvent mouseEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime(), WebCore::ForceAtClick); - bool handled = corePage()->userInputBridge().handleContextMenuEvent(mouseEvent, &corePage()->mainFrame()); + PlatformMouseEvent mouseEvent(point, point, RightButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime()); + bool handled = corePage()->mainFrame().eventHandler().sendContextMenuEvent(mouseEvent); if (!handled) return 0; @@ -1957,24 +1582,6 @@ const WebEvent* WebPage::currentEvent() return g_currentEvent; } -void WebPage::setLayerTreeStateIsFrozen(bool frozen) -{ - auto* drawingArea = this->drawingArea(); - if (!drawingArea) - return; - - drawingArea->setLayerTreeStateIsFrozen(frozen); -} - -bool WebPage::markLayersVolatileImmediatelyIfPossible() -{ - auto* drawingArea = this->drawingArea(); - if (!drawingArea) - return true; - - return drawingArea->markLayersVolatileImmediatelyIfPossible(); -} - class CurrentEvent { public: explicit CurrentEvent(const WebEvent& event) @@ -1995,11 +1602,16 @@ private: #if ENABLE(CONTEXT_MENUS) static bool isContextClick(const PlatformMouseEvent& event) { -#if PLATFORM(COCOA) - return WebEventFactory::shouldBeHandledAsContextClick(event); -#else - return event.button() == WebCore::RightButton; + if (event.button() == WebCore::RightButton) + return true; + +#if PLATFORM(MAC) + // FIXME: this really should be about OSX-style UI, not about the Mac port + if (event.button() == WebCore::LeftButton && event.ctrlKey()) + return true; #endif + + return false; } static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page) @@ -2010,8 +1622,8 @@ static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, Frame* frame = &page->corePage()->mainFrame(); if (result.innerNonSharedNode()) frame = result.innerNonSharedNode()->document().frame(); - - bool handled = page->corePage()->userInputBridge().handleContextMenuEvent(platformMouseEvent, frame); + + bool handled = frame->eventHandler().sendContextMenuEvent(platformMouseEvent); if (handled) page->contextMenu()->show(); @@ -2034,7 +1646,7 @@ static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, boo page->corePage()->contextMenuController().clearContextMenu(); #endif - bool handled = page->corePage()->userInputBridge().handleMousePressEvent(platformMouseEvent); + bool handled = frame.eventHandler().handleMousePressEvent(platformMouseEvent); #if ENABLE(CONTEXT_MENUS) if (isContextClick(platformMouseEvent)) handled = handleContextMenuEvent(platformMouseEvent, page); @@ -2042,18 +1654,12 @@ static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, boo return handled; } case PlatformEvent::MouseReleased: - return page->corePage()->userInputBridge().handleMouseReleaseEvent(platformMouseEvent); + return frame.eventHandler().handleMouseReleaseEvent(platformMouseEvent); case PlatformEvent::MouseMoved: if (onlyUpdateScrollbars) - return page->corePage()->userInputBridge().handleMouseMoveOnScrollbarEvent(platformMouseEvent); - return page->corePage()->userInputBridge().handleMouseMoveEvent(platformMouseEvent); - - case PlatformEvent::MouseForceChanged: - case PlatformEvent::MouseForceDown: - case PlatformEvent::MouseForceUp: - return page->corePage()->userInputBridge().handleMouseForceEvent(platformMouseEvent); - + return frame.eventHandler().passMouseMovedEventToScrollbars(platformMouseEvent); + return frame.eventHandler().mouseMoved(platformMouseEvent); default: ASSERT_NOT_REACHED(); return false; @@ -2062,26 +1668,21 @@ static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, boo void WebPage::mouseEvent(const WebMouseEvent& mouseEvent) { - m_page->pageThrottler().didReceiveUserInput(); - - bool shouldHandleEvent = true; - #if ENABLE(CONTEXT_MENUS) // Don't try to handle any pending mouse events if a context menu is showing. - if (m_isShowingContextMenu) - shouldHandleEvent = false; -#endif -#if ENABLE(DRAG_SUPPORT) - if (m_isStartingDrag) - shouldHandleEvent = false; -#endif - - if (!shouldHandleEvent) { + if (m_isShowingContextMenu) { send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false)); return; } - +#endif bool handled = false; + if (m_pageOverlays.size()) { + // Let the page overlay handle the event. + PageOverlayList::reverse_iterator end = m_pageOverlays.rend(); + for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it) + if ((handled = (*it)->mouseEvent(mouseEvent))) + break; + } #if !PLATFORM(IOS) if (!handled && m_headerBanner) @@ -2105,6 +1706,36 @@ void WebPage::mouseEvent(const WebMouseEvent& mouseEvent) send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled)); } +void WebPage::mouseEventSyncForTesting(const WebMouseEvent& mouseEvent, bool& handled) +{ + handled = false; + + if (m_pageOverlays.size()) { + PageOverlayList::reverse_iterator end = m_pageOverlays.rend(); + for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it) + if ((handled = (*it)->mouseEvent(mouseEvent))) + break; + } +#if !PLATFORM(IOS) + if (!handled && m_headerBanner) + handled = m_headerBanner->mouseEvent(mouseEvent); + if (!handled && m_footerBanner) + handled = m_footerBanner->mouseEvent(mouseEvent); +#endif // !PLATFORM(IOS) + + if (!handled) { + CurrentEvent currentEvent(mouseEvent); + + // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse + // button is currently pressed. It is possible that neither of those things will be true since on + // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one + // of those cases where the page is not active and the mouse is not pressed, then we can fire a more + // efficient scrollbars-only version of the event. + bool onlyUpdateScrollbars = !(m_page->focusController().isActive() || (mouseEvent.button() != WebMouseEvent::NoButton)); + handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars); + } +} + static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page) { Frame& frame = page->mainFrame(); @@ -2112,13 +1743,11 @@ static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page) return false; PlatformWheelEvent platformWheelEvent = platform(wheelEvent); - return page->userInputBridge().handleWheelEvent(platformWheelEvent); + return frame.eventHandler().handleWheelEvent(platformWheelEvent); } void WebPage::wheelEvent(const WebWheelEvent& wheelEvent) { - m_page->pageThrottler().didReceiveUserInput(); - bool handled = false; if (canHandleUserEvents()) { @@ -2129,20 +1758,25 @@ void WebPage::wheelEvent(const WebWheelEvent& wheelEvent) send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled)); } +void WebPage::wheelEventSyncForTesting(const WebWheelEvent& wheelEvent, bool& handled) +{ + CurrentEvent currentEvent(wheelEvent); + + handled = handleWheelEvent(wheelEvent, m_page.get()); +} + static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page) { if (!page->mainFrame().view()) return false; if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey()) - return page->userInputBridge().handleAccessKeyEvent(platform(keyboardEvent)); - return page->userInputBridge().handleKeyEvent(platform(keyboardEvent)); + return page->focusController().focusedOrMainFrame().eventHandler().handleAccessKey(platform(keyboardEvent)); + return page->focusController().focusedOrMainFrame().eventHandler().keyEvent(platform(keyboardEvent)); } void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent) { - m_page->pageThrottler().didReceiveUserInput(); - bool handled = false; if (canHandleUserEvents()) { @@ -2156,6 +1790,44 @@ void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent) send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled)); } +void WebPage::keyEventSyncForTesting(const WebKeyboardEvent& keyboardEvent, bool& handled) +{ + CurrentEvent currentEvent(keyboardEvent); + + Frame& frame = m_page->focusController().focusedOrMainFrame(); + frame.document()->updateStyleIfNeeded(); + + handled = handleKeyEvent(keyboardEvent, m_page.get()); + if (!handled) + handled = performDefaultBehaviorForKeyEvent(keyboardEvent); +} + +WKTypeRef WebPage::pageOverlayCopyAccessibilityAttributeValue(WKStringRef attribute, WKTypeRef parameter) +{ + if (!m_pageOverlays.size()) + return 0; + PageOverlayList::reverse_iterator end = m_pageOverlays.rend(); + for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it) { + WKTypeRef value = (*it)->copyAccessibilityAttributeValue(attribute, parameter); + if (value) + return value; + } + return 0; +} + +WKArrayRef WebPage::pageOverlayCopyAccessibilityAttributesNames(bool parameterizedNames) +{ + if (!m_pageOverlays.size()) + return 0; + PageOverlayList::reverse_iterator end = m_pageOverlays.rend(); + for (PageOverlayList::reverse_iterator it = m_pageOverlays.rbegin(); it != end; ++it) { + WKArrayRef value = (*it)->copyAccessibilityAttributeNames(parameterizedNames); + if (value) + return value; + } + return 0; +} + void WebPage::validateCommand(const String& commandName, uint64_t callbackID) { bool isEnabled = false; @@ -2172,23 +1844,39 @@ void WebPage::validateCommand(const String& commandName, uint64_t callbackID) send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID)); } -void WebPage::executeEditCommand(const String& commandName, const String& argument) +void WebPage::executeEditCommand(const String& commandName) { - executeEditingCommand(commandName, argument); + executeEditingCommand(commandName, String()); } -void WebPage::restoreSessionInternal(const Vector<BackForwardListItemState>& itemStates, WasRestoredByAPIRequest restoredByAPIRequest) +uint64_t WebPage::restoreSession(const SessionState& sessionState) { - for (const auto& itemState : itemStates) { - auto historyItem = toHistoryItem(itemState.pageState); - historyItem->setWasRestoredFromSession(restoredByAPIRequest == WasRestoredByAPIRequest::Yes); - WebBackForwardListProxy::addItemFromUIProcess(itemState.identifier, WTFMove(historyItem), m_pageID); - } + const BackForwardListItemVector& list = sessionState.list(); + size_t size = list.size(); + uint64_t currentItemID = 0; + for (size_t i = 0; i < size; ++i) { + WebBackForwardListItem* webItem = list[i].get(); + DecoderAdapter decoder(webItem->backForwardData().data(), webItem->backForwardData().size()); + + RefPtr<HistoryItem> item = HistoryItem::decodeBackForwardTree(webItem->url(), webItem->title(), webItem->originalURL(), decoder); + if (!item) { + LOG_ERROR("Failed to decode a HistoryItem from session state data."); + return 0; + } + + if (i == sessionState.currentIndex()) + currentItemID = webItem->itemID(); + + WebBackForwardListProxy::addItemFromUIProcess(list[i]->itemID(), item.release()); + } + ASSERT(currentItemID); + return currentItemID; } -void WebPage::restoreSession(const Vector<BackForwardListItemState>& itemStates) +void WebPage::restoreSessionAndNavigateToCurrentItem(const SessionState& sessionState) { - restoreSessionInternal(itemStates, WasRestoredByAPIRequest::Yes); + if (uint64_t currentItemID = restoreSession(sessionState)) + goToBackForwardItem(currentItemID); } #if ENABLE(TOUCH_EVENTS) @@ -2199,33 +1887,11 @@ static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page) return page->mainFrame().eventHandler().handleTouchEvent(platform(touchEvent)); } -#endif -#if ENABLE(IOS_TOUCH_EVENTS) -void WebPage::dispatchTouchEvent(const WebTouchEvent& touchEvent, bool& handled) -{ - m_userIsInteracting = true; - - m_lastInteractionLocation = touchEvent.position(); - CurrentEvent currentEvent(touchEvent); - handled = handleTouchEvent(touchEvent, m_page.get()); - - m_userIsInteracting = false; -} - -void WebPage::touchEventSync(const WebTouchEvent& touchEvent, bool& handled) -{ - EventDispatcher::TouchEventQueue queuedEvents; - WebProcess::singleton().eventDispatcher().getQueuedTouchEventsForPage(*this, queuedEvents); - dispatchAsynchronousTouchEvents(queuedEvents); - - dispatchTouchEvent(touchEvent, handled); -} -#elif ENABLE(TOUCH_EVENTS) void WebPage::touchEvent(const WebTouchEvent& touchEvent) { - bool handled = false; + if (canHandleUserEvents()) { CurrentEvent currentEvent(touchEvent); @@ -2233,37 +1899,22 @@ void WebPage::touchEvent(const WebTouchEvent& touchEvent) } send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled)); } -#endif -#if ENABLE(MAC_GESTURE_EVENTS) -static bool handleGestureEvent(const WebGestureEvent& event, Page* page) +void WebPage::touchEventSyncForTesting(const WebTouchEvent& touchEvent, bool& handled) { - if (!page->mainFrame().view()) - return false; - - return page->mainFrame().eventHandler().handleGestureEvent(platform(event)); -} - -void WebPage::gestureEvent(const WebGestureEvent& gestureEvent) -{ - bool handled = false; - if (canHandleUserEvents()) { - CurrentEvent currentEvent(gestureEvent); - handled = handleGestureEvent(gestureEvent, m_page.get()); - } - send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled)); + CurrentEvent currentEvent(touchEvent); + handled = handleTouchEvent(touchEvent, m_page.get()); } - #endif bool WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity) { - return page->userInputBridge().scrollRecursively(direction, granularity); + return page->focusController().focusedOrMainFrame().eventHandler().scrollRecursively(direction, granularity); } bool WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity) { - return page->userInputBridge().logicalScrollRecursively(direction, granularity); + return page->focusController().focusedOrMainFrame().eventHandler().logicalScrollRecursively(direction, granularity); } bool WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity) @@ -2278,17 +1929,17 @@ void WebPage::centerSelectionInVisibleArea() m_findController.showFindIndicatorInSelection(); } -#if ENABLE(REMOTE_INSPECTOR) -void WebPage::setAllowsRemoteInspection(bool allow) +void WebPage::setActive(bool isActive) { - m_page->setRemoteInspectionAllowed(allow); + m_page->focusController().setActive(isActive); } -void WebPage::setRemoteInspectionNameOverride(const String& name) +void WebPage::setViewIsVisible(bool isVisible) { - m_page->setRemoteInspectionNameOverride(name); + corePage()->focusController().setContentIsVisible(isVisible); + + m_page->setIsVisible(m_viewState & ViewState::IsVisible, false); } -#endif void WebPage::setDrawsBackground(bool drawsBackground) { @@ -2306,15 +1957,21 @@ void WebPage::setDrawsBackground(bool drawsBackground) m_drawingArea->setNeedsDisplay(); } -void WebPage::setTopContentInset(float contentInset) +void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground) { - if (contentInset == m_page->topContentInset()) + if (m_drawsTransparentBackground == drawsTransparentBackground) return; - m_page->setTopContentInset(contentInset); + m_drawsTransparentBackground = drawsTransparentBackground; - for (auto* pluginView : m_pluginViews) - pluginView->topContentInsetDidChange(); + Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white; + for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) { + if (FrameView* view = coreFrame->view()) + view->setBaseBackgroundColor(backgroundColor); + } + + m_drawingArea->pageBackgroundTransparencyChanged(); + m_drawingArea->setNeedsDisplay(); } void WebPage::viewWillStartLiveResize() @@ -2339,29 +1996,41 @@ void WebPage::viewWillEndLiveResize() view->willEndLiveResize(); } -void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event, uint64_t callbackID) +void WebPage::setFocused(bool isFocused) +{ + m_page->focusController().setFocused(isFocused); +} + +void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event) { if (!m_page) return; -#if PLATFORM(IOS) - TemporaryChange<bool> userIsInteractingChange { m_userIsInteracting, true }; -#endif - Frame& frame = m_page->focusController().focusedOrMainFrame(); frame.document()->setFocusedElement(0); if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) { PlatformKeyboardEvent platformEvent(platform(event)); platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown); - m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, &KeyboardEvent::create(platformEvent, frame.document()->defaultView()).get()); - - send(Messages::WebPageProxy::VoidCallback(callbackID)); + m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, KeyboardEvent::create(platformEvent, frame.document()->defaultView()).get()); return; } m_page->focusController().setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0); - send(Messages::WebPageProxy::VoidCallback(callbackID)); +} + +void WebPage::setWindowResizerSize(const IntSize& windowResizerSize) +{ + if (m_windowResizerSize == windowResizerSize) + return; + + m_windowResizerSize = windowResizerSize; + + for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree().traverseNext()) { + FrameView* view = coreFrame->view(); + if (view) + view->windowResizerRectChanged(); + } } void WebPage::setCanStartMediaTimerFired() @@ -2370,26 +2039,32 @@ void WebPage::setCanStartMediaTimerFired() m_page->setCanStartMedia(true); } +#if !PLATFORM(MAC) || PLATFORM(IOS) +void WebPage::didUpdateViewStateTimerFired() +{ + send(Messages::WebPageProxy::DidUpdateViewState()); +} +#endif + inline bool WebPage::canHandleUserEvents() const { -#if USE(COORDINATED_GRAPHICS) +#if USE(TILED_BACKING_STORE) // Should apply only if the area was frozen by didStartPageTransition(). return !m_drawingArea->layerTreeStateIsFrozen(); #endif return true; } -void WebPage::updateIsInWindow(bool isInitialState) +void WebPage::setIsInWindow(bool isInWindow) { - bool isInWindow = m_viewState & WebCore::ViewState::IsInWindow; - + bool pageWasInWindow = m_page->isInWindow(); + if (!isInWindow) { m_setCanStartMediaTimer.stop(); m_page->setCanStartMedia(false); - // The WebProcess does not yet know about this page; no need to tell it we're leaving the window. - if (!isInitialState) - WebProcess::singleton().pageWillLeaveWindow(m_pageID); + if (pageWasInWindow) + WebProcess::shared().pageWillLeaveWindow(m_pageID); } else { // Defer the call to Page::setCanStartMedia() since it ends up sending a synchronous message to the UI process // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing @@ -2397,29 +2072,48 @@ void WebPage::updateIsInWindow(bool isInitialState) if (m_mayStartMediaWhenInWindow) m_setCanStartMediaTimer.startOneShot(0); - WebProcess::singleton().pageDidEnterWindow(m_pageID); + if (!pageWasInWindow) + WebProcess::shared().pageDidEnterWindow(m_pageID); } + m_page->setIsInWindow(isInWindow); + if (isInWindow) layoutIfNeeded(); } -void WebPage::setViewState(ViewState::Flags viewState, bool wantsDidUpdateViewState, const Vector<uint64_t>& callbackIDs) +void WebPage::setViewState(ViewState::Flags viewState, bool wantsDidUpdateViewState) +{ + setViewStateInternal(viewState, false); + + if (wantsDidUpdateViewState) + m_sendDidUpdateViewStateTimer.startOneShot(0); +} + +void WebPage::setViewStateInternal(ViewState::Flags viewState, bool isInitialState) { ViewState::Flags changed = m_viewState ^ viewState; m_viewState = viewState; - if (changed) - updateUserActivity(); + m_drawingArea->viewStateDidChange(changed); + + // We want to make sure to update the active state while hidden, so if the view is hidden then update the active state + // early (in case it becomes visible), and if the view was visible then update active state later (in case it hides). + if (changed & ViewState::IsFocused) + setFocused(viewState & ViewState::IsFocused); + if (changed & ViewState::WindowIsActive && !(m_viewState & ViewState::IsVisible)) + setActive(viewState & ViewState::WindowIsActive); + if (changed & ViewState::IsVisible) + setViewIsVisible(viewState & ViewState::IsVisible); + if (changed & ViewState::WindowIsActive && m_viewState & ViewState::IsVisible) + setActive(viewState & ViewState::WindowIsActive); + if (changed & ViewState::IsInWindow) + setIsInWindow(viewState & ViewState::IsInWindow); + if (changed & ViewState::IsVisuallyIdle) + setIsVisuallyIdle(viewState & ViewState::IsVisuallyIdle); - m_page->setViewState(viewState); for (auto* pluginView : m_pluginViews) pluginView->viewStateDidChange(changed); - - m_drawingArea->viewStateDidChange(changed, wantsDidUpdateViewState, callbackIDs); - - if (changed & ViewState::IsInWindow) - updateIsInWindow(); } void WebPage::setLayerHostingMode(unsigned layerHostingMode) @@ -2432,37 +2126,34 @@ void WebPage::setLayerHostingMode(unsigned layerHostingMode) pluginView->setLayerHostingMode(m_layerHostingMode); } -void WebPage::setSessionID(SessionID sessionID) +uint64_t WebPage::sessionID() const { - if (sessionID.isEphemeral()) - WebProcess::singleton().ensurePrivateBrowsingSession(sessionID); - m_page->setSessionID(sessionID); + if (m_sessionID) + return m_sessionID; + + return m_page->settings().privateBrowsingEnabled() ? SessionTracker::legacyPrivateSessionID : SessionTracker::defaultSessionID; } -void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t navigationID, DownloadID downloadID) +void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID) { - WebFrame* frame = WebProcess::singleton().webFrame(frameID); + WebFrame* frame = WebProcess::shared().webFrame(frameID); if (!frame) return; - frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), navigationID, downloadID); + frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), downloadID); } void WebPage::didStartPageTransition() { m_drawingArea->setLayerTreeStateIsFrozen(true); -#if PLATFORM(IOS) - m_hasFocusedDueToUserInteraction = false; -#endif } void WebPage::didCompletePageTransition() { -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) - // m_mainFrame can be null since r170163. - if (m_mainFrame && m_mainFrame->coreFrame()->view()->delegatesScrolling()) { +#if USE(TILED_BACKING_STORE) + if (m_mainFrame->coreFrame()->view()->delegatesScrolling()) // Wait until the UI process sent us the visible rect it wants rendered. send(Messages::WebPageProxy::PageTransitionViewportReady()); - } else + else #endif m_drawingArea->setLayerTreeStateIsFrozen(false); @@ -2473,29 +2164,19 @@ void WebPage::show() send(Messages::WebPageProxy::ShowPage()); } -String WebPage::userAgent(const URL& webCoreURL) const +void WebPage::setUserAgent(const String& userAgent) { - return userAgent(nullptr, webCoreURL); + m_userAgent = userAgent; } -String WebPage::userAgent(WebFrame* frame, const URL& webcoreURL) const +String WebPage::userAgent(const URL& url) const { - if (frame && m_loaderClient.client().userAgentForURL) { - API::String* apiString = m_loaderClient.userAgentForURL(frame, API::URL::create(webcoreURL).ptr()); - if (apiString) - return apiString->string(); - } - - String userAgent = platformUserAgent(webcoreURL); + String userAgent = platformUserAgent(url); if (!userAgent.isEmpty()) return userAgent; + return m_userAgent; } - -void WebPage::setUserAgent(const String& userAgent) -{ - m_userAgent = userAgent; -} void WebPage::suspendActiveDOMObjectsAndAnimations() { @@ -2507,39 +2188,38 @@ void WebPage::resumeActiveDOMObjectsAndAnimations() m_page->resumeActiveDOMObjectsAndAnimations(); } -IntPoint WebPage::screenToRootView(const IntPoint& point) +IntPoint WebPage::screenToWindow(const IntPoint& point) { IntPoint windowPoint; - sendSync(Messages::WebPageProxy::ScreenToRootView(point), Messages::WebPageProxy::ScreenToRootView::Reply(windowPoint)); + sendSync(Messages::WebPageProxy::ScreenToWindow(point), Messages::WebPageProxy::ScreenToWindow::Reply(windowPoint)); return windowPoint; } -IntRect WebPage::rootViewToScreen(const IntRect& rect) +IntRect WebPage::windowToScreen(const IntRect& rect) { IntRect screenRect; - sendSync(Messages::WebPageProxy::RootViewToScreen(rect), Messages::WebPageProxy::RootViewToScreen::Reply(screenRect)); + sendSync(Messages::WebPageProxy::WindowToScreen(rect), Messages::WebPageProxy::WindowToScreen::Reply(screenRect)); return screenRect; } - -#if PLATFORM(IOS) -IntPoint WebPage::accessibilityScreenToRootView(const IntPoint& point) -{ - IntPoint windowPoint; - sendSync(Messages::WebPageProxy::AccessibilityScreenToRootView(point), Messages::WebPageProxy::AccessibilityScreenToRootView::Reply(windowPoint)); - return windowPoint; -} -IntRect WebPage::rootViewToAccessibilityScreen(const IntRect& rect) +IntRect WebPage::windowResizerRect() const { - IntRect screenRect; - sendSync(Messages::WebPageProxy::RootViewToAccessibilityScreen(rect), Messages::WebPageProxy::RootViewToAccessibilityScreen::Reply(screenRect)); - return screenRect; + if (m_windowResizerSize.isEmpty()) + return IntRect(); + + IntSize frameViewSize; + if (Frame* coreFrame = m_mainFrame->coreFrame()) { + if (FrameView* view = coreFrame->view()) + frameViewSize = view->size(); + } + + return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(), + m_windowResizerSize.width(), m_windowResizerSize.height()); } -#endif KeyboardUIMode WebPage::keyboardUIMode() { - bool fullKeyboardAccessEnabled = WebProcess::singleton().fullKeyboardAccessEnabled(); + bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled(); return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0)); } @@ -2548,20 +2228,18 @@ void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID // NOTE: We need to be careful when running scripts that the objects we depend on don't // disappear during script execution. + // Retain the SerializedScriptValue at this level so it (and the internal data) lives + // long enough for the DataReference to be encoded by the sent message. RefPtr<SerializedScriptValue> serializedResultValue; + IPC::DataReference dataReference; + JSLockHolder lock(JSDOMWindow::commonVM()); - bool hadException = true; - ExceptionDetails details; - if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true, &details).jsValue()) { - hadException = false; - serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(), - toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), nullptr); + if (JSValue resultValue = m_mainFrame->coreFrame()->script().executeScript(script, true).jsValue()) { + if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(), toRef(m_mainFrame->coreFrame()->script().globalObject(mainThreadNormalWorld())->globalExec(), resultValue), 0))) + dataReference = serializedResultValue->data(); } - IPC::DataReference dataReference; - if (serializedResultValue) - dataReference = serializedResultValue->data(); - send(Messages::WebPageProxy::ScriptValueCallback(dataReference, hadException, details, callbackID)); + send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID)); } void WebPage::getContentsAsString(uint64_t callbackID) @@ -2571,14 +2249,17 @@ void WebPage::getContentsAsString(uint64_t callbackID) } #if ENABLE(MHTML) -void WebPage::getContentsAsMHTMLData(uint64_t callbackID) +void WebPage::getContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding) { - RefPtr<SharedBuffer> buffer = MHTMLArchive::generateMHTMLData(m_page.get()); - - // FIXME: Use SharedBufferDataReference. IPC::DataReference dataReference; + + RefPtr<SharedBuffer> buffer = useBinaryEncoding + ? MHTMLArchive::generateMHTMLDataUsingBinaryEncoding(m_page.get()) + : MHTMLArchive::generateMHTMLData(m_page.get()); + if (buffer) dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size()); + send(Messages::WebPageProxy::DataCallback(dataReference, callbackID)); } #endif @@ -2601,17 +2282,20 @@ static Frame* frameWithSelection(Page* page) void WebPage::getSelectionAsWebArchiveData(uint64_t callbackID) { -#if PLATFORM(COCOA) + IPC::DataReference dataReference; + +#if PLATFORM(MAC) + RefPtr<LegacyWebArchive> archive; RetainPtr<CFDataRef> data; - if (Frame* frame = frameWithSelection(m_page.get())) - data = LegacyWebArchive::createFromSelection(frame)->rawDataRepresentation(); -#endif - IPC::DataReference dataReference; -#if PLATFORM(COCOA) - if (data) + Frame* frame = frameWithSelection(m_page.get()); + if (frame) { + archive = LegacyWebArchive::createFromSelection(frame); + data = archive->rawDataRepresentation(); dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get())); + } #endif + send(Messages::WebPageProxy::DataCallback(dataReference, callbackID)); } @@ -2626,7 +2310,7 @@ void WebPage::getSelectionOrContentsAsString(uint64_t callbackID) void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID) { String resultString; - if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) + if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) resultString = frame->source(); send(Messages::WebPageProxy::StringCallback(resultString, callbackID)); @@ -2634,20 +2318,24 @@ void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID) void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID) { - RefPtr<SharedBuffer> buffer; - if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) { - if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame())) - buffer = pluginView->liveResourceData(); - if (!buffer) { - if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader()) - buffer = loader->mainResourceData(); + IPC::DataReference dataReference; + + RefPtr<ResourceBuffer> buffer; + RefPtr<SharedBuffer> pdfResource; + if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) { + if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame())) { + if ((pdfResource = pluginView->liveResourceData())) + dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(pdfResource->data()), pdfResource->size()); + } + + if (dataReference.isEmpty()) { + if (DocumentLoader* loader = frame->coreFrame()->loader().documentLoader()) { + if ((buffer = loader->mainResourceData())) + dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size()); + } } } - // FIXME: Use SharedBufferDataReference. - IPC::DataReference dataReference; - if (buffer) - dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size()); send(Messages::WebPageProxy::DataCallback(dataReference, callbackID)); } @@ -2666,38 +2354,38 @@ static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& re void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID) { + IPC::DataReference dataReference; + URL resourceURL(URL(), resourceURLString); + RefPtr<SharedBuffer> buffer; - if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) { - URL resourceURL(URL(), resourceURLString); + if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) { buffer = resourceDataForFrame(frame->coreFrame(), resourceURL); if (!buffer) { // Try to get the resource data from the cache. buffer = cachedResponseDataForURL(resourceURL); } + + if (buffer) + dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size()); } - // FIXME: Use SharedBufferDataReference. - IPC::DataReference dataReference; - if (buffer) - dataReference = IPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size()); send(Messages::WebPageProxy::DataCallback(dataReference, callbackID)); } void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID) { -#if PLATFORM(COCOA) + IPC::DataReference dataReference; + +#if PLATFORM(MAC) RetainPtr<CFDataRef> data; - if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) - data = frame->webArchiveData(nullptr, nullptr); + if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) { + if ((data = frame->webArchiveData(0, 0))) + dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get())); + } #else UNUSED_PARAM(frameID); #endif - IPC::DataReference dataReference; -#if PLATFORM(COCOA) - if (data) - dataReference = IPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get())); -#endif send(Messages::WebPageProxy::DataCallback(dataReference, callbackID)); } @@ -2732,7 +2420,7 @@ void WebPage::updatePreferences(const WebPreferencesStore& store) m_scrollingPerformanceLoggingEnabled = store.getBoolValueForKey(WebPreferencesKey::scrollingPerformanceLoggingEnabledKey()); -#if PLATFORM(COCOA) +#if PLATFORM(MAC) m_pdfPluginEnabled = store.getBoolValueForKey(WebPreferencesKey::pdfPluginEnabledKey()); #endif @@ -2757,18 +2445,17 @@ void WebPage::updatePreferences(const WebPreferencesStore& store) settings.setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey())); settings.setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey())); settings.setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey())); - if (store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && !usesEphemeralSession()) - setSessionID(SessionID::legacyPrivateSessionID()); - else if (!store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()) && sessionID() == SessionID::legacyPrivateSessionID()) - setSessionID(SessionID::defaultSessionID()); + if (m_sessionID) + settings.setPrivateBrowsingEnabled(SessionTracker::isEphemeralID(m_sessionID)); + else + settings.setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey())); settings.setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey())); - settings.setJavaScriptRuntimeFlags(RuntimeFlags(store.getUInt32ValueForKey(WebPreferencesKey::javaScriptRuntimeFlagsKey()))); + settings.setJavaScriptExperimentsEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptExperimentsEnabledKey())); settings.setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey())); settings.setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey())); settings.setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey())); settings.setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey())); settings.setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey())); - settings.setDOMTimersThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::domTimersThrottlingEnabledKey())); #if ENABLE(WEB_ARCHIVE) settings.setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey())); #endif @@ -2784,10 +2471,15 @@ void WebPage::updatePreferences(const WebPreferencesStore& store) settings.setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey())); settings.setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey())); - settings.setMinimumFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumFontSizeKey())); - settings.setMinimumLogicalFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey())); - settings.setDefaultFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFontSizeKey())); - settings.setDefaultFixedFontSize(store.getDoubleValueForKey(WebPreferencesKey::defaultFixedFontSizeKey())); + settings.setMinimumFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumFontSizeKey())); + settings.setMinimumLogicalFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey())); + settings.setDefaultFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFontSizeKey())); + settings.setDefaultFixedFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFixedFontSizeKey())); + settings.setScreenFontSubstitutionEnabled(store.getBoolValueForKey(WebPreferencesKey::screenFontSubstitutionEnabledKey()) +#if PLATFORM(MAC) + || WebProcess::shared().shouldForceScreenFontSubstitution() +#endif + ); settings.setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey())); settings.setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey())); settings.setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey())); @@ -2795,50 +2487,35 @@ void WebPage::updatePreferences(const WebPreferencesStore& store) settings.setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey())); settings.setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey())); - settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey())); - settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey())); - settings.setDisplayListDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::displayListDrawingEnabledKey())); - settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey())); + settings.setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing()); + settings.setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing()); + settings.setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()) && LayerTreeHost::supportsAcceleratedCompositing()); settings.setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey())); settings.setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey())); settings.setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey())); - settings.setVisibleDebugOverlayRegions(store.getUInt32ValueForKey(WebPreferencesKey::visibleDebugOverlayRegionsKey())); - settings.setUseGiantTiles(store.getBoolValueForKey(WebPreferencesKey::useGiantTilesKey())); - settings.setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey())); - settings.setTemporaryTileCohortRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::temporaryTileCohortRetentionEnabledKey())); -#if ENABLE(CSS_ANIMATIONS_LEVEL_2) - RuntimeEnabledFeatures::sharedFeatures().setAnimationTriggersEnabled(store.getBoolValueForKey(WebPreferencesKey::cssAnimationTriggersEnabledKey())); -#endif -#if ENABLE(WEB_ANIMATIONS) - RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled(store.getBoolValueForKey(WebPreferencesKey::webAnimationsEnabledKey())); -#endif RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey())); RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCompositingEnabledKey())); + settings.setCSSGridLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::cssGridLayoutEnabledKey())); + settings.setRegionBasedColumnsEnabled(store.getBoolValueForKey(WebPreferencesKey::regionBasedColumnsEnabledKey())); settings.setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey())); + settings.setMultithreadedWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::multithreadedWebGLEnabledKey())); settings.setForceSoftwareWebGLRendering(store.getBoolValueForKey(WebPreferencesKey::forceSoftwareWebGLRenderingKey())); settings.setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey())); - settings.setRequiresUserGestureForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForMediaPlaybackKey())); - settings.setAudioPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::requiresUserGestureForAudioPlaybackKey())); - settings.setAllowsInlineMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsInlineMediaPlaybackKey())); - settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute(store.getBoolValueForKey(WebPreferencesKey::inlineMediaPlaybackRequiresPlaysInlineAttributeKey())); - settings.setInvisibleAutoplayNotPermitted(store.getBoolValueForKey(WebPreferencesKey::invisibleAutoplayNotPermittedKey())); - settings.setMediaDataLoadsAutomatically(store.getBoolValueForKey(WebPreferencesKey::mediaDataLoadsAutomaticallyKey())); - settings.setAllowsPictureInPictureMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsPictureInPictureMediaPlaybackKey())); - settings.setMediaControlsScaleWithPageZoom(store.getBoolValueForKey(WebPreferencesKey::mediaControlsScaleWithPageZoomKey())); + settings.setMediaPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackRequiresUserGestureKey())); + settings.setMediaPlaybackAllowsInline(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsInlineKey())); settings.setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey())); settings.setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey())); settings.setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey())); #if ENABLE(SMOOTH_SCROLLING) settings.setScrollAnimatorEnabled(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey())); #endif - settings.setForceUpdateScrollbarsOnMainThreadForPerformanceTesting(store.getBoolValueForKey(WebPreferencesKey::forceUpdateScrollbarsOnMainThreadForPerformanceTestingKey())); settings.setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey())); settings.setSpatialNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::spatialNavigationEnabledKey())); - settings.setHttpEquivEnabled(store.getBoolValueForKey(WebPreferencesKey::httpEquivEnabledKey())); - - DatabaseManager::singleton().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey())); +#if ENABLE(SQL_DATABASE) + DatabaseManager::manager().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey())); +#endif #if ENABLE(FULLSCREEN_API) settings.setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey())); @@ -2846,19 +2523,14 @@ void WebPage::updatePreferences(const WebPreferencesStore& store) #if USE(AVFOUNDATION) settings.setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey())); - settings.setAVFoundationNSURLSessionEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationNSURLSessionEnabledKey())); #endif -#if PLATFORM(COCOA) +#if PLATFORM(MAC) settings.setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey())); #endif -#if PLATFORM(IOS) && HAVE(AVKIT) - settings.setAVKitEnabled(true); -#endif - -#if ENABLE(IOS_TEXT_AUTOSIZING) - settings.setMinimumZoomFontSize(store.getDoubleValueForKey(WebPreferencesKey::minimumZoomFontSizeKey())); +#if USE(PLUGIN_PROXY_FOR_VIDEO) + settings->setVideoPluginProxyEnabled(store.getBoolValueForKey(WebPreferencesKey::isVideoPluginProxyEnabledKey())); #endif #if ENABLE(WEB_AUDIO) @@ -2869,18 +2541,7 @@ void WebPage::updatePreferences(const WebPreferencesStore& store) settings.setMediaStreamEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaStreamEnabledKey())); #endif -#if ENABLE(SERVICE_CONTROLS) - settings.setImageControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::imageControlsEnabledKey())); -#endif - -#if ENABLE(WIRELESS_PLAYBACK_TARGET) - settings.setAllowsAirPlayForMediaPlayback(store.getBoolValueForKey(WebPreferencesKey::allowsAirPlayForMediaPlaybackKey())); -#endif - -#if ENABLE(RESOURCE_USAGE) - settings.setResourceUsageOverlayVisible(store.getBoolValueForKey(WebPreferencesKey::resourceUsageOverlayVisibleKey())); -#endif - + settings.setApplicationChromeMode(store.getBoolValueForKey(WebPreferencesKey::applicationChromeModeKey())); settings.setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey())); settings.setIncrementalRenderingSuppressionTimeoutInSeconds(store.getDoubleValueForKey(WebPreferencesKey::incrementalRenderingSuppressionTimeoutKey())); settings.setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey())); @@ -2925,16 +2586,13 @@ void WebPage::updatePreferences(const WebPreferencesStore& store) #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING) settings.setHiddenPageDOMTimerThrottlingEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageDOMTimerThrottlingEnabledKey())); #endif - +#if ENABLE(PAGE_VISIBILITY_API) settings.setHiddenPageCSSAnimationSuspensionEnabled(store.getBoolValueForKey(WebPreferencesKey::hiddenPageCSSAnimationSuspensionEnabledKey())); +#endif + settings.setLowPowerVideoAudioBufferSizeEnabled(store.getBoolValueForKey(WebPreferencesKey::lowPowerVideoAudioBufferSizeEnabledKey())); settings.setSimpleLineLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutEnabledKey())); settings.setSimpleLineLayoutDebugBordersEnabled(store.getBoolValueForKey(WebPreferencesKey::simpleLineLayoutDebugBordersEnabledKey())); - - settings.setNewBlockInsideInlineModelEnabled(store.getBoolValueForKey(WebPreferencesKey::newBlockInsideInlineModelEnabledKey())); - settings.setAntialiasedFontDilationEnabled(store.getBoolValueForKey(WebPreferencesKey::antialiasedFontDilationEnabledKey())); - - settings.setSubpixelCSSOMElementMetricsEnabled(store.getBoolValueForKey(WebPreferencesKey::subpixelCSSOMElementMetricsEnabledKey())); settings.setUseLegacyTextAlignPositionedElementBehavior(store.getBoolValueForKey(WebPreferencesKey::useLegacyTextAlignPositionedElementBehaviorKey())); @@ -2942,139 +2600,29 @@ void WebPage::updatePreferences(const WebPreferencesStore& store) settings.setMediaSourceEnabled(store.getBoolValueForKey(WebPreferencesKey::mediaSourceEnabledKey())); #endif -#if ENABLE(MEDIA_STREAM) - settings.setMockCaptureDevicesEnabled(store.getBoolValueForKey(WebPreferencesKey::mockCaptureDevicesEnabledKey())); -#endif - - settings.setShouldConvertPositionStyleOnCopy(store.getBoolValueForKey(WebPreferencesKey::shouldConvertPositionStyleOnCopyKey())); - - settings.setStandalone(store.getBoolValueForKey(WebPreferencesKey::standaloneKey())); - settings.setTelephoneNumberParsingEnabled(store.getBoolValueForKey(WebPreferencesKey::telephoneNumberParsingEnabledKey())); - settings.setAllowMultiElementImplicitSubmission(store.getBoolValueForKey(WebPreferencesKey::allowMultiElementImplicitSubmissionKey())); - settings.setAlwaysUseAcceleratedOverflowScroll(store.getBoolValueForKey(WebPreferencesKey::alwaysUseAcceleratedOverflowScrollKey())); - - settings.setPasswordEchoEnabled(store.getBoolValueForKey(WebPreferencesKey::passwordEchoEnabledKey())); - settings.setPasswordEchoDurationInSeconds(store.getDoubleValueForKey(WebPreferencesKey::passwordEchoDurationKey())); - - settings.setLayoutInterval(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>(store.getDoubleValueForKey(WebPreferencesKey::layoutIntervalKey())))); - settings.setMaxParseDuration(store.getDoubleValueForKey(WebPreferencesKey::maxParseDurationKey())); - - settings.setEnableInheritURIQueryComponent(store.getBoolValueForKey(WebPreferencesKey::enableInheritURIQueryComponentKey())); - - settings.setShouldDispatchJavaScriptWindowOnErrorEvents(true); - -#if PLATFORM(IOS) - settings.setUseImageDocumentForSubframePDF(true); -#endif - -#if ENABLE(DATA_DETECTION) - settings.setDataDetectorTypes(static_cast<DataDetectorTypes>(store.getUInt32ValueForKey(WebPreferencesKey::dataDetectorTypesKey()))); -#endif -#if ENABLE(GAMEPAD) - RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled(store.getBoolValueForKey(WebPreferencesKey::gamepadsEnabledKey())); -#endif - -#if ENABLE(SERVICE_CONTROLS) - settings.setServiceControlsEnabled(store.getBoolValueForKey(WebPreferencesKey::serviceControlsEnabledKey())); -#endif - - bool processSuppressionEnabled = store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey()); - if (m_processSuppressionEnabled != processSuppressionEnabled) { - m_processSuppressionEnabled = processSuppressionEnabled; - updateUserActivity(); + if (store.getBoolValueForKey(WebPreferencesKey::pageVisibilityBasedProcessSuppressionEnabledKey())) { + if (m_processSuppressionDisabledByWebPreference.isActive()) + m_processSuppressionDisabledByWebPreference.endActivity(); + } else { + if (!m_processSuppressionDisabledByWebPreference.isActive()) + m_processSuppressionDisabledByWebPreference.beginActivity(); } platformPreferencesDidChange(store); if (m_drawingArea) m_drawingArea->updatePreferences(store); - -#if PLATFORM(IOS) - m_ignoreViewportScalingConstraints = store.getBoolValueForKey(WebPreferencesKey::ignoreViewportScalingConstraintsKey()); - m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints); - m_viewportConfiguration.setForceAlwaysUserScalable(store.getBoolValueForKey(WebPreferencesKey::forceAlwaysUserScalableKey())); -#endif } -#if ENABLE(DATA_DETECTION) -void WebPage::setDataDetectionResults(NSArray *detectionResults) -{ - DataDetectionResult dataDetectionResult; - dataDetectionResult.results = detectionResults; - send(Messages::WebPageProxy::SetDataDetectionResult(dataDetectionResult)); -} -#endif - -#if PLATFORM(COCOA) -void WebPage::willCommitLayerTree(RemoteLayerTreeTransaction& layerTransaction) -{ - layerTransaction.setContentsSize(corePage()->mainFrame().view()->contentsSize()); - layerTransaction.setScrollOrigin(corePage()->mainFrame().view()->scrollOrigin()); - layerTransaction.setPageScaleFactor(corePage()->pageScaleFactor()); - layerTransaction.setRenderTreeSize(corePage()->renderTreeSize()); - layerTransaction.setPageExtendedBackgroundColor(corePage()->pageExtendedBackgroundColor()); -#if PLATFORM(IOS) - layerTransaction.setScaleWasSetByUIProcess(scaleWasSetByUIProcess()); - layerTransaction.setMinimumScaleFactor(m_viewportConfiguration.minimumScale()); - layerTransaction.setMaximumScaleFactor(m_viewportConfiguration.maximumScale()); - layerTransaction.setInitialScaleFactor(m_viewportConfiguration.initialScale()); - layerTransaction.setViewportMetaTagWidth(m_viewportConfiguration.viewportArguments().width); - layerTransaction.setViewportMetaTagWidthWasExplicit(m_viewportConfiguration.viewportArguments().widthWasExplicit); - layerTransaction.setViewportMetaTagCameFromImageDocument(m_viewportConfiguration.viewportArguments().type == ViewportArguments::ImageDocument); - layerTransaction.setAllowsUserScaling(allowsUserScaling()); -#endif -#if PLATFORM(MAC) - layerTransaction.setScrollPosition(corePage()->mainFrame().view()->scrollPosition()); -#endif -} - -void WebPage::didFlushLayerTreeAtTime(std::chrono::milliseconds timestamp) -{ -#if PLATFORM(IOS) - if (m_oldestNonStableUpdateVisibleContentRectsTimestamp != std::chrono::milliseconds::zero()) { - std::chrono::milliseconds elapsed = timestamp - m_oldestNonStableUpdateVisibleContentRectsTimestamp; - m_oldestNonStableUpdateVisibleContentRectsTimestamp = std::chrono::milliseconds::zero(); - - m_estimatedLatency = std::chrono::milliseconds(static_cast<std::chrono::milliseconds::rep>(m_estimatedLatency.count() * 0.80 + elapsed.count() * 0.20)); - } -#else - UNUSED_PARAM(timestamp); -#endif -} -#endif - -WebInspector* WebPage::inspector(LazyCreationPolicy behavior) +#if ENABLE(INSPECTOR) +WebInspector* WebPage::inspector() { if (m_isClosed) - return nullptr; - if (!m_inspector && behavior == LazyCreationPolicy::CreateIfNeeded) - m_inspector = WebInspector::create(this); + return 0; + if (!m_inspector) + m_inspector = WebInspector::create(this, m_inspectorClient); return m_inspector.get(); } - -WebInspectorUI* WebPage::inspectorUI() -{ - if (m_isClosed) - return nullptr; - if (!m_inspectorUI) - m_inspectorUI = WebInspectorUI::create(*this); - return m_inspectorUI.get(); -} - -#if PLATFORM(IOS) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)) -WebVideoFullscreenManager* WebPage::videoFullscreenManager() -{ - if (!m_videoFullscreenManager) - m_videoFullscreenManager = WebVideoFullscreenManager::create(this); - return m_videoFullscreenManager.get(); -} -#endif - -#if PLATFORM(IOS) -void WebPage::setAllowsMediaDocumentInlinePlayback(bool allows) -{ - m_page->setAllowsMediaDocumentInlinePlayback(allows); -} #endif #if ENABLE(FULLSCREEN_API) @@ -3095,7 +2643,7 @@ NotificationPermissionRequestManager* WebPage::notificationPermissionRequestMana return m_notificationPermissionRequestManager.get(); } -#if !PLATFORM(GTK) && !PLATFORM(COCOA) +#if !PLATFORM(GTK) && !PLATFORM(MAC) bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt) { Node* node = evt->target()->toNode(); @@ -3137,29 +2685,27 @@ bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt) void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData) { if (!m_page) { - send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0)); + send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession())); DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData()); data->deref(); return; } switch (action) { - case DragControllerActionEntered: { - DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData); - send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted())); + case DragControllerActionEntered: + send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragEntered(dragData))); break; - } - case DragControllerActionUpdated: { - DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData); - send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted())); + + case DragControllerActionUpdated: + send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragUpdated(dragData))); break; - } + case DragControllerActionExited: m_page->dragController().dragExited(dragData); break; - case DragControllerActionPerformDragOperation: { - m_page->dragController().performDragOperation(dragData); + case DragControllerActionPerformDrag: { + m_page->dragController().performDrag(dragData); break; } @@ -3175,28 +2721,25 @@ void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dra void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const String& dragStorageName, uint32_t flags, const SandboxExtension::Handle& sandboxExtensionHandle, const SandboxExtension::HandleArray& sandboxExtensionsHandleArray) { if (!m_page) { - send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone, false, 0)); + send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession())); return; } DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags)); switch (action) { - case DragControllerActionEntered: { - DragOperation resolvedDragOperation = m_page->dragController().dragEntered(dragData); - send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted())); + case DragControllerActionEntered: + send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragEntered(dragData))); break; - } - case DragControllerActionUpdated: { - DragOperation resolvedDragOperation = m_page->dragController().dragUpdated(dragData); - send(Messages::WebPageProxy::DidPerformDragControllerAction(resolvedDragOperation, m_page->dragController().mouseIsOverFileInput(), m_page->dragController().numberOfItemsToBeAccepted())); + case DragControllerActionUpdated: + send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController().dragUpdated(dragData))); break; - } + case DragControllerActionExited: m_page->dragController().dragExited(dragData); break; - case DragControllerActionPerformDragOperation: { + case DragControllerActionPerformDrag: { ASSERT(!m_pendingDropSandboxExtension); m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle); @@ -3205,7 +2748,7 @@ void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint cli m_pendingDropExtensionsForFileUpload.append(extension); } - m_page->dragController().performDragOperation(dragData); + m_page->dragController().performDrag(dragData); // If we started loading a local file, the sandbox extension tracker would have adopted this // pending drop sandbox extension. If not, we'll play it safe and clear it. @@ -3231,7 +2774,7 @@ void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint glob if (!view) return; // FIXME: These are fake modifier keys here, but they should be real ones instead. - PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime(), 0); + PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime()); m_page->mainFrame().eventHandler().dragSourceEndedAt(event, (DragOperation)operation); } @@ -3354,7 +2897,7 @@ void WebPage::countStringMatches(const String& string, uint32_t options, uint32_ void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex) { changeSelectedIndex(newIndex); - m_activePopupMenu = nullptr; + m_activePopupMenu = 0; } void WebPage::changeSelectedIndex(int32_t index) @@ -3365,47 +2908,24 @@ void WebPage::changeSelectedIndex(int32_t index) m_activePopupMenu->didChangeSelectedIndex(index); } -#if PLATFORM(IOS) -void WebPage::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& files, const String& displayString, const IPC::DataReference& iconData) -{ - if (!m_activeOpenPanelResultListener) - return; - - RefPtr<Icon> icon; - if (!iconData.isEmpty()) { - RetainPtr<CFDataRef> dataRef = adoptCF(CFDataCreate(nullptr, iconData.data(), iconData.size())); - RetainPtr<CGDataProviderRef> imageProviderRef = adoptCF(CGDataProviderCreateWithCFData(dataRef.get())); - RetainPtr<CGImageRef> imageRef = adoptCF(CGImageCreateWithJPEGDataProvider(imageProviderRef.get(), nullptr, true, kCGRenderingIntentDefault)); - icon = Icon::createIconForImage(imageRef.get()); - } - - m_activeOpenPanelResultListener->didChooseFilesWithDisplayStringAndIcon(files, displayString, icon.get()); - m_activeOpenPanelResultListener = nullptr; -} -#endif - void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files) { if (!m_activeOpenPanelResultListener) return; m_activeOpenPanelResultListener->didChooseFiles(files); - m_activeOpenPanelResultListener = nullptr; + m_activeOpenPanelResultListener = 0; } void WebPage::didCancelForOpenPanel() { - m_activeOpenPanelResultListener = nullptr; + m_activeOpenPanelResultListener = 0; } -#if ENABLE(SANDBOX_EXTENSIONS) +#if ENABLE(WEB_PROCESS_SANDBOX) void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle) { - bool result = SandboxExtension::consumePermanently(handle); - if (!result) { - // We have reports of cases where this fails for some unknown reason, <rdar://problem/10156710>. - WTFLogAlways("WebPage::extendSandboxForFileFromOpenPanel(): Could not consume a sandbox extension"); - } + SandboxExtension::create(handle)->consumePermanently(); } #endif @@ -3421,18 +2941,6 @@ void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed); } -#if ENABLE(MEDIA_STREAM) -void WebPage::didReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed, const String& audioDeviceUID, const String& videoDeviceUID) -{ - m_userMediaPermissionRequestManager.didReceiveUserMediaPermissionDecision(userMediaID, allowed, audioDeviceUID, videoDeviceUID); -} - -void WebPage::didCompleteUserMediaPermissionCheck(uint64_t userMediaID, bool allowed) -{ - m_userMediaPermissionRequestManager.didCompleteUserMediaPermissionCheck(userMediaID, allowed); -} -#endif - #if !PLATFORM(IOS) void WebPage::advanceToNextMisspelling(bool startBeforeSelection) { @@ -3504,7 +3012,7 @@ void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& i return; m_contextMenu->itemSelected(item); - m_contextMenu = nullptr; + m_contextMenu = 0; } #endif @@ -3515,47 +3023,17 @@ void WebPage::replaceSelectionWithText(Frame* frame, const String& text) return frame->editor().replaceSelectionWithText(text, selectReplacement, smartReplace); } -#if !PLATFORM(IOS) void WebPage::clearSelection() { m_page->focusController().focusedOrMainFrame().selection().clear(); } -#endif - -void WebPage::restoreSelectionInFocusedEditableElement() -{ - Frame& frame = m_page->focusController().focusedOrMainFrame(); - if (!frame.selection().isNone()) - return; - - if (auto document = frame.document()) { - if (auto element = document->focusedElement()) - element->updateFocusAppearance(SelectionRestorationMode::Restore, SelectionRevealMode::DoNotReveal); - } -} - -bool WebPage::mainFrameHasCustomContentProvider() const -{ - if (Frame* frame = mainFrame()) { - WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame->loader().client()); - ASSERT(webFrameLoaderClient); - return webFrameLoaderClient->frameHasCustomContentProvider(); - } - - return false; -} - -void WebPage::addMIMETypeWithCustomContentProvider(const String& mimeType) -{ - m_mimeTypesWithCustomContentProviders.add(mimeType); -} void WebPage::updateMainFrameScrollOffsetPinning() { Frame& frame = m_page->mainFrame(); - ScrollPosition scrollPosition = frame.view()->scrollPosition(); - ScrollPosition maximumScrollPosition = frame.view()->maximumScrollPosition(); - ScrollPosition minimumScrollPosition = frame.view()->minimumScrollPosition(); + IntPoint scrollPosition = frame.view()->scrollPosition(); + IntPoint maximumScrollPosition = frame.view()->maximumScrollPosition(); + IntPoint minimumScrollPosition = frame.view()->minimumScrollPosition(); bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x()); bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x()); @@ -3580,16 +3058,20 @@ void WebPage::mainFrameDidLayout() m_cachedPageCount = pageCount; } -#if PLATFORM(MAC) - m_viewGestureGeometryCollector.mainFrameDidLayout(); -#endif -#if PLATFORM(IOS) - if (FrameView* frameView = mainFrameView()) { - IntSize newContentSize = frameView->contentsSize(); - if (m_viewportConfiguration.setContentsSize(newContentSize)) - viewportConfigurationChanged(); +#if USE(TILED_BACKING_STORE) && USE(ACCELERATED_COMPOSITING) + if (m_drawingArea && m_drawingArea->layerTreeHost()) { + double red, green, blue, alpha; + m_mainFrame->getDocumentBackgroundColor(&red, &green, &blue, &alpha); + RGBA32 rgba = makeRGBA32FromFloats(red, green, blue, alpha); + if (m_backgroundColor.rgb() != rgba) { + m_backgroundColor.setRGB(rgba); + m_drawingArea->layerTreeHost()->setBackgroundColor(m_backgroundColor); + } } - m_findController.redraw(); +#endif + +#if PLATFORM(MAC) && !PLATFORM(IOS) + m_viewGestureGeometryCollector.mainFrameDidLayout(); #endif } @@ -3617,13 +3099,13 @@ void WebPage::removePluginView(PluginView* pluginView) void WebPage::sendSetWindowFrame(const FloatRect& windowFrame) { -#if PLATFORM(COCOA) +#if PLATFORM(MAC) m_hasCachedWindowFrame = false; #endif send(Messages::WebPageProxy::SetWindowFrame(windowFrame)); } -#if PLATFORM(COCOA) +#if PLATFORM(MAC) void WebPage::windowAndViewFramesChanged(const FloatRect& windowFrameInScreenCoordinates, const FloatRect& windowFrameInUnflippedScreenCoordinates, const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates) { m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates; @@ -3663,27 +3145,29 @@ bool WebPage::windowAndWebPageAreFocused() const return m_page->focusController().isFocused() && m_page->focusController().isActive(); } -void WebPage::didReceiveMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder) +void WebPage::didReceiveMessage(IPC::Connection* connection, IPC::MessageDecoder& decoder) { -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) + if (decoder.messageReceiverName() == Messages::DrawingArea::messageReceiverName()) { + if (m_drawingArea) + m_drawingArea->didReceiveDrawingAreaMessage(connection, decoder); + return; + } + +#if USE(TILED_BACKING_STORE) && USE(ACCELERATED_COMPOSITING) if (decoder.messageReceiverName() == Messages::CoordinatedLayerTreeHost::messageReceiverName()) { if (m_drawingArea) m_drawingArea->didReceiveCoordinatedLayerTreeHostMessage(connection, decoder); return; } #endif - + +#if ENABLE(INSPECTOR) if (decoder.messageReceiverName() == Messages::WebInspector::messageReceiverName()) { if (WebInspector* inspector = this->inspector()) - inspector->didReceiveMessage(connection, decoder); - return; - } - - if (decoder.messageReceiverName() == Messages::WebInspectorUI::messageReceiverName()) { - if (WebInspectorUI* inspectorUI = this->inspectorUI()) - inspectorUI->didReceiveMessage(connection, decoder); + inspector->didReceiveWebInspectorMessage(connection, decoder); return; } +#endif #if ENABLE(FULLSCREEN_API) if (decoder.messageReceiverName() == Messages::WebFullScreenManager::messageReceiverName()) { @@ -3695,7 +3179,7 @@ void WebPage::didReceiveMessage(IPC::Connection& connection, IPC::MessageDecoder didReceiveWebPageMessage(connection, decoder); } -void WebPage::didReceiveSyncMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder) +void WebPage::didReceiveSyncMessage(IPC::Connection* connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder) { didReceiveSyncWebPageMessage(connection, decoder, replyEncoder); } @@ -3759,7 +3243,7 @@ static bool shouldReuseCommittedSandboxExtension(WebFrame* frame) FrameLoadType frameLoadType = frameLoader.loadType(); // If the page is being reloaded, it should reuse whatever extension is committed. - if (frameLoadType == FrameLoadType::Reload || frameLoadType == FrameLoadType::ReloadFromOrigin) + if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin) return true; DocumentLoader* documentLoader = frameLoader.documentLoader(); @@ -3846,7 +3330,7 @@ void WebPage::didRemoveBackForwardItem(uint64_t itemID) WebBackForwardListProxy::removeItem(itemID); } -#if PLATFORM(COCOA) +#if PLATFORM(MAC) bool WebPage::isSpeaking() { @@ -3866,16 +3350,19 @@ void WebPage::stopSpeaking() #endif -#if PLATFORM(MAC) +#if PLATFORM(MAC) && !PLATFORM(IOS) RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame) { Document* document = coreFrame->document(); - if (!is<PluginDocument>(document)) - return nullptr; + if (!document) + return 0; - PluginView* pluginView = static_cast<PluginView*>(downcast<PluginDocument>(*document).pluginWidget()); + if (!document->isPluginDocument()) + return 0; + + PluginView* pluginView = static_cast<PluginView*>(toPluginDocument(document)->pluginWidget()); if (!pluginView) - return nullptr; + return 0; return pluginView->pdfDocumentForPrinting(); } @@ -3883,7 +3370,7 @@ RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame) void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo) { - WebFrame* frame = WebProcess::singleton().webFrame(frameID); + WebFrame* frame = WebProcess::shared().webFrame(frameID); if (!frame) return; @@ -3891,13 +3378,13 @@ void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo) if (!coreFrame) return; -#if PLATFORM(MAC) +#if PLATFORM(MAC) && !PLATFORM(IOS) if (pdfDocumentForPrintingFrame(coreFrame)) return; #endif // PLATFORM(MAC) if (!m_printContext) - m_printContext = std::make_unique<PrintContext>(coreFrame); + m_printContext = adoptPtr(new PrintContext(coreFrame)); drawingArea()->setLayerTreeStateIsFrozen(true); m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight); @@ -3921,13 +3408,6 @@ void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printIn { Vector<IntRect> resultPageRects; double resultTotalScaleFactorForPrinting = 1; - computePagesForPrintingImpl(frameID, printInfo, resultPageRects, resultTotalScaleFactorForPrinting); - send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID)); -} - -void WebPage::computePagesForPrintingImpl(uint64_t frameID, const PrintInfo& printInfo, Vector<WebCore::IntRect>& resultPageRects, double& resultTotalScaleFactorForPrinting) -{ - ASSERT(resultPageRects.isEmpty()); beginPrinting(frameID, printInfo); @@ -3935,27 +3415,29 @@ void WebPage::computePagesForPrintingImpl(uint64_t frameID, const PrintInfo& pri resultPageRects = m_printContext->pageRects(); resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor; } -#if PLATFORM(COCOA) +#if PLATFORM(MAC) else computePagesForPrintingPDFDocument(frameID, printInfo, resultPageRects); -#endif // PLATFORM(COCOA) +#endif // PLATFORM(MAC) // If we're asked to print, we should actually print at least a blank page. if (resultPageRects.isEmpty()) resultPageRects.append(IntRect(0, 0, 1, 1)); + + send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID)); } -#if PLATFORM(COCOA) +#if PLATFORM(MAC) void WebPage::drawRectToImage(uint64_t frameID, const PrintInfo& printInfo, const IntRect& rect, const WebCore::IntSize& imageSize, uint64_t callbackID) { - WebFrame* frame = WebProcess::singleton().webFrame(frameID); + WebFrame* frame = WebProcess::shared().webFrame(frameID); Frame* coreFrame = frame ? frame->coreFrame() : 0; RefPtr<WebImage> image; #if USE(CG) if (coreFrame) { -#if PLATFORM(MAC) +#if PLATFORM(MAC) && !PLATFORM(IOS) ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame)); #else ASSERT(coreFrame->document()->printing()); @@ -3967,7 +3449,7 @@ void WebPage::drawRectToImage(uint64_t frameID, const PrintInfo& printInfo, cons float printingScale = static_cast<float>(imageSize.width()) / rect.width(); graphicsContext->scale(FloatSize(printingScale, printingScale)); -#if PLATFORM(MAC) +#if PLATFORM(MAC) && !PLATFORM(IOS) if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) { ASSERT(!m_printContext); graphicsContext->scale(FloatSize(1, -1)); @@ -3986,29 +3468,22 @@ void WebPage::drawRectToImage(uint64_t frameID, const PrintInfo& printInfo, cons ShareableBitmap::Handle handle; if (image) - image->bitmap()->createHandle(handle, SharedMemory::Protection::ReadOnly); + image->bitmap()->createHandle(handle, SharedMemory::ReadOnly); send(Messages::WebPageProxy::ImageCallback(handle, callbackID)); } void WebPage::drawPagesToPDF(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, uint64_t callbackID) { - RetainPtr<CFMutableDataRef> pdfPageData; - drawPagesToPDFImpl(frameID, printInfo, first, count, pdfPageData); - send(Messages::WebPageProxy::DataCallback(IPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID)); -} - -void WebPage::drawPagesToPDFImpl(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, RetainPtr<CFMutableDataRef>& pdfPageData) -{ - WebFrame* frame = WebProcess::singleton().webFrame(frameID); + WebFrame* frame = WebProcess::shared().webFrame(frameID); Frame* coreFrame = frame ? frame->coreFrame() : 0; - pdfPageData = adoptCF(CFDataCreateMutable(0, 0)); + RetainPtr<CFMutableDataRef> pdfPageData = adoptCF(CFDataCreateMutable(0, 0)); #if USE(CG) if (coreFrame) { -#if PLATFORM(MAC) +#if PLATFORM(MAC) && !PLATFORM(IOS) ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame)); #else ASSERT(coreFrame->document()->printing()); @@ -4020,7 +3495,7 @@ void WebPage::drawPagesToPDFImpl(uint64_t frameID, const PrintInfo& printInfo, u CGRect mediaBox = (m_printContext && m_printContext->pageCount()) ? m_printContext->pageRect(0) : CGRectMake(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight); RetainPtr<CGContextRef> context = adoptCF(CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0)); -#if PLATFORM(MAC) +#if PLATFORM(MAC) && !PLATFORM(IOS) if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) { ASSERT(!m_printContext); drawPagesToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, first, count); @@ -4046,6 +3521,8 @@ void WebPage::drawPagesToPDFImpl(uint64_t frameID, const PrintInfo& printInfo, u CGPDFContextClose(context.get()); } #endif + + send(Messages::WebPageProxy::DataCallback(IPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID)); } #elif PLATFORM(GTK) @@ -4072,59 +3549,18 @@ void WebPage::savePDFToFileInDownloadsFolder(const String& suggestedFilename, co send(Messages::WebPageProxy::SavePDFToFileInDownloadsFolder(suggestedFilename, originatingURLString, IPC::DataReference(data, size))); } -#if PLATFORM(COCOA) +#if PLATFORM(MAC) void WebPage::savePDFToTemporaryFolderAndOpenWithNativeApplication(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size, const String& pdfUUID) { send(Messages::WebPageProxy::SavePDFToTemporaryFolderAndOpenWithNativeApplication(suggestedFilename, originatingURLString, IPC::DataReference(data, size), pdfUUID)); } #endif -void WebPage::addResourceRequest(unsigned long identifier, const WebCore::ResourceRequest& request) -{ - if (!request.url().protocolIsInHTTPFamily()) - return; - - if (m_mainFrameProgressCompleted && !ScriptController::processingUserGesture()) - return; - - ASSERT(!m_trackedNetworkResourceRequestIdentifiers.contains(identifier)); - bool wasEmpty = m_trackedNetworkResourceRequestIdentifiers.isEmpty(); - m_trackedNetworkResourceRequestIdentifiers.add(identifier); - if (wasEmpty) - send(Messages::WebPageProxy::SetNetworkRequestsInProgress(true)); -} - -void WebPage::removeResourceRequest(unsigned long identifier) -{ - if (!m_trackedNetworkResourceRequestIdentifiers.remove(identifier)) - return; - - if (m_trackedNetworkResourceRequestIdentifiers.isEmpty()) - send(Messages::WebPageProxy::SetNetworkRequestsInProgress(false)); -} - void WebPage::setMediaVolume(float volume) { m_page->setMediaVolume(volume); } -void WebPage::setMuted(bool muted) -{ - m_page->setMuted(muted); -} - -#if ENABLE(MEDIA_SESSION) -void WebPage::handleMediaEvent(uint32_t eventType) -{ - m_page->handleMediaEvent(static_cast<MediaEventType>(eventType)); -} - -void WebPage::setVolumeOfMediaElement(double volume, uint64_t elementID) -{ - m_page->setVolumeOfMediaElement(volume, elementID); -} -#endif - void WebPage::setMayStartMediaWhenInWindow(bool mayStartMedia) { if (mayStartMedia == m_mayStartMediaWhenInWindow) @@ -4144,32 +3580,36 @@ void WebPage::runModal() m_isRunningModal = true; send(Messages::WebPageProxy::RunModal()); -#if !ASSERT_DISABLED - Ref<WebPage> protector(*this); -#endif RunLoop::run(); ASSERT(!m_isRunningModal); } +void WebPage::setMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled) +{ + m_page->setMemoryCacheClientCallsEnabled(memoryCacheMessagesEnabled); +} + bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request) { if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol())) return true; - if (request.url().protocolIsBlob()) +#if ENABLE(BLOB) + if (request.url().protocolIs("blob")) return true; +#endif return platformCanHandleRequest(request); } -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) +#if USE(TILED_BACKING_STORE) void WebPage::commitPageTransitionViewport() { m_drawingArea->setLayerTreeStateIsFrozen(false); } #endif -#if PLATFORM(COCOA) +#if PLATFORM(MAC) void WebPage::handleAlternativeTextUIResult(const String& result) { Frame& frame = m_page->focusController().focusedOrMainFrame(); @@ -4179,17 +3619,17 @@ void WebPage::handleAlternativeTextUIResult(const String& result) void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time) { - mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time, WebCore::ForceAtClick)); + mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time)); } void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time) { - mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time, WebCore::ForceAtClick)); + mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time)); } void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time) { - mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time, 0)); + mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time)); } void WebPage::setCompositionForTesting(const String& compositionString, uint64_t from, uint64_t length) @@ -4220,12 +3660,12 @@ void WebPage::confirmCompositionForTesting(const String& compositionString) frame.editor().confirmComposition(compositionString); } -void WebPage::wheelEventHandlersChanged(bool hasHandlers) +void WebPage::numWheelEventHandlersChanged(unsigned numWheelEventHandlers) { - if (m_hasWheelEventHandlers == hasHandlers) + if (m_numWheelEventHandlers == numWheelEventHandlers) return; - m_hasWheelEventHandlers = hasHandlers; + m_numWheelEventHandlers = numWheelEventHandlers; recomputeShortCircuitHorizontalWheelEventsState(); } @@ -4268,7 +3708,7 @@ static bool pageContainsAnyHorizontalScrollbars(Frame* mainFrame) void WebPage::recomputeShortCircuitHorizontalWheelEventsState() { - bool canShortCircuitHorizontalWheelEvents = !m_hasWheelEventHandlers; + bool canShortCircuitHorizontalWheelEvents = !m_numWheelEventHandlers; if (canShortCircuitHorizontalWheelEvents) { // Check if we have any horizontal scroll bars on the page. @@ -4283,9 +3723,9 @@ void WebPage::recomputeShortCircuitHorizontalWheelEventsState() send(Messages::WebPageProxy::SetCanShortCircuitHorizontalWheelEvents(m_canShortCircuitHorizontalWheelEvents)); } -MainFrame* WebPage::mainFrame() const +Frame* WebPage::mainFrame() const { - return m_page ? &m_page->mainFrame() : nullptr; + return m_page ? &m_page->mainFrame() : 0; } FrameView* WebPage::mainFrameView() const @@ -4293,7 +3733,18 @@ FrameView* WebPage::mainFrameView() const if (Frame* frame = mainFrame()) return frame->view(); - return nullptr; + return 0; +} + +void WebPage::setVisibilityStatePrerender() +{ + if (m_page) + m_page->setIsPrerender(); +} + +void WebPage::setIsVisuallyIdle(bool isVisuallyIdle) +{ + m_page->setIsVisuallyIdle(isVisuallyIdle); } void WebPage::setScrollingPerformanceLoggingEnabled(bool enabled) @@ -4311,7 +3762,7 @@ bool WebPage::canPluginHandleResponse(const ResourceResponse& response) { #if ENABLE(NETSCAPE_PLUGIN_API) uint32_t pluginLoadPolicy; - bool allowOnlyApplicationPlugins = !m_mainFrame->coreFrame()->loader().subframeLoader().allowPlugins(); + bool allowOnlyApplicationPlugins = !m_mainFrame->coreFrame()->loader().subframeLoader().allowPlugins(NotAboutToInstantiatePlugin); uint64_t pluginProcessToken; String newMIMEType; @@ -4319,132 +3770,13 @@ bool WebPage::canPluginHandleResponse(const ResourceResponse& response) if (!sendSync(Messages::WebPageProxy::FindPlugin(response.mimeType(), PluginProcessTypeNormal, response.url().string(), response.url().string(), response.url().string(), allowOnlyApplicationPlugins), Messages::WebPageProxy::FindPlugin::Reply(pluginProcessToken, newMIMEType, pluginLoadPolicy, unavailabilityDescription))) return false; - bool isBlockedPlugin = (pluginLoadPolicy == PluginModuleBlockedForSecurity) || (pluginLoadPolicy == PluginModuleBlockedForCompatibility); - return !isBlockedPlugin && pluginProcessToken; + return pluginLoadPolicy != PluginModuleBlocked && pluginProcessToken; #else UNUSED_PARAM(response); return false; #endif } -bool WebPage::shouldUseCustomContentProviderForResponse(const ResourceResponse& response) -{ - // If a plug-in exists that claims to support this response, it should take precedence over the custom content provider. - return m_mimeTypesWithCustomContentProviders.contains(response.mimeType()) && !canPluginHandleResponse(response); -} - -#if PLATFORM(COCOA) - -void WebPage::insertTextAsync(const String& text, const EditingRange& replacementEditingRange, bool registerUndoGroup, uint32_t editingRangeIsRelativeTo) -{ - Frame& frame = m_page->focusController().focusedOrMainFrame(); - - if (replacementEditingRange.location != notFound) { - RefPtr<Range> replacementRange = rangeFromEditingRange(frame, replacementEditingRange, static_cast<EditingRangeIsRelativeTo>(editingRangeIsRelativeTo)); - if (replacementRange) - frame.selection().setSelection(VisibleSelection(*replacementRange, SEL_DEFAULT_AFFINITY)); - } - - if (registerUndoGroup) - send(Messages::WebPageProxy::RegisterInsertionUndoGrouping()); - - if (!frame.editor().hasComposition()) { - // An insertText: might be handled by other responders in the chain if we don't handle it. - // One example is space bar that results in scrolling down the page. - frame.editor().insertText(text, nullptr); - } else - frame.editor().confirmComposition(text); -} - -void WebPage::getMarkedRangeAsync(uint64_t callbackID) -{ - Frame& frame = m_page->focusController().focusedOrMainFrame(); - - RefPtr<Range> range = frame.editor().compositionRange(); - size_t location; - size_t length; - if (!range || !TextIterator::getLocationAndLengthFromRange(frame.selection().rootEditableElementOrDocumentElement(), range.get(), location, length)) { - location = notFound; - length = 0; - } - - send(Messages::WebPageProxy::EditingRangeCallback(EditingRange(location, length), callbackID)); -} - -void WebPage::getSelectedRangeAsync(uint64_t callbackID) -{ - Frame& frame = m_page->focusController().focusedOrMainFrame(); - - size_t location; - size_t length; - RefPtr<Range> range = frame.selection().toNormalizedRange(); - if (!range || !TextIterator::getLocationAndLengthFromRange(frame.selection().rootEditableElementOrDocumentElement(), range.get(), location, length)) { - location = notFound; - length = 0; - } - - send(Messages::WebPageProxy::EditingRangeCallback(EditingRange(location, length), callbackID)); -} - -void WebPage::characterIndexForPointAsync(const WebCore::IntPoint& point, uint64_t callbackID) -{ - uint64_t index = notFound; - - HitTestResult result = m_page->mainFrame().eventHandler().hitTestResultAtPoint(point); - Frame* frame = result.innerNonSharedNode() ? result.innerNodeFrame() : &m_page->focusController().focusedOrMainFrame(); - - RefPtr<Range> range = frame->rangeForPoint(result.roundedPointInInnerNodeFrame()); - if (range) { - size_t location; - size_t length; - if (TextIterator::getLocationAndLengthFromRange(frame->selection().rootEditableElementOrDocumentElement(), range.get(), location, length)) - index = static_cast<uint64_t>(location); - } - - send(Messages::WebPageProxy::UnsignedCallback(index, callbackID)); -} - -void WebPage::firstRectForCharacterRangeAsync(const EditingRange& editingRange, uint64_t callbackID) -{ - Frame& frame = m_page->focusController().focusedOrMainFrame(); - IntRect result(IntPoint(0, 0), IntSize(0, 0)); - - RefPtr<Range> range = rangeFromEditingRange(frame, editingRange); - if (!range) { - send(Messages::WebPageProxy::RectForCharacterRangeCallback(result, EditingRange(notFound, 0), callbackID)); - return; - } - - result = frame.view()->contentsToWindow(frame.editor().firstRectForRange(range.get())); - - // FIXME: Update actualRange to match the range of first rect. - send(Messages::WebPageProxy::RectForCharacterRangeCallback(result, editingRange, callbackID)); -} - -void WebPage::setCompositionAsync(const String& text, Vector<CompositionUnderline> underlines, const EditingRange& selection, const EditingRange& replacementEditingRange) -{ - Frame& frame = m_page->focusController().focusedOrMainFrame(); - - if (frame.selection().selection().isContentEditable()) { - RefPtr<Range> replacementRange; - if (replacementEditingRange.location != notFound) { - replacementRange = rangeFromEditingRange(frame, replacementEditingRange); - if (replacementRange) - frame.selection().setSelection(VisibleSelection(*replacementRange, SEL_DEFAULT_AFFINITY)); - } - - frame.editor().setComposition(text, underlines, selection.location, selection.location + selection.length); - } -} - -void WebPage::confirmCompositionAsync() -{ - Frame& frame = m_page->focusController().focusedOrMainFrame(); - frame.editor().confirmComposition(); -} - -#endif // PLATFORM(COCOA) - #if PLATFORM(GTK) static Frame* targetFrameForEditing(WebPage* page) { @@ -4452,16 +3784,17 @@ static Frame* targetFrameForEditing(WebPage* page) Editor& editor = targetFrame.editor(); if (!editor.canEdit()) - return nullptr; + return 0; if (editor.hasComposition()) { // We should verify the parent node of this IME composition node are // editable because JavaScript may delete a parent node of the composition // node. In this case, WebKit crashes while deleting texts from the parent // node, which doesn't exist any longer. - if (auto range = editor.compositionRange()) { - if (!range->startContainer().isContentEditable()) - return nullptr; + if (PassRefPtr<Range> range = editor.compositionRange()) { + Node* node = range->startContainer(); + if (!node || !node->isContentEditable()) + return 0; } } return &targetFrame; @@ -4482,21 +3815,21 @@ void WebPage::confirmComposition(const String& compositionString, int64_t select return; } - Element* scope = targetFrame->selection().selection().rootEditableElement(); + Element* scope = targetFrame->selection().rootEditableElement(); RefPtr<Range> selectionRange = TextIterator::rangeFromLocationAndLength(scope, selectionStart, selectionLength); ASSERT_WITH_MESSAGE(selectionRange, "Invalid selection: [%lld:%lld] in text of length %d", static_cast<long long>(selectionStart), static_cast<long long>(selectionLength), scope->innerText().length()); if (selectionRange) { - VisibleSelection selection(*selectionRange, SEL_DEFAULT_AFFINITY); + VisibleSelection selection(selectionRange.get(), SEL_DEFAULT_AFFINITY); targetFrame->selection().setSelection(selection); } send(Messages::WebPageProxy::EditorStateChanged(editorState())); } -void WebPage::setComposition(const String& text, const Vector<CompositionUnderline>& underlines, uint64_t selectionStart, uint64_t selectionLength, uint64_t replacementStart, uint64_t replacementLength) +void WebPage::setComposition(const String& text, Vector<CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementStart, uint64_t replacementLength) { Frame* targetFrame = targetFrameForEditing(this); - if (!targetFrame || !targetFrame->selection().selection().isContentEditable()) { + if (!targetFrame || !targetFrame->selection().isContentEditable()) { send(Messages::WebPageProxy::EditorStateChanged(editorState())); return; } @@ -4505,14 +3838,14 @@ void WebPage::setComposition(const String& text, const Vector<CompositionUnderli // The layout needs to be uptodate before setting a selection targetFrame->document()->updateLayout(); - Element* scope = targetFrame->selection().selection().rootEditableElement(); + Element* scope = targetFrame->selection().rootEditableElement(); RefPtr<Range> replacementRange = TextIterator::rangeFromLocationAndLength(scope, replacementStart, replacementLength); targetFrame->editor().setIgnoreCompositionSelectionChange(true); - targetFrame->selection().setSelection(VisibleSelection(*replacementRange, SEL_DEFAULT_AFFINITY)); + targetFrame->selection().setSelection(VisibleSelection(replacementRange.get(), SEL_DEFAULT_AFFINITY)); targetFrame->editor().setIgnoreCompositionSelectionChange(false); } - targetFrame->editor().setComposition(text, underlines, selectionStart, selectionStart + selectionLength); + targetFrame->editor().setComposition(text, underlines, selectionStart, selectionEnd); send(Messages::WebPageProxy::EditorStateChanged(editorState())); } @@ -4526,46 +3859,12 @@ void WebPage::cancelComposition() void WebPage::didChangeSelection() { - Frame& frame = m_page->focusController().focusedOrMainFrame(); - FrameView* view = frame.view(); - - // If there is a layout pending, we should avoid populating EditorState that require layout to be done or it will - // trigger a synchronous layout every time the selection changes. sendPostLayoutEditorStateIfNeeded() will be called - // to send the full editor state after layout is done if we send a partial editor state here. - auto editorState = this->editorState(view && view->needsLayout() ? IncludePostLayoutDataHint::No : IncludePostLayoutDataHint::Yes); - m_isEditorStateMissingPostLayoutData = editorState.isMissingPostLayoutData; - -#if PLATFORM(MAC) - // Abandon the current inline input session if selection changed for any other reason but an input method direct action. - // FIXME: This logic should be in WebCore. - // FIXME: Many changes that affect composition node do not go through didChangeSelection(). We need to do something when DOM manipulation affects the composition, because otherwise input method's idea about it will be different from Editor's. - // FIXME: We can't cancel composition when selection changes to NoSelection, but we probably should. - if (frame.editor().hasComposition() && !frame.editor().ignoreCompositionSelectionChange() && !frame.selection().isNone()) { - frame.editor().cancelComposition(); - send(Messages::WebPageProxy::CompositionWasCanceled(editorState)); - } else - send(Messages::WebPageProxy::EditorStateChanged(editorState)); -#else - send(Messages::WebPageProxy::EditorStateChanged(editorState), pageID(), IPC::DispatchMessageEvenWhenWaitingForSyncReply); -#endif - -#if PLATFORM(IOS) - m_drawingArea->scheduleCompositingLayerFlush(); -#endif -} - -void WebPage::sendPostLayoutEditorStateIfNeeded() -{ - if (!m_isEditorStateMissingPostLayoutData) - return; - - send(Messages::WebPageProxy::EditorStateChanged(editorState(IncludePostLayoutDataHint::Yes)), pageID(), IPC::DispatchMessageEvenWhenWaitingForSyncReply); - m_isEditorStateMissingPostLayoutData = false; + send(Messages::WebPageProxy::EditorStateChanged(editorState())); } -void WebPage::discardedComposition() +void WebPage::setMainFrameInViewSourceMode(bool inViewSourceMode) { - send(Messages::WebPageProxy::CompositionWasCanceled(editorState())); + m_mainFrame->coreFrame()->setInViewSourceMode(inViewSourceMode); } void WebPage::setMinimumLayoutSize(const IntSize& minimumLayoutSize) @@ -4628,15 +3927,12 @@ bool WebPage::canShowMIMEType(const String& MIMEType) const if (MIMETypeRegistry::canShowMIMEType(MIMEType)) return true; - if (m_mimeTypesWithCustomContentProviders.contains(MIMEType)) - return true; - const PluginData& pluginData = m_page->pluginData(); - if (pluginData.supportsWebVisibleMimeType(MIMEType, PluginData::AllPlugins) && corePage()->mainFrame().loader().subframeLoader().allowPlugins()) + if (pluginData.supportsMimeType(MIMEType, PluginData::AllPlugins) && corePage()->mainFrame().loader().subframeLoader().allowPlugins(NotAboutToInstantiatePlugin)) return true; // We can use application plugins even if plugins aren't enabled. - if (pluginData.supportsWebVisibleMimeType(MIMEType, PluginData::OnlyApplicationPlugins)) + if (pluginData.supportsMimeType(MIMEType, PluginData::OnlyApplicationPlugins)) return true; return false; @@ -4665,36 +3961,8 @@ void WebPage::didCancelCheckingText(uint64_t requestID) request->didCancel(); } -void WebPage::willReplaceMultipartContent(const WebFrame& frame) -{ -#if PLATFORM(IOS) - if (!frame.isMainFrame()) - return; - - m_previousExposedContentRect = m_drawingArea->exposedContentRect(); -#endif -} - -void WebPage::didReplaceMultipartContent(const WebFrame& frame) -{ -#if PLATFORM(IOS) - if (!frame.isMainFrame()) - return; - - // Restore the previous exposed content rect so that it remains fixed when replacing content - // from multipart/x-mixed-replace streams. - m_drawingArea->setExposedContentRect(m_previousExposedContentRect); -#endif -} - void WebPage::didCommitLoad(WebFrame* frame) { -#if PLATFORM(IOS) - frame->setFirstLayerTreeTransactionIDAfterDidCommitLoad(downcast<RemoteLayerTreeDrawingArea>(*m_drawingArea).nextTransactionID()); - cancelPotentialTapInFrame(*frame); - resetAssistedNodeForFrame(frame); -#endif - if (!frame->isMainFrame()) return; @@ -4704,52 +3972,17 @@ void WebPage::didCommitLoad(WebFrame* frame) reportUsedFeatures(); // Only restore the scale factor for standard frame loads (of the main frame). - if (frame->coreFrame()->loader().loadType() == FrameLoadType::Standard) { + if (frame->coreFrame()->loader().loadType() == FrameLoadTypeStandard) { Page* page = frame->coreFrame()->page(); - -#if PLATFORM(MAC) - // As a very special case, we disable non-default layout modes in WKView for main-frame PluginDocuments. - // Ideally we would only worry about this in WKView or the WKViewLayoutStrategies, but if we allow - // a round-trip to the UI process, you'll see the wrong scale temporarily. So, we reset it here, and then - // again later from the UI process. - if (frame->coreFrame()->document()->isPluginDocument()) { - scaleView(1); - setUseFixedLayout(false); - } -#endif - if (page && page->pageScaleFactor() != 1) scalePage(1, IntPoint()); } -#if PLATFORM(IOS) - m_hasReceivedVisibleContentRectsAfterDidCommitLoad = false; - m_scaleWasSetByUIProcess = false; - m_userHasChangedPageScaleFactor = false; - m_estimatedLatency = std::chrono::milliseconds(1000 / 60); - -#if ENABLE(IOS_TOUCH_EVENTS) - WebProcess::singleton().eventDispatcher().clearQueuedTouchEventsForPage(*this); -#endif - - resetViewportDefaultConfiguration(frame); - const Frame* coreFrame = frame->coreFrame(); - - bool viewportChanged = false; - if (m_viewportConfiguration.setContentsSize(coreFrame->view()->contentsSize())) - viewportChanged = true; - - if (m_viewportConfiguration.setViewportArguments(coreFrame->document()->viewportArguments())) - viewportChanged = true; - - if (viewportChanged) - viewportConfigurationChanged(); -#endif #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC) resetPrimarySnapshottedPlugIn(); #endif - WebProcess::singleton().updateActivePages(); + WebProcess::shared().updateActivePages(); updateMainFrameScrollOffsetPinning(); } @@ -4769,14 +4002,13 @@ void WebPage::didFinishLoad(WebFrame* frame) } #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC) -static const int primarySnapshottedPlugInSearchLimit = 3000; -static const float primarySnapshottedPlugInSearchBucketSize = 1.1; -static const int primarySnapshottedPlugInMinimumWidth = 400; -static const int primarySnapshottedPlugInMinimumHeight = 300; -static const unsigned maxPrimarySnapshottedPlugInDetectionAttempts = 2; -static const int deferredPrimarySnapshottedPlugInDetectionDelay = 3; -static const float overlappingImageBoundsScale = 1.1; -static const float minimumOverlappingImageToPluginDimensionScale = .9; +static int primarySnapshottedPlugInSearchLimit = 3000; +static int primarySnapshottedPlugInSearchGap = 200; +static float primarySnapshottedPlugInSearchBucketSize = 1.1; +static int primarySnapshottedPlugInMinimumWidth = 400; +static int primarySnapshottedPlugInMinimumHeight = 300; +static unsigned maxPrimarySnapshottedPlugInDetectionAttempts = 2; +static int deferredPrimarySnapshottedPlugInDetectionDelay = 3; #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC) void WebPage::determinePrimarySnapshottedPlugInTimerFired() @@ -4814,71 +4046,59 @@ void WebPage::determinePrimarySnapshottedPlugIn() ++m_numberOfPrimarySnapshotDetectionAttempts; - layoutIfNeeded(); - - MainFrame& mainFrame = corePage()->mainFrame(); - if (!mainFrame.view()) - return; - if (!mainFrame.view()->renderView()) - return; - RenderView& mainRenderView = *mainFrame.view()->renderView(); + RenderView* renderView = corePage()->mainFrame().view()->renderView(); IntRect searchRect = IntRect(IntPoint(), corePage()->mainFrame().view()->contentsSize()); searchRect.intersect(IntRect(IntPoint(), IntSize(primarySnapshottedPlugInSearchLimit, primarySnapshottedPlugInSearchLimit))); HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::AllowChildFrameContent | HitTestRequest::IgnoreClipping | HitTestRequest::DisallowShadowContent); - HTMLPlugInImageElement* candidatePlugIn = nullptr; + HashSet<RenderObject*> seenRenderers; + HTMLPlugInImageElement* candidatePlugIn = 0; unsigned candidatePlugInArea = 0; - for (Frame* frame = &mainFrame; frame; frame = frame->tree().traverseNextRendered()) { - if (!frame->loader().subframeLoader().containsPlugins()) - continue; - if (!frame->document() || !frame->view()) - continue; - for (auto& plugInImageElement : descendantsOfType<HTMLPlugInImageElement>(*frame->document())) { - if (plugInImageElement.displayState() == HTMLPlugInElement::Playing) + for (int x = searchRect.x(); x <= searchRect.width(); x += primarySnapshottedPlugInSearchGap) { + for (int y = searchRect.y(); y <= searchRect.height(); y += primarySnapshottedPlugInSearchGap) { + HitTestResult hitTestResult = HitTestResult(LayoutPoint(x, y)); + renderView->hitTest(request, hitTestResult); + + Element* element = hitTestResult.innerElement(); + if (!element) continue; - auto pluginRenderer = plugInImageElement.renderer(); - if (!pluginRenderer || !pluginRenderer->isBox()) + RenderObject* renderer = element->renderer(); + if (!renderer || !renderer->isBox()) continue; - auto& pluginRenderBox = downcast<RenderBox>(*pluginRenderer); - if (!plugInIntersectsSearchRect(plugInImageElement)) + + RenderBox* renderBox = toRenderBox(renderer); + + if (!seenRenderers.add(renderer).isNewEntry) continue; - IntRect plugInRectRelativeToView = plugInImageElement.clientRect(); - ScrollPosition scrollPosition = mainFrame.view()->documentScrollPositionRelativeToViewOrigin(); - IntRect plugInRectRelativeToTopDocument(plugInRectRelativeToView.location() + scrollPosition, plugInRectRelativeToView.size()); - HitTestResult hitTestResult(plugInRectRelativeToTopDocument.center()); - mainRenderView.hitTest(request, hitTestResult); + if (!element->isPluginElement()) + continue; - Element* element = hitTestResult.innerElement(); - if (!element) + HTMLPlugInElement* plugInElement = toHTMLPlugInElement(element); + if (!plugInElement->isPlugInImageElement()) continue; - IntRect elementRectRelativeToView = element->clientRect(); - IntRect elementRectRelativeToTopDocument(elementRectRelativeToView.location() + scrollPosition, elementRectRelativeToView.size()); - LayoutRect inflatedPluginRect = plugInRectRelativeToTopDocument; - LayoutUnit xOffset = (inflatedPluginRect.width() * overlappingImageBoundsScale - inflatedPluginRect.width()) / 2; - LayoutUnit yOffset = (inflatedPluginRect.height() * overlappingImageBoundsScale - inflatedPluginRect.height()) / 2; - inflatedPluginRect.inflateX(xOffset); - inflatedPluginRect.inflateY(yOffset); - - if (element != &plugInImageElement) { - if (!(is<HTMLImageElement>(*element) - && inflatedPluginRect.contains(elementRectRelativeToTopDocument) - && elementRectRelativeToTopDocument.width() > pluginRenderBox.width() * minimumOverlappingImageToPluginDimensionScale - && elementRectRelativeToTopDocument.height() > pluginRenderBox.height() * minimumOverlappingImageToPluginDimensionScale)) - continue; - LOG(Plugins, "Primary Plug-In Detection: Plug-in is hidden by an image that is roughly aligned with it, autoplaying regardless of whether or not it's actually the primary plug-in."); - plugInImageElement.restartSnapshottedPlugIn(); - } + HTMLPlugInImageElement* plugInImageElement = toHTMLPlugInImageElement(plugInElement); + + if (plugInElement->displayState() == HTMLPlugInElement::Playing) + continue; - if (plugInIsPrimarySize(plugInImageElement, candidatePlugInArea)) - candidatePlugIn = &plugInImageElement; + if (renderBox->contentWidth() < primarySnapshottedPlugInMinimumWidth || renderBox->contentHeight() < primarySnapshottedPlugInMinimumHeight) + continue; + + LayoutUnit contentArea = renderBox->contentWidth() * renderBox->contentHeight(); + + if (contentArea > candidatePlugInArea * primarySnapshottedPlugInSearchBucketSize) { + candidatePlugIn = plugInImageElement; + candidatePlugInArea = contentArea; + } } } + if (!candidatePlugIn) { LOG(Plugins, "Primary Plug-In Detection: fail - did not find a candidate plug-in."); if (m_numberOfPrimarySnapshotDetectionAttempts < maxPrimarySnapshottedPlugInDetectionAttempts) { @@ -4912,40 +4132,6 @@ bool WebPage::matchesPrimaryPlugIn(const String& pageOrigin, const String& plugi return (pageOrigin == m_primaryPlugInPageOrigin && pluginOrigin == m_primaryPlugInOrigin && mimeType == m_primaryPlugInMimeType); } - -bool WebPage::plugInIntersectsSearchRect(HTMLPlugInImageElement& plugInImageElement) -{ - MainFrame& mainFrame = corePage()->mainFrame(); - if (!mainFrame.view()) - return false; - if (!mainFrame.view()->renderView()) - return false; - - IntRect searchRect = IntRect(IntPoint(), corePage()->mainFrame().view()->contentsSize()); - searchRect.intersect(IntRect(IntPoint(), IntSize(primarySnapshottedPlugInSearchLimit, primarySnapshottedPlugInSearchLimit))); - - IntRect plugInRectRelativeToView = plugInImageElement.clientRect(); - if (plugInRectRelativeToView.isEmpty()) - return false; - ScrollPosition scrollPosition = mainFrame.view()->documentScrollPositionRelativeToViewOrigin(); - IntRect plugInRectRelativeToTopDocument(plugInRectRelativeToView.location() + toIntSize(scrollPosition), plugInRectRelativeToView.size()); - - return plugInRectRelativeToTopDocument.intersects(searchRect); -} - -bool WebPage::plugInIsPrimarySize(WebCore::HTMLPlugInImageElement& plugInImageElement, unsigned& candidatePlugInArea) -{ - auto& pluginRenderBox = downcast<RenderBox>(*plugInImageElement.renderer()); - if (pluginRenderBox.contentWidth() < primarySnapshottedPlugInMinimumWidth || pluginRenderBox.contentHeight() < primarySnapshottedPlugInMinimumHeight) - return false; - - LayoutUnit contentArea = pluginRenderBox.contentWidth() * pluginRenderBox.contentHeight(); - if (contentArea > candidatePlugInArea * primarySnapshottedPlugInSearchBucketSize) { - candidatePlugInArea = contentArea; - return true; - } - return false; -} #endif // ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC) PassRefPtr<Range> WebPage::currentSelectionAsRange() @@ -4991,182 +4177,13 @@ void WebPage::setScrollPinningBehavior(uint32_t pinning) m_page->mainFrame().view()->setScrollPinningBehavior(m_scrollPinningBehavior); } -void WebPage::setScrollbarOverlayStyle(WTF::Optional<uint32_t> scrollbarStyle) -{ - if (scrollbarStyle) - m_scrollbarOverlayStyle = static_cast<ScrollbarOverlayStyle>(scrollbarStyle.value()); - else - m_scrollbarOverlayStyle = WTF::Optional<ScrollbarOverlayStyle>(); - m_page->mainFrame().view()->recalculateScrollbarOverlayStyle(); -} - -Ref<DocumentLoader> WebPage::createDocumentLoader(Frame& frame, const ResourceRequest& request, const SubstituteData& substituteData) -{ - Ref<WebDocumentLoader> documentLoader = WebDocumentLoader::create(request, substituteData); - - if (frame.isMainFrame()) { - if (m_pendingNavigationID) { - documentLoader->setNavigationID(m_pendingNavigationID); - m_pendingNavigationID = 0; - } - } - - return WTFMove(documentLoader); -} - -void WebPage::updateCachedDocumentLoader(WebDocumentLoader& documentLoader, Frame& frame) -{ - if (m_pendingNavigationID && frame.isMainFrame()) { - documentLoader.setNavigationID(m_pendingNavigationID); - m_pendingNavigationID = 0; - } -} - -void WebPage::getBytecodeProfile(uint64_t callbackID) -{ - if (!JSDOMWindow::commonVM().m_perBytecodeProfiler) { - send(Messages::WebPageProxy::StringCallback(String(), callbackID)); - return; - } - - String result = JSDOMWindow::commonVM().m_perBytecodeProfiler->toJSON(); - ASSERT(result.length()); - send(Messages::WebPageProxy::StringCallback(result, callbackID)); -} - -PassRefPtr<WebCore::Range> WebPage::rangeFromEditingRange(WebCore::Frame& frame, const EditingRange& range, EditingRangeIsRelativeTo editingRangeIsRelativeTo) -{ - ASSERT(range.location != notFound); - - // Sanitize the input, because TextIterator::rangeFromLocationAndLength takes signed integers. - if (range.location > INT_MAX) - return 0; - int length; - if (range.length <= INT_MAX && range.location + range.length <= INT_MAX) - length = static_cast<int>(range.length); - else - length = INT_MAX - range.location; - - if (editingRangeIsRelativeTo == EditingRangeIsRelativeTo::EditableRoot) { - // Our critical assumption is that this code path is called by input methods that - // concentrate on a given area containing the selection. - // We have to do this because of text fields and textareas. The DOM for those is not - // directly in the document DOM, so serialization is problematic. Our solution is - // to use the root editable element of the selection start as the positional base. - // That fits with AppKit's idea of an input context. - return TextIterator::rangeFromLocationAndLength(frame.selection().rootEditableElementOrDocumentElement(), static_cast<int>(range.location), length); - } - - ASSERT(editingRangeIsRelativeTo == EditingRangeIsRelativeTo::Paragraph); - - const VisibleSelection& selection = frame.selection().selection(); - RefPtr<Range> selectedRange = selection.toNormalizedRange(); - if (!selectedRange) - return 0; - - RefPtr<Range> paragraphRange = makeRange(startOfParagraph(selection.visibleStart()), selection.visibleEnd()); - if (!paragraphRange) - return 0; - - ContainerNode& rootNode = paragraphRange.get()->startContainer().treeScope().rootNode(); - int paragraphStartIndex = TextIterator::rangeLength(Range::create(rootNode.document(), &rootNode, 0, ¶graphRange->startContainer(), paragraphRange->startOffset()).ptr()); - return TextIterator::rangeFromLocationAndLength(&rootNode, paragraphStartIndex + static_cast<int>(range.location), length); -} - -void WebPage::didChangeScrollOffsetForFrame(Frame* frame) -{ - if (!frame->isMainFrame()) - return; - - // If this is called when tearing down a FrameView, the WebCore::Frame's - // current FrameView will be null. - if (!frame->view()) - return; - - updateMainFrameScrollOffsetPinning(); -} - -void WebPage::postMessage(const String& messageName, API::Object* messageBody) -{ - send(Messages::WebPageProxy::HandleMessage(messageName, UserData(WebProcess::singleton().transformObjectsToHandles(messageBody)))); -} - -void WebPage::postSynchronousMessageForTesting(const String& messageName, API::Object* messageBody, RefPtr<API::Object>& returnData) +PassRefPtr<DocumentLoader> WebPage::createDocumentLoader(Frame& frame, const ResourceRequest& request, const SubstituteData& substituteData) { - UserData returnUserData; + RefPtr<WebDocumentLoader> documentLoader = WebDocumentLoader::create(request, substituteData); - auto& webProcess = WebProcess::singleton(); - if (!sendSync(Messages::WebPageProxy::HandleSynchronousMessage(messageName, UserData(webProcess.transformObjectsToHandles(messageBody))), Messages::WebPageProxy::HandleSynchronousMessage::Reply(returnUserData), std::chrono::milliseconds::max(), IPC::SyncMessageSendFlags::UseFullySynchronousModeForTesting)) - returnData = nullptr; - else - returnData = webProcess.transformHandlesToObjects(returnUserData.object()); -} - -void WebPage::clearWheelEventTestTrigger() -{ - if (!m_page) - return; - - m_page->clearTrigger(); -} - -void WebPage::setShouldScaleViewToFitDocument(bool shouldScaleViewToFitDocument) -{ - if (!m_drawingArea) - return; + // FIXME: Set the navigation ID if possible. - m_drawingArea->setShouldScaleViewToFitDocument(shouldScaleViewToFitDocument); -} - -void WebPage::imageOrMediaDocumentSizeChanged(const IntSize& newSize) -{ - send(Messages::WebPageProxy::ImageOrMediaDocumentSizeChanged(newSize)); -} - -void WebPage::addUserScript(const String& source, WebCore::UserContentInjectedFrames injectedFrames, WebCore::UserScriptInjectionTime injectionTime) -{ - ASSERT(m_userContentController); - - WebCore::UserScript userScript(source, WebCore::blankURL(), Vector<String>(), Vector<String>(), injectionTime, injectedFrames); - - m_userContentController->userContentController().addUserScript(mainThreadNormalWorld(), std::make_unique<WebCore::UserScript>(userScript)); -} - -void WebPage::addUserStyleSheet(const String& source, WebCore::UserContentInjectedFrames injectedFrames) -{ - ASSERT(m_userContentController); - - WebCore::UserStyleSheet userStyleSheet(source, WebCore::blankURL(), Vector<String>(), Vector<String>(), injectedFrames, UserStyleUserLevel); - - m_userContentController->userContentController().addUserStyleSheet(mainThreadNormalWorld(), std::make_unique<WebCore::UserStyleSheet>(userStyleSheet), InjectInExistingDocuments); -} - -void WebPage::removeAllUserContent() -{ - if (!m_userContentController) - return; - - m_userContentController->userContentController().removeAllUserContent(); -} - -void WebPage::dispatchDidLayout(WebCore::LayoutMilestones milestones) -{ - RefPtr<API::Object> userData; - injectedBundleLoaderClient().didLayout(this, milestones, userData); - - // Clients should not set userData for this message, and it won't be passed through. - ASSERT(!userData); - - // The drawing area might want to defer dispatch of didLayout to the UI process. - if (m_drawingArea && m_drawingArea->dispatchDidLayout(milestones)) - return; - - send(Messages::WebPageProxy::DidLayout(milestones)); -} - -void WebPage::didRestoreScrollPosition() -{ - send(Messages::WebPageProxy::DidRestoreScrollPosition()); + return documentLoader.release(); } } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/WebPage.h b/Source/WebKit2/WebProcess/WebPage/WebPage.h index 8e89c0179..7f50290b6 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebPage.h +++ b/Source/WebKit2/WebProcess/WebPage/WebPage.h @@ -26,60 +26,48 @@ #ifndef WebPage_h #define WebPage_h -#include "APIInjectedBundleFormClient.h" -#include "APIInjectedBundlePageContextMenuClient.h" -#include "APIInjectedBundlePageUIClient.h" #include "APIObject.h" -#include "Download.h" -#include "EditingRange.h" +#include "DrawingArea.h" #include "FindController.h" #include "GeolocationPermissionRequestManager.h" #include "ImageOptions.h" #include "InjectedBundlePageDiagnosticLoggingClient.h" #include "InjectedBundlePageEditorClient.h" +#include "InjectedBundlePageFormClient.h" #include "InjectedBundlePageFullScreenClient.h" #include "InjectedBundlePageLoaderClient.h" #include "InjectedBundlePagePolicyClient.h" #include "InjectedBundlePageResourceLoadClient.h" -#include "LayerTreeContext.h" +#include "InjectedBundlePageUIClient.h" #include "MessageReceiver.h" #include "MessageSender.h" +#include "TapHighlightController.h" #include "Plugin.h" #include "SandboxExtension.h" #include "ShareableBitmap.h" -#include "UserData.h" -#include "UserMediaPermissionRequestManager.h" +#include "WebUndoStep.h" #include <WebCore/DictationAlternative.h> -#include <WebCore/DictionaryPopupInfo.h> #include <WebCore/DragData.h> #include <WebCore/Editor.h> #include <WebCore/FrameLoaderTypes.h> -#include <WebCore/HitTestResult.h> -#include <WebCore/HysteresisActivity.h> #include <WebCore/IntRect.h> -#include <WebCore/IntSizeHash.h> #include <WebCore/Page.h> -#include <WebCore/PageOverlay.h> #include <WebCore/PageVisibilityState.h> +#include <WebCore/PlatformScreen.h> #include <WebCore/ScrollTypes.h> #include <WebCore/TextChecking.h> -#include <WebCore/TextIndicator.h> #include <WebCore/UserActivity.h> -#include <WebCore/UserContentTypes.h> -#include <WebCore/UserScriptTypes.h> #include <WebCore/ViewState.h> -#include <WebCore/ViewportConfiguration.h> #include <WebCore/WebCoreKeyboardUIMode.h> -#include <memory> #include <wtf/HashMap.h> +#include <wtf/OwnPtr.h> #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> -#include <wtf/RunLoop.h> #include <wtf/text/WTFString.h> #if HAVE(ACCESSIBILITY) && (PLATFORM(GTK) || PLATFORM(EFL)) #include "WebPageAccessibilityObject.h" -#include <wtf/glib/GRefPtr.h> +#include <wtf/gobject/GRefPtr.h> #endif #if PLATFORM(GTK) @@ -87,33 +75,29 @@ #include "WebPrintOperationGtk.h" #endif +#if ENABLE(TOUCH_EVENTS) #if PLATFORM(IOS) -#include "GestureTypes.h" -#import "WebPageMessages.h" -#endif - -#if ENABLE(IOS_TOUCH_EVENTS) #include <WebKitAdditions/PlatformTouchEventIOS.h> -#elif ENABLE(TOUCH_EVENTS) +#else #include <WebCore/PlatformTouchEvent.h> #endif - -#if ENABLE(MAC_GESTURE_EVENTS) -#include <WebKitAdditions/PlatformGestureEventMac.h> #endif #if ENABLE(CONTEXT_MENUS) #include "InjectedBundlePageContextMenuClient.h" #endif -#if PLATFORM(COCOA) +#if PLATFORM(MAC) +#include "DictionaryPopupInfo.h" +#include "LayerHostingContext.h" #include "ViewGestureGeometryCollector.h" #include <wtf/RetainPtr.h> OBJC_CLASS CALayer; -OBJC_CLASS NSArray; OBJC_CLASS NSDictionary; OBJC_CLASS NSObject; OBJC_CLASS WKAccessibilityWebPageObject; + +#define ENABLE_PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC 1 #endif namespace API { @@ -121,91 +105,72 @@ class Array; } namespace IPC { -class ArgumentDecoder; -class Connection; + class ArgumentDecoder; + class Connection; } namespace WebCore { -class DocumentLoader; -class GraphicsContext; -class Frame; -class FrameView; -class HTMLPlugInElement; -class HTMLPlugInImageElement; -class IntPoint; -class KeyboardEvent; -class MediaPlaybackTargetContext; -class Page; -class PrintContext; -class Range; -class ResourceResponse; -class ResourceRequest; -class SharedBuffer; -class SubstituteData; -class TextCheckingRequest; -class URL; -class VisibleSelection; -struct Highlight; -struct KeypressCommand; -struct TextCheckingResult; - -#if ENABLE(VIDEO) && USE(GSTREAMER) -class MediaPlayerRequestInstallMissingPluginsCallback; -#endif + class GraphicsContext; + class Frame; + class FrameView; + class HTMLPlugInElement; + class IntPoint; + class KeyboardEvent; + class Page; + class PrintContext; + class Range; + class ResourceResponse; + class ResourceRequest; + class SharedBuffer; + class SubstituteData; + class TextCheckingRequest; + class URL; + class VisibleSelection; + struct KeypressCommand; + struct TextCheckingResult; } namespace WebKit { + class DrawingArea; class InjectedBundleBackForwardList; class NotificationPermissionRequestManager; -class PDFPlugin; class PageBanner; +class PageOverlay; class PluginView; -class VisibleContentRectUpdateInfo; +class SessionState; class WebColorChooser; class WebContextMenu; class WebContextMenuItemData; -class WebDocumentLoader; class WebEvent; class WebFrame; class WebFullScreenManager; class WebImage; class WebInspector; class WebInspectorClient; -class WebInspectorUI; -class WebGestureEvent; class WebKeyboardEvent; class WebMouseEvent; class WebNotificationClient; class WebOpenPanelResultListener; class WebPageGroupProxy; -class WebPageOverlay; class WebPopupMenu; -class WebUndoStep; -class WebUserContentController; -class WebVideoFullscreenManager; class WebWheelEvent; -struct AssistedNodeInformation; struct AttributedString; -struct BackForwardListItemState; -struct EditingRange; struct EditorState; struct InteractionInformationAtPosition; struct PrintInfo; struct WebPageCreationParameters; struct WebPreferencesStore; -#if PLATFORM(COCOA) -class RemoteLayerTreeTransaction; -#endif - #if ENABLE(TOUCH_EVENTS) class WebTouchEvent; #endif +typedef Vector<RefPtr<PageOverlay>> PageOverlayList; + class WebPage : public API::ObjectImpl<API::Object::Type::BundlePage>, public IPC::MessageReceiver, public IPC::MessageSender { public: - static Ref<WebPage> create(uint64_t pageID, const WebPageCreationParameters&); + static PassRefPtr<WebPage> create(uint64_t pageID, const WebPageCreationParameters&); virtual ~WebPage(); void reinitializeWebPage(const WebPageCreationParameters&); @@ -216,10 +181,8 @@ public: WebCore::Page* corePage() const { return m_page.get(); } uint64_t pageID() const { return m_pageID; } - WebCore::SessionID sessionID() const { return m_page->sessionID(); } - bool usesEphemeralSession() const { return m_page->usesEphemeralSession(); } - - void setSessionID(WebCore::SessionID); + uint64_t sessionID() const; + void setSessionID(uint64_t sessionID) { m_sessionID = sessionID; } void setSize(const WebCore::IntSize&); const WebCore::IntSize& size() const { return m_viewSize; } @@ -239,23 +202,8 @@ public: void centerSelectionInVisibleArea(); -#if PLATFORM(COCOA) - void willCommitLayerTree(RemoteLayerTreeTransaction&); - void didFlushLayerTreeAtTime(std::chrono::milliseconds); -#endif - - enum class LazyCreationPolicy { UseExistingOnly, CreateIfNeeded }; - - WebInspector* inspector(LazyCreationPolicy = LazyCreationPolicy::CreateIfNeeded); - WebInspectorUI* inspectorUI(); - bool isInspectorPage() { return !!m_inspectorUI; } - -#if PLATFORM(IOS) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)) - WebVideoFullscreenManager* videoFullscreenManager(); -#endif -#if PLATFORM(IOS) - void setAllowsMediaDocumentInlinePlayback(bool); - bool allowsMediaDocumentInlinePlayback() const { return m_allowsMediaDocumentInlinePlayback; } +#if ENABLE(INSPECTOR) + WebInspector* inspector(); #endif #if ENABLE(FULLSCREEN_API) @@ -265,21 +213,24 @@ public: // -- Called by the DrawingArea. // FIXME: We could genericize these into a DrawingArea client interface. Would that be beneficial? void drawRect(WebCore::GraphicsContext&, const WebCore::IntRect&); + void drawPageOverlay(PageOverlay*, WebCore::GraphicsContext&, const WebCore::IntRect&); void layoutIfNeeded(); // -- Called from WebCore clients. +#if PLATFORM(MAC) + bool handleEditingKeyboardEvent(WebCore::KeyboardEvent*, bool saveCommands); +#elif !PLATFORM(GTK) bool handleEditingKeyboardEvent(WebCore::KeyboardEvent*); +#endif void didStartPageTransition(); void didCompletePageTransition(); void didCommitLoad(WebFrame*); - void willReplaceMultipartContent(const WebFrame&); - void didReplaceMultipartContent(const WebFrame&); void didFinishLoad(WebFrame*); void show(); String userAgent(const WebCore::URL&) const; - String userAgent(WebFrame*, const WebCore::URL&) const; String platformUserAgent(const WebCore::URL&) const; + WebCore::IntRect windowResizerRect() const; WebCore::KeyboardUIMode keyboardUIMode(); WebUndoStep* webUndoStep(uint64_t); @@ -299,33 +250,33 @@ public: WebOpenPanelResultListener* activeOpenPanelResultListener() const { return m_activeOpenPanelResultListener.get(); } void setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener>); - void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; - void didReceiveSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&) override; + void didReceiveMessage(IPC::Connection*, IPC::MessageDecoder&) override; + void didReceiveSyncMessage(IPC::Connection*, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&) override; // -- InjectedBundle methods #if ENABLE(CONTEXT_MENUS) - void setInjectedBundleContextMenuClient(std::unique_ptr<API::InjectedBundle::PageContextMenuClient>); + void initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClientBase*); #endif void initializeInjectedBundleEditorClient(WKBundlePageEditorClientBase*); - void setInjectedBundleFormClient(std::unique_ptr<API::InjectedBundle::FormClient>); + void initializeInjectedBundleFormClient(WKBundlePageFormClientBase*); void initializeInjectedBundleLoaderClient(WKBundlePageLoaderClientBase*); void initializeInjectedBundlePolicyClient(WKBundlePagePolicyClientBase*); void initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClientBase*); - void setInjectedBundleUIClient(std::unique_ptr<API::InjectedBundle::PageUIClient>); + void initializeInjectedBundleUIClient(WKBundlePageUIClientBase*); #if ENABLE(FULLSCREEN_API) void initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClientBase*); #endif void initializeInjectedBundleDiagnosticLoggingClient(WKBundlePageDiagnosticLoggingClientBase*); #if ENABLE(CONTEXT_MENUS) - API::InjectedBundle::PageContextMenuClient& injectedBundleContextMenuClient() { return *m_contextMenuClient.get(); } + InjectedBundlePageContextMenuClient& injectedBundleContextMenuClient() { return m_contextMenuClient; } #endif InjectedBundlePageEditorClient& injectedBundleEditorClient() { return m_editorClient; } - API::InjectedBundle::FormClient& injectedBundleFormClient() { return *m_formClient.get(); } + InjectedBundlePageFormClient& injectedBundleFormClient() { return m_formClient; } InjectedBundlePageLoaderClient& injectedBundleLoaderClient() { return m_loaderClient; } InjectedBundlePagePolicyClient& injectedBundlePolicyClient() { return m_policyClient; } InjectedBundlePageResourceLoadClient& injectedBundleResourceLoadClient() { return m_resourceLoadClient; } - API::InjectedBundle::PageUIClient& injectedBundleUIClient() { return *m_uiClient.get(); } + InjectedBundlePageUIClient& injectedBundleUIClient() { return m_uiClient; } InjectedBundlePageDiagnosticLoggingClient& injectedBundleDiagnosticLoggingClient() { return m_logDiagnosticMessageClient; } #if ENABLE(FULLSCREEN_API) InjectedBundlePageFullScreenClient& injectedBundleFullScreenClient() { return m_fullScreenClient; } @@ -335,7 +286,7 @@ public: WebFrame* mainWebFrame() const { return m_mainFrame.get(); } - WebCore::MainFrame* mainFrame() const; // May return 0. + WebCore::Frame* mainFrame() const; // May return 0. WebCore::FrameView* mainFrameView() const; // May return 0. PassRefPtr<WebCore::Range> currentSelectionAsRange(); @@ -346,12 +297,9 @@ public: #if ENABLE(WEBGL) WebCore::WebGLLoadPolicy webGLPolicyForURL(WebFrame*, const String&); - WebCore::WebGLLoadPolicy resolveWebGLPolicyForURL(WebFrame*, const String&); #endif // ENABLE(WEBGL) - enum class IncludePostLayoutDataHint { No, Yes }; - EditorState editorState(IncludePostLayoutDataHint = IncludePostLayoutDataHint::Yes) const; - void sendPostLayoutEditorStateIfNeeded(); + EditorState editorState() const; String renderTreeExternalRepresentation() const; String renderTreeExternalRepresentationForPrinting() const; @@ -360,7 +308,7 @@ public: void setTracksRepaints(bool); bool isTrackingRepaints() const; void resetTrackedRepaints(); - Ref<API::Array> trackedRepaintRects(); + PassRefPtr<API::Array> trackedRepaintRects(); void executeEditingCommand(const String& commandName, const String& argument); bool isEditingCommandEnabled(const String& commandName); @@ -374,60 +322,52 @@ public: double pageZoomFactor() const; void setPageZoomFactor(double); void setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor); - void windowScreenDidChange(uint32_t); + void windowScreenDidChange(uint64_t); void scalePage(double scale, const WebCore::IntPoint& origin); - void scalePageInViewCoordinates(double scale, WebCore::IntPoint centerInViewCoordinates); double pageScaleFactor() const; - double totalScaleFactor() const; - double viewScaleFactor() const; - void scaleView(double scale); void setUseFixedLayout(bool); bool useFixedLayout() const { return m_useFixedLayout; } void setFixedLayoutSize(const WebCore::IntSize&); - WebCore::IntSize fixedLayoutSize() const; void listenForLayoutMilestones(uint32_t /* LayoutMilestones */); void setSuppressScrollbarAnimations(bool); - - void setEnableVerticalRubberBanding(bool); - void setEnableHorizontalRubberBanding(bool); - + void setBackgroundExtendsBeyondPage(bool); void setPaginationMode(uint32_t /* WebCore::Pagination::Mode */); void setPaginationBehavesLikeColumns(bool); void setPageLength(double); void setGapBetweenPages(double); - void setPaginationLineGridEnabled(bool); - - void postInjectedBundleMessage(const String& messageName, const UserData&); + + void postInjectedBundleMessage(const String& messageName, IPC::MessageDecoder&); bool drawsBackground() const { return m_drawsBackground; } + bool drawsTransparentBackground() const { return m_drawsTransparentBackground; } void setUnderlayColor(const WebCore::Color& color) { m_underlayColor = color; } WebCore::Color underlayColor() const { return m_underlayColor; } void stopLoading(); void stopLoadingFrame(uint64_t frameID); - bool defersLoading() const; void setDefersLoading(bool deferLoading); +#if USE(ACCELERATED_COMPOSITING) void enterAcceleratedCompositingMode(WebCore::GraphicsLayer*); void exitAcceleratedCompositingMode(); +#endif void addPluginView(PluginView*); void removePluginView(PluginView*); bool isVisible() const { return m_viewState & WebCore::ViewState::IsVisible; } - bool isVisibleOrOccluded() const { return m_viewState & WebCore::ViewState::IsVisibleOrOccluded; } LayerHostingMode layerHostingMode() const { return m_layerHostingMode; } void setLayerHostingMode(unsigned); -#if PLATFORM(COCOA) +#if PLATFORM(MAC) void updatePluginsActiveAndFocusedState(); const WebCore::FloatRect& windowFrameInScreenCoordinates() const { return m_windowFrameInScreenCoordinates; } const WebCore::FloatRect& windowFrameInUnflippedScreenCoordinates() const { return m_windowFrameInUnflippedScreenCoordinates; } @@ -441,10 +381,14 @@ public: #endif // !PLATFORM(IOS) void updateHeaderAndFooterLayersForDeviceScaleChange(float scaleFactor); -#endif // PLATFORM(COCOA) +#endif // PLATFORM(MAC) bool windowIsFocused() const; bool windowAndWebPageAreFocused() const; + void installPageOverlay(PassRefPtr<PageOverlay>, bool shouldFadeIn = false); + void uninstallPageOverlay(PageOverlay*, bool shouldFadeOut = false); + bool hasPageOverlay() const { return m_pageOverlays.size(); } + PageOverlayList& pageOverlays() { return m_pageOverlays; } #if !PLATFORM(IOS) void setHeaderPageBanner(PassRefPtr<PageBanner>); @@ -454,20 +398,12 @@ public: void hidePageBanners(); void showPageBanners(); - #endif // !PLATFORM(IOS) - WebCore::IntPoint screenToRootView(const WebCore::IntPoint&); - WebCore::IntRect rootViewToScreen(const WebCore::IntRect&); - -#if PLATFORM(IOS) - WebCore::IntPoint accessibilityScreenToRootView(const WebCore::IntPoint&); - WebCore::IntRect rootViewToAccessibilityScreen(const WebCore::IntRect&); -#endif - - PassRefPtr<WebImage> scaledSnapshotWithOptions(const WebCore::IntRect&, double additionalScaleFactor, SnapshotOptions); - PassRefPtr<WebImage> snapshotAtSize(const WebCore::IntRect&, const WebCore::IntSize& bitmapSize, SnapshotOptions); - PassRefPtr<WebImage> snapshotNode(WebCore::Node&, SnapshotOptions, unsigned maximumPixelCount = std::numeric_limits<unsigned>::max()); + WebCore::IntPoint screenToWindow(const WebCore::IntPoint&); + WebCore::IntRect windowToScreen(const WebCore::IntRect&); + + PassRefPtr<WebImage> scaledSnapshotWithOptions(const WebCore::IntRect&, double scaleFactor, SnapshotOptions); static const WebEvent* currentEvent(); @@ -477,116 +413,37 @@ public: GeolocationPermissionRequestManager& geolocationPermissionRequestManager() { return m_geolocationPermissionRequestManager; } #endif -#if PLATFORM(IOS) || PLATFORM(EFL) - void savePageState(WebCore::HistoryItem&); - void restorePageState(const WebCore::HistoryItem&); -#endif - -#if ENABLE(MEDIA_STREAM) - UserMediaPermissionRequestManager& userMediaPermissionRequestManager() { return m_userMediaPermissionRequestManager; } -#endif - #if PLATFORM(IOS) - WebCore::FloatSize screenSize() const; - WebCore::FloatSize availableScreenSize() const; - int32_t deviceOrientation() const { return m_deviceOrientation; } - void viewportPropertiesDidChange(const WebCore::ViewportArguments&); - void didReceiveMobileDocType(bool); - - void setUseTestingViewportConfiguration(bool useTestingViewport) { m_useTestingViewportConfiguration = useTestingViewport; } - bool isUsingTestingViewportConfiguration() const { return m_useTestingViewportConfiguration; } - - double minimumPageScaleFactor() const; - double maximumPageScaleFactor() const; - bool allowsUserScaling() const; - bool hasStablePageScaleFactor() const { return m_hasStablePageScaleFactor; } - - void handleTap(const WebCore::IntPoint&, uint64_t lastLayerTreeTransactionId); - void potentialTapAtPosition(uint64_t requestID, const WebCore::FloatPoint&); - void commitPotentialTap(uint64_t lastLayerTreeTransactionId); - void commitPotentialTapFailed(); - void cancelPotentialTap(); - void cancelPotentialTapInFrame(WebFrame&); + void handleTap(const WebCore::IntPoint&); void tapHighlightAtPosition(uint64_t requestID, const WebCore::FloatPoint&); - void inspectorNodeSearchMovedToPosition(const WebCore::FloatPoint&); - void inspectorNodeSearchEndedAtPosition(const WebCore::FloatPoint&); - void blurAssistedNode(); - void selectWithGesture(const WebCore::IntPoint&, uint32_t granularity, uint32_t gestureType, uint32_t gestureState, bool isInteractingWithAssistedNode, uint64_t callbackID); + void selectWithGesture(const WebCore::IntPoint&, uint32_t granularity, uint32_t gestureType, uint32_t gestureState, uint64_t callbackID); void updateSelectionWithTouches(const WebCore::IntPoint& point, uint32_t touches, bool baseIsStart, uint64_t callbackID); - void updateBlockSelectionWithTouch(const WebCore::IntPoint&, uint32_t touch, uint32_t handlePosition); void selectWithTwoTouches(const WebCore::IntPoint& from, const WebCore::IntPoint& to, uint32_t gestureType, uint32_t gestureState, uint64_t callbackID); void extendSelection(uint32_t granularity); - void selectWordBackward(); - void moveSelectionByOffset(int32_t offset, uint64_t callbackID); - void selectTextWithGranularityAtPoint(const WebCore::IntPoint&, uint32_t granularity, bool isInteractingWithAssistedNode, uint64_t callbackID); - void selectPositionAtBoundaryWithDirection(const WebCore::IntPoint&, uint32_t granularity, uint32_t direction, bool isInteractingWithAssistedNode, uint64_t callbackID); - void moveSelectionAtBoundaryWithDirection(uint32_t granularity, uint32_t direction, uint64_t callbackID); - void selectPositionAtPoint(const WebCore::IntPoint&, bool isInteractingWithAssistedNode, uint64_t callbackID); - void beginSelectionInDirection(uint32_t direction, uint64_t callbackID); - void updateSelectionWithExtentPoint(const WebCore::IntPoint&, bool isInteractingWithAssistedNode, uint64_t callbackID); - void updateSelectionWithExtentPointAndBoundary(const WebCore::IntPoint&, uint32_t granularity, bool isInteractingWithAssistedNode, uint64_t callbackID); - void elementDidFocus(WebCore::Node*); void elementDidBlur(WebCore::Node*); - void requestDictationContext(uint64_t callbackID); - void replaceDictatedText(const String& oldText, const String& newText); - void replaceSelectedText(const String& oldText, const String& newText); void requestAutocorrectionData(const String& textForAutocorrection, uint64_t callbackID); void applyAutocorrection(const String& correction, const String& originalText, uint64_t callbackID); - void syncApplyAutocorrection(const String& correction, const String& originalText, bool& correctionApplied); void requestAutocorrectionContext(uint64_t callbackID); void getAutocorrectionContext(String& beforeText, String& markedText, String& selectedText, String& afterText, uint64_t& location, uint64_t& length); + void insertText(const String& text, uint64_t replacementRangeStart, uint64_t replacementRangeEnd); + void setComposition(const String& text, Vector<WebCore::CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd); + void confirmComposition(); void getPositionInformation(const WebCore::IntPoint&, InteractionInformationAtPosition&); void requestPositionInformation(const WebCore::IntPoint&); - void startInteractionWithElementAtPosition(const WebCore::IntPoint&); - void stopInteraction(); - void performActionOnElement(uint32_t action); - void focusNextAssistedNode(bool isForward, uint64_t callbackID); - void setAssistedNodeValue(const String&); - void setAssistedNodeValueAsNumber(double); - void setAssistedNodeSelectedIndex(uint32_t index, bool allowMultipleSelection); - void resetAssistedNodeForFrame(WebFrame*); - WebCore::IntRect rectForElementAtInteractionLocation(); - void updateSelectionAppearance(); - void getLookupContextAtPoint(const WebCore::IntPoint, uint64_t callbackID); - -#if ENABLE(IOS_TOUCH_EVENTS) - void dispatchAsynchronousTouchEvents(const Vector<WebTouchEvent, 1>& queue); #endif - void contentSizeCategoryDidChange(const String&); - void executeEditCommandWithCallback(const String&, uint64_t callbackID); - - std::chrono::milliseconds eventThrottlingDelay() const; - - void showInspectorHighlight(const WebCore::Highlight&); - void hideInspectorHighlight(); - - void showInspectorIndication(); - void hideInspectorIndication(); - - void enableInspectorNodeSearch(); - void disableInspectorNodeSearch(); -#endif - - void setLayerTreeStateIsFrozen(bool); - bool markLayersVolatileImmediatelyIfPossible(); - NotificationPermissionRequestManager* notificationPermissionRequestManager(); void pageDidScroll(); -#if USE(COORDINATED_GRAPHICS) +#if USE(TILED_BACKING_STORE) void pageDidRequestScroll(const WebCore::IntPoint&); void setFixedVisibleContentRect(const WebCore::IntRect&); void sendViewportAttributesChanged(); #endif -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) - void commitPageTransitionViewport(); -#endif - #if ENABLE(CONTEXT_MENUS) WebContextMenu* contextMenu(); WebContextMenu* contextMenuAtPointInWindow(const WebCore::IntPoint&); @@ -625,21 +482,19 @@ public: void setThemePath(const String&); #endif +#if USE(TILED_BACKING_STORE) + void commitPageTransitionViewport(); +#endif + #if PLATFORM(GTK) - void setComposition(const String& text, const Vector<WebCore::CompositionUnderline>& underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementRangeStart, uint64_t replacementRangeLength); + void setComposition(const String& text, Vector<WebCore::CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementRangeStart, uint64_t replacementRangeEnd); void confirmComposition(const String& text, int64_t selectionStart, int64_t selectionLength); void cancelComposition(); #endif -#if PLATFORM (GTK) && HAVE(GTK_GESTURES) - void getCenterForZoomGesture(const WebCore::IntPoint& centerInViewCoordinates, WebCore::IntPoint& result); -#endif - - void didApplyStyle(); void didChangeSelection(); - void discardedComposition(); -#if PLATFORM(COCOA) +#if PLATFORM(MAC) void registerUIProcessAccessibilityTokens(const IPC::DataReference& elemenToken, const IPC::DataReference& windowToken); WKAccessibilityWebPageObject* accessibilityRemoteObject(); NSObject *accessibilityObjectForMainFramePlugin(); @@ -647,35 +502,33 @@ public: void sendComplexTextInputToPlugin(uint64_t pluginComplexTextInputIdentifier, const String& textInput); - void insertTextAsync(const String& text, const EditingRange& replacementRange, bool registerUndoGroup = false, uint32_t editingRangeIsRelativeTo = (uint32_t)EditingRangeIsRelativeTo::EditableRoot); - void getMarkedRangeAsync(uint64_t callbackID); - void getSelectedRangeAsync(uint64_t callbackID); - void characterIndexForPointAsync(const WebCore::IntPoint&, uint64_t callbackID); - void firstRectForCharacterRangeAsync(const EditingRange&, uint64_t callbackID); - void setCompositionAsync(const String& text, Vector<WebCore::CompositionUnderline> underlines, const EditingRange& selectionRange, const EditingRange& replacementRange); - void confirmCompositionAsync(); - -#if PLATFORM(MAC) - void insertDictatedTextAsync(const String& text, const EditingRange& replacementRange, const Vector<WebCore::DictationAlternative>& dictationAlternativeLocations, bool registerUndoGroup = false); - void attributedSubstringForCharacterRangeAsync(const EditingRange&, uint64_t callbackID); - void fontAtSelection(uint64_t callbackID); -#endif - + void cancelComposition(EditorState& newState); +#if !PLATFORM(IOS) + void insertText(const String& text, uint64_t replacementRangeStart, uint64_t replacementRangeEnd, bool& handled, EditorState& newState); + void setComposition(const String& text, Vector<WebCore::CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementRangeStart, uint64_t replacementRangeEnd, EditorState& newState); + void confirmComposition(EditorState& newState); +#endif + void getMarkedRange(uint64_t& location, uint64_t& length); + void getSelectedRange(uint64_t& location, uint64_t& length); + void getAttributedSubstringFromRange(uint64_t location, uint64_t length, AttributedString&); + void characterIndexForPoint(const WebCore::IntPoint point, uint64_t& result); + void firstRectForCharacterRange(uint64_t location, uint64_t length, WebCore::IntRect& resultRect); + void executeKeypressCommands(const Vector<WebCore::KeypressCommand>&, bool& handled, EditorState& newState); void readSelectionFromPasteboard(const WTF::String& pasteboardName, bool& result); void getStringSelectionForPasteboard(WTF::String& stringValue); void getDataSelectionForPasteboard(const WTF::String pasteboardType, SharedMemory::Handle& handle, uint64_t& size); void shouldDelayWindowOrderingEvent(const WebKit::WebMouseEvent&, bool& result); void acceptsFirstMouse(int eventNumber, const WebKit::WebMouseEvent&, bool& result); bool performNonEditingBehaviorForSelector(const String&, WebCore::KeyboardEvent*); - -#if ENABLE(SERVICE_CONTROLS) - void replaceSelectionWithPasteboardData(const Vector<String>& types, const IPC::DataReference&); -#endif - + void insertDictatedText(const String& text, uint64_t replacementRangeStart, uint64_t replacementRangeEnd, const Vector<WebCore::DictationAlternative>& dictationAlternativeLocations, bool& handled, EditorState& newState); #elif PLATFORM(EFL) void confirmComposition(const String& compositionString); void setComposition(const WTF::String& compositionString, const WTF::Vector<WebCore::CompositionUnderline>& underlines, uint64_t cursorPosition); void cancelComposition(); +#elif PLATFORM(GTK) +#if USE(TEXTURE_MAPPER_GL) + void setAcceleratedCompositingWindowId(int64_t nativeWindowHandle); +#endif #endif #if HAVE(ACCESSIBILITY) && (PLATFORM(GTK) || PLATFORM(EFL)) @@ -690,12 +543,13 @@ public: // any synchronous messages, and should be removed when <rdar://problem/8775115> is fixed. void dummy(bool&); -#if PLATFORM(COCOA) +#if PLATFORM(MAC) + void performDictionaryLookupForSelection(WebCore::Frame*, const WebCore::VisibleSelection&); + bool isSpeaking(); void speak(const String&); void stopSpeaking(); - void performDictionaryLookupForSelection(WebCore::Frame*, const WebCore::VisibleSelection&, WebCore::TextIndicatorPresentationTransition); #endif bool isSmartInsertDeleteEnabled(); @@ -706,7 +560,6 @@ public: void replaceSelectionWithText(WebCore::Frame*, const String&); void clearSelection(); - void restoreSelectionInFocusedEditableElement(); #if ENABLE(DRAG_SUPPORT) #if PLATFORM(GTK) @@ -718,44 +571,24 @@ public: void willPerformLoadDragDestinationAction(); void mayPerformUploadDragDestinationAction(); - - void willStartDrag() { ASSERT(!m_isStartingDrag); m_isStartingDrag = true; } - void didStartDrag() { ASSERT(m_isStartingDrag); m_isStartingDrag = false; } #endif // ENABLE(DRAG_SUPPORT) void beginPrinting(uint64_t frameID, const PrintInfo&); void endPrinting(); void computePagesForPrinting(uint64_t frameID, const PrintInfo&, uint64_t callbackID); - void computePagesForPrintingImpl(uint64_t frameID, const PrintInfo&, Vector<WebCore::IntRect>& pageRects, double& totalScaleFactor); -#if PLATFORM(COCOA) +#if PLATFORM(MAC) void drawRectToImage(uint64_t frameID, const PrintInfo&, const WebCore::IntRect&, const WebCore::IntSize&, uint64_t callbackID); void drawPagesToPDF(uint64_t frameID, const PrintInfo&, uint32_t first, uint32_t count, uint64_t callbackID); - void drawPagesToPDFImpl(uint64_t frameID, const PrintInfo&, uint32_t first, uint32_t count, RetainPtr<CFMutableDataRef>& pdfPageData); -#if PLATFORM(IOS) - void computePagesForPrintingAndStartDrawingToPDF(uint64_t frameID, const PrintInfo&, uint32_t firstPage, PassRefPtr<Messages::WebPage::ComputePagesForPrintingAndStartDrawingToPDF::DelayedReply>); -#endif #elif PLATFORM(GTK) void drawPagesForPrinting(uint64_t frameID, const PrintInfo&, uint64_t callbackID); void didFinishPrintOperation(const WebCore::ResourceError&, uint64_t callbackID); #endif - void addResourceRequest(unsigned long, const WebCore::ResourceRequest&); - void removeResourceRequest(unsigned long); - void setMediaVolume(float); - void setMuted(bool); void setMayStartMediaWhenInWindow(bool); -#if ENABLE(MEDIA_SESSION) - void handleMediaEvent(uint32_t /* WebCore::MediaEventType */); - void setVolumeOfMediaElement(double, uint64_t); -#endif - void updateMainFrameScrollOffsetPinning(); - bool mainFrameHasCustomContentProvider() const; - void addMIMETypeWithCustomContentProvider(const String&); - void mainFrameDidLayout(); bool canRunBeforeUnloadConfirmPanel() const { return m_canRunBeforeUnloadConfirmPanel; } @@ -769,11 +602,13 @@ public: void setDeviceScaleFactor(float); float deviceScaleFactor() const; + void setMemoryCacheMessagesEnabled(bool); + void forceRepaintWithoutCallback(); void unmarkAllMisspellings(); void unmarkAllBadGrammar(); -#if PLATFORM(COCOA) +#if PLATFORM(MAC) void handleAlternativeTextUIResult(const String&); #endif @@ -788,41 +623,21 @@ public: void wheelEvent(const WebWheelEvent&); - void wheelEventHandlersChanged(bool); + void numWheelEventHandlersChanged(unsigned); void recomputeShortCircuitHorizontalWheelEventsState(); -#if ENABLE(MAC_GESTURE_EVENTS) - void gestureEvent(const WebGestureEvent&); -#endif - + void setVisibilityStatePrerender(); void updateVisibilityState(bool isInitialState = false); #if PLATFORM(IOS) - void setViewportConfigurationMinimumLayoutSize(const WebCore::FloatSize&); - void setMaximumUnobscuredSize(const WebCore::FloatSize&); - void setDeviceOrientation(int32_t); - void dynamicViewportSizeUpdate(const WebCore::FloatSize& minimumLayoutSize, const WebCore::FloatSize& maximumUnobscuredSize, const WebCore::FloatRect& targetExposedContentRect, const WebCore::FloatRect& targetUnobscuredRect, const WebCore::FloatRect& targetUnobscuredRectInScrollViewCoordinates, double scale, int32_t deviceOrientation, uint64_t dynamicViewportSizeUpdateID); - void synchronizeDynamicViewportUpdate(double& newTargetScale, WebCore::FloatPoint& newScrollPosition, uint64_t& nextValidLayerTreeTransactionID); - void updateVisibleContentRects(const VisibleContentRectUpdateInfo&, double oldestTimestamp); - bool scaleWasSetByUIProcess() const { return m_scaleWasSetByUIProcess; } - void willStartUserTriggeredZooming(); - void applicationWillResignActive(); - void applicationDidEnterBackground(bool isSuspendedUnderLock); - void applicationWillEnterForeground(bool isSuspendedUnderLock); - void applicationDidBecomeActive(); - void zoomToRect(WebCore::FloatRect, double minimumScale, double maximumScale); - void completePendingSyntheticClickForContentChangeObserver(); -#endif - -#if ENABLE(IOS_TOUCH_EVENTS) - void dispatchTouchEvent(const WebTouchEvent&, bool& handled); + void didFinishScrolling(const WebCore::FloatPoint& contentOffset); + void didFinishZooming(float); #endif #if PLATFORM(GTK) && USE(TEXTURE_MAPPER_GL) uint64_t nativeWindowHandle() { return m_nativeWindowHandle; } #endif - bool shouldUseCustomContentProviderForResponse(const WebCore::ResourceResponse&); bool canPluginHandleResponse(const WebCore::ResourceResponse& response); bool asynchronousPluginInitializationEnabled() const { return m_asynchronousPluginInitializationEnabled; } @@ -837,14 +652,14 @@ public: bool scrollingPerformanceLoggingEnabled() const { return m_scrollingPerformanceLoggingEnabled; } void setScrollingPerformanceLoggingEnabled(bool); -#if PLATFORM(COCOA) +#if PLATFORM(MAC) bool shouldUsePDFPlugin() const; bool pdfPluginEnabled() const { return m_pdfPluginEnabled; } void setPDFPluginEnabled(bool enabled) { m_pdfPluginEnabled = enabled; } #endif void savePDFToFileInDownloadsFolder(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size); -#if PLATFORM(COCOA) +#if PLATFORM(MAC) void savePDFToTemporaryFolderAndOpenWithNativeApplication(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size, const String& pdfUUID); #endif @@ -867,12 +682,6 @@ public: void determinePrimarySnapshottedPlugInTimerFired(); void resetPrimarySnapshottedPlugIn(); bool matchesPrimaryPlugIn(const String& pageOrigin, const String& pluginOrigin, const String& mimeType) const; - bool plugInIntersectsSearchRect(WebCore::HTMLPlugInImageElement& pluginImageElement); - bool plugInIsPrimarySize(WebCore::HTMLPlugInImageElement& pluginImageElement, unsigned &pluginArea); -#endif - -#if ENABLE(DATA_DETECTION) - void setDataDetectionResults(NSArray *); #endif unsigned extendIncrementalRenderingSuppression(); @@ -882,47 +691,10 @@ public: WebCore::ScrollPinningBehavior scrollPinningBehavior() { return m_scrollPinningBehavior; } void setScrollPinningBehavior(uint32_t /* WebCore::ScrollPinningBehavior */ pinning); - WTF::Optional<WebCore::ScrollbarOverlayStyle> scrollbarOverlayStyle() { return m_scrollbarOverlayStyle; } - void setScrollbarOverlayStyle(WTF::Optional<uint32_t /* WebCore::ScrollbarOverlayStyle */> scrollbarStyle); - - Ref<WebCore::DocumentLoader> createDocumentLoader(WebCore::Frame&, const WebCore::ResourceRequest&, const WebCore::SubstituteData&); - void updateCachedDocumentLoader(WebDocumentLoader&, WebCore::Frame&); - - void getBytecodeProfile(uint64_t callbackID); - -#if ENABLE(SERVICE_CONTROLS) || ENABLE(TELEPHONE_NUMBER_DETECTION) - void handleTelephoneNumberClick(const String& number, const WebCore::IntPoint&); - void handleSelectionServiceClick(WebCore::FrameSelection&, const Vector<String>& telephoneNumbers, const WebCore::IntPoint&); -#endif - - void didChangeScrollOffsetForFrame(WebCore::Frame*); - - void setMainFrameProgressCompleted(bool completed) { m_mainFrameProgressCompleted = completed; } - bool shouldDispatchFakeMouseMoveEvents() const { return m_shouldDispatchFakeMouseMoveEvents; } - - void setPageActivityState(WebCore::PageActivityState::Flags); + WKTypeRef pageOverlayCopyAccessibilityAttributeValue(WKStringRef attribute, WKTypeRef parameter); + WKArrayRef pageOverlayCopyAccessibilityAttributesNames(bool parameterizedNames); - void postMessage(const String& messageName, API::Object* messageBody); - void postSynchronousMessageForTesting(const String& messageName, API::Object* messageBody, RefPtr<API::Object>& returnData); - -#if PLATFORM(GTK) - void setInputMethodState(bool); -#endif - - void imageOrMediaDocumentSizeChanged(const WebCore::IntSize&); -#if ENABLE(VIDEO) -#if USE(GSTREAMER) - void requestInstallMissingMediaPlugins(const String& details, const String& description, WebCore::MediaPlayerRequestInstallMissingPluginsCallback&); -#endif -#endif - - void addUserScript(const String& source, WebCore::UserContentInjectedFrames, WebCore::UserScriptInjectionTime); - void addUserStyleSheet(const String& source, WebCore::UserContentInjectedFrames); - void removeAllUserContent(); - - void dispatchDidLayout(WebCore::LayoutMilestones); - - void didRestoreScrollPosition(); + PassRefPtr<WebCore::DocumentLoader> createDocumentLoader(WebCore::Frame&, const WebCore::ResourceRequest&, const WebCore::SubstituteData&); private: WebPage(uint64_t pageID, const WebPageCreationParameters&); @@ -932,35 +704,11 @@ private: virtual uint64_t messageSenderDestinationID() override; void platformInitialize(); - void platformDetach(); - void platformEditorState(WebCore::Frame&, EditorState& result, IncludePostLayoutDataHint) const; - void didReceiveWebPageMessage(IPC::Connection&, IPC::MessageDecoder&); - void didReceiveSyncWebPageMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&); + void didReceiveWebPageMessage(IPC::Connection*, IPC::MessageDecoder&); + void didReceiveSyncWebPageMessage(IPC::Connection*, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&); -#if PLATFORM(IOS) - void resetViewportDefaultConfiguration(WebFrame* mainFrame); - void viewportConfigurationChanged(); - void updateViewportSizeForCSSViewportUnits(); - - static void convertSelectionRectsToRootView(WebCore::FrameView*, Vector<WebCore::SelectionRect>&); - PassRefPtr<WebCore::Range> rangeForWebSelectionAtPosition(const WebCore::IntPoint&, const WebCore::VisiblePosition&, SelectionFlags&); - PassRefPtr<WebCore::Range> rangeForBlockAtPoint(const WebCore::IntPoint&); - void computeExpandAndShrinkThresholdsForHandle(const WebCore::IntPoint&, SelectionHandlePosition, float& growThreshold, float& shrinkThreshold); - PassRefPtr<WebCore::Range> changeBlockSelection(const WebCore::IntPoint&, SelectionHandlePosition, float& growThreshold, float& shrinkThreshold, SelectionFlags&); - PassRefPtr<WebCore::Range> expandedRangeFromHandle(WebCore::Range*, SelectionHandlePosition); - PassRefPtr<WebCore::Range> contractedRangeFromHandle(WebCore::Range* currentRange, SelectionHandlePosition, SelectionFlags&); - void getAssistedNodeInformation(AssistedNodeInformation&); - void platformInitializeAccessibility(); - void handleSyntheticClick(WebCore::Node* nodeRespondingToClick, const WebCore::FloatPoint& location); - void completeSyntheticClick(WebCore::Node* nodeRespondingToClick, const WebCore::FloatPoint& location); - void sendTapHighlightForNodeIfNecessary(uint64_t requestID, WebCore::Node*); - void resetTextAutosizingBeforeLayoutIfNeeded(const WebCore::FloatSize& oldSize, const WebCore::FloatSize& newSize); - WebCore::VisiblePosition visiblePositionInFocusedNodeForPoint(const WebCore::Frame&, const WebCore::IntPoint&, bool isInteractingWithAssistedNode); - PassRefPtr<WebCore::Range> rangeForGranularityAtPoint(const WebCore::Frame&, const WebCore::IntPoint&, uint32_t granularity, bool isInteractingWithAssistedNode); - void volatilityTimerFired(); -#endif -#if !PLATFORM(COCOA) +#if !PLATFORM(MAC) static const char* interpretKeyEvent(const WebCore::KeyboardEvent*); #endif bool performDefaultBehaviorForKeyEvent(const WebKeyboardEvent&); @@ -971,40 +719,44 @@ private: String sourceForFrame(WebFrame*); - void loadDataImpl(uint64_t navigationID, PassRefPtr<WebCore::SharedBuffer>, const String& MIMEType, const String& encodingName, const WebCore::URL& baseURL, const WebCore::URL& failingURL, const UserData&); - void loadString(uint64_t navigationID, const String&, const String& MIMEType, const WebCore::URL& baseURL, const WebCore::URL& failingURL, const UserData&); + void loadDataImpl(PassRefPtr<WebCore::SharedBuffer>, const String& MIMEType, const String& encodingName, const WebCore::URL& baseURL, const WebCore::URL& failingURL, IPC::MessageDecoder&); + void loadString(const String&, const String& MIMEType, const WebCore::URL& baseURL, const WebCore::URL& failingURL, IPC::MessageDecoder&); bool platformHasLocalDataForURL(const WebCore::URL&); // Actions void tryClose(); - void loadRequest(uint64_t navigationID, const WebCore::ResourceRequest&, const SandboxExtension::Handle&, uint64_t shouldOpenExternalURLsPolicy, const UserData&); - void loadData(uint64_t navigationID, const IPC::DataReference&, const String& MIMEType, const String& encodingName, const String& baseURL, const UserData&); - void loadHTMLString(uint64_t navigationID, const String& htmlString, const String& baseURL, const UserData&); - void loadAlternateHTMLString(const String& htmlString, const String& baseURL, const String& unreachableURL, const String& provisionalLoadErrorURL, const UserData&); - void loadPlainTextString(const String&, const UserData&); - void loadWebArchiveData(const IPC::DataReference&, const UserData&); - void navigateToPDFLinkWithSimulatedClick(const String& url, WebCore::IntPoint documentPoint, WebCore::IntPoint screenPoint); - void reload(uint64_t navigationID, bool reloadFromOrigin, bool contentBlockersEnabled, const SandboxExtension::Handle&); - void goForward(uint64_t navigationID, uint64_t); - void goBack(uint64_t navigationID, uint64_t); - void goToBackForwardItem(uint64_t navigationID, uint64_t); + void loadRequest(const WebCore::ResourceRequest&, const SandboxExtension::Handle&, IPC::MessageDecoder&); + void loadData(const IPC::DataReference&, const String& MIMEType, const String& encodingName, const String& baseURL, IPC::MessageDecoder&); + void loadHTMLString(const String& htmlString, const String& baseURL, IPC::MessageDecoder&); + void loadAlternateHTMLString(const String& htmlString, const String& baseURL, const String& unreachableURL, IPC::MessageDecoder&); + void loadPlainTextString(const String&, IPC::MessageDecoder&); + void loadWebArchiveData(const IPC::DataReference&, IPC::MessageDecoder&); + void reload(bool reloadFromOrigin, const SandboxExtension::Handle&); + void goForward(uint64_t); + void goBack(uint64_t); + void goToBackForwardItem(uint64_t); void tryRestoreScrollPosition(); - void setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent&, uint64_t callbackID); - void updateIsInWindow(bool isInitialState = false); - void setViewState(WebCore::ViewState::Flags, bool wantsDidUpdateViewState, const Vector<uint64_t>& callbackIDs); + void setActive(bool); + void setFocused(bool); + void setViewIsVisible(bool); + void setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent&); + void setWindowResizerSize(const WebCore::IntSize&); + void setIsInWindow(bool); + void setIsVisuallyIdle(bool); + void setViewState(WebCore::ViewState::Flags, bool wantsDidUpdateViewState); + void setViewStateInternal(WebCore::ViewState::Flags, bool isInitialState); void validateCommand(const String&, uint64_t); - void executeEditCommand(const String&, const String&); - void setEditable(bool); - - void updateUserActivity(); + void executeEditCommand(const String&); void mouseEvent(const WebMouseEvent&); + void mouseEventSyncForTesting(const WebMouseEvent&, bool&); + void wheelEventSyncForTesting(const WebWheelEvent&, bool&); void keyEvent(const WebKeyboardEvent&); -#if ENABLE(IOS_TOUCH_EVENTS) - void touchEventSync(const WebTouchEvent&, bool& handled); -#elif ENABLE(TOUCH_EVENTS) + void keyEventSyncForTesting(const WebKeyboardEvent&, bool&); +#if ENABLE(TOUCH_EVENTS) void touchEvent(const WebTouchEvent&); + void touchEventSyncForTesting(const WebTouchEvent&, bool& handled); #endif #if ENABLE(CONTEXT_MENUS) void contextMenuHidden() { m_isShowingContextMenu = false; } @@ -1015,26 +767,20 @@ private: void loadURLInFrame(const String&, uint64_t frameID); - enum class WasRestoredByAPIRequest { No, Yes }; - void restoreSessionInternal(const Vector<BackForwardListItemState>&, WasRestoredByAPIRequest); - void restoreSession(const Vector<BackForwardListItemState>&); - void didRemoveBackForwardItem(uint64_t); + uint64_t restoreSession(const SessionState&); + void restoreSessionAndNavigateToCurrentItem(const SessionState&); -#if ENABLE(REMOTE_INSPECTOR) - void setAllowsRemoteInspection(bool); - void setRemoteInspectionNameOverride(const String&); -#endif + void didRemoveBackForwardItem(uint64_t); void setDrawsBackground(bool); - - void setTopContentInset(float); + void setDrawsTransparentBackground(bool); void viewWillStartLiveResize(); void viewWillEndLiveResize(); void getContentsAsString(uint64_t callbackID); #if ENABLE(MHTML) - void getContentsAsMHTMLData(uint64_t callbackID); + void getContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding); #endif void getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID); void getResourceDataFromFrame(uint64_t frameID, const String& resourceURL, uint64_t callbackID); @@ -1045,26 +791,20 @@ private: void getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID); void runJavaScriptInMainFrame(const String&, uint64_t callbackID); void forceRepaint(uint64_t callbackID); - void takeSnapshot(WebCore::IntRect snapshotRect, WebCore::IntSize bitmapSize, uint32_t options, uint64_t callbackID); void preferencesDidChange(const WebPreferencesStore&); void platformPreferencesDidChange(const WebPreferencesStore&); void updatePreferences(const WebPreferencesStore&); - void didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t navigationID, DownloadID); + void didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID); void setUserAgent(const String&); void setCustomTextEncodingName(const String&); void suspendActiveDOMObjectsAndAnimations(); void resumeActiveDOMObjectsAndAnimations(); -#if PLATFORM(COCOA) +#if PLATFORM(MAC) void performDictionaryLookupAtLocation(const WebCore::FloatPoint&); - void performDictionaryLookupOfCurrentSelection(); - void performDictionaryLookupForRange(WebCore::Frame*, WebCore::Range&, NSDictionary *options, WebCore::TextIndicatorPresentationTransition); - WebCore::DictionaryPopupInfo dictionaryPopupInfoForRange(WebCore::Frame*, WebCore::Range&, NSDictionary **options, WebCore::TextIndicatorPresentationTransition); -#if ENABLE(PDFKIT_PLUGIN) - WebCore::DictionaryPopupInfo dictionaryPopupInfoForSelectionInPDFPlugin(PDFSelection *, PDFPlugin&, NSDictionary **options, WebCore::TextIndicatorPresentationTransition); -#endif + void performDictionaryLookupForRange(WebCore::Frame*, WebCore::Range*, NSDictionary *options); void windowAndViewFramesChanged(const WebCore::FloatRect& windowFrameInScreenCoordinates, const WebCore::FloatRect& windowFrameInUnflippedScreenCoordinates, const WebCore::FloatRect& viewFrameInWindowCoordinates, const WebCore::FloatPoint& accessibilityViewCoordinates); @@ -1087,7 +827,7 @@ private: void hideFindUI(); void countStringMatches(const String&, uint32_t findOptions, uint32_t maxMatchCount); -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) +#if USE(COORDINATED_GRAPHICS) void findZoomableAreaForPoint(const WebCore::IntPoint&, const WebCore::IntSize& area); #endif @@ -1098,12 +838,9 @@ private: void failedToShowPopupMenu(); #endif -#if PLATFORM(IOS) - void didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>&, const String& displayString, const IPC::DataReference& iconData); -#endif void didChooseFilesForOpenPanel(const Vector<String>&); void didCancelForOpenPanel(); -#if ENABLE(SANDBOX_EXTENSIONS) +#if ENABLE(WEB_PROCESS_SANDBOX) void extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle&); #endif @@ -1111,11 +848,6 @@ private: void didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed); -#if ENABLE(MEDIA_STREAM) - void didReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed, const String& audioDeviceUID, const String& videoDeviceUID); - void didCompleteUserMediaPermissionCheck(uint64_t userMediaID, bool allowed); -#endif - void advanceToNextMisspelling(bool startBeforeSelection); void changeSpellingToWord(const String& word); #if USE(APPKIT) @@ -1130,54 +862,23 @@ private: void changeSelectedIndex(int32_t index); void setCanStartMediaTimerFired(); + void didUpdateViewStateTimerFired(); bool canHandleUserEvents() const; + void setMainFrameInViewSourceMode(bool); + static bool platformCanHandleRequest(const WebCore::ResourceRequest&); static PluginView* focusedPluginViewForFrame(WebCore::Frame&); static PluginView* pluginViewForFrame(WebCore::Frame*); - static PassRefPtr<WebCore::Range> rangeFromEditingRange(WebCore::Frame&, const EditingRange&, EditingRangeIsRelativeTo = EditingRangeIsRelativeTo::EditableRoot); - void reportUsedFeatures(); -#if PLATFORM(MAC) - void performImmediateActionHitTestAtLocation(WebCore::FloatPoint); - RefPtr<WebCore::Range> lookupTextAtLocation(WebCore::FloatPoint, NSDictionary **options); - void immediateActionDidUpdate(); - void immediateActionDidCancel(); - void immediateActionDidComplete(); - void setFont(const String& fontFamily, double fontSize, uint64_t fontTraits); - - void dataDetectorsDidPresentUI(WebCore::PageOverlay::PageOverlayID); - void dataDetectorsDidChangeUI(WebCore::PageOverlay::PageOverlayID); - void dataDetectorsDidHideUI(WebCore::PageOverlay::PageOverlayID); - - void handleAcceptedCandidate(WebCore::TextCheckingResult); -#endif - - void setShouldDispatchFakeMouseMoveEvents(bool dispatch) { m_shouldDispatchFakeMouseMoveEvents = dispatch; } - -#if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS) - void playbackTargetSelected(uint64_t, const WebCore::MediaPlaybackTargetContext& outputDevice) const; - void playbackTargetAvailabilityDidChange(uint64_t, bool); - void setShouldPlayToPlaybackTarget(uint64_t, bool); -#endif - - void clearWheelEventTestTrigger(); - - void setShouldScaleViewToFitDocument(bool); - - void pageStoppedScrolling(); - -#if ENABLE(VIDEO) && USE(GSTREAMER) - void didEndRequestInstallMissingMediaPlugins(uint32_t result); -#endif - uint64_t m_pageID; + uint64_t m_sessionID; - std::unique_ptr<WebCore::Page> m_page; + OwnPtr<WebCore::Page> m_page; RefPtr<WebFrame> m_mainFrame; RefPtr<InjectedBundleBackForwardList> m_backForwardList; @@ -1196,6 +897,7 @@ private: bool m_useFixedLayout; bool m_drawsBackground; + bool m_drawsTransparentBackground; WebCore::Color m_underlayColor; @@ -1212,10 +914,6 @@ private: bool m_mainFrameIsScrollable; -#if PLATFORM(IOS) - bool m_ignoreViewportScalingConstraints { false }; -#endif - #if ENABLE(PRIMARY_SNAPSHOTTED_PLUGIN_HEURISTIC) bool m_readyToFindPrimarySnapshottedPlugin; bool m_didFindPrimarySnapshottedPlugin; @@ -1229,7 +927,7 @@ private: // The layer hosting mode. LayerHostingMode m_layerHostingMode; -#if PLATFORM(COCOA) +#if PLATFORM(MAC) bool m_pdfPluginEnabled; bool m_hasCachedWindowFrame; @@ -1248,7 +946,11 @@ private: RetainPtr<WKAccessibilityWebPageObject> m_mockAccessibilityElement; + WebCore::KeyboardEvent* m_keyboardEventBeingInterpreted; + +#if !PLATFORM(IOS) ViewGestureGeometryCollector m_viewGestureGeometryCollector; +#endif #elif HAVE(ACCESSIBILITY) && (PLATFORM(GTK) || PLATFORM(EFL)) GRefPtr<WebPageAccessibilityObject> m_accessibilityObject; @@ -1265,33 +967,32 @@ private: #endif // !PLATFORM(IOS) RunLoop::Timer<WebPage> m_setCanStartMediaTimer; + RunLoop::Timer<WebPage> m_sendDidUpdateViewStateTimer; bool m_mayStartMediaWhenInWindow; HashMap<uint64_t, RefPtr<WebUndoStep>> m_undoStepMap; + WebCore::IntSize m_windowResizerSize; + #if ENABLE(CONTEXT_MENUS) - std::unique_ptr<API::InjectedBundle::PageContextMenuClient> m_contextMenuClient; + InjectedBundlePageContextMenuClient m_contextMenuClient; #endif InjectedBundlePageEditorClient m_editorClient; - std::unique_ptr<API::InjectedBundle::FormClient> m_formClient; + InjectedBundlePageFormClient m_formClient; InjectedBundlePageLoaderClient m_loaderClient; InjectedBundlePagePolicyClient m_policyClient; InjectedBundlePageResourceLoadClient m_resourceLoadClient; - std::unique_ptr<API::InjectedBundle::PageUIClient> m_uiClient; + InjectedBundlePageUIClient m_uiClient; #if ENABLE(FULLSCREEN_API) InjectedBundlePageFullScreenClient m_fullScreenClient; #endif InjectedBundlePageDiagnosticLoggingClient m_logDiagnosticMessageClient; FindController m_findController; + PageOverlayList m_pageOverlays; +#if ENABLE(INSPECTOR) RefPtr<WebInspector> m_inspector; - RefPtr<WebInspectorUI> m_inspectorUI; -#if PLATFORM(IOS) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)) - RefPtr<WebVideoFullscreenManager> m_videoFullscreenManager; -#endif -#if PLATFORM(IOS) - bool m_allowsMediaDocumentInlinePlayback { false }; #endif #if ENABLE(FULLSCREEN_API) RefPtr<WebFullScreenManager> m_fullScreenManager; @@ -1306,17 +1007,11 @@ private: RefPtr<WebOpenPanelResultListener> m_activeOpenPanelResultListener; RefPtr<NotificationPermissionRequestManager> m_notificationPermissionRequestManager; - RefPtr<WebUserContentController> m_userContentController; - #if ENABLE(GEOLOCATION) GeolocationPermissionRequestManager m_geolocationPermissionRequestManager; #endif -#if ENABLE(MEDIA_STREAM) - UserMediaPermissionRequestManager m_userMediaPermissionRequestManager; -#endif - - std::unique_ptr<WebCore::PrintContext> m_printContext; + OwnPtr<WebCore::PrintContext> m_printContext; #if PLATFORM(GTK) RefPtr<WebPrintOperationGtk> m_printOperation; #endif @@ -1326,28 +1021,20 @@ private: RefPtr<SandboxExtension> m_pendingDropSandboxExtension; Vector<RefPtr<SandboxExtension>> m_pendingDropExtensionsForFileUpload; - WebCore::HysteresisActivity m_pageScrolledHysteresis; - bool m_canRunBeforeUnloadConfirmPanel; bool m_canRunModal; bool m_isRunningModal; -#if ENABLE(DRAG_SUPPORT) - bool m_isStartingDrag; -#endif - bool m_cachedMainFrameIsPinnedToLeftSide; bool m_cachedMainFrameIsPinnedToRightSide; bool m_cachedMainFrameIsPinnedToTopSide; bool m_cachedMainFrameIsPinnedToBottomSide; bool m_canShortCircuitHorizontalWheelEvents; - bool m_hasWheelEventHandlers; + unsigned m_numWheelEventHandlers; unsigned m_cachedPageCount; - HashSet<unsigned long> m_trackedNetworkResourceRequestIdentifiers; - WebCore::IntSize m_minimumLayoutSize; bool m_autoSizingShouldExpandToViewHeight; @@ -1358,79 +1045,23 @@ private: #if PLATFORM(IOS) RefPtr<WebCore::Node> m_assistedNode; RefPtr<WebCore::Range> m_currentWordRange; - RefPtr<WebCore::Node> m_interactionNode; - WebCore::IntPoint m_lastInteractionLocation; - - enum SelectionAnchor { - Start, - End - }; - SelectionAnchor m_selectionAnchor; - - RefPtr<WebCore::Node> m_potentialTapNode; - WebCore::FloatPoint m_potentialTapLocation; - - WebCore::ViewportConfiguration m_viewportConfiguration; - bool m_hasReceivedVisibleContentRectsAfterDidCommitLoad; - bool m_scaleWasSetByUIProcess; - bool m_userHasChangedPageScaleFactor; - bool m_hasStablePageScaleFactor; - bool m_userIsInteracting; - bool m_hasFocusedDueToUserInteraction { false }; - bool m_hasPendingBlurNotification; - bool m_useTestingViewportConfiguration; - bool m_isInStableState; - std::chrono::milliseconds m_oldestNonStableUpdateVisibleContentRectsTimestamp; - std::chrono::milliseconds m_estimatedLatency; - WebCore::FloatSize m_screenSize; - WebCore::FloatSize m_availableScreenSize; - RefPtr<WebCore::Range> m_currentBlockSelection; - RefPtr<WebCore::Range> m_initialSelection; - WebCore::IntSize m_blockSelectionDesiredSize; - WebCore::FloatSize m_maximumUnobscuredSize; - int32_t m_deviceOrientation; - bool m_inDynamicSizeUpdate; - HashMap<std::pair<WebCore::IntSize, double>, WebCore::IntPoint> m_dynamicSizeUpdateHistory; - RefPtr<WebCore::Node> m_pendingSyntheticClickNode; - WebCore::FloatPoint m_pendingSyntheticClickLocation; - WebCore::FloatRect m_previousExposedContentRect; - WebCore::Timer m_volatilityTimer; -#endif - - HashSet<String, ASCIICaseInsensitiveHash> m_mimeTypesWithCustomContentProviders; + bool m_shouldReturnWordAtSelection; +#endif + + WebInspectorClient* m_inspectorClient; + WebCore::Color m_backgroundColor; HashSet<unsigned> m_activeRenderingSuppressionTokens; unsigned m_maximumRenderingSuppressionToken; WebCore::ScrollPinningBehavior m_scrollPinningBehavior; - WTF::Optional<WebCore::ScrollbarOverlayStyle> m_scrollbarOverlayStyle; bool m_useAsyncScrolling; WebCore::ViewState::Flags m_viewState; - WebCore::PageActivityState::Flags m_activityState; - bool m_processSuppressionEnabled; - UserActivity m_userActivity; - - uint64_t m_pendingNavigationID; - -#if ENABLE(WEBGL) - WebCore::WebGLLoadPolicy m_systemWebGLPolicy; -#endif - - bool m_mainFrameProgressCompleted; - bool m_shouldDispatchFakeMouseMoveEvents; - bool m_isEditorStateMissingPostLayoutData { false }; - -#if PLATFORM(GTK) - bool m_inputMethodEnabled { false }; -#endif - -#if ENABLE(VIDEO) && USE(GSTREAMER) - RefPtr<WebCore::MediaPlayerRequestInstallMissingPluginsCallback> m_installMediaPluginsCallback; -#endif + UserActivity m_processSuppressionDisabledByWebPreference; }; } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/WebPage.messages.in b/Source/WebKit2/WebProcess/WebPage/WebPage.messages.in index de86c9a07..fdeb9c6c4 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebPage.messages.in +++ b/Source/WebKit2/WebProcess/WebPage/WebPage.messages.in @@ -21,15 +21,14 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. messages -> WebPage LegacyReceiver { - SetInitialFocus(bool forward, bool isKeyboardEventValid, WebKit::WebKeyboardEvent event, uint64_t callbackID) - SetViewState(unsigned viewState, bool wantsDidUpdateViewState, Vector<uint64_t> callbackIDs) + SetInitialFocus(bool forward, bool isKeyboardEventValid, WebKit::WebKeyboardEvent event) + SetViewState(unsigned viewState, bool wantsDidUpdateViewState) SetLayerHostingMode(unsigned layerHostingMode) - SetSessionID(WebCore::SessionID sessionID) + SetSessionID(uint64_t sessionID) SetDrawsBackground(bool drawsBackground) - - SetTopContentInset(float contentInset) + SetDrawsTransparentBackground(bool drawsTransparentBackground) SetUnderlayColor(WebCore::Color color) @@ -37,73 +36,32 @@ messages -> WebPage LegacyReceiver { ViewWillEndLiveResize() KeyEvent(WebKit::WebKeyboardEvent event) + KeyEventSyncForTesting(WebKit::WebKeyboardEvent event) -> (bool handled) MouseEvent(WebKit::WebMouseEvent event) + MouseEventSyncForTesting(WebKit::WebMouseEvent event) -> (bool handled) + WheelEventSyncForTesting(WebKit::WebWheelEvent event) -> (bool handled) #if PLATFORM(IOS) - SetViewportConfigurationMinimumLayoutSize(WebCore::FloatSize size) - SetMaximumUnobscuredSize(WebCore::FloatSize size) - SetDeviceOrientation(int32_t deviceOrientation) - DynamicViewportSizeUpdate(WebCore::FloatSize minimumLayoutSize, WebCore::FloatSize maximumUnobscuredSize, WebCore::FloatRect targetExposedContentRect, WebCore::FloatRect targetUnobscuredRect, WebCore::FloatRect targetUnobscuredRectInScrollViewCoordinates, double scale, int32_t deviceOrientation, uint64_t dynamicViewportSizeUpdateID) - SynchronizeDynamicViewportUpdate() -> (double newTargetScale, WebCore::FloatPoint newScrollPosition, uint64_t nextValidLayerTreeTransactionID) - - HandleTap(WebCore::IntPoint point, uint64_t lastLayerTreeTransactionId) - PotentialTapAtPosition(uint64_t requestID, WebCore::FloatPoint point) - CommitPotentialTap(uint64_t lastLayerTreeTransactionId) - CancelPotentialTap() + HandleTap(WebCore::IntPoint point) TapHighlightAtPosition(uint64_t requestID, WebCore::FloatPoint point) - InspectorNodeSearchMovedToPosition(WebCore::FloatPoint point) - InspectorNodeSearchEndedAtPosition(WebCore::FloatPoint point) BlurAssistedNode() - SelectWithGesture(WebCore::IntPoint point, uint32_t granularity, uint32_t gestureType, uint32_t gestureState, bool isInteractingWithAssistedNode, uint64_t callbackID) + SelectWithGesture(WebCore::IntPoint point, uint32_t granularity, uint32_t gestureType, uint32_t gestureState, uint64_t callbackID) UpdateSelectionWithTouches(WebCore::IntPoint point, uint32_t touches, bool baseIsStart, uint64_t callbackID) - UpdateBlockSelectionWithTouch(WebCore::IntPoint point, uint32_t touch, uint32_t handlePosition) SelectWithTwoTouches(WebCore::IntPoint from, WebCore::IntPoint to, uint32_t gestureType, uint32_t gestureState, uint64_t callbackID) ExtendSelection(uint32_t granularity) - SelectWordBackward() - MoveSelectionByOffset(int32_t offset, uint64_t callbackID) - SelectTextWithGranularityAtPoint(WebCore::IntPoint point, uint32_t granularity, bool isInteractingWithAssistedNode, uint64_t callbackID) - SelectPositionAtBoundaryWithDirection(WebCore::IntPoint point, uint32_t granularity, uint32_t direction, bool isInteractingWithAssistedNode, uint64_t callbackID) - MoveSelectionAtBoundaryWithDirection(uint32_t granularity, uint32_t direction, uint64_t callbackID) - SelectPositionAtPoint(WebCore::IntPoint point, bool isInteractingWithAssistedNode, uint64_t callbackID) - BeginSelectionInDirection(uint32_t direction, uint64_t callbackID) - UpdateSelectionWithExtentPoint(WebCore::IntPoint point, bool isInteractingWithAssistedNode, uint64_t callbackID) - UpdateSelectionWithExtentPointAndBoundary(WebCore::IntPoint point, uint32_t granularity, bool isInteractingWithAssistedNode, uint64_t callbackID) - RequestDictationContext(uint64_t callbackID) - ReplaceDictatedText(String oldText, String newText) - ReplaceSelectedText(String oldText, String newText) RequestAutocorrectionData(String textForAutocorrection, uint64_t callbackID) ApplyAutocorrection(String correction, String originalText, uint64_t callbackID) - SyncApplyAutocorrection(String correction, String originalText) -> (bool autocorrectionApplied) RequestAutocorrectionContext(uint64_t callbackID) GetAutocorrectionContext() -> (String beforeContext, String markedText, String selectedText, String afterContext, uint64_t location, uint64_t length) - GetPositionInformation(WebCore::IntPoint point) -> (struct WebKit::InteractionInformationAtPosition information) + InsertText(String text, uint64_t replacementRangeStart, uint64_t replacementRangeEnd) + SetComposition(String text, Vector<WebCore::CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd) + ConfirmComposition() + GetPositionInformation(WebCore::IntPoint point) -> (WebKit::InteractionInformationAtPosition information) RequestPositionInformation(WebCore::IntPoint point) - StartInteractionWithElementAtPosition(WebCore::IntPoint point) - StopInteraction() - PerformActionOnElement(uint32_t action) - FocusNextAssistedNode(bool isForward, uint64_t callbackID) - SetAssistedNodeValue(String value) - SetAssistedNodeValueAsNumber(double value) - SetAssistedNodeSelectedIndex(uint32_t index, bool allowMultipleSelection) - ApplicationWillResignActive() - ApplicationDidEnterBackground(bool isSuspendedUnderLock) - ApplicationWillEnterForeground(bool isSuspendedUnderLock) - ApplicationDidBecomeActive() - ContentSizeCategoryDidChange(String contentSizeCategory) - ExecuteEditCommandWithCallback(String name, uint64_t callbackID) - GetLookupContextAtPoint(WebCore::IntPoint point, uint64_t callbackID) - SetAllowsMediaDocumentInlinePlayback(bool allows) -#endif - -#if ENABLE(REMOTE_INSPECTOR) - SetAllowsRemoteInspection(bool allow) - SetRemoteInspectionNameOverride(String name) #endif -#if ENABLE(IOS_TOUCH_EVENTS) - TouchEventSync(WebKit::WebTouchEvent event) -> (bool handled) -#endif -#if !ENABLE(IOS_TOUCH_EVENTS) && ENABLE(TOUCH_EVENTS) +#if ENABLE(TOUCH_EVENTS) TouchEvent(WebKit::WebTouchEvent event) + TouchEventSyncForTesting(WebKit::WebTouchEvent event) -> (bool handled) #endif #if ENABLE(INPUT_TYPE_COLOR) @@ -118,38 +76,37 @@ messages -> WebPage LegacyReceiver { ScrollBy(uint32_t scrollDirection, uint32_t scrollGranularity) CenterSelectionInVisibleArea() - GoBack(uint64_t navigationID, uint64_t backForwardItemID) - GoForward(uint64_t navigationID, uint64_t backForwardItemID) - GoToBackForwardItem(uint64_t navigationID, uint64_t backForwardItemID) + GoBack(uint64_t backForwardItemID) + GoForward(uint64_t backForwardItemID) + GoToBackForwardItem(uint64_t backForwardItemID) TryRestoreScrollPosition() LoadURLInFrame(String url, uint64_t frameID) - LoadRequest(uint64_t navigationID, WebCore::ResourceRequest request, WebKit::SandboxExtension::Handle sandboxExtensionHandle, uint64_t shouldOpenExternalURLsPolicy, WebKit::UserData userData) - LoadData(uint64_t navigationID, IPC::DataReference data, String MIMEType, String encoding, String baseURL, WebKit::UserData userData) - LoadHTMLString(uint64_t navigationID, String htmlString, String baseURL, WebKit::UserData userData) - LoadAlternateHTMLString(String htmlString, String baseURL, String unreachableURL, String provisionalLoadErrorURL, WebKit::UserData userData) - LoadPlainTextString(String string, WebKit::UserData userData) - LoadWebArchiveData(IPC::DataReference webArchiveData, WebKit::UserData userData) - NavigateToPDFLinkWithSimulatedClick(String url, WebCore::IntPoint documentPoint, WebCore::IntPoint screenPoint) - - Reload(uint64_t navigationID, bool reloadFromOrigin, bool contentBlockersEnabled, WebKit::SandboxExtension::Handle sandboxExtensionHandle) + LoadRequest(WebCore::ResourceRequest request, WebKit::SandboxExtension::Handle sandboxExtensionHandle, WebKit::WebContextUserMessageEncoder userData) Variadic + LoadData(IPC::DataReference data, String MIMEType, String encoding, String baseURL, WebKit::WebContextUserMessageEncoder userData) Variadic + LoadHTMLString(String htmlString, String baseURL, WebKit::WebContextUserMessageEncoder userData) Variadic + LoadAlternateHTMLString(String htmlString, String baseURL, String unreachableURL, WebKit::WebContextUserMessageEncoder userData) Variadic + LoadPlainTextString(String string, WebKit::WebContextUserMessageEncoder userData) Variadic + LoadWebArchiveData(IPC::DataReference webArchiveData, WebKit::WebContextUserMessageEncoder userData) Variadic + + Reload(bool reloadFromOrigin, WebKit::SandboxExtension::Handle sandboxExtensionHandle) StopLoading() StopLoadingFrame(uint64_t frameID) - RestoreSession(Vector<WebKit::BackForwardListItemState> itemStates) + RestoreSession(WebKit::SessionState state) + RestoreSessionAndNavigateToCurrentItem(WebKit::SessionState state) DidRemoveBackForwardItem(uint64_t backForwardItemID) - DidReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t navigationID, WebKit::DownloadID downloadID) + DidReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID) ClearSelection() - RestoreSelectionInFocusedEditableElement() # Callbacks. GetContentsAsString(uint64_t callbackID) #if ENABLE(MHTML) - GetContentsAsMHTMLData(uint64_t callbackID) + GetContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding) #endif GetMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID) GetResourceDataFromFrame(uint64_t frameID, String resourceURL, uint64_t callbackID) @@ -161,17 +118,12 @@ messages -> WebPage LegacyReceiver { RunJavaScriptInMainFrame(String script, uint64_t callbackID) ForceRepaint(uint64_t callbackID) -#if PLATFORM(COCOA) +#if PLATFORM(MAC) # Dictionary support. PerformDictionaryLookupAtLocation(WebCore::FloatPoint point) #endif -#if PLATFORM(MAC) - PerformDictionaryLookupOfCurrentSelection() - SetFont(String fontFamily, double fontSize, uint64_t fontTraits) -#endif - - PreferencesDidChange(struct WebKit::WebPreferencesStore store) + PreferencesDidChange(WebKit::WebPreferencesStore store) SetUserAgent(String userAgent) SetCustomTextEncodingName(String encodingName) @@ -182,9 +134,8 @@ messages -> WebPage LegacyReceiver { Close() TryClose() - SetEditable(bool editable) ValidateCommand(String name, uint64_t callbackID) - ExecuteEditCommand(String name, String argument) + ExecuteEditCommand(String name) DidRemoveEditCommand(uint64_t commandID) ReapplyEditCommand(uint64_t commandID) @@ -193,29 +144,23 @@ messages -> WebPage LegacyReceiver { SetPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor) SetPageZoomFactor(double zoomFactor) SetTextZoomFactor(double zoomFactor) - WindowScreenDidChange(uint32_t displayID) + WindowScreenDidChange(uint64_t displayID) ScalePage(double scale, WebCore::IntPoint origin) - ScalePageInViewCoordinates(double scale, WebCore::IntPoint centerInViewCoordinates) - ScaleView(double scale) SetUseFixedLayout(bool fixed) SetFixedLayoutSize(WebCore::IntSize size) ListenForLayoutMilestones(uint32_t milestones) SetSuppressScrollbarAnimations(bool suppressAnimations) - SetEnableVerticalRubberBanding(bool enableVerticalRubberBanding) - SetEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding) - SetBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage) SetPaginationMode(uint32_t mode) SetPaginationBehavesLikeColumns(bool behavesLikeColumns) SetPageLength(double pageLength) SetGapBetweenPages(double gap) - SetPaginationLineGridEnabled(bool lineGridEnabled) - PostInjectedBundleMessage(String messageName, WebKit::UserData messageBody) + PostInjectedBundleMessage(String messageName, WebKit::WebContextUserMessageEncoder messageBody) Variadic # Find. FindString(String string, uint32_t findOptions, unsigned maxMatchCount) @@ -224,8 +169,6 @@ messages -> WebPage LegacyReceiver { SelectFindMatch(uint32_t matchIndex) HideFindUI() CountStringMatches(String string, uint32_t findOptions, unsigned maxMatchCount) - - AddMIMETypeWithCustomContentProvider(String mimeType) # Drag and drop. #if PLATFORM(GTK) && ENABLE(DRAG_SUPPORT) @@ -235,7 +178,6 @@ messages -> WebPage LegacyReceiver { PerformDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, String dragStorageName, uint32_t flags, WebKit::SandboxExtension::Handle sandboxExtensionHandle, WebKit::SandboxExtension::HandleArray sandboxExtensionsForUpload) #endif #if ENABLE(DRAG_SUPPORT) - DidStartDrag() DragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation) #endif @@ -252,12 +194,9 @@ messages -> WebPage LegacyReceiver { #endif # Open panel. -#if PLATFORM(IOS) - DidChooseFilesForOpenPanelWithDisplayStringAndIcon(Vector<String> fileURLs, String displayString, IPC::DataReference iconData) -#endif DidChooseFilesForOpenPanel(Vector<String> fileURLs) DidCancelForOpenPanel() -#if ENABLE(SANDBOX_EXTENSIONS) +#if ENABLE(WEB_PROCESS_SANDBOX) ExtendSandboxForFileFromOpenPanel(WebKit::SandboxExtension::Handle sandboxExtensionHandle) #endif @@ -271,7 +210,7 @@ messages -> WebPage LegacyReceiver { LowercaseWord() CapitalizeWord() #endif -#if PLATFORM(COCOA) +#if PLATFORM(MAC) SetSmartInsertDeleteEnabled(bool isSmartInsertDeleteEnabled) #endif @@ -280,39 +219,28 @@ messages -> WebPage LegacyReceiver { DidReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed) #endif -#if ENABLE(MEDIA_STREAM) - # MediaSteam - DidReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed, String audioDeviceUID, String videoDeviceUID) - DidCompleteUserMediaPermissionCheck(uint64_t userMediaID, bool allowed) -#endif - # Notification DidReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed) + SetWindowResizerSize(WebCore::IntSize intersectsView) + # Printing. - BeginPrinting(uint64_t frameID, struct WebKit::PrintInfo printInfo) + BeginPrinting(uint64_t frameID, WebKit::PrintInfo printInfo) EndPrinting() - ComputePagesForPrinting(uint64_t frameID, struct WebKit::PrintInfo printInfo, uint64_t callbackID) -#if PLATFORM(COCOA) - DrawRectToImage(uint64_t frameID, struct WebKit::PrintInfo printInfo, WebCore::IntRect rect, WebCore::IntSize imageSize, uint64_t callbackID) - DrawPagesToPDF(uint64_t frameID, struct WebKit::PrintInfo printInfo, uint32_t first, uint32_t count, uint64_t callbackID) -#if PLATFORM(IOS) - ComputePagesForPrintingAndStartDrawingToPDF(uint64_t frameID, struct WebKit::PrintInfo printInfo, uint32_t firstPage) -> (Vector<WebCore::IntRect> pageRects, double totalScaleFactor) Delayed -#endif + ComputePagesForPrinting(uint64_t frameID, WebKit::PrintInfo printInfo, uint64_t callbackID) +#if PLATFORM(MAC) + DrawRectToImage(uint64_t frameID, WebKit::PrintInfo printInfo, WebCore::IntRect rect, WebCore::IntSize imageSize, uint64_t callbackID) + DrawPagesToPDF(uint64_t frameID, WebKit::PrintInfo printInfo, uint32_t first, uint32_t count, uint64_t callbackID) #endif #if PLATFORM(GTK) - DrawPagesForPrinting(uint64_t frameID, struct WebKit::PrintInfo printInfo, uint64_t callbackID) + DrawPagesForPrinting(uint64_t frameID, WebKit::PrintInfo printInfo, uint64_t callbackID) #endif # Media SetMediaVolume(float volume) - SetMuted(bool muted) SetMayStartMediaWhenInWindow(bool mayStartMedia) -#if ENABLE(MEDIA_SESSION) - HandleMediaEvent(uint32_t eventType) - SetVolumeOfMediaElement(double volume, uint64_t elementID) -#endif + SetMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled) // FIXME: This a dummy message, to avoid breaking the build for platforms that don't require // any synchronous messages, and should be removed when <rdar://problem/8775115> is fixed. @@ -325,7 +253,7 @@ messages -> WebPage LegacyReceiver { SetThemePath(String themePath) #endif -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) +#if USE(TILED_BACKING_STORE) CommitPageTransitionViewport() #endif @@ -335,11 +263,7 @@ messages -> WebPage LegacyReceiver { CancelComposition() #endif -#if PLATFORM (GTK) && HAVE(GTK_GESTURES) - GetCenterForZoomGesture(WebCore::IntPoint centerInViewCoordinates) -> (WebCore::IntPoint center) -#endif - -#if PLATFORM(COCOA) +#if PLATFORM(MAC) # Complex text input support for plug-ins. SendComplexTextInputToPlugin(uint64_t pluginComplexTextInputIdentifier, String textInput) @@ -350,27 +274,23 @@ messages -> WebPage LegacyReceiver { GetDataSelectionForPasteboard(String pasteboardType) -> (WebKit::SharedMemory::Handle handle, uint64_t size) ReadSelectionFromPasteboard(String pasteboardName) -> (bool result) -#if ENABLE(SERVICE_CONTROLS) - ReplaceSelectionWithPasteboardData(Vector<String> types, IPC::DataReference data) -#endif - + # Text input. + CancelComposition() -> (WebKit::EditorState newState) + GetMarkedRange() -> (uint64_t location, uint64_t length) + GetSelectedRange() -> (uint64_t location, uint64_t length) + GetAttributedSubstringFromRange(uint64_t location, uint64_t length) -> (WebKit::AttributedString result) + CharacterIndexForPoint(WebCore::IntPoint point) -> (uint64_t result) + FirstRectForCharacterRange(uint64_t location, uint64_t length) -> (WebCore::IntRect resultRect) + ExecuteKeypressCommands(Vector<WebCore::KeypressCommand> savedCommands) -> (bool handled, WebKit::EditorState newState) ShouldDelayWindowOrderingEvent(WebKit::WebMouseEvent event) -> (bool result) AcceptsFirstMouse(int eventNumber, WebKit::WebMouseEvent event) -> (bool result) - - InsertTextAsync(String text, struct WebKit::EditingRange replacementRange, bool registerUndoGroup, uint32_t editingRangeIsRelativeTo) - GetMarkedRangeAsync(uint64_t callbackID) - GetSelectedRangeAsync(uint64_t callbackID) - CharacterIndexForPointAsync(WebCore::IntPoint point, uint64_t callbackID); - FirstRectForCharacterRangeAsync(struct WebKit::EditingRange range, uint64_t callbackID); - SetCompositionAsync(String text, Vector<WebCore::CompositionUnderline> underlines, struct WebKit::EditingRange selectionRange, struct WebKit::EditingRange replacementRange) - ConfirmCompositionAsync() + InsertDictatedText(String text, uint64_t replacementRangeStart, uint64_t replacementRangeEnd, Vector<WebCore::DictationAlternative> dictationAlternatives) -> (bool handled, WebKit::EditorState newState) #endif -#if PLATFORM(MAC) - InsertDictatedTextAsync(String text, struct WebKit::EditingRange replacementRange, Vector<WebCore::DictationAlternative> dictationAlternatives, bool registerUndoGroup) - AttributedSubstringForCharacterRangeAsync(struct WebKit::EditingRange range, uint64_t callbackID); - FontAtSelection(uint64_t callbackID); +#if PLATFORM(MAC) && !PLATFORM(IOS) + InsertText(String text, uint64_t replacementRangeStart, uint64_t replacementRangeEnd) -> (bool handled, WebKit::EditorState newState) + SetComposition(String text, Vector<WebCore::CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementRangeStart, uint64_t replacementRangeEnd) -> (WebKit::EditorState newState) + ConfirmComposition() -> (WebKit::EditorState newState) #endif - SetMinimumLayoutSize(WebCore::IntSize minimumLayoutSize) SetAutoSizingShouldExpandToViewHeight(bool shouldExpand) @@ -379,47 +299,26 @@ messages -> WebPage LegacyReceiver { SetComposition(String compositionString, Vector<WebCore::CompositionUnderline> underlines, uint64_t cursorPosition) CancelComposition() #endif -#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) +#if USE(COORDINATED_GRAPHICS) FindZoomableAreaForPoint(WebCore::IntPoint point, WebCore::IntSize area) #endif -#if PLATFORM(COCOA) +#if PLATFORM(MAC) HandleAlternativeTextUIResult(String result) #endif -#if PLATFORM(IOS) - WillStartUserTriggeredZooming(); -#endif - - SetScrollPinningBehavior(uint32_t pinning) - SetScrollbarOverlayStyle(Optional<uint32_t> scrollbarStyle) + SetVisibilityStatePrerender() - GetBytecodeProfile(uint64_t callbackID) - - TakeSnapshot(WebCore::IntRect snapshotRect, WebCore::IntSize bitmapSize, uint32_t options, uint64_t callbackID) -#if PLATFORM(MAC) - PerformImmediateActionHitTestAtLocation(WebCore::FloatPoint location) - ImmediateActionDidUpdate() - ImmediateActionDidCancel() - ImmediateActionDidComplete() - DataDetectorsDidPresentUI(WebCore::PageOverlay::PageOverlayID pageOverlay) - DataDetectorsDidChangeUI(WebCore::PageOverlay::PageOverlayID pageOverlay) - DataDetectorsDidHideUI(WebCore::PageOverlay::PageOverlayID pageOverlay) - HandleAcceptedCandidate(struct WebCore::TextCheckingResult acceptedCandidate) +#if PLATFORM(IOS) + DidFinishScrolling(WebCore::FloatPoint contentOffset); + DidFinishZooming(float scale); #endif - SetShouldDispatchFakeMouseMoveEvents(bool shouldDispatchFakeMouseMoveEvents) - -#if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS) - PlaybackTargetSelected(uint64_t contextId, WebCore::MediaPlaybackTargetContext target) - PlaybackTargetAvailabilityDidChange(uint64_t contextId, bool available) - SetShouldPlayToPlaybackTarget(uint64_t contextId, bool shouldPlay) +#if PLATFORM(GTK) && USE(TEXTURE_MAPPER_GL) + SetAcceleratedCompositingWindowId(int64_t id) #endif - ClearWheelEventTestTrigger() - SetShouldScaleViewToFitDocument(bool shouldScaleViewToFitDocument) - -#if ENABLE(VIDEO) && USE(GSTREAMER) - DidEndRequestInstallMissingMediaPlugins(uint32_t result) -#endif + SetMainFrameInViewSourceMode(bool inViewSourceMode) + + SetScrollPinningBehavior(uint32_t pinning) } diff --git a/Source/WebKit2/WebProcess/WebPage/WebPageGroupProxy.cpp b/Source/WebKit2/WebProcess/WebPage/WebPageGroupProxy.cpp index 4db5e431c..9164f480e 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebPageGroupProxy.cpp +++ b/Source/WebKit2/WebProcess/WebPage/WebPageGroupProxy.cpp @@ -26,12 +26,10 @@ #include "config.h" #include "WebPageGroupProxy.h" -#include "InjectedBundle.h" -#include "WebCompiledContentExtension.h" #include "WebProcess.h" +#include "InjectedBundle.h" #include <WebCore/DOMWrapperWorld.h> #include <WebCore/PageGroup.h> -#include <WebCore/UserContentController.h> namespace WebKit { @@ -39,80 +37,49 @@ PassRefPtr<WebPageGroupProxy> WebPageGroupProxy::create(const WebPageGroupData& { RefPtr<WebPageGroupProxy> pageGroup = adoptRef(new WebPageGroupProxy(data)); - if (pageGroup->isVisibleToInjectedBundle() && WebProcess::singleton().injectedBundle()) - WebProcess::singleton().injectedBundle()->didInitializePageGroup(pageGroup.get()); + if (pageGroup->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle()) + WebProcess::shared().injectedBundle()->didInitializePageGroup(pageGroup.get()); return pageGroup.release(); } -WebPageGroupProxy::WebPageGroupProxy(const WebPageGroupData& data) - : m_data(data) - , m_pageGroup(WebCore::PageGroup::pageGroup(m_data.identifier)) -{ - for (const auto& userStyleSheet : data.userStyleSheets) - addUserStyleSheet(userStyleSheet); - for (const auto& userScript : data.userScripts) - addUserScript(userScript); - -#if ENABLE(CONTENT_EXTENSIONS) - for (auto& slot : data.userContentExtensions) - addUserContentExtension(slot.key, slot.value); -#endif -} - WebPageGroupProxy::~WebPageGroupProxy() { } -WebCore::UserContentController& WebPageGroupProxy::userContentController() +WebPageGroupProxy::WebPageGroupProxy(const WebPageGroupData& data) + : m_data(data) + , m_pageGroup(WebCore::PageGroup::pageGroup(m_data.identifer)) { - if (!m_userContentController) - m_userContentController = WebCore::UserContentController::create(); - - return *m_userContentController; + for (size_t i = 0; i < data.userStyleSheets.size(); ++i) + addUserStyleSheet(data.userStyleSheets[i]); + for (size_t i = 0; i < data.userScripts.size(); ++i) + addUserScript(data.userScripts[i]); } void WebPageGroupProxy::addUserStyleSheet(const WebCore::UserStyleSheet& userStyleSheet) { - userContentController().addUserStyleSheet(WebCore::mainThreadNormalWorld(), std::make_unique<WebCore::UserStyleSheet>(userStyleSheet), WebCore::InjectInExistingDocuments); + m_pageGroup->addUserStyleSheetToWorld(WebCore::mainThreadNormalWorld(), userStyleSheet.source(), userStyleSheet.url(), userStyleSheet.whitelist(), userStyleSheet.blacklist(), userStyleSheet.injectedFrames(), userStyleSheet.level()); } void WebPageGroupProxy::addUserScript(const WebCore::UserScript& userScript) { - userContentController().addUserScript(WebCore::mainThreadNormalWorld(), std::make_unique<WebCore::UserScript>(userScript)); + m_pageGroup->addUserScriptToWorld(WebCore::mainThreadNormalWorld(), userScript.source(), userScript.url(), userScript.whitelist(), userScript.blacklist(), userScript.injectionTime(), userScript.injectedFrames()); } void WebPageGroupProxy::removeAllUserStyleSheets() { - userContentController().removeUserStyleSheets(WebCore::mainThreadNormalWorld()); + m_pageGroup->removeUserStyleSheetsFromWorld(WebCore::mainThreadNormalWorld()); } void WebPageGroupProxy::removeAllUserScripts() { - userContentController().removeUserScripts(WebCore::mainThreadNormalWorld()); + m_pageGroup->removeUserScriptsFromWorld(WebCore::mainThreadNormalWorld()); } void WebPageGroupProxy::removeAllUserContent() { - userContentController().removeAllUserContent(); -} - -#if ENABLE(CONTENT_EXTENSIONS) -void WebPageGroupProxy::addUserContentExtension(const String& name, WebCompiledContentExtensionData contentExtensionData) -{ - RefPtr<WebCompiledContentExtension> compiledContentExtension = WebCompiledContentExtension::create(WTFMove(contentExtensionData)); - userContentController().addUserContentExtension(name, compiledContentExtension); -} - -void WebPageGroupProxy::removeUserContentExtension(const String& name) -{ - userContentController().removeUserContentExtension(name); -} - -void WebPageGroupProxy::removeAllUserContentExtensions() -{ - userContentController().removeAllUserContentExtensions(); + m_pageGroup->removeAllUserContent(); } -#endif } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/WebPageGroupProxy.h b/Source/WebKit2/WebProcess/WebPage/WebPageGroupProxy.h index 4da5255a0..5e7d50b85 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebPageGroupProxy.h +++ b/Source/WebKit2/WebProcess/WebPage/WebPageGroupProxy.h @@ -37,27 +37,25 @@ class MessageDecoder; namespace WebCore { class PageGroup; -class UserContentController; } namespace WebKit { -class WebCompiledContentExtensionData; - class WebPageGroupProxy : public API::ObjectImpl<API::Object::Type::BundlePageGroup> { public: static PassRefPtr<WebPageGroupProxy> create(const WebPageGroupData&); virtual ~WebPageGroupProxy(); - const String& identifier() const { return m_data.identifier; } + const String& identifier() const { return m_data.identifer; } uint64_t pageGroupID() const { return m_data.pageGroupID; } bool isVisibleToInjectedBundle() const { return m_data.visibleToInjectedBundle; } bool isVisibleToHistoryClient() const { return m_data.visibleToHistoryClient; } WebCore::PageGroup* corePageGroup() const { return m_pageGroup; } - WebCore::UserContentController& userContentController(); + void didReceiveMessage(IPC::Connection*, IPC::MessageDecoder&); - void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&); +private: + WebPageGroupProxy(const WebPageGroupData&); void addUserStyleSheet(const WebCore::UserStyleSheet&); void addUserScript(const WebCore::UserScript&); @@ -65,19 +63,8 @@ public: void removeAllUserScripts(); void removeAllUserContent(); -#if ENABLE(CONTENT_EXTENSIONS) - void addUserContentExtension(const String& name, WebCompiledContentExtensionData); - void removeUserContentExtension(const String& name); - void removeAllUserContentExtensions(); -#endif - -private: - WebPageGroupProxy(const WebPageGroupData&); - WebPageGroupData m_data; WebCore::PageGroup* m_pageGroup; - - RefPtr<WebCore::UserContentController> m_userContentController; }; } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/WebPageGroupProxy.messages.in b/Source/WebKit2/WebProcess/WebPage/WebPageGroupProxy.messages.in index c054d5e23..8ba527a3d 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebPageGroupProxy.messages.in +++ b/Source/WebKit2/WebProcess/WebPage/WebPageGroupProxy.messages.in @@ -26,10 +26,4 @@ messages -> WebPageGroupProxy { RemoveAllUserStyleSheets(); RemoveAllUserScripts(); RemoveAllUserContent(); - -#if ENABLE(CONTENT_EXTENSIONS) - AddUserContentExtension(String name, WebKit::WebCompiledContentExtensionData contentExtension); - RemoveUserContentExtension(String name); - RemoveAllUserContentExtensions(); -#endif } diff --git a/Source/WebKit2/WebProcess/WebPage/WebPageOverlay.cpp b/Source/WebKit2/WebProcess/WebPage/WebPageOverlay.cpp deleted file mode 100644 index e802ed3bb..000000000 --- a/Source/WebKit2/WebProcess/WebPage/WebPageOverlay.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebPageOverlay.h" - -#include "WebFrame.h" -#include "WebPage.h" -#include <WebCore/GraphicsLayer.h> -#include <WebCore/PageOverlay.h> -#include <wtf/NeverDestroyed.h> - -using namespace WebCore; - -namespace WebKit { - -static HashMap<PageOverlay*, WebPageOverlay*>& overlayMap() -{ - static NeverDestroyed<HashMap<PageOverlay*, WebPageOverlay*>> map; - return map; -} - -Ref<WebPageOverlay> WebPageOverlay::create(std::unique_ptr<WebPageOverlay::Client> client, PageOverlay::OverlayType overlayType) -{ - return adoptRef(*new WebPageOverlay(WTFMove(client), overlayType)); -} - -WebPageOverlay::WebPageOverlay(std::unique_ptr<WebPageOverlay::Client> client, PageOverlay::OverlayType overlayType) - : m_overlay(PageOverlay::create(*this, overlayType)) - , m_client(WTFMove(client)) -{ - ASSERT(m_client); - overlayMap().add(m_overlay.get(), this); -} - -WebPageOverlay::~WebPageOverlay() -{ - if (!m_overlay) - return; - - overlayMap().remove(m_overlay.get()); - m_overlay = nullptr; -} - -WebPageOverlay* WebPageOverlay::fromCoreOverlay(PageOverlay& overlay) -{ - return overlayMap().get(&overlay); -} - -void WebPageOverlay::setNeedsDisplay(const IntRect& dirtyRect) -{ - m_overlay->setNeedsDisplay(dirtyRect); -} - -void WebPageOverlay::setNeedsDisplay() -{ - m_overlay->setNeedsDisplay(); -} - -void WebPageOverlay::clear() -{ - m_overlay->clear(); -} - -void WebPageOverlay::pageOverlayDestroyed(PageOverlay&) -{ - if (m_overlay) { - overlayMap().remove(m_overlay.get()); - m_overlay = nullptr; - } - - m_client->pageOverlayDestroyed(*this); -} - -void WebPageOverlay::willMoveToPage(PageOverlay&, Page* page) -{ - m_client->willMoveToPage(*this, page ? WebPage::fromCorePage(page) : nullptr); -} - -void WebPageOverlay::didMoveToPage(PageOverlay&, Page* page) -{ - m_client->didMoveToPage(*this, page ? WebPage::fromCorePage(page) : nullptr); -} - -void WebPageOverlay::drawRect(PageOverlay&, GraphicsContext& context, const IntRect& dirtyRect) -{ - m_client->drawRect(*this, context, dirtyRect); -} - -bool WebPageOverlay::mouseEvent(PageOverlay&, const PlatformMouseEvent& event) -{ - return m_client->mouseEvent(*this, event); -} - -void WebPageOverlay::didScrollFrame(PageOverlay&, Frame& frame) -{ - m_client->didScrollFrame(*this, WebFrame::fromCoreFrame(frame)); -} - -#if PLATFORM(MAC) -DDActionContext *WebPageOverlay::actionContextForResultAtPoint(FloatPoint location, RefPtr<WebCore::Range>& rangeHandle) -{ - return m_client->actionContextForResultAtPoint(*this, location, rangeHandle); -} - -void WebPageOverlay::dataDetectorsDidPresentUI() -{ - m_client->dataDetectorsDidPresentUI(*this); -} - -void WebPageOverlay::dataDetectorsDidChangeUI() -{ - m_client->dataDetectorsDidChangeUI(*this); -} - -void WebPageOverlay::dataDetectorsDidHideUI() -{ - m_client->dataDetectorsDidHideUI(*this); -} -#endif // PLATFORM(MAC) - -bool WebPageOverlay::copyAccessibilityAttributeStringValueForPoint(PageOverlay&, String attribute, FloatPoint parameter, String& value) -{ - return m_client->copyAccessibilityAttributeStringValueForPoint(*this, attribute, parameter, value); -} - -bool WebPageOverlay::copyAccessibilityAttributeBoolValueForPoint(PageOverlay&, String attribute, FloatPoint parameter, bool& value) -{ - return m_client->copyAccessibilityAttributeBoolValueForPoint(*this, attribute, parameter, value); -} - -Vector<String> WebPageOverlay::copyAccessibilityAttributeNames(PageOverlay&, bool parameterizedNames) -{ - return m_client->copyAccessibilityAttributeNames(*this, parameterizedNames); -} - -} // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/WebPageOverlay.h b/Source/WebKit2/WebProcess/WebPage/WebPageOverlay.h deleted file mode 100644 index 6c8ce96ad..000000000 --- a/Source/WebKit2/WebProcess/WebPage/WebPageOverlay.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2014 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebPageOverlay_h -#define WebPageOverlay_h - -#include "APIObject.h" -#include <WebCore/FloatPoint.h> -#include <WebCore/IntRect.h> -#include <WebCore/PageOverlay.h> -#include <WebCore/Range.h> -#include <wtf/PassRefPtr.h> -#include <wtf/RetainPtr.h> - -OBJC_CLASS DDActionContext; - -namespace WebKit { - -class WebFrame; -class WebPage; - -class WebPageOverlay : public API::ObjectImpl<API::Object::Type::BundlePageOverlay>, private WebCore::PageOverlay::Client { -public: - class Client { - public: - virtual ~Client() { } - - virtual void pageOverlayDestroyed(WebPageOverlay&) = 0; - virtual void willMoveToPage(WebPageOverlay&, WebPage*) = 0; - virtual void didMoveToPage(WebPageOverlay&, WebPage*) = 0; - virtual void drawRect(WebPageOverlay&, WebCore::GraphicsContext&, const WebCore::IntRect& dirtyRect) = 0; - virtual bool mouseEvent(WebPageOverlay&, const WebCore::PlatformMouseEvent&) = 0; - virtual void didScrollFrame(WebPageOverlay&, WebFrame*) { } - -#if PLATFORM(MAC) - virtual DDActionContext *actionContextForResultAtPoint(WebPageOverlay&, WebCore::FloatPoint location, RefPtr<WebCore::Range>& rangeHandle) { return nullptr; } - virtual void dataDetectorsDidPresentUI(WebPageOverlay&) { } - virtual void dataDetectorsDidChangeUI(WebPageOverlay&) { } - virtual void dataDetectorsDidHideUI(WebPageOverlay&) { } -#endif - - virtual bool copyAccessibilityAttributeStringValueForPoint(WebPageOverlay&, String /* attribute */, WebCore::FloatPoint /* parameter */, String& /* value */) { return false; } - virtual bool copyAccessibilityAttributeBoolValueForPoint(WebPageOverlay&, String /* attribute */, WebCore::FloatPoint /* parameter */, bool& /* value */) { return false; } - virtual Vector<String> copyAccessibilityAttributeNames(WebPageOverlay&, bool /* parameterizedNames */) { return Vector<String>(); } - }; - - static Ref<WebPageOverlay> create(std::unique_ptr<Client>, WebCore::PageOverlay::OverlayType = WebCore::PageOverlay::OverlayType::View); - static WebPageOverlay* fromCoreOverlay(WebCore::PageOverlay&); - virtual ~WebPageOverlay(); - - void setNeedsDisplay(const WebCore::IntRect& dirtyRect); - void setNeedsDisplay(); - - void clear(); - - WebCore::PageOverlay* coreOverlay() const { return m_overlay.get(); } - Client& client() const { return *m_client; } - -#if PLATFORM(MAC) - DDActionContext *actionContextForResultAtPoint(WebCore::FloatPoint, RefPtr<WebCore::Range>&); - void dataDetectorsDidPresentUI(); - void dataDetectorsDidChangeUI(); - void dataDetectorsDidHideUI(); -#endif - -private: - WebPageOverlay(std::unique_ptr<Client>, WebCore::PageOverlay::OverlayType); - - // WebCore::PageOverlay::Client - virtual void pageOverlayDestroyed(WebCore::PageOverlay&) override; - virtual void willMoveToPage(WebCore::PageOverlay&, WebCore::Page*) override; - virtual void didMoveToPage(WebCore::PageOverlay&, WebCore::Page*) override; - virtual void drawRect(WebCore::PageOverlay&, WebCore::GraphicsContext&, const WebCore::IntRect& dirtyRect) override; - virtual bool mouseEvent(WebCore::PageOverlay&, const WebCore::PlatformMouseEvent&) override; - virtual void didScrollFrame(WebCore::PageOverlay&, WebCore::Frame&) override; - - virtual bool copyAccessibilityAttributeStringValueForPoint(WebCore::PageOverlay&, String /* attribute */, WebCore::FloatPoint /* parameter */, String& value) override; - virtual bool copyAccessibilityAttributeBoolValueForPoint(WebCore::PageOverlay&, String /* attribute */, WebCore::FloatPoint /* parameter */, bool& value) override; - virtual Vector<String> copyAccessibilityAttributeNames(WebCore::PageOverlay&, bool /* parameterizedNames */) override; - - - RefPtr<WebCore::PageOverlay> m_overlay; - std::unique_ptr<Client> m_client; -}; - -} // namespace WebKit - -#endif // WebPageOverlay_h diff --git a/Source/WebKit2/WebProcess/WebPage/WebUndoStep.cpp b/Source/WebKit2/WebProcess/WebPage/WebUndoStep.cpp index 2caa8d0d4..7b41c5aa6 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebUndoStep.cpp +++ b/Source/WebKit2/WebProcess/WebPage/WebUndoStep.cpp @@ -34,13 +34,9 @@ static uint64_t generateUndoStep() return uniqueEntryID++; } -Ref<WebUndoStep> WebUndoStep::create(PassRefPtr<WebCore::UndoStep> step) -{ - return adoptRef(*new WebUndoStep(step, generateUndoStep())); -} - -WebUndoStep::~WebUndoStep() +PassRefPtr<WebUndoStep> WebUndoStep::create(PassRefPtr<WebCore::UndoStep> step) { + return adoptRef(new WebUndoStep(step, generateUndoStep())); } } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/WebUndoStep.h b/Source/WebKit2/WebProcess/WebPage/WebUndoStep.h index 11871e91f..745377a3c 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebUndoStep.h +++ b/Source/WebKit2/WebProcess/WebPage/WebUndoStep.h @@ -34,8 +34,7 @@ namespace WebKit { class WebUndoStep : public RefCounted<WebUndoStep> { public: - static Ref<WebUndoStep> create(PassRefPtr<WebCore::UndoStep>); - ~WebUndoStep(); + static PassRefPtr<WebUndoStep> create(PassRefPtr<WebCore::UndoStep>); WebCore::UndoStep* step() const { return m_step.get(); } uint64_t stepID() const { return m_stepID; } diff --git a/Source/WebKit2/WebProcess/WebPage/atk/WebPageAccessibilityObjectAtk.cpp b/Source/WebKit2/WebProcess/WebPage/atk/WebPageAccessibilityObjectAtk.cpp index 421fb8ddd..577a9671c 100644 --- a/Source/WebKit2/WebProcess/WebPage/atk/WebPageAccessibilityObjectAtk.cpp +++ b/Source/WebKit2/WebProcess/WebPage/atk/WebPageAccessibilityObjectAtk.cpp @@ -30,7 +30,6 @@ #include "WebPage.h" #include <WebCore/AXObjectCache.h> -#include <WebCore/Document.h> #include <WebCore/MainFrame.h> #include <WebCore/Page.h> @@ -56,11 +55,7 @@ static AtkObject* accessibilityRootObjectWrapper(AtkObject* atkObject) if (!coreFrame.document()) return 0; - AXObjectCache* cache = coreFrame.document()->axObjectCache(); - if (!cache) - return nullptr; - - AccessibilityObject* coreRootObject = cache->rootObject(); + AccessibilityObject* coreRootObject = coreFrame.document()->axObjectCache()->rootObject(); if (!coreRootObject) return 0; diff --git a/Source/WebKit2/WebProcess/WebPage/gstreamer/WebPageGStreamer.cpp b/Source/WebKit2/WebProcess/WebPage/gstreamer/WebPageGStreamer.cpp deleted file mode 100644 index 50545b30f..000000000 --- a/Source/WebKit2/WebProcess/WebPage/gstreamer/WebPageGStreamer.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2015 Igalia S.L. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebPage.h" - -#if ENABLE(VIDEO) && USE(GSTREAMER) - -#include "WebPageProxyMessages.h" -#include <WebCore/MediaPlayerRequestInstallMissingPluginsCallback.h> -#include <gst/pbutils/install-plugins.h> - -namespace WebKit { - -void WebPage::requestInstallMissingMediaPlugins(const String& details, const String& description, WebCore::MediaPlayerRequestInstallMissingPluginsCallback& callback) -{ - if (m_installMediaPluginsCallback) { - callback.complete(GST_INSTALL_PLUGINS_INSTALL_IN_PROGRESS); - return; - } - - m_installMediaPluginsCallback = &callback; - send(Messages::WebPageProxy::RequestInstallMissingMediaPlugins(details, description)); -} - -void WebPage::didEndRequestInstallMissingMediaPlugins(uint32_t result) -{ - if (!m_installMediaPluginsCallback) - return; - - m_installMediaPluginsCallback->complete(result); - m_installMediaPluginsCallback = nullptr; -} - -} // namespace WebKit - -#endif // ENABLE(VIDEO) && USE(GSTREAMER) diff --git a/Source/WebKit2/WebProcess/WebPage/gtk/LayerTreeHostGtk.cpp b/Source/WebKit2/WebProcess/WebPage/gtk/LayerTreeHostGtk.cpp index 5b83c723e..70f6c8365 100644 --- a/Source/WebKit2/WebProcess/WebPage/gtk/LayerTreeHostGtk.cpp +++ b/Source/WebKit2/WebProcess/WebPage/gtk/LayerTreeHostGtk.cpp @@ -61,71 +61,6 @@ using namespace WebCore; namespace WebKit { -LayerTreeHostGtk::RenderFrameScheduler::RenderFrameScheduler(std::function<bool()> renderer) - : m_renderer(WTFMove(renderer)) - , m_timer(RunLoop::main(), this, &LayerTreeHostGtk::RenderFrameScheduler::renderFrame) -{ - // We use a RunLoop timer because otherwise GTK+ event handling during dragging can starve WebCore timers, which have a lower priority. - // Use a higher priority than WebCore timers. - m_timer.setPriority(GDK_PRIORITY_REDRAW - 1); -} - -LayerTreeHostGtk::RenderFrameScheduler::~RenderFrameScheduler() -{ -} - -void LayerTreeHostGtk::RenderFrameScheduler::start() -{ - if (m_timer.isActive()) - return; - m_fireTime = 0; - nextFrame(); -} - -void LayerTreeHostGtk::RenderFrameScheduler::stop() -{ - m_timer.stop(); -} - -static inline bool shouldSkipNextFrameBecauseOfContinousImmediateFlushes(double current, double lastImmediateFlushTime) -{ - // 100ms is about a perceptable delay in UI, so when scheduling layer flushes immediately for more than 100ms, - // we skip the next frame to ensure pending timers have a change to be fired. - static const double maxDurationOfImmediateFlushes = 0.100; - if (!lastImmediateFlushTime) - return false; - return lastImmediateFlushTime + maxDurationOfImmediateFlushes < current; -} - -void LayerTreeHostGtk::RenderFrameScheduler::nextFrame() -{ - static const double targetFramerate = 1 / 60.0; - // When rendering layers takes more time than the target delay (0.016), we end up scheduling layer flushes - // immediately. Since the layer flush timer has a higher priority than WebCore timers, these are never - // fired while we keep scheduling layer flushes immediately. - double current = monotonicallyIncreasingTime(); - double timeToNextFlush = std::max(targetFramerate - (current - m_fireTime), 0.0); - if (timeToNextFlush) - m_lastImmediateFlushTime = 0; - else if (!m_lastImmediateFlushTime) - m_lastImmediateFlushTime = current; - - if (shouldSkipNextFrameBecauseOfContinousImmediateFlushes(current, m_lastImmediateFlushTime)) { - timeToNextFlush = targetFramerate; - m_lastImmediateFlushTime = 0; - } - - m_timer.startOneShot(timeToNextFlush); -} - -void LayerTreeHostGtk::RenderFrameScheduler::renderFrame() -{ - m_fireTime = monotonicallyIncreasingTime(); - if (!m_renderer() || m_timer.isActive()) - return; - nextFrame(); -} - PassRefPtr<LayerTreeHostGtk> LayerTreeHostGtk::create(WebPage* webPage) { RefPtr<LayerTreeHostGtk> host = adoptRef(new LayerTreeHostGtk(webPage)); @@ -137,43 +72,35 @@ LayerTreeHostGtk::LayerTreeHostGtk(WebPage* webPage) : LayerTreeHost(webPage) , m_isValid(true) , m_notifyAfterScheduledLayerFlush(false) + , m_lastFlushTime(0) , m_layerFlushSchedulingEnabled(true) - , m_viewOverlayRootLayer(nullptr) - , m_renderFrameScheduler(std::bind(&LayerTreeHostGtk::renderFrame, this)) + , m_layerFlushTimerCallbackId(0) { } -bool LayerTreeHostGtk::makeContextCurrent() +GLContext* LayerTreeHostGtk::glContext() { - if (!m_layerTreeContext.contextID) { - m_context = nullptr; - return false; - } + if (m_context) + return m_context.get(); - if (!m_context) { - m_context = GLContext::createContextForWindow(reinterpret_cast<GLNativeWindowType>(m_layerTreeContext.contextID), GLContext::sharingContext()); - if (!m_context) - return false; - } + uint64_t windowHandle = m_webPage->nativeWindowHandle(); + if (!windowHandle) + return 0; - return m_context->makeContextCurrent(); + m_context = GLContext::createContextForWindow(windowHandle, GLContext::sharingContext()); + return m_context.get(); } void LayerTreeHostGtk::initialize() { - m_rootLayer = GraphicsLayer::create(graphicsLayerFactory(), *this); + m_rootLayer = GraphicsLayer::create(graphicsLayerFactory(), this); m_rootLayer->setDrawsContent(false); m_rootLayer->setSize(m_webPage->size()); - m_scaleMatrix.makeIdentity(); - m_scaleMatrix.scale(m_webPage->deviceScaleFactor() * m_webPage->pageScaleFactor()); - downcast<GraphicsLayerTextureMapper>(*m_rootLayer).layer().setAnchorPoint(FloatPoint3D()); - downcast<GraphicsLayerTextureMapper>(*m_rootLayer).layer().setTransform(m_scaleMatrix); - // The non-composited contents are a child of the root layer. - m_nonCompositedContentLayer = GraphicsLayer::create(graphicsLayerFactory(), *this); + m_nonCompositedContentLayer = GraphicsLayer::create(graphicsLayerFactory(), this); m_nonCompositedContentLayer->setDrawsContent(true); - m_nonCompositedContentLayer->setContentsOpaque(m_webPage->drawsBackground()); + m_nonCompositedContentLayer->setContentsOpaque(m_webPage->drawsBackground() && !m_webPage->drawsTransparentBackground()); m_nonCompositedContentLayer->setSize(m_webPage->size()); if (m_webPage->corePage()->settings().acceleratedDrawingEnabled()) m_nonCompositedContentLayer->setAcceleratesDrawing(true); @@ -185,6 +112,28 @@ void LayerTreeHostGtk::initialize() m_rootLayer->addChild(m_nonCompositedContentLayer.get()); m_nonCompositedContentLayer->setNeedsDisplay(); + + m_layerTreeContext.windowHandle = m_webPage->nativeWindowHandle(); + + GLContext* context = glContext(); + if (!context) + return; + + // The creation of the TextureMapper needs an active OpenGL context. + context->makeContextCurrent(); + + m_textureMapper = TextureMapperGL::create(); + static_cast<TextureMapperGL*>(m_textureMapper.get())->setEnableEdgeDistanceAntialiasing(true); + toTextureMapperLayer(m_rootLayer.get())->setTextureMapper(m_textureMapper.get()); + + if (m_webPage->hasPageOverlay()) { + PageOverlayList& pageOverlays = m_webPage->pageOverlays(); + PageOverlayList::iterator end = pageOverlays.end(); + for (PageOverlayList::iterator it = pageOverlays.begin(); it != end; ++it) + createPageOverlayLayer(it->get()); + } + + scheduleLayerFlush(); } LayerTreeHostGtk::~LayerTreeHostGtk() @@ -219,11 +168,6 @@ void LayerTreeHostGtk::invalidate() { ASSERT(m_isValid); - // This can trigger destruction of GL objects so let's make sure that - // we have the right active context - if (m_context) - m_context->makeContextCurrent(); - cancelPendingLayerFlush(); m_rootLayer = nullptr; m_nonCompositedContentLayer = nullptr; @@ -236,12 +180,22 @@ void LayerTreeHostGtk::invalidate() void LayerTreeHostGtk::setNonCompositedContentsNeedDisplay() { m_nonCompositedContentLayer->setNeedsDisplay(); + + PageOverlayLayerMap::iterator end = m_pageOverlayLayers.end(); + for (PageOverlayLayerMap::iterator it = m_pageOverlayLayers.begin(); it != end; ++it) + it->value->setNeedsDisplay(); + scheduleLayerFlush(); } void LayerTreeHostGtk::setNonCompositedContentsNeedDisplayInRect(const IntRect& rect) { m_nonCompositedContentLayer->setNeedsDisplayInRect(rect); + + PageOverlayLayerMap::iterator end = m_pageOverlayLayers.end(); + for (PageOverlayLayerMap::iterator it = m_pageOverlayLayers.begin(); it != end; ++it) + it->value->setNeedsDisplayInRect(rect); + scheduleLayerFlush(); } @@ -270,6 +224,10 @@ void LayerTreeHostGtk::sizeDidChange(const IntSize& newSize) m_nonCompositedContentLayer->setNeedsDisplayInRect(FloatRect(0, oldSize.height(), newSize.width(), newSize.height() - oldSize.height())); m_nonCompositedContentLayer->setNeedsDisplay(); + PageOverlayLayerMap::iterator end = m_pageOverlayLayers.end(); + for (PageOverlayLayerMap::iterator it = m_pageOverlayLayers.begin(); it != end; ++it) + it->value->setSize(newSize); + compositeLayersToContext(ForResize); } @@ -277,10 +235,6 @@ void LayerTreeHostGtk::deviceOrPageScaleFactorChanged() { // Other layers learn of the scale factor change via WebPage::setDeviceScaleFactor. m_nonCompositedContentLayer->deviceOrPageScaleFactorChanged(); - - m_scaleMatrix.makeIdentity(); - m_scaleMatrix.scale(m_webPage->deviceScaleFactor() * m_webPage->pageScaleFactor()); - downcast<GraphicsLayerTextureMapper>(*m_rootLayer).layer().setTransform(m_scaleMatrix); } void LayerTreeHostGtk::forceRepaint() @@ -288,47 +242,88 @@ void LayerTreeHostGtk::forceRepaint() scheduleLayerFlush(); } -void LayerTreeHostGtk::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& graphicsContext, GraphicsLayerPaintingPhase, const FloatRect& clipRect) +void LayerTreeHostGtk::didInstallPageOverlay(PageOverlay* pageOverlay) { - if (graphicsLayer == m_nonCompositedContentLayer.get()) - m_webPage->drawRect(graphicsContext, enclosingIntRect(clipRect)); + createPageOverlayLayer(pageOverlay); + scheduleLayerFlush(); } -float LayerTreeHostGtk::deviceScaleFactor() const +void LayerTreeHostGtk::didUninstallPageOverlay(PageOverlay* pageOverlay) { - return m_webPage->deviceScaleFactor(); + destroyPageOverlayLayer(pageOverlay); + scheduleLayerFlush(); +} + +void LayerTreeHostGtk::setPageOverlayNeedsDisplay(PageOverlay* pageOverlay, const IntRect& rect) +{ + GraphicsLayer* layer = m_pageOverlayLayers.get(pageOverlay); + if (!layer) + return; + + layer->setNeedsDisplayInRect(rect); + scheduleLayerFlush(); } -float LayerTreeHostGtk::pageScaleFactor() const +void LayerTreeHostGtk::notifyAnimationStarted(const WebCore::GraphicsLayer*, double time) { - return m_webPage->pageScaleFactor(); } -bool LayerTreeHostGtk::renderFrame() +void LayerTreeHostGtk::notifyFlushRequired(const WebCore::GraphicsLayer*) { +} + +void LayerTreeHostGtk::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& graphicsContext, GraphicsLayerPaintingPhase, const IntRect& clipRect) +{ + if (graphicsLayer == m_nonCompositedContentLayer.get()) { + m_webPage->drawRect(graphicsContext, clipRect); + return; + } + + for (auto& pageOverlayLayer : m_pageOverlayLayers) { + if (pageOverlayLayer.value.get() == graphicsLayer) { + m_webPage->drawPageOverlay(pageOverlayLayer.key, graphicsContext, clipRect); + break; + } + } +} + +gboolean LayerTreeHostGtk::layerFlushTimerFiredCallback(LayerTreeHostGtk* layerTreeHost) +{ + layerTreeHost->layerFlushTimerFired(); + return FALSE; +} + +void LayerTreeHostGtk::layerFlushTimerFired() +{ + ASSERT(m_layerFlushTimerCallbackId); + m_layerFlushTimerCallbackId = 0; + flushAndRenderLayers(); - return downcast<GraphicsLayerTextureMapper>(*m_rootLayer).layer().descendantsOrSelfHaveRunningAnimations(); + + if (toTextureMapperLayer(m_rootLayer.get())->descendantsOrSelfHaveRunningAnimations() && !m_layerFlushTimerCallbackId) { + const double targetFPS = 60; + double nextFlush = std::max((1 / targetFPS) - (currentTime() - m_lastFlushTime), 0.0); + m_layerFlushTimerCallbackId = g_timeout_add_full(GDK_PRIORITY_EVENTS, nextFlush * 1000.0, reinterpret_cast<GSourceFunc>(layerFlushTimerFiredCallback), this, 0); + g_source_set_name_by_id(m_layerFlushTimerCallbackId, "[WebKit] layerFlushTimerFiredCallback"); + } } bool LayerTreeHostGtk::flushPendingLayerChanges() { - bool viewportIsStable = m_webPage->corePage()->mainFrame().view()->viewportIsStable(); - m_rootLayer->flushCompositingStateForThisLayerOnly(viewportIsStable); - m_nonCompositedContentLayer->flushCompositingStateForThisLayerOnly(viewportIsStable); - - if (!m_webPage->corePage()->mainFrame().view()->flushCompositingStateIncludingSubframes()) - return false; + m_rootLayer->flushCompositingStateForThisLayerOnly(); + m_nonCompositedContentLayer->flushCompositingStateForThisLayerOnly(); - if (m_viewOverlayRootLayer) - m_viewOverlayRootLayer->flushCompositingState(FloatRect(FloatPoint(), m_rootLayer->size()), viewportIsStable); + PageOverlayLayerMap::iterator end = m_pageOverlayLayers.end(); + for (PageOverlayLayerMap::iterator it = m_pageOverlayLayers.begin(); it != end; ++it) + it->value->flushCompositingStateForThisLayerOnly(); - downcast<GraphicsLayerTextureMapper>(*m_rootLayer).updateBackingStoreIncludingSubLayers(); - return true; + return m_webPage->corePage()->mainFrame().view()->flushCompositingStateIncludingSubframes(); } void LayerTreeHostGtk::compositeLayersToContext(CompositePurpose purpose) { - if (!makeContextCurrent()) + GLContext* context = glContext(); + if (!context || !context->makeContextCurrent()) return; // The window size may be out of sync with the page size at this point, and getting @@ -342,12 +337,11 @@ void LayerTreeHostGtk::compositeLayersToContext(CompositePurpose purpose) glClear(GL_COLOR_BUFFER_BIT); } - ASSERT(m_textureMapper); m_textureMapper->beginPainting(); - downcast<GraphicsLayerTextureMapper>(*m_rootLayer).layer().paint(); + toTextureMapperLayer(m_rootLayer.get())->paint(); m_textureMapper->endPainting(); - m_context->swapBuffers(); + context->swapBuffers(); } void LayerTreeHostGtk::flushAndRenderLayers() @@ -360,9 +354,11 @@ void LayerTreeHostGtk::flushAndRenderLayers() return; } - if (!makeContextCurrent()) + GLContext* context = glContext(); + if (!context || !context->makeContextCurrent()) return; + m_lastFlushTime = currentTime(); if (!flushPendingLayerChanges()) return; @@ -376,12 +372,41 @@ void LayerTreeHostGtk::flushAndRenderLayers() } } +void LayerTreeHostGtk::createPageOverlayLayer(PageOverlay* pageOverlay) +{ + std::unique_ptr<GraphicsLayer> layer = GraphicsLayer::create(graphicsLayerFactory(), this); +#ifndef NDEBUG + layer->setName("LayerTreeHost page overlay content"); +#endif + + layer->setAcceleratesDrawing(m_webPage->corePage()->settings().acceleratedDrawingEnabled()); + layer->setDrawsContent(true); + layer->setSize(m_webPage->size()); + layer->setShowDebugBorder(m_webPage->corePage()->settings().showDebugBorders()); + layer->setShowRepaintCounter(m_webPage->corePage()->settings().showRepaintCounter()); + + m_rootLayer->addChild(layer.get()); + m_pageOverlayLayers.add(pageOverlay, std::move(layer)); +} + +void LayerTreeHostGtk::destroyPageOverlayLayer(PageOverlay* pageOverlay) +{ + std::unique_ptr<GraphicsLayer> layer = m_pageOverlayLayers.take(pageOverlay); + ASSERT(layer); + + layer->removeFromParent(); +} + void LayerTreeHostGtk::scheduleLayerFlush() { - if (!m_layerFlushSchedulingEnabled || !m_textureMapper) + if (!m_layerFlushSchedulingEnabled) return; - m_renderFrameScheduler.start(); + // We use a GLib timer because otherwise GTK+ event handling during dragging can starve WebCore timers, which have a lower priority. + if (!m_layerFlushTimerCallbackId) { + m_layerFlushTimerCallbackId = g_timeout_add_full(GDK_PRIORITY_EVENTS, 0, reinterpret_cast<GSourceFunc>(layerFlushTimerFiredCallback), this, 0); + g_source_set_name_by_id(m_layerFlushTimerCallbackId, "[WebKit] layerFlushTimerFiredCallback"); + } } void LayerTreeHostGtk::setLayerFlushSchedulingEnabled(bool layerFlushingEnabled) @@ -401,37 +426,16 @@ void LayerTreeHostGtk::setLayerFlushSchedulingEnabled(bool layerFlushingEnabled) void LayerTreeHostGtk::pageBackgroundTransparencyChanged() { - m_nonCompositedContentLayer->setContentsOpaque(m_webPage->drawsBackground()); + m_nonCompositedContentLayer->setContentsOpaque(m_webPage->drawsBackground() && !m_webPage->drawsTransparentBackground()); } void LayerTreeHostGtk::cancelPendingLayerFlush() { - m_renderFrameScheduler.stop(); -} - -void LayerTreeHostGtk::setViewOverlayRootLayer(WebCore::GraphicsLayer* viewOverlayRootLayer) -{ - m_viewOverlayRootLayer = viewOverlayRootLayer; - if (m_viewOverlayRootLayer) - m_rootLayer->addChild(m_viewOverlayRootLayer); -} - -void LayerTreeHostGtk::setNativeSurfaceHandleForCompositing(uint64_t handle) -{ - cancelPendingLayerFlush(); - m_layerTreeContext.contextID = handle; - - // The creation of the TextureMapper needs an active OpenGL context. - if (!makeContextCurrent()) + if (!m_layerFlushTimerCallbackId) return; - ASSERT(m_isValid); - ASSERT(!m_textureMapper); - m_textureMapper = TextureMapper::create(); - static_cast<TextureMapperGL*>(m_textureMapper.get())->setEnableEdgeDistanceAntialiasing(true); - downcast<GraphicsLayerTextureMapper>(*m_rootLayer).layer().setTextureMapper(m_textureMapper.get()); - - scheduleLayerFlush(); + g_source_remove(m_layerFlushTimerCallbackId); + m_layerFlushTimerCallbackId = 0; } } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/gtk/LayerTreeHostGtk.h b/Source/WebKit2/WebProcess/WebPage/gtk/LayerTreeHostGtk.h index 2da9aacce..bb30b0990 100644 --- a/Source/WebKit2/WebProcess/WebPage/gtk/LayerTreeHostGtk.h +++ b/Source/WebKit2/WebProcess/WebPage/gtk/LayerTreeHostGtk.h @@ -34,12 +34,12 @@ #include "TextureMapperLayer.h" #include <WebCore/GLContext.h> #include <WebCore/GraphicsLayerClient.h> -#include <WebCore/TransformationMatrix.h> -#include <wtf/RunLoop.h> +#include <wtf/HashMap.h> +#include <wtf/OwnPtr.h> namespace WebKit { -class LayerTreeHostGtk final : public LayerTreeHost, WebCore::GraphicsLayerClient { +class LayerTreeHostGtk : public LayerTreeHost, WebCore::GraphicsLayerClient { public: static PassRefPtr<LayerTreeHostGtk> create(WebPage*); virtual ~LayerTreeHostGtk(); @@ -51,54 +51,39 @@ protected: void initialize(); - // LayerTreeHost - virtual void scheduleLayerFlush() override; - virtual void setLayerFlushSchedulingEnabled(bool layerFlushingEnabled) override; - virtual void setRootCompositingLayer(WebCore::GraphicsLayer*) override; - virtual void invalidate() override; - - virtual void forceRepaint() override; - virtual void sizeDidChange(const WebCore::IntSize& newSize) override; - virtual void deviceOrPageScaleFactorChanged() override; + // LayerTreeHost. + virtual void invalidate(); + virtual void sizeDidChange(const WebCore::IntSize& newSize); + virtual void deviceOrPageScaleFactorChanged(); + virtual void forceRepaint(); + virtual void setRootCompositingLayer(WebCore::GraphicsLayer*); + virtual void scheduleLayerFlush(); + virtual void setLayerFlushSchedulingEnabled(bool layerFlushingEnabled); virtual void pageBackgroundTransparencyChanged() override; - virtual void setNativeSurfaceHandleForCompositing(uint64_t) override; - private: - - class RenderFrameScheduler { - public: - RenderFrameScheduler(std::function<bool()>); - ~RenderFrameScheduler(); - - void start(); - void stop(); - - private: - void renderFrame(); - void nextFrame(); - - std::function<bool()> m_renderer; - RunLoop::Timer<RenderFrameScheduler> m_timer; - double m_fireTime { 0 }; - double m_lastImmediateFlushTime { 0 }; - }; - - // LayerTreeHost - virtual const LayerTreeContext& layerTreeContext() override; - virtual void setShouldNotifyAfterNextScheduledLayerFlush(bool) override; + // LayerTreeHost. + virtual const LayerTreeContext& layerTreeContext(); + virtual void setShouldNotifyAfterNextScheduledLayerFlush(bool); virtual void setNonCompositedContentsNeedDisplay() override; virtual void setNonCompositedContentsNeedDisplayInRect(const WebCore::IntRect&) override; - virtual void scrollNonCompositedContents(const WebCore::IntRect& scrollRect) override; - virtual void setViewOverlayRootLayer(WebCore::GraphicsLayer*) override; + virtual void scrollNonCompositedContents(const WebCore::IntRect& scrollRect); + + virtual void didInstallPageOverlay(PageOverlay*) override; + virtual void didUninstallPageOverlay(PageOverlay*) override; + virtual void setPageOverlayNeedsDisplay(PageOverlay*, const WebCore::IntRect&) override; + + virtual bool flushPendingLayerChanges(); // GraphicsLayerClient - virtual void paintContents(const WebCore::GraphicsLayer*, WebCore::GraphicsContext&, WebCore::GraphicsLayerPaintingPhase, const WebCore::FloatRect& clipRect) override; - virtual float deviceScaleFactor() const override; - virtual float pageScaleFactor() const override; + virtual void notifyAnimationStarted(const WebCore::GraphicsLayer*, double time); + virtual void notifyFlushRequired(const WebCore::GraphicsLayer*); + virtual void paintContents(const WebCore::GraphicsLayer*, WebCore::GraphicsContext&, WebCore::GraphicsLayerPaintingPhase, const WebCore::IntRect& clipRect); + virtual void didCommitChangesForLayer(const WebCore::GraphicsLayer*) const { } - bool flushPendingLayerChanges(); + void createPageOverlayLayer(PageOverlay*); + void destroyPageOverlayLayer(PageOverlay*); enum CompositePurpose { ForResize, NotForResize }; void compositeLayersToContext(CompositePurpose = NotForResize); @@ -106,21 +91,23 @@ private: void flushAndRenderLayers(); void cancelPendingLayerFlush(); - bool renderFrame(); + void layerFlushTimerFired(); + static gboolean layerFlushTimerFiredCallback(LayerTreeHostGtk*); - bool makeContextCurrent(); + WebCore::GLContext* glContext(); LayerTreeContext m_layerTreeContext; bool m_isValid; bool m_notifyAfterScheduledLayerFlush; std::unique_ptr<WebCore::GraphicsLayer> m_rootLayer; std::unique_ptr<WebCore::GraphicsLayer> m_nonCompositedContentLayer; - std::unique_ptr<WebCore::TextureMapper> m_textureMapper; - std::unique_ptr<WebCore::GLContext> m_context; + typedef HashMap<PageOverlay*, std::unique_ptr<WebCore::GraphicsLayer>> PageOverlayLayerMap; + PageOverlayLayerMap m_pageOverlayLayers; + OwnPtr<WebCore::TextureMapper> m_textureMapper; + OwnPtr<WebCore::GLContext> m_context; + double m_lastFlushTime; bool m_layerFlushSchedulingEnabled; - WebCore::GraphicsLayer* m_viewOverlayRootLayer; - WebCore::TransformationMatrix m_scaleMatrix; - RenderFrameScheduler m_renderFrameScheduler; + unsigned m_layerFlushTimerCallbackId; }; } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/gtk/PrinterListGtk.cpp b/Source/WebKit2/WebProcess/WebPage/gtk/PrinterListGtk.cpp index 8ddc912f6..2d54bcc6c 100644 --- a/Source/WebKit2/WebProcess/WebPage/gtk/PrinterListGtk.cpp +++ b/Source/WebKit2/WebProcess/WebPage/gtk/PrinterListGtk.cpp @@ -26,7 +26,7 @@ #include "config.h" #include "PrinterListGtk.h" -#if HAVE(GTK_UNIX_PRINTING) +#ifdef HAVE_GTK_UNIX_PRINTING #include <gtk/gtkunixprint.h> @@ -34,26 +34,27 @@ namespace WebKit { PrinterListGtk* PrinterListGtk::s_sharedPrinterList = nullptr; -RefPtr<PrinterListGtk> PrinterListGtk::getOrCreate() +RefPtr<PrinterListGtk> PrinterListGtk::shared() { if (s_sharedPrinterList) - return s_sharedPrinterList->isEnumeratingPrinters() ? nullptr : s_sharedPrinterList; + return s_sharedPrinterList; return adoptRef(new PrinterListGtk); } +gboolean PrinterListGtk::enumeratePrintersFunction(GtkPrinter* printer) +{ + ASSERT(s_sharedPrinterList); + s_sharedPrinterList->addPrinter(printer); + return FALSE; +} + PrinterListGtk::PrinterListGtk() : m_defaultPrinter(nullptr) - , m_enumeratingPrinters(true) { ASSERT(!s_sharedPrinterList); s_sharedPrinterList = this; - gtk_enumerate_printers([](GtkPrinter* printer, gpointer) -> gboolean { - ASSERT(s_sharedPrinterList); - s_sharedPrinterList->addPrinter(printer); - return FALSE; - }, nullptr, nullptr, TRUE); - m_enumeratingPrinters = false; + gtk_enumerate_printers(reinterpret_cast<GtkPrinterFunc>(&enumeratePrintersFunction), nullptr, nullptr, TRUE); } PrinterListGtk::~PrinterListGtk() @@ -80,4 +81,4 @@ GtkPrinter* PrinterListGtk::findPrinter(const char* printerName) const } // namespace WebKit -#endif // HAVE(GTK_UNIX_PRINTING) +#endif // HAVE_GTK_UNIX_PRINTING diff --git a/Source/WebKit2/WebProcess/WebPage/gtk/PrinterListGtk.h b/Source/WebKit2/WebProcess/WebPage/gtk/PrinterListGtk.h index e13cb2995..8d8a952b4 100644 --- a/Source/WebKit2/WebProcess/WebPage/gtk/PrinterListGtk.h +++ b/Source/WebKit2/WebProcess/WebPage/gtk/PrinterListGtk.h @@ -26,11 +26,11 @@ #ifndef PrinterListGtk_h #define PrinterListGtk_h -#if HAVE(GTK_UNIX_PRINTING) +#ifdef HAVE_GTK_UNIX_PRINTING #include <wtf/RefCounted.h> #include <wtf/Vector.h> -#include <wtf/glib/GRefPtr.h> +#include <wtf/gobject/GRefPtr.h> typedef struct _GtkPrinter GtkPrinter; @@ -38,7 +38,7 @@ namespace WebKit { class PrinterListGtk: public RefCounted<PrinterListGtk> { public: - static RefPtr<PrinterListGtk> getOrCreate(); + static RefPtr<PrinterListGtk> shared(); ~PrinterListGtk(); GtkPrinter* findPrinter(const char*) const; @@ -47,17 +47,16 @@ public: private: PrinterListGtk(); + static gboolean enumeratePrintersFunction(GtkPrinter*); void addPrinter(GtkPrinter*); - bool isEnumeratingPrinters() const { return m_enumeratingPrinters; } Vector<GRefPtr<GtkPrinter>, 4> m_printerList; GtkPrinter* m_defaultPrinter; - bool m_enumeratingPrinters; static PrinterListGtk* s_sharedPrinterList; }; } // namespace WebKit -#endif // HAVE(GTK_UNIX_PRINTING) +#endif // HAVE_GTK_UNIX_PRINTING #endif // WebPrintOperationGtk_h diff --git a/Source/WebKit2/WebProcess/WebPage/gtk/WebInspectorUIGtk.cpp b/Source/WebKit2/WebProcess/WebPage/gtk/WebInspectorGtk.cpp index fd895cbb3..5a0ef9e32 100644 --- a/Source/WebKit2/WebProcess/WebPage/gtk/WebInspectorUIGtk.cpp +++ b/Source/WebKit2/WebProcess/WebPage/gtk/WebInspectorGtk.cpp @@ -25,7 +25,9 @@ */ #include "config.h" -#include "WebInspectorUI.h" +#include "WebInspector.h" + +#if ENABLE(INSPECTOR) #include <WebCore/FileSystem.h> #include <glib.h> @@ -33,14 +35,16 @@ namespace WebKit { -bool WebInspectorUI::canSave() +bool WebInspector::canSave() const { return false; } -String WebInspectorUI::localizedStringsURL() +String WebInspector::localizedStringsURL() const { return String("resource:///org/webkitgtk/inspector/Localizations/en.lproj/localizedStrings.js"); } } // namespace WebKit + +#endif // ENABLE(INSPECTOR) diff --git a/Source/WebKit2/WebProcess/WebPage/gtk/WebPageGtk.cpp b/Source/WebKit2/WebProcess/WebPage/gtk/WebPageGtk.cpp index e6b8074c9..338cf565b 100644 --- a/Source/WebKit2/WebProcess/WebPage/gtk/WebPageGtk.cpp +++ b/Source/WebKit2/WebProcess/WebPage/gtk/WebPageGtk.cpp @@ -28,7 +28,6 @@ #include "config.h" #include "WebPage.h" -#include "EditorState.h" #include "NotImplemented.h" #include "WebEvent.h" #include "WebPageAccessibilityObject.h" @@ -38,14 +37,13 @@ #include <WebCore/EventHandler.h> #include <WebCore/FocusController.h> #include <WebCore/Frame.h> -#include <WebCore/FrameView.h> #include <WebCore/KeyboardEvent.h> #include <WebCore/Page.h> #include <WebCore/PasteboardHelper.h> #include <WebCore/PlatformKeyboardEvent.h> #include <WebCore/Settings.h> #include <WebCore/UserAgentGtk.h> -#include <wtf/glib/GUniquePtr.h> +#include <wtf/gobject/GUniquePtr.h> using namespace WebCore; @@ -62,46 +60,10 @@ void WebPage::platformInitialize() GUniquePtr<gchar> plugID(atk_plug_get_id(ATK_PLUG(m_accessibilityObject.get()))); send(Messages::WebPageProxy::BindAccessibilityTree(String(plugID.get()))); #endif -} - -void WebPage::platformDetach() -{ -} - -void WebPage::platformEditorState(Frame& frame, EditorState& result, IncludePostLayoutDataHint shouldIncludePostLayoutData) const -{ - if (shouldIncludePostLayoutData == IncludePostLayoutDataHint::No) { - result.isMissingPostLayoutData = true; - return; - } - auto& postLayoutData = result.postLayoutData(); - postLayoutData.caretRectAtStart = frame.selection().absoluteCaretBounds(); - - const VisibleSelection& selection = frame.selection().selection(); - if (selection.isNone()) - return; - - const Editor& editor = frame.editor(); - if (selection.isRange()) { - if (editor.selectionHasStyle(CSSPropertyFontWeight, "bold") == TrueTriState) - postLayoutData.typingAttributes |= AttributeBold; - if (editor.selectionHasStyle(CSSPropertyFontStyle, "italic") == TrueTriState) - postLayoutData.typingAttributes |= AttributeItalics; - if (editor.selectionHasStyle(CSSPropertyWebkitTextDecorationsInEffect, "underline") == TrueTriState) - postLayoutData.typingAttributes |= AttributeUnderline; - if (editor.selectionHasStyle(CSSPropertyWebkitTextDecorationsInEffect, "line-through") == TrueTriState) - postLayoutData.typingAttributes |= AttributeStrikeThrough; - } else if (selection.isCaret()) { - if (editor.selectionStartHasStyle(CSSPropertyFontWeight, "bold")) - postLayoutData.typingAttributes |= AttributeBold; - if (editor.selectionStartHasStyle(CSSPropertyFontStyle, "italic")) - postLayoutData.typingAttributes |= AttributeItalics; - if (editor.selectionStartHasStyle(CSSPropertyWebkitTextDecorationsInEffect, "underline")) - postLayoutData.typingAttributes |= AttributeUnderline; - if (editor.selectionStartHasStyle(CSSPropertyWebkitTextDecorationsInEffect, "line-through")) - postLayoutData.typingAttributes |= AttributeStrikeThrough; - } +#if USE(TEXTURE_MAPPER_GL) + m_nativeWindowHandle = 0; +#endif } #if HAVE(ACCESSIBILITY) @@ -119,12 +81,23 @@ void WebPage::platformPreferencesDidChange(const WebPreferencesStore&) notImplemented(); } +static inline void scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity) +{ + page->focusController().focusedOrMainFrame().eventHandler().scrollRecursively(direction, granularity); +} + bool WebPage::performDefaultBehaviorForKeyEvent(const WebKeyboardEvent& keyboardEvent) { if (keyboardEvent.type() != WebEvent::KeyDown && keyboardEvent.type() != WebEvent::RawKeyDown) return false; switch (keyboardEvent.windowsVirtualKeyCode()) { + case VK_BACK: + if (keyboardEvent.shiftKey()) + m_page->backForward().goForward(); + else + m_page->backForward().goBack(); + break; case VK_SPACE: scroll(m_page.get(), keyboardEvent.shiftKey() ? ScrollUp : ScrollDown, ScrollByPage); break; @@ -189,6 +162,12 @@ PassRefPtr<SharedBuffer> WebPage::cachedResponseDataForURL(const URL&) return 0; } +#if USE(TEXTURE_MAPPER_GL) +void WebPage::setAcceleratedCompositingWindowId(int64_t nativeWindowHandle) +{ + m_nativeWindowHandle = nativeWindowHandle; +} +#endif String WebPage::platformUserAgent(const URL& url) const { @@ -198,22 +177,4 @@ String WebPage::platformUserAgent(const URL& url) const return WebCore::standardUserAgentForURL(url); } -#if HAVE(GTK_GESTURES) -void WebPage::getCenterForZoomGesture(const IntPoint& centerInViewCoordinates, IntPoint& result) -{ - result = mainFrameView()->rootViewToContents(centerInViewCoordinates); - double scale = m_page->pageScaleFactor(); - result.scale(1 / scale, 1 / scale); -} -#endif - -void WebPage::setInputMethodState(bool enabled) -{ - if (m_inputMethodEnabled == enabled) - return; - - m_inputMethodEnabled = enabled; - send(Messages::WebPageProxy::SetInputMethodState(enabled)); -} - } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/WebPage/gtk/WebPrintOperationGtk.cpp b/Source/WebKit2/WebProcess/WebPage/gtk/WebPrintOperationGtk.cpp index b6205db94..e79cc75c2 100644 --- a/Source/WebKit2/WebProcess/WebPage/gtk/WebPrintOperationGtk.cpp +++ b/Source/WebKit2/WebProcess/WebPage/gtk/WebPrintOperationGtk.cpp @@ -40,11 +40,10 @@ #include <WebCore/ResourceError.h> #include <WebCore/URL.h> #include <gtk/gtk.h> -#include <memory> #include <wtf/Vector.h> -#include <wtf/glib/GUniquePtr.h> +#include <wtf/gobject/GUniquePtr.h> -#if HAVE(GTK_UNIX_PRINTING) +#ifdef HAVE_GTK_UNIX_PRINTING #include "PrinterListGtk.h" #include <cairo-pdf.h> #include <cairo-ps.h> @@ -53,7 +52,7 @@ namespace WebKit { -#if HAVE(GTK_UNIX_PRINTING) +#ifdef HAVE_GTK_UNIX_PRINTING class WebPrintOperationGtkUnix final: public WebPrintOperationGtk { public: WebPrintOperationGtkUnix(WebPage* page, const PrintInfo& printInfo) @@ -67,8 +66,7 @@ public: m_printContext = printContext; m_callbackID = callbackID; - RefPtr<PrinterListGtk> printerList = PrinterListGtk::getOrCreate(); - ASSERT(printerList); + RefPtr<PrinterListGtk> printerList = PrinterListGtk::shared(); const char* printerName = gtk_print_settings_get_printer(m_printSettings.get()); GtkPrinter* printer = printerName ? printerList->findPrinter(printerName) : printerList->defaultPrinter(); if (!printer) { @@ -106,7 +104,7 @@ public: print(surface, 72, 72); } - void startPage(cairo_t*) override + void startPage(cairo_t* cr) override { if (!currentPageIsFirstPageOfSheet()) return; @@ -141,7 +139,7 @@ public: cairo_show_page(cr); } - static void printJobComplete(GtkPrintJob*, WebPrintOperationGtkUnix* printOperation, const GError* error) + static void printJobComplete(GtkPrintJob* printJob, WebPrintOperationGtkUnix* printOperation, const GError* error) { printOperation->printDone(error ? printError(printOperation->frameURL(), error->message) : WebCore::ResourceError()); printOperation->m_printJob = 0; @@ -150,13 +148,13 @@ public: static void printJobFinished(WebPrintOperationGtkUnix* printOperation) { printOperation->deref(); - WebProcess::singleton().enableTermination(); + WebProcess::shared().enableTermination(); } void endPrint() override { // Disable web process termination until the print job finishes. - WebProcess::singleton().disableTermination(); + WebProcess::shared().disableTermination(); cairo_surface_finish(gtk_print_job_get_surface(m_printJob.get(), 0)); // Make sure the operation is alive until the job is sent. @@ -381,13 +379,11 @@ struct PrintPagesData { PassRefPtr<WebPrintOperationGtk> WebPrintOperationGtk::create(WebPage* page, const PrintInfo& printInfo) { -#if HAVE(GTK_UNIX_PRINTING) +#ifdef HAVE_GTK_UNIX_PRINTING return adoptRef(new WebPrintOperationGtkUnix(page, printInfo)); #elif defined(G_OS_WIN32) return adoptRef(new WebPrintOperationGtkWin32(page, printInfo)); #else - UNUSED_PARAM(page); - UNUSED_PARAM(printInfo); return 0; #endif } @@ -699,7 +695,7 @@ void WebPrintOperationGtk::printPagesDone() { m_printPagesIdleId = 0; endPrint(); - m_cairoContext = nullptr; + m_cairoContext = 0; } void WebPrintOperationGtk::printDone(const WebCore::ResourceError& error) @@ -717,7 +713,7 @@ void WebPrintOperationGtk::print(cairo_surface_t* surface, double xDPI, double y { ASSERT(m_printContext); - auto data = std::make_unique<PrintPagesData>(this); + OwnPtr<PrintPagesData> data = adoptPtr(new PrintPagesData(this)); if (!data->isValid) { cairo_surface_finish(surface); printDone(invalidPageRangeToPrint(frameURL())); @@ -733,7 +729,7 @@ void WebPrintOperationGtk::print(cairo_surface_t* surface, double xDPI, double y // operation has finished. See https://bugs.webkit.org/show_bug.cgi?id=122801. unsigned idlePriority = m_printMode == PrintInfo::PrintModeSync ? G_PRIORITY_DEFAULT - 10 : G_PRIORITY_DEFAULT_IDLE + 10; GMainLoop* mainLoop = data->mainLoop.get(); - m_printPagesIdleId = gdk_threads_add_idle_full(idlePriority, printPagesIdle, data.release(), printPagesIdleDone); + m_printPagesIdleId = gdk_threads_add_idle_full(idlePriority, printPagesIdle, data.leakPtr(), printPagesIdleDone); if (m_printMode == PrintInfo::PrintModeSync) { ASSERT(mainLoop); g_main_loop_run(mainLoop); diff --git a/Source/WebKit2/WebProcess/WebPage/gtk/WebPrintOperationGtk.h b/Source/WebKit2/WebProcess/WebPage/gtk/WebPrintOperationGtk.h index f5fec106c..c201a2ef9 100644 --- a/Source/WebKit2/WebProcess/WebPage/gtk/WebPrintOperationGtk.h +++ b/Source/WebKit2/WebProcess/WebPage/gtk/WebPrintOperationGtk.h @@ -30,7 +30,7 @@ #include <WebCore/RefPtrCairo.h> #include <wtf/PassRefPtr.h> #include <wtf/RefCounted.h> -#include <wtf/glib/GRefPtr.h> +#include <wtf/gobject/GRefPtr.h> typedef struct _GtkPrintSettings GtkPrintSettings; typedef struct _GtkPageSetup GtkPageSetup; |
