-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtray.rs
More file actions
2111 lines (1949 loc) · 72.9 KB
/
Copy pathtray.rs
File metadata and controls
2111 lines (1949 loc) · 72.9 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::collections::HashMap;
use std::sync::Arc;
use std::thread::JoinHandle;
use anyhow::Context;
use eframe::egui;
use tray_icon::menu::accelerator::{Accelerator, Code, Modifiers};
use tray_icon::menu::{Menu, MenuEvent, MenuItem};
use tray_icon::{Icon, TrayIconBuilder};
use crate::approval_flow::protocol::Decision;
use crate::approval_flow::session::PendingPrompt;
use crate::approval_flow::window::{
self, CredentialCardPrompt, SignInCard, Snapshot, StackItem, WindowState,
};
use crate::credential_flow::session::CredentialDecisionRequest;
use crate::credential_flow::store::CredentialEntry;
use crate::shutdown::Shutdown;
use crate::ui::{Button, ButtonKind, theme};
use lns_policy::integrations::TokenFallback;
pub const WINDOW_WIDTH: f32 = 380.0;
const WINDOW_HEIGHT: f32 = 300.0;
const SCREEN_EDGE_MARGIN: f32 = 20.0;
const SCREEN_RIGHT_MARGIN: f32 = 0.0;
pub const MIN_WINDOW_HEIGHT: f32 = 140.0;
const FALLBACK_MAX_HEIGHT: f32 = 720.0;
const INFORM_ITEM_HEIGHT: f32 = 88.0;
const CONNECTING_ITEM_HEIGHT: f32 = 112.0;
const CARD_ITEM_HEIGHT: f32 = 282.0;
const TOKEN_REVEAL_EXTRA: f32 = 150.0;
const FOLD_SECONDS: f32 = 0.34;
const SLIDE_SECONDS: f32 = 0.22;
const PILE_PEEK: f32 = 9.0;
const PILE_INSET: f32 = 10.0;
const PILE_MAX_LEDGES: usize = 2;
const PILE_HEADER_H: f32 = 19.0;
const PILE_HEADER_BUTTON_CENTER: f32 = 16.0;
/// Builds the tray icon + Quit menu and installs the global menu-event handler (Quit signals shutdown); `on_event` lets the caller repaint after any menu event.
fn build_tray_icon(
shutdown: Arc<Shutdown>,
on_event: impl Fn() + Send + Sync + 'static,
) -> anyhow::Result<tray_icon::TrayIcon> {
let menu = Menu::new();
let quit_item = MenuItem::new(
"Quit Lens Sandbox",
true,
Some(Accelerator::new(Some(Modifiers::META), Code::KeyQ)),
);
menu.append(&quit_item)
.context("failed to append quit menu item")?;
let quit_id = quit_item.id().clone();
let icon = load_icon().context("load embedded tray icon")?;
let builder = TrayIconBuilder::new()
.with_menu(Box::new(menu))
.with_tooltip("Lens Sandbox")
.with_icon(icon);
// Template rendering (monochrome mask adapting to the menu bar) is a macOS concept; on Linux the recolored icon is shown as-is.
#[cfg(target_os = "macos")]
let builder = builder.with_icon_as_template(true);
let tray = builder.build().context("build tray icon")?;
MenuEvent::set_event_handler(Some(move |event: MenuEvent| {
if event.id == quit_id {
shutdown.signal();
}
on_event();
}));
Ok(tray)
}
/// Runs the tray on its own GTK main loop (tray-icon needs gtk on Linux), the only place gtk lives; the winit/eframe window owns the main thread. Degrades to no-tray if gtk can't init.
#[cfg(target_os = "linux")]
fn spawn_gtk_tray(shutdown: Arc<Shutdown>) -> std::thread::JoinHandle<()> {
std::thread::spawn(move || {
if let Err(e) = gtk::init() {
crate::log::warn!(
"tray unavailable: gtk init failed ({e}); running without a tray icon"
);
return;
}
let _tray = match build_tray_icon(shutdown.clone(), || {}) {
Ok(tray) => tray,
Err(e) => {
crate::log::warn!("tray unavailable: {e:#}; running without a tray icon");
return;
}
};
let quit_shutdown = shutdown.clone();
gtk::glib::timeout_add_local(std::time::Duration::from_millis(200), move || {
if quit_shutdown.is_set() {
gtk::main_quit();
gtk::glib::ControlFlow::Break
} else {
gtk::glib::ControlFlow::Continue
}
});
gtk::main();
})
}
pub fn run_tray(
shutdown: Arc<Shutdown>,
ipc_handle: JoinHandle<anyhow::Result<()>>,
window_state: Arc<WindowState>,
) -> anyhow::Result<()> {
#[cfg(target_os = "linux")]
let gtk_tray = spawn_gtk_tray(shutdown.clone());
let viewport = egui::ViewportBuilder::default()
.with_title("Lens Sandbox")
.with_position([0.0, 0.0])
.with_visible(false)
.with_decorations(false)
// Resizable so the card can grow programmatically when a token field is revealed; with no decorations there are no user-facing resize handles.
.with_resizable(true)
.with_always_on_top()
.with_transparent(true)
.with_mouse_passthrough(true)
.with_inner_size([WINDOW_WIDTH, WINDOW_HEIGHT]);
let mut native_options = eframe::NativeOptions {
viewport,
run_and_return: true,
..Default::default()
};
install_activation_policy(&mut native_options);
let app_shutdown = shutdown.clone();
let result = eframe::run_native(
"lns-service",
native_options,
Box::new(move |cc| {
cc.egui_ctx.set_visuals(window::lds_visuals());
window::quiet_debug_overlays(&cc.egui_ctx);
window::install_system_fonts(&cc.egui_ctx);
window::install_icon_font(&cc.egui_ctx);
window::install_ctx(cc.egui_ctx.clone());
let app = TrayApp::new(cc.egui_ctx.clone(), app_shutdown, window_state)
.map_err(|e| format!("{e:#}"))?;
Ok(Box::new(app))
}),
);
shutdown.signal();
let _ = ipc_handle.join();
#[cfg(target_os = "linux")]
let _ = gtk_tray.join();
result.map_err(|e| anyhow::anyhow!("eframe run_native failed: {e}"))
}
/// Whether a desktop session the tray can attach to is present: macOS always has a window server, while Linux needs Wayland or X11 — whose absence (headless servers, CI, plain SSH) means winit cannot create an event loop.
pub fn display_present() -> bool {
if cfg!(target_os = "macos") {
return true;
}
has_linux_display(|key| std::env::var_os(key).is_some())
}
fn has_linux_display(present: impl Fn(&str) -> bool) -> bool {
present("WAYLAND_DISPLAY") || present("WAYLAND_SOCKET") || present("DISPLAY")
}
/// Run the service without the tray UI — wait for shutdown, then join the IPC thread and surface its result — so a headless host keeps the sandbox running instead of aborting at startup.
pub fn run_headless(
shutdown: Arc<Shutdown>,
ipc_handle: JoinHandle<anyhow::Result<()>>,
) -> anyhow::Result<()> {
crate::log::warn!(
"no display detected — running headless without the tray; interactive approval prompts can't be shown, so pre-authorize access in lns-policy.yaml"
);
shutdown.wait_sync();
match ipc_handle.join() {
Ok(result) => result,
Err(_) => anyhow::bail!("the ipc thread panicked"),
}
}
struct TrayApp {
shutdown: Arc<Shutdown>,
window_state: Arc<WindowState>,
#[cfg(target_os = "macos")]
_tray: tray_icon::TrayIcon,
last_visible: bool,
/// Kept on `TrayApp` (not [`WindowState`]) so the snapshot passed to [`render_stack`] stays immutable.
credential_inputs: HashMap<String, String>,
/// Per-card progressive-disclosure state for the "use a token instead" fallback, keyed by the shown card's id.
token_drafts: HashMap<String, TokenDraft>,
/// Per-network-card "remember this decision" toggle, keyed by request id; true persists the choice as an always-rule.
remember: HashMap<String, bool>,
/// The viewport inner height last applied; grows to fit a revealed token field and shrinks back when none is open.
current_height: f32,
}
/// The transient UI state of one card's token fallback: whether the field is revealed and what's been typed.
#[derive(Default)]
pub struct TokenDraft {
revealed: bool,
value: String,
}
impl TrayApp {
fn new(
ctx: egui::Context,
shutdown: Arc<Shutdown>,
window_state: Arc<WindowState>,
) -> anyhow::Result<Self> {
// Linux owns the tray on a dedicated gtk-main thread (spawn_gtk_tray); only macOS builds it in-app.
#[cfg(target_os = "macos")]
let _tray = {
let menu_ctx = ctx.clone();
build_tray_icon(shutdown.clone(), move || menu_ctx.request_repaint())?
};
let watch_shutdown = shutdown.clone();
let watch_ctx = ctx;
std::thread::spawn(move || {
watch_shutdown.wait_sync();
watch_ctx.request_repaint();
});
Ok(Self {
shutdown,
window_state,
#[cfg(target_os = "macos")]
_tray,
last_visible: false,
credential_inputs: HashMap::new(),
token_drafts: HashMap::new(),
remember: HashMap::new(),
current_height: WINDOW_HEIGHT,
})
}
fn sync_viewport_visibility(&mut self, ctx: &egui::Context) {
let order = self.window_state.snapshot().order;
let should_show = !order.is_empty();
match visibility_transition(should_show, self.last_visible) {
VisibilityTransition::Show => {
// Place and size the window before revealing it, or macOS flashes it un-positioned mid-screen for a frame.
let Some(pos) = top_right_position(ctx) else {
ctx.request_repaint();
return;
};
// A seed height keeps the reveal frame (which skips ui()) close to size; ui() then snaps the window to its measured content so no estimate slop shows as bottom padding.
let revealed = self.token_drafts.values().filter(|d| d.revealed).count();
let monitor_height = ctx.input(|i| i.viewport().monitor_size).map(|m| m.y);
let seed = target_height(&order, revealed, monitor_height);
join_all_spaces();
ctx.send_viewport_cmd(egui::ViewportCommand::OuterPosition(pos));
ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(
WINDOW_WIDTH,
seed,
)));
ctx.send_viewport_cmd(egui::ViewportCommand::MousePassthrough(false));
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
// The frame that reveals the window saw is_visible=false, so eframe skipped ui(); kick a repaint so the now-visible window paints its cards and fits its height.
ctx.request_repaint();
self.current_height = seed;
self.last_visible = true;
}
VisibilityTransition::Hide => {
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
ctx.send_viewport_cmd(egui::ViewportCommand::MousePassthrough(true));
self.last_visible = false;
}
// Resizing while visible is driven by ui()'s content measurement, not an estimate.
VisibilityTransition::Unchanged => {}
}
}
/// Snaps the viewport to `target` using measured content size, not the window-bounded `min_rect`, so a card taller than the current window grows it instead of being clipped.
fn fit_height_to_content(&mut self, ctx: &egui::Context, target: f32) {
if (self.current_height - target).abs() > 0.5 {
ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(
WINDOW_WIDTH,
target,
)));
self.current_height = target;
}
}
}
impl eframe::App for TrayApp {
fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
[0.0, 0.0, 0.0, 0.0]
}
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
if self.shutdown.is_set() {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
return;
}
self.sync_viewport_visibility(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
let snapshot = self.window_state.snapshot();
prune_credential_inputs(&mut self.credential_inputs, &snapshot);
prune_token_drafts(&mut self.token_drafts, &snapshot);
prune_remember(&mut self.remember, &snapshot);
let monitor_height = ui.ctx().input(|i| i.viewport().monitor_size).map(|m| m.y);
let cap = content_cap(monitor_height);
let (action, content_height) = render_stack(
ui,
&snapshot,
&mut self.credential_inputs,
&mut self.token_drafts,
&mut self.remember,
cap,
);
let target = content_height.clamp(MIN_WINDOW_HEIGHT, cap);
self.fit_height_to_content(ui.ctx(), target);
match action {
Some(CardAction::CloseAll) => {
close_all(&self.window_state, &snapshot);
ui.ctx().request_repaint();
}
Some(CardAction::Decide { id, decision }) => {
self.window_state.decide(&id, decision);
ui.ctx().request_repaint();
}
Some(CardAction::DecideCredential { id, request }) => {
self.credential_inputs.remove(&id);
self.window_state.decide_credential(&id, request);
ui.ctx().request_repaint();
}
Some(CardAction::DismissInform { index }) => {
self.window_state.dismiss_inform(index);
ui.ctx().request_repaint();
}
Some(CardAction::OpenBrowser { url }) => {
crate::browser::open(&url);
ui.ctx().request_repaint();
}
Some(CardAction::CancelSignIn { credential_id }) => {
self.window_state.cancel_sign_in(&credential_id);
ui.ctx().request_repaint();
}
Some(CardAction::ConnectOffer { id }) => {
self.window_state.connect_offer(&id);
ui.ctx().request_repaint();
}
Some(CardAction::DeclineOffer { id }) => {
self.window_state.decline_offer(&id);
ui.ctx().request_repaint();
}
Some(CardAction::UseOfferToken { id, value }) => {
self.window_state.use_offer_token(&id, value);
ui.ctx().request_repaint();
}
Some(CardAction::UseTokenSignIn {
credential_id,
value,
}) => {
self.window_state.pivot_sign_in(&credential_id, value);
ui.ctx().request_repaint();
}
None => {}
}
refresh_window_shadows();
}
}
const BTN_GAP: f32 = 12.0;
#[derive(Debug, PartialEq, Eq)]
pub enum CardAction {
/// Dismiss every card at once (the pile's close-all header button), denying or cancelling each held request.
CloseAll,
Decide {
id: String,
decision: Decision,
},
DecideCredential {
id: String,
request: CredentialDecisionRequest,
},
DismissInform {
index: usize,
},
OpenBrowser {
url: String,
},
CancelSignIn {
credential_id: String,
},
ConnectOffer {
id: String,
},
DeclineOffer {
id: String,
},
UseOfferToken {
id: String,
value: String,
},
UseTokenSignIn {
credential_id: String,
value: String,
},
}
/// What the user did in the token-fallback affordance shared by every connect card.
enum TokenFallbackEvent {
Save(String),
OpenHelp(String),
}
fn item_height(item: &StackItem) -> f32 {
match item {
StackItem::Inform(_) => INFORM_ITEM_HEIGHT,
StackItem::Connecting(_) => CONNECTING_ITEM_HEIGHT,
_ => CARD_ITEM_HEIGHT,
}
}
/// The tallest the window may grow before the stack scrolls rather than running off-screen — the usable monitor height, or a fixed fallback when the monitor size isn't known yet.
pub fn content_cap(monitor_height: Option<f32>) -> f32 {
monitor_height
.map(|h| (h - 2.0 * SCREEN_EDGE_MARGIN).max(MIN_WINDOW_HEIGHT))
.unwrap_or(FALLBACK_MAX_HEIGHT)
}
/// A pre-measurement height seed for the reveal frame alone (which skips ui()), after which ui() snaps the window to its measured content.
fn target_height(items: &[StackItem], revealed: usize, monitor_height: Option<f32>) -> f32 {
if items.is_empty() {
return MIN_WINDOW_HEIGHT;
}
let content = items.iter().map(item_height).sum::<f32>()
+ theme::CARD_GAP * (items.len() - 1) as f32
+ revealed as f32 * TOKEN_REVEAL_EXTRA
+ 2.0 * theme::STACK_MARGIN as f32;
content.clamp(MIN_WINDOW_HEIGHT, content_cap(monitor_height))
}
/// Renders the stack and returns the fired action plus the content's natural height (the scroll area's `content_size`, not the window-bounded laid-out size), which the caller sizes the window from so a card taller than the window grows it instead of being clipped.
pub fn render_stack(
ui: &mut egui::Ui,
snapshot: &Snapshot,
credential_inputs: &mut HashMap<String, String>,
token_drafts: &mut HashMap<String, TokenDraft>,
remember: &mut HashMap<String, bool>,
scroll_max: f32,
) -> (Option<CardAction>, f32) {
if snapshot.order.is_empty() {
return (None, 0.0);
}
if snapshot.order.len() == 1 {
ui.ctx()
.data_mut(|d| d.insert_temp(egui::Id::new("approval-pile-expanded"), false));
return render_single(
ui,
snapshot,
credential_inputs,
token_drafts,
remember,
scroll_max,
);
}
render_pile(
ui,
snapshot,
credential_inputs,
token_drafts,
remember,
scroll_max,
)
}
fn render_single(
ui: &mut egui::Ui,
snapshot: &Snapshot,
credential_inputs: &mut HashMap<String, String>,
token_drafts: &mut HashMap<String, TokenDraft>,
remember: &mut HashMap<String, bool>,
scroll_max: f32,
) -> (Option<CardAction>, f32) {
use egui::{Frame, Margin};
ui.style_mut().spacing.scroll.floating = true;
ui.style_mut().spacing.scroll.fade.strength = 0.0;
let out = egui::ScrollArea::vertical()
.max_height(scroll_max)
.auto_shrink([false, true])
.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden)
.show(ui, |ui| {
let card_width = WINDOW_WIDTH - 2.0 * theme::STACK_MARGIN as f32;
Frame::new()
.inner_margin(Margin::same(theme::STACK_MARGIN))
.show(ui, |ui| {
let mut action = None;
for (idx, item) in snapshot.order.iter().enumerate() {
if idx > 0 {
ui.add_space(theme::CARD_GAP);
}
let (item_action, response) = render_item(
ui,
item,
snapshot,
credential_inputs,
token_drafts,
remember,
card_width,
);
let mut fired = item_action;
let close_rect = egui::Rect::from_center_size(
response.rect.left_top() + egui::vec2(3.0, 3.0),
egui::Vec2::splat(22.0),
);
if fired.is_none()
&& ui.rect_contains_pointer(response.rect.union(close_rect))
&& let Some(close) = close_action(item, snapshot)
&& close_button(ui, egui::Id::new(("card-close", idx)), close_rect)
.clicked()
{
fired = Some(close);
}
action = action.or(fired);
}
action
})
.inner
});
(out.inner, out.content_size.y)
}
fn lerp(a: f32, b: f32, t: f32) -> f32 {
a + (b - a) * t
}
fn ease_out_cubic(t: f32) -> f32 {
1.0 - (1.0 - t).powi(3)
}
fn ledge_alpha(depth: usize) -> f32 {
match depth {
1 => 0.60,
_ => 0.32,
}
}
struct PileGeom {
left: f32,
top: f32,
width: f32,
}
/// The two layouts a notification pile animates between, derived purely from measured card heights so the rendering and the window sizing agree: each card's expanded slot offset, the folded/expanded content heights, and how many ledges peek when collapsed.
struct PileLayout {
expanded_y: Vec<f32>,
expanded_h: f32,
folded_h: f32,
visible: usize,
}
impl PileLayout {
fn new(heights: &[f32]) -> Self {
let n = heights.len();
let mut expanded_y = vec![0.0_f32; n];
expanded_y[0] = PILE_HEADER_H;
for i in 1..n {
expanded_y[i] = expanded_y[i - 1] + heights[i - 1] + theme::CARD_GAP;
}
let expanded_h = expanded_y[n - 1] + heights[n - 1];
let visible = (n - 1).min(PILE_MAX_LEDGES);
let folded_h = heights[0] + visible as f32 * PILE_PEEK;
Self {
expanded_y,
expanded_h,
folded_h,
visible,
}
}
fn depth(&self, i: usize) -> usize {
i.min(self.visible).max(1)
}
/// Card `i`'s top offset at fold fraction `t`, lerping from its folded peek to its fanned-out slot.
fn card_y(&self, i: usize, t: f32) -> f32 {
let folded = if i == 0 {
0.0
} else {
self.depth(i) as f32 * PILE_PEEK
};
lerp(folded, self.expanded_y[i], t)
}
/// Card `i`'s per-side horizontal inset at fold fraction `t`: narrowed as a ledge when folded, flush when fanned out.
fn card_inset(&self, i: usize, t: f32) -> f32 {
if i == 0 {
return 0.0;
}
lerp(self.depth(i) as f32 * PILE_INSET, 0.0, t)
}
}
struct PileMemory {
expanded: bool,
heights: Vec<f32>,
}
/// Keyed by underlying id, not list position, so a mid-list removal can't reuse a neighbour's scope id (an egui id-clash flash) or cached height.
fn card_key(item: &StackItem, snapshot: &Snapshot) -> egui::Id {
match *item {
StackItem::Network(i) => egui::Id::new(("pile-net", &snapshot.pending[i].id)),
StackItem::Credential(i) => {
egui::Id::new(("pile-cred", &snapshot.pending_credentials[i].id))
}
StackItem::SignIn(i) => egui::Id::new(("pile-signin", &snapshot.sign_ins[i].credential_id)),
StackItem::Connecting(i) => egui::Id::new(("pile-conn", &snapshot.connecting[i])),
StackItem::Inform(i) => egui::Id::new(("pile-inform", i)),
}
}
fn read_pile_memory(ctx: &egui::Context, snapshot: &Snapshot) -> PileMemory {
let expanded = ctx
.data(|d| d.get_temp::<bool>(egui::Id::new("approval-pile-expanded")))
.unwrap_or(false);
let cache = ctx
.data(|d| d.get_temp::<HashMap<egui::Id, f32>>(egui::Id::new("approval-pile-heights")))
.unwrap_or_default();
let heights = snapshot
.order
.iter()
.map(|item| {
cache
.get(&card_key(item, snapshot))
.copied()
.unwrap_or_else(|| item_height(item))
})
.collect();
PileMemory { expanded, heights }
}
/// Reads and updates the pile's scroll offset; only the fully-expanded pile scrolls, and only when its fanned-out content overflows the window.
fn pile_scroll_offset(
ctx: &egui::Context,
ui: &egui::Ui,
geom: &PileGeom,
expanded: bool,
max_scroll: f32,
) -> f32 {
let id = egui::Id::new("approval-pile-scroll");
let mut scroll = ctx.data(|d| d.get_temp::<f32>(id)).unwrap_or(0.0);
if !expanded || max_scroll <= 0.0 {
scroll = 0.0;
} else {
let region = egui::Rect::from_min_size(
egui::pos2(geom.left, geom.top),
egui::vec2(geom.width, ui.max_rect().height()),
);
if ui.rect_contains_pointer(region) {
let dy = ui.input(|i| i.smooth_scroll_delta.y);
if dy != 0.0 {
ctx.request_repaint();
}
scroll -= dy;
}
scroll = scroll.clamp(0.0, max_scroll);
}
ctx.data_mut(|d| d.insert_temp(id, scroll));
scroll
}
fn close_all(state: &WindowState, snapshot: &Snapshot) {
let mut had_inform = false;
for item in &snapshot.order {
match *item {
StackItem::Network(i) => {
state.decide(&snapshot.pending[i].id, Decision::DenyOnce);
}
StackItem::Credential(i) => {
state.decide_credential(
&snapshot.pending_credentials[i].id,
CredentialDecisionRequest::Deny,
);
}
StackItem::SignIn(i) => {
state.cancel_sign_in(&snapshot.sign_ins[i].credential_id);
}
StackItem::Inform(_) => had_inform = true,
StackItem::Connecting(_) => {}
}
}
if had_inform {
state.clear_informs();
}
}
fn paint_pile_ledges(ui: &egui::Ui, geom: &PileGeom, layout: &PileLayout, top_h: f32, t: f32) {
use egui::{Color32, CornerRadius, Stroke, StrokeKind, pos2, vec2};
if t >= 0.999 {
return;
}
let radius = CornerRadius::same(theme::CARD_CORNER_RADIUS);
for depth in (1..=layout.visible).rev() {
let inset = depth as f32 * PILE_INSET;
let rect = egui::Rect::from_min_size(
pos2(geom.left + inset, geom.top + depth as f32 * PILE_PEEK),
vec2(geom.width - 2.0 * inset, top_h),
);
let a = ledge_alpha(depth) * (1.0 - t);
let fill = Color32::from_rgba_unmultiplied(
window::BG_SECONDARY.r(),
window::BG_SECONDARY.g(),
window::BG_SECONDARY.b(),
(theme::CARD_FILL_ALPHA as f32 * a) as u8,
);
ui.painter().rect(
rect,
radius,
fill,
Stroke::new(1.0, window::BORDER.gamma_multiply(a)),
StrokeKind::Inside,
);
}
}
/// Renders the real cards at their interpolated positions (deepest first so the top card wins input), clipped under the header so scrolled cards vanish behind it, and returns the fired action plus each card's freshly-measured height.
#[allow(clippy::too_many_arguments)]
fn render_pile_cards(
ui: &mut egui::Ui,
ctx: &egui::Context,
snapshot: &Snapshot,
credential_inputs: &mut HashMap<String, String>,
token_drafts: &mut HashMap<String, TokenDraft>,
remember: &mut HashMap<String, bool>,
geom: &PileGeom,
layout: &PileLayout,
heights: &[f32],
t: f32,
scroll: f32,
) -> (Option<CardAction>, Vec<f32>) {
use egui::{Layout, Rect, UiBuilder, pos2, vec2};
let order = &snapshot.order;
let n = order.len();
let mut measured = heights.to_vec();
let mut action: Option<CardAction> = None;
let allow_close = !(0.001..=0.999).contains(&t);
let clip = Rect::from_min_max(
pos2(geom.left - 8.0, geom.top + PILE_HEADER_H * t),
pos2(geom.left + geom.width + 8.0, ui.max_rect().bottom()),
);
let mut indices: Vec<usize> = (1..n).rev().collect();
indices.push(0);
for i in indices {
if i != 0 && t <= 0.001 {
continue;
}
let key = card_key(&order[i], snapshot);
let inset = layout.card_inset(i, t);
let w = geom.width - 2.0 * inset;
// Animate the layout slot (not the scroll offset, which must track the wheel 1:1) so a removal slides neighbours up macOS-style; during the fold the slot is already driven by `t`, so track it instantly.
let slot_y = geom.top + layout.card_y(i, t);
let settle = if t >= 0.999 { SLIDE_SECONDS } else { 0.0 };
let y = ctx.animate_value_with_time(key.with("slide"), slot_y, settle) - scroll;
let min = pos2(geom.left + inset, y);
let alpha = if i == 0 { 1.0 } else { t };
let res = ui.scope_builder(
UiBuilder::new()
.id_salt(key)
.max_rect(Rect::from_min_size(min, vec2(w, 10_000.0)))
.layout(Layout::top_down(egui::Align::Min)),
|ui| {
ui.set_clip_rect(clip);
ui.set_opacity(alpha);
ui.set_width(w);
render_item(
ui,
&order[i],
snapshot,
credential_inputs,
token_drafts,
remember,
w,
)
},
);
let (item_action, card_resp) = res.inner;
measured[i] = card_resp.rect.height();
if action.is_none() {
action = item_action;
}
if action.is_none()
&& allow_close
&& let Some(close) = pile_close(ui, &order[i], snapshot, card_resp.rect, key)
{
action = Some(close);
}
}
(action, measured)
}
/// The hover ✕ on a settled card, mirroring [`render_single`]'s close affordance.
fn pile_close(
ui: &mut egui::Ui,
item: &StackItem,
snapshot: &Snapshot,
card_rect: egui::Rect,
key: egui::Id,
) -> Option<CardAction> {
let close_rect = egui::Rect::from_center_size(
card_rect.left_top() + egui::vec2(3.0, 3.0),
egui::Vec2::splat(22.0),
);
if ui.rect_contains_pointer(card_rect.union(close_rect))
&& let Some(close) = close_action(item, snapshot)
&& close_button(ui, key.with("close"), close_rect).clicked()
{
return Some(close);
}
None
}
enum PileHeaderEvent {
ShowLess,
CloseAll,
}
/// A macOS-style translucent capsule that reads on any wallpaper, brightening on hover and depressing on press; returns its response and the (press-scaled) content rect to draw a label or glyph into.
fn pile_pill(
ui: &mut egui::Ui,
ctx: &egui::Context,
rect: egui::Rect,
id: egui::Id,
alpha: f32,
) -> (egui::Response, egui::Rect) {
use egui::{Color32, CornerRadius, Sense, Stroke, StrokeKind};
let resp = ui.interact(rect, id, Sense::click());
let hover = ctx.animate_bool_with_time(id.with("hover"), resp.hovered(), 0.10);
let press =
ctx.animate_bool_with_time(id.with("press"), resp.is_pointer_button_down_on(), 0.06);
let r = egui::Rect::from_center_size(rect.center(), rect.size() * (1.0 - 0.06 * press));
let radius = CornerRadius::same((r.height() * 0.5) as u8);
let fill_a = ((170.0 + 55.0 * hover) * alpha).clamp(0.0, 255.0) as u8;
let stroke_a = ((55.0 + 45.0 * hover) * alpha).clamp(0.0, 255.0) as u8;
ui.painter().rect(
r,
radius,
Color32::from_rgba_unmultiplied(96, 97, 104, fill_a),
Stroke::new(1.0, Color32::from_white_alpha(stroke_a)),
StrokeKind::Inside,
);
if resp.hovered() {
ctx.set_cursor_icon(egui::CursorIcon::PointingHand);
}
(resp, r)
}
/// The fanned-out header: a "Show Less" pill and a circular close-all button, right-aligned and fading in with the pile; returns whichever was clicked.
fn pile_header(
ui: &mut egui::Ui,
ctx: &egui::Context,
geom: &PileGeom,
t: f32,
) -> Option<PileHeaderEvent> {
use egui::{Align2, Color32, FontId, Id, Rect, Stroke, Vec2, pos2, vec2};
if t <= 0.01 {
return None;
}
let h = 22.0;
let cy = geom.top - theme::STACK_MARGIN as f32 + PILE_HEADER_BUTTON_CENTER;
let right = geom.left + geom.width;
let label = "Show Less";
let text_w = ui
.painter()
.layout_no_wrap(label.to_owned(), FontId::proportional(12.0), Color32::WHITE)
.rect
.width();
let close_rect = Rect::from_center_size(pos2(right - h / 2.0, cy), Vec2::splat(h));
let pill_rect = Rect::from_center_size(
pos2(close_rect.left() - 8.0 - (text_w + 24.0) / 2.0, cy),
vec2(text_w + 24.0, h),
);
let fg = Color32::from_rgba_unmultiplied(236, 237, 242, (255.0 * t) as u8);
let mut event = None;
let (show_less, content) = pile_pill(ui, ctx, pill_rect, Id::new("approval-pile-showless"), t);
ui.painter().text(
content.center(),
Align2::CENTER_CENTER,
label,
FontId::proportional(12.0),
fg,
);
if show_less.clicked() {
event = Some(PileHeaderEvent::ShowLess);
}
let (close_all, content) = pile_pill(ui, ctx, close_rect, Id::new("approval-pile-closeall"), t);
let arm = content.width() * 0.18;
let c = content.center();
let x = Stroke::new(1.6, fg);
ui.painter()
.line_segment([c - vec2(arm, arm), c + vec2(arm, arm)], x);
ui.painter()
.line_segment([c + vec2(arm, -arm), c - vec2(arm, -arm)], x);
if close_all.clicked() {
event = Some(PileHeaderEvent::CloseAll);
}
event
}
/// The click target over a collapsed pile — the whole top card and its peeking ledges — registered under the cards so the top card's own buttons still win; returns whether it was clicked to fan the pile out.
fn pile_expand_hit(
ui: &mut egui::Ui,
ctx: &egui::Context,
geom: &PileGeom,
layout: &PileLayout,
t: f32,
expanded: bool,
) -> bool {
use egui::{Id, Rect, Sense, pos2};
if expanded || t >= 0.5 {
return false;
}
let hit = Rect::from_min_max(
pos2(geom.left, geom.top),
pos2(geom.left + geom.width, geom.top + layout.folded_h + 6.0),
);
let resp = ui.interact(hit, Id::new("approval-pile-expand"), Sense::click());
if resp.contains_pointer() {
ctx.set_cursor_icon(egui::CursorIcon::PointingHand);
}
resp.clicked()
}
/// Renders the multi-card stack as a macOS-style notification pile: collapsed it shows the top card with the rest peeking as stacked ledges; a click fans them out, a "Show Less" header folds them back, and the fully-fanned list scrolls when it overflows — every position, width, and opacity animating between the two layouts.
fn render_pile(
ui: &mut egui::Ui,
snapshot: &Snapshot,
credential_inputs: &mut HashMap<String, String>,
token_drafts: &mut HashMap<String, TokenDraft>,
remember: &mut HashMap<String, bool>,
scroll_max: f32,
) -> (Option<CardAction>, f32) {
use egui::{Id, vec2};
let ctx = ui.ctx().clone();
let mut mem = read_pile_memory(&ctx, snapshot);
let t = ease_out_cubic(ctx.animate_bool_with_time(
Id::new("approval-pile-t"),
mem.expanded,
FOLD_SECONDS,
));
let layout = PileLayout::new(&mem.heights);
let margin = theme::STACK_MARGIN as f32;
let geom = PileGeom {
left: ui.max_rect().min.x + margin,
top: ui.max_rect().min.y + margin,
width: WINDOW_WIDTH - 2.0 * margin,
};
let top_h = mem.heights[0];
let viewport_h = (scroll_max - 2.0 * margin).max(0.0);
let max_scroll = (layout.expanded_h - viewport_h).max(0.0);
let scroll = pile_scroll_offset(&ctx, ui, &geom, mem.expanded, max_scroll);
paint_pile_ledges(ui, &geom, &layout, top_h, t);
let expand_clicked = pile_expand_hit(ui, &ctx, &geom, &layout, t, mem.expanded);
let (mut action, measured) = render_pile_cards(
ui,
&ctx,
snapshot,
credential_inputs,
token_drafts,
remember,
&geom,
&layout,
&mem.heights,
t,
scroll,
);
match pile_header(ui, &ctx, &geom, t) {
Some(PileHeaderEvent::ShowLess) => {
mem.expanded = false;
ctx.request_repaint();
}
Some(PileHeaderEvent::CloseAll) => {