kuizer-gui 0.3.1

Desktop app for kuizer, a keyboard-driven PC cleaner that also deeply cleans developer artifacts, caches, toolchains, Docker and duplicates, built on GPUI
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
use std::cell::Cell;
use std::path::Path;
use std::rc::Rc;
use std::time::Instant;

use gpui::{
    Animation, AnimationExt, AnyView, App, Bounds, Context, Corner, DispatchPhase, ElementId,
    Entity, FontWeight, Global, IntoElement, KeyDownEvent, MouseDownEvent, MouseMoveEvent,
    ParentElement, Pixels, Point, Render, ScrollWheelEvent, SharedString, Styled, Task, Window,
    anchored, canvas, deferred, div, point, prelude::*,
};
use kuizer::platform::display_path;

use crate::glossary::Term;
use crate::motion;
use crate::theme::{self, font, size, space, unit};
use crate::ui;

const RISE: f32 = 3.;
const ROOM: f32 = 160.;
const WRAP_AT: usize = 48;

type Build = Rc<dyn Fn(&mut Window, &mut App) -> AnyView>;

pub struct Typeface(pub SharedString);

impl Global for Typeface {}

struct Shared(Entity<Layer>);

impl Global for Shared {}

#[derive(Clone)]
pub struct Tooltip {
    title: Option<SharedString>,
    text: Option<SharedString>,
    keys: Vec<SharedString>,
    rows: Vec<(SharedString, SharedString)>,
}

impl Tooltip {
    pub fn new(text: impl Into<SharedString>) -> Self {
        Self {
            title: None,
            text: Some(text.into()),
            keys: Vec::new(),
            rows: Vec::new(),
        }
    }

    pub fn details(title: impl Into<SharedString>) -> Self {
        Self {
            title: Some(title.into()),
            text: None,
            keys: Vec::new(),
            rows: Vec::new(),
        }
    }

    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
        self.title = Some(title.into());
        self
    }

    pub fn keys(mut self, keys: &[&str]) -> Self {
        self.keys = keys
            .iter()
            .map(|key| SharedString::from((*key).to_owned()))
            .collect();
        self
    }

    pub fn row(mut self, label: impl Into<SharedString>, value: impl Into<SharedString>) -> Self {
        self.rows.push((label.into(), value.into()));
        self
    }

    pub fn note(mut self, text: impl Into<SharedString>) -> Self {
        self.text = Some(text.into());
        self
    }

    pub fn build(self) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static {
        move |_, cx| cx.new(|_| self.clone()).into()
    }
}

impl Render for Tooltip {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let font = cx.try_global::<Typeface>().map(|face| face.0.clone());
        let heading = self.title.clone().map(|title| {
            div()
                .flex()
                .items_center()
                .gap(unit(space::L))
                .child(
                    div()
                        .flex_1()
                        .min_w_0()
                        .font_weight(FontWeight::MEDIUM)
                        .text_color(theme::text())
                        .child(title),
                )
                .children(self.keys.iter().cloned().map(ui::kbd))
        });
        let keys_inline = self.title.is_none() && !self.keys.is_empty();
        let wraps = self
            .text
            .as_ref()
            .is_some_and(|text| text.chars().count() > WRAP_AT);
        div()
            .flex()
            .flex_col()
            .gap(unit(space::XS))
            .max_w(unit(size::LIST))
            .when(wraps, |this| this.w(unit(size::LIST)))
            .px(unit(space::M))
            .py(unit(space::S))
            .rounded(theme::radius_control())
            .bg(theme::elevated())
            .border_1()
            .border_color(theme::border_strong())
            .debug_selector(|| "tooltip".to_owned())
            .text_size(unit(font::SMALL))
            .text_color(theme::muted())
            .when_some(font, |this, font| this.font_family(font))
            .children(heading)
            .when_some(self.text.clone(), |this, text| {
                let body = div()
                    .debug_selector(|| "tooltip-text".to_owned())
                    .child(text);
                if keys_inline {
                    this.child(
                        div()
                            .flex()
                            .items_center()
                            .gap(unit(space::L))
                            .child(body)
                            .children(self.keys.iter().cloned().map(ui::kbd)),
                    )
                } else {
                    this.child(body)
                }
            })
            .when(!self.rows.is_empty(), |this| {
                this.child(div().flex().flex_col().gap(unit(space::XXS)).children(
                    self.rows.iter().map(|(label, value)| {
                        div()
                            .flex()
                            .gap(unit(space::XL))
                            .child(
                                div()
                                    .flex_1()
                                    .min_w_0()
                                    .text_color(theme::faint())
                                    .child(label.clone()),
                            )
                            .child(
                                div()
                                    .min_w_0()
                                    .text_color(theme::text())
                                    .child(value.clone()),
                            )
                    }),
                ))
            })
    }
}

