Repository navigation
Expand file tree
/
Copy pathsettings.rs
More file actions
1414 lines (1351 loc) · 49.3 KB
/
Copy pathsettings.rs
File metadata and controls
1414 lines (1351 loc) · 49.3 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 General pane: listener status, the Dictation, Output, and Application
//! cards with the shortcuts in their place, Advanced options behind a
//! disclosure, and recording shortcuts through the host.
use std::time::{Duration, Instant};
use rune::{Edge, El, Key, KeyEvent, Transition, Tx, col, row, spacer, text};
use super::controls::{
ButtonKind, Choice, DESCRIPTION, KEY_GAP, KeySize, METRICS, Paint, button, fixed_select,
keycap, note, pulsing_dot, section, select, setting_row, status_dot,
};
use super::host;
use super::{Menu, Request, Service, ShortcutTarget, Ui};
use crate::app_settings::{
AppSettings, HotkeyBinding, HotkeyKey, HotkeyModifiers, KeyboardModelChoice, ModifierSide,
};
use crate::desktop::host::{
DesktopAction, DesktopGrantedShortcut, DesktopShortcut, DesktopShortcuts, DesktopUpdateStatus,
};
use crate::desktop::i18n::{tr, tr_fill};
use crate::dictation::ShortcutMode;
use crate::transcription::keyboard_model_switching::InputSource;
use crate::transcription::models::{self as transcription_models, ModelPreparationStage};
static CHECK: &rune::Icon = &rune_theme_opencode::icons::CHECK_SMALL;
pub(super) const SOUND_VOLUME_STEPS: [(&str, f32); 5] = [
("Off", 0.0),
("25%", 0.25),
("50%", 0.5),
("75%", 0.75),
("100%", 1.0),
];
/// How long a newly saved shortcut shows "Saved".
const SAVED_FOR: Duration = Duration::from_secs(1);
/// How long to wait for the service to start a requested shortcut edit.
const EDIT_START_TIMEOUT: Duration = Duration::from_secs(3);
#[derive(Clone, Copy, PartialEq, Debug)]
pub(super) enum Capture {
Idle,
/// Waiting for the chord; `message` explains a rejected one, and `held`
/// shows the modifiers releasing them would record.
Listening {
target: ShortcutTarget,
message: Option<&'static str>,
held: HotkeyModifiers,
},
/// Sent to the service, which validates, registers, and saves it.
Saving {
target: ShortcutTarget,
since: Instant,
seen_edit: bool,
},
/// `until` is on the poll clock, set by the first poll that sees it.
Saved {
target: ShortcutTarget,
until: Option<f64>,
},
}
/// A chord the host recorded outside the window's key events (Windows
/// polls the keyboard, since modifier-only chords never reach the window).
#[cfg_attr(target_os = "linux", allow(dead_code))]
pub(super) enum Chord {
/// The modifiers held so far, shown while the chord is in progress.
Held(HotkeyModifiers),
Captured(Result<HotkeyBinding, &'static str>),
Cancelled,
}
/// Follows the host's side of a shortcut edit.
pub(super) fn advance_capture(ui: &mut Ui, clock: f64, tx: &mut Tx) -> bool {
let mut changed = false;
loop {
let chord = match &mut ui.service {
Service::Live(backend) => backend.take_chord(),
_ => None,
};
let (Some(chord), Capture::Listening { target, .. }) = (chord, ui.capture) else {
break;
};
match chord {
Chord::Held(modifiers) => {
hold(ui, modifiers);
changed = true;
}
Chord::Captured(binding) => {
record(ui, target, binding);
return true;
}
Chord::Cancelled => {
cancel_capture(ui);
return true;
}
}
}
if changed {
return true;
}
let editing = ui.view.as_ref().is_some_and(|view| view.editing);
match ui.capture {
Capture::Saving {
target,
since,
seen_edit,
} => {
let finished = if seen_edit {
!editing
} else if editing {
ui.capture = Capture::Saving {
target,
since,
seen_edit: true,
};
return false;
} else {
since.elapsed() >= EDIT_START_TIMEOUT
};
if finished {
ui.capture = Capture::Saved {
target,
until: None,
};
}
finished
}
Capture::Saved {
target,
until: None,
} => {
ui.capture = Capture::Saved {
target,
until: Some(clock + SAVED_FOR.as_secs_f64()),
};
tx.wake_after(SAVED_FOR);
false
}
Capture::Saved {
until: Some(until), ..
} if clock >= until => {
ui.capture = Capture::Idle;
true
}
_ => false,
}
}
/// Records a shortcut while capture listens; otherwise leaves keys alone.
/// Where the host records chords itself, the window only takes Escape and
/// keeps every other key out of the page.
pub(super) fn on_key(ui: &mut Ui, event: &KeyEvent, _: &mut Tx) -> bool {
let Capture::Listening { target, .. } = ui.capture else {
return false;
};
if event.key == Key::Escape {
cancel_capture(ui);
return true;
}
if host::RECORDS_KEY_EVENTS {
match event.key {
Key::Modifier { modifier, pressed } => {
modifier_alone(ui, modifier, pressed, event.mods)
}
_ => record(ui, target, recorded_binding(event)),
}
}
true
}
/// Where the window records key events (Linux), a modifier pressed on its
/// own shows among the held keys, and releasing them all without a key
/// says why Linux can't bind that and what it can: a key with them. The
/// GlobalShortcuts portal and X11 grabs take a key plus modifiers, never a
/// modifier alone or one side of it.
fn modifier_alone(ui: &mut Ui, modifier: rune::Modifier, pressed: bool, mods: rune::Mods) {
let Capture::Listening { message, held, .. } = &mut ui.capture else {
return;
};
if pressed {
use rune::Modifier as M;
let slot = match modifier {
M::ControlLeft | M::ControlRight => &mut held.control,
M::AltLeft | M::AltRight => &mut held.option,
M::ShiftLeft | M::ShiftRight => &mut held.shift,
M::SuperLeft | M::SuperRight => &mut held.command,
_ => return,
};
let side = match modifier.side() {
Some(rune::KeySide::Left) => ModifierSide::Left,
Some(rune::KeySide::Right) => ModifierSide::Right,
None => ModifierSide::Either,
};
*slot = Some(match (*slot, side) {
(Some(ModifierSide::Left), ModifierSide::Right)
| (Some(ModifierSide::Right), ModifierSide::Left) => ModifierSide::Both,
(Some(current), _) => current,
(None, side) => side,
});
*message = None;
return;
}
if mods.ctrl || mods.alt || mods.shift || mods.logo {
return;
}
let peak = std::mem::take(held);
if !peak.is_empty() {
*message = Some(modifier_only_hint(peak));
}
}
/// The nearest chord Linux binds to modifiers held alone: the same
/// modifiers, one side or either, with a key.
pub(super) fn modifier_only_hint(peak: HotkeyModifiers) -> &'static str {
let both =
[peak.control, peak.option, peak.shift, peak.command].contains(&Some(ModifierSide::Both));
if both {
tr("Linux can't bind both sides. Use one with a key, like Space")
} else {
tr("Linux needs a key too. Hold these and press one, like Space")
}
}
/// Saves a recorded chord, or keeps listening with why it was rejected.
fn record(ui: &mut Ui, target: ShortcutTarget, binding: Result<HotkeyBinding, &'static str>) {
let message = match binding.and_then(|binding| {
validate(&ui.settings, target, &binding)?;
Ok(binding)
}) {
Ok(binding) if host::HOST_SAVES_SHORTCUTS => {
ui.send(Request::SetShortcut {
target,
shortcut: desktop_shortcut(&binding),
});
if matches!(ui.service, Service::Fixture(_)) {
set_binding(&mut ui.settings, target, binding);
}
ui.capture = Capture::Saving {
target,
since: Instant::now(),
seen_edit: false,
};
return;
}
Ok(binding) => {
// The window saves the binding; the host restarts its listener
// with it.
cancel_capture(ui);
if ui.update(|settings| set_binding(settings, target, binding)) {
ui.capture = Capture::Saved {
target,
until: None,
};
}
return;
}
Err(message) => message,
};
ui.capture = Capture::Listening {
target,
message: Some(message),
held: HotkeyModifiers::default(),
};
}
/// Shows the modifiers held so far; pressing any clears a rejection.
pub(super) fn hold(ui: &mut Ui, modifiers: HotkeyModifiers) {
if let Capture::Listening { message, held, .. } = &mut ui.capture {
if !modifiers.is_empty() {
*message = None;
}
*held = modifiers;
}
}
pub(super) fn begin_capture(ui: &mut Ui, target: ShortcutTarget) {
if let Capture::Listening { target: active, .. } = ui.capture {
cancel_capture(ui);
if active == target {
return;
}
}
ui.send(Request::CaptureShortcutFor(target));
ui.capture = Capture::Listening {
target,
message: None,
held: HotkeyModifiers::default(),
};
}
pub(super) fn cancel_capture(ui: &mut Ui) {
if matches!(ui.capture, Capture::Listening { .. }) {
ui.send(Request::CancelShortcut);
}
ui.capture = Capture::Idle;
}
/// The chord a key press records, in the key names Linux registers.
pub(super) fn recorded_binding(event: &KeyEvent) -> Result<HotkeyBinding, &'static str> {
let name = match &event.key {
Key::Text(text) if text == " " => "space".to_string(),
Key::Text(text) if text.chars().count() == 1 => text.to_lowercase(),
Key::Command(letter) => letter.to_string(),
Key::Function(number) => format!("f{number}"),
Key::Enter => "enter".into(),
Key::Tab => "tab".into(),
Key::Backspace => "backspace".into(),
Key::Delete => "delete".into(),
Key::Left => "left".into(),
Key::Right => "right".into(),
Key::Up => "up".into(),
Key::Down => "down".into(),
Key::Home => "home".into(),
Key::End => "end".into(),
_ => return Err(tr("Unsupported key")),
};
let held = |down: bool| down.then_some(ModifierSide::Either);
let modifiers = HotkeyModifiers {
control: held(event.mods.ctrl),
option: held(event.mods.alt),
shift: held(event.mods.shift),
command: held(event.mods.logo),
function: false,
};
// The § key alone is checked against Labs › Section key alone in
// `validate` (Linux).
let lone_section = cfg!(target_os = "linux") && HotkeyKey::section_name(&name);
if modifiers.is_empty() && !matches!(event.key, Key::Function(_)) && !lone_section {
return Err(tr("Add a modifier"));
}
Ok(HotkeyBinding {
modifiers,
key: Some(HotkeyKey::named(&name)),
})
}
pub(super) fn validate(
settings: &AppSettings,
target: ShortcutTarget,
binding: &HotkeyBinding,
) -> Result<(), &'static str> {
// A bare left click would swallow every click, this window's included.
if binding.is_bare_primary_click() {
return Err(tr("Add a modifier"));
}
// Menu, Pause, and Scroll Lock need Labs › Special keys alone (Linux).
if cfg!(target_os = "linux")
&& binding.key.as_ref().is_some_and(HotkeyKey::is_special)
&& !settings.special_keys_allowed()
{
return Err(if binding.modifiers.is_empty() {
tr("Add a modifier")
} else {
tr("Unsupported key")
});
}
// The § key alone needs Labs › Section key alone (Linux).
if cfg!(target_os = "linux") && binding.is_lone_section_key() && !settings.section_key_allowed()
{
return Err(tr("Add a modifier"));
}
// A navigation key alone needs Labs › Special keys alone (Windows).
if cfg!(target_os = "windows")
&& binding.is_lone_navigation_key()
&& !settings.special_keys_allowed()
{
return Err(tr("Add a modifier"));
}
host::validate_hotkey(target, binding)?;
if conflicts(settings, target, binding) {
return Err(tr("Already in use"));
}
Ok(())
}
/// Whether `binding` overlaps a shortcut `target` must not share: the other
/// active shortcuts and, where meetings exist (macOS), meeting paste.
pub(super) fn conflicts(
settings: &AppSettings,
target: ShortcutTarget,
binding: &HotkeyBinding,
) -> bool {
use crate::app_settings::HotkeySlot;
let slot = match target {
ShortcutTarget::Dictation => HotkeySlot::Dictation,
ShortcutTarget::PasteLast => HotkeySlot::PasteLast,
ShortcutTarget::RawDictation => HotkeySlot::RawDictation,
ShortcutTarget::Cancel => HotkeySlot::Cancel,
#[cfg(hex_capture)]
ShortcutTarget::Capture => HotkeySlot::Capture,
#[cfg(target_os = "macos")]
ShortcutTarget::SecondDictation => HotkeySlot::SecondDictation,
};
settings.hotkey_in_use(slot, binding)
}
pub(super) fn desktop_shortcut(binding: &HotkeyBinding) -> DesktopShortcut {
let modifiers = binding.modifiers;
DesktopShortcut {
alt: modifiers.option.is_some(),
control: modifiers.control.is_some(),
function: false,
key: binding
.key
.as_ref()
.map(HotkeyKey::name)
.unwrap_or_default(),
platform: modifiers.command.is_some(),
shift: modifiers.shift.is_some(),
}
}
pub(super) fn binding(settings: &AppSettings, target: ShortcutTarget) -> Option<&HotkeyBinding> {
match target {
ShortcutTarget::Dictation => Some(&settings.dictation_hotkey),
ShortcutTarget::PasteLast => settings.paste_last_hotkey.as_ref(),
ShortcutTarget::RawDictation => settings.raw_dictation_hotkey.as_ref(),
ShortcutTarget::Cancel => Some(&settings.cancel_hotkey),
#[cfg(hex_capture)]
ShortcutTarget::Capture => Some(&settings.capture.hotkey),
#[cfg(target_os = "macos")]
ShortcutTarget::SecondDictation => settings.second_dictation_hotkey.as_ref(),
}
}
pub(super) fn set_binding(
settings: &mut AppSettings,
target: ShortcutTarget,
binding: HotkeyBinding,
) {
match target {
ShortcutTarget::Dictation => settings.dictation_hotkey = binding,
ShortcutTarget::PasteLast => settings.paste_last_hotkey = Some(binding),
ShortcutTarget::RawDictation => settings.raw_dictation_hotkey = Some(binding),
ShortcutTarget::Cancel => settings.cancel_hotkey = binding,
#[cfg(hex_capture)]
ShortcutTarget::Capture => settings.capture.hotkey = binding,
#[cfg(target_os = "macos")]
ShortcutTarget::SecondDictation => settings.second_dictation_hotkey = Some(binding),
}
}
/// Labs › Restore shortcut default: puts `default` back as `target`'s
/// shortcut under the rules a recorded one meets. A default another
/// shortcut already uses changes nothing and opens the recorder with the
/// usual conflict, so another can be recorded.
pub(super) fn restore_default(ui: &mut Ui, target: ShortcutTarget, default: HotkeyBinding) {
match validate(&ui.settings, target, &default) {
Ok(()) => {
cancel_capture(ui);
ui.update(|settings| set_binding(settings, target, default.clone()));
}
Err(message) => {
if !matches!(ui.capture, Capture::Listening { target: active, .. } if active == target)
{
begin_capture(ui, target);
}
if let Capture::Listening { message: shown, .. } = &mut ui.capture {
*shown = Some(message);
}
}
}
}
pub(super) fn sound_volume_index(settings: &AppSettings) -> usize {
if !settings.sound_effects {
return 0;
}
SOUND_VOLUME_STEPS[1..]
.iter()
.enumerate()
.min_by(|(_, (_, left)), (_, (_, right))| {
(settings.sound_effect_volume - left)
.abs()
.total_cmp(&(settings.sound_effect_volume - right).abs())
})
.map_or(0, |(index, _)| index + 1)
}
pub(super) fn toggle_menu(ui: &mut Ui, menu: Menu) {
ui.open = (ui.open != Some(menu)).then_some(menu);
if matches!(ui.open, Some(Menu::Microphone)) {
refresh_microphones(ui);
}
}
/// Lists the microphones again, and what System default resolves to, on a
/// worker thread; [`poll_microphones`] adopts the result. A change during a
/// listing in flight is listed again after it.
pub(super) fn refresh_microphones(ui: &mut Ui) {
if matches!(ui.service, Service::Fixture(_)) || ui.microphones_listing.is_some() {
return;
}
ui.microphones_route = Some(crate::audio::input_route_generation());
let (sender, receiver) = std::sync::mpsc::sync_channel(1);
let spawned = std::thread::Builder::new()
.name("hex-microphones".into())
.spawn(move || {
let _ = sender.send(crate::audio::input_devices().map_err(|error| error.to_string()));
});
match spawned {
Ok(_) => ui.microphones_listing = Some(receiver),
Err(error) => ui.microphones = Err(error.to_string()),
}
}
/// Adopts a finished listing. Returns whether the microphones changed.
pub(super) fn poll_microphones(ui: &mut Ui) -> bool {
let Some(listing) = &ui.microphones_listing else {
return false;
};
let listed = match listing.try_recv() {
Ok(listed) => listed,
Err(std::sync::mpsc::TryRecvError::Empty) => return false,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Err("the microphone list stopped".to_owned())
}
};
ui.microphones_listing = None;
let changed = ui.microphones != listed;
ui.microphones = listed;
changed
}
/// A saved microphone the input list no longer names. Only a list that
/// names inputs can tell.
pub(super) fn missing_microphone(ui: &Ui) -> Option<&str> {
let listed = ui.microphones.as_ref().ok();
ui.settings.microphone.as_deref().filter(|saved| {
listed.is_some_and(|devices| {
!devices.names.is_empty() && !devices.names.iter().any(|name| name == saved)
})
})
}
/// The microphone menu's choices, shared by General and the tour: System
/// default with the input it resolves to, every listed input, and a saved
/// one that is missing. Choosing saves through `Ui::update`.
pub(super) fn microphone_choices(ui: &Ui) -> Vec<Choice> {
let settings = &ui.settings;
let listed = ui.microphones.as_ref().ok();
let off = listed.and_then(|devices| devices.off_with_lid_closed.as_deref());
let mut devices = vec![Choice {
label: tr("System default").to_owned(),
detail: listed.and_then(|devices| devices.system_default.clone()),
selected: settings.microphone.is_none(),
choose: Box::new(|ui: &mut Ui| {
ui.open = None;
ui.update(|settings| settings.microphone = None);
}),
}];
if let Some(listed) = listed {
devices.extend(listed.names.iter().map(|device| {
let name = device.clone();
Choice {
label: device.clone(),
detail: (off == Some(device.as_str()))
.then(|| tr("off while the lid is closed").to_owned()),
selected: settings.microphone.as_deref() == Some(device),
choose: Box::new(move |ui: &mut Ui| {
ui.open = None;
let name = name.clone();
ui.update(|settings| settings.microphone = Some(name));
}),
}
}));
}
if let Some(saved) = missing_microphone(ui) {
devices.push(Choice {
label: saved.to_owned(),
detail: Some(tr("not connected").to_owned()),
selected: true,
choose: Box::new(|ui: &mut Ui| ui.open = None),
});
}
devices
}
pub(super) fn error_notes(p: Paint, error: &str) -> [El; 2] {
[
note(
"error-title",
tr("Hex could not apply this change."),
p.danger(),
),
note("error", error, p.muted()),
]
}
pub(super) fn listener_card(ui: &Ui, p: Paint) -> El {
let running = ui.running();
let status = match &ui.view {
Some(view) => tr(&view.listener.status).to_string(),
None if matches!(ui.service, Service::Fixture(_)) || ui.connection_error.is_some() => {
tr("Service disconnected").to_string()
}
None => tr("Connecting…").to_string(),
};
// The key the desktop granted, which it may have changed in its own
// settings (#723), else the one Hex records.
let shortcut = match portal_grant(ui, ShortcutTarget::Dictation) {
Some(DesktopGrantedShortcut {
trigger: Some(trigger),
..
}) => trigger.clone(),
_ => ui.settings.dictation_hotkey.keycaps().join("+"),
};
let no_model = super::general::missing_model(ui).is_some();
let hint = match (running, ui.settings.shortcut_mode) {
_ if no_model => tr("Hex can't dictate until a speech model is installed").to_string(),
_ if !ui.records_shortcuts() => {
tr("Ready anywhere · Use your desktop's shortcuts to dictate").to_string()
}
(true, ShortcutMode::Toggle) => tr_fill(
"Ready anywhere · Press {} to start and stop dictating",
&shortcut,
),
(true, ShortcutMode::Hold) => tr_fill("Ready anywhere · Hold {} to dictate", &shortcut),
(false, _) => tr_fill("Enable Hex to dictate into any app with {}", &shortcut),
};
let failure = ui
.view
.as_ref()
.and_then(|view| view.listener.warning.clone())
.map(|failure| tr_fill("Last dictation failed: {}", &failure));
let error = ui
.error
.clone()
.or_else(|| ui.connection_error.clone())
.or_else(|| {
ui.view
.as_ref()
.and_then(|view| view.operation_error.clone())
});
let action = if running {
button(
p,
"toggle-listening",
tr("Disable"),
ButtonKind::Secondary,
|ui: &mut Ui, _| ui.send(Request::Desktop(DesktopAction::StopListening)),
)
} else {
button(
p,
"toggle-listening",
tr("Enable"),
ButtonKind::Primary,
|ui: &mut Ui, _| ui.send(Request::Desktop(DesktopAction::StartListening)),
)
};
let summary = row()
.key("listener")
.min_h(METRICS.row_h_described)
.px(METRICS.row_px)
.py(8.0)
.gap(12.0)
.center_y()
.child(status_dot(if running && !no_model {
p.success()
} else {
p.muted()
}))
.child(
col()
.key("copy")
.grow(1.0)
.shrink()
.gap(2.0)
.child(
text(status)
.key("status")
.font(p.k.ty.ui_medium)
.color(p.text()),
)
.child(
text(hint)
.key("hint")
.font(DESCRIPTION)
.color(if no_model { p.danger() } else { p.muted() })
.wrap(),
)
.children(failure.map(|failure| {
text(failure)
.key("failure")
.font(DESCRIPTION)
.color(p.danger())
.wrap()
})),
)
.child(action);
let mut rows = vec![summary];
if let Some(error) = error {
rows.extend(error_notes(p, &error));
}
section(p, "listening", tr("Status"), rows)
}
/// What a shortcuts portal granted for `target`, since the desktop decides
/// which trigger Hex actually gets.
pub(super) fn granted(ui: &Ui, p: Paint, target: ShortcutTarget) -> Option<(String, rune::Color)> {
Some(match portal_grant(ui, target)? {
DesktopGrantedShortcut {
trigger: Some(trigger),
..
} => (tr_fill("Your desktop granted {}", trigger), p.muted()),
DesktopGrantedShortcut {
trigger: None,
unconfirmed: true,
..
} => (
tr("Your desktop assigns this key itself, so Hex can't confirm it").to_string(),
p.muted(),
),
DesktopGrantedShortcut { trigger: None, .. } => (
tr("Your desktop did not grant this shortcut").to_string(),
p.danger(),
),
})
}
fn portal_grant(ui: &Ui, target: ShortcutTarget) -> Option<&DesktopGrantedShortcut> {
let Some(DesktopShortcuts::Portal(granted)) = ui.shortcuts() else {
return None;
};
let name = match target {
ShortcutTarget::Dictation => "Dictation",
ShortcutTarget::PasteLast => "Paste last dictation",
ShortcutTarget::RawDictation => "Dictate without processing",
// The portal never holds the cancel key.
ShortcutTarget::Cancel => return None,
// The portal lists Annotate's shortcut under that name.
#[cfg(hex_capture)]
ShortcutTarget::Capture => "Annotate",
// macOS has no shortcuts portal.
#[cfg(target_os = "macos")]
ShortcutTarget::SecondDictation => return None,
};
granted.iter().find(|shortcut| shortcut.name == name)
}
/// Keys GNOME keeps for itself by default (window menu, input sources, app
/// switching, the overview, screenshots, …), normalized as [`chord`] writes
/// them. A portal shortcut on one is listed in GNOME Settings but never
/// reaches Hex (#723).
const GNOME_KEYS: &[&str] = &[
"alt+space",
"super+space",
"shift+super+space",
"alt+tab",
"alt+shift+tab",
"super+tab",
"alt+f1",
"alt+f2",
"alt+f4",
"alt+f7",
"alt+f8",
"alt+f10",
"super+a",
"super+h",
"super+l",
"super+s",
"super+v",
"super+up",
"super+down",
"super+left",
"super+right",
"print",
"alt+print",
"shift+print",
"alt+ctrl+delete",
];
/// `keys` (`Ctrl+Alt+Space`, `Super+D`) lowercased with its modifiers in
/// one order, so the same chord always reads the same.
fn chord(keys: &str) -> String {
let mut parts = keys
.split('+')
.map(|part| match part.trim().to_ascii_lowercase().as_str() {
"control" => "ctrl".to_string(),
"meta" | "logo" => "super".to_string(),
other => other.to_string(),
})
.collect::<Vec<_>>();
let key = parts.pop().unwrap_or_default();
parts.sort();
parts.push(key);
parts.join("+")
}
fn gnome_keeps(keys: &str) -> bool {
GNOME_KEYS.contains(&chord(keys).as_str())
}
#[cfg(target_os = "linux")]
fn on_gnome() -> bool {
crate::linux::portal::gnome()
}
#[cfg(not(target_os = "linux"))]
fn on_gnome() -> bool {
false
}
/// On GNOME, the note under `target`'s row when its key, the one GNOME
/// granted or else the one Hex asks for, is one GNOME keeps for itself.
pub(super) fn gnome_clash_note(ui: &Ui, p: Paint, target: ShortcutTarget) -> Option<El> {
if !on_gnome() {
return None;
}
let keys = match portal_grant(ui, target) {
Some(DesktopGrantedShortcut {
trigger: Some(trigger),
..
}) => trigger.clone(),
_ => binding(&ui.settings, target)?.keycaps().join("+"),
};
gnome_keeps(&keys).then(|| {
note(
"gnome-clash",
&tr_fill(
"GNOME uses {} itself, so it never reaches Hex. Record another shortcut, or change it in GNOME Settings › Keyboard › Keyboard Shortcuts.",
&keys,
),
p.danger(),
)
})
}
/// The desktop kept `target`'s shortcut for itself: the note under its row.
pub(super) fn refused_note(ui: &Ui, p: Paint, target: ShortcutTarget) -> Option<El> {
portal_grant(ui, target)
.is_some_and(|shortcut| shortcut.trigger.is_none() && !shortcut.unconfirmed)
.then(|| {
note(
"refused",
if binding(&ui.settings, target).is_some_and(|binding| binding.key.as_ref().is_some_and(HotkeyKey::is_mouse)) {
tr("Configure mouse shortcuts in your Wayland desktop using the hex commands")
} else {
tr("Your desktop kept a shortcut for itself. Record another one, or free it in your desktop's keyboard settings (on niri, remove its bind from config.kdl).")
},
p.danger(),
)
})
}
/// Without a shortcuts portal the desktop's keybindings own every shortcut:
/// the commands to bind there.
pub(super) fn desktop_commands(ui: &Ui, p: Paint) -> El {
let mut rows = vec![
note(
"no-portal",
tr(
"Your desktop has no shortcuts portal. Bind these commands in its keyboard settings.",
),
p.muted(),
),
command_row(
p,
"hold",
tr("Hold to dictate"),
tr("Bind start to the key press and stop to its release"),
&["hex dictation start", "hex dictation stop"],
),
command_row(
p,
"toggle",
tr("Toggle dictation"),
tr("Press to start dictating, press again to transcribe"),
&["hex dictation toggle"],
),
command_row(
p,
"paste-last",
tr("Paste last dictation"),
tr("Re-paste the most recent dictation"),
&["hex paste-last"],
),
command_row(
p,
"raw-dictation",
tr("Dictate without processing"),
tr("Paste your words as Hex heard them, skipping every step"),
&["hex dictation toggle --raw"],
),
];
// GNOME without a shortcuts portal (GNOME 46 and older, #781): Hex writes
// the commands into GNOME's own custom shortcuts.
if on_gnome() {
rows.insert(1, gnome_shortcuts_row(ui, p));
}
section(p, "desktop-shortcuts", tr("Desktop shortcuts"), rows)
}
/// Adds or removes Hex's GNOME custom keyboard shortcuts.
fn gnome_shortcuts_row(ui: &Ui, p: Paint) -> El {
let on = ui.settings.gnome_keyboard_shortcuts;
let description = if on {
tr(
"Added to GNOME Settings › Keyboard › Custom Shortcuts while Hex is enabled. GNOME runs them on the key press, so your dictation shortcut toggles dictation. Change the keys there.",
)
} else {
tr(
"Adds dictation, paste last and Annotate to GNOME Settings › Keyboard › Custom Shortcuts with your shortcuts. GNOME runs them on the key press, so dictation toggles.",
)
};
let action = button(
p,
"gnome-shortcuts-control",
if on {
tr("Remove")
} else {
tr("Add GNOME keyboard shortcuts")
},
ButtonKind::Secondary,
move |ui: &mut Ui, _| {
ui.update(|settings| settings.gnome_keyboard_shortcuts = !on);
},
);
setting_row(
p,
"gnome-shortcuts",
tr("GNOME keyboard shortcuts"),
Some(description),
action,
)
}
fn command_row(p: Paint, key: &str, title: &str, description: &str, commands: &[&str]) -> El {
let lines = col()
.key("commands")
.gap(2.0)
.children(commands.iter().enumerate().map(|(index, command)| {
text(*command)
.key(format!("command{index}"))
.font(p.k.ty.mono)
.color(p.muted())
.align(rune::Align::End)
}));
setting_row(p, key, title, Some(description), lines)
}
/// Lists keyboard input sources every few seconds while General shows the
/// switching rows. The window lists them itself on Windows and Linux.
#[cfg(not(target_os = "macos"))]
pub(super) fn poll_input_sources(ui: &mut Ui, clock: f64) -> bool {
let switching =
ui.platform.caps.keyboard_model_switching && ui.settings.keyboard_model_switching.enabled;
if !switching {
let changed = !ui.platform.input_sources.is_empty();
ui.platform.input_sources.clear();
return changed;
}
if ui.pane != super::Pane::General
|| !ui.live()
|| !ui.window.as_ref().is_some_and(rune::AppHandle::is_visible)
|| clock < ui.input_sources_listed_at + 2.0
{
return false;
}
ui.input_sources_listed_at = clock;
let listed = crate::keyboard_input_sources::enabled();
let changed = ui.platform.input_sources != listed;
ui.platform.input_sources = listed;
changed
}
/// One row per enabled input source: "Don't switch" or an installed model,
/// then a language that model supports, as the Language row offers it.
pub(super) fn input_source_rows(ui: &Ui, p: Paint, layer: &mut Vec<El>) -> Vec<El> {
ui.platform
.input_sources
.iter()
.enumerate()
.map(|(index, source)| {
let mapped = ui
.settings
.keyboard_model_switching
.mappings
.get(&source.id)
.cloned();
let source_id = source.id.clone();
let mut choices = vec![Choice {
label: tr("Don't switch").into(),
detail: None,
selected: mapped.is_none(),
choose: Box::new(move |ui| {
ui.open = None;
ui.update(|settings| {
settings
.keyboard_model_switching
.mappings
.remove(&source_id);
});
}),
}];
choices.extend(
transcription_models::all_models()
.into_iter()