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
11 changes: 10 additions & 1 deletion App/Dashboard/DashboardView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,14 @@ struct DashboardView: View {
}
}

private var keepAwakeHelp: String {
if keepAwake.isBlockedByLowBattery, let cutoff = keepAwake.lowBatteryCutoff {
"Keep Awake is off at \(cutoff.percent)% battery or below until you plug in"
} else {
keepAwake.isEnabled ? "Keep Awake is on" : "Keep Awake"
}
}

private var footer: some View {
HStack(spacing: 4) {
Button("Activity Monitor", action: actions.openActivityMonitor)
Expand All @@ -135,7 +143,8 @@ struct DashboardView: View {
.toggleStyle(.button)
.labelStyle(.iconOnly)
.foregroundStyle(keepAwake.isEnabled ? AnyShapeStyle(DashboardSection.power.tint) : AnyShapeStyle(.secondary))
.help(keepAwake.isEnabled ? "Keep Awake is on" : "Keep Awake")
.disabled(keepAwake.isBlockedByLowBattery)
.help(keepAwakeHelp)
Spacer()
Button("Settings…", action: actions.openSettings)
.keyboardShortcut(",")
Expand Down
26 changes: 26 additions & 0 deletions App/Settings/KeepAwakePane.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,24 @@ struct KeepAwakePane: View {
Text("Turn on Keep Awake with the cup in the dashboard, or ⌥-click any Barometry item in the menu bar. While it's on, Barometry moves the cursor a point and back after this long without input, so apps that check for activity still see some.")
.foregroundStyle(.secondary)
}
// The battery module is unavailable exactly when this Mac has no battery.
if preferences.menuBarModules.isAvailable(.battery) {
Section {
Toggle("Turn off on low battery", isOn: $preferences.keepAwakeStopsOnLowBattery)
LabeledContent("Battery at or below") {
HStack {
Text("\(preferences.lowBatteryCutoff.percent)%")
.monospacedDigit()
Stepper("Battery at or below", value: lowBatteryCutoffPercent, in: LowBatteryCutoff.range, step: 5)
.labelsHidden()
}
}
.disabled(!preferences.keepAwakeStopsOnLowBattery)
} footer: {
Text("While on battery power, Keep Awake turns off at this charge and stays off until you plug in.")
.foregroundStyle(.secondary)
}
}
}
.settingsPane()
// Accessibility approval can change while the window is open.
Expand All @@ -40,6 +58,14 @@ struct KeepAwakePane: View {
}
}

private var lowBatteryCutoffPercent: Binding<Int> {
Binding {
preferences.lowBatteryCutoff.percent
} set: { percent in
preferences.lowBatteryCutoff = LowBatteryCutoff(percent: percent)
}
}

/// Turning it on asks for Accessibility permission, which macOS needs to post the movement.
private var movesCursorWhenIdle: Binding<Bool> {
Binding {
Expand Down
3 changes: 3 additions & 0 deletions App/StatusItemController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ final class StatusItemController: NSObject {
}

private func applyPreferences() {
// Before reading `shownModules`, so a cutoff that turns Keep Awake off removes its item now.
keepAwake.lowBatteryCutoff = preferences.keepAwakeStopsOnLowBattery ? preferences.lowBatteryCutoff : nil
keepAwake.battery = monitor.battery
let wanted = ItemLayout(layout: preferences.menuBarLayout, style: preferences.menuBarStyle, modules: shownModules)
if wanted != itemLayout {
rebuildItems(wanted)
Expand Down
51 changes: 49 additions & 2 deletions Packages/BarometryKit/Sources/BarometryKit/KeepAwake.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import Observation

/// Keeps the display, and with it the system, from idle sleep while enabled, like
/// `caffeinate -d`, and optionally nudges the cursor so apps watching for user activity
/// see some. Starts disabled each launch.
/// see some. Starts disabled each launch, and stays off while the battery is at or below
/// `lowBatteryCutoff`.
@MainActor
@Observable
public final class KeepAwake {
Expand All @@ -23,6 +24,24 @@ public final class KeepAwake {
}
}

/// Whether the battery is at or below `lowBatteryCutoff`, which keeps Keep Awake off.
public private(set) var isBlockedByLowBattery = false

/// Charge at or below which Keep Awake turns off and can't be turned on while on battery
/// power, or nil to ignore the battery.
@ObservationIgnored public var lowBatteryCutoff: LowBatteryCutoff? {
didSet {
if lowBatteryCutoff != oldValue { applyLowBatteryCutoff() }
}
}

/// The latest reading, or nil on Macs without a battery.
@ObservationIgnored public var battery: BatterySample? {
didSet {
if battery != oldValue { applyLowBatteryCutoff() }
}
}

@ObservationIgnored private var assertion: PowerAssertion?
@ObservationIgnored private var cursorNudger: CursorNudger?

Expand All @@ -32,14 +51,21 @@ public final class KeepAwake {
setEnabled(!isEnabled)
}

/// Stays disabled if macOS refuses the assertion.
/// Stays disabled if macOS refuses the assertion or the battery is too low.
public func setEnabled(_ enabled: Bool) {
let enabled = enabled && !isBlockedByLowBattery
guard enabled != isEnabled else { return }
assertion = enabled ? PowerAssertion(type: Self.assertionType, name: Self.assertionName) : nil
isEnabled = assertion != nil
updateCursorNudger()
}

private func applyLowBatteryCutoff() {
let isBlocked = lowBatteryCutoff?.isReached(by: battery) ?? false
if isBlocked != isBlockedByLowBattery { isBlockedByLowBattery = isBlocked }
if isBlocked { setEnabled(false) }
}

private func updateCursorNudger() {
if isEnabled, let interval = cursorNudgeInterval {
cursorNudger = CursorNudger(every: interval.duration)
Expand All @@ -48,3 +74,24 @@ public final class KeepAwake {
}
}
}

/// Battery charge, in whole percent, at or below which Keep Awake turns off while on
/// battery power.
public struct LowBatteryCutoff: Hashable, Sendable {
public static let range = 5...50
public static let `default` = LowBatteryCutoff(percent: 20)

public let percent: Int

/// Clamps to `range`.
public init(percent: Int) {
self.percent = min(max(percent, Self.range.lowerBound), Self.range.upperBound)
}

/// Compares the charge rounded the way it's shown, so the cutoff matches the displayed
/// percentage. Charging, charged, or plugged-in batteries never reach it.
func isReached(by battery: BatterySample?) -> Bool {
guard let battery, case .discharging = battery.state else { return false }
return Int((battery.charge.fraction * 100).rounded()) <= percent
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,15 @@ public final class Preferences {
didSet { defaults.set(cursorNudgeInterval.rawValue, forKey: Key.cursorNudgeInterval) }
}

/// Whether Keep Awake turns off at `lowBatteryCutoff` while on battery power.
public var keepAwakeStopsOnLowBattery: Bool {
didSet { defaults.set(keepAwakeStopsOnLowBattery, forKey: Key.keepAwakeStopsOnLowBattery) }
}

public var lowBatteryCutoff: LowBatteryCutoff {
didSet { defaults.set(lowBatteryCutoff.percent, forKey: Key.lowBatteryCutoff) }
}

@ObservationIgnored private let defaults: UserDefaults

/// The unavailable modules are ones this Mac can't show, such as battery on a desktop.
Expand All @@ -87,6 +96,8 @@ public final class Preferences {
hiddenDashboardSections = Set(Self.decode(defaults.stringArray(forKey: Key.hiddenDashboardSections)) ?? [])
movesCursorWhenIdle = defaults.bool(forKey: Key.movesCursorWhenIdle)
cursorNudgeInterval = CursorNudgeInterval(rawValue: defaults.integer(forKey: Key.cursorNudgeInterval)) ?? .oneMinute
keepAwakeStopsOnLowBattery = defaults.object(forKey: Key.keepAwakeStopsOnLowBattery) as? Bool ?? true
lowBatteryCutoff = (defaults.object(forKey: Key.lowBatteryCutoff) as? Int).map(LowBatteryCutoff.init(percent:)) ?? .default
}

/// Moves sections the way SwiftUI's `onMove` reports a drag.
Expand Down Expand Up @@ -119,6 +130,8 @@ public final class Preferences {
static let hiddenDashboardSections = "hiddenDashboardSections"
static let movesCursorWhenIdle = "movesCursorWhenIdle"
static let cursorNudgeInterval = "cursorNudgeInterval"
static let keepAwakeStopsOnLowBattery = "keepAwakeStopsOnLowBattery"
static let lowBatteryCutoff = "lowBatteryCutoff"
}
}

Expand Down
73 changes: 73 additions & 0 deletions Packages/BarometryKit/Tests/BarometryKitTests/KeepAwakeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,77 @@ struct KeepAwakeTests {
#expect(!keepAwake.isEnabled)
#expect(!heldAssertionNames().contains(KeepAwake.assertionName))
}

private func battery(_ percent: Double, _ state: BatterySample.State = .discharging(timeRemaining: nil)) -> BatterySample {
BatterySample(charge: Percent(percent / 100), state: state)
}

@Test func turnsOffAtTheCutoffOnBatteryPower() {
let keepAwake = KeepAwake()
keepAwake.lowBatteryCutoff = .default
keepAwake.battery = battery(21)
keepAwake.setEnabled(true)
#expect(keepAwake.isEnabled)

keepAwake.battery = battery(20)
#expect(!keepAwake.isEnabled)
#expect(keepAwake.isBlockedByLowBattery)
}

@Test func cannotBeTurnedBackOnBelowTheCutoff() {
let keepAwake = KeepAwake()
keepAwake.lowBatteryCutoff = .default
keepAwake.battery = battery(15)

keepAwake.toggle()
#expect(!keepAwake.isEnabled)
#expect(!heldAssertionNames().contains(KeepAwake.assertionName))
}

@Test(arguments: [
BatterySample.State.charging(timeToFull: nil),
.charged,
.notCharging,
])
func ignoresTheCutoffWhilePluggedIn(state: BatterySample.State) {
let keepAwake = KeepAwake()
keepAwake.lowBatteryCutoff = .default
keepAwake.battery = battery(10, state)

keepAwake.setEnabled(true)
#expect(keepAwake.isEnabled)
keepAwake.setEnabled(false)
}

@Test func ignoresTheBatteryWithoutACutoffOrBattery() {
let withoutCutoff = KeepAwake()
withoutCutoff.battery = battery(5)
withoutCutoff.setEnabled(true)
#expect(withoutCutoff.isEnabled)
withoutCutoff.setEnabled(false)

let withoutBattery = KeepAwake()
withoutBattery.lowBatteryCutoff = .default
withoutBattery.setEnabled(true)
#expect(withoutBattery.isEnabled)
withoutBattery.setEnabled(false)
}

@Test func pluggingInLiftsTheBlock() {
let keepAwake = KeepAwake()
keepAwake.lowBatteryCutoff = .default
keepAwake.battery = battery(15)
#expect(keepAwake.isBlockedByLowBattery)

keepAwake.battery = battery(15, .charging(timeToFull: nil))
#expect(!keepAwake.isBlockedByLowBattery)
keepAwake.setEnabled(true)
#expect(keepAwake.isEnabled)
keepAwake.setEnabled(false)
}

@Test func cutoffIsClampedToItsRange() {
#expect(LowBatteryCutoff(percent: 0).percent == LowBatteryCutoff.range.lowerBound)
#expect(LowBatteryCutoff(percent: 99).percent == LowBatteryCutoff.range.upperBound)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ struct PreferencesTests {
preferences.hiddenDashboardSections = [.disk]
preferences.movesCursorWhenIdle = true
preferences.cursorNudgeInterval = .fourMinutes
preferences.keepAwakeStopsOnLowBattery = false
preferences.lowBatteryCutoff = LowBatteryCutoff(percent: 35)

let reloaded = Preferences(defaults: defaults)

Expand All @@ -45,6 +47,8 @@ struct PreferencesTests {
#expect(reloaded.hiddenDashboardSections == [.disk])
#expect(reloaded.movesCursorWhenIdle)
#expect(reloaded.cursorNudgeInterval == .fourMinutes)
#expect(!reloaded.keepAwakeStopsOnLowBattery)
#expect(reloaded.lowBatteryCutoff.percent == 35)
}

@Test func automaticInterfaceClearsTheStoredName() {
Expand All @@ -70,6 +74,13 @@ struct PreferencesTests {
#expect(preferences.cursorNudgeInterval == .oneMinute)
}

@Test func lowBatteryCutoffDefaultsToOnAtTwentyPercent() {
let preferences = Preferences(defaults: defaults)

#expect(preferences.keepAwakeStopsOnLowBattery)
#expect(preferences.lowBatteryCutoff.percent == 20)
}

@Test func storedModuleOrderIsRepairedToContainEveryModuleOnce() {
defaults.set(["battery", "cpu", "battery", "removed"], forKey: "menuBarModuleOrder")

Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Barometry shows CPU, GPU, memory, network, sensor, and battery readings as compa
- A refresh interval of 1, 2, or 5 seconds, with 1-second updates while the dashboard is open
- Keep Awake, which stops idle sleep and keeps the display on, marked with a cup on the battery in the menu bar
- Optionally, while Keep Awake is on, an imperceptible cursor nudge after 30 seconds to 4 minutes without input, so apps that check for activity still see some
- Keep Awake turns off on battery power at a low-charge cutoff, 20% by default
- Launch at login
- Under 1% CPU while idle

Expand Down Expand Up @@ -54,7 +55,7 @@ In-app updates work only after you copy Barometry to `/Applications`. macOS tran

Barometry lives in the menu bar and has no Dock icon. Click a menu bar item to open the dashboard, and hover or click a section to see its details. Choose **Settings…** (⌘,) to pick modules, the layout, and the refresh interval. Quit from the dashboard or with ⌘Q.

Turn on Keep Awake with the cup button in the dashboard's footer, or ⌥-click any Barometry item in the menu bar. It stays on until you turn it off or quit Barometry.
Turn on Keep Awake with the cup button in the dashboard's footer, or ⌥-click any Barometry item in the menu bar. It stays on until you turn it off or quit Barometry, or until a MacBook on battery power drops to 20%. Change or turn off that cutoff under **Turn off on low battery** in **Settings → Keep Awake**. At or below the cutoff, Keep Awake can't be turned on again until you plug in.

To have Keep Awake also nudge the cursor when you're idle, turn on **Move cursor when idle** in **Settings → Keep Awake** and allow Barometry in **System Settings → Privacy & Security → Accessibility**, which macOS requires to move the cursor.

Expand Down
Loading