← back to djson9__focus-guard

Function bodies 8 total

All specs Real LLM only Function bodies
WindowPinner class · swift · L19-L79 (61 LOC)
FocusGuard.swift
class WindowPinner {
    static let shared = WindowPinner()
    private let cid = CGSMainConnectionID()
    private var pinnedWindows: [(windowID: UInt32, originalLevel: Int32)] = []

    /// Pin all windows of an app to floating level
    func pin(pid: pid_t) {
        unpin() // restore any previously pinned windows

        let windowIDs = getWindowIDs(for: pid)
        let floatingLevel = Int32(CGWindowLevelForKey(.floatingWindow))

        for wid in windowIDs {
            var originalLevel: Int32 = 0
            let getErr = CGSGetWindowLevel(cid, wid, &originalLevel)
            if getErr != .success {
                fgLog("WindowPinner: failed to get level for window \(wid): \(getErr.rawValue)")
                continue
            }

            let setErr = CGSSetWindowLevel(cid, wid, floatingLevel)
            if setErr == .success {
                pinnedWindows.append((windowID: wid, originalLevel: originalLevel))
                fgLog("WindowPinner: pinned window \(wid)
HotkeyManager class · swift · L83-L119 (37 LOC)
FocusGuard.swift
class HotkeyManager {
    static let shared = HotkeyManager()

    private var hotKeyRef: EventHotKeyRef?
    private var eventHandlerRef: EventHandlerRef?
    private var handler: (() -> Void)?

    private static let signatureRaw: UInt32 = {
        let chars: [UInt8] = [0x46, 0x47, 0x52, 0x44] // "FGRD"
        return UInt32(chars[0]) << 24 | UInt32(chars[1]) << 16 | UInt32(chars[2]) << 8 | UInt32(chars[3])
    }()

    func register(keyCode: UInt32, modifiers: UInt32, handler: @escaping () -> Void) {
        self.handler = handler
        unregister()

        var eventType = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
        InstallEventHandler(GetApplicationEventTarget(), { (_, event, _) -> OSStatus in
            HotkeyManager.shared.handler?()
            return noErr
        }, 1, &eventType, nil, &eventHandlerRef)

        let hotKeyID = EventHotKeyID(signature: HotkeyManager.signatureRaw, id: 1)
        RegisterEventHotKey(
HotkeyRecorderView class · swift · L123-L205 (83 LOC)
FocusGuard.swift
class HotkeyRecorderView: NSView {
    var onHotkeyRecorded: ((UInt32, UInt32, String) -> Void)?
    private var isRecording = false
    private var displayString: String = ""
    private var monitor: Any?

    override var acceptsFirstResponder: Bool { true }

    init(frame: NSRect, currentDisplay: String) {
        self.displayString = currentDisplay.isEmpty ? "Click to record" : currentDisplay
        super.init(frame: frame)
    }

    required init?(coder: NSCoder) { fatalError() }

    override func draw(_ dirtyRect: NSRect) {
        let bg: NSColor = isRecording ? .controlAccentColor.withAlphaComponent(0.15) : .controlBackgroundColor
        bg.setFill()
        let path = NSBezierPath(roundedRect: bounds.insetBy(dx: 1, dy: 1), xRadius: 6, yRadius: 6)
        path.fill()

        NSColor.separatorColor.setStroke()
        path.lineWidth = isRecording ? 2 : 1
        if isRecording { NSColor.controlAccentColor.setStroke() }
        path.stroke()

        let text = isRecording 
PulseOverlay class · swift · L221-L286 (66 LOC)
FocusGuard.swift
class PulseOverlay {
    static let shared = PulseOverlay()
    private var windows: [NSWindow] = []
    private var fadeTimer: Timer?
    private var initialized = false

    /// Pre-create overlay windows so flash() never allocates during focus events
    func setup() {
        guard !initialized else { return }
        initialized = true
        rebuildWindows()

        // Rebuild when screens change (monitor plugged/unplugged)
        NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in
            self?.rebuildWindows()
        }
    }

    private func rebuildWindows() {
        windows.forEach { $0.orderOut(nil) }
        windows.removeAll()

        for screen in NSScreen.screens {
            let w = NSWindow(
                contentRect: screen.frame,
                styleMask: .borderless,
                backing: .buffered,
                defer: false
            )
            w.
PulseBorderView class · swift · L288-L298 (11 LOC)
FocusGuard.swift
class PulseBorderView: NSView {
    override func draw(_ dirtyRect: NSRect) {
        let thickness: CGFloat = 4
        let color = NSColor.systemBlue.withAlphaComponent(0.8)
        color.setStroke()

        let path = NSBezierPath(rect: bounds.insetBy(dx: thickness / 2, dy: thickness / 2))
        path.lineWidth = thickness
        path.stroke()
    }
}
StateManager class · swift · L302-L347 (46 LOC)
FocusGuard.swift
class StateManager {
    static let shared = StateManager()
    private let dir: String

    init() {
        dir = NSHomeDirectory() + "/.config/focus-guard"
        try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
    }

    func writeState(isGuarding: Bool, lastStolenBy: String?) {
        var lines = ["guarding=\(isGuarding)"]
        if let stolen = lastStolenBy {
            lines.append("last_blocked=\(stolen)")
        }
        lines.append("pid=\(ProcessInfo.processInfo.processIdentifier)")
        lines.append("updated_at=\(ISO8601DateFormatter().string(from: Date()))")
        try? lines.joined(separator: "\n").write(toFile: dir + "/.state", atomically: true, encoding: .utf8)
    }

    func writeActiveApplication(bundleID: String?, name: String?) {
        if let bundleID = bundleID, let name = name {
            let lines = [
                "bundle_id=\(bundleID)",
                "name=\(name)",
                "guarded_since=\(IS
SettingsWindowController class · swift · L351-L432 (82 LOC)
FocusGuard.swift
class SettingsWindowController: NSObject {
    private var window: NSWindow?

    func show() {
        if let w = window {
            w.makeKeyAndOrderFront(nil)
            NSApp.activate(ignoringOtherApps: true)
            return
        }

        let w = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 380, height: 160),
            styleMask: [.titled, .closable],
            backing: .buffered,
            defer: false
        )
        w.title = "FocusGuard Settings"
        w.center()
        w.isReleasedWhenClosed = false

        let contentView = NSView(frame: w.contentView!.bounds)
        contentView.autoresizingMask = [.width, .height]

        // Label
        let label = NSTextField(labelWithString: "Toggle Hotkey:")
        label.frame = NSRect(x: 20, y: 100, width: 120, height: 20)
        label.font = .systemFont(ofSize: 13, weight: .medium)
        contentView.addSubview(label)

        // Hotkey recorder
        let currentDisplay = UserDefaults.stan
Repobility's GitHub App fixes findings like these · https://github.com/apps/repobility-bot
FocusGuard class · swift · L441-L722 (282 LOC)
FocusGuard.swift
class FocusGuard: NSObject {
    private var protectedBundleID: String?
    private var protectedApp: NSRunningApplication?
    private var isGuarding = false
    private var statusItem: NSStatusItem?
    private var lastStolenBy: String?
    private let settingsController = SettingsWindowController()

    override init() {
        super.init()
        setupStatusItem()
        setupNotifications()
        registerSavedHotkey()
        syncStateFiles()

        NotificationCenter.default.addObserver(
            self,
            selector: #selector(hotkeySettingsChanged),
            name: .hotkeyChanged,
            object: nil
        )

        // Listen for CLI commands from other instances
        DistributedNotificationCenter.default().addObserver(
            self,
            selector: #selector(handleCommand(_:)),
            name: .fgCommand,
            object: nil
        )
    }

    @objc private func handleCommand(_ notification: Notification) {
        guard let cmd =