From c7d428455c42e8039a6aedeb032b0685d7a47ebb Mon Sep 17 00:00:00 2001 From: Grégoire Duchêne Date: Sun, 2 Nov 2025 19:27:32 +0000 Subject: First version of the CLI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It’s pretty basic, and it only works on macOS for now. --- Sources/SleepInhibitor.swift | 48 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Sources/SleepInhibitor.swift (limited to 'Sources/SleepInhibitor.swift') diff --git a/Sources/SleepInhibitor.swift b/Sources/SleepInhibitor.swift new file mode 100644 index 0000000..0cfe895 --- /dev/null +++ b/Sources/SleepInhibitor.swift @@ -0,0 +1,48 @@ +import IOKit.pwr_mgt + +actor SleepInhibitor { + var assertionID = IOPMAssertionID?.none + var isInhibitingSleep: Bool { self.assertionID != nil } + + func create(name: String, details: String) throws { + guard self.assertionID == nil else { + return + } + + var assertionID = IOPMAssertionID(0) + let ioReturn = IOPMAssertionCreateWithDescription( + kIOPMAssertionTypePreventUserIdleSystemSleep as CFString, + name as CFString, + details as CFString, + nil, nil, 0, nil, + &assertionID + ) + guard ioReturn == kIOReturnSuccess else { + throw SleepInhibitorError(ioReturn: ioReturn) + } + self.assertionID = assertionID + } + + func release() throws { + guard let assertionID = self.assertionID else { + return + } + + let ioReturn = IOPMAssertionRelease(assertionID) + guard ioReturn == kIOReturnSuccess else { + throw SleepInhibitorError(ioReturn: ioReturn) + } + self.assertionID = nil + } +} + +struct SleepInhibitorError: CustomStringConvertible, Error { + let ioReturn: IOReturn + + var description: String { + guard let cString = mach_error_string(self.ioReturn) else { + return self.ioReturn.description + } + return String(cString: cString) + } +} -- cgit v1.2.3-70-g09d2