aboutsummaryrefslogtreecommitdiff
path: root/Sources/SleepInhibition.swift
blob: 0d9a05edbdc0d1dd91e8985ea6d800ca27c70652 (plain)
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
#if canImport(IOKit.pwr_mgt)
import IOKit.pwr_mgt

func withSleepInhibited(operation: () async throws -> Void) async throws {
  let assertionID = try {
    var assertionID = IOPMAssertionID(0)
    let ioReturn = IOPMAssertionCreateWithDescription(
      kIOPMAssertionTypePreventUserIdleSystemSleep as CFString,
      "caffeinate-downloads" as CFString,
      "There are files being downloaded" as CFString,
      nil, nil, 0, nil,
      &assertionID
    )
    guard ioReturn == kIOReturnSuccess else {
      throw SleepInhibitionError("failed to inhibit sleep", ioReturn)
    }
    return assertionID
  }()

  do {
    try await operation()
  } catch is CancellationError {
  }

  let ioReturn = IOPMAssertionRelease(assertionID)
  guard ioReturn == kIOReturnSuccess else {
    throw SleepInhibitionError("failed to allow sleep", ioReturn)
  }
}

struct SleepInhibitionError: CustomStringConvertible, Error {
    let description: String

    init(_ description: String, _ code: IOReturn) {
        if let code = mach_error_string(code) {
            self.description = "\(description): \(String(cString: code))"
        } else {
            self.description = "\(description): \(code)"
        }
    }
}
#endif