iOS/Sources/MacBridge/MacBridgeAppDelegateHandler.swift
Zac West 85ccc97e47
Fix crash in Mac extensions (#1466)
## Summary
Accessing the NSStatusBar in an extension causes a crash; this avoids calling it in extensions. We also should not be touching the status bar in an extension either way.

## Any other notes
Didn't show up during the betas, nor does it show up in Sentry. I'm guessing it's crashing so early in the MacBridge code that it doesn't have an opportunity to deal with crash logs.

Crashes look like:

```
Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_CRASH (SIGABRT)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Application Specific Information:
Assertion failed: (CGAtomicGet(&is_initialized)), function CGSConnectionByID, file /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/SkyLight/SkyLight-570.7/SkyLight/Services/Connection/CGSConnection.mm, line 133.
 

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   libsystem_kernel.dylib        	0x00007fff20504462 __pthread_kill + 10
1   libsystem_pthread.dylib       	0x00007fff20532610 pthread_kill + 263
2   libsystem_c.dylib             	0x00007fff20485720 abort + 120
3   libsystem_c.dylib             	0x00007fff204849d6 __assert_rtn + 314
4   com.apple.SkyLight            	0x00007fff24dad771 CGSConnectionByID + 423
5   com.apple.SkyLight            	0x00007fff24f9f58a SLSRegisterConnectionNotifyProc + 31
6   com.apple.AppKit              	0x00007fff236a476c +[NSCGSStatusItem addNavigationChangedNotificationHandler:] + 121
7   com.apple.AppKit              	0x00007fff230fe170 -[NSStatusBar init] + 202
8   com.apple.Foundation          	0x00007fff2136104c _NSFaultInObject + 27
9   io.robbie.HomeAssistant.dev.MacBridge	0x0000000107090389 MacBridgeStatusItem.init() + 105 (MacBridgeStatusItem.swift:4)
10  io.robbie.HomeAssistant.dev.MacBridge	0x0000000107090973 @objc MacBridgeStatusItem.init() + 19
11  io.robbie.HomeAssistant.dev.MacBridge	0x000000010709031b MacBridgeStatusItem.__allocating_init() + 27
12  io.robbie.HomeAssistant.dev.MacBridge	0x000000010709a295 MacBridgeImpl.init() + 213 (MacBridgeImpl.swift:12)
13  io.robbie.HomeAssistant.dev.MacBridge	0x000000010709a383 @objc MacBridgeImpl.init() + 19
14  io.robbie.HomeAssistant.dev.Shared	0x00000001037be6d9 closure #1 in variable initialization expression of Environment.macBridge + 2073 (Environment.swift:141)
15  io.robbie.HomeAssistant.dev.Shared	0x00000001037b9ad6 Environment.init() + 2150 (Environment.swift:132)
```
2021-02-06 19:01:04 +00:00

58 lines
2.2 KiB
Swift

import AppKit
import Foundation
import ObjectiveC.runtime
enum MacBridgeAppDelegateHandler {
static let terminationWillBeginNotification: Notification.Name = .init("ha_terminationWillBegin")
static func swizzleAppDelegate() {
guard !Bundle.main.isRunningInExtension else {
// Don't try and swizzle the App Delegate in an extension; there won't be one.
return
}
guard let delegate = NSApplication.shared.delegate else {
// this likely only happens one time; the delegate is set after initial setup but before the runloop starts
DispatchQueue.main.async {
swizzleAppDelegate()
}
return
}
struct SwizzleMethods {
let original: Selector
let replacement: Selector
}
let allMethods: [SwizzleMethods] = [
.init(
original: #selector(NSApplicationDelegate.applicationShouldTerminate(_:)),
replacement: #selector(NSObject.ha_applicationShouldTerminate(_:))
),
]
let klass = type(of: delegate)
for methods in allMethods {
guard let original = class_getInstanceMethod(klass, methods.original),
let replacement = class_getInstanceMethod(klass, methods.replacement) else {
fatalError("couldn't get methods for \(methods)")
}
method_exchangeImplementations(original, replacement)
}
}
}
private extension NSObject {
@objc func ha_applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
// we need to do this (a) long before actual termination, because we need to prevent it from happening
// and (b) before we ask the NSUIApplicationDelegate what its response is, in case it doesn't delay otherwise
// since we're going to (in effect) end up enqueueing background tasks as a result of this notification
NotificationCenter.default.post(.init(name: MacBridgeAppDelegateHandler.terminationWillBeginNotification))
// refers to the non-swizzled method
return ha_applicationShouldTerminate(sender)
}
}