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
16 changes: 11 additions & 5 deletions Magic Switch/AppDelegate/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate,
_ sender: NSApplication
) -> NSApplication.TerminateReply {
if quitFromStatusBarMenu { return .terminateNow }
if Self.isSystemInitiatedQuit() { return .terminateNow }
if Self.isSystemInitiatedQuit() {
if Self.quitReason == kAEShutDown { bluetoothStore.handOffForShutdown() }
return .terminateNow
}
if Self.isExternalQuitRequest() { return .terminateNow }
// Close the Settings window and its sheets. Sparkle's windows are left
// for the user to close, because closing them in code skips Sparkle's
Expand All @@ -163,10 +166,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate,
/// Without this check we'd block the system from quitting us during
/// shutdown, which can hang the logout flow.
private static func isSystemInitiatedQuit() -> Bool {
guard let event = NSAppleEventManager.shared().currentAppleEvent,
let reason = event.attributeDescriptor(forKeyword: AEKeyword(kAEQuitReason))?
.enumCodeValue
else { return false }
guard let reason = quitReason else { return false }
return reason == kAELogOut
|| reason == kAEReallyLogOut
|| reason == kAEShowRestartDialog
Expand All @@ -175,6 +175,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate,
|| reason == kAEShutDown
}

/// The current AppleEvent's quit reason, such as `kAEShutDown`.
private static var quitReason: OSType? {
NSAppleEventManager.shared().currentAppleEvent?
.attributeDescriptor(forKeyword: AEKeyword(kAEQuitReason))?.enumCodeValue
}

/// True when another app sent the quit AppleEvent. The Dock's Quit doesn't
/// count.
private static func isExternalQuitRequest() -> Bool {
Expand Down
20 changes: 20 additions & 0 deletions Magic Switch/Localizable.xcstrings
Original file line number Diff line number Diff line change
Expand Up @@ -2536,6 +2536,26 @@
}
}
},
"Release peripherals when this Mac sleeps or shuts down" : {
"localizations" : {
"es" : {
"stringUnit" : {
"state" : "translated",
"value" : "Liberar periféricos cuando este Mac entre en reposo o se apague"
}
}
}
},
"Release the peripherals just before this Mac sleeps so your other Mac can take them, and as it shuts down if your other Mac is awake to take them. Turn off to keep them paired with this Mac." : {
"localizations" : {
"es" : {
"stringUnit" : {
"state" : "translated",
"value" : "Libera los periféricos justo antes de que este Mac entre en reposo para que tu otro Mac pueda tomarlos, y al apagarse si tu otro Mac está activo para tomarlos. Desactívalo para mantenerlos emparejados con este Mac."
}
}
}
},
"Release the peripherals just before this Mac sleeps so your other Mac can take them. Turn off to keep them paired with this Mac while it sleeps." : {
"localizations" : {
"es" : {
Expand Down
92 changes: 84 additions & 8 deletions Magic Switch/Model/Store/BluetoothPeripheralStore.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Foundation
import IOBluetooth
import IOKit.ps
import SwiftUI

/// Protocol defining the interface for Bluetooth peripheral management operations
Expand Down Expand Up @@ -65,6 +66,9 @@ final class BluetoothPeripheralStore: NSObject, ObservableObject, BluetoothPerip
/// keeps a peer that vanished in the same instant from delaying sleep more
/// than briefly. Stays well inside the OS's ~30s power-handler watchdog.
static let sleepHandoffAckTimeout: TimeInterval = 3
/// How long a shutdown waits for the peer to answer a ping before it
/// keeps the peripherals paired here instead of handing them off.
static let shutdownPingTimeout: TimeInterval = 3
/// How often the auto-reconnect watcher pages a dropped peripheral to see
/// whether it's back (`answersPage`); only one that answers gets a connect
/// attempt. A short, *constant* cadence is deliberate: the watcher exists
Expand Down Expand Up @@ -609,14 +613,7 @@ final class BluetoothPeripheralStore: NSObject, ObservableObject, BluetoothPerip
else { continue }
connectedIDs.append(peripheral.id)
guard shouldRelease else { continue }
if keepPairingsOnSwitch {
beginReleaseLease(peripheral.id)
_ = device.closeConnection()
} else if device.responds(to: Selector(("remove"))) {
device.perform(Selector(("remove")))
} else {
_ = device.closeConnection()
}
releaseForHandoff(device, id: peripheral.id)
releasedIDs.append(peripheral.id)
}
}
Expand Down Expand Up @@ -655,6 +652,85 @@ final class BluetoothPeripheralStore: NSObject, ObservableObject, BluetoothPerip
}
}

