Repository navigation
Expand file tree
/
Copy pathcapture_host.rs
More file actions
5276 lines (4925 loc) · 191 KB
/
Copy pathcapture_host.rs
File metadata and controls
5276 lines (4925 loc) · 191 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 `capture` experiment (macOS, Linux, and Windows): Scrawl's capture
//! engine, the `scrawl-capture` crate, hosted inside Hex. Step 3 of
//! `docs/plans/capture-in-hex.md`. Everything here is shared; what differs
//! by OS is the engine's own platform adapter (ScreenCaptureKit; the portal,
//! PipeWire and VA-API; or Windows.Graphics.Capture), where the audio
//! timeline comes from (`DictationAudio` on macOS, the Linux and Windows
//! listeners' [`ListenerTimeline`]), "While dictating" ([`Environment`]),
//! the transcriber, and the clipboard.
//!
//! The engine records the screen and writes the bundle; Hex owns the
//! microphone and the model. A capture copies audio from the dictation
//! timeline through a bounded sink (no second stream) and hands it to
//! `SealedCapture::finish` ([`AudioIn::External`]), and its words come from
//! the dictation engine's loaded model as foreground work. The engine runs
//! with [`SharedResources::none`]: no ingest server, delivery retries, or
//! global shortcuts. [`CaptureHost::start`] does nothing unless the
//! experiment is on and the person turned captures on (`capture.enabled`).
//!
//! Step 4 adds the capture shortcut (`recognition`), and the pointer, Shift,
//! and key input the session tap reports while a capture records
//! ([`report_input`]), which the `capture-input` thread hands to the
//! capture's `InputSink` through the engine's pure input rules
//! (`scrawl_capture::hosted_input`).
//!
//! While a capture records it holds a recording-environment session with
//! "While dictating" (`recording_audio_behavior`, read at each start),
//! released when it stops, is cancelled, or Hex quits; dictation's own
//! session composes with it.
//!
//! Views never reach into the host: every change to a capture (started,
//! the screen recording, stopped, the engine's stages, settled) publishes
//! one [`CaptureSnapshot`], which [`snapshot`] reads and [`watch`] wakes on.
use std::fs;
use std::fs::DirBuilder;
#[cfg(unix)]
use std::os::unix::fs::DirBuilderExt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError};
use std::sync::{Arc, LazyLock, Mutex, OnceLock, Weak};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use color_eyre::eyre::{Result, WrapErr, eyre};
use scrawl_capture::audio::{GapSpan, RecordedAudio};
use scrawl_capture::capture::{
AudioIn, ConfigSource, Event, Host, InputSink, OwnWindows, SharedCaptureTelemetry,
SharedResources, Stage, Start, Target,
};
use scrawl_capture::handoff::EngineConfig;
use scrawl_capture::hosted_input::{HostInput, HostedInput, Modifiers};
use scrawl_capture::model::{TranscriptData, WordTiming};
#[cfg(target_os = "macos")]
use scrawl_capture::transcribe::AppleTranscriber;
use scrawl_capture::transcribe::Transcriber;
use crate::audio::CaptureInstant;
use crate::control::{
ControlReply, ScrawlCaptureAction, ScrawlCaptureOutcome, ScrawlCaptureReport,
ScrawlCaptureState,
};
use crate::dictation::StreamingResampler;
#[cfg(target_os = "macos")]
use crate::dictation_audio::DictationAudio;
#[cfg(target_os = "macos")]
pub use crate::recording_environment::RecordingEnvironmentController as Environment;
#[cfg(target_os = "macos")]
use crate::recording_environment::RecordingEnvironmentSession as Quiet;
use crate::transcription_engine::TranscriptionEngine;
use crate::transcription_models::{ModelRuntime, TranscriptionModelId};
// `hex annotate`'s folder commands; Windows has no control transport for
// them yet.
#[cfg_attr(target_os = "windows", allow(dead_code))]
mod library;
mod permissions;
mod routing;
#[cfg(target_os = "macos")]
mod screen_access;
mod sink;
pub use library::{
explain as explain_capture, list as list_captures, send as send_capture, show as show_capture,
};
pub use permissions::{
CaptureNeed, NeedState, allow as allow_permission, on_missing,
restart as restart_for_permission, state_of as permission_state,
};
pub use routing::CaptureRoute;
pub use routing::{RouteAnswer, RouteDelivery, RouteDest};
#[cfg(target_os = "macos")]
pub use screen_access::{ScreenAccess, screen_access, screen_access_now};
#[cfg(target_os = "macos")]
pub use sink::CaptureSink;
#[cfg(not(target_os = "macos"))]
pub use sink::ListenerTimeline;
pub use sink::{CaptureAudio, CaptureSinkClosed};
/// "While dictating" for a capture on Linux: its own audio suppressor, made
/// when the capture starts and restoring what it changed when dropped.
#[cfg(target_os = "linux")]
#[derive(Clone, Default)]
pub struct Environment;
#[cfg(target_os = "linux")]
type Quiet = crate::linux_audio_control::AudioSuppressor;
#[cfg(target_os = "linux")]
impl Environment {
fn begin_capture(&self, behavior: crate::app_settings::RecordingAudioBehavior) -> Quiet {
let quiet = Quiet::new(behavior);
quiet.suppress();
quiet
}
}
/// "While dictating" for a capture on Windows: its own suppressor, made when
/// the capture starts and restoring what it changed when dropped.
#[cfg(target_os = "windows")]
#[derive(Clone, Default)]
pub struct Environment;
#[cfg(target_os = "windows")]
type Quiet = crate::windows_audio_control::AudioSuppressor;
#[cfg(target_os = "windows")]
impl Environment {
fn begin_capture(&self, behavior: crate::app_settings::RecordingAudioBehavior) -> Quiet {
let quiet = Quiet::start(behavior);
quiet.suppress();
quiet
}
}
/// The sink's capacity in microphone chunks (about 10 ms each): seconds of
/// slack before a stalled collector starts dropping audio as a gap.
const SINK_CAPACITY: usize = 512;
const EVENT_CAPACITY: usize = 64;
const SAMPLE_RATE: u32 = 16_000;
/// A capture keeps at most this much audio; the rest is recorded as a gap.
const MAX_CAPTURE: Duration = Duration::from_secs(20 * 60);
const GAP_TOLERANCE: Duration = Duration::from_millis(50);
/// How long shutdown waits for capture threads, inside the quit deadline.
const SHUTDOWN_WAIT: Duration = Duration::from_secs(2);
/// Captures being written at once: the one finishing plus those queued
/// behind it. A start beyond this is refused.
const MAX_FINISHING: usize = 2;
/// Tap events waiting for the `capture-input` thread; past this they drop.
const INPUT_CAPACITY: usize = 1_024;
/// A second press of the capture shortcut sooner than this after the start
/// is a bounce, not a stop.
pub const SHORTCUT_DEBOUNCE: Duration = Duration::from_millis(400);
/// Retention passes over the captures folder.
const RETENTION_FIRST: Duration = Duration::from_secs(90);
const RETENTION_EVERY: Duration = Duration::from_secs(60 * 60);
/// How long captures wait to try again after the host failed to start.
const START_RETRY: Duration = Duration::from_secs(60);
// ---------------------------------------------------------------------------
// The engine, as Hex runs it.
/// What [`CaptureHost`] needs from an engine: Scrawl's in the app, and in
/// tests one that records no screen.
trait CaptureEngine: Send + Sync + 'static {
/// Starts recording the screen into `start.bundle_dir`. Blocking: it
/// finds the display and starts ScreenCaptureKit.
fn start(&self, start: Start) -> anyhow::Result<Box<dyn Recording>>;
/// What the engine records for `target`. Blocking: a window or area
/// reads ScreenCaptureKit's window list.
fn target(&self, target: CaptureTarget) -> anyhow::Result<Target> {
use scrawl_capture::capture::{discover_target_at, list_selectable_windows, region_target};
Ok(match target {
CaptureTarget::Pointer => Target::ActiveDisplay,
CaptureTarget::Display { at } => Target::Screen(discover_target_at(None, Some(at))),
// Wayland lists no windows: the portal's own picker chooses one.
#[cfg(target_os = "linux")]
CaptureTarget::Window { .. } => Target::Screen(scrawl_capture::model::TargetInfo {
mode: scrawl_capture::model::CaptureMode::Window,
..discover_target_at(None, None)
}),
#[cfg(not(target_os = "linux"))]
CaptureTarget::Window { id } => Target::Screen(
list_selectable_windows()
.into_iter()
.find(|window| window.window_id == Some(id))
.ok_or_else(|| anyhow::anyhow!("the window closed"))?,
),
CaptureTarget::Area {
rect: [x, y, width, height],
} => Target::Screen(region_target(
x,
y,
width,
height,
&list_selectable_windows(),
)),
CaptureTarget::Phone => Target::Phone {
device: None,
name: None,
},
})
}
/// The names of the cabled iPhones. Blocking: it runs `scrawl-helper
/// devices`, which reads the USB registry and asks for no permission.
fn phones(&self) -> anyhow::Result<Vec<String>> {
Ok(scrawl_capture::helper::devices()?
.into_iter()
.map(|phone| phone.name)
.collect())
}
}
/// What a capture records.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CaptureTarget {
/// The display under the pointer, cropped to what changes: the
/// shortcut's.
Pointer,
/// The whole display holding this point, in global top-left points.
Display { at: [f64; 2] },
/// A window, by its `CGWindowID`
/// (`scrawl_capture::capture::list_selectable_windows`).
Window { id: u32 },
/// A rect in global top-left points, kept to the display holding its
/// centre.
Area { rect: [f64; 4] },
/// The first cabled iPhone ([`CaptureSnapshot::phone`]), mirrored in a
/// window while it records. The narration is Hex's microphone timeline,
/// as for the screen; the mirror opens no microphone.
Phone,
}
impl CaptureTarget {
pub fn kind(self) -> TargetKind {
match self {
Self::Pointer => TargetKind::Pointer,
Self::Display { .. } => TargetKind::Display,
Self::Window { .. } => TargetKind::Window,
Self::Area { .. } => TargetKind::Area,
Self::Phone => TargetKind::Phone,
}
}
}
/// What a recording capture was started on: only the shortcut's
/// (`Pointer`) shows the capsule's switch chips.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TargetKind {
Pointer,
Display,
Window,
Area,
Phone,
}
/// What the capture capsule asks of the host, through
/// `RecognitionControl::CaptureCommand`.
#[derive(Clone, Debug, PartialEq)]
pub enum CaptureCommand {
/// Starts a capture on the picker's pick; nothing while one records.
Start(CaptureTarget),
/// Looks for a cabled iPhone off the listener's thread;
/// [`CaptureSnapshot::phone`] follows. Each start also looks.
FindPhone,
/// Drops the recording capture: its bundle is removed and it never
/// settles, so the capsule can turn into the picker in its place.
Discard,
/// Scrawl's `switch_recording`: drops the recording capture as
/// [`Self::Discard`] does and starts `target` in the same step, so no
/// snapshot shows nothing recording in between. With nothing recording,
/// only starts.
Switch(CaptureTarget),
/// Sends the newest written capture (`snapshot().last`) to `to` now: a
/// session ID, or a name its route lists, suggestions first. A send
/// already elsewhere is taken back first. `always` also saves a rule
/// sending its site or app there from now on.
Send { to: String, always: bool },
/// Takes back the newest capture's send: one OpenCode took is
/// withdrawn unless the session already acted on it.
Undo,
/// Pastes the newest written capture into the app in front, as
/// Scrawl's Paste chip does: its contact sheet, then its summary.
Paste,
/// Opens the newest written capture's contact sheet: Hex has no review
/// window, and opening the bundle could launch Scrawl.app, which takes
/// captures over.
Inspect,
}
/// A started capture.
trait Recording: Send {
/// Stops recording and removes the bundle.
fn cancel(self: Box<Self>);
/// Stops recording the screen, its windows, and input now, keeping what
/// was recorded for [`Sealed::finish`].
fn stop(self: Box<Self>) -> Box<dyn Sealed>;
/// Where the host's pointer and key input goes while it records.
fn input(&self) -> Option<InputSink> {
None
}
}
/// A stopped capture, waiting to be written.
trait Sealed: Send {
/// Removes the bundle.
fn cancel(self: Box<Self>);
/// Blocking: transcribes `audio`, picks keyframes, and writes the
/// bundle.
fn finish(self: Box<Self>, audio: RecordedAudio) -> anyhow::Result<Written>;
/// The apps in front when it stopped, for routing; `None` when it isn't
/// routed.
fn route_context(&self) -> Option<scrawl_capture::capture::RouteContext> {
None
}
}
/// What a written capture reports.
struct Written {
words: usize,
/// Spans of its audio that went missing.
gaps: usize,
/// Why it has no transcript, if it has none.
missing_transcript: Option<String>,
}
impl CaptureEngine for scrawl_capture::capture::Engine {
fn start(&self, start: Start) -> anyhow::Result<Box<dyn Recording>> {
Ok(Box::new(scrawl_capture::capture::Engine::start(
self, start,
)?))
}
}
impl Recording for scrawl_capture::capture::Capture {
fn cancel(self: Box<Self>) {
scrawl_capture::capture::Capture::cancel(*self);
}
fn stop(self: Box<Self>) -> Box<dyn Sealed> {
Box::new(scrawl_capture::capture::Capture::stop(*self))
}
fn input(&self) -> Option<InputSink> {
Some(scrawl_capture::capture::Capture::input(self).clone())
}
}
impl Sealed for scrawl_capture::capture::SealedCapture {
fn cancel(self: Box<Self>) {
scrawl_capture::capture::SealedCapture::cancel(*self);
}
fn finish(self: Box<Self>, audio: RecordedAudio) -> anyhow::Result<Written> {
let finished = scrawl_capture::capture::SealedCapture::finish(*self, Some(audio))?;
tracing::info!(
bundle = %finished.dir.display(),
duration_ms = finished.duration_ms,
summary = %finished.summary,
"capture written"
);
Ok(Written {
words: finished.words,
gaps: finished.gaps,
missing_transcript: finished.missing_transcript,
})
}
fn route_context(&self) -> Option<scrawl_capture::capture::RouteContext> {
Some(scrawl_capture::capture::SealedCapture::route_context(self).clone())
}
}
/// Scrawl's engine with nothing machine-wide: no ingest server (port
/// 47777), delivery retries, or global shortcuts. Hex never calls
/// `install_shared_resources`.
fn scrawl_engine(
events: SyncSender<Event>,
transcriber: Arc<dyn Transcriber>,
) -> scrawl_capture::capture::Engine {
scrawl_capture::capture::Engine::new(Arc::new(HexHost { events }), Arc::new(HexConfig))
.with_resources(SharedResources::none())
.with_transcriber(transcriber)
}
/// What the capture asks for: `target`, on the clock the dictation timeline
/// shares, with Hex's audio and Hex's folder.
fn start_request(t0: CaptureInstant, bundle: PathBuf, target: Target) -> Start {
Start {
t0_boot_ns: t0.as_nanos(),
target,
bundle_dir: Some(bundle),
audio: AudioIn::External,
window_log: true,
note: None,
}
}
/// Forwards events to a bounded channel (the `capture-events` thread logs
/// them) and logs through tracing. Never blocks: a full channel drops the
/// event. `Engine::new` also makes it the crate's process-wide log sink, so
/// the engine's own log lines arrive here once, never in Scrawl's log file.
struct HexHost {
events: SyncSender<Event>,
}
impl Host for HexHost {
fn emit(&self, event: Event) {
if let Err(TrySendError::Full(event)) = self.events.try_send(event) {
tracing::warn!(?event, "capture event queue is full; dropping an event");
}
}
fn log(&self, line: &str) {
tracing::info!("{line}");
}
fn metric(&self, name: &str, ms: f64) {
tracing::debug!(target: "hex::capture", name, ms, "capture metric");
}
fn own_windows(&self) -> OwnWindows {
own_windows_of(
&OWN_WINDOWS
.lock()
.unwrap_or_else(|error| error.into_inner()),
)
}
}
/// What a capture leaves out of its recording (every window Hex named) and
/// looks through for clicks: the ink overlay, and the capsule's panel, which
/// lets clicks through everywhere but its pill. Clicks on the pill never
/// reach the engine ([`CapsulePill`]).
fn own_windows_of(own: &[Option<u32>; 3]) -> OwnWindows {
OwnWindows {
excluded: own.iter().flatten().copied().collect(),
passthrough: [OwnWindow::Ink, OwnWindow::Capsule]
.into_iter()
.filter_map(|role| own[role as usize])
.collect(),
recorded: Arc::clone(&OWN_WINDOWS_RECORDED),
}
}
/// `capture.show_overlays_in_recordings`: while set, a capture records every
/// window of Hex's, its overlays included. A recording capture follows a
/// change at once.
static OWN_WINDOWS_RECORDED: LazyLock<Arc<AtomicBool>> = LazyLock::new(Arc::default);
/// Lets captures record Hex's own windows, or leaves them out again.
pub fn record_own_windows(recorded: bool) {
OWN_WINDOWS_RECORDED.store(recorded, Ordering::Release);
}
/// Whether screen recordings may show Hex's overlays, as last saved.
pub fn own_windows_recorded() -> bool {
OWN_WINDOWS_RECORDED.load(Ordering::Acquire)
}
/// The capsule's pill `[x, y, w, h]` in its panel's points while it shows.
static CAPSULE_PILL: Mutex<Option<[f32; 4]>> = Mutex::new(None);
/// Where the capsule's pill is in its panel while it shows, `None` when it
/// hides: the capsule's panel is far larger than the pill and lets clicks
/// through everywhere else.
pub fn set_capsule_pill(pill: Option<[f32; 4]>) {
*CAPSULE_PILL
.lock()
.unwrap_or_else(|error| error.into_inner()) = pill;
}
/// The capsule's pill in its panel's points, while it shows.
#[cfg(target_os = "linux")]
pub fn capsule_pill() -> Option<[f32; 4]> {
*CAPSULE_PILL
.lock()
.unwrap_or_else(|error| error.into_inner())
}
/// The engine's units per overlay point: Windows' targets, windows, and
/// pointer are physical pixels, and the overlays (on the primary display)
/// lay out in its points; elsewhere both are points.
pub fn pixels_per_point() -> f64 {
#[cfg(target_os = "windows")]
return scrawl_capture::win::primary_monitor().map_or(1.0, |monitor| monitor.scale);
#[cfg(not(target_os = "windows"))]
1.0
}
/// Whether a click lands on the capsule's pill, which takes it, rather than
/// the app beneath. The panel's place comes from the window list, reread at
/// most every 250 ms (scrolls come in bursts); it only moves between
/// captures.
#[derive(Default)]
struct CapsulePill {
panel: Option<(Instant, u32, Option<[f64; 2]>)>,
}
impl CapsulePill {
fn contains(&mut self, x: f64, y: f64) -> bool {
let Some(pill) = *CAPSULE_PILL
.lock()
.unwrap_or_else(|error| error.into_inner())
else {
return false;
};
let Some(window) = OWN_WINDOWS
.lock()
.unwrap_or_else(|error| error.into_inner())[OwnWindow::Capsule as usize]
else {
return false;
};
let origin = match self.panel {
Some((at, id, origin)) if id == window && at.elapsed() < Duration::from_millis(250) => {
origin
}
_ => {
let origin = panel_origin(&scrawl_capture::windows::raw_windows(), window);
self.panel = Some((Instant::now(), window, origin));
origin
}
};
origin.is_some_and(|origin| on_pill(origin, pill, x, y))
}
}
/// The top-left of `window` on screen, in global points.
fn panel_origin(windows: &[scrawl_capture::windows::RawWindow], window: u32) -> Option<[f64; 2]> {
windows
.iter()
.find(|w| w.id == window)
.map(|w| [w.bounds[0], w.bounds[1]])
}
/// Whether global point `(x, y)` is on `pill`, given in the points of a
/// panel whose top-left is `origin`.
fn on_pill(origin: [f64; 2], pill: [f32; 4], x: f64, y: f64) -> bool {
let [px, py, pw, ph] = pill.map(f64::from);
let (left, top) = (origin[0] + px, origin[1] + py);
x >= left && x <= left + pw && y >= top && y <= top + ph
}
/// Hex's windows a capture leaves out of its recording, one per role. A
/// capture reads them when it starts.
static OWN_WINDOWS: Mutex<[Option<u32>; 3]> = Mutex::new([None, None, None]);
/// Which of Hex's windows a capture leaves out.
#[derive(Clone, Copy, Debug)]
pub enum OwnWindow {
/// A panel far larger than the pill: click-through but for the pill
/// ([`set_capsule_pill`]).
Capsule,
/// Click-through, so a click on it never counts as a click on Hex.
Ink,
/// The on-screen picker, hidden before the capture it starts records.
Picker,
}
/// Leaves `window` out of every later capture's recording, replacing the
/// window that last held `role` (Rune may recreate an overlay's window).
pub fn exclude_window(role: OwnWindow, window: u32) {
OWN_WINDOWS
.lock()
.unwrap_or_else(|error| error.into_inner())[role as usize] = Some(window);
}
/// The engine's settings, from Hex rather than `~/.config/scrawl`. The
/// captures folder, retention, and transcriber are Hex's `capture.*`
/// settings, applied by [`CaptureHost`]; the rest are Scrawl's defaults,
/// chosen here: auto-crop on (it applies to display captures), and the
/// `agentContext` summary format off.
struct HexConfig;
impl ConfigSource for HexConfig {
fn engine_config(&self) -> anyhow::Result<EngineConfig> {
Ok(hex_engine_config())
}
}
fn hex_engine_config() -> EngineConfig {
let mut config = EngineConfig::default();
config.autocrop = Some(serde_json::Value::Bool(true));
config
.experiments
.insert(scrawl_capture::handoff::AGENT_CONTEXT.into(), false);
config
}
/// The listener's dictation engine, for the one capture engine's
/// transcriber; replaced when a listener starts captures.
static DICTATION_ENGINE: Mutex<Option<Weak<TranscriptionEngine>>> = Mutex::new(None);
/// Points captures at the listener's new engine after a model change.
#[cfg(not(target_os = "macos"))]
pub fn use_engine(engine: &Arc<TranscriptionEngine>) {
*DICTATION_ENGINE
.lock()
.unwrap_or_else(|error| error.into_inner()) = Some(Arc::downgrade(engine));
}
/// The process's one capture engine (it keeps process-global state), made
/// the first time captures turn on.
fn shared_engine(
dictation: Option<&Arc<TranscriptionEngine>>,
) -> Result<Arc<scrawl_capture::capture::Engine>> {
static ENGINE: Mutex<Option<Arc<scrawl_capture::capture::Engine>>> = Mutex::new(None);
*DICTATION_ENGINE
.lock()
.unwrap_or_else(|error| error.into_inner()) = dictation.map(Arc::downgrade);
let mut engine = ENGINE.lock().unwrap_or_else(|error| error.into_inner());
if let Some(engine) = &*engine {
return Ok(engine.clone());
}
// The portal remembers the screen Hex was given; the token is Hex's.
#[cfg(target_os = "linux")]
if let Ok(support) = crate::app_paths::support_dir() {
scrawl_capture::linux::set_token_path(support.join("screencast-token"));
}
let (events, received) = mpsc::sync_channel(EVENT_CAPACITY);
thread::Builder::new()
.name("capture-events".into())
.spawn(move || log_events(received))?;
let made = Arc::new(scrawl_engine(events, Arc::new(ChosenTranscriber)));
*engine = Some(made.clone());
Ok(made)
}
/// The transcriber `capture.transcriber` names when a capture is written.
struct ChosenTranscriber;
impl Transcriber for ChosenTranscriber {
fn transcribe(&self, audio: &RecordedAudio) -> anyhow::Result<Option<TranscriptData>> {
match crate::app_settings::capture_settings().transcriber {
crate::app_settings::CaptureTranscriber::Parakeet => HexTranscriber {
engine: DICTATION_ENGINE
.lock()
.unwrap_or_else(|error| error.into_inner())
.clone(),
}
.transcribe(audio),
#[cfg(target_os = "macos")]
crate::app_settings::CaptureTranscriber::Apple => {
AppleTranscriber::default().transcribe(audio)
}
// Apple's SpeechAnalyzer is macOS's; elsewhere it is Hex's model.
#[cfg(not(target_os = "macos"))]
crate::app_settings::CaptureTranscriber::Apple => HexTranscriber {
engine: DICTATION_ENGINE
.lock()
.unwrap_or_else(|error| error.into_inner())
.clone(),
}
.transcribe(audio),
}
}
}
/// Word-timed transcription on the dictation engine's loaded model. It holds
/// the engine weakly, so a capture still writing never keeps it alive.
struct HexTranscriber {
engine: Option<Weak<TranscriptionEngine>>,
}
impl Transcriber for HexTranscriber {
/// Word times are milliseconds from `audio.samples[0]`; the engine moves
/// them onto the capture's clock and builds the segments.
fn transcribe(&self, audio: &RecordedAudio) -> anyhow::Result<Option<TranscriptData>> {
let Some(engine) = &self.engine else {
return Ok(None);
};
let samples = if audio.sample_rate == SAMPLE_RATE {
audio.samples.clone()
} else {
crate::dictation::try_resample_for_parakeet(&audio.samples, audio.sample_rate)
.map_err(|error| anyhow::anyhow!(error))?
};
let (_, selection) = crate::app_settings::transcription_selection();
let (text, words) = transcribe_words(engine, &selection, samples)
.map_err(|error| anyhow::anyhow!("{error:#}"))?;
Ok(Some(TranscriptData {
source: "hex".into(),
model: Some(selection.model.as_str().into()),
text,
words: corrected_words(words, word_lag(selection.model)),
..TranscriptData::default()
}))
}
}
/// One word and its times, in ms from the clip's start.
pub struct TimedWord {
pub start_ms: i64,
pub end_ms: i64,
pub text: String,
}
/// The clip's text and words on the dictation engine's warm model.
#[cfg(target_os = "macos")]
fn transcribe_words(
engine: &Weak<TranscriptionEngine>,
selection: &crate::transcription_models::TranscriptionSelection,
samples: Vec<f32>,
) -> Result<(String, Vec<TimedWord>)> {
let transcript = crate::parakeet::transcribe_with_words(engine, selection, samples)?;
let words = transcript
.words
.into_iter()
.map(|word| TimedWord {
start_ms: word.start_ms,
end_ms: word.end_ms,
text: word.text,
})
.collect();
Ok((transcript.text, words))
}
/// The clip's text and words, as one foreground request on the Linux or
/// Windows listener's engine: after the dictation already sent, never inside
/// a live stream. Its model is whatever the listener has loaded.
#[cfg(not(target_os = "macos"))]
fn transcribe_words(
engine: &Weak<TranscriptionEngine>,
_selection: &crate::transcription_models::TranscriptionSelection,
samples: Vec<f32>,
) -> Result<(String, Vec<TimedWord>)> {
if samples.is_empty() {
return Ok((String::new(), Vec::new()));
}
let (send, transcript) = mpsc::sync_channel(1);
let offline: crate::transcription_engine::Offline = Box::new(move |model, samples| {
let (text, words) = model
.transcribe_words(&samples)
.map_err(|error| format!("{error:#}"))?;
let _ = send.send((text.clone(), words));
Ok(text)
});
engine
.upgrade()
.ok_or_else(|| eyre!("the transcription engine stopped"))?
.foreground(samples, offline)?
.wait()
.map_err(|error| eyre!(error))?;
let (text, words) = transcript
.try_recv()
.map_err(|_| eyre!("the transcription returned no words"))?;
let words = words
.into_iter()
.map(|(start_ms, end_ms, text)| TimedWord {
start_ms,
end_ms,
text,
})
.collect();
Ok((text, words))
}
/// How late a model's word times run, in ms: the median against Apple's
/// SpeechAnalyzer on 36 real captures (fitted on half, checked on the
/// other half; no drift, and the 30 s chunk seams cost nothing). Starts run
/// later after a pause.
#[derive(Debug, PartialEq)]
struct WordLag {
start: i64,
/// For a word whose gap since the previous word's end is at least
/// `pause`, and for the first word.
start_after_pause: i64,
pause: i64,
end: i64,
}
/// Each measured model with the pinned file it was measured on. A model or
/// file without an entry keeps its raw times: changing the pin drops the
/// correction until it is measured again (a test fails to say so).
const WORD_LAGS: &[(TranscriptionModelId, &str, WordLag)] = &[(
TranscriptionModelId::ParakeetUnifiedEnglish,
// parakeet-unified-en-0.6b-Q8_0.gguf, measured 2026-10-25.
"4b50b6dd862bf6e346929aaf4f5eaacec003bfa3f56462d6c874b41ef2f38795",
WordLag {
start: 280,
start_after_pause: 520,
pause: 250,
end: 195,
},
)];
fn word_lag(model: TranscriptionModelId) -> Option<&'static WordLag> {
let ModelRuntime::Gguf(artifact) = crate::transcription_models::definition(model).runtime
else {
return None;
};
WORD_LAGS
.iter()
.find(|(id, sha256, _)| *id == model && *sha256 == artifact.sha256)
.map(|(_, _, lag)| lag)
}
/// The model's words in ms from the clip's start, moved earlier by `lag`.
/// Pauses are judged on the raw times. Times stay at 0 or later, each word
/// ends no earlier than it starts, and starts and ends never go backwards.
/// Neighbours may overlap a little, as Apple's times do: starts move further
/// than ends.
fn corrected_words(words: Vec<TimedWord>, lag: Option<&WordLag>) -> Vec<WordTiming> {
let mut previous_end: Option<i64> = None;
let (mut floor_t0, mut floor_t1) = (0, 0);
words
.into_iter()
.map(|word| {
let (mut t0, mut t1) = (word.start_ms, word.end_ms);
if let Some(lag) = lag {
let paused = previous_end.is_none_or(|end| t0 - end >= lag.pause);
previous_end = Some(t1);
t0 -= if paused {
lag.start_after_pause
} else {
lag.start
};
t1 -= lag.end;
}
let t0 = t0.max(floor_t0);
let t1 = t1.max(t0).max(floor_t1);
(floor_t0, floor_t1) = (t0, t1);
WordTiming {
t0: t0 as u64,
t1: t1 as u64,
text: word.text,
}
})
.collect()
}
/// Creates `dir` and missing parents owner-only, and makes `dir` itself
/// owner-only if it already existed.
/// On Windows the folder inherits the profile's ACL, which is the user's.
fn private_dirs(dir: &Path) -> Result<()> {
let mut builder = DirBuilder::new();
builder.recursive(true);
#[cfg(unix)]
builder.mode(0o700);
builder
.create(dir)
.wrap_err_with(|| format!("could not create {}", dir.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(dir, fs::Permissions::from_mode(0o700))
.wrap_err_with(|| format!("could not restrict {}", dir.display()))?;
}
Ok(())
}
/// A fresh owner-only `<captures>/<unix ms>.scrawl` folder; never adopts one
/// that exists. Stamps never repeat within the process: a discarded capture's
/// folder is removed on its collector's thread, so a switch in the same
/// millisecond could otherwise reuse its path while it is still unfinished.
fn new_bundle_dir(captures_dir: &Path) -> Result<PathBuf> {
static LAST_STAMP: Mutex<u128> = Mutex::new(0);
private_dirs(captures_dir)?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis();
let stamp = {
let mut last = LAST_STAMP.lock().unwrap_or_else(|error| error.into_inner());
*last = now.max(*last + 1);
*last
};
for attempt in 0..100 {
let name = match attempt {
0 => format!("{stamp}.scrawl"),
n => format!("{stamp}-{n}.scrawl"),
};
let dir = captures_dir.join(name);
#[cfg_attr(not(unix), allow(unused_mut))]
let mut builder = DirBuilder::new();
#[cfg(unix)]
builder.mode(0o700);
match builder.create(&dir) {
Ok(()) => return Ok(dir),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => {
return Err(error).wrap_err_with(|| format!("could not create {}", dir.display()));
}
}
}
Err(eyre!(
"could not name a new capture in {}",
captures_dir.display()
))
}
/// Makes everything in `dir` owner-only. Scrawl writes its manifest, audio,
/// and frames `0600`, but the movie, the window log, and folders still get
/// the process umask. Windows files inherit the folder's ACL.
#[cfg(not(unix))]
fn restrict_bundle(_: &Path) {}
#[cfg(unix)]
fn restrict_bundle(dir: &Path) {
use std::os::unix::fs::PermissionsExt;
let mut pending = vec![dir.to_path_buf()];
while let Some(dir) = pending.pop() {
let Ok(entries) = fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let Ok(kind) = entry.file_type() else {
continue;
};
let mode = if kind.is_dir() {
pending.push(entry.path());
0o700
} else if kind.is_file() {
0o600
} else {
continue;
};
if let Err(error) = fs::set_permissions(entry.path(), fs::Permissions::from_mode(mode))
{
tracing::warn!(%error, path = %entry.path().display(), "could not restrict a capture file");
}
}
}
}
fn remove_bundle(dir: &Path) {
match fs::remove_dir_all(dir) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => tracing::warn!(%error, bundle = %dir.display(), "could not remove a capture"),
}
}
// ---------------------------------------------------------------------------
// The controller.
/// Where a capture's audio comes from: the dictation timeline.
pub trait AudioTimeline {
fn open_sink(&self, sink: SyncSender<CaptureAudio>, since: CaptureInstant) -> Result<()>;
fn close_sink(&self, through: CaptureInstant) -> Result<Option<CaptureSinkClosed>>;
}
#[cfg(target_os = "macos")]
impl AudioTimeline for DictationAudio {
fn open_sink(&self, sink: SyncSender<CaptureAudio>, since: CaptureInstant) -> Result<()> {
self.open_capture_sink(sink, since)
}
fn close_sink(&self, through: CaptureInstant) -> Result<Option<CaptureSinkClosed>> {
self.close_capture_sink(through)
}
}
/// How the host ends the recording capture.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum End {
/// Written in the background.
Finish,
/// Removed, settling as cancelled.
Cancel,
/// Removed without a trace, for another target ([`CaptureCommand::Discard`]).
Discard,
}
/// How a capture's collector ends.
enum Seal {
Finish {
through: CaptureInstant,
closed: Option<CaptureSinkClosed>,
},
Cancel,
}
struct Active {
bundle: PathBuf,
t0: CaptureInstant,
target: TargetKind,
seal: SyncSender<Seal>,
collector: JoinHandle<()>,
/// "While dictating", held until the capture stops.
quiet: Option<Quiet>,
}
/// A stopped capture and its audio, waiting for the finisher.
struct FinishJob {
bundle: PathBuf,
capture: Box<dyn Sealed>,
audio: RecordedAudio,
/// What the router saw when it stopped, handed over once the job was
/// queued; the sender is dropped without one when captures aren't sent.
look: Receiver<routing::Look>,
}
// ---------------------------------------------------------------------------
// What views see: one snapshot of every capture, published on each change.
/// Every capture Hex knows about, as one value. A view (the capture
/// capsule, the menu bar, `hex capture`) reads it whole instead of reaching