39 lines
1.3 KiB
Swift
39 lines
1.3 KiB
Swift
import Foundation
|
|
import Observation
|
|
import IOKit.pwr_mgt
|
|
|
|
/// Process-scoped power assertions; deliberately not persisted across launches.
|
|
@MainActor @Observable final class KeepAwakeService {
|
|
private(set) var isEnabled = false
|
|
private(set) var didFail = false
|
|
@ObservationIgnored private var assertions: [IOPMAssertionID] = []
|
|
|
|
func toggle() {
|
|
if isEnabled { disable(); return }
|
|
var acquired: [IOPMAssertionID] = []
|
|
for type in [kIOPMAssertionTypePreventUserIdleDisplaySleep, kIOPMAssertionTypePreventUserIdleSystemSleep] {
|
|
var identifier: IOPMAssertionID = 0
|
|
let result = IOPMAssertionCreateWithName(type as CFString, IOPMAssertionLevel(kIOPMAssertionLevelOn),
|
|
"Kymo Keep Awake" as CFString, &identifier)
|
|
guard result == kIOReturnSuccess else {
|
|
acquired.forEach { IOPMAssertionRelease($0) }
|
|
didFail = true
|
|
return
|
|
}
|
|
acquired.append(identifier)
|
|
}
|
|
assertions = acquired
|
|
didFail = false
|
|
isEnabled = true
|
|
}
|
|
|
|
func disable() {
|
|
assertions.forEach { IOPMAssertionRelease($0) }
|
|
assertions.removeAll()
|
|
isEnabled = false
|
|
didFail = false
|
|
}
|
|
|
|
deinit { assertions.forEach { IOPMAssertionRelease($0) } }
|
|
}
|