Macotron

macotron.power

Keep the Mac awake, run the power actions from the Apple menu, and react when the Mac sleeps, wakes, locks, or unlocks.

// Stay awake, screen included, until the toggle is pressed again.
macotron.command("Toggle Keep Awake", "Stop the Mac and screen from sleeping", () => {
  if (macotron.power.isPreventing()) {
    macotron.power.allowSleep();
  } else {
    macotron.power.preventSleep({ display: true, reason: "Macotron keep awake" });
  }
});

Keeping the Mac awake

Macotron holds at most one sleep assertion for all plugins. A plugin reload releases it, so a plugin that should stay awake across reloads calls preventSleep() again when it loads.

preventSleep(opts?: { display?: boolean; reason?: string }): boolean

Stops the Mac from going to sleep when it is idle. By default the screen can still dim and sleep, and the lock screen comes with it. With display: true, the screen stays on too. reason is the label that pmset -g assertions shows; it defaults to "Macotron".

A second call replaces the first. Returns false when macOS refuses the assertion.

allowSleep(): void

Releases the assertion. Does nothing when none is held.

isPreventing(): boolean

Whether Macotron holds an assertion now.

Power actions

Each call returns true when the action started and false when it failed.

lock(): boolean

Locks the screen at once.

sleep(): boolean

Puts the Mac to sleep.

displaySleep(): boolean

Turns the screens off and leaves the Mac running, like pmset displaysleepnow.

screensaver(): boolean

Starts the screen saver.

logOut(): boolean

Logs out the current user.

restart(): boolean

Restarts the Mac.

shutdown(): boolean

Shuts down the Mac.

sleep(), logOut(), restart(), and shutdown() send an Apple event to System Events. The first time, macOS asks the user to let Macotron control System Events. Until the user allows it, these calls return false.

Events

None of these events has a payload.

system:sleep

Fires when the Mac is about to sleep. The Mac is already on its way down, so keep the handler short and do not wait on a promise.

system:wake

Fires when the Mac wakes from sleep.

system:lock

Fires when the screen locks.

system:unlock

Fires when the user unlocks the screen.

macotron.on("system:unlock", () => {
  macotron.notify.toast("Welcome back");
});

See also