Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 78 additions & 4 deletions GoDark/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,20 @@ final class DisplayManager {
errorMessage = DisplayError.coreGraphics(callbackResult).localizedDescription
}

let workspaceNotifications = NSWorkspace.shared.notificationCenter
for (name, reason, isAsleep) in [
(NSWorkspace.willSleepNotification, SleepReason.system, true),
(NSWorkspace.didWakeNotification, SleepReason.system, false),
(NSWorkspace.screensDidSleepNotification, SleepReason.screens, true),
(NSWorkspace.screensDidWakeNotification, SleepReason.screens, false)
] {
workspaceNotifications.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in
MainActor.assumeIsolated {
self?.sleepChanged(reason, isAsleep: isAsleep)
}
}
}

Task { [weak self] in
// Fires on hot-plug and after our own reconfigurations.
for await _ in NotificationCenter.default.notifications(
Expand Down Expand Up @@ -140,6 +154,38 @@ final class DisplayManager {
/// Keeps App Nap from throttling the watchdog while the window is hidden.
private var watchdogActivity: NSObjectProtocol?

private enum SleepReason: Hashable {
case system, screens
}

private var sleepingReasons: Set<SleepReason> = []
private var wakeTask: Task<Void, Never>?
private var displayLossTask: Task<Void, Never>?
private var displayLossConfirmed = false

private func sleepChanged(_ reason: SleepReason, isAsleep: Bool) {
wakeTask?.cancel()
wakeTask = nil
resetDisplayLoss()
if isAsleep {
sleepingReasons.insert(reason)
} else {
sleepingReasons.remove(reason)
guard sleepingReasons.isEmpty else { return }
// WindowServer can briefly report missing displays while it rebuilds the configuration.
wakeTask = Task { [weak self] in
do {
try await Task.sleep(for: .seconds(5))
} catch {
return
}
guard let self else { return }
wakeTask = nil
refresh()
}
}
}

func refresh() {
restoreBuiltInIfStranded()

Expand Down Expand Up @@ -183,6 +229,7 @@ final class DisplayManager {
/// monitor goes away, macOS inserts an active placeholder display (seen as a 1920×1080 display
/// with a new ID), so the Mac never looks screenless.
private func restoreBuiltInIfStranded() {
guard sleepingReasons.isEmpty, wakeTask == nil else { return }
if let id = Self.displayIDs(.all).first(where: { CGDisplayIsBuiltin($0) != 0 }) {
builtInID = id
}
Expand All @@ -191,24 +238,51 @@ final class DisplayManager {
let active = Set(Self.displayIDs(.active))
guard !active.contains(builtIn) else {
externalsWhileBuiltInOff = nil
resetDisplayLoss()
return
}

guard let externals = externalsWhileBuiltInOff else {
if externalsWhileBuiltInOff == nil {
// First time we see the built-in display off: remember which monitors are in use.
externalsWhileBuiltInOff = active
Self.log.notice("Built-in display \(builtIn, privacy: .public) is off; watching displays \(active.sorted(), privacy: .public)")
if active.isEmpty { enableBuiltInDisplay(builtIn) }
return
}

guard let externals = externalsWhileBuiltInOff else { return }
let remaining = externals.intersection(active)
guard remaining.isEmpty else { return }
guard remaining.isEmpty else {
resetDisplayLoss()
return
}

guard displayLossConfirmed else {
// Screen-sleep notification can arrive after the display reconfiguration callback.
if displayLossTask == nil {
displayLossTask = Task { [weak self] in
do {
try await Task.sleep(for: .seconds(2))
} catch {
return
}
guard let self else { return }
displayLossTask = nil
displayLossConfirmed = true
refresh()
}
}
return
}

Self.log.notice("Displays \(externals.sorted(), privacy: .public) are gone (active: \(active.sorted(), privacy: .public)); turning built-in display \(builtIn, privacy: .public) back on")
enableBuiltInDisplay(builtIn)
}

private func resetDisplayLoss() {
displayLossTask?.cancel()
displayLossTask = nil
displayLossConfirmed = false
}

/// Runs `refresh()` every couple of seconds while the built-in display is off.
private func updateWatchdog(builtInIsOff: Bool) {
if builtInIsOff, watchdogTask == nil {
Expand Down
6 changes: 6 additions & 0 deletions docs/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,9 @@ defaults read com.dnafication.GoDark
## Testing

There's no test target. Display behaviour can only be checked on real hardware: toggle displays, and plug and unplug monitors while one is off.

To check sleep recovery, turn off the built-in display with an external monitor connected, let
the displays and the Mac sleep, then wake them. The built-in display should stay off without a
CoreGraphics error. Also unplug the external monitor while asleep and wake the Mac: after the
display configuration settles, the built-in display should turn back on. Check ordinary
hot-unplug with the Mac awake as well.