Repository navigation
Expand file tree
/
Copy pathmod.rs
More file actions
1412 lines (1328 loc) · 50 KB
/
Copy pathmod.rs
File metadata and controls
1412 lines (1328 loc) · 50 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 capsule on Rune: Scrawl's capsule (its picker, recording,
//! processing, and finished states, and the router's list) in a
//! click-through overlay at the top of the screen. Only its shell and
//! controls take clicks; it never takes focus.
//!
//! [`flow`] decides what it shows from the capture's stages, the router's
//! answer, and the capture input's keys; [`surface`] decides where every
//! piece rests and which spring moves it; the view below only draws that,
//! and Rune's springs animate between commits. The red dot, the spinner,
//! the shimmer on "Processing…", and the edge glow animate through `Live`
//! values a meter thread publishes, and the timer through a `LiveText`,
//! without re-running the view.
//!
//! Ported from Scrawl's Rune capsule (`scrawl-pill-lab`, `rune_pill`); its
//! colours are the OpenCode theme's, so it follows the system appearance.
mod always_view;
mod dock;
pub(crate) mod feed;
pub(crate) mod flow;
pub(crate) mod ink;
mod list_view;
pub(crate) mod notch;
pub(crate) mod picker;
#[cfg(target_os = "macos")]
pub(crate) mod playground;
#[cfg(target_os = "macos")]
pub(crate) mod recording_dim;
pub(crate) mod surface;
#[cfg(target_os = "macos")]
pub(crate) mod toolbar;
pub(crate) mod tuning;
mod undo_ring;
mod view;
// The macOS fixture is also rendered on the Linux golden runner.
#[cfg(all(test, any(target_os = "macos", target_os = "linux")))]
mod tests;
use std::cell::Cell;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use rune::{
Color, Compositor, Cx, El, Frame, LineCap, Live, LiveText, OverlayHandle, Path, Runtime, Shape,
SpringPair, Transition, Tx, canvas, col, el, row, text,
};
use rune_kit::TextInput;
use self::flow::{Action, Cue, Done, Flow, Footer, Input, Lead, List, Mode, Pres};
use self::list_view::*;
use self::surface::{
CHIP_H, CHIP_PX, HEADER_H, HINT_GAP, Id, LEAD_TEXT_X, LEVEL_GAP, LEVEL_W, LIST_PAD, LIST_Y,
PANEL_H, PANEL_W, PROCESSING_TEXT_X, ROW_H, SEG_ICON, SEG_ICON_GAP, Shown, Surface, THUMB_H,
THUMB_RADIUS, THUMB_W, THUMB_X, chord, clock_width, corner, done_style, done_text_x, ellipsize,
measure, medium, processing, small,
};
use self::tuning::ListFooter;
use self::view::*;
use super::controls::{CAPSULE, Paint};
use crate::desktop::i18n::{tr, tr_fill};
/// Peak blur (pt) of the picker's badge and the list's rows softening in
/// place.
const PRESENCE_BLUR: f32 = 1.5;
/// How long the capsule's exit gets before its overlay hides, in animation
/// seconds.
const HIDE_AFTER_S: f64 = 0.5;
/// The list's corners, and its rows'.
const LIST_RADIUS: f32 = surface::SHELL_RADIUS;
const ROW_RADIUS: f32 = CAPSULE.inner(CAPSULE.row_inset);
const ROW_PX: f32 = CAPSULE.row_px;
/// Under the list header's words.
const HEADER_PB: f32 = 4.0;
/// Between one hint and the next.
const HINTS_GAP: f32 = 16.0;
/// The list footer's band (A) and well (B).
const BAND_H: f32 = 32.0;
const WELL_H: f32 = 28.0;
/// The list slides down this far as it fades in.
const LIST_DROP: f32 = 6.0;
// ─── Live values ─────────────────────────────────────────────────────────────
/// Room for "Processing…" in the longest language.
const GLYPHS: usize = 24;
/// "Processing…" split into glyphs, each with its x and width as the whole
/// label shapes them.
fn processing_glyphs() -> [(char, f32, f32); GLYPHS] {
let mut out = [(' ', 0.0, 0.0); GLYPHS];
let label = processing();
for (k, (at, c)) in label.char_indices().enumerate().take(GLYPHS) {
let end = at + c.len_utf8();
let x = if at == 0 {
0.0
} else {
measure(&label[..at], medium())
};
out[k] = (c, x, measure(&label[..end], medium()) - x);
}
out
}
/// What the meter thread animates.
#[derive(Clone)]
struct Meter {
/// The dot's core breath, and its ripple ring's scale and fade (one
/// 1.6 s cycle).
core: Live<f32>,
ring_scale: Live<f32>,
ring_alpha: Live<f32>,
/// The spinner's eight dots.
spin: [Live<f32>; 8],
/// "Processing…" one glyph each, lit by a band of light passing across.
shimmer: [Live<f32>; GLYPHS],
/// Each glyph's centre across the label, 0…1.
shimmer_at: [f32; GLYPHS],
/// The glow inside the capsule's edge while it changes width.
glow: Live<f32>,
/// The microphone's level after the timer: each bar's rect, and how
/// lit they are.
level_bars: [Live<[f32; 4]>; 3],
level_ink: Live<f32>,
/// The level the bars show and the animation second it was last
/// followed at.
heard: Arc<Mutex<(f32, f64)>>,
/// A morph's settle time in seconds (`f32` bits) for the thread to
/// start a glow; 0 when none.
kick: Arc<AtomicU32>,
/// 0 idle, 1 recording, 2 processing.
activity: Arc<AtomicU8>,
reduced: Arc<AtomicBool>,
glowing: Arc<Mutex<Glow>>,
thread: Arc<OnceLock<std::thread::Thread>>,
}
#[derive(Default)]
struct Glow {
/// When the morph started, its settle time, and the level it rose from.
since: Option<(f64, f32, f32)>,
level: f32,
}
/// The edge glow `dt` seconds into a morph that settles in `settle`: from
/// `from` up to 1 over 0.05 s, then critically damped back to 0.
fn glow_at(dt: f32, settle: f32, from: f32) -> f32 {
const RISE: f32 = 0.05;
if dt < RISE {
return from + (1.0 - from) * dt / RISE;
}
let w = std::f32::consts::TAU / settle.max(0.2);
let t = dt - RISE;
(1.0 + w * t) * (-w * t).exp()
}
impl Meter {
fn new() -> Self {
let meter = Self {
core: Live::new(1.0),
ring_scale: Live::new(0.4),
ring_alpha: Live::new(0.0),
spin: std::array::from_fn(|_| Live::new(0.18)),
shimmer: std::array::from_fn(|_| Live::new(1.0)),
shimmer_at: {
let total = measure(processing(), medium()).max(1.0);
let glyphs = processing_glyphs();
std::array::from_fn(|k| (glyphs[k].1 + glyphs[k].2 * 0.5) / total)
},
glow: Live::new(0.0),
level_bars: std::array::from_fn(|k| Live::new(level_bar(k, 0.0))),
level_ink: Live::new(level_ink(0.0)),
heard: Arc::default(),
kick: Arc::default(),
activity: Arc::default(),
reduced: Arc::default(),
glowing: Arc::default(),
thread: Arc::default(),
};
meter.publish(0.0);
meter
}
/// The looping values at animation second `t`. Under Reduce Motion the
/// dot holds still, its ring and the shimmer stop, and only the spinner
/// turns: it is what says work is happening.
fn publish(&self, t: f64) {
let reduced = self.reduced.load(Ordering::Relaxed);
let phase = (t / 1.6).fract() as f32;
let breath = 0.5 + 0.5 * (std::f32::consts::TAU * phase).cos();
self.core
.set(if reduced { 1.0 } else { 0.78 + 0.22 * breath });
self.ring_scale.set((4.0 + 6.0 * phase) / 10.0);
self.ring_alpha.set(if reduced {
0.0
} else {
0.34 * (1.0 - phase) * (1.0 - phase)
});
let head = (t * 8.0).rem_euclid(8.0) as f32;
for (k, dot) in self.spin.iter().enumerate() {
let phase = (head - k as f32).rem_euclid(8.0);
dot.set((1.0 - phase / 7.5).clamp(0.18, 1.0));
}
// A 1.8 s ease-in-out sweep from left of the label to right of it.
let sweep = (t / 1.8).fract() as f32;
let centre = -0.3 + 1.6 * (0.5 - 0.5 * (std::f32::consts::PI * sweep).cos());
for (glyph, x) in self.shimmer.iter().zip(self.shimmer_at) {
let d = (x - centre) / 0.14;
glyph.set(if reduced {
1.0
} else {
0.62 + 0.38 * (-d * d).exp()
});
}
}
/// Everything at animation second `t`: the loops while something runs,
/// and the edge glow while a morph lights it. False when idle.
fn advance(&self, t: f64) -> bool {
let activity = self.activity.load(Ordering::Relaxed);
let active = activity != 0;
if active {
self.publish(t);
}
if activity == 1 {
let peak = crate::capture_host::recording_level().unwrap_or(0.0);
self.hear(peak, t);
}
let kick = f32::from_bits(self.kick.swap(0, Ordering::AcqRel));
let mut glow = self.glowing.lock().unwrap_or_else(|e| e.into_inner());
if kick > 0.0 {
glow.since = Some((t, kick, glow.level));
}
if let Some((since, settle, from)) = glow.since {
glow.level = glow_at((t - since) as f32, settle, from);
if t - since > 0.05 && glow.level < 0.002 {
glow.level = 0.0;
glow.since = None;
}
self.glow.set(glow.level);
}
active || glow.since.is_some()
}
/// Publishes at 120 Hz while something animates, the way an audio
/// callback would, and parks while nothing does.
fn spawn(self) {
let meter = self.clone();
let handle = std::thread::Builder::new()
.name("hex-capsule-meter".into())
.spawn(move || {
let mut t = 0.0_f64;
let mut last = std::time::Instant::now();
loop {
let now = std::time::Instant::now();
t += (now - last).as_secs_f64();
last = now;
if meter.advance(t) {
std::thread::sleep(Duration::from_millis(8));
} else {
std::thread::park();
last = std::time::Instant::now();
}
}
});
if let Ok(handle) = handle {
let _ = self.thread.set(handle.thread().clone());
}
}
/// Follows the microphone's latest `peak` at animation second `t`:
/// the bars rise at once and fall over a third of a second.
fn hear(&self, peak: f32, t: f64) {
let mut heard = self.heard.lock().unwrap_or_else(|e| e.into_inner());
let (level, at) = *heard;
let dt = (t - at).clamp(0.0, 0.1) as f32;
let level = (peak * 3.0).clamp(0.0, 1.0).max(level - dt * 3.0);
*heard = (level, t);
self.show_level(level);
}
/// The bars at `level`, 0 to 1.
fn show_level(&self, level: f32) {
for (k, bar) in self.level_bars.iter().enumerate() {
bar.set(level_bar(k, level));
}
self.level_ink.set(level_ink(level));
}
fn wake(&self) {
if let Some(thread) = self.thread.get() {
thread.unpark();
}
}
}
/// The level meter's bars: uneven at rest too, so they never read as an
/// ellipsis.
const LEVEL_WEIGHTS: [f32; 3] = [0.6, 1.0, 0.75];
/// Bar `k`'s rect in the meter's box at `level`, in whole points so a
/// level that rounds the same draws nothing new.
fn level_bar(k: usize, level: f32) -> [f32; 4] {
let weight = LEVEL_WEIGHTS[k];
let height = (2.0 + weight * 3.0 + level * weight * 9.0).round();
[
k as f32 * 4.0,
((CHIP_H - height) * 0.5).round(),
2.0,
height,
]
}
/// How lit the bars are at `level`: dim while nothing is heard.
fn level_ink(level: f32) -> f32 {
((0.4 + 0.6 * (level * 3.0).min(1.0)) * 20.0).round() / 20.0
}
/// What the capsule draws beside its `Surface`: the live values and the
/// timer's text.
pub(crate) struct Animated {
meter: Meter,
/// The timer, so a new second redraws without re-running the view; only
/// a change of length (9:59 → 10:00) re-lays the capsule out.
clock: LiveText,
/// `surface.morphs` as last passed to the meter's edge glow.
morphs: u32,
/// The shown capture's first frame, decoded, for [`Lead::Thumbnail`].
thumb: Option<rune::Image>,
/// The Undo chip's countdown, while it has one.
ring: Option<undo_ring::Ring>,
}
impl Animated {
fn new(surface: &Surface, spawn: bool) -> Self {
let meter = Meter::new();
if spawn {
meter.clone().spawn();
}
Self {
meter,
clock: LiveText::new(surface.clock.clone()),
morphs: surface.morphs,
thumb: None,
ring: None,
}
}
/// Shows `clock`; the surface re-lays out only when its length changes.
/// True when the view must re-run.
fn set_clock(&self, surface: &mut Surface, clock: &str, now: f64) -> bool {
self.clock.set(clock.to_owned());
surface.set_clock(clock, now)
}
/// Tells the meter what the surface shows: which loops run, at what
/// speed, and when a morph lights the edge.
fn sync(&mut self, surface: &Surface) {
let activity = match surface.pres {
Pres::Recording { .. } => 1,
Pres::Processing => 2,
_ => 0,
};
let was = self.meter.activity.swap(activity, Ordering::Relaxed);
self.meter.reduced.store(surface.reduced, Ordering::Relaxed);
let mut wake = was != activity && activity != 0;
if surface.morphs != self.morphs {
self.morphs = surface.morphs;
self.meter
.kick
.store(surface.morph_settle.max(0.2).to_bits(), Ordering::Release);
wake = true;
}
if wake {
self.meter.wake();
}
}
}
// ─── State ───────────────────────────────────────────────────────────────────
/// The pieces the pointer can be on: the pill, and the list hanging under
/// it, which sits outside the pill's clip.
#[derive(Clone, Copy)]
enum Part {
Pill,
List,
}
/// The overlay's visibility, anchor, and pointer-follow lifecycle on screen.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Presence {
/// Hidden: no overlay on screen.
Down,
/// Shown and active (`pres != Pres::Hidden`).
Up {
anchor: surface::Anchor,
follow: bool,
},
/// `pres == Pres::Hidden`, staying up for [`HIDE_AFTER_S`] while the exit
/// animation plays before hiding.
Leaving {
since: f64,
anchor: surface::Anchor,
follow: bool,
},
}
impl Presence {
fn is_shown(self) -> bool {
!matches!(self, Self::Down)
}
fn follow(self) -> bool {
match self {
Self::Up { follow, .. } | Self::Leaving { follow, .. } => follow,
Self::Down => false,
}
}
fn anchor(self) -> Option<surface::Anchor> {
match self {
Self::Up { anchor, .. } | Self::Leaving { anchor, .. } => Some(anchor),
Self::Down => None,
}
}
}
/// The on-screen picker paired with the mode it was last told to pick.
struct AttachedPicker {
overlay: picker::PickerOverlay,
mode: Option<Mode>,
}
impl AttachedPicker {
fn new(overlay: picker::PickerOverlay) -> Self {
Self {
overlay,
mode: None,
}
}
fn sync(&mut self, mode: Option<Mode>) {
if self.mode != mode {
self.mode = mode;
self.overlay.set(mode);
}
}
}
/// The host's side of a press or key: what to do with the capture.
pub(crate) type Act = Arc<dyn Fn(Action) + Send + Sync>;
/// The capsule overlay's state.
pub(crate) struct CapsuleState {
flow: Flow,
surface: Surface,
live: Animated,
/// Inputs from other threads, applied on the next poll.
inbox: Vec<Input>,
/// Clock seconds the recording started at, for the timer.
recording_since: Option<f64>,
/// The latest poll's clock.
now: f64,
/// Reduce Motion, as the view last saw it.
reduced: Cell<bool>,
act: Option<Act>,
overlay: Option<OverlayHandle<CapsuleState>>,
/// Overlay visibility, placed anchor, and pointer-follow state.
presence: Presence,
/// The notch the capsule hangs from on the pointer's display, when it
/// could be measured.
notch: Option<notch::Measured>,
/// Its place beside the meeting capsules (`desktop::overlay_dock`).
dock: dock::Docked,
/// The keys Hex's tap hands the capsule ([`Flow::keys`]): the overlay
/// never takes focus.
keys: Option<(
crate::capture_host::CapsuleKeys,
crate::capture_host::CapsuleKeyGrab,
)>,
/// Whether the pointer is on each [`Part`].
hovering: [bool; 2],
/// The attached on-screen picker, if any.
picker: Option<AttachedPicker>,
/// A still for goldens: it rests, nothing plays.
still: bool,
/// Draws a plain backdrop behind the capsule (stills and clips), so its
/// shadow and edge read.
backdrop: bool,
/// Plays the flow's cues; none in stills and tests, which stay silent.
sound: Option<Arc<dyn Fn(Cue) + Send + Sync>>,
/// The playground's controls and fake host (`hex capsule-playground`).
#[cfg(target_os = "macos")]
playground: Option<Box<playground::Playground>>,
}
impl CapsuleState {
fn new(spawn: bool) -> Self {
let surface = Surface::new();
let live = Animated::new(&surface, spawn);
Self {
flow: Flow::new().suggesting_on_route(!cfg!(target_os = "linux")),
surface,
live,
inbox: Vec::new(),
recording_since: None,
now: 0.0,
reduced: Cell::new(false),
act: None,
overlay: None,
presence: Presence::Down,
notch: None,
dock: dock::Docked::default(),
keys: None,
hovering: [false; 2],
picker: None,
still: false,
backdrop: false,
sound: None,
#[cfg(target_os = "macos")]
playground: None,
}
}
/// A recording still that shows its microphone at `level`, 0 to 1.
#[cfg(all(test, any(target_os = "macos", target_os = "linux")))]
pub(crate) fn hearing(mut self, level: f32) -> Self {
let pres = self.surface.pres.clone();
self.surface.metered = true;
self.surface = std::mem::take(&mut self.surface).settled(pres);
self.live.meter.show_level(level);
self
}
/// `pres` at rest with the timer at `clock`, as a still.
#[cfg_attr(
any(not(test), not(target_os = "macos")),
allow(dead_code, reason = "headless stills and motion runs")
)]
pub(crate) fn still(pres: Pres, clock: &str, thumb: Option<rune::Image>) -> Self {
let mut state = Self::new(false);
state.surface.clock = clock.to_owned();
state.live.clock.set(clock.to_owned());
state.live.thumb = thumb;
let pres = state.with_thumb(pres);
state.surface = std::mem::take(&mut state.surface).settled(pres);
// An Undo ring two seconds in, so a still shows it draining.
if let Pres::Done(Done {
countdown: Some(end),
window,
..
}) = &state.surface.pres
{
let now = end - window + 2.0;
undo_ring::sync(&mut state.live.ring, &state.surface.pres, now, false);
}
state.live.meter.publish(0.4);
// The shimmer's band would leave most of a still's label dim.
for glyph in &state.live.meter.shimmer {
glyph.set(1.0);
}
state.still = true;
state.backdrop = true;
state
}
fn dispatch(&mut self, actions: Vec<Action>) {
if let Some(act) = &self.act {
for action in actions {
act(action);
}
}
self.sound();
}
/// Plays the cues the flow has due.
fn sound(&mut self) {
for cue in self.flow.take_cues() {
if let Some(sound) = &self.sound {
sound(cue);
}
}
}
fn apply(&mut self, input: Input, now: f64) {
if matches!(
input,
Input::Stage(scrawl_capture::capture::Stage::Recording)
) {
self.recording_since = Some(now);
self.live.thumb = None;
}
let actions = self.flow.input(input, now);
self.dispatch(actions);
}
/// A press on `id`, at the latest poll's clock.
fn click(&mut self, id: Id, tx: &mut Tx) {
let now = self.now;
let actions = self.flow.click(id, now);
self.dispatch(actions);
self.present(now);
self.live.sync(&self.surface);
tx.wake_after(Duration::ZERO);
}
/// The pointer came onto `part` of the capsule or left it: chips never
/// fold under it, and a press there is never a click away.
fn hover(&mut self, part: Part, on: bool, tx: &mut Tx) {
let was = self.hovering != [false; 2];
self.hovering[part as usize] = on;
let on = self.hovering != [false; 2];
if on == was {
return;
}
let now = self.now;
let actions = self.flow.hover(on, now);
self.dispatch(actions);
self.present(now);
self.live.sync(&self.surface);
tx.wake_after(Duration::ZERO);
}
/// The pointer moved on the capsule: typing over its suggestions may
/// search now, so the tap's keys change at once, and a countdown under
/// it holds.
fn pointer_moved(&mut self, tx: &mut Tx) {
let now = self.now;
let moved = self.flow.pointer_moved(now);
if moved.keys {
take_keys(self);
}
if moved.held {
self.dispatch(moved.actions);
self.present(now);
self.live.sync(&self.surface);
}
if moved.keys || moved.held {
tx.wake_after(Duration::ZERO);
} else {
tx.live_only();
}
}
/// The pointer moved on the list's `row` (`on`) or left it: a Shift
/// pick goes there.
fn point(&mut self, row: usize, on: bool, tx: &mut Tx) {
if !self.flow.point(row, on) {
tx.live_only();
return;
}
let now = self.now;
self.present(now);
self.live.sync(&self.surface);
tx.wake_after(Duration::ZERO);
}
/// Moves the surface to what the flow shows. True when it changed.
fn present(&mut self, now: f64) -> bool {
let pres = self.with_thumb(self.flow.pres(now));
if !matches!(pres, Pres::Recording { .. } | Pres::Selecting { .. }) {
self.recording_since = None;
}
if pres == self.surface.pres {
return false;
}
self.surface.set(pres, now);
true
}
/// The capture's first frame takes the check's place once decoded; a
/// warning keeps its glyph.
fn with_thumb(&self, mut pres: Pres) -> Pres {
if let Pres::Done(done) = &mut pres
&& done.lead == Lead::Check
&& !done.no_frame
&& self
.live
.thumb
.as_ref()
.is_some_and(|image| image.is_ready() && image.error().is_none())
{
done.lead = Lead::Thumbnail;
}
pres
}
}
/// The overlay's frame hook: inputs, the flow's timers, the surface's due
/// steps, the clock, and showing or hiding the overlay.
fn poll(s: &mut CapsuleState, now: f64, tx: &mut Tx) -> bool {
if s.still {
return false;
}
s.now = now;
s.surface.reduced = s.reduced.get();
// The app follows `capture.capsule_flow`; the playground and tests set
// the tuning themselves.
if s.overlay.is_some() {
let flow = crate::app_settings::capsule_flow();
let mut t = tuning::get();
if t.flow != flow {
t.flow = flow;
tuning::set(t);
}
}
let mut changed = false;
let mut replaced = false;
for input in std::mem::take(&mut s.inbox) {
if matches!(
input,
Input::Stage(scrawl_capture::capture::Stage::Recording)
) {
replaced = true;
}
s.apply(input, now);
changed = true;
}
// Set before the recording shows, so it comes in with its level, and
// kept while it stops, so its width changes once.
if s.overlay.is_some() {
let metered = crate::capture_host::recording_level().is_some();
if metered || !matches!(s.surface.pres, Pres::Recording { .. }) {
changed |= s.surface.set_metered(metered, now);
}
}
changed |= s.flow.tick(now);
s.sound();
changed |= s.present(now);
changed |= s.surface.tick(now);
// Whether the overlay is up this poll: the capsule stays up while it
// leaves, then hides. Worked out before the place block so a capsule
// coming back from hidden is placed on the pointer's display before
// Rune shows it.
let hidden = matches!(s.surface.pres, Pres::Hidden);
let following = matches!(s.surface.pres, Pres::Selecting { .. });
let prev = s.presence;
let (next, leaving_wake) = match (hidden, prev) {
(false, _) => (
Presence::Up {
anchor: s.surface.anchor,
follow: following,
},
None,
),
(true, Presence::Down) => (Presence::Down, None),
(true, Presence::Up { .. }) => (
Presence::Leaving {
since: now,
anchor: s.surface.anchor,
follow: false,
},
Some(HIDE_AFTER_S),
),
(true, Presence::Leaving { since, .. }) => {
let remaining = since + HIDE_AFTER_S - now;
if remaining > 0.0 {
(
Presence::Leaving {
since,
anchor: s.surface.anchor,
follow: false,
},
Some(remaining),
)
} else {
(Presence::Down, None)
}
}
};
let shown = next.is_shown();
// Shown, the capsule stays put. It moves to the pointer's display when
// a new capture brings it, when its anchor changes, when it comes back
// from hidden, and while the picker is open; a notch read that changed
// on its own never moves it. Pinned to the measured screen, Rune's own
// follow never runs for it, so the picker's crossing is this block's:
// while the picker is open, the poll is woken every `DISPLAY_EVERY` to
// re-read the pointer's screen, and a changed read re-places display and
// inset together from one measurement, so the capsule crosses with the
// picker within that cadence. Only the fallback that couldn't read the
// screen keeps `UnderPointer`, where Rune can follow first and leave an
// inset from the other display for a frame. Without an overlay (the
// playground and stills) there is nothing to measure or place, so the
// pretend notch stays.
let moved = prev
.anchor()
.is_some_and(|anchor| anchor != s.surface.anchor);
let step = if shown {
move_of(
replaced && !hidden,
moved,
following,
shown && !prev.is_shown(),
)
} else {
Move::Stay
};
let mut remeasured = false;
if s.surface.anchor == surface::Anchor::Notch {
// The panel is fitted to the notch on the pointer's screen:
// measured on macOS, the pretend one elsewhere.
if step != Move::Stay && s.overlay.is_some() {
let notch = measured_notch();
if notch != s.notch {
s.notch = notch;
let geometry = notch.map_or_else(notch::Geometry::default, |m| m.geometry);
changed |= s.surface.set_notch(geometry);
remeasured = true;
}
}
} else {
s.notch = None;
}
if step.places(remeasured)
&& let Some(overlay) = &s.overlay
{
s.dock.measure(s.notch);
place(overlay, s.surface.anchor, s.notch, s.dock.margin());
}
let earliest = |wake: Option<f64>, at: Option<f64>| match (wake, at) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
};
let mut wake = s.surface.next_due().map(|due| due - now);
wake = earliest(wake, s.flow.next_due(now).map(|due| due - now));
// Pinned to the measured screen, Rune doesn't follow the pointer for
// the capsule and nothing else wakes an idle poll, so look again at the
// picker's cadence while it is open: the read that crosses displays
// comes within one check of the picker's own.
if follows_display(
following,
s.surface.anchor == surface::Anchor::Notch,
s.overlay.is_some(),
) {
wake = earliest(wake, Some(picker::DISPLAY_EVERY.as_secs_f64()));
}
if let Some(since) = s.recording_since {
let secs = (now - since).max(0.0);
let whole = secs as u64;
let clock = format!("{}:{:02}", whole / 60, whole % 60);
changed |= s.live.set_clock(&mut s.surface, &clock, now);
wake = earliest(wake, Some(whole as f64 + 1.0 - secs));
}
s.live.sync(&s.surface);
undo_ring::sync(&mut s.live.ring, &s.surface.pres, now, s.surface.reduced);
// The overlay stays up while the capsule leaves, then hides; placed
// above, before Rune is asked to show it.
if let Some(remaining) = leaving_wake {
wake = earliest(wake, Some(remaining));
}
// Shown in the same poll as the step that brings the capsule in, so
// Rune reveals the hidden pose and animates the entry from it.
if prev.is_shown() != shown
&& let Some(overlay) = &s.overlay
{
if shown {
float_on_xwayland(overlay);
overlay.show();
} else {
overlay.hide();
}
}
crate::capture_host::set_capsule_pill(shown.then_some(s.surface.shell));
// Under the menu bar it clears the meeting capsules, and moves again as
// they move, show, or go.
if s.dock
.sync(shown, s.surface.anchor, s.notch, s.surface.shell)
&& let Some(overlay) = &s.overlay
{
place(overlay, s.surface.anchor, s.notch, s.dock.margin());
}
// The picker follows the pointer between displays.
if prev.follow() != next.follow()
&& let Some(overlay) = &s.overlay
{
overlay.set_follow_pointer(next.follow());
}
s.presence = next;
take_keys(s);
// The on-screen picker shows what the capsule picks.
let picking = match s.surface.pres {
Pres::Selecting { mode, .. } => Some(mode),
_ => None,
};
if let Some(picker) = &mut s.picker {
picker.sync(picking);
}
if let Some(wake) = wake {
tx.wake_after(Duration::from_secs_f64(wake.max(0.0)));
}
for event in s.surface.events.drain(..) {
tx.trace_event(event);
}
if std::mem::take(&mut s.surface.instant) {
tx.instant();
}
changed
}
/// Moves the overlay to where the capsule rests: under the menu bar
/// `margin` points from the top, at the screen's top edge (the notch), or
/// at the pointer (the cursor's card, whose rect is global, so on the
/// primary display's origin).
/// `notch` is the notch measured on the pointer's screen; the panel is
/// pinned to that screen and its left edge put `panel_x` points from the
/// screen's, so it can't land on another display than the one measured.
/// Without one it stays centred on the pointer's screen.
fn place(
overlay: &OverlayHandle<CapsuleState>,
anchor: surface::Anchor,
notch: Option<notch::Measured>,
margin: f32,
) {
use rune::{Align, DisplayTarget, NativeDisplayId, OverlayPlacement, ScreenEdge};
let edge = |margin| OverlayPlacement::Edge {
edge: ScreenEdge::Top,
margin,
align: Align::Center,
inset: 0.0,
};
match anchor {
surface::Anchor::Top => {
overlay.set_display(DisplayTarget::UnderPointer);
overlay.set_placement(Some(edge(margin)));
}
surface::Anchor::Notch => {
// The measured screen's, so the panel and its notch agree even
// if the pointer moves before Rune places it; the pointer's
// when it couldn't be read.
overlay.set_display(match notch.and_then(|m| m.display) {
Some(id) => DisplayTarget::Native(NativeDisplayId::MacOS(id)),
None => DisplayTarget::UnderPointer,
});
// The panel's left edge on the display, so its walls land on the
// notch's; its top stays on the screen's as it always has.
overlay.set_placement(Some(match notch {
Some(notch) => OverlayPlacement::Edge {
edge: ScreenEdge::Top,
margin: 0.0,
align: Align::Start,
inset: notch.panel_x,
},
None => edge(0.0),
}));
}
surface::Anchor::Cursor => {
let Some([x, y]) = scrawl_capture::screens::pointer() else {
return;
};
overlay.set_display(DisplayTarget::Primary);
overlay.set_placement(Some(OverlayPlacement::Rect {
x: x as f32 + surface::POINTER_OFFSET[0] - surface::CURSOR_X,
y: y as f32 + surface::POINTER_OFFSET[1] - surface::CURSOR_Y,
width: PANEL_W,
height: PANEL_H,
}));
}
}
}
/// What a poll does about the panel's place.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Move {
/// Nothing asked it to move: the notch isn't even read.
Stay,
/// The picker follows the pointer: read the notch, and place only if it
/// changed.
Follow,
/// A new capture or a new anchor: read the notch and place.
Place,
}
/// Decides a poll's [`Move`]. The panel goes to the pointer's display on a
/// new capture (`replaced`), an anchor change (`moved`), a capsule coming
/// back from hidden (`appearing`), or while the picker is open
/// (`following`). A showing capsule that isn't following keeps its place
/// however the pointer's screen's notch reads now: no new capture, no new
/// anchor, and no show means nobody asked it to move.
fn move_of(replaced: bool, moved: bool, following: bool, appearing: bool) -> Move {
if replaced || moved || appearing {
Move::Place
} else if following {
Move::Follow
} else {
Move::Stay
}
}
/// Whether a poll must look at the pointer's screen again on its own: the
/// picker is open (`following`) over a capsule pinned to a measured notch
/// (`pinned`), with an overlay to place (`resolved`). Pinned, Rune's own
/// follow never runs, so this wake is what lets the capsule cross displays
/// with the picker.
fn follows_display(following: bool, pinned: bool, resolved: bool) -> bool {
following && pinned && resolved
}