fix: allow recording outside protected fields
This commit is contained in:
@@ -313,7 +313,14 @@ public final class DictationController {
|
||||
hotkeys.isRecordingActive = { [weak self] in self?.isRecording ?? false }
|
||||
hotkeys.canStartRecording = { [weak self] in
|
||||
guard let self else { return false }
|
||||
return self.startRefusal() == nil
|
||||
// Только предварительный допуск по состоянию. AX не вызывается
|
||||
// внутри event tap: полная проверка идёт в handlePress, до микрофона,
|
||||
// после dispatchHotkeyActions на главный актор.
|
||||
return dictationStartRefusal(modelReady: self.modelReady,
|
||||
isRecording: self.isRecording,
|
||||
isBusy: self.isBusy,
|
||||
secureInputActive: false,
|
||||
modelWarming: self.modelWarming) == nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -645,7 +652,8 @@ public final class DictationController {
|
||||
isRecording: isRecording,
|
||||
isBusy: isBusy,
|
||||
secureInputActive: Permissions.isSecureInputActive,
|
||||
modelWarming: modelWarming)
|
||||
modelWarming: modelWarming,
|
||||
focusedInputProtected: Permissions.focusedInputProtection)
|
||||
}
|
||||
|
||||
/// Смена аудиоустройства посреди записи: крючок AudioCapture до этого
|
||||
|
||||
@@ -171,8 +171,8 @@ let dictationWarmUpWaitLimitSeconds: Double = 180
|
||||
|
||||
// MARK: - Отказ старта записи
|
||||
|
||||
/// Почему запись не стартует. `secureInputActive` — новый класс отказа:
|
||||
/// в поле пароля синтетический ⌘V не дойдёт всё равно, честнее сказать сразу.
|
||||
/// Почему запись не стартует. Защита относится к текущему полю, а не к
|
||||
/// наличию фонового процесса с защищённым вводом клавиатуры.
|
||||
enum DictationStartRefusal: String, Equatable {
|
||||
case secureInputActive
|
||||
case modelNotReady
|
||||
@@ -180,6 +180,12 @@ enum DictationStartRefusal: String, Equatable {
|
||||
case transcriptionInFlight
|
||||
}
|
||||
|
||||
/// Неизвестное поле при активной системной защите не считается обычным.
|
||||
func dictationInputIsProtected(secureInputActive: Bool,
|
||||
focusedInputProtected: Bool?) -> Bool {
|
||||
focusedInputProtected ?? secureInputActive
|
||||
}
|
||||
|
||||
/// Отказать ли старту.
|
||||
///
|
||||
/// `modelWarming` отделяет «модель ещё грузится» от «модели нет». Разница
|
||||
@@ -195,8 +201,12 @@ func dictationStartRefusal(modelReady: Bool,
|
||||
isRecording: Bool,
|
||||
isBusy: Bool,
|
||||
secureInputActive: Bool,
|
||||
modelWarming: Bool = false) -> DictationStartRefusal? {
|
||||
if secureInputActive { return .secureInputActive }
|
||||
modelWarming: Bool = false,
|
||||
focusedInputProtected: Bool? = nil) -> DictationStartRefusal? {
|
||||
if dictationInputIsProtected(secureInputActive: secureInputActive,
|
||||
focusedInputProtected: focusedInputProtected) {
|
||||
return .secureInputActive
|
||||
}
|
||||
if !modelReady, !modelWarming { return .modelNotReady }
|
||||
if isRecording { return .alreadyRecording }
|
||||
if isBusy { return .transcriptionInFlight }
|
||||
|
||||
@@ -98,12 +98,17 @@ func dictationLearningReadFocusedText() -> (text: String, pid: pid_t)? {
|
||||
guard let app = NSWorkspace.shared.frontmostApplication else { return nil }
|
||||
let pid = app.processIdentifier
|
||||
let axApp = AXUIElementCreateApplication(pid)
|
||||
AXUIElementSetMessagingTimeout(axApp, 0.15)
|
||||
|
||||
var focusedRaw: AnyObject?
|
||||
guard AXUIElementCopyAttributeValue(axApp, kAXFocusedUIElementAttribute as CFString,
|
||||
&focusedRaw) == .success,
|
||||
let focused = focusedRaw else { return nil }
|
||||
let focused = focusedRaw,
|
||||
CFGetTypeID(focused) == AXUIElementGetTypeID() else { return nil }
|
||||
let element = focused as! AXUIElement
|
||||
// Проверяем именно этот элемент до AXValue. Неизвестное состояние —
|
||||
// тоже отказ: для обучения читать потенциально защищённый текст незачем.
|
||||
guard Permissions.inputProtection(of: element) == false else { return nil }
|
||||
|
||||
var roleRaw: AnyObject?
|
||||
AXUIElementCopyAttributeValue(element, kAXRoleAttribute as CFString, &roleRaw)
|
||||
|
||||
@@ -160,7 +160,8 @@ struct HotkeyTransitionState {
|
||||
|
||||
/// `canStartRecording` mirrors the app-side guard on handlePress
|
||||
/// (ready, not recording, not busy, not terminating). Toggle mode
|
||||
/// consults it before claiming either recording route.
|
||||
/// consults it only before claiming a recording route. Ordinary keyboard
|
||||
/// events must not trigger the app's potentially expensive AX query.
|
||||
mutating func transition(
|
||||
for event: HotkeyEventSnapshot,
|
||||
hotkey: HotkeyChoice,
|
||||
@@ -177,7 +178,7 @@ struct HotkeyTransitionState {
|
||||
translationHotkeyEnabled: Bool = false,
|
||||
triggerMode: TriggerMode,
|
||||
isRecording: Bool,
|
||||
canStartRecording: Bool = true
|
||||
canStartRecording: @autoclosure () -> Bool = true
|
||||
) -> HotkeyTransitionResult {
|
||||
if event.keycode == ESCAPE_KEYCODE {
|
||||
return transitionEscape(for: event, isRecording: isRecording)
|
||||
@@ -278,7 +279,7 @@ struct HotkeyTransitionState {
|
||||
// in toggle mode because the state machine gates it here.
|
||||
guard !isRecording,
|
||||
activeRecordingRoute == nil,
|
||||
canStartRecording else {
|
||||
canStartRecording() else {
|
||||
return HotkeyTransitionResult(suppress: shortcutResult.suppress,
|
||||
actions: [.rejectedBusyPress])
|
||||
}
|
||||
@@ -291,7 +292,7 @@ struct HotkeyTransitionState {
|
||||
private mutating func transitionPromptShortcut(
|
||||
for event: HotkeyEventSnapshot,
|
||||
isRecording: Bool,
|
||||
canStartRecording: Bool,
|
||||
canStartRecording: () -> Bool,
|
||||
promptHotkey: HotkeyChoice,
|
||||
triggerMode: TriggerMode
|
||||
) -> HotkeyTransitionResult? {
|
||||
@@ -338,7 +339,7 @@ struct HotkeyTransitionState {
|
||||
}
|
||||
guard !isRecording,
|
||||
activeRecordingRoute == nil,
|
||||
canStartRecording else {
|
||||
canStartRecording() else {
|
||||
return HotkeyTransitionResult(suppress: shortcutResult.suppress,
|
||||
actions: [.rejectedBusyPress])
|
||||
}
|
||||
@@ -352,7 +353,7 @@ struct HotkeyTransitionState {
|
||||
private mutating func transitionTranslationShortcut(
|
||||
for event: HotkeyEventSnapshot,
|
||||
isRecording: Bool,
|
||||
canStartRecording: Bool,
|
||||
canStartRecording: () -> Bool,
|
||||
translationHotkey: HotkeyChoice,
|
||||
triggerMode: TriggerMode
|
||||
) -> HotkeyTransitionResult? {
|
||||
@@ -399,7 +400,7 @@ struct HotkeyTransitionState {
|
||||
}
|
||||
guard !isRecording,
|
||||
activeRecordingRoute == nil,
|
||||
canStartRecording else {
|
||||
canStartRecording() else {
|
||||
return HotkeyTransitionResult(suppress: shortcutResult.suppress,
|
||||
actions: [.rejectedBusyPress])
|
||||
}
|
||||
|
||||
@@ -26,14 +26,57 @@ enum Permissions {
|
||||
}
|
||||
}
|
||||
|
||||
/// Активен ли защищённый ввод — поле пароля, Secure Keyboard Entry в
|
||||
/// терминале. Тот же системный вызов, что у AutoSwitchPolicy в IrizInput
|
||||
/// (тянуть IrizInput в IrizDictate не за чем — API системное).
|
||||
///
|
||||
/// Для диктовки это честный класс провала вставки: в защищённое поле
|
||||
/// синтетический ⌘V не дойдёт всё равно, а сырьё уже легло бы на диск.
|
||||
/// Глобальная защита клавиатурных событий: её может держать фоновый
|
||||
/// процесс. Сама по себе она не описывает поле в фокусе и не запрещает микрофон.
|
||||
static var isSecureInputActive: Bool { IsSecureEventInputEnabled() }
|
||||
|
||||
static var isDictationInputProtected: Bool {
|
||||
dictationInputIsProtected(secureInputActive: isSecureInputActive,
|
||||
focusedInputProtected: focusedInputProtection)
|
||||
}
|
||||
|
||||
/// Только метаданные текущего элемента; содержимое поля не запрашивается.
|
||||
/// Неизвестное состояние сохраняется как nil для осторожного fallback.
|
||||
static var focusedInputProtection: Bool? {
|
||||
guard let app = NSWorkspace.shared.frontmostApplication else { return nil }
|
||||
let axApp = AXUIElementCreateApplication(app.processIdentifier)
|
||||
AXUIElementSetMessagingTimeout(axApp, 0.15)
|
||||
var focused: CFTypeRef?
|
||||
guard AXUIElementCopyAttributeValue(axApp, kAXFocusedUIElementAttribute as CFString,
|
||||
&focused) == .success,
|
||||
let focused, CFGetTypeID(focused) == AXUIElementGetTypeID() else { return nil }
|
||||
return inputProtection(of: focused as! AXUIElement)
|
||||
}
|
||||
|
||||
static func inputProtection(of element: AXUIElement) -> Bool? {
|
||||
AXUIElementSetMessagingTimeout(element, 0.15)
|
||||
return inputProtection { attribute in
|
||||
var value: CFTypeRef?
|
||||
let error = AXUIElementCopyAttributeValue(element, attribute, &value)
|
||||
return (error, value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Тот же путь чтения в продукте и в пробе: проба не касается чужого окна.
|
||||
static func inputProtection(readAttribute: (CFString) -> (AXError, CFTypeRef?)) -> Bool? {
|
||||
let (roleError, roleValue) = readAttribute(kAXRoleAttribute as CFString)
|
||||
let (subroleError, subroleValue) = readAttribute(kAXSubroleAttribute as CFString)
|
||||
if subroleError == .success, subroleValue as? String == kAXSecureTextFieldSubrole { return true }
|
||||
let (protectedError, protectedValue) = readAttribute(
|
||||
NSAccessibility.Attribute.containsProtectedContent.rawValue as CFString)
|
||||
if protectedError == .success, protectedValue as? Bool == true { return true }
|
||||
|
||||
// Необязательного атрибута может не быть у обычного поля/окна.
|
||||
// Таймаут и ошибка связи отсутствием атрибута не считаются.
|
||||
// Явная защита выше ошибки роли: её нельзя потерять при частичном ответе AX.
|
||||
guard roleError == .success, let role = roleValue as? String, !role.isEmpty else { return nil }
|
||||
let optionalAbsent: [AXError] = [.attributeUnsupported, .noValue]
|
||||
guard (subroleError == .success && subroleValue is String) || optionalAbsent.contains(subroleError),
|
||||
(protectedError == .success && protectedValue is Bool) || optionalAbsent.contains(protectedError)
|
||||
else { return nil }
|
||||
return false
|
||||
}
|
||||
|
||||
/// Trigger the system prompt or, if previously denied, push the
|
||||
/// user toward the right Settings pane. Returns immediately;
|
||||
/// actual grant happens asynchronously.
|
||||
|
||||
@@ -103,7 +103,8 @@ func postKeyboardEventSteps(_ steps: [KeyboardEventStep], targetPID: pid_t? = ni
|
||||
enum KeyboardShortcutPoster {
|
||||
@discardableResult
|
||||
static func postReturn() -> Bool {
|
||||
postKeyboardEventSteps([
|
||||
guard TextInserter.targetAllowsPosting(nil) else { return false }
|
||||
return postKeyboardEventSteps([
|
||||
KeyboardEventStep(virtualKey: RETURN_KEYCODE, keyDown: true, flags: []),
|
||||
KeyboardEventStep(virtualKey: RETURN_KEYCODE, keyDown: false, flags: []),
|
||||
])
|
||||
@@ -188,10 +189,13 @@ enum TextInserter {
|
||||
}
|
||||
|
||||
fileprivate static func targetAllowsPosting(_ expectedTargetPID: pid_t?) -> Bool {
|
||||
textInsertionTargetAllowsPosting(
|
||||
guard let checkedPID = NSWorkspace.shared.frontmostApplication?.processIdentifier,
|
||||
textInsertionTargetAllowsPosting(
|
||||
expectedTargetPID: expectedTargetPID,
|
||||
currentTargetPID: NSWorkspace.shared.frontmostApplication?.processIdentifier
|
||||
)
|
||||
currentTargetPID: checkedPID
|
||||
), !Permissions.isDictationInputProtected else { return false }
|
||||
// AX — IPC: за время проверки фокус мог перейти к другому приложению.
|
||||
return NSWorkspace.shared.frontmostApplication?.processIdentifier == checkedPID
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user