-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathRunLoop.swift
466 lines (383 loc) · 17.3 KB
/
RunLoop.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
@_implementationOnly import CoreFoundation
internal let kCFRunLoopEntry = CFRunLoopActivity.entry.rawValue
internal let kCFRunLoopBeforeTimers = CFRunLoopActivity.beforeTimers.rawValue
internal let kCFRunLoopBeforeSources = CFRunLoopActivity.beforeSources.rawValue
internal let kCFRunLoopBeforeWaiting = CFRunLoopActivity.beforeWaiting.rawValue
internal let kCFRunLoopAfterWaiting = CFRunLoopActivity.afterWaiting.rawValue
internal let kCFRunLoopExit = CFRunLoopActivity.exit.rawValue
internal let kCFRunLoopAllActivities = CFRunLoopActivity.allActivities.rawValue
extension RunLoop {
public struct Mode : RawRepresentable, Equatable, Hashable, Sendable {
public let rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
}
}
extension RunLoop.Mode {
public static let `default`: RunLoop.Mode = RunLoop.Mode("kCFRunLoopDefaultMode")
public static let common: RunLoop.Mode = RunLoop.Mode("kCFRunLoopCommonModes")
// Use this instead of .rawValue._cfObject; this will allow CFRunLoop to use pointer equality internally.
fileprivate var _cfStringUniquingKnown: CFString {
if self == .default {
return kCFRunLoopDefaultMode
} else if self == .common {
return kCFRunLoopCommonModes
} else {
return rawValue._cfObject
}
}
}
#if !canImport(Dispatch)
@available(*, unavailable)
extension RunLoop : @unchecked Sendable { }
open class RunLoop: NSObject {
@available(*, unavailable, message: "RunLoop is not available on WASI")
open class var current: RunLoop {
fatalError("RunLoop is not available on WASI")
}
@available(*, unavailable, message: "RunLoop is not available on WASI")
open class var main: RunLoop {
fatalError("RunLoop is not available on WASI")
}
internal final var currentCFRunLoop: CFRunLoop { NSUnsupported() }
}
#else
internal func _NSRunLoopNew(_ cf: CFRunLoop) -> Unmanaged<AnyObject> {
let rl = Unmanaged<RunLoop>.passRetained(RunLoop(cfObject: cf))
return unsafeBitCast(rl, to: Unmanaged<AnyObject>.self) // this retain is balanced on the other side of the CF fence
}
@available(*, unavailable)
extension RunLoop : @unchecked Sendable { }
open class RunLoop: NSObject {
internal var _cfRunLoopStorage : AnyObject!
internal final var _cfRunLoop: CFRunLoop! {
get { unsafeBitCast(_cfRunLoopStorage, to: CFRunLoop?.self) }
set { _cfRunLoopStorage = newValue }
}
// TODO: We need some kind API to expose only the Sendable part of the main run loop
internal static nonisolated(unsafe) var _mainRunLoop: RunLoop = {
let cfObject: CFRunLoop! = CFRunLoopGetMain()
#if os(Windows)
// Enable the main runloop on Windows to process the Windows UI events.
// Windows, similar to AppKit and UIKit, expects to process the UI
// events on the main thread.
_CFRunLoopSetWindowsMessageQueueMask(cfObject, QS_ALLINPUT, kCFRunLoopDefaultMode)
#endif
return RunLoop(cfObject: cfObject)
}()
internal init(cfObject : CFRunLoop) {
_cfRunLoopStorage = cfObject
}
@available(*, noasync)
open class var current: RunLoop {
return _CFRunLoopGet2(CFRunLoopGetCurrent()) as! RunLoop
}
open class var main: RunLoop {
return _CFRunLoopGet2(_mainRunLoop._cfRunLoop) as! RunLoop
}
open var currentMode: RunLoop.Mode? {
if let mode = CFRunLoopCopyCurrentMode(_cfRunLoop) {
return RunLoop.Mode(mode._swiftObject)
} else {
return nil
}
}
// On platforms where it's available, getCFRunLoop() can be overridden and we use it below.
// Make sure we honor the override -- var currentCFRunLoop will do so on platforms where overrides are available.
// TODO: This has been removed as public API in port to the package, because CoreFoundation cannot be available as both toolchain "CoreFoundation" and package "_CoreFoundation"
#if os(Linux) || os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(OpenBSD) || os(FreeBSD)
internal var currentCFRunLoop: CFRunLoop { getCFRunLoop() }
internal func getCFRunLoop() -> CFRunLoop {
return _cfRunLoop
}
#else
internal final var currentCFRunLoop: CFRunLoop { _cfRunLoop }
internal func getCFRunLoop() -> Never {
fatalError()
}
#endif
open func add(_ timer: Timer, forMode mode: RunLoop.Mode) {
CFRunLoopAddTimer(_cfRunLoop, timer._cfObject, mode._cfStringUniquingKnown)
}
private let monitoredPortsWithModesLock = NSLock() // guards:
private var monitoredPortsWithModes: [Port: Set<RunLoop.Mode>] = [:]
private var monitoredPortObservers: [Port: NSObjectProtocol] = [:]
open func add(_ aPort: Port, forMode mode: RunLoop.Mode) {
var shouldSchedule = false
monitoredPortsWithModesLock.synchronized {
if monitoredPortsWithModes[aPort]?.contains(mode) != true {
monitoredPortsWithModes[aPort, default: []].insert(mode)
let shouldStartMonitoring = monitoredPortObservers[aPort] == nil
if shouldStartMonitoring {
nonisolated(unsafe) let strongNonisolatedSelf = self
nonisolated(unsafe) let nonisolatedPort = aPort
monitoredPortObservers[aPort] = NotificationCenter.default.addObserver(forName: Port.didBecomeInvalidNotification, object: aPort, queue: nil, using: { (notification) in
strongNonisolatedSelf.portDidInvalidate(nonisolatedPort)
})
}
shouldSchedule = true
}
}
if shouldSchedule {
aPort.schedule(in: self, forMode: mode)
}
}
private func portDidInvalidate(_ aPort: Port) {
monitoredPortsWithModesLock.synchronized {
if let observer = monitoredPortObservers.removeValue(forKey: aPort) {
NotificationCenter.default.removeObserver(observer)
}
monitoredPortsWithModes.removeValue(forKey: aPort)
}
}
open func remove(_ aPort: Port, forMode mode: RunLoop.Mode) {
var shouldRemove = false
monitoredPortsWithModesLock.synchronized {
guard let modes = monitoredPortsWithModes[aPort], modes.contains(mode) else {
return
}
shouldRemove = true
if modes.count == 1 {
if let observer = monitoredPortObservers.removeValue(forKey: aPort) {
NotificationCenter.default.removeObserver(observer)
}
monitoredPortsWithModes.removeValue(forKey: aPort)
} else {
monitoredPortsWithModes[aPort]?.remove(mode)
}
}
if shouldRemove {
aPort.remove(from: self, forMode: mode)
}
}
open func limitDate(forMode mode: RunLoop.Mode) -> Date? {
if _cfRunLoop !== CFRunLoopGetCurrent() {
return nil
}
let modeArg = mode.rawValue._cfObject
CFRunLoopRunInMode(modeArg, -10.0, true) /* poll run loop to fire ready timers and performers, as used to be done here */
if _CFRunLoopFinished(_cfRunLoop, modeArg) {
return nil
}
let nextTimerFireAbsoluteTime = CFRunLoopGetNextTimerFireDate(CFRunLoopGetCurrent(), modeArg)
if (nextTimerFireAbsoluteTime == 0) {
return Date.distantFuture
}
return Date(timeIntervalSinceReferenceDate: nextTimerFireAbsoluteTime)
}
@available(*, noasync)
open func acceptInput(forMode mode: String, before limitDate: Date) {
if _cfRunLoop !== CFRunLoopGetCurrent() {
return
}
CFRunLoopRunInMode(mode._cfObject, limitDate.timeIntervalSinceReferenceDate - CFAbsoluteTimeGetCurrent(), true)
}
}
extension RunLoop {
@available(*, noasync)
public func run() {
while run(mode: .default, before: Date.distantFuture) { }
}
@available(*, noasync)
public func run(until limitDate: Date) {
while run(mode: .default, before: limitDate) && limitDate.timeIntervalSinceReferenceDate > CFAbsoluteTimeGetCurrent() { }
}
@available(*, noasync)
public func run(mode: RunLoop.Mode, before limitDate: Date) -> Bool {
if _cfRunLoop !== CFRunLoopGetCurrent() {
return false
}
let modeArg = mode._cfStringUniquingKnown
if _CFRunLoopFinished(_cfRunLoop, modeArg) {
return false
}
let limitTime = limitDate.timeIntervalSinceReferenceDate
let ti = limitTime - CFAbsoluteTimeGetCurrent()
CFRunLoopRunInMode(modeArg, ti, true)
return true
}
public func perform(inModes modes: [RunLoop.Mode], block: @Sendable @escaping () -> Void) {
CFRunLoopPerformBlock(currentCFRunLoop, (modes.map { $0._cfStringUniquingKnown })._cfObject, block)
}
public func perform(_ block: @Sendable @escaping () -> Void) {
perform(inModes: [.default], block: block)
}
}
// These exist as SPI for XCTest for now. Do not rely on their contracts or continued existence.
extension RunLoop {
// TODO: Switch XCTest to SPI Annotation
// @available(*, deprecated, message: "For XCTest use only.")
public func _stop() {
CFRunLoopStop(currentCFRunLoop)
}
// TODO: Switch XCTest to SPI Annotation
// @available(*, deprecated, message: "For XCTest use only.")
public func _observe(_ activities: _Activities, in mode: RunLoop.Mode = .default, repeats: Bool = true, order: Int = 0, handler: @escaping (_Activity) -> Void) -> _Observer {
let observer = _Observer(activities: activities, repeats: repeats, order: order, handler: handler)
CFRunLoopAddObserver(self.currentCFRunLoop, observer.cfObserver, mode._cfStringUniquingKnown)
return observer
}
// TODO: Switch XCTest to SPI Annotation
// @available(*, deprecated, message: "For XCTest use only.")
public func _observe(_ activity: _Activity, in mode: RunLoop.Mode = .default, repeats: Bool = true, order: Int = 0, handler: @escaping (_Activity) -> Void) -> _Observer {
return _observe(_Activities(activity), in: mode, repeats: repeats, order: order, handler: handler)
}
// TODO: Switch XCTest to SPI Annotation
// @available(*, deprecated, message: "For XCTest use only.")
public func _add(_ source: _Source, forMode mode: RunLoop.Mode) {
CFRunLoopAddSource(_cfRunLoop, source.cfSource, mode._cfStringUniquingKnown)
}
// TODO: Switch XCTest to SPI Annotation
// @available(*, deprecated, message: "For XCTest use only.")
public func _remove(_ source: _Source, for mode: RunLoop.Mode) {
CFRunLoopRemoveSource(_cfRunLoop, source.cfSource, mode._cfStringUniquingKnown)
}
}
@available(*, unavailable)
extension RunLoop._Observer : Sendable { }
@available(*, unavailable)
extension RunLoop._Source : Sendable { }
extension RunLoop {
// TODO: Switch XCTest to SPI Annotation
// @available(*, deprecated, message: "For XCTest use only.")
public enum _Activity: UInt, Sendable {
// These must match CFRunLoopActivity.
case entry = 0
case beforeTimers = 1
case beforeSources = 2
case beforeWaiting = 32
case afterWaiting = 64
case exit = 128
}
// TODO: Switch XCTest to SPI Annotation
// @available(*, deprecated, message: "For XCTest use only.")
public struct _Activities: OptionSet, Sendable {
public var rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
public init(_ activity: _Activity) {
self.rawValue = activity.rawValue
}
public static let entry = _Activities(rawValue: _Activity.entry.rawValue)
public static let beforeTimers = _Activities(rawValue: _Activity.beforeTimers.rawValue)
public static let beforeSources = _Activities(rawValue: _Activity.beforeSources.rawValue)
public static let beforeWaiting = _Activities(rawValue: _Activity.beforeWaiting.rawValue)
public static let afterWaiting = _Activities(rawValue: _Activity.afterWaiting.rawValue)
public static let exit = _Activities(rawValue: _Activity.exit.rawValue)
public static let allActivities = _Activities(rawValue: 0x0FFFFFFF)
}
// TODO: Switch XCTest to SPI Annotation
// @available(*, deprecated, message: "For XCTest use only.")
public class _Observer {
fileprivate let _cfObserverStorage: AnyObject
fileprivate var cfObserver: CFRunLoopObserver { unsafeDowncast(_cfObserverStorage, to: CFRunLoopObserver.self) }
fileprivate init(activities: _Activities, repeats: Bool, order: Int, handler: @escaping (_Activity) -> Void) {
self._cfObserverStorage = CFRunLoopObserverCreateWithHandler(kCFAllocatorSystemDefault, CFOptionFlags(activities.rawValue), repeats, CFIndex(order), { (cfObserver, cfActivity) in
guard let activity = _Activity(rawValue: UInt(cfActivity.rawValue)) else { return }
handler(activity)
})
}
public func invalidate() {
CFRunLoopObserverInvalidate(cfObserver)
}
public var order: Int {
Int(CFRunLoopObserverGetOrder(cfObserver))
}
public var isValid: Bool {
CFRunLoopObserverIsValid(cfObserver)
}
deinit {
invalidate()
}
}
// TODO: Switch XCTest to SPI Annotation
// @available(*, deprecated, message: "For XCTest use only.")
open class _Source: NSObject {
fileprivate var _cfSourceStorage: AnyObject!
public init(order: Int = 0) {
super.init()
var context = CFRunLoopSourceContext(
version: 0,
info: Unmanaged.passUnretained(self).toOpaque(),
retain: nil,
release: nil,
copyDescription: { (info) -> Unmanaged<CFString>? in
let me = Unmanaged<_Source>.fromOpaque(info!).takeUnretainedValue()
return .passRetained(String(describing: me)._cfObject)
},
equal: { (infoA, infoB) in
let a = Unmanaged<_Source>.fromOpaque(infoA!).takeUnretainedValue()
let b = Unmanaged<_Source>.fromOpaque(infoB!).takeUnretainedValue()
return a == b ? true : false
},
hash: { (info) -> CFHashCode in
let me = Unmanaged<_Source>.fromOpaque(info!).takeUnretainedValue()
return CFHashCode(bitPattern: me.hashValue)
},
schedule: { (info, cfRunLoop, cfRunLoopMode) in
let me = Unmanaged<_Source>.fromOpaque(info!).takeUnretainedValue()
var mode: RunLoop.Mode = .default
if let cfRunLoopMode = cfRunLoopMode {
mode = RunLoop.Mode(rawValue: cfRunLoopMode._swiftObject)
}
me.didSchedule(in: mode)
},
cancel: { (info, cfRunLoop, cfRunLoopMode) in
let me = Unmanaged<_Source>.fromOpaque(info!).takeUnretainedValue()
var mode: RunLoop.Mode = .default
if let cfRunLoopMode = cfRunLoopMode {
mode = RunLoop.Mode(rawValue: cfRunLoopMode._swiftObject)
}
me.didCancel(in: mode)
},
perform: { (info) in
let me = Unmanaged<_Source>.fromOpaque(info!).takeUnretainedValue()
me.perform()
})
self._cfSourceStorage = CFRunLoopSourceCreate(kCFAllocatorSystemDefault, CFIndex(order), &context)
}
open func didSchedule(in mode: RunLoop.Mode) {
// Override me.
}
open func didCancel(in mode: RunLoop.Mode) {
// Override me.
}
open func perform() {
// Override me.
}
open func invalidate() {
CFRunLoopSourceInvalidate(cfSource)
}
open var order: Int {
Int(CFRunLoopSourceGetOrder(cfSource))
}
open var isValid: Bool {
CFRunLoopSourceIsValid(cfSource)
}
open func signal() {
CFRunLoopSourceSignal(cfSource)
}
deinit {
invalidate()
}
}
}
extension RunLoop._Source {
fileprivate var cfSource: CFRunLoopSource {
unsafeBitCast(_cfSourceStorage, to: CFRunLoopSource.self)
}
}
#endif // canImport(Dispatch)