aboutsummaryrefslogtreecommitdiff
path: root/src/pane/cursor.rs
blob: 13ac61f03ba9c968be403633e519dc7582e2e4de (plain)
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
use std::time::{Duration, Instant};

use super::terminal::TerminalCursorState;

pub(crate) const CURSOR_POSITION_SETTLE: Duration = Duration::from_millis(20);
const CURSOR_POSITION_MAX_HOLD: Duration = Duration::from_millis(100);

#[derive(Debug, Default)]
pub(crate) struct DecscusrTracker {
    state: DecscusrParseState,
    cursor_shape_overridden: bool,
}

#[derive(Debug, Default)]
enum DecscusrParseState {
    #[default]
    Ground,
    Escape,
    Csi {
        first_param: Option<u16>,
        collecting_first_param: bool,
        has_space_intermediate: bool,
    },
}

impl DecscusrTracker {
    pub(crate) fn observe(&mut self, bytes: &[u8]) {
        for &byte in bytes {
            self.observe_byte(byte);
        }
    }

    fn observe_byte(&mut self, byte: u8) {
        match &mut self.state {
            DecscusrParseState::Ground => {
                if byte == 0x1b {
                    self.state = DecscusrParseState::Escape;
                }
            }
            DecscusrParseState::Escape => {
                self.state = if byte == b'[' {
                    DecscusrParseState::Csi {
                        first_param: None,
                        collecting_first_param: true,
                        has_space_intermediate: false,
                    }
                } else if byte == 0x1b {
                    DecscusrParseState::Escape
                } else {
                    DecscusrParseState::Ground
                };
            }
            DecscusrParseState::Csi {
                first_param,
                collecting_first_param,
                has_space_intermediate,
            } => {
                if byte == 0x1b {
                    self.state = DecscusrParseState::Escape;
                } else if byte.is_ascii_digit() && *collecting_first_param {
                    let digit = u16::from(byte - b'0');
                    *first_param = Some(first_param.unwrap_or(0).saturating_mul(10) + digit);
                } else if byte == b';' || byte == b':' {
                    *collecting_first_param = false;
                } else if byte == b' ' {
                    *has_space_intermediate = true;
                    *collecting_first_param = false;
                } else if (0x40..=0x7e).contains(&byte) {
                    if byte == b'q' && *has_space_intermediate {
                        let param = first_param.unwrap_or(0);
                        if param <= 6 {
                            self.cursor_shape_overridden = param != 0;
                        }
                    }
                    self.state = DecscusrParseState::Ground;
                } else if !(0x20..=0x3f).contains(&byte) {
                    self.state = DecscusrParseState::Ground;
                }
            }
        }
    }

    pub(crate) fn cursor_shape_overridden(&self) -> bool {
        self.cursor_shape_overridden
    }
}

#[derive(Debug, Default)]
pub(crate) struct CursorPositionSettleState {
    settled: Option<TerminalCursorState>,
    candidate: Option<TerminalCursorState>,
    pending_since: Option<Instant>,
    candidate_since: Option<Instant>,
    /// True when this candidate jumped away from the settled caret (a different
    /// row, or a large same-row column move).
    ///
    /// Those are the shape of a redraw parking the cursor on a temporary cell,
    /// so they are held for the max window before being shown. Ordinary caret
    /// steps are small and same-row, and settle on the normal window.
    candidate_jump: bool,
}

impl CursorPositionSettleState {
    pub(crate) fn observe(&mut self, current: Option<TerminalCursorState>, now: Instant) {
        // A candidate that stayed quiet for its hold window is real, so preserve
        // it before considering the first (possibly temporary) position of a
        // later redraw.
        if let (Some(candidate), Some(since)) = (self.candidate, self.candidate_since) {
            if now.duration_since(since) >= self.candidate_hold() {
                self.settle(Some(candidate));
            }
        }
        let Some(current) = current else {
            self.settle(None);
            return;
        };
        if !current.visible {
            self.settle(Some(current));
            return;
        }
        let Some(settled) = self.settled else {
            self.settle(Some(current));
            return;
        };
        if same_cursor_position(settled, current) && settled.visible {
            self.settle(Some(current));
            return;
        }

        let Some(candidate) = self.candidate else {
            self.candidate = Some(current);
            self.pending_since = Some(now);
            self.candidate_since = Some(now);
            self.candidate_jump = is_jump(settled, current);
            return;
        };

        let pending_since = self.pending_since.unwrap_or(now);
        if now.duration_since(pending_since) >= CURSOR_POSITION_MAX_HOLD {
            self.settle(Some(current));
        } else {
            if !same_cursor_position(candidate, current) {
                self.candidate_since = Some(now);
                self.candidate_jump = is_jump(settled, current);
            }
            self.candidate = Some(current);
        }
    }

