# How Vorssaint-utils Detects Display Sleep and Power States for Keep Awake

> Discover how Vorssaint-utils detects display sleep and power states. Learn its IOKit and run-loop callback logic to keep your system awake dynamically.

- Repository: [vorssaint/vorssaint-utils](https://github.com/vorssaint/vorssaint-utils)
- Tags: how-to-guide
- Published: 2026-09-12

---

**Vorssaint-utils prevents system sleep by monitoring display states via IOKit assertions and power sources through run-loop callbacks, allowing the Keep Awake service to adapt dynamically to screen locks and AC/battery transitions.**

The Keep Awake feature in the [vorssaint/vorssaint-utils](https://github.com/vorssaint/vorssaint-utils) repository provides granular control over macOS idle sleep behavior. To achieve this, the library implements platform-specific detection logic that tracks when the display attempts to sleep, when the user locks the screen, and when the power source changes between battery and AC. This deep dive explores the IOKit integration and notification observers that enable accurate **display sleep and power state detection for Keep Awake** automation.

## Preventing Display Sleep with IOPM Assertions

At the core of display sleep prevention lies the `applyAssertions` method in [`Sources/Vorssaint/Services/KeepAwakeManager.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Sources/Vorssaint/Services/KeepAwakeManager.swift) (lines 27-34). When a Keep Awake session activates, the manager checks the `keepAwakeAllowDisplaySleep` user default to determine whether the display should remain on.

If the user prohibits display sleep, the code creates an IOKit power management assertion:

```swift
if !allowDisplaySleep, !hasDisplayAssertion {
    var id = IOPMAssertionID(0)
    let ok = IOPMAssertionCreateWithName(
        "PreventUserIdleDisplaySleep" as CFString,
        IOPMAssertionLevel(kIOPMAssertionLevelOn),
        "Vorssaint: keep the display on" as CFString,
        &id
    )
    if ok == kIOReturnSuccess {
        displayAssertion = id
        hasDisplayAssertion = true
    }
}

```

The `IOPMAssertionCreateWithName` function registers a `"PreventUserIdleDisplaySleep"` assertion with the system, signaling to macOS that the display must remain active. When the session ends or the user preference changes, `IOPMAssertionRelease` removes this restriction.

## Monitoring Screen Lock State

Beyond hardware display sleep, the library tracks logical screen locks through distributed notifications. The `syncScreenLockMonitoring` method (lines 37-58) registers observers for `com.apple.screenIsLocked` and `com.apple.screenIsUnlocked` notifications.

When these notifications fire, the `screenLockStateDidChange(locked:)` callback updates the internal `screenLocked` property. If the user enables `keepAwakePauseWhenLocked`, the manager immediately pauses the session by setting `sessionPausedForScreenLock` and triggers an automation re-evaluation. This ensures that Keep Awake does not maintain full system wakefulness while the machine is secured.

## Detecting Power Source Changes

Power state detection operates through two complementary mechanisms in [`KeepAwakeManager.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/KeepAwakeManager.swift): active monitoring via IOKit run-loop sources and on-demand battery queries.

### Registering Power Source Callbacks

The `setPowerMonitoringEnabled` method (lines 25-43) creates a run-loop source using `IOPSNotificationCreateRunLoopSource`. This API registers a low-level callback that fires whenever the system switches between AC power and battery:

```swift
private func setPowerMonitoringEnabled(_ enabled: Bool) {
    if enabled {
        guard powerSourceRunLoopSource == nil else { return }
        let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
        powerSourceRunLoopSource = IOPSNotificationCreateRunLoopSource({ context in
            guard let context else { return }
            let manager = Unmanaged<KeepAwakeManager>.fromOpaque(context).takeUnretainedValue()
            DispatchQueue.main.async {
                manager.scheduleAutomationEvaluation(after: 0.1)
            }
        }, context)?.takeRetainedValue()
        if let powerSourceRunLoopSource {
            CFRunLoopAddSource(CFRunLoopGetMain(), powerSourceRunLoopSource, .defaultMode)
        }
    } else {
        // Removal logic omitted for brevity
    }
}

```

The callback dispatches to the main queue and invokes `scheduleAutomationEvaluation(after: 0.1)`, introducing a 100-millisecond debounce before re-evaluating automation conditions.

### Querying Battery Status On-Demand

For immediate power state verification, the automation engine calls `SystemInfo.batterySnapshot()` defined in [`Sources/Vorssaint/Services/SystemInfo.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Sources/Vorssaint/Services/SystemInfo.swift) (lines 30-49). This method returns a `BatteryInfo` struct containing the `isOnBattery` boolean flag.

The `currentMatchingAutomationConditions` logic uses this snapshot to determine the `connectedToPower` status. When combined with the `allowDisplaySleep` preference, these flags decide whether to auto-activate or deactivate a Keep Awake session based on the user's power-aware automation rules.

## Coordinating Automation Logic

The detection mechanisms converge in the `evaluateAutomation` method, which orchestrates session management based on real-time conditions. When power sources shift or screen locks engage, the manager consults both the power monitoring state and the display assertion status to determine the correct session posture.

Key integration points include:

- **Power transitions** trigger immediate re-evaluation via the `IOPSNotificationCreateRunLoopSource` callback.
- **Screen lock events** pause or resume sessions depending on `keepAwakePauseWhenLocked`.
- **Display assertions** are created or released dynamically as `keepAwakeAllowDisplaySleep` changes.

This architecture ensures that Vorssaint-utils maintains minimal system impact while providing responsive adaptation to macOS power management events.

## Summary

- **Display sleep prevention** relies on `IOPMAssertionCreateWithName` with `"PreventUserIdleDisplaySleep"` in [`KeepAwakeManager.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/KeepAwakeManager.swift), gated by the `keepAwakeAllowDisplaySleep` user default.
- **Screen lock detection** uses distributed notifications (`com.apple.screenIsLocked`/`com.apple.screenIsUnlocked`) to pause sessions when the machine is secured.
- **Power state monitoring** employs `IOPSNotificationCreateRunLoopSource` for asynchronous change detection and `SystemInfo.batterySnapshot()` for synchronous battery status queries.
- **Automation coordination** ties these inputs together through `scheduleAutomationEvaluation` and `evaluateAutomation`, enabling context-aware Keep Awake behavior.

## Frequently Asked Questions

### How does Vorssaint-utils prevent the display from sleeping during a Keep Awake session?

When the `keepAwakeAllowDisplaySleep` preference is disabled, the `applyAssertions` method in [`KeepAwakeManager.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/KeepAwakeManager.swift) calls `IOPMAssertionCreateWithName` with the assertion type `"PreventUserIdleDisplaySleep"`. This registers a system-level hold that prevents macOS from dimming or sleeping the display until `IOPMAssertionRelease` is called.

### What happens to Keep Awake when the user locks the screen?

The `syncScreenLockMonitoring` method observes `com.apple.screenIsLocked` notifications. If `keepAwakePauseWhenLocked` is enabled, the manager sets `sessionPausedForScreenLock` to true and suspends active assertions, ensuring the system can sleep normally while the screen is locked for security.

### How does the library detect when the Mac switches from battery to AC power?

The `setPowerMonitoringEnabled` method installs a run-loop source via `IOPSNotificationCreateRunLoopSource`, which invokes a callback whenever the power source changes. The callback schedules an automation evaluation on the main thread, allowing the system to react to AC/battery transitions within approximately 100 milliseconds.

### Where does Vorssaint-utils query the current battery status?

Synchronous battery state checks occur in [`SystemInfo.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/SystemInfo.swift) through the `batterySnapshot()` method (lines 30-49). This function returns a `BatteryInfo` struct containing the `isOnBattery` property, which the automation logic uses to determine whether power-dependent Keep Awake rules should activate.