Repository navigation
Expand file tree
/
Copy pathcapture.rs
More file actions
4204 lines (3940 loc) · 149 KB
/
Copy pathcapture.rs
File metadata and controls
4204 lines (3940 loc) · 149 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
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use crate::log::scrawl_log;
use crate::model::{
CaptureMode, InteractionEvent, RgbaFrame, SCALE, Stroke, TargetFrame, TargetInfo,
};
// The operating system side of capture: global shortcuts, input monitoring, the frontmost app,
// displays and windows, and the screen recorder. Each platform module provides the same items.
#[cfg_attr(target_os = "macos", path = "capture/macos.rs")]
#[cfg_attr(target_os = "windows", path = "capture/windows.rs")]
#[cfg_attr(target_os = "linux", path = "capture/linux.rs")]
mod platform;
pub use platform::*;
pub const FRAME_SAMPLE_INTERVAL: Duration = Duration::from_millis(220);
/// Candidate frames only feed scene diffs and keyframe selection; the keyframes themselves are
/// decoded from `recording.mp4` at full size afterwards.
pub const CANDIDATE_EDGE: f64 = 480.0;
/// Without a recording to decode from, the candidates are the keyframes, so keep them sharper.
#[cfg_attr(target_os = "linux", allow(dead_code))]
pub(crate) const CANDIDATE_EDGE_NO_VIDEO: f64 = 1280.0;
/// The candidates' memory ceiling, however long the capture runs.
pub const CANDIDATE_BUDGET_BYTES: usize = 384 << 20;
/// The candidate frames of a capture, bounded in memory. When full it drops every other frame
/// (keeping the first and the ones taken for a click, stroke or shortcut) and samples half as
/// often from then on, so a long capture keeps its whole timeline, evenly, at a coarser step.
pub struct CandidateBuffer {
frames: Vec<(RgbaFrame, bool)>,
cap: usize,
budget: usize,
interval: Duration,
}
impl CandidateBuffer {
pub fn new(budget_bytes: usize) -> Self {
Self {
frames: Vec::new(),
cap: 0,
budget: budget_bytes,
interval: FRAME_SAMPLE_INTERVAL,
}
}
/// How often to sample now.
pub fn interval(&self) -> Duration {
self.interval
}
#[cfg(test)]
fn len(&self) -> usize {
self.frames.len()
}
pub fn push(&mut self, frame: RgbaFrame, urgent: bool) {
if self.cap == 0 {
self.cap = (self.budget / frame.rgba.len().max(1)).clamp(60, 1_200);
}
self.frames.push((frame, urgent));
if self.frames.len() >= self.cap {
self.thin();
}
}
fn thin(&mut self) {
let mut regular = 0_usize;
let mut kept: Vec<(RgbaFrame, bool)> = std::mem::take(&mut self.frames)
.into_iter()
.enumerate()
.filter(|(i, (_, urgent))| {
let keep = *i == 0 || *urgent || regular.is_multiple_of(2);
if !urgent {
regular += 1;
}
keep
})
.map(|(_, f)| f)
.collect();
// Mostly urgent frames (a storm of clicks): thin those too.
if kept.len() > self.cap * 3 / 4 {
kept = kept
.into_iter()
.enumerate()
.filter(|(i, _)| i.is_multiple_of(2))
.map(|(_, f)| f)
.collect();
}
self.frames = kept;
self.interval *= 2;
}
/// Forgets frames taken after `t_ms`, except the first.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub fn drop_since(&mut self, t_ms: u64) {
let mut index = 0;
self.frames.retain(|(frame, _)| {
index += 1;
index == 1 || frame.t_ms <= t_ms
});
}
pub fn into_frames(self) -> Vec<RgbaFrame> {
self.frames.into_iter().map(|(f, _)| f).collect()
}
}
/// What a finished screen capture leaves behind.
pub struct ScreenRecording {
/// Small candidate frames for keyframe selection (see `CANDIDATE_EDGE`).
pub frames: Vec<RgbaFrame>,
/// The movie, which may still be finishing: only what reads it waits ([`Movie::wait`]).
pub video: Option<Movie>,
pub duration_ms: u64,
/// Why there is no picture of the screen, when no frame was recorded: the summary says so
/// instead of showing anything.
pub no_screen: Option<String>,
}
/// Why a screen capture recorded no frame: what the screen source said, or the platform's reason.
pub fn no_screen_reason(failure: Option<String>) -> String {
match failure {
Some(why) => why,
None if screen_capture_usable(false) => "the screen recorded no frames".into(),
None => format!("Screen Recording is off for {}", host_app_name()),
}
}
/// The app this process runs as: its `.app` bundle's name, else its executable's.
fn host_app_name() -> String {
let exe = std::env::current_exe().unwrap_or_default();
exe.ancestors()
.find(|dir| dir.extension().is_some_and(|ext| ext == "app"))
.unwrap_or(&exe)
.file_stem()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| "this app".into())
}
impl ScreenRecording {
/// Blocks until nothing writes the movie any more, so its bundle can be removed.
pub fn discard(self) {
if let Some(movie) = self.video {
let _ = movie.wait();
}
}
}
/// A screen capture's movie. On macOS its file is still being finished when the capture stops:
/// the recording output closes it and its final frame is held to the stop.
pub struct Movie {
path: PathBuf,
state: MovieState,
}
enum MovieState {
Written {
offset_ms: u64,
},
#[cfg(target_os = "macos")]
Finishing(platform::FinishingMovie),
}
impl Movie {
/// A movie already written, starting `offset_ms` into the capture (on the frames' clock).
pub fn written(path: PathBuf, offset_ms: u64) -> Self {
Self {
path,
state: MovieState::Written { offset_ms },
}
}
#[cfg(target_os = "macos")]
pub(crate) fn finishing(path: PathBuf, finishing: platform::FinishingMovie) -> Self {
Self {
path,
state: MovieState::Finishing(finishing),
}
}
/// Where the movie is, finished or not.
pub fn path(&self) -> &Path {
&self.path
}
/// When the movie starts on the frames' clock, before it finishes: exact once written, an
/// estimate from when its recording started while it finishes.
pub fn offset_hint_ms(&self) -> u64 {
match &self.state {
MovieState::Written { offset_ms } => *offset_ms,
#[cfg(target_os = "macos")]
MovieState::Finishing(finishing) => finishing.offset_hint_ms(),
}
}
/// Blocks until the movie is finished. Returns its path and when it starts on the frames'
/// clock, or `None` when nothing playable was left.
pub fn wait(self) -> Option<(PathBuf, u64)> {
let offset_ms = match self.state {
MovieState::Written { offset_ms } => Some(offset_ms),
#[cfg(target_os = "macos")]
MovieState::Finishing(finishing) => finishing.wait(),
}?;
let written = self
.path
.metadata()
.is_ok_and(|m| m.is_file() && m.len() > 0);
written.then_some((self.path, offset_ms))
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Stage {
Recording,
Stopping,
Transcribing,
Rendering,
Writing,
Done,
Cancelled,
Failed,
}
impl Stage {
pub fn label(self) -> &'static str {
match self {
Self::Recording => "recording",
Self::Stopping => "stopping",
Self::Transcribing => "transcribing",
Self::Rendering => "rendering",
Self::Writing => "writing",
Self::Done => "done",
Self::Cancelled => "cancelled",
Self::Failed => "failed",
}
}
}
/// Live engine events emitted by the global input monitor, iPhone mirror and ingest server.
#[derive(Clone, Debug)]
pub enum Event {
/// ⌥⇧S (or the configured shortcut) went down; `shortcut::Shortcut` decides what it means.
CaptureShortcut,
PasteLatestShortcut,
RequestSnapshot,
/// The iPhone mirror ended on its own (unplugged, never found, or access denied).
PhoneEnded,
/// Lifecycle progress of an active or finishing capture.
Progress {
bundle: PathBuf,
stage: Stage,
},
/// A ScrawlKit recording was ingested from an iPhone and compiled into a `.scrawl` bundle.
IngestedBundle {
dir: PathBuf,
bundle: Box<crate::model::ScrawlBundle>,
status: Option<String>,
},
/// A capture bundle was delivered (or queued for retry) to a destination.
Delivered {
dir: PathBuf,
delivery: crate::delivery::Delivery,
},
}
#[derive(Clone, Debug, Default)]
pub struct OwnWindows {
/// Window IDs excluded from ScreenCaptureKit / Windows.Graphics.Capture recordings.
pub excluded: Vec<u32>,
/// Click-through window IDs (such as the ink overlay) ignored when checking whether a click
/// landed on the host's own UI.
pub passthrough: Vec<u32>,
/// Set, the recording shows the host's own windows: neither `excluded` nor the host's
/// other non-layer-0 windows are left out. Read while recording, so the host can flip it
/// mid-capture (a demo that shows the host's overlays).
pub recorded: Arc<AtomicBool>,
}
/// What the host provides. Every method has a default except `emit`; `emit` and `log` must return
/// without blocking.
pub trait Host: Send + Sync + 'static {
fn emit(&self, event: Event);
fn log(&self, line: &str) {
scrawl_log(line);
}
fn metric(&self, name: &str, ms: f64) {
crate::log::record_metric(name, ms);
}
fn clipboard(&self) -> Option<&dyn crate::handoff::Clipboard> {
None
}
/// Window IDs to leave out of recordings (overlay, capsule, host windows) and to let clicks
/// through (`excluded_window_ids` / `passthrough_window_ids`).
fn own_windows(&self) -> OwnWindows {
OwnWindows::default()
}
}
pub struct ChannelHost {
sender: flume::Sender<Event>,
}
impl ChannelHost {
pub fn new(sender: flume::Sender<Event>) -> Self {
Self { sender }
}
}
impl Host for ChannelHost {
fn emit(&self, event: Event) {
let _ = self.sender.try_send(event);
}
}
pub trait ConfigSource: Send + Sync {
fn engine_config(&self) -> Result<crate::handoff::EngineConfig>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct DefaultConfigSource;
impl ConfigSource for DefaultConfigSource {
fn engine_config(&self) -> Result<crate::handoff::EngineConfig> {
Ok(crate::handoff::engine_config())
}
}
#[derive(Clone, Debug, Default)]
pub enum Target {
/// Discover the display under the cursor (or focused window) when starting.
#[default]
ActiveDisplay,
/// Record a specific screen, window or region target.
Screen(TargetInfo),
/// Record a cabled iPhone (either a new session for `device` or an existing preview). With
/// [`AudioIn::External`] the mirror opens no microphone and `finish`'s audio is the
/// narration; otherwise the mirror records the Mac's microphone into the movie.
Phone {
device: Option<String>,
name: Option<String>,
},
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum AudioIn {
/// No engine-managed microphone stream; the host passes `Option<RecordedAudio>` to `finish`.
#[default]
External,
/// No audio at all.
None,
/// Open Scrawl's built-in `AudioRecorder` stream.
Microphone,
}
/// How a screen capture's movie is recorded (macOS; elsewhere always compact).
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum MovieQuality {
/// Sized for agents: H.264, 1280 px long edge (2560 for a whole display, for crops).
#[default]
Compact,
/// For people: hardware HEVC (`capture_core::Encoder::Hevc`) at the size, frame rate, and
/// quality asked.
Full(MovieSize),
}
/// A [`MovieQuality::Full`] movie's size, frame rate, and quality.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MovieSize {
/// At most one pixel a point, so a Retina display records at its size in points.
pub one_x: bool,
/// The longest side in pixels; `None` keeps the source's (or one pixel a point's).
pub long_edge: Option<u32>,
pub fps: u32,
/// HEVC's constant quality, in hundredths.
pub quality: u8,
/// Also records other apps' audio (never Hex's) into `system.m4a`.
pub system_audio: bool,
}
impl Default for MovieSize {
/// Every pixel at up to 60 fps, at `capture_core`'s quality for Retina text.
fn default() -> Self {
Self {
one_x: false,
long_edge: None,
fps: 60,
quality: 70,
system_audio: false,
}
}
}
impl MovieSize {
/// The long edge a source `points` large records at: one pixel a point with
/// [`Self::one_x`], capped at [`Self::long_edge`]. `None` keeps every pixel.
pub fn long_edge_for(self, points: (f64, f64)) -> Option<u32> {
let longest = points.0.max(points.1);
let one_x =
(self.one_x && longest.is_finite() && longest >= 1.0).then(|| longest.round() as u32);
match (one_x, self.long_edge) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}
}
mod start;
mod token;
pub use start::Start;
pub use token::{OutputBounds, PortalToken};
#[derive(Clone, Debug, Default)]
pub struct RouteContext {
pub front_bundle_id: Option<String>,
pub captured_bundle_id: Option<String>,
pub app_pid: Option<i32>,
}
#[derive(Clone, Debug)]
pub struct Finished {
pub dir: PathBuf,
pub bundle: crate::model::ScrawlBundle,
pub summary: String,
pub words: usize,
pub duration_ms: u64,
pub route_hint: RouteContext,
/// Number of audio gap spans where microphone samples were missing or dropped (`RecordedAudio::gaps`).
pub gaps: usize,
/// Structured reason when no transcript was produced (`"no_audio"` when no audio was
/// captured, or `bundle.transcript.missing.reason` when transcription failed or is pending).
pub missing_transcript: Option<String>,
}
// Carbon HIToolbox modifier bits. The shortcut is stored with them on every platform.
pub const CARBON_CMD_KEY: u32 = 1 << 8;
pub const CARBON_SHIFT_KEY: u32 = 1 << 9;
pub const CARBON_OPTION_KEY: u32 = 1 << 11;
pub const CARBON_CONTROL_KEY: u32 = 1 << 12;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ShortcutConfig {
pub key_code: u32,
pub carbon_modifiers: u32,
pub label: String,
}
impl Default for ShortcutConfig {
fn default() -> Self {
Self::default_record()
}
}
/// Scrawl's two global shortcuts.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ShortcutKind {
/// Start, switch or finish a recording (⌥⇧S).
Record,
/// Paste the latest capture into the app in front (⌥⇧V).
Paste,
}
impl ShortcutKind {
pub const ALL: [Self; 2] = [Self::Record, Self::Paste];
pub fn default_config(self) -> ShortcutConfig {
match self {
Self::Record => ShortcutConfig::default_record(),
Self::Paste => ShortcutConfig::default_paste(),
}
}
/// The letter of the default, on the active layout (Dvorak's S is not ANSI's).
fn default_char(self) -> char {
match self {
Self::Record => 's',
Self::Paste => 'v',
}
}
pub(crate) fn ansi_code(self) -> u16 {
match self {
Self::Record => KEY_S,
Self::Paste => KEY_V,
}
}
pub fn name(self) -> &'static str {
match self {
Self::Record => "Record",
Self::Paste => "Paste last capture",
}
}
/// Whether it can be turned off. Record can't: it's the way into Scrawl.
pub fn can_unset(self) -> bool {
self == Self::Paste
}
}
impl ShortcutConfig {
pub fn default_record() -> Self {
Self {
key_code: u32::from(layout_s_keycode()),
carbon_modifiers: CARBON_OPTION_KEY | CARBON_SHIFT_KEY,
label: shortcut_label(CARBON_OPTION_KEY | CARBON_SHIFT_KEY, "S"),
}
}
pub fn default_paste() -> Self {
Self {
key_code: u32::from(layout_v_keycode()),
carbon_modifiers: CARBON_OPTION_KEY | CARBON_SHIFT_KEY,
label: shortcut_label(CARBON_OPTION_KEY | CARBON_SHIFT_KEY, "V"),
}
}
pub fn defaults() -> (Self, Self) {
(Self::default_record(), Self::default_paste())
}
/// Default shortcuts using ANSI key codes (`KEY_S`, `KEY_V`) without querying macOS TIS/TSM,
/// safe to call off the main thread.
pub fn ansi_defaults() -> (Self, Self) {
(
Self {
key_code: u32::from(KEY_S),
carbon_modifiers: CARBON_OPTION_KEY | CARBON_SHIFT_KEY,
label: shortcut_label(CARBON_OPTION_KEY | CARBON_SHIFT_KEY, "S"),
},
Self {
key_code: u32::from(KEY_V),
carbon_modifiers: CARBON_OPTION_KEY | CARBON_SHIFT_KEY,
label: shortcut_label(CARBON_OPTION_KEY | CARBON_SHIFT_KEY, "V"),
},
)
}
/// No shortcut: nothing is registered and no key press matches. Only the paste shortcut can
/// be turned off.
pub fn unset() -> Self {
Self {
key_code: u32::MAX,
carbon_modifiers: 0,
label: String::new(),
}
}
pub fn is_unset(&self) -> bool {
self.label.is_empty()
}
/// Whether this is `kind`'s default, which also answers to its aliases (⌃⌥⇧, ⌘⌥⇧, ⌃⌥⌘
/// and the ANSI key).
pub fn is_default_for(&self, kind: ShortcutKind) -> bool {
self.carbon_modifiers == CARBON_OPTION_KEY | CARBON_SHIFT_KEY
&& shortcut_parts(&self.label).1 == kind.default_char().to_ascii_uppercase().to_string()
}
pub fn key_label(&self) -> &str {
shortcut_parts(&self.label).1
}
}
/// `⌃⌥⇧⌘` in the order macOS writes them, for Carbon modifier bits; on Windows the same
/// modifiers as `Ctrl+Win+Alt+Shift+` (ready to take a key).
pub fn modifier_symbols(carbon_modifiers: u32) -> String {
if cfg!(target_os = "windows") {
let label = shortcut_label(carbon_modifiers, "");
return label;
}
[
(CARBON_CONTROL_KEY, '⌃'),
(CARBON_OPTION_KEY, '⌥'),
(CARBON_SHIFT_KEY, '⇧'),
(CARBON_CMD_KEY, '⌘'),
]
.into_iter()
.filter(|(bit, _)| carbon_modifiers & bit != 0)
.map(|(_, symbol)| symbol)
.collect()
}
/// A shortcut as this platform writes it: `⌥⇧S` on macOS, `Alt+Shift+S` on Windows.
pub fn shortcut_label(carbon_modifiers: u32, key: &str) -> String {
let held = |bit: u32| carbon_modifiers & bit != 0;
if cfg!(target_os = "windows") {
let mut parts = Vec::new();
for (bit, name) in [
(CARBON_CONTROL_KEY, "Ctrl"),
(CARBON_CMD_KEY, "Win"),
(CARBON_OPTION_KEY, "Alt"),
(CARBON_SHIFT_KEY, "Shift"),
] {
if held(bit) {
parts.push(name);
}
}
parts.push(key);
parts.join("+")
} else {
let mut label = String::new();
for (bit, glyph) in [
(CARBON_CONTROL_KEY, '⌃'),
(CARBON_OPTION_KEY, '⌥'),
(CARBON_SHIFT_KEY, '⇧'),
(CARBON_CMD_KEY, '⌘'),
] {
if held(bit) {
label.push(glyph);
}
}
label.push_str(key);
label
}
}
/// The system paste keystroke: `⌘V` on macOS, `Ctrl+V` on Windows.
pub fn system_paste_label() -> &'static str {
if cfg!(target_os = "windows") {
"Ctrl+V"
} else {
"⌘V"
}
}
/// The keys of a shortcut label, one per keycap: `⌥⇧S` → `⌥`, `⇧`, `S`; `Alt+Shift+S` →
/// `Alt`, `Shift`, `S`.
pub fn shortcut_keys(label: &str) -> Vec<String> {
if label.contains('+') && label.len() > 1 {
let mut keys: Vec<String> = label
.split('+')
.filter(|key| !key.is_empty())
.map(str::to_owned)
.collect();
// `Ctrl++` binds the plus key itself.
if label.ends_with("++") {
keys.push("+".into());
}
keys
} else {
label.chars().map(String::from).collect()
}
}
/// A shortcut label split into its modifiers and key: `⌥⇧S` → (`⌥⇧`, `S`), and on Windows
/// `Alt+Shift+S` → (`Alt+Shift`, `S`).
pub fn shortcut_parts(label: &str) -> (&str, &str) {
// The key itself may be "+" (`Ctrl++`), or a letter outside ASCII.
let before_key = label.char_indices().last().map_or("", |(i, _)| &label[..i]);
if let Some(plus) = before_key.rfind('+') {
return (&label[..plus], &label[plus + 1..]);
}
let split = label
.char_indices()
.find(|(_, c)| !matches!(c, '⌃' | '⌥' | '⇧' | '⌘'))
.map_or(label.len(), |(i, _)| i);
label.split_at(split)
}
/// Whether a key press is the record shortcut. A custom one matches exactly; the default ⌥⇧S
/// also answers with ⌃ or ⌘ added and as ⌃⌥⌘S, on the active layout's S key (`s_code`) or the
/// ANSI one.
pub fn is_capture_shortcut(
cfg: &ShortcutConfig,
s_code: u16,
keycode: u16,
cmd: bool,
ctrl: bool,
alt: bool,
shift: bool,
) -> bool {
shortcut_matches(
ShortcutKind::Record,
cfg,
s_code,
keycode,
cmd,
ctrl,
alt,
shift,
)
}
/// `is_capture_shortcut` for any of Scrawl's shortcuts; `layout_code` is the default key on the
/// active layout.
#[allow(clippy::too_many_arguments)]
pub fn shortcut_matches(
kind: ShortcutKind,
cfg: &ShortcutConfig,
layout_code: u16,
keycode: u16,
cmd: bool,
ctrl: bool,
alt: bool,
shift: bool,
) -> bool {
if cfg.is_unset() {
return false;
}
let want_cmd = (cfg.carbon_modifiers & CARBON_CMD_KEY) != 0;
let want_ctrl = (cfg.carbon_modifiers & CARBON_CONTROL_KEY) != 0;
let want_alt = (cfg.carbon_modifiers & CARBON_OPTION_KEY) != 0;
let want_shift = (cfg.carbon_modifiers & CARBON_SHIFT_KEY) != 0;
let exact = u32::from(keycode) == cfg.key_code
&& cmd == want_cmd
&& ctrl == want_ctrl
&& alt == want_alt
&& shift == want_shift;
if exact {
return true;
}
let is_key = keycode == layout_code || keycode == kind.ansi_code();
cfg.is_default_for(kind) && is_key && alt && (shift || (ctrl && cmd))
}
/// The active layout's key for `kind`'s default letter (Windows' hooks and poller match on it).
#[cfg_attr(target_os = "macos", allow(dead_code))]
pub fn layout_default_keycode(kind: ShortcutKind) -> u16 {
key_code_for_char(kind.default_char()).unwrap_or(kind.ansi_code())
}
/// The key codes and Carbon modifiers `cfg` registers: itself, plus for a default its aliases
/// (⌃⌥⇧, ⌘⌥⇧, ⌃⌥⌘) on the active layout's key and the ANSI one.
pub fn hotkey_combos(kind: ShortcutKind, cfg: &ShortcutConfig) -> Vec<(u32, u32)> {
if cfg.is_unset() {
return Vec::new();
}
let mut combos = vec![(cfg.key_code, cfg.carbon_modifiers)];
if !cfg.is_default_for(kind) {
return combos;
}
let mut codes = vec![cfg.key_code];
if cfg.key_code != u32::from(kind.ansi_code()) {
codes.push(u32::from(kind.ansi_code()));
}
for code in codes {
for mods in [
CARBON_OPTION_KEY | CARBON_SHIFT_KEY,
CARBON_CONTROL_KEY | CARBON_OPTION_KEY | CARBON_SHIFT_KEY,
CARBON_CMD_KEY | CARBON_OPTION_KEY | CARBON_SHIFT_KEY,
CARBON_CONTROL_KEY | CARBON_OPTION_KEY | CARBON_CMD_KEY,
] {
if !combos.contains(&(code, mods)) {
combos.push((code, mods));
}
}
}
combos
}
#[cfg_attr(target_os = "linux", allow(dead_code))]
fn clean_label(input: &str) -> String {
let squashed = input.split_whitespace().collect::<Vec<_>>().join(" ");
let trimmed = squashed.trim();
if trimmed.chars().count() > 44 {
let prefix: String = trimmed.chars().take(43).collect();
format!("{}…", prefix.trim_end())
} else {
trimmed.to_string()
}
}
/// Which display to record: the one under `point`, else the one holding the focused window's
/// centre, else the first. Frames and points are global, top-left origin.
pub fn pick_display(
displays: &[[f64; 4]],
point: Option<[f64; 2]>,
focused: Option<[f64; 4]>,
) -> usize {
let inside = |p: [f64; 2]| {
displays
.iter()
.position(|&[x, y, w, h]| p[0] >= x && p[0] < x + w && p[1] >= y && p[1] < y + h)
};
point
.and_then(inside)
.or_else(|| focused.and_then(|[x, y, w, h]| inside([x + w / 2.0, y + h / 2.0])))
.unwrap_or(0)
}
pub fn selectable_window_at(windows: &[TargetInfo], x: f64, y: f64) -> Option<&TargetInfo> {
windows.iter().find(|window| {
let f = window.frame;
x >= f.x && x <= f.x + f.width && y >= f.y && y <= f.y + f.height
})
}
/// Resolves region metadata from the picker's snapshot, without another SCK query.
pub fn region_target(
x: f64,
y: f64,
width: f64,
height: f64,
windows: &[TargetInfo],
) -> TargetInfo {
let mid_x = x + width * 0.5;
let mid_y = y + height * 0.5;
let hit = selectable_window_at(windows, mid_x, mid_y);
let frontmost = frontmost_app_info();
// One display per recording: the area's (by its centre), trimmed to that display and at
// least `MIN_AREA` a side inside it, so this frame is exactly the recorded `sourceRect`.
let screens = crate::screens::displays();
let (display_id, scale, [x, y, width, height]) =
crate::screens::area_on_display(&screens, [x, y, width, height]).map_or_else(
|| {
let min = crate::screens::MIN_AREA;
let rect = [x, y, width.max(min), height.max(min)];
(main_display_id(), MAX_CAPTURE_SCALE, rect)
},
|(i, rect)| (screens[i].id, screens[i].scale, rect),
);
TargetInfo {
mode: CaptureMode::Region,
app: hit
.and_then(|window| window.app.clone())
.or_else(|| frontmost.as_ref().map(|(_, name, _)| name.clone())),
bundle_id: hit
.and_then(|window| window.bundle_id.clone())
.or_else(|| frontmost.and_then(|(_, _, bid)| bid)),
window_title: hit.and_then(|window| window.window_title.clone()),
window_id: None,
display_id,
frame: TargetFrame {
x,
y,
width,
height,
scale,
},
}
}
/// The capture size for `target` with its long edge at most `long_edge` px (and at most its
/// display's pixels: a 1x display isn't upscaled, and on Windows frames are pixels already,
/// `MAX_CAPTURE_SCALE`).
pub fn capture_size(target: &TargetInfo, long_edge: f64) -> (u32, u32) {
let max_dim = target.frame.width.max(target.frame.height).max(1.0);
let native = target.frame.scale.clamp(1.0, MAX_CAPTURE_SCALE);
let scale = (long_edge / max_dim).min(native);
(
((target.frame.width * scale).round() as u32).max(48) & !1,
((target.frame.height * scale).round() as u32).max(48) & !1,
)
}
/// What the platform's sampler thread records into. It runs until `stopping`, pushes candidate
/// frames (at once when `urgent`), and returns the movie it recorded.
pub(crate) struct Sampler {
pub target: TargetInfo,
pub video_output_path: Option<PathBuf>,
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub movie_quality: MovieQuality,
/// The screen-cast portal's token choice; ignored off Linux.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub portal_token: PortalToken,
/// Scrawl's own windows to leave out of the recording.
#[cfg_attr(any(target_os = "windows", target_os = "linux"), allow(dead_code))]
pub excluded_window_ids: Arc<Mutex<Vec<u32>>>,
/// [`OwnWindows::recorded`]: while set, nothing of the host's is left out.
#[cfg_attr(any(target_os = "windows", target_os = "linux"), allow(dead_code))]
pub own_windows_recorded: Arc<AtomicBool>,
pub started_at: Instant,
/// `started_at` on the host clock, which places the movie's start on the frames' clock.
#[cfg(target_os = "macos")]
pub started_host: capture_core::HostTime,
pub stopping: Arc<AtomicBool>,
pub urgent: Arc<AtomicBool>,
pub frames: Arc<Mutex<CandidateBuffer>>,
/// Why the screen source gave up before the stop (Linux: the portal's picker was cancelled
/// or the stream never started), so the host can end the capture.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub failure: Arc<Mutex<Option<String>>>,
/// Where the Windows recorder stores when its movie started (ms since `started_at`).
#[cfg(target_os = "windows")]
pub video_offset_ms: Arc<AtomicU64>,
}
/// Active screen + optional MP4 recorder (ScreenCaptureKit on macOS, Windows.Graphics.Capture
/// and Media Foundation on Windows).
pub struct ScreenCaptureSession {
started_at: Instant,
stopping: Arc<AtomicBool>,
urgent_snapshot: Arc<AtomicBool>,
frames: Arc<Mutex<CandidateBuffer>>,
failure: Arc<Mutex<Option<String>>>,
sampler_thread: Option<JoinHandle<Option<Movie>>>,
_recording: crate::retention::Recording,
}
impl ScreenCaptureSession {
pub fn start(
target: TargetInfo,
video_output_path: Option<PathBuf>,
excluded_window_ids: Arc<Mutex<Vec<u32>>>,
) -> Self {
Self::start_with_budget(
target,
video_output_path,
excluded_window_ids,
Arc::default(),
CANDIDATE_BUDGET_BYTES,
MovieQuality::Compact,
PortalToken::None,
)
}
pub fn start_with_budget(
target: TargetInfo,
video_output_path: Option<PathBuf>,
excluded_window_ids: Arc<Mutex<Vec<u32>>>,
own_windows_recorded: Arc<AtomicBool>,
budget_bytes: usize,
movie_quality: MovieQuality,
portal_token: PortalToken,
) -> Self {
let started_at = Instant::now();
#[cfg(target_os = "macos")]
let started_host = capture_core::HostTime::now();
let stopping = Arc::new(AtomicBool::new(false));
let urgent_snapshot = Arc::new(AtomicBool::new(true));
let frames = Arc::new(Mutex::new(CandidateBuffer::new(budget_bytes)));
let thread_stopping = Arc::clone(&stopping);
let thread_urgent = Arc::clone(&urgent_snapshot);
let thread_frames = Arc::clone(&frames);
let failure = Arc::new(Mutex::new(None));
let thread_failure = Arc::clone(&failure);
let sampler_target = target;
let sampler_thread = thread::Builder::new()
.name("scrawl-frame-sampler".into())
.spawn(move || {
platform::run_sampler(Sampler {
target: sampler_target,
video_output_path,
movie_quality,
portal_token,
excluded_window_ids,
own_windows_recorded,
started_at,
#[cfg(target_os = "macos")]
started_host,
stopping: thread_stopping,
urgent: thread_urgent,
frames: thread_frames,
failure: thread_failure,
#[cfg(target_os = "windows")]
video_offset_ms: Arc::new(AtomicU64::new(0)),
})
})
.ok();
Self {
started_at,
stopping,
urgent_snapshot,
frames,
failure,
sampler_thread,
_recording: crate::retention::Recording::start(),
}
}
/// Why the screen source gave up before the stop, if it did: nothing more of the screen
/// will be recorded.
pub fn failure(&self) -> Option<String> {
self.failure
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
pub fn request_immediate_frame(&self) {
self.urgent_snapshot.store(true, Ordering::Release);
if let Some(ref handle) = self.sampler_thread {
handle.thread().unpark();
}
}
pub fn elapsed_ms(&self) -> u64 {
self.started_at.elapsed().as_millis() as u64
}
/// Stops at once: the movie keeps finishing on its own (see [`Movie`]).
pub fn stop(mut self) -> ScreenRecording {
let duration_ms = self.elapsed_ms();
self.stopping.store(true, Ordering::Release);
let video = self
.sampler_thread
.take()
.and_then(|handle| {
handle.thread().unpark();
handle.join().ok()
})