    pub(crate) fn reported_cursor(
        &self,
        current: Option<TerminalCursorState>,
        now: Instant,
    ) -> Option<TerminalCursorState> {
        let current = current?;
        let Some(candidate) = self.candidate else {
            return Some(current);
        };
        let candidate_since = self.candidate_since.unwrap_or(now);
        let pending_since = self.pending_since.unwrap_or(now);
        // A jump-shaped candidate is treated as a redraw park until proven
        // otherwise, so it waits for the max window. An ordinary caret step only
        // waits the normal settle window; the max hold bounds either case.
        if now.duration_since(candidate_since) >= self.candidate_hold()
            || now.duration_since(pending_since) >= CURSOR_POSITION_MAX_HOLD
        {
            return Some(TerminalCursorState {
                visible: current.visible && candidate.visible,
                shape: current.shape,
                ..candidate
            });
        }
        self.settled
            .map(|settled| TerminalCursorState {
                visible: current.visible && settled.visible,
                shape: current.shape,
                ..settled
            })
            .or(Some(TerminalCursorState {
                visible: false,
                shape: current.shape,
                ..candidate
            }))
    }

    pub(crate) fn pending(&self) -> bool {
        self.candidate.is_some()
    }

    pub(crate) fn render_delay(&self) -> Option<Duration> {
        self.pending().then(|| self.candidate_hold())
    }

    fn candidate_hold(&self) -> Duration {
        if self.candidate_jump {
            CURSOR_POSITION_MAX_HOLD
        } else {
            CURSOR_POSITION_SETTLE
        }
    }

    fn settle(&mut self, cursor: Option<TerminalCursorState>) {
        *self = Self {
            settled: cursor,
            ..Self::default()
        };
    }
}

fn same_cursor_position(left: TerminalCursorState, right: TerminalCursorState) -> bool {
    left.x == right.x && left.y == right.y
}

