# Selection, clipboard and replacement
Module: `SprachmittlerCapture`. This is the only module that may import `ApplicationServices` or touch `NSPasteboard`.
## 1. Principles
1. Capture only on an explicit user action: the double-copy gesture, the menu item, or Services.
2. No global key tap, no Input Monitoring, no Accessibility observers, no screen capture.
3. Read the pasteboard string only after `changeCount` changes.
4. Keep at most the last two strings in memory; never log them; clear them when the session starts or the window expires.
5. Never replace text without an explicit click on **Replace**.
6. Verify the source app and, when available, the selected text before replacing.
7. If anything is uncertain, offer Copy instead of guessing.
## 2. Double-copy trigger
```text
poll changeCount every 120 ms
│
├─ unchanged → nothing
│
└─ changed
├─ is our own write / transient? → ignore, suppress 750 ms
├─ read string; trim; empty? → reset
├─ first change? → remember (hash, string, time)
└─ second change?
├─ within 500 ms and identical text? → emit CapturedText
└─ otherwise → replace the remembered value with this copy
```
Rules:
- Window: **500 ms** default, configurable 300–1000 ms.
- Identical text: compare normalized line endings and trimming only; do not collapse internal whitespace.
- Non-empty: at least one non-whitespace character.
- Length: 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts; above the limit, show `textTooLong` with the limit and no request.
- A new trigger during an active translation cancels the old one (ADR-015).
- Copying two different things quickly does not trigger; this is deliberate.
- Copying the same text twice slowly does not trigger; increase the window if needed.
### State machine
```mermaid
stateDiagram-v2
[*] --> idle
idle --> firstCopy: change with text
firstCopy --> idle: window expires / empty / own write
firstCopy --> triggered: second change, same text, in window
triggered --> idle: session started
triggered --> triggered: new trigger replaces session
```
### Own-write suppression
Every clipboard write by Sprachmittler adds:
- `com.schihei.sprachmittler.own` (custom marker), and
- `org.nspasteboard.TransientType` plus `org.nspasteboard.ConcealedType` (nspasteboard.org conventions).
The watcher ignores a change if any of those types is present, and ignores all changes for **750 ms** after a write. This prevents translating the translation and prevents the Replace paste from re-triggering.
## 3. Clipboard snapshot and restore
Used only for the synthetic-paste **Replace** fallback.
```text
1. snapshot = every item of NSPasteboard.general, every type, with Data forced
2. changeCount c0 = current
3. clearContents(); write translation + own/transient markers; changeCount c1
4. post ⌘V to the target PID
5. wait up to 300 ms for the paste to be delivered
6. if current changeCount == c1: clearContents(); restore snapshot
7. else: leave the clipboard alone (the user or another app changed it)
```
Limits to document:
- Lazy pasteboard data is forced up front; a provider that never resolves cannot be restored.
- Types with no data cannot be restored.
- A copy that lands after the restore window is not undone.
- If restore fails, report `pasteboardRestoreFailed` and leave the translation on the clipboard; Copy remains available.
## 4. Replacement
```swift
public protocol TextInserting: Sendable {
func replace(selection: CapturedText, with translation: String,
target: InsertionTarget) async throws -> InsertionOutcome
}
public struct InsertionTarget: Sendable, Equatable {
public let pid: pid_t
public let bundleID: String?
public let selectedText: String?
public let capturedAt: Date
}
```
### Strategy order
1. **Accessibility direct replacement** (preferred)
- Requires Accessibility trust.
- Get the focused element (`kAXFocusedUIElementAttribute`).
- Read `kAXSelectedTextAttribute`; it must equal the captured source (after T1 normalization).
- Set `kAXSelectedTextAttribute` to the translation.
- No clipboard mutation; undo is app-dependent.
2. **Synthetic paste fallback**
- Requires Accessibility trust to post events.
- Verify the source app is still frontmost and the target PID matches.
- Snapshot the clipboard, write the translation, post ⌘V to the target PID, restore the snapshot.
- Undo is the source app's normal paste undo.
### Safety rules
- Abort with `insertionTargetChanged` if the frontmost app is not the target.
- Abort if Accessibility is trusted and the selected text no longer equals the source.
- Never insert into a secure input field or a field that reports no settable selection.
- Block Replace when validation has a blocking warning (preamble, truncation, repetition, lost protected token).
- On failure, keep the panel open, show `userMessage` and offer Copy.
## 5. Permissions
| Permission | Needed for | When requested |
|---|---|---|
| Accessibility | Replace only | On the first Replace click (or onboarding if the user opts in). Never on the double-copy path. |
| Input Monitoring | Nothing | Never |
| Screen Recording | Nothing | Never |
| Camera / Microphone | Nothing | Never |
| Apple Events | Nothing | Never |
Check with `AXIsProcessTrusted()`. Prompt with `AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt: true])` only from onboarding or an explicit Replace click. Deep link: `x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility`.
If Accessibility is denied:
- Double copy, translation, Copy and Services still work.
- The Replace button remains visible but explains "Replace needs the Accessibility permission" and offers "Open System Settings" and "Copy instead". Do not nag on every trigger.
## 6. Services entry point
Info.plist:
```xml
NSServices
NSMenuItem
defaultTranslate with Sprachmittler
NSMessagetranslateSelection
NSPortNameSprachmittler
NSSendTypes
public.utf8-plain-textNSStringPboardType
NSRequiredContext
```
`AppDelegate` sets `NSApp.servicesProvider` to `ServicesProvider` in `SprachmittlerCapture` and calls `NSUpdateDynamicServices()`. The service receives an `NSPasteboard` from the system; it needs no polling and no Accessibility. Users can bind a shortcut under System Settings ▸ Keyboard ▸ Keyboard Shortcuts ▸ Services ▸ Text. After first install, a logout/login or `/System/Library/CoreServices/pbs -update` may be needed.
## 7. Compatibility matrix
**This table is filled in by a person, on a real Mac.** Double copy, Accessibility replacement and clipboard restoration differ in every app and cannot be tested headlessly. Until a row is tested its cells stay ☐; an untested cell is not a claim.
For each app test:
1. A plain paragraph.
2. Several paragraphs.
3. Text with a hyphenated line break.
4. A URL and an e-mail.
5. An empty selection (nothing should be translated).
6. Copy, then Replace; check ⌘Z and the previous clipboard (rich text or image).
| App | Bundle ID | Double copy | Replace (AX) | Replace (paste) | Clipboard restored | Notes |
|---|---|---|---|---|---|---|
| Safari | com.apple.Safari | ☐ | ☐ | ☐ | ☐ | |
| Google Chrome | com.google.Chrome | ☐ | ☐ | ☐ | ☐ | Electron-like; `AXManualAccessibility` |
| Firefox | org.mozilla.firefox | ☐ | ☐ | ☐ | ☐ | |
| Preview | com.apple.Preview | ☐ | ☐ | ☐ | ☐ | PDF text |
| 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 |
| Obsidian | md.obsidian | ☐ | ☐ | ☐ | ☐ | Electron |
| Slack | com.tinyspeck.slackmacgap | ☐ | ☐ | ☐ | ☐ | Electron |
| Terminal | com.apple.Terminal | ☐ | ☐ | ☐ | ☐ | Empty selection may copy the line |
Legend: ✅ works · ⚠️ partial (describe) · ❌ unsupported · ☐ not tested.
### Top failures to fix
| # | App | Path | What happens | Fix task |
|---|---|---|---|---|
| 1 | | | | |
| 2 | | | | |
| 3 | | | | |
## 8. Failure modes and messages
| Situation | User message | Recovery |
|---|---|---|
| No text after two copies | "No text was copied." | Nothing; copy again |
| Text too long | "This selection is too long (limit 4,000 characters)." | Shorten it or use the CLI |
| Ollama unreachable | "Ollama is not running." | Start Ollama |
| Model missing | "The Hy-MT3 model is not installed." | Copy the `ollama pull` command |
| Accessibility denied | "Replace needs the Accessibility permission." | Open System Settings / Copy instead |
| App does not accept replacement | "This app did not accept the replacement." | Copy instead |
| Selection changed | "The selection changed before Replace." | Copy instead |
| Pasteboard restore failed | "The previous clipboard could not be restored." | Translation is on the clipboard |
| Preamble warning | "The model added an explanation." | Review, Copy, or retry |
| Truncated | "The translation was cut off." | Retry or shorten |
| Repetition loop | "The translation started repeating." | Retry with the 1.8B or a shorter selection |