import Foundation import IOKit.ps import IOKit.pwr_mgt /// While a source is importing and the Mac is on mains power, hold a /// `PreventUserIdleSystemSleep` assertion so the run finishes (copied from /// CottonHost's `StayAwake` and `IOKitPowerAssertion`). The display still /// sleeps; the lid still sleeps the Mac; on battery nothing is held. @MainActor final class StayAwake { static let reason = "Cotton is importing into your database" private var identifier = IOPMAssertionID(0) private var holding = false func update(importing: Bool) { let wanted = importing && Self.isOnMainsPower if wanted, !holding { var created = IOPMAssertionID(0) let result = IOPMAssertionCreateWithName( kIOPMAssertPreventUserIdleSystemSleep as CFString, IOPMAssertionLevel(kIOPMAssertionLevelOn), Self.reason as CFString, &created ) if result == kIOReturnSuccess { identifier = created holding = true } } else if !wanted, holding { IOPMAssertionRelease(identifier) holding = false } } /// A desktop with no battery to ask about counts as mains. static var isOnMainsPower: Bool { guard let snapshot = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(), let kind = IOPSGetProvidingPowerSourceType(snapshot)?.takeUnretainedValue() as String? else { return true } return kind != kIOPMBatteryPowerKey } }