|
|
|
@ -1,22 +1,39 @@ |
|
|
|
import Cocoa |
|
|
|
import ApplicationServices |
|
|
|
|
|
|
|
/// Zero-Spam Production Text Injection Engine (v3.0): |
|
|
|
/// - Live Word-by-Word Mode: Injects characters directly via Quartz Unicode `CGEvent` (`keyboardSetUnicodeString`) |
|
|
|
/// with clean modifier flags (`flags = []`), touching `NSPasteboard.general` **0 times** while speaking! |
|
|
|
/// - Supports Provisional Live Words + Scalar-Safe Longest-Common-Prefix (LCP) Tail Rewrite so unfinalized words |
|
|
|
/// appear immediately and smoothly transform into the exact final polished sentence when speech finishes. |
|
|
|
/// - Batch Mode: Inserts the entire polished sentence at once upon key release, touching clipboard at most 1 time |
|
|
|
/// (or 0 permanent times when `ClipboardBehavior.preserveOriginal` is selected). |
|
|
|
public final class InputBoxManager { |
|
|
|
public static let shared = InputBoxManager() |
|
|
|
|
|
|
|
private let lock = NSLock() |
|
|
|
private var accumulatedStreamedText: String = "" |
|
|
|
private var pendingPrefixBuffer: String = "" |
|
|
|
private var isPrefixResolved: Bool = false |
|
|
|
private var needsNewlineBeforeNextDelta: Bool = false |
|
|
|
private var sessionGeneration: UInt64 = 0 |
|
|
|
private var clipboardRestoreWorkItem: DispatchWorkItem? |
|
|
|
private var hasInjectedAnyLiveText: Bool = false |
|
|
|
|
|
|
|
// Accessed exclusively on serial `pasteQueue` (or reset via generation check) |
|
|
|
private var displayedCharacters: [Character] = [] |
|
|
|
private var lastBackspaceRewriteTime: TimeInterval = 0 |
|
|
|
private var isExecutiveSlashSuppressed: Bool = false |
|
|
|
|
|
|
|
private let pasteQueue = DispatchQueue(label: "com.soniox.pasteQueue", qos: .userInteractive) |
|
|
|
|
|
|
|
private static let punctRegex: NSRegularExpression = { |
|
|
|
return try! NSRegularExpression(pattern: #"[.,!?:;،؛؟"'()\[\]{}«»–—\-…]"#, options: []) |
|
|
|
}() |
|
|
|
|
|
|
|
// Combining marks / zero-width joiners stripped ONLY during provisional live preview so |
|
|
|
// `1 Swift Character == 1 Backspace (kVK_Delete)` holds across 100% of macOS apps (AppKit, Chrome, Electron, Terminal). |
|
|
|
private static let provisionalUnsafeScalars: CharacterSet = { |
|
|
|
var set = CharacterSet.nonBaseCharacters |
|
|
|
set.insert(charactersIn: "\u{200B}\u{200D}\u{FEFF}") |
|
|
|
return set |
|
|
|
}() |
|
|
|
|
|
|
|
private init() {} |
|
|
|
|
|
|
|
public static func stripPunctuation(_ str: String) -> String { |
|
|
|
@ -24,412 +41,375 @@ public final class InputBoxManager { |
|
|
|
return punctRegex.stringByReplacingMatches(in: str, options: [], range: range, withTemplate: "") |
|
|
|
} |
|
|
|
|
|
|
|
/// Reset session state at the beginning of speech |
|
|
|
/// Converts provisional text into a strictly 1-character-per-backspace single-line representation. |
|
|
|
public static func makeBackspaceSafeProvisional(_ text: String) -> String { |
|
|
|
if text.isEmpty { return "" } |
|
|
|
var out = String.UnicodeScalarView() |
|
|
|
out.reserveCapacity(text.unicodeScalars.count) |
|
|
|
var prevWasSpace = false |
|
|
|
for scalar in text.unicodeScalars { |
|
|
|
if scalar == "\u{200C}" || scalar == "\n" || scalar == "\r" || scalar == "\t" || scalar == "\u{00A0}" { |
|
|
|
if !prevWasSpace { |
|
|
|
out.append(" ") |
|
|
|
prevWasSpace = true |
|
|
|
} |
|
|
|
continue |
|
|
|
} |
|
|
|
if provisionalUnsafeScalars.contains(scalar) { |
|
|
|
continue |
|
|
|
} |
|
|
|
let isSpace = (scalar == " ") |
|
|
|
if isSpace && prevWasSpace { |
|
|
|
continue |
|
|
|
} |
|
|
|
prevWasSpace = isSpace |
|
|
|
out.append(scalar) |
|
|
|
} |
|
|
|
return String(out) |
|
|
|
} |
|
|
|
|
|
|
|
/// Reset session state at the beginning of speech or on Escape cancel. |
|
|
|
public func resetSession() { |
|
|
|
lock.lock() |
|
|
|
sessionGeneration &+= 1 |
|
|
|
accumulatedStreamedText = "" |
|
|
|
pendingPrefixBuffer = "" |
|
|
|
isPrefixResolved = false |
|
|
|
needsNewlineBeforeNextDelta = false |
|
|
|
clipboardRestoreWorkItem?.cancel() |
|
|
|
clipboardRestoreWorkItem = nil |
|
|
|
hasInjectedAnyLiveText = false |
|
|
|
let gen = sessionGeneration |
|
|
|
lock.unlock() |
|
|
|
|
|
|
|
pasteQueue.async { [weak self] in |
|
|
|
guard let self = self else { return } |
|
|
|
self.lock.lock() |
|
|
|
let current = self.sessionGeneration |
|
|
|
self.lock.unlock() |
|
|
|
if current == gen { |
|
|
|
self.displayedCharacters.removeAll(keepingCapacity: true) |
|
|
|
self.lastBackspaceRewriteTime = 0 |
|
|
|
self.isExecutiveSlashSuppressed = false |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
/// Returns true if any text has been streamed into the input box during this session |
|
|
|
/// Returns true if any characters were typed live into the focused input box during this session. |
|
|
|
public var hasStreamedText: Bool { |
|
|
|
lock.lock() |
|
|
|
defer { lock.unlock() } |
|
|
|
let s = accumulatedStreamedText.trimmingCharacters(in: .whitespacesAndNewlines) |
|
|
|
let p = pendingPrefixBuffer.trimmingCharacters(in: .whitespacesAndNewlines) |
|
|
|
return !s.isEmpty || !p.isEmpty |
|
|
|
return hasInjectedAnyLiveText |
|
|
|
} |
|
|
|
|
|
|
|
/// Prepares session state before recording starts. |
|
|
|
/// STRICT RULE: Focus is 100% user-directed. Never steal focus to browser address bar or toolbar. |
|
|
|
/// Prepares session state before recording starts without stealing focus or blocking on modal prompts. |
|
|
|
public func ensureFocusedInputBox() { |
|
|
|
resetSession() |
|
|
|
|
|
|
|
let promptKey = kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String |
|
|
|
let isTrusted = AXIsProcessTrustedWithOptions([promptKey: true] as CFDictionary) |
|
|
|
guard isTrusted else { |
|
|
|
print("InputBoxManager: Accessibility not trusted.") |
|
|
|
return |
|
|
|
if !AXIsProcessTrusted() { |
|
|
|
print("InputBoxManager: Accessibility permission not yet granted (Unicode typing / paste requires Accessibility).") |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
/// Streams word-by-word delta text directly into the focused input box in real time |
|
|
|
public func streamDelta(text: String) { |
|
|
|
guard !text.isEmpty else { return } |
|
|
|
/// Updates live simultaneous typing in `.liveWordByWord` mode with ZERO clipboard usage. |
|
|
|
/// - Parameters: |
|
|
|
/// - fullCandidate: Confirmed tokens + current unfinalized hypothesis. |
|
|
|
/// - confirmedPrefix: Strictly finalized (`is_final == true`) tokens only. |
|
|
|
public func updateLiveTranscript(fullCandidate: String, confirmedPrefix: String) { |
|
|
|
guard SonioxSettings.shared.typingDeliveryMode == .liveWordByWord else { |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
// Suppress trailing end triggers ("and", "تمام", "end") ONLY in hands-free/toggle mode, never in Push-To-Talk |
|
|
|
if HotkeyManager.shared.currentMode != .pushToTalk { |
|
|
|
let triggerWords = text.components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty } |
|
|
|
if let lastRaw = triggerWords.last { |
|
|
|
let last = InputBoxManager.stripPunctuation(lastRaw).lowercased() |
|
|
|
if last == "and" || last == "تمام" || last == "end" { |
|
|
|
if triggerWords.count <= 1 { |
|
|
|
return |
|
|
|
let engineMode = SonioxSettings.shared.liveStreamEngineMode |
|
|
|
let rawSource: String |
|
|
|
switch engineMode { |
|
|
|
case .provisionalRewrite: |
|
|
|
rawSource = fullCandidate |
|
|
|
case .confirmedFinalsOnly: |
|
|
|
// Hold back the last unfinished compound number/punctuation word until next confirmed word arrives |
|
|
|
rawSource = Self.confirmedStableSlice(from: confirmedPrefix) |
|
|
|
} |
|
|
|
|
|
|
|
let trimmedCheck = fullCandidate.trimmingCharacters(in: .whitespacesAndNewlines) |
|
|
|
guard !trimmedCheck.isEmpty else { return } |
|
|
|
|
|
|
|
// Check Executive Slash Command holdback so "/chrome" or "اسلش چپ" is NEVER typed into the input box! |
|
|
|
if SonioxSettings.shared.voiceCommands && !BotCommandProcessor.isBotCommand(text: trimmedCheck) { |
|
|
|
let words = trimmedCheck.components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty } |
|
|
|
if let first = words.first { |
|
|
|
let cleanFirst = first.lowercased() |
|
|
|
let slashTriggers = ["اسلش", "اصلش", "slash", "slsh", "/", "\\"] |
|
|
|
let startsSlash = slashTriggers.contains(where: { cleanFirst.hasPrefix($0) }) |
|
|
|
if startsSlash && words.count < 2 { |
|
|
|
// Wait for 2nd word before deciding whether it's an executive command or normal text |
|
|
|
return |
|
|
|
} |
|
|
|
if VoiceCommandExecutor.shared.isSlashCommand(text: trimmedCheck) { |
|
|
|
lock.lock() |
|
|
|
let expectedGen = sessionGeneration |
|
|
|
lock.unlock() |
|
|
|
pasteQueue.async { [weak self] in |
|
|
|
guard let self = self else { return } |
|
|
|
self.lock.lock() |
|
|
|
let valid = (self.sessionGeneration == expectedGen) |
|
|
|
self.lock.unlock() |
|
|
|
guard valid else { return } |
|
|
|
if !self.displayedCharacters.isEmpty { |
|
|
|
self.postBackspaces(self.displayedCharacters.count) |
|
|
|
self.displayedCharacters.removeAll() |
|
|
|
} |
|
|
|
self.isExecutiveSlashSuppressed = true |
|
|
|
} |
|
|
|
let textWithoutEnd = triggerWords.dropLast().joined(separator: " ") + " " |
|
|
|
streamDelta(text: textWithoutEnd) |
|
|
|
return |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
// Apply lightweight inline formatting (domain vocabulary, voice punctuation, digits) so streamed words match final text |
|
|
|
let normalizedDelta = TextProcessor.shared.processLiveChunk(text) |
|
|
|
guard !rawSource.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } |
|
|
|
let formattedPreview = TextProcessor.shared.processLivePreview(rawSource) |
|
|
|
let safeProvisional = Self.makeBackspaceSafeProvisional(formattedPreview) |
|
|
|
guard !safeProvisional.isEmpty else { return } |
|
|
|
|
|
|
|
lock.lock() |
|
|
|
let expectedGen = sessionGeneration |
|
|
|
if isPrefixResolved { |
|
|
|
var textToPaste = normalizedDelta |
|
|
|
if needsNewlineBeforeNextDelta { |
|
|
|
needsNewlineBeforeNextDelta = false |
|
|
|
let trimmed = normalizedDelta.trimmingCharacters(in: .whitespacesAndNewlines) |
|
|
|
if !trimmed.isEmpty { |
|
|
|
textToPaste = "\n" + trimmed |
|
|
|
} |
|
|
|
} |
|
|
|
accumulatedStreamedText += textToPaste |
|
|
|
lock.unlock() |
|
|
|
lock.unlock() |
|
|
|
|
|
|
|
pasteQueue.async { [weak self] in |
|
|
|
guard let self = self else { return } |
|
|
|
self.lock.lock() |
|
|
|
let valid = (self.sessionGeneration == expectedGen) |
|
|
|
self.lock.unlock() |
|
|
|
guard valid, !self.isExecutiveSlashSuppressed else { return } |
|
|
|
|
|
|
|
pasteQueue.async { [weak self] in |
|
|
|
guard let self = self else { return } |
|
|
|
self.lock.lock() |
|
|
|
let valid = (self.sessionGeneration == expectedGen) |
|
|
|
self.lock.unlock() |
|
|
|
guard valid else { return } |
|
|
|
|
|
|
|
self.pasteSynchronously(textToPaste) |
|
|
|
let newChars = Array(safeProvisional) |
|
|
|
if newChars == self.displayedCharacters { |
|
|
|
return |
|
|
|
} |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
// Not resolved yet: buffer to check if speech starts with a slash command |
|
|
|
pendingPrefixBuffer += normalizedDelta |
|
|
|
let trimmed = pendingPrefixBuffer.trimmingCharacters(in: .whitespacesAndNewlines) |
|
|
|
let words = trimmed.components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty } |
|
|
|
|
|
|
|
guard let firstWord = words.first else { |
|
|
|
lock.unlock() |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
let slashTriggers = ["اسلش", "اصلش", "slash", "/", "\\"] |
|
|
|
let isSlashPrefix = slashTriggers.contains { firstWord.lowercased().hasPrefix($0) } |
|
|
|
|
|
|
|
if !isSlashPrefix { |
|
|
|
// Normal speech: flush buffer immediately and continue normal streaming! |
|
|
|
isPrefixResolved = true |
|
|
|
let toFlush = pendingPrefixBuffer |
|
|
|
pendingPrefixBuffer = "" |
|
|
|
accumulatedStreamedText += toFlush |
|
|
|
lock.unlock() |
|
|
|
|
|
|
|
pasteQueue.async { [weak self] in |
|
|
|
guard let self = self else { return } |
|
|
|
self.lock.lock() |
|
|
|
let valid = (self.sessionGeneration == expectedGen) |
|
|
|
self.lock.unlock() |
|
|
|
guard valid else { return } |
|
|
|
|
|
|
|
self.pasteSynchronously(toFlush) |
|
|
|
var lcp = 0 |
|
|
|
let limit = min(self.displayedCharacters.count, newChars.count) |
|
|
|
while lcp < limit && self.displayedCharacters[lcp] == newChars[lcp] { |
|
|
|
lcp += 1 |
|
|
|
} |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
// Starts with slash trigger: check if it matches a Bot Command (/steer, /queue, /cancel) |
|
|
|
if let botRes = BotCommandProcessor.parse(text: trimmed) { |
|
|
|
isPrefixResolved = true |
|
|
|
var textToPaste = botRes.command |
|
|
|
if !botRes.body.isEmpty { |
|
|
|
textToPaste += "\n" + botRes.body |
|
|
|
needsNewlineBeforeNextDelta = false |
|
|
|
} else { |
|
|
|
needsNewlineBeforeNextDelta = true |
|
|
|
|
|
|
|
let eraseCount = self.displayedCharacters.count - lcp |
|
|
|
if eraseCount > 0 { |
|
|
|
// Throttle mid-speech backspace rewrites (~160ms) to avoid sub-syllable flicker while typing forward at 0ms! |
|
|
|
let now = Date().timeIntervalSince1970 |
|
|
|
if (now - self.lastBackspaceRewriteTime) < 0.16 { |
|
|
|
return |
|
|
|
} |
|
|
|
self.lastBackspaceRewriteTime = now |
|
|
|
self.postBackspaces(eraseCount) |
|
|
|
} |
|
|
|
|
|
|
|
pendingPrefixBuffer = "" |
|
|
|
accumulatedStreamedText = textToPaste |
|
|
|
lock.unlock() |
|
|
|
if lcp < newChars.count { |
|
|
|
let deltaStr = String(newChars[lcp...]) |
|
|
|
self.typeUnicodeSynchronously(deltaStr) |
|
|
|
} |
|
|
|
|
|
|
|
pasteQueue.async { [weak self] in |
|
|
|
guard let self = self else { return } |
|
|
|
self.displayedCharacters = newChars |
|
|
|
if !newChars.isEmpty { |
|
|
|
self.lock.lock() |
|
|
|
let valid = (self.sessionGeneration == expectedGen) |
|
|
|
if self.sessionGeneration == expectedGen { |
|
|
|
self.hasInjectedAnyLiveText = true |
|
|
|
} |
|
|
|
self.lock.unlock() |
|
|
|
guard valid else { return } |
|
|
|
|
|
|
|
self.pasteSynchronously(textToPaste) |
|
|
|
} |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
// If 2 words have accumulated and it's NOT a bot command: |
|
|
|
if words.count >= 2 { |
|
|
|
isPrefixResolved = true |
|
|
|
// If it's an executive voice command, do NOT stream it to the input box! |
|
|
|
if SonioxSettings.shared.voiceCommands && VoiceCommandExecutor.shared.isSlashCommand(text: trimmed) { |
|
|
|
pendingPrefixBuffer = "" |
|
|
|
lock.unlock() |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
// Otherwise, it was just regular speech starting with "اسلش..." |
|
|
|
let toFlush = pendingPrefixBuffer |
|
|
|
pendingPrefixBuffer = "" |
|
|
|
accumulatedStreamedText += toFlush |
|
|
|
lock.unlock() |
|
|
|
|
|
|
|
pasteQueue.async { [weak self] in |
|
|
|
guard let self = self else { return } |
|
|
|
self.lock.lock() |
|
|
|
let valid = (self.sessionGeneration == expectedGen) |
|
|
|
self.lock.unlock() |
|
|
|
guard valid else { return } |
|
|
|
|
|
|
|
self.pasteSynchronously(toFlush) |
|
|
|
} |
|
|
|
|
|
|
|
/// Legacy delta entry point kept for compatibility. |
|
|
|
public func streamDelta(text: String) { |
|
|
|
// Handled cleanly via `updateLiveTranscript(fullCandidate:confirmedPrefix:)`. |
|
|
|
} |
|
|
|
|
|
|
|
/// Holds back the trailing word in `.confirmedFinalsOnly` mode if it could be the first half of a |
|
|
|
/// compound Persian number ("بیست" + "و پنج") or multi-word punctuation ("علامت" + "سوال"). |
|
|
|
private static func confirmedStableSlice(from confirmed: String) -> String { |
|
|
|
let trimmed = confirmed.trimmingCharacters(in: .whitespacesAndNewlines) |
|
|
|
guard !trimmed.isEmpty else { return "" } |
|
|
|
let words = trimmed.components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty } |
|
|
|
let holdbackTriggers: Set<String> = [ |
|
|
|
"بیست", "سی", "چهل", "پنجاه", "شصت", "هفتاد", "هشتاد", "نود", |
|
|
|
"صد", "دویست", "سیصد", "چهارصد", "پانصد", "ششصد", "هفتصد", "هشتصد", "نهصد", |
|
|
|
"علامت", "نقطه", "خط", "سطر", "سر", "دو", "سه", "گیومه", "پرانتز", |
|
|
|
"question", "exclamation", "semi", "full", "new", "enter", "open", "close" |
|
|
|
] |
|
|
|
if let last = words.last { |
|
|
|
let cleanLast = stripPunctuation(last).lowercased() |
|
|
|
if holdbackTriggers.contains(cleanLast) { |
|
|
|
if words.count <= 1 { return "" } |
|
|
|
return words.dropLast().joined(separator: " ") + " " |
|
|
|
} |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
lock.unlock() |
|
|
|
return confirmed |
|
|
|
} |
|
|
|
|
|
|
|
/// Commits the final speech result: ensures 100% complete text in input box & clipboard without ANY duplication |
|
|
|
/// Commits the final speech result: |
|
|
|
/// - In Live Word-by-Word mode: smoothly rewrites only the differing tail from `displayedCharacters` to `finalOutput` |
|
|
|
/// using pure Unicode keystrokes (0 `Cmd+V`), then copies full text ONCE to clipboard if configured. |
|
|
|
/// - In Batch mode: inserts full polished text atomically in one shot, writing clipboard at most ONCE (or restoring original). |
|
|
|
public func commitFinalText(fullText: String, addTrailingSpace: Bool) { |
|
|
|
let trimmed = fullText.trimmingCharacters(in: .whitespacesAndNewlines) |
|
|
|
guard !trimmed.isEmpty else { return } |
|
|
|
|
|
|
|
let textWithTrailing = addTrailingSpace ? (trimmed + " ") : trimmed |
|
|
|
let deliveryMode = SonioxSettings.shared.typingDeliveryMode |
|
|
|
|
|
|
|
lock.lock() |
|
|
|
let expectedGen = sessionGeneration |
|
|
|
// Flush any pending buffer if recording ended before prefix resolution |
|
|
|
if !isPrefixResolved && !pendingPrefixBuffer.isEmpty { |
|
|
|
let pending = pendingPrefixBuffer |
|
|
|
pendingPrefixBuffer = "" |
|
|
|
if let botRes = BotCommandProcessor.parse(text: pending) { |
|
|
|
accumulatedStreamedText = botRes.formattedText |
|
|
|
} else if !(SonioxSettings.shared.voiceCommands && VoiceCommandExecutor.shared.isSlashCommand(text: pending)) { |
|
|
|
accumulatedStreamedText += pending |
|
|
|
} |
|
|
|
} |
|
|
|
let rawStreamed = accumulatedStreamedText |
|
|
|
accumulatedStreamedText = "" |
|
|
|
lock.unlock() |
|
|
|
|
|
|
|
// CRITICAL: Process the streamed text through the EXACT same TextProcessor pipeline as fullText! |
|
|
|
// This guarantees that numbers (۱ -> 1), ellipses (... -> . . .), and punctuation tokens have identical word counts & tokens! |
|
|
|
let processedStreamed = rawStreamed.isEmpty ? "" : TextProcessor.shared.process(text: rawStreamed) |
|
|
|
let cleanStreamed = processedStreamed.trimmingCharacters(in: .whitespacesAndNewlines) |
|
|
|
let streamedEndedWithSpace = rawStreamed.unicodeScalars.last.map { CharacterSet.whitespacesAndNewlines.contains($0) } ?? false |
|
|
|
|
|
|
|
pasteQueue.async { [weak self] in |
|
|
|
guard let self = self else { return } |
|
|
|
self.lock.lock() |
|
|
|
let valid = (self.sessionGeneration == expectedGen) |
|
|
|
self.hasInjectedAnyLiveText = false |
|
|
|
self.lock.unlock() |
|
|
|
guard valid else { return } |
|
|
|
|
|
|
|
let restoreClipboardFullText = { [weak self] in |
|
|
|
guard let self = self else { return } |
|
|
|
let work = DispatchWorkItem { [weak self] in |
|
|
|
guard let self = self else { return } |
|
|
|
self.lock.lock() |
|
|
|
let stillValid = (self.sessionGeneration == expectedGen) |
|
|
|
self.lock.unlock() |
|
|
|
guard stillValid else { return } |
|
|
|
let pb = NSPasteboard.general |
|
|
|
pb.clearContents() |
|
|
|
pb.setString(textWithTrailing, forType: .string) |
|
|
|
guard !trimmed.isEmpty else { |
|
|
|
// Speech resolved to empty (e.g. stripped trigger): erase any provisional characters cleanly |
|
|
|
if !self.displayedCharacters.isEmpty { |
|
|
|
self.postBackspaces(self.displayedCharacters.count) |
|
|
|
self.displayedCharacters.removeAll() |
|
|
|
} |
|
|
|
self.lock.lock() |
|
|
|
self.clipboardRestoreWorkItem?.cancel() |
|
|
|
self.clipboardRestoreWorkItem = work |
|
|
|
self.lock.unlock() |
|
|
|
DispatchQueue.main.asyncAfter(deadline: .now() + 0.30, execute: work) |
|
|
|
} |
|
|
|
|
|
|
|
// Case 1: Nothing was streamed live -> Paste entire text |
|
|
|
if cleanStreamed.isEmpty { |
|
|
|
self.pasteSynchronously(textWithTrailing) |
|
|
|
restoreClipboardFullText() |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
// Case 2: Exactly matches streamed text |
|
|
|
if cleanStreamed == trimmed { |
|
|
|
if addTrailingSpace && !streamedEndedWithSpace { |
|
|
|
self.pasteSynchronously(" ") |
|
|
|
} |
|
|
|
restoreClipboardFullText() |
|
|
|
return |
|
|
|
} |
|
|
|
let finalOutput = addTrailingSpace ? (trimmed + " ") : trimmed |
|
|
|
|
|
|
|
// Case 3: Streamed prefix is exact prefix of trimmed final text |
|
|
|
if trimmed.count > cleanStreamed.count && trimmed.hasPrefix(cleanStreamed) { |
|
|
|
let rawSuffix = String(trimmed.dropFirst(cleanStreamed.count)) |
|
|
|
let cleanSuffix = rawSuffix.trimmingCharacters(in: .whitespacesAndNewlines) |
|
|
|
if !cleanSuffix.isEmpty { |
|
|
|
let needsLeadingSpace = !streamedEndedWithSpace && (rawSuffix.first?.isWhitespace == true) |
|
|
|
let suffixToPaste = (needsLeadingSpace ? " " : "") + cleanSuffix + (addTrailingSpace ? " " : "") |
|
|
|
self.pasteSynchronously(suffixToPaste) |
|
|
|
} else if addTrailingSpace && !streamedEndedWithSpace { |
|
|
|
self.pasteSynchronously(" ") |
|
|
|
// PATH A: Live text was already typed on screen -> Minimal LCP Tail Rewrite via Unicode Keystrokes (0 Cmd+V!) |
|
|
|
if !self.displayedCharacters.isEmpty { |
|
|
|
let finalChars = Array(finalOutput) |
|
|
|
var lcp = 0 |
|
|
|
let limit = min(self.displayedCharacters.count, finalChars.count) |
|
|
|
while lcp < limit && self.displayedCharacters[lcp] == finalChars[lcp] { |
|
|
|
lcp += 1 |
|
|
|
} |
|
|
|
|
|
|
|
let eraseCount = self.displayedCharacters.count - lcp |
|
|
|
if eraseCount > 0 { |
|
|
|
self.postBackspaces(eraseCount) |
|
|
|
} |
|
|
|
restoreClipboardFullText() |
|
|
|
if lcp < finalChars.count { |
|
|
|
let suffixToType = String(finalChars[lcp...]) |
|
|
|
self.typeUnicodeSynchronously(suffixToType) |
|
|
|
} |
|
|
|
|
|
|
|
self.displayedCharacters.removeAll(keepingCapacity: true) |
|
|
|
self.lastBackspaceRewriteTime = 0 |
|
|
|
self.isExecutiveSlashSuppressed = false |
|
|
|
|
|
|
|
// Record complete final text on clipboard at most ONCE (or 0 times if preserveOriginal) |
|
|
|
ClipboardGuard.shared.commitFinalClipboardRecordIfDesired(text: trimmed, deliveryMode: .liveWordByWord) |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
// Case 4: Word-level Tail-Anchor Matching with 1-to-1 Aligned Index Mapping |
|
|
|
let rawStreamedWords = cleanStreamed.components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty } |
|
|
|
let rawFinalWords = trimmed.components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty } |
|
|
|
// PATH B: Nothing was typed yet (Batch Mode, or short utterance before live threshold) |
|
|
|
self.isExecutiveSlashSuppressed = false |
|
|
|
|
|
|
|
let cleanWord: (String) -> String = { w in |
|
|
|
let noZwnj = w.replacingOccurrences(of: "\u{200C}", with: "").replacingOccurrences(of: "\u{200D}", with: "") |
|
|
|
return InputBoxManager.stripPunctuation(noZwnj).lowercased() |
|
|
|
// If user is still physically holding a modifier key (e.g. Option), avoid Cmd+V modifier collision |
|
|
|
// by injecting short/medium text via pure modifier-clean Unicode events! |
|
|
|
if HotkeyManager.shared.isPhysicalKeyDown && finalOutput.count <= 240 { |
|
|
|
self.typeUnicodeSynchronously(finalOutput) |
|
|
|
ClipboardGuard.shared.commitFinalClipboardRecordIfDesired(text: trimmed, deliveryMode: deliveryMode) |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
// Keep ONLY words that contain actual alphanumeric/Persian letters so standalone punctuation (".", "...") NEVER shifts indices! |
|
|
|
let streamedPairs: [(raw: String, norm: String)] = rawStreamedWords.compactMap { w in |
|
|
|
let nw = cleanWord(w) |
|
|
|
return nw.isEmpty ? nil : (w, nw) |
|
|
|
} |
|
|
|
let finalPairs: [(raw: String, norm: String)] = rawFinalWords.compactMap { w in |
|
|
|
let nw = cleanWord(w) |
|
|
|
return nw.isEmpty ? nil : (w, nw) |
|
|
|
} |
|
|
|
// Atomic Batch Paste (writes NSPasteboard at most ONCE, or snapshots+restores with TransientType) |
|
|
|
let horizontalSpaceSet = CharacterSet(charactersIn: " \t") |
|
|
|
let hasLeadingSpace = finalOutput.unicodeScalars.first.map { horizontalSpaceSet.contains($0) } ?? false |
|
|
|
let hasTrailingSpace = finalOutput.unicodeScalars.last.map { horizontalSpaceSet.contains($0) } ?? false |
|
|
|
let core = finalOutput.trimmingCharacters(in: horizontalSpaceSet) |
|
|
|
|
|
|
|
guard !finalPairs.isEmpty else { |
|
|
|
restoreClipboardFullText() |
|
|
|
if core.isEmpty { |
|
|
|
if hasLeadingSpace || hasTrailingSpace { |
|
|
|
self.typeUnicodeSynchronously(" ") |
|
|
|
} |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
let wordsMatch: (String, String) -> Bool = { w1, w2 in |
|
|
|
if w1 == w2 { return true } |
|
|
|
if w1.count >= 2 && w2.count >= 2 { |
|
|
|
if w1.hasPrefix(w2) || w2.hasPrefix(w1) { return true } |
|
|
|
} |
|
|
|
return false |
|
|
|
if hasLeadingSpace { |
|
|
|
self.typeUnicodeSynchronously(" ") |
|
|
|
} |
|
|
|
|
|
|
|
var unstreamedPairIndex: Int? = nil |
|
|
|
ClipboardGuard.shared.writeForAtomicPaste(textToPaste: core, cleanFinalText: trimmed) |
|
|
|
self.postCleanCmdV() |
|
|
|
usleep(25000) |
|
|
|
|
|
|
|
// Strategy 4A: 3-word tail anchor |
|
|
|
if streamedPairs.count >= 3 { |
|
|
|
let a1 = streamedPairs[streamedPairs.count - 3].norm |
|
|
|
let a2 = streamedPairs[streamedPairs.count - 2].norm |
|
|
|
let a3 = streamedPairs[streamedPairs.count - 1].norm |
|
|
|
for j in stride(from: finalPairs.count - 1, through: 2, by: -1) { |
|
|
|
if wordsMatch(finalPairs[j].norm, a3) && wordsMatch(finalPairs[j - 1].norm, a2) && wordsMatch(finalPairs[j - 2].norm, a1) { |
|
|
|
unstreamedPairIndex = j + 1 |
|
|
|
break |
|
|
|
} |
|
|
|
} |
|
|
|
if hasTrailingSpace { |
|
|
|
self.typeUnicodeSynchronously(" ") |
|
|
|
} |
|
|
|
|
|
|
|
// Strategy 4B: 2-word tail anchor |
|
|
|
if unstreamedPairIndex == nil && streamedPairs.count >= 2 { |
|
|
|
let a1 = streamedPairs[streamedPairs.count - 2].norm |
|
|
|
let a2 = streamedPairs[streamedPairs.count - 1].norm |
|
|
|
for j in stride(from: finalPairs.count - 1, through: 1, by: -1) { |
|
|
|
if wordsMatch(finalPairs[j].norm, a2) && wordsMatch(finalPairs[j - 1].norm, a1) { |
|
|
|
unstreamedPairIndex = j + 1 |
|
|
|
break |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
/// Types arbitrary Unicode text (Persian, ZWNJ, English, Arabic, emoji, multiline) directly via Quartz CGEvent |
|
|
|
/// with `flags = []` so held hardware modifiers (Option/Fn/Control) never corrupt output and NSPasteboard is untouched. |
|
|
|
private func typeUnicodeSynchronously(_ text: String) { |
|
|
|
guard !text.isEmpty else { return } |
|
|
|
let src = CGEventSource(stateID: .privateState) |
|
|
|
|
|
|
|
let segments = text.components(separatedBy: "\n") |
|
|
|
for (segIdx, segment) in segments.enumerated() { |
|
|
|
if !segment.isEmpty { |
|
|
|
let utf16 = Array(segment.utf16) |
|
|
|
var idx = 0 |
|
|
|
let maxChunk = 16 |
|
|
|
while idx < utf16.count { |
|
|
|
var end = min(idx + maxChunk, utf16.count) |
|
|
|
// Never split a UTF-16 high/low surrogate pair across two CGEvents |
|
|
|
if end < utf16.count && (0xD800...0xDBFF).contains(utf16[end - 1]) { |
|
|
|
end -= 1 |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
// Strategy 4C: 1-word tail anchor |
|
|
|
if unstreamedPairIndex == nil && !streamedPairs.isEmpty { |
|
|
|
let a1 = streamedPairs[streamedPairs.count - 1].norm |
|
|
|
let searchStart = max(0, finalPairs.count - max(15, streamedPairs.count)) |
|
|
|
for j in stride(from: finalPairs.count - 1, through: searchStart, by: -1) { |
|
|
|
if wordsMatch(finalPairs[j].norm, a1) { |
|
|
|
unstreamedPairIndex = j + 1 |
|
|
|
break |
|
|
|
let slice = Array(utf16[idx..<end]) |
|
|
|
if let down = CGEvent(keyboardEventSource: src, virtualKey: 0, keyDown: true), |
|
|
|
let up = CGEvent(keyboardEventSource: src, virtualKey: 0, keyDown: false) { |
|
|
|
down.flags = [] |
|
|
|
up.flags = [] |
|
|
|
slice.withUnsafeBufferPointer { buf in |
|
|
|
guard let base = buf.baseAddress else { return } |
|
|
|
down.keyboardSetUnicodeString(stringLength: buf.count, unicodeString: base) |
|
|
|
up.keyboardSetUnicodeString(stringLength: buf.count, unicodeString: base) |
|
|
|
} |
|
|
|
down.post(tap: .cgAnnotatedSessionEventTap) |
|
|
|
up.post(tap: .cgAnnotatedSessionEventTap) |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
// Strategy 4D: Forward prefix match fallback |
|
|
|
if unstreamedPairIndex == nil { |
|
|
|
var prefixMatchCount = 0 |
|
|
|
for i in 0..<min(streamedPairs.count, finalPairs.count) { |
|
|
|
if wordsMatch(streamedPairs[i].norm, finalPairs[i].norm) { |
|
|
|
prefixMatchCount = i + 1 |
|
|
|
} else { |
|
|
|
break |
|
|
|
idx = end |
|
|
|
if idx < utf16.count { |
|
|
|
usleep(2200) |
|
|
|
} |
|
|
|
} |
|
|
|
if prefixMatchCount > 0 { |
|
|
|
unstreamedPairIndex = prefixMatchCount |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
// Guaranteed Safety Fallback: aligned 1-to-1 on content-bearing pairs |
|
|
|
if unstreamedPairIndex == nil { |
|
|
|
unstreamedPairIndex = min(streamedPairs.count, finalPairs.count) |
|
|
|
if segIdx < segments.count - 1 { |
|
|
|
// Emit Shift+Return so multiline blocks (/steer\n..., "خط بعد") insert a clean line break |
|
|
|
// without prematurely submitting chat messages in Telegram, Slack, Hermes, or browsers! |
|
|
|
postShiftReturn(src: src) |
|
|
|
usleep(4000) |
|
|
|
} |
|
|
|
|
|
|
|
if let startIndex = unstreamedPairIndex { |
|
|
|
if startIndex < finalPairs.count { |
|
|
|
let remainingWords = finalPairs.dropFirst(startIndex).map { $0.raw } |
|
|
|
let suffix = remainingWords.joined(separator: " ") |
|
|
|
let leadingSpace = streamedEndedWithSpace ? "" : " " |
|
|
|
let trailingSpace = addTrailingSpace ? " " : "" |
|
|
|
let suffixToPaste = leadingSpace + suffix + trailingSpace |
|
|
|
self.pasteSynchronously(suffixToPaste) |
|
|
|
restoreClipboardFullText() |
|
|
|
return |
|
|
|
} else { |
|
|
|
if addTrailingSpace && !streamedEndedWithSpace { |
|
|
|
self.pasteSynchronously(" ") |
|
|
|
} |
|
|
|
restoreClipboardFullText() |
|
|
|
return |
|
|
|
} |
|
|
|
} |
|
|
|
restoreClipboardFullText() |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
/// Places core word(s) on NSPasteboard via Cmd+V, while injecting leading/trailing spaces |
|
|
|
/// via native Space keystrokes so apps that `.trim()` pasted clipboard text (like Hermes Desktop) |
|
|
|
/// never glue words together or double-space! |
|
|
|
private func pasteSynchronously(_ text: String) { |
|
|
|
guard !text.isEmpty else { return } |
|
|
|
let horizontalSpaceSet = CharacterSet(charactersIn: " \t") |
|
|
|
let hasLeadingSpace = text.unicodeScalars.first.map { horizontalSpaceSet.contains($0) } ?? false |
|
|
|
let hasTrailingSpace = text.unicodeScalars.last.map { horizontalSpaceSet.contains($0) } ?? false |
|
|
|
let core = text.trimmingCharacters(in: horizontalSpaceSet) |
|
|
|
|
|
|
|
if core.isEmpty { |
|
|
|
if hasLeadingSpace || hasTrailingSpace { |
|
|
|
postCleanSpace() |
|
|
|
usleep(12000) |
|
|
|
private func postBackspaces(_ count: Int) { |
|
|
|
guard count > 0 else { return } |
|
|
|
let src = CGEventSource(stateID: .privateState) |
|
|
|
let deleteKeyCode: CGKeyCode = 0x33 // kVK_Delete |
|
|
|
for i in 0..<count { |
|
|
|
if let down = CGEvent(keyboardEventSource: src, virtualKey: deleteKeyCode, keyDown: true), |
|
|
|
let up = CGEvent(keyboardEventSource: src, virtualKey: deleteKeyCode, keyDown: false) { |
|
|
|
down.flags = [] // Explicit empty flags prevents Option+Delete deleting whole words! |
|
|
|
up.flags = [] |
|
|
|
down.post(tap: .cgAnnotatedSessionEventTap) |
|
|
|
up.post(tap: .cgAnnotatedSessionEventTap) |
|
|
|
} |
|
|
|
if (i + 1) % 8 == 0 { |
|
|
|
usleep(2000) |
|
|
|
} else { |
|
|
|
usleep(700) |
|
|
|
} |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
if hasLeadingSpace { |
|
|
|
postCleanSpace() |
|
|
|
usleep(12000) |
|
|
|
} |
|
|
|
|
|
|
|
let pb = NSPasteboard.general |
|
|
|
pb.clearContents() |
|
|
|
pb.setString(core, forType: .string) |
|
|
|
postCleanCmdV() |
|
|
|
usleep(22000) // 22ms guard ensures browser/app reads NSPasteboard before next chunk overwrites it (~45 chunks/sec capacity) |
|
|
|
|
|
|
|
if hasTrailingSpace { |
|
|
|
postCleanSpace() |
|
|
|
usleep(12000) |
|
|
|
} |
|
|
|
|
|
|
|
private func postShiftReturn(src: CGEventSource?) { |
|
|
|
let returnKeyCode: CGKeyCode = 0x24 // kVK_Return |
|
|
|
if let down = CGEvent(keyboardEventSource: src, virtualKey: returnKeyCode, keyDown: true), |
|
|
|
let up = CGEvent(keyboardEventSource: src, virtualKey: returnKeyCode, keyDown: false) { |
|
|
|
down.flags = .maskShift |
|
|
|
up.flags = .maskShift |
|
|
|
down.post(tap: .cgAnnotatedSessionEventTap) |
|
|
|
up.post(tap: .cgAnnotatedSessionEventTap) |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
@ -445,20 +425,4 @@ public final class InputBoxManager { |
|
|
|
up.post(tap: .cgAnnotatedSessionEventTap) |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
private func postCleanSpace() { |
|
|
|
let src = CGEventSource(stateID: .privateState) |
|
|
|
let spaceKeyCode: CGKeyCode = 0x31 // ' ' (kVK_Space) |
|
|
|
var spaceChar: UniChar = 0x0020 |
|
|
|
|
|
|
|
if let down = CGEvent(keyboardEventSource: src, virtualKey: spaceKeyCode, keyDown: true), |
|
|
|
let up = CGEvent(keyboardEventSource: src, virtualKey: spaceKeyCode, keyDown: false) { |
|
|
|
down.flags = [] |
|
|
|
up.flags = [] |
|
|
|
down.keyboardSetUnicodeString(stringLength: 1, unicodeString: &spaceChar) |
|
|
|
up.keyboardSetUnicodeString(stringLength: 1, unicodeString: &spaceChar) |
|
|
|
down.post(tap: .cgAnnotatedSessionEventTap) |
|
|
|
up.post(tap: .cgAnnotatedSessionEventTap) |
|
|
|
} |
|
|
|
} |
|
|
|
} |