fix: improve model setup and native workflows
This commit is contained in:
@@ -519,6 +519,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
private lazy var firstRun: FirstRunWindowController = {
|
||||
let controller = FirstRunWindowController()
|
||||
controller.model.openAgentSettings = { [weak self] in
|
||||
self?.openSettings(page: .prompt)
|
||||
}
|
||||
controller.model.onSpeechModelInstalled = { [weak self] in
|
||||
_ = self?.dictationController.prepareAfterModelInstallation()
|
||||
}
|
||||
// Проба голосом идёт ТЕМ ЖЕ путём, что и обычная диктовка: кнопка
|
||||
// зовёт тот же обработчик, что и клавиша. Иначе знакомство показывало
|
||||
// бы не тот продукт, который человеку достанется.
|
||||
@@ -649,12 +655,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
//
|
||||
// Приглашение НЕ повторяется тем, кто уже прошёл этот путь руками:
|
||||
// решение целиком в firstRunShouldShow.
|
||||
let modelInstalled = speechModelCacheExists(for: DictationSettings.shared.speechEngine)
|
||||
if !interactive,
|
||||
firstRunShouldShow(defaults: .standard,
|
||||
permissionsGranted: acc && inp,
|
||||
modelInstalled: speechModelCacheExists(for: .multilingualV3)) {
|
||||
modelInstalled: modelInstalled) {
|
||||
rslog("First run: showing the welcome window")
|
||||
firstRun.show()
|
||||
if !modelInstalled && UserDefaults.standard.bool(forKey: FIRST_RUN_COMPLETED_KEY) {
|
||||
firstRun.showModelSetup()
|
||||
} else {
|
||||
firstRun.show()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1182,6 +1193,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
/// Окно живёт столько же, сколько приложение: пересоздавать его на каждый показ —
|
||||
/// значит терять несохранённую запись хоткея и позицию окна.
|
||||
private var settingsWindow: NSWindow?
|
||||
private let settingsNavigation = SettingsNavigation()
|
||||
|
||||
/// Открыть знакомство заново из меню.
|
||||
/// Идёт ли запись встречи. Меню спрашивает, чтобы назвать строку словом
|
||||
@@ -1203,7 +1215,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
firstRun.show()
|
||||
}
|
||||
|
||||
func openSettings(page: SettingsPage = .keys) {
|
||||
func showSpeechModelSetup() {
|
||||
firstRun.showModelSetup()
|
||||
}
|
||||
|
||||
func recoverDictation() {
|
||||
if !menuState.microphoneOK {
|
||||
firstRun.showMicrophoneSetup()
|
||||
} else if menuState.dictationRecoveryNeedsPermissions {
|
||||
recheckPermissions()
|
||||
} else {
|
||||
showSpeechModelSetup()
|
||||
}
|
||||
}
|
||||
|
||||
func openSettings(page: SettingsPage? = nil) {
|
||||
if let page { settingsNavigation.page = page }
|
||||
if let window = settingsWindow {
|
||||
NSApplication.shared.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
@@ -1211,7 +1238,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
}
|
||||
// Окно собирает общая фабрика: прибор снимает ровно это окно, а не
|
||||
// свою копию с другими флагами.
|
||||
let window = makeIrizSettingsWindow(page: page)
|
||||
let window = makeIrizSettingsWindow(navigation: settingsNavigation,
|
||||
openSpeechModelSetup: { [weak self] in
|
||||
self?.showSpeechModelSetup()
|
||||
})
|
||||
window.center()
|
||||
settingsWindow = window
|
||||
|
||||
@@ -1238,5 +1268,3 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
NSApplication.shared.terminate(nil)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -9,9 +9,8 @@
|
||||
// следующего переименования кнопки. Здесь кадры собираются из ТЕХ ЖЕ видов,
|
||||
// которыми живёт продукт, и пересобираются одной командой.
|
||||
//
|
||||
// Язык переключается настройкой, той же, которую владелец меняет в окне: другой
|
||||
// дороги нет и быть не должно - прибор обязан снимать то, что увидит человек, а
|
||||
// не свою параллельную сборку строк.
|
||||
// Язык подставляется в штатный поиск настроек через volatile domain: строки
|
||||
// остаются продуктовыми, а пользовательская настройка на диске не меняется.
|
||||
import AppKit
|
||||
import IrizCore
|
||||
import IrizDictate
|
||||
@@ -34,12 +33,15 @@ private struct DocShot {
|
||||
func captureDocShots(to directory: URL, appDelegate: AppDelegate) throws -> [URL] {
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o755])
|
||||
let previous = irizLanguageChoice()
|
||||
defer { setIrizLanguageChoice(previous) }
|
||||
let defaults = UserDefaults.standard
|
||||
let previous = defaults.volatileDomain(forName: UserDefaults.argumentDomain)
|
||||
defer { defaults.setVolatileDomain(previous, forName: UserDefaults.argumentDomain) }
|
||||
|
||||
var written: [URL] = []
|
||||
for language in [IrizLanguage.ru, .en, .zh] {
|
||||
setIrizLanguageChoice(language)
|
||||
var arguments = previous
|
||||
arguments[IRIZ_LANGUAGE_KEY] = language.rawValue
|
||||
defaults.setVolatileDomain(arguments, forName: UserDefaults.argumentDomain)
|
||||
let tag = language.rawValue
|
||||
|
||||
// Настройки: живое окно со стеклом, страница клавиш - её открывают первой.
|
||||
@@ -140,12 +142,38 @@ private func docShots(appDelegate: AppDelegate) -> [DocShot] {
|
||||
view: dictationHistoryShotView(.list)),
|
||||
DocShot(name: "rescue", width: 620, height: 520,
|
||||
view: dictationHistoryShotView(.rescue)),
|
||||
// Знакомство: единственная поверхность, которая переведена целиком.
|
||||
// Остальные пока показывают русский на любом выбранном языке - у них
|
||||
// нет ни одного вызова `L()`, и это честно названо в документации.
|
||||
DocShot(name: "firstrun", width: 620, height: 520,
|
||||
view: AnyView(FirstRunView(model: FirstRunModel()))),
|
||||
] + docFirstRunShots()
|
||||
}
|
||||
|
||||
/// Установка в кадре — заданное состояние, без загрузки, разрешений и записи
|
||||
/// настроек. Размер совпадает с FirstRunView: прежние 620×520 обрезали окно.
|
||||
@MainActor
|
||||
private func docFirstRunShots() -> [DocShot] {
|
||||
let scenes: [(name: String, installed: Bool, phase: SpeechModelInstallPhase?)] = [
|
||||
("firstrun", false, nil),
|
||||
("firstrun-model-missing", false, nil),
|
||||
("firstrun-model-downloading", false, .downloading(0.42)),
|
||||
("firstrun-model-failed", false, .failed(speechModelInstallFailureMessage(for: URLError(.notConnectedToInternet)))),
|
||||
("firstrun-model-ready", true, nil),
|
||||
]
|
||||
return scenes.map { scene in
|
||||
let defaults = UserDefaults(suiteName: "iriz.docshots.\(UUID().uuidString)")!
|
||||
// Registration domain живёт в памяти. NSArgumentDomain общий для
|
||||
// процесса: его замена здесь стирала язык, выбранный съёмкой выше.
|
||||
defaults.register(defaults: [
|
||||
"ru.smltlk.transcriptCorrectionsSeeded": true,
|
||||
"speech_engine_v1": SpeechModelProfile.multilingualV3.rawValue,
|
||||
])
|
||||
let model = FirstRunModel(defaults: defaults,
|
||||
settings: DictationSettings(defaults: defaults),
|
||||
refreshSystemState: false,
|
||||
modelProbe: { _ in scene.installed })
|
||||
model.refreshModelAvailability()
|
||||
if scene.name != "firstrun" { model.showModelSetup() }
|
||||
if let phase = scene.phase { model.installationDidProgress(phase) }
|
||||
return DocShot(name: scene.name, width: 640, height: 560,
|
||||
view: AnyView(FirstRunView(model: model)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Рабочее состояние меню: модель готова, история не пуста. Аварийные состояния
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
// Ничего не выбрать - нормальный исход. Диктовка и раскладка работают без
|
||||
// агента, и шаг об этом говорит прямо, а не намекает.
|
||||
import SwiftUI
|
||||
import IrizCore
|
||||
|
||||
struct FirstRunAgentConnect: View {
|
||||
@ObservedObject var model: FirstRunModel
|
||||
@@ -36,6 +37,15 @@ struct FirstRunAgentConnect: View {
|
||||
}
|
||||
.frame(maxHeight: 150)
|
||||
}
|
||||
if let error = model.agentConnectionError {
|
||||
Text(error)
|
||||
.font(.system(size: 12.5))
|
||||
.multilineTextAlignment(.center)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
.frame(maxWidth: 430)
|
||||
Button(L("firstrun.agentSettings", "Настройки агента…")) { model.openAgentSettings?() }
|
||||
.modifier(FirstRunTrialButtonStyle())
|
||||
}
|
||||
}
|
||||
.onAppear { model.refreshAgents() }
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ final class FirstRunModel: ObservableObject {
|
||||
/// Модель на диске. Читается живьём при каждом обновлении разрешений: она
|
||||
/// могла приехать и до знакомства.
|
||||
@Published private(set) var modelInstalled = false
|
||||
var onSpeechModelInstalled: (() -> Void)?
|
||||
|
||||
/// Агенты, которые уже стоят на этом Маке. Ищутся на диске, а не
|
||||
/// спрашиваются у человека: спросить «где у тебя лежит codex» значит
|
||||
@@ -45,6 +46,8 @@ final class FirstRunModel: ObservableObject {
|
||||
@Published private(set) var agents: [FirstRunAgent] = []
|
||||
/// Кто выбран. nil - никто, и это нормальный исход шага.
|
||||
@Published private(set) var connectedAgentID: String?
|
||||
@Published private(set) var agentConnectionError: String?
|
||||
var openAgentSettings: (() -> Void)?
|
||||
/// Перевод включён. Отдельно от подключения агента: агент нужен обоим
|
||||
/// режимам, но включать их за человека нельзя.
|
||||
@Published private(set) var translationEnabled = false
|
||||
@@ -95,19 +98,68 @@ final class FirstRunModel: ObservableObject {
|
||||
}
|
||||
|
||||
private let defaults: UserDefaults
|
||||
private let settings: DictationSettings
|
||||
private let modelProbe: (SpeechModelProfile) -> Bool
|
||||
private var poll: Timer?
|
||||
/// Что сделать, когда знакомство кончилось.
|
||||
var onFinish: (() -> Void)?
|
||||
|
||||
init(defaults: UserDefaults = .standard) {
|
||||
init(defaults: UserDefaults = .standard,
|
||||
settings: DictationSettings = .shared,
|
||||
refreshSystemState: Bool = true,
|
||||
modelProbe: @escaping (SpeechModelProfile) -> Bool = speechModelCacheExists) {
|
||||
self.defaults = defaults
|
||||
refreshPermissions()
|
||||
refreshHotkeyLabel()
|
||||
refreshTranslationHotkeyLabel()
|
||||
self.settings = settings
|
||||
self.modelProbe = modelProbe
|
||||
if refreshSystemState {
|
||||
refreshPermissions()
|
||||
refreshHotkeyLabel()
|
||||
refreshTranslationHotkeyLabel()
|
||||
}
|
||||
}
|
||||
|
||||
var canGoBack: Bool { firstRunPreviousStep(before: step) != nil }
|
||||
var isLastStep: Bool { firstRunNextStep(after: step) == nil }
|
||||
var selectedSpeechModel: SpeechModelProfile { settings.speechEngine }
|
||||
var selectedSpeechModelTitle: String { selectedSpeechModel.shortName }
|
||||
var modelIsReady: Bool {
|
||||
modelInstalled && (installPhase == nil || installPhase == .finished)
|
||||
}
|
||||
var isInstallingModel: Bool {
|
||||
switch installPhase {
|
||||
case .downloading, .compiling: true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
var modelInstallIsPrimaryAction: Bool {
|
||||
step == .model && !modelIsReady && !isInstallingModel
|
||||
}
|
||||
var nextButtonTitle: String {
|
||||
if isLastStep { return FirstRunCopy.done }
|
||||
if modelInstallIsPrimaryAction {
|
||||
return L("firstrun.model.installLater", "Скачать позже")
|
||||
}
|
||||
return FirstRunCopy.next
|
||||
}
|
||||
|
||||
func refreshModelAvailability() {
|
||||
modelInstalled = modelProbe(settings.speechEngine)
|
||||
}
|
||||
|
||||
func prepareForPresentation() {
|
||||
refreshModelAvailability()
|
||||
if !modelInstalled, defaults.bool(forKey: FIRST_RUN_COMPLETED_KEY) {
|
||||
showModelSetup()
|
||||
}
|
||||
}
|
||||
|
||||
func showModelSetup() {
|
||||
step = .model
|
||||
}
|
||||
|
||||
func showMicrophoneSetup() {
|
||||
step = .microphone
|
||||
}
|
||||
|
||||
func goNext() {
|
||||
guard firstRunCanAdvance(from: step) else { return }
|
||||
@@ -159,22 +211,53 @@ final class FirstRunModel: ObservableObject {
|
||||
/// Начать установку модели. Идёт в фоне: пока она едет, человек проходит
|
||||
/// разрешения, и время не тратится дважды.
|
||||
func installModel() {
|
||||
guard !SpeechModelInstaller.shared.isRunning else { return }
|
||||
guard !SpeechModelInstaller.shared.isRunning else {
|
||||
installationWasRefused(.alreadyRunning)
|
||||
return
|
||||
}
|
||||
installPhase = .downloading(0)
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await SpeechModelInstaller.shared.install(dictating: self.isRecording) { phase in
|
||||
Task { @MainActor in
|
||||
self.installPhase = phase
|
||||
if case .finished = phase { self.modelInstalled = true }
|
||||
}
|
||||
let refusal = await SpeechModelInstaller.shared.install(dictating: self.isRecording) { phase in
|
||||
self.installationDidProgress(phase)
|
||||
}
|
||||
if let refusal { self.installationWasRefused(refusal) }
|
||||
}
|
||||
}
|
||||
|
||||
func installationDidProgress(_ phase: SpeechModelInstallPhase) {
|
||||
if case .finished = phase {
|
||||
installationDidFinish()
|
||||
} else {
|
||||
installPhase = phase
|
||||
}
|
||||
}
|
||||
|
||||
func installationWasRefused(_ refusal: SpeechModelInstallRefusal) {
|
||||
switch refusal {
|
||||
case .alreadyInstalled:
|
||||
installationDidFinish()
|
||||
case .alreadyRunning:
|
||||
installPhase = .failed(L("firstrun.modelAlreadyDownloading", "Модель уже скачивается. Дождись окончания установки."))
|
||||
case .dictationBusy:
|
||||
installPhase = .failed(L("firstrun.modelInstallWhileRecording", "Сначала закончи запись, затем повтори установку модели."))
|
||||
}
|
||||
}
|
||||
|
||||
func installationDidFinish() {
|
||||
guard installPhase != .finished || !modelInstalled || settings.speechEngine != .multilingualV3 else { return }
|
||||
settings.speechEngine = .multilingualV3
|
||||
modelInstalled = true
|
||||
installPhase = .finished
|
||||
NotificationCenter.default.post(name: speechModelDidInstallNotification,
|
||||
object: SpeechModelProfile.multilingualV3)
|
||||
NotificationCenter.default.post(name: DictationController.settingsDidSaveNotification,
|
||||
object: settings)
|
||||
onSpeechModelInstalled?()
|
||||
}
|
||||
|
||||
/// Найти агентов на диске и вспомнить, кто выбран.
|
||||
func refreshAgents() {
|
||||
let settings = DictationSettings.shared
|
||||
agents = PromptAgentCatalog.identifiers.compactMap { id in
|
||||
guard let adapter = PromptAgentCatalog.adapter(id: id, customArguments: []) else { return nil }
|
||||
// Свой CLI без пути искать негде: он и есть «введи путь руками»,
|
||||
@@ -190,19 +273,28 @@ final class FirstRunModel: ObservableObject {
|
||||
/// Подключить агента: выбрать его и включить режим задания. Включение
|
||||
/// сказано вслух на самом шаге - молча уводить речь наружу нельзя.
|
||||
func connectAgent(_ id: String) {
|
||||
let settings = DictationSettings.shared
|
||||
guard let adapter = PromptAgentCatalog.adapter(id: id) else { return }
|
||||
guard !adapter.requiresModel || !settings.promptAgentModel.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
agentConnectionError = Lf("firstrun.agentModelRequired", "Для %@ выбери модель в настройках промпт-режима, затем подключи агента здесь.", adapter.displayName)
|
||||
return
|
||||
}
|
||||
settings.promptAgentID = id
|
||||
settings.promptModeEnabled = true
|
||||
connectedAgentID = id
|
||||
agentConnectionError = nil
|
||||
NotificationCenter.default.post(name: DictationController.settingsDidSaveNotification,
|
||||
object: settings)
|
||||
}
|
||||
|
||||
func enableTranslation() {
|
||||
DictationSettings.shared.translationModeEnabled = true
|
||||
settings.translationModeEnabled = true
|
||||
translationEnabled = true
|
||||
NotificationCenter.default.post(name: DictationController.settingsDidSaveNotification,
|
||||
object: settings)
|
||||
}
|
||||
|
||||
func refreshPermissions() {
|
||||
modelInstalled = speechModelCacheExists(for: .multilingualV3)
|
||||
refreshModelAvailability()
|
||||
refreshAgents()
|
||||
var next: [FirstRunPermission: Bool] = [:]
|
||||
for permission in FirstRunPermission.allCases {
|
||||
@@ -231,7 +323,10 @@ final class FirstRunModel: ObservableObject {
|
||||
|
||||
/// Проба голосом. Идёт тем же путём, что и обычная диктовка.
|
||||
func toggleTrial() {
|
||||
isRecording.toggle()
|
||||
guard modelIsReady else {
|
||||
showModelSetup()
|
||||
return
|
||||
}
|
||||
toggleDictation?()
|
||||
}
|
||||
|
||||
@@ -269,7 +364,18 @@ final class FirstRunWindowController: NSObject, NSWindowDelegate {
|
||||
private var window: NSWindow?
|
||||
let model = FirstRunModel()
|
||||
|
||||
func showModelSetup() {
|
||||
model.showModelSetup()
|
||||
show()
|
||||
}
|
||||
|
||||
func showMicrophoneSetup() {
|
||||
show()
|
||||
model.showMicrophoneSetup()
|
||||
}
|
||||
|
||||
func show() {
|
||||
model.prepareForPresentation()
|
||||
// Пока знакомство открыто, приложение перестаёт быть невидимкой из
|
||||
// строки меню. Без этого у окна нет ни значка в Dock, ни места в
|
||||
// Cmd-Tab: человек уходит в Системные настройки, окно проваливается за
|
||||
|
||||
@@ -29,7 +29,7 @@ enum FirstRunCopy {
|
||||
|
||||
/// Подпись у стрелки. Говорит, ЧТО случится от нажатия, а не «нажмите
|
||||
/// кнопку»: человек и так видит кнопку, ему нужна причина.
|
||||
static var hintModel: String { L("firstrun.hintModel", "нажми сюда, качать примерно пять минут") }
|
||||
static var hintModel: String { L("firstrun.hintModel", "Нажми кнопку ниже. iriz сам скачает и установит модель.") }
|
||||
static var hintMicrophone: String { L("firstrun.hintMicrophone", "нажми сюда") }
|
||||
static var hintAccessibility: String { L("firstrun.hintAccessibility", "нажми сюда, откроются настройки системы") }
|
||||
static var hintInputMonitoring: String { L("firstrun.hintInputMonitoring", "нажми сюда, откроются настройки системы") }
|
||||
@@ -64,7 +64,8 @@ enum FirstRunCopy {
|
||||
title: L("firstrun.welcome.title", "Ты говоришь, я печатаю"),
|
||||
body: L("firstrun.welcome.body", "Нажми клавишу, скажи фразу, нажми еще раз. Текст появится там, где стоял "
|
||||
+ "курсор: в письме, в чате, в терминале."),
|
||||
note: L("firstrun.welcome.note", "Все считается прямо на твоем Маке. Ни звук, ни текст никуда не отправляются.")
|
||||
note: L("firstrun.welcome.note", "Перед первой диктовкой скачаем модель распознавания: следующий шаг покажет кнопку установки. "
|
||||
+ "После этого речь будет распознаваться на твоём Маке, без интернета.")
|
||||
) }
|
||||
|
||||
static var whereItLives: Step { Step(
|
||||
@@ -77,13 +78,14 @@ enum FirstRunCopy {
|
||||
) }
|
||||
|
||||
static var model: Step { Step(
|
||||
title: L("firstrun.model.title", "Скачаем распознавание"),
|
||||
body: L("firstrun.model.body", "Речь я разбираю прямо у тебя на Маке, без интернета. Для этого нужна модель: "
|
||||
+ "полгигабайта, качается один раз."),
|
||||
note: L("firstrun.model.note", "В образе её нет намеренно: модель обновляется чаще, чем сам iriz. "
|
||||
+ "Клади её отдельно: иначе вместе с программой приедет устаревшая.\n\n"
|
||||
+ "Пока она скачивается, продолжай: разрешения можно выдать прямо сейчас."),
|
||||
action: L("firstrun.model.action", "Скачать модель")
|
||||
title: L("firstrun.model.title", "Установи распознавание речи"),
|
||||
body: L("firstrun.model.body", "Без модели диктовка не работает. Кнопка ниже скачает Parakeet, "
|
||||
+ "установит его в нужную папку и выберет для распознавания."),
|
||||
note: L("firstrun.model.note", "Скачается около 500 МБ. Нужны интернет и свободное место на диске. "
|
||||
+ "Скорость зависит от соединения; ход установки появится здесь. "
|
||||
+ "Файлы вручную искать и переносить не нужно.\n\n"
|
||||
+ "Пока модель скачивается, можно перейти к разрешениям. Диктовку попробуем после установки."),
|
||||
action: L("firstrun.model.action", "Скачать и установить Parakeet")
|
||||
) }
|
||||
|
||||
static var modelReady: String { L("firstrun.modelReady", "Модель на месте") }
|
||||
|
||||
@@ -31,6 +31,7 @@ struct FirstRunDictationField: NSViewRepresentable {
|
||||
func makeNSView(context: Context) -> FirstRunFieldBox {
|
||||
let textView = FirstRunTextView()
|
||||
textView.placeholder = placeholder
|
||||
textView.setAccessibilityLabel(placeholder)
|
||||
textView.delegate = context.coordinator
|
||||
textView.font = .systemFont(ofSize: 14)
|
||||
textView.isEditable = true
|
||||
@@ -56,6 +57,7 @@ struct FirstRunDictationField: NSViewRepresentable {
|
||||
guard let textView = box.textView else { return }
|
||||
if textView.string != text { textView.string = text }
|
||||
textView.placeholder = placeholder
|
||||
textView.setAccessibilityLabel(placeholder)
|
||||
context.coordinator.onSubmit = onSubmit
|
||||
// Курсор ставится в это поле и остаётся здесь: диктовка вставляет
|
||||
// текст туда, где он мигает.
|
||||
|
||||
@@ -24,7 +24,16 @@ struct FirstRunKeyTrial: View {
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 12) {
|
||||
if canHearKey {
|
||||
if !model.modelIsReady {
|
||||
Text(model.isInstallingModel
|
||||
? L("firstrun.trialModelDownloading", "Модель ещё скачивается. Ход установки виден на её странице.")
|
||||
: L("firstrun.trialModelMissing", "Модель ещё не установлена. Кнопка ниже вернёт к скачиванию."))
|
||||
.font(.system(size: 13, weight: .medium))
|
||||
.multilineTextAlignment(.center)
|
||||
.foregroundStyle(.secondary)
|
||||
Button(L("firstrun.trialOpenModelSetup", "К установке модели")) { model.showModelSetup() }
|
||||
.modifier(FirstRunProminentButton())
|
||||
} else if canHearKey {
|
||||
// Сама клавиша и есть кнопка замены. Строчка «Клавиша занята?
|
||||
// Поменять» снизу была незаметна: владелец 07.09.2026 сказал
|
||||
// прямо — «снизу не очень заметно… необходимо, чтобы вот та
|
||||
@@ -88,11 +97,13 @@ struct FirstRunKeyTrial: View {
|
||||
}
|
||||
}
|
||||
|
||||
FirstRunDictationField(text: $model.tryItText,
|
||||
placeholder: FirstRunCopy.trialFieldPlaceholder,
|
||||
onSubmit: { model.goNext() })
|
||||
.frame(height: 68)
|
||||
.frame(maxWidth: 440)
|
||||
if model.modelIsReady {
|
||||
FirstRunDictationField(text: $model.tryItText,
|
||||
placeholder: FirstRunCopy.trialFieldPlaceholder,
|
||||
onSubmit: { model.goNext() })
|
||||
.frame(height: 68)
|
||||
.frame(maxWidth: 440)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -10,13 +10,13 @@ import Foundation
|
||||
import IrizCore
|
||||
|
||||
/// Шаги знакомства. Порядок - это и есть сценарий, и он не случайный: сначала
|
||||
/// «что это» и «где оно живёт», потом разрешения от самого понятного к самому
|
||||
/// пугающему, и только потом проба голосом. Человек, которому уже объяснили,
|
||||
/// «что это» и установка распознавания, затем «где оно живёт», разрешения от
|
||||
/// самого понятного к самому пугающему и проба голосом. Человек, которому уже объяснили,
|
||||
/// зачем нужен микрофон, спокойнее отвечает на «сможет читать все нажатия».
|
||||
enum FirstRunStep: String, CaseIterable, Equatable {
|
||||
case welcome
|
||||
case whereItLives
|
||||
case model
|
||||
case whereItLives
|
||||
case microphone
|
||||
case accessibility
|
||||
case inputMonitoring
|
||||
@@ -103,11 +103,11 @@ let FIRST_RUN_COMPLETED_KEY = "ru.smltlk.firstRunCompleted"
|
||||
func firstRunShouldShow(defaults: UserDefaults,
|
||||
permissionsGranted: Bool,
|
||||
modelInstalled: Bool = true) -> Bool {
|
||||
if defaults.bool(forKey: FIRST_RUN_COMPLETED_KEY) { return false }
|
||||
// Без модели продукт не работает вовсе, а поставить её можно только
|
||||
// отсюда. Человек с выданными разрешениями и пустым диском иначе не увидел
|
||||
// бы ни знакомства, ни модели - только отказ распознавания.
|
||||
if !modelInstalled { return true }
|
||||
if defaults.bool(forKey: FIRST_RUN_COMPLETED_KEY) { return false }
|
||||
// Разрешения уже выданы - значит человек прошёл этот путь руками до того,
|
||||
// как знакомство появилось в продукте. Ему показывать нечего.
|
||||
return !permissionsGranted
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// который не видит движения, через минуту решает, что зависло, и закрывает
|
||||
// окно. Идти дальше при этом можно сразу - загрузка не держит знакомство.
|
||||
import IrizDictate
|
||||
import IrizCore
|
||||
import SwiftUI
|
||||
|
||||
struct FirstRunModelInstall: View {
|
||||
@@ -11,11 +12,7 @@ struct FirstRunModelInstall: View {
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 10) {
|
||||
if model.modelInstalled {
|
||||
Text(FirstRunCopy.modelReady)
|
||||
.font(.system(size: 13, weight: .medium))
|
||||
.foregroundStyle(.secondary)
|
||||
} else if let phase = model.installPhase {
|
||||
if let phase = model.installPhase, phase != .finished {
|
||||
switch phase {
|
||||
case .failed(let reason):
|
||||
Text(reason)
|
||||
@@ -25,6 +22,7 @@ struct FirstRunModelInstall: View {
|
||||
.frame(maxWidth: 420)
|
||||
Button(FirstRunCopy.modelFailedRetry) { model.installModel() }
|
||||
.modifier(FirstRunProminentButton())
|
||||
.keyboardShortcut(.defaultAction)
|
||||
default:
|
||||
Text(speechModelInstallTitle(phase))
|
||||
.font(.system(size: 13, weight: .medium))
|
||||
@@ -32,12 +30,23 @@ struct FirstRunModelInstall: View {
|
||||
.progressViewStyle(.linear)
|
||||
.frame(width: 260)
|
||||
}
|
||||
} else if model.modelInstalled {
|
||||
Text(FirstRunCopy.modelReady)
|
||||
.font(.system(size: 13, weight: .medium))
|
||||
.foregroundStyle(.secondary)
|
||||
if model.selectedSpeechModel == .multilingualV3 {
|
||||
Button(L("firstrun.model.verifyRepair", "Проверить и восстановить Parakeet")) {
|
||||
model.installModel()
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
}
|
||||
} else {
|
||||
Text(FirstRunCopy.hintModel)
|
||||
.font(.system(size: 12.5, weight: .medium))
|
||||
.foregroundStyle(.secondary)
|
||||
Button(FirstRunCopy.model.action ?? "") { model.installModel() }
|
||||
.modifier(FirstRunProminentButton())
|
||||
.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,19 +46,26 @@ struct FirstRunView: View {
|
||||
FirstRunHero(step: step)
|
||||
.frame(height: 96)
|
||||
|
||||
Text(step.copy.title)
|
||||
Text(step == .model && model.modelIsReady
|
||||
? L("firstrun.model.alreadyReadyTitle", "Распознавание уже установлено")
|
||||
: step.copy.title)
|
||||
.font(.system(size: 27, weight: .semibold))
|
||||
.multilineTextAlignment(.center)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
|
||||
Text(step.copy.body)
|
||||
Text(step == .model && model.modelIsReady
|
||||
? Lf("firstrun.model.alreadyReadyBody", "%@ готов к диктовке. Скачивать ничего не нужно.", model.selectedSpeechModelTitle)
|
||||
: (step == .tryIt && !model.modelIsReady
|
||||
? L("firstrun.trialNeedsModel", "Перед первой диктовкой нужно скачать модель распознавания.")
|
||||
: step.copy.body))
|
||||
.font(.system(size: 15))
|
||||
.foregroundStyle(.primary.opacity(0.88))
|
||||
.multilineTextAlignment(.center)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
.frame(maxWidth: 440)
|
||||
|
||||
if let note = step.copy.note {
|
||||
if let note = step.copy.note, !(step == .model && model.modelIsReady),
|
||||
!(step == .tryIt && !model.modelIsReady) {
|
||||
Text(note)
|
||||
.font(.system(size: 12.5))
|
||||
.foregroundStyle(.secondary)
|
||||
@@ -110,9 +117,14 @@ struct FirstRunView: View {
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer()
|
||||
Button(model.isLastStep ? FirstRunCopy.done : FirstRunCopy.next) { model.goNext() }
|
||||
.modifier(FirstRunProminentButton())
|
||||
.keyboardShortcut(.defaultAction)
|
||||
if model.modelInstallIsPrimaryAction {
|
||||
Button(model.nextButtonTitle) { model.goNext() }
|
||||
.buttonStyle(.bordered)
|
||||
} else {
|
||||
Button(model.nextButtonTitle) { model.goNext() }
|
||||
.modifier(FirstRunProminentButton())
|
||||
.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
}
|
||||
.overlay { FirstRunProgress(step: step) }
|
||||
}
|
||||
|
||||
@@ -192,7 +192,7 @@ struct MenuContentView: View {
|
||||
case .fault(let reason):
|
||||
actionRow(L("menu.dictation", "Диктовка"), key: reason, target: .dictation) {
|
||||
chrome.close()
|
||||
appDelegate.recheckPermissions()
|
||||
appDelegate.recoverDictation()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,7 +342,7 @@ struct MenuContentView: View {
|
||||
order.append(.mode)
|
||||
order.append(.layout)
|
||||
if case .fault = state.dictationHint { order.append(.dictation) }
|
||||
order += [.settings, .quit]
|
||||
order += [.meeting, .history, .welcome, .settings, .quit]
|
||||
return order
|
||||
}
|
||||
|
||||
@@ -361,10 +361,14 @@ struct MenuContentView: View {
|
||||
/// стрелки ← → обрабатывают сами, им активация не нужна.
|
||||
private func activateFocused() -> Bool {
|
||||
switch focus {
|
||||
case .permissions, .dictation:
|
||||
case .permissions:
|
||||
chrome.close()
|
||||
appDelegate.recheckPermissions()
|
||||
return true
|
||||
case .dictation:
|
||||
chrome.close()
|
||||
appDelegate.recoverDictation()
|
||||
return true
|
||||
case .meeting:
|
||||
chrome.close()
|
||||
appDelegate.toggleMeetingRecording()
|
||||
|
||||
@@ -69,6 +69,11 @@ final class MenuState: ObservableObject {
|
||||
/// Раскладка работает, только когда выданы оба разрешения.
|
||||
var permissionsOK: Bool { accessibilityOK && inputMonitoringOK }
|
||||
|
||||
/// Ошибка модели не должна отправлять проверять уже выданные разрешения.
|
||||
var dictationRecoveryNeedsPermissions: Bool {
|
||||
!permissionsOK || !microphoneOK || !inputTapOK
|
||||
}
|
||||
|
||||
/// Версия из бандла — показывается в окне настроек, не в меню.
|
||||
var version: String {
|
||||
Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "dev"
|
||||
|
||||
@@ -11,7 +11,9 @@ import IrizSettings
|
||||
import SwiftUI
|
||||
|
||||
@MainActor
|
||||
func makeIrizSettingsWindow(preview: Bool = false, page: SettingsPage = .keys) -> NSWindow {
|
||||
func makeIrizSettingsWindow(preview: Bool = false, page: SettingsPage = .keys,
|
||||
navigation: SettingsNavigation? = nil,
|
||||
openSpeechModelSetup: (() -> Void)? = nil) -> NSWindow {
|
||||
let window = NSWindow(
|
||||
// Окно шире прежнего: слева боковик со страницами, справа сама
|
||||
// страница. В 700 pt на две колонки не помещалось ничего.
|
||||
@@ -41,7 +43,9 @@ func makeIrizSettingsWindow(preview: Bool = false, page: SettingsPage = .keys) -
|
||||
// `.fullSizeContentView` сохраняет системную рамку. Замер по кадру дал
|
||||
// радиус около 27 pt при зашитых 16, то есть своя маска ещё и врала бы.
|
||||
window.contentMinSize = NSSize(width: 900, height: 620)
|
||||
window.contentView = NSHostingView(rootView: IrizSettingsView(preview: preview, page: page))
|
||||
window.contentView = NSHostingView(rootView: IrizSettingsView(preview: preview, page: page,
|
||||
navigation: navigation,
|
||||
openSpeechModelSetup: openSpeechModelSetup))
|
||||
window.isReleasedWhenClosed = false // иначе закрытие окна уронит приложение
|
||||
return window
|
||||
}
|
||||
|
||||
@@ -58,12 +58,14 @@ public extension Animation {
|
||||
/// Нажатие. Без отклика кнопка кажется картинкой: нажал, ничего не шевельнулось.
|
||||
/// 0.97 - предел, за которым сжатие уже видно как трюк.
|
||||
public struct IrizPressStyle: ButtonStyle {
|
||||
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||
|
||||
public init() {}
|
||||
|
||||
public func makeBody(configuration: Configuration) -> some View {
|
||||
configuration.label
|
||||
.scaleEffect(configuration.isPressed ? 0.97 : 1)
|
||||
.animation(.irizQuick, value: configuration.isPressed)
|
||||
.scaleEffect(configuration.isPressed && !reduceMotion ? 0.97 : 1)
|
||||
.animation(reduceMotion ? nil : .irizQuick, value: configuration.isPressed)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
"firstrun.hintAccessibility" = "click here, System Settings will open";
|
||||
"firstrun.hintInputMonitoring" = "click here, System Settings will open";
|
||||
"firstrun.hintMicrophone" = "click here";
|
||||
"firstrun.hintModel" = "click here, about five minutes to download";
|
||||
"firstrun.hintModel" = "Click below. iriz downloads and installs the model for you.";
|
||||
"firstrun.inputMonitoring.body" = "macOS calls it \"Input Monitoring\" and warns that I'll be able to see your keystrokes in every app. Those are its words, not mine.";
|
||||
"firstrun.inputMonitoring.note" = "I need two things: to know you pressed the dictation key, and to notice a phrase typed in the wrong keyboard layout. I see keystrokes only here, on your Mac: I save nothing and send nothing anywhere, and I don't work in password fields at all.\n\nRight after that I'll restart. macOS requires it, nothing is broken.";
|
||||
"firstrun.inputMonitoring.title" = "One permission left: the keyboard";
|
||||
@@ -23,10 +23,10 @@
|
||||
"firstrun.microphone.body" = "Without it I won't hear a word, so let's start there.";
|
||||
"firstrun.microphone.note" = "The audio is never saved: it lives exactly as long as it takes to work out what you said.";
|
||||
"firstrun.microphone.title" = "Microphone needed";
|
||||
"firstrun.model.action" = "Download model";
|
||||
"firstrun.model.body" = "I turn speech into text right on your Mac, no internet. For that I need a model: half a gigabyte, downloaded once.";
|
||||
"firstrun.model.note" = "It is deliberately not inside the disk image: the model updates more often than iriz itself. Keep it separate: otherwise an outdated one would ship along with the program.\n\nCarry on while it downloads: you can grant the permissions right now.";
|
||||
"firstrun.model.title" = "Let's get the speech model";
|
||||
"firstrun.model.action" = "Download and install Parakeet";
|
||||
"firstrun.model.body" = "Dictation needs a speech model. The button below downloads Parakeet, installs it in the right folder and selects it for recognition.";
|
||||
"firstrun.model.note" = "The download is about 500 MB. You need internet access and free disk space. Speed depends on your connection; progress appears here. No need to find or move files yourself.\n\nYou can grant permissions while the model downloads. We will try dictation after installation.";
|
||||
"firstrun.model.title" = "Install speech recognition";
|
||||
"firstrun.modelFailedRetry" = "Try again";
|
||||
"firstrun.modelReady" = "Model is in place";
|
||||
"firstrun.next" = "Next";
|
||||
@@ -52,7 +52,7 @@
|
||||
"firstrun.tryIt.note" = "The text lands in the field below and nowhere else: while this window is open, I type only here.";
|
||||
"firstrun.tryIt.title" = "Try it right now";
|
||||
"firstrun.welcome.body" = "Press the key, say a sentence, press it again. The text appears where your cursor was: in an email, in a chat, in the terminal.";
|
||||
"firstrun.welcome.note" = "It all runs right on your Mac. No audio, no text leaves it.";
|
||||
"firstrun.welcome.note" = "Before your first dictation, download a speech model using the install button on the next step. Then speech recognition runs on your Mac, without internet access.";
|
||||
"firstrun.welcome.title" = "You talk, I type";
|
||||
"firstrun.whenItBreaks.body" = "Text didn't paste? It isn't lost. The badge expands and shows it, and you can copy it from there.";
|
||||
"firstrun.whenItBreaks.note" = "Misheard a word? Just correct it right in the text. I notice the edit and ask whether to remember it: say yes, and from then on I write it your way. I never put anything into the dictionary on my own.\n\nKey taken by another app? Click it in the settings and set your own shortcut.\n\nThis window, the settings and the history all open from the icon in the menu bar.";
|
||||
@@ -332,3 +332,78 @@
|
||||
"snippets.delete.a11y" = "Delete snippet %d";
|
||||
"snippets.phrase.a11y" = "Snippet phrase %d";
|
||||
"snippets.text.a11y" = "Snippet text %d";
|
||||
|
||||
/* UI Stack: обработка, восстановление и доступность. */
|
||||
"files.choose" = "Choose files";
|
||||
"files.destinationExists" = "Text already exists: %@. Open it or rename the source recording before retrying.";
|
||||
"files.finished" = "Completed: %d of %d.";
|
||||
"files.language" = "Recording language";
|
||||
"files.languageAuto" = "Detect automatically";
|
||||
"files.noSpeech" = "No speech recognized. No text file was created.";
|
||||
"files.openFailed" = "Could not open %@. Check the file in Finder.";
|
||||
"files.openText" = "Open text";
|
||||
"files.preparing" = "loading the model";
|
||||
"files.reading" = "reading the recording";
|
||||
"files.refused" = "Files not accepted: %d. Choose readable recordings: %@.";
|
||||
"files.retry" = "Retry remaining files";
|
||||
"files.saving" = "saving text";
|
||||
"files.showDestination" = "Show output folder";
|
||||
"files.showInFinder" = "Show in Finder";
|
||||
"files.start" = "Transcribe recordings";
|
||||
"files.stopAfterCurrent" = "Stop after the current recording";
|
||||
"files.stopped" = "Queue stopped. You can start the remaining files again.";
|
||||
"files.stopping" = "Stopping after the current recording…";
|
||||
"files.transcribing" = "transcribing";
|
||||
"firstrun.agentModelRequired" = "Choose a model for %@ in prompt settings, then connect the agent here.";
|
||||
"firstrun.agentSettings" = "Agent settings…";
|
||||
"firstrun.modelAlreadyDownloading" = "The model is already downloading. Wait for installation to finish.";
|
||||
"firstrun.modelInstallWhileRecording" = "Finish recording, then try installing the model again.";
|
||||
"history.clearFailed" = "Could not move %d of %d recordings to the Trash. The others are already in the Trash.";
|
||||
"history.clearing" = "Preparing and clearing history…";
|
||||
"history.copiedTimed" = "Copied. The clipboard will clear in 2 minutes.";
|
||||
"history.copyFailed" = "Could not copy. Try again.";
|
||||
"history.deleteFailed" = "Could not move the recording to the Trash. Try again.";
|
||||
"history.readFailed" = "Could not read history. Try opening it again.";
|
||||
"hud.toggleExpanded" = "Expand or collapse overlay";
|
||||
"meeting.close" = "Close";
|
||||
"meeting.discardUnsaved" = "Delete unsaved recording";
|
||||
"meeting.emptyRecording" = "No audio was recorded";
|
||||
"meeting.emptyRecording.help" = "Check your microphone and record the meeting again.";
|
||||
"meeting.openProtocol" = "Open transcript";
|
||||
"meeting.processingFailed" = "Could not process the meeting";
|
||||
"meeting.protocolReady" = "Meeting transcript is ready";
|
||||
"meeting.recordingSaved" = "The recording is saved. Retry processing or find it in Finder.";
|
||||
"meeting.retryProcessing" = "Retry processing";
|
||||
"meeting.retrySave" = "Retry saving";
|
||||
"meeting.saveFailed" = "Could not save the meeting recording";
|
||||
"meeting.saveFailed.help" = "The audio is still in memory. Free some disk space and retry saving. Deleting the recording cannot be undone.";
|
||||
"meeting.showRecording" = "Show recording";
|
||||
"meeting.speakersUnresolved" = "Speakers could not be separated. The text was saved as one turn.";
|
||||
"meeting.title" = "Meeting";
|
||||
"meetings.openProtocol" = "Open transcript";
|
||||
"meetings.showFolder" = "Show meeting folder";
|
||||
"meetings.speakersUnresolved" = "%@: speakers could not be separated. The text is saved as one turn; check the transcript.";
|
||||
"meetings.storage" = "Recording in Russian. Audio and transcript are saved in the iriz archive; you can open the completed files here.";
|
||||
"settings.speechModelInstalled" = "%@: model installed";
|
||||
"settings.speechModelMissing" = "%@: model not installed";
|
||||
"settings.speechModelDownloadHelp" = "Speech recognition needs a model on this Mac. Automatic download is available only for Parakeet: about 0.5 GB, once. It becomes the selected recognizer after installation. Audio stays on your device.";
|
||||
"settings.speechModelSetup" = "Set up speech recognition…";
|
||||
"settings.downloadParakeet" = "Download Parakeet model…";
|
||||
"settings.parakeetAlreadyAvailable" = "Parakeet is already installed. Select it and save settings to use it for dictation.";
|
||||
"settings.selectInstalledParakeet" = "Select installed Parakeet";
|
||||
"firstrun.model.installLater" = "Download later";
|
||||
"firstrun.model.alreadyReadyTitle" = "Speech recognition is installed";
|
||||
"firstrun.model.alreadyReadyBody" = "%@ is ready for dictation. No download needed.";
|
||||
"firstrun.trialNeedsModel" = "Download a speech model before your first dictation.";
|
||||
"firstrun.trialModelDownloading" = "The model is still downloading. You can see progress on its setup page.";
|
||||
"firstrun.trialModelMissing" = "The model is not installed yet. The button below takes you to the download.";
|
||||
"firstrun.trialOpenModelSetup" = "Set up the model";
|
||||
"firstrun.model.verifyRepair" = "Check and repair Parakeet";
|
||||
"speechModel.downloading" = "Downloading speech model";
|
||||
"speechModel.verifying" = "Verifying downloaded model";
|
||||
"speechModel.ready" = "Model installed";
|
||||
"speechModel.failed" = "Download failed";
|
||||
"speechModel.error.offline" = "No internet connection. Connect to a network and retry the download.";
|
||||
"speechModel.error.connectionLost" = "The connection was lost. Check your internet connection and retry the download.";
|
||||
"speechModel.error.timeout" = "The server did not respond in time. Retry the download later.";
|
||||
"speechModel.error.cancelled" = "The download was cancelled. You can start it again.";
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
"firstrun.hintAccessibility" = "点这里,打开系统设置";
|
||||
"firstrun.hintInputMonitoring" = "点这里,打开系统设置";
|
||||
"firstrun.hintMicrophone" = "点这里";
|
||||
"firstrun.hintModel" = "点这里,下载大约要五分钟";
|
||||
"firstrun.hintModel" = "点击下方按钮,iriz 会自动下载并安装模型。";
|
||||
"firstrun.inputMonitoring.body" = "macOS 会把它叫做「输入监控」,还会警告你:我能看到所有程序里的按键。这是它的措辞,不是我的。";
|
||||
"firstrun.inputMonitoring.note" = "我只需要两件事:知道你按下了听写键,以及发现有句话是在错的键盘布局下打的。按键只在你这台 Mac 上看,不保存,不外发,密码框里我根本不工作。\n\n之后我会立刻重启。这是 macOS 的要求,不是出了故障。";
|
||||
"firstrun.inputMonitoring.title" = "还差按键权限";
|
||||
@@ -24,10 +24,10 @@
|
||||
"firstrun.microphone.body" = "没有它我一个字也听不见,所以先从它开始。";
|
||||
"firstrun.microphone.note" = "声音不会保存到任何地方:它只留到把话听明白为止。";
|
||||
"firstrun.microphone.title" = "需要麦克风";
|
||||
"firstrun.model.action" = "下载模型";
|
||||
"firstrun.model.body" = "语音就在你的 Mac 上识别,不联网。这需要一个模型:500 MB,只下一次。";
|
||||
"firstrun.model.note" = "它故意不放在磁盘映像里:模型的更新比 iriz 本身勤。分开放::不然随程序一起来的就是过时的那个。\n\n下载的时候继续往下走:权限现在就能给。";
|
||||
"firstrun.model.title" = "下载语音识别";
|
||||
"firstrun.model.action" = "下载并安装 Parakeet";
|
||||
"firstrun.model.body" = "听写需要语音模型。下方按钮会下载 Parakeet,将其安装到正确的文件夹,并选为识别引擎。";
|
||||
"firstrun.model.note" = "下载大小约为 500 MB,需要网络连接和可用磁盘空间。速度取决于网络,进度会显示在这里。不必手动查找或移动文件。\n\n下载期间可以继续授予权限。安装完成后再尝试听写。";
|
||||
"firstrun.model.title" = "安装语音识别模型";
|
||||
"firstrun.modelFailedRetry" = "重试";
|
||||
"firstrun.modelReady" = "模型已就位";
|
||||
"firstrun.next" = "下一步";
|
||||
@@ -53,7 +53,7 @@
|
||||
"firstrun.tryIt.note" = "文字会出现在下面的输入框里,不会传到别处:这个窗口开着的时候,我只往这里写。";
|
||||
"firstrun.tryIt.title" = "现在就试试";
|
||||
"firstrun.welcome.body" = "按一下键,说一句话,再按一下。文字会出现在光标所在的地方:邮件里、聊天里、终端里。";
|
||||
"firstrun.welcome.note" = "所有处理都在你的 Mac 上完成。声音和文字都不会发到任何地方。";
|
||||
"firstrun.welcome.note" = "首次听写前,需要下载语音模型。下一步会显示安装按钮。之后语音识别就在你的 Mac 上运行,无需联网。";
|
||||
"firstrun.welcome.title" = "你说,我来打字";
|
||||
"firstrun.whenItBreaks.body" = "文字没插进去?它没丢。提示条会展开把它显示出来,可以从那里复制。";
|
||||
"firstrun.whenItBreaks.note" = "有个词听错了?直接在文字里改掉就行。我会注意到这处修改,并问你要不要记住:你同意了,之后我就照你的写法来。我不会自己往词典里放任何东西。\n\n按键被别的程序占用了?在设置里点它,设你自己的组合。\n\n这个窗口、设置和历史,都从菜单栏的图标打开。";
|
||||
@@ -333,3 +333,78 @@
|
||||
"snippets.delete.a11y" = "删除第 %d 条片段";
|
||||
"snippets.phrase.a11y" = "第 %d 条片段的触发词";
|
||||
"snippets.text.a11y" = "第 %d 条片段的正文";
|
||||
|
||||
/* UI Stack: обработка, восстановление и доступность. */
|
||||
"files.choose" = "选择文件";
|
||||
"files.destinationExists" = "文本已存在:%@。请打开它,或重命名原录音后重试。";
|
||||
"files.finished" = "已完成:%d / %d。";
|
||||
"files.language" = "录音语言";
|
||||
"files.languageAuto" = "自动识别";
|
||||
"files.noSpeech" = "未识别到语音。未创建文本文件。";
|
||||
"files.openFailed" = "无法打开 %@。请在访达中检查该文件。";
|
||||
"files.openText" = "打开文本";
|
||||
"files.preparing" = "正在加载模型";
|
||||
"files.reading" = "正在读取录音";
|
||||
"files.refused" = "未接受的文件:%d。请选择可读取的录音:%@。";
|
||||
"files.retry" = "重试剩余文件";
|
||||
"files.saving" = "正在保存文本";
|
||||
"files.showDestination" = "显示结果文件夹";
|
||||
"files.showInFinder" = "在访达中显示";
|
||||
"files.start" = "转录录音";
|
||||
"files.stopAfterCurrent" = "完成当前录音后停止";
|
||||
"files.stopped" = "队列已停止。你可以重新处理剩余文件。";
|
||||
"files.stopping" = "完成当前录音后停止…";
|
||||
"files.transcribing" = "正在转录";
|
||||
"firstrun.agentModelRequired" = "请在提示词设置中为 %@ 选择模型,然后回到这里连接智能体。";
|
||||
"firstrun.agentSettings" = "智能体设置…";
|
||||
"firstrun.modelAlreadyDownloading" = "模型正在下载。请等待安装完成。";
|
||||
"firstrun.modelInstallWhileRecording" = "请先结束录音,再重试安装模型。";
|
||||
"history.clearFailed" = "有 %d 条录音未能移到废纸篓,共 %d 条。其余录音已移到废纸篓。";
|
||||
"history.clearing" = "正在准备并清空历史记录…";
|
||||
"history.copiedTimed" = "已复制。剪贴板将在 2 分钟后清空。";
|
||||
"history.copyFailed" = "无法复制。请重试。";
|
||||
"history.deleteFailed" = "无法将录音移到废纸篓。请重试。";
|
||||
"history.readFailed" = "无法读取历史记录。请重新打开。";
|
||||
"hud.toggleExpanded" = "展开或收起浮窗";
|
||||
"meeting.close" = "关闭";
|
||||
"meeting.discardUnsaved" = "删除未保存的录音";
|
||||
"meeting.emptyRecording" = "未录制到声音";
|
||||
"meeting.emptyRecording.help" = "请检查麦克风,然后重新录制会议。";
|
||||
"meeting.openProtocol" = "打开会议记录";
|
||||
"meeting.processingFailed" = "无法处理会议";
|
||||
"meeting.protocolReady" = "会议记录已就绪";
|
||||
"meeting.recordingSaved" = "录音已保存。你可以重试处理,或在访达中找到它。";
|
||||
"meeting.retryProcessing" = "重试处理";
|
||||
"meeting.retrySave" = "重试保存";
|
||||
"meeting.saveFailed" = "无法保存会议录音";
|
||||
"meeting.saveFailed.help" = "声音仍在内存中。请释放磁盘空间后重试保存。删除录音后将无法恢复。";
|
||||
"meeting.showRecording" = "显示录音";
|
||||
"meeting.speakersUnresolved" = "无法区分说话人。文本已保存为一段发言。";
|
||||
"meeting.title" = "会议";
|
||||
"meetings.openProtocol" = "打开会议记录";
|
||||
"meetings.showFolder" = "显示会议文件夹";
|
||||
"meetings.speakersUnresolved" = "%@:无法区分说话人。文本已保存为一段发言,请检查会议记录。";
|
||||
"meetings.storage" = "俄语录音。音频和会议记录将保存到 iriz 归档中;你可以在这里打开处理完成的文件。";
|
||||
"settings.speechModelInstalled" = "%@:模型已安装";
|
||||
"settings.speechModelMissing" = "%@:模型未安装";
|
||||
"settings.speechModelDownloadHelp" = "语音识别需要在这台 Mac 上安装模型。目前只能自动下载 Parakeet:约 0.5 GB,只需下载一次。安装后会成为所选识别引擎。音频始终留在你的设备上。";
|
||||
"settings.speechModelSetup" = "设置语音识别…";
|
||||
"settings.downloadParakeet" = "下载 Parakeet 模型…";
|
||||
"settings.parakeetAlreadyAvailable" = "Parakeet 已安装。选择它并保存设置,即可用于听写。";
|
||||
"settings.selectInstalledParakeet" = "选择已安装的 Parakeet";
|
||||
"firstrun.model.installLater" = "稍后下载";
|
||||
"firstrun.model.alreadyReadyTitle" = "语音识别模型已安装";
|
||||
"firstrun.model.alreadyReadyBody" = "%@ 已准备好听写,无需下载。";
|
||||
"firstrun.trialNeedsModel" = "首次听写前,请先下载语音模型。";
|
||||
"firstrun.trialModelDownloading" = "模型仍在下载,可在模型设置页面查看进度。";
|
||||
"firstrun.trialModelMissing" = "模型尚未安装。下方按钮可返回下载页面。";
|
||||
"firstrun.trialOpenModelSetup" = "前往安装模型";
|
||||
"firstrun.model.verifyRepair" = "检查并修复 Parakeet";
|
||||
"speechModel.downloading" = "正在下载语音模型";
|
||||
"speechModel.verifying" = "正在验证已下载的模型";
|
||||
"speechModel.ready" = "模型已安装";
|
||||
"speechModel.failed" = "下载失败";
|
||||
"speechModel.error.offline" = "没有互联网连接。请连接网络后重试下载。";
|
||||
"speechModel.error.connectionLost" = "连接已中断。请检查网络后重试下载。";
|
||||
"speechModel.error.timeout" = "服务器未能及时响应。请稍后重试下载。";
|
||||
"speechModel.error.cancelled" = "下载已取消。你可以重新开始。";
|
||||
|
||||
@@ -62,6 +62,7 @@ public final class DictationController {
|
||||
private var isBusy = false
|
||||
private var isRecording = false
|
||||
private var modelReady = false
|
||||
private var lastRequestedModelProfile: SpeechModelProfile?
|
||||
/// Идёт ли прогрев прямо сейчас. Отдельно от `modelReady`, потому что
|
||||
/// «грузится» и «нет вовсе» - разные состояния с разными последствиями.
|
||||
private var warmUpTask: Task<Void, Never>?
|
||||
@@ -88,6 +89,7 @@ public final class DictationController {
|
||||
private var powerLifecycle = AudioPowerLifecycle()
|
||||
/// Подмена таймаута распознавания — только тестами, чтобы не ждать живьём.
|
||||
private let transcriptionTimeoutOverride: Double?
|
||||
private let modelLoader: (@Sendable (SpeechModelProfile) async throws -> Void)?
|
||||
/// Счётчики доставки: их читает status.json (scripts/gate_app.sh).
|
||||
private let insertionStats: InsertionStats
|
||||
private var settingsObserver: NotificationObserver?
|
||||
@@ -95,6 +97,7 @@ public final class DictationController {
|
||||
public init() {
|
||||
self.settings = .shared
|
||||
self.transcriptionTimeoutOverride = nil
|
||||
self.modelLoader = nil
|
||||
self.insertionStats = InsertionStats()
|
||||
observeSettings()
|
||||
}
|
||||
@@ -102,9 +105,11 @@ public final class DictationController {
|
||||
/// Для тестов и будущих точек сборки.
|
||||
init(settings: DictationSettings,
|
||||
transcriptionTimeout: Double? = nil,
|
||||
insertionStats: InsertionStats = InsertionStats()) {
|
||||
insertionStats: InsertionStats = InsertionStats(),
|
||||
modelLoader: (@Sendable (SpeechModelProfile) async throws -> Void)? = nil) {
|
||||
self.settings = settings
|
||||
self.transcriptionTimeoutOverride = transcriptionTimeout
|
||||
self.modelLoader = modelLoader
|
||||
self.insertionStats = insertionStats
|
||||
observeSettings()
|
||||
}
|
||||
@@ -187,9 +192,17 @@ public final class DictationController {
|
||||
|
||||
public func stop() {
|
||||
if isRecording {
|
||||
// Sleep/выход отменяет клип: не запускаем распознавание и не
|
||||
// создаём raw/audio recovery-артефакт.
|
||||
handleCancel()
|
||||
if recordingPurpose == .meeting {
|
||||
// Уже записанная встреча переживает sleep/выход. ASR здесь
|
||||
// не запускаем: исходник можно разобрать после возвращения.
|
||||
isRecording = false
|
||||
recordingPurpose = .dictation
|
||||
let captured = audio.endRecording()
|
||||
finishMeetingRecording(samples: captured.samples, process: false)
|
||||
hotkeys.resetToggleState()
|
||||
} else {
|
||||
handleCancel()
|
||||
}
|
||||
}
|
||||
maxDurationTask?.cancel()
|
||||
maxDurationTask = nil
|
||||
@@ -223,9 +236,31 @@ public final class DictationController {
|
||||
start()
|
||||
}
|
||||
|
||||
/// Вызывается после явной установки. Греет выбранный движок, не повторяя
|
||||
/// start(), запросы разрешений и запуск записи; настройки не меняет.
|
||||
@discardableResult
|
||||
public func prepareAfterModelInstallation() -> Bool {
|
||||
guard !isBusy, !isRecording, warmUpTask == nil, !powerLifecycle.isSuspended else { return false }
|
||||
DownloadUtils.enforceOffline = true
|
||||
modelReady = false
|
||||
state = .warmingUp
|
||||
warmUpTask = Task { [weak self] in await self?.warmUpModel() }
|
||||
return true
|
||||
}
|
||||
|
||||
private func warmUpModel() async {
|
||||
let profile = settings.speechEngine
|
||||
lastRequestedModelProfile = profile
|
||||
defer {
|
||||
warmUpTask = nil
|
||||
if settings.speechEngine != profile { prepareChangedSpeechModelIfIdle() }
|
||||
}
|
||||
do {
|
||||
try await asr.load(profile: settings.speechEngine)
|
||||
if let modelLoader {
|
||||
try await modelLoader(profile)
|
||||
} else {
|
||||
try await asr.load(profile: profile)
|
||||
}
|
||||
// Рычаг под смешанную речь включен и в ЖИВОЙ диктовке, а не только в
|
||||
// CLI: без него термины внутри русской фразы ломаются ровно там, где
|
||||
// владелец диктует каждый день.
|
||||
@@ -233,6 +268,7 @@ public final class DictationController {
|
||||
modelReady = true
|
||||
if state == .warmingUp { state = .ready }
|
||||
} catch {
|
||||
modelReady = false
|
||||
log("ASR warmup failed: \(error.localizedDescription)")
|
||||
state = .unavailable(error.localizedDescription)
|
||||
}
|
||||
@@ -312,35 +348,123 @@ public final class DictationController {
|
||||
/// Файл пишется ДО разбора и остаётся на диске, даже если разбор упадёт:
|
||||
/// запись заседания дороже протокола, её нельзя терять из-за отказа
|
||||
/// распознавателя.
|
||||
private func finishMeetingRecording(samples: [Float]) {
|
||||
private func finishMeetingRecording(samples: [Float], process: Bool = true) {
|
||||
state = .ready
|
||||
guard !samples.isEmpty else {
|
||||
log("meeting: пустая запись, сохранять нечего")
|
||||
if process {
|
||||
let alert = NSAlert()
|
||||
alert.alertStyle = .warning
|
||||
alert.messageText = L("meeting.emptyRecording", "Звук не записался")
|
||||
alert.informativeText = L("meeting.emptyRecording.help", "Проверь микрофон и повтори запись встречи.")
|
||||
alert.addButton(withTitle: L("meeting.close", "Закрыть"))
|
||||
_ = runMeetingAlert(alert)
|
||||
}
|
||||
return
|
||||
}
|
||||
do {
|
||||
let url = try meetingRecordingScratchURL()
|
||||
let recording = try writeMeetingWAV(samples: samples,
|
||||
sampleRate: SAMPLE_RATE,
|
||||
to: url)
|
||||
log("meeting: записано \(Int(recording.seconds)) с в \(url.lastPathComponent)")
|
||||
Task { @MainActor in
|
||||
let pipeline = MeetingPipeline()
|
||||
let title = "Встреча " + meetingDateFormatter().string(from: Date())
|
||||
do {
|
||||
let result = try await pipeline.run(audio: recording.url, title: title)
|
||||
log("meeting: протокол готов, реплик \(result.turns.count)")
|
||||
} catch {
|
||||
// Разбор упал, но звук уже на диске - его можно принести в
|
||||
// окно встреч руками и разобрать ещё раз.
|
||||
log("meeting: разбор отказал (\(error)), звук остался в \(recording.url.path)")
|
||||
let date = Date()
|
||||
isBusy = true
|
||||
state = .transcribing
|
||||
let recording = saveMeetingRecording(samples: samples, at: date)
|
||||
isBusy = false
|
||||
state = .ready
|
||||
guard let recording else { return }
|
||||
log("meeting: записано \(Int(recording.seconds)) с в \(recording.url.lastPathComponent)")
|
||||
guard process else { return }
|
||||
processMeetingRecording(recording, at: date)
|
||||
}
|
||||
|
||||
private func saveMeetingRecording(samples: [Float], at date: Date) -> MeetingRecording? {
|
||||
while true {
|
||||
do {
|
||||
return try writeMeetingWAV(samples: samples, sampleRate: SAMPLE_RATE,
|
||||
to: meetingRecordingScratchURL(at: date))
|
||||
} catch {
|
||||
log("meeting: не удалось сохранить звук (\(error))")
|
||||
let alert = NSAlert()
|
||||
alert.alertStyle = .warning
|
||||
alert.messageText = L("meeting.saveFailed", "Не удалось сохранить запись встречи")
|
||||
alert.informativeText = L("meeting.saveFailed.help", "Звук ещё в памяти. Освободи место на диске и повтори сохранение. Если удалить запись, восстановить её будет нельзя.")
|
||||
+ "\n\n" + error.localizedDescription
|
||||
alert.addButton(withTitle: L("meeting.retrySave", "Повторить сохранение"))
|
||||
alert.addButton(withTitle: L("meeting.discardUnsaved", "Удалить несохранённую запись"))
|
||||
guard runMeetingAlert(alert) == .alertFirstButtonReturn else { return nil }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Тот же барьер, что у диктовки: пока встреча разбирается, второй
|
||||
/// распознаватель не запускается ни хоткеем, ни повтором из сообщения.
|
||||
func beginMeetingProcessing() -> UInt64? {
|
||||
guard !isBusy, !isRecording else { return nil }
|
||||
transcriptionGeneration &+= 1
|
||||
isBusy = true
|
||||
state = .transcribing
|
||||
return transcriptionGeneration
|
||||
}
|
||||
|
||||
private func processMeetingRecording(_ recording: MeetingRecording, at date: Date) {
|
||||
guard let generation = beginMeetingProcessing() else { return }
|
||||
let title = L("meeting.title", "Встреча") + " " + meetingDateFormatter().string(from: date)
|
||||
let pipeline = MeetingPipeline(transcriber: AudioFileTranscriber(engine: settings.speechEngine,
|
||||
initialPrompt: whisperDefaultInitialPrompt))
|
||||
pipelineTask = Task { [weak self] in
|
||||
guard let self else { return }
|
||||
defer { self.finishTranscription(generation: generation) }
|
||||
do {
|
||||
let result = try await pipeline.run(audio: recording.url, title: title, at: date)
|
||||
guard !Task.isCancelled, self.transcriptionGeneration == generation else { return }
|
||||
self.finishTranscription(generation: generation)
|
||||
let alert = NSAlert()
|
||||
alert.messageText = L("meeting.protocolReady", "Протокол встречи готов")
|
||||
alert.informativeText = result.artifacts.transcript.path
|
||||
if !result.speakersResolved {
|
||||
alert.informativeText += "\n\n" + L("meeting.speakersUnresolved", "Не удалось разделить говорящих. Текст сохранён одной репликой.")
|
||||
}
|
||||
alert.addButton(withTitle: L("meeting.openProtocol", "Открыть протокол"))
|
||||
alert.addButton(withTitle: L("meeting.showRecording", "Показать запись"))
|
||||
alert.addButton(withTitle: L("meeting.close", "Закрыть"))
|
||||
switch self.runMeetingAlert(alert) {
|
||||
case .alertFirstButtonReturn:
|
||||
if !NSWorkspace.shared.open(result.artifacts.transcript) {
|
||||
NSWorkspace.shared.activateFileViewerSelecting([result.artifacts.transcript])
|
||||
}
|
||||
case .alertSecondButtonReturn:
|
||||
NSWorkspace.shared.activateFileViewerSelecting([result.artifacts.audio])
|
||||
default: break
|
||||
}
|
||||
} catch {
|
||||
guard !Task.isCancelled, self.transcriptionGeneration == generation else { return }
|
||||
self.finishTranscription(generation: generation)
|
||||
let alert = NSAlert()
|
||||
alert.alertStyle = .warning
|
||||
alert.messageText = L("meeting.processingFailed", "Не удалось разобрать встречу")
|
||||
let reason = (error as? MeetingPipelineFailure)?.rawValue ?? error.localizedDescription
|
||||
alert.informativeText = reason + "\n\n"
|
||||
+ L("meeting.recordingSaved", "Запись сохранена. Можно повторить разбор или открыть её в Finder.")
|
||||
+ "\n" + recording.url.path
|
||||
alert.addButton(withTitle: L("meeting.retryProcessing", "Повторить разбор"))
|
||||
alert.addButton(withTitle: L("meeting.showRecording", "Показать запись"))
|
||||
alert.addButton(withTitle: L("meeting.close", "Закрыть"))
|
||||
switch self.runMeetingAlert(alert) {
|
||||
case .alertFirstButtonReturn:
|
||||
self.processMeetingRecording(recording, at: date)
|
||||
case .alertSecondButtonReturn:
|
||||
NSWorkspace.shared.activateFileViewerSelecting([recording.url])
|
||||
default: break
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
log("meeting: не удалось сохранить звук (\(error))")
|
||||
}
|
||||
}
|
||||
|
||||
private func runMeetingAlert(_ alert: NSAlert) -> NSApplication.ModalResponse {
|
||||
// LSUIElement не имеет обычного главного окна; alert должен оказаться
|
||||
// над постоянной floating-плашкой, иначе вопрос останется под ней.
|
||||
alert.window.level = .floating
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
return alert.runModal()
|
||||
}
|
||||
|
||||
/// Кого звать, когда с плашки просят настройки. Ставит приложение: у
|
||||
/// модуля диктовки окна настроек нет и быть не должно.
|
||||
public var onOpenSettings: (() -> Void)?
|
||||
@@ -361,6 +485,12 @@ public final class DictationController {
|
||||
hotkeys.setTranslationHotkeyEnabled(settings.translationModeEnabled)
|
||||
hotkeys.setAlternateCompletionEnabled(settings.alternateCompletionEnabled)
|
||||
hotkeys.setTriggerMode(settings.triggerMode)
|
||||
prepareChangedSpeechModelIfIdle()
|
||||
}
|
||||
|
||||
private func prepareChangedSpeechModelIfIdle() {
|
||||
guard let previous = lastRequestedModelProfile, previous != settings.speechEngine else { return }
|
||||
_ = prepareAfterModelInstallation()
|
||||
}
|
||||
|
||||
private func observeSettings() {
|
||||
@@ -556,7 +686,15 @@ public final class DictationController {
|
||||
}
|
||||
|
||||
public func toggleDictationFromUI() {
|
||||
handlePress(purpose: .dictation)
|
||||
if isRecording {
|
||||
// Кнопка HUD уже показывает «Закончить запись». Завершаем текущий
|
||||
// purpose тем же путём, что хоткей, не меняя встречу на диктовку.
|
||||
hotkeys.resetToggleState()
|
||||
handleRelease(shortcut: .standard,
|
||||
hotkeyDetectedAt: ProcessInfo.processInfo.systemUptime)
|
||||
} else {
|
||||
handlePress(purpose: .dictation)
|
||||
}
|
||||
}
|
||||
|
||||
/// Начать запись для промпта прямо из интерфейса. Тот же вход, что и у
|
||||
@@ -571,6 +709,7 @@ public final class DictationController {
|
||||
}
|
||||
|
||||
private func handlePress(purpose: DictationRecordingPurpose) {
|
||||
prepareChangedSpeechModelIfIdle()
|
||||
if let refusal = startRefusal() {
|
||||
log("dictation: press refused — \(refusal.rawValue)")
|
||||
hud?.startRefused(refusal)
|
||||
@@ -1249,6 +1388,7 @@ public final class DictationController {
|
||||
default:
|
||||
break
|
||||
}
|
||||
prepareChangedSpeechModelIfIdle()
|
||||
}
|
||||
|
||||
private func handleCancel() {
|
||||
@@ -1268,8 +1408,9 @@ public final class DictationController {
|
||||
|
||||
private func scheduleMaxDurationAutoRelease() {
|
||||
maxDurationTask?.cancel()
|
||||
let limit = Self.recordingLimitSeconds(for: recordingPurpose)
|
||||
maxDurationTask = Task { [weak self] in
|
||||
try? await Task.sleep(nanoseconds: UInt64(MAX_RECORDING_SECONDS) * 1_000_000_000)
|
||||
try? await Task.sleep(nanoseconds: UInt64(limit) * 1_000_000_000)
|
||||
guard !Task.isCancelled, let self, self.isRecording else { return }
|
||||
log("dictation: max recording duration reached — auto release")
|
||||
self.hotkeys.resetToggleState()
|
||||
@@ -1278,6 +1419,10 @@ public final class DictationController {
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated static func recordingLimitSeconds(for purpose: DictationRecordingPurpose) -> TimeInterval {
|
||||
purpose == .meeting ? meetingRecordingLimitSeconds : MAX_RECORDING_SECONDS
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
func simulateActiveRecordingForTesting() {
|
||||
audio.beginRecording()
|
||||
|
||||
@@ -122,7 +122,12 @@ public func dictationHUDNextLanguage(after current: DictationLanguage) -> Dictat
|
||||
/// значком без кнопки.
|
||||
final class DictationHUDActionButton: NSView {
|
||||
var action: DictationHUDAction {
|
||||
didSet { if action != oldValue { needsDisplay = true } }
|
||||
didSet {
|
||||
guard action != oldValue else { return }
|
||||
setAccessibilityLabel(action.title)
|
||||
toolTip = action.title
|
||||
needsDisplay = true
|
||||
}
|
||||
}
|
||||
var onPress: ((DictationHUDActionID) -> Void)?
|
||||
/// Кого звать, когда мышь пришла на кнопку или ушла с неё. Владелец
|
||||
@@ -132,6 +137,8 @@ final class DictationHUDActionButton: NSView {
|
||||
var onHover: ((DictationHUDAction?) -> Void)?
|
||||
|
||||
private var pressed = false
|
||||
private let reduceMotion: () -> Bool
|
||||
private var displayOptionsObserver: DictationHUDNotificationObserver?
|
||||
private var hovered = false {
|
||||
didSet {
|
||||
guard hovered != oldValue else { return }
|
||||
@@ -148,6 +155,14 @@ final class DictationHUDActionButton: NSView {
|
||||
guard let layer else { return }
|
||||
layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
|
||||
layer.position = CGPoint(x: frame.midX, y: frame.midY)
|
||||
guard !reduceMotion() else {
|
||||
layer.removeAnimation(forKey: "irizHoverLift")
|
||||
CATransaction.begin()
|
||||
CATransaction.setDisableActions(true)
|
||||
layer.transform = CATransform3DIdentity
|
||||
CATransaction.commit()
|
||||
return
|
||||
}
|
||||
let scale: CGFloat = hovered ? 1.18 : 1
|
||||
let lift = CABasicAnimation(keyPath: "transform.scale")
|
||||
lift.fromValue = layer.value(forKeyPath: "transform.scale") ?? 1
|
||||
@@ -168,12 +183,22 @@ final class DictationHUDActionButton: NSView {
|
||||
}
|
||||
private var tracking: NSTrackingArea?
|
||||
|
||||
init(action: DictationHUDAction) {
|
||||
init(action: DictationHUDAction,
|
||||
reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() },
|
||||
displayOptionsCenter: NotificationCenter = NSWorkspace.shared.notificationCenter) {
|
||||
self.action = action
|
||||
self.reduceMotion = reduceMotion
|
||||
super.init(frame: .zero)
|
||||
setAccessibilityElement(true)
|
||||
setAccessibilityRole(.button)
|
||||
setAccessibilityLabel(action.title)
|
||||
toolTip = action.title
|
||||
displayOptionsObserver = DictationHUDNotificationObserver(displayOptionsCenter.addObserver(
|
||||
forName: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification,
|
||||
object: nil, queue: .main
|
||||
) { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.applyHoverLift() }
|
||||
}, center: displayOptionsCenter)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
@@ -181,6 +206,12 @@ final class DictationHUDActionButton: NSView {
|
||||
|
||||
override var isFlipped: Bool { true }
|
||||
|
||||
override func accessibilityPerformPress() -> Bool {
|
||||
guard !isHiddenOrHasHiddenAncestor, let onPress else { return false }
|
||||
onPress(action.id)
|
||||
return true
|
||||
}
|
||||
|
||||
override func updateTrackingAreas() {
|
||||
if let tracking { removeTrackingArea(tracking) }
|
||||
let area = NSTrackingArea(rect: .zero,
|
||||
@@ -214,7 +245,7 @@ final class DictationHUDActionButton: NSView {
|
||||
pressed = false
|
||||
needsDisplay = true
|
||||
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
|
||||
onPress?(action.id)
|
||||
_ = accessibilityPerformPress()
|
||||
}
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
// Порядок показа плашки «идёт голос»: что и когда попадает на экран.
|
||||
//
|
||||
// Здесь нет ни AppKit, ни решений — решения в DictationHUD.swift, рисование в
|
||||
// Решения в DictationHUD.swift, рисование в
|
||||
// DictationHUDWindow.swift. Такое разделение позволяет проверить тестом всё
|
||||
// поведение (что показали, что погасили, крутится ли опрос уровня), ни разу не
|
||||
// поднимая живое окно: под `swift test` его и не поднять.
|
||||
import Foundation
|
||||
import AppKit
|
||||
|
||||
/// Поверхность, на которой плашка рисуется. Единственная реализация в продукте —
|
||||
/// `DictationHUDPanelSurface` (NSPanel). В тестах подставляется запоминающая
|
||||
@@ -112,6 +113,7 @@ final class DictationHUDPresenter {
|
||||
|
||||
private var surface: DictationHUDSurface?
|
||||
private var dismissTimer: Timer?
|
||||
private var displayOptionsObserver: DictationHUDNotificationObserver?
|
||||
private var smoothedLevel: Float = 0
|
||||
private var lastLevelSequence: UInt64?
|
||||
private var sameLevelSequenceTicks = 0
|
||||
@@ -131,6 +133,7 @@ final class DictationHUDPresenter {
|
||||
recordingPurpose: @escaping () -> DictationRecordingPurpose = { .dictation },
|
||||
reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() },
|
||||
pump: DictationHUDLevelPump = DictationHUDLevelPump(),
|
||||
displayOptionsCenter: NotificationCenter = NSWorkspace.shared.notificationCenter,
|
||||
surface: @escaping () -> DictationHUDSurface = { DictationHUDPanelSurface() }) {
|
||||
self.levelSnapshot = levelSnapshot
|
||||
self.staleGuardEnabled = true
|
||||
@@ -145,6 +148,7 @@ final class DictationHUDPresenter {
|
||||
self.pump = pump
|
||||
self.makeSurface = surface
|
||||
pump.onTick = { [weak self] in self?.render() }
|
||||
observeDisplayOptions(in: displayOptionsCenter)
|
||||
}
|
||||
|
||||
/// Совместимость тестов и простых поверхностей без sequence. Живой продукт
|
||||
@@ -155,6 +159,7 @@ final class DictationHUDPresenter {
|
||||
recordingPurpose: @escaping () -> DictationRecordingPurpose = { .dictation },
|
||||
reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() },
|
||||
pump: DictationHUDLevelPump = DictationHUDLevelPump(),
|
||||
displayOptionsCenter: NotificationCenter = NSWorkspace.shared.notificationCenter,
|
||||
surface: @escaping () -> DictationHUDSurface = { DictationHUDPanelSurface() }) {
|
||||
self.levelSnapshot = { (level(), 0) }
|
||||
self.staleGuardEnabled = false
|
||||
@@ -169,6 +174,18 @@ final class DictationHUDPresenter {
|
||||
self.pump = pump
|
||||
self.makeSurface = surface
|
||||
pump.onTick = { [weak self] in self?.render() }
|
||||
observeDisplayOptions(in: displayOptionsCenter)
|
||||
}
|
||||
|
||||
private func observeDisplayOptions(in center: NotificationCenter) {
|
||||
displayOptionsObserver = DictationHUDNotificationObserver(center.addObserver(
|
||||
forName: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification,
|
||||
object: nil, queue: .main
|
||||
) { [weak self] _ in
|
||||
// Ожидание и покой не опрашивают уровень: без уведомления уже
|
||||
// открытая плашка не узнаёт, что владелец изменил Reduce Motion.
|
||||
MainActor.assumeIsolated { self?.render() }
|
||||
}, center: center)
|
||||
}
|
||||
|
||||
// MARK: - Входы конвейера
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
// у неё нет подписей, она говорит цветом и формой. Панель - другое: её работа
|
||||
// и есть показать текст.
|
||||
import AppKit
|
||||
import IrizCore
|
||||
|
||||
/// Сколько строк займёт текст на самом деле.
|
||||
///
|
||||
@@ -298,14 +299,33 @@ final class DictationHUDTranscriptView: NSView {
|
||||
/// на любом фоне.
|
||||
final class DictationHUDCopyPill: NSView {
|
||||
var title: String = "" {
|
||||
didSet { if title != oldValue { needsDisplay = true } }
|
||||
didSet {
|
||||
guard title != oldValue else { return }
|
||||
setAccessibilityLabel(title)
|
||||
needsDisplay = true
|
||||
}
|
||||
}
|
||||
var onPress: (() -> Void)?
|
||||
|
||||
private var pressed = false
|
||||
|
||||
override init(frame frameRect: NSRect) {
|
||||
super.init(frame: frameRect)
|
||||
setAccessibilityElement(true)
|
||||
setAccessibilityRole(.button)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) не поддерживается") }
|
||||
|
||||
override var isFlipped: Bool { true }
|
||||
|
||||
override func accessibilityPerformPress() -> Bool {
|
||||
guard !isHiddenOrHasHiddenAncestor, let onPress else { return false }
|
||||
onPress()
|
||||
return true
|
||||
}
|
||||
|
||||
var fittingWidth: CGFloat {
|
||||
(title as NSString).size(withAttributes: [.font: Self.font]).width + 26
|
||||
}
|
||||
@@ -321,7 +341,7 @@ final class DictationHUDCopyPill: NSView {
|
||||
pressed = false
|
||||
needsDisplay = true
|
||||
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
|
||||
onPress?()
|
||||
_ = accessibilityPerformPress()
|
||||
}
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
@@ -359,8 +379,24 @@ final class DictationHUDCloseRing: NSView {
|
||||
|
||||
private var pressed = false
|
||||
|
||||
override init(frame frameRect: NSRect) {
|
||||
super.init(frame: frameRect)
|
||||
setAccessibilityElement(true)
|
||||
setAccessibilityRole(.button)
|
||||
setAccessibilityLabel(L("common.close", "Закрыть"))
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) не поддерживается") }
|
||||
|
||||
override var isFlipped: Bool { true }
|
||||
|
||||
override func accessibilityPerformPress() -> Bool {
|
||||
guard !isHiddenOrHasHiddenAncestor, let onPress else { return false }
|
||||
onPress()
|
||||
return true
|
||||
}
|
||||
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
pressed = true
|
||||
needsDisplay = true
|
||||
@@ -370,7 +406,7 @@ final class DictationHUDCloseRing: NSView {
|
||||
pressed = false
|
||||
needsDisplay = true
|
||||
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
|
||||
onPress?()
|
||||
_ = accessibilityPerformPress()
|
||||
}
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
|
||||
@@ -4,12 +4,17 @@
|
||||
import AppKit
|
||||
import Foundation
|
||||
import QuartzCore
|
||||
import IrizCore
|
||||
|
||||
private final class DictationHUDNotificationObserver: @unchecked Sendable {
|
||||
final class DictationHUDNotificationObserver: @unchecked Sendable {
|
||||
let token: NSObjectProtocol
|
||||
private let center: NotificationCenter
|
||||
|
||||
init(_ token: NSObjectProtocol) { self.token = token }
|
||||
deinit { NotificationCenter.default.removeObserver(token) }
|
||||
init(_ token: NSObjectProtocol, center: NotificationCenter = .default) {
|
||||
self.token = token
|
||||
self.center = center
|
||||
}
|
||||
deinit { center.removeObserver(token) }
|
||||
}
|
||||
|
||||
private final class DictationHUDDisplayLinkStorage: @unchecked Sendable {
|
||||
@@ -941,6 +946,13 @@ final class DictationHUDPanelSurface: NSObject, DictationHUDSurface, DictationHU
|
||||
container.delegate = self
|
||||
container.setAccessibilityElement(true)
|
||||
container.setAccessibilityRole(.group)
|
||||
container.setAccessibilityCustomActions([
|
||||
NSAccessibilityCustomAction(name: L("hud.toggleExpanded", "Развернуть или свернуть плашку")) { [weak self] in
|
||||
guard let handler = self?.openToggledHandler else { return false }
|
||||
handler()
|
||||
return true
|
||||
}
|
||||
])
|
||||
let capsule = DictationHUDCapsuleView(frame: CGRect(origin: .zero,
|
||||
size: DICTATION_HUD_BASE_SIZE))
|
||||
let hint = DictationHUDHintView(frame: .zero)
|
||||
@@ -1292,9 +1304,16 @@ final class DictationHUDPanelSurface: NSObject, DictationHUDSurface, DictationHU
|
||||
}
|
||||
if reduceMotionEnabled() {
|
||||
stopMotion()
|
||||
hoverProgress = hoverAnimation?.to ?? hoverProgress
|
||||
hoverAnimation = nil
|
||||
hint?.appearanceProgress = hoverProgress
|
||||
// Уже начатый морф тоже завершается при смене настройки.
|
||||
transcriptProgress = transcriptTarget
|
||||
advanceTranscript(dt: 0)
|
||||
revealAnimation = nil
|
||||
revealProgress = 1
|
||||
capsule?.revealProgress = 1
|
||||
layoutPanel(display: true)
|
||||
} else {
|
||||
startMotionIfNeeded()
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import IrizCore
|
||||
/// сортировки и то, что показывается владельцу. Ключ именно имя, а не mtime:
|
||||
/// после импорта из старого приложения mtime врёт (см. PromptEnvelope.swift,
|
||||
/// `latestDictation`) — папки пишутся на диск в обратном порядку номеров.
|
||||
public struct DictationHistoryEntry: Equatable, Identifiable {
|
||||
public struct DictationHistoryEntry: Equatable, Identifiable, Sendable {
|
||||
let directory: URL
|
||||
public let label: String
|
||||
/// Сырьё — ответ ASR байт в байт. Есть всегда, иначе записи нет.
|
||||
@@ -66,11 +66,16 @@ public let DICTATION_HISTORY_KEEP_LIMIT = 500
|
||||
/// никогда.
|
||||
public func dictationHistoryDirectories(in dictationsRoot: URL,
|
||||
fileManager: FileManager = .default) -> [URL] {
|
||||
let urls = (try? fileManager.contentsOfDirectory(
|
||||
(try? readDictationHistoryDirectories(in: dictationsRoot, fileManager: fileManager)) ?? []
|
||||
}
|
||||
|
||||
private func readDictationHistoryDirectories(in dictationsRoot: URL,
|
||||
fileManager: FileManager) throws -> [URL] {
|
||||
let urls = try fileManager.contentsOfDirectory(
|
||||
at: dictationsRoot,
|
||||
includingPropertiesForKeys: [.isDirectoryKey],
|
||||
options: [.skipsHiddenFiles]
|
||||
)) ?? []
|
||||
)
|
||||
return urls
|
||||
.filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true }
|
||||
.sorted { $0.lastPathComponent > $1.lastPathComponent }
|
||||
@@ -79,7 +84,14 @@ public func dictationHistoryDirectories(in dictationsRoot: URL,
|
||||
public func dictationHistoryEntries(in dictationsRoot: URL,
|
||||
limit: Int? = nil,
|
||||
fileManager: FileManager = .default) -> [DictationHistoryEntry] {
|
||||
var directories = dictationHistoryDirectories(in: dictationsRoot, fileManager: fileManager)
|
||||
(try? readDictationHistoryEntries(in: dictationsRoot, limit: limit, fileManager: fileManager)) ?? []
|
||||
}
|
||||
|
||||
/// Для интерфейса: недоступный каталог — ошибка, а не пустая история.
|
||||
public func readDictationHistoryEntries(in dictationsRoot: URL,
|
||||
limit: Int? = nil,
|
||||
fileManager: FileManager = .default) throws -> [DictationHistoryEntry] {
|
||||
var directories = try readDictationHistoryDirectories(in: dictationsRoot, fileManager: fileManager)
|
||||
// Обрезаем ДО чтения содержимого: смысл потолка в том, чтобы не открывать
|
||||
// тысячи файлов, а не в том, чтобы открыть их и показать сотню.
|
||||
if let limit, directories.count > limit { directories = Array(directories.prefix(limit)) }
|
||||
@@ -199,7 +211,8 @@ enum DictationHistoryKeyAction: Equatable {
|
||||
|
||||
func dictationHistoryKeyAction(keyCode: CGKeyCode,
|
||||
charactersIgnoringModifiers: String?,
|
||||
hasCommand: Bool) -> DictationHistoryKeyAction {
|
||||
hasCommand: Bool,
|
||||
hasTextSelection: Bool = false) -> DictationHistoryKeyAction {
|
||||
if hasCommand {
|
||||
// ⌘⌫ здесь СОЗНАТЕЛЬНО не занят. Это документированный системный
|
||||
// шорткат текстового поля («удалить от курсора до начала строки»), а
|
||||
@@ -208,7 +221,7 @@ func dictationHistoryKeyAction(keyCode: CGKeyCode,
|
||||
// расшифровку речи клиента. Удаление живёт в контекстном меню, где его
|
||||
// нельзя нажать не глядя.
|
||||
switch charactersIgnoringModifiers?.lowercased() {
|
||||
case "c": return .copySelected
|
||||
case "c": return hasTextSelection ? .passThrough : .copySelected
|
||||
default: return .passThrough
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,9 +59,14 @@ func pasteboardRestoreDecision(transientChangeCount: Int?,
|
||||
}
|
||||
|
||||
@MainActor
|
||||
enum DictationHistoryClipboard {
|
||||
public enum DictationHistoryClipboard {
|
||||
private static var pending: HistoryClipboardTransaction?
|
||||
|
||||
/// Общий путь копирования для настроек и плавающего окна.
|
||||
public static func copy(_ text: String) -> Bool {
|
||||
copy(text, pasteboard: .general)
|
||||
}
|
||||
|
||||
/// Кладёт текст в буфер. `false` — буфер отказал, вызывающий обязан сказать
|
||||
/// владельцу, что копирование не состоялось.
|
||||
///
|
||||
@@ -69,7 +74,7 @@ enum DictationHistoryClipboard {
|
||||
/// дописывает в живой лог владельца.
|
||||
@discardableResult
|
||||
static func copy(_ text: String,
|
||||
pasteboard: NSPasteboard = .general,
|
||||
pasteboard: NSPasteboard,
|
||||
hold: TimeInterval = HISTORY_CLIPBOARD_HOLD_SECONDS,
|
||||
logLine: @escaping (String) -> Void = { log($0) }) -> Bool {
|
||||
quench(reason: "вытеснено следующим копированием")
|
||||
|
||||
@@ -35,6 +35,7 @@ final class DictationHistoryPresenter {
|
||||
/// Поднят лист подтверждения «очистить всё». Пока он висит, клавиши окна
|
||||
/// не работают: Escape обязан закрывать вопрос, а не всё окно под ним.
|
||||
private var isConfirming = false
|
||||
private var presentationGeneration = 0
|
||||
private let dictationsRoot: () throws -> URL
|
||||
|
||||
init(dictationsRoot: @escaping () throws -> URL = { try DictationStore.dictationsDirectory() }) {
|
||||
@@ -59,6 +60,7 @@ final class DictationHistoryPresenter {
|
||||
// MARK: - Показ
|
||||
|
||||
private func present(rescue: DictationRescue?) {
|
||||
presentationGeneration += 1
|
||||
let entries: [DictationHistoryEntry]
|
||||
if rescue == nil {
|
||||
// Список читается ПОСЛЕ показа окна, в фоне. Владелец: «открываю
|
||||
@@ -116,12 +118,7 @@ final class DictationHistoryPresenter {
|
||||
model.focusSearchField = rescue == nil
|
||||
installKeyMonitor()
|
||||
if rescue == nil {
|
||||
model.didLoadAll = false
|
||||
model.onSearchStarted = { [weak self, weak model] in
|
||||
guard let self, let model else { return }
|
||||
self.loadAllForSearch(into: model)
|
||||
}
|
||||
loadEntriesInBackground(into: model)
|
||||
model.reload(from: dictationsRoot)
|
||||
}
|
||||
if let rescue {
|
||||
// Ни имени приложения, ни самого текста в логе: лог живёт на диске
|
||||
@@ -133,55 +130,6 @@ final class DictationHistoryPresenter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Прочитать надиктовки с диска и отдать их окну, когда прочитаются.
|
||||
///
|
||||
/// Отдельным ходом, а не внутри показа: чтение занимает секунды на большом
|
||||
/// каталоге, а окно обязано открыться мгновенно. Пока список едет, в окне
|
||||
/// стоит честная строка «Читаю надиктовки…», а не пустота, которую легко
|
||||
/// прочитать как «ничего нет».
|
||||
private func loadEntriesInBackground(into model: DictationHistoryModel) {
|
||||
model.isLoading = true
|
||||
let root = try? dictationsRoot()
|
||||
guard let root else {
|
||||
model.isLoading = false
|
||||
log("history: cannot reach dictations directory")
|
||||
return
|
||||
}
|
||||
Task.detached(priority: .userInitiated) {
|
||||
let startedAt = ProcessInfo.processInfo.systemUptime
|
||||
let found = dictationHistoryEntries(in: root, limit: DICTATION_HISTORY_VISIBLE_LIMIT)
|
||||
let spent = (ProcessInfo.processInfo.systemUptime - startedAt) * 1000
|
||||
await MainActor.run {
|
||||
model.load(found)
|
||||
model.isLoading = false
|
||||
log(String(format: "history: %d записей прочитано за %.0f мс (в фоне)",
|
||||
found.count, spent))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Догрузить остальное хранимое - по первому же поиску.
|
||||
///
|
||||
/// Окно открывается сотней свежих: их хватает, чтобы забрать вчерашнее.
|
||||
/// Но поиск по сотне врал бы молча - человек ищет фразу, которая лежит
|
||||
/// двухсотой, и получает «ничего не нашлось». Поэтому первый ввод в поле
|
||||
/// поиска дочитывает всё, что хранится, и делает это один раз за показ.
|
||||
private func loadAllForSearch(into model: DictationHistoryModel) {
|
||||
guard !model.didLoadAll else { return }
|
||||
model.didLoadAll = true
|
||||
guard let root = try? dictationsRoot() else { return }
|
||||
Task.detached(priority: .userInitiated) {
|
||||
let startedAt = ProcessInfo.processInfo.systemUptime
|
||||
let found = dictationHistoryEntries(in: root, limit: DICTATION_HISTORY_KEEP_LIMIT)
|
||||
let spent = (ProcessInfo.processInfo.systemUptime - startedAt) * 1000
|
||||
await MainActor.run {
|
||||
model.load(found)
|
||||
log(String(format: "history: поиск дочитал %d записей за %.0f мс",
|
||||
found.count, spent))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func makePanel(model: DictationHistoryModel) -> DictationHistoryPanel {
|
||||
let panel = DictationHistoryPanel(
|
||||
contentRect: historyPanelFrame(),
|
||||
@@ -241,7 +189,10 @@ final class DictationHistoryPresenter {
|
||||
// MARK: - Закрытие и возврат фокуса
|
||||
|
||||
private func close(returningFocus: Bool) {
|
||||
presentationGeneration += 1
|
||||
removeKeyMonitor()
|
||||
model?.cancelLoading()
|
||||
model?.isClearing = false
|
||||
model?.focusSearchField = false
|
||||
// Спасённый текст живёт ровно столько, сколько висит окно. Иначе
|
||||
// следующее открытие истории по хоткею подняло бы чужую позавчерашнюю
|
||||
@@ -400,6 +351,7 @@ final class DictationHistoryPresenter {
|
||||
|
||||
private func copy(text: String) {
|
||||
guard DictationHistoryClipboard.copy(text) else {
|
||||
model?.showError(L("history.copyFailed", "Не удалось скопировать. Попробуй ещё раз."))
|
||||
if DictationSettings.shared.playFeedbackSounds { Sounds.playError() }
|
||||
return
|
||||
}
|
||||
@@ -407,21 +359,49 @@ final class DictationHistoryPresenter {
|
||||
}
|
||||
|
||||
private func delete(_ entry: DictationHistoryEntry) {
|
||||
guard model?.isClearing != true else { return }
|
||||
do {
|
||||
try removeDictationHistoryEntry(entry)
|
||||
log("history: entry \(entry.label) moved to Trash with its directory")
|
||||
reload()
|
||||
} catch {
|
||||
log("history: cannot delete \(entry.label): \(error.localizedDescription)")
|
||||
model?.showError(L("history.deleteFailed", "Не удалось переместить запись в Корзину. Попробуй ещё раз."))
|
||||
if DictationSettings.shared.playFeedbackSounds { Sounds.playError() }
|
||||
}
|
||||
reload()
|
||||
}
|
||||
|
||||
private func clearAll() {
|
||||
guard let model, let panel, !model.entries.isEmpty, !isConfirming else { return }
|
||||
guard let model, let panel, !model.entries.isEmpty, !isConfirming, !model.isClearing else { return }
|
||||
let generation = presentationGeneration
|
||||
model.isClearing = true
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
do {
|
||||
let root = try self.dictationsRoot()
|
||||
let doomed = try await Task.detached(priority: .userInitiated) {
|
||||
try readDictationHistoryEntries(in: root)
|
||||
}.value
|
||||
guard self.presentationGeneration == generation, panel.isVisible else { return }
|
||||
guard !doomed.isEmpty else {
|
||||
model.isClearing = false
|
||||
self.reload()
|
||||
return
|
||||
}
|
||||
self.confirmClearAll(doomed, model: model, panel: panel)
|
||||
} catch {
|
||||
guard self.presentationGeneration == generation else { return }
|
||||
model.isClearing = false
|
||||
model.showError(L("history.readFailed", "Не удалось прочитать историю. Попробуй открыть её снова."))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func confirmClearAll(_ doomed: [DictationHistoryEntry],
|
||||
model: DictationHistoryModel,
|
||||
panel: DictationHistoryPanel) {
|
||||
// Число записей — ДО удаления и в самом вопросе: иначе владелец
|
||||
// подтверждает вслепую.
|
||||
let doomed = model.entries
|
||||
// подтверждает вслепую. Снимок включает весь архив, а не видимую сотню.
|
||||
let alert = NSAlert()
|
||||
alert.alertStyle = .warning
|
||||
alert.messageText = dictationHistoryClearConfirmation(count: doomed.count)
|
||||
@@ -438,31 +418,37 @@ final class DictationHistoryPresenter {
|
||||
guard let self else { return }
|
||||
self.isConfirming = false
|
||||
guard response == .alertFirstButtonReturn else {
|
||||
model.isClearing = false
|
||||
log("history: clear all cancelled (\(doomed.count) entries kept)")
|
||||
return
|
||||
}
|
||||
var deleted = 0
|
||||
for entry in doomed {
|
||||
do {
|
||||
try removeDictationHistoryEntry(entry)
|
||||
deleted += 1
|
||||
} catch {
|
||||
log("history: cannot delete \(entry.label): \(error.localizedDescription)")
|
||||
Task { @MainActor in
|
||||
let deleted = await Task.detached(priority: .userInitiated) {
|
||||
var deleted = 0
|
||||
for entry in doomed {
|
||||
do {
|
||||
try removeDictationHistoryEntry(entry)
|
||||
deleted += 1
|
||||
} catch {
|
||||
log("history: cannot delete \(entry.label): \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
return deleted
|
||||
}.value
|
||||
model.isClearing = false
|
||||
log("history: cleared \(deleted) of \(doomed.count) entries")
|
||||
self.reload()
|
||||
if deleted != doomed.count {
|
||||
model.showError(Lf("history.clearFailed", "Не удалось переместить в Корзину: %d из %d. Остальные записи уже в Корзине.", doomed.count - deleted, doomed.count))
|
||||
}
|
||||
}
|
||||
log("history: cleared \(deleted) of \(doomed.count) entries")
|
||||
self.reload()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func reload() {
|
||||
guard let model else { return }
|
||||
do {
|
||||
model.load(dictationHistoryEntries(in: try dictationsRoot()))
|
||||
} catch {
|
||||
log("history: cannot reach dictations directory: \(error.localizedDescription)")
|
||||
}
|
||||
model.reload(from: dictationsRoot)
|
||||
}
|
||||
|
||||
// MARK: - Клавиши
|
||||
@@ -488,10 +474,14 @@ final class DictationHistoryPresenter {
|
||||
/// `true` — нажатие съедено окном, в поле поиска не уходит.
|
||||
private func handle(_ event: NSEvent) -> Bool {
|
||||
guard let model, !isConfirming else { return false }
|
||||
// Выделенный текст принадлежит редактору поиска/спасения: ⌘C должен
|
||||
// копировать именно выделение, не выбранную запись и не закрывать окно.
|
||||
let editor = panel?.firstResponder as? NSTextView
|
||||
let action = dictationHistoryKeyAction(
|
||||
keyCode: CGKeyCode(event.keyCode),
|
||||
charactersIgnoringModifiers: event.charactersIgnoringModifiers,
|
||||
hasCommand: event.modifierFlags.contains(.command)
|
||||
hasCommand: event.modifierFlags.contains(.command),
|
||||
hasTextSelection: (editor?.selectedRange().length ?? 0) > 0
|
||||
)
|
||||
// В режиме спасения списка на экране нет, и те же клавиши обязаны
|
||||
// относиться к спасённому тексту, а не к невидимой выделенной записи.
|
||||
@@ -549,15 +539,18 @@ private final class DictationHistoryPanel: NSPanel {
|
||||
// MARK: - Модель списка
|
||||
|
||||
@MainActor
|
||||
final class DictationHistoryModel: ObservableObject {
|
||||
@Published private(set) var entries: [DictationHistoryEntry] = []
|
||||
@Published var query: String = "" {
|
||||
public final class DictationHistoryModel: ObservableObject {
|
||||
@Published public private(set) var entries: [DictationHistoryEntry] = []
|
||||
@Published public var query: String = "" {
|
||||
didSet {
|
||||
guard query != oldValue else { return }
|
||||
clampSelection()
|
||||
// Первый же символ запроса дочитывает всё хранимое: искать по
|
||||
// видимой сотне значит молча врать «ничего не нашлось».
|
||||
if !query.isEmpty { onSearchStarted?() }
|
||||
if !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
||||
!didLoadAll, !isLoadingAll, let root {
|
||||
loadInBackground(from: root, all: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@Published private(set) var selection: Int = 0
|
||||
@@ -565,12 +558,21 @@ final class DictationHistoryModel: ObservableObject {
|
||||
/// Список ещё читается с диска. Отдельный признак, а не пустой список:
|
||||
/// «пока ничего нет» и «ещё не прочитал» - разные вещи, и путать их значит
|
||||
/// врать владельцу, у которого две тысячи надиктовок.
|
||||
@Published var isLoading = false
|
||||
@Published public private(set) var isLoading = false
|
||||
@Published public var notice: String?
|
||||
@Published public var noticeIsError = false
|
||||
@Published var isClearing = false
|
||||
/// Дочитано ли всё хранимое. Показ начинается с сотни свежих; поиск
|
||||
/// дочитывает остальное один раз.
|
||||
var didLoadAll = false
|
||||
/// Кого звать, когда владелец начал искать.
|
||||
var onSearchStarted: (() -> Void)?
|
||||
private(set) var didLoadAll = false
|
||||
private var isLoadingAll = false
|
||||
private var loadGeneration = 0
|
||||
private var root: URL?
|
||||
private let isPreview: Bool
|
||||
|
||||
public init(preview: Bool = false) {
|
||||
isPreview = preview
|
||||
}
|
||||
/// Не `nil` — окно показывает не список, а текст, который не доехал до поля.
|
||||
@Published private(set) var rescue: DictationRescue?
|
||||
/// Почему не сработал повтор вставки. Звука тут мало: владелец должен
|
||||
@@ -587,8 +589,77 @@ final class DictationHistoryModel: ObservableObject {
|
||||
var onInsertRescue: (() -> Void)?
|
||||
var onCopyRescue: (() -> Void)?
|
||||
|
||||
var visible: [DictationHistoryEntry] {
|
||||
filteredDictationHistory(entries, query: query)
|
||||
public var visible: [DictationHistoryEntry] {
|
||||
query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
? Array(entries.prefix(DICTATION_HISTORY_VISIBLE_LIMIT))
|
||||
: filteredDictationHistory(entries, query: query)
|
||||
}
|
||||
|
||||
/// Превью проверяется ДО получения корня: даже путь к живому store не нужен.
|
||||
public func reload(from rootProvider: () throws -> URL) {
|
||||
cancelLoading()
|
||||
didLoadAll = false
|
||||
guard !isPreview else {
|
||||
load([])
|
||||
return
|
||||
}
|
||||
do {
|
||||
let root = try rootProvider()
|
||||
self.root = root
|
||||
loadInBackground(from: root,
|
||||
all: !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
} catch {
|
||||
showError(L("history.readFailed", "Не удалось прочитать историю. Попробуй открыть её снова."))
|
||||
}
|
||||
}
|
||||
|
||||
public func cancelLoading() {
|
||||
loadGeneration += 1
|
||||
isLoading = false
|
||||
isLoadingAll = false
|
||||
root = nil
|
||||
}
|
||||
|
||||
func showError(_ message: String) {
|
||||
notice = message
|
||||
noticeIsError = true
|
||||
}
|
||||
|
||||
private func loadInBackground(from root: URL, all: Bool) {
|
||||
let generation = beginLoading(all: all)
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
let result = Result {
|
||||
// ponytail: весь архив читается лишь при поиске; индекс нужен,
|
||||
// если измеренное время чтения станет мешать поиску.
|
||||
try readDictationHistoryEntries(in: root,
|
||||
limit: all ? nil : DICTATION_HISTORY_VISIBLE_LIMIT)
|
||||
}
|
||||
await self?.completeLoading(result, generation: generation, all: all)
|
||||
}
|
||||
}
|
||||
|
||||
/// Поколение общее для краткого списка, поиска и повторного открытия.
|
||||
func beginLoading(all: Bool) -> Int {
|
||||
loadGeneration += 1
|
||||
isLoading = true
|
||||
isLoadingAll = all
|
||||
notice = nil
|
||||
noticeIsError = false
|
||||
return loadGeneration
|
||||
}
|
||||
|
||||
func completeLoading(_ result: Result<[DictationHistoryEntry], Error>,
|
||||
generation: Int, all: Bool) {
|
||||
guard generation == loadGeneration else { return }
|
||||
isLoading = false
|
||||
isLoadingAll = false
|
||||
switch result {
|
||||
case .success(let found):
|
||||
load(found)
|
||||
didLoadAll = all
|
||||
case .failure:
|
||||
showError(L("history.readFailed", "Не удалось прочитать историю. Попробуй открыть её снова."))
|
||||
}
|
||||
}
|
||||
|
||||
var selectedEntry: DictationHistoryEntry? {
|
||||
@@ -661,7 +732,13 @@ struct DictationHistoryView: View {
|
||||
|
||||
Group {
|
||||
if model.visible.isEmpty {
|
||||
emptyState
|
||||
if let notice = model.notice, model.noticeIsError {
|
||||
Label(notice, systemImage: "exclamationmark.circle")
|
||||
.foregroundStyle(.red)
|
||||
.padding(24)
|
||||
} else {
|
||||
emptyState
|
||||
}
|
||||
} else {
|
||||
list
|
||||
}
|
||||
@@ -669,6 +746,17 @@ struct DictationHistoryView: View {
|
||||
.frame(maxHeight: .infinity)
|
||||
.background(IrizFloatingPlate())
|
||||
|
||||
if model.isLoading, !model.entries.isEmpty {
|
||||
ProgressView(L("history.loading", "Читаю надиктовки…"))
|
||||
.controlSize(.small)
|
||||
}
|
||||
if let notice = model.notice, !model.entries.isEmpty {
|
||||
Label(notice, systemImage: model.noticeIsError ? "exclamationmark.circle" : "checkmark.circle")
|
||||
.foregroundStyle(model.noticeIsError ? Color.red : Color.primary)
|
||||
.font(.system(size: 12))
|
||||
.padding(.horizontal, 12)
|
||||
}
|
||||
|
||||
footer
|
||||
.background(IrizFloatingPlate())
|
||||
}
|
||||
@@ -739,6 +827,11 @@ struct DictationHistoryView: View {
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
.accessibilityLabel(notice)
|
||||
}
|
||||
if let notice = model.notice {
|
||||
Label(notice, systemImage: "exclamationmark.circle")
|
||||
.foregroundStyle(.red)
|
||||
.font(.system(size: 12))
|
||||
}
|
||||
|
||||
HStack(spacing: 12) {
|
||||
hint("⏎", L("history.legendInsert", "вставить"))
|
||||
@@ -796,6 +889,7 @@ struct DictationHistoryView: View {
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help(L("history.searchClear", "Очистить поиск"))
|
||||
.accessibilityLabel(L("history.searchClear", "Очистить поиск"))
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 10)
|
||||
@@ -835,10 +929,16 @@ struct DictationHistoryView: View {
|
||||
ScrollView {
|
||||
LazyVStack(spacing: 2) {
|
||||
ForEach(Array(model.visible.enumerated()), id: \.element.id) { index, entry in
|
||||
row(entry, isSelected: index == model.selection)
|
||||
.id(entry.id)
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture { model.select(entry) }
|
||||
Button { model.select(entry) } label: {
|
||||
row(entry, isSelected: index == model.selection)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.accessibilityElement(children: .combine)
|
||||
.accessibilityAddTraits(index == model.selection ? .isSelected : [])
|
||||
.accessibilityAction(named: Text(L("history.insert", "Вставить"))) { model.onInsert?(entry) }
|
||||
.accessibilityAction(named: Text(L("history.copyButton", "Копировать"))) { model.onCopy?(entry) }
|
||||
.id(entry.id)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 6)
|
||||
@@ -888,6 +988,7 @@ struct DictationHistoryView: View {
|
||||
Button(L("history.copyButton", "Копировать")) { model.onCopy?(entry) }
|
||||
Divider()
|
||||
Button(L("history.trashOne", "Переместить в Корзину"), role: .destructive) { model.onDelete?(entry) }
|
||||
.disabled(model.isClearing)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -900,6 +1001,10 @@ struct DictationHistoryView: View {
|
||||
/// место под строкой.
|
||||
private var footer: some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
if model.isClearing {
|
||||
ProgressView(L("history.clearing", "Подготовка и очистка истории…"))
|
||||
.controlSize(.small)
|
||||
}
|
||||
HStack(spacing: 12) {
|
||||
hint("⏎", L("history.legendInsert", "вставить"))
|
||||
hint("⌘C", L("history.legendCopy", "копировать"))
|
||||
@@ -922,6 +1027,11 @@ struct DictationHistoryView: View {
|
||||
.font(.system(size: 11))
|
||||
.foregroundStyle(IRIZ_SUBTLE)
|
||||
.accessibilityLabel(L("history.clipboardNoteVoice", "Скопированное держится в буфере две минуты, потом буфер чистится"))
|
||||
if model.query.isEmpty, model.entries.count >= DICTATION_HISTORY_VISIBLE_LIMIT {
|
||||
Text(L("history.loadingBody", "Показываю последние сто. Остальные найдёт поиск."))
|
||||
.font(.system(size: 11))
|
||||
.foregroundStyle(IRIZ_SUBTLE)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 8)
|
||||
@@ -936,11 +1046,11 @@ struct DictationHistoryView: View {
|
||||
if #available(macOS 26.0, *) {
|
||||
Button(action: { model.onClearAll?() }) { label }
|
||||
.buttonStyle(.glass)
|
||||
.disabled(model.entries.isEmpty)
|
||||
.disabled(model.entries.isEmpty || model.isClearing)
|
||||
.help(L("history.clearAllHint", "Переместить все надиктовки в Корзину"))
|
||||
} else {
|
||||
Button(action: { model.onClearAll?() }) { label }
|
||||
.disabled(model.entries.isEmpty)
|
||||
.disabled(model.entries.isEmpty || model.isClearing)
|
||||
.help(L("history.clearAllHint", "Переместить все надиктовки в Корзину"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,20 @@ public enum MeetingPipelineFailure: String, Error, Equatable {
|
||||
case storeFailed = "не удалось сохранить встречу на диск"
|
||||
}
|
||||
|
||||
/// Whisper может вернуть текст без времён слов. Успешная диаризация сама по
|
||||
/// себе ещё не связывает слова с людьми: весь исходный текст должен сохраниться.
|
||||
func meetingSpeakerTurns(transcript: AudioFileTranscript, spans: [SpeakerSpan],
|
||||
names: SpeakerNames = SpeakerNames())
|
||||
-> (turns: [SpeakerTurn], speakersResolved: Bool) {
|
||||
let turns = speakerTurnsNamed(speakerTurns(tokens: transcript.tokenTimings, spans: spans), names: names)
|
||||
guard !spans.isEmpty,
|
||||
turns.contains(where: { !$0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) else {
|
||||
return ([SpeakerTurn(speaker: "Запись", text: transcript.text,
|
||||
start: 0, end: transcript.audioSeconds)], false)
|
||||
}
|
||||
return (turns, true)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
public final class MeetingPipeline {
|
||||
private let transcriber: AudioFileTranscriber
|
||||
@@ -52,20 +66,33 @@ public final class MeetingPipeline {
|
||||
public func run(audio url: URL, title: String, names: SpeakerNames = SpeakerNames(),
|
||||
at date: Date = Date(),
|
||||
progress: @escaping (String) -> Void = { _ in }) async throws -> MeetingResult {
|
||||
try Task.checkCancellation()
|
||||
progress("Читаю запись")
|
||||
guard let decoded = try? await AudioFileDecoder.decode(url) else {
|
||||
let decoded: DecodedAudio
|
||||
do {
|
||||
decoded = try await AudioFileDecoder.decode(url)
|
||||
} catch is CancellationError {
|
||||
throw CancellationError()
|
||||
} catch {
|
||||
try Task.checkCancellation()
|
||||
throw MeetingPipelineFailure.audioUnreadable
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
|
||||
progress("Расшифровываю")
|
||||
_ = try? await transcriber.prepare()
|
||||
let transcript: AudioFileTranscript
|
||||
do {
|
||||
_ = try await transcriber.prepare()
|
||||
try Task.checkCancellation()
|
||||
transcript = try await transcriber.transcribe(decoded, language: .russian)
|
||||
} catch is CancellationError {
|
||||
throw CancellationError()
|
||||
} catch {
|
||||
try Task.checkCancellation()
|
||||
log("meeting: расшифровка отказала (\(error))")
|
||||
throw MeetingPipelineFailure.transcriptionFailed
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
guard !transcript.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
throw MeetingPipelineFailure.nothingRecognized
|
||||
}
|
||||
@@ -73,22 +100,28 @@ public final class MeetingPipeline {
|
||||
progress("Разбираю говорящих")
|
||||
// Отказ диаризатора конвейер не роняет: протокол без разделения хуже
|
||||
// полного, но лучше отсутствующего.
|
||||
let spans = (try? await diarizer.spans(of: url)) ?? []
|
||||
let turns = spans.isEmpty
|
||||
? [SpeakerTurn(speaker: "Запись", text: transcript.text,
|
||||
start: 0, end: transcript.audioSeconds)]
|
||||
: speakerTurnsNamed(speakerTurns(tokens: transcript.tokenTimings, spans: spans),
|
||||
names: names)
|
||||
let spans: [SpeakerSpan]
|
||||
do {
|
||||
spans = try await diarizer.spans(of: url)
|
||||
} catch is CancellationError {
|
||||
throw CancellationError()
|
||||
} catch {
|
||||
try Task.checkCancellation()
|
||||
spans = []
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
let resolved = meetingSpeakerTurns(transcript: transcript, spans: spans, names: names)
|
||||
|
||||
progress("Сохраняю")
|
||||
let document = MeetingProtocolDocument(title: title, recordedAt: date,
|
||||
audioSeconds: transcript.audioSeconds,
|
||||
turns: turns)
|
||||
turns: resolved.turns)
|
||||
try Task.checkCancellation()
|
||||
do {
|
||||
let artifacts = try MeetingStore.save(audio: url, protocolText: document.text(),
|
||||
at: date, title: title, in: storeRoot)
|
||||
return MeetingResult(artifacts: artifacts, turns: turns,
|
||||
speakersResolved: !spans.isEmpty,
|
||||
return MeetingResult(artifacts: artifacts, turns: resolved.turns,
|
||||
speakersResolved: resolved.speakersResolved,
|
||||
audioSeconds: transcript.audioSeconds)
|
||||
} catch {
|
||||
log("meeting: запись на диск отказала (\(error))")
|
||||
|
||||
@@ -88,5 +88,5 @@ public func meetingRecordingScratchURL(at date: Date = Date()) throws -> URL {
|
||||
.appendingPathComponent("_recording", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o700])
|
||||
return root.appendingPathComponent("meeting-\(formatter.string(from: date)).wav")
|
||||
return root.appendingPathComponent("meeting-\(formatter.string(from: date))-\(UUID().uuidString.lowercased()).wav")
|
||||
}
|
||||
|
||||
@@ -45,21 +45,31 @@ public enum MeetingStore {
|
||||
@discardableResult
|
||||
public static func save(audio: URL, protocolText: String, at date: Date = Date(),
|
||||
title: String, in root: URL? = nil) throws -> MeetingArtifacts {
|
||||
let directory = try meetingDirectory(at: date, title: title, in: root)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o700])
|
||||
let audioCopy = directory.appendingPathComponent("audio." + audio.pathExtension)
|
||||
if FileManager.default.fileExists(atPath: audioCopy.path) {
|
||||
try FileManager.default.removeItem(at: audioCopy)
|
||||
}
|
||||
try FileManager.default.copyItem(at: audio, to: audioCopy)
|
||||
try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: audioCopy.path)
|
||||
let manager = FileManager.default
|
||||
let base = try meetingDirectory(at: date, title: title, in: root)
|
||||
let identifier = UUID().uuidString.lowercased()
|
||||
let directory = base.deletingLastPathComponent()
|
||||
.appendingPathComponent(base.lastPathComponent + "-" + identifier, isDirectory: true)
|
||||
let staging = base.deletingLastPathComponent()
|
||||
.appendingPathComponent(".saving-" + identifier, isDirectory: true)
|
||||
try manager.createDirectory(at: staging, withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o700])
|
||||
// Новый архив появляется только целиком. Старые записи, в том числе с
|
||||
// тем же названием и временем, никогда не служат временным каталогом.
|
||||
defer { try? manager.removeItem(at: staging) }
|
||||
let audioName = "audio." + audio.pathExtension
|
||||
let audioCopy = staging.appendingPathComponent(audioName)
|
||||
try manager.copyItem(at: audio, to: audioCopy)
|
||||
try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: audioCopy.path)
|
||||
|
||||
let transcript = directory.appendingPathComponent("protocol.md")
|
||||
let transcript = staging.appendingPathComponent("protocol.md")
|
||||
try protocolText.write(to: transcript, atomically: true, encoding: .utf8)
|
||||
try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: transcript.path)
|
||||
try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: transcript.path)
|
||||
try manager.moveItem(at: staging, to: directory)
|
||||
|
||||
return MeetingArtifacts(directory: directory, audio: audioCopy, transcript: transcript)
|
||||
return MeetingArtifacts(directory: directory,
|
||||
audio: directory.appendingPathComponent(audioName),
|
||||
transcript: directory.appendingPathComponent("protocol.md"))
|
||||
}
|
||||
|
||||
/// Имя папки из названия встречи: латиница и цифры, остальное в дефис.
|
||||
|
||||
@@ -6,19 +6,21 @@
|
||||
// приложение, а модель приезжает после установки - с показанным ходом и
|
||||
// понятной ценой.
|
||||
//
|
||||
// Правило «сеть в диктовке запрещена» при этом остаётся. `enforceOffline`
|
||||
// снимается ТОЛЬКО на время явной установки, которую начал человек, и
|
||||
// возвращается назад в `defer` - в том числе на ошибке и на отмене. Пока идёт
|
||||
// диктовка, установка не начинается вовсе: снятый рубильник при работающем
|
||||
// конвейере означал бы, что распознавание может молча полезть в сеть.
|
||||
import FluidAudio
|
||||
// Явная установка получает закреплённые файлы через URLSession. Рубильник
|
||||
// офлайна распознавателя не меняется даже на время скачивания. Новая копия
|
||||
// проверяется отдельно; существующий кэш сохраняется при любом отказе.
|
||||
import Foundation
|
||||
import IrizCore
|
||||
|
||||
public let speechModelDidInstallNotification = Notification.Name("iriz.speechModelDidInstall")
|
||||
// Сумма 21 файла закреплённого commit: официальный HF tree API, 12.09.2026.
|
||||
public let speechModelDownloadBytes: Int64 = 483_105_645
|
||||
|
||||
/// Что происходит с установкой прямо сейчас.
|
||||
public enum SpeechModelInstallPhase: Equatable, Sendable {
|
||||
/// Идёт скачивание, 0…1.
|
||||
case downloading(Double)
|
||||
/// Файлы получены, CoreML собирает модель под это железо.
|
||||
/// Файлы получены, проверяется их целостность перед использованием.
|
||||
case compiling
|
||||
case finished
|
||||
case failed(String)
|
||||
@@ -29,7 +31,7 @@ public enum SpeechModelInstallRefusal: String, Equatable, Sendable {
|
||||
case alreadyInstalled
|
||||
/// Установка уже идёт.
|
||||
case alreadyRunning
|
||||
/// Идёт диктовка: рубильник сети при работающем конвейере не снимаем.
|
||||
/// Идёт диктовка: установку не начинаем посреди активного сценария.
|
||||
case dictationBusy
|
||||
}
|
||||
|
||||
@@ -47,28 +49,45 @@ public func speechModelInstallRefusal(installed: Bool,
|
||||
/// Ход установки, как его показывает окно: доля и подпись.
|
||||
public func speechModelInstallTitle(_ phase: SpeechModelInstallPhase) -> String {
|
||||
switch phase {
|
||||
case .downloading: return "Качаю модель распознавания"
|
||||
case .compiling: return "Готовлю модель под твой Мак"
|
||||
case .finished: return "Модель на месте"
|
||||
case .failed: return "Скачать не вышло"
|
||||
case .downloading: return L("speechModel.downloading", "Качаю модель распознавания")
|
||||
case .compiling: return L("speechModel.verifying", "Проверяю скачанную модель")
|
||||
case .finished: return L("speechModel.ready", "Модель на месте")
|
||||
case .failed: return L("speechModel.failed", "Скачать не вышло")
|
||||
}
|
||||
}
|
||||
|
||||
public func speechModelInstallFraction(_ phase: SpeechModelInstallPhase) -> Double {
|
||||
switch phase {
|
||||
case .downloading(let value): return min(1, max(0, value))
|
||||
// Сборка идёт без хода: показываем почти полную полосу, а не откат назад.
|
||||
case .compiling: return 0.97
|
||||
// Все байты получены; проверка не откатывает полосу скачивания назад.
|
||||
case .compiling: return 1
|
||||
case .finished: return 1
|
||||
case .failed: return 0
|
||||
}
|
||||
}
|
||||
|
||||
public func speechModelInstallFailureMessage(for error: Error) -> String {
|
||||
if error is CancellationError || (error as? URLError)?.code == .cancelled {
|
||||
return L("speechModel.error.cancelled", "Скачивание отменено. Его можно запустить снова.")
|
||||
}
|
||||
switch (error as? URLError)?.code {
|
||||
case .notConnectedToInternet:
|
||||
return L("speechModel.error.offline", "Нет подключения к интернету. Подключись к сети и повтори скачивание.")
|
||||
case .networkConnectionLost:
|
||||
return L("speechModel.error.connectionLost", "Соединение прервалось. Проверь интернет и повтори скачивание.")
|
||||
case .timedOut:
|
||||
return L("speechModel.error.timeout", "Сервер не ответил вовремя. Повтори скачивание чуть позже.")
|
||||
default:
|
||||
return error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
public final class SpeechModelInstaller {
|
||||
public static let shared = SpeechModelInstaller()
|
||||
|
||||
private(set) public var isRunning = false
|
||||
private var downloadingFile: UUID?
|
||||
|
||||
private init() {}
|
||||
|
||||
@@ -78,33 +97,119 @@ public final class SpeechModelInstaller {
|
||||
public func install(dictating: Bool,
|
||||
progress: @escaping @MainActor (SpeechModelInstallPhase) -> Void)
|
||||
async -> SpeechModelInstallRefusal? {
|
||||
let installed = speechModelCacheExists(for: .multilingualV3)
|
||||
if let refusal = speechModelInstallRefusal(installed: installed,
|
||||
if let refusal = speechModelInstallRefusal(installed: false,
|
||||
running: isRunning,
|
||||
dictating: dictating) {
|
||||
if refusal == .alreadyInstalled { progress(.finished) }
|
||||
return refusal
|
||||
}
|
||||
isRunning = true
|
||||
DownloadUtils.enforceOffline = false
|
||||
defer {
|
||||
DownloadUtils.enforceOffline = true
|
||||
isRunning = false
|
||||
downloadingFile = nil
|
||||
}
|
||||
let directory = speechModelCacheDirectory(for: .multilingualV3)
|
||||
do {
|
||||
_ = try await AsrModels.download(version: .v3) { snapshot in
|
||||
Task { @MainActor in
|
||||
switch snapshot.phase {
|
||||
case .compiling: progress(.compiling)
|
||||
default: progress(.downloading(snapshot.fractionCompleted))
|
||||
let verified = await Task.detached(priority: .userInitiated) {
|
||||
(try? ModelIntegrity.verifyParakeetV3Model(at: directory)) != nil
|
||||
}.value
|
||||
try Task.checkCancellation()
|
||||
if verified {
|
||||
progress(.finished)
|
||||
return .alreadyInstalled
|
||||
}
|
||||
|
||||
let manager = FileManager.default
|
||||
let staging = directory.deletingLastPathComponent()
|
||||
.appendingPathComponent(".iriz-model-download-" + UUID().uuidString, isDirectory: true)
|
||||
try manager.createDirectory(at: staging, withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o700])
|
||||
defer { try? manager.removeItem(at: staging) }
|
||||
let files = ModelIntegrity.parakeetV3DownloadFiles
|
||||
var receivedBytes: Int64 = 0
|
||||
for file in files {
|
||||
try Task.checkCancellation()
|
||||
let completedBytes = receivedBytes
|
||||
let token = UUID()
|
||||
downloadingFile = token
|
||||
progress(.downloading(Double(completedBytes) / Double(speechModelDownloadBytes)))
|
||||
let delegate = SpeechModelDownloadProgress { [weak self] currentBytes in
|
||||
Task { @MainActor in
|
||||
guard self?.downloadingFile == token else { return }
|
||||
progress(.downloading(min(1, Double(completedBytes + currentBytes) / Double(speechModelDownloadBytes))))
|
||||
}
|
||||
}
|
||||
let (temporary, response) = try await URLSession.shared.download(
|
||||
from: speechModelDownloadURL(for: file), delegate: delegate)
|
||||
downloadingFile = nil
|
||||
defer { try? manager.removeItem(at: temporary) }
|
||||
try Task.checkCancellation()
|
||||
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
|
||||
throw URLError(.badServerResponse)
|
||||
}
|
||||
let target = staging.appendingPathComponent(file.relativePath)
|
||||
try manager.createDirectory(at: target.deletingLastPathComponent(),
|
||||
withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o700])
|
||||
try manager.moveItem(at: temporary, to: target)
|
||||
try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: target.path)
|
||||
receivedBytes += Int64(try target.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0)
|
||||
}
|
||||
progress(.compiling)
|
||||
try await Task.detached(priority: .userInitiated) {
|
||||
try ModelIntegrity.verifyParakeetV3Model(at: staging)
|
||||
}.value
|
||||
try Task.checkCancellation()
|
||||
try publishSpeechModelCache(from: staging, to: directory)
|
||||
progress(.finished)
|
||||
return nil
|
||||
} catch {
|
||||
progress(.failed(error.localizedDescription))
|
||||
progress(.failed(speechModelInstallFailureMessage(for: error)))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class SpeechModelDownloadProgress: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
|
||||
private let received: @Sendable (Int64) -> Void
|
||||
|
||||
init(received: @escaping @Sendable (Int64) -> Void) { self.received = received }
|
||||
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
|
||||
didWriteData bytesWritten: Int64, totalBytesWritten: Int64,
|
||||
totalBytesExpectedToWrite: Int64) {
|
||||
received(totalBytesWritten)
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
|
||||
didFinishDownloadingTo location: URL) {}
|
||||
}
|
||||
|
||||
/// Источник зафиксирован тем же commit, что и SHA-256 в загрузчике; ни main,
|
||||
/// ни переменные окружения с подменённым реестром сюда не попадают.
|
||||
func speechModelDownloadURL(for file: ModelFileDigest) throws -> URL {
|
||||
guard ModelIntegrity.parakeetV3DownloadFiles.contains(file),
|
||||
let url = URL(string: "https://huggingface.co/\(ModelIntegrity.parakeetV3Repository)/resolve/\(ModelIntegrity.parakeetV3RepositoryCommit)/\(file.relativePath)"),
|
||||
url.scheme == "https", url.host == "huggingface.co" else {
|
||||
throw URLError(.badURL)
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
/// Замена только после проверки новой копии. Предыдущая остаётся рядом;
|
||||
/// если публикация не удалась, возвращаем её на прежнее место.
|
||||
func publishSpeechModelCache(from staging: URL, to directory: URL) throws {
|
||||
let manager = FileManager.default
|
||||
var backup: URL?
|
||||
if manager.fileExists(atPath: directory.path) {
|
||||
let saved = directory.deletingLastPathComponent()
|
||||
.appendingPathComponent(".iriz-model-backup-" + UUID().uuidString, isDirectory: true)
|
||||
try manager.moveItem(at: directory, to: saved)
|
||||
backup = saved
|
||||
}
|
||||
do {
|
||||
try manager.moveItem(at: staging, to: directory)
|
||||
} catch {
|
||||
if let backup { try manager.moveItem(at: backup, to: directory) }
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,13 +163,20 @@ func speechModelCacheDirectory(for profile: SpeechModelProfile) -> URL {
|
||||
}
|
||||
|
||||
public func speechModelCacheExists(for profile: SpeechModelProfile) -> Bool {
|
||||
speechModelCacheIsComplete(for: profile, at: speechModelCacheDirectory(for: profile))
|
||||
}
|
||||
|
||||
/// Быстрый probe для интерфейса: состав файлов, не SHA-256 сотен мегабайт.
|
||||
/// Полная проверка по закреплённому манифесту остаётся перед загрузкой модели.
|
||||
func speechModelCacheIsComplete(for profile: SpeechModelProfile, at directory: URL) -> Bool {
|
||||
switch profile {
|
||||
case .multilingualV3:
|
||||
return FileManager.default.fileExists(atPath: speechModelCacheDirectory(for: profile).path)
|
||||
return ModelIntegrity.parakeetV3CacheIsComplete(at: directory)
|
||||
case .whisperLargeV3, .whisperTurbo:
|
||||
// У whisper модель - ОДИН файл, и каталог без него бесполезен: проверяем файл.
|
||||
guard let file = profile.whisperModelFile else { return false }
|
||||
return FileManager.default.fileExists(atPath: whisperModelURL(file).path)
|
||||
let values = try? directory.appendingPathComponent(file)
|
||||
.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
|
||||
return values?.isRegularFile == true && (values?.fileSize ?? 0) > 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,6 +248,25 @@ public enum ModelIntegrity {
|
||||
// END GENERATED PARAKEET_V3_MODEL_MANIFEST
|
||||
]
|
||||
|
||||
static var parakeetV3DownloadFiles: [ModelFileDigest] { parakeetV3Files }
|
||||
|
||||
static func parakeetV3CacheIsComplete(at directory: URL) -> Bool {
|
||||
do {
|
||||
let directories = Set(parakeetV3Files.flatMap { parentDirectories(of: $0.relativePath) })
|
||||
for name in directories {
|
||||
try requireDirectory(directory.appendingPathComponent(name), relativePath: name)
|
||||
}
|
||||
for file in parakeetV3Files {
|
||||
let url = directory.appendingPathComponent(file.relativePath)
|
||||
try requireRegularFile(url, relativePath: file.relativePath)
|
||||
guard (try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) > 0 else { return false }
|
||||
}
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
public static func verifyParakeetV3Model(at directory: URL) throws {
|
||||
try verifyFiles(root: directory,
|
||||
expectedFiles: parakeetV3Files,
|
||||
|
||||
@@ -38,7 +38,7 @@ public func irizDropSizeText(_ bytes: Int64) -> String {
|
||||
/// Годится ли файл. Чистая функция: решение о приёме проверяется тестом без
|
||||
/// окна и без диска.
|
||||
public func irizDropAccepts(_ url: URL, extensions: [String]) -> Bool {
|
||||
extensions.contains(url.pathExtension.lowercased())
|
||||
url.isFileURL && extensions.contains(url.pathExtension.lowercased())
|
||||
}
|
||||
|
||||
public struct IrizDropZone: View {
|
||||
@@ -49,6 +49,7 @@ public struct IrizDropZone: View {
|
||||
|
||||
@State private var dragging = false
|
||||
@State private var refused: String?
|
||||
@Environment(\.isEnabled) private var isEnabled
|
||||
|
||||
public init(title: String,
|
||||
subtitle: String,
|
||||
@@ -78,7 +79,7 @@ public struct IrizDropZone: View {
|
||||
.foregroundStyle(IRIZ_SUBTLE)
|
||||
.multilineTextAlignment(.center)
|
||||
|
||||
Button("Выбрать файлы") { choose() }
|
||||
Button(L("files.choose", "Выбрать файлы")) { choose() }
|
||||
.modifier(IrizDropZoneButton())
|
||||
.padding(.top, 2)
|
||||
}
|
||||
@@ -96,6 +97,7 @@ public struct IrizDropZone: View {
|
||||
// картинка, и человек не понимает, отпускать тут или нет.
|
||||
.animation(irizAnimation(.irizQuick), value: dragging)
|
||||
.onDrop(of: [.fileURL], isTargeted: $dragging) { providers in
|
||||
guard isEnabled, !providers.isEmpty else { return false }
|
||||
accept(providers)
|
||||
return true
|
||||
}
|
||||
@@ -111,6 +113,7 @@ public struct IrizDropZone: View {
|
||||
}
|
||||
|
||||
private func choose() {
|
||||
guard isEnabled else { return }
|
||||
let panel = NSOpenPanel()
|
||||
panel.allowsMultipleSelection = true
|
||||
panel.canChooseDirectories = false
|
||||
@@ -120,20 +123,33 @@ public struct IrizDropZone: View {
|
||||
}
|
||||
|
||||
private func accept(_ providers: [NSItemProvider]) {
|
||||
for provider in providers {
|
||||
_ = provider.loadObject(ofClass: URL.self) { url, _ in
|
||||
guard let url else { return }
|
||||
DispatchQueue.main.async { accept([url]) }
|
||||
Task { @MainActor in
|
||||
var urls: [URL] = []
|
||||
for provider in providers {
|
||||
let url: URL? = await withCheckedContinuation { continuation in
|
||||
_ = provider.loadObject(ofClass: URL.self) { url, _ in
|
||||
continuation.resume(returning: url)
|
||||
}
|
||||
}
|
||||
if let url { urls.append(url) }
|
||||
}
|
||||
accept(urls, unreadableCount: providers.count - urls.count)
|
||||
}
|
||||
}
|
||||
|
||||
private func accept(_ urls: [URL]) {
|
||||
let fitting = urls.filter { irizDropAccepts($0, extensions: extensions) }
|
||||
let refusedCount = urls.count - fitting.count
|
||||
private func accept(_ urls: [URL], unreadableCount: Int = 0) {
|
||||
guard isEnabled else { return }
|
||||
let fitting = urls.filter {
|
||||
irizDropAccepts($0, extensions: extensions)
|
||||
&& (try? $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true
|
||||
&& FileManager.default.isReadableFile(atPath: $0.path)
|
||||
}
|
||||
let refusedCount = urls.count - fitting.count + unreadableCount
|
||||
// Отказ называется вслух и с числом. Молча проглоченный файл выглядит
|
||||
// как поломка переноса, и человек пробует снова тем же способом.
|
||||
refused = refusedCount == 0 ? nil : "Не приняты файлы: \(refusedCount). Годятся только \(extensions.joined(separator: ", "))."
|
||||
refused = refusedCount == 0 ? nil
|
||||
: Lf("files.refused", "Не приняты файлы: %d. Выбери доступные для чтения записи: %@.",
|
||||
refusedCount, extensions.joined(separator: ", "))
|
||||
guard !fitting.isEmpty else { return }
|
||||
onAdd(fitting)
|
||||
}
|
||||
@@ -183,6 +199,8 @@ public struct IrizDropRow: View {
|
||||
Button(action: onRemove) {
|
||||
IrizGlyphView(.files, size: 12).opacity(0)
|
||||
.overlay(Text("✕").font(.system(size: 12)))
|
||||
.frame(minWidth: 24, minHeight: 24)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(IRIZ_SUBTLE)
|
||||
|
||||
@@ -13,6 +13,17 @@ private let HOTKEY_BUTTON_WIDTH: CGFloat = 150
|
||||
/// в строке подписей, иначе шапка съезжает относительно полей.
|
||||
private let CORRECTION_TRASH_WIDTH: CGFloat = 22
|
||||
|
||||
/// Общий выбор страницы у окна и его содержимого. Переход не пересоздаёт
|
||||
/// форму: несохранённые сочетания и очередь файлов остаются на месте.
|
||||
@MainActor
|
||||
public final class SettingsNavigation: ObservableObject {
|
||||
@Published public var page: SettingsPage
|
||||
|
||||
public init(page: SettingsPage = .keys) {
|
||||
self.page = page
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
public struct IrizSettingsView: View {
|
||||
@StateObject private var model: SettingsModel
|
||||
@@ -22,30 +33,49 @@ public struct IrizSettingsView: View {
|
||||
@State private var transferMessage: String?
|
||||
@State private var transferFailed = false
|
||||
@State private var appProfileMessage: String?
|
||||
@State private var page: SettingsPage
|
||||
@StateObject private var navigation: SettingsNavigation
|
||||
private var page: SettingsPage { navigation.page }
|
||||
@State private var languageChoice: IrizLanguage = irizLanguageChoice()
|
||||
@State private var appearanceChoice: IrizAppearanceChoice = irizAppearanceChoice()
|
||||
@State private var fileQueue: [IrizDropItem] = []
|
||||
@StateObject private var files = SettingsFileTranscription()
|
||||
@State private var fileLanguage: DictationLanguage = .auto
|
||||
@State private var meetingQueue: [IrizDropItem] = []
|
||||
@State private var meetingBusy = false
|
||||
@State private var meetingStopping = false
|
||||
@State private var meetingResults: [MeetingArtifacts] = []
|
||||
@State private var meetingProgress: String?
|
||||
@State private var meetingReport: String?
|
||||
@State private var meetingFailed = false
|
||||
@State private var diskEntries: [DiskUsageEntry] = []
|
||||
@State private var diskCounting = false
|
||||
@State private var historyEntries: [DictationHistoryEntry] = []
|
||||
@State private var historyQuery = ""
|
||||
@StateObject private var historyModel: DictationHistoryModel
|
||||
private let isPreview: Bool
|
||||
private let openSpeechModelSetup: (() -> Void)?
|
||||
@Namespace private var sidebarGlass
|
||||
/// Система гасит свою анимацию, но не наш `withAnimation` - морф стекла
|
||||
/// приходится гейтить руками (правило M07 линтера).
|
||||
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||
|
||||
public init(preview: Bool = false, page: SettingsPage = .keys) {
|
||||
public init(preview: Bool = false, page: SettingsPage = .keys,
|
||||
navigation: SettingsNavigation? = nil,
|
||||
openSpeechModelSetup: (() -> Void)? = nil) {
|
||||
_model = StateObject(wrappedValue: SettingsModel(preview: preview))
|
||||
_page = State(initialValue: page)
|
||||
_historyModel = StateObject(wrappedValue: DictationHistoryModel(preview: preview))
|
||||
isPreview = preview
|
||||
self.openSpeechModelSetup = openSpeechModelSetup
|
||||
_navigation = StateObject(wrappedValue: navigation ?? SettingsNavigation(page: page))
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
glassScene
|
||||
.onAppear { model.refreshSpeechModelReadiness() }
|
||||
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
|
||||
model.refreshSpeechModelReadiness()
|
||||
}
|
||||
.onReceive(NotificationCenter.default.publisher(for: speechModelDidInstallNotification)) { notification in
|
||||
guard !isPreview, let profile = notification.object as? SpeechModelProfile else { return }
|
||||
model.applyInstalledSpeechModel(profile)
|
||||
}
|
||||
}
|
||||
|
||||
/// Общего `GlassEffectContainer` здесь НЕТ, и это измеренное решение.
|
||||
@@ -174,7 +204,7 @@ public struct IrizSettingsView: View {
|
||||
// Пресет вместо магических чисел: `.snappy` и есть «доехать с весом,
|
||||
// без игры» (правило M02 линтера).
|
||||
withAnimation(reduceMotion ? nil : .irizMove) {
|
||||
page = item
|
||||
navigation.page = item
|
||||
}
|
||||
} label: {
|
||||
Label {
|
||||
@@ -240,8 +270,7 @@ public struct IrizSettingsView: View {
|
||||
/// кнопка сохранения, спрятанная на одной из девяти, находится случайно.
|
||||
private var footerBar: some View {
|
||||
HStack(spacing: 12) {
|
||||
if let message = model.validationMessage,
|
||||
!message.contains(L("settings.konflikt", "Конфликт")), !message.contains("macOS") {
|
||||
if let message = model.validationMessage {
|
||||
Label(message, systemImage: "exclamationmark.triangle.fill")
|
||||
.foregroundStyle(.red)
|
||||
.accessibilityLabel(Lf("settings.error.a11y", "Ошибка настроек: %@", message))
|
||||
@@ -455,12 +484,7 @@ public struct IrizSettingsView: View {
|
||||
}
|
||||
}
|
||||
|
||||
Picker(L("settings.raspoznavatel", "Распознаватель"), selection: $model.speechEngine) {
|
||||
ForEach(SpeechModelProfile.allCases, id: \.self) { profile in
|
||||
Text(profile.shortName).tag(profile)
|
||||
}
|
||||
}
|
||||
.accessibilityLabel(L("settings.kakoyDvizhokRaspoznavaniyaRechi", "Какой движок распознавания речи использовать"))
|
||||
speechRecognitionControls
|
||||
|
||||
settingsNote {
|
||||
Text(L("settings.parakeetBystreeV11", "Parakeet быстрее в 11-15 раз, но транслитерирует английские термины внутри русской фразы: git rebase слышится как «гид репейс». Whisper large-v3 берет их латиницей (19 процентов ошибок на смешанной речи против 44), зато надиктовка в полминуты ждет расшифровки около 16 секунд. Оба считают на этом Маке, наружу не уходит ничего."))
|
||||
@@ -830,8 +854,49 @@ public struct IrizSettingsView: View {
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private var speechRecognitionControls: some View {
|
||||
Picker(L("settings.raspoznavatel", "Распознаватель"), selection: $model.speechEngine) {
|
||||
ForEach(SpeechModelProfile.allCases, id: \.self) { profile in
|
||||
Text(profile.shortName).tag(profile)
|
||||
}
|
||||
}
|
||||
.disabled(files.busy || meetingBusy)
|
||||
.accessibilityLabel(L("settings.kakoyDvizhokRaspoznavaniyaRechi", "Какой движок распознавания речи использовать"))
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Label(model.speechModelInstalled
|
||||
? Lf("settings.speechModelInstalled", "%@: модель установлена", model.speechEngine.shortName)
|
||||
: Lf("settings.speechModelMissing", "%@: модель не установлена", model.speechEngine.shortName),
|
||||
systemImage: model.speechModelInstalled ? "checkmark.circle" : "arrow.down.circle")
|
||||
.foregroundStyle(.primary)
|
||||
if !model.speechModelInstalled {
|
||||
Text(model.canUseInstalledParakeet
|
||||
? L("settings.parakeetAlreadyAvailable", "Parakeet уже установлен. Выбери его и сохрани настройки, чтобы использовать для диктовки.")
|
||||
: L("settings.speechModelDownloadHelp", "Для распознавания нужна модель на этом Маке. Автоматически можно скачать только Parakeet: около 0,5 ГБ, один раз. После установки он станет выбранным распознавателем. Звук останется на устройстве."))
|
||||
.font(.footnote)
|
||||
.foregroundStyle(IRIZ_SUBTLE)
|
||||
}
|
||||
if !model.speechModelInstalled, model.canUseInstalledParakeet {
|
||||
Button(L("settings.selectInstalledParakeet", "Выбрать установленный Parakeet")) {
|
||||
model.speechEngine = .multilingualV3
|
||||
}
|
||||
.modifier(GlassButton())
|
||||
.disabled(files.busy || meetingBusy)
|
||||
} else {
|
||||
Button(model.speechModelInstalled
|
||||
? L("settings.speechModelSetup", "Настроить распознавание…")
|
||||
: L("settings.downloadParakeet", "Скачать модель Parakeet…")) {
|
||||
openSpeechModelSetup?()
|
||||
}
|
||||
.modifier(GlassButton())
|
||||
.disabled(isPreview || openSpeechModelSetup == nil || files.busy || meetingBusy)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var behaviorSection: some View {
|
||||
Section {
|
||||
speechRecognitionControls
|
||||
LabeledContent(L("settings.zaderzhkaEnter", "Задержка Enter")) {
|
||||
HStack(spacing: 6) {
|
||||
// labelsHidden обязателен: в Form(.grouped) заголовок TextField
|
||||
@@ -1224,13 +1289,77 @@ public struct IrizSettingsView: View {
|
||||
/// Расшифровка файлов: бросил запись - получил текст рядом с ней.
|
||||
private var filesSection: some View {
|
||||
Section {
|
||||
speechRecognitionControls
|
||||
IrizDropZone(title: L("settings.perenesiteZapisiSyuda", "Перенесите записи сюда"),
|
||||
subtitle: L("settings.diktofonZvonokEksportIz", "Диктофон, звонок, экспорт из встречи. Текст ляжет рядом с файлом."),
|
||||
extensions: AudioFileBatch.supportedExtensions.sorted()) { urls in
|
||||
enqueue(urls, into: $fileQueue)
|
||||
enqueue(urls, into: $files.queue)
|
||||
}
|
||||
ForEach(fileQueue) { item in
|
||||
IrizDropRow(item: item) { fileQueue.removeAll { $0.id == item.id } }
|
||||
.disabled(files.busy)
|
||||
Picker(L("files.language", "Язык записи"), selection: $fileLanguage) {
|
||||
ForEach(DictationLanguage.allCases, id: \.self) { language in
|
||||
Text(language == .auto ? L("files.languageAuto", "Определить автоматически")
|
||||
: Locale.current.localizedString(forLanguageCode: language.rawValue) ?? language.rawValue)
|
||||
.tag(language)
|
||||
}
|
||||
}
|
||||
.disabled(files.busy)
|
||||
ForEach(files.queue) { item in
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
IrizDropRow(item: item) { files.queue.removeAll { $0.id == item.id } }
|
||||
.disabled(files.busy)
|
||||
if let error = files.errors[item.id] {
|
||||
Label(error, systemImage: "exclamationmark.triangle.fill")
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.orange)
|
||||
.textSelection(.enabled)
|
||||
let destination = AudioFileBatch.destination(forSource: item.url, in: nil)
|
||||
Button(L("files.showDestination", "Показать папку результата")) {
|
||||
NSWorkspace.shared.activateFileViewerSelecting([destination.deletingLastPathComponent()])
|
||||
}
|
||||
.modifier(GlassButton())
|
||||
}
|
||||
}
|
||||
}
|
||||
if !files.queue.isEmpty {
|
||||
Button(files.errors.isEmpty ? L("files.start", "Расшифровать записи")
|
||||
: L("files.retry", "Повторить оставшиеся")) {
|
||||
guard !meetingBusy, !isPreview, model.speechModelInstalled else { return }
|
||||
files.start(engine: model.speechEngine, language: fileLanguage)
|
||||
}
|
||||
.modifier(GlassProminentButton())
|
||||
.disabled(files.busy || meetingBusy || isPreview || !model.speechModelInstalled)
|
||||
}
|
||||
if let progress = files.progress {
|
||||
if let fraction = files.fraction {
|
||||
ProgressView(value: fraction) { Text(progress) }
|
||||
} else {
|
||||
ProgressView { Text(progress) }
|
||||
.controlSize(.small)
|
||||
}
|
||||
Button(files.stopping ? L("files.stopping", "Останавливаю после текущей записи…")
|
||||
: L("files.stopAfterCurrent", "Остановить после текущей записи")) {
|
||||
files.stopAfterCurrent()
|
||||
}
|
||||
.modifier(GlassButton())
|
||||
.disabled(files.stopping)
|
||||
}
|
||||
if let report = files.report {
|
||||
Text(report).font(.footnote).textSelection(.enabled)
|
||||
}
|
||||
ForEach(files.results, id: \.source) { result in
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Label(result.destination.lastPathComponent, systemImage: "checkmark.circle")
|
||||
.textSelection(.enabled)
|
||||
HStack {
|
||||
Button(L("files.openText", "Открыть текст")) { openFileResult(result.destination) }
|
||||
.modifier(GlassButton())
|
||||
Button(L("files.showInFinder", "Показать в Finder")) {
|
||||
NSWorkspace.shared.activateFileViewerSelecting([result.destination])
|
||||
}
|
||||
.modifier(GlassButton())
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(L("settings.rasshifrovkaIdetNaEtom", "Расшифровка идёт на этом Маке тем же движком, что и диктовка. "
|
||||
+ "Звук никуда не отправляется, а сам файл остаётся там, где лежал."))
|
||||
@@ -1254,25 +1383,39 @@ public struct IrizSettingsView: View {
|
||||
/// «вставить» означало бы вставить в него же. Копирование есть.
|
||||
private var historySection: some View {
|
||||
Section {
|
||||
if historyEntries.isEmpty {
|
||||
Text(L("settings.pokaPustoNadiktovannoePoyavitsya", "Пока пусто. Надиктованное появится здесь."))
|
||||
HStack(spacing: 8) {
|
||||
IrizGlyphView(.history, size: 13)
|
||||
.foregroundStyle(IRIZ_SUBTLE)
|
||||
} else {
|
||||
// Системная оправа `.roundedBorder` рисуется непрозрачной
|
||||
// коробкой: в стеклянном окне она читается как дырка. Своя
|
||||
// оправа - то же стекло, что у плит, только тоньше.
|
||||
HStack(spacing: 8) {
|
||||
IrizGlyphView(.history, size: 13)
|
||||
.foregroundStyle(IRIZ_SUBTLE)
|
||||
TextField(L("settings.poiskPoNadiktovkam", "Поиск по надиктовкам"), text: $historyQuery)
|
||||
.textFieldStyle(.plain)
|
||||
.accessibilityLabel(L("settings.poiskPoNadiktovkam", "Поиск по надиктовкам"))
|
||||
}
|
||||
.padding(.horizontal, 10)
|
||||
.padding(.vertical, 7)
|
||||
.background(IrizSearchFieldPlate())
|
||||
TextField(L("settings.poiskPoNadiktovkam", "Поиск по надиктовкам"), text: $historyModel.query)
|
||||
.textFieldStyle(.plain)
|
||||
.accessibilityLabel(L("settings.poiskPoNadiktovkam", "Поиск по надиктовкам"))
|
||||
}
|
||||
.padding(.horizontal, 10)
|
||||
.padding(.vertical, 7)
|
||||
.background(IrizSearchFieldPlate())
|
||||
|
||||
ForEach(filteredDictationHistory(historyEntries, query: historyQuery)) { entry in
|
||||
if historyModel.isLoading {
|
||||
ProgressView(L("history.loading", "Читаю надиктовки…"))
|
||||
.controlSize(.small)
|
||||
}
|
||||
if let notice = historyModel.notice {
|
||||
Label(notice, systemImage: historyModel.noticeIsError ? "exclamationmark.circle" : "checkmark.circle")
|
||||
.foregroundStyle(historyModel.noticeIsError ? Color.red : Color.primary)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
if !historyModel.isLoading, historyModel.visible.isEmpty, !historyModel.noticeIsError {
|
||||
Text(historyModel.entries.isEmpty
|
||||
? L("settings.pokaPustoNadiktovannoePoyavitsya", "Пока пусто. Надиктованное появится здесь.")
|
||||
: L("history.notFoundTitle", "Ничего не нашлось"))
|
||||
.foregroundStyle(IRIZ_SUBTLE)
|
||||
}
|
||||
if historyModel.query.isEmpty, historyModel.entries.count >= DICTATION_HISTORY_VISIBLE_LIMIT {
|
||||
Text(L("history.loadingBody", "Показываю последние сто. Остальные найдёт поиск."))
|
||||
.font(.footnote)
|
||||
.foregroundStyle(IRIZ_SUBTLE)
|
||||
}
|
||||
ForEach(historyModel.visible) { entry in
|
||||
HStack(alignment: .top, spacing: 12) {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(dictationHistoryPreview(entry.displayText))
|
||||
.lineLimit(3)
|
||||
@@ -1286,55 +1429,53 @@ public struct IrizSettingsView: View {
|
||||
.foregroundStyle(IRIZ_SUBTLE)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.contentShape(Rectangle())
|
||||
.contextMenu {
|
||||
Button(L("settings.kopirovat", "Копировать")) { copyHistory(entry) }
|
||||
}
|
||||
Button(L("settings.kopirovat", "Копировать")) { copyHistory(entry) }
|
||||
.disabled(isPreview)
|
||||
}
|
||||
.contextMenu {
|
||||
Button(L("settings.kopirovat", "Копировать")) { copyHistory(entry) }
|
||||
.disabled(isPreview)
|
||||
}
|
||||
}
|
||||
} header: {
|
||||
Text(L("settings.istoriyaNadiktovok", "История надиктовок"))
|
||||
}
|
||||
.onAppear { loadHistory() }
|
||||
.onDisappear { historyModel.cancelLoading() }
|
||||
}
|
||||
|
||||
private func loadHistory() {
|
||||
// Читается с диска при каждом открытии страницы, а не держится в
|
||||
// памяти: диктовки пишутся другим процессом окна, и кэш разъехался бы
|
||||
// с диском ровно тогда, когда владелец ищет только что сказанное.
|
||||
//
|
||||
// В ФОНЕ и с потолком. Здесь стоял тот же дефект, что в окне истории:
|
||||
// две тысячи каталогов по три файла читались синхронно, 1386 мс, и всё
|
||||
// это время окно настроек не рисовалось. Владелец поймал это дважды -
|
||||
// сперва в окне, потом на этой странице.
|
||||
guard let root = try? DictationStore.dictationsDirectory() else { return }
|
||||
Task.detached(priority: .userInitiated) {
|
||||
let found = dictationHistoryEntries(in: root, limit: DICTATION_HISTORY_VISIBLE_LIMIT)
|
||||
await MainActor.run { historyEntries = found }
|
||||
}
|
||||
historyModel.reload { try DictationStore.dictationsDirectory() }
|
||||
}
|
||||
|
||||
private func copyHistory(_ entry: DictationHistoryEntry) {
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString(entry.displayText, forType: .string)
|
||||
statusMessage = L("settings.skopirovanoVBuferObmena", "Скопировано в буфер обмена.")
|
||||
guard !isPreview else { return }
|
||||
let copied = DictationHistoryClipboard.copy(entry.displayText)
|
||||
historyModel.noticeIsError = !copied
|
||||
historyModel.notice = copied
|
||||
? L("history.copiedTimed", "Скопировано. Буфер очистится через 2 минуты.")
|
||||
: L("history.copyFailed", "Не удалось скопировать. Попробуй ещё раз.")
|
||||
}
|
||||
|
||||
private var meetingsSection: some View {
|
||||
Section {
|
||||
speechRecognitionControls
|
||||
IrizDropZone(title: L("settings.perenesiteZapisVstrechi", "Перенесите запись встречи"),
|
||||
subtitle: L("settings.zapisZasedaniyaIliSozvona", "Запись заседания или созвона. Рядом ляжет протокол."),
|
||||
subtitle: L("meetings.storage", "Запись на русском языке. Звук и протокол сохранятся в архиве iriz; готовые файлы можно открыть отсюда."),
|
||||
extensions: AudioFileBatch.supportedExtensions.sorted()) { urls in
|
||||
enqueue(urls, into: $meetingQueue)
|
||||
}
|
||||
.disabled(meetingBusy)
|
||||
ForEach(meetingQueue) { item in
|
||||
IrizDropRow(item: item) { meetingQueue.removeAll { $0.id == item.id } }
|
||||
.disabled(meetingBusy)
|
||||
}
|
||||
|
||||
if !meetingQueue.isEmpty {
|
||||
Button(L("settings.razobratZapisi", "Разобрать записи")) { runMeetings() }
|
||||
Button(meetingFailed ? L("files.retry", "Повторить оставшиеся")
|
||||
: L("settings.razobratZapisi", "Разобрать записи")) { runMeetings() }
|
||||
.modifier(GlassProminentButton())
|
||||
.disabled(meetingProgress != nil)
|
||||
.disabled(meetingBusy || files.busy || isPreview || !model.speechModelInstalled)
|
||||
.accessibilityLabel(L("settings.razobratZapisiVstrech", "Разобрать записи встреч"))
|
||||
}
|
||||
|
||||
@@ -1342,9 +1483,14 @@ public struct IrizSettingsView: View {
|
||||
// Ход показывается словами, а не полосой: у часовой записи
|
||||
// полоса врёт про остаток, а название шага честно говорит,
|
||||
// что именно сейчас происходит.
|
||||
Label(meetingProgress, systemImage: "hourglass")
|
||||
.font(.footnote)
|
||||
.foregroundStyle(IRIZ_SUBTLE)
|
||||
ProgressView { Text(meetingProgress) }
|
||||
.controlSize(.small)
|
||||
Button(meetingStopping ? L("files.stopping", "Останавливаю после текущей записи…")
|
||||
: L("files.stopAfterCurrent", "Остановить после текущей записи")) {
|
||||
meetingStopping = true
|
||||
}
|
||||
.modifier(GlassButton())
|
||||
.disabled(meetingStopping)
|
||||
}
|
||||
|
||||
if let meetingReport {
|
||||
@@ -1355,6 +1501,21 @@ public struct IrizSettingsView: View {
|
||||
.textSelection(.enabled)
|
||||
}
|
||||
|
||||
ForEach(meetingResults, id: \.directory) { artifacts in
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Label(artifacts.directory.lastPathComponent, systemImage: "checkmark.circle")
|
||||
.textSelection(.enabled)
|
||||
HStack {
|
||||
Button(L("meetings.openProtocol", "Открыть протокол")) { openFileResult(artifacts.transcript) }
|
||||
.modifier(GlassButton())
|
||||
Button(L("meetings.showFolder", "Показать папку встречи")) {
|
||||
NSWorkspace.shared.activateFileViewerSelecting([artifacts.directory])
|
||||
}
|
||||
.modifier(GlassButton())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Здесь продукт нарушает собственное правило, и молчать об этом
|
||||
// нельзя: в диктовке звук не сохраняется никогда, а у встречи он
|
||||
// остаётся вместе с расшифровкой. Иначе протокол нечем сверить.
|
||||
@@ -1377,47 +1538,66 @@ public struct IrizSettingsView: View {
|
||||
/// Отказ на одной записи не отменяет остальные: владелец принёс папку, и
|
||||
/// одна битая запись не должна стоить ему разбора всех.
|
||||
private func runMeetings() {
|
||||
guard !meetingBusy, !files.busy, !meetingQueue.isEmpty, !isPreview, model.speechModelInstalled else { return }
|
||||
meetingBusy = true
|
||||
meetingStopping = false
|
||||
let items = meetingQueue
|
||||
let engine = model.speechEngine
|
||||
meetingReport = nil
|
||||
meetingFailed = false
|
||||
Task { @MainActor in
|
||||
let pipeline = MeetingPipeline()
|
||||
let pipeline = MeetingPipeline(transcriber: AudioFileTranscriber(engine: engine))
|
||||
var done = 0
|
||||
var failures: [String] = []
|
||||
for item in items {
|
||||
guard !meetingStopping else { break }
|
||||
let name = item.url.deletingPathExtension().lastPathComponent
|
||||
meetingProgress = "\(name): читаю"
|
||||
meetingProgress = "\(name): \(L("files.reading", "читаю запись"))"
|
||||
do {
|
||||
let result = try await pipeline.run(
|
||||
audio: item.url,
|
||||
title: name,
|
||||
progress: { step in
|
||||
Task { @MainActor in meetingProgress = "\(name): \(step.lowercased())" }
|
||||
Task { @MainActor in
|
||||
guard meetingBusy else { return }
|
||||
meetingProgress = "\(name): \(step.lowercased())"
|
||||
}
|
||||
}
|
||||
)
|
||||
done += 1
|
||||
meetingQueue.removeAll { $0.id == item.id }
|
||||
meetingResults.append(result.artifacts)
|
||||
if !result.speakersResolved {
|
||||
// Владелец должен отличить монолог от неудавшегося
|
||||
// разделения: в первом случае имена расставлять не
|
||||
// нужно, во втором нужно.
|
||||
failures.append("\(name): говорящие не разобраны, протокол одной репликой")
|
||||
failures.append(Lf("meetings.speakersUnresolved", "%@: говорящие не разделены. Текст сохранён одной репликой; проверьте протокол.", name))
|
||||
}
|
||||
} catch {
|
||||
let reason = (error as? MeetingPipelineFailure)?.rawValue ?? "\(error)"
|
||||
let reason = (error as? MeetingPipelineFailure)?.rawValue ?? error.localizedDescription
|
||||
failures.append("\(name): \(reason)")
|
||||
}
|
||||
}
|
||||
meetingProgress = nil
|
||||
meetingBusy = false
|
||||
meetingFailed = !failures.isEmpty
|
||||
let base = done > 0 ? "Разобрано записей: \(done)." : L("settings.razobratNeUdalos", "Разобрать не удалось.")
|
||||
meetingReport = failures.isEmpty ? base : base + " " + failures.joined(separator: "; ")
|
||||
let base = Lf("files.finished", "Готово: %d из %d.", done, items.count)
|
||||
+ (meetingStopping ? " " + L("files.stopped", "Очередь остановлена. Оставшиеся файлы можно запустить снова.") : "")
|
||||
meetingReport = failures.isEmpty ? base : base + "\n" + failures.joined(separator: "\n")
|
||||
}
|
||||
}
|
||||
|
||||
private func openFileResult(_ url: URL) {
|
||||
if !NSWorkspace.shared.open(url) {
|
||||
statusMessage = Lf("files.openFailed", "Не удалось открыть %@. Проверь файл через Finder.", url.lastPathComponent)
|
||||
}
|
||||
}
|
||||
|
||||
/// Положить файлы в очередь, не задваивая уже принесённые.
|
||||
private func enqueue(_ urls: [URL], into queue: Binding<[IrizDropItem]>) {
|
||||
for url in urls where !queue.wrappedValue.contains(where: { $0.url == url }) {
|
||||
for source in urls {
|
||||
let url = source.standardizedFileURL
|
||||
guard !queue.wrappedValue.contains(where: { $0.url.standardizedFileURL == url }) else { continue }
|
||||
let bytes = (try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int64) ?? 0
|
||||
queue.wrappedValue.append(IrizDropItem(url: url, bytes: bytes ?? 0))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import Combine
|
||||
import Darwin
|
||||
import Foundation
|
||||
import IrizCore
|
||||
import IrizDictate
|
||||
|
||||
/// Очередь переживает смену страницы; повтор запускает только оставшиеся файлы.
|
||||
@MainActor
|
||||
final class SettingsFileTranscription: ObservableObject {
|
||||
typealias Progress = @Sendable (String, Double?) async -> Void
|
||||
typealias ProcessFile = @Sendable (AudioTranscriptionJob, AudioFileTranscriber,
|
||||
DictationLanguage, @escaping Progress) async throws -> Void
|
||||
|
||||
@Published var queue: [IrizDropItem] = []
|
||||
@Published private(set) var busy = false
|
||||
@Published private(set) var stopping = false
|
||||
@Published private(set) var progress: String?
|
||||
@Published private(set) var fraction: Double?
|
||||
@Published private(set) var report: String?
|
||||
@Published private(set) var errors: [UUID: String] = [:]
|
||||
@Published private(set) var results: [AudioTranscriptionJob] = []
|
||||
private let processFile: ProcessFile
|
||||
|
||||
init(processFile: @escaping ProcessFile = SettingsFileTranscription.process) {
|
||||
self.processFile = processFile
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func start(engine: SpeechModelProfile, language: DictationLanguage) -> Task<Void, Never>? {
|
||||
guard !busy, !queue.isEmpty else { return nil }
|
||||
// До Task: второе нажатие в том же проходе run loop уже не запустит модель.
|
||||
busy = true
|
||||
stopping = false
|
||||
report = nil
|
||||
errors = [:]
|
||||
let items = queue
|
||||
let transcriber = AudioFileTranscriber(engine: engine)
|
||||
return Task {
|
||||
var done = 0
|
||||
defer {
|
||||
busy = false
|
||||
progress = nil
|
||||
fraction = nil
|
||||
report = Lf("files.finished", "Готово: %d из %d.", done, items.count)
|
||||
+ (stopping ? " " + L("files.stopped", "Очередь остановлена. Оставшиеся файлы можно запустить снова.") : "")
|
||||
}
|
||||
for (index, item) in items.enumerated() {
|
||||
guard !stopping else { break }
|
||||
let name = item.url.lastPathComponent
|
||||
progress = "[\(index + 1)/\(items.count)] \(name)"
|
||||
fraction = nil
|
||||
do {
|
||||
let jobs = try await Task.detached(priority: .userInitiated) {
|
||||
try AudioFileBatch.plan(inputPath: item.url.path, force: false)
|
||||
}.value
|
||||
guard let job = jobs.first, jobs.count == 1 else {
|
||||
throw AudioBatchPlanError.pathNotReadable(item.url.path)
|
||||
}
|
||||
try await processFile(job, transcriber, language) { step, value in
|
||||
await MainActor.run {
|
||||
self.progress = "[\(index + 1)/\(items.count)] \(name): \(step)"
|
||||
self.fraction = value
|
||||
}
|
||||
}
|
||||
results.removeAll { $0.source == job.source }
|
||||
results.append(job)
|
||||
queue.removeAll { $0.id == item.id }
|
||||
done += 1
|
||||
} catch {
|
||||
errors[item.id] = Self.message(for: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// У распознавателя нет безопасного мгновенного прерывания. Текущий результат
|
||||
/// сохраняется, следующий файл не начинается; это прямо написано на кнопке.
|
||||
func stopAfterCurrent() { if busy { stopping = true } }
|
||||
|
||||
nonisolated private static func process(_ job: AudioTranscriptionJob,
|
||||
transcriber: AudioFileTranscriber,
|
||||
language: DictationLanguage,
|
||||
progress: @escaping Progress) async throws {
|
||||
await progress(L("files.preparing", "загружаю модель"), nil)
|
||||
_ = try await transcriber.prepare()
|
||||
await progress(L("files.reading", "читаю запись"), nil)
|
||||
let audio = try await AudioFileDecoder.decode(job.source)
|
||||
await progress(L("files.transcribing", "расшифровываю"), nil)
|
||||
var reporter: Task<Void, Never>?
|
||||
if AudioFileTranscriber.reportsProgress(forSamples: audio.samples.count),
|
||||
let stream = await transcriber.progressStream() {
|
||||
reporter = Task {
|
||||
do {
|
||||
for try await value in stream {
|
||||
guard !Task.isCancelled else { break }
|
||||
await progress(L("files.transcribing", "расшифровываю"), min(1, max(0, value)))
|
||||
}
|
||||
} catch { /* Текстовая стадия остаётся видимой, если поток прогресса закрыт. */ }
|
||||
}
|
||||
}
|
||||
defer { reporter?.cancel() }
|
||||
let transcript = try await transcriber.transcribe(audio, language: language)
|
||||
reporter?.cancel()
|
||||
await reporter?.value
|
||||
await progress(L("files.saving", "сохраняю текст"), nil)
|
||||
try saveTranscript(transcript.text, to: job.destination)
|
||||
}
|
||||
|
||||
/// Готовый текст появляется целиком, с правами 0600. link отказывает при
|
||||
/// существующем имени даже тогда, когда файл появился уже после plan().
|
||||
nonisolated static func saveTranscript(_ text: String, to destination: URL) throws {
|
||||
let text = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !text.isEmpty else {
|
||||
throw NSError(domain: "IrizFileTranscription", code: 1,
|
||||
userInfo: [NSLocalizedDescriptionKey: L("files.noSpeech", "Речь не распознана. Текстовый файл не создан.")])
|
||||
}
|
||||
let temporary = destination.deletingLastPathComponent()
|
||||
.appendingPathComponent(".iriz-transcript-\(UUID().uuidString)")
|
||||
let descriptor = Darwin.open(temporary.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
|
||||
PRIVATE_LOG_FILE_MODE)
|
||||
guard descriptor >= 0 else { throw IrizCore.currentPOSIXError() }
|
||||
defer {
|
||||
_ = Darwin.close(descriptor)
|
||||
_ = Darwin.unlink(temporary.path)
|
||||
}
|
||||
try IrizCore.writeAllData(Data((text + "\n").utf8), to: descriptor)
|
||||
guard Darwin.link(temporary.path, destination.path) == 0 else {
|
||||
if errno == EEXIST { throw AudioBatchPlanError.destinationExists(destination.path) }
|
||||
throw IrizCore.currentPOSIXError()
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated static func message(for error: Error) -> String {
|
||||
if case AudioBatchPlanError.destinationExists(let path) = error {
|
||||
return Lf("files.destinationExists", "Текст уже есть: %@. Открой его или переименуй исходную запись перед повтором.", path)
|
||||
}
|
||||
return (error as? AudioBatchPlanError)?.message
|
||||
?? (error as? AudioDecodingError)?.message
|
||||
?? error.localizedDescription
|
||||
}
|
||||
}
|
||||
@@ -194,7 +194,10 @@ final class SettingsModel: ObservableObject {
|
||||
/// Какой распознаватель стоит. Выбор с ценой на обеих сторонах, поэтому он
|
||||
/// у владельца, а не зашит: Whisper берет английские термины внутри русской
|
||||
/// фразы, Parakeet быстрее в 11-15 раз. Разбор - `bench/BENCH-CANDIDATES-2026-09-03.md`.
|
||||
@Published var speechEngine: SpeechModelProfile
|
||||
@Published var speechEngine: SpeechModelProfile {
|
||||
didSet { refreshSpeechModelReadiness() }
|
||||
}
|
||||
@Published private(set) var speechModelInstalled = false
|
||||
@Published var promptRecipient: PromptRecipientSetting
|
||||
/// Явные записи «приложение → профиль». Всё, чего в списке нет, получает
|
||||
/// `promptRecipient`, поэтому отдельного «дефолтного» ряда тут не бывает.
|
||||
@@ -212,6 +215,8 @@ final class SettingsModel: ObservableObject {
|
||||
private let layoutSettings: LayoutSettingsAccess
|
||||
private let layoutHotkeys: LayoutHotkeySettingsAccess
|
||||
private let agentDetector: (String, PromptAgentAdapter) -> URL?
|
||||
private let installedSpeechEngine: () -> SpeechModelProfile
|
||||
private let speechModelProbe: (SpeechModelProfile) -> Bool
|
||||
private var savedLaunchAtLogin: Bool
|
||||
|
||||
convenience init(preview: Bool = false) {
|
||||
@@ -220,7 +225,8 @@ final class SettingsModel: ObservableObject {
|
||||
self.init(
|
||||
dictationSettings: DictationSettings(defaults: defaults),
|
||||
layoutSettings: .preview(defaults: defaults),
|
||||
layoutHotkeys: .settings(SettingsManager(defaults: defaults))
|
||||
layoutHotkeys: .settings(SettingsManager(defaults: defaults)),
|
||||
speechModelProbe: { _ in false }
|
||||
)
|
||||
} else {
|
||||
self.init(
|
||||
@@ -238,11 +244,15 @@ final class SettingsModel: ObservableObject {
|
||||
dictationSettings: DictationSettings,
|
||||
layoutSettings: LayoutSettingsAccess,
|
||||
layoutHotkeys: LayoutHotkeySettingsAccess,
|
||||
codexDetector: ((String) -> URL?)? = nil
|
||||
codexDetector: ((String) -> URL?)? = nil,
|
||||
installedSpeechEngine: @escaping () -> SpeechModelProfile = { .installedDefault() },
|
||||
speechModelProbe: @escaping (SpeechModelProfile) -> Bool = speechModelCacheExists
|
||||
) {
|
||||
self.dictationSettings = dictationSettings
|
||||
self.layoutSettings = layoutSettings
|
||||
self.layoutHotkeys = layoutHotkeys
|
||||
self.installedSpeechEngine = installedSpeechEngine
|
||||
self.speechModelProbe = speechModelProbe
|
||||
agentDetector = codexDetector.map { detector in
|
||||
{ path, _ in detector(path) }
|
||||
} ?? { path, adapter in
|
||||
@@ -279,6 +289,21 @@ final class SettingsModel: ObservableObject {
|
||||
wavePalette = dictationSettings.dictationHUDWavePalette
|
||||
rescueWindowEnabled = dictationSettings.rescueWindowEnabled
|
||||
hotkeys = Self.loadHotkeys(dictationSettings: dictationSettings, layoutHotkeys: layoutHotkeys)
|
||||
refreshSpeechModelReadiness()
|
||||
}
|
||||
|
||||
func refreshSpeechModelReadiness() {
|
||||
speechModelInstalled = speechModelProbe(speechEngine)
|
||||
}
|
||||
|
||||
var canUseInstalledParakeet: Bool {
|
||||
speechEngine != .multilingualV3 && speechModelProbe(.multilingualV3)
|
||||
}
|
||||
|
||||
/// Явная установка выбирает скачанный движок. Остальные черновики формы
|
||||
/// остаются у пользователя; общая settingsDidSave сюда не подключается.
|
||||
func applyInstalledSpeechModel(_ profile: SpeechModelProfile) {
|
||||
speechEngine = profile
|
||||
}
|
||||
|
||||
/// Адаптер выбранного агента: свой CLI собирается из введённых аргументов.
|
||||
@@ -586,8 +611,13 @@ final class SettingsModel: ObservableObject {
|
||||
launchAtLogin = true
|
||||
corrections = []
|
||||
snippets = []
|
||||
retentionDays = DICTATION_RETENTION_DEFAULT_DAYS
|
||||
hudShowsHints = false
|
||||
hudSize = DICTATION_HUD_DEFAULT_SIZE
|
||||
promptGuidanceInstructions = PromptUserGuidance.none.instructions
|
||||
promptGuidanceExamples = PromptUserGuidance.none.examples
|
||||
promptModeEnabled = false
|
||||
speechEngine = .whisperTurbo
|
||||
speechEngine = installedSpeechEngine()
|
||||
promptRecipient = .codex
|
||||
appProfiles = []
|
||||
promptAgentID = PromptAgentCatalog.defaultID
|
||||
|
||||
Reference in New Issue
Block a user