/// Whether this Mac hands its peripherals off as it shuts down: only a Mac
/// with a built-in battery.
static let handsOffAtShutdown: Bool = {
guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),
let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef]
else { return false }
return sources.contains { source in
let description =
IOPSGetPowerSourceDescription(info, source)?.takeUnretainedValue() as? [String: Any]
return description?[kIOPSTypeKey] as? String == kIOPSInternalBatteryType
}
}()

/// Runs (on main) as the system shuts down, holding the shutdown until it
/// returns. Hands the peripherals held here to the peer like
/// `prepareForSleep`, but only on a laptop (`handsOffAtShutdown`) and once
/// the peer answers a ping; otherwise they stay paired here.
func handOffForShutdown() {
let networkStore = NetworkDeviceStore.shared
guard Self.handsOffAtShutdown, releaseOnSleep, PairingStore.shared.isPaired,
let peer = networkStore.networkDevices.first, peer.pendingFingerprint == nil,
peer.isActive || networkStore.isReachable(peer.id),
peripherals.contains(where: { connectionState(for: $0.id) == .connected }),
Self.waitForReply(
timeout: Constants.shutdownPingTimeout,
{ reply in
networkStore.executeCommand(
.ping, on: peer, countsTowardRateLimit: false, completion: reply)
})
else { return }
let registered = peripherals
var releasedIDs: [String] = []
bluetoothQueue.sync {
for peripheral in registered {
guard let device = IOBluetoothDevice(addressString: peripheral.id),
device.isConnected()
else { continue }
releaseForHandoff(device, id: peripheral.id)
releasedIDs.append(peripheral.id)
}
}
guard !releasedIDs.isEmpty else { return }
Log.bluetooth.notice("Before shutdown: handing \(releasedIDs.count) to \(peer.name)")
_ = Self.waitForReply(timeout: Constants.sleepHandoffAckTimeout) { reply in
networkStore.executeAdoptReleased(addresses: releasedIDs, on: peer, completion: reply)
}
}

/// Lets go of `device` for a handoff: closes the connection in keep-pairings
/// mode, otherwise removes the pairing. Call on `bluetoothQueue`.
private func releaseForHandoff(_ device: IOBluetoothDevice, id: String) {
if keepPairingsOnSwitch {
beginReleaseLease(id)
_ = device.closeConnection()
} else if device.responds(to: Selector(("remove"))) {
device.perform(Selector(("remove")))
} else {
_ = device.closeConnection()
}
}

/// Blocks until `send` replies or `timeout` passes, and returns whether it
/// replied with success. `send` must reply off the calling queue.
private static func waitForReply(
timeout: TimeInterval,
_ send: (@escaping (Result<Void, OutgoingFailure>) -> Void) -> Void
) -> Bool {
let replied = DispatchSemaphore(value: 0)
var result: Result<Void, OutgoingFailure>?
send { reply in
result = reply
replied.signal()
}
guard replied.wait(timeout: .now() + timeout) == .success, case .success? = result else {
return false
}
return true
}

