diff --git a/Sources/Hushtype/DictationController.swift b/Sources/Hushtype/DictationController.swift index 63e61e7..c342774 100644 --- a/Sources/Hushtype/DictationController.swift +++ b/Sources/Hushtype/DictationController.swift @@ -1,6 +1,7 @@ import AppKit import Carbon.HIToolbox import HushtypeCore +import os /// Runs one dictation at a time: hold key → record and transcribe live → polish → paste. @MainActor @@ -365,55 +366,142 @@ final class DictationController: ObservableObject { if let reason = result.fallbackReason { show(notice: reason) } if let field = target?.field, let location = target?.context.selectionLocation { watchForCorrections(PendingCorrection(field: field, location: location, inserted: result.text)) + } else if settings.learnFromCorrections { + learningLog.info("No text field to watch for corrections in \(target?.context.appName ?? "this app", privacy: .public)") } } // MARK: - Learning from corrections struct PendingCorrection: Sendable { + let id = UUID() let field: FocusedField let location: Int let inserted: String } + /// How long after a paste Hushtype keeps an eye on the field. + private static let correctionWatchSeconds = 90.0 + private let learningLog = Logger(subsystem: "app.hushtype.Hushtype", category: "learning") + private let returnKeyTap = ReturnKeyTap() private var pendingCorrection: PendingCorrection? private var correctionTask: Task? - - /// Re-reads the field a few times after pasting. If the user respelled a word Hushtype typed, - /// the new spelling joins the dictionary. + /// Fixes in the latest settled read of the field, learned when the watch ends. + private var correctionCandidate: [CorrectionLearner.Correction] = [] + /// The previous poll, so a read only counts once the field has held still for a second. + private var lastCorrectionRead: String? + private var failedCorrectionReads = 0 + + /// Follows the field after pasting, so a word the user respells joins the dictionary. It reads + /// the field every second, and right as Return goes down: chat apps send and clear the text on + /// Return, often a moment after the fix. The fixes are learned once the text is gone, when the + /// next dictation starts, or after a minute and a half. private func watchForCorrections(_ pending: PendingCorrection) { - correctionTask?.cancel() + stopWatchingForCorrections() guard settings.learnFromCorrections else { return } pendingCorrection = pending + correctionCandidate = [] + lastCorrectionRead = nil + failedCorrectionReads = 0 + learningLog.info("Watching \(pending.inserted.count) characters at \(pending.location) for corrections") + + returnKeyTap.start(read: { Self.readCorrectionWindow(pending) }) { [weak self] window in + Task { @MainActor in self?.considerCorrectionRead(window, of: pending, settled: true, source: "Return") } + } correctionTask = Task { [weak self] in - for delay in [8, 20, 45] { - try? await Task.sleep(for: .seconds(delay)) + let deadline = Date().addingTimeInterval(Self.correctionWatchSeconds) + while Date() < deadline { + try? await Task.sleep(for: .seconds(1)) guard !Task.isCancelled else { return } - await self?.checkForCorrections(pending) + let window = await Task.detached(priority: .utility) { Self.readCorrectionWindow(pending) }.value + guard !Task.isCancelled, let self else { return } + if !self.considerCorrectionRead(window, of: pending, settled: false, source: "poll") { + // The text is gone. A Return read may still be on its way to the main actor. + try? await Task.sleep(for: .milliseconds(300)) + guard !Task.isCancelled else { return } + break + } } + self?.finishWatchingForCorrections(readAgain: false) } } - /// Checks once more, then stops watching. Called when the next dictation starts. - private func finishWatchingForCorrections() { + /// Reads the stretch of the field around the dictation. Runs off the main thread. + nonisolated private static func readCorrectionWindow(_ pending: PendingCorrection) -> String? { + let length = (pending.inserted as NSString).length + let start = max(0, pending.location - 60) + var range = NSRange(location: start, length: pending.location - start + length + 120) + if let count = pending.field.characterCount { + // Asking past the end fails in most apps. + range.length = max(0, min(range.length, count - start)) + } + return pending.field.text(in: range) + } + + /// Takes in one read of the field. Returns false once the dictation is no longer there. + @discardableResult + private func considerCorrectionRead(_ window: String?, of pending: PendingCorrection, + settled: Bool, source: String) -> Bool { + guard pendingCorrection?.id == pending.id else { return false } + guard let window else { + failedCorrectionReads += 1 + learningLog.info("Couldn't read the field (\(source, privacy: .public))") + // The field went away, like a chat box replaced after sending. + return failedCorrectionReads < 3 + } + failedCorrectionReads = 0 + let analysis = CorrectionLearner.analyze(inserted: pending.inserted, edited: window) + guard analysis.isPresent else { + learningLog.info("Dictation no longer in the field (\(source, privacy: .public))") + return false + } + // A poll mid-word could catch half a fix, so it only counts once the field held still. + let counts = settled || window == lastCorrectionRead + if counts { correctionCandidate = analysis.corrections } + lastCorrectionRead = window + if !analysis.corrections.isEmpty { + learningLog.info("Read \(analysis.corrections.count) fix(es) (\(source, privacy: .public), counted: \(counts))") + } + return true + } + + private func stopWatchingForCorrections() { correctionTask?.cancel() correctionTask = nil - guard let pending = pendingCorrection else { return } + returnKeyTap.stop() + pendingCorrection = nil + } + + /// Learns what the watch found and stops watching. Called when the next dictation starts + /// (after one last look, off the main thread) and when the watch runs out or the text is gone. + private func finishWatchingForCorrections(readAgain: Bool = true) { + guard let pending = pendingCorrection else { return stopWatchingForCorrections() } + correctionTask?.cancel() + correctionTask = nil + returnKeyTap.stop() + guard readAgain else { return concludeWatch(pending) } + Task { [weak self] in + let window = await Task.detached(priority: .utility) { Self.readCorrectionWindow(pending) }.value + self?.considerCorrectionRead(window, of: pending, settled: true, source: "final") + self?.concludeWatch(pending) + } + } + + private func concludeWatch(_ pending: PendingCorrection) { + guard pendingCorrection?.id == pending.id else { return } + let corrections = correctionCandidate pendingCorrection = nil - Task { await checkForCorrections(pending) } + correctionCandidate = [] + lastCorrectionRead = nil + learn(from: corrections) } - private func checkForCorrections(_ pending: PendingCorrection) async { - let corrections = await Task.detached(priority: .utility) { () -> [CorrectionLearner.Correction] in - let length = (pending.inserted as NSString).length - let start = max(0, pending.location - 60) - guard let window = pending.field.text(in: NSRange(location: start, length: pending.location - start + length + 120)) - else { return [] } - return CorrectionLearner.corrections(inserted: pending.inserted, edited: window) - }.value + private func learn(from corrections: [CorrectionLearner.Correction]) { let known = Set(settings.vocabulary.map { $0.lowercased() }) let learned = corrections.filter { Self.worthLearning($0, known: known) }.map(\.to) + learningLog.info("Watch ended: \(corrections.count) fix(es), \(learned.count) worth learning") guard !learned.isEmpty else { return } + learningLog.info("Learned \(learned.joined(separator: ", "), privacy: .private)") settings.addToDictionary(learned) if phase == .idle || isNotice { let names = learned.map { "“\($0)”" }.joined(separator: ", ") diff --git a/Sources/Hushtype/ReturnKeyTap.swift b/Sources/Hushtype/ReturnKeyTap.swift new file mode 100644 index 0000000..82a6859 --- /dev/null +++ b/Sources/Hushtype/ReturnKeyTap.swift @@ -0,0 +1,90 @@ +import CoreGraphics +import Foundation + +/// While Hushtype watches a dictation for corrections, reads the field the instant Return goes +/// down. Chat apps send and clear the message on Return, so any later look finds an empty box and +/// misses the word the user just fixed. This is an active tap, so macOS holds the Return until the +/// read is done (a fraction of a second at most, and only while watching). It runs on its own +/// thread so a busy main thread never slows typing, and it's switched off the rest of the time. +final class ReturnKeyTap: @unchecked Sendable { + typealias Reader = @Sendable () -> String? + typealias Handler = @Sendable (String?) -> Void + + private let lock = NSLock() + private var reader: Reader? + private var handler: Handler? + private var tap: CFMachPort? + private var thread: Thread? + + /// Calls `read` on every Return until `stop()`, and passes each result to `onRead` on the + /// tap's thread. + func start(read: @escaping Reader, onRead: @escaping Handler) { + let tap = lock.withLock { () -> CFMachPort? in + reader = read + handler = onRead + return self.tap + } + if let tap { + CGEvent.tapEnable(tap: tap, enable: true) + } else if thread == nil { + launch() + } + } + + func stop() { + let tap = lock.withLock { () -> CFMachPort? in + reader = nil + handler = nil + return self.tap + } + if let tap { CGEvent.tapEnable(tap: tap, enable: false) } + } + + private func launch() { + let thread = Thread { [self] in run() } + thread.name = "Hushtype Return key" + thread.qualityOfService = .userInteractive + self.thread = thread + thread.start() + } + + private func run() { + let refcon = Unmanaged.passUnretained(self).toOpaque() + guard let tap = CGEvent.tapCreate( + tap: .cgSessionEventTap, + place: .headInsertEventTap, + options: .defaultTap, + eventsOfInterest: CGEventMask(1 << CGEventType.keyDown.rawValue), + callback: { _, type, event, refcon in + if let refcon { + Unmanaged.fromOpaque(refcon).takeUnretainedValue().handle(type: type, event: event) + } + return Unmanaged.passUnretained(event) + }, + userInfo: refcon + ) else { return } + let source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0) + CFRunLoopAddSource(CFRunLoopGetCurrent(), source, .commonModes) + let watching = lock.withLock { () -> Bool in + self.tap = tap + return reader != nil + } + CGEvent.tapEnable(tap: tap, enable: watching) + CFRunLoopRun() + } + + private func handle(type: CGEventType, event: CGEvent) { + let (read, onRead, tap) = lock.withLock { (reader, handler, self.tap) } + switch type { + case .tapDisabledByTimeout, .tapDisabledByUserInput: + if read != nil, let tap { CGEvent.tapEnable(tap: tap, enable: true) } + case .keyDown: + let keyCode = event.getIntegerValueField(.keyboardEventKeycode) + // kVK_Return, kVK_ANSI_KeypadEnter + guard keyCode == 36 || keyCode == 76, let read, let onRead else { return } + onRead(read()) + default: + break + } + } +} diff --git a/Sources/HushtypeCore/CorrectionLearner.swift b/Sources/HushtypeCore/CorrectionLearner.swift index 6f328c6..b13da5f 100644 --- a/Sources/HushtypeCore/CorrectionLearner.swift +++ b/Sources/HushtypeCore/CorrectionLearner.swift @@ -13,16 +13,33 @@ public enum CorrectionLearner { public let atSentenceStart: Bool } + /// What one read of the field says about a dictation Hushtype inserted. + public struct Analysis: Equatable, Sendable { + /// Word fixes in the field, as `corrections(inserted:edited:)` finds them. + public let corrections: [Correction] + /// The dictation is still in the field, as typed or with a few words respelled. False once + /// the text is gone (a chat app sent and cleared it) or was rewritten. + public let isPresent: Bool + } + /// Compares what was inserted with the same stretch of the field a little later. /// `edited` may include extra words on either side; they're ignored. /// Returns one-for-one word swaps that look like spelling fixes, not rewrites. public static func corrections(inserted: String, edited: String) -> [Correction] { + analyze(inserted: inserted, edited: edited).corrections + } + + /// Like `corrections(inserted:edited:)`, and also says whether the dictation is still there. + public static func analyze(inserted: String, edited: String) -> Analysis { let old = words(inserted) let new = words(edited) - guard !old.isEmpty, !new.isEmpty, old.count <= 400, new.count <= 600 else { return [] } + guard !old.isEmpty, !new.isEmpty, old.count <= 400, new.count <= 600 else { + return Analysis(corrections: [], isPresent: false) + } var result: [Correction] = [] - for hunk in diff(old.map(\.text), new.map(\.text)) { + let (hunks, matched) = diff(old.map(\.text), new.map(\.text)) + for hunk in hunks { // Only same-length replacements of up to three words: a respelling, not new wording. guard hunk.removed.count == hunk.added.count, hunk.removed.count <= 3 else { continue } for (offset, index) in hunk.removed.enumerated() { @@ -34,7 +51,9 @@ public enum CorrectionLearner { atSentenceStart: target.atSentenceStart)) } } - return result + // At least half the dictated words are still there, unchanged or respelled. + let isPresent = (matched + result.count) * 2 >= old.count + return Analysis(corrections: result, isPresent: isPresent) } /// True when `to` is plausibly the same word spelled differently. @@ -63,8 +82,9 @@ public enum CorrectionLearner { /// Word-level LCS diff of the inserted words `a` against the field's words `b`, returned as runs /// of removed (indexes into `a`) and added (indexes into `b`) words. Words of `b` before and - /// after the inserted stretch are surrounding text and are left out. - static func diff(_ a: [String], _ b: [String]) -> [Hunk] { + /// after the inserted stretch are surrounding text and are left out. Also returns how many + /// words of `a` appear unchanged in `b`. + static func diff(_ a: [String], _ b: [String]) -> (hunks: [Hunk], matched: Int) { let n = a.count, m = b.count var lcs = Array(repeating: Array(repeating: 0, count: m + 1), count: n + 1) for i in stride(from: n - 1, through: 0, by: -1) { @@ -96,7 +116,8 @@ public enum CorrectionLearner { current.removed.append(i); i += 1 } } - guard !current.removed.isEmpty else { return hunks } + let matched = lcs[0][0] + guard !current.removed.isEmpty else { return (hunks, matched) } if matchedAny { // Trailing run: a respelled last word, then surrounding text. hunks.append(Hunk(removed: current.removed, added: Array(current.added.prefix(current.removed.count)))) @@ -107,7 +128,7 @@ public enum CorrectionLearner { // A single inserted word with nothing else to anchor on: pick the closest word. hunks.append(Hunk(removed: [0], added: [best])) } - return hunks + return (hunks, matched) } static func editDistance(_ a: [Character], _ b: [Character]) -> Int { diff --git a/Tests/HushtypeCoreTests/HushtypeCoreTests.swift b/Tests/HushtypeCoreTests/HushtypeCoreTests.swift index 1c65420..9844f05 100644 --- a/Tests/HushtypeCoreTests/HushtypeCoreTests.swift +++ b/Tests/HushtypeCoreTests/HushtypeCoreTests.swift @@ -193,6 +193,27 @@ final class CorrectionLearnerTests: XCTestCase { let found = CorrectionLearner.corrections(inserted: "hushtipe", edited: "try Hushtype now") XCTAssertEqual(found.map(\.to), ["Hushtype"]) } + + func testDictationStillPresentWhileBeingFixed() { + let analysis = CorrectionLearner.analyze(inserted: "Ask shiranjib about the cubernetes rollout.", + edited: "Ask Chiranjeeb about the Kubernetes rollout.") + XCTAssertTrue(analysis.isPresent) + XCTAssertEqual(analysis.corrections.map(\.to), ["Chiranjeeb", "Kubernetes"]) + } + + func testSentMessageIsNoLongerPresent() { + let inserted = "Ask shiranjib about the rollout." + // A chat app cleared the box after Enter, or the next message is being typed. + XCTAssertFalse(CorrectionLearner.analyze(inserted: inserted, edited: "").isPresent) + XCTAssertFalse(CorrectionLearner.analyze(inserted: inserted, edited: "ok thanks").isPresent) + XCTAssertTrue(CorrectionLearner.analyze(inserted: inserted, edited: "ok thanks").corrections.isEmpty) + } + + func testSingleRespelledWordIsPresent() { + let analysis = CorrectionLearner.analyze(inserted: "hushtipe", edited: "Hushtype") + XCTAssertTrue(analysis.isPresent) + XCTAssertEqual(analysis.corrections.map(\.to), ["Hushtype"]) + } } final class SnippetTests: XCTestCase {