[macOS] Switching to discrete GPU should be done in the UI process
[WebKit-https.git] / Source / WebKit / WebProcess / cocoa / WebProcessCocoa.mm
1 /*
2  * Copyright (C) 2010-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 #import "config.h"
27 #import "WebProcess.h"
28 #import "WebProcessCocoa.h"
29
30 #import "LegacyCustomProtocolManager.h"
31 #import "LogInitialization.h"
32 #import "Logging.h"
33 #import "ObjCObjectGraph.h"
34 #import "SandboxExtension.h"
35 #import "SandboxInitializationParameters.h"
36 #import "SessionTracker.h"
37 #import "WKAPICast.h"
38 #import "WKBrowsingContextHandleInternal.h"
39 #import "WKCrashReporter.h"
40 #import "WKFullKeyboardAccessWatcher.h"
41 #import "WKTypeRefWrapper.h"
42 #import "WKWebProcessPlugInBrowserContextControllerInternal.h"
43 #import "WebFrame.h"
44 #import "WebInspector.h"
45 #import "WebPage.h"
46 #import "WebProcessCreationParameters.h"
47 #import "WebProcessProxyMessages.h"
48 #import "WebsiteDataStoreParameters.h"
49 #import <JavaScriptCore/ConfigFile.h>
50 #import <JavaScriptCore/Options.h>
51 #import <WebCore/AVFoundationMIMETypeCache.h>
52 #import <WebCore/AXObjectCache.h>
53 #import <WebCore/CPUMonitor.h>
54 #import <WebCore/FileSystem.h>
55 #import <WebCore/FontCache.h>
56 #import <WebCore/FontCascade.h>
57 #import <WebCore/LocalizedStrings.h>
58 #import <WebCore/LogInitialization.h>
59 #import <WebCore/MemoryRelease.h>
60 #import <WebCore/NSScrollerImpDetails.h>
61 #import <WebCore/PerformanceLogging.h>
62 #import <WebCore/RuntimeApplicationChecks.h>
63 #import <WebCore/WebCoreNSURLExtras.h>
64 #import <algorithm>
65 #import <dispatch/dispatch.h>
66 #import <objc/runtime.h>
67 #import <pal/spi/cg/CoreGraphicsSPI.h>
68 #import <pal/spi/cocoa/LaunchServicesSPI.h>
69 #import <pal/spi/cocoa/QuartzCoreSPI.h>
70 #import <pal/spi/cocoa/pthreadSPI.h>
71 #import <pal/spi/mac/NSAccessibilitySPI.h>
72 #import <pal/spi/mac/NSApplicationSPI.h>
73 #import <stdio.h>
74
75 #if PLATFORM(IOS)
76 #import "WKAccessibilityWebPageObjectIOS.h"
77 #import <UIKit/UIAccessibility.h>
78 #import <pal/spi/ios/GraphicsServicesSPI.h>
79 #endif
80
81 #if PLATFORM(IOS) && USE(APPLE_INTERNAL_SDK)
82 #import <AXRuntime/AXDefines.h>
83 #import <AXRuntime/AXNotificationConstants.h>
84 #endif
85
86 #if PLATFORM(IOS) && !USE(APPLE_INTERNAL_SDK)
87 #define kAXPidStatusChangedNotification 0
88 #endif
89
90 #if PLATFORM(MAC)
91 #import "WKAccessibilityWebPageObjectMac.h"
92 #import "WebSwitchingGPUClient.h"
93 #import <WebCore/GraphicsContext3DManager.h>
94 #import <WebCore/ScrollbarThemeMac.h>
95 #import <pal/spi/mac/NSScrollerImpSPI.h>
96 #endif
97
98 #if USE(OS_STATE)
99 #import <os/state_private.h>
100 #endif
101
102 namespace WebKit {
103 using namespace WebCore;
104
105 #if PLATFORM(MAC)
106 static const Seconds cpuMonitoringInterval { 8_min };
107 #endif
108
109 void WebProcess::platformSetCacheModel(CacheModel)
110 {
111 }
112
113 #if USE(APPKIT)
114 static id NSApplicationAccessibilityFocusedUIElement(NSApplication*, SEL)
115 {
116     WebPage* page = WebProcess::singleton().focusedWebPage();
117     if (!page || !page->accessibilityRemoteObject())
118         return 0;
119
120     return [page->accessibilityRemoteObject() accessibilityFocusedUIElement];
121 }
122 #endif
123
124 void WebProcess::platformInitializeWebProcess(WebProcessCreationParameters&& parameters)
125 {
126 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
127     WebCore::initializeLogChannelsIfNecessary(parameters.webCoreLoggingChannels);
128     WebKit::initializeLogChannelsIfNecessary(parameters.webKitLoggingChannels);
129 #endif
130
131     WebCore::setApplicationBundleIdentifier(parameters.uiProcessBundleIdentifier);
132     WebCore::setApplicationSDKVersion(parameters.uiProcessSDKVersion);
133
134     SessionTracker::setIdentifierBase(parameters.uiProcessBundleIdentifier);
135
136 #if ENABLE(SANDBOX_EXTENSIONS)
137     SandboxExtension::consumePermanently(parameters.uiProcessBundleResourcePathExtensionHandle);
138     SandboxExtension::consumePermanently(parameters.webSQLDatabaseDirectoryExtensionHandle);
139     SandboxExtension::consumePermanently(parameters.applicationCacheDirectoryExtensionHandle);
140     SandboxExtension::consumePermanently(parameters.mediaCacheDirectoryExtensionHandle);
141     SandboxExtension::consumePermanently(parameters.mediaKeyStorageDirectoryExtensionHandle);
142     SandboxExtension::consumePermanently(parameters.javaScriptConfigurationDirectoryExtensionHandle);
143 #if ENABLE(MEDIA_STREAM)
144     SandboxExtension::consumePermanently(parameters.audioCaptureExtensionHandle);
145 #endif
146 #if PLATFORM(IOS)
147     SandboxExtension::consumePermanently(parameters.cookieStorageDirectoryExtensionHandle);
148     SandboxExtension::consumePermanently(parameters.containerCachesDirectoryExtensionHandle);
149     SandboxExtension::consumePermanently(parameters.containerTemporaryDirectoryExtensionHandle);
150 #endif
151 #endif
152
153     if (!parameters.javaScriptConfigurationDirectory.isEmpty()) {
154         String javaScriptConfigFile = parameters.javaScriptConfigurationDirectory + "/JSC.config";
155         JSC::processConfigFile(javaScriptConfigFile.latin1().data(), "com.apple.WebKit.WebContent", parameters.uiProcessBundleIdentifier.latin1().data());
156     }
157
158     // Disable NSURLCache.
159     auto urlCache = adoptNS([[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil]);
160     [NSURLCache setSharedURLCache:urlCache.get()];
161
162 #if PLATFORM(MAC)
163     WebCore::FontCache::setFontWhitelist(parameters.fontWhitelist);
164 #endif
165
166     m_compositingRenderServerPort = WTFMove(parameters.acceleratedCompositingPort);
167
168     WebCore::registerMemoryReleaseNotifyCallbacks();
169     MemoryPressureHandler::ReliefLogger::setLoggingEnabled(parameters.shouldEnableMemoryPressureReliefLogging);
170
171     setEnhancedAccessibility(parameters.accessibilityEnhancedUserInterfaceEnabled);
172
173 #if USE(APPKIT)
174     [[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"NSApplicationCrashOnExceptions" : @YES }];
175
176     // rdar://9118639 accessibilityFocusedUIElement in NSApplication defaults to use the keyWindow. Since there's
177     // no window in WK2, NSApplication needs to use the focused page's focused element.
178     Method methodToPatch = class_getInstanceMethod([NSApplication class], @selector(accessibilityFocusedUIElement));
179     method_setImplementation(methodToPatch, (IMP)NSApplicationAccessibilityFocusedUIElement);
180 #endif
181     
182 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_NSRUNLOOP)
183     // Need to initialize accessibility for VoiceOver to work when the WebContent process is using NSRunLoop.
184     // Currently, it is also needed to allocate and initialize an NSApplication object.
185     // FIXME: Remove the following line when rdar://problem/36323569 is fixed.
186     [NSApplication sharedApplication];
187     [NSApplication _accessibilityInitialize];
188 #endif
189
190 #if TARGET_OS_IPHONE
191     // Priority decay on iOS 9 is impacting page load time so we fix the priority of the WebProcess' main thread (rdar://problem/22003112).
192     pthread_set_fixedpriority_self();
193 #endif
194
195     if (!parameters.mediaMIMETypes.isEmpty())
196         setMediaMIMETypes(parameters.mediaMIMETypes);
197     else {
198         AVFoundationMIMETypeCache::singleton().setCacheMIMETypesCallback([this](const Vector<String>& types) {
199             parentProcessConnection()->send(Messages::WebProcessProxy::CacheMediaMIMETypes(types), 0);
200         });
201     }
202
203 #if PLATFORM(MAC)
204     WebCore::setScreenProperties(parameters.screenProperties);
205 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
206     scrollerStylePreferenceChanged(parameters.useOverlayScrollbars);
207 #endif
208 #endif
209 }
210
211 void WebProcess::initializeProcessName(const ChildProcessInitializationParameters& parameters)
212 {
213 #if !PLATFORM(IOS)
214     NSString *applicationName;
215     if (parameters.extraInitializationData.get("inspector-process"_s) == "1")
216         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Inspector", "Visible name of Web Inspector's web process. The argument is the application name."), (NSString *)parameters.uiProcessName];
217 #if ENABLE(SERVICE_WORKER)
218     else if (parameters.extraInitializationData.get("service-worker-process"_s) == "1")
219         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Service Worker (%@)", "Visible name of Service Worker process. The argument is the application name."), (NSString *)parameters.uiProcessName, (NSString *)parameters.extraInitializationData.get("security-origin"_s)];
220 #endif
221     else
222         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)parameters.uiProcessName];
223     _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), _kLSDisplayNameKey, (CFStringRef)applicationName, nullptr);
224 #endif
225 }
226
227 static void registerWithAccessibility()
228 {
229 #if USE(APPKIT)
230     [NSAccessibilityRemoteUIElement setRemoteUIApp:YES];
231 #endif
232 #if PLATFORM(IOS)
233     NSString *accessibilityBundlePath = [(NSString *)GSSystemRootDirectory() stringByAppendingString:@"/System/Library/AccessibilityBundles/WebProcessLoader.axbundle"];
234     NSError *error = nil;
235     if (![[NSBundle bundleWithPath:accessibilityBundlePath] loadAndReturnError:&error])
236         LOG_ERROR("Failed to load accessibility bundle at %@: %@", accessibilityBundlePath, error);
237 #endif
238 }
239
240 #if USE(OS_STATE)
241 void WebProcess::registerWithStateDumper()
242 {
243     os_state_add_handler(dispatch_get_main_queue(), ^(os_state_hints_t hints) {
244
245         @autoreleasepool {
246             os_state_data_t os_state = nil;
247
248             // Only gather state on faults and sysdiagnose. It's overkill for
249             // general error messages.
250             if (hints->osh_api == OS_STATE_API_ERROR)
251                 return os_state;
252
253             // Create a dictionary to contain the collected state. This
254             // dictionary will be serialized and passed back to os_state.
255             auto stateDict = adoptNS([[NSMutableDictionary alloc] init]);
256
257             {
258                 auto memoryUsageStats = adoptNS([[NSMutableDictionary alloc] init]);
259                 for (auto& it : PerformanceLogging::memoryUsageStatistics(ShouldIncludeExpensiveComputations::Yes)) {
260                     auto keyString = adoptNS([[NSString alloc] initWithUTF8String:it.key]);
261                     [memoryUsageStats setObject:@(it.value) forKey:keyString.get()];
262                 }
263                 [stateDict setObject:memoryUsageStats.get() forKey:@"Memory Usage Stats"];
264             }
265
266             {
267                 auto jsObjectCounts = adoptNS([[NSMutableDictionary alloc] init]);
268                 for (auto& it : PerformanceLogging::javaScriptObjectCounts()) {
269                     auto keyString = adoptNS([[NSString alloc] initWithUTF8String:it.key]);
270                     [jsObjectCounts setObject:@(it.value) forKey:keyString.get()];
271                 }
272                 [stateDict setObject:jsObjectCounts.get() forKey:@"JavaScript Object Counts"];
273             }
274
275             auto pageLoadTimes = adoptNS([[NSMutableArray alloc] init]);
276             for (auto& page : m_pageMap.values()) {
277                 if (page->usesEphemeralSession())
278                     continue;
279
280                 NSDate* date = [NSDate dateWithTimeIntervalSince1970:page->loadCommitTime().secondsSinceEpoch().seconds()];
281                 [pageLoadTimes addObject:date];
282             }
283
284             // Adding an empty array to the process state may provide an
285             // indication of the existance of private sessions, which we'd like
286             // to hide, so don't add empty arrays.
287             if ([pageLoadTimes count])
288                 [stateDict setObject:pageLoadTimes.get() forKey:@"Page Load Times"];
289
290             // --- Possibly add other state here as other entries in the dictionary. ---
291
292             // Submitting an empty process state object may provide an
293             // indication of the existance of private sessions, which we'd like
294             // to hide, so don't return empty dictionaries.
295             if (![stateDict count])
296                 return os_state;
297
298             // Serialize the accumulated process state so that we can put the
299             // result in an os_state_data_t structure.
300             NSError* error = nil;
301             NSData* data = [NSPropertyListSerialization dataWithPropertyList:stateDict.get() format:NSPropertyListBinaryFormat_v1_0 options:0 error:&error];
302
303             if (!data) {
304                 ASSERT(data);
305                 return os_state;
306             }
307
308             size_t neededSize = OS_STATE_DATA_SIZE_NEEDED(data.length);
309             os_state = (os_state_data_t)malloc(neededSize);
310             if (os_state) {
311                 memset(os_state, 0, neededSize);
312                 os_state->osd_type = OS_STATE_DATA_SERIALIZED_NSCF_OBJECT;
313                 os_state->osd_data_size = data.length;
314                 strlcpy(os_state->osd_title, "WebContent state", sizeof(os_state->osd_title));
315                 memcpy(os_state->osd_data, data.bytes, data.length);
316             }
317
318             return os_state;
319         }
320     });
321 }
322 #endif
323
324 void WebProcess::platformInitializeProcess(const ChildProcessInitializationParameters&)
325 {
326 #if PLATFORM(MAC)
327 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
328     // Deny the WebContent process access to the WindowServer.
329     // This call will not succeed if there are open WindowServer connections at this point.
330     auto retval = CGSSetDenyWindowServerConnections(true);
331     RELEASE_ASSERT(retval == kCGErrorSuccess);
332     // Make sure that we close any WindowServer connections after checking in with Launch Services.
333     CGSShutdownServerConnections();
334
335     SwitchingGPUClient::setSingleton(WebSwitchingGPUClient::singleton());
336 #else
337     if (![NSApp isRunning]) {
338         // This call is needed when the WebProcess is not running the NSApplication event loop.
339         // Otherwise, calling enableSandboxStyleFileQuarantine() will fail.
340         launchServicesCheckIn();
341     }
342 #endif // ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
343 #endif // PLATFORM(MAC)
344
345     registerWithAccessibility();
346
347 #if USE(OS_STATE)
348     registerWithStateDumper();
349 #endif
350 }
351
352 #if USE(APPKIT)
353 void WebProcess::stopRunLoop()
354 {
355 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_NSRUNLOOP)
356     ChildProcess::stopNSRunLoop();
357 #else
358     ChildProcess::stopNSAppRunLoop();
359 #endif
360 }
361 #endif
362
363 void WebProcess::platformTerminate()
364 {
365     AVFoundationMIMETypeCache::singleton().setCacheMIMETypesCallback(nullptr);
366 }
367
368 RetainPtr<CFDataRef> WebProcess::sourceApplicationAuditData() const
369 {
370 #if PLATFORM(IOS)
371     audit_token_t auditToken;
372     ASSERT(parentProcessConnection());
373     if (!parentProcessConnection() || !parentProcessConnection()->getAuditToken(auditToken))
374         return nullptr;
375     return adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
376 #else
377     return nullptr;
378 #endif
379 }
380
381 void WebProcess::initializeSandbox(const ChildProcessInitializationParameters& parameters, SandboxInitializationParameters& sandboxParameters)
382 {
383 #if ENABLE(WEB_PROCESS_SANDBOX)
384 #if ENABLE(MANUAL_SANDBOXING)
385     // Need to override the default, because service has a different bundle ID.
386 #if WK_API_ENABLED
387     NSBundle *webKit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKWebView")];
388 #else
389     NSBundle *webKit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKView")];
390 #endif
391 #if PLATFORM(IOS) && !PLATFORM(IOSMAC)
392     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebKit.WebContent" ofType:@"sb"]);
393 #else
394     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebProcess" ofType:@"sb"]);
395 #endif
396     ChildProcess::initializeSandbox(parameters, sandboxParameters);
397 #endif
398 #else
399     UNUSED_PARAM(parameters);
400     UNUSED_PARAM(sandboxParameters);
401 #endif
402 }
403
404 #if PLATFORM(MAC)
405
406 static NSURL *origin(WebPage& page)
407 {
408     WebFrame* mainFrame = page.mainWebFrame();
409     if (!mainFrame)
410         return nil;
411
412     URL mainFrameURL(URL(), mainFrame->url());
413     Ref<SecurityOrigin> mainFrameOrigin = SecurityOrigin::create(mainFrameURL);
414     String mainFrameOriginString;
415     if (!mainFrameOrigin->isUnique())
416         mainFrameOriginString = mainFrameOrigin->toRawString();
417     else
418         mainFrameOriginString = makeString(mainFrameURL.protocol(), ':'); // toRawString() is not supposed to work with unique origins, and would just return "://".
419
420     // +[NSURL URLWithString:] returns nil when its argument is malformed. It's unclear when we would have a malformed URL here,
421     // but it happens in practice according to <rdar://problem/14173389>. Leaving an assertion in to catch a reproducible case.
422     ASSERT([NSURL URLWithString:mainFrameOriginString]);
423
424     return [NSURL URLWithString:mainFrameOriginString];
425 }
426
427 #endif
428
429 void WebProcess::updateActivePages()
430 {
431 #if PLATFORM(MAC)
432     auto activePageURLs = adoptNS([[NSMutableArray alloc] init]);
433
434     for (auto& page : m_pageMap.values()) {
435         if (page->usesEphemeralSession() || page->isSuspended())
436             continue;
437
438         if (NSURL *originAsURL = origin(*page))
439             [activePageURLs addObject:userVisibleString(originAsURL)];
440     }
441
442     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), [activePageURLs] {
443         _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), CFSTR("LSActivePageUserVisibleOriginsKey"), (__bridge CFArrayRef)activePageURLs.get(), nullptr);
444     });
445 #endif
446 }
447
448 void WebProcess::updateCPULimit()
449 {
450 #if PLATFORM(MAC)
451     std::optional<double> cpuLimit;
452
453     // Use the largest limit among all pages in this process.
454     for (auto& page : m_pageMap.values()) {
455         auto pageCPULimit = page->cpuLimit();
456         if (!pageCPULimit) {
457             cpuLimit = std::nullopt;
458             break;
459         }
460         if (!cpuLimit || pageCPULimit > cpuLimit.value())
461             cpuLimit = pageCPULimit;
462     }
463
464     if (m_cpuLimit == cpuLimit)
465         return;
466
467     m_cpuLimit = cpuLimit;
468     updateCPUMonitorState(CPUMonitorUpdateReason::LimitHasChanged);
469 #endif
470 }
471
472 void WebProcess::updateCPUMonitorState(CPUMonitorUpdateReason reason)
473 {
474 #if PLATFORM(MAC)
475     if (!m_cpuLimit) {
476         if (m_cpuMonitor)
477             m_cpuMonitor->setCPULimit(std::nullopt);
478         return;
479     }
480
481     if (!m_cpuMonitor) {
482         m_cpuMonitor = std::make_unique<CPUMonitor>(cpuMonitoringInterval, [this](double cpuUsage) {
483             RELEASE_LOG(PerformanceLogging, "%p - WebProcess exceeded CPU limit of %.1f%% (was using %.1f%%) hasVisiblePages? %d", this, m_cpuLimit.value() * 100, cpuUsage * 100, hasVisibleWebPage());
484             parentProcessConnection()->send(Messages::WebProcessProxy::DidExceedCPULimit(), 0);
485         });
486     } else if (reason == CPUMonitorUpdateReason::VisibilityHasChanged) {
487         // If the visibility has changed, stop the CPU monitor before setting its limit. This is needed because the CPU usage can vary wildly based on visibility and we would
488         // not want to report that a process has exceeded its background CPU limit even though most of the CPU time was used while the process was visible.
489         m_cpuMonitor->setCPULimit(std::nullopt);
490     }
491     m_cpuMonitor->setCPULimit(m_cpuLimit.value());
492 #else
493     UNUSED_PARAM(reason);
494 #endif
495 }
496
497 RefPtr<ObjCObjectGraph> WebProcess::transformHandlesToObjects(ObjCObjectGraph& objectGraph)
498 {
499     struct Transformer final : ObjCObjectGraph::Transformer {
500         Transformer(WebProcess& webProcess)
501             : m_webProcess(webProcess)
502         {
503         }
504
505         bool shouldTransformObject(id object) const override
506         {
507 #if WK_API_ENABLED
508             if (dynamic_objc_cast<WKBrowsingContextHandle>(object))
509                 return true;
510
511             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
512             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
513                 return true;
514             ALLOW_DEPRECATED_DECLARATIONS_END
515 #endif
516             return false;
517         }
518
519         RetainPtr<id> transformObject(id object) const override
520         {
521 #if WK_API_ENABLED
522             if (auto* handle = dynamic_objc_cast<WKBrowsingContextHandle>(object)) {
523                 if (auto* webPage = m_webProcess.webPage(handle._pageID))
524                     return wrapper(*webPage);
525
526                 return [NSNull null];
527             }
528
529             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
530             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
531                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(m_webProcess.transformHandlesToObjects(toImpl(wrapper.object)).get())]);
532             ALLOW_DEPRECATED_DECLARATIONS_END
533 #endif
534             return object;
535         }
536
537         WebProcess& m_webProcess;
538     };
539
540     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer(*this)).get());
541 }
542
543 RefPtr<ObjCObjectGraph> WebProcess::transformObjectsToHandles(ObjCObjectGraph& objectGraph)
544 {
545     struct Transformer final : ObjCObjectGraph::Transformer {
546         bool shouldTransformObject(id object) const override
547         {
548 #if WK_API_ENABLED
549             if (dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
550                 return true;
551
552             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
553             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
554                 return true;
555             ALLOW_DEPRECATED_DECLARATIONS_END
556 #endif
557
558             return false;
559         }
560
561         RetainPtr<id> transformObject(id object) const override
562         {
563 #if WK_API_ENABLED
564             if (auto* controller = dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
565                 return controller.handle;
566
567             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
568             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
569                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(transformObjectsToHandles(toImpl(wrapper.object)).get())]);
570             ALLOW_DEPRECATED_DECLARATIONS_END
571 #endif
572             return object;
573         }
574     };
575
576     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer()).get());
577 }
578
579 void WebProcess::destroyRenderingResources()
580 {
581 #if !RELEASE_LOG_DISABLED
582     MonotonicTime startTime = MonotonicTime::now();
583 #endif
584     CABackingStoreCollectBlocking();
585 #if !RELEASE_LOG_DISABLED
586     MonotonicTime endTime = MonotonicTime::now();
587 #endif
588     RELEASE_LOG(ProcessSuspension, "%p - WebProcess::destroyRenderingResources() took %.2fms", this, (endTime - startTime).milliseconds());
589 }
590
591 // FIXME: This should live somewhere else, and it should have the implementation in line instead of calling out to WKSI.
592 void _WKSetCrashReportApplicationSpecificInformation(NSString *infoString)
593 {
594     return setCrashReportApplicationSpecificInformation((__bridge CFStringRef)infoString);
595 }
596
597 #if PLATFORM(IOS)
598 void WebProcess::accessibilityProcessSuspendedNotification(bool suspended)
599 {
600     UIAccessibilityPostNotification(kAXPidStatusChangedNotification, @{ @"pid" : @(getpid()), @"suspended" : @(suspended) });
601 }
602 #endif
603
604 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
605 void WebProcess::scrollerStylePreferenceChanged(bool useOverlayScrollbars)
606 {
607     ScrollerStyle::setUseOverlayScrollbars(useOverlayScrollbars);
608
609     ScrollbarTheme& theme = ScrollbarTheme::theme();
610     if (theme.isMockTheme())
611         return;
612
613     static_cast<ScrollbarThemeMac&>(theme).preferencesChanged();
614     
615     NSScrollerStyle style = useOverlayScrollbars ? NSScrollerStyleOverlay : NSScrollerStyleLegacy;
616     [NSScrollerImpPair _updateAllScrollerImpPairsForNewRecommendedScrollerStyle:style];
617 }
618
619 void WebProcess::displayConfigurationChanged(CGDirectDisplayID displayID, CGDisplayChangeSummaryFlags flags)
620 {
621     GraphicsContext3DManager::displayWasReconfigured(displayID, flags, nullptr);
622 }
623 #endif
624
625 void WebProcess::setMediaMIMETypes(const Vector<String> types)
626 {
627     AVFoundationMIMETypeCache::singleton().setSupportedTypes(types);
628 }
629
630 } // namespace WebKit