6.6 KiB
Selection capture
Module: VorleserCapture. This is the only module that may import ApplicationServices and use AX APIs.
Principles
- Capture only on an explicit user trigger.
- Capture before any Vorleser window is shown or activated. The controller is a non-activating panel.
- Return an immutable snapshot (
CapturedSelection). - Never read more than the selection: no full-document
kAXValueAttributereads as a fallback. - When capture fails, the error names the method and app (
captureUnsupported(app:)) so the user knows to use the Services menu or enable clipboard fallback.
Entry points
| Entry point | Path into the app | Capture strategy |
|---|---|---|
| Global hotkey "Read selection" (default ⌥⎋) | KeyboardShortcuts.onKeyUp |
CaptureChain (AX, then clipboard if enabled) |
| Services menu "Read with Vorleser" | NSApp.servicesProvider → readSelection(_:userData:error:) |
Pasteboard provided by the system |
| Menu-bar "Read selection" | Menu item | Same as hotkey. Note: opening the menu-bar menu does not activate Vorleser, but capture still has to target the previously frontmost app. Record NSWorkspace.shared.frontmostApplication on menuWillOpen. |
Strategy 1: Accessibility (AXSelectionCapturer)
Permission: Accessibility. Check with AXIsProcessTrusted(). Prompt with AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt: true]) from onboarding only and never on the hotkey path. Deep-link: x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility.
Algorithm:
1. app = NSWorkspace.shared.frontmostApplication (skip if it is Vorleser itself)
2. appElement = AXUIElementCreateApplication(app.pid)
3. If app is Electron/Chromium-based (bundle ID list or presence of "AXManualAccessibility"):
AXUIElementSetAttributeValue(appElement, "AXManualAccessibility", true)
(Chromium: "AXEnhancedUserInterface" true is an alternative; set it only for the
duration of the capture and then restore it, because it can affect window animations.)
4. focused = AXUIElementCopyAttributeValue(systemWide, kAXFocusedUIElementAttribute)
?? AXUIElementCopyAttributeValue(appElement, kAXFocusedUIElementAttribute)
5. text = AXUIElementCopyAttributeValue(focused, kAXSelectedTextAttribute) as? String
6. If text is nil/empty:
range = kAXSelectedTextRangeAttribute → if non-empty, use
kAXStringForRangeParameterizedAttribute(range) on focused element
7. If still empty: walk up to 3 parents (kAXParentAttribute) repeating 5–6 (web areas often
hold the selection on an ancestor "AXWebArea").
8. Return text or throw .noSelection / .captureUnsupported(app.localizedName)
Rules:
- Messaging timeout:
AXUIElementSetMessagingTimeout(appElement, 0.25). Hung apps must not freeze the hotkey path. - Run AX calls off the main thread, on a dedicated serial
DispatchQueuewrapped in an async function. AX is thread-safe per element. - Return
kAXErrorAPIDisabled/kAXErrorNotImplemented/kAXErrorCannotCompleteascaptureUnsupported.AXIsProcessTrusted() == false→accessibilityNotTrusted.
Strategy 2: Services (ServicesSelectionReceiver)
Info.plist (NSServices):
<key>NSServices</key>
<array>
<dict>
<key>NSMenuItem</key>
<dict><key>default</key><string>Read with Vorleser</string></dict>
<key>NSMessage</key><string>readSelection</string>
<key>NSPortName</key><string>Vorleser</string>
<key>NSSendTypes</key>
<array><string>public.utf8-plain-text</string><string>NSStringPboardType</string></array>
<key>NSRequiredContext</key><dict/>
</dict>
</array>
AppDelegate:
NSApp.servicesProvider = servicesHandler
NSUpdateDynamicServices()
@objc func readSelection(_ pboard: NSPasteboard, userData: String?, error: AutoreleasingUnsafeMutablePointer<NSString?>) {
guard let text = pboard.string(forType: .string), !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
// build CapturedSelection(method: .service) and start session
}
Users can bind a shortcut under System Settings ▸ Keyboard ▸ Keyboard Shortcuts ▸ Services ▸ Text. Onboarding should mention this. Services may need a logout/login or /System/Library/CoreServices/pbs -update after first install. Document this under Troubleshooting.
Strategy 3: Clipboard fallback (ClipboardSelectionCapturer, opt-in)
Disabled by default. Settings must disclose: "Vorleser will briefly copy your selection and then restore your clipboard."
1. snapshot = all items of NSPasteboard.general (all types, as Data), changeCount c0
2. Post ⌘C via CGEvent (keyDown/keyUp with .maskCommand) to HID tap
3. Poll changeCount every 10 ms up to 300 ms
4. If changed → text = string(forType: .string)
5. Restore snapshot (clearContents + write all items), regardless of success
6. If unchanged → throw captureUnsupported
Requires Accessibility trust to post events. Mark the restore with NSPasteboard.general.setString("", forType: .init("org.nspasteboard.TransientType")) so clipboard managers ignore the transient copy (nspasteboard.org convention).
Capture chain
public struct CaptureChain: SelectionCapturing {
let strategies: [SelectionCapturing] // built from settings.captureOrder
// Try in order. Stop at the first non-empty result.
// Errors: if all fail, throw the most informative one
// (accessibilityNotTrusted > captureUnsupported > noSelection).
}
Compatibility matrix (fill in during M6/M9 testing)
Test each with: plain paragraph, multi-paragraph, selection containing a hyphenated line break (PDF), and an empty selection.
| App | Bundle ID | AX hotkey | Services | Clipboard | Notes |
|---|---|---|---|---|---|
| Safari | com.apple.Safari | ☐ | ☐ | ☐ | |
| Google Chrome | com.google.Chrome | ☐ | ☐ | ☐ | AXEnhancedUserInterface |
| Firefox | org.mozilla.firefox | ☐ | ☐ | ☐ | |
| Preview (PDF) | com.apple.Preview | ☐ | ☐ | ☐ | Hyphenation join |
| Adobe Acrobat | com.adobe.Acrobat.Pro | ☐ | ☐ | ☐ | |
| Pages | com.apple.iWork.Pages | ☐ | ☐ | ☐ | |
| Microsoft Word | com.microsoft.Word | ☐ | ☐ | ☐ | |
| com.apple.mail | ☐ | ☐ | ☐ | ||
| Notes | com.apple.Notes | ☐ | ☐ | ☐ | |
| TextEdit | com.apple.TextEdit | ☐ | ☐ | ☐ | Baseline |
| Visual Studio Code | com.microsoft.VSCode | ☐ | ☐ | ☐ | Electron, AXManualAccessibility |
| Obsidian | md.obsidian | ☐ | ☐ | ☐ | Electron |
| Slack | com.tinyspeck.slackmacgap | ☐ | ☐ | ☐ | Electron |
| Terminal | com.apple.Terminal | ☐ | ☐ | ☐ |
Legend: ✅ works · ⚠️ partial (describe) · ❌ unsupported.