Add a WebViewDidMoveToWindowObserver for WKWebView
[WebKit-https.git] / Source / WebKit / UIProcess / SuspendedPageProxy.cpp
1 /*
2  * Copyright (C) 2018 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "SuspendedPageProxy.h"
28
29 #include "DrawingAreaProxy.h"
30 #include "Logging.h"
31 #include "WebPageMessages.h"
32 #include "WebPageProxy.h"
33 #include "WebPageProxyMessages.h"
34 #include "WebProcessMessages.h"
35 #include "WebProcessPool.h"
36 #include "WebProcessProxy.h"
37 #include <wtf/DebugUtilities.h>
38 #include <wtf/HexNumber.h>
39 #include <wtf/URL.h>
40
41 namespace WebKit {
42 using namespace WebCore;
43
44 static const Seconds suspensionTimeout { 10_s };
45
46 #if !LOG_DISABLED
47 static const HashSet<IPC::StringReference>& messageNamesToIgnoreWhileSuspended()
48 {
49     static NeverDestroyed<HashSet<IPC::StringReference>> messageNames;
50     static std::once_flag onceFlag;
51     std::call_once(onceFlag, [] {
52         messageNames.get().add("BackForwardAddItem");
53         messageNames.get().add("ClearAllEditCommands");
54         messageNames.get().add("DidChangeContentSize");
55         messageNames.get().add("DidChangeMainDocument");
56         messageNames.get().add("DidChangeProgress");
57         messageNames.get().add("DidCommitLoadForFrame");
58         messageNames.get().add("DidDestroyNavigation");
59         messageNames.get().add("DidFinishDocumentLoadForFrame");
60         messageNames.get().add("DidFinishProgress");
61         messageNames.get().add("DidCompletePageTransition");
62         messageNames.get().add("DidFirstLayoutForFrame");
63         messageNames.get().add("DidFirstVisuallyNonEmptyLayoutForFrame");
64         messageNames.get().add("DidNavigateWithNavigationData");
65         messageNames.get().add("DidReachLayoutMilestone");
66         messageNames.get().add("DidRestoreScrollPosition");
67         messageNames.get().add("DidSaveToPageCache");
68         messageNames.get().add("DidStartProgress");
69         messageNames.get().add("DidStartProvisionalLoadForFrame");
70         messageNames.get().add("EditorStateChanged");
71         messageNames.get().add("PageExtendedBackgroundColorDidChange");
72         messageNames.get().add("SetRenderTreeSize");
73         messageNames.get().add("SetStatusText");
74         messageNames.get().add("SetNetworkRequestsInProgress");
75     });
76
77     return messageNames;
78 }
79 #endif
80
81 SuspendedPageProxy::SuspendedPageProxy(WebPageProxy& page, Ref<WebProcessProxy>&& process, WebBackForwardListItem& item, uint64_t mainFrameID)
82     : m_page(page)
83     , m_process(WTFMove(process))
84     , m_mainFrameID(mainFrameID)
85     , m_registrableDomain(toRegistrableDomain(URL(URL(), item.url())))
86     , m_suspensionTimeoutTimer(RunLoop::main(), this, &SuspendedPageProxy::suspensionTimedOut)
87 #if PLATFORM(IOS_FAMILY)
88     , m_suspensionToken(m_process->throttler().backgroundActivityToken())
89 #endif
90 {
91     item.setSuspendedPage(this);
92     m_process->incrementSuspendedPageCount();
93     m_process->addMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_page.pageID(), *this);
94
95     m_suspensionTimeoutTimer.startOneShot(suspensionTimeout);
96     m_process->send(Messages::WebPage::SetIsSuspended(true), m_page.pageID());
97 }
98
99 SuspendedPageProxy::~SuspendedPageProxy()
100 {
101     m_process->decrementSuspendedPageCount();
102
103     if (m_readyToUnsuspendHandler) {
104         RunLoop::main().dispatch([readyToUnsuspendHandler = WTFMove(m_readyToUnsuspendHandler)]() mutable {
105             readyToUnsuspendHandler(nullptr);
106         });
107     }
108
109     if (m_suspensionState == SuspensionState::Resumed)
110         return;
111
112     // If the suspended page was not consumed before getting destroyed, then close the corresponding page
113     // on the WebProcess side.
114     close();
115
116     if (m_suspensionState == SuspensionState::Suspending)
117         m_process->removeMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_page.pageID());
118
119     // We call maybeShutDown() asynchronously since the SuspendedPage is currently being removed from the WebProcessPool
120     // and we want to avoid re-entering WebProcessPool methods.
121     RunLoop::main().dispatch([process = m_process.copyRef()] {
122         process->maybeShutDown();
123     });
124 }
125
126 void SuspendedPageProxy::waitUntilReadyToUnsuspend(CompletionHandler<void(SuspendedPageProxy*)>&& completionHandler)
127 {
128     if (m_readyToUnsuspendHandler)
129         m_readyToUnsuspendHandler(nullptr);
130
131     switch (m_suspensionState) {
132     case SuspensionState::Suspending:
133         m_readyToUnsuspendHandler = WTFMove(completionHandler);
134         break;
135     case SuspensionState::FailedToSuspend:
136     case SuspensionState::Suspended:
137         completionHandler(this);
138         break;
139     case SuspensionState::Resumed:
140         ASSERT_NOT_REACHED();
141         completionHandler(nullptr);
142         break;
143     }
144 }
145
146 void SuspendedPageProxy::unsuspend()
147 {
148     ASSERT(m_suspensionState == SuspensionState::Suspended);
149
150     m_suspensionState = SuspensionState::Resumed;
151     m_process->send(Messages::WebPage::SetIsSuspended(false), m_page.pageID());
152 }
153
154 void SuspendedPageProxy::close()
155 {
156     ASSERT(m_suspensionState != SuspensionState::Resumed);
157
158     if (m_isClosed)
159         return;
160
161     m_isClosed = true;
162     m_process->send(Messages::WebPage::Close(), m_page.pageID());
163 }
164
165 void SuspendedPageProxy::didProcessRequestToSuspend(SuspensionState newSuspensionState)
166 {
167     LOG(ProcessSwapping, "SuspendedPageProxy %s from process %i finished transition to suspended", loggingString(), m_process->processIdentifier());
168
169     ASSERT(m_suspensionState == SuspensionState::Suspending);
170     ASSERT(newSuspensionState == SuspensionState::Suspended || newSuspensionState == SuspensionState::FailedToSuspend);
171
172     m_suspensionState = newSuspensionState;
173
174     m_suspensionTimeoutTimer.stop();
175
176 #if PLATFORM(IOS_FAMILY)
177     m_suspensionToken = nullptr;
178 #endif
179
180     m_process->removeMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_page.pageID());
181
182     bool shouldDelayClosingOnFailure = false;
183 #if PLATFORM(MAC)
184     // With web process side tiles, we need to keep the suspended page around on failure to avoid flashing.
185     // It is removed by WebPageProxy::enterAcceleratedCompositingMode when the target page is ready.
186     shouldDelayClosingOnFailure = m_page.drawingArea() && m_page.drawingArea()->type() == DrawingAreaTypeTiledCoreAnimation;
187 #endif
188     if (m_suspensionState == SuspensionState::FailedToSuspend && !shouldDelayClosingOnFailure)
189         close();
190
191     if (m_readyToUnsuspendHandler)
192         m_readyToUnsuspendHandler(this);
193 }
194
195 void SuspendedPageProxy::suspensionTimedOut()
196 {
197     RELEASE_LOG_ERROR(ProcessSwapping, "%p - SuspendedPageProxy::suspensionTimedOut() destroying the suspended page because it failed to suspend in time", this);
198     m_process->processPool().removeSuspendedPage(*this); // Will destroy |this|.
199 }
200
201 void SuspendedPageProxy::didReceiveMessage(IPC::Connection&, IPC::Decoder& decoder)
202 {
203     ASSERT(decoder.messageReceiverName() == Messages::WebPageProxy::messageReceiverName());
204
205     if (decoder.messageName() == Messages::WebPageProxy::DidSuspendAfterProcessSwap::name()) {
206         didProcessRequestToSuspend(SuspensionState::Suspended);
207         return;
208     }
209
210     if (decoder.messageName() == Messages::WebPageProxy::DidFailToSuspendAfterProcessSwap::name()) {
211         didProcessRequestToSuspend(SuspensionState::FailedToSuspend);
212         return;
213     }
214
215 #if !LOG_DISABLED
216     if (!messageNamesToIgnoreWhileSuspended().contains(decoder.messageName()))
217         LOG(ProcessSwapping, "SuspendedPageProxy received unexpected WebPageProxy message '%s'", decoder.messageName().toString().data());
218 #endif
219 }
220
221 void SuspendedPageProxy::didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&)
222 {
223 }
224
225 #if !LOG_DISABLED
226
227 const char* SuspendedPageProxy::loggingString() const
228 {
229     return debugString("(0x", hex(reinterpret_cast<uintptr_t>(this)), " page ID ", m_page.pageID(), ", m_suspensionState ", static_cast<unsigned>(m_suspensionState), ')');
230 }
231
232 #endif
233
234 } // namespace WebKit