/// A cursor move that changes row, or jumps more than a couple of columns, is
/// the shape of a redraw parking the cursor rather than an ordinary caret step.
fn is_jump(settled: TerminalCursorState, current: TerminalCursorState) -> bool {
    current.y != settled.y || current.x.abs_diff(settled.x) > 2
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cursor(x: u16, y: u16, visible: bool, shape: u8) -> TerminalCursorState {
        TerminalCursorState {
            x,
            y,
            visible,
            shape,
        }
    }

    #[test]
    fn cursor_settle_holds_position_change_until_quiet_window() {
        let now = Instant::now();
        let mut settle = CursorPositionSettleState::default();
        settle.observe(Some(cursor(1, 0, true, 0)), now);
        settle.observe(Some(cursor(20, 5, true, 0)), now + Duration::from_millis(1));

        let reported = settle
            .reported_cursor(Some(cursor(20, 5, true, 0)), now + Duration::from_millis(2))
            .unwrap();

        assert_eq!((reported.x, reported.y), (1, 0));
    }

    #[test]
    fn cursor_settle_adopts_position_change_after_quiet_window() {
        let now = Instant::now();
        let mut settle = CursorPositionSettleState::default();
        settle.observe(Some(cursor(1, 0, true, 0)), now);
        settle.observe(Some(cursor(2, 0, true, 0)), now + Duration::from_millis(1));

        let reported = settle
            .reported_cursor(
                Some(cursor(2, 0, true, 0)),
                now + CURSOR_POSITION_SETTLE + Duration::from_millis(1),
            )
            .unwrap();

        assert_eq!((reported.x, reported.y), (2, 0));
    }

    #[test]
    fn cursor_settle_keeps_previous_caret_during_next_system_conpty_redraw() {
        let now = Instant::now();
        let mut settle = CursorPositionSettleState::default();
        let caret = cursor(2, 12, true, 0);
        let typed_caret = cursor(3, 12, true, 0);
        let repair = cursor(0, 10, true, 0);
        settle.observe(Some(caret), now);
        settle.observe(Some(typed_caret), now + Duration::from_millis(1));

        // System ConPTY closes the next frame at the repair cell, then emits
        // the caret restoration separately about 10 ms later.
        settle.observe(Some(repair), now + Duration::from_millis(160));
        assert_eq!(
            settle.reported_cursor(Some(repair), now + Duration::from_millis(161)),
            Some(typed_caret)
        );
        settle.observe(Some(typed_caret), now + Duration::from_millis(170));
        assert_eq!(
            settle.reported_cursor(Some(typed_caret), now + Duration::from_millis(171)),
            Some(typed_caret)
        );
    }

    #[test]
    fn cursor_settle_restarts_quiet_window_when_candidate_moves() {
        let now = Instant::now();
        let mut settle = CursorPositionSettleState::default();
        let initial = cursor(1, 0, true, 0);
        let latest = cursor(3, 0, true, 0);
        settle.observe(Some(initial), now);
        settle.observe(Some(cursor(2, 0, true, 0)), now + Duration::from_millis(1));
        settle.observe(Some(latest), now + Duration::from_millis(19));
        assert_eq!(
            settle.reported_cursor(Some(latest), now + Duration::from_millis(22)),
            Some(initial)
        );
        assert_eq!(
            settle.reported_cursor(Some(latest), now + Duration::from_millis(39)),
            Some(latest)
        );
    }

    #[test]
    fn cursor_settle_caps_continuous_position_changes_from_first_pending_time() {
        let now = Instant::now();
        let mut settle = CursorPositionSettleState::default();
        settle.observe(Some(cursor(1, 0, true, 0)), now);
        settle.observe(Some(cursor(2, 0, true, 0)), now + Duration::from_millis(1));
        for ms in (11..=91).step_by(10) {
            settle.observe(
                Some(cursor(ms as u16, 0, true, 0)),
                now + Duration::from_millis(ms),
            );
        }
        settle.observe(
            Some(cursor(3, 0, true, 0)),
            now + CURSOR_POSITION_MAX_HOLD + Duration::from_millis(1),
        );

        assert!(!settle.pending());
        assert_eq!(
            settle.reported_cursor(
                Some(cursor(3, 0, true, 0)),
                now + CURSOR_POSITION_MAX_HOLD + Duration::from_millis(2),
            ),
            Some(cursor(3, 0, true, 0))
        );
    }

    #[test]
    fn cursor_settle_caps_hold_even_without_another_observation() {
        let now = Instant::now();
        for step in [10, 30] {
            let mut settle = CursorPositionSettleState::default();
            settle.observe(Some(cursor(0, 0, true, 0)), now);
            for ms in (1..=91).step_by(step) {
                settle.observe(
                    Some(cursor(ms as u16, 1, true, 0)),
                    now + Duration::from_millis(ms),
                );
            }
            assert_eq!(
                settle.reported_cursor(
                    Some(cursor(91, 1, true, 0)),
                    now + Duration::from_millis(101)
                ),
                Some(cursor(91, 1, true, 0))
            );
        }
    }

    #[test]
    fn cursor_settle_repeated_position_does_not_restart_quiet_window() {
        let now = Instant::now();
        let mut settle = CursorPositionSettleState::default();
        let next = cursor(2, 0, true, 0);
        settle.observe(Some(cursor(1, 0, true, 0)), now);
        settle.observe(Some(next), now + Duration::from_millis(1));
        settle.observe(Some(next), now + Duration::from_millis(19));
        assert_eq!(
            settle.reported_cursor(Some(next), now + Duration::from_millis(21)),
            Some(next)
        );
    }

    #[test]
    fn cursor_settle_repeated_jump_position_does_not_starve() {
        let now = Instant::now();
        let mut settle = CursorPositionSettleState::default();
        let next = cursor(2, 1, true, 0);
        settle.observe(Some(cursor(2, 0, true, 0)), now);
        for ms in [1, 31, 61, 91] {
            settle.observe(Some(next), now + Duration::from_millis(ms));
        }
        assert_eq!(
            settle.reported_cursor(Some(next), now + Duration::from_millis(101)),
            Some(next)
        );
    }

    #[test]
    fn cursor_settle_keeps_render_read_pure() {
        let now = Instant::now();
        let mut settle = CursorPositionSettleState::default();
        settle.observe(Some(cursor(1, 0, true, 0)), now);
        settle.observe(Some(cursor(2, 0, true, 0)), now + Duration::from_millis(1));

        assert!(settle.pending());
        let _ = settle.reported_cursor(
            Some(cursor(2, 0, true, 0)),
            now + CURSOR_POSITION_SETTLE + Duration::from_millis(1),
        );

        assert!(settle.pending());
    }

    #[test]
    fn cursor_settle_passes_shape_through_while_position_is_held() {
        let now = Instant::now();
        let mut settle = CursorPositionSettleState::default();
        settle.observe(Some(cursor(1, 0, true, 2)), now);
        settle.observe(Some(cursor(2, 0, true, 6)), now + Duration::from_millis(1));

        let reported = settle
            .reported_cursor(Some(cursor(2, 0, true, 6)), now + Duration::from_millis(2))
            .unwrap();

        assert_eq!((reported.x, reported.y, reported.shape), (1, 0, 6));
    }

    #[test]
    fn cursor_settle_passes_shape_through_after_quiet_window() {
        let now = Instant::now();
        let mut settle = CursorPositionSettleState::default();
        settle.observe(Some(cursor(1, 0, true, 2)), now);
        settle.observe(Some(cursor(2, 0, true, 2)), now + Duration::from_millis(1));

        let reported = settle
            .reported_cursor(
                Some(cursor(2, 0, true, 6)),
                now + CURSOR_POSITION_SETTLE + Duration::from_millis(1),
            )
            .unwrap();

        assert_eq!((reported.x, reported.y, reported.shape), (2, 0, 6));
    }

    #[test]
    fn cursor_settle_hides_immediately_and_waits_to_reveal() {
        let now = Instant::now();
        let mut settle = CursorPositionSettleState::default();
        settle.observe(Some(cursor(1, 0, true, 0)), now);
        settle.observe(Some(cursor(1, 0, false, 0)), now + Duration::from_millis(1));

        assert_eq!(
            settle.reported_cursor(Some(cursor(1, 0, false, 0)), now + Duration::from_millis(2)),
            Some(cursor(1, 0, false, 0))
        );

        settle.observe(Some(cursor(1, 0, true, 0)), now + Duration::from_millis(3));
        assert_eq!(
            settle.reported_cursor(Some(cursor(1, 0, true, 0)), now + Duration::from_millis(4)),
            Some(cursor(1, 0, false, 0))
        );
    }

    #[test]
    fn cursor_settle_does_not_publish_a_jump_before_the_max_hold() {
        let now = Instant::now();
        let mut settle = CursorPositionSettleState::default();
        let caret = cursor(2, 26, true, 0);
        let park = cursor(0, 25, true, 0);
        settle.observe(Some(caret), now);

        // A transition redraw parks the cursor on a cell above the composer and
        // restores the caret in a later write, more than one settle window away.
        // The park must not be published in the meantime.
        settle.observe(Some(park), now + Duration::from_millis(1));
        assert_eq!(
            settle.reported_cursor(
                Some(park),
                now + CURSOR_POSITION_SETTLE + Duration::from_millis(1)
            ),
            Some(caret)
        );
        assert_eq!(
            settle.reported_cursor(Some(park), now + Duration::from_millis(70)),
            Some(caret)
        );

        // An ordinary same-row caret step still settles on the normal window.
        settle.observe(
            Some(cursor(3, 26, true, 0)),
            now + Duration::from_millis(80),
        );
        settle.observe(
            Some(cursor(4, 26, true, 0)),
            now + Duration::from_millis(81),
        );
        assert_eq!(
            settle.reported_cursor(
                Some(cursor(4, 26, true, 0)),
                now + CURSOR_POSITION_SETTLE + Duration::from_millis(82)
            ),
            Some(cursor(4, 26, true, 0))
        );
    }
}