Repository navigation
Expand file tree
/
Copy pathcontrol.rs
More file actions
1235 lines (1166 loc) · 41 KB
/
Copy pathcontrol.rs
File metadata and controls
1235 lines (1166 loc) · 41 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
//! `hex` control: the typed command/reply protocol an agent uses to drive the
//! one running Hex, the settings registry behind `hex settings`, and the CLI
//! client. Transports (the macOS local API's `POST /control`) only move
//! [`ControlRequest`]s and [`ControlResponse`]s; the app's host carries out
//! each command, and every rule shared between the window and the CLI lives
//! here or in the app's own setters.
pub mod cli;
#[cfg(not(target_os = "macos"))]
pub(crate) mod host;
pub mod settings;
use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender};
use std::time::Duration;
use serde::{Deserialize, Serialize};
use crate::vocabulary::{self, VocabularyEntry};
/// The wire version of [`ControlRequest`] and [`ControlResponse`]. A change
/// that breaks either shape increments it.
pub const CONTROL_VERSION: u32 = 4;
/// What a capture command does. Commands are idempotent: starting while
/// recording or stopping while idle changes nothing and succeeds.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum CaptureAction {
/// Start recording, locked as after a double tap: the shortcut or
/// `stop` finishes it, Escape or `cancel` discards it.
Start,
/// Finish the recording and transcribe it.
Stop,
/// Discard the recording, or the newest unfinished dictation.
Cancel,
/// Start when idle, otherwise stop.
Toggle,
}
/// What `hex capture` does (the `capture` experiment).
/// Idempotent like [`CaptureAction`].
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum ScrawlCaptureAction {
Start,
/// End the capture and write its bundle in the background.
Stop,
/// End the capture and discard its bundle.
Cancel,
Status,
}
/// The window's panes, by the names `hex window show` takes.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum Pane {
Settings,
/// Settings with the transcription model picker open.
Models,
#[value(alias = "replacements")]
Modes,
History,
Meetings,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "command", rename_all = "kebab-case")]
pub enum ControlCommand {
Status,
Quit {
#[serde(default)]
force: bool,
},
Restart {
#[serde(default)]
force: bool,
},
Dictation {
action: CaptureAction,
/// `stop` only: answer with the transcript instead of pasting it.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
print: bool,
/// `start` and `toggle` only: the dictation this starts pastes the
/// transcript as heard, skipping the Output pane's steps.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
raw: bool,
},
PasteLast,
MeetingRecord {
#[serde(default)]
title: Option<String>,
},
MeetingStop,
MeetingCopyLast,
SettingsGet {
#[serde(default)]
key: Option<String>,
},
SettingsSet {
key: String,
value: String,
},
/// Several settings at once, all or none (`hex settings apply`).
SettingsApply {
values: serde_json::Map<String, serde_json::Value>,
},
ModelList,
ModelUse {
model: String,
#[serde(default)]
language: Option<String>,
},
ModelInstall {
model: String,
#[serde(default)]
language: Option<String>,
},
ModelCancel,
WindowShow {
#[serde(default)]
pane: Option<Pane>,
},
WindowHide,
/// Replay the first-run onboarding in the window (dev, test, and local
/// builds); settings, history, models, and permissions stay.
OnboardingReset,
/// Open the window on a playground story (Labs).
WindowStory {
story: String,
#[serde(default)]
variant: Option<String>,
#[serde(default)]
play: bool,
},
HistoryClear,
CheckForUpdates,
/// Report Launch at Login, or turn it on or off.
LaunchAtLogin {
#[serde(default)]
enabled: Option<bool>,
},
/// The shared vocabulary.
VocabularyList,
VocabularyAdd {
term: String,
#[serde(default)]
sounds_like: Vec<String>,
},
VocabularyRemove {
term: String,
},
/// A Scrawl capture (the `capture` experiment).
ScrawlCapture {
action: ScrawlCaptureAction,
},
/// The newest captures in the captures folder, newest first.
ScrawlCaptureList {
#[serde(default)]
limit: Option<usize>,
},
/// One capture, by bundle name, path, or `latest`.
ScrawlCaptureShow {
capture: String,
},
/// Sends a capture to an OpenCode session: `to`, or where its route or
/// its last send says.
ScrawlCaptureSend {
capture: String,
#[serde(default)]
to: Option<String>,
/// Also save a rule sending the capture's site or app there (the
/// newest routed capture only).
#[serde(default)]
always: bool,
},
/// Takes the newest send back while it can be undone.
ScrawlCaptureUndo,
/// What routing sees for a capture and what it decides. `ask_jev` asks
/// Jev again (one call).
ScrawlCaptureRoute {
capture: String,
#[serde(default)]
ask_jev: bool,
},
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ControlRequest {
pub version: u32,
#[serde(flatten)]
pub command: ControlCommand,
}
impl ControlRequest {
pub fn new(command: ControlCommand) -> Self {
Self {
version: CONTROL_VERSION,
command,
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "status", rename_all = "kebab-case")]
pub enum ControlReply {
/// The command ran. `changed` is false when it was already so.
Done {
message: String,
changed: bool,
},
Status(Box<StatusReport>),
Settings {
settings: Vec<settings::SettingValue>,
},
Models {
models: Vec<ModelInfo>,
},
Vocabulary {
entries: Vec<VocabularyEntry>,
},
ScrawlCapture(Box<ScrawlCaptureReport>),
ScrawlCaptures {
captures: Vec<ScrawlCaptureSummary>,
},
ScrawlCaptureDetail(Box<ScrawlCaptureDetail>),
ScrawlCaptureRoute {
explanation: String,
},
/// `hex dictation stop --print`: the processed transcript.
Transcript {
text: String,
},
Error {
code: String,
message: String,
},
}
impl ControlReply {
pub fn done(message: impl Into<String>) -> Self {
Self::Done {
message: message.into(),
changed: true,
}
}
pub fn unchanged(message: impl Into<String>) -> Self {
Self::Done {
message: message.into(),
changed: false,
}
}
pub fn error(code: impl Into<String>, message: impl Into<String>) -> Self {
Self::Error {
code: code.into(),
message: message.into(),
}
}
}
impl From<ControlError> for ControlReply {
fn from(error: ControlError) -> Self {
Self::error(error.code, error.message)
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ControlResponse {
pub version: u32,
#[serde(flatten)]
pub reply: ControlReply,
}
impl From<ControlReply> for ControlResponse {
fn from(reply: ControlReply) -> Self {
Self {
version: CONTROL_VERSION,
reply,
}
}
}
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ScrawlCaptureState {
#[default]
Idle,
Recording,
}
/// A `scrawl-capture` command's answer.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct ScrawlCaptureReport {
/// False when the command found nothing to do.
pub changed: bool,
pub state: ScrawlCaptureState,
/// The recording capture's bundle, or the one `stop`/`cancel` just ended.
pub bundle: Option<std::path::PathBuf>,
pub elapsed_ms: Option<u64>,
/// Stopped captures still transcribing or writing.
#[serde(default)]
pub finishing: Vec<std::path::PathBuf>,
/// The most recent capture that finished, failed, or was cancelled.
pub last: Option<ScrawlCaptureOutcome>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ScrawlCaptureOutcome {
pub bundle: std::path::PathBuf,
/// done, failed, or cancelled.
pub stage: String,
pub words: Option<usize>,
/// Spans of a written capture's audio that went missing.
#[serde(default)]
pub gaps: Option<usize>,
/// Why a written capture has no transcript: `no_audio`, or the engine's
/// reason.
#[serde(default)]
pub missing_transcript: Option<String>,
}
/// A capture on disk, as `hex capture list` shows it.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct ScrawlCaptureSummary {
/// The bundle's folder name, which `show`, `send`, and `route` take.
pub id: String,
pub bundle: std::path::PathBuf,
pub created_at_ms: u64,
pub duration_ms: u64,
/// `screen`, `window`, `area`, or `iphone`.
pub mode: String,
pub app: Option<String>,
pub words: usize,
/// The session it was sent to, if it was.
pub sent_to: Option<ScrawlCaptureSession>,
/// OpenCode didn't take its send yet; Hex retries it.
#[serde(default)]
pub queued: bool,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ScrawlCaptureSession {
pub session: String,
pub title: String,
}
/// `hex capture show`: a capture's summary with its words and files.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct ScrawlCaptureDetail {
#[serde(flatten)]
pub summary: ScrawlCaptureSummary,
pub window_title: Option<String>,
pub transcript: String,
pub note: Option<String>,
/// Why there is no transcript although there was audio.
pub missing_transcript: Option<String>,
pub marks: usize,
pub keyframes: usize,
pub video: Option<std::path::PathBuf>,
pub audio: Option<std::path::PathBuf>,
pub contact_sheet: Option<std::path::PathBuf>,
}
/// A refused or failed command, with a stable code (see `docs/cli.md`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ControlError {
pub code: &'static str,
pub message: String,
}
impl ControlError {
pub fn new(code: &'static str, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
}
}
}
/// How long `hex dictation stop --print` waits for its transcript.
pub const PRINT_WAIT: Duration = Duration::from_secs(60);
/// How long the app may take to carry out any other control command.
const CONTROL_DEADLINE: Duration = Duration::from_secs(10);
impl ControlCommand {
/// How long a transport waits for the app's answer to this command.
pub fn deadline(&self) -> Duration {
match self {
Self::Dictation { print: true, .. } => PRINT_WAIT + Duration::from_secs(5),
_ => CONTROL_DEADLINE,
}
}
}
/// What a printing stop gets back from the listener once its dictation
/// finishes: the transcript, processed as a paste would be, or why there is
/// none. A printed transcript is never pasted.
#[derive(Debug, Eq, PartialEq)]
pub enum PrintedTranscript {
Text(String),
NoSpeech,
/// The Linux and Windows listeners stop by themselves without a recording.
#[cfg_attr(target_os = "macos", allow(dead_code))]
NotRecording,
Failed(String),
}
/// The one-shot channel a printing stop rides through the listener's queue.
#[derive(Clone, Debug)]
pub struct PrintReply(SyncSender<PrintedTranscript>);
impl PrintReply {
pub fn channel() -> (Self, Receiver<PrintedTranscript>) {
let (sender, receiver) = std::sync::mpsc::sync_channel(1);
(Self(sender), receiver)
}
/// Answers the waiting command; one that gave up is not told.
pub fn send(self, transcript: PrintedTranscript) {
let _ = self.0.send(transcript);
}
}
/// Shortcut events compare by kind; where a reply goes is not part of it.
impl PartialEq for PrintReply {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl Eq for PrintReply {}
/// Waits up to `wait` for a printing stop's transcript. A dropped reply
/// means the dictation was cancelled or failed before it had text.
pub fn await_printed(receiver: &Receiver<PrintedTranscript>, wait: Duration) -> ControlReply {
match receiver.recv_timeout(wait) {
Ok(PrintedTranscript::Text(text)) => ControlReply::Transcript { text },
Ok(PrintedTranscript::NoSpeech) => {
ControlReply::error("no-speech", "no speech was recorded; nothing to print")
}
Ok(PrintedTranscript::NotRecording) => ControlReply::error(
"not-recording",
"dictation isn't recording; nothing to print",
),
Ok(PrintedTranscript::Failed(error)) => {
ControlReply::error("failed", format!("couldn't transcribe it: {error}"))
}
Err(RecvTimeoutError::Timeout) => ControlReply::error(
"failed",
format!(
"no transcript within {} s; nothing was printed or pasted",
wait.as_secs()
),
),
Err(RecvTimeoutError::Disconnected) => ControlReply::error(
"failed",
"the dictation was cancelled or failed; nothing to print",
),
}
}
/// `print` applies only to `stop`.
pub fn check_flags(action: CaptureAction, print: bool, raw: bool) -> Result<(), ControlError> {
if print && action != CaptureAction::Stop {
return Err(ControlError::new(
"invalid-value",
"--print works only with `hex dictation stop`",
));
}
if raw && !matches!(action, CaptureAction::Start | CaptureAction::Toggle) {
return Err(ControlError::new(
"invalid-value",
"--raw works only with `hex dictation start` and `hex dictation toggle`",
));
}
Ok(())
}
/// One request from a transport to the app's control host.
pub struct ControlCall {
pub request: ControlRequest,
pub reply: SyncSender<ControlResponse>,
}
/// Rejects a request from a `hex` built for another protocol version.
pub fn check_version(request: &ControlRequest) -> Result<(), ControlError> {
if request.version == CONTROL_VERSION {
return Ok(());
}
Err(version_mismatch(request.version.into()))
}
pub fn version_mismatch(version: u64) -> ControlError {
ControlError::new(
"version-mismatch",
format!(
"this hex speaks control version {version}, but the running Hex speaks \
{CONTROL_VERSION}; use the hex inside the running app or restart Hex"
),
)
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct StatusReport {
pub app_version: String,
pub pid: u32,
/// The process's physical memory footprint, as Activity Monitor shows it.
pub memory_footprint_bytes: Option<u64>,
pub listener: ListenerReport,
pub capture: CaptureReport,
pub meeting: MeetingReport,
pub model: ModelReport,
pub features: FeatureReport,
pub permissions: PermissionReport,
pub window: WindowReport,
/// current, checking, available, or unavailable.
pub update: String,
/// The Labs features turned on (`crate::labs`), by `hex labs` name.
#[serde(default)]
pub labs: Vec<String>,
/// What this OS's Hex can do, by capability name (`rune_ui::platform`).
/// A command for one it can't do answers `unsupported`.
#[serde(default)]
pub capabilities: std::collections::BTreeMap<String, bool>,
}
/// `StatusReport::update` for an updater status.
pub fn update_label(status: &crate::desktop_host::DesktopUpdateStatus) -> &'static str {
use crate::desktop_host::DesktopUpdateStatus;
match status {
DesktopUpdateStatus::Checking | DesktopUpdateStatus::Downloading => "checking",
DesktopUpdateStatus::Available
| DesktopUpdateStatus::ReadyToRestart
| DesktopUpdateStatus::SwitchAvailable { .. }
| DesktopUpdateStatus::PackageUpdate { .. } => "available",
DesktopUpdateStatus::Unavailable
| DesktopUpdateStatus::Managed
| DesktopUpdateStatus::Failed => "unavailable",
DesktopUpdateStatus::Current
| DesktopUpdateStatus::SourceBuild
| DesktopUpdateStatus::PackageManager => "current",
}
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct ListenerReport {
pub running: bool,
pub status: String,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CaptureState {
#[default]
Idle,
Recording,
Transcribing,
/// The listener did not answer in time.
Unknown,
}
/// What is recording.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CaptureKind {
Dictation,
/// A host-audio dictation through the local API (`POST /dictations`).
Service,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct CaptureReport {
pub state: CaptureState,
pub recording: Option<CaptureKind>,
/// Accepted dictations still transcribing, processing, or pasting.
pub pending_jobs: usize,
}
/// The listener's capture state, as it answers a status query.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct CaptureSnapshot {
pub recording: Option<CaptureKind>,
pub pending_jobs: usize,
/// No microphone is open: none was found, or the stream is reopening.
pub microphone_unavailable: bool,
}
impl From<CaptureSnapshot> for CaptureReport {
fn from(snapshot: CaptureSnapshot) -> Self {
Self {
state: if snapshot.recording.is_some() {
CaptureState::Recording
} else if snapshot.pending_jobs > 0 {
CaptureState::Transcribing
} else {
CaptureState::Idle
},
recording: snapshot.recording,
pending_jobs: snapshot.pending_jobs,
}
}
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct MeetingReport {
/// idle, starting, recording, or transcribing.
pub state: String,
pub title: Option<String>,
pub elapsed_seconds: Option<u64>,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct ModelReport {
pub id: String,
pub name: String,
pub language: String,
pub installed: bool,
/// The model being downloaded or loaded, if any.
pub preparing: Option<String>,
pub downloaded_bytes: u64,
pub error: Option<String>,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct FeatureReport {
pub meetings: bool,
pub release_microphone_while_idle: bool,
pub history_retention: String,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct PermissionReport {
/// Every permission granted and the selected model installed.
pub ready: bool,
/// ready, needs-request, needs-settings, or needs-restart.
pub microphone: String,
pub accessibility: String,
pub transcription_model: bool,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct WindowReport {
pub open: bool,
pub pane: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ModelInfo {
pub id: String,
pub name: String,
pub languages: Vec<String>,
pub size: String,
pub installed: bool,
pub selected: bool,
pub streams: bool,
pub supports_recognition_hints: bool,
}
/// Every model `hex model` can name, with what this Mac has installed.
pub fn model_infos(
selection: &crate::transcription_models::TranscriptionSelection,
) -> Vec<ModelInfo> {
crate::transcription_models::MODELS
.iter()
.filter(|model| model.available())
.map(|model| ModelInfo {
id: model.id.as_str().into(),
name: model.name.into(),
languages: model.languages.iter().map(|&code| code.into()).collect(),
size: model.size_label(),
installed: crate::transcription_models::is_installed(model, &selection.language),
selected: model.id == selection.model,
streams: model.streams,
supports_recognition_hints: model.supports_recognition_hints,
})
.collect()
}
/// The selection `hex model use` or `install` asks for: a known, available
/// model, and a language it supports (the model's best match for the
/// current language when none is given).
pub fn model_selection(
settings: &crate::app_settings::AppSettings,
model: &str,
language: Option<&str>,
) -> Result<crate::transcription_models::TranscriptionSelection, ControlError> {
let id = model
.parse::<crate::transcription_models::TranscriptionModelId>()
.ok()
.filter(|id| crate::transcription_models::definition(*id).available())
.ok_or_else(|| {
ControlError::new(
"unknown-model",
format!("unknown model `{model}`; run `hex model list` for the ids"),
)
})?;
// The model's own remembered language and recognition hints, as the
// menu bar picks them; only the language can be overridden.
let mut selection = settings.transcription_for_model(id);
if let Some(language) = language {
selection.language = language.into();
}
let definition = crate::transcription_models::definition(id);
if !definition.supports_recognition_hints {
selection.recognition_hints.clear();
}
crate::transcription_models::validate(&selection).map_err(|error| {
let supported = if definition.languages.contains(&"*") {
"any language code Hex knows (en, de, fr, ja, …)".to_owned()
} else {
definition.languages.join(", ")
};
ControlError::new(
"invalid-value",
format!("{error}; {} supports {supported}", definition.name),
)
})?;
Ok(selection)
}
/// Refuses to stop Hex while it records, unless forced. `capture` is the
/// listener's answer (idle when no listener runs or setup gates it); a
/// listener that couldn't answer might be recording, so it refuses too.
pub fn check_quit(
meeting: &MeetingReport,
capture: Result<CaptureSnapshot, ControlError>,
force: bool,
) -> Result<(), ControlError> {
if force {
return Ok(());
}
if meeting.state != "idle" {
return Err(ControlError::new(
"meeting-active",
format!(
"a meeting is {}; stop it first (`hex meetings stop`) or pass --force",
meeting.state
),
));
}
match capture {
Ok(capture) if capture.recording.is_some() || capture.pending_jobs > 0 => {
Err(ControlError::new(
"busy",
"a dictation is recording or transcribing; wait for it or pass --force",
))
}
Ok(_) => Ok(()),
Err(error) => Err(ControlError::new(
"busy",
format!(
"couldn't confirm nothing is recording ({}); try again or pass --force",
error.message
),
)),
}
}
/// Carries out `hex vocabulary add|remove` on the saved list. The reply's
/// `changed` says whether the list needs saving.
pub fn edit_vocabulary(
list: &mut Vec<VocabularyEntry>,
command: &ControlCommand,
) -> Result<ControlReply, ControlError> {
let invalid = |message: String| ControlError::new("invalid-value", message);
match command {
ControlCommand::VocabularyAdd { term, sounds_like } => {
let sounds_like: Vec<String> = sounds_like
.iter()
.flat_map(|spellings| vocabulary::parse_sounds_like(spellings))
.collect();
let existed = vocabulary::contains(list, term);
Ok(
match vocabulary::add(list, term, &sounds_like).map_err(invalid)? {
false => ControlReply::unchanged(format!(
"“{}” is already in the vocabulary",
term.trim()
)),
true if existed => {
ControlReply::done(format!("Added spellings to “{}”", term.trim()))
}
true => ControlReply::done(format!("Added “{}”", term.trim())),
},
)
}
ControlCommand::VocabularyRemove { term } => Ok(if vocabulary::remove(list, term) {
ControlReply::done(format!("Removed “{}”", term.trim()))
} else {
ControlReply::unchanged(format!("“{}” isn't in the vocabulary", term.trim()))
}),
_ => Err(ControlError::new("internal", "not a vocabulary edit")),
}
}
/// Process memory footprint on macOS; `None` where unmeasured.
pub fn memory_footprint() -> Option<u64> {
#[cfg(target_os = "macos")]
{
// SAFETY: rusage_info_v4 is plain data that proc_pid_rusage fills.
let mut info = unsafe { std::mem::zeroed::<libc::rusage_info_v4>() };
// SAFETY: the pointer refers to a live, correctly sized buffer.
let status = unsafe {
libc::proc_pid_rusage(
std::process::id() as i32,
libc::RUSAGE_INFO_V4,
(&mut info as *mut libc::rusage_info_v4).cast(),
)
};
(status == 0).then_some(info.ri_phys_footprint)
}
#[cfg(not(target_os = "macos"))]
{
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_printing_stop_answers_through_its_reply_channel() {
let wait = Duration::from_millis(50);
let (reply, printed) = PrintReply::channel();
reply.send(PrintedTranscript::Text("Ship it.".into()));
assert_eq!(
await_printed(&printed, wait),
ControlReply::Transcript {
text: "Ship it.".into()
}
);
let (reply, printed) = PrintReply::channel();
reply.send(PrintedTranscript::NoSpeech);
assert!(matches!(
await_printed(&printed, wait),
ControlReply::Error { code, .. } if code == "no-speech"
));
// A dictation cancelled or failed before it had text drops the reply.
let (reply, printed) = PrintReply::channel();
drop(reply);
assert!(matches!(
await_printed(&printed, wait),
ControlReply::Error { code, .. } if code == "failed"
));
let (_reply, printed) = PrintReply::channel();
assert!(matches!(
await_printed(&printed, wait),
ControlReply::Error { code, .. } if code == "failed"
));
// Only `stop` prints, and older requests without the field still parse.
assert!(check_flags(CaptureAction::Start, true, false).is_err());
assert!(check_flags(CaptureAction::Stop, true, false).is_ok());
assert!(check_flags(CaptureAction::Toggle, false, true).is_ok());
assert!(check_flags(CaptureAction::Stop, false, true).is_err());
assert_eq!(
serde_json::from_str::<ControlRequest>(
r#"{"version":4,"command":"dictation","action":"stop"}"#
)
.unwrap()
.command,
ControlCommand::Dictation {
action: CaptureAction::Stop,
print: false,
raw: false,
}
);
}
fn round_trip_request(command: ControlCommand) {
let request = ControlRequest::new(command);
let json = serde_json::to_string(&request).unwrap();
assert_eq!(
serde_json::from_str::<ControlRequest>(&json).unwrap(),
request
);
}
#[test]
fn every_command_round_trips() {
for command in [
ControlCommand::Status,
ControlCommand::Quit { force: true },
ControlCommand::Restart { force: false },
ControlCommand::Dictation {
action: CaptureAction::Toggle,
print: false,
raw: false,
},
ControlCommand::Dictation {
action: CaptureAction::Stop,
print: true,
raw: false,
},
ControlCommand::Dictation {
action: CaptureAction::Start,
print: false,
raw: true,
},
ControlCommand::PasteLast,
ControlCommand::MeetingRecord {
title: Some("Design sync".into()),
},
ControlCommand::MeetingStop,
ControlCommand::MeetingCopyLast,
ControlCommand::SettingsGet { key: None },
ControlCommand::SettingsSet {
key: "release_microphone_while_idle".into(),
value: "on".into(),
},
ControlCommand::SettingsApply {
values: serde_json::Map::from_iter([("sound_effects".into(), false.into())]),
},
ControlCommand::ModelList,
ControlCommand::ModelUse {
model: "parakeet_v3".into(),
language: Some("pl".into()),
},
ControlCommand::ModelInstall {
model: "parakeet_v2".into(),
language: None,
},
ControlCommand::ModelCancel,
ControlCommand::WindowShow {
pane: Some(Pane::History),
},
ControlCommand::WindowHide,
ControlCommand::OnboardingReset,
ControlCommand::WindowStory {
story: "HUD/Processing".into(),
variant: Some("2".into()),
play: true,
},
ControlCommand::HistoryClear,
ControlCommand::CheckForUpdates,
ControlCommand::LaunchAtLogin {
enabled: Some(true),
},
ControlCommand::VocabularyList,
ControlCommand::VocabularyAdd {
term: "abattoir".into(),
sounds_like: vec!["avatar".into()],
},
ControlCommand::VocabularyRemove {
term: "abattoir".into(),
},
] {
round_trip_request(command);
}
let request: ControlRequest =
serde_json::from_str(r#"{"version":4,"command":"vocabulary-add","term":"Rune"}"#)
.unwrap();
assert_eq!(
request.command,
ControlCommand::VocabularyAdd {
term: "Rune".into(),
sounds_like: vec![],
}
);
}
#[test]
fn vocabulary_edits_report_whether_they_changed_the_list() {
let add = |term: &str, sounds_like: &[&str]| ControlCommand::VocabularyAdd {
term: term.into(),
sounds_like: sounds_like.iter().map(|&text| text.into()).collect(),
};
let remove = |term: &str| ControlCommand::VocabularyRemove { term: term.into() };
let mut list = Vec::new();
assert_eq!(
edit_vocabulary(&mut list, &add("abattoir", &["avatar, a bat war"])).unwrap(),
ControlReply::done("Added “abattoir”")
);
assert_eq!(list[0].sounds_like, ["avatar", "a bat war"]);
assert_eq!(
edit_vocabulary(&mut list, &add("Abattoir", &[])).unwrap(),
ControlReply::unchanged("“Abattoir” is already in the vocabulary")
);
assert_eq!(
edit_vocabulary(&mut list, &add("abattoir", &["abba toy"])).unwrap(),
ControlReply::done("Added spellings to “abattoir”")
);
assert_eq!(
edit_vocabulary(&mut list, &add(" ", &[])).unwrap_err().code,
"invalid-value"
);
assert_eq!(
edit_vocabulary(&mut list, &remove("ABATTOIR")).unwrap(),
ControlReply::done("Removed “ABATTOIR”")
);
assert_eq!(
edit_vocabulary(&mut list, &remove("abattoir")).unwrap(),
ControlReply::unchanged("“abattoir” isn't in the vocabulary")
);
assert!(list.is_empty());
}
#[test]
fn requests_are_flat_and_versioned() {
let json = serde_json::to_value(ControlRequest::new(ControlCommand::MeetingRecord {