Repository navigation
Expand file tree
/
Copy pathrune_ui.rs
More file actions
2705 lines (2594 loc) · 93.6 KB
/
Copy pathrune_ui.rs
File metadata and controls
2705 lines (2594 loc) · 93.6 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's window on every OS, on Rune.
//!
//! The window talks to a host in the same process: on Linux the dictation
//! host beside it (`linux_host`); on Windows and macOS the runtime thread
//! `windows_rune` or `macos_rune` starts (`windows_host`, `macos_host`).
//! Either way it saves `settings.json` through the host, which adopts it,
//! and sends the same requests for listening, shortcuts, models, and
//! updates. `platform::Capabilities` decides which panes and rows each OS
//! shows. Everything is drawn with `rune-kit`'s components in OpenCode's
//! design language (`rune-theme-opencode`); see `docs/design-system.md`.
mod activity;
#[cfg(hex_capture)]
pub(crate) mod capture_capsule;
mod controls;
mod explainer;
mod fun;
mod general;
mod hero;
mod history;
#[cfg_attr(target_os = "linux", path = "rune_ui/linux_host.rs")]
#[cfg_attr(target_os = "windows", path = "rune_ui/windows_host.rs")]
#[cfg_attr(target_os = "macos", path = "rune_ui/macos_host.rs")]
mod host;
mod hud_lab;
#[cfg(target_os = "macos")]
mod hud_stories;
mod icons;
mod labs;
mod list_detail;
mod lists;
mod live_notes;
pub(crate) mod live_text;
pub(crate) mod meeting_capsules;
mod meetings;
mod meetings_host;
mod models;
mod modes;
mod onboarding;
mod onboarding_kit;
mod output;
mod picker;
mod platform;
mod platform_settings;
pub(crate) mod playground;
mod practice;
#[cfg(hex_capture)]
mod scrawl;
mod settings;
mod sound_sets;
mod spark;
#[cfg(target_os = "macos")]
pub(crate) mod story_link;
mod vocabulary;
use std::sync::Arc;
use std::time::{Duration, Instant};
use rune::{
Anim, AppSpec, Cx, El, Icon, ScrollSpec, TextEdit, Tx, Waker, col, el, icon, row, text,
};
use crate::app_settings::{AppSettings, HotkeyBinding, HotkeyKey, HotkeyModifiers, ModifierSide};
use crate::desktop_host::{
DesktopAction, DesktopGrantedShortcut, DesktopListenerSnapshot, DesktopShortcuts,
DesktopTranscriptionSnapshot, DesktopUpdateStatus,
};
use crate::desktop_i18n::{tr, tr_fill};
use crate::transcription_models::TranscriptionModelId;
use controls::{METRICS, Paint};
use host::{Backend, Request, ShortcutTarget};
use settings::Capture;
/// How long typing pauses before a text field's edit is saved.
const DRAFT_DELAY: Duration = Duration::from_millis(250);
/// How often timed state (draft saves, "Saved" badges, the OpenCode retry,
/// the setup beat, permission polling) is checked while the window shows.
const WINDOW_TICK: Duration = Duration::from_millis(250);
static SETTINGS_ICON: Icon = Icon {
name: "hex-settings",
view: 24.0,
body: include_str!("../assets/icons/settings.svg"),
};
static MODES_ICON: Icon = Icon {
name: "hex-modes",
view: 24.0,
body: include_str!("../assets/icons/modes.svg"),
};
static OUTPUT_ICON: Icon = Icon {
name: "hex-output",
view: 24.0,
body: include_str!("../assets/icons/output.svg"),
};
static HISTORY_ICON: Icon = Icon {
name: "hex-history",
view: 24.0,
body: include_str!("../assets/icons/history.svg"),
};
static ACTIVITY_ICON: Icon = Icon {
name: "hex-activity",
view: 24.0,
body: include_str!("../assets/icons/activity.svg"),
};
static HUD_LAB_ICON: Icon = Icon {
name: "hex-hud-lab",
view: 24.0,
body: include_str!("../assets/icons/hud-lab.svg"),
};
static VOICE_FILTER_ICON: Icon = Icon {
name: "hex-voice-filter",
view: 24.0,
body: include_str!("../assets/icons/voice-filter.svg"),
};
static MEETINGS_ICON: Icon = Icon {
name: "hex-meetings",
view: 24.0,
body: include_str!("../assets/icons/meetings.svg"),
};
#[cfg(hex_capture)]
static SCRAWL_ICON: Icon = Icon {
name: "hex-scrawl",
view: 24.0,
body: include_str!("../assets/icons/scrawl.svg"),
};
/// Runs the Linux window's app on the main thread until Hex quits: the
/// window side of `linux_app`'s seam. It starts without a window; each
/// `Activate` opens or focuses it with the launcher's activation token, and
/// closing it keeps the app, its state, and the host running.
#[cfg(target_os = "linux")]
pub(crate) fn run_app(
host: crate::linux_app::HostHandle,
requests: std::sync::mpsc::Receiver<crate::linux_service::Control>,
first: Option<crate::linux_service::Activation>,
shutdown: &'static std::sync::atomic::AtomicBool,
) {
use crate::linux_service::{Activation, Control};
rune::set_app_id(crate::linux_portal::APP_ID);
let mut app = self::app(Some(host.clone()))
.args(Vec::new())
.windowless()
.float_on_open();
crate::linux_rune_hud::install(&mut app);
live_text::install(&mut app, crate::rune_hud::live_text_place);
// The capture capsule, picker, and ink.
let _capture_overlays =
crate::rune_ui::capture_capsule::feed::CaptureOverlays::install(&mut app);
let meetings = crate::meeting_runtime::Meetings::install(&mut app, shutdown)
.inspect_err(|error| tracing::error!(%error, "meetings could not start"))
.ok();
let handle = app.handle();
host.set_window_visible({
let handle = handle.clone();
Arc::new(move || handle.is_visible())
});
let show = move |activation: Activation| match activation.token.or(activation.startup_id) {
Some(token) => handle.activate(token),
None => handle.open(),
};
if let Some(activation) = first {
show(activation);
}
let quit = app.handle();
let window = app.handle();
std::thread::Builder::new()
.name("hex-window-requests".into())
.spawn(move || {
while let Ok(request) = requests.recv() {
match request {
Control::Activate(activation) => show(activation),
Control::Show(pane) => {
show(Activation::default());
window.update(move |ui, tx| self::show(ui, destination(pane), tx));
}
Control::Hide => window.close(),
Control::OnboardingReset(answer) => {
show(Activation::default());
window.update(move |ui, tx| {
let _ = answer.send(restart_onboarding(ui, tx));
});
}
Control::Quit => {
quit.quit();
break;
}
}
}
})
.expect("could not start the window request thread");
app.run();
// A recording stops, keeping its audio for the next launch.
shutdown.store(true, std::sync::atomic::Ordering::Release);
if let Some(meetings) = meetings {
meetings.join();
}
}
/// The window as a Rune app whose lifetime the caller chooses, connected to
/// its host through `connect`, with the playground that Labs › Playground
/// opens.
pub(crate) fn app(connect: host::Connect) -> rune::App<Ui> {
onboarding_kit::set_live_window(true);
let app = build(connect, PlaygroundMode::Gated);
#[cfg(target_os = "macos")]
let app = app.on_open_url(on_open_url);
app
}
/// A `hex://` link the system opened with Hex: a story link opens the window
/// on that playground story; anything else is ignored.
#[cfg(target_os = "macos")]
fn on_open_url(_: &mut Ui, link: &str, tx: &mut Tx) {
let link = match story_link::parse(link, story_link::scheme()) {
Ok(link) => link,
Err(why) => {
tracing::warn!(%why, "ignored a link opened with Hex");
return;
}
};
if let Err(why) = story_link::open(&link, tx) {
tracing::warn!(story = %link.story, %why, "a story link opened only the window");
}
crate::macos_rune::bring_window_forward();
}
/// `hex app -- --snap …`: a headless render of a fixture scene. With the
/// Labs on, `--playground [story]` renders the playground.
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub(crate) fn render_app(rune_args: Vec<String>) -> rune::App<Ui> {
let playground = rune_args.iter().any(|arg| arg == "--playground");
let headless = rune_args
.iter()
.any(|arg| arg == "--snap" || arg == "--video" || arg == "--list-scenes");
onboarding_kit::set_live_window(playground && !headless);
let app = build(
Default::default(),
if playground && playground::enabled() {
PlaygroundMode::Attached
} else {
PlaygroundMode::None
},
)
.args(rune_args);
if playground && !headless {
app.handle().update_if(|_, _| {
crate::feedback::set_enabled(true);
crate::feedback::set_volume(0.65);
let _ = crate::feedback::preload();
false
});
}
app
}
/// The window's compositor: the UI, then the welcome hero over the tour's
/// stage and the Sounds sheet's HUD over its stage.
#[derive(Default)]
pub(crate) struct WindowCompositor {
hero: hero::HeroCompositor,
sounds: sound_sets::Preview,
}
impl rune::compose::Compositor<Ui> for WindowCompositor {
fn features(&self) -> wgpu::Features {
// The Sounds sheet's HUD, and one device shared with the HUD overlay.
self.hero.features() | crate::rune_hud::Painter::FEATURES
}
fn animating(&self) -> bool {
self.hero.animating()
}
fn summary(&mut self, device: &wgpu::Device) -> Option<String> {
self.hero.summary(device)
}
fn render(&mut self, f: &mut rune::compose::Frame<'_, Ui>) {
self.hero.render(f);
self.sounds.render(f);
}
}
/// Whether and how the window has the playground.
#[derive(Clone, Copy, PartialEq, Eq)]
enum PlaygroundMode {
None,
/// With Rune's own ⇧⌘D (headless `--playground` renders).
#[cfg_attr(target_os = "linux", allow(dead_code))]
Attached,
/// Opened only while Labs › Playground is on (the window).
Gated,
}
fn build(connect: host::Connect, playground: PlaygroundMode) -> rune::App<Ui> {
let spec = if playground == PlaygroundMode::None {
spec()
} else {
playground::spec(spec())
};
let app = rune::App::new(spec)
.init(move || Ui::load_with(connect))
.on_close(on_close)
.compositor(WindowCompositor::default());
#[cfg(target_os = "macos")]
let app = app.gpu_backend(rune::GpuBackend::Metal);
// Linux records shortcuts from the window's keys, so a modifier pressed
// alone reaches the recorder, which says Linux needs a key with it.
#[cfg(target_os = "linux")]
let app = app.modifier_keys();
let app = match playground {
PlaygroundMode::None => app,
PlaygroundMode::Attached => playground::attach(app),
PlaygroundMode::Gated => playground::attach_gated(app),
};
let window = app.handle();
// Nothing shown reads the handle, so this asks for no frame. The first
// frame's poll ran without it, so the window's tick starts from here.
window.update_if({
let window = window.clone();
move |ui, tx| {
ui.window = Some(window);
tx.wake_after(WINDOW_TICK);
false
}
});
app
}
/// Closing the window saves pending text edits and stops a shortcut
/// recording, as leaving a pane does. Hex keeps running.
fn on_close(ui: &mut Ui, _: &mut Tx) {
ui.flush_drafts();
settings::cancel_capture(ui);
ui.open = None;
models::close(ui);
picker::close(ui);
explainer::close(ui);
sound_sets::close(ui);
vocabulary::close(ui);
// HUD Lab's demo would otherwise stay on screen; reopening starts at
// General, and coming back to HUD Lab starts the demo again.
if ui.pane == Pane::HudLab {
ui.ask(platform::PlatformRequest::EndHudDemo);
ui.pane = Pane::General;
}
if let Service::Live(backend) = &mut ui.service {
backend.closed();
}
#[cfg(target_os = "macos")]
crate::macos_rune::window_closed();
}
/// Where the menu bar, a meeting, or a `hex window show` sends the window.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Destination {
Settings,
/// Settings with the transcription picker open.
Models,
/// The Meetings pane, with a meeting selected when given.
Meetings(Option<String>),
Modes,
History,
}
/// Where `hex window show` opens the window. While Meetings is off, its
/// pane shows the opt-in.
#[cfg(not(target_os = "macos"))]
pub(crate) fn destination(pane: Option<crate::control::Pane>) -> Destination {
use crate::control::Pane as Named;
match pane {
None | Some(Named::Settings) => Destination::Settings,
Some(Named::Models) => Destination::Models,
Some(Named::Modes) => Destination::Modes,
Some(Named::History) => Destination::History,
Some(Named::Meetings) => Destination::Meetings(None),
}
}
/// Shows `destination` in the window (the caller opens it).
pub(crate) fn show(ui: &mut Ui, destination: Destination, tx: &mut Tx) {
let pane = match &destination {
Destination::Settings | Destination::Models => Pane::General,
Destination::Meetings(_) => Pane::Meetings,
Destination::Modes => Pane::Output,
Destination::History => Pane::History,
};
picker::close(ui);
explainer::close(ui);
sound_sets::close(ui);
vocabulary::close(ui);
if pane.shown(ui) {
ui.select_pane(pane, tx);
}
match destination {
Destination::Models => picker::open(ui),
Destination::Meetings(Some(id)) => {
ui.meetings.view = meetings::View::Recordings;
ui.meetings.select(id);
}
_ => {}
}
}
/// What this OS's Hex can do, by capability name, for `hex status` and the
/// settings `hex settings` can change here.
pub(crate) fn capabilities() -> std::collections::BTreeMap<String, bool> {
platform::Capabilities::current()
.fields()
.into_iter()
.map(|(name, on)| (name.to_owned(), on))
.collect()
}
/// Whether this OS's Hex has the capability `name` ([`capabilities`]).
pub(crate) fn capability(name: &str) -> bool {
platform::Capabilities::current()
.fields()
.into_iter()
.any(|(field, on)| field == name && on)
}
/// `hex onboarding reset`: replays the first run in the window now; the
/// window also shows why it couldn't.
pub(crate) fn restart_onboarding(ui: &mut Ui, tx: &mut Tx) -> Result<(), String> {
onboarding_kit::live::restart(ui, tx).inspect_err(|why| ui.error = Some(why.clone()))
}
/// The pane the window shows, by its `hex window show` name: General is
/// still `settings` there.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn current_pane(ui: &Ui) -> &'static str {
match ui.pane {
Pane::General => "settings",
pane => pane.key().trim_start_matches("nav-"),
}
}
/// The OS's rules for a shortcut, the ones Settings applies when recording
/// one; shared with `hex settings set`.
pub(crate) fn shortcut_rule(
slot: crate::app_settings::HotkeySlot,
binding: &HotkeyBinding,
) -> Result<(), &'static str> {
use crate::app_settings::HotkeySlot;
let target = match slot {
HotkeySlot::Dictation => ShortcutTarget::Dictation,
HotkeySlot::PasteLast => ShortcutTarget::PasteLast,
HotkeySlot::RawDictation => ShortcutTarget::RawDictation,
#[cfg(hex_capture)]
HotkeySlot::Capture => ShortcutTarget::Capture,
#[cfg(target_os = "macos")]
HotkeySlot::SecondDictation => ShortcutTarget::SecondDictation,
// Labs › Second dictation shortcut is macOS's; elsewhere a saved one
// meets the dictation shortcut's rules.
#[cfg(not(target_os = "macos"))]
HotkeySlot::SecondDictation => ShortcutTarget::Dictation,
};
host::validate_hotkey(target, binding)
}
/// The key `name` names on the active keyboard layout ("v", "space", "f5").
#[cfg(target_os = "macos")]
pub(crate) fn hotkey_key_named(name: &str) -> Result<HotkeyKey, &'static str> {
host::hotkey_key_named(name)
}
/// The key `name` names: Linux and Windows bind keys by name, and the
/// shortcut's rule ([`shortcut_rule`]) checks it can register.
#[cfg(not(target_os = "macos"))]
pub(crate) fn hotkey_key_named(name: &str) -> Result<HotkeyKey, &'static str> {
Ok(HotkeyKey::named(name))
}
/// The OS's shortcut rules for `hex settings set`.
pub(crate) fn shortcut_rules() -> crate::control::settings::ShortcutRules {
crate::control::settings::ShortcutRules {
key_named: |name| hotkey_key_named(name).map_err(str::to_owned),
rule: |slot, binding| shortcut_rule(slot, binding).map_err(str::to_owned),
}
}
/// A capsule's "Never offer" or "Always record" choice, kept in the window's
/// live settings so its next save doesn't drop it.
pub(crate) fn meeting_provider_chosen(
ui: &mut Ui,
choice: crate::app_settings::MeetingProviderChoice,
) {
crate::app_settings::set_meeting_provider(&mut ui.settings.meetings, choice);
}
/// The corner the recording capsule was dragged to, kept in the window's live
/// settings so its next save doesn't move it back.
pub(crate) fn meeting_corner_moved(
ui: &mut Ui,
corner: crate::app_settings::MeetingIndicatorCorner,
) {
ui.settings.meetings.recording_indicator_corner = corner;
}
/// A meeting recording could not start or finish; the Meetings pane says why.
pub(crate) fn meeting_failed(ui: &mut Ui, error: String) {
ui.meetings.start_pending = false;
ui.meetings.stop_pending = false;
ui.meetings.runtime_error = Some(error);
}
/// `hex app -- --snap out.png --scene …`: a headless render of a fixture
/// scene, or `live` for the running Hex's `hex status`.
#[cfg(target_os = "linux")]
pub(crate) fn render() {
let with_playground =
std::env::args().any(|arg| arg == "--playground") && playground::enabled();
if !with_playground {
rune::run_with(spec(), WindowCompositor::default());
return;
}
let app = rune::App::new(playground::spec(spec())).compositor(WindowCompositor::default());
playground::attach(app).run();
}
/// The window's logical size, which every pane and the picker fit.
const WINDOW_SIZE: (f32, f32) = (980.0, 760.0);
/// One fixed size the user cannot change, which macOS tiling window managers
/// (AeroSpace, yabai) float: the first-run tour opens centred this way. With
/// the playground, it resizes, so the stage beside its columns has room.
#[cfg(target_os = "macos")]
pub(crate) fn fixed_window() -> rune::WindowOptions {
if playground::enabled() {
return rune::WindowOptions::default();
}
rune::WindowOptions {
min_size: Some(WINDOW_SIZE),
max_size: Some(WINDOW_SIZE),
resizable: false,
..Default::default()
}
}
fn spec() -> AppSpec<Ui> {
AppSpec {
title: "Hex",
size: WINDOW_SIZE,
// Narrower windows crowd the sidebar and rows.
min_size: Some((860.0, 560.0)),
init: Ui::load,
view,
scenes: SCENES,
fonts: rune_theme_opencode::FONTS,
families: rune_theme_opencode::FAMILIES,
setup: Some(setup),
poll: Some(poll),
on_key: Some(on_key),
}
}
/// Where the window sends its requests.
enum Service {
/// Not connected yet: `setup` connects, with what the window's host handed
/// over, unless a scene chose a fixture.
Pending(host::Connect),
Live(Box<Backend>),
/// Snapshots and tests: requests are recorded, never sent.
Fixture(Vec<Request>),
}
/// The host's latest state.
struct HostState {
view: ServiceView,
settings: AppSettings,
}
/// What the window shows of the service, from its latest snapshot.
#[derive(Clone, PartialEq)]
struct ServiceView {
listener: DesktopListenerSnapshot,
operation_error: Option<String>,
transcription: DesktopTranscriptionSnapshot,
update_status: DesktopUpdateStatus,
/// The service is recording or saving a shortcut.
editing: bool,
}
/// Every pane, in navigation order. Which ones show depends on the OS's
/// [`platform::Capabilities`] and opt-ins ([`Pane::shown`]).
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
enum Pane {
/// Dictation, output, and application basics.
#[default]
General,
/// What Hex does to every dictation and in some apps, read-only: the
/// person's agent edits it.
Output,
/// The old per-app editor, kept for its scenes until it is removed.
Modes,
/// Recorded calls and their settings, or the opt-in (macOS beta).
Meetings,
History,
/// Annotate (Scrawl's captures inside Hex): the switch, shortcuts,
/// permission, transcriber, folder, retention, and Scrawl's own app.
/// Dev builds, macOS and Linux only.
#[cfg(hex_capture)]
Annotate,
/// The Hex Microphone's driver, tuning, and try-it demo (macOS, while
/// its Labs toggle is on).
VoiceFilter,
/// The dictation indicator's tuning scene (Playground only).
HudLab,
/// Legacy event-log inspector scene (Playground only).
Activity,
}
impl Pane {
#[cfg(all(test, target_os = "linux"))]
const ALL: &[Pane] = &[
Pane::General,
Pane::Output,
Pane::Modes,
Pane::Meetings,
Pane::History,
#[cfg(hex_capture)]
Pane::Annotate,
Pane::VoiceFilter,
Pane::HudLab,
Pane::Activity,
];
fn shown(self, ui: &Ui) -> bool {
let caps = ui.platform.caps;
match self {
Pane::Modes | Pane::HudLab | Pane::Activity => false,
Pane::Meetings => caps.meetings && meetings::available(ui),
// On from Labs, or kept by a driver apps already use.
Pane::VoiceFilter => caps.fun && fun::running(ui),
#[cfg(hex_capture)]
Pane::Annotate => ui.platform.scrawl.is_some(),
_ => true,
}
}
fn title(self) -> &'static str {
match self {
Pane::General => tr("General"),
Pane::Output => tr("Output"),
Pane::Modes => tr("Modes"),
Pane::History => tr("History"),
Pane::Meetings => tr("Meetings"),
#[cfg(hex_capture)]
Pane::Annotate => tr("Annotate"),
Pane::VoiceFilter => tr("Voice Filter"),
Pane::HudLab => "HUD Lab",
Pane::Activity => tr("Activity"),
}
}
fn key(self) -> &'static str {
match self {
Pane::General => "nav-general",
Pane::Output => "nav-output",
Pane::Modes => "nav-modes",
Pane::History => "nav-history",
Pane::Meetings => "nav-meetings",
#[cfg(hex_capture)]
Pane::Annotate => "nav-annotate",
Pane::VoiceFilter => "nav-voice-filter",
Pane::HudLab => "nav-hud-lab",
Pane::Activity => "nav-activity",
}
}
fn icon(self) -> &'static Icon {
match self {
Pane::General => &SETTINGS_ICON,
Pane::Output => &OUTPUT_ICON,
Pane::Modes => &MODES_ICON,
Pane::History => &HISTORY_ICON,
Pane::Meetings => &MEETINGS_ICON,
#[cfg(hex_capture)]
Pane::Annotate => &SCRAWL_ICON,
Pane::VoiceFilter => &VOICE_FILTER_ICON,
Pane::HudLab => &HUD_LAB_ICON,
Pane::Activity => &ACTIVITY_ICON,
}
}
}
/// The one anchored menu or popover that is open.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Menu {
Microphone,
/// An input source's model in keyboard model switching.
InputSourceModel(usize),
/// An input source's language in keyboard model switching.
InputSourceLanguage(usize),
/// The microphone under the tour's practice field.
TourMicrophone,
/// How long History keeps dictations.
HistoryRetention,
/// The OpenCode thinking variant.
Variant,
/// The selected meeting's overflow menu.
MeetingActions,
/// The calendars meeting reminders read.
Calendars,
/// The transformations a mode can add (the Modes pane).
Transformations,
/// How long annotations are kept (the Annotate pane).
#[cfg(hex_capture)]
CaptureRetention,
/// A settings row's quiet select, by the row's key.
Pick(&'static str),
/// A detected call provider's policy, by its row.
Call(usize),
}
pub(crate) struct Ui {
settings: AppSettings,
service: Service,
/// This window's app, to know whether it shows (`app` sets it).
window: Option<rune::AppHandle<Ui>>,
/// The poll clock when the next timed check is due.
tick_at: f64,
view: Option<ServiceView>,
/// A save or policy change that failed here.
error: Option<String>,
/// Why the window cannot reach the host.
connection_error: Option<String>,
/// The settings the host last reported, to adopt only its changes.
service_settings: Option<AppSettings>,
pane: Pane,
open: Option<Menu>,
// General
microphones: Result<crate::audio::InputDevices, String>,
/// The [`crate::audio::input_route_generation`] `microphones` was listed at.
microphones_route: Option<u64>,
/// The poll clock `microphones` was last listed at.
microphones_listed_at: f64,
/// When Windows and Linux last listed keyboard input sources; macOS's
/// native host lists them.
#[cfg_attr(target_os = "macos", allow(dead_code))]
input_sources_listed_at: f64,
/// A listing in flight. Listing reads CoreAudio or COM endpoint
/// properties, which can block, so it runs off the UI thread.
microphones_listing:
Option<std::sync::mpsc::Receiver<Result<crate::audio::InputDevices, String>>>,
confirm_release: bool,
mic_level: general::MicLevel,
/// The panes whose Advanced fold is open.
advanced: Vec<Pane>,
/// The Labs page shows in place of a pane.
labs_open: bool,
/// A scene previewing the badge of a build kind this binary is not.
build_preview: Option<BuildKind>,
capture: Capture,
hints: TextEdit,
vocabulary: vocabulary::VocabularyEditor,
/// The model the service was last seen preparing, and since when.
preparing: Option<(TranscriptionModelId, Instant)>,
/// When a text field last changed without being saved.
draft_since: Option<Instant>,
duck_volume_drag: Option<f32>,
models: models::Models,
history: history::HistoryPane,
modes: modes::ModesPane,
output: output::OutputPane,
picker: picker::Picker,
explainer: explainer::Explainer,
sound_sets: sound_sets::SoundSets,
tour: Option<onboarding::Tour>,
/// The new first run over the tour (Labs).
first_run: Option<onboarding_kit::Onboard>,
/// The OS's capabilities and the OS-only state its panes show.
platform: platform::PlatformState,
host: platform::PlatformHost,
meetings: meetings::MeetingsPane,
fun: fun::FunPane,
activity: activity::ActivityPane,
/// HUD Lab's preset was copied since it last changed.
hud_copied: bool,
/// HUD Lab saved Dot scope's tuning, until the next change.
hud_saved: bool,
/// Settings saves and Quit Hex a fixture recorded.
saved: usize,
quit_requested: bool,
}
/// Which of the window's text editors hold unsaved typing.
#[derive(Clone, Copy, Debug)]
struct Drafts {
hints: bool,
modes: bool,
vocabulary: bool,
}
impl Ui {
fn load() -> Self {
Self::load_with(host::Connect::default())
}
fn load_with(connect: host::Connect) -> Self {
let (settings, error) = match AppSettings::load() {
Ok(settings) => (settings, None),
Err(error) => (AppSettings::default(), Some(format!("{error:#}"))),
};
crate::desktop_i18n::apply(settings.ui_language.as_deref());
let store = host::history(&connect, settings.history_retention);
let mut ui = Self::with(settings, Service::Pending(connect));
ui.error = error;
// A mouse-button shortcut went back to its default: say so once.
if ui.settings.mouse_shortcut_notice {
ui.settings.mouse_shortcut_notice = false;
if let Err(error) = ui.settings.save() {
tracing::warn!(%error, "could not clear the mouse shortcut note");
}
ui.error.get_or_insert_with(|| {
tr("Mouse shortcuts are in Labs now, so your mouse-button shortcut went back to the default. Turn on Labs › Mouse shortcuts to use one again.").to_owned()
});
}
ui.history = history::HistoryPane::shared(store);
ui.modes.load_personal_commands();
ui.platform.developer =
crate::dev_build::is_dev_build() && crate::DEVELOPER_FEATURES_ENABLED;
ui.platform.hud.tuning = crate::dot_scope::lab();
ui.tour = onboarding::Tour::start(&ui.settings, &ui.platform);
ui.platform.set_login_item(host::launch_at_login());
ui
}
fn with(settings: AppSettings, service: Service) -> Self {
let hints = TextEdit::new(settings.transcription.recognition_hints.clone());
let modes = modes::ModesPane::new(&settings);
let vocabulary = vocabulary::VocabularyEditor::new(&settings.vocabulary);
Self {
settings,
service,
view: None,
error: None,
connection_error: None,
service_settings: None,
pane: Pane::General,
open: None,
microphones: Ok(Default::default()),
microphones_route: None,
microphones_listed_at: 0.0,
input_sources_listed_at: f64::NEG_INFINITY,
microphones_listing: None,
confirm_release: false,
mic_level: general::MicLevel::default(),
advanced: Vec::new(),
labs_open: false,
build_preview: None,
capture: Capture::Idle,
hints,
vocabulary,
preparing: None,
draft_since: None,
duck_volume_drag: None,
models: models::Models::default(),
history: history::HistoryPane::default(),
modes,
output: output::OutputPane::default(),
picker: picker::Picker::default(),
explainer: explainer::Explainer::default(),
sound_sets: sound_sets::SoundSets::default(),
tour: None,
first_run: None,
platform: platform::PlatformState::new(platform::Capabilities::current()),
host: platform::PlatformHost::Local(Default::default()),
meetings: meetings::MeetingsPane::default(),
fun: fun::FunPane::default(),
activity: activity::ActivityPane::default(),
hud_copied: false,
hud_saved: false,
saved: 0,
quit_requested: false,
window: None,
tick_at: 0.0,
}
}
fn live(&self) -> bool {
matches!(self.service, Service::Live(_))
}
fn send(&mut self, request: Request) {
match &mut self.service {
Service::Live(client) => {
if let Err(error) = client.send(request) {
self.error = Some(format!("{error:#}"));
}
}
Service::Fixture(sent) => sent.push(request),
Service::Pending(_) => {}
}
}
/// Saves `settings.json` through the host, which adopts the change. A
/// failed save leaves the shown settings alone.
fn update(&mut self, change: impl FnOnce(&mut AppSettings)) -> bool {
let mut candidate = self.drafted();
change(&mut candidate);
self.commit(candidate)
}
fn commit(&mut self, candidate: AppSettings) -> bool {
match &mut self.service {
Service::Live(backend) => {
if let Err(error) = backend.save(&candidate) {
self.error = Some(format!("{error:#}"));
return false;
}
}
Service::Fixture(_) => self.saved += 1,
Service::Pending(_) => {}
}
self.error = None;
self.settings = candidate;
self.draft_since = None;
self.settings_changed();
true
}
/// Meetings turned off forgets its view: turning it back on lists the
/// recordings.
fn settings_changed(&mut self) {
if !meetings::available(self) {
self.meetings.view = meetings::View::Recordings;
}
}
/// The settings with every text field's current text applied.
fn drafted(&self) -> AppSettings {
let mut candidate = self.settings.clone();
if self.hints_shown(&candidate) {
candidate.transcription.recognition_hints = self.hints.text.clone();
}
self.modes.project(&mut candidate);
candidate.vocabulary = self.vocabulary.project();
candidate
}
fn hints_shown(&self, settings: &AppSettings) -> bool {
crate::transcription_models::definition(settings.transcription.model)
.supports_recognition_hints
}
/// Which editors hold typing the saved settings don't have yet.
fn drafts(&self) -> Drafts {
let settings = &self.settings;
let mut modes = settings.clone();
self.modes.project(&mut modes);
Drafts {
hints: self.hints_shown(settings)
&& self.hints.text != settings.transcription.recognition_hints,
modes: modes.dictation_processing != settings.dictation_processing,
vocabulary: self.vocabulary.project() != settings.vocabulary,
}
}
/// Saves text-field edits once typing pauses for [`DRAFT_DELAY`].
fn save_drafts(&mut self, now: Instant) -> bool {
let candidate = self.drafted();
if candidate == self.settings {
self.draft_since = None;
return false;
}
let since = *self.draft_since.get_or_insert(now);
if now.duration_since(since) < DRAFT_DELAY {
return false;
}
self.commit(candidate)
}
/// Saves pending text-field edits now (leaving a pane or a mode).
fn flush_drafts(&mut self) {
let candidate = self.drafted();
if candidate != self.settings {
self.commit(candidate);
}
}
/// Asks the OS host for something only it can do.
fn ask(&mut self, request: platform::PlatformRequest) {
match &request {
platform::PlatformRequest::Permission(
crate::onboarding::PermissionAction::RequestMicrophone,
) => self
.platform
.note_asked(crate::onboarding::PermissionKind::Microphone),
platform::PlatformRequest::Permission(
crate::onboarding::PermissionAction::ShowGuide(kind),
) => {
// Previews grant Screen Recording on the second ask, as for
// system audio.
#[cfg(hex_capture)]
if *kind == crate::onboarding::PermissionKind::ScreenRecording
&& self.host.is_fixture()
&& self.platform.asked(*kind)
&& let Some(view) = self.platform.scrawl.as_mut()