Repository navigation
Expand file tree
/
Copy pathcli.rs
More file actions
1642 lines (1575 loc) · 55.2 KB
/
Copy pathcli.rs
File metadata and controls
1642 lines (1575 loc) · 55.2 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
//! The `hex` control client: parses a command, sends it to the running Hex,
//! and prints the answer for a person or, with `--json`, the versioned reply.
//!
//! Exit codes: 0 when the command ran (or there was nothing to change), 1
//! when Hex refused or failed it, 2 for usage errors (clap), 3 when Hex
//! isn't running, and 4 when `dictation stop --print` heard no speech. Nothing here launches Hex except `start` and `restart`.
use std::io::Write;
use clap::{Args, Subcommand};
use serde_json::Value;
use super::{
CONTROL_VERSION, CaptureAction, ControlCommand, ControlReply, ControlRequest, ControlResponse,
ModelInfo, Pane, StatusReport, settings::SettingValue,
};
use crate::vocabulary::VocabularyEntry;
pub const EXIT_REFUSED: u8 = 1;
pub const EXIT_NOT_RUNNING: u8 = 3;
pub const EXIT_NO_SPEECH: u8 = 4;
#[derive(Args, Clone, Copy, Debug, Default)]
pub struct Output {
/// Print the versioned JSON reply (see docs/cli.md).
#[arg(long)]
pub json: bool,
}
/// The control commands at the top of `hex`.
#[derive(Subcommand, Debug)]
pub enum ControlCli {
/// Show what the running Hex is doing.
///
/// Recording, meeting, model, features, permissions, window, version,
/// pid, and memory footprint.
Status {
#[command(flatten)]
output: Output,
},
/// Open Hex if it isn't running, and wait until it answers.
Start {
#[command(flatten)]
output: Output,
},
/// Quit Hex.
///
/// Refused while a meeting or dictation is in progress unless --force.
Quit {
/// Quit even while recording; the recording is lost.
#[arg(long)]
force: bool,
#[command(flatten)]
output: Output,
},
/// Quit and reopen Hex (or open it if it isn't running).
Restart {
/// Restart even while recording; the recording is lost.
#[arg(long)]
force: bool,
#[command(flatten)]
output: Output,
},
/// Start, stop, cancel, or toggle a dictation, as the shortcut would.
///
/// `start` locks the recording: `stop` or the shortcut finishes it,
/// `cancel` or Escape discards it. Repeating a command changes nothing.
Dictation {
#[arg(value_enum)]
action: CaptureAction,
/// With `stop`: wait for the transcript and print it instead of
/// pasting it. Exits 4, printing nothing, when no speech was heard.
#[arg(long)]
print: bool,
/// With `start` or `toggle`: paste the transcript as heard,
/// skipping the Output pane's steps, like Dictate without
/// processing.
#[arg(long)]
raw: bool,
#[command(flatten)]
output: Output,
},
/// Paste the last dictation at the current focus (Option-Shift-V).
PasteLast {
#[command(flatten)]
output: Output,
},
/// Read and change any persisted setting, shortcuts included.
Settings {
#[command(subcommand)]
command: SettingsCommand,
},
/// List, switch, and install transcription models.
Model {
#[command(subcommand)]
command: ModelCommand,
},
/// Open the Hex window at a pane, or close it.
Window {
#[command(subcommand)]
command: WindowCommand,
},
/// Replay the first-run onboarding (needs Labs on).
Onboarding {
#[command(subcommand)]
command: OnboardingCommand,
},
/// Check for a Hex update now; Hex shows what it finds.
CheckForUpdates {
#[command(flatten)]
output: Output,
},
/// Show Launch at Login, or turn it on or off.
LaunchAtLogin {
#[arg(value_enum)]
state: Option<Toggle>,
#[command(flatten)]
output: Output,
},
/// List, add, and remove vocabulary terms.
Vocabulary {
#[command(subcommand)]
command: VocabularyCommand,
},
/// Read retained dictation history without starting the app, or clear
/// it in the running Hex (`hex history clear --yes`).
#[command(args_conflicts_with_subcommands = true)]
History(crate::transcript_cli::HistoryArgs),
/// Read and search recorded meetings without starting the app; record
/// and stop them in the running Hex.
Meetings {
#[command(subcommand)]
command: crate::transcript_cli::MeetingsCommand,
},
/// Serve recorded meetings to agents over MCP (stdio). Read-only.
Mcp {
/// Read meetings from this folder instead of Application Support, such
/// as a mirrored copy on another computer.
#[arg(long)]
meetings_dir: Option<std::path::PathBuf>,
},
/// Manage the ~/.config/hex personal transformations workspace.
Commands {
#[command(subcommand)]
command: CommandsCommand,
},
/// List the Labs features, or turn one on or off.
Labs {
#[command(subcommand)]
command: Option<crate::labs::LabsCommand>,
},
/// Replaced by `hex labs`.
#[command(hide = true)]
Experiments {
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
/// Annotate: record your screen with drawing and narration in the
/// running Hex, then list and send what you recorded (`hex capture`
/// still works).
#[command(name = "annotate", alias = "capture")]
Annotate {
#[command(subcommand)]
command: CaptureCommand,
},
/// Print Hex's recent log lines; works without Hex running.
Logs {
/// Read process.log (Rust and native diagnostics) instead of the
/// live.ndjson event log.
#[arg(long)]
process: bool,
/// How many lines from the end.
#[arg(short = 'n', long, default_value_t = 50)]
lines: usize,
/// Keep printing new lines until interrupted.
#[arg(short, long)]
follow: bool,
},
}
#[derive(Subcommand, Debug)]
pub enum CommandsCommand {
/// Create ~/.config/hex with a starter config, or refresh its typings.
Init,
/// Load ~/.config/hex's config as Hex would and report what it registers
/// or why it fails.
Check,
}
#[derive(Subcommand, Debug)]
pub enum SettingsCommand {
/// Every setting with its value, kind, and whether it can be set.
List {
#[command(flatten)]
output: Output,
},
/// One setting's value, or every setting under a prefix (`meetings`).
Get {
key: String,
#[command(flatten)]
output: Output,
},
/// Change a setting as the window would.
///
/// Booleans take on/off, shortcuts take text such as `option+shift+v`,
/// `right-command`, `fn`, or `f5`, and optional settings take `none`.
Set {
key: String,
value: String,
#[command(flatten)]
output: Output,
},
/// Set several settings at once from a JSON object of `key: value`,
/// all or none; other settings keep their values.
///
/// Values are JSON (`true`, `0.4`, `"option+space"`, `null` for none);
/// `transcription.model` and `transcription.language` select a model
/// without downloading it. With Hex stopped, writes settings.json
/// directly.
Apply {
/// A JSON file, or `-` for standard input.
file: std::path::PathBuf,
#[command(flatten)]
output: Output,
},
}
#[derive(Subcommand, Debug)]
pub enum ModelCommand {
/// Every model with its languages, size, and whether it's installed.
List {
#[command(flatten)]
output: Output,
},
/// Switch to an installed model. Never downloads.
Use {
/// A model id from `hex model list`.
model: String,
/// A language the model supports (default: its best match for the
/// current language).
#[arg(long)]
language: Option<String>,
#[command(flatten)]
output: Output,
},
/// Download a model, then switch to it. Without a model, the selected
/// one. On Linux and Windows it downloads here when Hex isn't running.
Install {
model: Option<String>,
#[arg(long)]
language: Option<String>,
#[command(flatten)]
output: Output,
},
/// Stop a download or load in progress.
Cancel {
#[command(flatten)]
output: Output,
},
/// Whether a model (the selected one unless given) is installed and
/// checksum-verified. Runs here; Linux and Windows.
Status {
model: Option<String>,
#[arg(long)]
language: Option<String>,
},
/// The transcribe.cpp compute devices Hex can use. Linux and Windows.
Devices,
/// Load and prewarm an installed model here. Linux and Windows.
Check {
model: Option<String>,
#[arg(long)]
language: Option<String>,
},
/// Transcribe a WAV file with an installed model here. Linux and Windows.
Transcribe {
wav: std::path::PathBuf,
#[arg(long)]
model: Option<String>,
#[arg(long)]
language: Option<String>,
},
}
#[derive(Subcommand, Debug)]
pub enum OnboardingCommand {
/// Open the first-run onboarding in the window now, as on a new install.
///
/// Forgets that onboarding finished. Settings, history, models, and permissions stay,
/// so their steps pass at once.
#[command(visible_alias = "restart")]
Reset {
#[command(flatten)]
output: Output,
},
}
#[derive(Subcommand, Debug)]
pub enum WindowCommand {
/// Open the window, at a pane if given.
Show {
#[arg(value_enum)]
pane: Option<Pane>,
#[command(flatten)]
output: Output,
},
/// Close the window. Hex keeps running in the menu bar.
Hide {
#[command(flatten)]
output: Output,
},
/// Labs: open the window on a playground story by its path, name, or
/// slug (`Prototypes/HUD/Processing`, `prototypes-hud-processing`).
Story {
story: String,
/// The variant, by number from 1 or by name.
#[arg(long)]
variant: Option<String>,
/// Run the story's `r` trigger once it's open, as pressing R does.
#[arg(long)]
play: bool,
#[command(flatten)]
output: Output,
},
}
#[derive(Subcommand, Debug)]
pub enum VocabularyCommand {
/// Every term with its "sounds like" spellings.
List {
#[command(flatten)]
output: Output,
},
/// Add a term, or more spellings to a term already in the list.
Add {
term: String,
/// Spellings a transcript may show instead, comma-separated
/// (`--sounds-like "avatar,a bat war"`).
#[arg(long, value_name = "SPELLINGS")]
sounds_like: Option<String>,
#[command(flatten)]
output: Output,
},
/// Remove a term and its spellings.
Remove {
term: String,
#[command(flatten)]
output: Output,
},
}
#[derive(Clone, Copy, Debug, clap::ValueEnum)]
pub enum Toggle {
On,
Off,
}
/// Exits with `code` once stdout is flushed.
pub fn finish(code: u8) -> ! {
let _ = std::io::stdout().flush();
std::process::exit(code.into())
}
pub fn run(command: ControlCli) -> u8 {
match command {
ControlCli::Status { output } => send(ControlCommand::Status, output),
ControlCli::Start { output } => start(output),
ControlCli::Quit { force, output } => send(ControlCommand::Quit { force }, output),
ControlCli::Restart { force, output } => {
if !running() {
return start(output);
}
#[cfg(target_os = "linux")]
if let Err(error) = crate::linux_service::prepare_restart() {
return print(ControlReply::error("failed", format!("{error:#}")), output);
}
#[cfg(target_os = "macos")]
return send(ControlCommand::Restart { force }, output);
#[cfg(not(target_os = "macos"))]
match call(ControlRequest::new(ControlCommand::Restart { force })) {
Ok(ControlResponse {
reply: ControlReply::Done { .. },
..
}) => print(reopen_after_restart(), output),
Ok(response) => print(response.reply, output),
Err(reply) => print(reply, output),
}
}
ControlCli::Dictation {
action,
print,
raw,
output,
} => {
if let Err(error) = super::check_flags(action, print, raw) {
eprintln!("hex: {}", error.message);
return 2;
}
send(ControlCommand::Dictation { action, print, raw }, output)
}
ControlCli::PasteLast { output } => send(ControlCommand::PasteLast, output),
ControlCli::Settings { command } => settings(command),
ControlCli::Model { command } => match command {
ModelCommand::List { output } => send(ControlCommand::ModelList, output),
ModelCommand::Use {
model,
language,
output,
} => send(ControlCommand::ModelUse { model, language }, output),
ModelCommand::Install {
model,
language,
output,
} => install_model(model, language, output),
ModelCommand::Cancel { output } => send(ControlCommand::ModelCancel, output),
command => offline_model(command),
},
ControlCli::Window { command } => match command {
WindowCommand::Show { pane, output } => {
send(ControlCommand::WindowShow { pane }, output)
}
WindowCommand::Hide { output } => send(ControlCommand::WindowHide, output),
WindowCommand::Story {
story,
variant,
play,
output,
} => send(
ControlCommand::WindowStory {
story,
variant,
play,
},
output,
),
},
ControlCli::Onboarding {
command: OnboardingCommand::Reset { output },
} => send(ControlCommand::OnboardingReset, output),
ControlCli::CheckForUpdates { output } => send(ControlCommand::CheckForUpdates, output),
ControlCli::LaunchAtLogin { state, output } => send(
ControlCommand::LaunchAtLogin {
enabled: state.map(|state| matches!(state, Toggle::On)),
},
output,
),
ControlCli::Vocabulary { command } => match command {
VocabularyCommand::List { output } => send(ControlCommand::VocabularyList, output),
VocabularyCommand::Add {
term,
sounds_like,
output,
} => send(
ControlCommand::VocabularyAdd {
term,
sounds_like: sounds_like.into_iter().collect(),
},
output,
),
VocabularyCommand::Remove { term, output } => {
send(ControlCommand::VocabularyRemove { term }, output)
}
},
ControlCli::Logs {
process,
lines,
follow,
} => logs(process, lines, follow),
ControlCli::History(crate::transcript_cli::HistoryArgs {
action: Some(crate::transcript_cli::HistoryAction::Clear { yes, output }),
..
}) => clear_history(yes, output),
ControlCli::History(args) => report(crate::transcript_cli::history(&args)),
ControlCli::Meetings { command } => meetings(command),
ControlCli::Mcp { meetings_dir } => report(mcp(meetings_dir)),
ControlCli::Commands { command } => report(match command {
CommandsCommand::Init => crate::personal_commands::initialize_workspace()
.map(|workspace| println!("{}", workspace.display())),
CommandsCommand::Check => {
crate::personal_commands::check_workspace().map(|report| println!("{report}"))
}
}),
ControlCli::Labs { command } => report(crate::labs::run(command.as_ref())),
ControlCli::Experiments { .. } => report(crate::labs::run_retired_experiments()),
ControlCli::Annotate { command } => capture(command),
}
}
/// `hex model install`: the running Hex downloads in the background;
/// without one, Linux and Windows download here.
fn install_model(model: Option<String>, language: Option<String>, output: Output) -> u8 {
let model = match model {
Some(model) => model,
None => match crate::app_settings::AppSettings::load() {
Ok(settings) => settings.transcription.model.as_str().to_owned(),
Err(error) => return fail(&format!("couldn't read settings: {error:#}")),
},
};
#[cfg(not(target_os = "macos"))]
if !running() {
return report(selection(Some(model), language).and_then(|selection| {
crate::local_transcriber::install(
&selection,
&std::sync::atomic::AtomicBool::new(false),
)
}));
}
send(ControlCommand::ModelInstall { model, language }, output)
}
/// The selection a local model command names: `model` with its remembered
/// language unless `language` is given, or the selected model.
#[cfg(not(target_os = "macos"))]
fn selection(
model: Option<String>,
language: Option<String>,
) -> color_eyre::Result<crate::transcription_models::TranscriptionSelection> {
let settings = crate::app_settings::AppSettings::load().unwrap_or_default();
let model = model.unwrap_or_else(|| settings.transcription.model.as_str().to_owned());
super::model_selection(&settings, &model, language.as_deref())
.map_err(|error| color_eyre::eyre::eyre!(error.message))
}
/// `hex model status|devices|check|transcribe`, run in this process.
#[cfg(not(target_os = "macos"))]
fn offline_model(command: ModelCommand) -> u8 {
use crate::transcription_models::{definition, is_installed, is_verified, model_path};
report((|| match command {
ModelCommand::Status { model, language } => {
let selection = selection(model, language)?;
let model = definition(selection.model);
let installed = is_installed(model, &selection.language);
println!(
"{}\t{}\t{}\t{}",
if installed { "installed" } else { "missing" },
if installed && is_verified(model) {
"verified"
} else {
"unverified"
},
model.name,
model_path(model)?.display()
);
Ok(())
}
ModelCommand::Devices => {
for device in crate::local_transcriber::devices()? {
println!("{device}");
}
Ok(())
}
ModelCommand::Check { model, language } => {
let transcriber =
crate::local_transcriber::LocalTranscriber::load(&selection(model, language)?)?;
println!("ready\t{}", transcriber.device_label());
Ok(())
}
ModelCommand::Transcribe {
wav,
model,
language,
} => {
println!(
"{}",
crate::local_transcriber::transcribe_wav_with_selection(
&wav,
&selection(model, language)?
)?
);
Ok(())
}
_ => unreachable!("Hex carries out the other model commands"),
})())
}
/// macOS runs models only inside the app.
#[cfg(target_os = "macos")]
fn offline_model(_: ModelCommand) -> u8 {
print(
ControlReply::error(
"unsupported",
"this `hex model` command is for Linux and Windows; use `hex model list`",
),
Output::default(),
)
}
/// The exit code of a command that runs here rather than in Hex.
fn report(result: color_eyre::Result<()>) -> u8 {
match result {
Ok(()) => 0,
Err(error) => fail(&format!("{error:#}")),
}
}
/// `hex meetings`: record, stop, and copy in the running Hex; the rest
/// read the meetings folder here.
fn meetings(command: crate::transcript_cli::MeetingsCommand) -> u8 {
use crate::transcript_cli::MeetingsCommand;
match command {
MeetingsCommand::Record { title, output } => {
send(ControlCommand::MeetingRecord { title }, output)
}
MeetingsCommand::Stop { output } => send(ControlCommand::MeetingStop, output),
MeetingsCommand::CopyLast { output } => send(ControlCommand::MeetingCopyLast, output),
command => report(crate::transcript_cli::meetings(&command)),
}
}
/// `hex mcp`: logs to stderr only (stdout carries MCP messages) and touches
/// no app state.
fn mcp(meetings_dir: Option<std::path::PathBuf>) -> color_eyre::Result<()> {
tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_ansi(false)
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_env("HEX_MCP_LOG")
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn")),
)
.init();
let root = match meetings_dir {
Some(directory) => directory,
None => crate::meeting::root()?,
};
crate::meeting_mcp::run(root)
}
/// `hex annotate` (alias `hex capture`).
#[derive(Subcommand, Debug)]
pub enum CaptureCommand {
/// Start recording a capture.
Start {
#[command(flatten)]
output: Output,
},
/// End the capture and write it in the background.
Stop {
#[command(flatten)]
output: Output,
},
/// End the capture and discard it.
Cancel {
#[command(flatten)]
output: Output,
},
/// What records, what is being written, and the last capture.
Status {
#[command(flatten)]
output: Output,
},
/// The newest captures, newest first.
List {
/// How many to show (20 unless given).
#[arg(long)]
limit: Option<usize>,
#[command(flatten)]
output: Output,
},
/// One capture's words, files, and where it went.
Show {
/// A bundle name, path, or `latest`.
capture: String,
#[command(flatten)]
output: Output,
},
/// Send a capture to an OpenCode session.
Send {
/// A bundle name, path, or `latest`.
capture: String,
/// A session ID, or for the newest capture a session its route
/// lists by name. Without it, where its route or last send says.
#[arg(long)]
to: Option<String>,
/// Also save a rule that always sends this capture's site or app
/// there (the newest routed capture only).
#[arg(long)]
always: bool,
#[command(flatten)]
output: Output,
},
/// Turn the pen on or off while a recording runs (as the capsule's pen),
/// or start one that draws. Bind it in your desktop's keyboard shortcuts
/// when it has no shortcuts portal.
#[cfg(target_os = "linux")]
Draw {
#[command(flatten)]
output: Output,
},
/// Take back the newest send while it can be undone (as the capsule's
/// Undo).
Undo {
#[command(flatten)]
output: Output,
},
/// What routing sees for a capture and what it decides (Scrawl's
/// `route --explain`). Sends nothing.
Route {
/// A bundle name, path, or `latest`.
capture: String,
/// Accepted for Scrawl's spelling; `route` only ever explains.
#[arg(long, hide = true)]
explain: bool,
/// Ask Jev again now (one call).
#[arg(long)]
ask_jev: bool,
#[command(flatten)]
output: Output,
},
}
/// Runs `hex capture`: on macOS through the running Hex; on Linux the
/// folder reads (`list`, `show`, `route`, `send`) run here, and the
/// recording commands go to the running Hex's listener; on Windows every
/// command goes to the running Hex. A build without the capture engine
/// answers `unsupported`.
pub fn capture(command: CaptureCommand) -> u8 {
use crate::control::{ControlCommand as C, ScrawlCaptureAction as A};
let (command, output) = match command {
CaptureCommand::Start { output } => (C::ScrawlCapture { action: A::Start }, output),
CaptureCommand::Stop { output } => (C::ScrawlCapture { action: A::Stop }, output),
CaptureCommand::Cancel { output } => (C::ScrawlCapture { action: A::Cancel }, output),
CaptureCommand::Status { output } => (C::ScrawlCapture { action: A::Status }, output),
CaptureCommand::List { limit, output } => (C::ScrawlCaptureList { limit }, output),
CaptureCommand::Show { capture, output } => (C::ScrawlCaptureShow { capture }, output),
CaptureCommand::Send {
capture,
to,
always,
output,
} => (
C::ScrawlCaptureSend {
capture,
to,
always,
},
output,
),
CaptureCommand::Route {
capture,
explain: _,
ask_jev,
output,
} => (C::ScrawlCaptureRoute { capture, ask_jev }, output),
CaptureCommand::Undo { output } => (C::ScrawlCaptureUndo, output),
#[cfg(target_os = "linux")]
CaptureCommand::Draw { output } => {
return print(crate::linux_service::capture_draw(), output);
}
};
#[cfg(not(hex_capture))]
{
let _ = command;
print(
ControlReply::error("unsupported", "Annotate isn't available on this OS yet"),
output,
)
}
#[cfg(all(hex_capture, any(target_os = "macos", target_os = "windows")))]
return send(command, output);
#[cfg(all(hex_capture, target_os = "linux"))]
{
let reply = match command {
C::ScrawlCaptureList { limit } => crate::capture_host::list_captures(limit),
C::ScrawlCaptureShow { capture } => crate::capture_host::show_capture(&capture),
// The running Hex's router sends, so its Undo can take it back.
C::ScrawlCaptureSend {
capture,
to,
always,
} => Ok(crate::linux_service::capture_send(capture, to, always)),
C::ScrawlCaptureUndo => Ok(crate::linux_service::capture_undo()),
C::ScrawlCaptureRoute { capture, ask_jev } => {
crate::capture_host::explain_capture(&capture, ask_jev)
}
C::ScrawlCapture { action } => Ok(crate::linux_service::capture(action)),
_ => unreachable!("only capture commands"),
};
print(reply.unwrap_or_else(ControlReply::from), output)
}
}
pub fn settings(command: SettingsCommand) -> u8 {
match command {
SettingsCommand::List { output } => send(ControlCommand::SettingsGet { key: None }, output),
SettingsCommand::Get { key, output } => {
send(ControlCommand::SettingsGet { key: Some(key) }, output)
}
SettingsCommand::Set { key, value, output } => {
send(ControlCommand::SettingsSet { key, value }, output)
}
SettingsCommand::Apply { file, output } => apply_settings(&file, output),
}
}
/// `hex settings apply`: the running Hex saves and adopts the settings, so
/// it never overwrites them from memory; with no Hex running they are
/// written to settings.json here.
fn apply_settings(file: &std::path::Path, output: Output) -> u8 {
use std::io::Read;
let mut text = String::new();
let read = if file == std::path::Path::new("-") {
std::io::stdin().read_to_string(&mut text).map(drop)
} else {
std::fs::read_to_string(file).map(|read| text = read)
};
if let Err(error) = read {
return fail(&format!("couldn't read {}: {error}", file.display()));
}
let values: serde_json::Map<String, serde_json::Value> = match serde_json::from_str(&text) {
Ok(values) => values,
Err(error) => return fail(&format!("expected a JSON object of settings: {error}")),
};
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(35);
loop {
if running() {
return send(ControlCommand::SettingsApply { values }, output);
}
// A Hex that holds the service lock may have read settings.json
// already; wait for it to answer instead of writing behind it.
#[cfg(target_os = "linux")]
let lock = crate::instance::acquire("service");
#[cfg(not(target_os = "linux"))]
let lock: color_eyre::Result<()> = Ok(());
match lock {
Ok(_lock) if !running() => return print(apply_offline(&values), output),
Ok(_) => {}
Err(_) if std::time::Instant::now() >= deadline => {
return print(
ControlReply::error(
"busy",
"Hex is starting but didn't answer; run `hex settings apply` again",
),
output,
);
}
Err(_) => std::thread::sleep(std::time::Duration::from_millis(100)),
}
}
}
fn apply_offline(values: &serde_json::Map<String, serde_json::Value>) -> ControlReply {
let result = crate::app_settings::AppSettings::load()
.map_err(|error| {
super::ControlError::new("internal", format!("couldn't read settings: {error:#}"))
})
.and_then(|before| {
let change =
super::settings::apply_all(&before, values, &crate::rune_ui::shortcut_rules())?;
if !change.changed(&before) {
return Ok(ControlReply::unchanged(
"Every setting already has its value",
));
}
change.settings.save().map_err(|error| {
super::ControlError::new("internal", format!("couldn't save: {error:#}"))
})?;
Ok(ControlReply::done(change.message))
});
result.unwrap_or_else(ControlReply::from)
}
/// `hex history clear`; the confirmation is asked here, before Hex is.
pub fn clear_history(confirm: bool, output: Output) -> u8 {
if !confirm {
return print(
ControlReply::error(
"confirmation-required",
"this deletes every retained dictation; pass --yes to clear history",
),
output,
);
}
send(ControlCommand::HistoryClear, output)
}
pub fn send(command: ControlCommand, output: Output) -> u8 {
match call(ControlRequest::new(command)) {
Ok(response) => print(response.reply, output),
Err(reply) => print(reply, output),
}
}
/// Every OS reaches the running Hex through its local API's owner-only
/// discovery file and bearer-authenticated `POST /control`.
fn running() -> bool {
crate::local_api::running_pid().is_some()
}
/// `hex settings set key value` in the running Hex, which saves and applies
/// it; `None` when no Hex runs.
pub(crate) fn set_in_running_hex(key: &str, value: &str) -> Option<ControlReply> {
running().then(|| {
call(ControlRequest::new(ControlCommand::SettingsSet {
key: key.into(),
value: value.into(),
}))
.map_or_else(|reply| reply, |response| response.reply)
})
}
fn call(request: ControlRequest) -> Result<ControlResponse, ControlReply> {
if !running() {
return Err(not_running());
}
crate::local_api::call_control(&request)
.map_err(|error| ControlReply::error("transport", format!("{error:#}")))
}
pub(crate) fn not_running() -> ControlReply {
ControlReply::error("not-running", "Hex is not running; run `hex start`")
}
#[cfg(target_os = "macos")]
fn start(output: Output) -> u8 {
use std::time::{Duration, Instant};
if let Some(pid) = crate::local_api::running_pid() {
return print(
ControlReply::unchanged(format!("Hex is already running (pid {pid})")),
output,
);
}
let arguments = open_arguments(
installed_bundle().as_deref(),
crate::app_paths::is_macos_test_build(),
std::env::vars_os(),
);
match std::process::Command::new("/usr/bin/open")
.args(arguments)
.status()
{
Ok(status) if status.success() => {}
Ok(_) | Err(_) => {
return print(
ControlReply::error("failed", "couldn't open Hex.app; is it installed?"),
output,
);
}
}
let started = Instant::now();
while started.elapsed() < Duration::from_secs(20) {
if let Some(pid) = crate::local_api::running_pid() {
return print(
ControlReply::done(format!("Started Hex (pid {pid})")),
output,
);
}
std::thread::sleep(Duration::from_millis(200));
}
print(
ControlReply::done("Opened Hex; it isn't answering yet (setup may be waiting)"),
output,
)
}
/// `hex start` on Linux and Windows: a detached `hex app --hidden`, which
/// forwards to the running Hex, starts its systemd unit, or becomes Hex,
/// then waits until it answers.
#[cfg(not(target_os = "macos"))]
fn start(output: Output) -> u8 {
print(start_reply(), output)
}
#[cfg(not(target_os = "macos"))]
fn start_reply() -> ControlReply {
use std::time::{Duration, Instant};
if running() {
return ControlReply::unchanged("Hex is already running");
}
let executable = match std::env::current_exe() {
Ok(executable) => executable,
Err(error) => return ControlReply::error("failed", format!("couldn't find hex: {error}")),
};
let mut command = std::process::Command::new(executable);
command
.args(["app", "--hidden"])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
#[cfg(target_os = "linux")]
std::os::unix::process::CommandExt::process_group(&mut command, 0);
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
// DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console, and
// Ctrl-C in this terminal doesn't reach it.
command.creation_flags(0x0000_0008 | 0x0000_0200);
}
if let Err(error) = command.spawn() {
return ControlReply::error("failed", format!("couldn't start Hex: {error}"));
}
let started = Instant::now();
while started.elapsed() < Duration::from_secs(20) {
if running() {
return ControlReply::done("Started Hex");
}
std::thread::sleep(Duration::from_millis(200));
}