Repository navigation
Expand file tree
/
Copy pathrecognition.rs
More file actions
2055 lines (1975 loc) · 82.9 KB
/
Copy pathrecognition.rs
File metadata and controls
2055 lines (1975 loc) · 82.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{BTreeMap, VecDeque};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, SyncSender, TrySendError};
use std::time::{Duration, Instant};
use color_eyre::Result;
use crate::audio::CaptureInstant;
use crate::audio::recording_environment::RecordingEnvironmentController;
use crate::control::{CaptureAction, CaptureKind, CaptureSnapshot, ControlReply, PrintReply};
use crate::desktop::events::{DictationPhase, EventLog, VoiceEvent, VoiceState, now_ms};
use crate::dictation::audio::{DictationAudio, DictationAudioEvent, LostCapture};
use crate::dictation::context::ContextSnapshot;
use crate::dictation::indicator::{DictationIndicatorEvent, DictationIndicatorSender};
use crate::dictation::service::{
Completion, DictationAudioChunk, DictationControl, DictationLevel, LEASE, MICROPHONE_LOST,
ProgrammaticDictationResult, ProgrammaticDictationStart, TerminalOutcome, finish_with_result,
lease_expired, level_for, remember_completion,
};
use crate::dictation::{DictationClip, Finish, POST_RELEASE_TAIL};
use crate::feedback::{self, Tone};
use crate::parakeet::{DictationWorker, TranscriptionTarget, WorkerEvent};
use crate::suppression::{DictationHotkey, DiscardCause, HotkeyAction, InputMonitor};
#[cfg(hex_capture)]
pub(crate) mod cancelled_words;
mod capture_actions;
mod context_watch;
mod events;
mod guards;
mod hotkeys;
mod output;
#[cfg(hex_capture)]
mod paste_picker;
mod stop_phrase;
use capture_actions::{control_dictation, handle_hotkey_action, paste_last};
use context_watch::ContextWatch;
use events::handle_dictation_event;
use guards::{
Release, WarmRelease, caps_lock_can_press, capture_boundary, capture_refusal, claims_escape,
paste_last_refusal,
};
use hotkeys::{Hotkeys, Shortcut};
use output::{finish_dictation, finish_dictation_with, interrupted_dictation};
enum FinishResult {
Discarded,
Silent,
Submitted,
Rejected(String),
}
/// The HUD and the Caps Lock light see the same dictation events. The HUD
/// channel has one consumer; the light's model is fed beside each send
/// instead of taking that channel over.
#[derive(Clone, Copy)]
struct DictationSink<'a> {
hud: Option<&'a DictationIndicatorSender>,
caps_lock: &'a crate::caps_lock_dictation::CapsLockDictation,
}
impl DictationSink<'_> {
fn send(&self, event: DictationIndicatorEvent) {
if let Some(hud) = self.hud {
hud.send(event.clone());
}
self.caps_lock.observe(event);
}
/// One chunk's loudness reaches both consumers: the light even when no
/// HUD listens, and the HUD exactly as it would have received it.
fn meter(&self, samples: &[f32]) {
if let Some(event) = DictationIndicatorEvent::meter(samples) {
self.send(event);
}
}
/// A non-dictation capture (Annotate) moves only the Caps Lock light, not
/// the dictation HUD.
#[cfg(hex_capture)]
fn caps_only(&self, event: DictationIndicatorEvent) {
self.caps_lock.observe(event);
}
}
#[derive(Debug)]
pub enum RecognitionControl {
/// Pastes the last dictation once nothing records; `reply` answers
/// `hex paste-last`, and the menu bar sends none.
PasteLast {
reply: Option<SyncSender<ControlReply>>,
},
/// `hex dictation`: drives the shortcut machine as a press would, so the
/// shortcut still finishes it.
/// A `stop` with `print` answers `reply` once recording stops and sends
/// the transcript to `print` instead of pasting it; a `start` with
/// `print` keeps `print` for however that recording ends.
Capture {
action: CaptureAction,
print: Option<PrintReply>,
/// Skip processing for the dictation this starts.
raw: bool,
reply: SyncSender<ControlReply>,
},
/// What is recording, for `hex status`.
CaptureStatus { reply: SyncSender<CaptureSnapshot> },
/// `hex capture` (the `capture` experiment; see `capture_host`).
#[cfg(hex_capture)]
ScrawlCapture {
action: crate::control::ScrawlCaptureAction,
reply: SyncSender<ControlReply>,
},
/// The capture capsule's switch chips and picker (`capture_host`).
#[cfg(hex_capture)]
CaptureCommand {
command: crate::capture_host::CaptureCommand,
reply: SyncSender<ControlReply>,
},
/// `/dictations`, which a local API client owns.
Dictation(DictationControl),
}
impl From<DictationControl> for RecognitionControl {
fn from(control: DictationControl) -> Self {
Self::Dictation(control)
}
}
struct ProgrammaticDictation {
id: u64,
owner_token: String,
source: String,
levels: SyncSender<DictationLevel>,
audio: Option<SyncSender<DictationAudioChunk>>,
/// Whether this capture was pressed while the warm microphone was
/// released, so its finish uses wall-clock time instead of the stream's.
pressed_cold: bool,
last_level: Instant,
lease_deadline: Instant,
}
impl ProgrammaticDictation {
fn matches_owner(&self, id: u64, owner_token: &str) -> bool {
self.id == id && self.owner_token == owner_token
}
}
/// A programmatic capture the microphone cut short: the audio delivered
/// before the loss, waiting for its owner's `/finish` or `/cancel` while
/// heartbeats renew its lease.
struct LostProgrammaticDictation {
id: u64,
owner_token: String,
source: String,
lease_deadline: Instant,
clip: DictationClip,
}
impl LostProgrammaticDictation {
fn matches_owner(&self, id: u64, owner_token: &str) -> bool {
self.id == id && self.owner_token == owner_token
}
}
struct FinishingProgrammaticDictation {
id: u64,
source: String,
owner_token: String,
duration_ms: u64,
replies: Vec<SyncSender<Result<ProgrammaticDictationResult, String>>>,
}
impl FinishingProgrammaticDictation {
fn matches_owner(&self, id: u64, owner_token: &str) -> bool {
self.id == id && self.owner_token == owner_token
}
}
pub fn listen(
events: EventLog,
device_override: Option<&str>,
shutdown: &AtomicBool,
indicator: Option<DictationIndicatorSender>,
history: Option<crate::history::History>,
controls: Option<Receiver<RecognitionControl>>,
transformations: Arc<crate::personal_commands::TransformationClient>,
) -> Result<()> {
shutdown.store(false, Ordering::Relaxed);
// Feedback admission is advisory: a cold audio stack can exceed the
// preload timeout, and missing tones must not stop desktop recognition.
if let Err(error) = feedback::preload() {
tracing::warn!(%error, "recording sounds are unavailable; continuing without feedback");
}
// A warm microphone is released while the setting asks or the person
// demonstrably cannot dictate; the owner is told as that changes. A
// capture keeps what its own press saw: the latch clears once the stream
// is back, but that capture still owes its start tone.
let (mut warm_release, mut release) = WarmRelease::start();
let mut events = events;
let input_monitor = InputMonitor::start()?;
let mut context = ContextWatch::start(input_monitor.activity.clone());
let mut hotkeys = Hotkeys::new(
DictationHotkey::new(
CaptureInstant::now(),
crate::app_settings::double_tap_lock(),
crate::app_settings::dictation_hotkey(),
),
DictationHotkey::new(
CaptureInstant::now(),
false,
crate::app_settings::RuntimeHotkey::default(),
),
);
hotkeys.configure(CaptureInstant::now());
let hud = indicator;
let caps_lock = crate::caps_lock_dictation::CapsLockDictation::new();
let indicator = DictationSink {
hud: hud.as_ref(),
caps_lock: &caps_lock,
};
let recording_environment = RecordingEnvironmentController::start();
#[cfg(hex_capture)]
let capture_environment = recording_environment.clone();
let (mut microphone_revision, microphone) = crate::app_settings::microphone_selection();
#[cfg(hex_capture)]
let mut paste_picker =
crate::paste::recent::enabled().then(|| paste_picker::Picker::new(history.clone()));
#[cfg(hex_capture)]
let cancel_history = history.clone().filter(|_| crate::paste::recent::enabled());
let dictation_worker = DictationWorker::start(
input_monitor.activity.clone(),
transformations.clone(),
history,
);
#[cfg(hex_capture)]
let cancel_writer = cancel_history
.zip(dictation_worker.engine())
.and_then(|(history, engine)| cancelled_words::Writer::start(history, engine));
let input = DictationAudio::open(
device_override,
microphone_revision,
microphone.as_deref(),
recording_environment,
input_monitor.pending_events(),
release.press,
dictation_worker.engine(),
)?;
#[cfg(hex_capture)]
let mut capture_host =
crate::capture_host::CaptureHost::start(dictation_worker.engine(), &capture_environment);
#[cfg(hex_capture)]
let mut capture_shortcut = crate::capture_host::CaptureShortcut::default();
let (mut transcription_revision, _) = crate::app_settings::transcription_selection();
let mut personal_host_enabled = crate::personal_commands::host_needed(
crate::app_settings::custom_transformations_selected(),
);
let mut next_personal_host_check = Instant::now();
let mut personal_commands = personal_host_enabled
.then(|| crate::personal_commands::PersonalCommands::start(transformations.clone()))
.flatten();
let mut next_programmatic_id = 1_u64;
let mut programmatic = None::<ProgrammaticDictation>;
let mut programmatic_lost = None::<LostProgrammaticDictation>;
let mut programmatic_results =
BTreeMap::<crate::parakeet::DictationJobId, FinishingProgrammaticDictation>::new();
let mut programmatic_completions = VecDeque::<Completion>::new();
events.emit(&VoiceEvent::SessionStarted {
timestamp_ms: now_ms(),
})?;
if input.is_recovering() {
hotkeys.suspend_all();
}
if hotkeys.dictation.is_recording() {
let accepted = input.start(capture_boundary(&input, release.press))?;
if accepted {
release.begin();
events.dictation(DictationPhase::Started, "")?;
indicator.send(DictationIndicatorEvent::Started);
} else {
hotkeys.dictation.suspend();
}
}
emit_state(&mut events, hotkeys.any_recording(), &input.device_name())?;
tracing::info!(device = %input.device_name(), "dictation listener started");
#[cfg(hex_capture)]
let mut capture_was_recording = false;
while !shutdown.load(Ordering::Relaxed) {
release = warm_release.reconcile(&input, release);
#[cfg(hex_capture)]
crate::capture_host::CaptureHost::reconcile(
&mut capture_host,
dictation_worker.engine().as_ref(),
&capture_environment,
&input,
);
#[cfg(hex_capture)]
{
let capture_recording = capture_host
.as_mut()
.is_some_and(|host| host.recording_since(&input).is_some());
if capture_recording != capture_was_recording {
capture_was_recording = capture_recording;
indicator.caps_only(if capture_recording {
DictationIndicatorEvent::Started
} else {
DictationIndicatorEvent::Cancelled
});
}
}
let caps_lock_on = crate::labs::caps_lock_dictation();
caps_lock.set_enabled(caps_lock_on);
// Turning the lab off mid-capture cancels it, as unbinding the
// second shortcut does.
if !caps_lock_on && hotkeys.stop_caps_lock() {
handle_hotkey_action(
HotkeyAction::Cancel,
false,
None,
input.captured_through(),
&input,
&dictation_worker,
&mut context,
&input.device_name(),
&mut events,
indicator,
&mut release,
)?;
}
if let Some(controls) = &controls {
while let Ok(control) = controls.try_recv() {
match control {
RecognitionControl::PasteLast { reply } => {
let capture_active = programmatic.is_some()
|| hotkeys.suppresses_recognition()
|| input.is_recording();
#[cfg(hex_capture)]
let capture_active = capture_active
|| paste_picker
.as_ref()
.is_some_and(paste_picker::Picker::busy);
let answer = match paste_last_refusal(capture_active) {
Some(refusal) => refusal,
None => {
paste_last(&dictation_worker, &input.device_name(), &mut events)?
}
};
if let Some(reply) = reply {
let _ = reply.send(answer);
}
}
#[cfg(hex_capture)]
RecognitionControl::ScrawlCapture { action, reply } => {
let answer = match capture_host.as_mut() {
Some(host) => host.control(action, &input),
None => ControlReply::error(
"feature-off",
"Annotate is off; turn it on in Settings › Annotate or \
run `hex settings set capture.enabled true`",
),
};
let _ = reply.send(answer);
}
#[cfg(hex_capture)]
RecognitionControl::CaptureCommand { command, reply } => {
let answer = match capture_host.as_mut() {
Some(host) => host.command(command, &input),
None => ControlReply::error("feature-off", "captures are off"),
};
let _ = reply.send(answer);
}
RecognitionControl::CaptureStatus { reply } => {
let recording = if programmatic.is_some() {
Some(CaptureKind::Service)
} else if hotkeys.any_recording() {
Some(CaptureKind::Dictation)
} else {
None
};
let _ = reply.send(CaptureSnapshot {
recording,
pending_jobs: dictation_worker.pending_count(),
microphone_unavailable: input.is_recovering(),
});
}
RecognitionControl::Capture {
action,
print,
raw,
reply,
} => {
let other_recording = programmatic.is_some();
let suspended =
crate::app_settings::hotkey_capture_active() || input.is_recovering();
let outcome = control_dictation(
action,
print,
raw,
other_recording,
suspended,
&mut hotkeys,
&input,
&dictation_worker,
&mut context,
&mut events,
indicator,
&mut release,
)?;
let _ = reply.send(outcome);
}
RecognitionControl::Dictation(DictationControl::Start {
source,
owner_token,
levels,
partials,
reply,
}) => {
// A programmatic capture doesn't stream here, so it
// has no live text: a client's partials end at once.
drop(partials);
if programmatic.is_some() || input.is_recording() || hotkeys.any_recording()
{
let _ = reply.send(Err("dictation-busy".into()));
continue;
}
let id = next_programmatic_id;
next_programmatic_id = next_programmatic_id.wrapping_add(1).max(1);
let boundary = capture_boundary(&input, release.press);
match input.start_programmatic(boundary) {
Ok(()) => {
hotkeys.disarm_pending_gestures();
tracing::info!(
dictation_id = id,
source,
"programmatic dictation started"
);
programmatic = Some(ProgrammaticDictation {
id,
owner_token,
source,
levels,
audio: None,
pressed_cold: release.press,
last_level: Instant::now() - Duration::from_millis(30),
lease_deadline: Instant::now() + LEASE,
});
let _ = reply.send(Ok(ProgrammaticDictationStart {
id,
sample_rate: input.sample_rate(),
}));
}
Err(error) => {
let _ = reply.send(Err(error.to_string()));
}
}
}
RecognitionControl::Dictation(DictationControl::AttachAudio {
id,
owner_token,
audio,
reply,
}) => {
let Some(active) = programmatic
.as_mut()
.filter(|active| active.matches_owner(id, &owner_token))
else {
let _ = reply.send(Err("dictation-not-active".into()));
continue;
};
if active.audio.is_some() {
let _ = reply.send(Err("audio-already-subscribed".into()));
continue;
}
active.audio = Some(audio);
let _ = reply.send(Ok(()));
}
RecognitionControl::Dictation(DictationControl::Finish {
id,
owner_token,
reply,
}) => {
if let Some(finishing) = programmatic_results
.values_mut()
.find(|finishing| finishing.matches_owner(id, &owner_token))
{
finishing.replies.push(reply);
continue;
}
if let Some(completion) = programmatic_completions
.iter()
.rev()
.find(|completion| completion.matches_owner(id, &owner_token))
{
let result = match &completion.outcome {
TerminalOutcome::Finished(result) => result.clone(),
TerminalOutcome::Cancelled => Err("cancelled".into()),
};
let _ = reply.send(result);
continue;
}
let (source, finish) = if let Some(lost) =
programmatic_lost.take_if(|lost| lost.matches_owner(id, &owner_token))
{
(lost.source, Finish::Transcribe(lost.clip))
} else if programmatic
.as_ref()
.is_some_and(|active| active.matches_owner(id, &owner_token))
{
let active = programmatic.take().expect("active dictation was checked");
let boundary = capture_boundary(&input, active.pressed_cold);
// The microphone may have failed before this
// finish reached the audio owner, with its loss
// still queued.
let finish = match input.finish(boundary)? {
Finish::Discard => match input.take_loss() {
Some(LostCapture::Kept(clip)) => Finish::Transcribe(clip),
Some(LostCapture::Empty) => {
log_programmatic_ended(Some(active), "mic-lost");
finish_with_result(
id,
owner_token,
vec![reply],
Err(MICROPHONE_LOST.into()),
&mut programmatic_completions,
);
continue;
}
None => Finish::Discard,
},
finish => finish,
};
(active.source, finish)
} else {
let _ = reply.send(Err("dictation-not-active".into()));
continue;
};
match finish {
Finish::Transcribe(clip) => {
let duration_ms = clip.duration_ms();
match dictation_worker.transcribe(
clip,
TranscriptionTarget::Service,
ContextSnapshot::default(),
None,
) {
Ok(job_id) => {
programmatic_results.insert(
job_id,
FinishingProgrammaticDictation {
id,
source: source.clone(),
owner_token,
duration_ms,
replies: vec![reply],
},
);
tracing::info!(
dictation_id = id,
source,
"programmatic dictation submitted"
);
}
Err(error) => {
tracing::warn!(
dictation_id = id,
source,
outcome = "worker-error",
error = %error,
"programmatic dictation ended"
);
finish_with_result(
id,
owner_token,
vec![reply],
Err(error.into()),
&mut programmatic_completions,
);
}
}
}
Finish::Discard => {
tracing::warn!(
dictation_id = id,
source,
outcome = "discarded",
"programmatic dictation ended"
);
finish_with_result(
id,
owner_token,
vec![reply],
Err("capture-discarded".into()),
&mut programmatic_completions,
);
}
}
}
RecognitionControl::Dictation(DictationControl::Cancel {
id,
owner_token,
reply,
}) => {
if let Some(completion) = programmatic_completions
.iter()
.rev()
.find(|completion| completion.matches_owner(id, &owner_token))
&& matches!(completion.outcome, TerminalOutcome::Cancelled)
{
let _ = reply.send(Ok(()));
continue;
}
if programmatic_results
.values()
.any(|finishing| finishing.matches_owner(id, &owner_token))
{
let _ = reply.send(Err("dictation-finishing".into()));
continue;
}
if let Some(lost) =
programmatic_lost.take_if(|lost| lost.matches_owner(id, &owner_token))
{
tracing::info!(
dictation_id = id,
source = lost.source,
"programmatic dictation cancelled"
);
remember_completion(
&mut programmatic_completions,
Completion {
id,
owner_token,
outcome: TerminalOutcome::Cancelled,
},
);
let _ = reply.send(Ok(()));
continue;
}
if programmatic
.as_ref()
.is_none_or(|active| !active.matches_owner(id, &owner_token))
{
let _ = reply.send(Err("dictation-not-active".into()));
continue;
}
let active = programmatic.take().expect("active dictation was checked");
tracing::info!(
dictation_id = id,
source = active.source,
"programmatic dictation cancelled"
);
cancel_programmatic_capture(active, &input, &mut programmatic_completions)?;
let _ = reply.send(Ok(()));
}
RecognitionControl::Dictation(DictationControl::Heartbeat {
id,
owner_token,
reply,
}) => {
let lease_deadline = if let Some(active) = programmatic
.as_mut()
.filter(|active| active.matches_owner(id, &owner_token))
{
&mut active.lease_deadline
} else if let Some(lost) = programmatic_lost
.as_mut()
.filter(|lost| lost.matches_owner(id, &owner_token))
{
&mut lost.lease_deadline
} else {
let _ = reply.send(Err("dictation-not-active".into()));
continue;
};
*lease_deadline = Instant::now() + LEASE;
let _ = reply.send(Ok(()));
}
}
}
}
if programmatic
.as_ref()
.is_some_and(|active| lease_expired(active.lease_deadline, Instant::now()))
{
let expired = programmatic.take().expect("expired dictation was checked");
tracing::warn!(
dictation_id = expired.id,
source = expired.source,
"programmatic dictation lease expired"
);
cancel_programmatic_capture(expired, &input, &mut programmatic_completions)?;
}
if let Some(expired) =
programmatic_lost.take_if(|lost| lease_expired(lost.lease_deadline, Instant::now()))
{
tracing::warn!(
dictation_id = expired.id,
source = expired.source,
"programmatic dictation lease expired"
);
remember_completion(
&mut programmatic_completions,
Completion {
id: expired.id,
owner_token: expired.owner_token,
outcome: TerminalOutcome::Cancelled,
},
);
}
context.drain(&mut events)?;
if Instant::now() >= next_personal_host_check {
next_personal_host_check = Instant::now() + Duration::from_millis(250);
let next_personal_host_enabled = crate::personal_commands::host_needed(
crate::app_settings::custom_transformations_selected(),
);
if next_personal_host_enabled != personal_host_enabled {
personal_host_enabled = next_personal_host_enabled;
personal_commands = personal_host_enabled
.then(|| {
crate::personal_commands::PersonalCommands::start(transformations.clone())
})
.flatten();
}
}
if hotkeys.configure(CaptureInstant::now()) {
handle_hotkey_action(
HotkeyAction::Cancel,
false,
None,
input.captured_through(),
&input,
&dictation_worker,
&mut context,
&input.device_name(),
&mut events,
indicator,
&mut release,
)?;
}
let (next_microphone_revision, microphone) = crate::app_settings::microphone_selection();
if next_microphone_revision != microphone_revision {
input.request_selection(next_microphone_revision, microphone.as_deref());
microphone_revision = next_microphone_revision;
}
let (next_revision, selection) = crate::app_settings::transcription_selection();
if next_revision != transcription_revision && dictation_worker.reload(selection).is_ok() {
transcription_revision = next_revision;
}
let hotkey_capture_suspended = crate::shortcut_pause::tick() || input.is_recovering();
if hotkeys.suspend_when(hotkey_capture_suspended) {
handle_hotkey_action(
HotkeyAction::Cancel,
false,
None,
input.captured_through(),
&input,
&dictation_worker,
&mut context,
&input.device_name(),
&mut events,
indicator,
&mut release,
)?;
}
// Caps Lock presses arrive from the tap, off the audio and input
// threads, with the physical press's own timestamp. Never start one
// while a shortcut is recorded or a programmatic dictation owns the
// microphone.
while let Some(at) = caps_lock.try_recv_press() {
if hotkey_capture_suspended || programmatic.is_some() {
continue;
}
let caps_recording = hotkeys.caps_lock.is_recording();
#[cfg(hex_capture)]
let annotate_recording = capture_host
.as_mut()
.is_some_and(|host| host.recording_since(&input).is_some());
#[cfg(not(hex_capture))]
let annotate_recording = false;
if !caps_lock_can_press(caps_recording, annotate_recording) {
continue;
}
let Some(action) = hotkeys.caps_lock_press() else {
continue;
};
let accepted = handle_hotkey_action(
action,
hotkeys.raw_capture,
None,
at,
&input,
&dictation_worker,
&mut context,
&input.device_name(),
&mut events,
indicator,
&mut release,
)?;
if !accepted {
hotkeys.suspend(Shortcut::CapsLock);
}
}
// The capture shortcut ignores keys while shortcuts are suspended or
// a programmatic dictation holds them, so their releases go unseen.
#[cfg(hex_capture)]
if hotkey_capture_suspended || programmatic.is_some() {
capture_shortcut.reset();
}
while let Ok(observed) = input_monitor.events.try_recv() {
let _acknowledge = input_monitor.acknowledge_after(observed);
let input_event = observed.event;
let capture_at = observed.capture_at;
// Escape included: it belongs to the owner app (closing a
// picker while a note records), which cancels through the API.
if programmatic.is_some() {
hotkeys.track_key_state(input_event, capture_at);
continue;
}
if hotkey_capture_suspended {
continue;
}
#[cfg(hex_capture)]
if let Some(picker) = paste_picker.as_mut()
&& let Err(error) = picker.edge(input_event, capture_at, &dictation_worker)
{
events.dictation(DictationPhase::Failed(error.into()), "")?;
}
// Labs › YOLO mode: Escape after a release skips that
// dictation's Return.
if input_event.is_escape_down() {
crate::dictation::yolo_mode::note_escape();
}
#[cfg(hex_capture)]
if let Some(host) = capture_host.as_mut() {
// Escape while drawing stops drawing, never the recording.
if input_event.is_escape_down() && crate::capture_host::exit_drawing() {
continue;
}
let activity = host.shortcut_activity(capture_at, &input);
let action = capture_shortcut.input(
input_event,
crate::app_settings::runtime_hotkeys(),
activity,
);
let swallow = matches!(
action,
crate::capture_host::ShortcutAction::Cancel
| crate::capture_host::ShortcutAction::ReplayCancel
);
host.shortcut_at(action, capture_at, &input);
if swallow {
// Escape before the shortcut's keys came up (or while
// narrating a replay): nothing else hears it.
continue;
}
}
// Escape closes the capsule's picker or open list (never an
// Undo: that is a click). It never ends a dictation or a
// recording capture: it may be meant for the app in front (#786).
#[cfg(hex_capture)]
if input_event.is_escape_down()
&& crate::capture_host::capsule_key(crate::capture_host::CapsuleKey::Escape)
{
continue;
}
// Annotate records the narration itself: while it records, the
// dictation shortcut starts nothing. The tap still swallows its
// chord, so it never reaches the app.
#[cfg(hex_capture)]
if !hotkeys.any_recording()
&& capture_host
.as_mut()
.is_some_and(|host| host.recording_since(&input).is_some())
{
hotkeys.track_key_state(input_event, capture_at);
continue;
}
for (shortcut, action) in hotkeys.process(input_event, capture_at) {
// Only a physical edge from the owner of a shortcut recording.
// Control requests also use CancelShortcut, but never come here.
#[cfg(hex_capture)]
if action == HotkeyAction::CancelShortcut
&& dictation_worker.started_by_shortcut()
&& let Some(writer) = &cancel_writer
{
writer.cancel(&input, capture_at)?;
context.cancel();
feedback::retract_start();
crate::screenshots::narration::ended();
feedback::play(Tone::Cancel);
report_capture_end(
CaptureEnd::Cancelled,
&input.device_name(),
&mut events,
indicator,
)?;
continue;
}
#[cfg(hex_capture)]
if action == HotkeyAction::PasteLast
&& let Some(picker) = paste_picker.as_mut()
&& let Some(binding) = crate::app_settings::runtime_hotkeys().paste_last
{
context.cancel();
feedback::retract_start();
input.cancel()?;
if let Err(error) = picker.press(binding, capture_at, &dictation_worker) {
events.dictation(DictationPhase::Failed(error.into()), "")?;
}
emit_engine_state(&mut events, false, &dictation_worker, &input.device_name())?;
continue;
}
if action == HotkeyAction::Start {
hotkeys.raw_capture = shortcut == Shortcut::Raw;
}
let print = hotkeys.print_for(shortcut, action);
let accepted = handle_hotkey_action(
action,
hotkeys.raw_capture,
print,
capture_at,
&input,
&dictation_worker,
&mut context,
&input.device_name(),
&mut events,
indicator,
&mut release,
)?;
if !accepted {
hotkeys.suspend(shortcut);
}
}
}
if programmatic.is_none()
&& !hotkey_capture_suspended
&& input_monitor.pending_events().oldest().is_none()
{
hotkeys.recover_stale_keys();
}
if hotkeys.any_recording()
&& input.become_intentional(capture_boundary(&input, release.capture))?
{
// The press is a real capture now: read its page once, here
// rather than on every provisional press. A tap this loop never
// sees that way asks when it finishes instead. A capture pressed
// while the microphone was released still owes its tone here,
// even if the stream has come back since.
context.intend();
if release.capture {
feedback::play(Tone::DictationStart);
}
}
// Only once every queued edge is handled, so a release already seen
// ends the press first.
if !hotkey_capture_suspended && input_monitor.pending_events().oldest().is_none() {
hotkeys.break_chords(CaptureInstant::now());
}
#[cfg(hex_capture)]
if let Some(picker) = paste_picker.as_mut()
&& let Err(error) = picker.tick(
hotkey_capture_suspended
|| programmatic.is_some()
|| hotkeys.any_recording()
|| capture_was_recording,
&dictation_worker,
)
{
events.dictation(DictationPhase::Failed(error.into()), "")?;
}
let mut received_worker_event = false;
while let Some(event) = dictation_worker.try_recv() {
received_worker_event = true;
match event {
WorkerEvent::Completed {
job_id,
target: TranscriptionTarget::Service,
result,
..
} => {
if let Some(finishing) = programmatic_results.remove(&job_id) {
match &result {
Ok(transcript) => tracing::info!(
dictation_id = finishing.id,
source = finishing.source,
outcome = "transcribed",
transcript_chars = transcript.chars().count(),
duration_ms = finishing.duration_ms,
"programmatic dictation ended"
),
Err(error) => tracing::warn!(
dictation_id = finishing.id,
source = finishing.source,
outcome = "worker-error",
duration_ms = finishing.duration_ms,
error = %error,
"programmatic dictation ended"
),