Prewarm FontDatabase on process swap
[WebKit-https.git] / Source / WebKit / UIProcess / WebProcessPool.h
1 /*
2  * Copyright (C) 2010-2016 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 #pragma once
27
28 #include "APIDictionary.h"
29 #include "APIObject.h"
30 #include "APIProcessPoolConfiguration.h"
31 #include "APIWebsiteDataStore.h"
32 #include "DownloadProxyMap.h"
33 #include "GenericCallback.h"
34 #include "HiddenPageThrottlingAutoIncreasesCounter.h"
35 #include "MessageReceiver.h"
36 #include "MessageReceiverMap.h"
37 #include "NetworkProcessProxy.h"
38 #include "PlugInAutoStartProvider.h"
39 #include "PluginInfoStore.h"
40 #include "ProcessThrottler.h"
41 #include "ServiceWorkerProcessProxy.h"
42 #include "StatisticsRequest.h"
43 #include "VisitedLinkStore.h"
44 #include "WebContextClient.h"
45 #include "WebContextConnectionClient.h"
46 #include "WebProcessProxy.h"
47 #include <WebCore/SecurityOriginHash.h>
48 #include <WebCore/SharedStringHash.h>
49 #include <pal/SessionID.h>
50 #include <wtf/Forward.h>
51 #include <wtf/HashMap.h>
52 #include <wtf/HashSet.h>
53 #include <wtf/MemoryPressureHandler.h>
54 #include <wtf/ProcessID.h>
55 #include <wtf/RefCounter.h>
56 #include <wtf/RefPtr.h>
57 #include <wtf/text/StringHash.h>
58 #include <wtf/text/WTFString.h>
59
60 #if ENABLE(MEDIA_SESSION)
61 #include "WebMediaSessionFocusManager.h"
62 #endif
63
64 #if USE(SOUP)
65 #include <WebCore/SoupNetworkProxySettings.h>
66 #endif
67
68 #if PLATFORM(COCOA)
69 OBJC_CLASS NSMutableDictionary;
70 OBJC_CLASS NSObject;
71 OBJC_CLASS NSString;
72 #endif
73
74 namespace API {
75 class AutomationClient;
76 class CustomProtocolManagerClient;
77 class DownloadClient;
78 class HTTPCookieStore;
79 class InjectedBundleClient;
80 class LegacyContextHistoryClient;
81 class Navigation;
82 class PageConfiguration;
83 }
84
85 namespace WebCore {
86 struct MockMediaDevice;
87 }
88
89 namespace WebKit {
90
91 class DownloadProxy;
92 class HighPerformanceGraphicsUsageSampler;
93 class UIGamepad;
94 class PerActivityStateCPUUsageSampler;
95 class ServiceWorkerProcessProxy;
96 class WebAutomationSession;
97 class WebContextSupplement;
98 class WebPageGroup;
99 class WebPageProxy;
100 struct NetworkProcessCreationParameters;
101 struct StatisticsData;
102 struct WebProcessCreationParameters;
103     
104 typedef GenericCallback<API::Dictionary*> DictionaryCallback;
105
106 #if PLATFORM(COCOA)
107 int networkProcessLatencyQOS();
108 int networkProcessThroughputQOS();
109 int webProcessLatencyQOS();
110 int webProcessThroughputQOS();
111 #endif
112
113 enum class ProcessSwapRequestedByClient;
114
115 class WebProcessPool final : public API::ObjectImpl<API::Object::Type::ProcessPool>, public CanMakeWeakPtr<WebProcessPool>, private IPC::MessageReceiver {
116 public:
117     static Ref<WebProcessPool> create(API::ProcessPoolConfiguration&);
118
119     explicit WebProcessPool(API::ProcessPoolConfiguration&);        
120     virtual ~WebProcessPool();
121
122     void notifyThisWebProcessPoolWasCreated();
123
124     API::ProcessPoolConfiguration& configuration() { return m_configuration.get(); }
125
126     static const Vector<WebProcessPool*>& allProcessPools();
127
128     template <typename T>
129     T* supplement()
130     {
131         return static_cast<T*>(m_supplements.get(T::supplementName()));
132     }
133
134     template <typename T>
135     void addSupplement()
136     {
137         m_supplements.add(T::supplementName(), T::create(this));
138     }
139
140     void addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver&);
141     void addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver&);
142     void removeMessageReceiver(IPC::StringReference messageReceiverName);
143     void removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID);
144
145     bool dispatchMessage(IPC::Connection&, IPC::Decoder&);
146     bool dispatchSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
147
148     void initializeClient(const WKContextClientBase*);
149     void setInjectedBundleClient(std::unique_ptr<API::InjectedBundleClient>&&);
150     void initializeConnectionClient(const WKContextConnectionClientBase*);
151     void setHistoryClient(std::unique_ptr<API::LegacyContextHistoryClient>&&);
152     void setDownloadClient(std::unique_ptr<API::DownloadClient>&&);
153     void setAutomationClient(std::unique_ptr<API::AutomationClient>&&);
154     void setLegacyCustomProtocolManagerClient(std::unique_ptr<API::CustomProtocolManagerClient>&&);
155
156     void setMaximumNumberOfProcesses(unsigned); // Can only be called when there are no processes running.
157     unsigned maximumNumberOfProcesses() const { return !m_configuration->maximumProcessCount() ? UINT_MAX : m_configuration->maximumProcessCount(); }
158
159     void setCustomWebContentServiceBundleIdentifier(const String&);
160     const String& customWebContentServiceBundleIdentifier() { return m_configuration->customWebContentServiceBundleIdentifier(); }
161
162     const Vector<RefPtr<WebProcessProxy>>& processes() const { return m_processes; }
163
164     // WebProcess or NetworkProcess as approporiate for current process model. The connection must be non-null.
165     IPC::Connection* networkingProcessConnection();
166
167     template<typename T> void sendToAllProcesses(const T& message);
168     template<typename T> void sendToAllProcessesRelaunchingThemIfNecessary(const T& message);
169     template<typename T> void sendToOneProcess(T&& message);
170
171     // Sends the message to WebProcess or NetworkProcess as approporiate for current process model.
172     template<typename T> void sendToNetworkingProcess(T&& message);
173     template<typename T, typename U> void sendSyncToNetworkingProcess(T&& message, U&& reply);
174     template<typename T> void sendToNetworkingProcessRelaunchingIfNecessary(T&& message);
175
176     void processDidFinishLaunching(WebProcessProxy*);
177
178     // Disconnect the process from the context.
179     void disconnectProcess(WebProcessProxy*);
180
181     API::WebsiteDataStore* websiteDataStore() const { return m_websiteDataStore.get(); }
182     void setPrimaryDataStore(API::WebsiteDataStore& dataStore) { m_websiteDataStore = &dataStore; }
183
184     Ref<WebPageProxy> createWebPage(PageClient&, Ref<API::PageConfiguration>&&);
185
186     void pageBeginUsingWebsiteDataStore(WebPageProxy&);
187     void pageEndUsingWebsiteDataStore(WebPageProxy&);
188
189     const String& injectedBundlePath() const { return m_configuration->injectedBundlePath(); }
190
191     DownloadProxy* download(WebPageProxy* initiatingPage, const WebCore::ResourceRequest&, const String& suggestedFilename = { });
192     DownloadProxy* resumeDownload(const API::Data* resumeData, const String& path);
193
194     void setInjectedBundleInitializationUserData(RefPtr<API::Object>&& userData) { m_injectedBundleInitializationUserData = WTFMove(userData); }
195
196     void postMessageToInjectedBundle(const String&, API::Object*);
197
198     void populateVisitedLinks();
199
200     void handleMemoryPressureWarning(Critical);
201
202 #if ENABLE(NETSCAPE_PLUGIN_API)
203     void setAdditionalPluginsDirectory(const String&);
204     void refreshPlugins();
205
206     PluginInfoStore& pluginInfoStore() { return m_pluginInfoStore; }
207
208     void setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy, const String& host, const String& bundleIdentifier, const String& versionString);
209     void resetPluginLoadClientPolicies(HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&&);
210     void clearPluginClientPolicies();
211     const HashMap<String, HashMap<String, HashMap<String, uint8_t>>>& pluginLoadClientPolicies() const { return m_pluginLoadClientPolicies; }
212 #endif
213
214     void addSupportedPlugin(String&& matchingDomain, String&& name, HashSet<String>&& mimeTypes, HashSet<String> extensions);
215     void clearSupportedPlugins();
216
217     ProcessID networkProcessIdentifier();
218
219     WebPageGroup& defaultPageGroup() { return m_defaultPageGroup.get(); }
220
221     void setAlwaysUsesComplexTextCodePath(bool);
222     void setShouldUseFontSmoothing(bool);
223     
224     void registerURLSchemeAsEmptyDocument(const String&);
225     void registerURLSchemeAsSecure(const String&);
226     void registerURLSchemeAsBypassingContentSecurityPolicy(const String&);
227     void setDomainRelaxationForbiddenForURLScheme(const String&);
228     void setCanHandleHTTPSServerTrustEvaluation(bool);
229     void registerURLSchemeAsLocal(const String&);
230     void registerURLSchemeAsNoAccess(const String&);
231     void registerURLSchemeAsDisplayIsolated(const String&);
232     void registerURLSchemeAsCORSEnabled(const String&);
233     void registerURLSchemeAsCachePartitioned(const String&);
234     void registerURLSchemeServiceWorkersCanHandle(const String&);
235     void registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String&);
236
237     void preconnectToServer(const WebCore::URL&);
238
239     VisitedLinkStore& visitedLinkStore() { return m_visitedLinkStore.get(); }
240
241     void setCacheModel(CacheModel);
242     CacheModel cacheModel() const { return m_configuration->cacheModel(); }
243
244     void setDefaultRequestTimeoutInterval(double);
245
246     void startMemorySampler(const double interval);
247     void stopMemorySampler();
248
249 #if USE(SOUP)
250     void setInitialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) { m_initialHTTPCookieAcceptPolicy = policy; }
251     void setNetworkProxySettings(const WebCore::SoupNetworkProxySettings&);
252 #endif
253     void setEnhancedAccessibility(bool);
254     
255     // Downloads.
256     DownloadProxy* createDownloadProxy(const WebCore::ResourceRequest&, WebPageProxy* originatingPage);
257     API::DownloadClient& downloadClient() { return *m_downloadClient; }
258
259     API::LegacyContextHistoryClient& historyClient() { return *m_historyClient; }
260     WebContextClient& client() { return m_client; }
261
262     API::CustomProtocolManagerClient& customProtocolManagerClient() const { return *m_customProtocolManagerClient; }
263
264     struct Statistics {
265         unsigned wkViewCount;
266         unsigned wkPageCount;
267         unsigned wkFrameCount;
268     };
269     static Statistics& statistics();    
270
271     void useTestingNetworkSession();
272     bool isUsingTestingNetworkSession() const { return m_shouldUseTestingNetworkSession; }
273
274     void setAllowsAnySSLCertificateForWebSocket(bool);
275
276     void clearCachedCredentials();
277     void terminateNetworkProcess();
278     void terminateServiceWorkerProcesses();
279     void disableServiceWorkerProcessTerminationDelay();
280
281     void syncNetworkProcessCookies();
282
283     void setShouldMakeNextWebProcessLaunchFailForTesting(bool value) { m_shouldMakeNextWebProcessLaunchFailForTesting = value; }
284     bool shouldMakeNextWebProcessLaunchFailForTesting() const { return m_shouldMakeNextWebProcessLaunchFailForTesting; }
285     void setShouldMakeNextNetworkProcessLaunchFailForTesting(bool value) { m_shouldMakeNextNetworkProcessLaunchFailForTesting = value; }
286     bool shouldMakeNextNetworkProcessLaunchFailForTesting() const { return m_shouldMakeNextNetworkProcessLaunchFailForTesting; }
287
288     void reportWebContentCPUTime(Seconds cpuTime, uint64_t activityState);
289
290     void allowSpecificHTTPSCertificateForHost(const WebCertificateInfo*, const String& host);
291
292     WebProcessProxy& createNewWebProcessRespectingProcessCountLimit(WebsiteDataStore&); // Will return an existing one if limit is met.
293     void prewarmProcess();
294
295     bool shouldTerminate(WebProcessProxy*);
296
297     void disableProcessTermination() { m_processTerminationEnabled = false; }
298     void enableProcessTermination();
299
300     void updateAutomationCapabilities() const;
301     void setAutomationSession(RefPtr<WebAutomationSession>&&);
302     WebAutomationSession* automationSession() const { return m_automationSession.get(); }
303
304     // Defaults to false.
305     void setHTTPPipeliningEnabled(bool);
306     bool httpPipeliningEnabled() const;
307
308     void getStatistics(uint32_t statisticsMask, Function<void (API::Dictionary*, CallbackBase::Error)>&&);
309     
310     bool javaScriptConfigurationFileEnabled() { return m_javaScriptConfigurationFileEnabled; }
311     void setJavaScriptConfigurationFileEnabled(bool flag);
312 #if PLATFORM(IOS)
313     void setJavaScriptConfigurationFileEnabledFromDefaults();
314 #endif
315
316     void garbageCollectJavaScriptObjects();
317     void setJavaScriptGarbageCollectorTimerEnabled(bool flag);
318
319 #if PLATFORM(COCOA)
320     static bool omitPDFSupport();
321 #endif
322
323     void fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled);
324 #if OS(LINUX)
325     void sendMemoryPressureEvent(bool isCritical);
326 #endif
327     void textCheckerStateChanged();
328
329     Ref<API::Dictionary> plugInAutoStartOriginHashes() const;
330     void setPlugInAutoStartOriginHashes(API::Dictionary&);
331     void setPlugInAutoStartOrigins(API::Array&);
332     void setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary&, WallTime);
333
334     // Network Process Management
335     NetworkProcessProxy& ensureNetworkProcess(WebsiteDataStore* withWebsiteDataStore = nullptr);
336     NetworkProcessProxy* networkProcess() { return m_networkProcess.get(); }
337     void networkProcessCrashed(NetworkProcessProxy&, Vector<std::pair<RefPtr<WebProcessProxy>, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>>&&);
338
339     void getNetworkProcessConnection(WebProcessProxy&, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&&);
340
341 #if ENABLE(SERVICE_WORKER)
342     void establishWorkerContextConnectionToNetworkProcess(NetworkProcessProxy&, WebCore::SecurityOriginData&&, std::optional<PAL::SessionID>);
343     ServiceWorkerProcessProxy* serviceWorkerProcessProxyFromPageID(uint64_t pageID) const;
344     const HashMap<WebCore::SecurityOriginData, ServiceWorkerProcessProxy*>& serviceWorkerProxies() const { return m_serviceWorkerProcesses; }
345     void setAllowsAnySSLCertificateForServiceWorker(bool allows) { m_allowsAnySSLCertificateForServiceWorker = allows; }
346     bool allowsAnySSLCertificateForServiceWorker() const { return m_allowsAnySSLCertificateForServiceWorker; }
347     void updateServiceWorkerUserAgent(const String& userAgent);
348     bool mayHaveRegisteredServiceWorkers(const WebsiteDataStore&);
349 #endif
350
351 #if PLATFORM(COCOA)
352     bool processSuppressionEnabled() const;
353 #endif
354
355     void windowServerConnectionStateChanged();
356
357     static void willStartUsingPrivateBrowsing();
358     static void willStopUsingPrivateBrowsing();
359
360 #if USE(SOUP)
361     void setIgnoreTLSErrors(bool);
362     bool ignoreTLSErrors() const { return m_ignoreTLSErrors; }
363 #endif
364
365     static void setInvalidMessageCallback(void (*)(WKStringRef));
366     static void didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName);
367
368     void processDidCachePage(WebProcessProxy*);
369
370     bool isURLKnownHSTSHost(const String& urlString, bool privateBrowsingEnabled) const;
371     void resetHSTSHosts();
372     void resetHSTSHostsAddedAfterDate(double startDateIntervalSince1970);
373
374     void registerSchemeForCustomProtocol(const String&);
375     void unregisterSchemeForCustomProtocol(const String&);
376
377     static void registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
378     static void unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
379
380 #if PLATFORM(COCOA)
381     void updateProcessSuppressionState();
382
383     NSMutableDictionary *ensureBundleParameters();
384     NSMutableDictionary *bundleParameters() { return m_bundleParameters.get(); }
385 #else
386     void updateProcessSuppressionState() const { }
387 #endif
388
389     void updateHiddenPageThrottlingAutoIncreaseLimit();
390
391     void setMemoryCacheDisabled(bool);
392     void setFontWhitelist(API::Array*);
393
394     UserObservablePageCounter::Token userObservablePageCount()
395     {
396         return m_userObservablePageCounter.count();
397     }
398
399     ProcessSuppressionDisabledToken processSuppressionDisabledForPageCount()
400     {
401         return m_processSuppressionDisabledForPageCounter.count();
402     }
403
404     HiddenPageThrottlingAutoIncreasesCounter::Token hiddenPageThrottlingAutoIncreasesCount()
405     {
406         return m_hiddenPageThrottlingAutoIncreasesCounter.count();
407     }
408
409     void setResourceLoadStatisticsEnabled(bool);
410     void clearResourceLoadStatistics();
411
412     bool alwaysRunsAtBackgroundPriority() const { return m_alwaysRunsAtBackgroundPriority; }
413     bool shouldTakeUIBackgroundAssertion() const { return m_shouldTakeUIBackgroundAssertion; }
414
415 #if ENABLE(GAMEPAD)
416     void gamepadConnected(const UIGamepad&);
417     void gamepadDisconnected(const UIGamepad&);
418
419     void setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>&);
420 #endif
421
422 #if PLATFORM(COCOA)
423     bool cookieStoragePartitioningEnabled() const { return m_cookieStoragePartitioningEnabled; }
424     void setCookieStoragePartitioningEnabled(bool);
425     bool storageAccessAPIEnabled() const { return m_storageAccessAPIEnabled; }
426     void setStorageAccessAPIEnabled(bool);
427 #endif
428
429 #if ENABLE(SERVICE_WORKER)
430     void postMessageToServiceWorkerClient(const WebCore::ServiceWorkerClientIdentifier& destinationIdentifier, WebCore::MessageWithMessagePorts&&, WebCore::ServiceWorkerIdentifier sourceIdentifier, const String& sourceOrigin);
431     void postMessageToServiceWorker(WebCore::ServiceWorkerIdentifier destination, WebCore::MessageWithMessagePorts&&, const WebCore::ServiceWorkerOrClientIdentifier& source, WebCore::SWServerConnectionIdentifier);
432 #endif
433
434     static uint64_t registerProcessPoolCreationListener(Function<void(WebProcessPool&)>&&);
435     static void unregisterProcessPoolCreationListener(uint64_t identifier);
436
437 #if PLATFORM(IOS)
438     ForegroundWebProcessToken foregroundWebProcessToken() const { return ForegroundWebProcessToken(m_foregroundWebProcessCounter.count()); }
439     BackgroundWebProcessToken backgroundWebProcessToken() const { return BackgroundWebProcessToken(m_backgroundWebProcessCounter.count()); }
440 #endif
441
442     Ref<WebProcessProxy> processForNavigation(WebPageProxy&, const API::Navigation&, ProcessSwapRequestedByClient, WebCore::PolicyAction&, String& reason);
443     void registerSuspendedPageProxy(SuspendedPageProxy&);
444     void unregisterSuspendedPageProxy(SuspendedPageProxy&);
445     void didReachGoodTimeToPrewarm();
446
447     void didCollectPrewarmInformation(const String& registrableDomain, const WebCore::PrewarmInformation&);
448
449     void screenPropertiesStateChanged();
450
451     void addMockMediaDevice(const WebCore::MockMediaDevice&);
452     void clearMockMediaDevices();
453     void removeMockMediaDevice(const String& persistentId);
454     void resetMockMediaDevices();
455
456     void sendDisplayConfigurationChangedMessageForTesting();
457
458 private:
459     void platformInitialize();
460
461     void platformInitializeWebProcess(WebProcessCreationParameters&);
462     void platformInvalidateContext();
463
464     Ref<WebProcessProxy> processForNavigationInternal(WebPageProxy&, const API::Navigation&, ProcessSwapRequestedByClient, WebCore::PolicyAction&, String& reason);
465
466     RefPtr<WebProcessProxy> tryTakePrewarmedProcess(WebsiteDataStore&);
467
468     WebProcessProxy& createNewWebProcess(WebsiteDataStore&, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
469     void initializeNewWebProcess(WebProcessProxy&, WebsiteDataStore&);
470
471     void requestWebContentStatistics(StatisticsRequest*);
472     void requestNetworkingStatistics(StatisticsRequest*);
473
474     void platformInitializeNetworkProcess(NetworkProcessCreationParameters&);
475
476     void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody);
477     void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, UserData& returnUserData);
478
479     void didGetStatistics(const StatisticsData&, uint64_t callbackID);
480
481 #if ENABLE(GAMEPAD)
482     void startedUsingGamepads(IPC::Connection&);
483     void stoppedUsingGamepads(IPC::Connection&);
484
485     void processStoppedUsingGamepads(WebProcessProxy&);
486 #endif
487
488     void reinstateNetworkProcessAssertionState(NetworkProcessProxy&);
489     void updateProcessAssertions();
490
491     // IPC::MessageReceiver.
492     // Implemented in generated WebProcessPoolMessageReceiver.cpp
493     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
494     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
495
496     static void languageChanged(void* context);
497     void languageChanged();
498
499 #if PLATFORM(IOS)
500     String cookieStorageDirectory() const;
501 #endif
502
503 #if PLATFORM(IOS)
504     String parentBundleDirectory() const;
505     String networkingCachesDirectory() const;
506     String webContentCachesDirectory() const;
507     String containerTemporaryDirectory() const;
508 #endif
509
510 #if PLATFORM(COCOA)
511     void registerNotificationObservers();
512     void unregisterNotificationObservers();
513 #endif
514
515     void addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, PAL::SessionID);
516     void plugInDidReceiveUserInteraction(unsigned plugInOriginHash, PAL::SessionID);
517
518     void setAnyPageGroupMightHavePrivateBrowsingEnabled(bool);
519
520     void resolvePathsForSandboxExtensions();
521     void platformResolvePathsForSandboxExtensions();
522
523     void addProcessToOriginCacheSet(WebPageProxy&);
524     void removeProcessFromOriginCacheSet(WebProcessProxy&);
525
526     Ref<API::ProcessPoolConfiguration> m_configuration;
527
528     IPC::MessageReceiverMap m_messageReceiverMap;
529
530     Vector<RefPtr<WebProcessProxy>> m_processes;
531     WebProcessProxy* m_prewarmedProcess { nullptr };
532
533     WebProcessProxy* m_processWithPageCache { nullptr };
534 #if ENABLE(SERVICE_WORKER)
535     HashMap<WebCore::SecurityOriginData, ServiceWorkerProcessProxy*> m_serviceWorkerProcesses;
536     bool m_waitingForWorkerContextProcessConnection { false };
537     bool m_allowsAnySSLCertificateForServiceWorker { false };
538     bool m_shouldDisableServiceWorkerProcessTerminationDelay { false };
539     String m_serviceWorkerUserAgent;
540     std::optional<WebPreferencesStore> m_serviceWorkerPreferences;
541     HashMap<String, bool> m_mayHaveRegisteredServiceWorkers;
542 #endif
543
544     Ref<WebPageGroup> m_defaultPageGroup;
545
546     RefPtr<API::Object> m_injectedBundleInitializationUserData;
547     std::unique_ptr<API::InjectedBundleClient> m_injectedBundleClient;
548
549     WebContextClient m_client;
550     WebContextConnectionClient m_connectionClient;
551     std::unique_ptr<API::AutomationClient> m_automationClient;
552     std::unique_ptr<API::DownloadClient> m_downloadClient;
553     std::unique_ptr<API::LegacyContextHistoryClient> m_historyClient;
554     std::unique_ptr<API::CustomProtocolManagerClient> m_customProtocolManagerClient;
555
556     RefPtr<WebAutomationSession> m_automationSession;
557
558 #if ENABLE(NETSCAPE_PLUGIN_API)
559     PluginInfoStore m_pluginInfoStore;
560 #endif
561     Ref<VisitedLinkStore> m_visitedLinkStore;
562     bool m_visitedLinksPopulated { false };
563
564     PlugInAutoStartProvider m_plugInAutoStartProvider { this };
565         
566     HashSet<String> m_schemesToRegisterAsEmptyDocument;
567     HashSet<String> m_schemesToRegisterAsSecure;
568     HashSet<String> m_schemesToRegisterAsBypassingContentSecurityPolicy;
569     HashSet<String> m_schemesToSetDomainRelaxationForbiddenFor;
570     HashSet<String> m_schemesToRegisterAsLocal;
571     HashSet<String> m_schemesToRegisterAsNoAccess;
572     HashSet<String> m_schemesToRegisterAsDisplayIsolated;
573     HashSet<String> m_schemesToRegisterAsCORSEnabled;
574     HashSet<String> m_schemesToRegisterAsAlwaysRevalidated;
575     HashSet<String> m_schemesToRegisterAsCachePartitioned;
576     HashSet<String> m_schemesServiceWorkersCanHandle;
577     HashSet<String> m_schemesToRegisterAsCanDisplayOnlyIfCanRequest;
578
579     bool m_alwaysUsesComplexTextCodePath { false };
580     bool m_shouldUseFontSmoothing { true };
581
582     Vector<String> m_fontWhitelist;
583
584     // Messages that were posted before any pages were created.
585     // The client should use initialization messages instead, so that a restarted process would get the same state.
586     Vector<std::pair<String, RefPtr<API::Object>>> m_messagesToInjectedBundlePostedToEmptyContext;
587
588     bool m_memorySamplerEnabled { false };
589     double m_memorySamplerInterval { 1400.0 };
590
591     RefPtr<API::WebsiteDataStore> m_websiteDataStore;
592
593     typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap;
594     WebContextSupplementMap m_supplements;
595
596 #if USE(SOUP)
597     HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy { HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain };
598     WebCore::SoupNetworkProxySettings m_networkProxySettings;
599 #endif
600     HashSet<String, ASCIICaseInsensitiveHash> m_urlSchemesRegisteredForCustomProtocols;
601
602 #if PLATFORM(MAC)
603     RetainPtr<NSObject> m_enhancedAccessibilityObserver;
604     RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver;
605     RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver;
606     RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver;
607     RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver;
608     RetainPtr<NSObject> m_accessibilityDisplayOptionsNotificationObserver;
609 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
610     RetainPtr<NSObject> m_scrollerStyleNotificationObserver;
611 #endif
612
613     std::unique_ptr<HighPerformanceGraphicsUsageSampler> m_highPerformanceGraphicsUsageSampler;
614     std::unique_ptr<PerActivityStateCPUUsageSampler> m_perActivityStateCPUUsageSampler;
615 #endif
616
617     bool m_shouldUseTestingNetworkSession { false };
618
619     bool m_processTerminationEnabled { true };
620
621     bool m_canHandleHTTPSServerTrustEvaluation { true };
622     bool m_didNetworkProcessCrash { false };
623     std::unique_ptr<NetworkProcessProxy> m_networkProcess;
624
625     HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks;
626     HashMap<uint64_t, RefPtr<StatisticsRequest>> m_statisticsRequests;
627
628 #if USE(SOUP)
629     bool m_ignoreTLSErrors { true };
630 #endif
631
632     bool m_memoryCacheDisabled { false };
633     bool m_javaScriptConfigurationFileEnabled { false };
634     bool m_alwaysRunsAtBackgroundPriority;
635     bool m_shouldTakeUIBackgroundAssertion;
636     bool m_shouldMakeNextWebProcessLaunchFailForTesting { false };
637     bool m_shouldMakeNextNetworkProcessLaunchFailForTesting { false };
638
639     UserObservablePageCounter m_userObservablePageCounter;
640     ProcessSuppressionDisabledCounter m_processSuppressionDisabledForPageCounter;
641     HiddenPageThrottlingAutoIncreasesCounter m_hiddenPageThrottlingAutoIncreasesCounter;
642     RunLoop::Timer<WebProcessPool> m_hiddenPageThrottlingTimer;
643
644 #if PLATFORM(COCOA)
645     RetainPtr<NSMutableDictionary> m_bundleParameters;
646     ProcessSuppressionDisabledToken m_pluginProcessManagerProcessSuppressionDisabledToken;
647 #endif
648
649 #if ENABLE(CONTENT_EXTENSIONS)
650     HashMap<String, String> m_encodedContentExtensions;
651 #endif
652
653 #if ENABLE(NETSCAPE_PLUGIN_API)
654     HashMap<String, HashMap<String, HashMap<String, uint8_t>>> m_pluginLoadClientPolicies;
655 #endif
656
657 #if ENABLE(GAMEPAD)
658     HashSet<WebProcessProxy*> m_processesUsingGamepads;
659 #endif
660
661 #if PLATFORM(COCOA)
662     bool m_cookieStoragePartitioningEnabled { false };
663     bool m_storageAccessAPIEnabled { false };
664 #endif
665
666     struct Paths {
667         String injectedBundlePath;
668         String applicationCacheDirectory;
669         String webSQLDatabaseDirectory;
670         String mediaCacheDirectory;
671         String mediaKeyStorageDirectory;
672         String uiProcessBundleResourcePath;
673         String indexedDatabaseDirectory;
674
675 #if PLATFORM(IOS)
676         String cookieStorageDirectory;
677         String containerCachesDirectory;
678         String containerTemporaryDirectory;
679 #endif
680
681         Vector<String> additionalWebProcessSandboxExtensionPaths;
682     };
683     Paths m_resolvedPaths;
684
685     HashMap<PAL::SessionID, HashSet<WebPageProxy*>> m_sessionToPagesMap;
686     RunLoop::Timer<WebProcessPool> m_serviceWorkerProcessesTerminationTimer;
687
688 #if PLATFORM(IOS)
689     ForegroundWebProcessCounter m_foregroundWebProcessCounter;
690     BackgroundWebProcessCounter m_backgroundWebProcessCounter;
691     ProcessThrottler::ForegroundActivityToken m_foregroundTokenForNetworkProcess;
692     ProcessThrottler::BackgroundActivityToken m_backgroundTokenForNetworkProcess;
693 #if ENABLE(SERVICE_WORKER)
694     HashMap<WebCore::SecurityOriginData, ProcessThrottler::ForegroundActivityToken> m_foregroundTokensForServiceWorkerProcesses;
695     HashMap<WebCore::SecurityOriginData, ProcessThrottler::BackgroundActivityToken> m_backgroundTokensForServiceWorkerProcesses;
696 #endif
697 #endif
698
699     HashMap<WebCore::SecurityOriginData, Vector<SuspendedPageProxy*>> m_suspendedPages;
700     HashMap<String, RefPtr<WebProcessProxy>> m_swappedProcessesPerRegistrableDomain;
701
702     HashMap<String, std::unique_ptr<WebCore::PrewarmInformation>> m_prewarmInformationPerRegistrableDomain;
703 };
704
705 template<typename T>
706 void WebProcessPool::sendToNetworkingProcess(T&& message)
707 {
708     if (m_networkProcess && m_networkProcess->canSendMessage())
709         m_networkProcess->send(std::forward<T>(message), 0);
710 }
711
712 template<typename T>
713 void WebProcessPool::sendToNetworkingProcessRelaunchingIfNecessary(T&& message)
714 {
715     ensureNetworkProcess();
716     m_networkProcess->send(std::forward<T>(message), 0);
717 }
718
719 template<typename T>
720 void WebProcessPool::sendToAllProcesses(const T& message)
721 {
722     size_t processCount = m_processes.size();
723     for (size_t i = 0; i < processCount; ++i) {
724         WebProcessProxy* process = m_processes[i].get();
725         if (process->canSendMessage())
726             process->send(T(message), 0);
727     }
728 }
729
730 template<typename T>
731 void WebProcessPool::sendToAllProcessesRelaunchingThemIfNecessary(const T& message)
732 {
733     // FIXME (Multi-WebProcess): WebProcessPool doesn't track processes that have exited, so it cannot relaunch these. Perhaps this functionality won't be needed in this mode.
734     sendToAllProcesses(message);
735 }
736
737 template<typename T>
738 void WebProcessPool::sendToOneProcess(T&& message)
739 {
740     bool messageSent = false;
741     size_t processCount = m_processes.size();
742     for (size_t i = 0; i < processCount; ++i) {
743         WebProcessProxy* process = m_processes[i].get();
744         if (process->canSendMessage()) {
745             process->send(std::forward<T>(message), 0);
746             messageSent = true;
747             break;
748         }
749     }
750
751     if (!messageSent) {
752         prewarmProcess();
753         RefPtr<WebProcessProxy> process = m_processes.last();
754         if (process->canSendMessage())
755             process->send(std::forward<T>(message), 0);
756     }
757 }
758
759 } // namespace WebKit