How the WindowLayout Service Enables Window Snapping: A Deep Dive into vorssaint-utils

The WindowLayout service enables window snapping by intercepting low-level pointer events through a dedicated CGEvent tap, tracking drag gestures against screen edges, and resolving them into concrete snap actions via the Accessibility API.

The vorssaint-utils repository provides a comprehensive macOS window management utility where the WindowLayout service handles window snapping functionality. This Swift-based implementation listens for mouse events at the system level to detect intentional edge-drag gestures before repositioning windows.

Event Tap Architecture for Low-Level Input Capture

The foundation of window snapping relies on capturing input events before they reach foreground applications. The service establishes a system-wide event monitoring infrastructure to detect when users initiate drag operations near screen boundaries.

Creating the CFMachPort and Run Loop Source

In Sources/Vorssaint/Services/WindowLayout/WindowLayoutService.swift, the service creates a dedicated CFMachPort (edgeSnapTap) and corresponding CFRunLoopSource (edgeSnapRunLoopSource) at lines 52-53. These taps receive every mouse-move and mouse-down event while the service remains active.

// Initiate edge-snap tap (simplified from WindowLayoutService.swift)
edgeSnapTap = CGEvent.tapCreate(
    .cghidEventTap,
    .headInsertEventTap,
    .defaultTap,
    CGEventMaskBit(.mouseMoved) | CGEventMaskBit(.leftMouseDown),
    edgeSnapCallback,
    nil
)

edgeSnapRunLoopSource = CFMachPortCreateRunLoopSource(
    kCFAllocatorDefault,
    edgeSnapTap,
    0
)

CFRunLoopAddSource(
    CFRunLoopGetCurrent(),
    edgeSnapRunLoopSource,
    .commonModes
)

Filtering Mouse Events

The callback function processes raw event data to distinguish between normal pointer movement and potential snap gestures. When the user presses the mouse button, the initial location is stored in edgeSnapPressOrigin (line 56), marking the start of a possible snap sequence. On the first press, the service queries the Window Server for a WindowServerWindowCandidate that matches the pointer location (edgeSnapPressCandidate) at line 57.

Gesture Detection and Drag Tracking

Once the event tap infrastructure is active, the service implements state management to track the lifecycle of a drag operation from initiation to potential snap resolution.

Tracking the Press Origin and Window Candidate

The service maintains several critical state variables to manage the snapping lifecycle. When a mouse-down event occurs, the system captures the initial coordinates in edgeSnapPressOrigin and identifies the frontmost window under the cursor as a WindowServerWindowCandidate. This candidate represents the window that may be snapped if the drag meets specific criteria.

Debouncing with Sequence Suppression Flags

To prevent false positives, the service employs a set of flags (edgeSnapSequenceSuppressed, edgeSnapResolveAttempts, edgeSnapLastResolveAt) at lines 58-60 to debounce rapid or noisy inputs. These mechanisms ensure that snapping only occurs after a deliberate edge-drag gesture, avoiding accidental window moves when users perform quick, unrelated mouse movements.

// High-level callback structure (conceptual)
func edgeSnapCallback(
    proxy: CGEventTapProxy,
    type: CGEventType,
    event: CGEvent,
    refcon: UnsafeMutableRawPointer?
) -> Unmanaged<CGEvent>? {
    // Store press origin, update drag, resolve snap target...
    return Unmanaged.passRetained(event)
}

Resolving Snap Targets and Visual Feedback

As the pointer moves toward screen edges, the service accumulates movement data and calculates potential snap zones.

Building the WindowEdgeSnapDrag Object

A WindowEdgeSnapDrag object (edgeSnapDrag) accumulates the movement at line 61. This object tracks the displacement between the original press origin and the current pointer location, calculating when the gesture crosses the threshold required to trigger a snap action. When the drag reaches a screen edge and the window has followed the pointer far enough, the service resolves the gesture into a concrete WindowEdgeSnapTarget.

// Example: Resolving snap targets during drag operations
if let target = resolveSnapTarget(drag) {
    edgeSnapPreviewGeneration += 1
    // Target identifies specific snap zones (leftHalf, rightHalf, maximize)
}

