1
//! The mouse: the wheel steps the scrollable surface under the pointer, a left click acts on
2
//! what the last frame drew under it.
3

            
4
use std::time::{Duration, Instant};
5

            
6
use crate::app::{App, Face, MenuId, Owner};
7
use crate::event::{Intent, apply, apply_to_view};
8
use crate::focus::{FocusTarget, current_focus};
9
use crate::hits::{Surface, Target};
10
use crate::keymap;
11
use crate::modal::Modal;
12
use crate::widgets::WidgetKind;
13
use crate::widgets::grid::CellId;
14
use crate::window::WindowId;
15
use ratatui::crossterm::event::{MouseButton, MouseEvent, MouseEventKind};
16
use ratatui::layout::{Position, Rect};
17

            
18
/// The longest time between two clicks that make a double click.
19
const DOUBLE_CLICK: Duration = Duration::from_millis(400);
20

            
21
/// A left click on a list row or a grid cell: when it came, what it hit and its area.
22
#[derive(Debug, Clone, Copy)]
23
pub(crate) struct Click {
24
    at: Instant,
25
    target: Target,
26
    area: Rect,
27
    /// Whether the click opened a drop-down: a quick second click on it is no click away.
28
    opened: bool,
29
}
30

            
31
impl Click {
32
    /// Whether the click hit a grid cell or the text of one.
33
54
    fn in_grid(self) -> bool {
34
54
        matches!(
35
54
            self.target,
36
            Target::Cell { .. } | Target::Caret { cell: Some(_), .. }
37
        )
38
54
    }
39

            
40
    /// Whether a click at `position` and time `at` is the second of this one: it lands on the
41
    /// area where this one hit, soon enough.
42
75
    fn followed_by(self, position: Position, at: Instant) -> bool {
43
75
        self.area.contains(position) && at.saturating_duration_since(self.at) <= DOUBLE_CLICK
44
75
    }
45
}
46

            
47
/// Applies the wheel and the left button; other buttons do nothing.
48
607
pub(crate) fn handle_mouse(app: &mut App, mouse: MouseEvent, at: Instant) {
49
607
    dispatch(app, mouse, at);
50
607
    app.preview_options();
51
607
}
52

            
53
607
fn dispatch(app: &mut App, mouse: MouseEvent, at: Instant) {
54
607
    let position = Position::new(mouse.column, mouse.row);
55
607
    if app.flush_key_press() {
56
1
        return;
57
606
    }
58
606
    if app.pointer_dragging() && !follow_drag(app, mouse.kind, position) {
59
44
        return;
60
562
    }
61
562
    if current_focus(app) == FocusTarget::Drag {
62
8
        return;
63
554
    }
64
554
    match mouse.kind {
65
377
        MouseEventKind::Down(MouseButton::Left) => click(app, position, at),
66
42
        MouseEventKind::Up(MouseButton::Left) => release(app, position),
67
8
        MouseEventKind::Drag(MouseButton::Left) => app.track_press(position),
68
24
        MouseEventKind::ScrollUp => wheel::step(app, position, true),
69
98
        MouseEventKind::ScrollDown => wheel::step(app, position, false),
70
5
        _ => {}
71
    }
72
607
}
73

            
74
/// Feeds a drag the mouse began its motion and release. False when the event is over with: a
75
/// press ends the drag and goes on as a click.
76
47
fn follow_drag(app: &mut App, kind: MouseEventKind, position: Position) -> bool {
77
47
    match kind {
78
29
        MouseEventKind::Drag(MouseButton::Left) => app.drag_to(position),
79
14
        MouseEventKind::Up(MouseButton::Left) => app.end_drag(true),
80
        MouseEventKind::Down(MouseButton::Left) => {
81
3
            app.end_drag(true);
82
3
            return true;
83
        }
84
1
        _ => {}
85
    }
86
44
    false
87
47
}
88

            
89
/// Acts on what the last frame drew under `position`; a row a click already selected,
90
/// clicked again in time, does what Enter does on it.
91
377
fn click(app: &mut App, position: Position, at: Instant) {
92
377
    let first = app.last_click.take();
93
377
    let Some((area, target, window)) = resolve(app, first, position, at) else {
94
1
        return;
95
    };
96
376
    let click = Click {
97
376
        at,
98
376
        target,
99
376
        area,
100
376
        opened: false,
101
376
    };
102
376
    if let Some(rear) = window.filter(|id| app.front_window() != Some(*id)) {
103
6
        apply(app, Intent::RaiseWindow(rear));
104
6
        if target == Target::Title {
105
2
            app.last_click = Some(click);
106
4
        }
107
6
        return;
108
370
    }
109
370
    if list_open(app) && target.surface() != Some(Surface::Options) {
110
9
        if !first.is_some_and(|first| first.opened && first.followed_by(position, at)) {
111
6
            apply(app, Intent::SelectCancel);
112
3
        }
113
9
        return;
114
361
    }
115
361
    let double = first.is_some_and(|first| first.followed_by(position, at));
116
361
    match target {
117
54
        Target::Row(row) => click_row(app, row, click, double),
118
        Target::Cell { field, cell } => {
119
33
            click_form(app, (field, Some(cell)), click, Opens::Again, position);
120
        }
121
        Target::Mark { field, cell } => {
122
18
            click_form(app, (field, cell), click, Opens::Always, position);
123
        }
124
        Target::Caret { field, cell } => {
125
27
            click_form(app, (field, cell), click, Opens::Never, position);
126
        }
127
3
        Target::Option(index) => apply(app, Intent::SelectPick(index)),
128
85
        Target::Scroll(surface, part) => wheel::press_bar(app, surface, part),
129
22
        Target::Block | Target::Body(_) => {}
130
        Target::MenuBackdrop => apply(app, Intent::CloseMenu),
131
20
        Target::MenuTitle(index) => click_menu_title(app, index),
132
        Target::MenuItem(index) => {
133
9
            app.select_menu_item(index);
134
9
            apply(app, Intent::MenuSelect);
135
        }
136
17
        Target::Button(index) => app.hold_press(owner_of(window), Face::Button(index), area),
137
19
        Target::Field(index) => click_form(app, (index, None), click, Opens::Again, position),
138
6
        Target::Hint(intent) => apply(app, intent),
139
8
        Target::Close => app.hold_press(owner_of(window), Face::Close, area),
140
4
        Target::Zoom => apply(app, Intent::ToggleZoom),
141
27
        Target::Title => click_title(app, click, double, (window, position)),
142
9
        Target::Grow => window
143
9
            .iter()
144
9
            .for_each(|id| app.begin_corner_drag(*id, position)),
145
    }
146
377
}
147

            
148
/// Who a press at a target belongs to: the window that drew it, else the dialog on top.
149
50
fn owner_of(window: Option<WindowId>) -> Owner {
150
50
    window.map_or(Owner::Layer, Owner::Window)
151
50
}
152

            
153
/// The release that ends a press on a button or on `[â– ]`: the button acts, or the window closes,
154
/// only if the pointer is still on it.
155
42
fn release(app: &mut App, position: Position) {
156
42
    match app.release_press(position) {
157
12
        Some(Face::Button(index)) => press_button(app, index),
158
4
        Some(Face::Close) => apply(app, Intent::CloseWindow),
159
26
        None => {}
160
    }
161
42
}
162

            
163
/// A press on the top row of a window or dialog: a second one soon after zooms a window, else it takes
164
/// hold of it to drag it.
165
27
fn click_title(
166
27
    app: &mut App,
167
27
    click: Click,
168
27
    double: bool,
169
27
    (window, position): (Option<WindowId>, Position),
170
27
) {
171
27
    if double && window.is_some() {
172
2
        return apply(app, Intent::ToggleZoom);
173
25
    }
174
25
    app.last_click = Some(click);
175
25
    app.begin_title_drag(owner_of(window), position);
176
27
}
177

            
178
/// A click on a menu title opens its menu, or closes it when it is the open one.
179
20
fn click_menu_title(app: &mut App, index: usize) {
180
20
    let Some(menu) = MenuId::ALL.get(index).copied() else {
181
        return;
182
    };
183
20
    match app.menu_title() {
184
10
        Some(open) if open == menu => app.close_menu(),
185
3
        Some(_) => app.open_menu_of(menu),
186
10
        None => crate::event::open_menu(app, menu),
187
    }
188
20
}
189

            
190
/// What a click at `position` hits. A quick second click on a grid cell or its text lands where
191
/// the first one did, though focusing it may have shifted the grid under the pointer.
192
377
fn resolve(
193
377
    app: &App,
194
377
    first: Option<Click>,
195
377
    position: Position,
196
377
    at: Instant,
197
377
) -> Option<(Rect, Target, Option<WindowId>)> {
198
377
    match first {
199
54
        Some(first) if first.in_grid() && first.followed_by(position, at) => {
200
12
            Some((first.area, first.target, None))
201
        }
202
365
        _ => app.hits.hit_at(position),
203
    }
204
377
}
205

            
206
/// Whether a form's drop-down is open for the keys: a click off it closes it, as Esc does.
207
370
fn list_open(app: &App) -> bool {
208
370
    let Some(Modal::Form(form)) = app.overlays.top() else {
209
223
        return false;
210
    };
211
147
    current_focus(app) == FocusTarget::Overlay && form.focused_select().is_some_and(|s| s.open)
212
370
}
213

            
214
54
fn click_row(app: &mut App, row: usize, click: Click, double: bool) {
215
54
    apply_to_view(app, Intent::ListSelectRow(row));
216
54
    if current_focus(app) != FocusTarget::ViewPane {
217
12
        return;
218
42
    }
219
42
    match (double, keymap::in_view(app).bound("Enter")) {
220
8
        (true, Some(enter)) => apply(app, enter),
221
        (true, None) => {}
222
34
        (false, _) => app.last_click = Some(click),
223
    }
224
54
}
225

            
226
/// When a click on a form target opens the select it focuses.
227
#[derive(Clone, Copy)]
228
enum Opens {
229
    Never,
230
    /// The target was focused already: a select cell or field, as the first click leaves it.
231
    Again,
232
    /// The target is the select's mark.
233
    Always,
234
}
235

            
236
/// Focuses the field or grid cell a click hit, then opens its select as `opens` says, or puts
237
/// the caret under `position` for a text; the click is recorded for the quick second one.
238
97
fn click_form(
239
97
    app: &mut App,
240
97
    (field, cell): (usize, Option<CellId>),
241
97
    click: Click,
242
97
    opens: Opens,
243
97
    position: Position,
244
97
) {
245
97
    let framed = app.hits.caret_frame(position);
246
97
    let Some(Modal::Form(form)) = app.overlays.top_mut() else {
247
        return;
248
    };
249
97
    let again = cell.map_or(form.focus == field, |cell| form.cell_focused(field, cell));
250
97
    match cell {
251
50
        Some(cell) => form.focus_cell(field, cell),
252
47
        None => form.focus_field(field),
253
    }
254
97
    if matches!(click.target, Target::Caret { .. }) {
255
27
        let (area, shift) = framed.unwrap_or((click.area, 0));
256
27
        form.place_caret(
257
27
            area,
258
27
            Position::new(position.x.saturating_add(shift), position.y),
259
27
        );
260
70
    }
261
97
    let select = match cell {
262
50
        Some(_) => form.focused_select().is_some(),
263
47
        None => form.focused_widget_kind() == Some(WidgetKind::Select),
264
    };
265
97
    let opens = select
266
64
        && match opens {
267
            Opens::Never => false,
268
46
            Opens::Again => again,
269
18
            Opens::Always => true,
270
        };
271
97
    if opens {
272
30
        apply(app, Intent::SelectOpen);
273
67
    }
274
97
    app.last_click = Some(Click {
275
97
        opened: opens,
276
97
        ..click
277
97
    });
278
97
    app.fetch_tag_hints();
279
97
}
280

            
281
12
fn press_button(app: &mut App, index: usize) {
282
12
    let intent = app
283
12
        .overlays
284
12
        .top()
285
12
        .and_then(|modal| modal.button_specs().get(index))
286
        .map(|&(_, intent)| intent);
287
12
    if let Some(intent) = intent {
288
12
        apply(app, intent);
289
    }
290
12
}
291

            
292
#[cfg(test)]
293
mod bar_tests;
294
#[cfg(test)]
295
mod button_tests;
296
#[cfg(test)]
297
mod caret_tests;
298
#[cfg(test)]
299
mod cell_tests;
300
#[cfg(test)]
301
mod click_tests;
302
#[cfg(test)]
303
mod close_tests;
304
#[cfg(test)]
305
mod history_tests;
306
#[cfg(test)]
307
mod tests;
308
mod wheel;