/// Runs (on main) from `SleepMonitor` after wake. When auto-reconnect is on,
/// arms the watcher for *everything this Mac was holding before sleep*
/// (`connectedBeforeSleep`) so it chases back whatever didn't return on its
Expand Down
18 changes: 14 additions & 4 deletions Magic Switch/View/Settings/OtherSettingsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ struct OtherSettingsView: View {
@AppStorage(BluetoothPeripheralStore.keepPairingsOnSwitchDefaultsKey)
private var keepPairingsOnSwitch: Bool = false

private var releaseOnSleepTitle: LocalizedStringKey {
BluetoothPeripheralStore.handsOffAtShutdown
? "Release peripherals when this Mac sleeps or shuts down"
: "Release peripherals when this Mac sleeps"
}

private var releaseOnSleepHelp: LocalizedStringKey {
BluetoothPeripheralStore.handsOffAtShutdown
? "Release the peripherals just before this Mac sleeps so your other Mac can take them, and as it shuts down if your other Mac is awake to take them. Turn off to keep them paired with this Mac."
: "Release the peripherals just before this Mac sleeps so your other Mac can take them. Turn off to keep them paired with this Mac while it sleeps."
}

// MARK: - View Content

/// Form content containing setting options
Expand Down Expand Up @@ -60,10 +72,8 @@ struct OtherSettingsView: View {
}
}
Section(header: Text("Peripheral Handling")) {
Toggle("Release peripherals when this Mac sleeps", isOn: $releaseOnSleep)
.help(
"Release the peripherals just before this Mac sleeps so your other Mac can take them. Turn off to keep them paired with this Mac while it sleeps."
)
Toggle(releaseOnSleepTitle, isOn: $releaseOnSleep)
.help(releaseOnSleepHelp)
Toggle("Reconnect peripherals if they drop", isOn: $autoReconnect)
.help(
"Keep trying for up to 10 minutes to reconnect a peripheral that dropped from this Mac, and take over the ones your other Mac leaves behind when it sleeps. Never takes a peripheral your other Mac is using."
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ A Magic keyboard, trackpad or mouse waits for the last Mac it used. If that Mac
Usually that's all you need to do, because Magic Switch is already trying to connect it. When a peripheral should come to this Mac but doesn't connect, this Mac looks for it every few seconds for 10 minutes and connects it as soon as it's back on. That happens after:

- **a switch to this Mac**: from either Mac's menu, a keyboard shortcut, the URL scheme, or a marked display;
- **a handoff at sleep**: your other Mac gave this Mac its peripherals as it went to sleep;
- **a handoff**: your other Mac gave this Mac its peripherals as it went to sleep or shut down;
- **a drop**: a peripheral dropped off this Mac;
- **a wake**: this Mac woke up, for what it had before sleeping and what an unreachable other Mac left behind;
- **your other Mac going offline**: for what that Mac had.
Expand All @@ -100,7 +100,7 @@ To run into this less, leave **Release peripherals when this Mac sleeps** enable

### Example

You work on a MacBook plugged into a desk display, next to an iMac. On the MacBook, the display is marked under **Take Peripherals When a Display Connects**. In the evening you shut the iMac down while it has the keyboard and trackpad. Magic Switch lets go of peripherals when a Mac sleeps, but not when it shuts down, so they keep waiting for the iMac.
You work on a MacBook plugged into a desk display, next to an iMac. On the MacBook, the display is marked under **Take Peripherals When a Display Connects**. In the evening you shut the iMac down while it has the keyboard and trackpad. A desktop Mac keeps its peripherals when it shuts down, so they keep waiting for the iMac.

The next morning you plug the MacBook into the display, and it tries to take the keyboard and trackpad. Neither answers. You switch each one off and on, and a few seconds later both are on the MacBook. You never open the menu.

Expand Down Expand Up @@ -134,7 +134,7 @@ Run it on the Mac that should act; `-g` keeps your current app focused. `take` w

- **Open at Login** (macOS 13 and later).
- **Connect over Bluetooth when the network can't**: see [If the Macs can't find each other](#if-the-macs-cant-find-each-other).
- **Release peripherals when this Mac sleeps** (on by default): closing or sleeping this Mac hands its peripherals to your other Mac, or frees them for it, instead of leaving them waiting for a sleeping Mac. If both Macs end up asleep, freed peripherals belong to neither and may need a key press right after waking, or switching off and on. Turned off, peripherals stay paired with this Mac while it sleeps, and the other Mac needs the off-and-on instead.
- **Release peripherals when this Mac sleeps** (on by default; "…sleeps or shuts down" on a Mac laptop): closing or sleeping this Mac hands its peripherals to your other Mac, or frees them for it, instead of leaving them waiting for a sleeping Mac. A Mac laptop also hands them over as it shuts down, if your other Mac is awake to take them. A desktop Mac keeps them when it shuts down, so it has them at the login window when it starts up. If both Macs end up asleep, freed peripherals belong to neither and may need a key press right after waking, or switching off and on. Turned off, peripherals stay paired with this Mac while it sleeps or is off, and the other Mac needs the off-and-on instead.
- **Reconnect peripherals if they drop** (on by default): the 10-minute retries in [If a peripheral won't connect](#if-a-peripheral-wont-connect).
- **Switch peripherals without unpairing them** (off by default): reconnect peripherals instead of pairing them again, for ones that stay paired with both Macs at once. Leave it off with Apple's Magic keyboards, trackpads and mice: with it on, they go back to the last Mac they used.
- **Keyboard Shortcuts**: send, take or toggle every peripheral. A take shortcut works even while the other Mac is asleep.
Expand Down
2 changes: 1 addition & 1 deletion docs/annotate-screenshots.sh
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ annotate other-tab "#1E1E1E" 517 88 1915 47 \
10 1028 1560 1056 1560" \
"1|Open at Login — start Magic Switch when you log in
2|Bluetooth fallback — connect when the network blocks the Macs
3|Release peripherals to the other Mac when this Mac sleeps
3|Release peripherals to the other Mac when this Mac sleeps or shuts down
4|Reconnect peripherals automatically if they drop
5|Hand over peripherals paired to both Macs without re-pairing
6|Record a shortcut — send, take, or toggle every peripheral from anywhere
Expand Down
Binary file modified docs/assets/other-tab.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading