Blog

Building a clipboard manager for macOS: polling, passwords, and the notch

I recently shipped Clipket, a clipboard history app for macOS that opens from the MacBook notch. Clipboard managers look simple, but a few parts of the macOS API surprised me. Here's what I learned, with code.

1. There is no "clipboard changed" notification

On iOS you get UIPasteboard.changedNotification. On macOS there's nothing equivalent. The standard approach is to poll changeCount:

let pasteboard = NSPasteboard.general
var lastChangeCount = pasteboard.changeCount

let timer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true) { _ in
    guard pasteboard.changeCount != lastChangeCount else { return }
    lastChangeCount = pasteboard.changeCount
    handleNewClip(from: pasteboard)
}

Reading changeCount is cheap, so polling is fine. I settled on ~0.3s: faster wastes CPU, slower feels laggy when you copy and immediately open the history. Pause polling when the screen is locked or the Mac sleeps.

2. Never save passwords: respect concealed types

Password managers mark their copies so clipboard tools know to ignore them. The convention, documented at nspasteboard.org, uses these types:

let skippedTypes: Set<NSPasteboard.PasteboardType> = [
    .init("org.nspasteboard.ConcealedType"),
    .init("org.nspasteboard.TransientType"),
    .init("org.nspasteboard.AutoGeneratedType"),
]

func shouldSkip(_ pasteboard: NSPasteboard) -> Bool {
    guard let types = pasteboard.types else { return false }
    return !skippedTypes.isDisjoint(with: types)
}

If any of these are present, don't store the clip at all. On top of that I run pattern checks for API keys, JWTs and Luhn-valid card numbers, and hide those.

3. Pasting for the user

To paste into the app the user was working in, you need to:

  1. Remember the frontmost app before your UI appears
  2. Put the clip on the pasteboard
  3. Reactivate that app
  4. Simulate ⌘V
func paste(into app: NSRunningApplication) {
    app.activate()
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
        let source = CGEventSource(stateID: .combinedSessionState)
        let keyDown = CGEvent(keyboardEventSource: source, virtualKey: 0x09, keyDown: true)
        let keyUp = CGEvent(keyboardEventSource: source, virtualKey: 0x09, keyDown: false)
        keyDown?.flags = .maskCommand
        keyUp?.flags = .maskCommand
        keyDown?.post(tap: .cghidEventTap)
        keyUp?.post(tap: .cghidEventTap)
    }
}

0x09 is the virtual key code for V. Posting key events needs Accessibility permission, so check AXIsProcessTrusted() and show a clear prompt instead of failing silently.

4. A panel in the notch that doesn't steal focus

If your panel becomes the key window, the app the user was typing in loses focus, and the paste lands in the wrong place. The fix is a non-activating panel:

final class NotchPanel: NSPanel {
    var wantsKeyboard = false

    init() {
        super.init(contentRect: .zero,
                   styleMask: [.borderless, .nonactivatingPanel],
                   backing: .buffered,
                   defer: false)
        level = .statusBar
        collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary]
        isOpaque = false
        backgroundColor = .clear
        hasShadow = false
    }

    override var canBecomeKey: Bool { wantsKeyboard }
}

Only let it become key when the user actually types in the search field.

To find the notch, check safeAreaInsets.top > 0, and use auxiliaryTopLeftArea / auxiliaryTopRightArea (macOS 12+) to work out its width:

if let screen = NSScreen.main,
   let left = screen.auxiliaryTopLeftArea,
   let right = screen.auxiliaryTopRightArea {
    let notchWidth = screen.frame.width - left.width - right.width
}

On displays without a notch, I fall back to a floating pill at the top centre.

5. Searching inside screenshots with Vision

Text recognition runs fully on device:

import Vision

func recognizeText(in image: CGImage) async throws -> String {
    try await withCheckedThrowingContinuation { continuation in
        let request = VNRecognizeTextRequest { request, error in
            if let error { continuation.resume(throwing: error); return }
            let lines = (request.results as? [VNRecognizedTextObservation])?
                .compactMap { $0.topCandidates(1).first?.string } ?? []
            continuation.resume(returning: lines.joined(separator: "\n"))
        }
        request.recognitionLevel = .accurate
        request.usesLanguageCorrection = true
        do {
            try VNImageRequestHandler(cgImage: image).perform([request])
        } catch {
            continuation.resume(throwing: error)
        }
    }
}

Run it on a background queue at low priority and store the text with the clip, so search is instant later.

6. Big images

A 4K screenshot can be 10–20MB. I keep a small thumbnail in the database and the full image as a file on disk. The grid only ever loads thumbnails, which keeps scrolling smooth with thousands of clips.

Wrapping up

The hardest parts weren't the UI. They were the invisible rules: no change notification, concealed types, focus handling, and permissions.

If you want to see how it all comes together, Clipket is at clipket.tech. Happy to answer questions in the comments.