Files
Vorleser-Kit/docs/SELECTION_CAPTURE.md
T

132 lines
6.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Selection capture
Module: `VorleserCapture`. This is the only module that may import `ApplicationServices` and use AX APIs.
## Principles
1. Capture only on an explicit user trigger.
2. Capture before any Vorleser window is shown or activated. The controller is a non-activating panel.
3. Return an immutable snapshot (`CapturedSelection`).
4. Never read more than the selection: no full-document `kAXValueAttribute` reads as a fallback.
5. 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:
```text
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 `DispatchQueue` wrapped in an async function. AX is thread-safe per element.
- Return `kAXErrorAPIDisabled` / `kAXErrorNotImplemented` / `kAXErrorCannotComplete` as `captureUnsupported`. `AXIsProcessTrusted() == false` → `accessibilityNotTrusted`.
## Strategy 2: Services (`ServicesSelectionReceiver`)
Info.plist (`NSServices`):
```xml
<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:
```swift
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."
```text
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
```swift
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 | ☐ | ☐ | ☐ | |
| Mail | 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.