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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ tagged `vX.Y.Z`.

### Fixed

- **The pointer no longer gets stranded on the Edge.** The fence only ever acted on a pointer
that moved, so a cursor warped there by an application, or left behind by a display being
rearranged, simply stayed: the next click or scroll went to the dashboard instead of the window
you were looking at. The fence now also checks where the pointer really is, five times a
second, and pushes it back. That half works even without the Accessibility grant, since moving
the cursor needs no permission (@mcouzinet, #9).

- **The clipboard widget masks one-time codes.** A six-digit code copied from a text message or
an authenticator (`482913`, `482 913`, `4829-1375`) showed in full on the Edge and on a paired
iPad; any run of four to eight digits copied on its own is now shown as a secret, and still
Expand Down
2 changes: 1 addition & 1 deletion docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ the issue is public.
| "Touch: Input Monitoring missing — open Settings…" | Input Monitoring not granted to *this build* of the helper, or [never asked](#input-monitoring-was-never-asked) | Click the line: it opens Privacy & Security → Input Monitoring with the helper listed. Turn "Fremkit" (the app) or "Fremkit Helper" (a source install) on. Touch starts within seconds, or the line asks for a relaunch |
| "Touch: allowed — quit and reopen Fremkit…" | Input Monitoring is granted, but macOS applies it only to a relaunched process | Click the line: Fremkit quits (stopping its server as usual) and opens again |
| "Touch: taken by another driver" | Touchscreen Gestures, another driver or a `--probe` run holds the panel | Quit it, and unload its launchd agent so it does not come back |
| "Fence: Accessibility missing — open Settings…" (or the same on the Touch or Notifications line) | Accessibility not granted | Click the line: it opens Privacy & Security → Accessibility, with the helper listed. Turn "Fremkit" (the app) or "Fremkit Helper" (a source install) on; the line clears within seconds |
| "Fence: Accessibility missing — open Settings…" (or the same on the Touch or Notifications line) | Accessibility not granted | Click the line: it opens Privacy & Security → Accessibility, with the helper listed. Turn "Fremkit" (the app) or "Fremkit Helper" (a source install) on; the line clears within seconds Until then the fence still pushes a resting pointer off the Edge, but it cannot filter a mouse moving across it |
| "Fremkit can't be opened" / "is damaged and can't be opened" | The download was altered or is not the published one | Download the DMG again from the release page; see [Gatekeeper](#gatekeeper) |
| Input Monitoring and Accessibility asked again after moving to the app | The app's Developer ID signature is a new code identity | Expected once; see [The app asks for permissions again](#the-app-asks-for-permissions-again) |
| Permissions reset after every rebuild | Ad-hoc signature: a new code identity each build | Run `scripts/create-signing-identity.sh`, rebuild, grant once more |
Expand Down
21 changes: 21 additions & 0 deletions native/Sources/FremkitCore/FenceMath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,27 @@ public enum FenceMath {
return projectOutside(p, edge: edge, safe: safe)
}

/**
Where a resting cursor should be pushed back to, or nil when there is nothing to do.

The event tap only ever sees movement, and a cursor can arrive on the Edge without any: an
application warping it there (`CGWarpMouseCursorPosition` posts no event), a tap the system
disabled for a moment, a display rearranged under a pointer that was not moving. Once it is
there, a click or a scroll that moves nothing lands on the dashboard, and the user is left
pressing buttons they cannot see.

- Parameters:
- cursor: the pointer's real position, or nil when it could not be read.
- edge: the Edge display's bounds, or nil when there is no Edge display.
- driven: true while a touch gesture owns the cursor on purpose. The driver warps the
pointer onto the panel for the duration of a gesture and puts it back itself; pushing it
away in the meantime would fight the finger.
*/
public static func patrol(cursor: CGPoint?, edge: CGRect?, last: CGPoint?, safe: CGRect, driven: Bool) -> CGPoint? {
guard !driven, let cursor, let edge else { return nil }
return clamp(cursor, edge: edge, last: last, safe: safe)
}

/// Projects a point one point outside the nearest side of `edge`, or onto the centre of
/// `safe` when that projection would land on no display.
private static func projectOutside(_ p: CGPoint, edge: CGRect, safe: CGRect) -> CGPoint {
Expand Down
3 changes: 3 additions & 0 deletions native/Sources/FremkitHelper/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
self.driver = driver

let fence = MouseFence(edge: nil)
// The driver parks the cursor on the panel for the length of a gesture and restores it
// itself; the patrol stands back while that is happening.
fence.cursorIsDriven = { [poster] in poster.isDrivingCursor }
fence.onStateChange = { [weak self] state in
self?.menu?.update { $0.fence = state }
}
Expand Down
12 changes: 12 additions & 0 deletions native/Sources/FremkitHelper/EventPoster.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,18 @@ final class EventPoster: PointerPoster {
*/
private var gesture: UInt64 = 0

/**
True while a gesture owns the cursor: warped onto the panel and not yet put back.

The fence's patrol asks before pushing a resting pointer off the Edge, so that the finger on
the panel is not fought by the very thing that keeps the mouse away from it.
*/
var isDrivingCursor: Bool {
lock.lock()
defer { lock.unlock() }
return cursorHidden || pendingRestore != nil
}

init() {
source = CGEventSource(stateID: .hidSystemState)
source?.userData = Self.userData
Expand Down
51 changes: 50 additions & 1 deletion native/Sources/FremkitHelper/MouseFence.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,26 @@ final class MouseFence {
/// Delay between two attempts to create the tap while Accessibility is missing.
private static let retryInterval: TimeInterval = 5

/**
How often the pointer's real position is looked at, over and above the events the tap sees.

Short enough that a cursor that lands on the panel is gone before a hand reaches the mouse,
long enough to cost nothing: one `CGEvent(source: nil)` read, no event, no round trip.
*/
private static let patrolInterval: TimeInterval = 0.2

/// Bounds of the Edge display; the fence does nothing while this is nil.
var edge: CGRect?

/// Called on the main thread whenever the effective state changes.
var onStateChange: ((FenceState) -> Void)?

/// Asked before the patrol pushes: true while a touch gesture owns the cursor on purpose.
var cursorIsDriven: () -> Bool = { false }

private var tap: CFMachPort?
private var source: CFRunLoopSource?
private var patrolTimer: Timer?
/// Latest pointer position seen outside `edge`, where the cursor is pushed back to.
private var last: CGPoint?
/// True between `start()` and `stop()`, even while the tap itself is missing.
Expand Down Expand Up @@ -62,6 +74,9 @@ final class MouseFence {
@discardableResult
func start() -> Bool {
wantsRunning = true
// Before the tap, and whatever becomes of it: warping the cursor needs no permission, so
// the patrol is the half of the fence that works on a Mac that granted nothing.
startPatrol()
guard !isRunning else { return true }

if createTap() {
Expand All @@ -70,7 +85,8 @@ final class MouseFence {
return true
}

FileHandle.standardError.write(Data("fremkit: mouse fence needs Accessibility access\n".utf8))
FileHandle.standardError.write(Data(
"fremkit: mouse fence needs Accessibility access; until then the patrol pushes the pointer back, but a move across the panel is not filtered\n".utf8))
state = .missingPermission
startRetrying()
return false
Expand All @@ -79,6 +95,7 @@ final class MouseFence {
func stop() {
wantsRunning = false
stopRetrying()
stopPatrol()

guard isRunning else {
state = .off
Expand Down Expand Up @@ -157,6 +174,38 @@ final class MouseFence {
}
}

// MARK: - Patrol

private func startPatrol() {
guard patrolTimer == nil else { return }
// `.common` so the patrol keeps ticking while a menu is being tracked, which is exactly
// when a stray pointer is most in the way.
let timer = Timer(timeInterval: Self.patrolInterval, repeats: true) { [weak self] _ in
self?.patrolTick()
}
RunLoop.main.add(timer, forMode: .common)
patrolTimer = timer
}

private func stopPatrol() {
patrolTimer?.invalidate()
patrolTimer = nil
}

/// One look at where the pointer actually is, and a push back when it is on the Edge.
private func patrolTick() {
guard wantsRunning else { return }
// The main display is the one rectangle guaranteed to exist and to hold a cursor.
let safe = CGDisplayBounds(CGMainDisplayID())
guard let clamped = FenceMath.patrol(cursor: CGEvent(source: nil)?.location,
edge: edge,
last: last,
safe: safe,
driven: cursorIsDriven()) else { return }
last = clamped
warpCursor(to: clamped)
}

// MARK: - Tap callback

private func handle(type: CGEventType, event: CGEvent) -> Unmanaged<CGEvent>? {
Expand Down
26 changes: 26 additions & 0 deletions native/Tests/FremkitCoreTests/FenceMathTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,30 @@ final class FenceMathTests: XCTestCase {
XCTAssertEqual(FenceMath.clamp(CGPoint(x: 1950, y: -1309), edge: edge, last: nil, safe: around),
CGPoint(x: 1949, y: -1309))
}

// MARK: - The patrol, which looks at a pointer that is not moving

func testPatrolPushesAPointerThatIsSimplyResting() {
// No event brought it here: an application warped it, or a display moved under it.
let last = CGPoint(x: 800, y: 400)
XCTAssertEqual(FenceMath.patrol(cursor: CGPoint(x: 3000, y: -900), edge: edge,
last: last, safe: primary, driven: false), last)
}

func testPatrolLeavesAPointerOnAnotherDisplayAlone() {
XCTAssertNil(FenceMath.patrol(cursor: CGPoint(x: 100, y: 100), edge: edge,
last: nil, safe: primary, driven: false))
}

func testPatrolStandsBackWhileAGestureOwnsTheCursor() {
// The driver puts the cursor on the panel on purpose and restores it afterwards.
XCTAssertNil(FenceMath.patrol(cursor: CGPoint(x: 3000, y: -900), edge: edge,
last: nil, safe: primary, driven: true))
}

func testPatrolDoesNothingWithoutAnEdgeOrAPosition() {
XCTAssertNil(FenceMath.patrol(cursor: CGPoint(x: 3000, y: -900), edge: nil,
last: nil, safe: primary, driven: false))
XCTAssertNil(FenceMath.patrol(cursor: nil, edge: edge, last: nil, safe: primary, driven: false))
}
}
4 changes: 4 additions & 0 deletions native/Tests/Shim/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ let suites: [(String, () -> XCTestCase, [TestMethod])] = [
("testProjectionOnNearestEdgeWithoutLastPosition", { ($0 as! FenceMathTests).testProjectionOnNearestEdgeWithoutLastPosition() }),
("testFallbackLandsInsideTheSafeRectangleWithTheRealLayout", { ($0 as! FenceMathTests).testFallbackLandsInsideTheSafeRectangleWithTheRealLayout() }),
("testCornerTieBreakPrefersTheLeftSide", { ($0 as! FenceMathTests).testCornerTieBreakPrefersTheLeftSide() }),
("testPatrolPushesAPointerThatIsSimplyResting", { ($0 as! FenceMathTests).testPatrolPushesAPointerThatIsSimplyResting() }),
("testPatrolLeavesAPointerOnAnotherDisplayAlone", { ($0 as! FenceMathTests).testPatrolLeavesAPointerOnAnotherDisplayAlone() }),
("testPatrolStandsBackWhileAGestureOwnsTheCursor", { ($0 as! FenceMathTests).testPatrolStandsBackWhileAGestureOwnsTheCursor() }),
("testPatrolDoesNothingWithoutAnEdgeOrAPosition", { ($0 as! FenceMathTests).testPatrolDoesNothingWithoutAnEdgeOrAPosition() }),
]),
("HelperConfigTests", { HelperConfigTests() }, [
("testDefaults", { ($0 as! HelperConfigTests).testDefaults() }),
Expand Down
Loading