#[derive(Clone, Copy, PartialEq)]
struct Anchor {
    bounds: Bounds<Pixels>,
}

struct Shown {
    anchor: Anchor,
    view: AnyView,
    animate: bool,
    epoch: usize,
}

#[derive(Default)]
pub struct Layer {
    shown: Option<Shown>,
    pending: Option<(Anchor, Task<()>)>,
    closed: Option<Instant>,
    epoch: usize,
    focus: Option<ElementId>,
    offered: bool,
}

impl Layer {
    #[cfg(test)]
    pub fn showing(&self) -> bool {
        self.shown.is_some()
    }

    fn aim(&mut self, focus: Option<ElementId>, cx: &mut Context<Self>) {
        if self.focus == focus {
            return;
        }
        if self.focus.is_some() {
            self.dismiss(cx);
        }
        self.focus = focus;
        self.offered = false;
    }

    /// Whether the control `id` should open its tooltip for the keyboard now. True once per
    /// focus, so a tooltip closed by a key or the mouse stays closed until the focus moves.
    fn claim(&mut self, id: &ElementId) -> bool {
        let due = !self.offered && self.focus.as_ref() == Some(id);
        self.offered |= due;
        due
    }

    fn request(
        &mut self,
        anchor: Anchor,
        build: Build,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if self
            .shown
            .as_ref()
            .is_some_and(|shown| shown.anchor.bounds == anchor.bounds)
        {
            return;
        }
        let warm = self.shown.is_some()
            || self
                .closed
                .is_some_and(|closed| closed.elapsed() < motion::TOOLTIP_WARM);
        if warm {
            self.show(anchor, &build, false, window, cx);
            return;
        }
        let task = cx.spawn_in(window, async move |layer, cx| {
            cx.background_executor().timer(motion::TOOLTIP_DELAY).await;
            layer
                .update_in(cx, |layer, window, cx| {
                    if layer
                        .pending
                        .as_ref()
                        .is_some_and(|(pending, _)| pending.bounds == anchor.bounds)
                    {
                        layer.pending = None;
                        layer.show(anchor, &build, true, window, cx);
                    }
                })
                .ok();
        });
        self.pending = Some((anchor, task));
    }

    fn show(
        &mut self,
        anchor: Anchor,
        build: &Build,
        animate: bool,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.pending = None;
        self.epoch += 1;
        self.shown = Some(Shown {
            anchor,
            view: build(window, cx),
            animate: animate
                && self
                    .closed
                    .is_none_or(|closed| closed.elapsed() >= motion::TOOLTIP_WARM),
            epoch: self.epoch,
        });
        cx.notify();
    }

    fn dismiss(&mut self, cx: &mut Context<Self>) {
        self.pending = None;
        if self.shown.take().is_some() {
            self.closed = Some(Instant::now());
            cx.notify();
        }
    }

    fn track(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
        if self
            .pending
            .as_ref()
            .is_some_and(|(pending, _)| !pending.bounds.contains(&position))
        {
            self.pending = None;
        }
        if self
            .shown
            .as_ref()
            .is_some_and(|shown| !shown.anchor.bounds.contains(&position))
        {
            self.dismiss(cx);
        }
    }
}

impl Render for Layer {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let this = cx.entity().downgrade();
        let active = self.shown.is_some() || self.pending.is_some();
        let listener = canvas(
            |_, _, _| {},
            move |_, (), window, _| {
                if !active {
                    return;
                }
                let moved = this.clone();
                window.on_mouse_event(move |event: &MouseMoveEvent, phase, _, cx| {
                    if phase == DispatchPhase::Capture {
                        moved
                            .update(cx, |layer, cx| layer.track(event.position, cx))
                            .ok();
                    }
                });
                let pressed = this.clone();
                window.on_mouse_event(move |_: &MouseDownEvent, phase, _, cx| {
                    if phase == DispatchPhase::Capture {
                        pressed.update(cx, |layer, cx| layer.dismiss(cx)).ok();
                    }
                });
                let scrolled = this.clone();
                window.on_mouse_event(move |_: &ScrollWheelEvent, phase, _, cx| {
                    if phase == DispatchPhase::Capture {
                        scrolled.update(cx, |layer, cx| layer.dismiss(cx)).ok();
                    }
                });
                let typed = this;
                window.on_key_event(move |_: &KeyDownEvent, phase, _, cx| {
                    if phase == DispatchPhase::Capture {
                        typed.update(cx, |layer, cx| layer.dismiss(cx)).ok();
                    }
                });
            },
        )
        .absolute()
        .size_0();
        let card = self.shown.as_ref().map(|shown| {
            let bounds = shown.anchor.bounds;
            let above = bounds.bottom() + unit(ROOM).to_pixels(window.rem_size())
                > window.viewport_size().height;
            let gap = unit(space::S).to_pixels(window.rem_size());
            let margin = unit(space::M).to_pixels(window.rem_size());
            let trailing = bounds.center().x > window.viewport_size().width / 2.;
            let x = if trailing {
                bounds.right()
            } else {
                bounds.left()
            };
            let (corner, y) = match (above, trailing) {
                (true, false) => (Corner::BottomLeft, bounds.top() - gap),
                (true, true) => (Corner::BottomRight, bounds.top() - gap),
                (false, false) => (Corner::TopLeft, bounds.bottom() + gap),
                (false, true) => (Corner::TopRight, bounds.bottom() + gap),
            };
            let direction = if above { -RISE } else { RISE };
            let content = div().relative().child(shown.view.clone());
            let content = if shown.animate && !motion::reduced() {
                content
                    .with_animation(
                        ("tooltip-enter", shown.epoch),
                        Animation::new(motion::TOOLTIP_IN).with_easing(motion::ease_out),
                        move |card, progress| {
                            card.opacity(progress)
                                .top(unit(direction * (1. - progress)))
                        },
                    )
                    .into_any_element()
            } else {
                content.into_any_element()
            };
            deferred(
                anchored()
                    .anchor(corner)
                    .position(point(x, y))
                    .snap_to_window_with_margin(margin)
                    .child(content),
            )
            .with_priority(1)
        });
        div().child(listener).children(card)
    }
}

