extras: awake assertion, fullscreen rule, drawn cursor, transfer notices
- MWBMac/Awake.swift: DisplayAwake renews an IOPMAssertion (PreventUserIdleDisplaySleep, 90 s timeout) on every Awake (21), the macOS answer to Common.HumanBeingDetected/PokeMyself (Receiver.cs:244-249, Common.cs:561-591) without posting input. - MWBMac/Fullscreen.swift: the frontmost app's excluded-apps test and a covers-a-whole-display window check, cached 250 ms; gated in the Engine by IsEasyMouseSwitchAllowed's two early outs (Common.cs:1638-1650), so it is asked only on the edge path. - MWBMac/FakeCursor.swift: CursorOverlay draws NSCursor.arrow at the last injected position (Receiver.cs:186-188) and hides on park, local input and shutdown (Common.cs:1495, InputHook.cs:256-264); FakeCursor coalesces the main-thread hops. - Settings.drawMouseCursor accessor + the Behaviour-pane toggle, answering app-ui's open request. - UIBridge.TransferNotices wires ClipboardAction.note to the Notifier, answering clipboard's open request (Clipboard.cs:610-618, 869-881, 916). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
1 parent
b73e878ae4
commit
21c886165e
9 files changed
+508
-9
No files matched your search
@@ -0,0 +1,96 @@
|
||||
// Keeping this Mac's display awake while somebody drives it from another
|
||||
// machine — the receiving half of `BlockScreenSaverOnOtherMachines`.
|
||||
//
|
||||
// Windows: a peer that has seen real input since its previous beat sends
|
||||
// `Awake (21)` instead of `Heartbeat (20)` (`Common.SendAwakeBeat`,
|
||||
// `Common.cs:545-559`, docs/protocol.md §3.3), and the receiver answers it with
|
||||
// `Common.HumanBeingDetected()` (`Receiver.cs:245-248`). That method
|
||||
// (`Common.cs:561-572`) checks whether *local* input has happened since its own
|
||||
// previous call and, if not, runs `PokeMyself()` (`:574-591`): ten ±9-pixel
|
||||
// relative mouse jiggles, 50 ms apart, stopping early if the local user moves.
|
||||
// The jiggle is there to reset the Windows idle timer, which is the only lever
|
||||
// a user-mode process has.
|
||||
//
|
||||
// macOS has the lever directly: a power assertion. `kIOPMAssertionTypePrevent
|
||||
// UserIdleDisplaySleep` holds the display on without touching the pointer, which
|
||||
// also keeps CLAUDE.md invariant 5 — nothing here posts an event. The assertion
|
||||
// carries its own 90 s timeout and is re-created by each `Awake`, so it lapses
|
||||
// on its own about half a beat after the beats stop (60 s cadence, §3.3).
|
||||
//
|
||||
// `IOKit` is imported here and nowhere else in the port.
|
||||
|
||||
import Foundation
|
||||
import IOKit.pwr_mgt
|
||||
import os
|
||||
|
||||
/// Holds the display awake for as long as `Awake` packets keep arriving.
|
||||
///
|
||||
/// One per process, owned by the Engine. Thread-safe: `renew()` is called from
|
||||
/// the Engine actor and `release()` also from the shutdown path.
|
||||
public final class DisplayAwake: Sendable {
|
||||
/// How long one `Awake` packet is worth. A peer beats every 60 s while it is
|
||||
/// blocking screen savers (`Common.cs:547`, §3.3), so one and a half beats
|
||||
/// of slack keeps the display on through a late packet and lets the
|
||||
/// assertion lapse by itself when the peer goes quiet.
|
||||
public static let timeout: TimeInterval = 90
|
||||
|
||||
/// What the assertion is called in `pmset -g assertions`.
|
||||
static let assertionName = "Mouse Without Borders: a remote user is active"
|
||||
|
||||
private let assertion: OSAllocatedUnfairLock<IOPMAssertionID?>
|
||||
|
||||
/// A releaser that holds nothing yet.
|
||||
public init() {
|
||||
assertion = OSAllocatedUnfairLock(initialState: nil)
|
||||
}
|
||||
|
||||
/// Whether an assertion is being held right now. `false` says nothing about
|
||||
/// the display: the assertion may simply have timed out in the kernel.
|
||||
public var isAsserted: Bool { assertion.withLock { $0 != nil } }
|
||||
|
||||
/// Takes a fresh assertion and drops the previous one, in that order so the
|
||||
/// display is never momentarily unasserted.
|
||||
///
|
||||
/// Call this on every `Awake (21)`, never on a plain `Heartbeat (20)` —
|
||||
/// that distinction is the whole of the sender's
|
||||
/// `BlockScreenSaverOnOtherMachines` setting, and the receiver honours it
|
||||
/// unconditionally, exactly as `Receiver.cs:245-248` does.
|
||||
public func renew(seconds: TimeInterval = DisplayAwake.timeout) {
|
||||
guard let fresh = DisplayAwake.create(seconds: seconds) else { return }
|
||||
let previous = assertion.withLock { held -> IOPMAssertionID? in
|
||||
let previous = held
|
||||
held = fresh
|
||||
return previous
|
||||
}
|
||||
if let previous { IOPMAssertionRelease(previous) }
|
||||
}
|
||||
|
||||
/// Drops the assertion now. Idempotent, and safe to call when none is held.
|
||||
public func release() {
|
||||
let previous = assertion.withLock { held -> IOPMAssertionID? in
|
||||
let previous = held
|
||||
held = nil
|
||||
return previous
|
||||
}
|
||||
if let previous { IOPMAssertionRelease(previous) }
|
||||
}
|
||||
|
||||
/// One assertion with its own expiry, so a lost `release()` cannot leave a
|
||||
/// Mac awake for ever.
|
||||
private static func create(seconds: TimeInterval) -> IOPMAssertionID? {
|
||||
let properties: [String: Any] = [
|
||||
kIOPMAssertionTypeKey: kIOPMAssertionTypePreventUserIdleDisplaySleep,
|
||||
kIOPMAssertionNameKey: assertionName,
|
||||
kIOPMAssertionLevelKey: kIOPMAssertionLevelOn,
|
||||
kIOPMAssertionTimeoutKey: seconds,
|
||||
kIOPMAssertionTimeoutActionKey: kIOPMAssertionTimeoutActionRelease,
|
||||
]
|
||||
var id = IOPMAssertionID(0)
|
||||
let result = IOPMAssertionCreateWithProperties(properties as CFDictionary, &id)
|
||||
guard result == kIOReturnSuccess else {
|
||||
Log.app.error("could not hold the display awake: IOKit error \(result)")
|
||||
return nil
|
||||
}
|
||||
return id
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// The drawn cursor: a small arrow where the remote pointer is, on the Mac that
|
||||
// is being controlled. `DrawMouseCursor` in the settings.
|
||||
//
|
||||
// Windows: `CustomCursor.ShowFakeMouseCursor(x, y)` (`CustomCursor.cs:68-146`)
|
||||
// is one call that both shows and hides — `int.MinValue` for either coordinate
|
||||
// means hide. It is fed from `Receiver.cs:184-188`, which injects the remote
|
||||
// mouse event, reads `GetCursorPos` into `Common.LastX/LastY` and draws there;
|
||||
// and it is called with `int.MinValue` from `Common.HideMouseCursor`
|
||||
// (`Common.cs:1495`), from the three `Helper` form routines (`:192, 224, 244`)
|
||||
// and from the mouse hook when the local user moves their own mouse
|
||||
// (`InputHook.cs:261-263`). The form itself is a 32×32 borderless top-most
|
||||
// window placed at (x+1, y+1) (`CustomCursor.cs:100-103`).
|
||||
//
|
||||
// Two deviations, both recorded in the feature README:
|
||||
//
|
||||
// 1. Windows only draws while the real cursor is hidden or suppressed
|
||||
// (`GetCursorInfo`, `ci.flags != 1`, `CustomCursor.cs:73-79`). macOS has no
|
||||
// read-only equivalent, and a Mac being driven keeps its real pointer
|
||||
// visible because the injected moves move it, so the overlay is a second,
|
||||
// deliberately offset marker rather than a replacement.
|
||||
// 2. `DrawMouseEx` selects a richer drawing path on Windows
|
||||
// (`frmMouseCursor.cs:32-52` paints pixels straight onto the desktop DC).
|
||||
// It is accepted and ignored here; there is no macOS equivalent worth
|
||||
// having.
|
||||
|
||||
import AppKit
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
import MWBCore
|
||||
import os
|
||||
|
||||
/// The Engine's door to the drawn cursor: callable from any isolation, one
|
||||
/// coalesced hop to the main thread per burst of positions.
|
||||
///
|
||||
/// The overlay is an AppKit window, so it can only be touched on the main
|
||||
/// thread; a controlled Mac receives up to a hundred mouse packets a second and
|
||||
/// one `Task` per packet would both allocate and arrive out of order. Instead
|
||||
/// the latest wanted state lives under a lock and one hop is scheduled at a
|
||||
/// time — whatever the hop finds when it runs is what gets drawn.
|
||||
public final class FakeCursor: Sendable {
|
||||
private struct Wanted: Sendable {
|
||||
var enabled = false
|
||||
var target: CGPoint?
|
||||
var hopScheduled = false
|
||||
}
|
||||
|
||||
private let wanted = OSAllocatedUnfairLock(initialState: Wanted())
|
||||
@MainActor private var overlay: CursorOverlay?
|
||||
|
||||
/// A driver that draws nothing until `setEnabled(true)`.
|
||||
public init() {}
|
||||
|
||||
/// Follows the `DrawMouseCursor` setting. Turning it off hides the overlay
|
||||
/// at once (`Setting.cs:97-101`, `frmMatrix.cs:1096-1101`).
|
||||
public func setEnabled(_ isOn: Bool) {
|
||||
update { $0.enabled = isOn }
|
||||
}
|
||||
|
||||
/// `ShowFakeMouseCursor(x, y)`: draw the arrow at this screen position, in
|
||||
/// CoreGraphics coordinates (top-left origin).
|
||||
public func show(at point: CGPoint) {
|
||||
update { $0.target = point }
|
||||
}
|
||||
|
||||
/// `ShowFakeMouseCursor(int.MinValue, int.MinValue)`: take it away.
|
||||
public func hide() {
|
||||
update { $0.target = nil }
|
||||
}
|
||||
|
||||
private func update(_ body: @Sendable (inout Wanted) -> Void) {
|
||||
let schedule = wanted.withLock { state -> Bool in
|
||||
body(&state)
|
||||
guard !state.hopScheduled else { return false }
|
||||
state.hopScheduled = true
|
||||
return true
|
||||
}
|
||||
guard schedule else { return }
|
||||
Task { @MainActor in self.draw() }
|
||||
}
|
||||
|
||||
@MainActor private func draw() {
|
||||
let state = wanted.withLock { state -> Wanted in
|
||||
state.hopScheduled = false
|
||||
return state
|
||||
}
|
||||
guard state.enabled, let target = state.target else {
|
||||
overlay?.hide()
|
||||
return
|
||||
}
|
||||
let overlay = overlay ?? CursorOverlay()
|
||||
self.overlay = overlay
|
||||
overlay.show(at: target)
|
||||
}
|
||||
}
|
||||
|
||||
/// The borderless, click-through window that draws the arrow.
|
||||
@MainActor public final class CursorOverlay {
|
||||
/// Windows offsets the form by one pixel so it does not sit exactly under
|
||||
/// the real pointer (`CustomCursor.cs:100-101`).
|
||||
static let offset = CGPoint(x: 1, y: 1)
|
||||
|
||||
private var window: NSWindow?
|
||||
private var isShowing = false
|
||||
|
||||
/// An overlay that has not been drawn yet. The window is built on the first
|
||||
/// `show(at:)`, so a Mac that is never controlled never makes one.
|
||||
public init() {}
|
||||
|
||||
/// Puts the arrow at `point`, in CoreGraphics screen coordinates.
|
||||
public func show(at point: CGPoint) {
|
||||
let window = window ?? CursorOverlay.makeWindow()
|
||||
self.window = window
|
||||
window.setFrameOrigin(CursorOverlay.frameOrigin(for: point, size: window.frame.size))
|
||||
if !isShowing {
|
||||
window.orderFrontRegardless()
|
||||
isShowing = true
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the arrow away. Idempotent.
|
||||
public func hide() {
|
||||
guard isShowing else { return }
|
||||
isShowing = false
|
||||
window?.orderOut(nil)
|
||||
}
|
||||
|
||||
/// CoreGraphics puts (0, 0) at the top-left of the main display and grows
|
||||
/// downwards; AppKit puts it at that display's bottom-left and grows
|
||||
/// upwards, and a window's origin is its *bottom* left.
|
||||
static func frameOrigin(for point: CGPoint, size: CGSize) -> CGPoint {
|
||||
let mainHeight = NSScreen.screens.first?.frame.height ?? 0
|
||||
let top = point.y + offset.y
|
||||
return CGPoint(x: point.x + offset.x, y: mainHeight - top - size.height)
|
||||
}
|
||||
|
||||
private static func makeWindow() -> NSWindow {
|
||||
let image = NSCursor.arrow.image
|
||||
let frame = NSRect(origin: .zero, size: image.size)
|
||||
let window = NSWindow(
|
||||
contentRect: frame, styleMask: .borderless, backing: .buffered, defer: false)
|
||||
window.isReleasedWhenClosed = false
|
||||
window.isOpaque = false
|
||||
window.backgroundColor = .clear
|
||||
window.hasShadow = false
|
||||
window.ignoresMouseEvents = true
|
||||
// Above ordinary windows and above a full-screen app's own space, and
|
||||
// present on every space without following the user between them.
|
||||
window.level = .screenSaver
|
||||
window.collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle]
|
||||
|
||||
let view = NSImageView(frame: frame)
|
||||
view.image = image
|
||||
view.imageScaling = .scaleNone
|
||||
window.contentView = view
|
||||
return window
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// "Is a full-screen app in front?" — the test behind
|
||||
// `DisableEasyMouseWhenForegroundWindowIsFullscreen`.
|
||||
//
|
||||
// Windows asks the shell: `IsEasyMouseBlockedByFullscreenWindow`
|
||||
// (`Common.cs:1602-1636`) calls `SHQueryUserNotificationState` and treats BUSY,
|
||||
// RUNNING_D3D_FULL_SCREEN and PRESENTATION_MODE as "full screen", after ruling
|
||||
// out the desktop and the shell window themselves; an app whose image name is in
|
||||
// `EasyMouseFullscreenSwitchBlockExcludedApps` is then forgiven
|
||||
// (`IsAppIgnoredByEasyMouseFullscreenCheck`, `:1567-1600`, matching both
|
||||
// `Path.GetFileName` and `Path.GetFileNameWithoutExtension`,
|
||||
// `StringComparer.OrdinalIgnoreCase`).
|
||||
//
|
||||
// macOS has no equivalent single question, so this asks the two halves directly:
|
||||
// `NSWorkspace` for which app is in front, and the window list for whether that
|
||||
// app has an on-screen window filling a whole display. Window *bounds* need no
|
||||
// Screen Recording grant; window *names* would, and are never read.
|
||||
//
|
||||
// The gate around the whole thing lives in the Engine (`IsEasyMouseSwitchAllowed`,
|
||||
// `Common.cs:1638-1650`): the check is skipped entirely when the setting is off
|
||||
// or when this Mac is not the one holding the pointer.
|
||||
|
||||
import AppKit
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
import MWBCore
|
||||
import os
|
||||
|
||||
/// Whether the app in front of this Mac is running full screen.
|
||||
public enum Fullscreen {
|
||||
/// How long one answer is reused. An edge storm arrives at the tap's rate;
|
||||
/// asking the window server per event would be a syscall per mouse move.
|
||||
public static let cacheInterval: TimeInterval = 0.25
|
||||
|
||||
/// How far a window's bounds may differ from a display's and still count as
|
||||
/// covering it, in points.
|
||||
static let tolerance: CGFloat = 1
|
||||
|
||||
private struct Cache: Sendable {
|
||||
var at: TimeInterval?
|
||||
var excluded: Set<String> = []
|
||||
var answer = false
|
||||
}
|
||||
|
||||
private static let cache = OSAllocatedUnfairLock(initialState: Cache())
|
||||
|
||||
/// `true` when the frontmost application is showing a window that covers a
|
||||
/// whole display and is not on the excluded list.
|
||||
///
|
||||
/// `displays` is `ScreenLayout.displays`; the caller passes it so nothing
|
||||
/// here re-reads the display list. The answer is cached for
|
||||
/// `cacheInterval`, keyed on the excluded set so that editing the list takes
|
||||
/// effect at once.
|
||||
public static func frontmostIsFullscreen(excluding excluded: Set<String>, displays: [CGRect])
|
||||
-> Bool
|
||||
{
|
||||
let now = EventTap.now()
|
||||
if let cached = cachedAnswer(excluded: excluded, now: now) { return cached }
|
||||
let answer = measure(excluding: excluded, displays: displays)
|
||||
cache.withLock { $0 = Cache(at: now, excluded: excluded, answer: answer) }
|
||||
return answer
|
||||
}
|
||||
|
||||
/// Forgets the cached answer. For a settings change that must be felt now.
|
||||
public static func invalidate() {
|
||||
cache.withLock { $0 = Cache() }
|
||||
}
|
||||
|
||||
private static func cachedAnswer(excluded: Set<String>, now: TimeInterval) -> Bool? {
|
||||
cache.withLock { cache in
|
||||
guard let at = cache.at, now - at < cacheInterval, cache.excluded == excluded
|
||||
else { return nil }
|
||||
return cache.answer
|
||||
}
|
||||
}
|
||||
|
||||
private static func measure(excluding excluded: Set<String>, displays: [CGRect]) -> Bool {
|
||||
guard let app = NSWorkspace.shared.frontmostApplication else { return false }
|
||||
// `Common.cs:1607-1612`: the desktop and the shell are never full screen.
|
||||
// Finder owns the desktop on a Mac, and it is in front whenever no app is.
|
||||
guard app.bundleIdentifier != "com.apple.finder" else { return false }
|
||||
guard !isExcluded(app, in: excluded) else { return false }
|
||||
return coversADisplay(pid: app.processIdentifier, displays: displays)
|
||||
}
|
||||
|
||||
/// The excluded-apps test, case-insensitively, against everything a user
|
||||
/// might reasonably type: the bundle identifier, the app's display name and
|
||||
/// its bundle's file name with and without the `.app` extension — the two
|
||||
/// spellings `Common.cs:1597-1599` accepts, in macOS terms.
|
||||
static func isExcluded(_ app: NSRunningApplication, in excluded: Set<String>) -> Bool {
|
||||
guard !excluded.isEmpty else { return false }
|
||||
let folded = Set(excluded.map { $0.lowercased() })
|
||||
var names: [String] = []
|
||||
if let identifier = app.bundleIdentifier { names.append(identifier) }
|
||||
if let name = app.localizedName { names.append(name) }
|
||||
if let url = app.bundleURL ?? app.executableURL {
|
||||
names.append(url.lastPathComponent)
|
||||
names.append(url.deletingPathExtension().lastPathComponent)
|
||||
}
|
||||
return names.contains { folded.contains($0.lowercased()) }
|
||||
}
|
||||
|
||||
/// Whether this process has an ordinary on-screen window the size of one
|
||||
/// whole display.
|
||||
///
|
||||
/// A macOS window in native full screen owns its Space and matches the
|
||||
/// display exactly; a merely zoomed window stops below the menu bar, so the
|
||||
/// equality is what separates the two. `kCGWindowLayer == 0` keeps status
|
||||
/// items, panels and wallpaper windows out of it.
|
||||
static func coversADisplay(pid: pid_t, displays: [CGRect]) -> Bool {
|
||||
guard !displays.isEmpty,
|
||||
let windows = CGWindowListCopyWindowInfo(
|
||||
[.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID)
|
||||
as? [[String: Any]]
|
||||
else { return false }
|
||||
|
||||
for window in windows {
|
||||
guard let owner = window[kCGWindowOwnerPID as String] as? pid_t, owner == pid,
|
||||
let layer = window[kCGWindowLayer as String] as? Int, layer == 0,
|
||||
let raw = window[kCGWindowBounds as String] as? NSDictionary,
|
||||
let bounds = CGRect(dictionaryRepresentation: raw as CFDictionary)
|
||||
else { continue }
|
||||
if displays.contains(where: { covers(bounds, $0) }) { return true }
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private static func covers(_ window: CGRect, _ display: CGRect) -> Bool {
|
||||
abs(window.origin.x - display.origin.x) <= tolerance
|
||||
&& abs(window.origin.y - display.origin.y) <= tolerance
|
||||
&& abs(window.size.width - display.size.width) <= tolerance
|
||||
&& abs(window.size.height - display.size.height) <= tolerance
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,13 @@ struct BehaviourPane: View {
|
||||
"Block mouse at screen corners to avoid accident machine-switch at screen "
|
||||
+ "corners",
|
||||
isOn: model.binding(\.blockMouseAtScreenCorners))
|
||||
SettingsToggle(
|
||||
"Draw mouse cursor",
|
||||
help:
|
||||
"Draw an arrow on this Mac where the remote pointer is while another "
|
||||
+ "machine is controlling it. macOS already moves the real pointer, so "
|
||||
+ "this is a second marker rather than a replacement.",
|
||||
isOn: model.binding(\.drawMouseCursor))
|
||||
}
|
||||
|
||||
SettingsSection("Easy Mouse") {
|
||||
@@ -99,13 +106,9 @@ struct BehaviourPane: View {
|
||||
|
||||
NotYetActive(
|
||||
text:
|
||||
"Clipboard sharing, file transfer and screen-saver blocking are saved here "
|
||||
+ "and sent to the other machines as settings, but this build does not act "
|
||||
+ "on them yet — they arrive with the clipboard and extras work.")
|
||||
NotYetActive(
|
||||
text:
|
||||
"Draw mouse cursor has no macOS equivalent and is not shown here; the value "
|
||||
+ "in settings.json is kept untouched for the Windows machines that read it.")
|
||||
"Draw mouse cursor is accepted by Windows peers as two settings; the second, "
|
||||
+ "DrawMouseEx, selects a Windows-only drawing path and is kept untouched "
|
||||
+ "in settings.json for the machines that read it.")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user