diff --git a/Sources/MWBCore/Settings.swift b/Sources/MWBCore/Settings.swift index 096ad47..cd770c5 100644 --- a/Sources/MWBCore/Settings.swift +++ b/Sources/MWBCore/Settings.swift @@ -195,6 +195,14 @@ public struct Settings: Sendable, Equatable, Codable { set { setBoxed("HideMouseAtScreenEdge", .bool(newValue)) } } + /// `DrawMouseCursor`: draw an arrow where the remote pointer is while a peer + /// is driving this Mac (`CustomCursor.cs:68-146`). `DrawMouseEx`, which + /// selects the richer Windows drawing path, is accepted and ignored. + public var drawMouseCursor: Bool { + get { bool("DrawMouseCursor") } + set { setBoxed("DrawMouseCursor", .bool(newValue)) } + } + /// `ValidateRemoteMachineIP`: only accept peers whose address resolves back /// to their name. public var validateRemoteMachineIP: Bool { diff --git a/Sources/MWBMac/Awake.swift b/Sources/MWBMac/Awake.swift new file mode 100644 index 0000000..9dad8aa --- /dev/null +++ b/Sources/MWBMac/Awake.swift @@ -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 + + /// 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 + } +} diff --git a/Sources/MWBMac/FakeCursor.swift b/Sources/MWBMac/FakeCursor.swift new file mode 100644 index 0000000..2e27a21 --- /dev/null +++ b/Sources/MWBMac/FakeCursor.swift @@ -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 + } +} diff --git a/Sources/MWBMac/Fullscreen.swift b/Sources/MWBMac/Fullscreen.swift new file mode 100644 index 0000000..e97c143 --- /dev/null +++ b/Sources/MWBMac/Fullscreen.swift @@ -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 = [] + 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, 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, 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, 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) -> 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 + } +} diff --git a/Sources/MWBMac/SettingsWindow/BehaviourPane.swift b/Sources/MWBMac/SettingsWindow/BehaviourPane.swift index 5c3781e..48f786e 100644 --- a/Sources/MWBMac/SettingsWindow/BehaviourPane.swift +++ b/Sources/MWBMac/SettingsWindow/BehaviourPane.swift @@ -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.") } } } diff --git a/Sources/mwb/ClipboardBridge.swift b/Sources/mwb/ClipboardBridge.swift index 1a8d9d5..3678e2d 100644 --- a/Sources/mwb/ClipboardBridge.swift +++ b/Sources/mwb/ClipboardBridge.swift @@ -460,6 +460,7 @@ extension Engine { /// A bulk transfer did not. func clipboardFailed(_ reason: String) { Log.engine.info("clipboard: \(reason)") + Task { @MainActor in TransferNotices.post(reason) } // the extras lane } // MARK: - Performing the bridge's actions @@ -481,6 +482,7 @@ extension Engine { commitReceivedFile(staged: staged, name: name) case .note(let text): Log.engine.info("clipboard: \(text)") + Task { @MainActor in TransferNotices.post(text) } // the extras lane } } } @@ -546,6 +548,8 @@ extension Engine { let file = try ReceivedFile.commit(staged: staged, toFileNamed: name, in: directory) clipboard?.announce(file) Log.engine.info("clipboard: received \(name)") + // `Clipboard.cs:869-881`: " from is in Clipboard." + Task { @MainActor in TransferNotices.post("Received \(name).") } // the extras lane Task { @MainActor in ReceivedFile.reveal(file) } } catch { ReceivedFile.discard(staged) diff --git a/Sources/mwb/Engine.swift b/Sources/mwb/Engine.swift index 225bae9..128d657 100644 --- a/Sources/mwb/Engine.swift +++ b/Sources/mwb/Engine.swift @@ -159,6 +159,12 @@ public actor Engine { let screens: Screens let cursor = Cursor() let injector: Injector + /// The receiving half of `BlockScreenSaverOnOtherMachines`: every `Awake` + /// packet renews a power assertion (the extras lane, `Awake.swift`). + let displayAwake = DisplayAwake() + /// `DrawMouseCursor`: the arrow drawn where the remote pointer is while a + /// peer drives this Mac (the extras lane, `FakeCursor.swift`). + let fakeCursor = FakeCursor() var tap: EventTap? var channel: ControlChannel? /// Clipboard sharing: the bulk channel, the pasteboard watcher and the @@ -283,6 +289,10 @@ public actor Engine { pump = nil injector.releaseAll() cursor.restoreEverything() + // Nothing may outlive the process: an assertion we still hold would keep + // the display awake, and the overlay would be the last thing on screen. + displayAwake.release() + fakeCursor.hide() persistOnExit() Log.app.info("engine stopped") } @@ -438,7 +448,12 @@ public actor Engine { // `Event.RealInputEventCount++` (`Event.cs:51-55`): the sessions only // ask whether it moved since their own previous beat, so one bump per // drain that saw input says exactly what `SendAwakeBeat` needs. - if sawRealInput { channel?.noteUserActivity() } + guard sawRealInput else { return } + channel?.noteUserActivity() + // `InputHook.cs:256-264`: real input with the pointer on this Mac — + // `local`, i.e. the destination is us or ALL — takes the drawn cursor + // away. `hide()` is a no-op when it is already gone. + if !switcher.destinationIsRemote { fakeCursor.hide() } } private func sendKey(vk: Int32, flags: Int32) { @@ -469,10 +484,33 @@ public actor Engine { private func considerCrossing(at point: CGPoint, now: TimeInterval) { guard let jump = switcher.crossing(at: point, now: now) else { return } + // `Event.cs:79`: the fullscreen rule is asked *after* the edge geometry + // says a switch would happen, so a blocked switch still updates + // `LastX`/`LastY` inside `crossing`, exactly as Windows does. + guard easyMouseSwitchAllowed() else { + Log.engine.debug("edge \(jump.direction) blocked: full-screen app in front") + return + } Log.engine.debug("edge \(jump.direction) → \(jump.targetName)") perform(switcher.prepareToSwitch(to: jump.targetID, landing: jump.landing, now: now)) } + /// `Common.IsEasyMouseSwitchAllowed` (`Common.cs:1638-1650`). + /// + /// Two early outs before anything looks at a window: the setting is off, or + /// this Mac is not the one holding the pointer — "never prevent a switch if + /// we are not moving out of the host machine" (`:1646`). That second test is + /// also what keeps the check off the relative-mode path, where the machine + /// doing the edge detection is the one being controlled + /// (`Receiver.cs:156-170`, which never consults it). + private func easyMouseSwitchAllowed() -> Bool { + guard settings.disableEasyMouseWhenFullscreen else { return true } + guard switcher.desMachineID == switcher.localID else { return true } + return !Fullscreen.frontmostIsFullscreen( + excluding: Set(settings.easyMouseFullscreenExcludedApps), + displays: screens.layout.displays) + } + // MARK: - Received packets (`Receiver.ProcessPackage`, `Receiver.cs:86-390`) /// The port of `ProcessPackage`'s switch. Long on purpose (CLAUDE.md, file @@ -494,11 +532,22 @@ public actor Engine { guard forUs else { break } takeControlBack() // Receiver.cs:122-125 injector.inject(packet, layout: screens.layout) + // `Receiver.cs:186-188`: the pointer has just been moved, so this is + // where Windows records `LastX`/`LastY` and draws the fake cursor. + fakeCursor.show(at: pointerPosition()) reportEdgeToController(packet, now: now) case .nextMachine: // `Receiver.cs:192-198`: the machine we are controlling hit its own // edge in relative mode and is telling us where to go next. + // + // Windows tests `Event.IsSwitchingByMouseEnabled()` (`Event.cs:152-155`), + // which is `EasyMouse == Enable` **or** the Ctrl/Shift Easy-Mouse key + // being held. That second half lives in the tap + // (`EventTap.easyMouseKeyDown`) and is not published, so with Easy + // Mouse set to Ctrl or Shift a relative-mode `NextMachine` is ignored + // here where Windows would switch. Filed in the extras README as a + // Handshake request to input-capture. guard settings.easyMouse == .enable else { break } let data = packet.mouse perform( @@ -506,7 +555,16 @@ public actor Engine { to: UInt32(bitPattern: data.wheelDelta), landing: UniversalPoint(x: data.x, y: data.y), now: now)) - case .heartbeat, .heartbeatEx, .awake, .hello: + case .awake: + // `Receiver.cs:244-249`: learn the sender, then + // `Common.HumanBeingDetected()` (`Common.cs:561-572`) — a human is + // busy on that machine, so this one's display stays on. The sender's + // `BlockScreenSaverOnOtherMachines` decides whether `Awake` is sent + // at all (`Common.cs:545-559`); the receiver always honours it. + perform(switcher.learn(from: packet, now: now)) + displayAwake.renew() + + case .heartbeat, .heartbeatEx, .hello: // `AddToMachinePool` (`Receiver.cs:207-262`). `Heartbeat_ex` and its // two follow-ups are the Windows key-propagation handshake, which is // out of scope (README D6); the packet still identifies its sender, diff --git a/Sources/mwb/EngineActions.swift b/Sources/mwb/EngineActions.swift index 4ea4288..ed3482b 100644 --- a/Sources/mwb/EngineActions.swift +++ b/Sources/mwb/EngineActions.swift @@ -63,6 +63,10 @@ extension Engine { hideMouse: settings.hideMouseAtScreenEdge, layout: screens.layout, destinationIsRemote: destinationIsRemote, byHideMouseMessage: byHideMouseMessage) + // `Common.HideMouseCursor` ends with `ShowFakeMouseCursor(int.MinValue, + // int.MinValue)` (`Common.cs:1495`): control moved, so the arrow the + // last remote move drew is stale either way. + fakeCursor.hide() case .moveCursor(let landing): noteCursorLanding(landing) @@ -229,6 +233,11 @@ extension Engine { moveRelatively: settings.moveMouseRelatively) tap?.reconfigure(captureConfig()) injector.reconfigure(InjectorConfig(lockMachine: settings.lockMachineShortcut)) + // `Setting.cs:97-101`: turning `DrawMouseCursor` off hides the drawn + // cursor there and then. The excluded-apps list is part of the cached + // fullscreen answer, so an edit to it must not wait 250 ms. + fakeCursor.setEnabled(settings.drawMouseCursor) + Fullscreen.invalidate() applyClipboardConfiguration() // the clipboard lane syncRouting() } diff --git a/Sources/mwb/UIBridge.swift b/Sources/mwb/UIBridge.swift index 41745e5..9504faf 100644 --- a/Sources/mwb/UIBridge.swift +++ b/Sources/mwb/UIBridge.swift @@ -16,6 +16,35 @@ import MWBCore import MWBMac import MWBNet +/// Clipboard and file transfers, shown to the user. +/// +/// Windows pops one tray balloon per transfer — "Receiving X from Y…" +/// (`Clipboard.cs:610-618`), "X from Y is in Clipboard." (`:869-881`) and the +/// failure message (`:916`) — each passing `Setting.Values.ShowClipNetStatus` to +/// `ShowToolTip`, so the setting is the gate. `Notifier` already holds that gate +/// (`enabledChanged(_:)` follows +/// `ShowClipboardAndNetworkStatusMessages`), so all that was missing was the +/// wire: the clipboard lane's `ClipboardAction.note` carries the text and the +/// Engine only logged it. +/// +/// A static rendezvous rather than a property on the Engine because the Engine +/// is an actor, the `Notifier` is `@MainActor`, and there is exactly one of each +/// for the life of the process. +@MainActor enum TransferNotices { + private static weak var notifier: Notifier? + + /// UIBridge hands its notifier over when the menu bar appears, and takes it + /// back on the way out. + static func install(_ notifier: Notifier?) { + TransferNotices.notifier = notifier + } + + /// Shows one transfer message, if the user asked for them. + static func post(_ text: String) { + notifier?.post(title: "Mouse Without Borders", body: text) + } +} + /// Owns the menu bar, the settings window and the notifier, and keeps all three /// in step with the Engine. @MainActor final class UIBridge { @@ -43,11 +72,13 @@ import MWBNet /// the first snapshot has something to draw into. func start() { statusItem = StatusItemController(actions: makeActions()) + TransferNotices.install(notifier) render(EngineSnapshot()) } /// Takes the item away again, on the way out. func stop() { + TransferNotices.install(nil) statusItem?.remove() statusItem = nil }