/// Points the keyboard tooltip at the control with `id`, the one the focus ring rests on, or at
/// nothing. That control opens its own tooltip the next time it is drawn, after the hover delay.
pub fn focus(id: Option<ElementId>, cx: &mut App) {
    let layer = layer(cx);
    layer.update(cx, |layer, cx| layer.aim(id, cx));
}

fn offer(id: &ElementId, area: Bounds<Pixels>, build: &Build, window: &mut Window, cx: &mut App) {
    let Some(shared) = cx.try_global::<Shared>() else {
        return;
    };
    let layer = shared.0.clone();
    if !layer.update(cx, |layer, _| layer.claim(id)) {
        return;
    }
    let build = Rc::clone(build);
    window.defer(cx, move |window, cx| {
        layer.update(cx, |layer, cx| {
            layer.request(Anchor { bounds: area }, build, window, cx);
        });
    });
}

pub fn layer(cx: &mut App) -> Entity<Layer> {
    if let Some(shared) = cx.try_global::<Shared>() {
        return shared.0.clone();
    }
    let layer = cx.new(|_| Layer::default());
    cx.set_global(Shared(layer.clone()));
    layer
}

pub trait Tip: StatefulInteractiveElement + ParentElement + Sized {
    fn tip(self, build: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self {
        self.tip_hover(build, |_, _, _| {})
    }

    /// Like `tip`, and also calls `listener` when the hover starts or ends. GPUI keeps one
    /// hover listener per element, so use this instead of `on_hover` next to a tooltip.
    /// The tooltip also opens while the focus ring rests on the element, see `focus`.
    fn tip_hover(
        mut self,
        build: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
        listener: impl Fn(&bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        let bounds = Rc::new(Cell::new(None::<Bounds<Pixels>>));
        let build: Build = Rc::new(build);
        let id = self.interactivity().element_id.clone();
        let probe = {
            let bounds = Rc::clone(&bounds);
            let build = Rc::clone(&build);
            canvas(
                move |area, window, cx| {
                    bounds.set(Some(area));
                    if let Some(id) = &id {
                        offer(id, area, &build, window, cx);
                    }
                },
                |_, (), _, _| {},
            )
            .absolute()
            .top_0()
            .left_0()
            .size_full()
        };
        self.child(probe).on_hover(move |hovered, window, cx| {
            listener(hovered, window, cx);
            let Some(area) = bounds.get() else {
                return;
            };
            let layer = layer(cx);
            layer.update(cx, |layer, cx| {
                let anchor = Anchor { bounds: area };
                if *hovered {
                    layer.request(anchor, Rc::clone(&build), window, cx);
                } else {
                    layer.track(window.mouse_position(), cx);
                }
            });
        })
    }
}

impl<E: StatefulInteractiveElement + ParentElement> Tip for E {}

pub fn plain(text: impl Into<SharedString>) -> impl Fn(&mut Window, &mut App) -> AnyView {
    Tooltip::new(text).build()
}

pub fn path(path: &Path) -> impl Fn(&mut Window, &mut App) -> AnyView + use<> {
    plain(display_path(path))
}

pub fn term(term: Term) -> impl Fn(&mut Window, &mut App) -> AnyView {
    Tooltip::new(term.text()).title(term.title()).build()
}

#[cfg(test)]
mod tests {
    use gpui::{Modifiers, TestAppContext, VisualTestContext, px};

    use super::*;

    const LONG: &str = "Caches that package managers and tools keep in your home folder, \
        which are rebuilt the next time they are needed";

    struct Target;

    impl Render for Target {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            div()
                .size_full()
                .child(
                    div()
                        .id("first")
                        .w(px(200.))
                        .h(px(40.))
                        .tip(term(Term::Review))
                        .child("review"),
                )
                .child(
                    div()
                        .id("second")
                        .w(px(200.))
                        .h(px(40.))
                        .tip(Tooltip::new("Starts the scan").keys(&["Enter"]).build())
                        .child("start"),
                )
                .child(
                    div()
                        .id("third")
                        .w(px(200.))
                        .h(px(40.))
                        .tip(plain(LONG))
                        .child("long"),
                )
                .child(
                    div()
                        .id("fourth")
                        .w(px(200.))
                        .h(px(40.))
                        .tip(term(Term::ItemsRemoved))
                        .child("removed"),
                )
                .child(layer(cx))
        }
    }

    fn hover(cx: &mut VisualTestContext, x: f32, y: f32) {
        cx.simulate_event(MouseMoveEvent {
            position: point(px(x), px(y)),
            pressed_button: None,
            modifiers: Modifiers::default(),
        });
    }

    fn shown(cx: &mut VisualTestContext) -> Option<Bounds<Pixels>> {
        cx.debug_bounds("tooltip")
    }

    fn visible(cx: &mut VisualTestContext) -> bool {
        cx.update(|_, cx| layer(cx).read(cx).shown.is_some())
    }

    fn open(cx: &mut TestAppContext) -> &mut VisualTestContext {
        let (_view, cx) = cx.add_window_view(|_, _| Target);
        cx.run_until_parked();
        cx
    }

    #[gpui::test]
    fn tooltip_waits_switches_and_dismisses(cx: &mut TestAppContext) {
        let cx = open(cx);
        hover(cx, 20., 20.);
        cx.executor().advance_clock(motion::TOOLTIP_DELAY / 2);
        cx.run_until_parked();
        assert!(!visible(cx));
        cx.executor().advance_clock(motion::TOOLTIP_DELAY);
        cx.run_until_parked();
        assert!(shown(cx).is_some());

        hover(cx, 20., 60.);
        cx.run_until_parked();
        assert!(shown(cx).is_some(), "the next tooltip opens at once");

        cx.simulate_click(point(px(20.), px(60.)), Modifiers::default());
        assert!(!visible(cx), "a click closes the tooltip");

        hover(cx, 20., 20.);
        cx.executor().advance_clock(motion::TOOLTIP_DELAY);
        cx.run_until_parked();
        assert!(visible(cx));
        hover(cx, 600., 400.);
        cx.run_until_parked();
        assert!(!visible(cx), "leaving the trigger closes the tooltip");
    }

    fn aim(cx: &mut VisualTestContext, id: Option<&'static str>) {
        cx.update(|window, cx| {
            focus(id.map(ElementId::from), cx);
            window.refresh();
        });
        cx.run_until_parked();
    }

    #[gpui::test]
    fn the_focused_control_opens_its_tooltip_until_the_focus_moves(cx: &mut TestAppContext) {
        let cx = open(cx);
        aim(cx, Some("second"));
        assert!(!visible(cx), "the keyboard waits like the mouse");
        cx.executor().advance_clock(motion::TOOLTIP_DELAY);
        cx.run_until_parked();
        let bounds = shown(cx).expect("the tooltip is painted");
        assert!(
            bounds.origin.y >= px(80.),
            "it opens below the focused control"
        );

        aim(cx, Some("first"));
        let bounds = shown(cx).expect("the next one opens at once");
        assert!(bounds.origin.y >= px(40.) && bounds.origin.y < px(80.));

        aim(cx, None);
        assert!(!visible(cx), "leaving the controls closes it");
    }

    #[gpui::test]
    fn long_text_wraps_inside_the_card(cx: &mut TestAppContext) {
        let cx = open(cx);
        hover(cx, 20., 100.);
        cx.executor().advance_clock(motion::TOOLTIP_DELAY);
        cx.run_until_parked();
        let bounds = shown(cx).expect("the tooltip is painted");
        let text = cx.debug_bounds("tooltip-text").expect("the tooltip text");
        assert!(text.right() <= bounds.right());
    }

    #[gpui::test]
    fn the_card_grows_to_hold_wrapped_text(cx: &mut TestAppContext) {
        let cx = open(cx);
        hover(cx, 20., 140.);
        cx.executor().advance_clock(motion::TOOLTIP_DELAY);
        cx.run_until_parked();
        let bounds = shown(cx).expect("the tooltip is painted");
        let text = cx.debug_bounds("tooltip-text").expect("the tooltip text");
        assert!(bounds.bottom() - text.bottom() >= px(space::S));
    }
}