Displaying the Preview Panel

Before committing the snap, a lightweight NSPanel (edgeSnapPreviewPanel) shown at lines 63-64 provides visual feedback indicating where the window will land. The preview regenerates only when the generation counter changes, preventing stale UI artifacts during rapid pointer movements.

// Display preview when snap target is identified
if let target = resolveSnapTarget(drag) {
    edgeSnapPreviewGeneration += 1
    edgeSnapPreviewPanel?.orderFront(nil)   // display preview
    // Apply the snap once the user releases the mouse
}

Executing Snap Actions via Accessibility APIs

Once the drag gesture resolves to a valid target and the user releases the mouse button, the service executes the snap action. The service calls the appropriate WindowLayoutAction (e.g., .leftHalf, .rightHalf, .maximize, etc.), which ultimately uses macOS Accessibility APIs to reposition and resize the window.

The helper utilities in Sources/Vorssaint/Services/WindowLayout/WindowLayoutSupport.swift handle geometry calculations and tolerance thresholds used by the snapping algorithm. User preferences controlling which snap zones are active reside in Sources/Vorssaint/Core/Defaults.swift, allowing the service to disable edge-snap taps entirely when all zones are turned off.

Summary

  • The service creates a CGEvent tap (edgeSnapTap) and CFRunLoopSource (edgeSnapRunLoopSource) to intercept mouse events at the system level before they reach applications.
  • Press origins are stored in edgeSnapPressOrigin and matched against WindowServerWindowCandidate instances to identify which window should respond to the snap gesture.
  • Debouncing flags (edgeSnapSequenceSuppressed, edgeSnapResolveAttempts, edgeSnapLastResolveAt) prevent accidental snaps during rapid or noisy input sequences.
  • Drag movements accumulate in a WindowEdgeSnapDrag object (edgeSnapDrag) until reaching a valid WindowEdgeSnapTarget at screen edges.
  • An NSPanel (edgeSnapPreviewPanel) provides visual feedback indicating the snap destination before final execution.
  • The service ultimately executes WindowLayoutAction commands through macOS Accessibility APIs to resize and reposition windows, with geometry calculations handled by WindowLayoutSupport.swift.

Frequently Asked Questions

What prevents accidental window snapping when using the WindowLayout service?

The service implements multiple safeguards against accidental triggers. First, it stores the initial press origin in edgeSnapPressOrigin and requires the window to visibly follow the pointer toward a screen edge before activation. Second, debouncing flags (edgeSnapSequenceSuppressed, edgeSnapResolveAttempts, edgeSnapLastResolveAt) filter out rapid, noisy inputs. Finally, when all snap zones are disabled in Defaults.swift, the service never activates the edge-snap tap, preventing any interference with normal window management.

How does the WindowLayout service identify which window to snap?

When the initial mouse-down event occurs, the service queries the Window Server for a WindowServerWindowCandidate that matches the pointer location, storing this reference in edgeSnapPressCandidate (line 57). This candidate represents the topmost window under the cursor at the start of the drag operation. The service then tracks this specific window throughout the drag sequence using the WindowEdgeSnapDrag object, ensuring that only the originally selected window responds to the snap gesture.

What role does the edgeSnapPreviewPanel play in the snapping workflow?

The edgeSnapPreviewPanel (lines 63-64) is an NSPanel instance that displays visual feedback before committing a snap action. When the drag resolves to a valid WindowEdgeSnapTarget, the service increments edgeSnapPreviewGeneration and orders the panel to the front, showing a preview of where the window will be positioned. This gives users the opportunity to abort the snap by moving the cursor away from the edge before releasing the mouse button.

Which macOS APIs does the WindowLayout service use to move windows?

The service utilizes Core Graphics (CGEvent.tapCreate) to intercept low-level input events and Core Foundation (CFMachPortCreateRunLoopSource, CFRunLoopAddSource) to integrate the event tap into the run loop. For the actual window manipulation, it employs macOS Accessibility APIs to reposition and resize windows when executing WindowLayoutAction commands. The test suite in Tests/MetricsTests.swift (lines 5824-5854) validates these snap actions against expected window geometries.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →