Repository navigation
Expand file tree
/
Copy pathinteraction.rs
More file actions
383 lines (366 loc) · 14.8 KB
/
Copy pathinteraction.rs
File metadata and controls
383 lines (366 loc) · 14.8 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
//! User interaction handling for the chart widget.
//!
//! Implements tracking mode (auto-scroll to latest bar) and keyboard shortcuts
//! through the chart's shared, configurable shortcut map.
//! These methods are called by the main widget paint loop.
use egui::{Event, Id, Pos2, Rect, Response, TouchDeviceId, TouchId, TouchPhase, Ui};
use crate::widget::Chart;
use crate::widget::pan_zoom::raw_wheel_delta;
#[derive(Clone)]
struct TouchContact {
id: (TouchDeviceId, TouchId),
origin: Pos2,
position: Pos2,
started: f64,
tracking: bool,
}
/// UI state belongs to the chart response, like egui's own pointer gesture state.
#[derive(Clone, Default)]
pub(super) struct TouchCrosshair {
contact: Option<TouchContact>,
pub(super) position: Option<Pos2>,
pub(super) touch_input: bool,
}
pub(super) fn touch_crosshair(ui: &Ui, id: Id) -> TouchCrosshair {
ui.ctx().data(|data| {
data.get_temp::<TouchCrosshair>(id.with("touch_crosshair"))
.unwrap_or_default()
})
}
impl Chart {
/// Returns whether a held readout owns this frame's drag, including its release.
pub(super) fn handle_touch_crosshair(
&mut self,
ui: &Ui,
id: Id,
plot: Rect,
blocked: bool,
) -> bool {
use crate::config::TouchTrackingExitMode;
let options = &self.chart_options.tooltip;
let mut state = touch_crosshair(ui, id);
let was_active = state.position.is_some();
let pointer_in_plot = ui.rect_contains_pointer(plot);
let mut repaint_after = None;
let slop = ui
.ctx()
.options(|options| options.input_options.max_click_dist);
ui.input(|input| {
let touch_event = input
.events
.iter()
.any(|event| matches!(event, Event::Touch { .. }));
if touch_event {
state.touch_input = true;
} else if !input.any_touches()
&& input.events.iter().any(|event| {
matches!(
event,
Event::PointerMoved(_) | Event::PointerButton { pressed: true, .. }
)
})
{
state = TouchCrosshair::default();
}
if !options.enabled
|| !options.on_long_press
|| blocked
|| !input.focused
|| input.multi_touch().is_some()
{
state.contact = None;
state.position = None;
return;
}
if options.touch_exit_mode == TouchTrackingExitMode::OnTouchEnd
&& state.contact.is_none()
{
state.position = None;
}
for event in &input.events {
let Event::Touch {
device_id,
id,
phase,
pos,
..
} = event
else {
continue;
};
let contact_id = (*device_id, *id);
match phase {
TouchPhase::Start => {
if plot.contains(*pos) && pointer_in_plot {
state.contact = Some(TouchContact {
id: contact_id,
origin: *pos,
position: *pos,
started: input.time,
tracking: false,
});
} else {
state.contact = None;
state.position = None;
}
}
TouchPhase::Move => {
if let Some(contact) = &mut state.contact
&& contact.id == contact_id
{
if !contact.tracking && contact.origin.distance(*pos) > slop {
if state.position.is_some() {
contact.tracking = true;
} else {
state.contact = None;
continue;
}
}
contact.position = plot.clamp(*pos);
if contact.tracking {
state.position = Some(contact.position);
}
}
}
TouchPhase::End => {
if let Some(contact) = &state.contact
&& contact.id == contact_id
{
if !contact.tracking
|| options.touch_exit_mode == TouchTrackingExitMode::OnTouchEnd
{
state.position = None;
} else {
state.position = Some(plot.clamp(*pos));
}
state.contact = None;
}
}
TouchPhase::Cancel => {
state.contact = None;
state.position = None;
}
}
}
if let Some(contact) = &mut state.contact {
if !input.any_touches() {
state.contact = None;
state.position = None;
} else if !contact.tracking {
let elapsed =
std::time::Duration::try_from_secs_f64(input.time - contact.started)
.unwrap_or_default();
let remaining = options.long_press_delay.saturating_sub(elapsed);
if remaining.is_zero() {
contact.tracking = true;
state.position = Some(contact.position);
} else {
repaint_after = Some(remaining);
}
}
}
});
if let Some(delay) = repaint_after {
ui.ctx().request_repaint_after(delay);
}
let owns_drag = state.touch_input
&& (was_active || state.position.is_some() || state.contact.is_some());
if owns_drag {
self.kinetic_scroll.is_active = false;
}
ui.ctx()
.data_mut(|data| data.insert_temp(id.with("touch_crosshair"), state));
owns_drag
}
/// Manage tracking mode: auto-scroll to the latest bar while active.
///
/// Tracking mode keeps the chart viewport anchored to real-time data.
/// It exits automatically based on the configured
/// [`TrackingModeExitMode`](crate::config::TrackingModeExitMode): on mouse leave,
/// on next tap, or on touch end. Any manual scroll/zoom/drag also deactivates it.
pub(crate) fn handle_tracking_mode(&mut self, ui: &Ui, response: &Response) {
// Track mouse entering/leaving chart area for tracking mode
let was_in_chart = self.mouse_in_chart;
self.mouse_in_chart = response.hovered();
// Manual interaction (scroll, zoom, drag) cancels a pending `scroll_to_time`
let manual_interaction = response.dragged()
|| raw_wheel_delta(ui).length_sq() > 0.0
|| ui.input(|i| i.smooth_scroll_delta.length_sq() > 0.0);
if manual_interaction {
self.pending_scroll_time = None;
}
// Handle tracking mode exit conditions
use crate::config::TrackingModeExitMode;
if self.tracking_mode_active {
match self.chart_options.tracking_mode.exit_mode {
TrackingModeExitMode::OnMouseLeave => {
// Exit when mouse leaves the chart
if was_in_chart && !self.mouse_in_chart {
self.tracking_mode_active = false;
}
}
TrackingModeExitMode::OnNextTap => {
// Exit on any click
if response.clicked() {
self.tracking_mode_active = false;
}
}
TrackingModeExitMode::OnTouchEnd => {
// Exit when drag/touch ends
if !response.dragged() && self.scroll_start_pos.is_some() {
self.tracking_mode_active = false;
}
}
}
// Exit tracking mode on any manual interaction (scroll, zoom, drag)
if manual_interaction {
self.tracking_mode_active = false;
}
}
// If tracking mode is active, keep scrolling to latest
if self.tracking_mode_active {
self.state.time_scale_mut().scroll_to_realtime();
}
}
/// Dispatch configured shortcuts, retaining arrow-key focus on the chart.
/// Hosts call [`Self::dispatch_shortcuts`] before their toolbars and after dialogs.
pub(crate) fn handle_keyboard_shortcuts(
&mut self,
ui: &Ui,
response: &Response,
chart_width: f32,
chart_rect_min_x: f32,
) {
self.keyboard.chart_id = Some(response.id);
if response.has_focus() {
ui.memory_mut(|memory| {
memory.set_focus_lock_filter(
response.id,
egui::EventFilter {
horizontal_arrows: self.chart_options.keyboard.enabled,
vertical_arrows: self.chart_options.keyboard.enabled,
..Default::default()
},
);
});
}
// These bounds are current even on the first frame or after resizing.
self.last_rendered_price_rect.min.x = chart_rect_min_x;
self.last_rendered_price_rect.max.x = chart_rect_min_x + chart_width;
self.dispatch_shortcuts(ui.ctx());
}
/// Request keyboard focus when the user actually interacts with the chart
/// (click, pointer-down, or drag), so keyboard shortcuts become active.
///
/// Focus is deliberately *not* taken on bare hover: doing so would paint the
/// keyboard focus ring whenever the pointer merely passes over the chart,
/// which reads as a spurious selection. Tab/keyboard navigation still routes
/// focus here through egui's own focus machinery, so the focus ring remains a
/// genuine keyboard affordance.
pub(crate) fn request_focus_if_needed(&self, response: &mut Response) {
if self.chart_options.keyboard.enabled
&& (response.clicked() || response.dragged() || response.is_pointer_button_down_on())
{
response.request_focus();
}
}
/// Display a grabbing cursor while the user is actively dragging (panning) the chart.
pub(crate) fn set_panning_cursor(&self, ui: &Ui, response: &Response) {
if response.dragged() {
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
}
}
}
#[cfg(test)]
mod tests {
use crate::widget::test_frames::chart;
use egui::{Context, Event, Key, Modifiers, RawInput, Rect, Vec2};
#[test]
fn horizontal_arrows_pan_repeatedly_and_tab_leaves_the_chart() {
for enabled in [true, false] {
let ctx = Context::default();
let mut chart = chart(&[100.0], &[101.0]);
chart.chart_options.keyboard.enabled = enabled;
let mut chart_id = egui::Id::NULL;
chart.config.show_right_axis = false;
chart.config.show_ohlc_info = false;
let mut next_id = egui::Id::NULL;
for (pass, key) in [
None,
None,
Some(Key::ArrowLeft),
Some(Key::ArrowLeft),
Some(Key::ArrowRight),
Some(Key::Tab),
]
.into_iter()
.enumerate()
{
let before = chart.state.time_scale().right_offset();
let output = ctx.run_ui(
RawInput {
screen_rect: Some(Rect::from_min_size(
egui::Pos2::ZERO,
Vec2::new(1000.0, 500.0),
)),
events: key
.map(|key| Event::Key {
key,
physical_key: None,
pressed: true,
repeat: false,
modifiers: Modifiers::NONE,
})
.into_iter()
.collect(),
..Default::default()
},
|ui| {
ui.horizontal(|ui| {
let _ = ui.button("Before");
ui.allocate_ui(Vec2::new(700.0, 400.0), |ui| {
let response = chart.show(ui);
chart_id = response.id;
if pass == 0 {
response.request_focus();
}
});
next_id = ui.button("After").id;
});
},
);
output.drop_without_applying_deltas();
if pass >= 2 && key != Some(Key::Tab) {
let expected = if !enabled {
0.0
} else if key == Some(Key::ArrowLeft) {
-chart.chart_options.keyboard.pan_amount
} else {
chart.chart_options.keyboard.pan_amount
};
assert_eq!(
chart.state.time_scale().right_offset(),
before - expected,
"pass {pass}"
);
if enabled {
assert!(
ctx.memory(|memory| memory.has_focus(chart_id)),
"pass {pass}"
);
} else if pass == 2 {
assert!(
!ctx.memory(|memory| memory.has_focus(chart_id)),
"disabled arrows must keep native focus navigation"
);
}
}
}
assert!(!ctx.memory(|memory| memory.has_focus(chart_id)));
assert!(
ctx.memory(|memory| memory.focused().is_some()),
"expected keyboard focus after Tab, next {next_id:?}"
);
}
}
}